handler-playable-sdk 1.0.83 → 1.0.84

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-R2YB6RWS.js → chunk-ZDXLQU2P.js} +82 -82
  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 +28 -28
  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 +13 -13
  38. package/dist/three/index.js +1 -1
  39. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var to=Object.create;var en=Object.defineProperty;var no=Object.getOwnPropertyDescriptor;var io=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty;var Ee=(s,e)=>()=>(s&&(e=s(s=0)),e);var Lt=(s,e)=>{for(var t in e)en(s,t,{get:e[t],enumerable:!0})},Ka=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of io(e))!so.call(s,i)&&i!==t&&en(s,i,{get:()=>e[i],enumerable:!(n=no(e,i))||n.enumerable});return s};var at=(s,e,t)=>(t=s!=null?to(ao(s)):{},Ka(e||!s||!s.__esModule?en(t,"default",{value:s,enumerable:!0}):t,s)),ro=s=>Ka(en({},"__esModule",{value:!0}),s);var ce,sn=Ee(()=>{"use strict";ce=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};ce.store=new Map});function fo(){var s,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(s=document.querySelector("script"))==null?void 0:s.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function mo(){try{if(typeof window!="undefined"){let s=await fetch("./build-settings.json");if(s.ok){let e=await s.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function bo(){try{if(typeof window!="undefined"){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);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function yo(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${W}`),Object.keys(Ce).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(Ce)),Ce;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),Ce={...window.INLINE_ASSETS},Ce;if(!(W==="publish"&&be!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),Ce;if(!Pi){let e=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",e),Pi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return Ce=await Pi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(Ce)),Ce}function Ii(s){return s===null||typeof s!="object"||(Object.freeze(s),Object.values(s).forEach(e=>Ii(e))),s}function vo(s=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=s,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,s,e),i.strokeStyle="#000",i.strokeRect(0,0,s,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",s/2,e/2),Ae.Texture.from(n)}function Mi(s,e){Ts.set(s,e)}var Ae,Ls,ks,Ve,W,be,Re,Ce,Pi,Ts,We,rn=Ee(()=>{"use strict";Ae=require("pixi.js");sn();Ls=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ks=fo(),Ve=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,W=ks?"publish":Ls,be=Ve==null?void 0:Ve.assetsInlined;Ve!=null&&Ve.buildMode&&(W=Ve.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${W}`));Re=bo();Re!=null&&Re.buildMode&&(W=Re.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${W}`));(Re==null?void 0:Re.assetsInlined)!==void 0&&(be=Re.assetsInlined);mo().then(s=>{s!=null&&s.buildMode&&s.buildMode!==W&&(W=s.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${W}`)),(s==null?void 0:s.assetsInlined)!==void 0&&(be=s.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Ls}, Runtime: ${ks?"publish":"dev"}, Effective: ${W}`);Ce={},Pi=null;Ts=new Map;We=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,r=ce.get(a);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${W}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await yo(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let p=t.path.split("/");if(p.length>=2){let u=p[p.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),W==="publish"&&be!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let d=Ts.get(t.type);if(d)try{let p=await d(t.path,l,e,n);return ce.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}try{let p;switch(t.type){case"image":p=await this.loadImage(t.path,l);break;case"json":p=await this.loadJSON(t.path,l),p=Ii(p);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return ce.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}}static async loadImage(e,t){let n=W==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${W}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await Ae.Assets.load(t)}catch(a){throw console.error("[AssetLoader] Failed to load texture from data URI:",a),a}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await Ae.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Ae.Assets.load(e)}return await Ae.Assets.load(e)}static async loadJSON(e,t){let n=W==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${W}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(W==="dev"){let a=t==="image"?vo():Ii({__placeholder:!0,type:t});return ce.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Mi("image",async(s,e)=>{let t=W==="publish",n=t&&be!==!1,i=W==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${W}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Ae.Assets.load(e)}let r=s;return(i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),Ae.Assets.load(e||r)});Mi("json",async(s,e)=>{let t=W==="publish",n=t&&be!==!1,i=W==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${W}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=s;if((i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(r);if(!o.ok)throw new Error(`JSON fetch failed: ${s}`);return o.json()})});var Is={};Lt(Is,{AssetTextures:()=>ve,initAssetTextures:()=>Oi});function Oi(s,e){Ps.init(s,e),typeof window!="undefined"&&(window.__AssetTextures=ve)}var ji,Ps,ve,lt=Ee(()=>{"use strict";rn();ji=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var r;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let d=async()=>{var p;try{let u=(p=l.identity)==null?void 0:p.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await We.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(d()):a.push(d())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,d,p;try{let u=(d=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:d.call(c,o);return!!((p=u==null?void 0:u.render)!=null&&p.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),r>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},r)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},Ps=new ji,ve=new Proxy(Ps,{get(s,e){return e in s&&typeof s[e]=="function"?s[e].bind(s):s.get(e)},set(s,e,t){return s.set(e,t),!0}})});var Ne={};Lt(Ne,{applyConfigOverride:()=>re,applyConfigOverrides:()=>$e,applyConfigsToDisk:()=>vn,clearConfigOverrides:()=>pe,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,deepClone:()=>Q,exportConfigsAsJSON:()=>Xe,getConfigOverrides:()=>se,getConfigStateSummary:()=>De,getOverrideMode:()=>jt,redoLastConfigChange:()=>yn,removeConfigOverride:()=>Ot,resetToApplied:()=>Rt,resetToOriginal:()=>wn,setOverrideMode:()=>Bi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn});function hn(){return typeof window=="undefined"?null:window.__editableConfig||null}function Ni(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Di(s,e){var t,n;if(!s)return null;try{if(s instanceof Map)return(t=s.get(e))!=null?t:null;if(typeof s=="object")return(n=s[e])!=null?n:null}catch{}return null}function Vo(s,e,t){if(s){if(s instanceof Map){s.set(e,t);return}typeof s=="object"&&(s[e]=t)}}function js(s,e){for(let t of e)_t(s,t.path,t.value)}function fn(s){var o;if(typeof window=="undefined")return;let e=hn();if(!e)return;let t=Ni(),n=(o=t?Di(t.objects,s):null)!=null?o:Di(e.objects,s);if(!n)return;let i=Q(n),a=se().filter(l=>l.objectId===s);try{js(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",s,l);return}Vo(e.objects,s,i);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(s,i)}catch{}}function Hi(){var i;if(typeof window=="undefined")return;let s=hn();if(!(s!=null&&s.engine))return;let e=Ni(),t=Q(((i=e==null?void 0:e.engine)!=null?i:s.engine)||{}),n=se().filter(a=>!a.objectId&&!a.sceneId);try{js(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=s.engine;for(let r of Object.keys(a))r in t||delete a[r];for(let[r,o]of Object.entries(t))a[r]=o}catch{s.engine=t}}function Wo(){if(typeof window=="undefined")return"unknown";let s=window;return typeof s.__HANDLER_PROJECT_ID=="string"?s.__HANDLER_PROJECT_ID:"handler-default"}function Os(){return`handler_preview_config_overrides::${Wo()}`}function Yo(){if(typeof window=="undefined")return[];try{let s=window.localStorage.getItem(Os());if(!s)return[];let e=JSON.parse(s);return Array.isArray(e)?e:[]}catch{return[]}}function mn(s){if(typeof window!="undefined")try{window.localStorage.setItem(Os(),JSON.stringify(s))}catch{}}function jt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Bi(s){if(typeof window!="undefined"){window.__enableConfigOverrides=s;try{window.localStorage.setItem(Rs,s?"true":"false")}catch{}}}function re(s,e={}){var u,g;let{objectId:t,path:n,value:i}=s,{silent:a=!1,persist:r=!0,emitEvent:o=!0}=e,l=hn();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let d;try{d=Hs(c,n),_t(c,n,i)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:n,oldValue:d,newValue:i,ts:Date.now()}),h.length>Fi&&h.shift(),window.__configChangeRedo=[]}if(r){let h=se(),f=h.findIndex(m=>m.objectId===t&&m.sceneId===s.sceneId&&m.path===n);f>=0?h[f].value=i:h.push(s),window.__configOverrides=h,mn(h),jt()||Bi(!0)}a||console.log("[CONFIG] Applied override:",s),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:{...s,oldValue:d}}))}function $e(s,e={}){let t=e.emitEvent!==!1,n=[];for(let i of s)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),re(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:s.length}}))}}function pe(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],mn([]),console.log("[CONFIG] Cleared all overrides")}function zs(s){let e=se().filter(n=>n.objectId!==s);window.__configOverrides=e,mn(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==s),fn(s),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:s}}))}function Ot(s,e){let t=se().filter(i=>i.objectId!==s||i.path!==e);window.__configOverrides=t,mn(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==s||i.path!==e),s?fn(s):Hi(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:s,path:e}}))}function se(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Yo()),window.__configOverrides||[])}function bn(){var a;if(typeof window=="undefined")return!1;let s=window.__configChanges||[];if(s.length===0)return!1;let e=s.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:r}=e.metadata||{};return e.objectId&&r&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:r})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:r,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&r&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:r,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Ni(),i=!1;if(n){let r=e.objectId?Di(n.objects,e.objectId):n.engine;if(r){let o=Hs(r,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?Ot(e.objectId,e.path):(re({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?fn(e.objectId):Hi()),console.log("[CONFIG] Undo:",e.path),!0}function yn(){var n;if(typeof window=="undefined")return!1;let s=window.__configChangeRedo||[];if(s.length===0)return!1;let e=s.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},r=e.newValue;return e.objectId&&i&&r&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=r==null?void 0:r.identity)==null?void 0:n.id),config:r})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(r=>console.error("[CONFIG] Failed to delete object on redo:",r)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),re({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?fn(e.objectId):Hi(),console.log("[CONFIG] Redo:",e.path),!0}function Ds(s,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>Fi&&n.shift(),console.log("[CONFIG] Tracked object creation:",s)}function Ns(s,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>Fi&&n.shift(),console.log("[CONFIG] Tracked object deletion:",s)}function _t(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(r=a[o])!=null?r:{},a=a[o]}a[i]=t}function Hs(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Q(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(s instanceof Set)return new Set([...s].map(t=>Q(t)));if(ArrayBuffer.isView(s))return s.slice();if(s instanceof Array)return s.map(t=>Q(t));if(s instanceof Map){let t=new Map;return s.forEach((n,i)=>t.set(i,Q(n))),t}let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=Q(s[t]));return e}function Xe(){let s=window.__editableConfigBaseline;if(!s){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return _s(e)}return _s(s)}function _s(s){let e={objects:{},scenes:{},engine:Q(s.engine||{})},t=s.objects;if(t instanceof Map)t.forEach((a,r)=>{e.objects[r]=Q(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=Q(t[a]);let n=s.scenes;if(n instanceof Map)n.forEach((a,r)=>{e.scenes[r]=Q(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=Q(n[a]);let i=se();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),_t(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),_t(e.scenes[a.sceneId],a.path,a.value)):_t(e.engine,a.path,a.value);return e}function De(){let s=se(),e=new Set;for(let t of s)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:s.length,hasChanges:s.length>0,overrides:s}}async function vn(s){let e=Xe(),t={};for(let[i,a]of Object.entries(e.objects)){let r=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),r&&typeof r=="object"&&(r.identity||(r.identity={}),r.identity.id=o),t[`objects/${o}.json`]=r}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let r=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${r}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:se().length>0,versionName:s})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}pe();try{let i=hn();i&&(window.__editableConfigBaseline=Q(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Rt(){pe(),window.location.reload()}async function wn(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let e=await fetch("/api/reset-to-original",{method:"POST"});if(!e.ok){let t=await e.json();throw new Error(`Reset failed: ${t.error||"Unknown error"}`)}pe(),window.location.reload()}var Rs,Fi,$s,ee=Ee(()=>{"use strict";Rs="handler_preview_override_mode";if(typeof window!="undefined"){let s=window.localStorage.getItem(Rs);window.__enableConfigOverrides=s===null?!0:s==="true"}Fi=500;$s={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function Ko(s,e){try{if(typeof s=="object"&&s!==null)return s;if(typeof s!="string")return null;if(s.startsWith("data:")){let n=s.indexOf(",");if(n===-1)return null;let i=s.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=s.slice(n+1),r=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(r)}let t=s.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(s):null}catch{return null}}function Xo(s){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=s.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let r=e[a];if(r){let o=Ko(r,a);if(o!==null)return o}}return null}async function zt(s){if(Gi.has(s)&&!Ui)return console.log(`[CONFIG] Using cached config for: "${s}"`),Gi.get(s);if(console.log(`[CONFIG] loadConfigFile called with: "${s}", MODE: ${V.toUpperCase()}, CACHE: ${Ui?"DISABLED":"ENABLED"}`),V==="publish"){let n=Xo(s);return n?(console.log(`[CONFIG] \u2713 Loaded ${s} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${s} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}V==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${s}"`);let e;V==="brand"?e=[`./${s.split("/").pop()||s}`,`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=Ui?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let r=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${s} via ${i}`,r),r}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${V}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${s}; using defaults`),{}})();return Gi.set(s,t),t}async function xn(){console.log("[CONFIG] Loading component schemas...");let s=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of s)try{let n=V==="publish"||V==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await zt(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${V==="publish"||V==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function He(s){console.log(`[CONFIG] Loading object config: ${s}`);let e=V==="publish"||V==="brand"?`${s}.json`:`configs/objects/${s}.json`;return await zt(e)}async function Sn(s){let e=new Map;if(s.objects&&Array.isArray(s.objects)){for(let t of s.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await He(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await He(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await He(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function En(){console.log("[CONFIG] Loading engine configs...");let s=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(s.map(n=>{let i=`engine.${n}.json`,a=V==="publish"||V==="brand"?i:`configs/engine/${i}`;return zt(a)})),t=Object.fromEntries(s.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(s.map(n=>{var r;let i=(r=t[n])!=null?r:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function qi(){return await zt(V==="publish"||V==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Cn(s="scene.main"){console.log(`[CONFIG] Loading scene config: ${s}`);let e=V==="publish"||V==="brand"?`${s}.json`:`configs/scenes/${s}.json`;return await zt(e)}function dt(s,e){let t=[];if(!s.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])s.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(s)){if(i==="identity")continue;let r=e.get(i);if(r&&a&&typeof a=="object"){let o=a;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let d=o[l];if(d!==void 0&&c&&typeof c=="object"){let p=c;typeof d=="number"&&(p.min!==void 0&&d<p.min&&t.push(`${i}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${i}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function Je(s,e){let t={...s},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function ue(s,e,t,n){return typeof s!="number"||!Number.isFinite(s)?e:Math.min(Math.max(s,t),n)}function Bs(s,e){if(Array.isArray(s))return{x:ue(s[0],e.x,-2e3,2e3),y:ue(s[1],e.y,-2e3,2e3)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:ue(t,e.x,-2e3,2e3),y:ue(n,e.y,-2e3,2e3)}}function Jo(s,e){if(Array.isArray(s))return{x:ue(s[0],e.x,0,1),y:ue(s[1],e.y,0,1)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:ue(t,e.x,0,1),y:ue(n,e.y,0,1)}}function Zo(s){if(Array.isArray(s))return{x:ue(s[0],.5,-10,10),y:ue(s[1],.5,-10,10)};if(s&&typeof s=="object"){let{x:e,y:t}=s;return{x:ue(e,.5,-10,10),y:ue(t,.5,-10,10)}}return typeof s=="string"?s:null}async function Pe(s="scene.main",e){var l,c,d,p,u,g,h,f,m,b,y,v,w,T;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await xn(),n=se();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await Cn(s);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await En();console.log("[CONFIG] Loading object configs...");let r=await Sn(i);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[I,_]of r.entries()){let L=Je(_,t),M=dt(L,t);M.valid||console.warn(`Object ${I} validation errors:`,M.errors),(c=L.transform)!=null&&c.position&&(L.transform.position=Bs(L.transform.position,{x:0,y:0})),(d=L.transform)!=null&&d.offset&&(L.transform.offset=Bs(L.transform.offset,{x:0,y:0})),((p=L.transform)==null?void 0:p.anchor)!==void 0&&(L.transform.anchor=Zo(L.transform.anchor)),((u=L.transform)==null?void 0:u.position_ratio)!==void 0&&L.transform.position_ratio!==null&&(L.transform.position_ratio=Jo(L.transform.position_ratio,{x:.5,y:.5})),r.set(I,L)}if(e){if(e.objects)for(let[I,_]of e.objects.entries())r.set(I,_);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Je(o,t))),n.length>0&&jt()&&$e(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((f=a.runtime)!=null?f:{}),assets:Object.keys((m=a.assets)!=null?m:{}),splash:Object.keys((b=a.splash)!=null?b:{}),loading:Object.keys((y=a.loading)!=null?y:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((w=a.tutorial)!=null?w:{}),endgame:Object.keys((T=a.endgame)!=null?T:{})},scene:i.scene_id||"unknown"}),o}function Vi(s){var t,n,i,a,r,o,l,c,d,p,u,g,h,f,m,b,y,v,w,T,I,_,L,M,O,P,E,C,A,S,x,j,k;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[R,z]of s.objects.entries()){let D=((t=z.identity)==null?void 0:t.id)||R;D.includes("character")&&(e.gameplay.character_pos=((n=z.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=z.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((r=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=z.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((d=(c=z.gameplay)==null?void 0:c.tuning)==null?void 0:d.relief_speed)||.22),(D.includes("gun")||D.includes("flame"))&&(e.gameplay.gun=z.gun||{},e.gameplay.gunmuzzle=((p=z.effects)==null?void 0:p.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=z.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=z.effects)==null?void 0:g.flame)||{}),D.includes("diamond")&&(e.gameplay.diamond=z),D.includes("ice")&&(e.gameplay.melt=z.melt||{},e.gameplay.melt_anchor=((h=z.transform)==null?void 0:h.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((f=z.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((m=z.effects)==null?void 0:m.hybrid_melting)||{},e.gameplay.physics_chunks=((b=z.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=z.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=z.hard_ice||{}),D.includes("water")&&(e.gameplay.water_drops=z),D.includes("crack")&&(e.gameplay.crack=z),D.includes("hand")&&(e.gameplay.hand=((v=z.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((w=z.transform)==null?void 0:w.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((T=z.transform)==null?void 0:T.scale)||1.5),D.includes("hazard")&&(e.gameplay.hazard=((I=z.gameplay)==null?void 0:I.tuning)||{},e.gameplay.danger_pos=((_=z.transform)==null?void 0:_.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((M=(L=z.gameplay)==null?void 0:L.tuning)==null?void 0:M.danger_pulse)||{},e.gameplay.hazard_height=((P=(O=z.gameplay)==null?void 0:O.tuning)==null?void 0:P.hazard_height)||140)}return e.gameplay.timeline=((E=s.engine.runtime)==null?void 0:E.timeline)||{},e.gameplay.drag_surface=((C=s.engine.runtime)==null?void 0:C.drag_surface)||{},e.gameplay.background=((A=s.engine.runtime)==null?void 0:A.background)||{},e.gameplay.ui_styles=((S=s.engine.runtime)==null?void 0:S.ui_styles)||{},e.gameplay.label_pulse=((x=s.engine.runtime)==null?void 0:x.label_pulse)||{},e.ui=((j=s.engine.runtime)==null?void 0:j.ui)||{},e.theme=((k=s.engine.runtime)==null?void 0:k.theme)||{},e.assets=s.engine.assets||{},e}var Fs,V,Gi,Ui,Wi=Ee(()=>{"use strict";ee();Fs=null,V="dev";if(typeof window!="undefined"){let s=window.__BUILD_SETTINGS__;if(s!=null&&s.buildMode)Fs=s,V=s.buildMode,console.log("[CONFIG] Loaded inline build settings:",s,"buildMode:",V);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);Fs=t,V=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",V)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",V)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",V);Gi=new Map,Ui=V==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Yi(s,e){let t=[];function n(i,a,r=""){if(i!==a){if(typeof i!=typeof a){t.push(`${r}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=r?`${r}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(s,e),t}function Ki(s,e,t,n){let i={...t};for(let[a,r]of n.entries())i[a]&&r.defaults&&(i[a]={...r.defaults,...i[a]});return i}var $t,Ze,Xi=Ee(()=>{"use strict";$t=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},Ze=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),r=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==r&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==r){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,r)}else o||this.fileHashes.set(e,r)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Zi(s){if(typeof window=="undefined")return;let e=typeof Ji!="undefined"&&!!Ji.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,r=null;if(t){r=new Ze;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var b,y;if(!r)return;let f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let m=(y=(b=h.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||r.unwatch(v);for(let v of f)o.has(v)||r.watch(v,w=>g(w));o=f},c=new Set,d=!1,p=async h=>{let f=await He(h),m=Je(f,s.activeConfig.schemas),b=dt(m,s.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await s.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){s.audioSystem.destroy();let f=await Pe("scene.main");s.setActiveConfig(f),s.gameObjectManager.updateConfig(f),s.CustomAssets.updateConfig(f),await s.CustomAssets.ready();let m=s.createAudioSystem(f);s.setAudioSystem(m),window.__audioSystem=m,await m.start(),s.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${h})`)}else{let f=Array.from(c);c.clear();for(let m of f)await p(m);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{a=!1,d=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):d=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(h.type)},120)}e&&Ji.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(s.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Ji,Gs=Ee(()=>{"use strict";Xi();Wi();Ji={}});var Us={};Lt(Us,{ConfigWatcher:()=>Ze,DefaultReloadStrategy:()=>$t,applyDefaults:()=>Je,diffConfigs:()=>Yi,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>Pe,loadObjectConfig:()=>He,loadSceneConfig:()=>Cn,rehydrateObject:()=>Ki,setupHotReload:()=>Zi,toLegacyFormat:()=>Vi,validateObjectConfig:()=>dt});var An=Ee(()=>{"use strict";Wi();Xi();Gs()});var Mr={};Lt(Mr,{AssetEditorModal:()=>Ma});var Ma,_a=Ee(()=>{"use strict";Ma=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
1
+ "use strict";var to=Object.create;var en=Object.defineProperty;var no=Object.getOwnPropertyDescriptor;var io=Object.getOwnPropertyNames;var ao=Object.getPrototypeOf,so=Object.prototype.hasOwnProperty;var Ee=(s,e)=>()=>(s&&(e=s(s=0)),e);var Lt=(s,e)=>{for(var t in e)en(s,t,{get:e[t],enumerable:!0})},Ka=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of io(e))!so.call(s,i)&&i!==t&&en(s,i,{get:()=>e[i],enumerable:!(n=no(e,i))||n.enumerable});return s};var at=(s,e,t)=>(t=s!=null?to(ao(s)):{},Ka(e||!s||!s.__esModule?en(t,"default",{value:s,enumerable:!0}):t,s)),ro=s=>Ka(en({},"__esModule",{value:!0}),s);var ce,sn=Ee(()=>{"use strict";ce=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};ce.store=new Map});function fo(){var s,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(s=document.querySelector("script"))==null?void 0:s.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function mo(){try{if(typeof window!="undefined"){let s=await fetch("./build-settings.json");if(s.ok){let e=await s.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function bo(){try{if(typeof window!="undefined"){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);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function yo(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${W}`),Object.keys(Ce).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(Ce)),Ce;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),Ce={...window.INLINE_ASSETS},Ce;if(!(W==="publish"&&be!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),Ce;if(!Pi){let e=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",e),Pi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return Ce=await Pi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(Ce)),Ce}function Ii(s){return s===null||typeof s!="object"||(Object.freeze(s),Object.values(s).forEach(e=>Ii(e))),s}function vo(s=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=s,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,s,e),i.strokeStyle="#000",i.strokeRect(0,0,s,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",s/2,e/2),Ae.Texture.from(n)}function Mi(s,e){Ts.set(s,e)}var Ae,Ls,ks,Ve,W,be,Re,Ce,Pi,Ts,We,rn=Ee(()=>{"use strict";Ae=require("pixi.js");sn();Ls=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ks=fo(),Ve=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,W=ks?"publish":Ls,be=Ve==null?void 0:Ve.assetsInlined;Ve!=null&&Ve.buildMode&&(W=Ve.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${W}`));Re=bo();Re!=null&&Re.buildMode&&(W=Re.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${W}`));(Re==null?void 0:Re.assetsInlined)!==void 0&&(be=Re.assetsInlined);mo().then(s=>{s!=null&&s.buildMode&&s.buildMode!==W&&(W=s.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${W}`)),(s==null?void 0:s.assetsInlined)!==void 0&&(be=s.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Ls}, Runtime: ${ks?"publish":"dev"}, Effective: ${W}`);Ce={},Pi=null;Ts=new Map;We=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,r=ce.get(a);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${W}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await yo(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let p=t.path.split("/");if(p.length>=2){let u=p[p.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),W==="publish"&&be!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let d=Ts.get(t.type);if(d)try{let p=await d(t.path,l,e,n);return ce.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}try{let p;switch(t.type){case"image":p=await this.loadImage(t.path,l);break;case"json":p=await this.loadJSON(t.path,l),p=Ii(p);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return ce.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}}static async loadImage(e,t){let n=W==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${W}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await Ae.Assets.load(t)}catch(a){throw console.error("[AssetLoader] Failed to load texture from data URI:",a),a}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await Ae.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Ae.Assets.load(e)}return await Ae.Assets.load(e)}static async loadJSON(e,t){let n=W==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${W}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(W==="dev"){let a=t==="image"?vo():Ii({__placeholder:!0,type:t});return ce.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Mi("image",async(s,e)=>{let t=W==="publish",n=t&&be!==!1,i=W==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${W}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Ae.Assets.load(e)}let r=s;return(i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),Ae.Assets.load(e||r)});Mi("json",async(s,e)=>{let t=W==="publish",n=t&&be!==!1,i=W==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${W}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=s;if((i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(r);if(!o.ok)throw new Error(`JSON fetch failed: ${s}`);return o.json()})});var Is={};Lt(Is,{AssetTextures:()=>ve,initAssetTextures:()=>Oi});function Oi(s,e){Ps.init(s,e),typeof window!="undefined"&&(window.__AssetTextures=ve)}var ji,Ps,ve,lt=Ee(()=>{"use strict";rn();ji=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var r;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let d=async()=>{var p;try{let u=(p=l.identity)==null?void 0:p.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await We.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(d()):a.push(d())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,d,p;try{let u=(d=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:d.call(c,o);return!!((p=u==null?void 0:u.render)!=null&&p.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),r>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},r)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},Ps=new ji,ve=new Proxy(Ps,{get(s,e){return e in s&&typeof s[e]=="function"?s[e].bind(s):s.get(e)},set(s,e,t){return s.set(e,t),!0}})});var Ne={};Lt(Ne,{applyConfigOverride:()=>re,applyConfigOverrides:()=>$e,applyConfigsToDisk:()=>vn,clearConfigOverrides:()=>pe,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,deepClone:()=>Q,exportConfigsAsJSON:()=>Xe,getConfigOverrides:()=>se,getConfigStateSummary:()=>De,getOverrideMode:()=>jt,redoLastConfigChange:()=>yn,removeConfigOverride:()=>Ot,resetToApplied:()=>Rt,resetToOriginal:()=>wn,setOverrideMode:()=>Bi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn});function hn(){return typeof window=="undefined"?null:window.__editableConfig||null}function Ni(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Di(s,e){var t,n;if(!s)return null;try{if(s instanceof Map)return(t=s.get(e))!=null?t:null;if(typeof s=="object")return(n=s[e])!=null?n:null}catch{}return null}function Vo(s,e,t){if(s){if(s instanceof Map){s.set(e,t);return}typeof s=="object"&&(s[e]=t)}}function js(s,e){for(let t of e)_t(s,t.path,t.value)}function fn(s){var o;if(typeof window=="undefined")return;let e=hn();if(!e)return;let t=Ni(),n=(o=t?Di(t.objects,s):null)!=null?o:Di(e.objects,s);if(!n)return;let i=Q(n),a=se().filter(l=>l.objectId===s);try{js(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",s,l);return}Vo(e.objects,s,i);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(s,i)}catch{}}function Hi(){var i;if(typeof window=="undefined")return;let s=hn();if(!(s!=null&&s.engine))return;let e=Ni(),t=Q(((i=e==null?void 0:e.engine)!=null?i:s.engine)||{}),n=se().filter(a=>!a.objectId&&!a.sceneId);try{js(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=s.engine;for(let r of Object.keys(a))r in t||delete a[r];for(let[r,o]of Object.entries(t))a[r]=o}catch{s.engine=t}}function Wo(){if(typeof window=="undefined")return"unknown";let s=window;return typeof s.__HANDLER_PROJECT_ID=="string"?s.__HANDLER_PROJECT_ID:"handler-default"}function Os(){return`handler_preview_config_overrides::${Wo()}`}function Yo(){if(typeof window=="undefined")return[];try{let s=window.localStorage.getItem(Os());if(!s)return[];let e=JSON.parse(s);return Array.isArray(e)?e:[]}catch{return[]}}function mn(s){if(typeof window!="undefined")try{window.localStorage.setItem(Os(),JSON.stringify(s))}catch{}}function jt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Bi(s){if(typeof window!="undefined"){window.__enableConfigOverrides=s;try{window.localStorage.setItem(Rs,s?"true":"false")}catch{}}}function re(s,e={}){var u,g;let{objectId:t,path:n,value:i}=s,{silent:a=!1,persist:r=!0,emitEvent:o=!0}=e,l=hn();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let d;try{d=Hs(c,n),_t(c,n,i)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:n,oldValue:d,newValue:i,ts:Date.now()}),h.length>Fi&&h.shift(),window.__configChangeRedo=[]}if(r){let h=se(),f=h.findIndex(m=>m.objectId===t&&m.sceneId===s.sceneId&&m.path===n);f>=0?h[f].value=i:h.push(s),window.__configOverrides=h,mn(h),jt()||Bi(!0)}a||console.log("[CONFIG] Applied override:",s),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:{...s,oldValue:d}}))}function $e(s,e={}){let t=e.emitEvent!==!1,n=[];for(let i of s)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),re(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:s.length}}))}}function pe(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],mn([]),console.log("[CONFIG] Cleared all overrides")}function zs(s){let e=se().filter(n=>n.objectId!==s);window.__configOverrides=e,mn(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==s),fn(s),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:s}}))}function Ot(s,e){let t=se().filter(i=>i.objectId!==s||i.path!==e);window.__configOverrides=t,mn(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==s||i.path!==e),s?fn(s):Hi(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:s,path:e}}))}function se(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Yo()),window.__configOverrides||[])}function bn(){var a;if(typeof window=="undefined")return!1;let s=window.__configChanges||[];if(s.length===0)return!1;let e=s.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:r}=e.metadata||{};return e.objectId&&r&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:r})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:r,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&r&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:r,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Ni(),i=!1;if(n){let r=e.objectId?Di(n.objects,e.objectId):n.engine;if(r){let o=Hs(r,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?Ot(e.objectId,e.path):(re({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?fn(e.objectId):Hi()),console.log("[CONFIG] Undo:",e.path),!0}function yn(){var n;if(typeof window=="undefined")return!1;let s=window.__configChangeRedo||[];if(s.length===0)return!1;let e=s.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},r=e.newValue;return e.objectId&&i&&r&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=r==null?void 0:r.identity)==null?void 0:n.id),config:r})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(r=>console.error("[CONFIG] Failed to delete object on redo:",r)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),re({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?fn(e.objectId):Hi(),console.log("[CONFIG] Redo:",e.path),!0}function Ds(s,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>Fi&&n.shift(),console.log("[CONFIG] Tracked object creation:",s)}function Ns(s,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>Fi&&n.shift(),console.log("[CONFIG] Tracked object deletion:",s)}function _t(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(r=a[o])!=null?r:{},a=a[o]}a[i]=t}function Hs(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Q(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(s instanceof Set)return new Set([...s].map(t=>Q(t)));if(ArrayBuffer.isView(s))return s.slice();if(s instanceof Array)return s.map(t=>Q(t));if(s instanceof Map){let t=new Map;return s.forEach((n,i)=>t.set(i,Q(n))),t}let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=Q(s[t]));return e}function Xe(){let s=window.__editableConfigBaseline;if(!s){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return _s(e)}return _s(s)}function _s(s){let e={objects:{},scenes:{},engine:Q(s.engine||{})},t=s.objects;if(t instanceof Map)t.forEach((a,r)=>{e.objects[r]=Q(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=Q(t[a]);let n=s.scenes;if(n instanceof Map)n.forEach((a,r)=>{e.scenes[r]=Q(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=Q(n[a]);let i=se();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),_t(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),_t(e.scenes[a.sceneId],a.path,a.value)):_t(e.engine,a.path,a.value);return e}function De(){let s=se(),e=new Set;for(let t of s)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:s.length,hasChanges:s.length>0,overrides:s}}async function vn(s){let e=Xe(),t={};for(let[i,a]of Object.entries(e.objects)){let r=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),r&&typeof r=="object"&&(r.identity||(r.identity={}),r.identity.id=o),t[`objects/${o}.json`]=r}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let r=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${r}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:se().length>0,versionName:s})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}pe();try{let i=hn();i&&(window.__editableConfigBaseline=Q(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Rt(){pe(),window.location.reload()}async function wn(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let e=await fetch("/api/reset-to-original",{method:"POST"});if(!e.ok){let t=await e.json();throw new Error(`Reset failed: ${t.error||"Unknown error"}`)}pe(),window.location.reload()}var Rs,Fi,$s,ee=Ee(()=>{"use strict";Rs="handler_preview_override_mode";if(typeof window!="undefined"){let s=window.localStorage.getItem(Rs);window.__enableConfigOverrides=s===null?!0:s==="true"}Fi=500;$s={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function Ko(s,e){try{if(typeof s=="object"&&s!==null)return s;if(typeof s!="string")return null;if(s.startsWith("data:")){let n=s.indexOf(",");if(n===-1)return null;let i=s.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=s.slice(n+1),r=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(r)}let t=s.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(s):null}catch{return null}}function Xo(s){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=s.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let r=e[a];if(r){let o=Ko(r,a);if(o!==null)return o}}return null}async function zt(s){if(Gi.has(s)&&!Ui)return console.log(`[CONFIG] Using cached config for: "${s}"`),Gi.get(s);if(console.log(`[CONFIG] loadConfigFile called with: "${s}", MODE: ${V.toUpperCase()}, CACHE: ${Ui?"DISABLED":"ENABLED"}`),V==="publish"){let n=Xo(s);return n?(console.log(`[CONFIG] \u2713 Loaded ${s} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${s} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}V==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${s}"`);let e;V==="brand"?e=[`./${s.split("/").pop()||s}`,`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=Ui?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let r=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${s} via ${i}`,r),r}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${V}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${s}; using defaults`),{}})();return Gi.set(s,t),t}async function xn(){console.log("[CONFIG] Loading component schemas...");let s=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of s)try{let n=V==="publish"||V==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await zt(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${V==="publish"||V==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function He(s){console.log(`[CONFIG] Loading object config: ${s}`);let e=V==="publish"||V==="brand"?`${s}.json`:`configs/objects/${s}.json`;return await zt(e)}async function Sn(s){let e=new Map;if(s.objects&&Array.isArray(s.objects)){for(let t of s.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await He(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await He(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await He(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function En(){console.log("[CONFIG] Loading engine configs...");let s=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(s.map(n=>{let i=`engine.${n}.json`,a=V==="publish"||V==="brand"?i:`configs/engine/${i}`;return zt(a)})),t=Object.fromEntries(s.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(s.map(n=>{var r;let i=(r=t[n])!=null?r:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function qi(){return await zt(V==="publish"||V==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Cn(s="scene.main"){console.log(`[CONFIG] Loading scene config: ${s}`);let e=V==="publish"||V==="brand"?`${s}.json`:`configs/scenes/${s}.json`;return await zt(e)}function dt(s,e){let t=[];if(!s.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])s.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(s)){if(i==="identity")continue;let r=e.get(i);if(r&&a&&typeof a=="object"){let o=a;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let d=o[l];if(d!==void 0&&c&&typeof c=="object"){let p=c;typeof d=="number"&&(p.min!==void 0&&d<p.min&&t.push(`${i}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${i}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function Je(s,e){let t={...s},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function ue(s,e,t,n){return typeof s!="number"||!Number.isFinite(s)?e:Math.min(Math.max(s,t),n)}function Bs(s,e){if(Array.isArray(s))return{x:ue(s[0],e.x,-2e3,2e3),y:ue(s[1],e.y,-2e3,2e3)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:ue(t,e.x,-2e3,2e3),y:ue(n,e.y,-2e3,2e3)}}function Jo(s,e){if(Array.isArray(s))return{x:ue(s[0],e.x,0,1),y:ue(s[1],e.y,0,1)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:ue(t,e.x,0,1),y:ue(n,e.y,0,1)}}function Zo(s){if(Array.isArray(s))return{x:ue(s[0],.5,-10,10),y:ue(s[1],.5,-10,10)};if(s&&typeof s=="object"){let{x:e,y:t}=s;return{x:ue(e,.5,-10,10),y:ue(t,.5,-10,10)}}return typeof s=="string"?s:null}async function Pe(s="scene.main",e){var l,c,d,p,u,g,h,f,m,b,y,v,w,T;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await xn(),n=se();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await Cn(s);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await En();console.log("[CONFIG] Loading object configs...");let r=await Sn(i);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[P,j]of r.entries()){let L=Je(j,t),M=dt(L,t);M.valid||console.warn(`Object ${P} validation errors:`,M.errors),(c=L.transform)!=null&&c.position&&(L.transform.position=Bs(L.transform.position,{x:0,y:0})),(d=L.transform)!=null&&d.offset&&(L.transform.offset=Bs(L.transform.offset,{x:0,y:0})),((p=L.transform)==null?void 0:p.anchor)!==void 0&&(L.transform.anchor=Zo(L.transform.anchor)),((u=L.transform)==null?void 0:u.position_ratio)!==void 0&&L.transform.position_ratio!==null&&(L.transform.position_ratio=Jo(L.transform.position_ratio,{x:.5,y:.5})),r.set(P,L)}if(e){if(e.objects)for(let[P,j]of e.objects.entries())r.set(P,j);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Je(o,t))),n.length>0&&jt()&&$e(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((f=a.runtime)!=null?f:{}),assets:Object.keys((m=a.assets)!=null?m:{}),splash:Object.keys((b=a.splash)!=null?b:{}),loading:Object.keys((y=a.loading)!=null?y:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((w=a.tutorial)!=null?w:{}),endgame:Object.keys((T=a.endgame)!=null?T:{})},scene:i.scene_id||"unknown"}),o}function Vi(s){var t,n,i,a,r,o,l,c,d,p,u,g,h,f,m,b,y,v,w,T,P,j,L,M,R,I,E,C,A,S,x,_,k;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[O,z]of s.objects.entries()){let D=((t=z.identity)==null?void 0:t.id)||O;D.includes("character")&&(e.gameplay.character_pos=((n=z.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=z.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((r=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=z.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((d=(c=z.gameplay)==null?void 0:c.tuning)==null?void 0:d.relief_speed)||.22),(D.includes("gun")||D.includes("flame"))&&(e.gameplay.gun=z.gun||{},e.gameplay.gunmuzzle=((p=z.effects)==null?void 0:p.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=z.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=z.effects)==null?void 0:g.flame)||{}),D.includes("diamond")&&(e.gameplay.diamond=z),D.includes("ice")&&(e.gameplay.melt=z.melt||{},e.gameplay.melt_anchor=((h=z.transform)==null?void 0:h.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((f=z.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((m=z.effects)==null?void 0:m.hybrid_melting)||{},e.gameplay.physics_chunks=((b=z.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=z.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=z.hard_ice||{}),D.includes("water")&&(e.gameplay.water_drops=z),D.includes("crack")&&(e.gameplay.crack=z),D.includes("hand")&&(e.gameplay.hand=((v=z.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((w=z.transform)==null?void 0:w.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((T=z.transform)==null?void 0:T.scale)||1.5),D.includes("hazard")&&(e.gameplay.hazard=((P=z.gameplay)==null?void 0:P.tuning)||{},e.gameplay.danger_pos=((j=z.transform)==null?void 0:j.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((M=(L=z.gameplay)==null?void 0:L.tuning)==null?void 0:M.danger_pulse)||{},e.gameplay.hazard_height=((I=(R=z.gameplay)==null?void 0:R.tuning)==null?void 0:I.hazard_height)||140)}return e.gameplay.timeline=((E=s.engine.runtime)==null?void 0:E.timeline)||{},e.gameplay.drag_surface=((C=s.engine.runtime)==null?void 0:C.drag_surface)||{},e.gameplay.background=((A=s.engine.runtime)==null?void 0:A.background)||{},e.gameplay.ui_styles=((S=s.engine.runtime)==null?void 0:S.ui_styles)||{},e.gameplay.label_pulse=((x=s.engine.runtime)==null?void 0:x.label_pulse)||{},e.ui=((_=s.engine.runtime)==null?void 0:_.ui)||{},e.theme=((k=s.engine.runtime)==null?void 0:k.theme)||{},e.assets=s.engine.assets||{},e}var Fs,V,Gi,Ui,Wi=Ee(()=>{"use strict";ee();Fs=null,V="dev";if(typeof window!="undefined"){let s=window.__BUILD_SETTINGS__;if(s!=null&&s.buildMode)Fs=s,V=s.buildMode,console.log("[CONFIG] Loaded inline build settings:",s,"buildMode:",V);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);Fs=t,V=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",V)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",V)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",V);Gi=new Map,Ui=V==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Yi(s,e){let t=[];function n(i,a,r=""){if(i!==a){if(typeof i!=typeof a){t.push(`${r}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=r?`${r}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(s,e),t}function Ki(s,e,t,n){let i={...t};for(let[a,r]of n.entries())i[a]&&r.defaults&&(i[a]={...r.defaults,...i[a]});return i}var $t,Ze,Xi=Ee(()=>{"use strict";$t=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},Ze=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),r=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==r&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==r){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,r)}else o||this.fileHashes.set(e,r)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Zi(s){if(typeof window=="undefined")return;let e=typeof Ji!="undefined"&&!!Ji.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,r=null;if(t){r=new Ze;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var b,y;if(!r)return;let f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let m=(y=(b=h.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||r.unwatch(v);for(let v of f)o.has(v)||r.watch(v,w=>g(w));o=f},c=new Set,d=!1,p=async h=>{let f=await He(h),m=Je(f,s.activeConfig.schemas),b=dt(m,s.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await s.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){s.audioSystem.destroy();let f=await Pe("scene.main");s.setActiveConfig(f),s.gameObjectManager.updateConfig(f),s.CustomAssets.updateConfig(f),await s.CustomAssets.ready();let m=s.createAudioSystem(f);s.setAudioSystem(m),window.__audioSystem=m,await m.start(),s.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${h})`)}else{let f=Array.from(c);c.clear();for(let m of f)await p(m);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{a=!1,d=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):d=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(h.type)},120)}e&&Ji.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(s.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Ji,Gs=Ee(()=>{"use strict";Xi();Wi();Ji={}});var Us={};Lt(Us,{ConfigWatcher:()=>Ze,DefaultReloadStrategy:()=>$t,applyDefaults:()=>Je,diffConfigs:()=>Yi,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>Pe,loadObjectConfig:()=>He,loadSceneConfig:()=>Cn,rehydrateObject:()=>Ki,setupHotReload:()=>Zi,toLegacyFormat:()=>Vi,validateObjectConfig:()=>dt});var An=Ee(()=>{"use strict";Wi();Xi();Gs()});var Mr={};Lt(Mr,{AssetEditorModal:()=>Ma});var Ma,_a=Ee(()=>{"use strict";Ma=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
2
2
  <div class="asset-editor-card">
3
3
  <div class="asset-editor-header">
4
4
  <div>
@@ -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={};Lt(zl,{COLORS:()=>Se,ConfigWatcher:()=>Ze,DebugPanel:()=>Ut,DefaultReloadStrategy:()=>$t,Handler:()=>me,PlayableLoadingScreen:()=>gi,PreviewShell:()=>di,STROKE_WIDTH:()=>Nr,THEME:()=>Hr,applyConfigOverride:()=>re,applyConfigOverrides:()=>$e,applyConfigsToDisk:()=>vn,applyDefaults:()=>Je,baseLottie:()=>Li,bootstrap:()=>Al,clearConfigOverrides:()=>pe,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,createPreviewShell:()=>Ra,deepClone:()=>Q,default:()=>qe,defaultPreset:()=>Ln,deviceGroups:()=>ta,devicePresets:()=>ea,diffConfigs:()=>Yi,exportConfigsAsJSON:()=>Xe,getConfigOverrides:()=>se,getConfigStateSummary:()=>De,getOverrideMode:()=>jt,getPresetById:()=>Qe,getPresetsByCategory:()=>Qo,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>Pe,loadObjectConfig:()=>He,loadSceneConfig:()=>Cn,redoLastConfigChange:()=>yn,rehydrateObject:()=>Ki,removeConfigOverride:()=>Ot,resetToApplied:()=>Rt,resetToOriginal:()=>wn,setBootstrapDependencies:()=>El,setOverrideMode:()=>Bi,setupHotReload:()=>Zi,setupLiveEditBridge:()=>pi,toLegacyFormat:()=>Vi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn,validateObjectConfig:()=>dt});module.exports=ro(zl);var Oe={};function tn(s,e,t=!1){Oe[s]||(Oe[s]=[]),Oe[s].push({fn:e,once:t})}function Si(s,e){if(Oe[s]){if(!e){delete Oe[s];return}Oe[s]=Oe[s].filter(t=>t.fn!==e)}}function nn(s,...e){let t=Oe[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Si(s,n.fn)}function oe(s,e){tn(s,e,!0)}var K=null,he=[],st=null;function Za(s){K=s,he=[],st!==null&&(clearTimeout(st),st=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(he.push(s),he.length>t.maxQueue&&(he=he.slice(he.length-t.maxQueue)),he.length>=t.batchSize){Ja();return}st===null&&(st=window.setTimeout(()=>{st=null,Ja()},t.flushIntervalMs))}}async function Ja(){let s=Qa();if(!s.endpoint||he.length===0)return;let e=he.splice(0,s.batchSize);await Xa(s.endpoint,{events:e},s.transport,s.debug),he.length>0&&await Xa(s.endpoint,{events:he.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 kt(){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=kt();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 f=g.durationMs>0?h/g.durationMs:1,m=es(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let T=f-y;m=es(T)}let v=g.ease(m);g.yoyo&&y%2===1&&(v=1-v);for(let T of g.props)ts(g.target,T.key,T.from+(T.to-T.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(f>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var T;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+((T=u==null?void 0:u.delayMsOverride)!=null?T:0)),f=oo(p.ease),m=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 I of Object.keys(p)){if(y.has(I))continue;let _=p[I];typeof _=="number"&&v.push({key:I,from:lo(d,I),to:_})}let w=is(d,p);return{target:d,startMs:kt(),delayMs:h,durationMs:g,ease:f,props:v,scaleFrom:w.from,scaleTo:w.to,repeat:m,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=kt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:kt(),h=kt()-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=[],f=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},m=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,w){return m({kind:"to",target:y,vars:v,atMs:f(w)}),b},fromTo(y,v,w,T){return m({kind:"fromTo",target:y,vars:w,from:v,atMs:f(T)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let w of p)w.kind==="fromTo"&&c.set(w.target,(y=w.from)!=null?y:{}),h.push(c.to(w.target,{...w.vars,delay:w.atMs/1e3+((v=w.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.83",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 le=0,uo=le++,os=le++,ls=le++,cs=le++,ds=le++,ps=le++,us=le++,gs=le++,hs=le++,fs=le++,ms=le++,bs=le++,Y=uo;function ys(){return Y===os}function vs(){return Y===ls}function ws(){return Y===cs}function xs(){return Y===ds}function rt(){return Y===ps}function ot(){return Y===us}function Ss(){return Y===gs}function Es(){return Y===hs}function Cs(){return Y===fs}function Ci(){return Y===ms}function Ai(){return Y===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(),Y=os;return}catch{}else if(s==="dapi")try{dapi.isReady(),Y=ls;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Y=cs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Y=ds)}catch{}else if(e==="mintegral")window.gameReady&&(Y=ps);else if(e==="tapjoy")window.TJ_API&&(Y=us);else if(e==="tiktok")window.openAppStore&&(Y=gs);else if(e==="smadex")try{window.smxTracking&&(Y=hs)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Y=fs)}catch{}else e==="vungle"?Y=ms:(s==="nucleo"||e==="nucleo")&&(Y=bs)}var an=at(require("lottie-web"),1),Li=an.default;typeof window!="undefined"&&(window.lottie=an.default,window.__baseLottie=an.default);var go=require("pixi.js");var ki=require("pixi.js");var ho=null;function Ti(s){ho=s}rn();sn();var Tt=require("pixi.js");rn();var wo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",_i=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&&(_i=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${_i}`))}}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 ye=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${_i}`);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 f=new Tt.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}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 We.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 Tt.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 Tt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],m=!1;for(let b of f)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),m=!0;break}}catch{continue}m||(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 Pt=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=at(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Co);lt();var on=require("pixi.js");lt();var Ri=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Pt}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 ye.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 ye.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)}});lt();var To=require("pixi.js"),Le={width:400,height:600,designWidth:400,scaleFactor:1},cn={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*Le.scaleFactor;t(s,Le.width,Le.height,n,i,!0,!1)})}function zi(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Le.width=s,Le.height=e,Le.scaleFactor=Math.min(s/Le.designWidth,1.15),cn.scale=Le.scaleFactor,cn.position=1,console.log(`[SCREEN] Global multipliers - scale: ${cn.scale.toFixed(3)}`),Io()}var Mt={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=Mt[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function _o(){return Mt}var jo={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 ln(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Ke(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:ln(s[0],e.x),y:ln(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:ln(n.x,e.x),y:ln(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=jo[n])!=null?t:e}return e}function ze(s,e,t,n={}){var g,h,f,m,b,y;let i=Ke(t),a=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((f=a.left)!=null?f:0)+r.x,l=((m=a.right)!=null?m: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 ct(s,e,t,n={}){var f,m,b,y,v,w;let i=(f=n.inset)!=null?f:{},a=(m=n.padding)!=null?m:{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=((w=i.bottom)!=null?w:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Ke(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=_o,window.copyConfig=Uo,window.applyConfig=It,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 de(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,f,m,b,y,v,w,T,I,_,L,M;let i=0,a=0;switch(n.type){case"top":i=de(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=de(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,(f=(h=n.offset)==null?void 0:h.x)!=null?f:0),a=de(t,(b=(m=n.offset)==null?void 0:m.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=de(t,(T=(w=n.offset)==null?void 0:w.y)!=null?T:0);break;case"center":i=de(e,(_=(I=n.offset)==null?void 0:I.x)!=null?_:0),a=de(t,(M=(L=n.offset)==null?void 0:L.y)!=null?M: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);ke(s,de(e),l);let c=a?i*Le.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){ke(s,de(e),dn(t,n)),Te(s,i)}function $o(s,e,t,n=0,i=0,a=1){ke(s,de(e,n),de(t,i)),Te(s,a)}function Do(s,e,t,n=.1,i=1){ke(s,un(e,n),de(t)),Te(s,i)}function No(s,e,t,n=.1,i=1){ke(s,gn(e,n),de(t)),Te(s,i)}function Ho(s,e,t,n=.05,i=.05,a=1){ke(s,un(e,i),pn(t,n)),Te(s,a)}function Fo(s,e,t,n=.05,i=.05,a=1){ke(s,gn(e,i),pn(t,n)),Te(s,a)}function Bo(s,e,t,n=.05,i=.05,a=1){ke(s,un(e,i),dn(t,n)),Te(s,a)}function Go(s,e,t,n=.05,i=.05,a=1){ke(s,gn(e,i),dn(t,n)),Te(s,a)}function ke(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 Ye={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&&Ye[s]?JSON.parse(JSON.stringify(Ye[s])):JSON.parse(JSON.stringify(Mt))}function It(s){Object.keys(s).forEach(e=>{let t=e;Mt[t]&&s[t]&&Object.assign(Mt[t],s[t])}),console.log("Config applied:",s)}function qo(s,e){let t=s/e;t>1.6?(It(Ye.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(It(Ye.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(It(Ye.square),console.log("Applied SQUARE config for ratio:",t)):(It(Ye.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ye,s.resolveAnchorVec2=s.resolveAnchorVec2||Ke,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||ze,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||ct}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 Qe(s){return ea.find(e=>e.id===s)||Ln}function Qo(s){return ea.filter(e=>e.category===s)}ee();var we=class{async updateProperty(e,t,n,i={}){var l,c,d,p,u,g,h,f,m,b,y,v;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(re({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform.")){console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);let w=r==null?void 0:r.motion;if(w&&typeof w=="object"&&w.enabled!==!1&&(((p=w==null?void 0:w.intro)==null?void 0:p.enabled)===!0||((u=w==null?void 0:w.pulse)==null?void 0:u.enabled)===!0||((g=w==null?void 0:w.swing)==null?void 0:g.enabled)===!0||((h=w==null?void 0:w.continuousMove)==null?void 0:h.enabled)===!0||((f=w==null?void 0:w.continuousRotate)==null?void 0:f.enabled)===!0||((m=w==null?void 0:w.orbit)==null?void 0:m.enabled)===!0)){let _=window.applyEditableObjectConfig;if(typeof _=="function"){let L=window.__editableConfig,M=(v=(y=(b=L==null?void 0:L.objects)==null?void 0:b.get)==null?void 0:y.call(b,e))!=null?v:r;await _(e,M),console.log("[PropertyUpdateManager] Applied config for motion object")}}i.refreshInspector||requestAnimationFrame(()=>{window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e}}))})}else{let w=window.applyEditableObjectConfig;if(typeof w=="function"){let T=window.__editableConfig,I=(d=(c=(l=T==null?void 0:T.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await w(e,I),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 kn=class{constructor(){this.updateManager=new we}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}}},Tn=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={};Lt(zl,{COLORS:()=>Se,ConfigWatcher:()=>Ze,DebugPanel:()=>Ut,DefaultReloadStrategy:()=>$t,Handler:()=>me,PlayableLoadingScreen:()=>gi,PreviewShell:()=>di,STROKE_WIDTH:()=>Nr,THEME:()=>Hr,applyConfigOverride:()=>re,applyConfigOverrides:()=>$e,applyConfigsToDisk:()=>vn,applyDefaults:()=>Je,baseLottie:()=>Li,bootstrap:()=>Al,clearConfigOverrides:()=>pe,clearConfigOverridesForObject:()=>zs,configOverrideManager:()=>$s,createPreviewShell:()=>Ra,deepClone:()=>Q,default:()=>qe,defaultPreset:()=>Ln,deviceGroups:()=>ta,devicePresets:()=>ea,diffConfigs:()=>Yi,exportConfigsAsJSON:()=>Xe,getConfigOverrides:()=>se,getConfigStateSummary:()=>De,getOverrideMode:()=>jt,getPresetById:()=>Qe,getPresetsByCategory:()=>Qo,loadAllObjectConfigs:()=>Sn,loadComponentSchemas:()=>xn,loadEngineConfig:()=>En,loadGamePromptConfig:()=>qi,loadObjectCentricConfig:()=>Pe,loadObjectConfig:()=>He,loadSceneConfig:()=>Cn,redoLastConfigChange:()=>yn,rehydrateObject:()=>Ki,removeConfigOverride:()=>Ot,resetToApplied:()=>Rt,resetToOriginal:()=>wn,setBootstrapDependencies:()=>El,setOverrideMode:()=>Bi,setupHotReload:()=>Zi,setupLiveEditBridge:()=>pi,toLegacyFormat:()=>Vi,trackObjectCreation:()=>Ds,trackObjectDeletion:()=>Ns,undoLastConfigChange:()=>bn,validateObjectConfig:()=>dt});module.exports=ro(zl);var Oe={};function tn(s,e,t=!1){Oe[s]||(Oe[s]=[]),Oe[s].push({fn:e,once:t})}function Si(s,e){if(Oe[s]){if(!e){delete Oe[s];return}Oe[s]=Oe[s].filter(t=>t.fn!==e)}}function nn(s,...e){let t=Oe[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Si(s,n.fn)}function oe(s,e){tn(s,e,!0)}var K=null,he=[],st=null;function Za(s){K=s,he=[],st!==null&&(clearTimeout(st),st=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(he.push(s),he.length>t.maxQueue&&(he=he.slice(he.length-t.maxQueue)),he.length>=t.batchSize){Ja();return}st===null&&(st=window.setTimeout(()=>{st=null,Ja()},t.flushIntervalMs))}}async function Ja(){let s=Qa();if(!s.endpoint||he.length===0)return;let e=he.splice(0,s.batchSize);await Xa(s.endpoint,{events:e},s.transport,s.debug),he.length>0&&await Xa(s.endpoint,{events:he.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 kt(){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=kt();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 f=g.durationMs>0?h/g.durationMs:1,m=es(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let T=f-y;m=es(T)}let v=g.ease(m);g.yoyo&&y%2===1&&(v=1-v);for(let T of g.props)ts(g.target,T.key,T.from+(T.to-T.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(f>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var T;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+((T=u==null?void 0:u.delayMsOverride)!=null?T:0)),f=oo(p.ease),m=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 P of Object.keys(p)){if(y.has(P))continue;let j=p[P];typeof j=="number"&&v.push({key:P,from:lo(d,P),to:j})}let w=is(d,p);return{target:d,startMs:kt(),delayMs:h,durationMs:g,ease:f,props:v,scaleFrom:w.from,scaleTo:w.to,repeat:m,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=kt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:kt(),h=kt()-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=[],f=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},m=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,w){return m({kind:"to",target:y,vars:v,atMs:f(w)}),b},fromTo(y,v,w,T){return m({kind:"fromTo",target:y,vars:w,from:v,atMs:f(T)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let w of p)w.kind==="fromTo"&&c.set(w.target,(y=w.from)!=null?y:{}),h.push(c.to(w.target,{...w.vars,delay:w.atMs/1e3+((v=w.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.84",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 le=0,uo=le++,os=le++,ls=le++,cs=le++,ds=le++,ps=le++,us=le++,gs=le++,hs=le++,fs=le++,ms=le++,bs=le++,Y=uo;function ys(){return Y===os}function vs(){return Y===ls}function ws(){return Y===cs}function xs(){return Y===ds}function rt(){return Y===ps}function ot(){return Y===us}function Ss(){return Y===gs}function Es(){return Y===hs}function Cs(){return Y===fs}function Ci(){return Y===ms}function Ai(){return Y===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(),Y=os;return}catch{}else if(s==="dapi")try{dapi.isReady(),Y=ls;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Y=cs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Y=ds)}catch{}else if(e==="mintegral")window.gameReady&&(Y=ps);else if(e==="tapjoy")window.TJ_API&&(Y=us);else if(e==="tiktok")window.openAppStore&&(Y=gs);else if(e==="smadex")try{window.smxTracking&&(Y=hs)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Y=fs)}catch{}else e==="vungle"?Y=ms:(s==="nucleo"||e==="nucleo")&&(Y=bs)}var an=at(require("lottie-web"),1),Li=an.default;typeof window!="undefined"&&(window.lottie=an.default,window.__baseLottie=an.default);var go=require("pixi.js");var ki=require("pixi.js");var ho=null;function Ti(s){ho=s}rn();sn();var Tt=require("pixi.js");rn();var wo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",_i=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&&(_i=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${_i}`))}}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 ye=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${_i}`);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 f=new Tt.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}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 We.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 Tt.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 Tt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],m=!1;for(let b of f)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),m=!0;break}}catch{continue}m||(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 Pt=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=at(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Co);lt();var on=require("pixi.js");lt();var Ri=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Pt}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 ye.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 ye.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)}});lt();var To=require("pixi.js"),Le={width:400,height:600,designWidth:400,scaleFactor:1},cn={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*Le.scaleFactor;t(s,Le.width,Le.height,n,i,!0,!1)})}function zi(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Le.width=s,Le.height=e,Le.scaleFactor=Math.min(s/Le.designWidth,1.15),cn.scale=Le.scaleFactor,cn.position=1,console.log(`[SCREEN] Global multipliers - scale: ${cn.scale.toFixed(3)}`),Io()}var Mt={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=Mt[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function _o(){return Mt}var jo={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 ln(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Ke(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:ln(s[0],e.x),y:ln(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:ln(n.x,e.x),y:ln(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=jo[n])!=null?t:e}return e}function ze(s,e,t,n={}){var g,h,f,m,b,y;let i=Ke(t),a=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((f=a.left)!=null?f:0)+r.x,l=((m=a.right)!=null?m: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 ct(s,e,t,n={}){var f,m,b,y,v,w;let i=(f=n.inset)!=null?f:{},a=(m=n.padding)!=null?m:{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=((w=i.bottom)!=null?w:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Ke(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=_o,window.copyConfig=Uo,window.applyConfig=It,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 de(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,f,m,b,y,v,w,T,P,j,L,M;let i=0,a=0;switch(n.type){case"top":i=de(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=de(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,(f=(h=n.offset)==null?void 0:h.x)!=null?f:0),a=de(t,(b=(m=n.offset)==null?void 0:m.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=de(t,(T=(w=n.offset)==null?void 0:w.y)!=null?T:0);break;case"center":i=de(e,(j=(P=n.offset)==null?void 0:P.x)!=null?j:0),a=de(t,(M=(L=n.offset)==null?void 0:L.y)!=null?M: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);ke(s,de(e),l);let c=a?i*Le.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){ke(s,de(e),dn(t,n)),Te(s,i)}function $o(s,e,t,n=0,i=0,a=1){ke(s,de(e,n),de(t,i)),Te(s,a)}function Do(s,e,t,n=.1,i=1){ke(s,un(e,n),de(t)),Te(s,i)}function No(s,e,t,n=.1,i=1){ke(s,gn(e,n),de(t)),Te(s,i)}function Ho(s,e,t,n=.05,i=.05,a=1){ke(s,un(e,i),pn(t,n)),Te(s,a)}function Fo(s,e,t,n=.05,i=.05,a=1){ke(s,gn(e,i),pn(t,n)),Te(s,a)}function Bo(s,e,t,n=.05,i=.05,a=1){ke(s,un(e,i),dn(t,n)),Te(s,a)}function Go(s,e,t,n=.05,i=.05,a=1){ke(s,gn(e,i),dn(t,n)),Te(s,a)}function ke(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 Ye={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&&Ye[s]?JSON.parse(JSON.stringify(Ye[s])):JSON.parse(JSON.stringify(Mt))}function It(s){Object.keys(s).forEach(e=>{let t=e;Mt[t]&&s[t]&&Object.assign(Mt[t],s[t])}),console.log("Config applied:",s)}function qo(s,e){let t=s/e;t>1.6?(It(Ye.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(It(Ye.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(It(Ye.square),console.log("Applied SQUARE config for ratio:",t)):(It(Ye.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Ye,s.resolveAnchorVec2=s.resolveAnchorVec2||Ke,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||ze,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||ct}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 Qe(s){return ea.find(e=>e.id===s)||Ln}function Qo(s){return ea.filter(e=>e.category===s)}ee();var we=class{async updateProperty(e,t,n,i={}){var l,c,d,p,u,g,h,f,m,b,y,v;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(re({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform.")){console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);let w=r==null?void 0:r.motion;if(w&&typeof w=="object"&&w.enabled!==!1&&(((p=w==null?void 0:w.intro)==null?void 0:p.enabled)===!0||((u=w==null?void 0:w.pulse)==null?void 0:u.enabled)===!0||((g=w==null?void 0:w.swing)==null?void 0:g.enabled)===!0||((h=w==null?void 0:w.continuousMove)==null?void 0:h.enabled)===!0||((f=w==null?void 0:w.continuousRotate)==null?void 0:f.enabled)===!0||((m=w==null?void 0:w.orbit)==null?void 0:m.enabled)===!0)){let j=window.applyEditableObjectConfig;if(typeof j=="function"){let L=window.__editableConfig,M=(v=(y=(b=L==null?void 0:L.objects)==null?void 0:b.get)==null?void 0:y.call(b,e))!=null?v:r;await j(e,M),console.log("[PropertyUpdateManager] Applied config for motion object")}}i.refreshInspector||requestAnimationFrame(()=>{window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e}}))})}else{let w=window.applyEditableObjectConfig;if(typeof w=="function"){let T=window.__editableConfig,P=(d=(c=(l=T==null?void 0:T.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await w(e,P),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 kn=class{constructor(){this.updateManager=new we}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}}},Tn=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">
@@ -536,18 +536,18 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
536
536
  <button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Create Spawner</button>
537
537
  </div>
538
538
  </div>
539
- `;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},d=t.querySelectorAll(".add-menu-modal-tab"),p=t.querySelectorAll(".add-menu-modal-tab-content");d.forEach(v=>{v.addEventListener("click",()=>{var T;let w=v.dataset.tab;d.forEach(I=>I.classList.remove("active")),p.forEach(I=>I.classList.remove("active")),v.classList.add("active"),(T=t.querySelector(`[data-tab-content="${w}"]`))==null||T.classList.add("active")})});let u=v=>{let w=v.trim();if(!w)return null;try{return JSON.parse(w)}catch{return null}},g=()=>{var G;let v=t.querySelector("#spawner-instance-id").value.trim(),w=t.querySelector("#spawner-template-id").value.trim(),T=t.querySelector("#spawner-spawn-templates").value,I=t.querySelector("#spawner-position-source").value.trim(),_=t.querySelector("#spawner-point-mode").value.trim(),L=t.querySelector("#spawner-spawn-points").value,M=t.querySelector("#spawner-pattern").value.trim(),O=Number(t.querySelector("#spawner-rate").value.trim()),P=Number(t.querySelector("#spawner-pool").value.trim()),E=Number(t.querySelector("#spawner-lifetime").value.trim()),C=t.querySelector("#spawner-return-on-invisible").checked,A=t.querySelector("#spawner-movement").value.trim(),S=Number(t.querySelector("#spawner-vel-x").value.trim()),x=Number(t.querySelector("#spawner-vel-y").value.trim()),j=t.querySelector("#spawner-velocity-range").value,k=u(T),R=Array.isArray(k)&&k.length?k:null,z=typeof((G=R==null?void 0:R[0])==null?void 0:G.templateId)=="string"?String(R[0].templateId):w;if(!v){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let D={templateId:z,spawnPattern:M,spawnRate:Number.isFinite(O)?O:650,poolSize:Number.isFinite(P)?P:18,returnOnInvisible:C,positionSource:I,spawnPointMode:_,movementMode:A,lifetime:Number.isFinite(E)?E:5e3};R&&(D.spawnTemplates=R);let q=u(L);Array.isArray(q)&&(D.spawnPoints=q),Number.isFinite(S)&&Number.isFinite(x)&&(D.velocity={x:S,y:x});let F=u(j);F&&typeof F=="object"&&(D.velocityRange=F),c(),e({templateId:z,instanceId:v,spawnerProps:D})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",v=>v.stopPropagation()),(m=t.querySelector('[data-action="confirm"]'))==null||m.addEventListener("click",g),(b=t.querySelector('[data-action="cancel"]'))==null||b.addEventListener("click",h),(y=t.querySelector(".add-menu-modal-close"))==null||y.addEventListener("click",h),t.addEventListener("click",v=>{v.target===t&&h()}),document.body.appendChild(t),t.querySelector("#spawner-instance-id").focus()})}sanitizeInstanceId(e){let t=e.trim();return!t||!/^[a-zA-Z0-9._-]+$/.test(t)?null:t}buildDefaultConfig(e,t,n){let i=`json.${t}`,a={identity:{id:i,category:e==="ui-image"||e==="ui-text"?"ui":"environment"},transform:{position:{x:0,y:0},offset:{x:0,y:0},scale:e==="sprite"||e==="ui-image"?.2:1,rotation:0,anchor:"center",position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0},instance_id:t,object_config:i};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${n}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:n,font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",color:"#FFFFFF"}),e==="graphics"&&(a.effects={width:200,height:200,fill_color:"#FFFFFF",fill_alpha:1}),a}async handleCreateObject(e,t){var l,c,d;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(i);if(!a)return;let r=a,o=this.buildDefaultConfig(e,r,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:r,objectConfigId:o.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:o,forceSync:!0})}),u=await p.json().catch(()=>({}));if(!p.ok||(u==null?void 0:u.success)===!1){let h=((l=u==null?void 0:u.errors)==null?void 0:l.join(`
539
+ `;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},d=t.querySelectorAll(".add-menu-modal-tab"),p=t.querySelectorAll(".add-menu-modal-tab-content");d.forEach(v=>{v.addEventListener("click",()=>{var T;let w=v.dataset.tab;d.forEach(P=>P.classList.remove("active")),p.forEach(P=>P.classList.remove("active")),v.classList.add("active"),(T=t.querySelector(`[data-tab-content="${w}"]`))==null||T.classList.add("active")})});let u=v=>{let w=v.trim();if(!w)return null;try{return JSON.parse(w)}catch{return null}},g=()=>{var G;let v=t.querySelector("#spawner-instance-id").value.trim(),w=t.querySelector("#spawner-template-id").value.trim(),T=t.querySelector("#spawner-spawn-templates").value,P=t.querySelector("#spawner-position-source").value.trim(),j=t.querySelector("#spawner-point-mode").value.trim(),L=t.querySelector("#spawner-spawn-points").value,M=t.querySelector("#spawner-pattern").value.trim(),R=Number(t.querySelector("#spawner-rate").value.trim()),I=Number(t.querySelector("#spawner-pool").value.trim()),E=Number(t.querySelector("#spawner-lifetime").value.trim()),C=t.querySelector("#spawner-return-on-invisible").checked,A=t.querySelector("#spawner-movement").value.trim(),S=Number(t.querySelector("#spawner-vel-x").value.trim()),x=Number(t.querySelector("#spawner-vel-y").value.trim()),_=t.querySelector("#spawner-velocity-range").value,k=u(T),O=Array.isArray(k)&&k.length?k:null,z=typeof((G=O==null?void 0:O[0])==null?void 0:G.templateId)=="string"?String(O[0].templateId):w;if(!v){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let D={templateId:z,spawnPattern:M,spawnRate:Number.isFinite(R)?R:650,poolSize:Number.isFinite(I)?I:18,returnOnInvisible:C,positionSource:P,spawnPointMode:j,movementMode:A,lifetime:Number.isFinite(E)?E:5e3};O&&(D.spawnTemplates=O);let q=u(L);Array.isArray(q)&&(D.spawnPoints=q),Number.isFinite(S)&&Number.isFinite(x)&&(D.velocity={x:S,y:x});let F=u(_);F&&typeof F=="object"&&(D.velocityRange=F),c(),e({templateId:z,instanceId:v,spawnerProps:D})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",v=>v.stopPropagation()),(m=t.querySelector('[data-action="confirm"]'))==null||m.addEventListener("click",g),(b=t.querySelector('[data-action="cancel"]'))==null||b.addEventListener("click",h),(y=t.querySelector(".add-menu-modal-close"))==null||y.addEventListener("click",h),t.addEventListener("click",v=>{v.target===t&&h()}),document.body.appendChild(t),t.querySelector("#spawner-instance-id").focus()})}sanitizeInstanceId(e){let t=e.trim();return!t||!/^[a-zA-Z0-9._-]+$/.test(t)?null:t}buildDefaultConfig(e,t,n){let i=`json.${t}`,a={identity:{id:i,category:e==="ui-image"||e==="ui-text"?"ui":"environment"},transform:{position:{x:0,y:0},offset:{x:0,y:0},scale:e==="sprite"||e==="ui-image"?.2:1,rotation:0,anchor:"center",position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0},instance_id:t,object_config:i};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${n}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:n,font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",color:"#FFFFFF"}),e==="graphics"&&(a.effects={width:200,height:200,fill_color:"#FFFFFF",fill_alpha:1}),a}async handleCreateObject(e,t){var l,c,d;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(i);if(!a)return;let r=a,o=this.buildDefaultConfig(e,r,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:r,objectConfigId:o.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:o,forceSync:!0})}),u=await p.json().catch(()=>({}));if(!p.ok||(u==null?void 0:u.success)===!1){let h=((l=u==null?void 0:u.errors)==null?void 0:l.join(`
540
540
  `))||(u==null?void 0:u.error)||"Failed to create object.";alert(h);return}let{trackObjectCreation:g}=await Promise.resolve().then(()=>(ee(),Ne));g(r,n,o),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed")),(d=(c=this.options).onRefresh)==null||d.call(c)}catch(p){alert(`Failed to create object: ${p instanceof Error?p.message:String(p)}`)}}async handleCreateFromTemplate(e,t){var r,o,l;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",a=await this.promptName(i);if(a)try{let c=await fetch("/api/objects/create-from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e,instanceId:a,screenId:n,forceSync:!0})}),d=await c.json().catch(()=>({}));if(!c.ok||(d==null?void 0:d.success)===!1){let p=((r=d==null?void 0:d.errors)==null?void 0:r.join(`
541
- `))||(d==null?void 0:d.error)||"Failed to create from template.";alert(p);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(l=(o=this.options).onRefresh)==null||l.call(o)}catch(c){alert(`Failed to create from template: ${c instanceof Error?c.message:String(c)}`)}}async handleCreateSystem(e,t){var i,a,r,o,l,c,d,p,u,g,h,f,m,b,y,v,w,T,I,_,L,M,O,P,E,C,A;this.close();let n=t!=null?t:await this.promptScreen();if(n){if(e==="collectable-system")try{let S=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((i=x==null?void 0:x.errors)==null?void 0:i.join(`
542
- `))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(r=(a=this.options).onRefresh)==null||r.call(a)}catch(S){alert(`Failed to create collectable system: ${S instanceof Error?S.message:String(S)}`)}if(e==="drag-snap-couples")try{let S=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((o=x==null?void 0:x.errors)==null?void 0:o.join(`
543
- `))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(S){alert(`Failed to create drag-snap system: ${S instanceof Error?S.message:String(S)}`)}if(e==="swerve-collect")try{let S=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((d=x==null?void 0:x.errors)==null?void 0:d.join(`
544
- `))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(u=(p=this.options).onRefresh)==null||u.call(p)}catch(S){alert(`Failed to create swerve collect system: ${S instanceof Error?S.message:String(S)}`)}if(e==="tap-destroy")try{let S=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((g=x==null?void 0:x.errors)==null?void 0:g.join(`
545
- `))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(f=(h=this.options).onRefresh)==null||f.call(h)}catch(S){alert(`Failed to create tap destroy system: ${S instanceof Error?S.message:String(S)}`)}if(e==="scratch-card")try{let S=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((m=x==null?void 0:x.errors)==null?void 0:m.join(`
546
- `))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(y=(b=this.options).onRefresh)==null||y.call(b)}catch(S){alert(`Failed to create scratch card system: ${S instanceof Error?S.message:String(S)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let x=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="start-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let k=((v=j==null?void 0:j.errors)==null?void 0:v.join(`
547
- `))||(j==null?void 0:j.error)||"Failed to create start screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(T=(w=this.options).onRefresh)==null||T.call(w)}catch(S){alert(`Failed to create start screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let x=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="endgame-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let k=((I=j==null?void 0:j.errors)==null?void 0:I.join(`
548
- `))||(j==null?void 0:j.error)||"Failed to create endgame screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(L=(_=this.options).onRefresh)==null||L.call(_)}catch(S){alert(`Failed to create endgame screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="bullet-system")try{let S=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((M=x==null?void 0:x.errors)==null?void 0:M.join(`
549
- `))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(P=(O=this.options).onRefresh)==null||P.call(O)}catch(S){alert(`Failed to create bullet system: ${S instanceof Error?S.message:String(S)}`)}if(e==="spawner"){let S=await this.promptSpawnerConfig();if(!S)return;let{templateId:x,instanceId:j,spawnerProps:k}=S;try{let R=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,templateId:x,instanceId:j,spawnerProps:k,forceSync:!0})}),z=await R.json().catch(()=>({}));if(!R.ok||(z==null?void 0:z.success)===!1){let D=((E=z==null?void 0:z.errors)==null?void 0:E.join(`
550
- `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(D);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(A=(C=this.options).onRefresh)==null||A.call(C)}catch(R){alert(`Failed to create spawner: ${R instanceof Error?R.message:String(R)}`)}}}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[AddObjectMenu] Failed to sync screens:",e)}}};var Mn=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.selectedIds=new Set;this.lastSelectedIndex=-1;this.objectEntries=[];this.options=null;this.retryTimer=null;this.screenFilter="all";this.isContextMenuOpen=!1;this.systemBundles=new Map;this.collapsedGroups=new Set}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getCollapseStorageKey(){return`handler_preview_scene_collapsed::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}loadCollapsedGroups(){try{let e=window.localStorage.getItem(this.getCollapseStorageKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.collapsedGroups=new Set(t.filter(n=>typeof n=="string")))}catch{}}persistCollapsedGroups(){try{window.localStorage.setItem(this.getCollapseStorageKey(),JSON.stringify(Array.from(this.collapsedGroups)))}catch{}}isCollapsed(e){return this.collapsedGroups.has(e)}setCollapsed(e,t){t?this.collapsedGroups.add(e):this.collapsedGroups.delete(e),this.persistCollapsedGroups()}getCollapseKey(e){return encodeURIComponent(e)}getSystemBundleKey(e,t){return this.getCollapseKey(`bundle:${e}::${t}`)}render(){return`
541
+ `))||(d==null?void 0:d.error)||"Failed to create from template.";alert(p);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(l=(o=this.options).onRefresh)==null||l.call(o)}catch(c){alert(`Failed to create from template: ${c instanceof Error?c.message:String(c)}`)}}async handleCreateSystem(e,t){var i,a,r,o,l,c,d,p,u,g,h,f,m,b,y,v,w,T,P,j,L,M,R,I,E,C,A;this.close();let n=t!=null?t:await this.promptScreen();if(n){if(e==="collectable-system")try{let S=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((i=x==null?void 0:x.errors)==null?void 0:i.join(`
542
+ `))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(r=(a=this.options).onRefresh)==null||r.call(a)}catch(S){alert(`Failed to create collectable system: ${S instanceof Error?S.message:String(S)}`)}if(e==="drag-snap-couples")try{let S=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((o=x==null?void 0:x.errors)==null?void 0:o.join(`
543
+ `))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(S){alert(`Failed to create drag-snap system: ${S instanceof Error?S.message:String(S)}`)}if(e==="swerve-collect")try{let S=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((d=x==null?void 0:x.errors)==null?void 0:d.join(`
544
+ `))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(u=(p=this.options).onRefresh)==null||u.call(p)}catch(S){alert(`Failed to create swerve collect system: ${S instanceof Error?S.message:String(S)}`)}if(e==="tap-destroy")try{let S=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((g=x==null?void 0:x.errors)==null?void 0:g.join(`
545
+ `))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(f=(h=this.options).onRefresh)==null||f.call(h)}catch(S){alert(`Failed to create tap destroy system: ${S instanceof Error?S.message:String(S)}`)}if(e==="scratch-card")try{let S=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((m=x==null?void 0:x.errors)==null?void 0:m.join(`
546
+ `))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(y=(b=this.options).onRefresh)==null||y.call(b)}catch(S){alert(`Failed to create scratch card system: ${S instanceof Error?S.message:String(S)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let x=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="start-screen"})}),_=await x.json().catch(()=>({}));if(!x.ok||(_==null?void 0:_.success)===!1){let k=((v=_==null?void 0:_.errors)==null?void 0:v.join(`
547
+ `))||(_==null?void 0:_.error)||"Failed to create start screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(T=(w=this.options).onRefresh)==null||T.call(w)}catch(S){alert(`Failed to create start screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let x=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="endgame-screen"})}),_=await x.json().catch(()=>({}));if(!x.ok||(_==null?void 0:_.success)===!1){let k=((P=_==null?void 0:_.errors)==null?void 0:P.join(`
548
+ `))||(_==null?void 0:_.error)||"Failed to create endgame screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(L=(j=this.options).onRefresh)==null||L.call(j)}catch(S){alert(`Failed to create endgame screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="bullet-system")try{let S=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let _=((M=x==null?void 0:x.errors)==null?void 0:M.join(`
549
+ `))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(_);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(I=(R=this.options).onRefresh)==null||I.call(R)}catch(S){alert(`Failed to create bullet system: ${S instanceof Error?S.message:String(S)}`)}if(e==="spawner"){let S=await this.promptSpawnerConfig();if(!S)return;let{templateId:x,instanceId:_,spawnerProps:k}=S;try{let O=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,templateId:x,instanceId:_,spawnerProps:k,forceSync:!0})}),z=await O.json().catch(()=>({}));if(!O.ok||(z==null?void 0:z.success)===!1){let D=((E=z==null?void 0:z.errors)==null?void 0:E.join(`
550
+ `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(D);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(A=(C=this.options).onRefresh)==null||A.call(C)}catch(O){alert(`Failed to create spawner: ${O instanceof Error?O.message:String(O)}`)}}}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[AddObjectMenu] Failed to sync screens:",e)}}};var Mn=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.selectedIds=new Set;this.lastSelectedIndex=-1;this.objectEntries=[];this.options=null;this.retryTimer=null;this.screenFilter="all";this.isContextMenuOpen=!1;this.systemBundles=new Map;this.collapsedGroups=new Set}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getCollapseStorageKey(){return`handler_preview_scene_collapsed::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}loadCollapsedGroups(){try{let e=window.localStorage.getItem(this.getCollapseStorageKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.collapsedGroups=new Set(t.filter(n=>typeof n=="string")))}catch{}}persistCollapsedGroups(){try{window.localStorage.setItem(this.getCollapseStorageKey(),JSON.stringify(Array.from(this.collapsedGroups)))}catch{}}isCollapsed(e){return this.collapsedGroups.has(e)}setCollapsed(e,t){t?this.collapsedGroups.add(e):this.collapsedGroups.delete(e),this.persistCollapsedGroups()}getCollapseKey(e){return encodeURIComponent(e)}getSystemBundleKey(e,t){return this.getCollapseKey(`bundle:${e}::${t}`)}render(){return`
551
551
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
552
552
  <div class="scene-panel-header" data-panel-handle>
553
553
  <div class="panel-title">
@@ -582,7 +582,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
582
582
  </div>
583
583
  <div class="panel-resize-handle-v" data-panel-resize-v></div>
584
584
  </div>
585
- `}initialize(e,t){var a,r,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(r=this.root)==null?void 0:r.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var w;let h=g.target,f=h==null?void 0:h.closest("[data-collapse-key]");if(f){let T=f.dataset.collapseKey||"";if(!T)return;let I=(w=this.listContainer)==null?void 0:w.querySelector(`[data-collapse-content="${T}"]`),_=this.isCollapsed(T);I&&(I.style.display=_?"":"none"),f.textContent=_?"\u25BE":"\u25B8",this.setCollapsed(T,!_),g.preventDefault(),g.stopPropagation();return}let m=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(m){let T=m.dataset.objectId;if(!T)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(T);return}let b=h==null?void 0:h.closest("[data-system-bundle-action][data-system-bundle-id]");if(!b)return;g.preventDefault(),g.stopPropagation();let y=b.dataset.systemBundleAction,v=b.dataset.systemBundleId;if(!(!y||!v)){if(y==="toggle-visibility"){this.toggleSystemBundleVisibility(v);return}y==="delete"&&this.deleteSystemBundle(v)}});let n=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");n==null||n.addEventListener("click",g=>{g.stopPropagation();let h=n.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let i=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(i){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let g=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof g=="function"&&g().catch(()=>{})}catch{}i.addEventListener("change",()=>{let g=i.value||"all";this.screenFilter=g;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let h=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof h=="function"&&h().catch(()=>{})}catch{}this.refreshObjects()})}(p=this.root)==null||p.addEventListener("click",g=>{let h=g.target;if(!h||h.closest("[data-context-menu]"))return;if(h.tagName==="INPUT"&&h.classList.contains("scene-object-checkbox")){let w=h.dataset.objectId;if(!w)return;g.stopPropagation(),this.toggleBatchSelect(w);return}let f=h.closest(".scene-object-item[data-object-id]");if(!f)return;let m=f.dataset.objectId;if(!m)return;let b=g.ctrlKey||g.metaKey;g.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,m):b?this.toggleBatchSelect(m):this.select(m)}),(u=this.listContainer)==null||u.addEventListener("contextmenu",g=>{var w;let h=g.target,f=h==null?void 0:h.closest("[data-object-id]");if(!f)return;let m=f.dataset.objectId;if(!m)return;g.preventDefault();let b=window.getEditableObjectConfig,y=typeof b=="function"?b(m):null;if(!y){let T=window.__editableObjectConfigs;T&&typeof T.get=="function"&&(y=(w=T.get(m))!=null?w:null)}let v=this.inferScreen(m,y);this.showContextMenu(m,v,g.clientX,g.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){e?(this.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=e):(this.selectedIds.clear(),this.selectedId=null),this.updateSelectionUI()}getSelectedIds(){return Array.from(this.selectedIds)}updateSelectionUI(){var a,r,o,l,c;if(!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{let p=d.dataset.objectId,u=p?this.selectedIds.has(p):!1,g=p===this.selectedId;d.classList.toggle("selected",u),d.classList.toggle("active",g);let h=d.closest(".scene-object-item-wrapper"),f=h==null?void 0:h.querySelector(".scene-object-checkbox");f&&(f.checked=u)});let t=(a=this.root)==null?void 0:a.querySelector("[data-breadcrumbs]"),n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumb-screen]"),i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&n&&i){let d=this.selectedIds.size===1?this.selectedId:null;if(d){let p=window.getEditableObjectConfig,u=typeof p=="function"?p(d):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(l=b.get(d))!=null?l:null)}let g=this.inferScreen(d,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},f=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||d).toString(),m=this.formatDisplayName(f);n.textContent=h[g]||g,i.textContent=m,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var u;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectListAll,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let i=typeof t=="function"?t():e();if(!Array.isArray(i)||i.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(i=Array.from(g.keys()))}if(!Array.isArray(i)||i.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o={loading:{templates:[],systems:[],objects:[],bundles:new Map},start:{templates:[],systems:[],objects:[],bundles:new Map},gameplay:{templates:[],systems:[],objects:[],bundles:new Map},tutorial:{templates:[],systems:[],objects:[],bundles:new Map},endgame:{templates:[],systems:[],objects:[],bundles:new Map}};this.systemBundles=new Map;let l=g=>{var m,b,y,v,w;let h=(v=(y=(b=(m=window.__editableConfig)==null?void 0:m.objects)==null?void 0:b.get)==null?void 0:y.call(b,g))!=null?v:null;if(h)return h;let f=window.__editableObjectConfigs;return f&&typeof f.get=="function"&&(w=f.get(g))!=null?w:null};i.forEach(g=>{var A,S,x,j,k,R,z;let h=l(g),f=(((A=h==null?void 0:h.identity)==null?void 0:A.category)||"scene").toString(),m=(((S=h==null?void 0:h.identity)==null?void 0:S.id)||g).toString(),b=f.toLowerCase(),y=m.toLowerCase(),v=b.includes("ui")||y.startsWith("ui")||y.includes("label"),w=b==="system",T=((x=h==null?void 0:h.identity)==null?void 0:x.is_template)===!0||y.includes(".template")||g.toLowerCase().includes(".template"),I=typeof((j=h==null?void 0:h.identity)==null?void 0:j.system_group)=="string"?h.identity.system_group:null,_=typeof((k=h==null?void 0:h.identity)==null?void 0:k.system_label)=="string"?h.identity.system_label:I?this.formatDisplayName(I):null,L=this.formatDisplayName(m||g),M=((R=h==null?void 0:h.render)==null?void 0:R.visible)===!1||(h==null?void 0:h.enabled)===!1,O=this.getObjectType(h),P={id:g,label:L,category:f,isUi:v,isTemplate:T,isUnused:M,objectType:O,systemGroupId:I,systemLabel:_},E=this.inferScreen(P.id,h);if(!(this.screenFilter!=="all"&&E!==this.screenFilter||!(!a||P.id.toLowerCase().includes(a)||P.label.toLowerCase().includes(a)))){if(I){let D=this.getSystemBundleKey(E,I),q=_!=null?_:I,F=o[E],G=F.bundles.get(D);G?(G.entries.push(P),G.objectIds.push(g)):F.bundles.set(D,{key:D,label:q,objectIds:[g],entries:[P]});let B=(z=this.systemBundles.get(D))!=null?z:{label:q,objectIds:[]};B.label=q,B.objectIds.push(g),this.systemBundles.set(D,B);return}if(T){o[E].templates.push(P);return}w?o[E].systems.push(P):o[E].objects.push(P)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?r:[this.screenFilter],p=d.map(g=>this.renderScreenGroup(g,c[g],o[g])).join("");this.listContainer.innerHTML=p,this.objectEntries=[];for(let g of d){let h=o[g];this.objectEntries.push(...h.templates),h.bundles.forEach(f=>this.objectEntries.push(...f.entries)),this.objectEntries.push(...h.systems),this.objectEntries.push(...h.objects)}for(let g of d){let h=o[g];if(!h.systems.length)continue;let f=this.listContainer.querySelector(`[data-delete-system-group="${g}"]`);f==null||f.addEventListener("click",m=>{m.stopPropagation(),this.deleteSystemGroup(h.systems)})}this.updateSelectionUI()}renderSystemBundle(e,t,n,i){let a=this.isBundleAllHidden(n),r=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=i.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
585
+ `}initialize(e,t){var a,r,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(r=this.root)==null?void 0:r.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var w;let h=g.target,f=h==null?void 0:h.closest("[data-collapse-key]");if(f){let T=f.dataset.collapseKey||"";if(!T)return;let P=(w=this.listContainer)==null?void 0:w.querySelector(`[data-collapse-content="${T}"]`),j=this.isCollapsed(T);P&&(P.style.display=j?"":"none"),f.textContent=j?"\u25BE":"\u25B8",this.setCollapsed(T,!j),g.preventDefault(),g.stopPropagation();return}let m=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(m){let T=m.dataset.objectId;if(!T)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(T);return}let b=h==null?void 0:h.closest("[data-system-bundle-action][data-system-bundle-id]");if(!b)return;g.preventDefault(),g.stopPropagation();let y=b.dataset.systemBundleAction,v=b.dataset.systemBundleId;if(!(!y||!v)){if(y==="toggle-visibility"){this.toggleSystemBundleVisibility(v);return}y==="delete"&&this.deleteSystemBundle(v)}});let n=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");n==null||n.addEventListener("click",g=>{g.stopPropagation();let h=n.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let i=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(i){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let g=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof g=="function"&&g().catch(()=>{})}catch{}i.addEventListener("change",()=>{let g=i.value||"all";this.screenFilter=g;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let h=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof h=="function"&&h().catch(()=>{})}catch{}this.refreshObjects()})}(p=this.root)==null||p.addEventListener("click",g=>{let h=g.target;if(!h||h.closest("[data-context-menu]"))return;if(h.tagName==="INPUT"&&h.classList.contains("scene-object-checkbox")){let w=h.dataset.objectId;if(!w)return;g.stopPropagation(),this.toggleBatchSelect(w);return}let f=h.closest(".scene-object-item[data-object-id]");if(!f)return;let m=f.dataset.objectId;if(!m)return;let b=g.ctrlKey||g.metaKey;g.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,m):b?this.toggleBatchSelect(m):this.select(m)}),(u=this.listContainer)==null||u.addEventListener("contextmenu",g=>{var w;let h=g.target,f=h==null?void 0:h.closest("[data-object-id]");if(!f)return;let m=f.dataset.objectId;if(!m)return;g.preventDefault();let b=window.getEditableObjectConfig,y=typeof b=="function"?b(m):null;if(!y){let T=window.__editableObjectConfigs;T&&typeof T.get=="function"&&(y=(w=T.get(m))!=null?w:null)}let v=this.inferScreen(m,y);this.showContextMenu(m,v,g.clientX,g.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){e?(this.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=e):(this.selectedIds.clear(),this.selectedId=null),this.updateSelectionUI()}getSelectedIds(){return Array.from(this.selectedIds)}updateSelectionUI(){var a,r,o,l,c;if(!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{let p=d.dataset.objectId,u=p?this.selectedIds.has(p):!1,g=p===this.selectedId;d.classList.toggle("selected",u),d.classList.toggle("active",g);let h=d.closest(".scene-object-item-wrapper"),f=h==null?void 0:h.querySelector(".scene-object-checkbox");f&&(f.checked=u)});let t=(a=this.root)==null?void 0:a.querySelector("[data-breadcrumbs]"),n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumb-screen]"),i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&n&&i){let d=this.selectedIds.size===1?this.selectedId:null;if(d){let p=window.getEditableObjectConfig,u=typeof p=="function"?p(d):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(l=b.get(d))!=null?l:null)}let g=this.inferScreen(d,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},f=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||d).toString(),m=this.formatDisplayName(f);n.textContent=h[g]||g,i.textContent=m,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var u;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectListAll,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let i=typeof t=="function"?t():e();if(!Array.isArray(i)||i.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(i=Array.from(g.keys()))}if(!Array.isArray(i)||i.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o={loading:{templates:[],systems:[],objects:[],bundles:new Map},start:{templates:[],systems:[],objects:[],bundles:new Map},gameplay:{templates:[],systems:[],objects:[],bundles:new Map},tutorial:{templates:[],systems:[],objects:[],bundles:new Map},endgame:{templates:[],systems:[],objects:[],bundles:new Map}};this.systemBundles=new Map;let l=g=>{var m,b,y,v,w;let h=(v=(y=(b=(m=window.__editableConfig)==null?void 0:m.objects)==null?void 0:b.get)==null?void 0:y.call(b,g))!=null?v:null;if(h)return h;let f=window.__editableObjectConfigs;return f&&typeof f.get=="function"&&(w=f.get(g))!=null?w:null};i.forEach(g=>{var A,S,x,_,k,O,z;let h=l(g),f=(((A=h==null?void 0:h.identity)==null?void 0:A.category)||"scene").toString(),m=(((S=h==null?void 0:h.identity)==null?void 0:S.id)||g).toString(),b=f.toLowerCase(),y=m.toLowerCase(),v=b.includes("ui")||y.startsWith("ui")||y.includes("label"),w=b==="system",T=((x=h==null?void 0:h.identity)==null?void 0:x.is_template)===!0||y.includes(".template")||g.toLowerCase().includes(".template"),P=typeof((_=h==null?void 0:h.identity)==null?void 0:_.system_group)=="string"?h.identity.system_group:null,j=typeof((k=h==null?void 0:h.identity)==null?void 0:k.system_label)=="string"?h.identity.system_label:P?this.formatDisplayName(P):null,L=this.formatDisplayName(m||g),M=((O=h==null?void 0:h.render)==null?void 0:O.visible)===!1||(h==null?void 0:h.enabled)===!1,R=this.getObjectType(h),I={id:g,label:L,category:f,isUi:v,isTemplate:T,isUnused:M,objectType:R,systemGroupId:P,systemLabel:j},E=this.inferScreen(I.id,h);if(!(this.screenFilter!=="all"&&E!==this.screenFilter||!(!a||I.id.toLowerCase().includes(a)||I.label.toLowerCase().includes(a)))){if(P){let D=this.getSystemBundleKey(E,P),q=j!=null?j:P,F=o[E],G=F.bundles.get(D);G?(G.entries.push(I),G.objectIds.push(g)):F.bundles.set(D,{key:D,label:q,objectIds:[g],entries:[I]});let B=(z=this.systemBundles.get(D))!=null?z:{label:q,objectIds:[]};B.label=q,B.objectIds.push(g),this.systemBundles.set(D,B);return}if(T){o[E].templates.push(I);return}w?o[E].systems.push(I):o[E].objects.push(I)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?r:[this.screenFilter],p=d.map(g=>this.renderScreenGroup(g,c[g],o[g])).join("");this.listContainer.innerHTML=p,this.objectEntries=[];for(let g of d){let h=o[g];this.objectEntries.push(...h.templates),h.bundles.forEach(f=>this.objectEntries.push(...f.entries)),this.objectEntries.push(...h.systems),this.objectEntries.push(...h.objects)}for(let g of d){let h=o[g];if(!h.systems.length)continue;let f=this.listContainer.querySelector(`[data-delete-system-group="${g}"]`);f==null||f.addEventListener("click",m=>{m.stopPropagation(),this.deleteSystemGroup(h.systems)})}this.updateSelectionUI()}renderSystemBundle(e,t,n,i){let a=this.isBundleAllHidden(n),r=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=i.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
586
586
  <div class="scene-object-group scene-object-group-bundle" data-system-bundle="${c}">
587
587
  <div class="scene-object-group-title">
588
588
  <button class="scene-object-group-toggle" type="button" data-collapse-key="${d}">${p?"\u25B8":"\u25BE"}</button>
@@ -714,7 +714,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
714
714
  </div>
715
715
  </div>
716
716
  </div>
717
- `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var E;this.isCollapsed=!this.isCollapsed,(E=this.root)==null||E.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(E,C)=>{var S;let A=(S=this.root)==null?void 0:S.querySelector(`[data-status="${E}"]`);A&&A.classList.toggle("active",C)},r=this.root.querySelector("#debug-highlight-object");r==null||r.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightObject(!!r.checked),a("bounds",r.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightAnchor(!!o.checked),a("anchor",o.checked),window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}));try{localStorage.setItem(this.getSceneStorageKey("highlight_anchor"),o.checked?"true":"false")}catch{}});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)});let c=this.root.querySelector("#scene-grid-enabled"),d=this.root.querySelector("#scene-grid-gap"),p=this.root.querySelector("#scene-grid-alpha"),u=this.root.querySelector("#scene-grid-alpha-value"),g=this.root.querySelector("#scene-play-mode"),h=this.root.querySelector("#scene-background-cover"),f=this.root.querySelector("#scene-background-lock"),m=this.root.querySelector("[data-grid-toggle-btn]"),b=this.root.querySelector("[data-play-toggle-btn]"),y=()=>{if(!p)return .25;let E=Number(p.value),C=Number.isFinite(E)?Math.min(1,Math.max(0,E)):.25;return p.value=String(C),u&&(u.textContent=`${Math.round(C*100)}%`),C},v=(E,C,A)=>{var x,j;let S=A!==void 0?A:y();(j=(x=this.options)==null?void 0:x.onGridToggle)==null||j.call(x,E,C,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:E,gap:C,alpha:S}}))},w=E=>{var A,S;let C=y();(S=(A=this.options)==null?void 0:A.onGridGapChange)==null||S.call(A,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:E,alpha:C}}))},T=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onGridAlphaChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:M(),alpha:E}}))},I=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onPlayModeChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:E}}))},_=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onBackgroundCoverChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:background-cover",{detail:{enabled:E}}))},L=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onBackgroundLockChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:background-lock",{detail:{enabled:E}}))},M=()=>{if(!d)return 50;let E=Number(d.value),C=Number.isFinite(E)?Math.min(200,Math.max(4,E)):50;return d.value=String(C),C},O=E=>{c&&(c.checked=E),d&&(d.disabled=!E),p&&(p.disabled=!E),m==null||m.classList.toggle("active",E)},P=E=>{g&&(g.checked=E),b==null||b.classList.toggle("active",E)};try{let E=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),C=localStorage.getItem(this.getSceneStorageKey("grid_gap")),A=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),S=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),x=localStorage.getItem(this.getSceneStorageKey("background_cover")),j=localStorage.getItem(this.getSceneStorageKey("background_lock")),k=E?E==="true":!1;O(k),d&&(d.value=C||"50",d.disabled=!k),p&&(p.value=A||"0.25",p.disabled=!k,y()),o&&(o.checked=S==="true",a("anchor",o.checked));let R=!0;P(R),g&&(g.disabled=!0),b&&(b.disabled=!0);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),R?"true":"false")}catch{}v(k,M(),y()),I(R);let z=x?x==="true":!0,D=j?j==="true":!0;h&&(h.checked=z),f&&(f.checked=D),_(z),L(D),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let E=M(),C=y();d&&(d.disabled=!c.checked),p&&(p.disabled=!c.checked),m==null||m.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(C))}catch{}v(c.checked,E,C)}),d==null||d.addEventListener("input",()=>{let E=M(),C=y();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(C))}catch{}w(E)}),p==null||p.addEventListener("input",()=>{let E=y(),C=M();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(C))}catch{}T(E)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}b==null||b.classList.toggle("active",g.checked),I(g.checked)}),h==null||h.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_cover"),h.checked?"true":"false")}catch{}_(h.checked)}),f==null||f.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_lock"),f.checked?"true":"false")}catch{}L(f.checked)}),m==null||m.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),b==null||b.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var jn=class{constructor(){this.root=null;this.options=null}render(){return`
717
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var E;this.isCollapsed=!this.isCollapsed,(E=this.root)==null||E.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(E,C)=>{var S;let A=(S=this.root)==null?void 0:S.querySelector(`[data-status="${E}"]`);A&&A.classList.toggle("active",C)},r=this.root.querySelector("#debug-highlight-object");r==null||r.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightObject(!!r.checked),a("bounds",r.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var E;(E=this.options)==null||E.onHighlightAnchor(!!o.checked),a("anchor",o.checked),window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}));try{localStorage.setItem(this.getSceneStorageKey("highlight_anchor"),o.checked?"true":"false")}catch{}});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{a("nudge",l.checked)});let c=this.root.querySelector("#scene-grid-enabled"),d=this.root.querySelector("#scene-grid-gap"),p=this.root.querySelector("#scene-grid-alpha"),u=this.root.querySelector("#scene-grid-alpha-value"),g=this.root.querySelector("#scene-play-mode"),h=this.root.querySelector("#scene-background-cover"),f=this.root.querySelector("#scene-background-lock"),m=this.root.querySelector("[data-grid-toggle-btn]"),b=this.root.querySelector("[data-play-toggle-btn]"),y=()=>{if(!p)return .25;let E=Number(p.value),C=Number.isFinite(E)?Math.min(1,Math.max(0,E)):.25;return p.value=String(C),u&&(u.textContent=`${Math.round(C*100)}%`),C},v=(E,C,A)=>{var x,_;let S=A!==void 0?A:y();(_=(x=this.options)==null?void 0:x.onGridToggle)==null||_.call(x,E,C,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:E,gap:C,alpha:S}}))},w=E=>{var A,S;let C=y();(S=(A=this.options)==null?void 0:A.onGridGapChange)==null||S.call(A,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:E,alpha:C}}))},T=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onGridAlphaChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:M(),alpha:E}}))},P=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onPlayModeChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:E}}))},j=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onBackgroundCoverChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:background-cover",{detail:{enabled:E}}))},L=E=>{var C,A;(A=(C=this.options)==null?void 0:C.onBackgroundLockChange)==null||A.call(C,E),window.dispatchEvent(new CustomEvent("scene-editor:background-lock",{detail:{enabled:E}}))},M=()=>{if(!d)return 50;let E=Number(d.value),C=Number.isFinite(E)?Math.min(200,Math.max(4,E)):50;return d.value=String(C),C},R=E=>{c&&(c.checked=E),d&&(d.disabled=!E),p&&(p.disabled=!E),m==null||m.classList.toggle("active",E)},I=E=>{g&&(g.checked=E),b==null||b.classList.toggle("active",E)};try{let E=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),C=localStorage.getItem(this.getSceneStorageKey("grid_gap")),A=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),S=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),x=localStorage.getItem(this.getSceneStorageKey("background_cover")),_=localStorage.getItem(this.getSceneStorageKey("background_lock")),k=E?E==="true":!1;R(k),d&&(d.value=C||"50",d.disabled=!k),p&&(p.value=A||"0.25",p.disabled=!k,y()),o&&(o.checked=S==="true",a("anchor",o.checked));let O=!0;I(O),g&&(g.disabled=!0),b&&(b.disabled=!0);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),O?"true":"false")}catch{}v(k,M(),y()),P(O);let z=x?x==="true":!0,D=_?_==="true":!0;h&&(h.checked=z),f&&(f.checked=D),j(z),L(D),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let E=M(),C=y();d&&(d.disabled=!c.checked),p&&(p.disabled=!c.checked),m==null||m.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(C))}catch{}v(c.checked,E,C)}),d==null||d.addEventListener("input",()=>{let E=M(),C=y();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(C))}catch{}w(E)}),p==null||p.addEventListener("input",()=>{let E=y(),C=M();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(C))}catch{}T(E)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}b==null||b.classList.toggle("active",g.checked),P(g.checked)}),h==null||h.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_cover"),h.checked?"true":"false")}catch{}j(h.checked)}),f==null||f.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_lock"),f.checked?"true":"false")}catch{}L(f.checked)}),m==null||m.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),b==null||b.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var jn=class{constructor(){this.root=null;this.options=null}render(){return`
718
718
  <div class="nudge-panel hidden" data-panel="nudge-panel">
719
719
  <div class="nudge-panel-header" data-panel-handle>
720
720
  <span class="nudge-panel-title">Nudge Controls</span>
@@ -960,15 +960,15 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
960
960
  </select>
961
961
  </div>
962
962
  </div>
963
- `);for(let u in n){if(u==="id")continue;let g=n[u],h=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let m=[];for(let b in g){let y=g[b],v=`${h}.${b}`,w=o[b];if(b==="targetId"||b==="inputId"){let T=this.registry.getObjectIds(),I=typeof y=="string"?y:"",_=I&&!T.includes(I)?[I,...T]:T;m.push(`
963
+ `);for(let u in n){if(u==="id")continue;let g=n[u],h=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let m=[];for(let b in g){let y=g[b],v=`${h}.${b}`,w=o[b];if(b==="targetId"||b==="inputId"){let T=this.registry.getObjectIds(),P=typeof y=="string"?y:"",j=P&&!T.includes(P)?[P,...T]:T;m.push(`
964
964
  <div class="inspector-property inspector-property-text">
965
965
  <label class="inspector-property-label">${this.formatLabel(b)}</label>
966
966
  <div class="inspector-input-group">
967
967
  <select class="inspector-component-select inspector-input"
968
968
  data-property-path="${v}"
969
969
  data-object-id="${e}">
970
- <option value="" ${I?"":"selected"}>None</option>
971
- ${_.map(L=>`<option value="${L}" ${L===I?"selected":""}>${L}</option>`).join("")}
970
+ <option value="" ${P?"":"selected"}>None</option>
971
+ ${j.map(L=>`<option value="${L}" ${L===P?"selected":""}>${L}</option>`).join("")}
972
972
  </select>
973
973
  </div>
974
974
  </div>
@@ -1206,11 +1206,11 @@ ${f}
1206
1206
  ${m.join("")}
1207
1207
  </div>
1208
1208
  </div>
1209
- `);let T=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),I=[u("swing.enabled"),u("swing.amplitude"),u("swing.speed"),u("swing.axis")].filter(Boolean),_=[u("continuousMove.enabled"),u("continuousMove.axis"),u("continuousMove.speed"),u("continuousMove.direction"),u("continuousMove.lifetime")].filter(Boolean),L=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),M=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(T.length||I.length||_.length||L.length||M.length){let P=(C,A)=>A.length?`
1209
+ `);let T=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),P=[u("swing.enabled"),u("swing.amplitude"),u("swing.speed"),u("swing.axis")].filter(Boolean),j=[u("continuousMove.enabled"),u("continuousMove.axis"),u("continuousMove.speed"),u("continuousMove.direction"),u("continuousMove.lifetime")].filter(Boolean),L=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),M=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(T.length||P.length||j.length||L.length||M.length){let I=(C,A)=>A.length?`
1210
1210
  <div class="inspector-motion-continuous-group">
1211
1211
  <div class="inspector-subsection-title">${C}</div>
1212
1212
  <div class="inspector-subsection-content">${A.join("")}</div>
1213
- </div>`:"",E=[P("Pulse",T),P("Swing",I),P("Move forever",_),P("Rotate (pivoting itself)",L),P("Rotate around",M)].filter(Boolean).join("");i.push(`
1213
+ </div>`:"",E=[I("Pulse",T),I("Swing",P),I("Move forever",j),I("Rotate (pivoting itself)",L),I("Rotate around",M)].filter(Boolean).join("");i.push(`
1214
1214
  <div class="inspector-subsection inspector-subsection-continuous">
1215
1215
  <div class="inspector-subsection-title">Continuous</div>
1216
1216
  <div class="inspector-subsection-content inspector-motion-continuous-groups">
@@ -1230,7 +1230,7 @@ ${f}
1230
1230
  ${i.join("")}
1231
1231
  </div>
1232
1232
  </div>
1233
- `}attachEventListeners(){var w,T,I,_;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=il((L,M,O)=>{var P,E;this.updateManager.updateProperty(L,M,O),(E=(P=this.options)==null?void 0:P.onPropertyChange)==null||E.call(P,L,M,O)},300),n=L=>L?/(^|\.)logic(\.\d+)?\.id$/.test(L):!1;e.forEach(L=>{let M=E=>{var x,j;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId;if(A&&S){let k=C.value;if(C.type==="checkbox")k=C.checked;else if(C.type==="number"){if(k=parseFloat(C.value),isNaN(k))return}else if(C.dataset.json==="true")try{k=JSON.parse(C.value)}catch{return}C.type==="text"||C.type==="range"||C.tagName==="TEXTAREA"?t(S,A,k):(this.updateManager.updateProperty(S,A,k),(j=(x=this.options)==null?void 0:x.onPropertyChange)==null||j.call(x,S,A,k))}},O=L.dataset.propertyPath;O&&(O.includes("transform.anchor")||O.includes("render.anchor"))&&L.tagName==="SELECT"?L.addEventListener("change",async E=>{var j,k,R,z,D;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;if(!(!A||!S)&&x!=="custom")if(A.includes("transform.anchor")){let q=window.getEditableObjectConfig,F=typeof q=="function"?q(S):null,G=(j=F==null?void 0:F.transform)==null?void 0:j.anchor,B=G!=null&&G!==""?G:"top-left",U=x;await this.updateManager.updateProperty(S,A,x),(R=(k=this.options)==null?void 0:k.onPropertyChange)==null||R.call(k,S,A,x),B!==U&&window.dispatchEvent(new CustomEvent("scene-editor:anchor-changed",{detail:{objectId:S,previousAnchor:B,nextAnchor:U}}))}else await this.updateManager.updateProperty(S,A,x),(D=(z=this.options)==null?void 0:z.onPropertyChange)==null||D.call(z,S,A,x)}):n(O)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",O),L.addEventListener("change",async E=>{var D;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!A||!S)return;await this.updateManager.updateProperty(S,A,x),console.log("[Inspector v1.0.0] Logic ID updated");let j=window,k=(D=j==null?void 0:j.__HANDLER_LOGIC_META)==null?void 0:D[x],R=this.getDefaultPropsForLogic(x,k);console.log("[Inspector v1.0.0] New logic default props:",R);let z=A.replace(/\.id$/,".props");await this.updateManager.updateProperty(S,z,R),console.log("[Inspector v1.0.0] Logic props updated to:",R),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(S)})):(L.addEventListener("change",M),(L.tagName==="INPUT"||L.tagName==="TEXTAREA")&&L.addEventListener("input",M))}),this.contentContainer.querySelectorAll("[data-action]").forEach(L=>{L.addEventListener("click",M=>{let O=M.target,P=O.dataset.action,E=O.dataset.path,C=O.dataset.object;P&&E&&C&&this.quickActions.handleAction(P,C,E)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(L=>{L.addEventListener("click",M=>{var E,C;let O=M.target,P=O.dataset.sectionToggle||((E=O.closest("[data-section-toggle]"))==null?void 0:E.getAttribute("data-section-toggle"));if(P){let A=(C=this.contentContainer)==null?void 0:C.querySelector(`[data-section="${P}"]`);A==null||A.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(L=>{L.addEventListener("click",async M=>{let P=M.currentTarget.dataset.motionPreset;!P||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,P)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(L=>{L.addEventListener("click",async()=>{this.selectedObjectId&&await this.previewMotionIntro(this.selectedObjectId)})});let l=this.contentContainer.querySelector("[data-motion-simple-toggle]");l==null||l.addEventListener("click",()=>{this.motionSimpleMode=!this.motionSimpleMode;try{localStorage.setItem("inspector:motionSimple",String(this.motionSimpleMode))}catch{}this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),this.contentContainer.querySelectorAll("[data-spawnpoints-add]").forEach(L=>{L.addEventListener("click",async M=>{let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath;if(!P||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(P);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x=Array.isArray(S)?[...S]:[];x.push({x:0,y:0}),await this.updateManager.updateProperty(P,E,x),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(L=>{L.addEventListener("click",async M=>{let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath,C=Number(O.dataset.index||"-1");if(!P||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(P);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let j=x.filter((k,R)=>R!==C);await this.updateManager.updateProperty(P,E,j),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(L=>{L.addEventListener("click",async M=>{let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath;if(!P||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(P);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x=Array.isArray(S)?[...S]:[];x.push({templateId:"",weight:1}),await this.updateManager.updateProperty(P,E,x),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(L=>{L.addEventListener("click",async M=>{var k;let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath,C=Number((k=O.dataset.index)!=null?k:-1);if(!P||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(P);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(P,E,j),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(L=>{L.addEventListener("click",async M=>{var D;let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath;if(!P||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(P);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x;Array.isArray(S)?x=[...S]:S!=null?typeof S=="string"?x=[{id:S,props:{}}]:typeof S=="object"?x=[S]:x=[]:x=[];let j=this.getDefaultLogicId(),k=window,R=(D=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:D[j],z=this.getDefaultPropsForLogic(j,R);x.push({id:j,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:P,path:E,current:S,next:x}),await this.updateManager.updateProperty(P,E,x),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(L=>{L.addEventListener("click",async M=>{var k;let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath,C=Number((k=O.dataset.index)!=null?k:-1);if(!P||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(P);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(P,E,j),this.loadObject(P)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(L=>{L.addEventListener("click",async M=>{var q,F;let O=M.target,P=O.dataset.objectId,E=O.dataset.propertyPath,C=Number((q=O.dataset.index)!=null?q:-1);if(!P||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(P);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let j=x[C];if(typeof j!="string")return;let k=window,R=(F=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:F[j],z=this.getDefaultPropsForLogic(j,R),D=[...x];D[C]={id:j,props:z},await this.updateManager.updateProperty(P,E,D),this.loadObject(P)})});let m=(w=this.root)==null?void 0:w.querySelector("[data-inspector-advanced]");m==null||m.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(T=this.root)==null?void 0:T.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var M;let L=(M=this.root)==null?void 0:M.querySelector("[data-convert-menu]");L==null||L.classList.toggle("hidden")});let y=(I=this.contentContainer)==null?void 0:I.querySelector("[data-inspector-add-component-btn]"),v=(_=this.contentContainer)==null?void 0:_.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let L=v.value;L&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,L)})}getMotionDefaults(){var n,i,a,r;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(r=(a=t.motion)==null?void 0:a.defaults)!=null?r:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),r={...(l=i.motion)!=null?l:a},o={...(c=r.intro)!=null?c:{}};r.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",r.intro=o,await this.updateManager.updateProperty(e,"motion",r),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},r={...(l=a.intro)!=null?l:{}};a.enabled=!0,r.enabled=!0,a.intro=r,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,r=a==null?void 0:a.schemas,o=null;r instanceof Map?o=r.get(t):r&&typeof r=="object"&&(o=r[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(a=n.render)==null?void 0:a.asset)==null?void 0:r.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1233
+ `}attachEventListeners(){var w,T,P,j;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=il((L,M,R)=>{var I,E;this.updateManager.updateProperty(L,M,R),(E=(I=this.options)==null?void 0:I.onPropertyChange)==null||E.call(I,L,M,R)},300),n=L=>L?/(^|\.)logic(\.\d+)?\.id$/.test(L):!1;e.forEach(L=>{let M=E=>{var x,_;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId;if(A&&S){let k=C.value;if(C.type==="checkbox")k=C.checked;else if(C.type==="number"){if(k=parseFloat(C.value),isNaN(k))return}else if(C.dataset.json==="true")try{k=JSON.parse(C.value)}catch{return}C.type==="text"||C.type==="range"||C.tagName==="TEXTAREA"?t(S,A,k):(this.updateManager.updateProperty(S,A,k),(_=(x=this.options)==null?void 0:x.onPropertyChange)==null||_.call(x,S,A,k))}},R=L.dataset.propertyPath;R&&(R.includes("transform.anchor")||R.includes("render.anchor"))&&L.tagName==="SELECT"?L.addEventListener("change",async E=>{var _,k,O,z,D;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;if(!(!A||!S)&&x!=="custom")if(A.includes("transform.anchor")){let q=window.getEditableObjectConfig,F=typeof q=="function"?q(S):null,G=(_=F==null?void 0:F.transform)==null?void 0:_.anchor,B=G!=null&&G!==""?G:"top-left",U=x;await this.updateManager.updateProperty(S,A,x),(O=(k=this.options)==null?void 0:k.onPropertyChange)==null||O.call(k,S,A,x),B!==U&&window.dispatchEvent(new CustomEvent("scene-editor:anchor-changed",{detail:{objectId:S,previousAnchor:B,nextAnchor:U}}))}else await this.updateManager.updateProperty(S,A,x),(D=(z=this.options)==null?void 0:z.onPropertyChange)==null||D.call(z,S,A,x)}):n(R)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",R),L.addEventListener("change",async E=>{var D;let C=E.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!A||!S)return;await this.updateManager.updateProperty(S,A,x),console.log("[Inspector v1.0.0] Logic ID updated");let _=window,k=(D=_==null?void 0:_.__HANDLER_LOGIC_META)==null?void 0:D[x],O=this.getDefaultPropsForLogic(x,k);console.log("[Inspector v1.0.0] New logic default props:",O);let z=A.replace(/\.id$/,".props");await this.updateManager.updateProperty(S,z,O),console.log("[Inspector v1.0.0] Logic props updated to:",O),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(S)})):(L.addEventListener("change",M),(L.tagName==="INPUT"||L.tagName==="TEXTAREA")&&L.addEventListener("input",M))}),this.contentContainer.querySelectorAll("[data-action]").forEach(L=>{L.addEventListener("click",M=>{let R=M.target,I=R.dataset.action,E=R.dataset.path,C=R.dataset.object;I&&E&&C&&this.quickActions.handleAction(I,C,E)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(L=>{L.addEventListener("click",M=>{var E,C;let R=M.target,I=R.dataset.sectionToggle||((E=R.closest("[data-section-toggle]"))==null?void 0:E.getAttribute("data-section-toggle"));if(I){let A=(C=this.contentContainer)==null?void 0:C.querySelector(`[data-section="${I}"]`);A==null||A.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(L=>{L.addEventListener("click",async M=>{let I=M.currentTarget.dataset.motionPreset;!I||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,I)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(L=>{L.addEventListener("click",async()=>{this.selectedObjectId&&await this.previewMotionIntro(this.selectedObjectId)})});let l=this.contentContainer.querySelector("[data-motion-simple-toggle]");l==null||l.addEventListener("click",()=>{this.motionSimpleMode=!this.motionSimpleMode;try{localStorage.setItem("inspector:motionSimple",String(this.motionSimpleMode))}catch{}this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),this.contentContainer.querySelectorAll("[data-spawnpoints-add]").forEach(L=>{L.addEventListener("click",async M=>{let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath;if(!I||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(I);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x=Array.isArray(S)?[...S]:[];x.push({x:0,y:0}),await this.updateManager.updateProperty(I,E,x),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(L=>{L.addEventListener("click",async M=>{let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath,C=Number(R.dataset.index||"-1");if(!I||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(I);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let _=x.filter((k,O)=>O!==C);await this.updateManager.updateProperty(I,E,_),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(L=>{L.addEventListener("click",async M=>{let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath;if(!I||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(I);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x=Array.isArray(S)?[...S]:[];x.push({templateId:"",weight:1}),await this.updateManager.updateProperty(I,E,x),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(L=>{L.addEventListener("click",async M=>{var k;let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath,C=Number((k=R.dataset.index)!=null?k:-1);if(!I||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(I);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let _=x.filter((O,z)=>z!==C);await this.updateManager.updateProperty(I,E,_),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(L=>{L.addEventListener("click",async M=>{var D;let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath;if(!I||!E)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(I);if(!A)return;let S=this.updateManager.getNestedProperty(A,E),x;Array.isArray(S)?x=[...S]:S!=null?typeof S=="string"?x=[{id:S,props:{}}]:typeof S=="object"?x=[S]:x=[]:x=[];let _=this.getDefaultLogicId(),k=window,O=(D=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:D[_],z=this.getDefaultPropsForLogic(_,O);x.push({id:_,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:I,path:E,current:S,next:x}),await this.updateManager.updateProperty(I,E,x),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(L=>{L.addEventListener("click",async M=>{var k;let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath,C=Number((k=R.dataset.index)!=null?k:-1);if(!I||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(I);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let _=x.filter((O,z)=>z!==C);await this.updateManager.updateProperty(I,E,_),this.loadObject(I)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(L=>{L.addEventListener("click",async M=>{var q,F;let R=M.target,I=R.dataset.objectId,E=R.dataset.propertyPath,C=Number((q=R.dataset.index)!=null?q:-1);if(!I||!E||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(I);if(!S)return;let x=this.updateManager.getNestedProperty(S,E);if(!Array.isArray(x))return;let _=x[C];if(typeof _!="string")return;let k=window,O=(F=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:F[_],z=this.getDefaultPropsForLogic(_,O),D=[...x];D[C]={id:_,props:z},await this.updateManager.updateProperty(I,E,D),this.loadObject(I)})});let m=(w=this.root)==null?void 0:w.querySelector("[data-inspector-advanced]");m==null||m.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(T=this.root)==null?void 0:T.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var M;let L=(M=this.root)==null?void 0:M.querySelector("[data-convert-menu]");L==null||L.classList.toggle("hidden")});let y=(P=this.contentContainer)==null?void 0:P.querySelector("[data-inspector-add-component-btn]"),v=(j=this.contentContainer)==null?void 0:j.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let L=v.value;L&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,L)})}getMotionDefaults(){var n,i,a,r;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(r=(a=t.motion)==null?void 0:a.defaults)!=null?r:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),r={...(l=i.motion)!=null?l:a},o={...(c=r.intro)!=null?c:{}};r.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",r.intro=o,await this.updateManager.updateProperty(e,"motion",r),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},r={...(l=a.intro)!=null?l:{}};a.enabled=!0,r.enabled=!0,a.intro=r,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,r=a==null?void 0:a.schemas,o=null;r instanceof Map?o=r.get(t):r&&typeof r=="object"&&(o=r[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(a=n.render)==null?void 0:a.asset)==null?void 0:r.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1234
1234
  <div class="inspector-empty">
1235
1235
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
1236
1236
  <span class="inspector-empty-text">${e}</span>
@@ -1325,7 +1325,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
1325
1325
 
1326
1326
  OUTPUT:
1327
1327
  Generate the requested asset matching the brand style.${s.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
1328
- `.trim()}function er(s){return s.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function tr(s,e){return!(s.includes("background")&&(s.includes("_1")||s.includes("splash")||s.includes("endgame")||s.includes("main"))||e==="text"||e==="effects"&&s.includes("particle"))}async function nr(s){var r,o;let e=er(s.gameObjects),t={gamePrompt:s.gamePrompt,gameObjects:e,brandAssets:s.manifest.assets,brandDna:s.manifest.brand_dna,brandName:s.manifest.brand_name},n=Zs(t),i=[];if(s.flatDesignDataUrl)try{let l=ir(s.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await Kn(s.apiKey,n,i,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(r=l.message)!=null&&r.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return cl(a,s.gameObjects)}function cl(s,e){try{let t=s,n=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let a=s.match(/\{[\s\S]*\}/);a&&(t=a[0])}let i=JSON.parse(t);return i.mappings&&Array.isArray(i.mappings)?{mappingResult:i,rawResponse:s,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:s,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:s,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function la(s,e,t={}){var i;let n=e.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let r=n[a];(i=t.onProgress)==null||i.call(t,a+1,n.length,r.game_object);try{let o=await dl(s,r);r.output_dataUrl=o,r.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${r.game_object}:`,o),r.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function dl(s,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&s.manifest){let o=s.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=s.assetFiles.get(o.file);if(l){let c=await Fe(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(s.flatDesignDataUrl){let o=ir(s.flatDesignDataUrl);o&&t.push(o)}let n=tr(e.game_object),i={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:s.manifest.brand_dna,needsTransparency:n},a=Qs(i);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await ut(s.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await pt(r)||r}function ir(s){let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function ar(s,e){let t=s.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([i,a])=>({id:i,file:String(a),role:"visual element"})):n=[],s.assets=n;for(let i of n){let a=e.get(i.file);if(a){let r=await Fe(a);r&&(i.dataUrl=r.dataUrl)}}}function sr(s){var t,n;let e=new Map;if(!s)return console.warn("[CanvaZip] No position data provided"),e;if(typeof s=="string")try{s=JSON.parse(s)}catch(i){return console.error("[CanvaZip] Failed to parse position data JSON:",i),e}if(s!=null&&s.layers&&Array.isArray(s.layers)){console.log(`[CanvaZip] Parsing ${s.layers.length} layers from position data`);for(let i of s.layers){let a=i.asset;if(!a||!i.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",i);continue}let r=i.layout,o={x:typeof r.x=="number"?r.x:0,y:typeof r.y=="number"?r.y:0},l=typeof r.scaleX=="number"?r.scaleX:1,c=typeof r.scaleY=="number"?r.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof r.rotation=="number"?r.rotation:0;e.set(a,{position:o,scale:d,rotation:p}),console.log(`[CanvaZip] Parsed position for ${a}:`,{position:o,scale:d,rotation:p})}console.log(`[CanvaZip] Successfully parsed ${e.size} assets from position data`)}else console.warn("[CanvaZip] Position data does not have layers array:",s);if(e.size===0&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(a&&typeof a=="object"&&"layout"in a){let r=a.layout,o={x:0,y:0},l=1,c=0;if(r.position&&typeof r.position=="object"?o={x:r.position.x||0,y:r.position.y||0}:(typeof r.x=="number"||typeof r.y=="number")&&(o={x:r.x||0,y:r.y||0}),typeof r.scale=="number")l=r.scale;else if(typeof r.scaleX=="number"||typeof r.scaleY=="number"){let d=(t=r.scaleX)!=null?t:1,p=(n=r.scaleY)!=null?n:1;l=(d+p)/2}typeof r.rotation=="number"&&(c=r.rotation),e.set(i,{position:o,scale:l,rotation:c})}}return e}function rr(s,e){if(!s)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",s),null;if(e.has(s))return console.log(`[CanvaZip] Exact match found for ${s}`),e.get(s);let t=s.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${s} -> ${t}`),e.get(t);let n=t.toLowerCase();for(let[i,a]of e.entries()){let r=i.toLowerCase();if(r===n||r.includes(n)||n.includes(r))return console.log(`[CanvaZip] Partial match found for ${s} -> ${i}`),a}return console.warn(`[CanvaZip] No match found for ${s}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function pl(s){return s.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function or(){let s=window.getEditableAssets;if(typeof s!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=s();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let n of e.slots)n.assetType==="image"&&n.objectId&&t.push({id:n.objectId,name:n.displayName||pl(n.slotId||n.objectId),type:"sprite"});return t.sort((n,i)=>n.name.localeCompare(i.name))}var gt=require("pixi.js");lt();sn();ee();async function cr(s,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await gt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,d=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of d)ve[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let p=window.gameObjectManager;if(p)for(let u of d){let g=p.get(u);if(g){let h=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function dr(s,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,r=typeof a=="function"?a():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(m=>m.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),d=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",d);let p=await gt.Assets.load(d);if(!p){console.error("[LIBRARY] Failed to load default texture:",d);return}let u=window.CustomAssets,g=e.replace(/s$/,""),h=Object.keys(u||{}).filter(m=>m.startsWith(g)||m.includes(g));for(let m of h)ve[m]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=u[m])!=null&&n.texture&&(u[m].texture=p,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let f=window.gameObjectManager;if(f)for(let m of h){let b=f.get(m);if(b){let y=((i=b.getDisplayObject)==null?void 0:i.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=p,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function Xn(s,e,t,n){var i,a,r,o,l,c,d,p,u,g,h,f,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let w=ur(v),T=Date.now(),I=`/raw/library/${n}/${t}?t=${T}`;console.log("[LIBRARY] Loading texture from:",I);let _=await gt.Assets.load(I);if(!_){console.error("[LIBRARY] Failed to load texture:",I);return}console.log("[LIBRARY] \u2705 Texture loaded"),ve[v]=_,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let L=window.CustomAssets;L!=null&&L[v]&&(L[v].texture=_,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let M=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!M),M){let P=Array.from(((i=M.keys)==null?void 0:i.call(M))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",P);let E=M.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!E),E){let C=((a=E.getDisplayObject)==null?void 0:a.call(E))||E.pixiObject||E.pixi||E,A=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",A),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=_,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(A==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:S}=await import("pixi.js"),x=C.parent,j=(l=(o=x==null?void 0:x.getChildIndex)==null?void 0:o.call(x,C))!=null?l:0,k={x:C.x,y:C.y},R={x:(d=(c=C.anchor)==null?void 0:c.x)!=null?d:.5,y:(u=(p=C.anchor)==null?void 0:p.y)!=null?u:.5},z={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(m=(f=C.scale)==null?void 0:f.y)!=null?m:1},D=(b=C.alpha)!=null?b:1,q=(y=C.visible)!=null?y:!0,F=new S(_);F.anchor.set(R.x,R.y),F.position.set(k.x,k.y),F.scale.set(z.x,z.y),F.alpha=D,F.visible=q,x&&(x.removeChild(C),x.addChildAt(F,j),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),E.pixiObject&&(E.pixiObject=F),E.pixi&&(E.pixi=F),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let S=C.children.find(x=>x.texture);S?(S.texture=_,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let O=`raw/library/${n}/${t}`;gr(v,O,_,w),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:v,texture:_,assetPath:O}})),re({objectId:v,path:"render.asset.path",value:O}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",O)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function pr(s,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,r=ur(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await gt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}ve[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let d=window.CustomAssets;d!=null&&d[a]&&(d[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let u=p.get(a);if(u){let g=((i=u.getDisplayObject)==null?void 0:i.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}gr(a,t,c,r),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),re({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function ur(s){var e,t,n;try{let i=window.getEditableObjectConfig,a=typeof i=="function"?i(s):null;return(n=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?n:null}catch{return null}}function gr(s,e,t,n){if(e){try{let i=`${s}:${e}`;ce.set(i,t)}catch{}if(n&&n!==e)try{let i=ce.store;i!=null&&i.delete&&i.delete(`${s}:${n}`)}catch{}lr(e,t),n&&n!==e&&lr(n,null)}}function lr(s,e){if(!s)return;let t=gt.Assets.cache;if(!t)return;let n=s.replace(/^\.?\//,""),i=[n,`/${n}`];for(let a of i)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var Jn=class{constructor(){this.root=null;this.assets=[];this.positionMap=new Map;this.replaceableObjects=[];this.options=null;this.processedCount=0}render(){let e=this.assets.length,t=this.processedCount;return`
1328
+ `.trim()}function er(s){return s.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function tr(s,e){return!(s.includes("background")&&(s.includes("_1")||s.includes("splash")||s.includes("endgame")||s.includes("main"))||e==="text"||e==="effects"&&s.includes("particle"))}async function nr(s){var r,o;let e=er(s.gameObjects),t={gamePrompt:s.gamePrompt,gameObjects:e,brandAssets:s.manifest.assets,brandDna:s.manifest.brand_dna,brandName:s.manifest.brand_name},n=Zs(t),i=[];if(s.flatDesignDataUrl)try{let l=ir(s.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await Kn(s.apiKey,n,i,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(r=l.message)!=null&&r.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return cl(a,s.gameObjects)}function cl(s,e){try{let t=s,n=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let a=s.match(/\{[\s\S]*\}/);a&&(t=a[0])}let i=JSON.parse(t);return i.mappings&&Array.isArray(i.mappings)?{mappingResult:i,rawResponse:s,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:s,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:s,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function la(s,e,t={}){var i;let n=e.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let r=n[a];(i=t.onProgress)==null||i.call(t,a+1,n.length,r.game_object);try{let o=await dl(s,r);r.output_dataUrl=o,r.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${r.game_object}:`,o),r.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function dl(s,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&s.manifest){let o=s.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=s.assetFiles.get(o.file);if(l){let c=await Fe(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(s.flatDesignDataUrl){let o=ir(s.flatDesignDataUrl);o&&t.push(o)}let n=tr(e.game_object),i={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:s.manifest.brand_dna,needsTransparency:n},a=Qs(i);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await ut(s.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await pt(r)||r}function ir(s){let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function ar(s,e){let t=s.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([i,a])=>({id:i,file:String(a),role:"visual element"})):n=[],s.assets=n;for(let i of n){let a=e.get(i.file);if(a){let r=await Fe(a);r&&(i.dataUrl=r.dataUrl)}}}function sr(s){var t,n;let e=new Map;if(!s)return console.warn("[CanvaZip] No position data provided"),e;if(typeof s=="string")try{s=JSON.parse(s)}catch(i){return console.error("[CanvaZip] Failed to parse position data JSON:",i),e}if(s!=null&&s.layers&&Array.isArray(s.layers)){console.log(`[CanvaZip] Parsing ${s.layers.length} layers from position data`);for(let i of s.layers){let a=i.asset;if(!a||!i.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",i);continue}let r=i.layout,o={x:typeof r.x=="number"?r.x:0,y:typeof r.y=="number"?r.y:0},l=typeof r.scaleX=="number"?r.scaleX:1,c=typeof r.scaleY=="number"?r.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof r.rotation=="number"?r.rotation:0;e.set(a,{position:o,scale:d,rotation:p}),console.log(`[CanvaZip] Parsed position for ${a}:`,{position:o,scale:d,rotation:p})}console.log(`[CanvaZip] Successfully parsed ${e.size} assets from position data`)}else console.warn("[CanvaZip] Position data does not have layers array:",s);if(e.size===0&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(a&&typeof a=="object"&&"layout"in a){let r=a.layout,o={x:0,y:0},l=1,c=0;if(r.position&&typeof r.position=="object"?o={x:r.position.x||0,y:r.position.y||0}:(typeof r.x=="number"||typeof r.y=="number")&&(o={x:r.x||0,y:r.y||0}),typeof r.scale=="number")l=r.scale;else if(typeof r.scaleX=="number"||typeof r.scaleY=="number"){let d=(t=r.scaleX)!=null?t:1,p=(n=r.scaleY)!=null?n:1;l=(d+p)/2}typeof r.rotation=="number"&&(c=r.rotation),e.set(i,{position:o,scale:l,rotation:c})}}return e}function rr(s,e){if(!s)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",s),null;if(e.has(s))return console.log(`[CanvaZip] Exact match found for ${s}`),e.get(s);let t=s.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${s} -> ${t}`),e.get(t);let n=t.toLowerCase();for(let[i,a]of e.entries()){let r=i.toLowerCase();if(r===n||r.includes(n)||n.includes(r))return console.log(`[CanvaZip] Partial match found for ${s} -> ${i}`),a}return console.warn(`[CanvaZip] No match found for ${s}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function pl(s){return s.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function or(){let s=window.getEditableAssets;if(typeof s!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=s();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let n of e.slots)n.assetType==="image"&&n.objectId&&t.push({id:n.objectId,name:n.displayName||pl(n.slotId||n.objectId),type:"sprite"});return t.sort((n,i)=>n.name.localeCompare(i.name))}var gt=require("pixi.js");lt();sn();ee();async function cr(s,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await gt.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,d=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of d)ve[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let p=window.gameObjectManager;if(p)for(let u of d){let g=p.get(u);if(g){let h=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function dr(s,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,r=typeof a=="function"?a():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(m=>m.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),d=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",d);let p=await gt.Assets.load(d);if(!p){console.error("[LIBRARY] Failed to load default texture:",d);return}let u=window.CustomAssets,g=e.replace(/s$/,""),h=Object.keys(u||{}).filter(m=>m.startsWith(g)||m.includes(g));for(let m of h)ve[m]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=u[m])!=null&&n.texture&&(u[m].texture=p,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let f=window.gameObjectManager;if(f)for(let m of h){let b=f.get(m);if(b){let y=((i=b.getDisplayObject)==null?void 0:i.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=p,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function Xn(s,e,t,n){var i,a,r,o,l,c,d,p,u,g,h,f,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let w=ur(v),T=Date.now(),P=`/raw/library/${n}/${t}?t=${T}`;console.log("[LIBRARY] Loading texture from:",P);let j=await gt.Assets.load(P);if(!j){console.error("[LIBRARY] Failed to load texture:",P);return}console.log("[LIBRARY] \u2705 Texture loaded"),ve[v]=j,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let L=window.CustomAssets;L!=null&&L[v]&&(L[v].texture=j,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let M=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!M),M){let I=Array.from(((i=M.keys)==null?void 0:i.call(M))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",I);let E=M.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!E),E){let C=((a=E.getDisplayObject)==null?void 0:a.call(E))||E.pixiObject||E.pixi||E,A=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",A),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=j,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(A==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:S}=await import("pixi.js"),x=C.parent,_=(l=(o=x==null?void 0:x.getChildIndex)==null?void 0:o.call(x,C))!=null?l:0,k={x:C.x,y:C.y},O={x:(d=(c=C.anchor)==null?void 0:c.x)!=null?d:.5,y:(u=(p=C.anchor)==null?void 0:p.y)!=null?u:.5},z={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(m=(f=C.scale)==null?void 0:f.y)!=null?m:1},D=(b=C.alpha)!=null?b:1,q=(y=C.visible)!=null?y:!0,F=new S(j);F.anchor.set(O.x,O.y),F.position.set(k.x,k.y),F.scale.set(z.x,z.y),F.alpha=D,F.visible=q,x&&(x.removeChild(C),x.addChildAt(F,_),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),E.pixiObject&&(E.pixiObject=F),E.pixi&&(E.pixi=F),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let S=C.children.find(x=>x.texture);S?(S.texture=j,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let R=`raw/library/${n}/${t}`;gr(v,R,j,w),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:v,texture:j,assetPath:R}})),re({objectId:v,path:"render.asset.path",value:R}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",R)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function pr(s,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,r=ur(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await gt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}ve[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let d=window.CustomAssets;d!=null&&d[a]&&(d[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let u=p.get(a);if(u){let g=((i=u.getDisplayObject)==null?void 0:i.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}gr(a,t,c,r),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),re({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function ur(s){var e,t,n;try{let i=window.getEditableObjectConfig,a=typeof i=="function"?i(s):null;return(n=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?n:null}catch{return null}}function gr(s,e,t,n){if(e){try{let i=`${s}:${e}`;ce.set(i,t)}catch{}if(n&&n!==e)try{let i=ce.store;i!=null&&i.delete&&i.delete(`${s}:${n}`)}catch{}lr(e,t),n&&n!==e&&lr(n,null)}}function lr(s,e){if(!s)return;let t=gt.Assets.cache;if(!t)return;let n=s.replace(/^\.?\//,""),i=[n,`/${n}`];for(let a of i)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var Jn=class{constructor(){this.root=null;this.assets=[];this.positionMap=new Map;this.replaceableObjects=[];this.options=null;this.processedCount=0}render(){let e=this.assets.length,t=this.processedCount;return`
1329
1329
  <div class="canva-wizard-overlay" data-canva-wizard>
1330
1330
  <div class="canva-wizard-modal">
1331
1331
  <div class="canva-wizard-header">
@@ -1757,7 +1757,7 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1757
1757
  </div>
1758
1758
  </div>
1759
1759
  </div>
1760
- `;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",b=>{b.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=i.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var y,v,w;let b=(w=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?w:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(h=this.aiSaveLibraryBtn)==null||h.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,p,u,g,h,f,m,b,y,v,w,T,I,_,L,M,O,P,E,C;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(p=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:p.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",i=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=i,r=i,o=Number((T=(w=this.aiStrengthInput)==null?void 0:w.value)!=null?T:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((I=l==null?void 0:l.value)==null?void 0:I.trim())||((_=this.aiBaseValue)==null?void 0:_.trim())||"";this.setAiLoading(!0),this.setAiStatus(c?"Generating...":"Generating from scratch...");try{let A=null,S=null,x=(L=this.getSelectedAssetKey())!=null?L:"unknown",j=(M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((O=this.aiUseOutputToggle)!=null&&O.checked&&this.aiOutputDataUrl){let G=sa(this.aiOutputDataUrl,"ai-output.png");if(G){let B=await Fe(G);B&&(A={input:{base64:B.base64,mimeType:B.mimeType},dataUrl:B.dataUrl,width:B.width,height:B.height})}}!A&&c&&(A=await this.getImageDataFromAsset(c));let k=[];A&&k.push(A.input);let R=!1;if(this.aiReferenceFile){let G=await Fe(this.aiReferenceFile);G?(S={input:{base64:G.base64,mimeType:G.mimeType},dataUrl:G.dataUrl,width:G.width,height:G.height},k.push(S.input),R=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=hr(n,{includeReference:R,includeMagenta:a,changeLevel:o}),D=(E=(P=this.aiReferenceFile)==null?void 0:P.name)!=null?E:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:x,base:j,reference:D});let q=A?ra(A.width,A.height):S?ra(S.width,S.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let F=await ut(e,z,k,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",F==null?void 0:F.length),this.aiRawOutputDataUrl=F,await this.refreshAiOutputFromRaw()}catch(A){console.error("[CustomizePanel] AI Generate Error:",A),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((C=this.aiStatusEl)==null?void 0:C.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,r,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await pt(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&r)console.log("[CustomizePanel] Applying AI output directly to object:",a,r),this.applyObjectPropertyValue(a,r,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,r,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),d(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(b){console.warn("[CustomizePanel] Setup-library endpoint not available:",b)}let p=window.refreshAssetLibrary;typeof p=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await p());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),h=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),f=this.getSelectedAssetInput();if(f&&(f.value=c.path,this.handleAssetValueChange((o=f.dataset.assetKey)!=null?o:"",f)),g&&h){console.log("[CustomizePanel] Applying saved asset to object:",g,h);let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(c.path);await b(g,v,i)}else this.applyObjectPropertyValue(g,h,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let m=window.__highlightLibrarySlot;typeof m=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{m(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var r;let t=(r=this.aiContext)==null?void 0:r.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=sa(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let r=await aa(a);r&&this.setAiOutput(r)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let d=await this.getImageDimensions(i);if(d){let p=await this.showManualCropModal(e,d,i);if(!p)return;a=p}}let r=await aa(a);if(!r){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",p.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=p.path,this.handleAssetValueChange(n,t);let h=this.inferObjectIdFromAssetKey(n),f=this.inferPathFromAssetKey(n);if(h&&f){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(png|jpg|jpeg)$/i.test(String(p.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(p.path);await b(h,v,c)}else this.applyObjectPropertyValue(h,f,p.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let m=window.__highlightLibrarySlot;typeof m=="function"&&h&&setTimeout(()=>{m(h,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",p.error),alert(`Failed to save uploaded file: ${p.error}`)}catch(d){console.error("[CustomizePanel] \u274C Upload error:",d),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,r)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1760
+ `;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",b=>{b.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=i.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var y,v,w;let b=(w=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?w:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(h=this.aiSaveLibraryBtn)==null||h.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,p,u,g,h,f,m,b,y,v,w,T,P,j,L,M,R,I,E,C;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(p=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:p.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",i=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=i,r=i,o=Number((T=(w=this.aiStrengthInput)==null?void 0:w.value)!=null?T:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((P=l==null?void 0:l.value)==null?void 0:P.trim())||((j=this.aiBaseValue)==null?void 0:j.trim())||"";this.setAiLoading(!0),this.setAiStatus(c?"Generating...":"Generating from scratch...");try{let A=null,S=null,x=(L=this.getSelectedAssetKey())!=null?L:"unknown",_=(M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((R=this.aiUseOutputToggle)!=null&&R.checked&&this.aiOutputDataUrl){let G=sa(this.aiOutputDataUrl,"ai-output.png");if(G){let B=await Fe(G);B&&(A={input:{base64:B.base64,mimeType:B.mimeType},dataUrl:B.dataUrl,width:B.width,height:B.height})}}!A&&c&&(A=await this.getImageDataFromAsset(c));let k=[];A&&k.push(A.input);let O=!1;if(this.aiReferenceFile){let G=await Fe(this.aiReferenceFile);G?(S={input:{base64:G.base64,mimeType:G.mimeType},dataUrl:G.dataUrl,width:G.width,height:G.height},k.push(S.input),O=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=hr(n,{includeReference:O,includeMagenta:a,changeLevel:o}),D=(E=(I=this.aiReferenceFile)==null?void 0:I.name)!=null?E:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:x,base:_,reference:D});let q=A?ra(A.width,A.height):S?ra(S.width,S.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let F=await ut(e,z,k,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",F==null?void 0:F.length),this.aiRawOutputDataUrl=F,await this.refreshAiOutputFromRaw()}catch(A){console.error("[CustomizePanel] AI Generate Error:",A),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((C=this.aiStatusEl)==null?void 0:C.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,r,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await pt(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&r)console.log("[CustomizePanel] Applying AI output directly to object:",a,r),this.applyObjectPropertyValue(a,r,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,r,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),d(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(b){console.warn("[CustomizePanel] Setup-library endpoint not available:",b)}let p=window.refreshAssetLibrary;typeof p=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await p());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),h=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),f=this.getSelectedAssetInput();if(f&&(f.value=c.path,this.handleAssetValueChange((o=f.dataset.assetKey)!=null?o:"",f)),g&&h){console.log("[CustomizePanel] Applying saved asset to object:",g,h);let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(c.path);await b(g,v,i)}else this.applyObjectPropertyValue(g,h,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let m=window.__highlightLibrarySlot;typeof m=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{m(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var r;let t=(r=this.aiContext)==null?void 0:r.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=sa(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let r=await aa(a);r&&this.setAiOutput(r)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let d=await this.getImageDimensions(i);if(d){let p=await this.showManualCropModal(e,d,i);if(!p)return;a=p}}let r=await aa(a);if(!r){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",p.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=p.path,this.handleAssetValueChange(n,t);let h=this.inferObjectIdFromAssetKey(n),f=this.inferPathFromAssetKey(n);if(h&&f){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(png|jpg|jpeg)$/i.test(String(p.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(p.path);await b(h,v,c)}else this.applyObjectPropertyValue(h,f,p.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let m=window.__highlightLibrarySlot;typeof m=="function"&&h&&setTimeout(()=>{m(h,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",p.error),alert(`Failed to save uploaded file: ${p.error}`)}catch(d){console.error("[CustomizePanel] \u274C Upload error:",d),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,r)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1761
1761
  <div class="asset-preview-card">
1762
1762
  <div class="asset-preview-header">
1763
1763
  <div class="asset-preview-title">${e}</div>
@@ -1803,7 +1803,7 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1803
1803
  <button class="asset-crop-apply" type="button">Apply Crop</button>
1804
1804
  </div>
1805
1805
  </div>
1806
- `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),w=c.querySelector(".asset-crop-zoom"),T=c.querySelector(".asset-crop-zoom-value"),I=c.querySelector(".asset-crop-close"),_=c.querySelector(".asset-crop-cancel"),L=c.querySelector(".asset-crop-apply"),M=c.querySelector(".asset-crop-reset");if(!y||!v||!w||!T){l(null);return}let O=y.getContext("2d"),P=v.getContext("2d");if(!O||!P){l(null);return}let E=r.naturalWidth,C=r.naturalHeight,A=Math.max(y.width/E,y.height/C),S=1,x=0,j=0,k=!1,R=0,z=0,D=0,q=0,F=()=>{let H=A*S,ae=Math.max(0,(E*H-y.width)/2),te=Math.max(0,(C*H-y.height)/2);x=Math.min(ae,Math.max(-ae,x)),j=Math.min(te,Math.max(-te,j))},G=()=>{let H=A*S;O.clearRect(0,0,y.width,y.height);let ae=y.width/2-E*H/2+x,te=y.height/2-C*H/2+j;if(O.drawImage(r,ae,te,E*H,C*H),P.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let it=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),xi=v.width/2-o.naturalWidth*it/2,At=v.height/2-o.naturalHeight*it/2;P.drawImage(o,xi,At,o.naturalWidth*it,o.naturalHeight*it)}else P.fillStyle="rgba(255, 255, 255, 0.04)",P.fillRect(0,0,v.width,v.height),P.strokeStyle="rgba(255, 255, 255, 0.08)",P.strokeRect(4,4,v.width-8,v.height-8);let ne=v.width/y.width*(A*S),je=x*(v.width/y.width),ge=j*(v.height/y.height),vi=v.width/2-E*ne/2+je,wi=v.height/2-C*ne/2+ge;P.save(),P.globalAlpha=.7,P.drawImage(r,vi,wi,E*ne,C*ne),P.restore()},B=()=>{x=0,j=0,F(),G()};w.addEventListener("input",()=>{S=Number(w.value),T.textContent=`${S.toFixed(2)}\xD7`,F(),G()}),y.addEventListener("pointerdown",H=>{k=!0,R=H.clientX,z=H.clientY,D=x,q=j,y.setPointerCapture(H.pointerId)}),y.addEventListener("pointermove",H=>{k&&(x=D+(H.clientX-R),j=q+(H.clientY-z),F(),G())}),y.addEventListener("pointerup",H=>{k=!1,y.releasePointerCapture(H.pointerId)}),y.addEventListener("pointerleave",()=>{k=!1});let U=()=>{c.remove()},J=()=>{U(),l(null)},Z=async()=>{let H=document.createElement("canvas");H.width=t.width,H.height=t.height;let ae=H.getContext("2d");if(!ae){U(),l(null);return}let te=S,je=Math.max(H.width/E,H.height/C)*te,ge=H.width/y.width,vi=x*ge,wi=j*ge,it=H.width/2-E*je/2+vi,xi=H.height/2-C*je/2+wi;ae.drawImage(r,it,xi,E*je,C*je);let At=await new Promise(Qr=>{H.toBlob(eo=>Qr(eo),e.type||"image/png")});if(U(),!At){l(null);return}l(new File([At],e.name,{type:At.type}))};I==null||I.addEventListener("click",J),_==null||_.addEventListener("click",J),M==null||M.addEventListener("click",B),L==null||L.addEventListener("click",()=>{Z()}),c.addEventListener("click",H=>{H.target===c&&J()}),document.body.appendChild(c),B()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let i=await this.loadImage(n);if(i)return i}return null}};var ei=class{constructor(){this.root=null;this.options=null}render(){return`
1806
+ `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),w=c.querySelector(".asset-crop-zoom"),T=c.querySelector(".asset-crop-zoom-value"),P=c.querySelector(".asset-crop-close"),j=c.querySelector(".asset-crop-cancel"),L=c.querySelector(".asset-crop-apply"),M=c.querySelector(".asset-crop-reset");if(!y||!v||!w||!T){l(null);return}let R=y.getContext("2d"),I=v.getContext("2d");if(!R||!I){l(null);return}let E=r.naturalWidth,C=r.naturalHeight,A=Math.max(y.width/E,y.height/C),S=1,x=0,_=0,k=!1,O=0,z=0,D=0,q=0,F=()=>{let H=A*S,ae=Math.max(0,(E*H-y.width)/2),te=Math.max(0,(C*H-y.height)/2);x=Math.min(ae,Math.max(-ae,x)),_=Math.min(te,Math.max(-te,_))},G=()=>{let H=A*S;R.clearRect(0,0,y.width,y.height);let ae=y.width/2-E*H/2+x,te=y.height/2-C*H/2+_;if(R.drawImage(r,ae,te,E*H,C*H),I.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let it=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),xi=v.width/2-o.naturalWidth*it/2,At=v.height/2-o.naturalHeight*it/2;I.drawImage(o,xi,At,o.naturalWidth*it,o.naturalHeight*it)}else I.fillStyle="rgba(255, 255, 255, 0.04)",I.fillRect(0,0,v.width,v.height),I.strokeStyle="rgba(255, 255, 255, 0.08)",I.strokeRect(4,4,v.width-8,v.height-8);let ne=v.width/y.width*(A*S),je=x*(v.width/y.width),ge=_*(v.height/y.height),vi=v.width/2-E*ne/2+je,wi=v.height/2-C*ne/2+ge;I.save(),I.globalAlpha=.7,I.drawImage(r,vi,wi,E*ne,C*ne),I.restore()},B=()=>{x=0,_=0,F(),G()};w.addEventListener("input",()=>{S=Number(w.value),T.textContent=`${S.toFixed(2)}\xD7`,F(),G()}),y.addEventListener("pointerdown",H=>{k=!0,O=H.clientX,z=H.clientY,D=x,q=_,y.setPointerCapture(H.pointerId)}),y.addEventListener("pointermove",H=>{k&&(x=D+(H.clientX-O),_=q+(H.clientY-z),F(),G())}),y.addEventListener("pointerup",H=>{k=!1,y.releasePointerCapture(H.pointerId)}),y.addEventListener("pointerleave",()=>{k=!1});let U=()=>{c.remove()},J=()=>{U(),l(null)},Z=async()=>{let H=document.createElement("canvas");H.width=t.width,H.height=t.height;let ae=H.getContext("2d");if(!ae){U(),l(null);return}let te=S,je=Math.max(H.width/E,H.height/C)*te,ge=H.width/y.width,vi=x*ge,wi=_*ge,it=H.width/2-E*je/2+vi,xi=H.height/2-C*je/2+wi;ae.drawImage(r,it,xi,E*je,C*je);let At=await new Promise(Qr=>{H.toBlob(eo=>Qr(eo),e.type||"image/png")});if(U(),!At){l(null);return}l(new File([At],e.name,{type:At.type}))};P==null||P.addEventListener("click",J),j==null||j.addEventListener("click",J),M==null||M.addEventListener("click",B),L==null||L.addEventListener("click",()=>{Z()}),c.addEventListener("click",H=>{H.target===c&&J()}),document.body.appendChild(c),B()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let i=await this.loadImage(n);if(i)return i}return null}};var ei=class{constructor(){this.root=null;this.options=null}render(){return`
1807
1807
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
1808
1808
  <div class="scene-panel-header" data-panel-handle>
1809
1809
  <div class="panel-title">
@@ -1869,10 +1869,10 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1869
1869
  </div>
1870
1870
  </div>
1871
1871
  </div>
1872
- `}initialize(e,t){var y,v,w,T,I,_,L,M,O,P,E,C,A,S,x,j;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var R;let k=window.getEditableEngineConfig;if(typeof k=="function"){let z=k();return(R=z==null?void 0:z.loading)!=null?R:{}}return{}})(),a=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{type:a.value}),this.updateFieldVisibility(a.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=i.background_color||"#160a17",r.addEventListener("input",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{background_color:r.value})}));let o=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha"),l=(T=this.root)==null?void 0:T.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((I=i.overlay_alpha)!=null?I:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var R,z;let k=Number(o.value);l&&(l.textContent=k.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{overlay_alpha:k})}));let c=(_=this.root)==null?void 0:_.querySelector("#loading-text");c&&(c.value=i.text||"",c.addEventListener("input",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{text:c.value})}));let d=(L=this.root)==null?void 0:L.querySelector("#loading-text-scale"),p=(M=this.root)==null?void 0:M.querySelector("#loading-text-scale-value");d&&(d.value=String((O=i.text_scale)!=null?O:.6),p&&(p.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var R,z;let k=Number(d.value);p&&(p.textContent=k.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{text_scale:k})}));let u=(P=this.root)==null?void 0:P.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{enabled:u.checked})}));let g=(E=this.root)==null?void 0:E.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{blur_enabled:g.checked})}));let h=(C=this.root)==null?void 0:C.querySelector("#loading-blur-strength"),f=(A=this.root)==null?void 0:A.querySelector("#loading-blur-strength-value");h&&(h.value=String((S=i.blur_strength)!=null?S:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var k,R;f&&(f.textContent=h.value),(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{blur_strength:Number(h.value)})}));let m=(x=this.root)==null?void 0:x.querySelector("#loading-show-btn"),b=(j=this.root)==null?void 0:j.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onShowLoadingScreen)==null||R.call(k)}),b==null||b.addEventListener("click",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onHideLoadingScreen)==null||R.call(k)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var Bt=require("pixi.js");var ca=require("pixi.js"),Be=()=>window.debugConfig||{},mr=()=>window.resolveAnchorVec2||(s=>({x:.5,y:.5})),br=()=>window.resolveScreenAnchorPoint||(()=>new ca.Point),yr=()=>window.resolveScreenRatioPoint||(()=>new ca.Point);function vr(s){ti(s)&&(s.objectDebugRaf||(s.objectDebugRaf=window.requestAnimationFrame(()=>ni(s))))}function wr(s){s.objectDebugRaf&&(window.cancelAnimationFrame(s.objectDebugRaf),s.objectDebugRaf=null),Ft(s)}function ti(s){return s.isDebugOpen}function ni(s){var a,r,o;if(!ti(s)){s.objectDebugRaf=null;return}s.objectDebugRaf=window.requestAnimationFrame(()=>ni(s));let e=da(s);if(!e){Ht(s,null),Ft(s);return}let t=pa(s,e);if(!t){Ht(s,null),Ft(s);return}let n=new Bt.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=ua(s,t);Ht(s,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=i==null?void 0:i.x)!=null?r:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),s.highlightObject?ma(s,t):ya(s),s.highlightAnchor&&i?ba(s,i):va(s)}function da(s){var i;let e=s.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function pa(s,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Gt(s){let e=s.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function ua(s,e){var r,o;let t=Gt(s);if(!t)return null;let n=(r=t.transform)!=null?r:{},i=ga(s);if(!i)return null;if(n.position_ratio!=null)return yr()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&n.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),br()(i.width,i.height,a)}function ga(s){var a;let e=(a=s.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function ha(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectBoundsGfx&&s.objectBoundsGfx.parent!==e.stage&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectBoundsGfx||(s.objectBoundsGfx=new Bt.Graphics,s.objectBoundsGfx.zIndex=999999,e.stage.addChild(s.objectBoundsGfx)),s.objectBoundsGfx):null}function fa(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectAnchorGfx&&s.objectAnchorGfx.parent!==e.stage&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null),s.objectAnchorGfx||(s.objectAnchorGfx=new Bt.Graphics,s.objectAnchorGfx.zIndex=1e6,e.stage.addChild(s.objectAnchorGfx)),s.objectAnchorGfx):null}function ma(s,e){var i;let t=ha(s);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function ba(s,e){let t=fa(s);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function ya(s){s.objectBoundsGfx&&s.objectBoundsGfx.clear()}function va(s){s.objectAnchorGfx&&s.objectAnchorGfx.clear()}function Ft(s){s.objectBoundsGfx&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectAnchorGfx&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null)}function Ht(s,e){s.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function xr(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Sr(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n)a[o]=(r=a[o])!=null?r:{},a=a[o];a[i]=t}function wa(s){var n,i,a,r,o;if(!s)return!1;if((n=s.transform)!=null&&n.offset)return!0;let e=((a=(i=s.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(r=s.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function ai(s){let e=Be();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function Er(s){window.location.reload()}function si(s){let e=JSON.stringify(Be(),null,2);navigator.clipboard.writeText(e).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(e),alert("Config logged to console (clipboard not available)")})}async function Cr(s,e){var t,n,i;if(!(!s.configViewer||!s.container))try{let a=window.getEditableObjectConfig,r=typeof a=="function"?a(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(An(),Us)),p=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!p)return;let u=await l(p.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),ii(s,u),(n=s.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),ii(s,r),(i=s.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function ii(s,e){var u,g,h,f,m,b,y,v,w,T;if(!s.container)return;let t=s.container.querySelector("#config-pos-x"),n=s.container.querySelector("#config-pos-y"),i=s.container.querySelector("#config-scale"),a=s.container.querySelector("#config-anchor-preset"),r=s.container.querySelector("#config-anchor-x"),o=s.container.querySelector("#config-anchor-y"),c=wa(e)?(u=e.transform)==null?void 0:u.offset:(g=e.transform)==null?void 0:g.position;t&&(t.value=String((h=c==null?void 0:c.x)!=null?h:0)),n&&(n.value=String((f=c==null?void 0:c.y)!=null?f:0)),i&&(i.value=String((b=(m=e.transform)==null?void 0:m.scale)!=null?b:1));let d=(T=(w=(y=e.transform)==null?void 0:y.anchor)!=null?w:(v=e.render)==null?void 0:v.anchor)!=null?T:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let I=s.container.querySelectorAll(".anchor-custom-field"),_=a.value==="custom";I.forEach(L=>L.style.display=_?"block":"none")}let p=mr()(d);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function Ar(s){var l,c,d,p,u,g,h,f,m,b;let e=s.selectedObjectId;if(!e||!s.container)return;let t=(c=(l=s.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(p=(d=s.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",i=(g=(u=s.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(f=(h=s.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",r=(b=(m=s.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
1872
+ `}initialize(e,t){var y,v,w,T,P,j,L,M,R,I,E,C,A,S,x,_;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var O;let k=window.getEditableEngineConfig;if(typeof k=="function"){let z=k();return(O=z==null?void 0:z.loading)!=null?O:{}}return{}})(),a=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{type:a.value}),this.updateFieldVisibility(a.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=i.background_color||"#160a17",r.addEventListener("input",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{background_color:r.value})}));let o=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha"),l=(T=this.root)==null?void 0:T.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((P=i.overlay_alpha)!=null?P:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var O,z;let k=Number(o.value);l&&(l.textContent=k.toFixed(2)),(z=(O=this.options)==null?void 0:O.onUpdateLoading)==null||z.call(O,{overlay_alpha:k})}));let c=(j=this.root)==null?void 0:j.querySelector("#loading-text");c&&(c.value=i.text||"",c.addEventListener("input",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{text:c.value})}));let d=(L=this.root)==null?void 0:L.querySelector("#loading-text-scale"),p=(M=this.root)==null?void 0:M.querySelector("#loading-text-scale-value");d&&(d.value=String((R=i.text_scale)!=null?R:.6),p&&(p.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var O,z;let k=Number(d.value);p&&(p.textContent=k.toFixed(2)),(z=(O=this.options)==null?void 0:O.onUpdateLoading)==null||z.call(O,{text_scale:k})}));let u=(I=this.root)==null?void 0:I.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{enabled:u.checked})}));let g=(E=this.root)==null?void 0:E.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{blur_enabled:g.checked})}));let h=(C=this.root)==null?void 0:C.querySelector("#loading-blur-strength"),f=(A=this.root)==null?void 0:A.querySelector("#loading-blur-strength-value");h&&(h.value=String((S=i.blur_strength)!=null?S:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var k,O;f&&(f.textContent=h.value),(O=(k=this.options)==null?void 0:k.onUpdateLoading)==null||O.call(k,{blur_strength:Number(h.value)})}));let m=(x=this.root)==null?void 0:x.querySelector("#loading-show-btn"),b=(_=this.root)==null?void 0:_.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onShowLoadingScreen)==null||O.call(k)}),b==null||b.addEventListener("click",()=>{var k,O;(O=(k=this.options)==null?void 0:k.onHideLoadingScreen)==null||O.call(k)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var Bt=require("pixi.js");var ca=require("pixi.js"),Be=()=>window.debugConfig||{},mr=()=>window.resolveAnchorVec2||(s=>({x:.5,y:.5})),br=()=>window.resolveScreenAnchorPoint||(()=>new ca.Point),yr=()=>window.resolveScreenRatioPoint||(()=>new ca.Point);function vr(s){ti(s)&&(s.objectDebugRaf||(s.objectDebugRaf=window.requestAnimationFrame(()=>ni(s))))}function wr(s){s.objectDebugRaf&&(window.cancelAnimationFrame(s.objectDebugRaf),s.objectDebugRaf=null),Ft(s)}function ti(s){return s.isDebugOpen}function ni(s){var a,r,o;if(!ti(s)){s.objectDebugRaf=null;return}s.objectDebugRaf=window.requestAnimationFrame(()=>ni(s));let e=da(s);if(!e){Ht(s,null),Ft(s);return}let t=pa(s,e);if(!t){Ht(s,null),Ft(s);return}let n=new Bt.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=ua(s,t);Ht(s,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=i==null?void 0:i.x)!=null?r:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),s.highlightObject?ma(s,t):ya(s),s.highlightAnchor&&i?ba(s,i):va(s)}function da(s){var i;let e=s.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function pa(s,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Gt(s){let e=s.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function ua(s,e){var r,o;let t=Gt(s);if(!t)return null;let n=(r=t.transform)!=null?r:{},i=ga(s);if(!i)return null;if(n.position_ratio!=null)return yr()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&n.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),br()(i.width,i.height,a)}function ga(s){var a;let e=(a=s.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function ha(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectBoundsGfx&&s.objectBoundsGfx.parent!==e.stage&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectBoundsGfx||(s.objectBoundsGfx=new Bt.Graphics,s.objectBoundsGfx.zIndex=999999,e.stage.addChild(s.objectBoundsGfx)),s.objectBoundsGfx):null}function fa(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectAnchorGfx&&s.objectAnchorGfx.parent!==e.stage&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null),s.objectAnchorGfx||(s.objectAnchorGfx=new Bt.Graphics,s.objectAnchorGfx.zIndex=1e6,e.stage.addChild(s.objectAnchorGfx)),s.objectAnchorGfx):null}function ma(s,e){var i;let t=ha(s);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function ba(s,e){let t=fa(s);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function ya(s){s.objectBoundsGfx&&s.objectBoundsGfx.clear()}function va(s){s.objectAnchorGfx&&s.objectAnchorGfx.clear()}function Ft(s){s.objectBoundsGfx&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectAnchorGfx&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null)}function Ht(s,e){s.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function xr(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Sr(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n)a[o]=(r=a[o])!=null?r:{},a=a[o];a[i]=t}function wa(s){var n,i,a,r,o;if(!s)return!1;if((n=s.transform)!=null&&n.offset)return!0;let e=((a=(i=s.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(r=s.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function ai(s){let e=Be();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function Er(s){window.location.reload()}function si(s){let e=JSON.stringify(Be(),null,2);navigator.clipboard.writeText(e).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(e),alert("Config logged to console (clipboard not available)")})}async function Cr(s,e){var t,n,i;if(!(!s.configViewer||!s.container))try{let a=window.getEditableObjectConfig,r=typeof a=="function"?a(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(An(),Us)),p=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!p)return;let u=await l(p.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),ii(s,u),(n=s.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),ii(s,r),(i=s.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function ii(s,e){var u,g,h,f,m,b,y,v,w,T;if(!s.container)return;let t=s.container.querySelector("#config-pos-x"),n=s.container.querySelector("#config-pos-y"),i=s.container.querySelector("#config-scale"),a=s.container.querySelector("#config-anchor-preset"),r=s.container.querySelector("#config-anchor-x"),o=s.container.querySelector("#config-anchor-y"),c=wa(e)?(u=e.transform)==null?void 0:u.offset:(g=e.transform)==null?void 0:g.position;t&&(t.value=String((h=c==null?void 0:c.x)!=null?h:0)),n&&(n.value=String((f=c==null?void 0:c.y)!=null?f:0)),i&&(i.value=String((b=(m=e.transform)==null?void 0:m.scale)!=null?b:1));let d=(T=(w=(y=e.transform)==null?void 0:y.anchor)!=null?w:(v=e.render)==null?void 0:v.anchor)!=null?T:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let P=s.container.querySelectorAll(".anchor-custom-field"),j=a.value==="custom";P.forEach(L=>L.style.display=j?"block":"none")}let p=mr()(d);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function Ar(s){var l,c,d,p,u,g,h,f,m,b;let e=s.selectedObjectId;if(!e||!s.container)return;let t=(c=(l=s.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(p=(d=s.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",i=(g=(u=s.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(f=(h=s.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",r=(b=(m=s.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
1873
1873
  position: (${t}, ${n})
1874
1874
  scale: ${i}
1875
- anchor: (${a}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function xa(s,e){var u,g,h,f,m,b,y,v,w,T,I,_;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!s.container)return;let t=s.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((g=(u=s.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),i=Number((f=(h=s.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?f:0),a=Number((b=(m=s.container.querySelector("#config-scale"))==null?void 0:m.value)!=null?b:1),r=(v=(y=s.container.querySelector("#config-anchor-preset"))==null?void 0:y.value)!=null?v:"center",o=Number((T=(w=s.container.querySelector("#config-anchor-x"))==null?void 0:w.value)!=null?T:.5),l=Number((_=(I=s.container.querySelector("#config-anchor-y"))==null?void 0:I.value)!=null?_:.5),c=r==="custom"?{x:o,y:l}:r;console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(ee(),Ne));d({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.anchor",value:c},{silent:e==null?void 0:e.silent});let p=Gt(s);wa(p)&&d({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0})}async function Lr(s,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),Ne));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([d,p])=>{var u;if(d)if(d.includes(".")){let g=d.split("."),h=c;for(let f=0;f<g.length-1;f++){let m=g[f];h[m]=(u=h[m])!=null?u:{},h=h[m]}h[g[g.length-1]]=p}else c[d]=p}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function kr(s){s.selectedObjectId&&(s.objectAutoApplyTimer&&window.clearTimeout(s.objectAutoApplyTimer),s.objectAutoApplyTimer=window.setTimeout(()=>{s.objectAutoApplyTimer=null,xa(s,{silent:!0})},150))}var fl=3e3;function et(s,e,t){let n=t!=null?t:s.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,r=0,o=0,l=0,c=0,d=0,p=g=>{if(!i)return;let h=n.getBoundingClientRect();s.style.left=`${g.clientX-h.left-c}px`,s.style.top=`${g.clientY-h.top-d}px`},u=()=>{i&&(i=!1,s.classList.remove("dragging"),window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let h=g.target;if(h!=null&&h.closest("button, input, select, textarea"))return;g.preventDefault();let f=s.getBoundingClientRect(),m=n.getBoundingClientRect();console.log("[DRAG] Panel:",s.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] containerRect:",{left:m.left,top:m.top,width:m.width,height:m.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-f.left,d=g.clientY-f.top,console.log("[DRAG] offset:",{x:c,y:d});let b=f.left-m.left,y=f.top-m.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),s.style.left=`${b}px`,s.style.top=`${y}px`,s.style.right="auto",s.style.bottom="auto",s.style.zIndex=String(++fl),i=!0,s.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function ri(s,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,r=0,o=0,l=0,c=!1,d=u=>{var y;if(!c)return;let g=u.clientX-o,h=u.clientY-l,f=Math.max(n,a+g),m=Math.max(i,r+h);s.style.width=`${f}px`,(y=s.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(s.style.height=`${m}px`),t==null||t(f,m)},p=()=>{c&&(c=!1,window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=s.getBoundingClientRect();a=g.width,r=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function Sa(s,e){var f,m,b,y;let t=(b=(m=(f=s.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:s.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=s.container)!=null&&y.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,r=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>r&&(e.style.width=`${r}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,d=l.top-n.top,p=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),p),h=Math.min(Math.max(d,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function ht(s){var n,i;if(!s.container)return;let e=s.container.querySelector("#debug-workbench");if(!e)return;if(Sa(s,e),(n=s.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),r={activeTab:s.activeTab};if(a)try{r={...JSON.parse(a),activeTab:s.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(r));return}let t={activeTab:s.activeTab,width:e.style.width,height:(i=s.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function oi(s){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(s.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=s.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let r=(a=s.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!r?n.style.height=t.height:r&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Sa(s,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function Ea(s,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",Sa(s,e),ht(s))}function Tr(s){var i,a,r;if(!s.container)return;let e=s.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=s.toggleDebug)==null||o.call(s)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=s.toggleDebug)==null?void 0:o.call(s,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>ai(s)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>si(s)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;s.activeTab=l,Ca(s),ht(s)})}),La(s,e),Aa(s,e)}function Ca(s){if(!s.container)return;let e=s.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===s.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===s.activeTab)})}function Aa(s,e){fe(s,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),fe(s,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),fe(s,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),fe(s,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),fe(s,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),fe(s,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),fe(s,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),fe(s,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),fe(s,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=Be();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),r=Be();r.layout&&(r.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Pr(s){if(!s.container||!s.debugOverlay)return;let e=s.container.querySelector("#debug-workbench"),t=s.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),et(e,t,s.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{ht(s),Ea(s,e)},10)}));let n=s.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),et(n,i,s.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{Ea(s,n)},10)})),n&&a&&ri(n,a);let r=s.container.querySelector('[data-panel="scene-tools-corner"]'),o=r==null?void 0:r.querySelector("[data-panel-handle]");r&&o&&et(r,o,s.debugOverlay);let l=s.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&et(l,c,s.debugOverlay),oi(s)}function La(s,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function fe(s,e,t,n,i){let a=e.querySelector(`#${t}`),r=e.querySelector(i);if(!a||!r)return;let o=xr(Be(),n);typeof o=="number"&&(a.value=String(o),r.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);r.textContent=String(l),Sr(Be(),n,l)})}ee();var li=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async forceResyncAfterApply(){var e;try{let t=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:t})})}catch(t){console.warn("[ConfigPersistence] sync-screens failed:",t)}try{let t=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof t=="function"?await t():window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}try{(e=window.refreshEditableConfigIndex)==null||e.call(window)}catch{}try{window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}}))}catch{}}async initialize(e){this.container=e,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let e=De(),{hasChanges:t,overrideCount:n,overrides:i}=e,a={};for(let d of i){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1875
+ anchor: (${a}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function xa(s,e){var u,g,h,f,m,b,y,v,w,T,P,j;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!s.container)return;let t=s.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((g=(u=s.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),i=Number((f=(h=s.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?f:0),a=Number((b=(m=s.container.querySelector("#config-scale"))==null?void 0:m.value)!=null?b:1),r=(v=(y=s.container.querySelector("#config-anchor-preset"))==null?void 0:y.value)!=null?v:"center",o=Number((T=(w=s.container.querySelector("#config-anchor-x"))==null?void 0:w.value)!=null?T:.5),l=Number((j=(P=s.container.querySelector("#config-anchor-y"))==null?void 0:P.value)!=null?j:.5),c=r==="custom"?{x:o,y:l}:r;console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(ee(),Ne));d({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.anchor",value:c},{silent:e==null?void 0:e.silent});let p=Gt(s);wa(p)&&d({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0})}async function Lr(s,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),Ne));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([d,p])=>{var u;if(d)if(d.includes(".")){let g=d.split("."),h=c;for(let f=0;f<g.length-1;f++){let m=g[f];h[m]=(u=h[m])!=null?u:{},h=h[m]}h[g[g.length-1]]=p}else c[d]=p}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function kr(s){s.selectedObjectId&&(s.objectAutoApplyTimer&&window.clearTimeout(s.objectAutoApplyTimer),s.objectAutoApplyTimer=window.setTimeout(()=>{s.objectAutoApplyTimer=null,xa(s,{silent:!0})},150))}var fl=3e3;function et(s,e,t){let n=t!=null?t:s.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,r=0,o=0,l=0,c=0,d=0,p=g=>{if(!i)return;let h=n.getBoundingClientRect();s.style.left=`${g.clientX-h.left-c}px`,s.style.top=`${g.clientY-h.top-d}px`},u=()=>{i&&(i=!1,s.classList.remove("dragging"),window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let h=g.target;if(h!=null&&h.closest("button, input, select, textarea"))return;g.preventDefault();let f=s.getBoundingClientRect(),m=n.getBoundingClientRect();console.log("[DRAG] Panel:",s.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] containerRect:",{left:m.left,top:m.top,width:m.width,height:m.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-f.left,d=g.clientY-f.top,console.log("[DRAG] offset:",{x:c,y:d});let b=f.left-m.left,y=f.top-m.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),s.style.left=`${b}px`,s.style.top=`${y}px`,s.style.right="auto",s.style.bottom="auto",s.style.zIndex=String(++fl),i=!0,s.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function ri(s,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,r=0,o=0,l=0,c=!1,d=u=>{var y;if(!c)return;let g=u.clientX-o,h=u.clientY-l,f=Math.max(n,a+g),m=Math.max(i,r+h);s.style.width=`${f}px`,(y=s.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(s.style.height=`${m}px`),t==null||t(f,m)},p=()=>{c&&(c=!1,window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=s.getBoundingClientRect();a=g.width,r=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function Sa(s,e){var f,m,b,y;let t=(b=(m=(f=s.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:s.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=s.container)!=null&&y.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,r=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>r&&(e.style.width=`${r}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,d=l.top-n.top,p=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),p),h=Math.min(Math.max(d,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function ht(s){var n,i;if(!s.container)return;let e=s.container.querySelector("#debug-workbench");if(!e)return;if(Sa(s,e),(n=s.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),r={activeTab:s.activeTab};if(a)try{r={...JSON.parse(a),activeTab:s.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(r));return}let t={activeTab:s.activeTab,width:e.style.width,height:(i=s.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function oi(s){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(s.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=s.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let r=(a=s.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!r?n.style.height=t.height:r&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Sa(s,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function Ea(s,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",Sa(s,e),ht(s))}function Tr(s){var i,a,r;if(!s.container)return;let e=s.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=s.toggleDebug)==null||o.call(s)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=s.toggleDebug)==null?void 0:o.call(s,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>ai(s)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>si(s)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;s.activeTab=l,Ca(s),ht(s)})}),La(s,e),Aa(s,e)}function Ca(s){if(!s.container)return;let e=s.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===s.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===s.activeTab)})}function Aa(s,e){fe(s,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),fe(s,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),fe(s,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),fe(s,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),fe(s,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),fe(s,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),fe(s,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),fe(s,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),fe(s,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=Be();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),r=Be();r.layout&&(r.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Pr(s){if(!s.container||!s.debugOverlay)return;let e=s.container.querySelector("#debug-workbench"),t=s.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),et(e,t,s.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{ht(s),Ea(s,e)},10)}));let n=s.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),et(n,i,s.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{Ea(s,n)},10)})),n&&a&&ri(n,a);let r=s.container.querySelector('[data-panel="scene-tools-corner"]'),o=r==null?void 0:r.querySelector("[data-panel-handle]");r&&o&&et(r,o,s.debugOverlay);let l=s.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&et(l,c,s.debugOverlay),oi(s)}function La(s,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function fe(s,e,t,n,i){let a=e.querySelector(`#${t}`),r=e.querySelector(i);if(!a||!r)return;let o=xr(Be(),n);typeof o=="number"&&(a.value=String(o),r.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);r.textContent=String(l),Sr(Be(),n,l)})}ee();var li=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async forceResyncAfterApply(){var e;try{let t=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:t})})}catch(t){console.warn("[ConfigPersistence] sync-screens failed:",t)}try{let t=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof t=="function"?await t():window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}try{(e=window.refreshEditableConfigIndex)==null||e.call(window)}catch{}try{window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}}))}catch{}}async initialize(e){this.container=e,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let e=De(),{hasChanges:t,overrideCount:n,overrides:i}=e,a={};for(let d of i){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1876
1876
  <div class="config-persistence-panel">
1877
1877
  <!-- Status Footer (Always Visible) -->
1878
1878
  <div class="persistence-status-footer">
@@ -2304,7 +2304,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2304
2304
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
2305
2305
  </div>
2306
2306
  </div>
2307
- `,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)};ee();var $=require("pixi.js");ee();var ci=class{constructor(e){this.app=null;this.camera=new $.Container;this.bgContainer=new $.Container;this.mainContainer=new $.Container;this.uiContainer=new $.Container;this.gizmoLayer=new $.Container;this.screenFrame=new $.Graphics;this.gameFrame=new $.Graphics;this.gridLayer=new $.Graphics;this.spawnPointLayer=new $.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.dragLastPointer=null;this.dragPointerOffset=null;this.dragSyncHoldUntil=0;this.dragLogged=!1;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 $.Graphics;this.anchorVisualizationLayer=new $.Graphics;this.moveHandle=new $.Graphics;this.scaleHandle=new $.Graphics;this.rotateHandle=new $.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.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.updateManager=new we;this.backgroundCoverEnabled=!0;this.backgroundLocked=!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.playModeEnabled?this.schedulePostScreenSync({width:t,height:n}):this.syncFromConfig())};this.handleAnchorChanged=e=>{let t=e==null?void 0:e.detail,n=t==null?void 0:t.objectId;if(!n)return;let i=t==null?void 0:t.previousAnchor,a=t==null?void 0:t.nextAnchor;this.adjustPositionForAnchorChange(n,i,a)};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.path,i=t.objectId;if(n==="transform.anchor"&&i){let r=t.value,o=t.oldValue;o!=null&&this.adjustPositionForAnchorChange(i,o,r)}let a=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(a)&&a.length>0){this.syncFromConfig(a);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.playModeEnabled&&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 $.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.handleBackgroundCover=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&(this.backgroundCoverEnabled=t,this.syncFromConfig(),this.updateGizmos())};this.handleBackgroundLock=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;if(typeof t=="boolean"&&(this.backgroundLocked=t,t&&this.selectedId)){let i=this.getEditableObjectConfig(this.selectedId),a=this.objectMap.get(this.selectedId);this.isBackgroundObject(this.selectedId,i,a==null?void 0:a.displayObject)&&this.setSelected(null)}};this.handlePlayModeChange=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&(!this.playModeInitialized&&(this.playModeInitialized=!0,!t)||t&&this.applyPlayModeState(!0))};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),re({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=>{var i;if(!this.dragMode||!this.selectedId||!this.dragContainer||!this.dragStartPointer||!this.dragStartPos)return;let t=this.objectMap.get(this.selectedId);if(!(t!=null&&t.displayObject))return;let n=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(n){if(this.dragMode==="move"){let a=this.dragPointerOffset;if(!a)return;let r=n.x+a.x,o=n.y+a.y;t.displayObject.position.set(r,o),this.updateLiveConfigPosition(r,o),this.dragLastPointer=new $.Point(n.x,n.y),this.dragLogged||(this.dragLogged=!0,console.log("[SceneEditor][DragMove]",{objectId:this.selectedId,pointer:{x:n.x,y:n.y},nextPos:{x:r,y:o}}))}if(this.dragMode==="scale"&&this.dragAnchorLocal){let r=Math.max(1,this.distance(n,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*r);(i=t.displayObject.scale)!=null&&i.set?t.displayObject.scale.set(o,o):t.displayObject.scale&&(t.displayObject.scale.x=o,t.displayObject.scale.y=o),this.updateLiveConfigScale(o)}if(this.dragMode==="rotate"&&this.dragAnchorLocal){let a=Math.atan2(n.y-this.dragAnchorLocal.y,n.x-this.dragAnchorLocal.x),r=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=r,this.updateLiveConfigRotation(r)}this.updateGizmos()}};this.onDragEnd=()=>{this.dragMode&&(this.selectedId&&(window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:this.selectedId}})),this.dragSyncHoldUntil=performance.now()+200),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,this.dragLastPointer=null,this.dragPointerOffset=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 $.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(){this.app||(this.app=new $.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.bgContainer.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.bgContainer),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.bgContainer.zIndex=-5e3,this.bgContainer.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(),this.applyPlayModeState(!0),!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:background-cover",this.handleBackgroundCover),window.removeEventListener("scene-editor:background-lock",this.handleBackgroundLock),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.removeEventListener("scene-editor:anchor-changed",this.handleAnchorChanged),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:background-cover",this.handleBackgroundCover),window.addEventListener("scene-editor:background-lock",this.handleBackgroundLock),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.addEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.addEventListener("scene-editor:anchor-changed",this.handleAnchorChanged),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.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t)),this.applyEditControls()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}adjustPositionForAnchorChange(e,t,n){var L,M,O,P,E,C;if(t==null||n==null||t===n)return;let i=this.getEditableObjectConfig(e);if(!i)return;let a=(L=i.transform)!=null?L:{};if(a.position_ratio!=null)return;let r=(M=this.getRuntimeScreenSize())!=null?M:this.getScreen();if(!(r!=null&&r.width)||!(r!=null&&r.height))return;let o=this.objectMap.get(e),l=this.isBackgroundObject(e,i,o==null?void 0:o.displayObject),c=this.getRuntimeScale(),d=ze(r.width,r.height,t),p=ze(r.width,r.height,n),u=d.x,g=d.y,h=p.x,f=p.y;l||(u=(d.x-r.width/2)/c,g=(d.y-r.height/2)/c,h=(p.x-r.width/2)/c,f=(p.y-r.height/2)/c);let m=u-h,b=g-f,y=a.position,v=Array.isArray(y)?Number((O=y[0])!=null?O:0):Number((P=y==null?void 0:y.x)!=null?P:0),w=Array.isArray(y)?Number((E=y[1])!=null?E:0):Number((C=y==null?void 0:y.y)!=null?C:0),T=(Number.isFinite(v)?v:0)+m,I=(Number.isFinite(w)?w:0)+b,_=this.buildPositionValue(a,{x:T,y:I});this.updateManager.updateProperty(e,"transform.position",_,{refreshInspector:!0})}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1||this.backgroundLocked&&this.isBackgroundObject(i,this.getEditableObjectConfig(i),r))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")),i=window.localStorage.getItem(this.getSceneStorageKey("background_cover")),a=window.localStorage.getItem(this.getSceneStorageKey("background_lock"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let r=Number(t);Number.isFinite(r)&&r>2&&(this.gridGap=r)}if(n!==null){let r=Number(n);Number.isFinite(r)&&r>=0&&r<=1&&(this.gridAlpha=r)}i!==null&&(this.backgroundCoverEnabled=i==="true"),a!==null&&(this.backgroundLocked=a==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}applyPlayModeState(e){var t;this.playModeEnabled=e,(t=this.app)!=null&&t.ticker&&(this.app.ticker.remove(this.syncFromGameObjects),e&&this.app.ticker.add(this.syncFromGameObjects)),this.applyEditControls(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})}applyEditControls(){this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static"}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&this.playModeEnabled&&(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 f=Number((o=e.renderer.resolution)!=null?o:1)||1,m=Number((l=e.renderer.width)!=null?l:0)/f,b=Number((c=e.renderer.height)!=null?c:0)/f;if(Number.isFinite(m)&&m>0&&Number.isFinite(b)&&b>0)return{width:m,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,f,m,b,y,v,w,T,I,_,L,M,O,P,E,C,A,S,x,j,k,R,z,D,q;let e=window.__screenManager;if(e){let F=["gameplay","start","tutorial","endgame","loading"];for(let G of F){let B=(a=e.get)==null?void 0:a.call(e,G);if(B!=null&&B.visible){let U=(r=B.getContentLayer)==null?void 0:r.call(B);if(U){let J=(o=B.x)!=null?o:0,Z=(l=B.y)!=null?l:0,H=(c=U.x)!=null?c:0,ae=(d=U.y)!=null?d:0,te=(u=(p=U.scale)==null?void 0:p.x)!=null?u:1,ne=(h=(g=U.scale)==null?void 0:g.y)!=null?h:te;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:G,contentLayerScale:{x:te,y:ne},position:{x:J+H,y:Z+ae}}),{scale:{x:te,y:ne},position:{x:J+H,y:Z+ae},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let G of F){let B=(f=e.get)==null?void 0:f.call(e,G);if(B){if(!B.visible&&typeof B.updateLayout=="function"){let J=window.gameApp;if((m=J==null?void 0:J.renderer)!=null&&m.screen){let Z=J.renderer.screen.width,H=J.renderer.screen.height;Z>0&&H>0&&B.updateLayout(Z,H)}}let U=(b=B.getContentLayer)==null?void 0:b.call(B);if(U){let J=(y=B.x)!=null?y:0,Z=(v=B.y)!=null?v:0,H=(w=U.x)!=null?w:0,ae=(T=U.y)!=null?T:0,te=(_=(I=U.scale)==null?void 0:I.x)!=null?_:1,ne=(M=(L=U.scale)==null?void 0:L.y)!=null?M:te;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:G,visible:B.visible,contentLayerScale:{x:te,y:ne},position:{x:J+H,y:Z+ae}}),{scale:{x:te,y:ne},position:{x:J+H,y:Z+ae},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let t=window.__mainContainer;if(t){let F=(P=(O=t.scale)==null?void 0:O.x)!=null?P:1,G=(C=(E=t.scale)==null?void 0:E.y)!=null?C:F;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:F,y:G},position:{x:(A=t.position)==null?void 0:A.x,y:(S=t.position)==null?void 0:S.y}}),t}let n=window.gameApp,i=(x=n==null?void 0:n.stage)!=null?x:null;if(i){let F=(k=(j=i.scale)==null?void 0:j.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:(D=i.position)==null?void 0:D.x,y:(q=i.position)==null?void 0:q.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeScale(){var n,i;let e=this.getRuntimeLayoutReference(),t=Number((i=(n=e==null?void 0:e.scale)==null?void 0:n.x)!=null?i:1);return Number.isFinite(t)&&t>0?t:Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1}getRuntimeParentContainer(e){var c,d,p,u,g;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((c=n==null?void 0:n.getDisplayObject)==null?void 0:c.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.parent;if(!a)return null;let r=window.__screenManager;if(r){let h=["gameplay","start","tutorial","endgame","loading"];for(let f of h){let m=(d=r.get)==null?void 0:d.call(r,f);if(!m)continue;let b=(u=(p=m.getBgLayer)==null?void 0:p.call(m))!=null?u:m.bgLayer;if(b&&(a===b||typeof b.contains=="function"&&b.contains(a)))return this.bgContainer}}let o=this.getRuntimeLayoutReference(),l=(g=window.gameApp)==null?void 0:g.stage;return o&&l&&o===l?this.mainContainer:o&&typeof o.contains=="function"&&o.contains(a)?this.mainContainer:a===o||a===l?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,f;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 m=Number((g=(u=e.pivot)==null?void 0:u.x)!=null?g:0),b=Number((f=(h=e.pivot)==null?void 0:h.y)!=null?f:0);Number.isFinite(m)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(m,b),this.uiContainer.pivot.set(m,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.playModeEnabled?this.getRuntimeParentContainer(e):null,l=this.isBackgroundObject(e,t)?this.bgContainer:a?this.uiContainer:this.mainContainer,c=r!=null?r:l;if(!i||i.assetKey!==n||i.isUi!==a){i&&this.removeObject(e);let p=await this.createDisplayObject(e,t);if(!p)return;c.addChild(p),this.objectMap.set(e,{id:e,displayObject:p,assetKey:n,isUi:a}),this.attachObjectInteraction(p,e)}let d=this.objectMap.get(e);d&&(d.displayObject.parent!==c&&c.addChild(d.displayObject),this.applyVisualConfig(d.displayObject,t),this.playModeEnabled||this.applyTransformFromConfig(e,d.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,f,m,b,y,v,w,T;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 _=await ye.create(e,t,this.app);if(_ instanceof $.Container)return _}}catch(I){console.warn("[SceneEditor] ObjectFactory failed for",e,I)}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 I=this.getScreen(),_=(p=I==null?void 0:I.width)!=null?p:0,L=(u=I==null?void 0:I.height)!=null?u:0,M=new $.Graphics,O=this.parseColor(i.background_color,0),P=typeof i.background_alpha=="number"?i.background_alpha:1;_>0&&L>0&&M.rect(0,0,_,L).fill({color:O,alpha:P});let E=new $.Container;return E.addChild(M),E}if(a){let I=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",_=new $.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(f=n==null?void 0:n.fontSize)!=null?f:16,fill:I,align:(m=n==null?void 0:n.align)!=null?m:"center",letterSpacing:(b=n==null?void 0:n.letterSpacing)!=null?b:0});return new $.Text({text:(y=n==null?void 0:n.text)!=null?y:"",style:_})}if((v=t==null?void 0:t.effects)!=null&&v.width||(w=t==null?void 0:t.effects)!=null&&w.height){let I=new $.Graphics,_=typeof t.effects.width=="number"?t.effects.width:100,L=typeof t.effects.height=="number"?t.effects.height:100,M=(T=t.effects.fill_color)!=null?T:"#ffffff",O=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,P=Number.parseInt(String(M).replace("#",""),16);return I.rect(0,0,_,L).fill({color:Number.isFinite(P)?P:16777215,alpha:O}),I}return new $.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 $.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")}isBackgroundObject(e,t,n){var r,o;if((n==null?void 0:n.parent)===this.bgContainer)return!0;let i=(((r=t==null?void 0:t.identity)==null?void 0:r.category)||"").toString().toLowerCase(),a=(((o=t==null?void 0:t.identity)==null?void 0:o.id)||e||"").toString().toLowerCase();return!!(i.includes("bg")||i.includes("background")||a.startsWith("background_")||a.includes("background"))}applyVisualConfig(e,t){var a,r,o;if(!e)return;let n=(a=t==null?void 0:t.render)!=null?a:{};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={x:.5,y:.5};if((r=e.anchor)!=null&&r.set)e.anchor.set(i.x,i.y);else if(e.pivot){let l=(o=e.getLocalBounds)==null?void 0:o.call(e);l&&e.pivot.set(l.width*i.x,l.height*i.y)}}applyTransformFromConfig(e,t,n){var _,L,M,O,P,E,C,A,S,x,j,k,R,z,D,q,F,G,B,U,J;if(!t)return;let i=this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return;let a=(_=n==null?void 0:n.transform)!=null?_:{},r=this.getPositioningAnchor(e,a),o=a==null?void 0:a.position_ratio,l=a==null?void 0:a.position,c=a==null?void 0:a.offset,d=Array.isArray(l)?Number((L=l[0])!=null?L:0):Number((M=l==null?void 0:l.x)!=null?M:0),p=Array.isArray(l)?Number((O=l[1])!=null?O:0):Number((P=l==null?void 0:l.y)!=null?P:0),u=Array.isArray(c)?Number((E=c[0])!=null?E:0):Number((C=c==null?void 0:c.x)!=null?C:0),g=Array.isArray(c)?Number((A=c[1])!=null?A:0):Number((S=c==null?void 0:c.y)!=null?S:0),h=(Number.isFinite(d)?d:0)+(Number.isFinite(u)?u:0),f=(Number.isFinite(p)?p:0)+(Number.isFinite(g)?g:0);if(this.backgroundCoverEnabled&&this.isBackgroundObject(e,n,t)){let Z=Number((j=(x=t==null?void 0:t.texture)==null?void 0:x.width)!=null?j:0),H=Number((R=(k=t==null?void 0:t.texture)==null?void 0:k.height)!=null?R:0);if(!Number.isFinite(Z)||Z<=0||!Number.isFinite(H)||H<=0){let ge=(z=t==null?void 0:t.getLocalBounds)==null?void 0:z.call(t);Z=Number((D=ge==null?void 0:ge.width)!=null?D:0),H=Number((q=ge==null?void 0:ge.height)!=null?q:0)}if(!Number.isFinite(Z)||Z<=0||!Number.isFinite(H)||H<=0)return;(F=t.anchor)!=null&&F.set&&t.anchor.set(.5,.5),(G=t.position)!=null&&G.set?t.position.set(i.width/2,i.height/2):t.position&&(t.position.x=i.width/2,t.position.y=i.height/2);let ae=i.width/Z,te=i.height/H,ne=Math.max(ae,te);(B=t.scale)!=null&&B.set?t.scale.set(ne,ne):t.scale&&(t.scale.x=ne,t.scale.y=ne);let je=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(je);return}let m=o!=null?ct(i.width,i.height,o):ze(i.width,i.height,r),b=this.getRuntimeScale(),y=(m.x-i.width/2)/b+h,v=(m.y-i.height/2)/b+f;(U=t.position)!=null&&U.set?t.position.set(y,v):t.position&&(t.position.x=y,t.position.y=v);let T=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*this.getRuntimeScale();(J=t.scale)!=null&&J.set?t.scale.set(T,T):t.scale&&(t.scale.x=T,t.scale.y=T);let I=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(I)}getAnchorLocalPoint(e,t=this.mainContainer){var d;let n=(d=this.getRuntimeScreenSize())!=null?d:this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let i="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),r=(e==null?void 0:e.position_ratio)!=null?ct(n.width,n.height,e.position_ratio):ze(n.width,n.height,a!=null?a:i);if(t===this.bgContainer)return new $.Point(r.x,r.y);let o=this.getRuntimeScale(),l=(r.x-n.width/2)/o,c=(r.y-n.height/2)/o;return new $.Point(l,c)}getPositioningAnchor(e,t){var n,i,a,r,o,l,c,d,p,u;if((t==null?void 0:t.anchor)!=null&&t.anchor!=="")return t.anchor;if(typeof window!="undefined"&&e){let g=window,h=g.__editableConfig,f=(i=(n=h==null?void 0:h.objects)==null?void 0:n.get)==null?void 0:i.call(n,e),m=(o=(a=f==null?void 0:f.transform)==null?void 0:a.anchor)!=null?o:(r=f==null?void 0:f.render)==null?void 0:r.anchor;if(m!=null&&m!=="")return m;let b=g.__editableConfigBaseline,y=(c=(l=b==null?void 0:b.objects)==null?void 0:l.get)==null?void 0:c.call(l,e),v=(u=(d=y==null?void 0:y.transform)==null?void 0:d.anchor)!=null?u:(p=y==null?void 0:y.render)==null?void 0:p.anchor;if(v!=null&&v!=="")return v}return"top-left"}getActiveScreenSize(e){var t,n;return this.playModeEnabled?(n=(t=this.getRuntimeScreenSize())!=null?t:e)!=null?n:this.getScreen():e!=null?e:this.getScreen()}updateLayout(e){var n,i,a,r,o,l,c,d,p;let t=this.getActiveScreenSize(e);if(!(!(t!=null&&t.width)||!(t!=null&&t.height))){if(console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.playModeEnabled){let u=this.getRuntimeLayoutReference();if(u){let g=Number((i=(n=u.position)==null?void 0:n.x)!=null?i:t.width/2),h=Number((r=(a=u.position)==null?void 0:a.y)!=null?r:t.height/2);this.mainContainer.position.set(g,h),this.uiContainer.position.set(g,h);let f=Number((l=(o=u.scale)==null?void 0:o.x)!=null?l:1);Number.isFinite(f)&&f>0&&(this.layoutScale=f)}this.bgContainer.position.set(0,0),this.bgContainer.scale.set(1,1),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1)}else this.bgContainer.position.set(0,0),this.bgContainer.scale.set(1,1),this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.rotation=0,this.uiContainer.rotation=0,(c=this.mainContainer.pivot)!=null&&c.set&&this.mainContainer.pivot.set(0,0),(d=this.uiContainer.pivot)!=null&&d.set&&this.uiContainer.pivot.set(0,0);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),(p=this.app)!=null&&p.stage&&(this.app.stage.hitArea=new $.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 $.Point(0,0)),i=this.camera.toLocal(new $.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,f=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let m=h;m<=r;m+=u)this.gridLayer.moveTo(m,o),this.gridLayer.lineTo(m,l);for(let m=f;m<=l;m+=g)this.gridLayer.moveTo(a,m),this.gridLayer.lineTo(r,m);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){let t=this.getActiveScreenSize(e);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,p;if(!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode||this.selectedId&&performance.now()<this.dragSyncHoldUntil?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(t&&u===t)continue;let h=e.get(u),f=((n=h==null?void 0:h.getDisplayObject)==null?void 0:n.call(h))||(h==null?void 0:h.pixiObject)||h;if(!f)continue;let m=(a=(i=g.displayObject)==null?void 0:i.parent)!=null?a:this.mainContainer,b=new $.Point;if(typeof f.getGlobalPosition=="function"){f.getGlobalPosition(b);let I=m.toLocal(b,this.camera);g.displayObject.position.set(I.x,I.y)}else if(f.worldTransform){b.set(f.worldTransform.tx,f.worldTransform.ty);let I=m.toLocal(b,this.camera);g.displayObject.position.set(I.x,I.y)}let y=this.getWorldScale(f);if(y){let I=Number((o=(r=m.scale)==null?void 0:r.x)!=null?o:1)||1,_=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,L=y.x/I,M=y.y/_;(d=g.displayObject.scale)!=null&&d.set?g.displayObject.scale.set(L,M):g.displayObject.scale&&(g.displayObject.scale.x=L,g.displayObject.scale.y=M)}let v=this.getWorldRotation(f);if(typeof v=="number"){let I=m?m.rotation:0,_=v-I;g.displayObject.rotation=_;let L=this.getEditableObjectConfig(u);if(L){let M=(p=L.transform)!=null?p:{};L.transform||(L.transform=M);let O=this.toDegrees(_),P=typeof M.rotation=="number"?M.rotation:0;if(Math.abs(O-P)>.01){let E=Math.round(O*100)/100;M.rotation=E}}}let w=f.parent,T=typeof(w==null?void 0:w.getChildIndex)=="function"?w.getChildIndex(f):0;typeof f.zIndex=="number"?g.displayObject.zIndex=f.zIndex:Number.isFinite(T)&&(g.displayObject.zIndex=T)}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(){if(!this.app)return;let e=this.getActiveScreenSize();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 f,m;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=(m=(f=e.displayObject).getBounds)==null?void 0:m.call(f);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new $.Point(t.x,t.y)),i=this.camera.toLocal(new $.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});let c=7,d={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(o,l,c).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(d),this.moveHandle.cursor="move";let p=n.x+a,u=n.y+r;this.scaleHandle.clear(),this.scaleHandle.rect(p-c,u-c,c*2,c*2).fill({color:3718648,alpha:.95}),this.scaleHandle.stroke(d),this.scaleHandle.cursor="nwse-resize";let g=o,h=n.y-c*2;this.rotateHandle.clear(),this.rotateHandle.circle(g,h,c).fill({color:16347926,alpha:.95}),this.rotateHandle.stroke(d),this.rotateHandle.cursor="crosshair"}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 $.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="static",a.on("pointerdown",o=>this.startSpawnPointDrag(i,o)),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 $.Point(e.x,e.y)),n=new $.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 $.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){var d,p,u,g,h,f,m;if(!this.selectedId)return;let n=this.objectMap.get(this.selectedId);if(!(n!=null&&n.displayObject))return;let i=this.getEditableObjectConfig(this.selectedId);if(!i||this.backgroundLocked&&this.isBackgroundObject(this.selectedId,i,n.displayObject))return;let a=(d=i.transform)!=null?d:{},r=(p=n.displayObject.parent)!=null?p:this.mainContainer,o=this.getEventLocalPoint(t,r);if(!o)return;(u=t==null?void 0:t.stopPropagation)==null||u.call(t),(g=t==null?void 0:t.stopImmediatePropagation)==null||g.call(t);let l=this.getPositioningAnchor(this.selectedId,a);(a.anchor==null||a.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"transform.anchor",l),(((h=i==null?void 0:i.render)==null?void 0:h.anchor)==null||i.render.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"render.anchor",l),this.dragMode=e,this.dragContainer=r,this.dragStartPointer=new $.Point(o.x,o.y),this.dragStartPos=new $.Point(n.displayObject.position.x,n.displayObject.position.y),this.dragLastPointer=new $.Point(o.x,o.y),this.dragPointerOffset=new $.Point(n.displayObject.position.x-o.x,n.displayObject.position.y-o.y),this.dragLogged=!1;let c=(f=this.getRuntimeScreenSize())!=null?f:this.getScreen();console.log("[SceneEditor][DragStart]",{objectId:this.selectedId,mode:e,isBackground:this.isBackgroundObject(this.selectedId,i,n.displayObject),screen:c,runtimeScale:this.getRuntimeScale(),pointer:{x:o.x,y:o.y},objectPos:{x:n.displayObject.position.x,y:n.displayObject.position.y},container:r===this.bgContainer?"bg":r===this.uiContainer?"ui":"main"}),this.dragStartScale=typeof((m=n.displayObject.scale)==null?void 0:m.x)=="number"?n.displayObject.scale.x:1,this.dragStartRotation=typeof n.displayObject.rotation=="number"?n.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,r),this.dragStartValue=this.getDragStartValue(e,a),this.dragAnchorLocal&&(this.dragStartAngle=Math.atan2(o.y-this.dragAnchorLocal.y,o.x-this.dragAnchorLocal.x),this.dragStartDistance=Math.max(1,this.distance(o,this.dragAnchorLocal))),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}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 w,T,I,_,L,M,O,P;if(!this.selectedId)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=(w=n.transform)!=null?w:{};n.transform||(n.transform=i);let a=(T=this.getRuntimeScreenSize())!=null?T:this.getScreen();if(!(a!=null&&a.width)||!(a!=null&&a.height))return;let r=this.objectMap.get(this.selectedId),o=((I=r==null?void 0:r.displayObject)==null?void 0:I.parent)===this.bgContainer,l=this.getPositioningAnchor(this.selectedId,i),c=(i==null?void 0:i.position_ratio)!=null?ct(a.width,a.height,i.position_ratio):ze(a.width,a.height,l),d=c.x,p=c.y,u=e,g=t;if(!o){let E=this.getRuntimeScale();d=(c.x-a.width/2)/E,p=(c.y-a.height/2)/E,u=e/E,g=t/E}let h=u-d,f=g-p,m=(_=i.offset)!=null?_:{x:0,y:0},b=Array.isArray(m)?Number((L=m[0])!=null?L:0):Number((M=m==null?void 0:m.x)!=null?M:0),y=Array.isArray(m)?Number((O=m[1])!=null?O:0):Number((P=m==null?void 0:m.y)!=null?P:0),v=this.buildPositionValue(i,{x:h-b,y:f-y});this.updateManager.updateProperty(this.selectedId,"transform.position",v,{refreshInspector:!0})}updateLiveConfigScale(e){var a;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(a=t.transform)!=null?a:{};t.transform||(t.transform=n);let i=Math.round(e*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.scale",i,{refreshInspector:!0})}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;if(Math.abs(i-a)>.01){let o=Math.round(i*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.rotation",o,{refreshInspector:!0})}}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),re({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),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}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 $.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 $.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 $.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 $.Point;return t.toLocal(new $.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 $.Point;return n.toLocal(new $.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=[Qe("playable-portrait"),Qe("iphone-14"),Qe("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=Qe(e.defaultDevice||Ln.id),this.debugPanel=new Ut,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=Qe(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,f=p-g-200;return Math.max(200,f)},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 f=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",m=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${f} minmax(${b}px, 1fr) ${m}`}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&&et(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=`
2307
+ `,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)};ee();var $=require("pixi.js");ee();var ci=class{constructor(e){this.app=null;this.camera=new $.Container;this.bgContainer=new $.Container;this.mainContainer=new $.Container;this.uiContainer=new $.Container;this.gizmoLayer=new $.Container;this.screenFrame=new $.Graphics;this.gameFrame=new $.Graphics;this.gridLayer=new $.Graphics;this.spawnPointLayer=new $.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.dragLastPointer=null;this.dragPointerOffset=null;this.dragSyncHoldUntil=0;this.dragLogged=!1;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 $.Graphics;this.anchorVisualizationLayer=new $.Graphics;this.moveHandle=new $.Graphics;this.scaleHandle=new $.Graphics;this.rotateHandle=new $.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.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.updateManager=new we;this.backgroundCoverEnabled=!0;this.backgroundLocked=!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.playModeEnabled?this.schedulePostScreenSync({width:t,height:n}):this.syncFromConfig())};this.handleAnchorChanged=e=>{let t=e==null?void 0:e.detail,n=t==null?void 0:t.objectId;if(!n)return;let i=t==null?void 0:t.previousAnchor,a=t==null?void 0:t.nextAnchor;this.adjustPositionForAnchorChange(n,i,a)};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.path,i=t.objectId;if(n==="transform.anchor"&&i){let r=t.value,o=t.oldValue;o!=null&&this.adjustPositionForAnchorChange(i,o,r)}let a=t.objectIds;if(i){this.syncFromConfig([i]);return}if(Array.isArray(a)&&a.length>0){this.syncFromConfig(a);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.playModeEnabled&&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 $.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.handleBackgroundCover=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&(this.backgroundCoverEnabled=t,this.syncFromConfig(),this.updateGizmos())};this.handleBackgroundLock=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;if(typeof t=="boolean"&&(this.backgroundLocked=t,t&&this.selectedId)){let i=this.getEditableObjectConfig(this.selectedId),a=this.objectMap.get(this.selectedId);this.isBackgroundObject(this.selectedId,i,a==null?void 0:a.displayObject)&&this.setSelected(null)}};this.handlePlayModeChange=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&(!this.playModeInitialized&&(this.playModeInitialized=!0,!t)||t&&this.applyPlayModeState(!0))};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),re({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=>{var i;if(!this.dragMode||!this.selectedId||!this.dragContainer||!this.dragStartPointer||!this.dragStartPos)return;let t=this.objectMap.get(this.selectedId);if(!(t!=null&&t.displayObject))return;let n=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(n){if(this.dragMode==="move"){let a=this.dragPointerOffset;if(!a)return;let r=n.x+a.x,o=n.y+a.y;t.displayObject.position.set(r,o),this.updateLiveConfigPosition(r,o),this.dragLastPointer=new $.Point(n.x,n.y),this.dragLogged||(this.dragLogged=!0,console.log("[SceneEditor][DragMove]",{objectId:this.selectedId,pointer:{x:n.x,y:n.y},nextPos:{x:r,y:o}}))}if(this.dragMode==="scale"&&this.dragAnchorLocal){let r=Math.max(1,this.distance(n,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*r);(i=t.displayObject.scale)!=null&&i.set?t.displayObject.scale.set(o,o):t.displayObject.scale&&(t.displayObject.scale.x=o,t.displayObject.scale.y=o),this.updateLiveConfigScale(o)}if(this.dragMode==="rotate"&&this.dragAnchorLocal){let a=Math.atan2(n.y-this.dragAnchorLocal.y,n.x-this.dragAnchorLocal.x),r=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=r,this.updateLiveConfigRotation(r)}this.updateGizmos()}};this.onDragEnd=()=>{this.dragMode&&(this.selectedId&&(window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:this.selectedId}})),this.dragSyncHoldUntil=performance.now()+200),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,this.dragLastPointer=null,this.dragPointerOffset=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 $.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(){this.app||(this.app=new $.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.bgContainer.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.bgContainer),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.bgContainer.zIndex=-5e3,this.bgContainer.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(),this.applyPlayModeState(!0),!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:background-cover",this.handleBackgroundCover),window.removeEventListener("scene-editor:background-lock",this.handleBackgroundLock),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.removeEventListener("scene-editor:anchor-changed",this.handleAnchorChanged),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:background-cover",this.handleBackgroundCover),window.addEventListener("scene-editor:background-lock",this.handleBackgroundLock),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.addEventListener("scene-editor:play-mode",this.handlePlayModeChange),window.addEventListener("scene-editor:anchor-changed",this.handleAnchorChanged),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.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t)),this.applyEditControls()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}adjustPositionForAnchorChange(e,t,n){var E,C,A,S,x,_,k,O,z,D;if(t==null||n==null||t===n)return;let i=this.getEditableObjectConfig(e);if(!i)return;let a=(E=i.transform)!=null?E:{};if(a.position_ratio!=null)return;let r=(C=this.getRuntimeScreenSize())!=null?C:this.getScreen();if(!(r!=null&&r.width)||!(r!=null&&r.height))return;let o=this.objectMap.get(e);if(!(o!=null&&o.displayObject))return;let l=this.isBackgroundObject(e,i,o.displayObject),c=this.getRuntimeScale(),d=o.displayObject.position.x,p=o.displayObject.position.y,u=ze(r.width,r.height,t),g=ze(r.width,r.height,n),h=g.x,f=g.y;l||(h=(g.x-r.width/2)/c,f=(g.y-r.height/2)/c);let m=d-h,b=p-f,y=a.position,v=a.offset,w=Array.isArray(y)?Number((A=y[0])!=null?A:0):Number((S=y==null?void 0:y.x)!=null?S:0),T=Array.isArray(y)?Number((x=y[1])!=null?x:0):Number((_=y==null?void 0:y.y)!=null?_:0),P=Array.isArray(v)?Number((k=v[0])!=null?k:0):Number((O=v==null?void 0:v.x)!=null?O:0),j=Array.isArray(v)?Number((z=v[1])!=null?z:0):Number((D=v==null?void 0:v.y)!=null?D:0),L=(Number.isFinite(w)?w:0)+(Number.isFinite(P)?P:0),M=m-P,R=b-j,I=this.buildPositionValue(a,{x:M,y:R});this.updateManager.updateProperty(e,"transform.position",I,{refreshInspector:!0})}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1||this.backgroundLocked&&this.isBackgroundObject(i,this.getEditableObjectConfig(i),r))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")),i=window.localStorage.getItem(this.getSceneStorageKey("background_cover")),a=window.localStorage.getItem(this.getSceneStorageKey("background_lock"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let r=Number(t);Number.isFinite(r)&&r>2&&(this.gridGap=r)}if(n!==null){let r=Number(n);Number.isFinite(r)&&r>=0&&r<=1&&(this.gridAlpha=r)}i!==null&&(this.backgroundCoverEnabled=i==="true"),a!==null&&(this.backgroundLocked=a==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}applyPlayModeState(e){var t;this.playModeEnabled=e,(t=this.app)!=null&&t.ticker&&(this.app.ticker.remove(this.syncFromGameObjects),e&&this.app.ticker.add(this.syncFromGameObjects)),this.applyEditControls(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})}applyEditControls(){this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static"}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&this.playModeEnabled&&(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 f=Number((o=e.renderer.resolution)!=null?o:1)||1,m=Number((l=e.renderer.width)!=null?l:0)/f,b=Number((c=e.renderer.height)!=null?c:0)/f;if(Number.isFinite(m)&&m>0&&Number.isFinite(b)&&b>0)return{width:m,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,f,m,b,y,v,w,T,P,j,L,M,R,I,E,C,A,S,x,_,k,O,z,D,q;let e=window.__screenManager;if(e){let F=["gameplay","start","tutorial","endgame","loading"];for(let G of F){let B=(a=e.get)==null?void 0:a.call(e,G);if(B!=null&&B.visible){let U=(r=B.getContentLayer)==null?void 0:r.call(B);if(U){let J=(o=B.x)!=null?o:0,Z=(l=B.y)!=null?l:0,H=(c=U.x)!=null?c:0,ae=(d=U.y)!=null?d:0,te=(u=(p=U.scale)==null?void 0:p.x)!=null?u:1,ne=(h=(g=U.scale)==null?void 0:g.y)!=null?h:te;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:G,contentLayerScale:{x:te,y:ne},position:{x:J+H,y:Z+ae}}),{scale:{x:te,y:ne},position:{x:J+H,y:Z+ae},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let G of F){let B=(f=e.get)==null?void 0:f.call(e,G);if(B){if(!B.visible&&typeof B.updateLayout=="function"){let J=window.gameApp;if((m=J==null?void 0:J.renderer)!=null&&m.screen){let Z=J.renderer.screen.width,H=J.renderer.screen.height;Z>0&&H>0&&B.updateLayout(Z,H)}}let U=(b=B.getContentLayer)==null?void 0:b.call(B);if(U){let J=(y=B.x)!=null?y:0,Z=(v=B.y)!=null?v:0,H=(w=U.x)!=null?w:0,ae=(T=U.y)!=null?T:0,te=(j=(P=U.scale)==null?void 0:P.x)!=null?j:1,ne=(M=(L=U.scale)==null?void 0:L.y)!=null?M:te;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:G,visible:B.visible,contentLayerScale:{x:te,y:ne},position:{x:J+H,y:Z+ae}}),{scale:{x:te,y:ne},position:{x:J+H,y:Z+ae},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let t=window.__mainContainer;if(t){let F=(I=(R=t.scale)==null?void 0:R.x)!=null?I:1,G=(C=(E=t.scale)==null?void 0:E.y)!=null?C:F;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:F,y:G},position:{x:(A=t.position)==null?void 0:A.x,y:(S=t.position)==null?void 0:S.y}}),t}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=(O=i.scale)==null?void 0:O.y)!=null?z:F;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:F,y:G},position:{x:(D=i.position)==null?void 0:D.x,y:(q=i.position)==null?void 0:q.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeScale(){var n,i;let e=this.getRuntimeLayoutReference(),t=Number((i=(n=e==null?void 0:e.scale)==null?void 0:n.x)!=null?i:1);return Number.isFinite(t)&&t>0?t:Number.isFinite(this.layoutScale)&&this.layoutScale>0?this.layoutScale:1}getRuntimeParentContainer(e){var c,d,p,u,g;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((c=n==null?void 0:n.getDisplayObject)==null?void 0:c.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.parent;if(!a)return null;let r=window.__screenManager;if(r){let h=["gameplay","start","tutorial","endgame","loading"];for(let f of h){let m=(d=r.get)==null?void 0:d.call(r,f);if(!m)continue;let b=(u=(p=m.getBgLayer)==null?void 0:p.call(m))!=null?u:m.bgLayer;if(b&&(a===b||typeof b.contains=="function"&&b.contains(a)))return this.bgContainer}}let o=this.getRuntimeLayoutReference(),l=(g=window.gameApp)==null?void 0:g.stage;return o&&l&&o===l?this.mainContainer:o&&typeof o.contains=="function"&&o.contains(a)?this.mainContainer:a===o||a===l?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,f;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 m=Number((g=(u=e.pivot)==null?void 0:u.x)!=null?g:0),b=Number((f=(h=e.pivot)==null?void 0:h.y)!=null?f:0);Number.isFinite(m)&&Number.isFinite(b)&&(this.mainContainer.pivot.set(m,b),this.uiContainer.pivot.set(m,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.playModeEnabled?this.getRuntimeParentContainer(e):null,l=this.isBackgroundObject(e,t)?this.bgContainer:a?this.uiContainer:this.mainContainer,c=r!=null?r:l;if(!i||i.assetKey!==n||i.isUi!==a){i&&this.removeObject(e);let p=await this.createDisplayObject(e,t);if(!p)return;c.addChild(p),this.objectMap.set(e,{id:e,displayObject:p,assetKey:n,isUi:a}),this.attachObjectInteraction(p,e)}let d=this.objectMap.get(e);d&&(d.displayObject.parent!==c&&c.addChild(d.displayObject),this.applyVisualConfig(d.displayObject,t),this.playModeEnabled||this.applyTransformFromConfig(e,d.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,f,m,b,y,v,w,T;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let j=await ye.create(e,t,this.app);if(j instanceof $.Container)return j}}catch(P){console.warn("[SceneEditor] ObjectFactory failed for",e,P)}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 P=this.getScreen(),j=(p=P==null?void 0:P.width)!=null?p:0,L=(u=P==null?void 0:P.height)!=null?u:0,M=new $.Graphics,R=this.parseColor(i.background_color,0),I=typeof i.background_alpha=="number"?i.background_alpha:1;j>0&&L>0&&M.rect(0,0,j,L).fill({color:R,alpha:I});let E=new $.Container;return E.addChild(M),E}if(a){let P=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",j=new $.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(f=n==null?void 0:n.fontSize)!=null?f:16,fill:P,align:(m=n==null?void 0:n.align)!=null?m:"center",letterSpacing:(b=n==null?void 0:n.letterSpacing)!=null?b:0});return new $.Text({text:(y=n==null?void 0:n.text)!=null?y:"",style:j})}if((v=t==null?void 0:t.effects)!=null&&v.width||(w=t==null?void 0:t.effects)!=null&&w.height){let P=new $.Graphics,j=typeof t.effects.width=="number"?t.effects.width:100,L=typeof t.effects.height=="number"?t.effects.height:100,M=(T=t.effects.fill_color)!=null?T:"#ffffff",R=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,I=Number.parseInt(String(M).replace("#",""),16);return P.rect(0,0,j,L).fill({color:Number.isFinite(I)?I:16777215,alpha:R}),P}return new $.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 $.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")}isBackgroundObject(e,t,n){var r,o;if((n==null?void 0:n.parent)===this.bgContainer)return!0;let i=(((r=t==null?void 0:t.identity)==null?void 0:r.category)||"").toString().toLowerCase(),a=(((o=t==null?void 0:t.identity)==null?void 0:o.id)||e||"").toString().toLowerCase();return!!(i.includes("bg")||i.includes("background")||a.startsWith("background_")||a.includes("background"))}applyVisualConfig(e,t){var a,r,o;if(!e)return;let n=(a=t==null?void 0:t.render)!=null?a:{};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={x:.5,y:.5};if((r=e.anchor)!=null&&r.set)e.anchor.set(i.x,i.y);else if(e.pivot){let l=(o=e.getLocalBounds)==null?void 0:o.call(e);l&&e.pivot.set(l.width*i.x,l.height*i.y)}}applyTransformFromConfig(e,t,n){var j,L,M,R,I,E,C,A,S,x,_,k,O,z,D,q,F,G,B,U,J;if(!t)return;let i=this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return;let a=(j=n==null?void 0:n.transform)!=null?j:{},r=this.getPositioningAnchor(e,a),o=a==null?void 0:a.position_ratio,l=a==null?void 0:a.position,c=a==null?void 0:a.offset,d=Array.isArray(l)?Number((L=l[0])!=null?L:0):Number((M=l==null?void 0:l.x)!=null?M:0),p=Array.isArray(l)?Number((R=l[1])!=null?R:0):Number((I=l==null?void 0:l.y)!=null?I:0),u=Array.isArray(c)?Number((E=c[0])!=null?E:0):Number((C=c==null?void 0:c.x)!=null?C:0),g=Array.isArray(c)?Number((A=c[1])!=null?A:0):Number((S=c==null?void 0:c.y)!=null?S:0),h=(Number.isFinite(d)?d:0)+(Number.isFinite(u)?u:0),f=(Number.isFinite(p)?p:0)+(Number.isFinite(g)?g:0);if(this.backgroundCoverEnabled&&this.isBackgroundObject(e,n,t)){let Z=Number((_=(x=t==null?void 0:t.texture)==null?void 0:x.width)!=null?_:0),H=Number((O=(k=t==null?void 0:t.texture)==null?void 0:k.height)!=null?O:0);if(!Number.isFinite(Z)||Z<=0||!Number.isFinite(H)||H<=0){let ge=(z=t==null?void 0:t.getLocalBounds)==null?void 0:z.call(t);Z=Number((D=ge==null?void 0:ge.width)!=null?D:0),H=Number((q=ge==null?void 0:ge.height)!=null?q:0)}if(!Number.isFinite(Z)||Z<=0||!Number.isFinite(H)||H<=0)return;(F=t.anchor)!=null&&F.set&&t.anchor.set(.5,.5),(G=t.position)!=null&&G.set?t.position.set(i.width/2,i.height/2):t.position&&(t.position.x=i.width/2,t.position.y=i.height/2);let ae=i.width/Z,te=i.height/H,ne=Math.max(ae,te);(B=t.scale)!=null&&B.set?t.scale.set(ne,ne):t.scale&&(t.scale.x=ne,t.scale.y=ne);let je=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(je);return}let m=o!=null?ct(i.width,i.height,o):ze(i.width,i.height,r),b=this.getRuntimeScale(),y=(m.x-i.width/2)/b+h,v=(m.y-i.height/2)/b+f;(U=t.position)!=null&&U.set?t.position.set(y,v):t.position&&(t.position.x=y,t.position.y=v);let T=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*this.getRuntimeScale();(J=t.scale)!=null&&J.set?t.scale.set(T,T):t.scale&&(t.scale.x=T,t.scale.y=T);let P=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(P)}getAnchorLocalPoint(e,t=this.mainContainer){var d;let n=(d=this.getRuntimeScreenSize())!=null?d:this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let i="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),r=(e==null?void 0:e.position_ratio)!=null?ct(n.width,n.height,e.position_ratio):ze(n.width,n.height,a!=null?a:i);if(t===this.bgContainer)return new $.Point(r.x,r.y);let o=this.getRuntimeScale(),l=(r.x-n.width/2)/o,c=(r.y-n.height/2)/o;return new $.Point(l,c)}getPositioningAnchor(e,t){var n,i,a,r,o,l,c,d,p,u;if((t==null?void 0:t.anchor)!=null&&t.anchor!=="")return t.anchor;if(typeof window!="undefined"&&e){let g=window,h=g.__editableConfig,f=(i=(n=h==null?void 0:h.objects)==null?void 0:n.get)==null?void 0:i.call(n,e),m=(o=(a=f==null?void 0:f.transform)==null?void 0:a.anchor)!=null?o:(r=f==null?void 0:f.render)==null?void 0:r.anchor;if(m!=null&&m!=="")return m;let b=g.__editableConfigBaseline,y=(c=(l=b==null?void 0:b.objects)==null?void 0:l.get)==null?void 0:c.call(l,e),v=(u=(d=y==null?void 0:y.transform)==null?void 0:d.anchor)!=null?u:(p=y==null?void 0:y.render)==null?void 0:p.anchor;if(v!=null&&v!=="")return v}return"top-left"}getActiveScreenSize(e){var t,n;return this.playModeEnabled?(n=(t=this.getRuntimeScreenSize())!=null?t:e)!=null?n:this.getScreen():e!=null?e:this.getScreen()}updateLayout(e){var n,i,a,r,o,l,c,d,p;let t=this.getActiveScreenSize(e);if(!(!(t!=null&&t.width)||!(t!=null&&t.height))){if(console.log("[SceneEditor] updateLayout: called",{screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.playModeEnabled){let u=this.getRuntimeLayoutReference();if(u){let g=Number((i=(n=u.position)==null?void 0:n.x)!=null?i:t.width/2),h=Number((r=(a=u.position)==null?void 0:a.y)!=null?r:t.height/2);this.mainContainer.position.set(g,h),this.uiContainer.position.set(g,h);let f=Number((l=(o=u.scale)==null?void 0:o.x)!=null?l:1);Number.isFinite(f)&&f>0&&(this.layoutScale=f)}this.bgContainer.position.set(0,0),this.bgContainer.scale.set(1,1),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1)}else this.bgContainer.position.set(0,0),this.bgContainer.scale.set(1,1),this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.rotation=0,this.uiContainer.rotation=0,(c=this.mainContainer.pivot)!=null&&c.set&&this.mainContainer.pivot.set(0,0),(d=this.uiContainer.pivot)!=null&&d.set&&this.uiContainer.pivot.set(0,0);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),(p=this.app)!=null&&p.stage&&(this.app.stage.hitArea=new $.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 $.Point(0,0)),i=this.camera.toLocal(new $.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,f=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let m=h;m<=r;m+=u)this.gridLayer.moveTo(m,o),this.gridLayer.lineTo(m,l);for(let m=f;m<=l;m+=g)this.gridLayer.moveTo(a,m),this.gridLayer.lineTo(r,m);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){let t=this.getActiveScreenSize(e);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,p;if(!this.app||!this.isVisible)return;let e=window.gameObjectManager;if(!(e!=null&&e.get))return;let t=this.dragMode||this.selectedId&&performance.now()<this.dragSyncHoldUntil?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(t&&u===t)continue;let h=e.get(u),f=((n=h==null?void 0:h.getDisplayObject)==null?void 0:n.call(h))||(h==null?void 0:h.pixiObject)||h;if(!f)continue;let m=(a=(i=g.displayObject)==null?void 0:i.parent)!=null?a:this.mainContainer,b=new $.Point;if(typeof f.getGlobalPosition=="function"){f.getGlobalPosition(b);let P=m.toLocal(b,this.camera);g.displayObject.position.set(P.x,P.y)}else if(f.worldTransform){b.set(f.worldTransform.tx,f.worldTransform.ty);let P=m.toLocal(b,this.camera);g.displayObject.position.set(P.x,P.y)}let y=this.getWorldScale(f);if(y){let P=Number((o=(r=m.scale)==null?void 0:r.x)!=null?o:1)||1,j=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,L=y.x/P,M=y.y/j;(d=g.displayObject.scale)!=null&&d.set?g.displayObject.scale.set(L,M):g.displayObject.scale&&(g.displayObject.scale.x=L,g.displayObject.scale.y=M)}let v=this.getWorldRotation(f);if(typeof v=="number"){let P=m?m.rotation:0,j=v-P;g.displayObject.rotation=j;let L=this.getEditableObjectConfig(u);if(L){let M=(p=L.transform)!=null?p:{};L.transform||(L.transform=M);let R=this.toDegrees(j),I=typeof M.rotation=="number"?M.rotation:0;if(Math.abs(R-I)>.01){let E=Math.round(R*100)/100;M.rotation=E}}}let w=f.parent,T=typeof(w==null?void 0:w.getChildIndex)=="function"?w.getChildIndex(f):0;typeof f.zIndex=="number"?g.displayObject.zIndex=f.zIndex:Number.isFinite(T)&&(g.displayObject.zIndex=T)}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(){if(!this.app)return;let e=this.getActiveScreenSize();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 f,m;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=(m=(f=e.displayObject).getBounds)==null?void 0:m.call(f);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new $.Point(t.x,t.y)),i=this.camera.toLocal(new $.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});let c=7,d={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(o,l,c).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(d),this.moveHandle.cursor="move";let p=n.x+a,u=n.y+r;this.scaleHandle.clear(),this.scaleHandle.rect(p-c,u-c,c*2,c*2).fill({color:3718648,alpha:.95}),this.scaleHandle.stroke(d),this.scaleHandle.cursor="nwse-resize";let g=o,h=n.y-c*2;this.rotateHandle.clear(),this.rotateHandle.circle(g,h,c).fill({color:16347926,alpha:.95}),this.rotateHandle.stroke(d),this.rotateHandle.cursor="crosshair"}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 $.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="static",a.on("pointerdown",o=>this.startSpawnPointDrag(i,o)),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 $.Point(e.x,e.y)),n=new $.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 $.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){var d,p,u,g,h,f,m;if(!this.selectedId)return;let n=this.objectMap.get(this.selectedId);if(!(n!=null&&n.displayObject))return;let i=this.getEditableObjectConfig(this.selectedId);if(!i||this.backgroundLocked&&this.isBackgroundObject(this.selectedId,i,n.displayObject))return;let a=(d=i.transform)!=null?d:{},r=(p=n.displayObject.parent)!=null?p:this.mainContainer,o=this.getEventLocalPoint(t,r);if(!o)return;(u=t==null?void 0:t.stopPropagation)==null||u.call(t),(g=t==null?void 0:t.stopImmediatePropagation)==null||g.call(t);let l=this.getPositioningAnchor(this.selectedId,a);(a.anchor==null||a.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"transform.anchor",l),(((h=i==null?void 0:i.render)==null?void 0:h.anchor)==null||i.render.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"render.anchor",l),this.dragMode=e,this.dragContainer=r,this.dragStartPointer=new $.Point(o.x,o.y),this.dragStartPos=new $.Point(n.displayObject.position.x,n.displayObject.position.y),this.dragLastPointer=new $.Point(o.x,o.y),this.dragPointerOffset=new $.Point(n.displayObject.position.x-o.x,n.displayObject.position.y-o.y),this.dragLogged=!1;let c=(f=this.getRuntimeScreenSize())!=null?f:this.getScreen();console.log("[SceneEditor][DragStart]",{objectId:this.selectedId,mode:e,isBackground:this.isBackgroundObject(this.selectedId,i,n.displayObject),screen:c,runtimeScale:this.getRuntimeScale(),pointer:{x:o.x,y:o.y},objectPos:{x:n.displayObject.position.x,y:n.displayObject.position.y},container:r===this.bgContainer?"bg":r===this.uiContainer?"ui":"main"}),this.dragStartScale=typeof((m=n.displayObject.scale)==null?void 0:m.x)=="number"?n.displayObject.scale.x:1,this.dragStartRotation=typeof n.displayObject.rotation=="number"?n.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,r),this.dragStartValue=this.getDragStartValue(e,a),this.dragAnchorLocal&&(this.dragStartAngle=Math.atan2(o.y-this.dragAnchorLocal.y,o.x-this.dragAnchorLocal.x),this.dragStartDistance=Math.max(1,this.distance(o,this.dragAnchorLocal))),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}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 w,T,P,j,L,M,R,I;if(!this.selectedId)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=(w=n.transform)!=null?w:{};n.transform||(n.transform=i);let a=(T=this.getRuntimeScreenSize())!=null?T:this.getScreen();if(!(a!=null&&a.width)||!(a!=null&&a.height))return;let r=this.objectMap.get(this.selectedId),o=((P=r==null?void 0:r.displayObject)==null?void 0:P.parent)===this.bgContainer,l=this.getPositioningAnchor(this.selectedId,i),c=(i==null?void 0:i.position_ratio)!=null?ct(a.width,a.height,i.position_ratio):ze(a.width,a.height,l),d=c.x,p=c.y,u=e,g=t;if(!o){let E=this.getRuntimeScale();d=(c.x-a.width/2)/E,p=(c.y-a.height/2)/E,u=e/E,g=t/E}let h=u-d,f=g-p,m=(j=i.offset)!=null?j:{x:0,y:0},b=Array.isArray(m)?Number((L=m[0])!=null?L:0):Number((M=m==null?void 0:m.x)!=null?M:0),y=Array.isArray(m)?Number((R=m[1])!=null?R:0):Number((I=m==null?void 0:m.y)!=null?I:0),v=this.buildPositionValue(i,{x:h-b,y:f-y});this.updateManager.updateProperty(this.selectedId,"transform.position",v,{refreshInspector:!0})}updateLiveConfigScale(e){var a;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(a=t.transform)!=null?a:{};t.transform||(t.transform=n);let i=Math.round(e*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.scale",i,{refreshInspector:!0})}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;if(Math.abs(i-a)>.01){let o=Math.round(i*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.rotation",o,{refreshInspector:!0})}}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),re({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),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}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 $.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 $.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 $.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 $.Point;return t.toLocal(new $.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 $.Point;return n.toLocal(new $.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=[Qe("playable-portrait"),Qe("iphone-14"),Qe("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=Qe(e.defaultDevice||Ln.id),this.debugPanel=new Ut,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=Qe(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,f=p-g-200;return Math.max(200,f)},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 f=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",m=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",b=400;g.style.gridTemplateColumns=`${f} minmax(${b}px, 1fr) ${m}`}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&&et(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=`
2308
2308
  <div class="preview-toolbar">
2309
2309
  <div class="preview-toolbar-left">
2310
2310
  <span class="preview-logo">PREVIEWER</span>
@@ -2496,7 +2496,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2496
2496
  </div>
2497
2497
 
2498
2498
  </div>
2499
- `,this.setupEventListeners(e),e}setupEventListeners(e){var I,_,L,M,O,P,E,C;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",A=>{if(this.viewMode==="compare")return;let S=A.target.value;this.setDevice(S)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",A=>{let S=A.target.value;this.setTheme(S)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.viewToggle;S&&this.setViewMode(S)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.layoutToggle;S&&this.setLayoutMode(S)})});let r=e.querySelector("#scene-toggle");r==null||r.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=A=>{let S=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${A}::${S}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(A,S,x)=>{A&&(A.textContent=S?`${x} On`:`${x} Off`,A.setAttribute("aria-pressed",S?"true":"false"))},u=()=>{let A=window.localStorage.getItem(l("grid_gap")),S=Number(A!=null?A:50);return Number.isFinite(S)?S:50},g=A=>{try{window.localStorage.setItem(l("grid_enabled"),A?"true":"false")}catch{}p(c,A,"Grid");let S=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:S}}))},h=A=>{try{window.localStorage.setItem(l("play_mode"),A?"true":"false")}catch{}p(d,A,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:A}}))};try{let A=window.localStorage.getItem(l("grid_enabled"))==="true",S=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(p(c,A,"Grid"),p(d,S,"Play"),d&&(d.disabled=!0),c){let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:S}}))}catch{}c==null||c.addEventListener("click",()=>{let A=c.getAttribute("aria-pressed")==="true";g(!A)}),d==null||d.addEventListener("click",()=>{let A=d.getAttribute("aria-pressed")==="true";h(!A)}),(I=e.querySelector("#rotate-btn"))==null||I.addEventListener("click",()=>this.toggleRotation()),(_=e.querySelector("#zoom-in-btn"))==null||_.addEventListener("click",()=>this.adjustUserZoom(.1)),(L=e.querySelector("#zoom-out-btn"))==null||L.addEventListener("click",()=>this.adjustUserZoom(-.1)),(M=e.querySelector("#refresh-btn"))==null||M.addEventListener("click",()=>this.refresh());let f=e.querySelector("#bottom-dock"),m=e.querySelector("#bottom-dock-resize");f&&m&&this.makeBottomDockResizable(f,m);let b=Array.from(e.querySelectorAll(".bottom-dock-tab"));b.forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.dockTab;if(!S)return;b.forEach(j=>j.classList.remove("active")),A.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(j=>{let k=j.dataset.dockPanel;j.classList.toggle("active",k===S)})})}),(O=e.querySelector("#console-clear"))==null||O.addEventListener("click",()=>this.clearConsole()),(P=e.querySelector("#corner-zoom-in-btn"))==null||P.addEventListener("click",()=>this.adjustUserZoom(.1)),(E=e.querySelector("#corner-zoom-out-btn"))==null||E.addEventListener("click",()=>this.adjustUserZoom(-.1)),(C=e.querySelector("#corner-grab-btn"))==null||C.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let y=e.querySelector(".scene-panel.scene-objects"),v=y==null?void 0:y.querySelector("[data-panel-resize-v]");y&&v&&this.makeSidebarResizable(y,v,"left");let w=e.querySelector(".debug-workbench"),T=w==null?void 0:w.querySelector("#workbench-resize-v");w&&T&&this.makeSidebarResizable(w,T,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=i/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(r,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let n=this.gameViewPane||this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),bn();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),yn();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=De().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,n;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(n=(t=this.options).onDeviceChange)==null||n.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(r=>typeof r=="object"?this.safeStringify(r):String(r)).join(" ");this.consoleMessages.push({type:t,message:i,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let r=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=r>0?`${r}!`:"0",a.classList.toggle("has-errors",r>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(p=>p.id===n);if(!i)return;let a=t.querySelector("[data-compare-slot]"),r=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!r||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:r,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let n=this.container.querySelector("#rotate-btn");n&&(n.disabled=e==="compare");let i=this.container.querySelector("#scene-toggle");if(i&&(i.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,r=i/e.preset.height,o=Math.max(.01,Math.min(a,r));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,r=t.canvas.height,o=Math.min(a/n.width,r/n.height),l=n.width*o,c=n.height*o,d=(a-l)/2,p=(r-c)/2;i.clearRect(0,0,a,r),i.drawImage(n,d,p,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let n=this.gameViewPane||this.previewContainer;return{width:n.clientWidth-40,height:n.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function Ra(s={}){let e=new di(s);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ee();function za(s){try{if(s&&typeof s.keys=="function")return Array.from(s.keys())}catch{}return[]}function _r(s){var e;return s?((e=s.getDisplayObject)==null?void 0:e.call(s))||s.pixiObject||s:null}function wl(s,e){if(!s||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);s.eventMode=n?"static":"none",s.interactive=n,n&&(s.cursor=t.draggable?"move":"pointer")}function jr(s,e){var d,p,u;if(!s||!e)return;let t=e.transform||{};wl(s,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0),o=333,l=111;a+=o,r+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,r,"(raw + 333, +111)"),(d=s.position)!=null&&d.set?s.position.set(a,r):(typeof s.x=="number"&&(s.x=a),typeof s.y=="number"&&(s.y=r)),typeof t.scale=="number"&&((p=s.scale)!=null&&p.set?s.scale.set(t.scale):s.scale&&(s.scale.x=t.scale,s.scale.y=t.scale));let c=t.anchor;if(c&&((u=s.anchor)!=null&&u.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&s.anchor.set(g.x,g.y)}}function Or(s){if(typeof window=="undefined")return;let e=s==null?void 0:s.objects,t=za(e),n=a=>{var r;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(r=l==null?void 0:l.screenToInstances)==null?void 0:r[o];if(Array.isArray(c)&&c.length>0){let p=new Set(c);return a.filter(u=>p.has(u))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(p=>d[p]===o):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Or(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(za((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return za((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,f,m;let r=(h=(g=(u=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:u.get)==null?void 0:g.call(u,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(f=l==null?void 0:l.screenToInstances)==null?void 0:f[o];if(Array.isArray(c))return c.includes(a)?r:null;let d=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[a];return d&&d===o?r:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return a}}function xl(){if(typeof window=="undefined")return;let s=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,r,o;let i=s(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(lt(),Is))]),d=Date.now(),p=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${d}`:`?t=${d}`),u=await l.load(p);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let h=window.gameObjectManager,f=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(f){let m=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(m!=null&&m.texture)m.texture=u;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=se();Array.isArray(n)&&n.length&&(window.__editableConfig=t,$e(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=se();Array.isArray(n)&&n.length&&(window.__editableConfig=t,$e(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,r]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:r});if(t.assets)for(let[a,r]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:r}),typeof r=="string"&&e(a,r);if(t.splash)for(let[a,r]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:r});if(t.loading)for(let[a,r]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:r});if(t.start)for(let[a,r]of Object.entries(t.start))i.push({path:`start.${a}`,value:r});i.length&&$e(i,{silent:!0,persist:!0,emitEvent:!0})}}function pi(s){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=s;t&&(t.onObjectRebuildRequired=async(a,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let p=window.gameApp,u=await ye.create(a,r,p);c&&(d!==void 0&&d!==-1?c.addChildAt(u,d):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(xl(),window.applyEditableObjectConfig=(a,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let p=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!p),p&&(console.log("[LIVE-EDIT] gameObject type:",(c=p.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof p.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof p.onConfigUpdate=="function")),p&&typeof p.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),p.updateConfig(r);else if(p&&typeof p.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),p.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=_r(p);jr(u,r)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let i={async applyObjectConfig(a,r){var d,p;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(p=t==null?void 0:t.get)==null?void 0:p.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(r);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=_r(l);jr(u,r)}let c=[a];n==null||n(a,r,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Or(a))}};return i.rebuildIndexes(),i}ee();var $r=at(require("lottie-web"),1);Ti(Li);typeof window!="undefined"&&!window.lottie&&(window.lottie=$r.default);var mt=null,Sl=async()=>{if(!mt){let s=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(s==null?void 0:s["handler.config"])||(s==null?void 0:s["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);mt=JSON.parse(n)}else mt=JSON.parse(e);return mt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}mt=await(await fetch("./handler.config.json")).json()}return mt},Na,Wt,Dr,bt,$a,Da;function El(s){Na=s.initGame,Wt=s.CustomAssets,Dr=s.updateScreenState,bt=s.globalResponsiveMultipliers,$a=s.layout,Da=s.clearResponsiveElements}var ui="web_embed",Vt="https://example.com",Rr={profile_id:ui},Ge=null,xe=null,qt={width:0,height:0},Cl=!0,Al=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let s=await Sl();Rr={...s.ids||{},profile_id:ui},Vt=s.destination_url||((d=(c=s.export_profiles)==null?void 0:c[ui])==null?void 0:d.destination_url)||Vt,qe.init({ids:Rr,profile:ui,destinationUrl:Vt});let e=qe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),xe=Ra({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),zr()},onRefresh:zr});let g=xe.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,w,T,I,_,L,M,O,P,E,C,A,S;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(qt.width=b,qt.height=y,Dr(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let x=f.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&m&&$a)try{let x=(v=window.__mainContainer)!=null?v:f.stage,j=(M=(L=(I=window.__tutorialLabel)!=null?I:(T=(w=m.get("label_1"))==null?void 0:w.getDisplayObject)==null?void 0:T.call(w))!=null?L:(_=m.get("label_1"))==null?void 0:_.pixiObject)!=null?M:m.get("label_1"),k=m.get("background_1"),R=(C=(E=(P=window.__background)!=null?P:(O=k==null?void 0:k.getDisplayObject)==null?void 0:O.call(k))!=null?E:k==null?void 0:k.pixiObject)!=null?C:k;if(x){let z=x===f.stage;$a({mainContainer:x,label:j,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:f},t,0,qt,m,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:qt.width,height:qt.height,presetId:(S=(A=h.detail)==null?void 0:A.presetId)!=null?S:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Pe("scene.main");window.__editableConfig=t,r(),window.__editableConfigBaseline||(window.__editableConfigBaseline=Q(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(p=t.engine.runtime)==null?void 0:p.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await Pe("scene.main"));let n=await Na(e,t,Vt,xe);Ge=n.app;let i=n.gameObjectManager;window.gameApp=Ge,window.gameObjectManager=i;try{window.__liveEditBridge=pi({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:Wt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}xe&&xe.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(bt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Ge,i);async function r(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,w=await fetch(v,{cache:"no-cache"});if(!w.ok)return null;let T=await w.text();try{return JSON.parse(T)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let f=h.screens;if(!f||typeof f!="object")return;let m={},b={};for(let[y,v]of Object.entries(f)){let w=v==null?void 0:v.source;if(typeof w!="string")continue;let T=await g(w),I=T==null?void 0:T.elements;if(!Array.isArray(I))continue;let _=I.map(L=>L==null?void 0:L.instance_id).filter(L=>typeof L=="string");m[y]=_;for(let L of _)b[L]||(b[L]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Cl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${bt.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((w,T)=>{if(w&&w.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(w&&w.scale){let I=w.scale.x||1,_=w.scale.y||1;w.__originalScale||(w.__originalScale={x:I,y:_},console.log(`${v}[RESPONSIVE] Stored original scale for child[${T}]: ${I.toFixed(3)}, ${_.toFixed(3)}`));let L=w.__originalScale.x*bt.scale,M=w.__originalScale.y*bt.scale;typeof w.scale.set=="function"?w.scale.set(L,M):(w.scale.x=L,w.scale.y=M),console.log(`${v}[RESPONSIVE] Child[${T}] scale: ${I.toFixed(3)}\u2192${w.scale.x.toFixed(3)} (type: ${w.constructor.name})`),m(w,y+1)}else w&&console.log(`${v}[RESPONSIVE] Child[${T}] has no scale (type: ${w.constructor.name})`)})};var f=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){bt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,f=window.gameObjectManager;h&&f?(o(h,f),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,qe.start()},zr=async()=>{var e,t,n,i;console.log("[PREVIEW] Restarting game in 1 seconds...");let s=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(s){let a=((t=s.getDisplayObject)==null?void 0:t.call(s))||s;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(xe){xe.notifyGameDestroyed();try{Da&&Da()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=xe.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),Ge){try{Ge.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Ge=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Wt.resetScene=="function"&&Wt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Pe("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Q(o)),Na(a,o,Vt).then(l=>{Ge=l.app,window.gameApp=Ge,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=pi({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Wt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}xe&&xe.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{qe.start()}catch{}})})},100)},1e3)}};An();ee();var Se={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Nr=1.25,Hr={fontFamily:"Inter, system-ui, sans-serif"};var gi=class{constructor(e={}){this.currentProgress=0;var t;this.currentProgress=(t=e.progress)!=null?t:0,this.container=this.createContainer()}createContainer(){let e=document.createElement("div");e.className="handler-loading-screen",e.style.cssText=`
2499
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var P,j,L,M,R,I,E,C;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",A=>{if(this.viewMode==="compare")return;let S=A.target.value;this.setDevice(S)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",A=>{let S=A.target.value;this.setTheme(S)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.viewToggle;S&&this.setViewMode(S)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.layoutToggle;S&&this.setLayoutMode(S)})});let r=e.querySelector("#scene-toggle");r==null||r.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=A=>{let S=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${A}::${S}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(A,S,x)=>{A&&(A.textContent=S?`${x} On`:`${x} Off`,A.setAttribute("aria-pressed",S?"true":"false"))},u=()=>{let A=window.localStorage.getItem(l("grid_gap")),S=Number(A!=null?A:50);return Number.isFinite(S)?S:50},g=A=>{try{window.localStorage.setItem(l("grid_enabled"),A?"true":"false")}catch{}p(c,A,"Grid");let S=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:S}}))},h=A=>{try{window.localStorage.setItem(l("play_mode"),A?"true":"false")}catch{}p(d,A,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:A}}))};try{let A=window.localStorage.getItem(l("grid_enabled"))==="true",S=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(p(c,A,"Grid"),p(d,S,"Play"),d&&(d.disabled=!0),c){let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:S}}))}catch{}c==null||c.addEventListener("click",()=>{let A=c.getAttribute("aria-pressed")==="true";g(!A)}),d==null||d.addEventListener("click",()=>{let A=d.getAttribute("aria-pressed")==="true";h(!A)}),(P=e.querySelector("#rotate-btn"))==null||P.addEventListener("click",()=>this.toggleRotation()),(j=e.querySelector("#zoom-in-btn"))==null||j.addEventListener("click",()=>this.adjustUserZoom(.1)),(L=e.querySelector("#zoom-out-btn"))==null||L.addEventListener("click",()=>this.adjustUserZoom(-.1)),(M=e.querySelector("#refresh-btn"))==null||M.addEventListener("click",()=>this.refresh());let f=e.querySelector("#bottom-dock"),m=e.querySelector("#bottom-dock-resize");f&&m&&this.makeBottomDockResizable(f,m);let b=Array.from(e.querySelectorAll(".bottom-dock-tab"));b.forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.dockTab;if(!S)return;b.forEach(_=>_.classList.remove("active")),A.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(_=>{let k=_.dataset.dockPanel;_.classList.toggle("active",k===S)})})}),(R=e.querySelector("#console-clear"))==null||R.addEventListener("click",()=>this.clearConsole()),(I=e.querySelector("#corner-zoom-in-btn"))==null||I.addEventListener("click",()=>this.adjustUserZoom(.1)),(E=e.querySelector("#corner-zoom-out-btn"))==null||E.addEventListener("click",()=>this.adjustUserZoom(-.1)),(C=e.querySelector("#corner-grab-btn"))==null||C.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let y=e.querySelector(".scene-panel.scene-objects"),v=y==null?void 0:y.querySelector("[data-panel-resize-v]");y&&v&&this.makeSidebarResizable(y,v,"left");let w=e.querySelector(".debug-workbench"),T=w==null?void 0:w.querySelector("#workbench-resize-v");w&&T&&this.makeSidebarResizable(w,T,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=i/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(r,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let n=this.gameViewPane||this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),bn();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),yn();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=De().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,n;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(n=(t=this.options).onDeviceChange)==null||n.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(r=>typeof r=="object"?this.safeStringify(r):String(r)).join(" ");this.consoleMessages.push({type:t,message:i,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let r=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=r>0?`${r}!`:"0",a.classList.toggle("has-errors",r>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(p=>p.id===n);if(!i)return;let a=t.querySelector("[data-compare-slot]"),r=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!r||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:r,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let n=this.container.querySelector("#rotate-btn");n&&(n.disabled=e==="compare");let i=this.container.querySelector("#scene-toggle");if(i&&(i.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,r=i/e.preset.height,o=Math.max(.01,Math.min(a,r));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,r=t.canvas.height,o=Math.min(a/n.width,r/n.height),l=n.width*o,c=n.height*o,d=(a-l)/2,p=(r-c)/2;i.clearRect(0,0,a,r),i.drawImage(n,d,p,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let n=this.gameViewPane||this.previewContainer;return{width:n.clientWidth-40,height:n.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function Ra(s={}){let e=new di(s);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ee();function za(s){try{if(s&&typeof s.keys=="function")return Array.from(s.keys())}catch{}return[]}function _r(s){var e;return s?((e=s.getDisplayObject)==null?void 0:e.call(s))||s.pixiObject||s:null}function wl(s,e){if(!s||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);s.eventMode=n?"static":"none",s.interactive=n,n&&(s.cursor=t.draggable?"move":"pointer")}function jr(s,e){var d,p,u;if(!s||!e)return;let t=e.transform||{};wl(s,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0),o=333,l=111;a+=o,r+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,r,"(raw + 333, +111)"),(d=s.position)!=null&&d.set?s.position.set(a,r):(typeof s.x=="number"&&(s.x=a),typeof s.y=="number"&&(s.y=r)),typeof t.scale=="number"&&((p=s.scale)!=null&&p.set?s.scale.set(t.scale):s.scale&&(s.scale.x=t.scale,s.scale.y=t.scale));let c=t.anchor;if(c&&((u=s.anchor)!=null&&u.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&s.anchor.set(g.x,g.y)}}function Or(s){if(typeof window=="undefined")return;let e=s==null?void 0:s.objects,t=za(e),n=a=>{var r;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(r=l==null?void 0:l.screenToInstances)==null?void 0:r[o];if(Array.isArray(c)&&c.length>0){let p=new Set(c);return a.filter(u=>p.has(u))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(p=>d[p]===o):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Or(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(za((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return za((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,f,m;let r=(h=(g=(u=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:u.get)==null?void 0:g.call(u,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(f=l==null?void 0:l.screenToInstances)==null?void 0:f[o];if(Array.isArray(c))return c.includes(a)?r:null;let d=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[a];return d&&d===o?r:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return a}}function xl(){if(typeof window=="undefined")return;let s=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,r,o;let i=s(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(lt(),Is))]),d=Date.now(),p=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${d}`:`?t=${d}`),u=await l.load(p);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let h=window.gameObjectManager,f=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(f){let m=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(m!=null&&m.texture)m.texture=u;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=se();Array.isArray(n)&&n.length&&(window.__editableConfig=t,$e(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=se();Array.isArray(n)&&n.length&&(window.__editableConfig=t,$e(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,r]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:r});if(t.assets)for(let[a,r]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:r}),typeof r=="string"&&e(a,r);if(t.splash)for(let[a,r]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:r});if(t.loading)for(let[a,r]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:r});if(t.start)for(let[a,r]of Object.entries(t.start))i.push({path:`start.${a}`,value:r});i.length&&$e(i,{silent:!0,persist:!0,emitEvent:!0})}}function pi(s){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=s;t&&(t.onObjectRebuildRequired=async(a,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let p=window.gameApp,u=await ye.create(a,r,p);c&&(d!==void 0&&d!==-1?c.addChildAt(u,d):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(xl(),window.applyEditableObjectConfig=(a,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let p=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!p),p&&(console.log("[LIVE-EDIT] gameObject type:",(c=p.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof p.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof p.onConfigUpdate=="function")),p&&typeof p.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),p.updateConfig(r);else if(p&&typeof p.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),p.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=_r(p);jr(u,r)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let i={async applyObjectConfig(a,r){var d,p;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(p=t==null?void 0:t.get)==null?void 0:p.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(r);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=_r(l);jr(u,r)}let c=[a];n==null||n(a,r,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Or(a))}};return i.rebuildIndexes(),i}ee();var $r=at(require("lottie-web"),1);Ti(Li);typeof window!="undefined"&&!window.lottie&&(window.lottie=$r.default);var mt=null,Sl=async()=>{if(!mt){let s=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(s==null?void 0:s["handler.config"])||(s==null?void 0:s["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);mt=JSON.parse(n)}else mt=JSON.parse(e);return mt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}mt=await(await fetch("./handler.config.json")).json()}return mt},Na,Wt,Dr,bt,$a,Da;function El(s){Na=s.initGame,Wt=s.CustomAssets,Dr=s.updateScreenState,bt=s.globalResponsiveMultipliers,$a=s.layout,Da=s.clearResponsiveElements}var ui="web_embed",Vt="https://example.com",Rr={profile_id:ui},Ge=null,xe=null,qt={width:0,height:0},Cl=!0,Al=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let s=await Sl();Rr={...s.ids||{},profile_id:ui},Vt=s.destination_url||((d=(c=s.export_profiles)==null?void 0:c[ui])==null?void 0:d.destination_url)||Vt,qe.init({ids:Rr,profile:ui,destinationUrl:Vt});let e=qe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),xe=Ra({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),zr()},onRefresh:zr});let g=xe.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,w,T,P,j,L,M,R,I,E,C,A,S;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(qt.width=b,qt.height=y,Dr(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let x=f.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&m&&$a)try{let x=(v=window.__mainContainer)!=null?v:f.stage,_=(M=(L=(P=window.__tutorialLabel)!=null?P:(T=(w=m.get("label_1"))==null?void 0:w.getDisplayObject)==null?void 0:T.call(w))!=null?L:(j=m.get("label_1"))==null?void 0:j.pixiObject)!=null?M:m.get("label_1"),k=m.get("background_1"),O=(C=(E=(I=window.__background)!=null?I:(R=k==null?void 0:k.getDisplayObject)==null?void 0:R.call(k))!=null?E:k==null?void 0:k.pixiObject)!=null?C:k;if(x){let z=x===f.stage;$a({mainContainer:x,label:_,background:O,backgroundTexture:(O==null?void 0:O.texture)||null,app:f},t,0,qt,m,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:qt.width,height:qt.height,presetId:(S=(A=h.detail)==null?void 0:A.presetId)!=null?S:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Pe("scene.main");window.__editableConfig=t,r(),window.__editableConfigBaseline||(window.__editableConfigBaseline=Q(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(p=t.engine.runtime)==null?void 0:p.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await Pe("scene.main"));let n=await Na(e,t,Vt,xe);Ge=n.app;let i=n.gameObjectManager;window.gameApp=Ge,window.gameObjectManager=i;try{window.__liveEditBridge=pi({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:Wt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}xe&&xe.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(bt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Ge,i);async function r(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,w=await fetch(v,{cache:"no-cache"});if(!w.ok)return null;let T=await w.text();try{return JSON.parse(T)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let f=h.screens;if(!f||typeof f!="object")return;let m={},b={};for(let[y,v]of Object.entries(f)){let w=v==null?void 0:v.source;if(typeof w!="string")continue;let T=await g(w),P=T==null?void 0:T.elements;if(!Array.isArray(P))continue;let j=P.map(L=>L==null?void 0:L.instance_id).filter(L=>typeof L=="string");m[y]=j;for(let L of j)b[L]||(b[L]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Cl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${bt.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((w,T)=>{if(w&&w.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(w&&w.scale){let P=w.scale.x||1,j=w.scale.y||1;w.__originalScale||(w.__originalScale={x:P,y:j},console.log(`${v}[RESPONSIVE] Stored original scale for child[${T}]: ${P.toFixed(3)}, ${j.toFixed(3)}`));let L=w.__originalScale.x*bt.scale,M=w.__originalScale.y*bt.scale;typeof w.scale.set=="function"?w.scale.set(L,M):(w.scale.x=L,w.scale.y=M),console.log(`${v}[RESPONSIVE] Child[${T}] scale: ${P.toFixed(3)}\u2192${w.scale.x.toFixed(3)} (type: ${w.constructor.name})`),m(w,y+1)}else w&&console.log(`${v}[RESPONSIVE] Child[${T}] has no scale (type: ${w.constructor.name})`)})};var f=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){bt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,f=window.gameObjectManager;h&&f?(o(h,f),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,qe.start()},zr=async()=>{var e,t,n,i;console.log("[PREVIEW] Restarting game in 1 seconds...");let s=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(s){let a=((t=s.getDisplayObject)==null?void 0:t.call(s))||s;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(xe){xe.notifyGameDestroyed();try{Da&&Da()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=xe.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),Ge){try{Ge.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Ge=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Wt.resetScene=="function"&&Wt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Pe("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=Q(o)),Na(a,o,Vt).then(l=>{Ge=l.app,window.gameApp=Ge,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=pi({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Wt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}xe&&xe.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{qe.start()}catch{}})})},100)},1e3)}};An();ee();var Se={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Nr=1.25,Hr={fontFamily:"Inter, system-ui, sans-serif"};var gi=class{constructor(e={}){this.currentProgress=0;var t;this.currentProgress=(t=e.progress)!=null?t:0,this.container=this.createContainer()}createContainer(){let e=document.createElement("div");e.className="handler-loading-screen",e.style.cssText=`
2500
2500
  position: fixed;
2501
2501
  inset: 0;
2502
2502
  display: flex;