handler-playable-sdk 1.0.59 → 1.0.60

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.
Files changed (39) hide show
  1. package/dist/{chunk-KMXVYHSV.js → chunk-G7EAC7UJ.js} +2 -2
  2. package/dist/cli/brand-dna.mjs +1 -1
  3. package/dist/cli/canva-import.mjs +1 -1
  4. package/dist/cli/cleanup-assets.mjs +1 -1
  5. package/dist/cli/fix-scales.mjs +1 -1
  6. package/dist/cli/index.js +1 -1
  7. package/dist/cli/screen-helper.mjs +1 -1
  8. package/dist/cli/setup-library.mjs +1 -1
  9. package/dist/cli/student-helper/add-logic.mjs +1 -1
  10. package/dist/cli/student-helper/add-object.mjs +1 -1
  11. package/dist/cli/student-helper/arg-parsing.mjs +1 -1
  12. package/dist/cli/student-helper/asset-registry.mjs +1 -1
  13. package/dist/cli/student-helper/bullet-system.mjs +1 -1
  14. package/dist/cli/student-helper/collectable-system.mjs +1 -1
  15. package/dist/cli/student-helper/constants.mjs +1 -1
  16. package/dist/cli/student-helper/drag-snap-couples.mjs +1 -1
  17. package/dist/cli/student-helper/endgame-screen.mjs +1 -1
  18. package/dist/cli/student-helper/fs-io.mjs +1 -1
  19. package/dist/cli/student-helper/logic-defaults.mjs +1 -1
  20. package/dist/cli/student-helper/print-help.mjs +1 -1
  21. package/dist/cli/student-helper/prompts.mjs +1 -1
  22. package/dist/cli/student-helper/scratch-card.mjs +1 -1
  23. package/dist/cli/student-helper/screen-utils.mjs +1 -1
  24. package/dist/cli/student-helper/snippets.mjs +1 -1
  25. package/dist/cli/student-helper/start-screen.mjs +1 -1
  26. package/dist/cli/student-helper/swerve-collect.mjs +1 -1
  27. package/dist/cli/student-helper/tap-destroy.mjs +1 -1
  28. package/dist/cli/student-helper/template-packs.mjs +1 -1
  29. package/dist/cli/student-helper.mjs +1 -1
  30. package/dist/cli/sync-screens.mjs +1 -1
  31. package/dist/cli/validate-assets.mjs +1 -1
  32. package/dist/cli/validate.mjs +1 -1
  33. package/dist/index.cjs +2 -2
  34. package/dist/index.js +1 -1
  35. package/dist/pixi/index.cjs +1 -1
  36. package/dist/pixi/index.js +1 -1
  37. package/dist/three/index.cjs +1 -1
  38. package/dist/three/index.js +1 -1
  39. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -43,7 +43,7 @@
43
43
  <button class="debug-btn primary" data-modal-apply>Apply</button>
44
44
  </div>
45
45
  </div>
46
- `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(r=>{r.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var zl={};Et(zl,{COLORS:()=>we,ConfigWatcher:()=>Ke,DebugPanel:()=>Ft,DefaultReloadStrategy:()=>Ot,Handler:()=>he,PlayableLoadingScreen:()=>gi,PreviewShell:()=>di,STROKE_WIDTH:()=>Nr,THEME:()=>Hr,applyConfigOverride:()=>ae,applyConfigOverrides:()=>Oe,applyConfigsToDisk:()=>vn,applyDefaults:()=>Ye,baseLottie:()=>Li,bootstrap:()=>Al,clearConfigOverrides:()=>ce,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,createPreviewShell:()=>Ra,deepClone:()=>J,default:()=>Ge,defaultPreset:()=>Ln,deviceGroups:()=>ta,devicePresets:()=>ea,diffConfigs:()=>Yi,exportConfigsAsJSON:()=>We,getConfigOverrides:()=>te,getConfigStateSummary:()=>Re,getOverrideMode:()=>It,getPresetById:()=>Xe,getPresetsByCategory:()=>Qo,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>ke,loadObjectConfig:()=>$e,loadSceneConfig:()=>Cn,redoLastConfigChange:()=>yn,rehydrateObject:()=>Ki,removeConfigOverride:()=>Mt,resetToApplied:()=>jt,resetToOriginal:()=>wn,setBootstrapDependencies:()=>El,setOverrideMode:()=>Bi,setupHotReload:()=>Zi,setupLiveEditBridge:()=>pi,toLegacyFormat:()=>Vi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn,validateObjectConfig:()=>ot});module.exports=ro(zl);var je={};function Qt(s,e,t=!1){je[s]||(je[s]=[]),je[s].push({fn:e,once:t})}function Si(s,e){if(je[s]){if(!e){delete je[s];return}je[s]=je[s].filter(t=>t.fn!==e)}}function en(s,...e){let t=je[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Si(s,n.fn)}function se(s,e){Qt(s,e,!0)}var K=null,ue=[],it=null;function Za(s){K=s,ue=[],it!==null&&(clearTimeout(it),it=null)}function Qa(){var s,e,t;return{endpoint:(K==null?void 0:K.endpoint)||"",transport:(K==null?void 0:K.transport)||"beacon",batchSize:(s=K==null?void 0:K.batchSize)!=null?s:10,flushIntervalMs:(e=K==null?void 0:K.flushIntervalMs)!=null?e:300,maxQueue:(t=K==null?void 0:K.maxQueue)!=null?t:200,debug:!!(K!=null&&K.debug)}}async function Xa(s,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function Ei(s,e){let t=Qa();if(e&&t.endpoint){if(ue.push(s),ue.length>t.maxQueue&&(ue=ue.slice(ue.length-t.maxQueue)),ue.length>=t.batchSize){Ja();return}it===null&&(it=window.setTimeout(()=>{it=null,Ja()},t.flushIntervalMs))}}async function Ja(){let s=Qa();if(!s.endpoint||ue.length===0)return;let e=ue.splice(0,s.batchSize);await Xa(s.endpoint,{events:e},s.transport,s.debug),ue.length>0&&await Xa(s.endpoint,{events:ue.splice(0,s.batchSize)},s.transport,s.debug)}function es(s){return Math.max(0,Math.min(1,s))}function oo(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.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function Ct(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function lo(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function ts(s,e,t){try{s[e]=t}catch{}}function co(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function ns(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 is(s,e){let t=co(s);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function as(){let s=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&n()})},i=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),n()},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=Ct();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=es(m),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let C=m-y;f=es(C)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let C of g.props)ts(g.target,C.key,C.from+(C.to-C.from)*v);g.scaleFrom&&g.scaleTo&&ns(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});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 C;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+((C=u==null?void 0:u.delayMsOverride)!=null?C:0)),m=oo(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,b=p.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let M of Object.keys(p)){if(y.has(M))continue;let O=p[M];typeof O=="number"&&v.push({key:M,from:lo(d,M),to:O})}let E=is(d,p);return{target:d,startMs:Ct(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:E.from,scaleTo:E.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 i(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=Ct())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:Ct(),h=Ct()-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"&&ts(d,g,h)}let u=is(d,p);u.to&&ns(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=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{p.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,E){return f({kind:"to",target:y,vars:v,atMs:m(E)}),b},fromTo(y,v,E,C){return f({kind:"fromTo",target:y,vars:E,from:v,atMs:m(C)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let E of p)E.kind==="fromTo"&&c.set(E.target,(y=E.from)!=null?y:{}),h.push(c.to(E.target,{...E.vars,delay:E.atMs/1e3+((v=E.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function ss(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=as()}catch{}}var rs={name:"handler-playable-sdk",version:"1.0.59",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/ && mkdir -p dist/cli/student-helper && cp src/cli/student-helper/*.mjs dist/cli/student-helper/ && chmod +x dist/cli/*.mjs dist/cli/student-helper/*.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 dist/cli/student-helper/*.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 re=0,uo=re++,os=re++,ls=re++,cs=re++,ds=re++,ps=re++,us=re++,gs=re++,hs=re++,ms=re++,fs=re++,bs=re++,V=uo;function ys(){return V===os}function vs(){return V===ls}function ws(){return V===cs}function xs(){return V===ds}function at(){return V===ps}function st(){return V===us}function Ss(){return V===gs}function Es(){return V===hs}function Cs(){return V===ms}function Ci(){return V===fs}function Ai(){return V===bs}function As(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),V=os;return}catch{}else if(s==="dapi")try{dapi.isReady(),V=ls;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(V=cs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(V=ds)}catch{}else if(e==="mintegral")window.gameReady&&(V=ps);else if(e==="tapjoy")window.TJ_API&&(V=us);else if(e==="tiktok")window.openAppStore&&(V=gs);else if(e==="smadex")try{window.smxTracking&&(V=hs)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(V=ms)}catch{}else e==="vungle"?V=fs:(s==="nucleo"||e==="nucleo")&&(V=bs)}var tn=nt(require("lottie-web"),1),Li=tn.default;typeof window!="undefined"&&(window.lottie=tn.default,window.__baseLottie=tn.default);var go=require("pixi.js");var Ti=require("pixi.js");var ho=null;function ki(s){ho=s}an();nn();var At=require("pixi.js");an();var wo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ji=wo;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&&(ji=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${ji}`))}}catch{}function xo(s){var t,n,i,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:(n=s[1])!=null?n:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(i=s.x)!=null?i:.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 be=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${ji}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new At.Container;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: ${i.type}, path: ${i.path}`);let r=await qe.load(e,i,n,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(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new At.Sprite(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(i.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 At.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let b of m)try{let y=await fetch(b);if(y.ok){o=await y.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,n){var i,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i: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=xo(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var Lt=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var Co=nt(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Co);rt();var sn=require("pixi.js");rt();var Ri=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Lt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let r=this.registry.get(a);if(!r){console.warn("[Assets] No config found for object:",a);return}try{let l=await be.create(a,r,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await be.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},Ao=new Ri,Lo=new Proxy(Ao,{get(s,e){if(e in s&&typeof s[e]=="function")return s[e].bind(s);if(s.get(e))return s.get(e)}});rt();var ko=require("pixi.js"),Ce={width:400,height:600,designWidth:400,scaleFactor:1},on={scale:1,position:1},$i=[];function Po(s,e,t,n,i,a,r){$i.push({element:s,originalScale:a,positionHelper:e,heightPercent:i}),e(s,t,n,i,a,r,!1)}function Io(){$i.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*Ce.scaleFactor;t(s,Ce.width,Ce.height,n,i,!0,!1)})}function zi(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Ce.width=s,Ce.height=e,Ce.scaleFactor=Math.min(s/Ce.designWidth,1.15),on.scale=Ce.scaleFactor,on.position=1,console.log(`[SCREEN] Global multipliers - scale: ${on.scale.toFixed(3)}`),Io()}var kt={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 Mo(s,e,t){let n=kt[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function jo(){return kt}var _o={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 rn(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Ae(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:rn(s[0],e.x),y:rn(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:rn(n.x,e.x),y:rn(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=_o[n])!=null?t:e}return e}function ln(s,e,t,n={}){var g,h,m,f,b,y;let i=Ae(t),a=(g=n.inset)!=null?g:{},r=(h=n.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=((y=a.bottom)!=null?y:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*i.x,y:c+u*i.y}}function cn(s,e,t,n={}){var m,f,b,y,v,E;let i=(m=n.inset)!=null?m:{},a=(f=n.padding)!=null?f:{x:0,y:0},r=((b=i.left)!=null?b:0)+a.x,o=((y=i.right)!=null?y:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((E=i.bottom)!=null?E:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Ae(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}}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==s||i!==e)&&(s=n,e=i,zi(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),zi(window.innerWidth,window.innerHeight),window.updateDebugConfig=Mo,window.getDebugConfig=jo,window.copyConfig=Uo,window.applyConfig=Tt,window.applyConfigForRatio=qo,window.positionAtBottom=Ms,window.positionAtTop=zo,window.positionAtCenter=$o,window.positionAtLeft=Do,window.positionAtRight=No,window.positionAtBottomLeft=Ho,window.positionAtBottomRight=Fo,window.positionAtTopLeft=Bo,window.positionAtTopRight=Go,window.applyPositionContract=Ro,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 dn(s,e,t=0){return s*e+t}function pn(s,e,t=0){return s*(1-e)+t}function un(s,e,t=0){return s*e+t}function gn(s,e,t=0){return s*(1-e)+t}function le(s,e=0){return s/2+e}function Oo(s,e){return s*e}function Ro(s,e,t,n){var r,o,l,c,d,p,u,g,h,m,f,b,y,v,E,C,M,O,w,P;let i=0,a=0;switch(n.type){case"top":i=le(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),a=dn(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=le(e,(p=(d=n.offset)==null?void 0:d.x)!=null?p:0),a=pn(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=un(e,n.percent,(m=(h=n.offset)==null?void 0:h.x)!=null?m:0),a=le(t,(b=(f=n.offset)==null?void 0:f.y)!=null?b:0);break;case"right":i=gn(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),a=le(t,(C=(E=n.offset)==null?void 0:E.y)!=null?C:0);break;case"center":i=le(e,(O=(M=n.offset)==null?void 0:M.x)!=null?O:0),a=le(t,(P=(w=n.offset)==null?void 0:w.y)!=null?P:0);break}s.position?s.position.set(i,a):(s.x=i,s.y=a),n.scale!==void 0&&n.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(n.scale,n.scale):(s.scale.x=n.scale,s.scale.y=n.scale))}function Ms(s,e,t,n=.2,i=1,a=!0,r=!1){let o=Oo(t,n),l=pn(t,n/2);Le(s,le(e),l);let c=a?i*Ce.scaleFactor:i;Te(s,c),r&&!$i.find(d=>d.element===s)&&Po(s,Ms,e,t,n,i,a)}function zo(s,e,t,n=.1,i=1){Le(s,le(e),dn(t,n)),Te(s,i)}function $o(s,e,t,n=0,i=0,a=1){Le(s,le(e,n),le(t,i)),Te(s,a)}function Do(s,e,t,n=.1,i=1){Le(s,un(e,n),le(t)),Te(s,i)}function No(s,e,t,n=.1,i=1){Le(s,gn(e,n),le(t)),Te(s,i)}function Ho(s,e,t,n=.05,i=.05,a=1){Le(s,un(e,i),pn(t,n)),Te(s,a)}function Fo(s,e,t,n=.05,i=.05,a=1){Le(s,gn(e,i),pn(t,n)),Te(s,a)}function Bo(s,e,t,n=.05,i=.05,a=1){Le(s,un(e,i),dn(t,n)),Te(s,a)}function Go(s,e,t,n=.05,i=.05,a=1){Le(s,gn(e,i),dn(t,n)),Te(s,a)}function Le(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 Te(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 Ve={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 Uo(s){return s&&Ve[s]?JSON.parse(JSON.stringify(Ve[s])):JSON.parse(JSON.stringify(kt))}function Tt(s){Object.keys(s).forEach(e=>{let t=e;kt[t]&&s[t]&&Object.assign(kt[t],s[t])}),console.log("Config applied:",s)}function qo(s,e){let t=s/e;t>1.6?(Tt(Ve.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(Tt(Ve.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(Tt(Ve.square),console.log("Applied SQUARE config for ratio:",t)):(Tt(Ve.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ve,s.resolveAnchorVec2=s.resolveAnchorVec2||Ae,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||ln,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||cn}An();function X(s,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(s,e);return`${s/n}:${e/n}`}var pd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:X(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:X(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:X(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:X(360,780)}],ud=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:X(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:X(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:X(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:X(412,915)}],gd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:X(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:X(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:X(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:X(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:X(800,1280)}],Qi=[{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:X(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:X(768,1024),mraidScale:.7}];var ea=[...Qi],ta=[{category:"playable",label:"Playable Ad",devices:Qi}],Ln=Qi[0];function Xe(s){return ea.find(e=>e.id===s)||Ln}function Qo(s){return ea.filter(e=>e.category===s)}Z();var De=class{async updateProperty(e,t,n,i={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,n);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}if(ae({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let p=window.applyEditableObjectConfig;if(typeof p=="function"){let u=window.__editableConfig,g=(d=(c=(l=u==null?void 0:u.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await p(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function na(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let r=i.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.")}},i.readAsDataURL(n)},e.click()}var Tn=class{constructor(){this.updateManager=new De}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,r);break;case"ai-edit":this.openAIEditor(t,n,r);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;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=((i=(n=t.transform)==null?void 0:n.scale)!=null?i: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 n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.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),i.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"}),i.categories&&!i.categories.includes(d)&&i.categories.push(d),i.libraryAssets&&!i.libraryAssets[d]&&(i.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(i.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),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((r=i==null?void 0:i.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");na({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let p=window.__debugContext;(h=(g=p==null?void 0:p.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let u=window.__highlightLibrarySlot;typeof u=="function"&&setTimeout(()=>{u(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(i):typeof r.schemas=="object"&&(o=r.schemas[i]),!(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,n){let i=window.__openAiEditor;if(typeof i=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||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),i(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 el=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],tl=["environment","ui","character","system","backgrounds"],nl=["bg","world","ui"],qs={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}}},kn=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=`
46
+ `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(r=>{r.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var zl={};Et(zl,{COLORS:()=>we,ConfigWatcher:()=>Ke,DebugPanel:()=>Ft,DefaultReloadStrategy:()=>Ot,Handler:()=>he,PlayableLoadingScreen:()=>gi,PreviewShell:()=>di,STROKE_WIDTH:()=>Nr,THEME:()=>Hr,applyConfigOverride:()=>ae,applyConfigOverrides:()=>Oe,applyConfigsToDisk:()=>vn,applyDefaults:()=>Ye,baseLottie:()=>Li,bootstrap:()=>Al,clearConfigOverrides:()=>ce,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,createPreviewShell:()=>Ra,deepClone:()=>J,default:()=>Ge,defaultPreset:()=>Ln,deviceGroups:()=>ta,devicePresets:()=>ea,diffConfigs:()=>Yi,exportConfigsAsJSON:()=>We,getConfigOverrides:()=>te,getConfigStateSummary:()=>Re,getOverrideMode:()=>It,getPresetById:()=>Xe,getPresetsByCategory:()=>Qo,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>ke,loadObjectConfig:()=>$e,loadSceneConfig:()=>Cn,redoLastConfigChange:()=>yn,rehydrateObject:()=>Ki,removeConfigOverride:()=>Mt,resetToApplied:()=>jt,resetToOriginal:()=>wn,setBootstrapDependencies:()=>El,setOverrideMode:()=>Bi,setupHotReload:()=>Zi,setupLiveEditBridge:()=>pi,toLegacyFormat:()=>Vi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn,validateObjectConfig:()=>ot});module.exports=ro(zl);var je={};function Qt(s,e,t=!1){je[s]||(je[s]=[]),je[s].push({fn:e,once:t})}function Si(s,e){if(je[s]){if(!e){delete je[s];return}je[s]=je[s].filter(t=>t.fn!==e)}}function en(s,...e){let t=je[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Si(s,n.fn)}function se(s,e){Qt(s,e,!0)}var K=null,ue=[],it=null;function Za(s){K=s,ue=[],it!==null&&(clearTimeout(it),it=null)}function Qa(){var s,e,t;return{endpoint:(K==null?void 0:K.endpoint)||"",transport:(K==null?void 0:K.transport)||"beacon",batchSize:(s=K==null?void 0:K.batchSize)!=null?s:10,flushIntervalMs:(e=K==null?void 0:K.flushIntervalMs)!=null?e:300,maxQueue:(t=K==null?void 0:K.maxQueue)!=null?t:200,debug:!!(K!=null&&K.debug)}}async function Xa(s,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function Ei(s,e){let t=Qa();if(e&&t.endpoint){if(ue.push(s),ue.length>t.maxQueue&&(ue=ue.slice(ue.length-t.maxQueue)),ue.length>=t.batchSize){Ja();return}it===null&&(it=window.setTimeout(()=>{it=null,Ja()},t.flushIntervalMs))}}async function Ja(){let s=Qa();if(!s.endpoint||ue.length===0)return;let e=ue.splice(0,s.batchSize);await Xa(s.endpoint,{events:e},s.transport,s.debug),ue.length>0&&await Xa(s.endpoint,{events:ue.splice(0,s.batchSize)},s.transport,s.debug)}function es(s){return Math.max(0,Math.min(1,s))}function oo(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.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function Ct(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function lo(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function ts(s,e,t){try{s[e]=t}catch{}}function co(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function ns(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 is(s,e){let t=co(s);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function as(){let s=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&n()})},i=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),n()},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=Ct();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=es(m),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(m),b-1):0;if(g.repeat>0&&m>=1){let C=m-y;f=es(C)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let C of g.props)ts(g.target,C.key,C.from+(C.to-C.from)*v);g.scaleFrom&&g.scaleTo&&ns(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});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 C;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+((C=u==null?void 0:u.delayMsOverride)!=null?C:0)),m=oo(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,b=p.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let M of Object.keys(p)){if(y.has(M))continue;let O=p[M];typeof O=="number"&&v.push({key:M,from:lo(d,M),to:O})}let E=is(d,p);return{target:d,startMs:Ct(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:E.from,scaleTo:E.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 i(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=Ct())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:Ct(),h=Ct()-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"&&ts(d,g,h)}let u=is(d,p);u.to&&ns(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=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{p.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,E){return f({kind:"to",target:y,vars:v,atMs:m(E)}),b},fromTo(y,v,E,C){return f({kind:"fromTo",target:y,vars:E,from:v,atMs:m(C)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let E of p)E.kind==="fromTo"&&c.set(E.target,(y=E.from)!=null?y:{}),h.push(c.to(E.target,{...E.vars,delay:E.atMs/1e3+((v=E.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return d.paused||b.play(),b}};return c}function ss(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=as()}catch{}}var rs={name:"handler-playable-sdk",version:"1.0.60",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/ && mkdir -p dist/cli/student-helper && cp src/cli/student-helper/*.mjs dist/cli/student-helper/ && chmod +x dist/cli/*.mjs dist/cli/student-helper/*.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 dist/cli/student-helper/*.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 re=0,uo=re++,os=re++,ls=re++,cs=re++,ds=re++,ps=re++,us=re++,gs=re++,hs=re++,ms=re++,fs=re++,bs=re++,V=uo;function ys(){return V===os}function vs(){return V===ls}function ws(){return V===cs}function xs(){return V===ds}function at(){return V===ps}function st(){return V===us}function Ss(){return V===gs}function Es(){return V===hs}function Cs(){return V===ms}function Ci(){return V===fs}function Ai(){return V===bs}function As(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),V=os;return}catch{}else if(s==="dapi")try{dapi.isReady(),V=ls;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(V=cs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(V=ds)}catch{}else if(e==="mintegral")window.gameReady&&(V=ps);else if(e==="tapjoy")window.TJ_API&&(V=us);else if(e==="tiktok")window.openAppStore&&(V=gs);else if(e==="smadex")try{window.smxTracking&&(V=hs)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(V=ms)}catch{}else e==="vungle"?V=fs:(s==="nucleo"||e==="nucleo")&&(V=bs)}var tn=nt(require("lottie-web"),1),Li=tn.default;typeof window!="undefined"&&(window.lottie=tn.default,window.__baseLottie=tn.default);var go=require("pixi.js");var Ti=require("pixi.js");var ho=null;function ki(s){ho=s}an();nn();var At=require("pixi.js");an();var wo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ji=wo;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&&(ji=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${ji}`))}}catch{}function xo(s){var t,n,i,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:(n=s[1])!=null?n:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(i=s.x)!=null?i:.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 be=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${ji}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new At.Container;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: ${i.type}, path: ${i.path}`);let r=await qe.load(e,i,n,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(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new At.Sprite(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(i.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 At.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let b of m)try{let y=await fetch(b);if(y.ok){o=await y.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,n){var i,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i: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=xo(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var Lt=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var Co=nt(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Co);rt();var sn=require("pixi.js");rt();var Ri=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Lt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let r=this.registry.get(a);if(!r){console.warn("[Assets] No config found for object:",a);return}try{let l=await be.create(a,r,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await be.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},Ao=new Ri,Lo=new Proxy(Ao,{get(s,e){if(e in s&&typeof s[e]=="function")return s[e].bind(s);if(s.get(e))return s.get(e)}});rt();var ko=require("pixi.js"),Ce={width:400,height:600,designWidth:400,scaleFactor:1},on={scale:1,position:1},$i=[];function Po(s,e,t,n,i,a,r){$i.push({element:s,originalScale:a,positionHelper:e,heightPercent:i}),e(s,t,n,i,a,r,!1)}function Io(){$i.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*Ce.scaleFactor;t(s,Ce.width,Ce.height,n,i,!0,!1)})}function zi(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Ce.width=s,Ce.height=e,Ce.scaleFactor=Math.min(s/Ce.designWidth,1.15),on.scale=Ce.scaleFactor,on.position=1,console.log(`[SCREEN] Global multipliers - scale: ${on.scale.toFixed(3)}`),Io()}var kt={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 Mo(s,e,t){let n=kt[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function jo(){return kt}var _o={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 rn(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Ae(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:rn(s[0],e.x),y:rn(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:rn(n.x,e.x),y:rn(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=_o[n])!=null?t:e}return e}function ln(s,e,t,n={}){var g,h,m,f,b,y;let i=Ae(t),a=(g=n.inset)!=null?g:{},r=(h=n.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=((y=a.bottom)!=null?y:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*i.x,y:c+u*i.y}}function cn(s,e,t,n={}){var m,f,b,y,v,E;let i=(m=n.inset)!=null?m:{},a=(f=n.padding)!=null?f:{x:0,y:0},r=((b=i.left)!=null?b:0)+a.x,o=((y=i.right)!=null?y:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((E=i.bottom)!=null?E:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Ae(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}}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==s||i!==e)&&(s=n,e=i,zi(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),zi(window.innerWidth,window.innerHeight),window.updateDebugConfig=Mo,window.getDebugConfig=jo,window.copyConfig=Uo,window.applyConfig=Tt,window.applyConfigForRatio=qo,window.positionAtBottom=Ms,window.positionAtTop=zo,window.positionAtCenter=$o,window.positionAtLeft=Do,window.positionAtRight=No,window.positionAtBottomLeft=Ho,window.positionAtBottomRight=Fo,window.positionAtTopLeft=Bo,window.positionAtTopRight=Go,window.applyPositionContract=Ro,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 dn(s,e,t=0){return s*e+t}function pn(s,e,t=0){return s*(1-e)+t}function un(s,e,t=0){return s*e+t}function gn(s,e,t=0){return s*(1-e)+t}function le(s,e=0){return s/2+e}function Oo(s,e){return s*e}function Ro(s,e,t,n){var r,o,l,c,d,p,u,g,h,m,f,b,y,v,E,C,M,O,w,P;let i=0,a=0;switch(n.type){case"top":i=le(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),a=dn(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=le(e,(p=(d=n.offset)==null?void 0:d.x)!=null?p:0),a=pn(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=un(e,n.percent,(m=(h=n.offset)==null?void 0:h.x)!=null?m:0),a=le(t,(b=(f=n.offset)==null?void 0:f.y)!=null?b:0);break;case"right":i=gn(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),a=le(t,(C=(E=n.offset)==null?void 0:E.y)!=null?C:0);break;case"center":i=le(e,(O=(M=n.offset)==null?void 0:M.x)!=null?O:0),a=le(t,(P=(w=n.offset)==null?void 0:w.y)!=null?P:0);break}s.position?s.position.set(i,a):(s.x=i,s.y=a),n.scale!==void 0&&n.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(n.scale,n.scale):(s.scale.x=n.scale,s.scale.y=n.scale))}function Ms(s,e,t,n=.2,i=1,a=!0,r=!1){let o=Oo(t,n),l=pn(t,n/2);Le(s,le(e),l);let c=a?i*Ce.scaleFactor:i;Te(s,c),r&&!$i.find(d=>d.element===s)&&Po(s,Ms,e,t,n,i,a)}function zo(s,e,t,n=.1,i=1){Le(s,le(e),dn(t,n)),Te(s,i)}function $o(s,e,t,n=0,i=0,a=1){Le(s,le(e,n),le(t,i)),Te(s,a)}function Do(s,e,t,n=.1,i=1){Le(s,un(e,n),le(t)),Te(s,i)}function No(s,e,t,n=.1,i=1){Le(s,gn(e,n),le(t)),Te(s,i)}function Ho(s,e,t,n=.05,i=.05,a=1){Le(s,un(e,i),pn(t,n)),Te(s,a)}function Fo(s,e,t,n=.05,i=.05,a=1){Le(s,gn(e,i),pn(t,n)),Te(s,a)}function Bo(s,e,t,n=.05,i=.05,a=1){Le(s,un(e,i),dn(t,n)),Te(s,a)}function Go(s,e,t,n=.05,i=.05,a=1){Le(s,gn(e,i),dn(t,n)),Te(s,a)}function Le(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 Te(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 Ve={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 Uo(s){return s&&Ve[s]?JSON.parse(JSON.stringify(Ve[s])):JSON.parse(JSON.stringify(kt))}function Tt(s){Object.keys(s).forEach(e=>{let t=e;kt[t]&&s[t]&&Object.assign(kt[t],s[t])}),console.log("Config applied:",s)}function qo(s,e){let t=s/e;t>1.6?(Tt(Ve.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(Tt(Ve.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(Tt(Ve.square),console.log("Applied SQUARE config for ratio:",t)):(Tt(Ve.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ve,s.resolveAnchorVec2=s.resolveAnchorVec2||Ae,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||ln,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||cn}An();function X(s,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(s,e);return`${s/n}:${e/n}`}var pd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:X(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:X(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:X(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:X(360,780)}],ud=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:X(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:X(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:X(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:X(412,915)}],gd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:X(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:X(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:X(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:X(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:X(800,1280)}],Qi=[{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:X(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:X(768,1024),mraidScale:.7}];var ea=[...Qi],ta=[{category:"playable",label:"Playable Ad",devices:Qi}],Ln=Qi[0];function Xe(s){return ea.find(e=>e.id===s)||Ln}function Qo(s){return ea.filter(e=>e.category===s)}Z();var De=class{async updateProperty(e,t,n,i={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,n);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}if(ae({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let p=window.applyEditableObjectConfig;if(typeof p=="function"){let u=window.__editableConfig,g=(d=(c=(l=u==null?void 0:u.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await p(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function na(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let r=i.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.")}},i.readAsDataURL(n)},e.click()}var Tn=class{constructor(){this.updateManager=new De}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,r);break;case"ai-edit":this.openAIEditor(t,n,r);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;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=((i=(n=t.transform)==null?void 0:n.scale)!=null?i: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 n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.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),i.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"}),i.categories&&!i.categories.includes(d)&&i.categories.push(d),i.libraryAssets&&!i.libraryAssets[d]&&(i.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(i.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),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((r=i==null?void 0:i.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");na({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let p=window.__debugContext;(h=(g=p==null?void 0:p.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let u=window.__highlightLibrarySlot;typeof u=="function"&&setTimeout(()=>{u(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(i):typeof r.schemas=="object"&&(o=r.schemas[i]),!(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,n){let i=window.__openAiEditor;if(typeof i=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||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),i(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 el=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],tl=["environment","ui","character","system","backgrounds"],nl=["bg","world","ui"],qs={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}}},kn=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=`
47
47
  <div class="wizard-card">
48
48
  <div class="wizard-header">
49
49
  <div class="wizard-title">
@@ -2296,7 +2296,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2296
2296
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
2297
2297
  </div>
2298
2298
  </div>
2299
- `,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 n;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),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=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,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-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,n=this.cropWidth*this.scale,i=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,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-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 n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,r=Math.min(i,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,d=(n-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",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.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,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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 i;if(!this.image||!((i=this.options)!=null&&i.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 n=e.toDataURL("image/png");this.options.onCrop(n),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 Oa().open(s)};Z();var D=require("pixi.js");Z();var ci=class{constructor(e){this.app=null;this.camera=new D.Container;this.mainContainer=new D.Container;this.uiContainer=new D.Container;this.gizmoLayer=new D.Container;this.screenFrame=new D.Graphics;this.gameFrame=new D.Graphics;this.gridLayer=new D.Graphics;this.spawnPointLayer=new D.Container;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 D.Graphics;this.anchorVisualizationLayer=new D.Graphics;this.moveHandle=new D.Graphics;this.scaleHandle=new D.Graphics;this.rotateHandle=new D.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:n}=e.detail;!t||!n||(this.hasUserCamera=!1,this.updateLayout({width:t,height:n}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:n}))};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 n=t.objectId,i=t.objectIds;if(n){this.syncFromConfig([n]);return}if(Array.isArray(i)&&i.length>0){this.syncFromConfig(i);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},n=t.objectId,i=t.texture;if(!n||!i)return;let a=this.objectMap.get(n);if(!a)return;let r=a.displayObject;if(r!=null&&r.texture)r.texture=i;else if(r!=null&&r.children){let c=r.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=i)}let o=this.getEditableObjectConfig(n);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var r;if(!this.isVisible)return;let t=(r=e==null?void 0:e.detail)!=null?r:{},n=Number(t.width),i=Number(t.height),a=Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var n,i;let t=(i=(n=e==null?void 0:e.detail)==null?void 0:n.objectId)!=null?i: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 n=this.getEventGlobalPoint(e);if(!n)return;let i=new D.Point(n.x,n.y),a=this.getPickCandidates(i);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=i,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(i,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=i,this.lastPickTime=r,this.setSelected(p)};this.handleGridSettings=e=>{var a,r,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,n=(r=e==null?void 0:e.detail)==null?void 0:r.gap,i=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof n=="number"&&Number.isFinite(n)&&n>2&&(this.gridGap=n),typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i),this.updateGrid()};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal()};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let n=t.x+this.spawnPointDrag.offset.x,i=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,n,i)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,n=this.getEditableObjectConfig(e),i=n?this.getSpawnPoints(n):null;n&&i&&(this.setNestedValue(n,"logic.props.spawnPoints",t),ae({objectId:e,path:"logic.props.spawnPoints",value:i},{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=>{};this.onDragEnd=()=>{this.dragMode&&(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 n=Math.sign(e.deltaY)<0?1.1:.9,i=Math.min(6,Math.max(.1,this.cameraScale*n)),a=new D.Point(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=i,this.camera.scale.set(i);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,n=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+n),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){var e;this.app||(this.app=new D.Application,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.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!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.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),(e=this.app)!=null&&e.ticker&&this.app.ticker.add(this.syncFromGameObjects),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){var e;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:asset-updated",this.handleAssetUpdated),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),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:asset-updated",this.handleAssetUpdated),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="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none"}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(n=r.getBounds)==null?void 0:n.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:i,order:u})}return t.sort((i,a)=>a.order-i.order),t.map(i=>i.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])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")),n=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let i=Number(t);Number.isFinite(i)&&i>2&&(this.gridGap=i)}if(n!==null){let i=Number(n);Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i)}}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(),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"),n=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),i=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:null}getRuntimeLayoutReference(){var a,r,o,l,c,d,p,u,g,h,m,f,b,y,v,E,C,M,O,w,P,j,T,I,A,L,S,x,_,k,R,z,N,Y;let e=window.__mainContainer;if(e){let F=(r=(a=e.scale)==null?void 0:a.x)!=null?r:1,G=(l=(o=e.scale)==null?void 0:o.y)!=null?l:F;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:F,y:G},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y}}),e}let t=window.__screenManager;if(t){let F=["gameplay","start","tutorial","endgame","loading"];for(let G of F){let B=(p=t.get)==null?void 0:p.call(t,G);if(B!=null&&B.visible){let W=(u=B.getContentLayer)==null?void 0:u.call(B);if(W){let ee=(g=B.x)!=null?g:0,me=(h=B.y)!=null?h:0,H=(m=W.x)!=null?m:0,ie=(f=W.y)!=null?f:0,ne=(y=(b=W.scale)==null?void 0:b.x)!=null?y:1,pe=(E=(v=W.scale)==null?void 0:v.y)!=null?E:ne;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:G,contentLayerScale:{x:ne,y:pe},position:{x:ee+H,y:me+ie}}),{scale:{x:ne,y:pe},position:{x:ee+H,y:me+ie},pivot:W.pivot?{x:W.pivot.x,y:W.pivot.y}:void 0}}}}for(let G of F){let B=(C=t.get)==null?void 0:C.call(t,G);if(B){if(!B.visible&&typeof B.updateLayout=="function"){let ee=window.gameApp;if((M=ee==null?void 0:ee.renderer)!=null&&M.screen){let me=ee.renderer.screen.width,H=ee.renderer.screen.height;me>0&&H>0&&B.updateLayout(me,H)}}let W=(O=B.getContentLayer)==null?void 0:O.call(B);if(W){let ee=(w=B.x)!=null?w:0,me=(P=B.y)!=null?P:0,H=(j=W.x)!=null?j:0,ie=(T=W.y)!=null?T:0,ne=(A=(I=W.scale)==null?void 0:I.x)!=null?A:1,pe=(S=(L=W.scale)==null?void 0:L.y)!=null?S:ne;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:G,visible:B.visible,contentLayerScale:{x:ne,y:pe},position:{x:ee+H,y:me+ie}}),{scale:{x:ne,y:pe},position:{x:ee+H,y:me+ie},pivot:W.pivot?{x:W.pivot.x,y:W.pivot.y}:void 0}}}}}let n=window.gameApp,i=(x=n==null?void 0:n.stage)!=null?x:null;if(i){let F=(k=(_=i.scale)==null?void 0:_.x)!=null?k:1,G=(z=(R=i.scale)==null?void 0:R.y)!=null?z:F;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:F,y:G},position:{x:(N=i.position)==null?void 0:N.x,y:(Y=i.position)==null?void 0:Y.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((l=n==null?void 0:n.getDisplayObject)==null?void 0:l.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.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;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,n=1,i=Number((o=(r=e.position)==null?void 0:r.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(i)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:i,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:n},position:{x:i,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(i,a),this.uiContainer.position.set(i,a),e.pivot&&((d=this.mainContainer.pivot)!=null&&d.set)&&((p=this.uiContainer.pivot)!=null&&p.set)){let f=Number((g=(u=e.pivot)==null?void 0:u.x)!=null?g:0),b=Number((m=(h=e.pivot)==null?void 0:h.y)!=null?m:0);Number.isFinite(f)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(f,b),this.uiContainer.pivot.set(f,b))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let n=this.getEditableConfig();return n!=null&&n.objects?typeof n.objects.get=="function"?(i=n.objects.get(e))!=null?i:null:(a=n.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let n=e();if(Array.isArray(n))return n}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 n=e!=null&&e.length?e:this.getEditableObjectIds(),i=new Set(n);if(!e)for(let a of Array.from(this.objectMap.keys()))i.has(a)||this.removeObject(a);for(let a of n){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 n,i;let t=this.objectMap.get(e);if(t){try{(i=(n=t.displayObject)==null?void 0:n.destroy)==null||i.call(n)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let n=this.getAssetKey(t),i=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(!i||i.assetKey!==n||i.isUi!==a){i&&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:n,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))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,b,y,v,E,C;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 O=await be.create(e,t,this.app);if(O instanceof D.Container)return O}}catch(M){console.warn("[SceneEditor] ObjectFactory failed for",e,M)}let n=t==null?void 0:t.ui,i=(d=t==null?void 0:t.render)!=null?d:{},a=(n==null?void 0:n.text)||(n==null?void 0:n.kind)==="text";if(!!i.background_color){let M=this.getScreen(),O=(p=M==null?void 0:M.width)!=null?p:0,w=(u=M==null?void 0:M.height)!=null?u:0,P=new D.Graphics,j=this.parseColor(i.background_color,0),T=typeof i.background_alpha=="number"?i.background_alpha:1;O>0&&w>0&&P.rect(0,0,O,w).fill({color:j,alpha:T});let I=new D.Container;return I.addChild(P),I}if(a){let M=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",O=new D.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(m=n==null?void 0:n.fontSize)!=null?m:16,fill:M,align:(f=n==null?void 0:n.align)!=null?f:"center",letterSpacing:(b=n==null?void 0:n.letterSpacing)!=null?b:0});return new D.Text({text:(y=n==null?void 0:n.text)!=null?y:"",style:O})}if((v=t==null?void 0:t.effects)!=null&&v.width||(E=t==null?void 0:t.effects)!=null&&E.height){let M=new D.Graphics,O=typeof t.effects.width=="number"?t.effects.width:100,w=typeof t.effects.height=="number"?t.effects.height:100,P=(C=t.effects.fill_color)!=null?C:"#ffffff",j=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,T=Number.parseInt(String(P).replace("#",""),16);return M.rect(0,0,O,w).fill({color:Number.isFinite(T)?T:16777215,alpha:j}),M}return new D.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let n=e.getLocalBounds();n&&n.width>0&&n.height>0&&(e.hitArea=new D.Rectangle(n.x,n.y,n.width,n.height))}}getAssetKey(e){var n;let t=(n=e==null?void 0:e.render)==null?void 0:n.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let n=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),i=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return n.includes("ui")||i.startsWith("ui")||i.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u,g,h;if(!e)return;let n=(r=t==null?void 0:t.render)!=null?r:{};typeof n.alpha=="number"&&(e.alpha=n.alpha),e.visible=n.visible!==!1,e.zIndex=typeof n.z_index=="number"?n.z_index:0;let i=(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:"bottom-right";i==="bottom-right"&&!((p=t==null?void 0:t.render)!=null&&p.anchor)&&!((u=t==null?void 0:t.transform)!=null&&u.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 bottom-right");let a=Ae(i,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}getAnchorLocalPoint(e,t=this.mainContainer){var d,p;let n=(d=this.getScreen())!=null?d:this.getRuntimeScreenSize();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let a=(e==null?void 0:e.position_ratio)!=null?cn(n.width,n.height,e.position_ratio):ln(n.width,n.height,(p=e==null?void 0:e.anchor)!=null?p:"top-right"),r=t.position.x,o=t.position.y,l=a.x-r,c=a.y-o;return new D.Point(l,c)}updateLayout(e){var i,a,r,o,l;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}});let n=this.getRuntimeLayoutReference();if(n){let c=Number((a=(i=n.position)==null?void 0:i.x)!=null?a:t.width/2),d=Number((o=(r=n.position)==null?void 0:r.y)!=null?o:t.height/2);this.mainContainer.position.set(c,d),this.uiContainer.position.set(c,d)}this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),console.log("[SceneEditor] updateLayout: result",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y}}),this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(l=this.app)!=null&&l.stage&&(this.app.stage.hitArea=new D.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,n=this.camera.toLocal(new D.Point(0,0)),i=this.camera.toLocal(new D.Point(t.width,t.height)),a=Math.min(n.x,i.x),r=Math.max(n.x,i.x),o=Math.min(n.y,i.y),l=Math.max(n.y,i.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(),this.gridLayer.visible=!0;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:this.gridAlpha})}updateGameFrame(e){var d,p,u;let t=(d=e!=null?e:this.getScreen())!=null?d:this.getRuntimeScreenSize();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let n=this.getRuntimeLayoutReference(),i=(u=(p=n==null?void 0:n.scale)==null?void 0:p.x)!=null?u:1,a=i>0?1/i:1,r=t.width*a,o=t.height*a,l=(t.width-r)/2,c=(t.height-o)/2;this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height&&this.lastGameFrameSize.frameScale===i||(this.lastGameFrameSize={width:t.width,height:t.height,frameScale:i},this.gameFrame.clear(),this.gameFrame.rect(l,c,r,o),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var n,i,a,r,o,l,c,d;if(!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode?this.selectedId:null;for(let[p,u]of this.objectMap.entries()){if(t&&p===t)continue;let g=e.get(p),h=((n=g==null?void 0:g.getDisplayObject)==null?void 0:n.call(g))||(g==null?void 0:g.pixiObject)||g;if(!h)continue;let m=(a=(i=u.displayObject)==null?void 0:i.parent)!=null?a:this.mainContainer,f=new D.Point;if(typeof h.getGlobalPosition=="function"){h.getGlobalPosition(f);let C=m.toLocal(f,this.camera);u.displayObject.position.set(C.x,C.y)}else if(h.worldTransform){f.set(h.worldTransform.tx,h.worldTransform.ty);let C=m.toLocal(f,this.camera);u.displayObject.position.set(C.x,C.y)}let b=this.getWorldScale(h);if(b){let C=Number((o=(r=m.scale)==null?void 0:r.x)!=null?o:1)||1,M=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,O=b.x/C,w=b.y/M;(d=u.displayObject.scale)!=null&&d.set?u.displayObject.scale.set(O,w):u.displayObject.scale&&(u.displayObject.scale.x=O,u.displayObject.scale.y=w)}let y=this.getWorldRotation(h);if(typeof y=="number"){let C=m?m.rotation:0;u.displayObject.rotation=y-C}let v=h.parent,E=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(h):0;typeof h.zIndex=="number"?u.displayObject.zIndex=h.zIndex:Number.isFinite(E)&&(u.displayObject.zIndex=E)}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 n=Math.sqrt(t.a*t.a+t.b*t.b),i=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(n)||!Number.isFinite(i)?null:{x:n,y:i}}getWorldRotation(e){var n,i;let t=(i=e==null?void 0:e.worldTransform)!=null?i:(n=e==null?void 0:e.transform)==null?void 0:n.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.getScreen())!=null?a:this.getRuntimeScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,n=this.app.renderer.height,i=Math.max(.01,Math.min(t/e.width,n/e.height));this.cameraScale=i,this.camera.scale.set(i),this.camera.position.set((t-e.width*i)/2,(n-e.height*i)/2)}updateGizmos(){var c,d;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=(d=(c=e.displayObject).getBounds)==null?void 0:d.call(c);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new D.Point(t.x,t.y)),i=this.camera.toLocal(new D.Point(t.x+t.width,t.y+t.height)),a=i.x-n.x,r=i.y-n.y,o=n.x+a/2,l=n.y+r/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(n.x,n.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}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((n,i)=>{let a=new D.Graphics;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(n);a.position.set(r.x,r.y),a.cursor="move",a.eventMode="none",this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var n;(n=t.destroy)==null||n.call(t)})}isSpawnerConfig(e){var n,i;return((n=e==null?void 0:e.logic)==null?void 0:n.id)==="Spawner"?!0:String(((i=e==null?void 0:e.identity)==null?void 0:i.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var n,i;let t=(i=(n=e==null?void 0:e.logic)==null?void 0:n.props)==null?void 0:i.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 D.Point(e.x,e.y)),n=new D.Point;return this.camera.toLocal(t,void 0,n),n}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=this.getSpawnPoints(n);if(!i||!i[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=i[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new D.Point(r.x-a.x,r.y-a.y),startPoints:i.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,n,i){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:n,y:i}:{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 n=window.__previewSelectObject;typeof n=="function"&&n(e)}}startDrag(e,t){}getDragStartValue(e,t){var n,i,a;return e==="move"?(n=t==null?void 0:t.position)!=null?n:{x:0,y:0}:e==="scale"?(i=t==null?void 0:t.scale)!=null?i: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 n=e-this.dragAnchorLocal.x,i=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:n-l,y:i-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var i;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(i=t.transform)!=null?i:{};t.transform||(t.transform=n),n.scale=Math.round(e*100)/100}updateLiveConfigRotation(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.toDegrees(e),a=typeof n.rotation=="number"?n.rotation:0;Math.abs(i-a)>.01&&(n.rotation=Math.round(i*100)/100)}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),ae({objectId:e,path:t,value:n},{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 n=this.getEditableObjectConfig(t),i=window.applyEditableObjectConfig;typeof i=="function"&&n&&i(t,n)}))}setNestedValue(e,t,n){let i=t.split("."),a=e;for(let r=0;r<i.length-1;r+=1){let o=i[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[i[i.length-1]]=n}buildPositionValue(e,t){let n=e==null?void 0:e.position,i=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(n)?[i,a]:{x:i,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}getPointerButton(e){var t,n,i;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((i=(n=e==null?void 0:e.data)==null?void 0:n.originalEvent)==null?void 0:i.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 D.Point(t.x,t.y);if(!this.app)return null;let n=e==null?void 0:e.clientX,i=e==null?void 0:e.clientY;if(typeof n!="number"||typeof i!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(n-a.left)*(this.app.renderer.width/a.width),o=(i-a.top)*(this.app.renderer.height/a.height);return new D.Point(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 D.Point(o.x,o.y)}let n=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!n)return null;let i=new D.Point;return t.toLocal(new D.Point(n.x,n.y),void 0,i),i}getPointerInContainer(e,t,n){if(!this.app)return null;let i=this.app.canvas.getBoundingClientRect(),a=(e-i.left)*(this.app.renderer.width/i.width),r=(t-i.top)*(this.app.renderer.height/i.height),o=new D.Point;return n.toLocal(new D.Point(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim().replace("#",""),i=Number.parseInt(n,16);if(Number.isFinite(i))return i}return t}};var di=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[Xe("playable-portrait"),Xe("iphone-14"),Xe("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.hasForceSynced=!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,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,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=Xe(e.defaultDevice||Ln.id),this.debugPanel=new Ft,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 n=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=n===null?!0:n==="true"}catch{}let t="dark";try{let n=window.localStorage.getItem(this.getThemeStorageKey());(n==="light"||n==="dark")&&(t=n)}catch{}this.setTheme(t),this.sceneEditor=new ci({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,this.scheduleForceSync()}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()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(n=>{console.warn("[PreviewShell] Force sync on refresh failed:",n)})},250))}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 i,a;let n=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Xe(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),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(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.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"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-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(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,r=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let p=c.getBoundingClientRect().width,u=n==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=u?u.offsetWidth:n==="left"?350:300,m=p-g-200;return Math.max(200,m)},o=c=>{let d=n==="left"?c.clientX-i:i-c.clientX,p=r(),u=Math.max(200,Math.min(p,a+d));e.style.width=`${u}px`;let g=this.container.querySelector(".preview-main");if(g){let m=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${m} minmax(${b}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),i=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),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"}`}getThemeStorageKey(){return`handler_preview_theme::${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]"),n=this.container.querySelector("[data-preview-split]");e&&Je(this.scenePane,e,n!=null?n:this.previewContainer),t&&ri(this.scenePane,t,void 0,260,200);let i=this.getStoredSceneWidth();i&&(this.scenePane.style.width=`${i}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 n;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(n=this.sceneEditor)==null||n.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=`
2299
+ `,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 n;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),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=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,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-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,n=this.cropWidth*this.scale,i=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,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-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 n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,r=Math.min(i,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,d=(n-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",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.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,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,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 i;if(!this.image||!((i=this.options)!=null&&i.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 n=e.toDataURL("image/png");this.options.onCrop(n),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 Oa().open(s)};Z();var D=require("pixi.js");Z();var ci=class{constructor(e){this.app=null;this.camera=new D.Container;this.mainContainer=new D.Container;this.uiContainer=new D.Container;this.gizmoLayer=new D.Container;this.screenFrame=new D.Graphics;this.gameFrame=new D.Graphics;this.gridLayer=new D.Graphics;this.spawnPointLayer=new D.Container;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 D.Graphics;this.anchorVisualizationLayer=new D.Graphics;this.moveHandle=new D.Graphics;this.scaleHandle=new D.Graphics;this.rotateHandle=new D.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:n}=e.detail;!t||!n||(this.hasUserCamera=!1,this.updateLayout({width:t,height:n}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:n}))};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 n=t.objectId,i=t.objectIds;if(n){this.syncFromConfig([n]);return}if(Array.isArray(i)&&i.length>0){this.syncFromConfig(i);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},n=t.objectId,i=t.texture;if(!n||!i)return;let a=this.objectMap.get(n);if(!a)return;let r=a.displayObject;if(r!=null&&r.texture)r.texture=i;else if(r!=null&&r.children){let c=r.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=i)}let o=this.getEditableObjectConfig(n);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var r;if(!this.isVisible)return;let t=(r=e==null?void 0:e.detail)!=null?r:{},n=Number(t.width),i=Number(t.height),a=Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var n,i;let t=(i=(n=e==null?void 0:e.detail)==null?void 0:n.objectId)!=null?i: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 n=this.getEventGlobalPoint(e);if(!n)return;let i=new D.Point(n.x,n.y),a=this.getPickCandidates(i);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=i,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(i,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=i,this.lastPickTime=r,this.setSelected(p)};this.handleGridSettings=e=>{var a,r,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,n=(r=e==null?void 0:e.detail)==null?void 0:r.gap,i=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof n=="number"&&Number.isFinite(n)&&n>2&&(this.gridGap=n),typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i),this.updateGrid()};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal()};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let n=t.x+this.spawnPointDrag.offset.x,i=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,n,i)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,n=this.getEditableObjectConfig(e),i=n?this.getSpawnPoints(n):null;n&&i&&(this.setNestedValue(n,"logic.props.spawnPoints",t),ae({objectId:e,path:"logic.props.spawnPoints",value:i},{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=>{};this.onDragEnd=()=>{this.dragMode&&(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 n=Math.sign(e.deltaY)<0?1.1:.9,i=Math.min(6,Math.max(.1,this.cameraScale*n)),a=new D.Point(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=i,this.camera.scale.set(i);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,n=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+n),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){var e;this.app||(this.app=new D.Application,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.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!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.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),(e=this.app)!=null&&e.ticker&&this.app.ticker.add(this.syncFromGameObjects),!this.isVisible&&this.app.ticker&&this.app.ticker.stop())}destroy(){var e;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:asset-updated",this.handleAssetUpdated),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),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:asset-updated",this.handleAssetUpdated),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="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none"}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(n=r.getBounds)==null?void 0:n.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:i,order:u})}return t.sort((i,a)=>a.order-i.order),t.map(i=>i.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])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")),n=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let i=Number(t);Number.isFinite(i)&&i>2&&(this.gridGap=i)}if(n!==null){let i=Number(n);Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i)}}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(),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"),n=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),i=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:null}getRuntimeLayoutReference(){var a,r,o,l,c,d,p,u,g,h,m,f,b,y,v,E,C,M,O,w,P,j,T,I,A,L,S,x,_,k,R,z,N,Y;let e=window.__mainContainer;if(e){let F=(r=(a=e.scale)==null?void 0:a.x)!=null?r:1,G=(l=(o=e.scale)==null?void 0:o.y)!=null?l:F;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:F,y:G},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y}}),e}let t=window.__screenManager;if(t){let F=["gameplay","start","tutorial","endgame","loading"];for(let G of F){let B=(p=t.get)==null?void 0:p.call(t,G);if(B!=null&&B.visible){let W=(u=B.getContentLayer)==null?void 0:u.call(B);if(W){let ee=(g=B.x)!=null?g:0,me=(h=B.y)!=null?h:0,H=(m=W.x)!=null?m:0,ie=(f=W.y)!=null?f:0,ne=(y=(b=W.scale)==null?void 0:b.x)!=null?y:1,pe=(E=(v=W.scale)==null?void 0:v.y)!=null?E:ne;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:G,contentLayerScale:{x:ne,y:pe},position:{x:ee+H,y:me+ie}}),{scale:{x:ne,y:pe},position:{x:ee+H,y:me+ie},pivot:W.pivot?{x:W.pivot.x,y:W.pivot.y}:void 0}}}}for(let G of F){let B=(C=t.get)==null?void 0:C.call(t,G);if(B){if(!B.visible&&typeof B.updateLayout=="function"){let ee=window.gameApp;if((M=ee==null?void 0:ee.renderer)!=null&&M.screen){let me=ee.renderer.screen.width,H=ee.renderer.screen.height;me>0&&H>0&&B.updateLayout(me,H)}}let W=(O=B.getContentLayer)==null?void 0:O.call(B);if(W){let ee=(w=B.x)!=null?w:0,me=(P=B.y)!=null?P:0,H=(j=W.x)!=null?j:0,ie=(T=W.y)!=null?T:0,ne=(A=(I=W.scale)==null?void 0:I.x)!=null?A:1,pe=(S=(L=W.scale)==null?void 0:L.y)!=null?S:ne;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:G,visible:B.visible,contentLayerScale:{x:ne,y:pe},position:{x:ee+H,y:me+ie}}),{scale:{x:ne,y:pe},position:{x:ee+H,y:me+ie},pivot:W.pivot?{x:W.pivot.x,y:W.pivot.y}:void 0}}}}}let n=window.gameApp,i=(x=n==null?void 0:n.stage)!=null?x:null;if(i){let F=(k=(_=i.scale)==null?void 0:_.x)!=null?k:1,G=(z=(R=i.scale)==null?void 0:R.y)!=null?z:F;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:F,y:G},position:{x:(N=i.position)==null?void 0:N.x,y:(Y=i.position)==null?void 0:Y.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((l=n==null?void 0:n.getDisplayObject)==null?void 0:l.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.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;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,n=1,i=Number((o=(r=e.position)==null?void 0:r.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(i)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:i,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:n},position:{x:i,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(i,a),this.uiContainer.position.set(i,a),e.pivot&&((d=this.mainContainer.pivot)!=null&&d.set)&&((p=this.uiContainer.pivot)!=null&&p.set)){let f=Number((g=(u=e.pivot)==null?void 0:u.x)!=null?g:0),b=Number((m=(h=e.pivot)==null?void 0:h.y)!=null?m:0);Number.isFinite(f)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(f,b),this.uiContainer.pivot.set(f,b))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getEditableObjectConfig(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let n=this.getEditableConfig();return n!=null&&n.objects?typeof n.objects.get=="function"?(i=n.objects.get(e))!=null?i:null:(a=n.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let n=e();if(Array.isArray(n))return n}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 n=e!=null&&e.length?e:this.getEditableObjectIds(),i=new Set(n);if(!e)for(let a of Array.from(this.objectMap.keys()))i.has(a)||this.removeObject(a);for(let a of n){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 n,i;let t=this.objectMap.get(e);if(t){try{(i=(n=t.displayObject)==null?void 0:n.destroy)==null||i.call(n)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let n=this.getAssetKey(t),i=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(!i||i.assetKey!==n||i.isUi!==a){i&&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:n,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))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,b,y,v,E,C;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 O=await be.create(e,t,this.app);if(O instanceof D.Container)return O}}catch(M){console.warn("[SceneEditor] ObjectFactory failed for",e,M)}let n=t==null?void 0:t.ui,i=(d=t==null?void 0:t.render)!=null?d:{},a=(n==null?void 0:n.text)||(n==null?void 0:n.kind)==="text";if(!!i.background_color){let M=this.getScreen(),O=(p=M==null?void 0:M.width)!=null?p:0,w=(u=M==null?void 0:M.height)!=null?u:0,P=new D.Graphics,j=this.parseColor(i.background_color,0),T=typeof i.background_alpha=="number"?i.background_alpha:1;O>0&&w>0&&P.rect(0,0,O,w).fill({color:j,alpha:T});let I=new D.Container;return I.addChild(P),I}if(a){let M=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",O=new D.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(m=n==null?void 0:n.fontSize)!=null?m:16,fill:M,align:(f=n==null?void 0:n.align)!=null?f:"center",letterSpacing:(b=n==null?void 0:n.letterSpacing)!=null?b:0});return new D.Text({text:(y=n==null?void 0:n.text)!=null?y:"",style:O})}if((v=t==null?void 0:t.effects)!=null&&v.width||(E=t==null?void 0:t.effects)!=null&&E.height){let M=new D.Graphics,O=typeof t.effects.width=="number"?t.effects.width:100,w=typeof t.effects.height=="number"?t.effects.height:100,P=(C=t.effects.fill_color)!=null?C:"#ffffff",j=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,T=Number.parseInt(String(P).replace("#",""),16);return M.rect(0,0,O,w).fill({color:Number.isFinite(T)?T:16777215,alpha:j}),M}return new D.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let n=e.getLocalBounds();n&&n.width>0&&n.height>0&&(e.hitArea=new D.Rectangle(n.x,n.y,n.width,n.height))}}getAssetKey(e){var n;let t=(n=e==null?void 0:e.render)==null?void 0:n.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let n=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),i=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return n.includes("ui")||i.startsWith("ui")||i.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u,g,h;if(!e)return;let n=(r=t==null?void 0:t.render)!=null?r:{};typeof n.alpha=="number"&&(e.alpha=n.alpha),e.visible=n.visible!==!1,e.zIndex=typeof n.z_index=="number"?n.z_index:0;let i=(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:"bottom-right";i==="bottom-right"&&!((p=t==null?void 0:t.render)!=null&&p.anchor)&&!((u=t==null?void 0:t.transform)!=null&&u.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 bottom-right");let a=Ae(i,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}getAnchorLocalPoint(e,t=this.mainContainer){var d,p;let n=(d=this.getScreen())!=null?d:this.getRuntimeScreenSize();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let a=(e==null?void 0:e.position_ratio)!=null?cn(n.width,n.height,e.position_ratio):ln(n.width,n.height,(p=e==null?void 0:e.anchor)!=null?p:"top-right"),r=t.position.x,o=t.position.y,l=a.x-r,c=a.y-o;return new D.Point(l,c)}updateLayout(e){var i,a,r,o,l;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}});let n=this.getRuntimeLayoutReference();if(n){let c=Number((a=(i=n.position)==null?void 0:i.x)!=null?a:t.width/2),d=Number((o=(r=n.position)==null?void 0:r.y)!=null?o:t.height/2);this.mainContainer.position.set(c,d),this.uiContainer.position.set(c,d)}this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),console.log("[SceneEditor] updateLayout: result",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y}}),this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(l=this.app)!=null&&l.stage&&(this.app.stage.hitArea=new D.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,n=this.camera.toLocal(new D.Point(0,0)),i=this.camera.toLocal(new D.Point(t.width,t.height)),a=Math.min(n.x,i.x),r=Math.max(n.x,i.x),o=Math.min(n.y,i.y),l=Math.max(n.y,i.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(),this.gridLayer.visible=!0;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:this.gridAlpha})}updateGameFrame(e){var o;let t=(o=e!=null?e:this.getScreen())!=null?o:this.getRuntimeScreenSize();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let n=t.width,i=t.height,a=0,r=0;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(a,r,n,i),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var n,i,a,r,o,l,c,d;if(!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode?this.selectedId:null;for(let[p,u]of this.objectMap.entries()){if(t&&p===t)continue;let g=e.get(p),h=((n=g==null?void 0:g.getDisplayObject)==null?void 0:n.call(g))||(g==null?void 0:g.pixiObject)||g;if(!h)continue;let m=(a=(i=u.displayObject)==null?void 0:i.parent)!=null?a:this.mainContainer,f=new D.Point;if(typeof h.getGlobalPosition=="function"){h.getGlobalPosition(f);let C=m.toLocal(f,this.camera);u.displayObject.position.set(C.x,C.y)}else if(h.worldTransform){f.set(h.worldTransform.tx,h.worldTransform.ty);let C=m.toLocal(f,this.camera);u.displayObject.position.set(C.x,C.y)}let b=this.getWorldScale(h);if(b){let C=Number((o=(r=m.scale)==null?void 0:r.x)!=null?o:1)||1,M=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,O=b.x/C,w=b.y/M;(d=u.displayObject.scale)!=null&&d.set?u.displayObject.scale.set(O,w):u.displayObject.scale&&(u.displayObject.scale.x=O,u.displayObject.scale.y=w)}let y=this.getWorldRotation(h);if(typeof y=="number"){let C=m?m.rotation:0;u.displayObject.rotation=y-C}let v=h.parent,E=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(h):0;typeof h.zIndex=="number"?u.displayObject.zIndex=h.zIndex:Number.isFinite(E)&&(u.displayObject.zIndex=E)}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 n=Math.sqrt(t.a*t.a+t.b*t.b),i=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(n)||!Number.isFinite(i)?null:{x:n,y:i}}getWorldRotation(e){var n,i;let t=(i=e==null?void 0:e.worldTransform)!=null?i:(n=e==null?void 0:e.transform)==null?void 0:n.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.getScreen())!=null?a:this.getRuntimeScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,n=this.app.renderer.height,i=Math.max(.01,Math.min(t/e.width,n/e.height));this.cameraScale=i,this.camera.scale.set(i),this.camera.position.set((t-e.width*i)/2,(n-e.height*i)/2)}updateGizmos(){var c,d;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=(d=(c=e.displayObject).getBounds)==null?void 0:d.call(c);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new D.Point(t.x,t.y)),i=this.camera.toLocal(new D.Point(t.x+t.width,t.y+t.height)),a=i.x-n.x,r=i.y-n.y,o=n.x+a/2,l=n.y+r/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(n.x,n.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}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((n,i)=>{let a=new D.Graphics;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(n);a.position.set(r.x,r.y),a.cursor="move",a.eventMode="none",this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var n;(n=t.destroy)==null||n.call(t)})}isSpawnerConfig(e){var n,i;return((n=e==null?void 0:e.logic)==null?void 0:n.id)==="Spawner"?!0:String(((i=e==null?void 0:e.identity)==null?void 0:i.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var n,i;let t=(i=(n=e==null?void 0:e.logic)==null?void 0:n.props)==null?void 0:i.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 D.Point(e.x,e.y)),n=new D.Point;return this.camera.toLocal(t,void 0,n),n}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=this.getSpawnPoints(n);if(!i||!i[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=i[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new D.Point(r.x-a.x,r.y-a.y),startPoints:i.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,n,i){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:n,y:i}:{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 n=window.__previewSelectObject;typeof n=="function"&&n(e)}}startDrag(e,t){}getDragStartValue(e,t){var n,i,a;return e==="move"?(n=t==null?void 0:t.position)!=null?n:{x:0,y:0}:e==="scale"?(i=t==null?void 0:t.scale)!=null?i: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 n=e-this.dragAnchorLocal.x,i=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:n-l,y:i-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var i;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(i=t.transform)!=null?i:{};t.transform||(t.transform=n),n.scale=Math.round(e*100)/100}updateLiveConfigRotation(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.toDegrees(e),a=typeof n.rotation=="number"?n.rotation:0;Math.abs(i-a)>.01&&(n.rotation=Math.round(i*100)/100)}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),ae({objectId:e,path:t,value:n},{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 n=this.getEditableObjectConfig(t),i=window.applyEditableObjectConfig;typeof i=="function"&&n&&i(t,n)}))}setNestedValue(e,t,n){let i=t.split("."),a=e;for(let r=0;r<i.length-1;r+=1){let o=i[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[i[i.length-1]]=n}buildPositionValue(e,t){let n=e==null?void 0:e.position,i=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(n)?[i,a]:{x:i,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}getPointerButton(e){var t,n,i;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((i=(n=e==null?void 0:e.data)==null?void 0:n.originalEvent)==null?void 0:i.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 D.Point(t.x,t.y);if(!this.app)return null;let n=e==null?void 0:e.clientX,i=e==null?void 0:e.clientY;if(typeof n!="number"||typeof i!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(n-a.left)*(this.app.renderer.width/a.width),o=(i-a.top)*(this.app.renderer.height/a.height);return new D.Point(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 D.Point(o.x,o.y)}let n=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!n)return null;let i=new D.Point;return t.toLocal(new D.Point(n.x,n.y),void 0,i),i}getPointerInContainer(e,t,n){if(!this.app)return null;let i=this.app.canvas.getBoundingClientRect(),a=(e-i.left)*(this.app.renderer.width/i.width),r=(t-i.top)*(this.app.renderer.height/i.height),o=new D.Point;return n.toLocal(new D.Point(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim().replace("#",""),i=Number.parseInt(n,16);if(Number.isFinite(i))return i}return t}};var di=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[Xe("playable-portrait"),Xe("iphone-14"),Xe("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.hasForceSynced=!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,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,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=Xe(e.defaultDevice||Ln.id),this.debugPanel=new Ft,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 n=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=n===null?!0:n==="true"}catch{}let t="dark";try{let n=window.localStorage.getItem(this.getThemeStorageKey());(n==="light"||n==="dark")&&(t=n)}catch{}this.setTheme(t),this.sceneEditor=new ci({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,this.scheduleForceSync()}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()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(n=>{console.warn("[PreviewShell] Force sync on refresh failed:",n)})},250))}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 i,a;let n=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Xe(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),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(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.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"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-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(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,r=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let p=c.getBoundingClientRect().width,u=n==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=u?u.offsetWidth:n==="left"?350:300,m=p-g-200;return Math.max(200,m)},o=c=>{let d=n==="left"?c.clientX-i:i-c.clientX,p=r(),u=Math.max(200,Math.min(p,a+d));e.style.width=`${u}px`;let g=this.container.querySelector(".preview-main");if(g){let m=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${m} minmax(${b}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),i=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),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"}`}getThemeStorageKey(){return`handler_preview_theme::${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]"),n=this.container.querySelector("[data-preview-split]");e&&Je(this.scenePane,e,n!=null?n:this.previewContainer),t&&ri(this.scenePane,t,void 0,260,200);let i=this.getStoredSceneWidth();i&&(this.scenePane.style.width=`${i}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 n;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(n=this.sceneEditor)==null||n.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=`
2300
2300
  <div class="preview-toolbar">
2301
2301
  <div class="preview-toolbar-left">
2302
2302
  <span class="preview-logo">PREVIEWER</span>
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{E as J,F as K,G as L,H as M,I as N,J as O,K as P,L as Q,M as R,N as S,O as T,P as U,Q as V,R as W,S as X,T as Y,U as Z,a}from"./chunk-KMXVYHSV.js";import"./chunk-I5OOVR5U.js";import{a as u,b as v,c as w,d as x,e as y,f as z,g as A,h as B,i as C,j as D,k as E,l as F,m as G,n as H,o as I}from"./chunk-PW2FGMCO.js";import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q,q as r,r as s,s as t}from"./chunk-HVKF2KYL.js";import"./chunk-E6WJCS24.js";import"./chunk-JXBG6UFL.js";export{U as COLORS,F as ConfigWatcher,O as DebugPanel,E as DefaultReloadStrategy,Y as Handler,X as PlayableLoadingScreen,P as PreviewShell,V as STROKE_WIDTH,W as THEME,d as applyConfigOverride,e as applyConfigOverrides,r as applyConfigsToDisk,B as applyDefaults,a as baseLottie,T as bootstrap,f as clearConfigOverrides,g as clearConfigOverridesForObject,j as configOverrideManager,Q as createPreviewShell,o as deepClone,Z as default,L as defaultPreset,K as deviceGroups,J as devicePresets,G as diffConfigs,p as exportConfigsAsJSON,i as getConfigOverrides,q as getConfigStateSummary,b as getOverrideMode,M as getPresetById,N as getPresetsByCategory,w as loadAllObjectConfigs,u as loadComponentSchemas,x as loadEngineConfig,y as loadGamePromptConfig,C as loadObjectCentricConfig,v as loadObjectConfig,z as loadSceneConfig,l as redoLastConfigChange,H as rehydrateObject,h as removeConfigOverride,s as resetToApplied,t as resetToOriginal,S as setBootstrapDependencies,c as setOverrideMode,I as setupHotReload,R as setupLiveEditBridge,D as toLegacyFormat,m as trackObjectCreation,n as trackObjectDeletion,k as undoLastConfigChange,A as validateObjectConfig};
1
+ import{E as J,F as K,G as L,H as M,I as N,J as O,K as P,L as Q,M as R,N as S,O as T,P as U,Q as V,R as W,S as X,T as Y,U as Z,a}from"./chunk-G7EAC7UJ.js";import"./chunk-I5OOVR5U.js";import{a as u,b as v,c as w,d as x,e as y,f as z,g as A,h as B,i as C,j as D,k as E,l as F,m as G,n as H,o as I}from"./chunk-PW2FGMCO.js";import{a as b,b as c,c as d,d as e,e as f,f as g,g as h,h as i,i as j,j as k,k as l,l as m,m as n,n as o,o as p,p as q,q as r,r as s,s as t}from"./chunk-HVKF2KYL.js";import"./chunk-E6WJCS24.js";import"./chunk-JXBG6UFL.js";export{U as COLORS,F as ConfigWatcher,O as DebugPanel,E as DefaultReloadStrategy,Y as Handler,X as PlayableLoadingScreen,P as PreviewShell,V as STROKE_WIDTH,W as THEME,d as applyConfigOverride,e as applyConfigOverrides,r as applyConfigsToDisk,B as applyDefaults,a as baseLottie,T as bootstrap,f as clearConfigOverrides,g as clearConfigOverridesForObject,j as configOverrideManager,Q as createPreviewShell,o as deepClone,Z as default,L as defaultPreset,K as deviceGroups,J as devicePresets,G as diffConfigs,p as exportConfigsAsJSON,i as getConfigOverrides,q as getConfigStateSummary,b as getOverrideMode,M as getPresetById,N as getPresetsByCategory,w as loadAllObjectConfigs,u as loadComponentSchemas,x as loadEngineConfig,y as loadGamePromptConfig,C as loadObjectCentricConfig,v as loadObjectConfig,z as loadSceneConfig,l as redoLastConfigChange,H as rehydrateObject,h as removeConfigOverride,s as resetToApplied,t as resetToOriginal,S as setBootstrapDependencies,c as setOverrideMode,I as setupHotReload,R as setupLiveEditBridge,D as toLegacyFormat,m as trackObjectCreation,n as trackObjectDeletion,k as undoLastConfigChange,A as validateObjectConfig};