handler-playable-sdk 1.0.103 → 1.0.105

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 (42) hide show
  1. package/dist/{chunk-NOMTJOWU.js → chunk-5MZHT5UT.js} +2 -2
  2. package/dist/chunk-EOKPQFKK.js +1 -0
  3. package/dist/cli/brand-dna.mjs +1 -1
  4. package/dist/cli/canva-import.mjs +1 -1
  5. package/dist/cli/cleanup-assets.mjs +1 -1
  6. package/dist/cli/fix-scales.mjs +1 -1
  7. package/dist/cli/index.js +1 -1
  8. package/dist/cli/screen-helper.mjs +1 -1
  9. package/dist/cli/setup-library.mjs +1 -1
  10. package/dist/cli/student-helper/add-logic.mjs +1 -1
  11. package/dist/cli/student-helper/add-object.mjs +1 -1
  12. package/dist/cli/student-helper/arg-parsing.mjs +1 -1
  13. package/dist/cli/student-helper/asset-registry.mjs +1 -1
  14. package/dist/cli/student-helper/bullet-system.mjs +1 -1
  15. package/dist/cli/student-helper/collectable-system.mjs +1 -1
  16. package/dist/cli/student-helper/constants.mjs +1 -1
  17. package/dist/cli/student-helper/drag-snap-couples.mjs +1 -1
  18. package/dist/cli/student-helper/endgame-screen.mjs +1 -1
  19. package/dist/cli/student-helper/fs-io.mjs +1 -1
  20. package/dist/cli/student-helper/logic-defaults.mjs +1 -1
  21. package/dist/cli/student-helper/print-help.mjs +1 -1
  22. package/dist/cli/student-helper/prompts.mjs +1 -1
  23. package/dist/cli/student-helper/scratch-card.mjs +1 -1
  24. package/dist/cli/student-helper/screen-utils.mjs +1 -1
  25. package/dist/cli/student-helper/snippets.mjs +1 -1
  26. package/dist/cli/student-helper/start-screen.mjs +1 -1
  27. package/dist/cli/student-helper/swerve-collect.mjs +1 -1
  28. package/dist/cli/student-helper/tap-destroy.mjs +1 -1
  29. package/dist/cli/student-helper/template-packs.mjs +1 -1
  30. package/dist/cli/student-helper.mjs +1 -1
  31. package/dist/cli/sync-screens.mjs +1 -1
  32. package/dist/cli/validate-assets.mjs +1 -1
  33. package/dist/cli/validate.mjs +1 -1
  34. package/dist/{config-HQX4AQNX.js → config-M6BRZXRD.js} +1 -1
  35. package/dist/index.cjs +34 -34
  36. package/dist/index.js +1 -1
  37. package/dist/pixi/index.cjs +1 -1
  38. package/dist/pixi/index.js +1 -1
  39. package/dist/three/index.cjs +1 -1
  40. package/dist/three/index.js +1 -1
  41. package/package.json +1 -1
  42. package/dist/chunk-FOTLNUIS.js +0 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var oo=Object.create;var oi=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var po=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var we=(r,e)=>()=>(r&&(e=r(r=0)),e);var ot=(r,e)=>{for(var t in e)oi(r,t,{get:e[t],enumerable:!0})},ns=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of co(e))!uo.call(r,n)&&n!==t&&oi(r,n,{get:()=>e[n],enumerable:!(i=lo(e,n))||i.enumerable});return r};var lt=(r,e,t)=>(t=r!=null?oo(po(r)):{},ns(e||!r||!r.__esModule?oi(t,"default",{value:r,enumerable:!0}):t,r)),go=r=>ns(oi({},"__esModule",{value:!0}),r);var pe,pi=we(()=>{"use strict";pe=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()}};pe.store=new Map});function xo(){var r,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(r=document.querySelector("script"))==null?void 0:r.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),i=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!i)}catch{return!1}}async function So(){try{if(typeof window!="undefined"){let r=await fetch("./build-settings.json");if(r.ok){let e=await r.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Eo(){try{if(typeof window!="undefined"){let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Co(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${X}`),Object.keys(Te).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(Te)),Te;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),Te={...window.INLINE_ASSETS},Te;if(!(X==="publish"&&xe!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),Te;if(!Rn){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),Rn=(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 i=await t.text();console.log("[AssetLoader] Received JS code, length:",i.length);let n=i.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(n)try{let a=n[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}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:",i.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return Te=await Rn,console.log("[AssetLoader] Final inline assets cache:",Object.keys(Te)),Te}function zn(r){return r===null||typeof r!="object"||(Object.freeze(r),Object.values(r).forEach(e=>zn(e))),r}function Ao(r=64,e=64,t=16711680){let i=document.createElement("canvas");i.width=r,i.height=e;let n=i.getContext("2d");return n.fillStyle=`#${t.toString(16).padStart(6,"0")}`,n.fillRect(0,0,r,e),n.strokeStyle="#000",n.strokeRect(0,0,r,e),n.fillStyle="#fff",n.font="10px sans-serif",n.textAlign="center",n.fillText("MISSING",r/2,e/2),Ie.Texture.from(i)}function $n(r,e){zs.set(r,e)}var Ie,Os,Rs,Ke,X,xe,De,Te,Rn,zs,Xe,ui=we(()=>{"use strict";Ie=require("pixi.js");pi();Os=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Rs=xo(),Ke=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,X=Rs?"publish":Os,xe=Ke==null?void 0:Ke.assetsInlined;Ke!=null&&Ke.buildMode&&(X=Ke.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${X}`));De=Eo();De!=null&&De.buildMode&&(X=De.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${X}`));(De==null?void 0:De.assetsInlined)!==void 0&&(xe=De.assetsInlined);So().then(r=>{r!=null&&r.buildMode&&r.buildMode!==X&&(X=r.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${X}`)),(r==null?void 0:r.assetsInlined)!==void 0&&(xe=r.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Os}, Runtime: ${Rs?"publish":"dev"}, Effective: ${X}`);Te={},Rn=null;zs=new Map;Xe=class{static async load(e,t,i,n){let a=`${e}:${t.path}`,s=pe.get(a);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${X}`),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 Co(),l=o[e];if(!l&&n&&(l=o[n],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${n}`)),!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"),X==="publish"&&xe!==!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=zs.get(t.type);if(d)try{let p=await d(t.path,l,e,i);return pe.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=zn(p);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return pe.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}}static async loadImage(e,t){let i=X==="publish",n=i&&xe!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${X}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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 Ie.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 Ie.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Ie.Assets.load(e)}return await Ie.Assets.load(e)}static async loadJSON(e,t){let i=X==="publish",n=i&&xe!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${X}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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 s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}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,i){if(X==="dev"){let a=t==="image"?Ao():zn({__placeholder:!0,type:t});return pe.set(e+":"+((i==null?void 0:i.path)||"missing"),a),a}throw i}};$n("image",async(r,e)=>{let t=X==="publish",i=t&&xe!==!1,n=X==="brand",a=t&&xe===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${X}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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: ${r}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Ie.Assets.load(e)}let s=r;return(n||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),Ie.Assets.load(e||s)});$n("json",async(r,e)=>{let t=X==="publish",i=t&&xe!==!1,n=X==="brand",a=t&&xe===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${X}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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: ${r}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let s=r;if((n||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),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(s);if(!o.ok)throw new Error(`JSON fetch failed: ${r}`);return o.json()})});var Ds={};ot(Ds,{AssetTextures:()=>Ee,initAssetTextures:()=>Hn});function Hn(r,e){$s.init(r,e),typeof window!="undefined"&&(window.__AssetTextures=Ee)}var Nn,$s,Ee,ut=we(()=>{"use strict";ui();Nn=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(i=>{this.priorityReadyResolve=i}),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 s;console.log("[AssetTextures] Loading all assets...");let i=new Set(["background_loading_1"]),n=[],a=[];for(let[o,l]of e.objects.entries()){let c=(s=l.render)==null?void 0:s.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 Xe.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{}}};i.has(o)?n.push(d()):a.push(d())}n.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(n),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 n=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(n.length===0)return;this.ready().catch(()=>{});let a=()=>n.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let s=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(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:n}),o())},s)})}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())}},$s=new Nn,Ee=new Proxy($s,{get(r,e){return e in r&&typeof r[e]=="function"?r[e].bind(r):r.get(e)},set(r,e,t){return r.set(e,t),!0}})});var je={};ot(je,{applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>Ai,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Bs,configOverrideManager:()=>Gs,deepClone:()=>ee,exportConfigsAsJSON:()=>Jn,exportConfigsFromActiveCache:()=>Qe,getConfigOverrides:()=>oe,getConfigStateSummary:()=>Fe,getOverrideMode:()=>Nt,redoLastConfigChange:()=>Ci,removeConfigOverride:()=>Ht,resetToApplied:()=>Ft,resetToOriginal:()=>Li,setOverrideMode:()=>Xn,trackObjectCreation:()=>Us,trackObjectDeletion:()=>qs,undoLastConfigChange:()=>Ei});function wi(){return typeof window=="undefined"?null:window.__editableConfig||null}function Vn(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Un(r,e){var t,i;if(!r)return null;try{if(r instanceof Map)return(t=r.get(e))!=null?t:null;if(typeof r=="object")return(i=r[e])!=null?i:null}catch{}return null}function Zo(r,e,t){if(r){if(r instanceof Map){r.set(e,t);return}typeof r=="object"&&(r[e]=t)}}function Hs(r,e){for(let t of e)Dt(r,t.path,t.value)}function xi(r){var o;if(typeof window=="undefined")return;let e=wi();if(!e)return;let t=Vn(),i=(o=t?Un(t.objects,r):null)!=null?o:Un(e.objects,r);if(!i)return;let n=ee(i),a=oe().filter(l=>l.objectId===r);try{Hs(n,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",r,l);return}Zo(e.objects,r,n);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(r,n)}catch{}}function Yn(){var n;if(typeof window=="undefined")return;let r=wi();if(!(r!=null&&r.engine))return;let e=Vn(),t=ee(((n=e==null?void 0:e.engine)!=null?n:r.engine)||{}),i=oe().filter(a=>!a.objectId&&!a.sceneId);try{Hs(t,i)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=r.engine;for(let s of Object.keys(a))s in t||delete a[s];for(let[s,o]of Object.entries(t))a[s]=o}catch{r.engine=t}}function Qo(){if(typeof window=="undefined")return"unknown";let r=window;return typeof r.__HANDLER_PROJECT_ID=="string"?r.__HANDLER_PROJECT_ID:"handler-default"}function Wn(){return`handler_preview_config_overrides::${Qo()}`}function el(){if(typeof window=="undefined")return[];try{let r=window.localStorage.getItem(Wn());if(!r)return[];let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function Si(r){if(typeof window!="undefined")try{window.localStorage.setItem(Wn(),JSON.stringify(r))}catch{}}function Nt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Xn(r){if(typeof window!="undefined"){window.__enableConfigOverrides=r;try{window.localStorage.setItem(Fs,r?"true":"false")}catch{}}}function le(r,e={}){var u,g;let{objectId:t,path:i,value:n}=r,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=e,l=wi();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:i,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:i,value:n});let d;try{d=Vs(c,i),Dt(c,i,n)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:i,value:n},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:i,oldValue:d,newValue:n,ts:Date.now()}),h.length>Kn&&h.shift(),window.__configChangeRedo=[]}if(s){let h=oe(),f=h.findIndex(y=>y.objectId===t&&y.sceneId===r.sceneId&&y.path===i);f>=0?(console.log(`[CONFIG] Updating existing override at index ${f}:`,{objectId:t,path:i,oldValue:h[f].value,newValue:n}),h[f].value=n):(console.log("[CONFIG] Adding new override:",{objectId:t,path:i,value:typeof n=="string"?n.substring(0,50):n}),h.push(r)),window.__configOverrides=h,Si(h);let m=Wn(),b=typeof window!="undefined"?window.localStorage.getItem(m):null;if(b){let y=JSON.parse(b);y.find(v=>v.objectId===t&&v.path===i)?console.log(`[CONFIG] \u2705 Override persisted to localStorage successfully. Total overrides: ${y.length}`):console.error("[CONFIG] \u274C Override NOT found in localStorage after persist!")}else console.error(`[CONFIG] \u274C localStorage key ${m} is empty after persist!`);Nt()||(console.log("[CONFIG] Override mode was disabled, enabling it now to ensure overrides apply on reload"),Xn(!0))}a||console.log("[CONFIG] Applied override:",r),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:{...r,oldValue:d}}))}function He(r,e={}){let t=e.emitEvent!==!1,i=[];for(let n of r)n!=null&&n.objectId&&typeof n.objectId=="string"&&i.push(n.objectId),le(n,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let n=Array.from(new Set(i));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:n,count:r.length}}))}}function ge(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],Si([]),console.log("[CONFIG] Cleared all overrides")}function Bs(r){let e=oe().filter(i=>i.objectId!==r);window.__configOverrides=e,Si(e);let t=window.__configChanges||[];window.__configChanges=t.filter(i=>i.objectId!==r),xi(r),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:r}}))}function Ht(r,e){let t=oe().filter(n=>n.objectId!==r||n.path!==e);window.__configOverrides=t,Si(t);let i=window.__configChanges||[];window.__configChanges=i.filter(n=>n.objectId!==r||n.path!==e),r?xi(r):Yn(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:r,path:e}}))}function oe(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=el()),window.__configOverrides||[])}function Ei(){var a;if(typeof window=="undefined")return!1;let r=window.__configChanges||[];if(r.length===0)return!1;let e=r.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:s}=e.metadata||{};return e.objectId&&s&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:s})}).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:s,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&s&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:s,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 i=Vn(),n=!1;if(i){let s=e.objectId?Un(i.objects,e.objectId):i.engine;if(s){let o=Vs(s,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(n=!0)}}return n?Ht(e.objectId,e.path):(le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xi(e.objectId):Yn()),console.log("[CONFIG] Undo:",e.path),!0}function Ci(){var i;if(typeof window=="undefined")return!1;let r=window.__configChangeRedo||[];if(r.length===0)return!1;let e=r.pop();if(e.changeType==="object_create"){let{screenId:n,objectConfigId:a}=e.metadata||{},s=e.newValue;return e.objectId&&n&&s&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:e.objectId,objectConfigId:a||((i=s==null?void 0:s.identity)==null?void 0:i.id),config:s})}).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:n}=e.metadata||{};return e.objectId&&n&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:n})}).catch(s=>console.error("[CONFIG] Failed to delete object on redo:",s)),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}),le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xi(e.objectId):Yn(),console.log("[CONFIG] Redo:",e.path),!0}function Us(r,e,t){var n;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(n=t==null?void 0:t.identity)==null?void 0:n.id}}),window.__configChangeRedo=[],i.length>Kn&&i.shift(),console.log("[CONFIG] Tracked object creation:",r)}function qs(r,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],i.length>Kn&&i.shift(),console.log("[CONFIG] Tracked object deletion:",r)}function Dt(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(s=a[o])!=null?s:{},a=a[o]}a[n]=t}function Vs(r,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,r)}function ee(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof Set)return new Set([...r].map(t=>ee(t)));if(ArrayBuffer.isView(r))return r.slice();if(r instanceof Array)return r.map(t=>ee(t));if(r instanceof Map){let t=new Map;return r.forEach((i,n)=>t.set(n,ee(i))),t}let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=ee(r[t]));return e}function Jn(){let r=window.__editableConfigBaseline;if(!r){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return qn(e)}return qn(r)}function Qe(){let r=window.__editableConfig;return r?qn(r):Jn()}function qn(r){let e={objects:{},scenes:{},engine:ee(r.engine||{})},t=r.objects;if(t instanceof Map)t.forEach((o,l)=>{e.objects[l]=ee(o)});else if(t&&typeof t=="object")for(let o in t)e.objects[o]=ee(t[o]);let i=r.scenes;if(i instanceof Map)i.forEach((o,l)=>{e.scenes[l]=ee(o)});else if(i&&typeof i=="object")for(let o in i)e.scenes[o]=ee(i[o]);let n=oe();console.log(`[CONFIG] Export: Applying ${n.length} overrides to baseline`);let a=new Map;for(let o of n){let l=o.objectId||(o.sceneId?`scene:${o.sceneId}`:"__engine__");a.has(l)||a.set(l,[]),a.get(l).push(o)}let s=new Map;for(let o of n)if(o.path==="render.asset.path"&&o.objectId){let l=o.value;s.has(l)||s.set(l,[]),s.get(l).push(o.objectId)}for(let[o,l]of s.entries())l.length>1&&console.log(`[CONFIG] \u26A0\uFE0F Multiple objects sharing same asset: ${o} used by ${l.join(", ")}`);for(let o of n)o.objectId?(e.objects[o.objectId]||(console.warn(`[CONFIG] \u26A0\uFE0F Override references non-existent object: ${o.objectId}`),e.objects[o.objectId]={}),console.log(`[CONFIG] Export: Applying override to ${o.objectId}.${o.path} = ${typeof o.value=="string"?o.value.substring(0,50):o.value}`),Dt(e.objects[o.objectId],o.path,o.value)):o.sceneId?(e.scenes[o.sceneId]||(e.scenes[o.sceneId]={}),Dt(e.scenes[o.sceneId],o.path,o.value)):Dt(e.engine,o.path,o.value);return e}function Fe(){let r=oe(),e=new Set;for(let t of r)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:r.length,hasChanges:r.length>0,overrides:r}}async function Ai(r){let e=Qe(),t={};for(let[n,a]of Object.entries(e.objects)){let s=a,o=n;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${n}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),t[`objects/${o}.json`]=s}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[n,a]of Object.entries(e.scenes)){let s=n.startsWith("scene.")?n:`scene.${n}`;t[`scenes/${s}.json`]=a}let i=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:oe().length>0,versionName:r})});if(!i.ok){let n=await i.json();throw new Error(`Apply failed: ${n.error||"Unknown error"}`)}ge();try{let n=wi();n&&(window.__editableConfigBaseline=ee(n))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Ft(){ge(),window.location.reload()}async function Li(){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"}`)}ge(),window.location.reload()}var Fs,Kn,Gs,ae=we(()=>{"use strict";Fs="handler_preview_override_mode";if(typeof window!="undefined"){let r=window.localStorage.getItem(Fs);window.__enableConfigOverrides=r===null?!0:r==="true"}Kn=500;Gs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function tl(r,e){try{if(typeof r=="object"&&r!==null)return r;if(typeof r!="string")return null;if(r.startsWith("data:")){let i=r.indexOf(",");if(i===-1)return null;let n=r.slice(0,i);if(!n.includes("application/json")&&!n.includes("text/plain"))return null;let a=r.slice(i+1),s=n.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(s)}let t=r.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(r):null}catch{return null}}function il(r){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=r.replace(/^\.\/+/,""),i=t.split("/").pop()||t,n=[t,i,t.replace(/\.json$/,""),i.replace(/\.json$/,"")];for(let a of n){let s=e[a];if(s){let o=tl(s,a);if(o!==null)return o}}return null}async function Bt(r){if(Zn.has(r)&&!Qn)return console.log(`[CONFIG] Using cached config for: "${r}"`),Zn.get(r);if(console.log(`[CONFIG] loadConfigFile called with: "${r}", MODE: ${K.toUpperCase()}, CACHE: ${Qn?"DISABLED":"ENABLED"}`),K==="publish"){let i=il(r);return i?(console.log(`[CONFIG] \u2713 Loaded ${r} via INLINE_ASSETS`),i):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${r} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}K==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${r}"`);let e;K==="brand"?e=[`./${r.split("/").pop()||r}`,`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(i=>i.startsWith("./")?[i,`/${i.slice(2)}`]:i.startsWith("/")?[i]:[i,`/${i}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let i=Qn?"no-store":"force-cache";for(let n of e)try{let a=await fetch(n,{cache:i});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${r} via ${n}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${n} (mode: ${K}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${r}; using defaults`),{}})();return Zn.set(r,t),t}async function Ti(){console.log("[CONFIG] Loading component schemas...");let r=["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 r)try{let i=K==="publish"||K==="brand"?t.split("/").pop()||t:`configs/${t}`,n=await Bt(i);n.component&&(e.set(n.component,n),console.log(`[CONFIG] \u2713 Schema loaded: ${n.component} ${K==="publish"||K==="brand"?"(flattened)":"(nested)"}`))}catch(i){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,i)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Be(r){console.log(`[CONFIG] Loading object config: ${r}`);let e=K==="publish"||K==="brand"?`${r}.json`:`configs/objects/${r}.json`;return await Bt(e)}async function Ii(r){let e=new Map;if(r.objects&&Array.isArray(r.objects)){for(let t of r.objects)if(t.enabled&&t.object_config)try{let i=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(i)||(i=`json.${i}`);let n=await Be(i);(!n||Object.keys(n).length===0)&&i!==t.instance_id&&(n=await Be(t.instance_id)),!n||Object.keys(n).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),n=await Be(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...n,instance_id:t.instance_id,object_config:t.object_config})}catch(i){console.warn(`Failed to load object ${t.object_config}:`,i)}}return e}async function ki(){console.log("[CONFIG] Loading engine configs...");let r=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(r.map(i=>{let n=`engine.${i}.json`,a=K==="publish"||K==="brand"?n:`configs/engine/${n}`;return Bt(a)})),t=Object.fromEntries(r.map((i,n)=>[i,e[n]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(r.map(i=>{var s;let n=(s=t[i])!=null?s:{},a=Object.keys(n);return[i,a.length>0?a:"empty"]}))),t}async function ea(){return await Bt(K==="publish"||K==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Pi(r="scene.main"){console.log(`[CONFIG] Loading scene config: ${r}`);let e=K==="publish"||K==="brand"?`${r}.json`:`configs/scenes/${r}.json`;return await Bt(e)}function ht(r,e){let t=[];if(!r.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let i=e.get("identity");if(i)for(let n of i.required||[])r.identity[n]||t.push(`Missing required identity field: ${n}`);for(let[n,a]of Object.entries(r)){if(n==="identity")continue;let s=e.get(n);if(s&&a&&typeof a=="object"){let o=a;for(let l of s.required||[])o[l]===void 0&&t.push(`Missing required field in ${n}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.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(`${n}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${n}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function et(r,e){let t={...r},i=["identity","transform","render"];for(let[n,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(i.includes(n)||t[n])&&(t[n]||(t[n]={}),t[n]={...a.defaults,...t[n]});return t}function he(r,e,t,i){return typeof r!="number"||!Number.isFinite(r)?e:Math.min(Math.max(r,t),i)}function Ws(r,e){if(Array.isArray(r))return{x:he(r[0],e.x,-2e3,2e3),y:he(r[1],e.y,-2e3,2e3)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:he(t,e.x,-2e3,2e3),y:he(i,e.y,-2e3,2e3)}}function nl(r,e){if(Array.isArray(r))return{x:he(r[0],e.x,0,1),y:he(r[1],e.y,0,1)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:he(t,e.x,0,1),y:he(i,e.y,0,1)}}function al(r){if(Array.isArray(r))return{x:he(r[0],.5,-10,10),y:he(r[1],.5,-10,10)};if(r&&typeof r=="object"){let{x:e,y:t}=r;return{x:he(e,.5,-10,10),y:he(t,.5,-10,10)}}return typeof r=="string"?r:null}async function _e(r="scene.main",e){var c,d,p,u,g,h,f,m,b,y,w,v,P,I,_,k,j,L;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await Ti(),i=oe(),n=Nt();console.log(`[CONFIG] Loader: Found ${i.length} persisted overrides, override mode: ${n}`),i.length>0&&console.log("[CONFIG] Override details:",i.map(x=>({objectId:x.objectId,path:x.path,value:typeof x.value=="string"?x.value.substring(0,50):x.value})));let a=await Pi(r);console.log(`[CONFIG] Scene config loaded: ${((c=a.objects)==null?void 0:c.length)||0} objects`);let s=await ki();console.log("[CONFIG] Loading object configs...");let o=await Ii(a);console.log(`[CONFIG] Loaded ${o.size} object configs:`,Array.from(o.keys()));for(let[x,S]of o.entries()){let E=et(S,t),C=ht(E,t);C.valid||console.warn(`Object ${x} validation errors:`,C.errors),(d=E.transform)!=null&&d.position&&(E.transform.position=Ws(E.transform.position,{x:0,y:0})),(p=E.transform)!=null&&p.offset&&(E.transform.offset=Ws(E.transform.offset,{x:0,y:0})),((u=E.transform)==null?void 0:u.anchor)!==void 0&&(E.transform.anchor=al(E.transform.anchor)),((g=E.transform)==null?void 0:g.position_ratio)!==void 0&&E.transform.position_ratio!==null&&(E.transform.position_ratio=nl(E.transform.position_ratio,{x:.5,y:.5})),o.set(x,E)}if(e){if(e.objects)for(let[x,S]of e.objects.entries())o.set(x,S);e.engine&&(s.runtime={...s.runtime,...e.engine.runtime},s.assets={...s.assets,...e.engine.assets},s.splash={...(h=s.splash)!=null?h:{},...(f=e.engine.splash)!=null?f:{}})}let l={objects:o,engine:s,scene:a,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};if(typeof window!="undefined"&&(window.__editableConfig=l,window.__editableConfigBaseline||(window.__editableConfigBaseline=et(l,t))),i.length>0&&n){console.log(`[CONFIG] \u2705 Applying ${i.length} persisted overrides on startup`);let x=new Map;for(let C of i)if(C.path==="render.asset.path"&&C.objectId){let A=C.value;x.has(A)||x.set(A,[]),x.get(A).push(C.objectId)}for(let[C,A]of x.entries())A.length>1&&console.log(`[CONFIG] \u{1F4CB} Multiple objects sharing asset on startup: "${C}" used by: ${A.join(", ")}`);let S=new Map;for(let C of i){let A=C.objectId||"__engine__";S.has(A)||S.set(A,[]),S.get(A).push(C)}console.log("[CONFIG] Override distribution:",{totalOverrides:i.length,objectsWithOverrides:Array.from(S.keys()),overridesPerObject:Array.from(S.entries()).map(([C,A])=>({objectId:C,count:A.length,paths:A.map(T=>T.path)}))}),He(i,{silent:!1,persist:!1});let E=window.__editableConfig;if(E){for(let C of i.slice(0,5))if(C.objectId){let A=((b=(m=E.objects)==null?void 0:m.get)==null?void 0:b.call(m,C.objectId))||((y=E.objects)==null?void 0:y[C.objectId]);if(A){let T=C.path.split(".").reduce((O,M)=>O==null?void 0:O[M],A);T===C.value?console.log(`[CONFIG] \u2705 Verified override applied: ${C.objectId}.${C.path} = ${typeof C.value=="string"?C.value.substring(0,40):"\u2713"}`):console.error(`[CONFIG] \u274C Override NOT applied correctly: ${C.objectId}.${C.path}. Expected: ${C.value}, Got: ${T}`)}else console.error(`[CONFIG] \u274C Object not found after override application: ${C.objectId}`)}}console.log("[CONFIG] \u2705 Overrides applied. Current config state:",{objectCount:((w=l.objects)==null?void 0:w.size)||0,sampleOverrides:i.slice(0,3).map(C=>`${C.objectId||"engine"}.${C.path} = ${typeof C.value=="string"?C.value.substring(0,30):JSON.stringify(C.value).substring(0,30)}`)})}else i.length>0&&!n?console.warn(`[CONFIG] \u26A0\uFE0F Found ${i.length} persisted overrides but override mode is DISABLED. Overrides will NOT be applied.`):i.length===0&&console.log("[CONFIG] No persisted overrides found in localStorage");return console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(o.keys()),engine:{runtime:Object.keys((v=s.runtime)!=null?v:{}),assets:Object.keys((P=s.assets)!=null?P:{}),splash:Object.keys((I=s.splash)!=null?I:{}),loading:Object.keys((_=s.loading)!=null?_:{}),start:Object.keys((k=s.start)!=null?k:{}),tutorial:Object.keys((j=s.tutorial)!=null?j:{}),endgame:Object.keys((L=s.endgame)!=null?L:{})},scene:a.scene_id||"unknown"}),l}function ta(r){var t,i,n,a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,P,I,_,k,j,L,x,S,E,C,A,T,O,M;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[R,z]of r.objects.entries()){let F=((t=z.identity)==null?void 0:t.id)||R;F.includes("character")&&(e.gameplay.character_pos=((i=z.transform)==null?void 0:i.position)||{x:0,y:0},e.gameplay.character_scale=((n=z.transform)==null?void 0:n.scale)||1,e.gameplay.character_anim_speed=((s=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:s.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),(F.includes("gun")||F.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)||{}),F.includes("diamond")&&(e.gameplay.diamond=z),F.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||{}),F.includes("water")&&(e.gameplay.water_drops=z),F.includes("crack")&&(e.gameplay.crack=z),F.includes("hand")&&(e.gameplay.hand=((w=z.gameplay)==null?void 0:w.tuning)||{},e.gameplay.brush_start_pos=((v=z.transform)==null?void 0:v.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((P=z.transform)==null?void 0:P.scale)||1.5),F.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=((j=(k=z.gameplay)==null?void 0:k.tuning)==null?void 0:j.danger_pulse)||{},e.gameplay.hazard_height=((x=(L=z.gameplay)==null?void 0:L.tuning)==null?void 0:x.hazard_height)||140)}return e.gameplay.timeline=((S=r.engine.runtime)==null?void 0:S.timeline)||{},e.gameplay.drag_surface=((E=r.engine.runtime)==null?void 0:E.drag_surface)||{},e.gameplay.background=((C=r.engine.runtime)==null?void 0:C.background)||{},e.gameplay.ui_styles=((A=r.engine.runtime)==null?void 0:A.ui_styles)||{},e.gameplay.label_pulse=((T=r.engine.runtime)==null?void 0:T.label_pulse)||{},e.ui=((O=r.engine.runtime)==null?void 0:O.ui)||{},e.theme=((M=r.engine.runtime)==null?void 0:M.theme)||{},e.assets=r.engine.assets||{},e}var Ys,K,Zn,Qn,ia=we(()=>{"use strict";ae();Ys=null,K="dev";if(typeof window!="undefined"){let r=window.__BUILD_SETTINGS__;if(r!=null&&r.buildMode)Ys=r,K=r.buildMode,console.log("[CONFIG] Loaded inline build settings:",r,"buildMode:",K);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);Ys=t,K=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",K)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",K)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",K);Zn=new Map,Qn=K==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function na(r,e){let t=[];function i(n,a,s=""){if(n!==a){if(typeof n!=typeof a){t.push(`${s}: type changed`);return}if(typeof n=="object"&&n!==null&&a!==null){let o=new Set([...Object.keys(n),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in n?l in a?i(n[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return i(r,e),t}function aa(r,e,t,i){let n={...t};for(let[a,s]of i.entries())n[a]&&s.defaults&&(n[a]={...s.defaults,...n[a]});return n}var Gt,tt,sa=we(()=>{"use strict";Gt=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},tt=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 i=`${e}?t=${Date.now()}&r=${Math.random()}`,n=await fetch(i,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(n.ok){let a=await n.text(),s=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,s)}else o||this.fileHashes.set(e,s)}}catch(i){console.warn(`Failed to check ${e}:`,i)}}determineEventType(e){var t,i;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:(i=e.split("/").pop())==null?void 0:i.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,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 oa(r){if(typeof window=="undefined")return;let e=typeof ra!="undefined"&&!!ra.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let n=null,a=!1,s=null;if(t){s=new tt;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=s}let o=new Set,l=h=>{var b,y;if(!s)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 w of m)w!=null&&w.object_config&&f.add(`configs/objects/${w.object_config}.json`);for(let w of o)f.has(w)||s.unwatch(w);for(let w of f)o.has(w)||s.watch(w,v=>g(v));o=f},c=new Set,d=!1,p=async h=>{let f=await Be(h),m=et(f,r.activeConfig.schemas),b=ht(m,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){r.audioSystem.destroy();let f=await _e("scene.main");r.setActiveConfig(f),r.gameObjectManager.updateConfig(f),r.CustomAssets.updateConfig(f),await r.CustomAssets.ready();let m=r.createAudioSystem(f);r.setAudioSystem(m),window.__audioSystem=m,await m.start(),r.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,n&&window.clearTimeout(n),n=window.setTimeout(()=>{u(h.type)},120)}e&&ra.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(r.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var ra,Ks=we(()=>{"use strict";sa();ia();ra={}});var Xs={};ot(Xs,{ConfigWatcher:()=>tt,DefaultReloadStrategy:()=>Gt,applyDefaults:()=>et,diffConfigs:()=>na,loadAllObjectConfigs:()=>Ii,loadComponentSchemas:()=>Ti,loadEngineConfig:()=>ki,loadGamePromptConfig:()=>ea,loadObjectCentricConfig:()=>_e,loadObjectConfig:()=>Be,loadSceneConfig:()=>Pi,rehydrateObject:()=>aa,setupHotReload:()=>oa,toLegacyFormat:()=>ta,validateObjectConfig:()=>ht});var Mi=we(()=>{"use strict";ia();sa();Ks()});var Ut={};ot(Ut,{AssetEditorModal:()=>ua});var ua,ft=we(()=>{"use strict";ua=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,i,n){this.currentObjectId=e,this.currentPath=t,this.currentAsset=i,this.onApplyCallback=n,this.createModal(e,i),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let i=document.createElement("div");i.className="asset-editor-modal",i.innerHTML=`
1
+ "use strict";var oo=Object.create;var oi=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var co=Object.getOwnPropertyNames;var po=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var we=(r,e)=>()=>(r&&(e=r(r=0)),e);var ot=(r,e)=>{for(var t in e)oi(r,t,{get:e[t],enumerable:!0})},ns=(r,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of co(e))!uo.call(r,n)&&n!==t&&oi(r,n,{get:()=>e[n],enumerable:!(i=lo(e,n))||i.enumerable});return r};var lt=(r,e,t)=>(t=r!=null?oo(po(r)):{},ns(e||!r||!r.__esModule?oi(t,"default",{value:r,enumerable:!0}):t,r)),go=r=>ns(oi({},"__esModule",{value:!0}),r);var pe,pi=we(()=>{"use strict";pe=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()}};pe.store=new Map});function xo(){var r,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(r=document.querySelector("script"))==null?void 0:r.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),i=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!i)}catch{return!1}}async function So(){try{if(typeof window!="undefined"){let r=await fetch("./build-settings.json");if(r.ok){let e=await r.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Eo(){try{if(typeof window!="undefined"){let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Co(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${X}`),Object.keys(Te).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(Te)),Te;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),Te={...window.INLINE_ASSETS},Te;if(!(X==="publish"&&xe!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),Te;if(!Rn){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),Rn=(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 i=await t.text();console.log("[AssetLoader] Received JS code, length:",i.length);let n=i.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(n)try{let a=n[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}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:",i.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return Te=await Rn,console.log("[AssetLoader] Final inline assets cache:",Object.keys(Te)),Te}function zn(r){return r===null||typeof r!="object"||(Object.freeze(r),Object.values(r).forEach(e=>zn(e))),r}function Ao(r=64,e=64,t=16711680){let i=document.createElement("canvas");i.width=r,i.height=e;let n=i.getContext("2d");return n.fillStyle=`#${t.toString(16).padStart(6,"0")}`,n.fillRect(0,0,r,e),n.strokeStyle="#000",n.strokeRect(0,0,r,e),n.fillStyle="#fff",n.font="10px sans-serif",n.textAlign="center",n.fillText("MISSING",r/2,e/2),Ie.Texture.from(i)}function $n(r,e){zs.set(r,e)}var Ie,Os,Rs,Ke,X,xe,De,Te,Rn,zs,Xe,ui=we(()=>{"use strict";Ie=require("pixi.js");pi();Os=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Rs=xo(),Ke=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,X=Rs?"publish":Os,xe=Ke==null?void 0:Ke.assetsInlined;Ke!=null&&Ke.buildMode&&(X=Ke.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${X}`));De=Eo();De!=null&&De.buildMode&&(X=De.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${X}`));(De==null?void 0:De.assetsInlined)!==void 0&&(xe=De.assetsInlined);So().then(r=>{r!=null&&r.buildMode&&r.buildMode!==X&&(X=r.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${X}`)),(r==null?void 0:r.assetsInlined)!==void 0&&(xe=r.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Os}, Runtime: ${Rs?"publish":"dev"}, Effective: ${X}`);Te={},Rn=null;zs=new Map;Xe=class{static async load(e,t,i,n){let a=`${e}:${t.path}`,s=pe.get(a);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${X}`),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 Co(),l=o[e];if(!l&&n&&(l=o[n],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${n}`)),!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"),X==="publish"&&xe!==!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=zs.get(t.type);if(d)try{let p=await d(t.path,l,e,i);return pe.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=zn(p);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return pe.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}}static async loadImage(e,t){let i=X==="publish",n=i&&xe!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${X}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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 Ie.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 Ie.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Ie.Assets.load(e)}return await Ie.Assets.load(e)}static async loadJSON(e,t){let i=X==="publish",n=i&&xe!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${X}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){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 s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}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,i){if(X==="dev"){let a=t==="image"?Ao():zn({__placeholder:!0,type:t});return pe.set(e+":"+((i==null?void 0:i.path)||"missing"),a),a}throw i}};$n("image",async(r,e)=>{let t=X==="publish",i=t&&xe!==!1,n=X==="brand",a=t&&xe===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${X}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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: ${r}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Ie.Assets.load(e)}let s=r;return(n||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),Ie.Assets.load(e||s)});$n("json",async(r,e)=>{let t=X==="publish",i=t&&xe!==!1,n=X==="brand",a=t&&xe===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${X}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){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: ${r}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let s=r;if((n||a)&&r&&!r.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=r,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${r}" as-is`)):(s=`assets/${r}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${r}" -> "${s}"`))),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(s);if(!o.ok)throw new Error(`JSON fetch failed: ${r}`);return o.json()})});var Ds={};ot(Ds,{AssetTextures:()=>Ee,initAssetTextures:()=>Hn});function Hn(r,e){$s.init(r,e),typeof window!="undefined"&&(window.__AssetTextures=Ee)}var Nn,$s,Ee,ut=we(()=>{"use strict";ui();Nn=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(i=>{this.priorityReadyResolve=i}),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 s;console.log("[AssetTextures] Loading all assets...");let i=new Set(["background_loading_1"]),n=[],a=[];for(let[o,l]of e.objects.entries()){let c=(s=l.render)==null?void 0:s.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 Xe.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{}}};i.has(o)?n.push(d()):a.push(d())}n.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(n),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 n=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(n.length===0)return;this.ready().catch(()=>{});let a=()=>n.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let s=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(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:n}),o())},s)})}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())}},$s=new Nn,Ee=new Proxy($s,{get(r,e){return e in r&&typeof r[e]=="function"?r[e].bind(r):r.get(e)},set(r,e,t){return r.set(e,t),!0}})});var je={};ot(je,{applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>Ai,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Bs,configOverrideManager:()=>Gs,deepClone:()=>ee,exportConfigsAsJSON:()=>Jn,exportConfigsFromActiveCache:()=>Qe,getConfigOverrides:()=>oe,getConfigStateSummary:()=>Fe,getOverrideMode:()=>Nt,redoLastConfigChange:()=>Ci,removeConfigOverride:()=>Ht,resetToApplied:()=>Ft,resetToOriginal:()=>Li,setOverrideMode:()=>Xn,trackObjectCreation:()=>Us,trackObjectDeletion:()=>qs,undoLastConfigChange:()=>Ei});function wi(){return typeof window=="undefined"?null:window.__editableConfig||null}function Vn(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Un(r,e){var t,i;if(!r)return null;try{if(r instanceof Map)return(t=r.get(e))!=null?t:null;if(typeof r=="object")return(i=r[e])!=null?i:null}catch{}return null}function Zo(r,e,t){if(r){if(r instanceof Map){r.set(e,t);return}typeof r=="object"&&(r[e]=t)}}function Hs(r,e){for(let t of e)Dt(r,t.path,t.value)}function xi(r){var o;if(typeof window=="undefined")return;let e=wi();if(!e)return;let t=Vn(),i=(o=t?Un(t.objects,r):null)!=null?o:Un(e.objects,r);if(!i)return;let n=ee(i),a=oe().filter(l=>l.objectId===r);try{Hs(n,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",r,l);return}Zo(e.objects,r,n);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(r,n)}catch{}}function Yn(){var n;if(typeof window=="undefined")return;let r=wi();if(!(r!=null&&r.engine))return;let e=Vn(),t=ee(((n=e==null?void 0:e.engine)!=null?n:r.engine)||{}),i=oe().filter(a=>!a.objectId&&!a.sceneId);try{Hs(t,i)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=r.engine;for(let s of Object.keys(a))s in t||delete a[s];for(let[s,o]of Object.entries(t))a[s]=o}catch{r.engine=t}}function Qo(){if(typeof window=="undefined")return"unknown";let r=window;return typeof r.__HANDLER_PROJECT_ID=="string"?r.__HANDLER_PROJECT_ID:"handler-default"}function Wn(){return`handler_preview_config_overrides::${Qo()}`}function el(){if(typeof window=="undefined")return[];try{let r=window.localStorage.getItem(Wn());if(!r)return[];let e=JSON.parse(r);return Array.isArray(e)?e:[]}catch{return[]}}function Si(r){if(typeof window!="undefined")try{window.localStorage.setItem(Wn(),JSON.stringify(r))}catch{}}function Nt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Xn(r){if(typeof window!="undefined"){window.__enableConfigOverrides=r;try{window.localStorage.setItem(Fs,r?"true":"false")}catch{}}}function le(r,e={}){var u,g;let{objectId:t,path:i,value:n}=r,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=e,l=wi();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:i,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:i,value:n});let d;try{d=Vs(c,i),Dt(c,i,n)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:i,value:n},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:i,oldValue:d,newValue:n,ts:Date.now()}),h.length>Kn&&h.shift(),window.__configChangeRedo=[]}if(s){let h=oe(),f=h.findIndex(y=>y.objectId===t&&y.sceneId===r.sceneId&&y.path===i);f>=0?(console.log(`[CONFIG] Updating existing override at index ${f}:`,{objectId:t,path:i,oldValue:h[f].value,newValue:n}),h[f].value=n):(console.log("[CONFIG] Adding new override:",{objectId:t,path:i,value:typeof n=="string"?n.substring(0,50):n}),h.push(r)),window.__configOverrides=h,Si(h);let m=Wn(),b=typeof window!="undefined"?window.localStorage.getItem(m):null;if(b){let y=JSON.parse(b);y.find(v=>v.objectId===t&&v.path===i)?console.log(`[CONFIG] \u2705 Override persisted to localStorage successfully. Total overrides: ${y.length}`):console.error("[CONFIG] \u274C Override NOT found in localStorage after persist!")}else console.error(`[CONFIG] \u274C localStorage key ${m} is empty after persist!`);Nt()||(console.log("[CONFIG] Override mode was disabled, enabling it now to ensure overrides apply on reload"),Xn(!0))}a||console.log("[CONFIG] Applied override:",r),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:{...r,oldValue:d}}))}function He(r,e={}){let t=e.emitEvent!==!1,i=[];for(let n of r)n!=null&&n.objectId&&typeof n.objectId=="string"&&i.push(n.objectId),le(n,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let n=Array.from(new Set(i));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:n,count:r.length}}))}}function ge(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],Si([]),console.log("[CONFIG] Cleared all overrides")}function Bs(r){let e=oe().filter(i=>i.objectId!==r);window.__configOverrides=e,Si(e);let t=window.__configChanges||[];window.__configChanges=t.filter(i=>i.objectId!==r),xi(r),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:r}}))}function Ht(r,e){let t=oe().filter(n=>n.objectId!==r||n.path!==e);window.__configOverrides=t,Si(t);let i=window.__configChanges||[];window.__configChanges=i.filter(n=>n.objectId!==r||n.path!==e),r?xi(r):Yn(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:r,path:e}}))}function oe(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=el()),window.__configOverrides||[])}function Ei(){var a;if(typeof window=="undefined")return!1;let r=window.__configChanges||[];if(r.length===0)return!1;let e=r.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:s}=e.metadata||{};return e.objectId&&s&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:s})}).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:s,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&s&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:s,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 i=Vn(),n=!1;if(i){let s=e.objectId?Un(i.objects,e.objectId):i.engine;if(s){let o=Vs(s,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(n=!0)}}return n?Ht(e.objectId,e.path):(le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xi(e.objectId):Yn()),console.log("[CONFIG] Undo:",e.path),!0}function Ci(){var i;if(typeof window=="undefined")return!1;let r=window.__configChangeRedo||[];if(r.length===0)return!1;let e=r.pop();if(e.changeType==="object_create"){let{screenId:n,objectConfigId:a}=e.metadata||{},s=e.newValue;return e.objectId&&n&&s&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:e.objectId,objectConfigId:a||((i=s==null?void 0:s.identity)==null?void 0:i.id),config:s})}).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:n}=e.metadata||{};return e.objectId&&n&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:n})}).catch(s=>console.error("[CONFIG] Failed to delete object on redo:",s)),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}),le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xi(e.objectId):Yn(),console.log("[CONFIG] Redo:",e.path),!0}function Us(r,e,t){var n;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(n=t==null?void 0:t.identity)==null?void 0:n.id}}),window.__configChangeRedo=[],i.length>Kn&&i.shift(),console.log("[CONFIG] Tracked object creation:",r)}function qs(r,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let i=window.__configChanges;i.push({objectId:r,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],i.length>Kn&&i.shift(),console.log("[CONFIG] Tracked object deletion:",r)}function Dt(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(s=a[o])!=null?s:{},a=a[o]}a[n]=t}function Vs(r,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,r)}function ee(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return new Date(r.getTime());if(r instanceof Set)return new Set([...r].map(t=>ee(t)));if(ArrayBuffer.isView(r))return r.slice();if(r instanceof Array)return r.map(t=>ee(t));if(r instanceof Map){let t=new Map;return r.forEach((i,n)=>t.set(n,ee(i))),t}let e={};for(let t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=ee(r[t]));return e}function Jn(){let r=window.__editableConfigBaseline;if(!r){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return qn(e)}return qn(r)}function Qe(){let r=window.__editableConfig;return r?qn(r):Jn()}function qn(r){let e={objects:{},scenes:{},engine:ee(r.engine||{})},t=r.objects;if(t instanceof Map)t.forEach((o,l)=>{e.objects[l]=ee(o)});else if(t&&typeof t=="object")for(let o in t)e.objects[o]=ee(t[o]);let i=r.scenes;if(i instanceof Map)i.forEach((o,l)=>{e.scenes[l]=ee(o)});else if(i&&typeof i=="object")for(let o in i)e.scenes[o]=ee(i[o]);let n=oe();console.log(`[CONFIG] Export: Applying ${n.length} overrides to baseline`);let a=new Map;for(let o of n){let l=o.objectId||(o.sceneId?`scene:${o.sceneId}`:"__engine__");a.has(l)||a.set(l,[]),a.get(l).push(o)}let s=new Map;for(let o of n)if(o.path==="render.asset.path"&&o.objectId){let l=o.value;s.has(l)||s.set(l,[]),s.get(l).push(o.objectId)}for(let[o,l]of s.entries())l.length>1&&console.log(`[CONFIG] \u26A0\uFE0F Multiple objects sharing same asset: ${o} used by ${l.join(", ")}`);for(let o of n)o.objectId?(e.objects[o.objectId]||(console.warn(`[CONFIG] \u26A0\uFE0F Override references non-existent object: ${o.objectId}`),e.objects[o.objectId]={}),console.log(`[CONFIG] Export: Applying override to ${o.objectId}.${o.path} = ${typeof o.value=="string"?o.value.substring(0,50):o.value}`),Dt(e.objects[o.objectId],o.path,o.value)):o.sceneId?(e.scenes[o.sceneId]||(e.scenes[o.sceneId]={}),Dt(e.scenes[o.sceneId],o.path,o.value)):Dt(e.engine,o.path,o.value);return e}function Fe(){let r=oe(),e=new Set;for(let t of r)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:r.length,hasChanges:r.length>0,overrides:r}}async function Ai(r){let e=Qe(),t={};for(let[n,a]of Object.entries(e.objects)){let s=a,o=n;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${n}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),t[`objects/${o}.json`]=s}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[n,a]of Object.entries(e.scenes)){let s=n.startsWith("scene.")?n:`scene.${n}`;t[`scenes/${s}.json`]=a}let i=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:oe().length>0,versionName:r})});if(!i.ok){let n=await i.json();throw new Error(`Apply failed: ${n.error||"Unknown error"}`)}ge();try{let n=wi();n&&(window.__editableConfigBaseline=ee(n))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Ft(){ge(),window.location.reload()}async function Li(){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"}`)}ge(),window.location.reload()}var Fs,Kn,Gs,ae=we(()=>{"use strict";Fs="handler_preview_override_mode";if(typeof window!="undefined"){let r=window.localStorage.getItem(Fs);window.__enableConfigOverrides=r===null?!0:r==="true"}Kn=500;Gs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function tl(r,e){try{if(typeof r=="object"&&r!==null)return r;if(typeof r!="string")return null;if(r.startsWith("data:")){let i=r.indexOf(",");if(i===-1)return null;let n=r.slice(0,i);if(!n.includes("application/json")&&!n.includes("text/plain"))return null;let a=r.slice(i+1),s=n.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(s)}let t=r.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(r):null}catch{return null}}function il(r){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=r.replace(/^\.\/+/,""),i=t.split("/").pop()||t,n=[t,i,t.replace(/\.json$/,""),i.replace(/\.json$/,"")];for(let a of n){let s=e[a];if(s){let o=tl(s,a);if(o!==null)return o}}return null}async function Bt(r){if(Zn.has(r)&&!Qn)return console.log(`[CONFIG] Using cached config for: "${r}"`),Zn.get(r);if(console.log(`[CONFIG] loadConfigFile called with: "${r}", MODE: ${K.toUpperCase()}, CACHE: ${Qn?"DISABLED":"ENABLED"}`),K==="publish"){let i=il(r);return i?(console.log(`[CONFIG] \u2713 Loaded ${r} via INLINE_ASSETS`),i):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${r} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}K==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${r}"`);let e;K==="brand"?e=[`./${r.split("/").pop()||r}`,`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${r}`,`./${r.replace(/^configs\//,"")}`,`./${r.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(i=>i.startsWith("./")?[i,`/${i.slice(2)}`]:i.startsWith("/")?[i]:[i,`/${i}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let i=Qn?"no-store":"force-cache";for(let n of e)try{let a=await fetch(n,{cache:i});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${r} via ${n}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${n} (mode: ${K}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${r}; using defaults`),{}})();return Zn.set(r,t),t}async function Ti(){console.log("[CONFIG] Loading component schemas...");let r=["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 r)try{let i=K==="publish"||K==="brand"?t.split("/").pop()||t:`configs/${t}`,n=await Bt(i);n.component&&(e.set(n.component,n),console.log(`[CONFIG] \u2713 Schema loaded: ${n.component} ${K==="publish"||K==="brand"?"(flattened)":"(nested)"}`))}catch(i){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,i)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Be(r){console.log(`[CONFIG] Loading object config: ${r}`);let e=K==="publish"||K==="brand"?`${r}.json`:`configs/objects/${r}.json`;return await Bt(e)}async function Ii(r){let e=new Map;if(r.objects&&Array.isArray(r.objects)){for(let t of r.objects)if(t.enabled&&t.object_config)try{let i=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(i)||(i=`json.${i}`);let n=await Be(i);(!n||Object.keys(n).length===0)&&i!==t.instance_id&&(n=await Be(t.instance_id)),!n||Object.keys(n).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),n=await Be(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...n,instance_id:t.instance_id,object_config:t.object_config})}catch(i){console.warn(`Failed to load object ${t.object_config}:`,i)}}return e}async function ki(){console.log("[CONFIG] Loading engine configs...");let r=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(r.map(i=>{let n=`engine.${i}.json`,a=K==="publish"||K==="brand"?n:`configs/engine/${n}`;return Bt(a)})),t=Object.fromEntries(r.map((i,n)=>[i,e[n]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(r.map(i=>{var s;let n=(s=t[i])!=null?s:{},a=Object.keys(n);return[i,a.length>0?a:"empty"]}))),t}async function ea(){return await Bt(K==="publish"||K==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Pi(r="scene.main"){console.log(`[CONFIG] Loading scene config: ${r}`);let e=K==="publish"||K==="brand"?`${r}.json`:`configs/scenes/${r}.json`;return await Bt(e)}function ht(r,e){let t=[];if(!r.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let i=e.get("identity");if(i)for(let n of i.required||[])r.identity[n]||t.push(`Missing required identity field: ${n}`);for(let[n,a]of Object.entries(r)){if(n==="identity")continue;let s=e.get(n);if(s&&a&&typeof a=="object"){let o=a;for(let l of s.required||[])o[l]===void 0&&t.push(`Missing required field in ${n}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.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(`${n}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${n}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function et(r,e){let t={...r},i=["identity","transform","render"];for(let[n,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(i.includes(n)||t[n])&&(t[n]||(t[n]={}),t[n]={...a.defaults,...t[n]});return t}function he(r,e,t,i){return typeof r!="number"||!Number.isFinite(r)?e:Math.min(Math.max(r,t),i)}function Ws(r,e){if(Array.isArray(r))return{x:he(r[0],e.x,-2e3,2e3),y:he(r[1],e.y,-2e3,2e3)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:he(t,e.x,-2e3,2e3),y:he(i,e.y,-2e3,2e3)}}function nl(r,e){if(Array.isArray(r))return{x:he(r[0],e.x,0,1),y:he(r[1],e.y,0,1)};if(!r||typeof r!="object")return e;let{x:t,y:i}=r;return{x:he(t,e.x,0,1),y:he(i,e.y,0,1)}}function al(r){if(Array.isArray(r))return{x:he(r[0],.5,-10,10),y:he(r[1],.5,-10,10)};if(r&&typeof r=="object"){let{x:e,y:t}=r;return{x:he(e,.5,-10,10),y:he(t,.5,-10,10)}}return typeof r=="string"?r:null}async function _e(r="scene.main",e){var c,d,p,u,g,h,f,m,b,y,w,v,j,T,O,M,_,C;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await Ti(),i=oe(),n=Nt();console.log(`[CONFIG] Loader: Found ${i.length} persisted overrides, override mode: ${n}`),i.length>0&&console.log("[CONFIG] Override details:",i.map(x=>({objectId:x.objectId,path:x.path,value:typeof x.value=="string"?x.value.substring(0,50):x.value})));let a=await Pi(r);console.log(`[CONFIG] Scene config loaded: ${((c=a.objects)==null?void 0:c.length)||0} objects`);let s=await ki();console.log("[CONFIG] Loading object configs...");let o=await Ii(a);console.log(`[CONFIG] Loaded ${o.size} object configs:`,Array.from(o.keys()));for(let[x,S]of o.entries()){let E=et(S,t),I=ht(E,t);I.valid||console.warn(`Object ${x} validation errors:`,I.errors),(d=E.transform)!=null&&d.position&&(E.transform.position=Ws(E.transform.position,{x:0,y:0})),(p=E.transform)!=null&&p.offset&&(E.transform.offset=Ws(E.transform.offset,{x:0,y:0})),((u=E.transform)==null?void 0:u.anchor)!==void 0&&(E.transform.anchor=al(E.transform.anchor)),((g=E.transform)==null?void 0:g.position_ratio)!==void 0&&E.transform.position_ratio!==null&&(E.transform.position_ratio=nl(E.transform.position_ratio,{x:.5,y:.5})),o.set(x,E)}if(e){if(e.objects)for(let[x,S]of e.objects.entries())o.set(x,S);e.engine&&(s.runtime={...s.runtime,...e.engine.runtime},s.assets={...s.assets,...e.engine.assets},s.splash={...(h=s.splash)!=null?h:{},...(f=e.engine.splash)!=null?f:{}})}let l={objects:o,engine:s,scene:a,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};if(typeof window!="undefined"&&(window.__editableConfig=l,window.__editableConfigBaseline||(window.__editableConfigBaseline=et(l,t))),i.length>0&&n){console.log(`[CONFIG] \u2705 Applying ${i.length} persisted overrides on startup`);let x=[],S=new Set;for(let P of i){if(!P.objectId){x.push(P);continue}o.has(P.objectId)?x.push(P):S.add(P.objectId)}if(S.size>0){let P=i.length-x.length;if(console.warn(`[CONFIG] \u26A0\uFE0F Found ${P} override(s) for objects that don't exist: ${Array.from(S).join(", ")}. These will be filtered out.`),console.warn("[CONFIG] \u{1F4A1} Tip: Overrides are automatically cleaned up when config reloads after object deletion."),typeof window!="undefined"){window.__configOverrides=x;try{let R=`handler_preview_config_overrides::${window.__HANDLER_PROJECT_ID||"handler-default"}`;window.localStorage.setItem(R,JSON.stringify(x)),console.log(`[CONFIG] \u2713 Cleaned up ${P} stale override(s) from localStorage (safety net)`)}catch(k){console.warn("[CONFIG] Failed to clean up invalid overrides from localStorage:",k)}}}let E=x,I=new Map;for(let P of E)if(P.path==="render.asset.path"&&P.objectId){let k=P.value;I.has(k)||I.set(k,[]),I.get(k).push(P.objectId)}for(let[P,k]of I.entries())k.length>1&&console.log(`[CONFIG] \u{1F4CB} Multiple objects sharing asset on startup: "${P}" used by: ${k.join(", ")}`);let L=new Map;for(let P of E){let k=P.objectId||"__engine__";L.has(k)||L.set(k,[]),L.get(k).push(P)}console.log("[CONFIG] Override distribution:",{totalOverrides:E.length,objectsWithOverrides:Array.from(L.keys()),overridesPerObject:Array.from(L.entries()).map(([P,k])=>({objectId:P,count:k.length,paths:k.map(R=>R.path)}))}),He(E,{silent:!1,persist:!1});let A=window.__editableConfig;if(A){for(let P of E.slice(0,5))if(P.objectId){let k=((b=(m=A.objects)==null?void 0:m.get)==null?void 0:b.call(m,P.objectId))||((y=A.objects)==null?void 0:y[P.objectId]);if(k){let R=P.path.split(".").reduce((z,F)=>z==null?void 0:z[F],k);R===P.value?console.log(`[CONFIG] \u2705 Verified override applied: ${P.objectId}.${P.path} = ${typeof P.value=="string"?P.value.substring(0,40):"\u2713"}`):console.error(`[CONFIG] \u274C Override NOT applied correctly: ${P.objectId}.${P.path}. Expected: ${P.value}, Got: ${R}`)}else console.warn(`[CONFIG] \u26A0\uFE0F Object not found after override application: ${P.objectId} (this should have been filtered out)`)}}console.log("[CONFIG] \u2705 Overrides applied. Current config state:",{objectCount:((w=l.objects)==null?void 0:w.size)||0,sampleOverrides:E.slice(0,3).map(P=>`${P.objectId||"engine"}.${P.path} = ${typeof P.value=="string"?P.value.substring(0,30):JSON.stringify(P.value).substring(0,30)}`)})}else i.length>0&&!n?console.warn(`[CONFIG] \u26A0\uFE0F Found ${i.length} persisted overrides but override mode is DISABLED. Overrides will NOT be applied.`):i.length===0&&console.log("[CONFIG] No persisted overrides found in localStorage");return console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(o.keys()),engine:{runtime:Object.keys((v=s.runtime)!=null?v:{}),assets:Object.keys((j=s.assets)!=null?j:{}),splash:Object.keys((T=s.splash)!=null?T:{}),loading:Object.keys((O=s.loading)!=null?O:{}),start:Object.keys((M=s.start)!=null?M:{}),tutorial:Object.keys((_=s.tutorial)!=null?_:{}),endgame:Object.keys((C=s.endgame)!=null?C:{})},scene:a.scene_id||"unknown"}),l}function ta(r){var t,i,n,a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,j,T,O,M,_,C,x,S,E,I,L,A,P,k;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[R,z]of r.objects.entries()){let F=((t=z.identity)==null?void 0:t.id)||R;F.includes("character")&&(e.gameplay.character_pos=((i=z.transform)==null?void 0:i.position)||{x:0,y:0},e.gameplay.character_scale=((n=z.transform)==null?void 0:n.scale)||1,e.gameplay.character_anim_speed=((s=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:s.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),(F.includes("gun")||F.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)||{}),F.includes("diamond")&&(e.gameplay.diamond=z),F.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||{}),F.includes("water")&&(e.gameplay.water_drops=z),F.includes("crack")&&(e.gameplay.crack=z),F.includes("hand")&&(e.gameplay.hand=((w=z.gameplay)==null?void 0:w.tuning)||{},e.gameplay.brush_start_pos=((v=z.transform)==null?void 0:v.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((j=z.transform)==null?void 0:j.scale)||1.5),F.includes("hazard")&&(e.gameplay.hazard=((T=z.gameplay)==null?void 0:T.tuning)||{},e.gameplay.danger_pos=((O=z.transform)==null?void 0:O.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((_=(M=z.gameplay)==null?void 0:M.tuning)==null?void 0:_.danger_pulse)||{},e.gameplay.hazard_height=((x=(C=z.gameplay)==null?void 0:C.tuning)==null?void 0:x.hazard_height)||140)}return e.gameplay.timeline=((S=r.engine.runtime)==null?void 0:S.timeline)||{},e.gameplay.drag_surface=((E=r.engine.runtime)==null?void 0:E.drag_surface)||{},e.gameplay.background=((I=r.engine.runtime)==null?void 0:I.background)||{},e.gameplay.ui_styles=((L=r.engine.runtime)==null?void 0:L.ui_styles)||{},e.gameplay.label_pulse=((A=r.engine.runtime)==null?void 0:A.label_pulse)||{},e.ui=((P=r.engine.runtime)==null?void 0:P.ui)||{},e.theme=((k=r.engine.runtime)==null?void 0:k.theme)||{},e.assets=r.engine.assets||{},e}var Ys,K,Zn,Qn,ia=we(()=>{"use strict";ae();Ys=null,K="dev";if(typeof window!="undefined"){let r=window.__BUILD_SETTINGS__;if(r!=null&&r.buildMode)Ys=r,K=r.buildMode,console.log("[CONFIG] Loaded inline build settings:",r,"buildMode:",K);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);Ys=t,K=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",K)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",K)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",K);Zn=new Map,Qn=K==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function na(r,e){let t=[];function i(n,a,s=""){if(n!==a){if(typeof n!=typeof a){t.push(`${s}: type changed`);return}if(typeof n=="object"&&n!==null&&a!==null){let o=new Set([...Object.keys(n),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in n?l in a?i(n[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return i(r,e),t}function aa(r,e,t,i){let n={...t};for(let[a,s]of i.entries())n[a]&&s.defaults&&(n[a]={...s.defaults,...n[a]});return n}var Gt,tt,sa=we(()=>{"use strict";Gt=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},tt=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 i=`${e}?t=${Date.now()}&r=${Math.random()}`,n=await fetch(i,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(n.ok){let a=await n.text(),s=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,s)}else o||this.fileHashes.set(e,s)}}catch(i){console.warn(`Failed to check ${e}:`,i)}}determineEventType(e){var t,i;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:(i=e.split("/").pop())==null?void 0:i.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,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 oa(r){if(typeof window=="undefined")return;let e=typeof ra!="undefined"&&!!ra.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let n=null,a=!1,s=null;if(t){s=new tt;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=s}let o=new Set,l=h=>{var b,y;if(!s)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 w of m)w!=null&&w.object_config&&f.add(`configs/objects/${w.object_config}.json`);for(let w of o)f.has(w)||s.unwatch(w);for(let w of f)o.has(w)||s.watch(w,v=>g(v));o=f},c=new Set,d=!1,p=async h=>{let f=await Be(h),m=et(f,r.activeConfig.schemas),b=ht(m,r.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await r.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){r.audioSystem.destroy();let f=await _e("scene.main");r.setActiveConfig(f),r.gameObjectManager.updateConfig(f),r.CustomAssets.updateConfig(f),await r.CustomAssets.ready();let m=r.createAudioSystem(f);r.setAudioSystem(m),window.__audioSystem=m,await m.start(),r.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,n&&window.clearTimeout(n),n=window.setTimeout(()=>{u(h.type)},120)}e&&ra.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(r.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var ra,Ks=we(()=>{"use strict";sa();ia();ra={}});var Xs={};ot(Xs,{ConfigWatcher:()=>tt,DefaultReloadStrategy:()=>Gt,applyDefaults:()=>et,diffConfigs:()=>na,loadAllObjectConfigs:()=>Ii,loadComponentSchemas:()=>Ti,loadEngineConfig:()=>ki,loadGamePromptConfig:()=>ea,loadObjectCentricConfig:()=>_e,loadObjectConfig:()=>Be,loadSceneConfig:()=>Pi,rehydrateObject:()=>aa,setupHotReload:()=>oa,toLegacyFormat:()=>ta,validateObjectConfig:()=>ht});var Mi=we(()=>{"use strict";ia();sa();Ks()});var Ut={};ot(Ut,{AssetEditorModal:()=>ua});var ua,ft=we(()=>{"use strict";ua=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,i,n){this.currentObjectId=e,this.currentPath=t,this.currentAsset=i,this.onApplyCallback=n,this.createModal(e,i),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let i=document.createElement("div");i.className="asset-editor-modal",i.innerHTML=`
2
2
  <div class="asset-editor-card">
3
3
  <div class="asset-editor-header">
4
4
  <div>
@@ -94,7 +94,7 @@
94
94
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
95
95
  </div>
96
96
  </div>
97
- `,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.image&&this.image.naturalWidth>0&&this.image.naturalHeight>0?(console.log("[AssetCropModal] Image loaded:",this.image.naturalWidth,"x",this.image.naturalHeight),this.initializeCrop(),this.render()):(console.error("[AssetCropModal] Image loaded but invalid dimensions"),this.showError("Failed to load image"))},this.image.onerror=e=>{console.error("[AssetCropModal] Image load error:",e),this.showError("Failed to load image. Please check the image URL.")},this.image.src=this.options.imageSrc,this.canvas&&this.ctx&&(this.ctx.fillStyle="rgba(128, 128, 128, 0.3)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="rgba(255, 255, 255, 0.7)",this.ctx.font="14px sans-serif",this.ctx.textAlign="center",this.ctx.fillText("Loading image...",this.canvas.width/2,this.canvas.height/2)))}showError(e){var i;if(!this.canvas||!this.ctx)return;this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="rgba(255, 0, 0, 0.2)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="#ff4444",this.ctx.font="14px sans-serif",this.ctx.textAlign="center",this.ctx.fillText(e,this.canvas.width/2,this.canvas.height/2);let t=(i=this.modal)==null?void 0:i.querySelector(".asset-crop-preview-canvas");if(t){let n=t.getContext("2d");n&&(n.fillStyle="rgba(255, 0, 0, 0.2)",n.fillRect(0,0,t.width,t.height))}}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){if(!(!this.ctx||!this.canvas)){if(!this.image||!this.image.complete||this.image.naturalWidth===0||this.image.naturalHeight===0){console.warn("[AssetCropModal] Image not ready for rendering"),this.showError("Image not loaded");return}this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);try{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()}catch(e){console.error("[AssetCropModal] Error drawing image:",e),this.showError("Error drawing image");return}this.drawCropOverlay(),this.updatePreview()}}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image||!this.image.complete||this.image.naturalWidth===0||this.image.naturalHeight===0)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i,t.clearRect(0,0,i,i);let n=i/this.cropWidth,a=i/this.cropHeight,s=Math.min(n,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(i-o)/2,d=(i-l)/2;try{t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}catch(p){console.error("[AssetCropModal] Error drawing preview:",p),t.fillStyle="rgba(255, 0, 0, 0.2)",t.fillRect(0,0,i,i)}}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(r){new Ri().open(r)}});var Bl={};ot(Bl,{COLORS:()=>Le,ConfigWatcher:()=>tt,DebugPanel:()=>Jt,DefaultReloadStrategy:()=>Gt,Handler:()=>ye,PlayableLoadingScreen:()=>xn,PreviewShell:()=>yn,STROKE_WIDTH:()=>qr,THEME:()=>Vr,applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>Ai,applyDefaults:()=>et,baseLottie:()=>jn,bootstrap:()=>Ml,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Bs,configOverrideManager:()=>Gs,createPreviewShell:()=>Ga,deepClone:()=>ee,default:()=>We,defaultPreset:()=>ji,deviceGroups:()=>da,devicePresets:()=>ca,diffConfigs:()=>na,exportConfigsAsJSON:()=>Jn,exportConfigsFromActiveCache:()=>Qe,getConfigOverrides:()=>oe,getConfigStateSummary:()=>Fe,getOverrideMode:()=>Nt,getPresetById:()=>it,getPresetsByCategory:()=>sl,loadAllObjectConfigs:()=>Ii,loadComponentSchemas:()=>Ti,loadEngineConfig:()=>ki,loadGamePromptConfig:()=>ea,loadObjectCentricConfig:()=>_e,loadObjectConfig:()=>Be,loadSceneConfig:()=>Pi,redoLastConfigChange:()=>Ci,rehydrateObject:()=>aa,removeConfigOverride:()=>Ht,resetToApplied:()=>Ft,resetToOriginal:()=>Li,setBootstrapDependencies:()=>kl,setOverrideMode:()=>Xn,setupHotReload:()=>oa,setupLiveEditBridge:()=>vn,toLegacyFormat:()=>ta,trackObjectCreation:()=>Us,trackObjectDeletion:()=>qs,undoLastConfigChange:()=>Ei,validateObjectConfig:()=>ht});module.exports=go(Bl);var $e={};function li(r,e,t=!1){$e[r]||($e[r]=[]),$e[r].push({fn:e,once:t})}function In(r,e){if($e[r]){if(!e){delete $e[r];return}$e[r]=$e[r].filter(t=>t.fn!==e)}}function ci(r,...e){let t=$e[r];if(t)for(let i of[...t])i.fn(...e),i.once&&In(r,i.fn)}function ce(r,e){li(r,e,!0)}var ie=null,me=[],ct=null;function rs(r){ie=r,me=[],ct!==null&&(clearTimeout(ct),ct=null)}function os(){var r,e,t;return{endpoint:(ie==null?void 0:ie.endpoint)||"",transport:(ie==null?void 0:ie.transport)||"beacon",batchSize:(r=ie==null?void 0:ie.batchSize)!=null?r:10,flushIntervalMs:(e=ie==null?void 0:ie.flushIntervalMs)!=null?e:300,maxQueue:(t=ie==null?void 0:ie.maxQueue)!=null?t:200,debug:!!(ie!=null&&ie.debug)}}async function as(r,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function kn(r,e){let t=os();if(e&&t.endpoint){if(me.push(r),me.length>t.maxQueue&&(me=me.slice(me.length-t.maxQueue)),me.length>=t.batchSize){ss();return}ct===null&&(ct=window.setTimeout(()=>{ct=null,ss()},t.flushIntervalMs))}}async function ss(){let r=os();if(!r.endpoint||me.length===0)return;let e=me.splice(0,r.batchSize);await as(r.endpoint,{events:e},r.transport,r.debug),me.length>0&&await as(r.endpoint,{events:me.splice(0,r.batchSize)},r.transport,r.debug)}function ls(r){return Math.max(0,Math.min(1,r))}function ho(r){let e=String(r!=null?r:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function _t(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function fo(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function cs(r,e,t){try{r[e]=t}catch{}}function mo(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function ds(r,e){let t=r==null?void 0:r.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 ps(r,e){let t=mo(r);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function us(){let r=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&i()})},n=d=>{var u;r.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),i()},a=d=>{r.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=_t();for(let g of Array.from(r)){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=ls(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 P=f-y;m=ls(P)}let w=g.ease(m);g.yoyo&&y%2===1&&(w=1-w);for(let P of g.props)cs(g.target,P.key,P.from+(P.to-P.from)*w);g.scaleFrom&&g.scaleTo&&ds(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*w,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*w});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(f>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var P;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+((P=u==null?void 0:u.delayMsOverride)!=null?P:0)),f=ho(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"]),w=[];for(let I of Object.keys(p)){if(y.has(I))continue;let _=p[I];typeof _=="number"&&w.push({key:I,from:fo(d,I),to:_})}let v=ps(d,p);return{target:d,startMs:_t(),delayMs:h,durationMs:g,ease:f,props:w,scaleFrom:v.from,scaleTo:v.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 n(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=_t())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:_t(),h=_t()-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"&&cs(d,g,h)}let u=ps(d,p);u.to&&ds(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))s(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],f=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let w=typeof y=="string"?y.trim():"";return w.startsWith("+=")?u+Math.max(0,Number(w.slice(2))*1e3||0):w?Math.max(0,Number(w)*1e3||0):u},m=y=>{p.push(y);let w=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+w)},b={to(y,w,v){return m({kind:"to",target:y,vars:w,atMs:f(v)}),b},fromTo(y,w,v,P){return m({kind:"fromTo",target:y,vars:v,from:w,atMs:f(P)}),b},play(){var y,w;if(g)return b;g=!0,h=[];for(let v of p)v.kind==="fromTo"&&c.set(v.target,(y=v.from)!=null?y:{}),h.push(c.to(v.target,{...v.vars,delay:v.atMs/1e3+((w=v.vars.delay)!=null?w: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 gs(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=us()}catch{}}var hs={name:"handler-playable-sdk",version:"1.0.103",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 de=0,yo=de++,fs=de++,ms=de++,bs=de++,ys=de++,vs=de++,ws=de++,xs=de++,Ss=de++,Es=de++,Cs=de++,As=de++,Z=yo;function Ls(){return Z===fs}function Ts(){return Z===ms}function Is(){return Z===bs}function ks(){return Z===ys}function dt(){return Z===vs}function pt(){return Z===ws}function Ps(){return Z===xs}function Ms(){return Z===Ss}function js(){return Z===Es}function Pn(){return Z===Cs}function Mn(){return Z===As}function _s(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),Z=fs;return}catch{}else if(r==="dapi")try{dapi.isReady(),Z=ms;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Z=bs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Z=ys)}catch{}else if(e==="mintegral")window.gameReady&&(Z=vs);else if(e==="tapjoy")window.TJ_API&&(Z=ws);else if(e==="tiktok")window.openAppStore&&(Z=xs);else if(e==="smadex")try{window.smxTracking&&(Z=Ss)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Z=Es)}catch{}else e==="vungle"?Z=Cs:(r==="nucleo"||e==="nucleo")&&(Z=As)}var di=lt(require("lottie-web"),1),jn=di.default;typeof window!="undefined"&&(window.lottie=di.default,window.__baseLottie=di.default);var vo=require("pixi.js");var _n=require("pixi.js");var wo=null;function On(r){wo=r}ui();pi();var Ot=require("pixi.js");ui();var Lo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Dn=Lo;if(typeof window!="undefined")try{let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);e!=null&&e.buildMode&&(Dn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${Dn}`))}}catch{}function To(r){var t,i,n,a,s;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(r);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(r))return{x:(t=r[0])!=null?t:.5,y:(i=r[1])!=null?i:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(n=r.x)!=null?n:.5,y:(a=r.y)!=null?a:.5};if(typeof r=="string"){let o=r.trim().toLowerCase();return(s=e[o])!=null?s:{x:.5,y:.5}}return null}var Se=class{static async create(e,t,i){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${Dn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new Ot.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: ${n.type}, path: ${n.path}`);let s=await Xe.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new Ot.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=s==null?void 0:s.constructor)==null?void 0:u.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof Ot.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.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=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s: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=To(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 Rt=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 Po=lt(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Po);ut();var gi=require("pixi.js");ut();var Fn=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Rt}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(n=>!this.instanceCache.has(n));if(t.length===0)return;let i=async n=>{n.length&&(console.log("[Assets] Loading objects:",n),await Promise.all(n.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let l=await Se.create(a,s,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 i(t);let n=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));n.length>0&&(console.warn("[Assets] Retrying missing assets:",n),await i(n)),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 i=await Se.create(e,t,this.app);this.instanceCache.set(e,i)}}get(e){return this.instanceCache.get(e)}},Mo=new Fn,jo=new Proxy(Mo,{get(r,e){if(e in r&&typeof r[e]=="function")return r[e].bind(r);if(r.get(e))return r.get(e)}});ut();var Oo=require("pixi.js"),ke={width:400,height:600,designWidth:400,scaleFactor:1},fi={scale:1,position:1},Gn=[];function Ro(r,e,t,i,n,a,s){Gn.push({element:r,originalScale:a,positionHelper:e,heightPercent:n}),e(r,t,i,n,a,s,!1)}function zo(){Gn.forEach(({element:r,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*ke.scaleFactor;t(r,ke.width,ke.height,i,n,!0,!1)})}function Bn(r,e){console.log(`[SCREEN] updateScreenState called: ${r}x${e}`),ke.width=r,ke.height=e,ke.scaleFactor=Math.min(r/ke.designWidth,1.15),fi.scale=ke.scaleFactor,fi.position=1,console.log(`[SCREEN] Global multipliers - scale: ${fi.scale.toFixed(3)}`),zo()}var $t={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 $o(r,e,t){let i=$t[r];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${r}.${e} = ${t}`))}function Do(){return $t}var No={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 hi(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Ze(r,e={x:.5,y:.5}){var t;if(Array.isArray(r))return{x:hi(r[0],e.x),y:hi(r[1],e.y)};if(r&&typeof r=="object"){let i=r;return{x:hi(i.x,e.x),y:hi(i.y,e.y)}}if(typeof r=="string"){let i=r.trim().toLowerCase();return(t=No[i])!=null?t:e}return e}function Ne(r,e,t,i={}){var g,h,f,m,b,y;let n=Ze(t),a=(g=i.inset)!=null?g:{},s=(h=i.padding)!=null?h:{x:0,y:0},o=((f=a.left)!=null?f:0)+s.x,l=((m=a.right)!=null?m:0)+s.x,c=((b=a.top)!=null?b:0)+s.y,d=((y=a.bottom)!=null?y:0)+s.y,p=Math.max(0,r-o-l),u=Math.max(0,e-c-d);return{x:o+p*n.x,y:c+u*n.y}}function gt(r,e,t,i={}){var f,m,b,y,w,v;let n=(f=i.inset)!=null?f:{},a=(m=i.padding)!=null?m:{x:0,y:0},s=((b=n.left)!=null?b:0)+a.x,o=((y=n.right)!=null?y:0)+a.x,l=((w=n.top)!=null?w:0)+a.y,c=((v=n.bottom)!=null?v:0)+a.y,d=Math.max(0,r-s-o),p=Math.max(0,e-l-c),u=Ze(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:s+d*g,y:l+p*h}}if(typeof window!="undefined"){let r=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,n=window.innerHeight;(i!==r||n!==e)&&(r=i,e=n,Bn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Bn(window.innerWidth,window.innerHeight),window.updateDebugConfig=$o,window.getDebugConfig=Do,window.copyConfig=Xo,window.applyConfig=zt,window.applyConfigForRatio=Jo,window.positionAtBottom=Ns,window.positionAtTop=Bo,window.positionAtCenter=Go,window.positionAtLeft=Uo,window.positionAtRight=qo,window.positionAtBottomLeft=Vo,window.positionAtBottomRight=Yo,window.positionAtTopLeft=Wo,window.positionAtTopRight=Ko,window.applyPositionContract=Fo,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 mi(r,e,t=0){return r*e+t}function bi(r,e,t=0){return r*(1-e)+t}function yi(r,e,t=0){return r*e+t}function vi(r,e,t=0){return r*(1-e)+t}function ue(r,e=0){return r/2+e}function Ho(r,e){return r*e}function Fo(r,e,t,i){var s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,P,I,_,k,j;let n=0,a=0;switch(i.type){case"top":n=ue(e,(o=(s=i.offset)==null?void 0:s.x)!=null?o:0),a=mi(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=ue(e,(p=(d=i.offset)==null?void 0:d.x)!=null?p:0),a=bi(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=yi(e,i.percent,(f=(h=i.offset)==null?void 0:h.x)!=null?f:0),a=ue(t,(b=(m=i.offset)==null?void 0:m.y)!=null?b:0);break;case"right":n=vi(e,i.percent,(w=(y=i.offset)==null?void 0:y.x)!=null?w:0),a=ue(t,(P=(v=i.offset)==null?void 0:v.y)!=null?P:0);break;case"center":n=ue(e,(_=(I=i.offset)==null?void 0:I.x)!=null?_:0),a=ue(t,(j=(k=i.offset)==null?void 0:k.y)!=null?j:0);break}r.position?r.position.set(n,a):(r.x=n,r.y=a),i.scale!==void 0&&i.scale!==1&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(i.scale,i.scale):(r.scale.x=i.scale,r.scale.y=i.scale))}function Ns(r,e,t,i=.2,n=1,a=!0,s=!1){let o=Ho(t,i),l=bi(t,i/2);Pe(r,ue(e),l);let c=a?n*ke.scaleFactor:n;Me(r,c),s&&!Gn.find(d=>d.element===r)&&Ro(r,Ns,e,t,i,n,a)}function Bo(r,e,t,i=.1,n=1){Pe(r,ue(e),mi(t,i)),Me(r,n)}function Go(r,e,t,i=0,n=0,a=1){Pe(r,ue(e,i),ue(t,n)),Me(r,a)}function Uo(r,e,t,i=.1,n=1){Pe(r,yi(e,i),ue(t)),Me(r,n)}function qo(r,e,t,i=.1,n=1){Pe(r,vi(e,i),ue(t)),Me(r,n)}function Vo(r,e,t,i=.05,n=.05,a=1){Pe(r,yi(e,n),bi(t,i)),Me(r,a)}function Yo(r,e,t,i=.05,n=.05,a=1){Pe(r,vi(e,n),bi(t,i)),Me(r,a)}function Wo(r,e,t,i=.05,n=.05,a=1){Pe(r,yi(e,n),mi(t,i)),Me(r,a)}function Ko(r,e,t,i=.05,n=.05,a=1){Pe(r,vi(e,n),mi(t,i)),Me(r,a)}function Pe(r,e,t){r&&r.position?typeof r.position.set=="function"?r.position.set(e,t):(r.position.x=e,r.position.y=t):r&&(r.x=e,r.y=t)}function Me(r,e){e!==1&&r&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(e,e):r.scale.x!==void 0&&r.scale.y!==void 0&&(r.scale.x=e,r.scale.y=e))}var Je={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 Xo(r){return r&&Je[r]?JSON.parse(JSON.stringify(Je[r])):JSON.parse(JSON.stringify($t))}function zt(r){Object.keys(r).forEach(e=>{let t=e;$t[t]&&r[t]&&Object.assign($t[t],r[t])}),console.log("Config applied:",r)}function Jo(r,e){let t=r/e;t>1.6?(zt(Je.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(zt(Je.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(zt(Je.square),console.log("Applied SQUARE config for ratio:",t)):(zt(Je.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let r=window;r.configPresets=Je,r.resolveAnchorVec2=r.resolveAnchorVec2||Ze,r.resolveScreenAnchorPoint=r.resolveScreenAnchorPoint||Ne,r.resolveScreenRatioPoint=r.resolveScreenRatioPoint||gt}Mi();function ne(r,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(r,e);return`${r/i}:${e/i}`}var bd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ne(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ne(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ne(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ne(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ne(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ne(360,780)}],yd=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ne(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ne(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ne(412,915)}],vd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ne(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ne(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ne(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ne(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ne(800,1280)}],la=[{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:ne(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ne(768,1024),mraidScale:.7}];var ca=[...la],da=[{category:"playable",label:"Playable Ad",devices:la}],ji=la[0];function it(r){return ca.find(e=>e.id===r)||ji}function sl(r){return ca.filter(e=>e.category===r)}ae();var Ce=class{async updateProperty(e,t,i,n={}){var l,c,d,p,u,g,h,f,m,b,y,w;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(le({objectId:e,path:t,value:i},{persist:!0}),t==="transform"||t.startsWith("transform.")){console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);let v=s==null?void 0:s.motion;if(v&&typeof v=="object"&&v.enabled!==!1&&(((p=v==null?void 0:v.intro)==null?void 0:p.enabled)===!0||((u=v==null?void 0:v.pulse)==null?void 0:u.enabled)===!0||((g=v==null?void 0:v.swing)==null?void 0:g.enabled)===!0||((h=v==null?void 0:v.continuousMove)==null?void 0:h.enabled)===!0||((f=v==null?void 0:v.continuousRotate)==null?void 0:f.enabled)===!0||((m=v==null?void 0:v.orbit)==null?void 0:m.enabled)===!0)){let _=window.applyEditableObjectConfig;if(typeof _=="function"){let k=window.__editableConfig,j=(w=(y=(b=k==null?void 0:k.objects)==null?void 0:b.get)==null?void 0:y.call(b,e))!=null?w:s;await _(e,j),console.log("[PropertyUpdateManager] Applied config for motion object")}}n.refreshInspector||requestAnimationFrame(()=>{window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e}}))})}else{let v=window.applyEditableObjectConfig;if(typeof v=="function"){let P=window.__editableConfig,I=(d=(c=(l=P==null?void 0:P.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:s;await v(e,I),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function pa(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{var g,h,f,m;let s=n.result;if(!s||typeof s!="string"){alert("Failed to read file: Invalid data URL"),console.error("[QuickActionsBar] Invalid data URL:",typeof s,s==null?void 0:s.substring(0,50));return}if(!s.startsWith("data:image/")){alert("Invalid file format: Not an image file"),console.error("[QuickActionsBar] Invalid data URL format:",s.substring(0,100));return}let o=s.match(/^data:image\/[^;]+;base64,(.+)$/);if(!o||!o[1]||o[1].length===0){alert("Failed to read file: Invalid base64 data"),console.error("[QuickActionsBar] Invalid base64 data in data URL");return}try{let b=o[1],y=atob(b.substring(0,Math.min(100,b.length)));if(!y||y.length===0)throw new Error("Base64 decode test failed");console.log("[QuickActionsBar] \u2705 Data URL validated, length:",s.length)}catch(b){alert("Failed to read file: Corrupted image data"),console.error("[QuickActionsBar] Base64 validation failed:",b);return}let l=r.category||"misc",c=(r.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),d=((g=i.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:g[1])||"png",p=d==="jpg"?"jpeg":d,u=`${c||"new_asset"}_uploaded_${Date.now()}.${p}`;console.log("[QuickActionsBar] Uploading file:",u,"to category:",l,"data URL length:",s.length);try{let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:u,data:s,overwrite:!0})})).json();if(!(y!=null&&y.success)){alert(`Upload failed: ${(y==null?void 0:y.error)||"Unknown error"}`);return}await new Promise(x=>setTimeout(x,100));let w=window.addAssetToRegistry;typeof w=="function"&&(w(l,u),console.log("[QuickActionsBar] \u2705 Added to registry:",l,u));let v=window.getEditableAssets;if(typeof v=="function"){let x=v();x&&!x.categories&&(x.categories=[]),x!=null&&x.categories&&!x.categories.includes(l)&&(x.categories.push(l),console.log(`[QuickActionsBar] Added category ${l} to registry`))}let P=!1,I=0,_=10;for(;!P&&I<_;){I++,console.log(`[QuickActionsBar] Refresh attempt ${I}/${_}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[QuickActionsBar] \u2705 Registry rebuilt from disk")}catch{}await new Promise(C=>setTimeout(C,300));let x=window.refreshAssetLibrary;typeof x=="function"&&(console.log("[QuickActionsBar] Refreshing library panel..."),await x());let S=window.reRenderAssetLibrary;typeof S=="function"&&(console.log("[QuickActionsBar] Re-rendering library panel..."),S());let E=window.getEditableAssets;if(typeof E=="function"){let C=E(),A=((h=C==null?void 0:C.libraryAssets)==null?void 0:h[l])||[];A.some(O=>(O==null?void 0:O.filename)===u)?(console.log("[QuickActionsBar] \u2705 Asset found in registry!"),P=!0):(console.log(`[QuickActionsBar] Asset not found yet, retrying... (found ${A.length} assets in ${l})`),await new Promise(O=>setTimeout(O,500)))}else I>=2&&(P=!0)}P||console.warn("[QuickActionsBar] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway..."),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[QuickActionsBar] Dispatched config:changed event")}catch(x){console.warn("[QuickActionsBar] Failed to refresh textures:",x)}},300),console.log("[QuickActionsBar] Applying asset to object:",y.path);let k=!1,j=0,L=5;for(;!k&&j<L;){j++;try{await r.onApply(y.path),await new Promise(S=>setTimeout(S,200));let x=window.getEditableObjectConfig;if(typeof x=="function"){let S=x(r.objectId),E=((m=(f=S==null?void 0:S.render)==null?void 0:f.asset)==null?void 0:m.path)||"";E===y.path||E.includes(u)?(console.log("[QuickActionsBar] \u2705 Asset confirmed applied to object"),k=!0):(console.log(`[QuickActionsBar] Asset not applied yet (attempt ${j}), retrying...`),await new Promise(C=>setTimeout(C,300)))}else k=!0}catch(x){console.error(`[QuickActionsBar] Apply attempt ${j} failed:`,x),j<L&&await new Promise(S=>setTimeout(S,500))}}k?console.log("[QuickActionsBar] \u2705 Asset upload and apply complete!"):console.warn("[QuickActionsBar] \u26A0\uFE0F Asset may not have been applied, but upload succeeded")}catch(b){console.error("[QuickActionsBar] Upload error:",b),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var _i=class{constructor(){this.updateManager=new Ce}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,s);break;case"ai-edit":this.openAIEditor(t,i,s);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(n.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((s=n==null?void 0:n.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");pa({objectId:e,category:a,onApply:async o=>{var g,h;console.log("[QuickActionsBar] Upload complete, applying asset:",o);let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);if(typeof l=="function"&&c&&d){console.log("[QuickActionsBar] Applying asset to slot:",e,c,a);try{await l(e,c,a),console.log("[QuickActionsBar] \u2705 Asset applied to slot")}catch(f){console.error("[QuickActionsBar] Failed to apply asset to slot:",f)}}console.log("[QuickActionsBar] Updating property:",e,t,o);try{await this.updateManager.updateProperty(e,t,o),console.log("[QuickActionsBar] \u2705 Property updated")}catch(f){console.error("[QuickActionsBar] Failed to update property:",f)}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)},1e3),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e,action:"update",path:t}})),console.log("[QuickActionsBar] \u2705 Upload and apply complete")}})}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 i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(n):typeof s.schemas=="object"&&(o=s.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,s,"",{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 rl=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],ol=["environment","ui","character","system","backgrounds"],ll=["bg","world","ui"],Js={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}}},Oi=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=`
97
+ `,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.image&&this.image.naturalWidth>0&&this.image.naturalHeight>0?(console.log("[AssetCropModal] Image loaded:",this.image.naturalWidth,"x",this.image.naturalHeight),this.initializeCrop(),this.render()):(console.error("[AssetCropModal] Image loaded but invalid dimensions"),this.showError("Failed to load image"))},this.image.onerror=e=>{console.error("[AssetCropModal] Image load error:",e),this.showError("Failed to load image. Please check the image URL.")},this.image.src=this.options.imageSrc,this.canvas&&this.ctx&&(this.ctx.fillStyle="rgba(128, 128, 128, 0.3)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="rgba(255, 255, 255, 0.7)",this.ctx.font="14px sans-serif",this.ctx.textAlign="center",this.ctx.fillText("Loading image...",this.canvas.width/2,this.canvas.height/2)))}showError(e){var i;if(!this.canvas||!this.ctx)return;this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="rgba(255, 0, 0, 0.2)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.fillStyle="#ff4444",this.ctx.font="14px sans-serif",this.ctx.textAlign="center",this.ctx.fillText(e,this.canvas.width/2,this.canvas.height/2);let t=(i=this.modal)==null?void 0:i.querySelector(".asset-crop-preview-canvas");if(t){let n=t.getContext("2d");n&&(n.fillStyle="rgba(255, 0, 0, 0.2)",n.fillRect(0,0,t.width,t.height))}}initializeCrop(){var i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){if(!(!this.ctx||!this.canvas)){if(!this.image||!this.image.complete||this.image.naturalWidth===0||this.image.naturalHeight===0){console.warn("[AssetCropModal] Image not ready for rendering"),this.showError("Image not loaded");return}this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);try{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()}catch(e){console.error("[AssetCropModal] Error drawing image:",e),this.showError("Error drawing image");return}this.drawCropOverlay(),this.updatePreview()}}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+i-a,t],[e,t+n-a],[e+i-a,t+n-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image||!this.image.complete||this.image.naturalWidth===0||this.image.naturalHeight===0)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let i=150;e.width=i,e.height=i,t.clearRect(0,0,i,i);let n=i/this.cropWidth,a=i/this.cropHeight,s=Math.min(n,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(i-o)/2,d=(i-l)/2;try{t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}catch(p){console.error("[AssetCropModal] Error drawing preview:",p),t.fillStyle="rgba(255, 0, 0, 0.2)",t.fillRect(0,0,i,i)}}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(r){new Ri().open(r)}});var Bl={};ot(Bl,{COLORS:()=>Le,ConfigWatcher:()=>tt,DebugPanel:()=>Jt,DefaultReloadStrategy:()=>Gt,Handler:()=>ye,PlayableLoadingScreen:()=>xn,PreviewShell:()=>yn,STROKE_WIDTH:()=>qr,THEME:()=>Vr,applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>Ai,applyDefaults:()=>et,baseLottie:()=>jn,bootstrap:()=>Ml,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Bs,configOverrideManager:()=>Gs,createPreviewShell:()=>Ga,deepClone:()=>ee,default:()=>We,defaultPreset:()=>ji,deviceGroups:()=>da,devicePresets:()=>ca,diffConfigs:()=>na,exportConfigsAsJSON:()=>Jn,exportConfigsFromActiveCache:()=>Qe,getConfigOverrides:()=>oe,getConfigStateSummary:()=>Fe,getOverrideMode:()=>Nt,getPresetById:()=>it,getPresetsByCategory:()=>sl,loadAllObjectConfigs:()=>Ii,loadComponentSchemas:()=>Ti,loadEngineConfig:()=>ki,loadGamePromptConfig:()=>ea,loadObjectCentricConfig:()=>_e,loadObjectConfig:()=>Be,loadSceneConfig:()=>Pi,redoLastConfigChange:()=>Ci,rehydrateObject:()=>aa,removeConfigOverride:()=>Ht,resetToApplied:()=>Ft,resetToOriginal:()=>Li,setBootstrapDependencies:()=>kl,setOverrideMode:()=>Xn,setupHotReload:()=>oa,setupLiveEditBridge:()=>vn,toLegacyFormat:()=>ta,trackObjectCreation:()=>Us,trackObjectDeletion:()=>qs,undoLastConfigChange:()=>Ei,validateObjectConfig:()=>ht});module.exports=go(Bl);var $e={};function li(r,e,t=!1){$e[r]||($e[r]=[]),$e[r].push({fn:e,once:t})}function In(r,e){if($e[r]){if(!e){delete $e[r];return}$e[r]=$e[r].filter(t=>t.fn!==e)}}function ci(r,...e){let t=$e[r];if(t)for(let i of[...t])i.fn(...e),i.once&&In(r,i.fn)}function ce(r,e){li(r,e,!0)}var ie=null,me=[],ct=null;function rs(r){ie=r,me=[],ct!==null&&(clearTimeout(ct),ct=null)}function os(){var r,e,t;return{endpoint:(ie==null?void 0:ie.endpoint)||"",transport:(ie==null?void 0:ie.transport)||"beacon",batchSize:(r=ie==null?void 0:ie.batchSize)!=null?r:10,flushIntervalMs:(e=ie==null?void 0:ie.flushIntervalMs)!=null?e:300,maxQueue:(t=ie==null?void 0:ie.maxQueue)!=null?t:200,debug:!!(ie!=null&&ie.debug)}}async function as(r,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(r,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(a){i&&console.warn("[handler.telemetry] fetch failed",a)}}function kn(r,e){let t=os();if(e&&t.endpoint){if(me.push(r),me.length>t.maxQueue&&(me=me.slice(me.length-t.maxQueue)),me.length>=t.batchSize){ss();return}ct===null&&(ct=window.setTimeout(()=>{ct=null,ss()},t.flushIntervalMs))}}async function ss(){let r=os();if(!r.endpoint||me.length===0)return;let e=me.splice(0,r.batchSize);await as(r.endpoint,{events:e},r.transport,r.debug),me.length>0&&await as(r.endpoint,{events:me.splice(0,r.batchSize)},r.transport,r.debug)}function ls(r){return Math.max(0,Math.min(1,r))}function ho(r){let e=String(r!=null?r:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function _t(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function fo(r,e){let t=r==null?void 0:r[e];return typeof t=="number"?t:0}function cs(r,e,t){try{r[e]=t}catch{}}function mo(r){let e=r==null?void 0:r.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function ds(r,e){let t=r==null?void 0:r.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 ps(r,e){let t=mo(r);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function us(){let r=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),r.size>0&&i()})},n=d=>{var u;r.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),i()},a=d=>{r.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=_t();for(let g of Array.from(r)){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=ls(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 j=f-y;m=ls(j)}let w=g.ease(m);g.yoyo&&y%2===1&&(w=1-w);for(let j of g.props)cs(g.target,j.key,j.from+(j.to-j.from)*w);g.scaleFrom&&g.scaleTo&&ds(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*w,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*w});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(f>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var j;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+((j=u==null?void 0:u.delayMsOverride)!=null?j:0)),f=ho(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"]),w=[];for(let T of Object.keys(p)){if(y.has(T))continue;let O=p[T];typeof O=="number"&&w.push({key:T,from:fo(d,T),to:O})}let v=ps(d,p);return{target:d,startMs:_t(),delayMs:h,durationMs:g,ease:f,props:w,scaleFrom:v.from,scaleTo:v.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 n(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=_t())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:_t(),h=_t()-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"&&cs(d,g,h)}let u=ps(d,p);u.to&&ds(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))s(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],f=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let w=typeof y=="string"?y.trim():"";return w.startsWith("+=")?u+Math.max(0,Number(w.slice(2))*1e3||0):w?Math.max(0,Number(w)*1e3||0):u},m=y=>{p.push(y);let w=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+w)},b={to(y,w,v){return m({kind:"to",target:y,vars:w,atMs:f(v)}),b},fromTo(y,w,v,j){return m({kind:"fromTo",target:y,vars:v,from:w,atMs:f(j)}),b},play(){var y,w;if(g)return b;g=!0,h=[];for(let v of p)v.kind==="fromTo"&&c.set(v.target,(y=v.from)!=null?y:{}),h.push(c.to(v.target,{...v.vars,delay:v.atMs/1e3+((w=v.vars.delay)!=null?w: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 gs(){if(typeof window=="undefined")return;let r=window;if(!r.gsap)try{r.gsap=us()}catch{}}var hs={name:"handler-playable-sdk",version:"1.0.105",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 de=0,yo=de++,fs=de++,ms=de++,bs=de++,ys=de++,vs=de++,ws=de++,xs=de++,Ss=de++,Es=de++,Cs=de++,As=de++,Z=yo;function Ls(){return Z===fs}function Ts(){return Z===ms}function Is(){return Z===bs}function ks(){return Z===ys}function dt(){return Z===vs}function pt(){return Z===ws}function Ps(){return Z===xs}function Ms(){return Z===Ss}function js(){return Z===Es}function Pn(){return Z===Cs}function Mn(){return Z===As}function _s(){let r=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(r==="mraid")try{mraid.getState(),Z=fs;return}catch{}else if(r==="dapi")try{dapi.isReady(),Z=ms;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(Z=bs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(Z=ys)}catch{}else if(e==="mintegral")window.gameReady&&(Z=vs);else if(e==="tapjoy")window.TJ_API&&(Z=ws);else if(e==="tiktok")window.openAppStore&&(Z=xs);else if(e==="smadex")try{window.smxTracking&&(Z=Ss)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(Z=Es)}catch{}else e==="vungle"?Z=Cs:(r==="nucleo"||e==="nucleo")&&(Z=As)}var di=lt(require("lottie-web"),1),jn=di.default;typeof window!="undefined"&&(window.lottie=di.default,window.__baseLottie=di.default);var vo=require("pixi.js");var _n=require("pixi.js");var wo=null;function On(r){wo=r}ui();pi();var Ot=require("pixi.js");ui();var Lo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Dn=Lo;if(typeof window!="undefined")try{let r=new XMLHttpRequest;if(r.open("GET","./build-settings.json",!1),r.send(),r.status===200&&r.responseText){let e=JSON.parse(r.responseText);e!=null&&e.buildMode&&(Dn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${Dn}`))}}catch{}function To(r){var t,i,n,a,s;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(r);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(r))return{x:(t=r[0])!=null?t:.5,y:(i=r[1])!=null?i:.5};if(r&&typeof r=="object"&&"x"in r&&"y"in r)return{x:(n=r.x)!=null?n:.5,y:(a=r.y)!=null?a:.5};if(typeof r=="string"){let o=r.trim().toLowerCase();return(s=e[o])!=null?s:{x:.5,y:.5}}return null}var Se=class{static async create(e,t,i){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${Dn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new Ot.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: ${n.type}, path: ${n.path}`);let s=await Xe.load(e,n,i,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new Ot.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=s==null?void 0:s.constructor)==null?void 0:u.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof Ot.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.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=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,i){var n,a,s,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s: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=To(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 Rt=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 Po=lt(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Po);ut();var gi=require("pixi.js");ut();var Fn=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Rt}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(n=>!this.instanceCache.has(n));if(t.length===0)return;let i=async n=>{n.length&&(console.log("[Assets] Loading objects:",n),await Promise.all(n.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let l=await Se.create(a,s,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 i(t);let n=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));n.length>0&&(console.warn("[Assets] Retrying missing assets:",n),await i(n)),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 i=await Se.create(e,t,this.app);this.instanceCache.set(e,i)}}get(e){return this.instanceCache.get(e)}},Mo=new Fn,jo=new Proxy(Mo,{get(r,e){if(e in r&&typeof r[e]=="function")return r[e].bind(r);if(r.get(e))return r.get(e)}});ut();var Oo=require("pixi.js"),ke={width:400,height:600,designWidth:400,scaleFactor:1},fi={scale:1,position:1},Gn=[];function Ro(r,e,t,i,n,a,s){Gn.push({element:r,originalScale:a,positionHelper:e,heightPercent:n}),e(r,t,i,n,a,s,!1)}function zo(){Gn.forEach(({element:r,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*ke.scaleFactor;t(r,ke.width,ke.height,i,n,!0,!1)})}function Bn(r,e){console.log(`[SCREEN] updateScreenState called: ${r}x${e}`),ke.width=r,ke.height=e,ke.scaleFactor=Math.min(r/ke.designWidth,1.15),fi.scale=ke.scaleFactor,fi.position=1,console.log(`[SCREEN] Global multipliers - scale: ${fi.scale.toFixed(3)}`),zo()}var $t={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 $o(r,e,t){let i=$t[r];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${r}.${e} = ${t}`))}function Do(){return $t}var No={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 hi(r,e){return typeof r=="number"&&Number.isFinite(r)?r:e}function Ze(r,e={x:.5,y:.5}){var t;if(Array.isArray(r))return{x:hi(r[0],e.x),y:hi(r[1],e.y)};if(r&&typeof r=="object"){let i=r;return{x:hi(i.x,e.x),y:hi(i.y,e.y)}}if(typeof r=="string"){let i=r.trim().toLowerCase();return(t=No[i])!=null?t:e}return e}function Ne(r,e,t,i={}){var g,h,f,m,b,y;let n=Ze(t),a=(g=i.inset)!=null?g:{},s=(h=i.padding)!=null?h:{x:0,y:0},o=((f=a.left)!=null?f:0)+s.x,l=((m=a.right)!=null?m:0)+s.x,c=((b=a.top)!=null?b:0)+s.y,d=((y=a.bottom)!=null?y:0)+s.y,p=Math.max(0,r-o-l),u=Math.max(0,e-c-d);return{x:o+p*n.x,y:c+u*n.y}}function gt(r,e,t,i={}){var f,m,b,y,w,v;let n=(f=i.inset)!=null?f:{},a=(m=i.padding)!=null?m:{x:0,y:0},s=((b=n.left)!=null?b:0)+a.x,o=((y=n.right)!=null?y:0)+a.x,l=((w=n.top)!=null?w:0)+a.y,c=((v=n.bottom)!=null?v:0)+a.y,d=Math.max(0,r-s-o),p=Math.max(0,e-l-c),u=Ze(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:s+d*g,y:l+p*h}}if(typeof window!="undefined"){let r=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,n=window.innerHeight;(i!==r||n!==e)&&(r=i,e=n,Bn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Bn(window.innerWidth,window.innerHeight),window.updateDebugConfig=$o,window.getDebugConfig=Do,window.copyConfig=Xo,window.applyConfig=zt,window.applyConfigForRatio=Jo,window.positionAtBottom=Ns,window.positionAtTop=Bo,window.positionAtCenter=Go,window.positionAtLeft=Uo,window.positionAtRight=qo,window.positionAtBottomLeft=Vo,window.positionAtBottomRight=Yo,window.positionAtTopLeft=Wo,window.positionAtTopRight=Ko,window.applyPositionContract=Fo,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 mi(r,e,t=0){return r*e+t}function bi(r,e,t=0){return r*(1-e)+t}function yi(r,e,t=0){return r*e+t}function vi(r,e,t=0){return r*(1-e)+t}function ue(r,e=0){return r/2+e}function Ho(r,e){return r*e}function Fo(r,e,t,i){var s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,j,T,O,M,_;let n=0,a=0;switch(i.type){case"top":n=ue(e,(o=(s=i.offset)==null?void 0:s.x)!=null?o:0),a=mi(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=ue(e,(p=(d=i.offset)==null?void 0:d.x)!=null?p:0),a=bi(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=yi(e,i.percent,(f=(h=i.offset)==null?void 0:h.x)!=null?f:0),a=ue(t,(b=(m=i.offset)==null?void 0:m.y)!=null?b:0);break;case"right":n=vi(e,i.percent,(w=(y=i.offset)==null?void 0:y.x)!=null?w:0),a=ue(t,(j=(v=i.offset)==null?void 0:v.y)!=null?j:0);break;case"center":n=ue(e,(O=(T=i.offset)==null?void 0:T.x)!=null?O:0),a=ue(t,(_=(M=i.offset)==null?void 0:M.y)!=null?_:0);break}r.position?r.position.set(n,a):(r.x=n,r.y=a),i.scale!==void 0&&i.scale!==1&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(i.scale,i.scale):(r.scale.x=i.scale,r.scale.y=i.scale))}function Ns(r,e,t,i=.2,n=1,a=!0,s=!1){let o=Ho(t,i),l=bi(t,i/2);Pe(r,ue(e),l);let c=a?n*ke.scaleFactor:n;Me(r,c),s&&!Gn.find(d=>d.element===r)&&Ro(r,Ns,e,t,i,n,a)}function Bo(r,e,t,i=.1,n=1){Pe(r,ue(e),mi(t,i)),Me(r,n)}function Go(r,e,t,i=0,n=0,a=1){Pe(r,ue(e,i),ue(t,n)),Me(r,a)}function Uo(r,e,t,i=.1,n=1){Pe(r,yi(e,i),ue(t)),Me(r,n)}function qo(r,e,t,i=.1,n=1){Pe(r,vi(e,i),ue(t)),Me(r,n)}function Vo(r,e,t,i=.05,n=.05,a=1){Pe(r,yi(e,n),bi(t,i)),Me(r,a)}function Yo(r,e,t,i=.05,n=.05,a=1){Pe(r,vi(e,n),bi(t,i)),Me(r,a)}function Wo(r,e,t,i=.05,n=.05,a=1){Pe(r,yi(e,n),mi(t,i)),Me(r,a)}function Ko(r,e,t,i=.05,n=.05,a=1){Pe(r,vi(e,n),mi(t,i)),Me(r,a)}function Pe(r,e,t){r&&r.position?typeof r.position.set=="function"?r.position.set(e,t):(r.position.x=e,r.position.y=t):r&&(r.x=e,r.y=t)}function Me(r,e){e!==1&&r&&r.scale&&(typeof r.scale.set=="function"?r.scale.set(e,e):r.scale.x!==void 0&&r.scale.y!==void 0&&(r.scale.x=e,r.scale.y=e))}var Je={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 Xo(r){return r&&Je[r]?JSON.parse(JSON.stringify(Je[r])):JSON.parse(JSON.stringify($t))}function zt(r){Object.keys(r).forEach(e=>{let t=e;$t[t]&&r[t]&&Object.assign($t[t],r[t])}),console.log("Config applied:",r)}function Jo(r,e){let t=r/e;t>1.6?(zt(Je.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(zt(Je.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(zt(Je.square),console.log("Applied SQUARE config for ratio:",t)):(zt(Je.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let r=window;r.configPresets=Je,r.resolveAnchorVec2=r.resolveAnchorVec2||Ze,r.resolveScreenAnchorPoint=r.resolveScreenAnchorPoint||Ne,r.resolveScreenRatioPoint=r.resolveScreenRatioPoint||gt}Mi();function ne(r,e){let t=(n,a)=>a===0?n:t(a,n%a),i=t(r,e);return`${r/i}:${e/i}`}var bd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:ne(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:ne(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:ne(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:ne(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:ne(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:ne(360,780)}],yd=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:ne(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:ne(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:ne(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:ne(412,915)}],vd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:ne(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:ne(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:ne(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:ne(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:ne(800,1280)}],la=[{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:ne(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:ne(768,1024),mraidScale:.7}];var ca=[...la],da=[{category:"playable",label:"Playable Ad",devices:la}],ji=la[0];function it(r){return ca.find(e=>e.id===r)||ji}function sl(r){return ca.filter(e=>e.category===r)}ae();var Ce=class{async updateProperty(e,t,i,n={}){var l,c,d,p,u,g,h,f,m,b,y,w;console.log("[PropertyUpdateManager] Updating:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(le({objectId:e,path:t,value:i},{persist:!0}),t==="transform"||t.startsWith("transform.")){console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);let v=s==null?void 0:s.motion;if(v&&typeof v=="object"&&v.enabled!==!1&&(((p=v==null?void 0:v.intro)==null?void 0:p.enabled)===!0||((u=v==null?void 0:v.pulse)==null?void 0:u.enabled)===!0||((g=v==null?void 0:v.swing)==null?void 0:g.enabled)===!0||((h=v==null?void 0:v.continuousMove)==null?void 0:h.enabled)===!0||((f=v==null?void 0:v.continuousRotate)==null?void 0:f.enabled)===!0||((m=v==null?void 0:v.orbit)==null?void 0:m.enabled)===!0)){let O=window.applyEditableObjectConfig;if(typeof O=="function"){let M=window.__editableConfig,_=(w=(y=(b=M==null?void 0:M.objects)==null?void 0:b.get)==null?void 0:y.call(b,e))!=null?w:s;await O(e,_),console.log("[PropertyUpdateManager] Applied config for motion object")}}n.refreshInspector||requestAnimationFrame(()=>{window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e}}))})}else{let v=window.applyEditableObjectConfig;if(typeof v=="function"){let j=window.__editableConfig,T=(d=(c=(l=j==null?void 0:j.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:s;await v(e,T),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let a of i)if(n&&typeof n=="object"&&a in n)n=n[a];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function pa(r){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let i=(a=t.target.files)==null?void 0:a[0];if(!i)return;let n=new FileReader;n.onload=async()=>{var g,h,f,m;let s=n.result;if(!s||typeof s!="string"){alert("Failed to read file: Invalid data URL"),console.error("[QuickActionsBar] Invalid data URL:",typeof s,s==null?void 0:s.substring(0,50));return}if(!s.startsWith("data:image/")){alert("Invalid file format: Not an image file"),console.error("[QuickActionsBar] Invalid data URL format:",s.substring(0,100));return}let o=s.match(/^data:image\/[^;]+;base64,(.+)$/);if(!o||!o[1]||o[1].length===0){alert("Failed to read file: Invalid base64 data"),console.error("[QuickActionsBar] Invalid base64 data in data URL");return}try{let b=o[1],y=atob(b.substring(0,Math.min(100,b.length)));if(!y||y.length===0)throw new Error("Base64 decode test failed");console.log("[QuickActionsBar] \u2705 Data URL validated, length:",s.length)}catch(b){alert("Failed to read file: Corrupted image data"),console.error("[QuickActionsBar] Base64 validation failed:",b);return}let l=r.category||"misc",c=(r.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),d=((g=i.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:g[1])||"png",p=d==="jpg"?"jpeg":d,u=`${c||"new_asset"}_uploaded_${Date.now()}.${p}`;console.log("[QuickActionsBar] Uploading file:",u,"to category:",l,"data URL length:",s.length);try{let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:u,data:s,overwrite:!0})})).json();if(!(y!=null&&y.success)){alert(`Upload failed: ${(y==null?void 0:y.error)||"Unknown error"}`);return}await new Promise(x=>setTimeout(x,100));let w=window.addAssetToRegistry;typeof w=="function"&&(w(l,u),console.log("[QuickActionsBar] \u2705 Added to registry:",l,u));let v=window.getEditableAssets;if(typeof v=="function"){let x=v();x&&!x.categories&&(x.categories=[]),x!=null&&x.categories&&!x.categories.includes(l)&&(x.categories.push(l),console.log(`[QuickActionsBar] Added category ${l} to registry`))}let j=!1,T=0,O=10;for(;!j&&T<O;){T++,console.log(`[QuickActionsBar] Refresh attempt ${T}/${O}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[QuickActionsBar] \u2705 Registry rebuilt from disk")}catch{}await new Promise(I=>setTimeout(I,300));let x=window.refreshAssetLibrary;typeof x=="function"&&(console.log("[QuickActionsBar] Refreshing library panel..."),await x());let S=window.reRenderAssetLibrary;typeof S=="function"&&(console.log("[QuickActionsBar] Re-rendering library panel..."),S());let E=window.getEditableAssets;if(typeof E=="function"){let I=E(),L=((h=I==null?void 0:I.libraryAssets)==null?void 0:h[l])||[];L.some(P=>(P==null?void 0:P.filename)===u)?(console.log("[QuickActionsBar] \u2705 Asset found in registry!"),j=!0):(console.log(`[QuickActionsBar] Asset not found yet, retrying... (found ${L.length} assets in ${l})`),await new Promise(P=>setTimeout(P,500)))}else T>=2&&(j=!0)}j||console.warn("[QuickActionsBar] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway..."),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[QuickActionsBar] Dispatched config:changed event")}catch(x){console.warn("[QuickActionsBar] Failed to refresh textures:",x)}},300),console.log("[QuickActionsBar] Applying asset to object:",y.path);let M=!1,_=0,C=5;for(;!M&&_<C;){_++;try{await r.onApply(y.path),await new Promise(S=>setTimeout(S,200));let x=window.getEditableObjectConfig;if(typeof x=="function"){let S=x(r.objectId),E=((m=(f=S==null?void 0:S.render)==null?void 0:f.asset)==null?void 0:m.path)||"";E===y.path||E.includes(u)?(console.log("[QuickActionsBar] \u2705 Asset confirmed applied to object"),M=!0):(console.log(`[QuickActionsBar] Asset not applied yet (attempt ${_}), retrying...`),await new Promise(I=>setTimeout(I,300)))}else M=!0}catch(x){console.error(`[QuickActionsBar] Apply attempt ${_} failed:`,x),_<C&&await new Promise(S=>setTimeout(S,500))}}M?console.log("[QuickActionsBar] \u2705 Asset upload and apply complete!"):console.warn("[QuickActionsBar] \u26A0\uFE0F Asset may not have been applied, but upload succeeded")}catch(b){console.error("[QuickActionsBar] Upload error:",b),alert("Upload failed. Check console.")}},n.readAsDataURL(i)},e.click()}var _i=class{constructor(){this.updateManager=new Ce}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let a=n(t);if(!a)return;let s=this.updateManager.getNestedProperty(a,i);if(e==="ai-convert"||e==="upload"||e==="library"){let o=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,s);break;case"ai-edit":this.openAIEditor(t,i,s);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),n.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),n.categories&&!n.categories.includes(d)&&n.categories.push(d),n.libraryAssets&&!n.libraryAssets[d]&&(n.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,i){var a;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(n.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let a=t.split(".").pop()||t;n(a,`Edit ${a} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var s;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e),a=((s=n==null?void 0:n.identity)==null?void 0:s.category)||(t.split(".")[0]==="render"?"environment":"ui");pa({objectId:e,category:a,onApply:async o=>{var g,h;console.log("[QuickActionsBar] Upload complete, applying asset:",o);let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);if(typeof l=="function"&&c&&d){console.log("[QuickActionsBar] Applying asset to slot:",e,c,a);try{await l(e,c,a),console.log("[QuickActionsBar] \u2705 Asset applied to slot")}catch(f){console.error("[QuickActionsBar] Failed to apply asset to slot:",f)}}console.log("[QuickActionsBar] Updating property:",e,t,o);try{await this.updateManager.updateProperty(e,t,o),console.log("[QuickActionsBar] \u2705 Property updated")}catch(f){console.error("[QuickActionsBar] Failed to update property:",f)}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)},1e3),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:e,action:"update",path:t}})),console.log("[QuickActionsBar] \u2705 Upload and apply complete")}})}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 i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],a=i.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(n):typeof s.schemas=="object"&&(o=s.schemas[n]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),n(e,s,"",{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 rl=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],ol=["environment","ui","character","system","backgrounds"],ll=["bg","world","ui"],Js={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}}},Oi=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=`
98
98
  <div class="wizard-card">
99
99
  <div class="wizard-header">
100
100
  <div class="wizard-title">
@@ -603,18 +603,18 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
603
603
  <button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Create Spawner</button>
604
604
  </div>
605
605
  </div>
606
- `;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(w=>{w.addEventListener("click",()=>{var P;let v=w.dataset.tab;d.forEach(I=>I.classList.remove("active")),p.forEach(I=>I.classList.remove("active")),w.classList.add("active"),(P=t.querySelector(`[data-tab-content="${v}"]`))==null||P.classList.add("active")})});let u=w=>{let v=w.trim();if(!v)return null;try{return JSON.parse(v)}catch{return null}},g=()=>{var H;let w=t.querySelector("#spawner-instance-id").value.trim(),v=t.querySelector("#spawner-template-id").value.trim(),P=t.querySelector("#spawner-spawn-templates").value,I=t.querySelector("#spawner-position-source").value.trim(),_=t.querySelector("#spawner-point-mode").value.trim(),k=t.querySelector("#spawner-spawn-points").value,j=t.querySelector("#spawner-pattern").value.trim(),L=Number(t.querySelector("#spawner-rate").value.trim()),x=Number(t.querySelector("#spawner-pool").value.trim()),S=Number(t.querySelector("#spawner-lifetime").value.trim()),E=t.querySelector("#spawner-return-on-invisible").checked,C=t.querySelector("#spawner-movement").value.trim(),A=Number(t.querySelector("#spawner-vel-x").value.trim()),T=Number(t.querySelector("#spawner-vel-y").value.trim()),O=t.querySelector("#spawner-velocity-range").value,M=u(P),R=Array.isArray(M)&&M.length?M:null,z=typeof((H=R==null?void 0:R[0])==null?void 0:H.templateId)=="string"?String(R[0].templateId):v;if(!w){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let F={templateId:z,spawnPattern:j,spawnRate:Number.isFinite(L)?L:650,poolSize:Number.isFinite(x)?x:18,returnOnInvisible:E,positionSource:I,spawnPointMode:_,movementMode:C,lifetime:Number.isFinite(S)?S:5e3};R&&(F.spawnTemplates=R);let q=u(k);Array.isArray(q)&&(F.spawnPoints=q),Number.isFinite(A)&&Number.isFinite(T)&&(F.velocity={x:A,y:T});let N=u(O);N&&typeof N=="object"&&(F.velocityRange=N),c(),e({templateId:z,instanceId:w,spawnerProps:F})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",w=>w.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",w=>{w.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,i){let n=`json.${t}`,a={identity:{id:n,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:n};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${i}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:i,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 i=t!=null?t:await this.promptScreen();if(!i)return;let n=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(n);if(!a)return;let s=a,o=this.buildDefaultConfig(e,s,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:s,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(`
606
+ `;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(w=>{w.addEventListener("click",()=>{var j;let v=w.dataset.tab;d.forEach(T=>T.classList.remove("active")),p.forEach(T=>T.classList.remove("active")),w.classList.add("active"),(j=t.querySelector(`[data-tab-content="${v}"]`))==null||j.classList.add("active")})});let u=w=>{let v=w.trim();if(!v)return null;try{return JSON.parse(v)}catch{return null}},g=()=>{var H;let w=t.querySelector("#spawner-instance-id").value.trim(),v=t.querySelector("#spawner-template-id").value.trim(),j=t.querySelector("#spawner-spawn-templates").value,T=t.querySelector("#spawner-position-source").value.trim(),O=t.querySelector("#spawner-point-mode").value.trim(),M=t.querySelector("#spawner-spawn-points").value,_=t.querySelector("#spawner-pattern").value.trim(),C=Number(t.querySelector("#spawner-rate").value.trim()),x=Number(t.querySelector("#spawner-pool").value.trim()),S=Number(t.querySelector("#spawner-lifetime").value.trim()),E=t.querySelector("#spawner-return-on-invisible").checked,I=t.querySelector("#spawner-movement").value.trim(),L=Number(t.querySelector("#spawner-vel-x").value.trim()),A=Number(t.querySelector("#spawner-vel-y").value.trim()),P=t.querySelector("#spawner-velocity-range").value,k=u(j),R=Array.isArray(k)&&k.length?k:null,z=typeof((H=R==null?void 0:R[0])==null?void 0:H.templateId)=="string"?String(R[0].templateId):v;if(!w){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let F={templateId:z,spawnPattern:_,spawnRate:Number.isFinite(C)?C:650,poolSize:Number.isFinite(x)?x:18,returnOnInvisible:E,positionSource:T,spawnPointMode:O,movementMode:I,lifetime:Number.isFinite(S)?S:5e3};R&&(F.spawnTemplates=R);let q=u(M);Array.isArray(q)&&(F.spawnPoints=q),Number.isFinite(L)&&Number.isFinite(A)&&(F.velocity={x:L,y:A});let N=u(P);N&&typeof N=="object"&&(F.velocityRange=N),c(),e({templateId:z,instanceId:w,spawnerProps:F})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",w=>w.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",w=>{w.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,i){let n=`json.${t}`,a={identity:{id:n,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:n};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${i}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:i,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 i=t!=null?t:await this.promptScreen();if(!i)return;let n=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(n);if(!a)return;let s=a,o=this.buildDefaultConfig(e,s,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:s,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(`
607
607
  `))||(u==null?void 0:u.error)||"Failed to create object.";alert(h);return}let{trackObjectCreation:g}=await Promise.resolve().then(()=>(ae(),je));g(s,i,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 s,o,l;this.close();let i=t!=null?t:await this.promptScreen();if(!i)return;let n=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",a=await this.promptName(n);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:i,forceSync:!0})}),d=await c.json().catch(()=>({}));if(!c.ok||(d==null?void 0:d.success)===!1){let p=((s=d==null?void 0:d.errors)==null?void 0:s.join(`
608
- `))||(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 n,a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,P,I,_,k,j,L,x,S,E,C;this.close();let i=t!=null?t:await this.promptScreen();if(i){if(e==="collectable-system")try{let A=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((n=T==null?void 0:T.errors)==null?void 0:n.join(`
609
- `))||(T==null?void 0:T.error)||"Failed to create collectable system.";alert(O);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(s=(a=this.options).onRefresh)==null||s.call(a)}catch(A){alert(`Failed to create collectable system: ${A instanceof Error?A.message:String(A)}`)}if(e==="drag-snap-couples")try{let A=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((o=T==null?void 0:T.errors)==null?void 0:o.join(`
610
- `))||(T==null?void 0:T.error)||"Failed to create drag-snap system.";alert(O);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(A){alert(`Failed to create drag-snap system: ${A instanceof Error?A.message:String(A)}`)}if(e==="swerve-collect")try{let A=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((d=T==null?void 0:T.errors)==null?void 0:d.join(`
611
- `))||(T==null?void 0:T.error)||"Failed to create swerve collect system.";alert(O);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(A){alert(`Failed to create swerve collect system: ${A instanceof Error?A.message:String(A)}`)}if(e==="tap-destroy")try{let A=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((g=T==null?void 0:T.errors)==null?void 0:g.join(`
612
- `))||(T==null?void 0:T.error)||"Failed to create tap destroy system.";alert(O);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(A){alert(`Failed to create tap destroy system: ${A instanceof Error?A.message:String(A)}`)}if(e==="scratch-card")try{let A=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((m=T==null?void 0:T.errors)==null?void 0:m.join(`
613
- `))||(T==null?void 0:T.error)||"Failed to create scratch card system.";alert(O);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(A){alert(`Failed to create scratch card system: ${A instanceof Error?A.message:String(A)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let T=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,withHand:e==="start-screen"})}),O=await T.json().catch(()=>({}));if(!T.ok||(O==null?void 0:O.success)===!1){let M=((w=O==null?void 0:O.errors)==null?void 0:w.join(`
614
- `))||(O==null?void 0:O.error)||"Failed to create start screen template.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(P=(v=this.options).onRefresh)==null||P.call(v)}catch(A){alert(`Failed to create start screen template: ${A instanceof Error?A.message:String(A)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let T=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,withHand:e==="endgame-screen"})}),O=await T.json().catch(()=>({}));if(!T.ok||(O==null?void 0:O.success)===!1){let M=((I=O==null?void 0:O.errors)==null?void 0:I.join(`
615
- `))||(O==null?void 0:O.error)||"Failed to create endgame screen template.";alert(M);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(k=(_=this.options).onRefresh)==null||k.call(_)}catch(A){alert(`Failed to create endgame screen template: ${A instanceof Error?A.message:String(A)}`)}if(e==="bullet-system")try{let A=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),T=await A.json().catch(()=>({}));if(!A.ok||(T==null?void 0:T.success)===!1){let O=((j=T==null?void 0:T.errors)==null?void 0:j.join(`
616
- `))||(T==null?void 0:T.error)||"Failed to create bullet system.";alert(O);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(x=(L=this.options).onRefresh)==null||x.call(L)}catch(A){alert(`Failed to create bullet system: ${A instanceof Error?A.message:String(A)}`)}if(e==="spawner"){let A=await this.promptSpawnerConfig();if(!A)return;let{templateId:T,instanceId:O,spawnerProps:M}=A;try{let R=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,templateId:T,instanceId:O,spawnerProps:M,forceSync:!0})}),z=await R.json().catch(()=>({}));if(!R.ok||(z==null?void 0:z.success)===!1){let F=((S=z==null?void 0:z.errors)==null?void 0:S.join(`
617
- `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(F);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(C=(E=this.options).onRefresh)==null||C.call(E)}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 $i=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(i=>typeof i=="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`
608
+ `))||(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 n,a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,j,T,O,M,_,C,x,S,E,I;this.close();let i=t!=null?t:await this.promptScreen();if(i){if(e==="collectable-system")try{let L=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((n=A==null?void 0:A.errors)==null?void 0:n.join(`
609
+ `))||(A==null?void 0:A.error)||"Failed to create collectable system.";alert(P);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(s=(a=this.options).onRefresh)==null||s.call(a)}catch(L){alert(`Failed to create collectable system: ${L instanceof Error?L.message:String(L)}`)}if(e==="drag-snap-couples")try{let L=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((o=A==null?void 0:A.errors)==null?void 0:o.join(`
610
+ `))||(A==null?void 0:A.error)||"Failed to create drag-snap system.";alert(P);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(L){alert(`Failed to create drag-snap system: ${L instanceof Error?L.message:String(L)}`)}if(e==="swerve-collect")try{let L=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((d=A==null?void 0:A.errors)==null?void 0:d.join(`
611
+ `))||(A==null?void 0:A.error)||"Failed to create swerve collect system.";alert(P);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(L){alert(`Failed to create swerve collect system: ${L instanceof Error?L.message:String(L)}`)}if(e==="tap-destroy")try{let L=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((g=A==null?void 0:A.errors)==null?void 0:g.join(`
612
+ `))||(A==null?void 0:A.error)||"Failed to create tap destroy system.";alert(P);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(L){alert(`Failed to create tap destroy system: ${L instanceof Error?L.message:String(L)}`)}if(e==="scratch-card")try{let L=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((m=A==null?void 0:A.errors)==null?void 0:m.join(`
613
+ `))||(A==null?void 0:A.error)||"Failed to create scratch card system.";alert(P);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(L){alert(`Failed to create scratch card system: ${L instanceof Error?L.message:String(L)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let A=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,withHand:e==="start-screen"})}),P=await A.json().catch(()=>({}));if(!A.ok||(P==null?void 0:P.success)===!1){let k=((w=P==null?void 0:P.errors)==null?void 0:w.join(`
614
+ `))||(P==null?void 0:P.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")),(j=(v=this.options).onRefresh)==null||j.call(v)}catch(L){alert(`Failed to create start screen template: ${L instanceof Error?L.message:String(L)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let A=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,withHand:e==="endgame-screen"})}),P=await A.json().catch(()=>({}));if(!A.ok||(P==null?void 0:P.success)===!1){let k=((T=P==null?void 0:P.errors)==null?void 0:T.join(`
615
+ `))||(P==null?void 0:P.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")),(M=(O=this.options).onRefresh)==null||M.call(O)}catch(L){alert(`Failed to create endgame screen template: ${L instanceof Error?L.message:String(L)}`)}if(e==="bullet-system")try{let L=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i})}),A=await L.json().catch(()=>({}));if(!L.ok||(A==null?void 0:A.success)===!1){let P=((_=A==null?void 0:A.errors)==null?void 0:_.join(`
616
+ `))||(A==null?void 0:A.error)||"Failed to create bullet system.";alert(P);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(x=(C=this.options).onRefresh)==null||x.call(C)}catch(L){alert(`Failed to create bullet system: ${L instanceof Error?L.message:String(L)}`)}if(e==="spawner"){let L=await this.promptSpawnerConfig();if(!L)return;let{templateId:A,instanceId:P,spawnerProps:k}=L;try{let R=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,templateId:A,instanceId:P,spawnerProps:k,forceSync:!0})}),z=await R.json().catch(()=>({}));if(!R.ok||(z==null?void 0:z.success)===!1){let F=((S=z==null?void 0:z.errors)==null?void 0:S.join(`
617
+ `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(F);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(I=(E=this.options).onRefresh)==null||I.call(E)}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 $i=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(i=>typeof i=="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`
618
618
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
619
619
  <div class="scene-panel-header" data-panel-handle>
620
620
  <div class="panel-title">
@@ -649,7 +649,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
649
649
  </div>
650
650
  <div class="panel-resize-handle-v" data-panel-resize-v></div>
651
651
  </div>
652
- `}initialize(e,t){var a,s,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=(s=this.root)==null?void 0:s.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var v;let h=g.target,f=h==null?void 0:h.closest("[data-collapse-key]");if(f){let P=f.dataset.collapseKey||"";if(!P)return;let I=(v=this.listContainer)==null?void 0:v.querySelector(`[data-collapse-content="${P}"]`),_=this.isCollapsed(P);I&&(I.style.display=_?"":"none"),f.textContent=_?"\u25BE":"\u25B8",this.setCollapsed(P,!_),g.preventDefault(),g.stopPropagation();return}let m=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(m){let P=m.dataset.objectId;if(!P)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(P);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,w=b.dataset.systemBundleId;if(!(!y||!w)){if(y==="toggle-visibility"){this.toggleSystemBundleVisibility(w);return}y==="delete"&&this.deleteSystemBundle(w)}});let i=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");i==null||i.addEventListener("click",g=>{g.stopPropagation();let h=i.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let n=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(n){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}n.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{}n.addEventListener("change",()=>{let g=n.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 v=h.dataset.objectId;if(!v)return;g.stopPropagation(),this.toggleBatchSelect(v);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 v;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 P=window.__editableObjectConfigs;P&&typeof P.get=="function"&&(y=(v=P.get(m))!=null?v:null)}let w=this.inferScreen(m,y);this.showContextMenu(m,w,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,s,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]"),i=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumb-screen]"),n=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&i&&n){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);i.textContent=h[g]||g,n.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,i=window.refreshEditableConfigIndex;if(typeof i=="function"&&i(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let n=typeof t=="function"?t():e();if(!Array.isArray(n)||n.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(n=Array.from(g.keys()))}if(!Array.isArray(n)||n.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),s=["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,w,v;let h=(w=(y=(b=(m=window.__editableConfig)==null?void 0:m.objects)==null?void 0:b.get)==null?void 0:y.call(b,g))!=null?w:null;if(h)return h;let f=window.__editableObjectConfigs;return f&&typeof f.get=="function"&&(v=f.get(g))!=null?v:null};n.forEach(g=>{var C,A,T,O,M,R,z;let h=l(g),f=(((C=h==null?void 0:h.identity)==null?void 0:C.category)||"scene").toString(),m=(((A=h==null?void 0:h.identity)==null?void 0:A.id)||g).toString(),b=f.toLowerCase(),y=m.toLowerCase(),w=b.includes("ui")||y.startsWith("ui")||y.includes("label"),v=b==="system",P=((T=h==null?void 0:h.identity)==null?void 0:T.is_template)===!0||y.includes(".template")||g.toLowerCase().includes(".template"),I=typeof((O=h==null?void 0:h.identity)==null?void 0:O.system_group)=="string"?h.identity.system_group:null,_=typeof((M=h==null?void 0:h.identity)==null?void 0:M.system_label)=="string"?h.identity.system_label:I?this.formatDisplayName(I):null,k=this.formatDisplayName(m||g),j=((R=h==null?void 0:h.render)==null?void 0:R.visible)===!1||(h==null?void 0:h.enabled)===!1,L=this.getObjectType(h),x={id:g,label:k,category:f,isUi:w,isTemplate:P,isUnused:j,objectType:L,systemGroupId:I,systemLabel:_},S=this.inferScreen(x.id,h);if(!(this.screenFilter!=="all"&&S!==this.screenFilter||!(!a||x.id.toLowerCase().includes(a)||x.label.toLowerCase().includes(a)))){if(I){let F=this.getSystemBundleKey(S,I),q=_!=null?_:I,N=o[S],H=N.bundles.get(F);H?(H.entries.push(x),H.objectIds.push(g)):N.bundles.set(F,{key:F,label:q,objectIds:[g],entries:[x]});let $=(z=this.systemBundles.get(F))!=null?z:{label:q,objectIds:[]};$.label=q,$.objectIds.push(g),this.systemBundles.set(F,$);return}if(P){o[S].templates.push(x);return}v?o[S].systems.push(x):o[S].objects.push(x)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?s:[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,i,n){let a=this.isBundleAllHidden(i),s=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=n.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
652
+ `}initialize(e,t){var a,s,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=(s=this.root)==null?void 0:s.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var v;let h=g.target,f=h==null?void 0:h.closest("[data-collapse-key]");if(f){let j=f.dataset.collapseKey||"";if(!j)return;let T=(v=this.listContainer)==null?void 0:v.querySelector(`[data-collapse-content="${j}"]`),O=this.isCollapsed(j);T&&(T.style.display=O?"":"none"),f.textContent=O?"\u25BE":"\u25B8",this.setCollapsed(j,!O),g.preventDefault(),g.stopPropagation();return}let m=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(m){let j=m.dataset.objectId;if(!j)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(j);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,w=b.dataset.systemBundleId;if(!(!y||!w)){if(y==="toggle-visibility"){this.toggleSystemBundleVisibility(w);return}y==="delete"&&this.deleteSystemBundle(w)}});let i=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");i==null||i.addEventListener("click",g=>{g.stopPropagation();let h=i.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let n=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(n){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}n.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{}n.addEventListener("change",()=>{let g=n.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 v=h.dataset.objectId;if(!v)return;g.stopPropagation(),this.toggleBatchSelect(v);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 v;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 j=window.__editableObjectConfigs;j&&typeof j.get=="function"&&(y=(v=j.get(m))!=null?v:null)}let w=this.inferScreen(m,y);this.showContextMenu(m,w,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,s,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]"),i=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumb-screen]"),n=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&i&&n){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);i.textContent=h[g]||g,n.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,i=window.refreshEditableConfigIndex;if(typeof i=="function"&&i(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let n=typeof t=="function"?t():e();if(!Array.isArray(n)||n.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(n=Array.from(g.keys()))}if(!Array.isArray(n)||n.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),s=["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,w,v;let h=(w=(y=(b=(m=window.__editableConfig)==null?void 0:m.objects)==null?void 0:b.get)==null?void 0:y.call(b,g))!=null?w:null;if(h)return h;let f=window.__editableObjectConfigs;return f&&typeof f.get=="function"&&(v=f.get(g))!=null?v:null};n.forEach(g=>{var I,L,A,P,k,R,z;let h=l(g),f=(((I=h==null?void 0:h.identity)==null?void 0:I.category)||"scene").toString(),m=(((L=h==null?void 0:h.identity)==null?void 0:L.id)||g).toString(),b=f.toLowerCase(),y=m.toLowerCase(),w=b.includes("ui")||y.startsWith("ui")||y.includes("label"),v=b==="system",j=((A=h==null?void 0:h.identity)==null?void 0:A.is_template)===!0||y.includes(".template")||g.toLowerCase().includes(".template"),T=typeof((P=h==null?void 0:h.identity)==null?void 0:P.system_group)=="string"?h.identity.system_group:null,O=typeof((k=h==null?void 0:h.identity)==null?void 0:k.system_label)=="string"?h.identity.system_label:T?this.formatDisplayName(T):null,M=this.formatDisplayName(m||g),_=((R=h==null?void 0:h.render)==null?void 0:R.visible)===!1||(h==null?void 0:h.enabled)===!1,C=this.getObjectType(h),x={id:g,label:M,category:f,isUi:w,isTemplate:j,isUnused:_,objectType:C,systemGroupId:T,systemLabel:O},S=this.inferScreen(x.id,h);if(!(this.screenFilter!=="all"&&S!==this.screenFilter||!(!a||x.id.toLowerCase().includes(a)||x.label.toLowerCase().includes(a)))){if(T){let F=this.getSystemBundleKey(S,T),q=O!=null?O:T,N=o[S],H=N.bundles.get(F);H?(H.entries.push(x),H.objectIds.push(g)):N.bundles.set(F,{key:F,label:q,objectIds:[g],entries:[x]});let $=(z=this.systemBundles.get(F))!=null?z:{label:q,objectIds:[]};$.label=q,$.objectIds.push(g),this.systemBundles.set(F,$);return}if(j){o[S].templates.push(x);return}v?o[S].systems.push(x):o[S].objects.push(x)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?s:[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,i,n){let a=this.isBundleAllHidden(i),s=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=n.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
653
653
  <div class="scene-object-group scene-object-group-bundle" data-system-bundle="${c}">
654
654
  <div class="scene-object-group-title">
655
655
  <button class="scene-object-group-toggle" type="button" data-collapse-key="${d}">${p?"\u25B8":"\u25BE"}</button>
@@ -781,7 +781,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
781
781
  </div>
782
782
  </div>
783
783
  </div>
784
- `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let n=this.root.querySelector("[data-tools-collapse]");n==null||n.addEventListener("click",()=>{var S;this.isCollapsed=!this.isCollapsed,(S=this.root)==null||S.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(S,E)=>{var A;let C=(A=this.root)==null?void 0:A.querySelector(`[data-status="${S}"]`);C&&C.classList.toggle("active",E)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var S;(S=this.options)==null||S.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var S;(S=this.options)==null||S.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 S=Number(p.value),E=Number.isFinite(S)?Math.min(1,Math.max(0,S)):.25;return p.value=String(E),u&&(u.textContent=`${Math.round(E*100)}%`),E},w=(S,E,C)=>{var T,O;let A=C!==void 0?C:y();(O=(T=this.options)==null?void 0:T.onGridToggle)==null||O.call(T,S,E,A),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:S,gap:E,alpha:A}}))},v=S=>{var C,A;let E=y();(A=(C=this.options)==null?void 0:C.onGridGapChange)==null||A.call(C,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:S,alpha:E}}))},P=S=>{var E,C;(C=(E=this.options)==null?void 0:E.onGridAlphaChange)==null||C.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:j(),alpha:S}}))},I=S=>{var E,C;(C=(E=this.options)==null?void 0:E.onPlayModeChange)==null||C.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:S}}))},_=S=>{var E,C;(C=(E=this.options)==null?void 0:E.onBackgroundCoverChange)==null||C.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:background-cover",{detail:{enabled:S}}))},k=S=>{var E,C;(C=(E=this.options)==null?void 0:E.onBackgroundLockChange)==null||C.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:background-lock",{detail:{enabled:S}}))},j=()=>{if(!d)return 50;let S=Number(d.value),E=Number.isFinite(S)?Math.min(200,Math.max(4,S)):50;return d.value=String(E),E},L=S=>{c&&(c.checked=S),d&&(d.disabled=!S),p&&(p.disabled=!S),m==null||m.classList.toggle("active",S)},x=S=>{g&&(g.checked=S),b==null||b.classList.toggle("active",S)};try{let S=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),E=localStorage.getItem(this.getSceneStorageKey("grid_gap")),C=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),A=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),T=localStorage.getItem(this.getSceneStorageKey("background_cover")),O=localStorage.getItem(this.getSceneStorageKey("background_lock")),M=S?S==="true":!1;L(M),d&&(d.value=E||"50",d.disabled=!M),p&&(p.value=C||"0.25",p.disabled=!M,y()),o&&(o.checked=A==="true",a("anchor",o.checked));let R=!0;x(R),g&&(g.disabled=!0),b&&(b.disabled=!0);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),R?"true":"false")}catch{}w(M,j(),y()),I(R);let z=T?T==="true":!0,F=O?O==="true":!0;h&&(h.checked=z),f&&(f.checked=F),_(z),k(F),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let S=j(),E=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(S)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E))}catch{}w(c.checked,S,E)}),d==null||d.addEventListener("input",()=>{let S=j(),E=y();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(S)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E))}catch{}v(S)}),p==null||p.addEventListener("input",()=>{let S=y(),E=j();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(S)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E))}catch{}P(S)}),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{}k(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 Ni=class{constructor(){this.root=null;this.options=null}render(){return`
784
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let n=this.root.querySelector("[data-tools-collapse]");n==null||n.addEventListener("click",()=>{var S;this.isCollapsed=!this.isCollapsed,(S=this.root)==null||S.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(S,E)=>{var L;let I=(L=this.root)==null?void 0:L.querySelector(`[data-status="${S}"]`);I&&I.classList.toggle("active",E)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var S;(S=this.options)==null||S.onHighlightObject(!!s.checked),a("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var S;(S=this.options)==null||S.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 S=Number(p.value),E=Number.isFinite(S)?Math.min(1,Math.max(0,S)):.25;return p.value=String(E),u&&(u.textContent=`${Math.round(E*100)}%`),E},w=(S,E,I)=>{var A,P;let L=I!==void 0?I:y();(P=(A=this.options)==null?void 0:A.onGridToggle)==null||P.call(A,S,E,L),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:S,gap:E,alpha:L}}))},v=S=>{var I,L;let E=y();(L=(I=this.options)==null?void 0:I.onGridGapChange)==null||L.call(I,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:S,alpha:E}}))},j=S=>{var E,I;(I=(E=this.options)==null?void 0:E.onGridAlphaChange)==null||I.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:_(),alpha:S}}))},T=S=>{var E,I;(I=(E=this.options)==null?void 0:E.onPlayModeChange)==null||I.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:S}}))},O=S=>{var E,I;(I=(E=this.options)==null?void 0:E.onBackgroundCoverChange)==null||I.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:background-cover",{detail:{enabled:S}}))},M=S=>{var E,I;(I=(E=this.options)==null?void 0:E.onBackgroundLockChange)==null||I.call(E,S),window.dispatchEvent(new CustomEvent("scene-editor:background-lock",{detail:{enabled:S}}))},_=()=>{if(!d)return 50;let S=Number(d.value),E=Number.isFinite(S)?Math.min(200,Math.max(4,S)):50;return d.value=String(E),E},C=S=>{c&&(c.checked=S),d&&(d.disabled=!S),p&&(p.disabled=!S),m==null||m.classList.toggle("active",S)},x=S=>{g&&(g.checked=S),b==null||b.classList.toggle("active",S)};try{let S=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),E=localStorage.getItem(this.getSceneStorageKey("grid_gap")),I=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),L=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),A=localStorage.getItem(this.getSceneStorageKey("background_cover")),P=localStorage.getItem(this.getSceneStorageKey("background_lock")),k=S?S==="true":!1;C(k),d&&(d.value=E||"50",d.disabled=!k),p&&(p.value=I||"0.25",p.disabled=!k,y()),o&&(o.checked=L==="true",a("anchor",o.checked));let R=!0;x(R),g&&(g.disabled=!0),b&&(b.disabled=!0);try{localStorage.setItem(this.getSceneStorageKey("play_mode"),R?"true":"false")}catch{}w(k,_(),y()),T(R);let z=A?A==="true":!0,F=P?P==="true":!0;h&&(h.checked=z),f&&(f.checked=F),O(z),M(F),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let S=_(),E=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(S)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E))}catch{}w(c.checked,S,E)}),d==null||d.addEventListener("input",()=>{let S=_(),E=y();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(S)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(E))}catch{}v(S)}),p==null||p.addEventListener("input",()=>{let S=y(),E=_();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(S)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(E))}catch{}j(S)}),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),T(g.checked)}),h==null||h.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_cover"),h.checked?"true":"false")}catch{}O(h.checked)}),f==null||f.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("background_lock"),f.checked?"true":"false")}catch{}M(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 Ni=class{constructor(){this.root=null;this.options=null}render(){return`
785
785
  <div class="nudge-panel hidden" data-panel="nudge-panel">
786
786
  <div class="nudge-panel-header" data-panel-handle>
787
787
  <span class="nudge-panel-title">Nudge Controls</span>
@@ -866,7 +866,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
866
866
  </div>
867
867
  <div class="panel-resize-handle" data-panel-resize></div>
868
868
  </div>
869
- `}initialize(e,t){var a,s,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]"),this.assetsContainer=(s=this.root)==null?void 0:s.querySelector("[data-library-assets]"),this.assetSearchInput=(o=this.root)==null?void 0:o.querySelector("[data-library-asset-search]"),this.slotSearchInput=(l=this.root)==null?void 0:l.querySelector("[data-library-slot-search]");let i=(c=this.root)==null?void 0:c.querySelector("[data-create-ai]");i==null||i.addEventListener("click",()=>{this.handleCreateWithAI()});let n=(d=this.root)==null?void 0:d.querySelector("[data-refresh-library]");n==null||n.addEventListener("click",()=>{n.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>n.classList.remove("pulse-anim"),500)}),(p=this.assetSearchInput)==null||p.addEventListener("input",()=>this.scheduleRenderAssets()),(u=this.slotSearchInput)==null||u.addEventListener("input",()=>this.scheduleRenderSlots()),window.addEventListener("preview:select",g=>{var f;let h=(f=g.detail)==null?void 0:f.objectId;h&&this.highlightCurrentObject(h)}),this.loadAssetRegistry()}highlightCurrentObject(e){if(!this.registry)return;let t=this.registry.slots.find(i=>i.objectId===e);t&&(this.selectedSlotId=t.slotId,this.scheduleRenderSlots(),setTimeout(()=>{var n;let i=(n=this.slotsContainer)==null?void 0:n.querySelector(`[data-slot-id="${t.slotId}"]`);i&&i.scrollIntoView({behavior:"smooth",block:"center"})},100))}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let e=window.getEditableAssets,t=typeof e=="function"?e():null,i=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(i.ok){let n=await i.json(),a=this.mergeRegistries(t,n);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}resetSearch(){this.assetSearchInput&&(this.assetSearchInput.value=""),this.slotSearchInput&&(this.slotSearchInput.value=""),this.scheduleRenderAssets(),this.scheduleRenderSlots()}loadAssetRegistry(e=0){var i,n,a,s;let t=window.getEditableAssets;if(typeof t=="function"){let o=t();if(o!=null&&o.slots&&Array.isArray(o.slots)&&o.slots.length>0){if(this.registry=o,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.cacheBust=Date.now(),this.cachedAssets={},this.pendingAssetFetches={},this.missingPreviewPaths.clear(),!(this.selectedSlotId&&this.registry.slots.some(c=>c.slotId===this.selectedSlotId))){let c=window.__getSelectedObjectId,d=typeof c=="function"?c():null;if(d){let p=this.registry.slots.find(u=>u.objectId===d);p?this.selectedSlotId=p.slotId:this.selectedSlotId=(n=(i=this.registry.slots[0])==null?void 0:i.slotId)!=null?n:null}else this.selectedSlotId=(s=(a=this.registry.slots[0])==null?void 0:a.slotId)!=null?s:null}this.renderSlots(),this.renderAssets();return}}e<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${e+1}/15)`),setTimeout(()=>this.loadAssetRegistry(e+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){var n;if(!this.slotsContainer||!this.registry)return;let e={};for(let a of this.registry.slots)e[a.category]||(e[a.category]=[]),e[a.category].push(a);let t=this.cacheBust||Date.now(),i=(((n=this.slotSearchInput)==null?void 0:n.value)||"").trim().toLowerCase();this.slotsContainer.innerHTML="";for(let a of this.getCategories()){let s=(e[a]||[]).filter(d=>i?`${d.displayName} ${d.slotId} ${d.objectId} ${d.currentAsset}`.toLowerCase().includes(i):!0);if(s.length===0)continue;let o=document.createElement("div");o.className="library-category";let l=document.createElement("div");l.className="library-category-header",l.textContent=this.formatCategoryName(a),o.appendChild(l);let c=document.createElement("div");c.className="library-category-slots";for(let d of s){let p=this.createSlotElement(d,t);c.appendChild(p)}o.appendChild(c),this.slotsContainer.appendChild(o)}if(!this.slotsContainer.hasChildNodes()){let a=document.createElement("div");a.className="library-info",a.textContent=i?"No slots match your search":"No editable slots available",this.slotsContainer.appendChild(a)}}createSlotElement(e,t){var y,w;let i=this.selectedSlotId===e.slotId,n=window.__getSelectedObjectId,s=(typeof n=="function"?n():null)===e.objectId,o=document.createElement("div");o.className=`library-slot ${i?"expanded":""} ${s?"current-object":""}`,o.dataset.slotId=e.slotId,o.dataset.objectId=e.objectId;let l=document.createElement("div");l.className="slot-header";let c=document.createElement("div");if(c.className="slot-current",(y=e.currentAsset)==null?void 0:y.toLowerCase().endsWith(".json")){let v=document.createElement("div");v.className="slot-thumbnail slot-thumbnail-json",v.textContent="\u{1F3AC}",v.title="Lottie/JSON Animation",c.appendChild(v)}else{let v=document.createElement("img"),P=this.resolveSlotPreviewPaths(e),I=P.primary,_=(w=P.fallback)!=null?w:null;if(!I)v.style.display="none";else if(this.missingPreviewPaths.has(I.key)&&(!_||this.missingPreviewPaths.has(_.key)))v.style.display="none";else{v.src=I.src(t),v.alt=e.displayName,v.className="slot-thumbnail",v.loading="lazy";let k=!1;v.onerror=()=>{if(k){v.onerror=null,v.style.display="none";return}if(this.missingPreviewPaths.add(I.key),_&&!this.missingPreviewPaths.has(_.key)){k=!0,v.src=_.src(t);return}_&&this.missingPreviewPaths.add(_.key),v.style.display="none"}}c.appendChild(v)}l.appendChild(c);let p=document.createElement("div");p.className="slot-info";let u=document.createElement("div");u.className="slot-name",u.textContent=e.displayName;let g=document.createElement("div");g.className="slot-asset",g.textContent=e.currentAsset,p.appendChild(u),p.appendChild(g),l.appendChild(p);let h=document.createElement("div");h.className="slot-actions";let f=document.createElement("button");f.className="slot-ai-edit",f.title="Edit with AI",f.textContent="\u2728 AI",f.addEventListener("click",async v=>{v.stopPropagation(),await this.handleAIEdit(e)}),h.appendChild(f);let m=document.createElement("button");m.className="slot-upload",m.title="Upload new asset",m.textContent="\u{1F4E4}",m.addEventListener("click",async v=>{v.stopPropagation(),await this.handleUpload(e)}),h.appendChild(m);let b=document.createElement("button");return b.className="slot-reset",b.title="Reset to default",b.textContent="\u21BA",b.addEventListener("click",async v=>{v.stopPropagation(),await this.handleReset(e)}),h.appendChild(b),l.appendChild(h),l.addEventListener("click",()=>{this.selectedSlotId=e.slotId,this.renderSlots(),this.renderAssets()}),o.appendChild(l),o}renderAssets(){var l;if(!this.assetsContainer||!this.registry)return;let e=this.cacheBust||Date.now(),t=(((l=this.assetSearchInput)==null?void 0:l.value)||"").trim().toLowerCase(),i=this.getSelectedSlot();this.assetsContainer.innerHTML="";let n=document.createElement("div");n.className="library-selected",n.textContent=i?`Selected slot: ${i.displayName} (${i.currentAsset||"no asset"})`:"Select a slot to apply assets",n.style.gridColumn="1 / -1",this.assetsContainer.appendChild(n);let a=this.getCategories(),s=!1,o=!1;for(let c of a){let d=this.getCategoryAssets(c,e);if(!d){let f=document.createElement("div");f.className="library-empty",f.textContent=`Loading ${this.formatCategoryName(c)} assets...`,this.assetsContainer.appendChild(f),o=!0;continue}let p=d.filter(f=>t?`${f.displayName} ${f.filename} ${c}`.toLowerCase().includes(t):!0);if(p.length===0)continue;let u=document.createElement("div");u.className="library-category";let g=document.createElement("div");g.className="library-category-header",g.textContent=this.formatCategoryName(c),u.appendChild(g);let h=document.createElement("div");h.className="slot-library",h.style.borderTop="none",h.style.padding="10px";for(let f of p){let m=document.createElement("div");m.className="library-item",i&&i.currentAsset===f.filename&&i.libraryFolder===c&&m.classList.add("selected");let b=document.createElement("img"),y=this.resolveLibraryAssetPath(c,f.filename);this.missingPreviewPaths.has(y.key)?b.style.display="none":b.src=y.src(e),b.alt=f.displayName,b.className="library-thumbnail",b.loading="lazy",b.onerror=()=>{this.missingPreviewPaths.add(y.key),b.style.opacity="0.3"},m.appendChild(b);let w=document.createElement("div");w.className="library-label",w.textContent=f.displayName,m.appendChild(w),m.addEventListener("click",async()=>{if(!i){alert("Select a slot first to apply an asset.");return}await this.handleApply(i,f.filename,c)}),h.appendChild(m),s=!0}u.appendChild(h),this.assetsContainer.appendChild(u)}if(!s&&!o){let c=document.createElement("div");c.className="library-empty",c.textContent=t?"No assets match your search":"No assets available",this.assetsContainer.appendChild(c)}}getCategoryAssets(e,t){var i;if(this.cachedAssets[e])return this.cachedAssets[e];if(!this.pendingAssetFetches[e]){let n=((i=this.registry)==null?void 0:i.libraryAssets[e])||[];this.pendingAssetFetches[e]=this.fetchFolderAssets(e,t).then(a=>{let s=new Map;for(let o of n)s.set(o.filename,o);for(let o of a)s.has(o.filename)||s.set(o.filename,o);return this.cachedAssets[e]=Array.from(s.values()),delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]}).catch(()=>(this.cachedAssets[e]=n,delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]))}return null}async fetchFolderAssets(e,t){try{let i=await fetch(`/raw/library/${e}/?t=${t}`);if(!i.ok)return[];let n=await i.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(n))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:l,displayName:c})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t,i){var n,a,s;if(this.isApplying){console.warn("[LIBRARY] \u26A0\uFE0F Apply already in progress, ignoring duplicate click");return}this.isApplying=!0,console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let o=window.__wizardAssetPicker;if(o!=null&&o.onPick){let d=`raw/library/${i||e.libraryFolder||e.category}/${t}`;o.onPick(d),window.__wizardAssetPicker=null;return}let l=i||e.libraryFolder||e.category;if((n=this.options)!=null&&n.onApply){await this.options.onApply(e.objectId,t,l),await new Promise(d=>setTimeout(d,200));let c=window.getEditableObjectConfig;if(typeof c=="function"){let d=c(e.objectId),p=((s=(a=d==null?void 0:d.render)==null?void 0:a.asset)==null?void 0:s.path)||"",u=`raw/library/${l}/${t}`;if(p===u||p.includes(t))console.log("[LIBRARY] \u2705 Asset confirmed applied:",p);else throw console.error("[LIBRARY] \u274C Asset NOT applied! Expected:",u,"Got:",p),new Error(`Asset was not applied correctly. Expected: ${u}, Got: ${p}`)}}e.currentAsset=t,e.libraryFolder=l,this.renderSlots(),this.renderAssets()}catch(o){throw console.error("[LIBRARY] \u274C Failed to apply asset:",o),alert(`Failed to apply asset: ${o instanceof Error?o.message:String(o)}`),o}finally{this.isApplying=!1}}async handleReset(e){var t;console.log("[LIBRARY] Resetting slot:",e.slotId,"to default:",e.defaultAsset);try{await((t=this.options)==null?void 0:t.onReset(e.objectId,e.defaultAsset,e.category)),e.currentAsset=e.defaultAsset,this.renderSlots(),this.renderAssets()}catch(i){console.error("[LIBRARY] Failed to reset slot:",i)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}getCategories(){if(!this.registry)return[];let e=new Set;if(Array.isArray(this.registry.categories))for(let t of this.registry.categories)t&&e.add(t);for(let t of Object.keys(this.registry.libraryAssets||{}))t&&e.add(t);for(let t of this.registry.slots||[])t!=null&&t.category&&e.add(t.category);return Array.from(e)}getSelectedSlot(){return!this.registry||!this.selectedSlotId?null:this.registry.slots.find(e=>e.slotId===this.selectedSlotId)||null}scheduleRenderSlots(){this.slotSearchDebounce&&window.clearTimeout(this.slotSearchDebounce),this.slotSearchDebounce=window.setTimeout(()=>{this.slotSearchDebounce=null,this.renderSlots()},150)}scheduleRenderAssets(){this.assetSearchDebounce&&window.clearTimeout(this.assetSearchDebounce),this.assetSearchDebounce=window.setTimeout(()=>{this.assetSearchDebounce=null,this.renderAssets()},150)}resolveSlotPreviewPaths(e){let t=(e.currentAsset||"").trim();if(!t)return{primary:null,fallback:null};let i=t.replace(/^\/+/,""),n=null,a=null;return i.startsWith("raw/")?n=i:i.startsWith("library/")?n=`raw/${i}`:i.includes("/")?n=i:e.libraryFolder?(n=`raw/library/${e.libraryFolder}/${i}`,a=`raw/${i}`):n=`raw/${i}`,{primary:n?{key:n,src:l=>`/${n}?t=${l}`}:null,fallback:a?{key:a,src:l=>`/${a}?t=${l}`}:null}}resolveLibraryAssetPath(e,t){let i=t.replace(/^\/+/,""),n="";return i.startsWith("raw/")?n=i:i.startsWith("library/")?n=`raw/${i}`:i.includes("/")?n=i:n=`raw/library/${e}/${i}`,{key:n,src:a=>`/${n}?t=${a}`}}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let i=e.slotId||e.objectId,n="render.texture";e.category==="ui"&&(n="ui.image"),e.category==="audio"&&(n="audio.src"),t(i,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:n})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var n,a,s,o,l;let i=(n=t.files)==null?void 0:n[0];if(i){console.log("[Library] File selected:",i.name);try{let c=await this.fileToDataUrl(i);if(!c){alert("Failed to read file");return}let d=e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),p=((a=i.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:a[1])||"png",u=p==="jpg"?"jpeg":p,g=`${d}_uploaded_${Date.now()}.${u}`,h=e.category;console.log("[Library] Saving uploaded file:",g,"to category:",h);let m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:h,filename:g,data:c,overwrite:!0})})).json();if(m.success){console.log("[Library] \u2705 Upload saved:",m.path),await new Promise(j=>setTimeout(j,100));let b=window.addAssetToRegistry;typeof b=="function"&&(b(h,g),console.log("[Library] \u2705 Added to registry:",h,g));let y=window.getEditableAssets;if(typeof y=="function"){let j=y();j&&!j.categories&&(j.categories=[]),j!=null&&j.categories&&!j.categories.includes(h)&&(j.categories.push(h),console.log(`[Library] Added category ${h} to registry`))}let w=!1,v=0,P=10;for(;!w&&v<P;){v++,console.log(`[Library] Refresh attempt ${v}/${P}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[Library] \u2705 Registry rebuilt from disk")}catch(x){console.warn("[Library] Setup-library not available:",x)}await new Promise(x=>setTimeout(x,300)),await this.refresh();let j=window.reRenderAssetLibrary;typeof j=="function"&&(console.log("[Library] Re-rendering library panel..."),j());let L=window.getEditableAssets;if(typeof L=="function"){let x=L(),S=((s=x==null?void 0:x.libraryAssets)==null?void 0:s[h])||[];S.some(C=>(C==null?void 0:C.filename)===g)?(console.log("[Library] \u2705 Asset found in registry!"),w=!0):(console.log(`[Library] Asset not found yet, retrying... (found ${S.length} assets in ${h})`),await new Promise(C=>setTimeout(C,500)))}else v>=2&&(w=!0)}w||console.warn("[Library] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway...");let I=!1,_=0,k=5;for(;!I&&_<k;){_++;try{console.log(`[Library] Applying asset attempt ${_}/${k}...`),await this.handleApply(e,g,e.category),await new Promise(L=>setTimeout(L,200));let j=window.getEditableObjectConfig;if(typeof j=="function"){let L=j(e.objectId),x=((l=(o=L==null?void 0:L.render)==null?void 0:o.asset)==null?void 0:l.path)||"";x===m.path||x.includes(g)?(console.log("[Library] \u2705 Asset confirmed applied to object"),I=!0):(console.log(`[Library] Asset not applied yet (attempt ${_}), retrying...`),await new Promise(S=>setTimeout(S,300)))}else I=!0}catch(j){console.error(`[Library] Apply attempt ${_} failed:`,j),_<k&&await new Promise(L=>setTimeout(L,500))}}e.currentAsset=g,await this.refresh(),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[Library] Dispatched config:changed event")}catch(j){console.warn("[Library] Failed to refresh textures:",j)}},300),setTimeout(()=>{this.highlightSlot(e.objectId,h)},1e3),I?console.log("[Library] \u2705 Upload complete and applied!"):console.warn("[Library] \u26A0\uFE0F Upload succeeded but apply may have failed")}else console.error("[Library] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(c){console.error("[Library] \u274C Upload error:",c),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let i=e.startsWith("json.")?e.replace("json.",""):e,n=this.registry.slots.find(a=>(a.objectId===i||a.slotId===i)&&(!t||a.category===t));n?(console.log("[LIBRARY] Highlighting slot:",n.slotId),this.selectedSlotId=n.slotId,this.renderSlots(),this.renderAssets(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${n.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var Hi=class{detectType(e,t,i){let n=e.toLowerCase();return n==="logic_id"||n==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":n.includes("color")||n.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var Fi=class{render(e,t,i,n){let a=this.formatLabel(t),s=i?this.getThumbnailUrl(i):"";return`
869
+ `}initialize(e,t){var a,s,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]"),this.assetsContainer=(s=this.root)==null?void 0:s.querySelector("[data-library-assets]"),this.assetSearchInput=(o=this.root)==null?void 0:o.querySelector("[data-library-asset-search]"),this.slotSearchInput=(l=this.root)==null?void 0:l.querySelector("[data-library-slot-search]");let i=(c=this.root)==null?void 0:c.querySelector("[data-create-ai]");i==null||i.addEventListener("click",()=>{this.handleCreateWithAI()});let n=(d=this.root)==null?void 0:d.querySelector("[data-refresh-library]");n==null||n.addEventListener("click",()=>{n.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>n.classList.remove("pulse-anim"),500)}),(p=this.assetSearchInput)==null||p.addEventListener("input",()=>this.scheduleRenderAssets()),(u=this.slotSearchInput)==null||u.addEventListener("input",()=>this.scheduleRenderSlots()),window.addEventListener("preview:select",g=>{var f;let h=(f=g.detail)==null?void 0:f.objectId;h&&this.highlightCurrentObject(h)}),this.loadAssetRegistry()}highlightCurrentObject(e){if(!this.registry)return;let t=this.registry.slots.find(i=>i.objectId===e);t&&(this.selectedSlotId=t.slotId,this.scheduleRenderSlots(),setTimeout(()=>{var n;let i=(n=this.slotsContainer)==null?void 0:n.querySelector(`[data-slot-id="${t.slotId}"]`);i&&i.scrollIntoView({behavior:"smooth",block:"center"})},100))}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let e=window.getEditableAssets,t=typeof e=="function"?e():null,i=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(i.ok){let n=await i.json(),a=this.mergeRegistries(t,n);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}resetSearch(){this.assetSearchInput&&(this.assetSearchInput.value=""),this.slotSearchInput&&(this.slotSearchInput.value=""),this.scheduleRenderAssets(),this.scheduleRenderSlots()}loadAssetRegistry(e=0){var i,n,a,s;let t=window.getEditableAssets;if(typeof t=="function"){let o=t();if(o!=null&&o.slots&&Array.isArray(o.slots)&&o.slots.length>0){if(this.registry=o,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.cacheBust=Date.now(),this.cachedAssets={},this.pendingAssetFetches={},this.missingPreviewPaths.clear(),!(this.selectedSlotId&&this.registry.slots.some(c=>c.slotId===this.selectedSlotId))){let c=window.__getSelectedObjectId,d=typeof c=="function"?c():null;if(d){let p=this.registry.slots.find(u=>u.objectId===d);p?this.selectedSlotId=p.slotId:this.selectedSlotId=(n=(i=this.registry.slots[0])==null?void 0:i.slotId)!=null?n:null}else this.selectedSlotId=(s=(a=this.registry.slots[0])==null?void 0:a.slotId)!=null?s:null}this.renderSlots(),this.renderAssets();return}}e<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${e+1}/15)`),setTimeout(()=>this.loadAssetRegistry(e+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){var n;if(!this.slotsContainer||!this.registry)return;let e={};for(let a of this.registry.slots)e[a.category]||(e[a.category]=[]),e[a.category].push(a);let t=this.cacheBust||Date.now(),i=(((n=this.slotSearchInput)==null?void 0:n.value)||"").trim().toLowerCase();this.slotsContainer.innerHTML="";for(let a of this.getCategories()){let s=(e[a]||[]).filter(d=>i?`${d.displayName} ${d.slotId} ${d.objectId} ${d.currentAsset}`.toLowerCase().includes(i):!0);if(s.length===0)continue;let o=document.createElement("div");o.className="library-category";let l=document.createElement("div");l.className="library-category-header",l.textContent=this.formatCategoryName(a),o.appendChild(l);let c=document.createElement("div");c.className="library-category-slots";for(let d of s){let p=this.createSlotElement(d,t);c.appendChild(p)}o.appendChild(c),this.slotsContainer.appendChild(o)}if(!this.slotsContainer.hasChildNodes()){let a=document.createElement("div");a.className="library-info",a.textContent=i?"No slots match your search":"No editable slots available",this.slotsContainer.appendChild(a)}}createSlotElement(e,t){var y,w;let i=this.selectedSlotId===e.slotId,n=window.__getSelectedObjectId,s=(typeof n=="function"?n():null)===e.objectId,o=document.createElement("div");o.className=`library-slot ${i?"expanded":""} ${s?"current-object":""}`,o.dataset.slotId=e.slotId,o.dataset.objectId=e.objectId;let l=document.createElement("div");l.className="slot-header";let c=document.createElement("div");if(c.className="slot-current",(y=e.currentAsset)==null?void 0:y.toLowerCase().endsWith(".json")){let v=document.createElement("div");v.className="slot-thumbnail slot-thumbnail-json",v.textContent="\u{1F3AC}",v.title="Lottie/JSON Animation",c.appendChild(v)}else{let v=document.createElement("img"),j=this.resolveSlotPreviewPaths(e),T=j.primary,O=(w=j.fallback)!=null?w:null;if(!T)v.style.display="none";else if(this.missingPreviewPaths.has(T.key)&&(!O||this.missingPreviewPaths.has(O.key)))v.style.display="none";else{v.src=T.src(t),v.alt=e.displayName,v.className="slot-thumbnail",v.loading="lazy";let M=!1;v.onerror=()=>{if(M){v.onerror=null,v.style.display="none";return}if(this.missingPreviewPaths.add(T.key),O&&!this.missingPreviewPaths.has(O.key)){M=!0,v.src=O.src(t);return}O&&this.missingPreviewPaths.add(O.key),v.style.display="none"}}c.appendChild(v)}l.appendChild(c);let p=document.createElement("div");p.className="slot-info";let u=document.createElement("div");u.className="slot-name",u.textContent=e.displayName;let g=document.createElement("div");g.className="slot-asset",g.textContent=e.currentAsset,p.appendChild(u),p.appendChild(g),l.appendChild(p);let h=document.createElement("div");h.className="slot-actions";let f=document.createElement("button");f.className="slot-ai-edit",f.title="Edit with AI",f.textContent="\u2728 AI",f.addEventListener("click",async v=>{v.stopPropagation(),await this.handleAIEdit(e)}),h.appendChild(f);let m=document.createElement("button");m.className="slot-upload",m.title="Upload new asset",m.textContent="\u{1F4E4}",m.addEventListener("click",async v=>{v.stopPropagation(),await this.handleUpload(e)}),h.appendChild(m);let b=document.createElement("button");return b.className="slot-reset",b.title="Reset to default",b.textContent="\u21BA",b.addEventListener("click",async v=>{v.stopPropagation(),await this.handleReset(e)}),h.appendChild(b),l.appendChild(h),l.addEventListener("click",()=>{this.selectedSlotId=e.slotId,this.renderSlots(),this.renderAssets()}),o.appendChild(l),o}renderAssets(){var l;if(!this.assetsContainer||!this.registry)return;let e=this.cacheBust||Date.now(),t=(((l=this.assetSearchInput)==null?void 0:l.value)||"").trim().toLowerCase(),i=this.getSelectedSlot();this.assetsContainer.innerHTML="";let n=document.createElement("div");n.className="library-selected",n.textContent=i?`Selected slot: ${i.displayName} (${i.currentAsset||"no asset"})`:"Select a slot to apply assets",n.style.gridColumn="1 / -1",this.assetsContainer.appendChild(n);let a=this.getCategories(),s=!1,o=!1;for(let c of a){let d=this.getCategoryAssets(c,e);if(!d){let f=document.createElement("div");f.className="library-empty",f.textContent=`Loading ${this.formatCategoryName(c)} assets...`,this.assetsContainer.appendChild(f),o=!0;continue}let p=d.filter(f=>t?`${f.displayName} ${f.filename} ${c}`.toLowerCase().includes(t):!0);if(p.length===0)continue;let u=document.createElement("div");u.className="library-category";let g=document.createElement("div");g.className="library-category-header",g.textContent=this.formatCategoryName(c),u.appendChild(g);let h=document.createElement("div");h.className="slot-library",h.style.borderTop="none",h.style.padding="10px";for(let f of p){let m=document.createElement("div");m.className="library-item",i&&i.currentAsset===f.filename&&i.libraryFolder===c&&m.classList.add("selected");let b=document.createElement("img"),y=this.resolveLibraryAssetPath(c,f.filename);this.missingPreviewPaths.has(y.key)?b.style.display="none":b.src=y.src(e),b.alt=f.displayName,b.className="library-thumbnail",b.loading="lazy",b.onerror=()=>{this.missingPreviewPaths.add(y.key),b.style.opacity="0.3"},m.appendChild(b);let w=document.createElement("div");w.className="library-label",w.textContent=f.displayName,m.appendChild(w),m.addEventListener("click",async()=>{if(!i){alert("Select a slot first to apply an asset.");return}await this.handleApply(i,f.filename,c)}),h.appendChild(m),s=!0}u.appendChild(h),this.assetsContainer.appendChild(u)}if(!s&&!o){let c=document.createElement("div");c.className="library-empty",c.textContent=t?"No assets match your search":"No assets available",this.assetsContainer.appendChild(c)}}getCategoryAssets(e,t){var i;if(this.cachedAssets[e])return this.cachedAssets[e];if(!this.pendingAssetFetches[e]){let n=((i=this.registry)==null?void 0:i.libraryAssets[e])||[];this.pendingAssetFetches[e]=this.fetchFolderAssets(e,t).then(a=>{let s=new Map;for(let o of n)s.set(o.filename,o);for(let o of a)s.has(o.filename)||s.set(o.filename,o);return this.cachedAssets[e]=Array.from(s.values()),delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]}).catch(()=>(this.cachedAssets[e]=n,delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]))}return null}async fetchFolderAssets(e,t){try{let i=await fetch(`/raw/library/${e}/?t=${t}`);if(!i.ok)return[];let n=await i.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(n))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:l,displayName:c})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t,i){var n,a,s;if(this.isApplying){console.warn("[LIBRARY] \u26A0\uFE0F Apply already in progress, ignoring duplicate click");return}this.isApplying=!0,console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let o=window.__wizardAssetPicker;if(o!=null&&o.onPick){let d=`raw/library/${i||e.libraryFolder||e.category}/${t}`;o.onPick(d),window.__wizardAssetPicker=null;return}let l=i||e.libraryFolder||e.category;if((n=this.options)!=null&&n.onApply){await this.options.onApply(e.objectId,t,l),await new Promise(d=>setTimeout(d,200));let c=window.getEditableObjectConfig;if(typeof c=="function"){let d=c(e.objectId),p=((s=(a=d==null?void 0:d.render)==null?void 0:a.asset)==null?void 0:s.path)||"",u=`raw/library/${l}/${t}`;if(p===u||p.includes(t))console.log("[LIBRARY] \u2705 Asset confirmed applied:",p);else throw console.error("[LIBRARY] \u274C Asset NOT applied! Expected:",u,"Got:",p),new Error(`Asset was not applied correctly. Expected: ${u}, Got: ${p}`)}}e.currentAsset=t,e.libraryFolder=l,this.renderSlots(),this.renderAssets()}catch(o){throw console.error("[LIBRARY] \u274C Failed to apply asset:",o),alert(`Failed to apply asset: ${o instanceof Error?o.message:String(o)}`),o}finally{this.isApplying=!1}}async handleReset(e){var t;console.log("[LIBRARY] Resetting slot:",e.slotId,"to default:",e.defaultAsset);try{await((t=this.options)==null?void 0:t.onReset(e.objectId,e.defaultAsset,e.category)),e.currentAsset=e.defaultAsset,this.renderSlots(),this.renderAssets()}catch(i){console.error("[LIBRARY] Failed to reset slot:",i)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}getCategories(){if(!this.registry)return[];let e=new Set;if(Array.isArray(this.registry.categories))for(let t of this.registry.categories)t&&e.add(t);for(let t of Object.keys(this.registry.libraryAssets||{}))t&&e.add(t);for(let t of this.registry.slots||[])t!=null&&t.category&&e.add(t.category);return Array.from(e)}getSelectedSlot(){return!this.registry||!this.selectedSlotId?null:this.registry.slots.find(e=>e.slotId===this.selectedSlotId)||null}scheduleRenderSlots(){this.slotSearchDebounce&&window.clearTimeout(this.slotSearchDebounce),this.slotSearchDebounce=window.setTimeout(()=>{this.slotSearchDebounce=null,this.renderSlots()},150)}scheduleRenderAssets(){this.assetSearchDebounce&&window.clearTimeout(this.assetSearchDebounce),this.assetSearchDebounce=window.setTimeout(()=>{this.assetSearchDebounce=null,this.renderAssets()},150)}resolveSlotPreviewPaths(e){let t=(e.currentAsset||"").trim();if(!t)return{primary:null,fallback:null};let i=t.replace(/^\/+/,""),n=null,a=null;return i.startsWith("raw/")?n=i:i.startsWith("library/")?n=`raw/${i}`:i.includes("/")?n=i:e.libraryFolder?(n=`raw/library/${e.libraryFolder}/${i}`,a=`raw/${i}`):n=`raw/${i}`,{primary:n?{key:n,src:l=>`/${n}?t=${l}`}:null,fallback:a?{key:a,src:l=>`/${a}?t=${l}`}:null}}resolveLibraryAssetPath(e,t){let i=t.replace(/^\/+/,""),n="";return i.startsWith("raw/")?n=i:i.startsWith("library/")?n=`raw/${i}`:i.includes("/")?n=i:n=`raw/library/${e}/${i}`,{key:n,src:a=>`/${n}?t=${a}`}}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let i=e.slotId||e.objectId,n="render.texture";e.category==="ui"&&(n="ui.image"),e.category==="audio"&&(n="audio.src"),t(i,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:n})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var n,a,s,o,l;let i=(n=t.files)==null?void 0:n[0];if(i){console.log("[Library] File selected:",i.name);try{let c=await this.fileToDataUrl(i);if(!c){alert("Failed to read file");return}let d=e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),p=((a=i.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:a[1])||"png",u=p==="jpg"?"jpeg":p,g=`${d}_uploaded_${Date.now()}.${u}`,h=e.category;console.log("[Library] Saving uploaded file:",g,"to category:",h);let m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:h,filename:g,data:c,overwrite:!0})})).json();if(m.success){console.log("[Library] \u2705 Upload saved:",m.path),await new Promise(_=>setTimeout(_,100));let b=window.addAssetToRegistry;typeof b=="function"&&(b(h,g),console.log("[Library] \u2705 Added to registry:",h,g));let y=window.getEditableAssets;if(typeof y=="function"){let _=y();_&&!_.categories&&(_.categories=[]),_!=null&&_.categories&&!_.categories.includes(h)&&(_.categories.push(h),console.log(`[Library] Added category ${h} to registry`))}let w=!1,v=0,j=10;for(;!w&&v<j;){v++,console.log(`[Library] Refresh attempt ${v}/${j}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[Library] \u2705 Registry rebuilt from disk")}catch(x){console.warn("[Library] Setup-library not available:",x)}await new Promise(x=>setTimeout(x,300)),await this.refresh();let _=window.reRenderAssetLibrary;typeof _=="function"&&(console.log("[Library] Re-rendering library panel..."),_());let C=window.getEditableAssets;if(typeof C=="function"){let x=C(),S=((s=x==null?void 0:x.libraryAssets)==null?void 0:s[h])||[];S.some(I=>(I==null?void 0:I.filename)===g)?(console.log("[Library] \u2705 Asset found in registry!"),w=!0):(console.log(`[Library] Asset not found yet, retrying... (found ${S.length} assets in ${h})`),await new Promise(I=>setTimeout(I,500)))}else v>=2&&(w=!0)}w||console.warn("[Library] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway...");let T=!1,O=0,M=5;for(;!T&&O<M;){O++;try{console.log(`[Library] Applying asset attempt ${O}/${M}...`),await this.handleApply(e,g,e.category),await new Promise(C=>setTimeout(C,200));let _=window.getEditableObjectConfig;if(typeof _=="function"){let C=_(e.objectId),x=((l=(o=C==null?void 0:C.render)==null?void 0:o.asset)==null?void 0:l.path)||"";x===m.path||x.includes(g)?(console.log("[Library] \u2705 Asset confirmed applied to object"),T=!0):(console.log(`[Library] Asset not applied yet (attempt ${O}), retrying...`),await new Promise(S=>setTimeout(S,300)))}else T=!0}catch(_){console.error(`[Library] Apply attempt ${O} failed:`,_),O<M&&await new Promise(C=>setTimeout(C,500))}}e.currentAsset=g,await this.refresh(),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[Library] Dispatched config:changed event")}catch(_){console.warn("[Library] Failed to refresh textures:",_)}},300),setTimeout(()=>{this.highlightSlot(e.objectId,h)},1e3),T?console.log("[Library] \u2705 Upload complete and applied!"):console.warn("[Library] \u26A0\uFE0F Upload succeeded but apply may have failed")}else console.error("[Library] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(c){console.error("[Library] \u274C Upload error:",c),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let i=e.startsWith("json.")?e.replace("json.",""):e,n=this.registry.slots.find(a=>(a.objectId===i||a.slotId===i)&&(!t||a.category===t));n?(console.log("[LIBRARY] Highlighting slot:",n.slotId),this.selectedSlotId=n.slotId,this.renderSlots(),this.renderAssets(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${n.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var Hi=class{detectType(e,t,i){let n=e.toLowerCase();return n==="logic_id"||n==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":n.includes("color")||n.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var Fi=class{render(e,t,i,n){let a=this.formatLabel(t),s=i?this.getThumbnailUrl(i):"";return`
870
870
  <div class="inspector-property" data-property-type="image">
871
871
  <div class="inspector-property-header">
872
872
  <label class="inspector-label">${a}</label>
@@ -1037,15 +1037,15 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1037
1037
  </select>
1038
1038
  </div>
1039
1039
  </div>
1040
- `);for(let u in i){if(u==="id")continue;let g=i[u],h=`${n}.${u}`;if(u==="props"&&g&&typeof g=="object"){let m=[];for(let b in g){let y=g[b],w=`${h}.${b}`,v=o[b];if(b==="targetId"||b==="inputId"){let P=this.registry.getObjectIds(),I=typeof y=="string"?y:"",_=I&&!P.includes(I)?[I,...P]:P;m.push(`
1040
+ `);for(let u in i){if(u==="id")continue;let g=i[u],h=`${n}.${u}`;if(u==="props"&&g&&typeof g=="object"){let m=[];for(let b in g){let y=g[b],w=`${h}.${b}`,v=o[b];if(b==="targetId"||b==="inputId"){let j=this.registry.getObjectIds(),T=typeof y=="string"?y:"",O=T&&!j.includes(T)?[T,...j]:j;m.push(`
1041
1041
  <div class="inspector-property inspector-property-text">
1042
1042
  <label class="inspector-property-label">${this.formatLabel(b)}</label>
1043
1043
  <div class="inspector-input-group">
1044
1044
  <select class="inspector-component-select inspector-input"
1045
1045
  data-property-path="${w}"
1046
1046
  data-object-id="${e}">
1047
- <option value="" ${I?"":"selected"}>None</option>
1048
- ${_.map(k=>`<option value="${k}" ${k===I?"selected":""}>${k}</option>`).join("")}
1047
+ <option value="" ${T?"":"selected"}>None</option>
1048
+ ${O.map(M=>`<option value="${M}" ${M===T?"selected":""}>${M}</option>`).join("")}
1049
1049
  </select>
1050
1050
  </div>
1051
1051
  </div>
@@ -1056,11 +1056,11 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1056
1056
  <select class="inspector-component-select inspector-input"
1057
1057
  data-property-path="${w}"
1058
1058
  data-object-id="${e}">
1059
- ${v.map(P=>`<option value="${String(P)}" ${String(P)===String(y)?"selected":""}>${String(P)}</option>`).join("")}
1059
+ ${v.map(j=>`<option value="${String(j)}" ${String(j)===String(y)?"selected":""}>${String(j)}</option>`).join("")}
1060
1060
  </select>
1061
1061
  </div>
1062
1062
  </div>
1063
- `);else{let P=this.registry.renderProperty(e,b,y,w);P&&m.push(P)}}m.length&&a.push(`
1063
+ `);else{let j=this.registry.renderProperty(e,b,y,w);j&&m.push(j)}}m.length&&a.push(`
1064
1064
  <div class="inspector-property inspector-property-object">
1065
1065
  <div class="inspector-object-header">Props</div>
1066
1066
  <div class="inspector-object-body">
@@ -1283,11 +1283,11 @@ ${f}
1283
1283
  ${m.join("")}
1284
1284
  </div>
1285
1285
  </div>
1286
- `);let P=[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),k=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),j=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(P.length||I.length||_.length||k.length||j.length){let x=(E,C)=>C.length?`
1286
+ `);let j=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),T=[u("swing.enabled"),u("swing.amplitude"),u("swing.speed"),u("swing.axis")].filter(Boolean),O=[u("continuousMove.enabled"),u("continuousMove.axis"),u("continuousMove.speed"),u("continuousMove.direction"),u("continuousMove.lifetime")].filter(Boolean),M=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),_=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(j.length||T.length||O.length||M.length||_.length){let x=(E,I)=>I.length?`
1287
1287
  <div class="inspector-motion-continuous-group">
1288
1288
  <div class="inspector-subsection-title">${E}</div>
1289
- <div class="inspector-subsection-content">${C.join("")}</div>
1290
- </div>`:"",S=[x("Pulse",P),x("Swing",I),x("Move forever",_),x("Rotate (pivoting itself)",k),x("Rotate around",j)].filter(Boolean).join("");n.push(`
1289
+ <div class="inspector-subsection-content">${I.join("")}</div>
1290
+ </div>`:"",S=[x("Pulse",j),x("Swing",T),x("Move forever",O),x("Rotate (pivoting itself)",M),x("Rotate around",_)].filter(Boolean).join("");n.push(`
1291
1291
  <div class="inspector-subsection inspector-subsection-continuous">
1292
1292
  <div class="inspector-subsection-title">Continuous</div>
1293
1293
  <div class="inspector-subsection-content inspector-motion-continuous-groups">
@@ -1307,7 +1307,7 @@ ${f}
1307
1307
  ${n.join("")}
1308
1308
  </div>
1309
1309
  </div>
1310
- `}attachEventListeners(){var v,P,I,_;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=cl((k,j,L)=>{var x,S;this.updateManager.updateProperty(k,j,L),(S=(x=this.options)==null?void 0:x.onPropertyChange)==null||S.call(x,k,j,L)},300),i=k=>k?/(^|\.)logic(\.\d+)?\.id$/.test(k):!1;e.forEach(k=>{let j=S=>{var T,O;let E=S.target,C=E.dataset.propertyPath,A=E.dataset.objectId;if(C&&A){let M=E.value;if(E.type==="checkbox")M=E.checked;else if(E.type==="number"){if(M=parseFloat(E.value),isNaN(M))return}else if(E.dataset.json==="true")try{M=JSON.parse(E.value)}catch{return}E.type==="text"||E.type==="range"||E.tagName==="TEXTAREA"?t(A,C,M):(this.updateManager.updateProperty(A,C,M),(O=(T=this.options)==null?void 0:T.onPropertyChange)==null||O.call(T,A,C,M))}},L=k.dataset.propertyPath;L&&(L.includes("transform.anchor")||L.includes("render.anchor"))&&k.tagName==="SELECT"?k.addEventListener("change",async S=>{var O,M,R,z,F;let E=S.target,C=E.dataset.propertyPath,A=E.dataset.objectId,T=E.value;if(!(!C||!A)&&T!=="custom")if(C.includes("transform.anchor")){let q=window.getEditableObjectConfig,N=typeof q=="function"?q(A):null,H=(O=N==null?void 0:N.transform)==null?void 0:O.anchor,$=H!=null&&H!==""?H:"top-left",U=T;await this.updateManager.updateProperty(A,C,T),(R=(M=this.options)==null?void 0:M.onPropertyChange)==null||R.call(M,A,C,T),$!==U&&window.dispatchEvent(new CustomEvent("scene-editor:anchor-changed",{detail:{objectId:A,previousAnchor:$,nextAnchor:U}}))}else await this.updateManager.updateProperty(A,C,T),(F=(z=this.options)==null?void 0:z.onPropertyChange)==null||F.call(z,A,C,T)}):i(L)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",L),k.addEventListener("change",async S=>{var F;let E=S.target,C=E.dataset.propertyPath,A=E.dataset.objectId,T=E.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",T),!C||!A)return;await this.updateManager.updateProperty(A,C,T),console.log("[Inspector v1.0.0] Logic ID updated");let O=window,M=(F=O==null?void 0:O.__HANDLER_LOGIC_META)==null?void 0:F[T],R=this.getDefaultPropsForLogic(T,M);console.log("[Inspector v1.0.0] New logic default props:",R);let z=C.replace(/\.id$/,".props");await this.updateManager.updateProperty(A,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(A)})):(k.addEventListener("change",j),(k.tagName==="INPUT"||k.tagName==="TEXTAREA")&&k.addEventListener("input",j))}),this.contentContainer.querySelectorAll("[data-action]").forEach(k=>{k.addEventListener("click",j=>{let L=j.target,x=L.dataset.action,S=L.dataset.path,E=L.dataset.object;x&&S&&E&&this.quickActions.handleAction(x,E,S)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(k=>{k.addEventListener("click",j=>{var S,E;let L=j.target,x=L.dataset.sectionToggle||((S=L.closest("[data-section-toggle]"))==null?void 0:S.getAttribute("data-section-toggle"));if(x){let C=(E=this.contentContainer)==null?void 0:E.querySelector(`[data-section="${x}"]`);C==null||C.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(k=>{k.addEventListener("click",async j=>{let x=j.currentTarget.dataset.motionPreset;!x||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,x)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(k=>{k.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(k=>{k.addEventListener("click",async j=>{let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,C=E==null?void 0:E(x);if(!C)return;let A=this.updateManager.getNestedProperty(C,S),T=Array.isArray(A)?[...A]:[];T.push({x:0,y:0}),await this.updateManager.updateProperty(x,S,T),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(k=>{k.addEventListener("click",async j=>{let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath,E=Number(L.dataset.index||"-1");if(!x||!S||E<0)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(x);if(!A)return;let T=this.updateManager.getNestedProperty(A,S);if(!Array.isArray(T))return;let O=T.filter((M,R)=>R!==E);await this.updateManager.updateProperty(x,S,O),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(k=>{k.addEventListener("click",async j=>{let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,C=E==null?void 0:E(x);if(!C)return;let A=this.updateManager.getNestedProperty(C,S),T=Array.isArray(A)?[...A]:[];T.push({templateId:"",weight:1}),await this.updateManager.updateProperty(x,S,T),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(k=>{k.addEventListener("click",async j=>{var M;let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath,E=Number((M=L.dataset.index)!=null?M:-1);if(!x||!S||E<0)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(x);if(!A)return;let T=this.updateManager.getNestedProperty(A,S);if(!Array.isArray(T))return;let O=T.filter((R,z)=>z!==E);await this.updateManager.updateProperty(x,S,O),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(k=>{k.addEventListener("click",async j=>{var F;let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,C=E==null?void 0:E(x);if(!C)return;let A=this.updateManager.getNestedProperty(C,S),T;Array.isArray(A)?T=[...A]:A!=null?typeof A=="string"?T=[{id:A,props:{}}]:typeof A=="object"?T=[A]:T=[]:T=[];let O=this.getDefaultLogicId(),M=window,R=(F=M==null?void 0:M.__HANDLER_LOGIC_META)==null?void 0:F[O],z=this.getDefaultPropsForLogic(O,R);T.push({id:O,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:x,path:S,current:A,next:T}),await this.updateManager.updateProperty(x,S,T),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(k=>{k.addEventListener("click",async j=>{var M;let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath,E=Number((M=L.dataset.index)!=null?M:-1);if(!x||!S||E<0)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(x);if(!A)return;let T=this.updateManager.getNestedProperty(A,S);if(!Array.isArray(T))return;let O=T.filter((R,z)=>z!==E);await this.updateManager.updateProperty(x,S,O),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(k=>{k.addEventListener("click",async j=>{var q,N;let L=j.target,x=L.dataset.objectId,S=L.dataset.propertyPath,E=Number((q=L.dataset.index)!=null?q:-1);if(!x||!S||E<0)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(x);if(!A)return;let T=this.updateManager.getNestedProperty(A,S);if(!Array.isArray(T))return;let O=T[E];if(typeof O!="string")return;let M=window,R=(N=M==null?void 0:M.__HANDLER_LOGIC_META)==null?void 0:N[O],z=this.getDefaultPropsForLogic(O,R),F=[...T];F[E]={id:O,props:z},await this.updateManager.updateProperty(x,S,F),this.loadObject(x)})});let m=(v=this.root)==null?void 0:v.querySelector("[data-inspector-advanced]");m==null||m.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(P=this.root)==null?void 0:P.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var j;let k=(j=this.root)==null?void 0:j.querySelector("[data-convert-menu]");k==null||k.classList.toggle("hidden")});let y=(I=this.contentContainer)==null?void 0:I.querySelector("[data-inspector-add-component-btn]"),w=(_=this.contentContainer)==null?void 0:_.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let k=w.value;k&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,k)})}getMotionDefaults(){var i,n,a,s;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(n=(i=t.get("motion"))==null?void 0:i.defaults)!=null?n:{enabled:!0}:t&&typeof t=="object"?(s=(a=t.motion)==null?void 0:a.defaults)!=null?s:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n)return;let a=this.getMotionDefaults(),s={...(l=n.motion)!=null?l:a},o={...(c=s.intro)!=null?c:{}};s.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",s.intro=o,await this.updateManager.updateProperty(e,"motion",s),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,i=t==null?void 0:t(e);if(!i)return;let n=this.getMotionDefaults(),a={...(o=i.motion)!=null?o:n},s={...(l=a.intro)!=null?l:{}};a.enabled=!0,s.enabled=!0,a.intro=s,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};n[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,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(t):s&&typeof s=="object"&&(o=s[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};n[t]={...l},await this.updateManager.updateProperty(e,t,n[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,i){var a,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(a=i.render)==null?void 0:a.asset)==null?void 0:s.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 n=Object.keys(t);return n.length===0||n.length===1&&n[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1310
+ `}attachEventListeners(){var v,j,T,O;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=cl((M,_,C)=>{var x,S;this.updateManager.updateProperty(M,_,C),(S=(x=this.options)==null?void 0:x.onPropertyChange)==null||S.call(x,M,_,C)},300),i=M=>M?/(^|\.)logic(\.\d+)?\.id$/.test(M):!1;e.forEach(M=>{let _=S=>{var A,P;let E=S.target,I=E.dataset.propertyPath,L=E.dataset.objectId;if(I&&L){let k=E.value;if(E.type==="checkbox")k=E.checked;else if(E.type==="number"){if(k=parseFloat(E.value),isNaN(k))return}else if(E.dataset.json==="true")try{k=JSON.parse(E.value)}catch{return}E.type==="text"||E.type==="range"||E.tagName==="TEXTAREA"?t(L,I,k):(this.updateManager.updateProperty(L,I,k),(P=(A=this.options)==null?void 0:A.onPropertyChange)==null||P.call(A,L,I,k))}},C=M.dataset.propertyPath;C&&(C.includes("transform.anchor")||C.includes("render.anchor"))&&M.tagName==="SELECT"?M.addEventListener("change",async S=>{var P,k,R,z,F;let E=S.target,I=E.dataset.propertyPath,L=E.dataset.objectId,A=E.value;if(!(!I||!L)&&A!=="custom")if(I.includes("transform.anchor")){let q=window.getEditableObjectConfig,N=typeof q=="function"?q(L):null,H=(P=N==null?void 0:N.transform)==null?void 0:P.anchor,$=H!=null&&H!==""?H:"top-left",U=A;await this.updateManager.updateProperty(L,I,A),(R=(k=this.options)==null?void 0:k.onPropertyChange)==null||R.call(k,L,I,A),$!==U&&window.dispatchEvent(new CustomEvent("scene-editor:anchor-changed",{detail:{objectId:L,previousAnchor:$,nextAnchor:U}}))}else await this.updateManager.updateProperty(L,I,A),(F=(z=this.options)==null?void 0:z.onPropertyChange)==null||F.call(z,L,I,A)}):i(C)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",C),M.addEventListener("change",async S=>{var F;let E=S.target,I=E.dataset.propertyPath,L=E.dataset.objectId,A=E.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",A),!I||!L)return;await this.updateManager.updateProperty(L,I,A),console.log("[Inspector v1.0.0] Logic ID updated");let P=window,k=(F=P==null?void 0:P.__HANDLER_LOGIC_META)==null?void 0:F[A],R=this.getDefaultPropsForLogic(A,k);console.log("[Inspector v1.0.0] New logic default props:",R);let z=I.replace(/\.id$/,".props");await this.updateManager.updateProperty(L,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(L)})):(M.addEventListener("change",_),(M.tagName==="INPUT"||M.tagName==="TEXTAREA")&&M.addEventListener("input",_))}),this.contentContainer.querySelectorAll("[data-action]").forEach(M=>{M.addEventListener("click",_=>{let C=_.target,x=C.dataset.action,S=C.dataset.path,E=C.dataset.object;x&&S&&E&&this.quickActions.handleAction(x,E,S)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(M=>{M.addEventListener("click",_=>{var S,E;let C=_.target,x=C.dataset.sectionToggle||((S=C.closest("[data-section-toggle]"))==null?void 0:S.getAttribute("data-section-toggle"));if(x){let I=(E=this.contentContainer)==null?void 0:E.querySelector(`[data-section="${x}"]`);I==null||I.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(M=>{M.addEventListener("click",async _=>{let x=_.currentTarget.dataset.motionPreset;!x||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,x)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(M=>{M.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(M=>{M.addEventListener("click",async _=>{let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,I=E==null?void 0:E(x);if(!I)return;let L=this.updateManager.getNestedProperty(I,S),A=Array.isArray(L)?[...L]:[];A.push({x:0,y:0}),await this.updateManager.updateProperty(x,S,A),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(M=>{M.addEventListener("click",async _=>{let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath,E=Number(C.dataset.index||"-1");if(!x||!S||E<0)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(x);if(!L)return;let A=this.updateManager.getNestedProperty(L,S);if(!Array.isArray(A))return;let P=A.filter((k,R)=>R!==E);await this.updateManager.updateProperty(x,S,P),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(M=>{M.addEventListener("click",async _=>{let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,I=E==null?void 0:E(x);if(!I)return;let L=this.updateManager.getNestedProperty(I,S),A=Array.isArray(L)?[...L]:[];A.push({templateId:"",weight:1}),await this.updateManager.updateProperty(x,S,A),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(M=>{M.addEventListener("click",async _=>{var k;let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath,E=Number((k=C.dataset.index)!=null?k:-1);if(!x||!S||E<0)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(x);if(!L)return;let A=this.updateManager.getNestedProperty(L,S);if(!Array.isArray(A))return;let P=A.filter((R,z)=>z!==E);await this.updateManager.updateProperty(x,S,P),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(M=>{M.addEventListener("click",async _=>{var F;let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath;if(!x||!S)return;let E=window.getEditableObjectConfig,I=E==null?void 0:E(x);if(!I)return;let L=this.updateManager.getNestedProperty(I,S),A;Array.isArray(L)?A=[...L]:L!=null?typeof L=="string"?A=[{id:L,props:{}}]:typeof L=="object"?A=[L]:A=[]:A=[];let P=this.getDefaultLogicId(),k=window,R=(F=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:F[P],z=this.getDefaultPropsForLogic(P,R);A.push({id:P,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:x,path:S,current:L,next:A}),await this.updateManager.updateProperty(x,S,A),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(M=>{M.addEventListener("click",async _=>{var k;let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath,E=Number((k=C.dataset.index)!=null?k:-1);if(!x||!S||E<0)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(x);if(!L)return;let A=this.updateManager.getNestedProperty(L,S);if(!Array.isArray(A))return;let P=A.filter((R,z)=>z!==E);await this.updateManager.updateProperty(x,S,P),this.loadObject(x)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(M=>{M.addEventListener("click",async _=>{var q,N;let C=_.target,x=C.dataset.objectId,S=C.dataset.propertyPath,E=Number((q=C.dataset.index)!=null?q:-1);if(!x||!S||E<0)return;let I=window.getEditableObjectConfig,L=I==null?void 0:I(x);if(!L)return;let A=this.updateManager.getNestedProperty(L,S);if(!Array.isArray(A))return;let P=A[E];if(typeof P!="string")return;let k=window,R=(N=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:N[P],z=this.getDefaultPropsForLogic(P,R),F=[...A];F[E]={id:P,props:z},await this.updateManager.updateProperty(x,S,F),this.loadObject(x)})});let m=(v=this.root)==null?void 0:v.querySelector("[data-inspector-advanced]");m==null||m.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let b=(j=this.root)==null?void 0:j.querySelector("[data-convert-toggle]");b==null||b.addEventListener("click",()=>{var _;let M=(_=this.root)==null?void 0:_.querySelector("[data-convert-menu]");M==null||M.classList.toggle("hidden")});let y=(T=this.contentContainer)==null?void 0:T.querySelector("[data-inspector-add-component-btn]"),w=(O=this.contentContainer)==null?void 0:O.querySelector("[data-inspector-component-select]");y==null||y.addEventListener("click",async()=>{let M=w.value;M&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,M)})}getMotionDefaults(){var i,n,a,s;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(n=(i=t.get("motion"))==null?void 0:i.defaults)!=null?n:{enabled:!0}:t&&typeof t=="object"?(s=(a=t.motion)==null?void 0:a.defaults)!=null?s:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n)return;let a=this.getMotionDefaults(),s={...(l=n.motion)!=null?l:a},o={...(c=s.intro)!=null?c:{}};s.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",s.intro=o,await this.updateManager.updateProperty(e,"motion",s),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,i=t==null?void 0:t(e);if(!i)return;let n=this.getMotionDefaults(),a={...(o=i.motion)!=null?o:n},s={...(l=a.intro)!=null?l:{}};a.enabled=!0,s.enabled=!0,a.intro=s,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...s,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};n[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,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(t):s&&typeof s=="object"&&(o=s[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};n[t]={...l},await this.updateManager.updateProperty(e,t,n[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,i){var a,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(a=i.render)==null?void 0:a.asset)==null?void 0:s.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 n=Object.keys(t);return n.length===0||n.length===1&&n[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1311
1311
  <div class="inspector-empty">
1312
1312
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
1313
1313
  <span class="inspector-empty-text">${e}</span>
@@ -1402,7 +1402,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
1402
1402
 
1403
1403
  OUTPUT:
1404
1404
  Generate the requested asset matching the brand style.${r.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
1405
- `.trim()}function or(r){return r.map(e=>{if(typeof e=="string"){let t=e,i,n;return t.includes("background")?(i="background",n="background"):t.includes("button")||t.includes("cta")?(i="ui",n="button"):t.includes("logo")?(i="ui",n="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(i="text",n="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(i="effects",n="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(i="ui",n="image"):(i="environment",n="interactive"),{id:t,category:i,type:n}}return e})}function lr(r,e){return!(r.includes("background")&&(r.includes("_1")||r.includes("splash")||r.includes("endgame")||r.includes("main"))||e==="text"||e==="effects"&&r.includes("particle"))}async function cr(r){var s,o;let e=or(r.gameObjects),t={gamePrompt:r.gamePrompt,gameObjects:e,brandAssets:r.manifest.assets,brandDna:r.manifest.brand_dna,brandName:r.manifest.brand_name},i=sr(t),n=[];if(r.flatDesignDataUrl)try{let l=dr(r.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(n.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",n.length,"images...");let a;try{a=await tn(r.apiKey,i,n,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(s=l.message)!=null&&s.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 fl(a,r.gameObjects)}function fl(r,e){try{let t=r,i=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(i)t=i[1].trim();else{let a=r.match(/\{[\s\S]*\}/);a&&(t=a[0])}let n=JSON.parse(t);return n.mappings&&Array.isArray(n.mappings)?{mappingResult:n,rawResponse:r,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:r,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(i=>({game_object:i,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:r,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function va(r,e,t={}){var n;let i=e.mappings.filter(a=>a.action==="GENERATE");if(i.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${i.length} assets...`);for(let a=0;a<i.length;a++){let s=i[a];(n=t.onProgress)==null||n.call(t,a+1,i.length,s.game_object);try{let o=await ml(r,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function ml(r,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&r.manifest){let o=r.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=r.assetFiles.get(o.file);if(l){let c=await Ge(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(r.flatDesignDataUrl){let o=dr(r.flatDesignDataUrl);o&&t.push(o)}let i=lr(e.game_object),n={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:r.manifest.brand_dna,needsTransparency:i},a=rr(n);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${i})`);let s=await yt(r.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return i&&await bt(s)||s}function dr(r){let[e,t]=r.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return t&&i?{base64:t,mimeType:i[1]}:null}async function pr(r,e){let t=r.assets,i=[];Array.isArray(t)?i=t:t&&typeof t=="object"?i=Object.entries(t).map(([n,a])=>({id:n,file:String(a),role:"visual element"})):i=[],r.assets=i;for(let n of i){let a=e.get(n.file);if(a){let s=await Ge(a);s&&(n.dataUrl=s.dataUrl)}}}function ur(r){var t,i;let e=new Map;if(!r)return console.warn("[CanvaZip] No position data provided"),e;if(typeof r=="string")try{r=JSON.parse(r)}catch(n){return console.error("[CanvaZip] Failed to parse position data JSON:",n),e}if(r!=null&&r.layers&&Array.isArray(r.layers)){console.log(`[CanvaZip] Parsing ${r.layers.length} layers from position data`);for(let n of r.layers){let a=n.asset;if(!a||!n.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",n);continue}let s=n.layout,o={x:typeof s.x=="number"?s.x:0,y:typeof s.y=="number"?s.y:0},l=typeof s.scaleX=="number"?s.scaleX:1,c=typeof s.scaleY=="number"?s.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof s.rotation=="number"?s.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:",r);if(e.size===0&&typeof r=="object"&&!Array.isArray(r)){for(let[n,a]of Object.entries(r))if(a&&typeof a=="object"&&"layout"in a){let s=a.layout,o={x:0,y:0},l=1,c=0;if(s.position&&typeof s.position=="object"?o={x:s.position.x||0,y:s.position.y||0}:(typeof s.x=="number"||typeof s.y=="number")&&(o={x:s.x||0,y:s.y||0}),typeof s.scale=="number")l=s.scale;else if(typeof s.scaleX=="number"||typeof s.scaleY=="number"){let d=(t=s.scaleX)!=null?t:1,p=(i=s.scaleY)!=null?i:1;l=(d+p)/2}typeof s.rotation=="number"&&(c=s.rotation),e.set(n,{position:o,scale:l,rotation:c})}}return e}function gr(r,e){if(!r)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",r),null;if(e.has(r))return console.log(`[CanvaZip] Exact match found for ${r}`),e.get(r);let t=r.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${r} -> ${t}`),e.get(t);let i=t.toLowerCase();for(let[n,a]of e.entries()){let s=n.toLowerCase();if(s===i||s.includes(i)||i.includes(s))return console.log(`[CanvaZip] Partial match found for ${r} -> ${n}`),a}return console.warn(`[CanvaZip] No match found for ${r}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function bl(r){return r.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function hr(){let r=window.getEditableAssets;if(typeof r!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=r();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let i of e.slots)i.assetType==="image"&&i.objectId&&t.push({id:i.objectId,name:i.displayName||bl(i.slotId||i.objectId),type:"sprite"});return t.sort((i,n)=>i.name.localeCompare(n.name))}var vt=require("pixi.js");ut();pi();ae();async function mr(r,e,t){var i,n;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 vt.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)Ee[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(i=c[u])!=null&&i.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=((n=g.getDisplayObject)==null?void 0:n.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 br(r,e){var t,i,n;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(t=s==null?void 0:s.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 vt.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)Ee[m]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(i=u[m])!=null&&i.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=((n=b.getDisplayObject)==null?void 0:n.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)}}var nn=new Map;async function an(r,e,t,i){let a=`${e.startsWith("json.")?e.replace("json.",""):e}:${t}`;if(nn.has(a)){console.log(`[LIBRARY] \u23F3 Operation already in progress for ${a}, waiting...`);try{await nn.get(a),console.log("[LIBRARY] \u2705 Previous operation completed, current apply should be redundant");return}catch(o){console.warn("[LIBRARY] Previous operation failed, proceeding with new apply:",o)}}let s=(async()=>{var o,l,c,d,p,u,g,h,f,m,b,y,w,v,P;console.log("[LIBRARY] applySlotAsset called:",{objectId:e,assetFilename:t,category:i});try{let I=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key derived:",I,"(from objectId:",e+")");let k=(window.__configOverrides||[]).filter(N=>N.path==="render.asset.path"&&N.objectId!==I&&N.value&&N.value.includes(t));k.length>0&&(console.log("[LIBRARY] \u26A0\uFE0F WARNING: Other objects already using this asset:",{assetFilename:t,currentObject:I,otherObjects:k.map(N=>({objectId:N.objectId,assetPath:N.value}))}),console.log("[LIBRARY] This is OK - each object will have its own override entry"));let j=vr(I),L=Date.now(),x=`/raw/library/${i}/${t}?t=${L}`;console.log("[LIBRARY] Loading texture from:",x);try{let N=await fetch(x,{method:"HEAD"});if(N.ok){let H=N.headers.get("content-type");console.log("[LIBRARY] File accessible, Content-Type:",H)}else{console.error("[LIBRARY] \u274C File not accessible:",x,"Status:",N.status);let H=await fetch(x),$=H.headers.get("content-type");if(console.error("[LIBRARY] Content-Type:",$,"Status:",H.status),!H.ok)throw new Error(`File not accessible: ${H.status} ${H.statusText}`)}}catch(N){console.error("[LIBRARY] \u274C Failed to verify file accessibility:",N)}let S,E=3,C=0,A=null;for(;C<E&&!S;)try{C++,console.log(`[LIBRARY] Loading texture attempt ${C}/${E}:`,x);let N=`${x}${x.includes("?")?"&":"?"}retry=${C}`;if(S=await vt.Assets.load(N),!S)throw new Error("Assets.load returned null/undefined");console.log("[LIBRARY] \u2705 Texture loaded successfully"),console.log("[LIBRARY] Texture dimensions:",S.width,"x",S.height);break}catch(N){if(A=N,console.warn(`[LIBRARY] \u26A0\uFE0F Texture load attempt ${C} failed:`,N instanceof Error?N.message:String(N)),C<E){let H=Math.min(300*C,1e3);console.log(`[LIBRARY] Waiting ${H}ms before retry...`),await new Promise($=>setTimeout($,H))}}if(!S)try{console.error("[LIBRARY] \u274C Assets.load failed for:",x),console.error("[LIBRARY] Error details:",A),console.error("[LIBRARY] Error message:",A instanceof Error?A.message:String(A)),console.error("[LIBRARY] Error stack:",A instanceof Error?A.stack:"No stack");try{let H=await(await fetch(x)).blob();console.log("[LIBRARY] Direct fetch successful, blob size:",H.size,"bytes, type:",H.type);let $=new Image,U=URL.createObjectURL(H);await new Promise((Y,V)=>{$.onload=()=>{console.log("[LIBRARY] \u2705 Image decoded successfully via Image API, dimensions:",$.width,"x",$.height),URL.revokeObjectURL(U),Y(null)},$.onerror=G=>{console.error("[LIBRARY] \u274C Image API also failed to decode:",G),URL.revokeObjectURL(U),V(G)},$.src=U}),console.log("[LIBRARY] \u26A0\uFE0F Image is valid via Image API but PixiJS Assets.load failed. This might be a PixiJS-specific issue.")}catch(N){console.error("[LIBRARY] \u274C Image verification also failed:",N)}throw new Error(`Failed to load texture after ${E} attempts: ${A instanceof Error?A.message:String(A)}`)}catch(N){throw N}Ee[I]=S,console.log("[LIBRARY] \u2705 Updated AssetTextures."+I);let T=window.CustomAssets;T!=null&&T[I]&&(T[I].texture=S,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+I));let O=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!O),O){let N=Array.from(((o=O.keys)==null?void 0:o.call(O))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",N);let H=O.get(I);if(console.log("[LIBRARY] gameObject for "+I+"?",!!H),H){let $=((l=H.getDisplayObject)==null?void 0:l.call(H))||H.pixiObject||H.pixi||H,U=(c=$==null?void 0:$.constructor)==null?void 0:c.name;if(console.log("[LIBRARY] displayObject:",$),console.log("[LIBRARY] displayObject type:",U),console.log("[LIBRARY] has texture?",!!($!=null&&$.texture)),$!=null&&$.texture)$.texture=S,console.log("[LIBRARY] \u2705 Applied to display object:",I);else if(U==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:Y}=await import("pixi.js"),V=$.parent,G=(p=(d=V==null?void 0:V.getChildIndex)==null?void 0:d.call(V,$))!=null?p:0,te={x:$.x,y:$.y},W={x:(g=(u=$.anchor)==null?void 0:u.x)!=null?g:.5,y:(f=(h=$.anchor)==null?void 0:h.y)!=null?f:.5},J={x:(b=(m=$.scale)==null?void 0:m.x)!=null?b:1,y:(w=(y=$.scale)==null?void 0:y.y)!=null?w:1},Q=(v=$.alpha)!=null?v:1,fe=(P=$.visible)!=null?P:!0,se=new Y(S);se.anchor.set(W.x,W.y),se.position.set(te.x,te.y),se.scale.set(J.x,J.y),se.alpha=Q,se.visible=fe,V&&(V.removeChild($),V.addChildAt(se,G),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),H.pixiObject&&(H.pixiObject=se),H.pixi&&(H.pixi=se),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if($!=null&&$.children){let Y=$.children.find(V=>V.texture);Y?(Y.texture=S,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let M=`raw/library/${i}/${t}`;wr(I,M,S,j),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:I,texture:S,assetPath:M}})),console.log("[LIBRARY] \u{1F4DD} Applying config override:",{objectId:I,path:"render.asset.path",value:M,persist:!0,emitEvent:!0}),le({objectId:I,path:"render.asset.path",value:M},{persist:!0,emitEvent:!0});let R=window.__configOverrides||[],z=R.find(N=>N.objectId===I&&N.path==="render.asset.path");z?console.log("[LIBRARY] \u2705 Override confirmed in localStorage:",{objectId:z.objectId,path:z.path,value:z.value,totalOverrides:R.length}):console.error("[LIBRARY] \u274C Override NOT found in localStorage after save!"),console.log("[LIBRARY] \u2705 Staged config override for:",I,"path:",M),await new Promise(N=>setTimeout(N,100));let q=(window.__configOverrides||[]).find(N=>N.objectId===I&&N.path==="render.asset.path");if(!q)throw new Error("Override not found in localStorage after save! This is a critical error.");if(q.value!==M)throw new Error(`Override value mismatch! Expected: ${M}, Got: ${q.value}`);console.log("[LIBRARY] \u2705 Override verified in localStorage")}catch(I){throw console.error("[LIBRARY] \u274C Error applying slot asset:",I),I}finally{nn.delete(a)}})();nn.set(a,s),await s}async function yr(r,e,t,i){var n;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:i});try{let a=e.startsWith("json.")?e.replace("json.",""):e,s=vr(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await vt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}Ee[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=((n=u.getDisplayObject)==null?void 0:n.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}wr(a,t,c,s),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),le({objectId:a,path:"render.asset.path",value:t},{persist:!0,emitEvent:!0}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function vr(r){var e,t,i;try{let n=window.getEditableObjectConfig,a=typeof n=="function"?n(r):null;return(i=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?i:null}catch{return null}}function wr(r,e,t,i){if(e){try{let n=`${r}:${e}`;pe.set(n,t)}catch{}if(i&&i!==e)try{let n=pe.store;n!=null&&n.delete&&n.delete(`${r}:${i}`)}catch{}fr(e,t),i&&i!==e&&fr(i,null)}}function fr(r,e){if(!r)return;let t=vt.Assets.cache;if(!t)return;let i=r.replace(/^\.?\//,""),n=[i,`/${i}`];for(let a of n)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var sn=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`
1405
+ `.trim()}function or(r){return r.map(e=>{if(typeof e=="string"){let t=e,i,n;return t.includes("background")?(i="background",n="background"):t.includes("button")||t.includes("cta")?(i="ui",n="button"):t.includes("logo")?(i="ui",n="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(i="text",n="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(i="effects",n="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(i="ui",n="image"):(i="environment",n="interactive"),{id:t,category:i,type:n}}return e})}function lr(r,e){return!(r.includes("background")&&(r.includes("_1")||r.includes("splash")||r.includes("endgame")||r.includes("main"))||e==="text"||e==="effects"&&r.includes("particle"))}async function cr(r){var s,o;let e=or(r.gameObjects),t={gamePrompt:r.gamePrompt,gameObjects:e,brandAssets:r.manifest.assets,brandDna:r.manifest.brand_dna,brandName:r.manifest.brand_name},i=sr(t),n=[];if(r.flatDesignDataUrl)try{let l=dr(r.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(n.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",n.length,"images...");let a;try{a=await tn(r.apiKey,i,n,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(s=l.message)!=null&&s.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 fl(a,r.gameObjects)}function fl(r,e){try{let t=r,i=r.match(/```(?:json)?\s*([\s\S]*?)```/);if(i)t=i[1].trim();else{let a=r.match(/\{[\s\S]*\}/);a&&(t=a[0])}let n=JSON.parse(t);return n.mappings&&Array.isArray(n.mappings)?{mappingResult:n,rawResponse:r,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:r,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(i=>({game_object:i,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:r,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function va(r,e,t={}){var n;let i=e.mappings.filter(a=>a.action==="GENERATE");if(i.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${i.length} assets...`);for(let a=0;a<i.length;a++){let s=i[a];(n=t.onProgress)==null||n.call(t,a+1,i.length,s.game_object);try{let o=await ml(r,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function ml(r,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&r.manifest){let o=r.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=r.assetFiles.get(o.file);if(l){let c=await Ge(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(r.flatDesignDataUrl){let o=dr(r.flatDesignDataUrl);o&&t.push(o)}let i=lr(e.game_object),n={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:r.manifest.brand_dna,needsTransparency:i},a=rr(n);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${i})`);let s=await yt(r.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return i&&await bt(s)||s}function dr(r){let[e,t]=r.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return t&&i?{base64:t,mimeType:i[1]}:null}async function pr(r,e){let t=r.assets,i=[];Array.isArray(t)?i=t:t&&typeof t=="object"?i=Object.entries(t).map(([n,a])=>({id:n,file:String(a),role:"visual element"})):i=[],r.assets=i;for(let n of i){let a=e.get(n.file);if(a){let s=await Ge(a);s&&(n.dataUrl=s.dataUrl)}}}function ur(r){var t,i;let e=new Map;if(!r)return console.warn("[CanvaZip] No position data provided"),e;if(typeof r=="string")try{r=JSON.parse(r)}catch(n){return console.error("[CanvaZip] Failed to parse position data JSON:",n),e}if(r!=null&&r.layers&&Array.isArray(r.layers)){console.log(`[CanvaZip] Parsing ${r.layers.length} layers from position data`);for(let n of r.layers){let a=n.asset;if(!a||!n.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",n);continue}let s=n.layout,o={x:typeof s.x=="number"?s.x:0,y:typeof s.y=="number"?s.y:0},l=typeof s.scaleX=="number"?s.scaleX:1,c=typeof s.scaleY=="number"?s.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof s.rotation=="number"?s.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:",r);if(e.size===0&&typeof r=="object"&&!Array.isArray(r)){for(let[n,a]of Object.entries(r))if(a&&typeof a=="object"&&"layout"in a){let s=a.layout,o={x:0,y:0},l=1,c=0;if(s.position&&typeof s.position=="object"?o={x:s.position.x||0,y:s.position.y||0}:(typeof s.x=="number"||typeof s.y=="number")&&(o={x:s.x||0,y:s.y||0}),typeof s.scale=="number")l=s.scale;else if(typeof s.scaleX=="number"||typeof s.scaleY=="number"){let d=(t=s.scaleX)!=null?t:1,p=(i=s.scaleY)!=null?i:1;l=(d+p)/2}typeof s.rotation=="number"&&(c=s.rotation),e.set(n,{position:o,scale:l,rotation:c})}}return e}function gr(r,e){if(!r)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",r),null;if(e.has(r))return console.log(`[CanvaZip] Exact match found for ${r}`),e.get(r);let t=r.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${r} -> ${t}`),e.get(t);let i=t.toLowerCase();for(let[n,a]of e.entries()){let s=n.toLowerCase();if(s===i||s.includes(i)||i.includes(s))return console.log(`[CanvaZip] Partial match found for ${r} -> ${n}`),a}return console.warn(`[CanvaZip] No match found for ${r}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function bl(r){return r.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function hr(){let r=window.getEditableAssets;if(typeof r!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=r();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let i of e.slots)i.assetType==="image"&&i.objectId&&t.push({id:i.objectId,name:i.displayName||bl(i.slotId||i.objectId),type:"sprite"});return t.sort((i,n)=>i.name.localeCompare(n.name))}var vt=require("pixi.js");ut();pi();ae();async function mr(r,e,t){var i,n;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 vt.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)Ee[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(i=c[u])!=null&&i.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=((n=g.getDisplayObject)==null?void 0:n.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 br(r,e){var t,i,n;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(t=s==null?void 0:s.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 vt.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)Ee[m]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(i=u[m])!=null&&i.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=((n=b.getDisplayObject)==null?void 0:n.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)}}var nn=new Map;async function an(r,e,t,i){let a=`${e.startsWith("json.")?e.replace("json.",""):e}:${t}`;if(nn.has(a)){console.log(`[LIBRARY] \u23F3 Operation already in progress for ${a}, waiting...`);try{await nn.get(a),console.log("[LIBRARY] \u2705 Previous operation completed, current apply should be redundant");return}catch(o){console.warn("[LIBRARY] Previous operation failed, proceeding with new apply:",o)}}let s=(async()=>{var o,l,c,d,p,u,g,h,f,m,b,y,w,v,j;console.log("[LIBRARY] applySlotAsset called:",{objectId:e,assetFilename:t,category:i});try{let T=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key derived:",T,"(from objectId:",e+")");let M=(window.__configOverrides||[]).filter(N=>N.path==="render.asset.path"&&N.objectId!==T&&N.value&&N.value.includes(t));M.length>0&&(console.log("[LIBRARY] \u26A0\uFE0F WARNING: Other objects already using this asset:",{assetFilename:t,currentObject:T,otherObjects:M.map(N=>({objectId:N.objectId,assetPath:N.value}))}),console.log("[LIBRARY] This is OK - each object will have its own override entry"));let _=vr(T),C=Date.now(),x=`/raw/library/${i}/${t}?t=${C}`;console.log("[LIBRARY] Loading texture from:",x);try{let N=await fetch(x,{method:"HEAD"});if(N.ok){let H=N.headers.get("content-type");console.log("[LIBRARY] File accessible, Content-Type:",H)}else{console.error("[LIBRARY] \u274C File not accessible:",x,"Status:",N.status);let H=await fetch(x),$=H.headers.get("content-type");if(console.error("[LIBRARY] Content-Type:",$,"Status:",H.status),!H.ok)throw new Error(`File not accessible: ${H.status} ${H.statusText}`)}}catch(N){console.error("[LIBRARY] \u274C Failed to verify file accessibility:",N)}let S,E=3,I=0,L=null;for(;I<E&&!S;)try{I++,console.log(`[LIBRARY] Loading texture attempt ${I}/${E}:`,x);let N=`${x}${x.includes("?")?"&":"?"}retry=${I}`;if(S=await vt.Assets.load(N),!S)throw new Error("Assets.load returned null/undefined");console.log("[LIBRARY] \u2705 Texture loaded successfully"),console.log("[LIBRARY] Texture dimensions:",S.width,"x",S.height);break}catch(N){if(L=N,console.warn(`[LIBRARY] \u26A0\uFE0F Texture load attempt ${I} failed:`,N instanceof Error?N.message:String(N)),I<E){let H=Math.min(300*I,1e3);console.log(`[LIBRARY] Waiting ${H}ms before retry...`),await new Promise($=>setTimeout($,H))}}if(!S)try{console.error("[LIBRARY] \u274C Assets.load failed for:",x),console.error("[LIBRARY] Error details:",L),console.error("[LIBRARY] Error message:",L instanceof Error?L.message:String(L)),console.error("[LIBRARY] Error stack:",L instanceof Error?L.stack:"No stack");try{let H=await(await fetch(x)).blob();console.log("[LIBRARY] Direct fetch successful, blob size:",H.size,"bytes, type:",H.type);let $=new Image,U=URL.createObjectURL(H);await new Promise((Y,V)=>{$.onload=()=>{console.log("[LIBRARY] \u2705 Image decoded successfully via Image API, dimensions:",$.width,"x",$.height),URL.revokeObjectURL(U),Y(null)},$.onerror=G=>{console.error("[LIBRARY] \u274C Image API also failed to decode:",G),URL.revokeObjectURL(U),V(G)},$.src=U}),console.log("[LIBRARY] \u26A0\uFE0F Image is valid via Image API but PixiJS Assets.load failed. This might be a PixiJS-specific issue.")}catch(N){console.error("[LIBRARY] \u274C Image verification also failed:",N)}throw new Error(`Failed to load texture after ${E} attempts: ${L instanceof Error?L.message:String(L)}`)}catch(N){throw N}Ee[T]=S,console.log("[LIBRARY] \u2705 Updated AssetTextures."+T);let A=window.CustomAssets;A!=null&&A[T]&&(A[T].texture=S,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+T));let P=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!P),P){let N=Array.from(((o=P.keys)==null?void 0:o.call(P))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",N);let H=P.get(T);if(console.log("[LIBRARY] gameObject for "+T+"?",!!H),H){let $=((l=H.getDisplayObject)==null?void 0:l.call(H))||H.pixiObject||H.pixi||H,U=(c=$==null?void 0:$.constructor)==null?void 0:c.name;if(console.log("[LIBRARY] displayObject:",$),console.log("[LIBRARY] displayObject type:",U),console.log("[LIBRARY] has texture?",!!($!=null&&$.texture)),$!=null&&$.texture)$.texture=S,console.log("[LIBRARY] \u2705 Applied to display object:",T);else if(U==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:Y}=await import("pixi.js"),V=$.parent,G=(p=(d=V==null?void 0:V.getChildIndex)==null?void 0:d.call(V,$))!=null?p:0,te={x:$.x,y:$.y},W={x:(g=(u=$.anchor)==null?void 0:u.x)!=null?g:.5,y:(f=(h=$.anchor)==null?void 0:h.y)!=null?f:.5},J={x:(b=(m=$.scale)==null?void 0:m.x)!=null?b:1,y:(w=(y=$.scale)==null?void 0:y.y)!=null?w:1},Q=(v=$.alpha)!=null?v:1,fe=(j=$.visible)!=null?j:!0,se=new Y(S);se.anchor.set(W.x,W.y),se.position.set(te.x,te.y),se.scale.set(J.x,J.y),se.alpha=Q,se.visible=fe,V&&(V.removeChild($),V.addChildAt(se,G),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),H.pixiObject&&(H.pixiObject=se),H.pixi&&(H.pixi=se),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if($!=null&&$.children){let Y=$.children.find(V=>V.texture);Y?(Y.texture=S,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let k=`raw/library/${i}/${t}`;wr(T,k,S,_),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:T,texture:S,assetPath:k}})),console.log("[LIBRARY] \u{1F4DD} Applying config override:",{objectId:T,path:"render.asset.path",value:k,persist:!0,emitEvent:!0}),le({objectId:T,path:"render.asset.path",value:k},{persist:!0,emitEvent:!0});let R=window.__configOverrides||[],z=R.find(N=>N.objectId===T&&N.path==="render.asset.path");z?console.log("[LIBRARY] \u2705 Override confirmed in localStorage:",{objectId:z.objectId,path:z.path,value:z.value,totalOverrides:R.length}):console.error("[LIBRARY] \u274C Override NOT found in localStorage after save!"),console.log("[LIBRARY] \u2705 Staged config override for:",T,"path:",k),await new Promise(N=>setTimeout(N,100));let q=(window.__configOverrides||[]).find(N=>N.objectId===T&&N.path==="render.asset.path");if(!q)throw new Error("Override not found in localStorage after save! This is a critical error.");if(q.value!==k)throw new Error(`Override value mismatch! Expected: ${k}, Got: ${q.value}`);console.log("[LIBRARY] \u2705 Override verified in localStorage")}catch(T){throw console.error("[LIBRARY] \u274C Error applying slot asset:",T),T}finally{nn.delete(a)}})();nn.set(a,s),await s}async function yr(r,e,t,i){var n;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:i});try{let a=e.startsWith("json.")?e.replace("json.",""):e,s=vr(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await vt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}Ee[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=((n=u.getDisplayObject)==null?void 0:n.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}wr(a,t,c,s),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),le({objectId:a,path:"render.asset.path",value:t},{persist:!0,emitEvent:!0}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function vr(r){var e,t,i;try{let n=window.getEditableObjectConfig,a=typeof n=="function"?n(r):null;return(i=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?i:null}catch{return null}}function wr(r,e,t,i){if(e){try{let n=`${r}:${e}`;pe.set(n,t)}catch{}if(i&&i!==e)try{let n=pe.store;n!=null&&n.delete&&n.delete(`${r}:${i}`)}catch{}fr(e,t),i&&i!==e&&fr(i,null)}}function fr(r,e){if(!r)return;let t=vt.Assets.cache;if(!t)return;let i=r.replace(/^\.?\//,""),n=[i,`/${i}`];for(let a of n)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var sn=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`
1406
1406
  <div class="canva-wizard-overlay" data-canva-wizard>
1407
1407
  <div class="canva-wizard-modal">
1408
1408
  <div class="canva-wizard-header">
@@ -1639,7 +1639,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
1639
1639
  </div>
1640
1640
  <div class="panel-resize-handle" data-panel-resize></div>
1641
1641
  </div>
1642
- `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,i,n,a,s,o,l,c,d,p,u,g,h,f;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let m="/dashboard";window.location.pathname!==m&&(window.location.href=m)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(m=>{m.addEventListener("click",()=>{let b=m.dataset.visionTab;this.switchTab(b)})}),(i=this.root.querySelector("[data-vision-upload-method]"))==null||i.addEventListener("change",m=>{let b=m.target.value;this.switchUploadMethod(b)}),(n=this.root.querySelector("[data-vision-upload-manifest]"))==null||n.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-manifest-input]"))==null||b.click()}),(a=this.root.querySelector("[data-vision-upload-batch-png]"))==null||a.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-batch-png-input]"))==null||b.click()}),(s=this.root.querySelector("[data-vision-batch-png-input]"))==null||s.addEventListener("change",m=>{this.handleBatchPNGUpload(m)}),(o=this.root.querySelector("[data-vision-upload-zip]"))==null||o.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-zip-input]"))==null||b.click()}),(l=this.root.querySelector("[data-vision-zip-input]"))==null||l.addEventListener("change",m=>{this.handleZipUpload(m)}),(c=this.root.querySelector("[data-vision-manifest-input]"))==null||c.addEventListener("change",m=>{this.handleManifestUpload(m)}),(d=this.root.querySelector("[data-vision-upload-assets]"))==null||d.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-assets-input]"))==null||b.click()}),(p=this.root.querySelector("[data-vision-assets-input]"))==null||p.addEventListener("change",m=>{this.handleAssetsUpload(m)}),(u=this.root.querySelector("[data-vision-upload-flat]"))==null||u.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-flat-input]"))==null||b.click()}),(g=this.root.querySelector("[data-vision-flat-input]"))==null||g.addEventListener("change",m=>{this.handleFlatDesignUpload(m)}),(h=this.root.querySelector("[data-vision-generate-all]"))==null||h.addEventListener("click",()=>{this.generateAllMissing()}),(f=this.root.querySelector("[data-vision-apply-all]"))==null||f.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",m=>{let b=m.target;if(!b)return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;w&&(b.closest("[data-mapping-apply-one]")&&this.applyOne(w),b.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(w),b.closest("[data-mapping-edit-one]")&&this.openEditorForOne(w),b.closest("[data-mapping-generate-one]")&&this.generateOne(w),b.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",m=>{let b=m.target;if(!b||!this.mappingResult)return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;if(!w)return;let v=this.mappingResult.mappings.find(P=>P.game_object===w);v&&(b.matches("[data-mapping-action]")&&(v.action=String(b.value||"KEEP"),v.status="Edited",this.renderMappings()),b.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(b.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",m=>{let b=m.target;if(!b||!this.mappingResult||!b.matches("[data-mapping-prompt]"))return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;if(!w)return;let v=this.mappingResult.mappings.find(P=>P.game_object===w);v&&(v.generation_prompt=String(b.value||""),v.status="Edited")})}switchTab(e){var t,i;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(n=>n.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(n=>n.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(i=this.root.querySelector(`[data-vision-content="${e}"]`))==null||i.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(i=>{i.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleBatchPNGUpload(e){var s;let t=e.target,i=Array.from(t.files||[]);if(i.length===0)return;let n=i.filter(o=>o.type.startsWith("image/"));if(n.length===0){this.setStatus("upload","\u26A0\uFE0F No image files selected");return}let a=(s=this.root)==null?void 0:s.querySelector("[data-vision-batch-png-status]");a&&(a.textContent=`Processing ${n.length} PNG${n.length>1?"s":""}...`);try{let o=window.__HANDLER_ACTIVE_SCREEN,l=o==="loading"||o==="start"||o==="gameplay"||o==="tutorial"||o==="endgame"?o:"gameplay",c=[];for(let g=0;g<n.length;g++){let h=n[g];try{let f=await this.fileToDataUrl(h);if(!f){c.push({success:!1,filename:h.name,error:"Failed to read file"});continue}let m=h.name.replace(/\.[^/.]+$/,""),b=this.inferCategoryFromFilename(m),y=m.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase(),w=`${y}_${Date.now()}${g>0?`_${g}`:""}`,v=`json.${w}`,P=`${y}.png`,_=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:b,filename:P,data:f,overwrite:!1})})).json();if(!_.success){c.push({success:!1,filename:h.name,error:_.error});continue}let k={identity:{id:v,category:b},transform:{anchor:"center",position:{x:0,y:0},scale:1,rotation:0},render:{z_index:0,alpha:1,visible:!0,anchor:{x:.5,y:.5},asset:{type:"image",path:_.path||`raw/library/${b}/${P}`}}},j=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:l,instanceId:w,objectConfigId:v,config:k,layer:b==="ui"?"ui":"world"})}),L=await j.json();j.ok&&L.success?c.push({success:!0,filename:h.name}):c.push({success:!1,filename:h.name,error:L.error})}catch(f){c.push({success:!1,filename:h.name,error:f instanceof Error?f.message:String(f)})}}let d=c.filter(g=>g.success).length,p=c.length-d;a&&(p===0?a.textContent=`\u2705 Added ${d} PNG${d>1?"s":""} to scene`:a.textContent=`\u26A0\uFE0F Added ${d}, failed ${p}`),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh"));let u=window.refreshAssetLibrary;typeof u=="function"&&u(),t.value=""}catch(o){a&&(a.textContent=`\u274C Error: ${o instanceof Error?o.message:String(o)}`),console.error("[BrandVision] Batch PNG upload failed:",o)}}inferCategoryFromFilename(e){let t=e.toLowerCase();return t.startsWith("ui_")||t.includes("button")||t.includes("label")?"ui":t.startsWith("bg_")||t.includes("background")?"backgrounds":t.includes("character")||t.includes("player")?"character":"environment"}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}async handleZipUpload(e){var n;let i=(n=e.target.files)==null?void 0:n[0];if(i){this.zipFile=i,this.setStatus("zip",`Selected: ${i.name} (${(i.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(i)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(e){var l;let t=null;if(typeof window!="undefined"&&window.JSZip)t=window.JSZip,console.log("[BrandVision] \u2705 Found window.JSZip");else try{let c=await import("jszip");t=c.default||c,console.log("[BrandVision] \u2705 Loaded JSZip via dynamic import")}catch(c){throw new Error(`JSZip is not properly imported. Make sure jszip is loaded globally (window.JSZip) or available as a module: ${(c==null?void 0:c.message)||"Unknown error"}`)}if(!t||typeof t.loadAsync!="function")throw new Error("JSZip is not properly imported - loadAsync method not found");let i=await t.loadAsync(e),n=[],a=[];i.forEach((c,d)=>{let p=c.toLowerCase();p.endsWith(".json")?n.push({name:c,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:c,file:d})});for(let c of n)try{let d=await((l=i.file(c.name))==null?void 0:l.async("text"));d&&(c.content=JSON.parse(d))}catch(d){console.warn(`Failed to parse ${c.name}:`,d)}let s=[];for(let c of a)try{let d=await c.file.async("uint8array"),p=new Blob([d],{type:"image/png"}),u=c.name.split("/").pop()||c.name;console.log(`Processing ${u}, uint8array length: ${d.length}, blob size: ${p.size}`);let g;try{g=await this.blobToDataUrl(p)}catch(h){console.warn(`FileReader failed for ${u}, using fallback:`,h),g=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(d)))}`}if(!g.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${u}:`,g.substring(0,100));continue}s.push({filename:u,dataUrl:g})}catch(d){console.warn(`Failed to extract ${c.name}:`,d)}let o=null;for(let c of n){let d=c.name.toLowerCase();if(d.includes("positionnormalizedpack")||d.includes("positionnormalized")){o=c.content,console.log(`[BrandVision] Found position data file: ${c.name}`,{hasContent:!!o,isString:typeof o=="string",isObject:typeof o=="object",hasLayers:o!=null&&o.layers?o.layers.length:0});break}}if(o||console.warn("[BrandVision] No positionnormalizedpack.json found in ZIP. Available JSON files:",n.map(c=>c.name)),s.length>0){await this.showCanvaZipWizard(s,o),this.setStatus("zip",`\u2705 Wizard completed - ${s.length} assets processed`);return}else{this.setStatus("zip","\u26A0\uFE0F No PNG files found in ZIP");return}}async showCanvaZipWizard(e,t){return new Promise(i=>{let n=e.filter(o=>!this.wizardProcessedAssets.has(o.filename));if(n.length===0){console.log("[BrandVision] All assets already processed by wizard"),i();return}let a=document.createElement("div");document.body.appendChild(a),new sn().initialize(a,n,t,{onComplete:o=>{console.log("[BrandVision] Wizard completed, processed assets:",o),o.forEach(l=>{this.wizardProcessedAssets.add(l.filename)}),a.remove(),i()},onCancel:()=>{console.log("[BrandVision] Wizard cancelled"),a.remove(),i()}})})}async blobToDataUrl(e){return new Promise((t,i)=>{let n=new FileReader;n.onload=()=>{let a=n.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),t(a)},n.onerror=a=>{console.error("FileReader error:",a),i(a)},n.readAsDataURL(e)})}inferAssetCategory(e){let t=e.toLowerCase();return t.includes("background")||t.includes("bg")?"backgrounds":t.includes("ui")||t.includes("button")||t.includes("cta")||t.includes("logo")||t.includes("text")?"ui":t.includes("sparkle")||t.includes("effect")||t.includes("particle")?"effects":t.includes("bottle")||t.includes("product")||t.includes("item")?"products":"misc"}addAssetsToRegistry(e){let t=window.getEditableAssets;if(typeof t!="function")return;let i=t();if(!(i!=null&&i.libraryAssets))return;let n={};for(let a of e){let s=a.category||"misc";n[s]||(n[s]=[]),i.libraryAssets[s]||(i.libraryAssets[s]=[]),i.libraryAssets[s].some(l=>l.filename===a.filename)||(i.libraryAssets[s].unshift({filename:a.filename,displayName:a.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${a.filename} to registry category ${s}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var s;let t=e.target,i=t.files;if(!i||i.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let n="";for(let o of Array.from(i))try{let l=await o.text(),c=JSON.parse(l);this.uploadedJsons.set(o.name,c),c.layers?n+=`\u2705 Layers: ${o.name}
1642
+ `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,i,n,a,s,o,l,c,d,p,u,g,h,f;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let m="/dashboard";window.location.pathname!==m&&(window.location.href=m)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(m=>{m.addEventListener("click",()=>{let b=m.dataset.visionTab;this.switchTab(b)})}),(i=this.root.querySelector("[data-vision-upload-method]"))==null||i.addEventListener("change",m=>{let b=m.target.value;this.switchUploadMethod(b)}),(n=this.root.querySelector("[data-vision-upload-manifest]"))==null||n.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-manifest-input]"))==null||b.click()}),(a=this.root.querySelector("[data-vision-upload-batch-png]"))==null||a.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-batch-png-input]"))==null||b.click()}),(s=this.root.querySelector("[data-vision-batch-png-input]"))==null||s.addEventListener("change",m=>{this.handleBatchPNGUpload(m)}),(o=this.root.querySelector("[data-vision-upload-zip]"))==null||o.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-zip-input]"))==null||b.click()}),(l=this.root.querySelector("[data-vision-zip-input]"))==null||l.addEventListener("change",m=>{this.handleZipUpload(m)}),(c=this.root.querySelector("[data-vision-manifest-input]"))==null||c.addEventListener("change",m=>{this.handleManifestUpload(m)}),(d=this.root.querySelector("[data-vision-upload-assets]"))==null||d.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-assets-input]"))==null||b.click()}),(p=this.root.querySelector("[data-vision-assets-input]"))==null||p.addEventListener("change",m=>{this.handleAssetsUpload(m)}),(u=this.root.querySelector("[data-vision-upload-flat]"))==null||u.addEventListener("click",()=>{var m,b;(b=(m=this.root)==null?void 0:m.querySelector("[data-vision-flat-input]"))==null||b.click()}),(g=this.root.querySelector("[data-vision-flat-input]"))==null||g.addEventListener("change",m=>{this.handleFlatDesignUpload(m)}),(h=this.root.querySelector("[data-vision-generate-all]"))==null||h.addEventListener("click",()=>{this.generateAllMissing()}),(f=this.root.querySelector("[data-vision-apply-all]"))==null||f.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",m=>{let b=m.target;if(!b)return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;w&&(b.closest("[data-mapping-apply-one]")&&this.applyOne(w),b.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(w),b.closest("[data-mapping-edit-one]")&&this.openEditorForOne(w),b.closest("[data-mapping-generate-one]")&&this.generateOne(w),b.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",m=>{let b=m.target;if(!b||!this.mappingResult)return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;if(!w)return;let v=this.mappingResult.mappings.find(j=>j.game_object===w);v&&(b.matches("[data-mapping-action]")&&(v.action=String(b.value||"KEEP"),v.status="Edited",this.renderMappings()),b.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(b.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",m=>{let b=m.target;if(!b||!this.mappingResult||!b.matches("[data-mapping-prompt]"))return;let y=b.closest("[data-mapping-item]"),w=y==null?void 0:y.dataset.mappingItem;if(!w)return;let v=this.mappingResult.mappings.find(j=>j.game_object===w);v&&(v.generation_prompt=String(b.value||""),v.status="Edited")})}switchTab(e){var t,i;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(n=>n.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(n=>n.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(i=this.root.querySelector(`[data-vision-content="${e}"]`))==null||i.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(i=>{i.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleBatchPNGUpload(e){var s;let t=e.target,i=Array.from(t.files||[]);if(i.length===0)return;let n=i.filter(o=>o.type.startsWith("image/"));if(n.length===0){this.setStatus("upload","\u26A0\uFE0F No image files selected");return}let a=(s=this.root)==null?void 0:s.querySelector("[data-vision-batch-png-status]");a&&(a.textContent=`Processing ${n.length} PNG${n.length>1?"s":""}...`);try{let o=window.__HANDLER_ACTIVE_SCREEN,l=o==="loading"||o==="start"||o==="gameplay"||o==="tutorial"||o==="endgame"?o:"gameplay",c=[];for(let g=0;g<n.length;g++){let h=n[g];try{let f=await this.fileToDataUrl(h);if(!f){c.push({success:!1,filename:h.name,error:"Failed to read file"});continue}let m=h.name.replace(/\.[^/.]+$/,""),b=this.inferCategoryFromFilename(m),y=m.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase(),w=`${y}_${Date.now()}${g>0?`_${g}`:""}`,v=`json.${w}`,j=`${y}.png`,O=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:b,filename:j,data:f,overwrite:!1})})).json();if(!O.success){c.push({success:!1,filename:h.name,error:O.error});continue}let M={identity:{id:v,category:b},transform:{anchor:"center",position:{x:0,y:0},scale:1,rotation:0},render:{z_index:0,alpha:1,visible:!0,anchor:{x:.5,y:.5},asset:{type:"image",path:O.path||`raw/library/${b}/${j}`}}},_=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:l,instanceId:w,objectConfigId:v,config:M,layer:b==="ui"?"ui":"world"})}),C=await _.json();_.ok&&C.success?c.push({success:!0,filename:h.name}):c.push({success:!1,filename:h.name,error:C.error})}catch(f){c.push({success:!1,filename:h.name,error:f instanceof Error?f.message:String(f)})}}let d=c.filter(g=>g.success).length,p=c.length-d;a&&(p===0?a.textContent=`\u2705 Added ${d} PNG${d>1?"s":""} to scene`:a.textContent=`\u26A0\uFE0F Added ${d}, failed ${p}`),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh"));let u=window.refreshAssetLibrary;typeof u=="function"&&u(),t.value=""}catch(o){a&&(a.textContent=`\u274C Error: ${o instanceof Error?o.message:String(o)}`),console.error("[BrandVision] Batch PNG upload failed:",o)}}inferCategoryFromFilename(e){let t=e.toLowerCase();return t.startsWith("ui_")||t.includes("button")||t.includes("label")?"ui":t.startsWith("bg_")||t.includes("background")?"backgrounds":t.includes("character")||t.includes("player")?"character":"environment"}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}async handleZipUpload(e){var n;let i=(n=e.target.files)==null?void 0:n[0];if(i){this.zipFile=i,this.setStatus("zip",`Selected: ${i.name} (${(i.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(i)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(e){var l;let t=null;if(typeof window!="undefined"&&window.JSZip)t=window.JSZip,console.log("[BrandVision] \u2705 Found window.JSZip");else try{let c=await import("jszip");t=c.default||c,console.log("[BrandVision] \u2705 Loaded JSZip via dynamic import")}catch(c){throw new Error(`JSZip is not properly imported. Make sure jszip is loaded globally (window.JSZip) or available as a module: ${(c==null?void 0:c.message)||"Unknown error"}`)}if(!t||typeof t.loadAsync!="function")throw new Error("JSZip is not properly imported - loadAsync method not found");let i=await t.loadAsync(e),n=[],a=[];i.forEach((c,d)=>{let p=c.toLowerCase();p.endsWith(".json")?n.push({name:c,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:c,file:d})});for(let c of n)try{let d=await((l=i.file(c.name))==null?void 0:l.async("text"));d&&(c.content=JSON.parse(d))}catch(d){console.warn(`Failed to parse ${c.name}:`,d)}let s=[];for(let c of a)try{let d=await c.file.async("uint8array"),p=new Blob([d],{type:"image/png"}),u=c.name.split("/").pop()||c.name;console.log(`Processing ${u}, uint8array length: ${d.length}, blob size: ${p.size}`);let g;try{g=await this.blobToDataUrl(p)}catch(h){console.warn(`FileReader failed for ${u}, using fallback:`,h),g=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(d)))}`}if(!g.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${u}:`,g.substring(0,100));continue}s.push({filename:u,dataUrl:g})}catch(d){console.warn(`Failed to extract ${c.name}:`,d)}let o=null;for(let c of n){let d=c.name.toLowerCase();if(d.includes("positionnormalizedpack")||d.includes("positionnormalized")){o=c.content,console.log(`[BrandVision] Found position data file: ${c.name}`,{hasContent:!!o,isString:typeof o=="string",isObject:typeof o=="object",hasLayers:o!=null&&o.layers?o.layers.length:0});break}}if(o||console.warn("[BrandVision] No positionnormalizedpack.json found in ZIP. Available JSON files:",n.map(c=>c.name)),s.length>0){await this.showCanvaZipWizard(s,o),this.setStatus("zip",`\u2705 Wizard completed - ${s.length} assets processed`);return}else{this.setStatus("zip","\u26A0\uFE0F No PNG files found in ZIP");return}}async showCanvaZipWizard(e,t){return new Promise(i=>{let n=e.filter(o=>!this.wizardProcessedAssets.has(o.filename));if(n.length===0){console.log("[BrandVision] All assets already processed by wizard"),i();return}let a=document.createElement("div");document.body.appendChild(a),new sn().initialize(a,n,t,{onComplete:o=>{console.log("[BrandVision] Wizard completed, processed assets:",o),o.forEach(l=>{this.wizardProcessedAssets.add(l.filename)}),a.remove(),i()},onCancel:()=>{console.log("[BrandVision] Wizard cancelled"),a.remove(),i()}})})}async blobToDataUrl(e){return new Promise((t,i)=>{let n=new FileReader;n.onload=()=>{let a=n.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),t(a)},n.onerror=a=>{console.error("FileReader error:",a),i(a)},n.readAsDataURL(e)})}inferAssetCategory(e){let t=e.toLowerCase();return t.includes("background")||t.includes("bg")?"backgrounds":t.includes("ui")||t.includes("button")||t.includes("cta")||t.includes("logo")||t.includes("text")?"ui":t.includes("sparkle")||t.includes("effect")||t.includes("particle")?"effects":t.includes("bottle")||t.includes("product")||t.includes("item")?"products":"misc"}addAssetsToRegistry(e){let t=window.getEditableAssets;if(typeof t!="function")return;let i=t();if(!(i!=null&&i.libraryAssets))return;let n={};for(let a of e){let s=a.category||"misc";n[s]||(n[s]=[]),i.libraryAssets[s]||(i.libraryAssets[s]=[]),i.libraryAssets[s].some(l=>l.filename===a.filename)||(i.libraryAssets[s].unshift({filename:a.filename,displayName:a.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${a.filename} to registry category ${s}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var s;let t=e.target,i=t.files;if(!i||i.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let n="";for(let o of Array.from(i))try{let l=await o.text(),c=JSON.parse(l);this.uploadedJsons.set(o.name,c),c.layers?n+=`\u2705 Layers: ${o.name}
1643
1643
  `:c.brand_dna||c.colors?n+=`\u2705 Brand: ${o.name}
1644
1644
  `:n+=`\u2705 Loaded: ${o.name}
1645
1645
  `}catch{n+=`\u274C Error in ${o.name}
@@ -1849,7 +1849,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
1849
1849
  </div>
1850
1850
  </div>
1851
1851
  </div>
1852
- `;let a=n.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),n.addEventListener("click",b=>{b.target===n&&this.closeAiModal()}),this.aiModal=n,this.aiKeyInput=n.querySelector("[data-ai-key]"),this.aiModelSelect=n.querySelector("[data-ai-model]"),this.aiPromptInput=n.querySelector("[data-ai-prompt]"),this.aiStrengthInput=n.querySelector("[data-ai-strength]"),this.aiStrengthValue=n.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=n.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=n.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=n.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=n.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=n.querySelector("[data-ai-ref-input]"),this.aiReferenceName=n.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=n.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=n.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=n.querySelector("[data-ai-generate]"),this.aiApplyBtn=n.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=n.querySelector("[data-ai-save-library]"),this.aiCropBtn=n.querySelector("[data-ai-crop]"),this.aiDownloadBtn=n.querySelector("[data-ai-download]"),this.aiPreviewImg=n.querySelector("[data-ai-preview]"),this.aiStatusEl=n.querySelector("[data-ai-status]"),this.aiLoadingEl=n.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=n.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=n.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=n.querySelector("[data-ai-ref-button]");s==null||s.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,w;let b=(w=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?w:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var y,w;let b=(w=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?w:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var y,w,v;let b=(v=(w=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:w[0])!=null?v: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(n),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,w,v,P,I,_,k,j,L,x,S,E;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",i=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",n=(w=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?w:!1,a=n,s=n,o=Number((P=(v=this.aiStrengthInput)==null?void 0:v.value)!=null?P:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!i){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 C=null,A=null,T=(k=this.getSelectedAssetKey())!=null?k:"unknown",O=(j=this.aiUseOutputToggle)!=null&&j.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((L=this.aiUseOutputToggle)!=null&&L.checked&&this.aiOutputDataUrl){let H=ma(this.aiOutputDataUrl,"ai-output.png");if(H){let $=await Ge(H);$&&(C={input:{base64:$.base64,mimeType:$.mimeType},dataUrl:$.dataUrl,width:$.width,height:$.height})}}!C&&c&&(C=await this.getImageDataFromAsset(c));let M=[];C&&M.push(C.input);let R=!1;if(this.aiReferenceFile){let H=await Ge(this.aiReferenceFile);H?(A={input:{base64:H.base64,mimeType:H.mimeType},dataUrl:H.dataUrl,width:H.width,height:H.height},M.push(A.input),R=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=xr(i,{includeReference:R,includeMagenta:a,changeLevel:o}),F=(S=(x=this.aiReferenceFile)==null?void 0:x.name)!=null?S:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:T,base:O,reference:F});let q=C?ba(C.width,C.height):A?ba(A.width,A.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let N=await yt(e,z,M,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",N==null?void 0:N.length),this.aiRawOutputDataUrl=N,await this.refreshAiOutputFromRaw()}catch(C){console.error("[CustomizePanel] AI Generate Error:",C),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((E=this.aiStatusEl)==null?void 0:E.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var n,a,s,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(n=this.aiRemoveBgToggle)==null?void 0:n.checked)!=null?a:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),i=this.aiRawOutputDataUrl;if(e){let l=await bt(this.aiRawOutputDataUrl,t);l&&(i=l)}this.setAiOutput(i),this.setAiStatus("Ready.")}setAiOutput(e){var i,n;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(i=this.previewModal)==null?void 0:i.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(n=this.activePreviewKey)!=null?n: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,i,n;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=((i=this.aiContext)==null?void 0:i.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((n=this.aiContext)==null?void 0:n.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,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,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let i=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,n=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:n,filename:`${i}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${i}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",n),d(n,`${i}.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=((s=this.aiContext)==null?void 0:s.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 w=this.getFilenameFromPath(c.path);await b(g,w,n)}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,n),setTimeout(()=>{m(g,n)},500)),this.setAiStatus(`\u2705 Saved and applied ${i}.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 s;let t=(s=this.aiContext)==null?void 0:s.objectId,i=e||this.aiTargetKey||"",n=window.getEditableAssets;if(typeof n=="function"){let o=n();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===i||c.slotId===i||c.currentAsset&&c.currentAsset.includes(i)||i.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=i.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 i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(a=>a.currentAsset===e||a.slotId===e);return(n==null?void 0:n.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!n)return null;let a=n.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:"",i=await this.getImageDimensions(t);if(!i){this.setAiStatus("Unable to read target dimensions.");return}let n=ma(this.aiOutputDataUrl,"ai-output.png");if(!n)return;let a=await this.showManualCropModal(n,i,t);if(!a)return;let s=await fa(a);s&&this.setAiOutput(s)}handleAiDownload(){var i;if(!this.aiOutputDataUrl)return;let e=(i=this.getSelectedAssetKey())!=null?i:"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,i){var u,g,h,f,m;console.log("[CustomizePanel] Handling asset upload for:",i);let n=t.value,a=e;if(e.type.startsWith("image/")){let b=await this.getImageDimensions(n);if(b){let y=await this.showManualCropModal(e,b,n);if(!y)return;a=y}}let s=await fa(a);if(!s){console.error("[CustomizePanel] Failed to convert file to data URL");return}let o=i.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),l=((u=e.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:u[1])||"png",c=l==="jpg"?"jpeg":l,d=`${o}_uploaded_${Date.now()}.${c}`,p=this.inferCategoryFromAssetKey(i);console.log("[CustomizePanel] Saving uploaded file to library:",d,"category:",p);try{let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:p,filename:d,data:s,overwrite:!0})})).json();if(y.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",y.path),await new Promise(L=>setTimeout(L,100));let w=window.addAssetToRegistry;typeof w=="function"&&(w(p,d),console.log("[CustomizePanel] \u2705 Added to registry:",p,d));let v=window.getEditableAssets;if(typeof v=="function"){let L=v();L&&!L.categories&&(L.categories=[]),L!=null&&L.categories&&!L.categories.includes(p)&&(L.categories.push(p),console.log(`[CustomizePanel] Added category ${p} to registry`))}let P=!1,I=0,_=10;for(;!P&&I<_;){I++,console.log(`[CustomizePanel] Refresh attempt ${I}/${_}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[CustomizePanel] \u2705 Registry rebuilt from disk")}catch(E){console.warn("[CustomizePanel] Setup-library not available:",E)}await new Promise(E=>setTimeout(E,300));let L=window.refreshAssetLibrary;typeof L=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await L());let x=window.reRenderAssetLibrary;typeof x=="function"&&(console.log("[CustomizePanel] Re-rendering library panel..."),x());let S=window.getEditableAssets;if(typeof S=="function"){let E=S(),C=((g=E==null?void 0:E.libraryAssets)==null?void 0:g[p])||[];C.some(T=>(T==null?void 0:T.filename)===d)?(console.log("[CustomizePanel] \u2705 Asset found in registry!"),P=!0):(console.log(`[CustomizePanel] Asset not found yet, retrying... (found ${C.length} assets in ${p})`),await new Promise(T=>setTimeout(T,500)))}else I>=2&&(P=!0)}P||console.warn("[CustomizePanel] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway..."),t.value=y.path,this.handleAssetValueChange(i,t);let k=this.inferObjectIdFromAssetKey(i),j=this.inferPathFromAssetKey(i);if(k&&j){let L=!1,x=0,S=5;for(;!L&&x<S;){x++;try{console.log(`[CustomizePanel] Applying asset attempt ${x}/${S}...`);let C=window.applyAssetToSlot,A=/texture|image|sprite|asset\\.path/i.test(j)||/\\.(png|jpg|jpeg)$/i.test(String(y.path||""));if(typeof C=="function"&&A){let O=this.getFilenameFromPath(y.path);await C(k,O,p)}else this.applyObjectPropertyValue(k,j,y.path);await new Promise(O=>setTimeout(O,200));let T=window.getEditableObjectConfig;if(typeof T=="function"){let O=T(k),M=((f=(h=O==null?void 0:O.render)==null?void 0:h.asset)==null?void 0:f.path)||((m=O==null?void 0:O.ui)==null?void 0:m.image)||"";M===y.path||M.includes(d)?(console.log("[CustomizePanel] \u2705 Asset confirmed applied to object"),L=!0):(console.log(`[CustomizePanel] Asset not applied yet (attempt ${x}), retrying...`),await new Promise(R=>setTimeout(R,300)))}else L=!0}catch(C){console.error(`[CustomizePanel] Apply attempt ${x} failed:`,C),x<S&&await new Promise(A=>setTimeout(A,500))}}window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:k,action:"update",path:j}})),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[CustomizePanel] Dispatched config:changed event")}catch(C){console.warn("[CustomizePanel] Failed to refresh textures:",C)}},300);let E=window.__highlightLibrarySlot;typeof E=="function"&&k&&setTimeout(()=>{E(k,p)},1e3),L?console.log("[CustomizePanel] \u2705 Upload complete and applied!"):console.warn("[CustomizePanel] \u26A0\uFE0F Upload succeeded but apply may have failed")}else console.log("[CustomizePanel] \u2705 Upload complete (no object context to apply)")}else console.error("[CustomizePanel] \u274C Upload save failed:",y.error),alert(`Failed to save uploaded file: ${y.error}`)}catch(b){console.error("[CustomizePanel] \u274C Upload error:",b),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,i,n){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let s=i||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=n!=null?n:null,this.openPreviewModal(e,t,a,s)}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 i=t.replace(/^\.?\//,""),n=[];return i.startsWith("raw/")?n=[`/${i}`,`/assets/${i}`]:i.startsWith("assets/")?n=[`/${i}`]:n=[`/raw/${i}`,`/assets/raw/${i}`,`/assets/${i}`,`/${i}`],console.log("[CustomizePanel] Resolved to possible paths:",n),n}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,i,n){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1852
+ `;let a=n.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),n.addEventListener("click",b=>{b.target===n&&this.closeAiModal()}),this.aiModal=n,this.aiKeyInput=n.querySelector("[data-ai-key]"),this.aiModelSelect=n.querySelector("[data-ai-model]"),this.aiPromptInput=n.querySelector("[data-ai-prompt]"),this.aiStrengthInput=n.querySelector("[data-ai-strength]"),this.aiStrengthValue=n.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=n.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=n.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=n.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=n.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=n.querySelector("[data-ai-ref-input]"),this.aiReferenceName=n.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=n.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=n.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=n.querySelector("[data-ai-generate]"),this.aiApplyBtn=n.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=n.querySelector("[data-ai-save-library]"),this.aiCropBtn=n.querySelector("[data-ai-crop]"),this.aiDownloadBtn=n.querySelector("[data-ai-download]"),this.aiPreviewImg=n.querySelector("[data-ai-preview]"),this.aiStatusEl=n.querySelector("[data-ai-status]"),this.aiLoadingEl=n.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=n.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=n.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=n.querySelector("[data-ai-ref-button]");s==null||s.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,w;let b=(w=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?w:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var y,w;let b=(w=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?w:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var y,w,v;let b=(v=(w=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:w[0])!=null?v: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(n),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,w,v,j,T,O,M,_,C,x,S,E;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",i=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",n=(w=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?w:!1,a=n,s=n,o=Number((j=(v=this.aiStrengthInput)==null?void 0:v.value)!=null?j:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!i){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((T=l==null?void 0:l.value)==null?void 0:T.trim())||((O=this.aiBaseValue)==null?void 0:O.trim())||"";this.setAiLoading(!0),this.setAiStatus(c?"Generating...":"Generating from scratch...");try{let I=null,L=null,A=(M=this.getSelectedAssetKey())!=null?M:"unknown",P=(_=this.aiUseOutputToggle)!=null&&_.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((C=this.aiUseOutputToggle)!=null&&C.checked&&this.aiOutputDataUrl){let H=ma(this.aiOutputDataUrl,"ai-output.png");if(H){let $=await Ge(H);$&&(I={input:{base64:$.base64,mimeType:$.mimeType},dataUrl:$.dataUrl,width:$.width,height:$.height})}}!I&&c&&(I=await this.getImageDataFromAsset(c));let k=[];I&&k.push(I.input);let R=!1;if(this.aiReferenceFile){let H=await Ge(this.aiReferenceFile);H?(L={input:{base64:H.base64,mimeType:H.mimeType},dataUrl:H.dataUrl,width:H.width,height:H.height},k.push(L.input),R=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=xr(i,{includeReference:R,includeMagenta:a,changeLevel:o}),F=(S=(x=this.aiReferenceFile)==null?void 0:x.name)!=null?S:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:A,base:P,reference:F});let q=I?ba(I.width,I.height):L?ba(L.width,L.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let N=await yt(e,z,k,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",N==null?void 0:N.length),this.aiRawOutputDataUrl=N,await this.refreshAiOutputFromRaw()}catch(I){console.error("[CustomizePanel] AI Generate Error:",I),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((E=this.aiStatusEl)==null?void 0:E.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var n,a,s,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(n=this.aiRemoveBgToggle)==null?void 0:n.checked)!=null?a:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),i=this.aiRawOutputDataUrl;if(e){let l=await bt(this.aiRawOutputDataUrl,t);l&&(i=l)}this.setAiOutput(i),this.setAiStatus("Ready.")}setAiOutput(e){var i,n;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(i=this.previewModal)==null?void 0:i.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(n=this.activePreviewKey)!=null?n: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,i,n;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=((i=this.aiContext)==null?void 0:i.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((n=this.aiContext)==null?void 0:n.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,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,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let i=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,n=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:n,filename:`${i}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${i}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",n),d(n,`${i}.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=((s=this.aiContext)==null?void 0:s.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 w=this.getFilenameFromPath(c.path);await b(g,w,n)}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,n),setTimeout(()=>{m(g,n)},500)),this.setAiStatus(`\u2705 Saved and applied ${i}.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 s;let t=(s=this.aiContext)==null?void 0:s.objectId,i=e||this.aiTargetKey||"",n=window.getEditableAssets;if(typeof n=="function"){let o=n();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===i||c.slotId===i||c.currentAsset&&c.currentAsset.includes(i)||i.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=i.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 i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(a=>a.currentAsset===e||a.slotId===e);return(n==null?void 0:n.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!n)return null;let a=n.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:"",i=await this.getImageDimensions(t);if(!i){this.setAiStatus("Unable to read target dimensions.");return}let n=ma(this.aiOutputDataUrl,"ai-output.png");if(!n)return;let a=await this.showManualCropModal(n,i,t);if(!a)return;let s=await fa(a);s&&this.setAiOutput(s)}handleAiDownload(){var i;if(!this.aiOutputDataUrl)return;let e=(i=this.getSelectedAssetKey())!=null?i:"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,i){var u,g,h,f,m;console.log("[CustomizePanel] Handling asset upload for:",i);let n=t.value,a=e;if(e.type.startsWith("image/")){let b=await this.getImageDimensions(n);if(b){let y=await this.showManualCropModal(e,b,n);if(!y)return;a=y}}let s=await fa(a);if(!s){console.error("[CustomizePanel] Failed to convert file to data URL");return}let o=i.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),l=((u=e.name.toLowerCase().match(/\.(png|jpg|jpeg|gif|webp)$/))==null?void 0:u[1])||"png",c=l==="jpg"?"jpeg":l,d=`${o}_uploaded_${Date.now()}.${c}`,p=this.inferCategoryFromAssetKey(i);console.log("[CustomizePanel] Saving uploaded file to library:",d,"category:",p);try{let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:p,filename:d,data:s,overwrite:!0})})).json();if(y.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",y.path),await new Promise(C=>setTimeout(C,100));let w=window.addAssetToRegistry;typeof w=="function"&&(w(p,d),console.log("[CustomizePanel] \u2705 Added to registry:",p,d));let v=window.getEditableAssets;if(typeof v=="function"){let C=v();C&&!C.categories&&(C.categories=[]),C!=null&&C.categories&&!C.categories.includes(p)&&(C.categories.push(p),console.log(`[CustomizePanel] Added category ${p} to registry`))}let j=!1,T=0,O=10;for(;!j&&T<O;){T++,console.log(`[CustomizePanel] Refresh attempt ${T}/${O}...`);try{(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok&&console.log("[CustomizePanel] \u2705 Registry rebuilt from disk")}catch(E){console.warn("[CustomizePanel] Setup-library not available:",E)}await new Promise(E=>setTimeout(E,300));let C=window.refreshAssetLibrary;typeof C=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await C());let x=window.reRenderAssetLibrary;typeof x=="function"&&(console.log("[CustomizePanel] Re-rendering library panel..."),x());let S=window.getEditableAssets;if(typeof S=="function"){let E=S(),I=((g=E==null?void 0:E.libraryAssets)==null?void 0:g[p])||[];I.some(A=>(A==null?void 0:A.filename)===d)?(console.log("[CustomizePanel] \u2705 Asset found in registry!"),j=!0):(console.log(`[CustomizePanel] Asset not found yet, retrying... (found ${I.length} assets in ${p})`),await new Promise(A=>setTimeout(A,500)))}else T>=2&&(j=!0)}j||console.warn("[CustomizePanel] \u26A0\uFE0F Asset not found in registry after retries, proceeding anyway..."),t.value=y.path,this.handleAssetValueChange(i,t);let M=this.inferObjectIdFromAssetKey(i),_=this.inferPathFromAssetKey(i);if(M&&_){let C=!1,x=0,S=5;for(;!C&&x<S;){x++;try{console.log(`[CustomizePanel] Applying asset attempt ${x}/${S}...`);let I=window.applyAssetToSlot,L=/texture|image|sprite|asset\\.path/i.test(_)||/\\.(png|jpg|jpeg)$/i.test(String(y.path||""));if(typeof I=="function"&&L){let P=this.getFilenameFromPath(y.path);await I(M,P,p)}else this.applyObjectPropertyValue(M,_,y.path);await new Promise(P=>setTimeout(P,200));let A=window.getEditableObjectConfig;if(typeof A=="function"){let P=A(M),k=((f=(h=P==null?void 0:P.render)==null?void 0:h.asset)==null?void 0:f.path)||((m=P==null?void 0:P.ui)==null?void 0:m.image)||"";k===y.path||k.includes(d)?(console.log("[CustomizePanel] \u2705 Asset confirmed applied to object"),C=!0):(console.log(`[CustomizePanel] Asset not applied yet (attempt ${x}), retrying...`),await new Promise(R=>setTimeout(R,300)))}else C=!0}catch(I){console.error(`[CustomizePanel] Apply attempt ${x} failed:`,I),x<S&&await new Promise(L=>setTimeout(L,500))}}window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectId:M,action:"update",path:_}})),setTimeout(()=>{try{window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),console.log("[CustomizePanel] Dispatched config:changed event")}catch(I){console.warn("[CustomizePanel] Failed to refresh textures:",I)}},300);let E=window.__highlightLibrarySlot;typeof E=="function"&&M&&setTimeout(()=>{E(M,p)},1e3),C?console.log("[CustomizePanel] \u2705 Upload complete and applied!"):console.warn("[CustomizePanel] \u26A0\uFE0F Upload succeeded but apply may have failed")}else console.log("[CustomizePanel] \u2705 Upload complete (no object context to apply)")}else console.error("[CustomizePanel] \u274C Upload save failed:",y.error),alert(`Failed to save uploaded file: ${y.error}`)}catch(b){console.error("[CustomizePanel] \u274C Upload error:",b),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,i,n){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let s=i||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=n!=null?n:null,this.openPreviewModal(e,t,a,s)}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 i=t.replace(/^\.?\//,""),n=[];return i.startsWith("raw/")?n=[`/${i}`,`/assets/${i}`]:i.startsWith("assets/")?n=[`/${i}`]:n=[`/raw/${i}`,`/assets/raw/${i}`,`/assets/${i}`,`/${i}`],console.log("[CustomizePanel] Resolved to possible paths:",n),n}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,i,n){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1853
1853
  <div class="asset-preview-card">
1854
1854
  <div class="asset-preview-header">
1855
1855
  <div class="asset-preview-title">${e}</div>
@@ -1895,7 +1895,7 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
1895
1895
  <button class="asset-crop-apply" type="button">Apply Crop</button>
1896
1896
  </div>
1897
1897
  </div>
1898
- `;let y=c.querySelector(".asset-crop-canvas"),w=c.querySelector(".asset-crop-preview"),v=c.querySelector(".asset-crop-zoom"),P=c.querySelector(".asset-crop-zoom-value"),I=c.querySelector(".asset-crop-close"),_=c.querySelector(".asset-crop-cancel"),k=c.querySelector(".asset-crop-apply"),j=c.querySelector(".asset-crop-reset");if(!y||!w||!v||!P){l(null);return}let L=y.getContext("2d"),x=w.getContext("2d");if(!L||!x){l(null);return}let S=s.naturalWidth,E=s.naturalHeight,C=Math.max(y.width/S,y.height/E),A=1,T=0,O=0,M=!1,R=0,z=0,F=0,q=0,N=()=>{let G=C*A,te=Math.max(0,(S*G-y.width)/2),W=Math.max(0,(E*G-y.height)/2);T=Math.min(te,Math.max(-te,T)),O=Math.min(W,Math.max(-W,O))},H=()=>{if(!s||!s.complete||s.naturalWidth===0||s.naturalHeight===0){console.warn("[CustomizePanel] Image not ready for drawing"),L.fillStyle="rgba(128, 128, 128, 0.3)",L.fillRect(0,0,y.width,y.height),L.fillStyle="rgba(255, 255, 255, 0.5)",L.font="14px sans-serif",L.textAlign="center",L.fillText("Loading image...",y.width/2,y.height/2);return}let G=C*A;L.clearRect(0,0,y.width,y.height);let te=y.width/2-S*G/2+T,W=y.height/2-E*G/2+O;try{L.drawImage(s,te,W,S*G,E*G)}catch(ve){console.error("[CustomizePanel] Error drawing image:",ve),L.fillStyle="rgba(255, 0, 0, 0.3)",L.fillRect(0,0,y.width,y.height),L.fillStyle="#ff0000",L.font="14px sans-serif",L.textAlign="center",L.fillText("Error drawing image",y.width/2,y.height/2)}if(x.clearRect(0,0,w.width,w.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let ve=Math.max(w.width/o.naturalWidth,w.height/o.naturalHeight),jt=w.width/2-o.naturalWidth*ve/2,Ye=w.height/2-o.naturalHeight*ve/2;x.drawImage(o,jt,Ye,o.naturalWidth*ve,o.naturalHeight*ve)}else x.fillStyle="rgba(255, 255, 255, 0.04)",x.fillRect(0,0,w.width,w.height),x.strokeStyle="rgba(255, 255, 255, 0.08)",x.strokeRect(4,4,w.width-8,w.height-8);let J=w.width/y.width*(C*A),Q=T*(w.width/y.width),fe=O*(w.height/y.height),se=w.width/2-S*J/2+Q,Mt=w.height/2-E*J/2+fe;x.save(),x.globalAlpha=.7,x.drawImage(s,se,Mt,S*J,E*J),x.restore()},$=()=>{T=0,O=0,N(),H()};v.addEventListener("input",()=>{A=Number(v.value),P.textContent=`${A.toFixed(2)}\xD7`,N(),H()}),y.addEventListener("pointerdown",G=>{M=!0,R=G.clientX,z=G.clientY,F=T,q=O,y.setPointerCapture(G.pointerId)}),y.addEventListener("pointermove",G=>{M&&(T=F+(G.clientX-R),O=q+(G.clientY-z),N(),H())}),y.addEventListener("pointerup",G=>{M=!1,y.releasePointerCapture(G.pointerId)}),y.addEventListener("pointerleave",()=>{M=!1});let U=()=>{c.remove();try{URL.revokeObjectURL(a)}catch{}},Y=()=>{U(),l(null)},V=async()=>{let G=document.createElement("canvas");G.width=t.width,G.height=t.height;let te=G.getContext("2d");if(!te){U(),l(null);return}let W=A,Q=Math.max(G.width/S,G.height/E)*W,fe=G.width/y.width,se=T*fe,Mt=O*fe,ve=G.width/2-S*Q/2+se,jt=G.height/2-E*Q/2+Mt;te.drawImage(s,ve,jt,S*Q,E*Q);let Ye=await new Promise(rt=>{G.toBlob(Tn=>rt(Tn),e.type||"image/png")});if(U(),!Ye){l(null);return}l(new File([Ye],e.name,{type:Ye.type}))};I==null||I.addEventListener("click",Y),_==null||_.addEventListener("click",Y),j==null||j.addEventListener("click",$),k==null||k.addEventListener("click",()=>{V()}),c.addEventListener("click",G=>{G.target===c&&Y()}),document.body.appendChild(c),s.complete&&s.naturalWidth>0&&s.naturalHeight>0?$():(s.onload=()=>{console.log("[CustomizePanel] Image fully loaded, drawing crop modal"),$()},s.onerror=()=>{console.error("[CustomizePanel] Image failed to load"),U(),l(null)})})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let i of t){let n=await this.loadImage(i);if(n)return n}return null}};var ln=class{constructor(){this.root=null;this.options=null}render(){return`
1898
+ `;let y=c.querySelector(".asset-crop-canvas"),w=c.querySelector(".asset-crop-preview"),v=c.querySelector(".asset-crop-zoom"),j=c.querySelector(".asset-crop-zoom-value"),T=c.querySelector(".asset-crop-close"),O=c.querySelector(".asset-crop-cancel"),M=c.querySelector(".asset-crop-apply"),_=c.querySelector(".asset-crop-reset");if(!y||!w||!v||!j){l(null);return}let C=y.getContext("2d"),x=w.getContext("2d");if(!C||!x){l(null);return}let S=s.naturalWidth,E=s.naturalHeight,I=Math.max(y.width/S,y.height/E),L=1,A=0,P=0,k=!1,R=0,z=0,F=0,q=0,N=()=>{let G=I*L,te=Math.max(0,(S*G-y.width)/2),W=Math.max(0,(E*G-y.height)/2);A=Math.min(te,Math.max(-te,A)),P=Math.min(W,Math.max(-W,P))},H=()=>{if(!s||!s.complete||s.naturalWidth===0||s.naturalHeight===0){console.warn("[CustomizePanel] Image not ready for drawing"),C.fillStyle="rgba(128, 128, 128, 0.3)",C.fillRect(0,0,y.width,y.height),C.fillStyle="rgba(255, 255, 255, 0.5)",C.font="14px sans-serif",C.textAlign="center",C.fillText("Loading image...",y.width/2,y.height/2);return}let G=I*L;C.clearRect(0,0,y.width,y.height);let te=y.width/2-S*G/2+A,W=y.height/2-E*G/2+P;try{C.drawImage(s,te,W,S*G,E*G)}catch(ve){console.error("[CustomizePanel] Error drawing image:",ve),C.fillStyle="rgba(255, 0, 0, 0.3)",C.fillRect(0,0,y.width,y.height),C.fillStyle="#ff0000",C.font="14px sans-serif",C.textAlign="center",C.fillText("Error drawing image",y.width/2,y.height/2)}if(x.clearRect(0,0,w.width,w.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let ve=Math.max(w.width/o.naturalWidth,w.height/o.naturalHeight),jt=w.width/2-o.naturalWidth*ve/2,Ye=w.height/2-o.naturalHeight*ve/2;x.drawImage(o,jt,Ye,o.naturalWidth*ve,o.naturalHeight*ve)}else x.fillStyle="rgba(255, 255, 255, 0.04)",x.fillRect(0,0,w.width,w.height),x.strokeStyle="rgba(255, 255, 255, 0.08)",x.strokeRect(4,4,w.width-8,w.height-8);let J=w.width/y.width*(I*L),Q=A*(w.width/y.width),fe=P*(w.height/y.height),se=w.width/2-S*J/2+Q,Mt=w.height/2-E*J/2+fe;x.save(),x.globalAlpha=.7,x.drawImage(s,se,Mt,S*J,E*J),x.restore()},$=()=>{A=0,P=0,N(),H()};v.addEventListener("input",()=>{L=Number(v.value),j.textContent=`${L.toFixed(2)}\xD7`,N(),H()}),y.addEventListener("pointerdown",G=>{k=!0,R=G.clientX,z=G.clientY,F=A,q=P,y.setPointerCapture(G.pointerId)}),y.addEventListener("pointermove",G=>{k&&(A=F+(G.clientX-R),P=q+(G.clientY-z),N(),H())}),y.addEventListener("pointerup",G=>{k=!1,y.releasePointerCapture(G.pointerId)}),y.addEventListener("pointerleave",()=>{k=!1});let U=()=>{c.remove();try{URL.revokeObjectURL(a)}catch{}},Y=()=>{U(),l(null)},V=async()=>{let G=document.createElement("canvas");G.width=t.width,G.height=t.height;let te=G.getContext("2d");if(!te){U(),l(null);return}let W=L,Q=Math.max(G.width/S,G.height/E)*W,fe=G.width/y.width,se=A*fe,Mt=P*fe,ve=G.width/2-S*Q/2+se,jt=G.height/2-E*Q/2+Mt;te.drawImage(s,ve,jt,S*Q,E*Q);let Ye=await new Promise(rt=>{G.toBlob(Tn=>rt(Tn),e.type||"image/png")});if(U(),!Ye){l(null);return}l(new File([Ye],e.name,{type:Ye.type}))};T==null||T.addEventListener("click",Y),O==null||O.addEventListener("click",Y),_==null||_.addEventListener("click",$),M==null||M.addEventListener("click",()=>{V()}),c.addEventListener("click",G=>{G.target===c&&Y()}),document.body.appendChild(c),s.complete&&s.naturalWidth>0&&s.naturalHeight>0?$():(s.onload=()=>{console.log("[CustomizePanel] Image fully loaded, drawing crop modal"),$()},s.onerror=()=>{console.error("[CustomizePanel] Image failed to load"),U(),l(null)})})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let i of t){let n=await this.loadImage(i);if(n)return n}return null}};var ln=class{constructor(){this.root=null;this.options=null}render(){return`
1899
1899
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
1900
1900
  <div class="scene-panel-header" data-panel-handle>
1901
1901
  <div class="panel-title">
@@ -1961,10 +1961,10 @@ Generate the requested asset matching the brand style.${r.needsTransparency?" Ba
1961
1961
  </div>
1962
1962
  </div>
1963
1963
  </div>
1964
- `}initialize(e,t){var y,w,v,P,I,_,k,j,L,x,S,E,C,A,T,O;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let n=(()=>{var R;let M=window.getEditableEngineConfig;if(typeof M=="function"){let z=M();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=n.type==="image"?"image":"color",a.addEventListener("change",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(w=this.root)==null?void 0:w.querySelector("#loading-background-color");s&&(s.value=n.background_color||"#160a17",s.addEventListener("input",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{background_color:s.value})}));let o=(v=this.root)==null?void 0:v.querySelector("#loading-overlay-alpha"),l=(P=this.root)==null?void 0:P.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((I=n.overlay_alpha)!=null?I:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var R,z;let M=Number(o.value);l&&(l.textContent=M.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{overlay_alpha:M})}));let c=(_=this.root)==null?void 0:_.querySelector("#loading-text");c&&(c.value=n.text||"",c.addEventListener("input",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{text:c.value})}));let d=(k=this.root)==null?void 0:k.querySelector("#loading-text-scale"),p=(j=this.root)==null?void 0:j.querySelector("#loading-text-scale-value");d&&(d.value=String((L=n.text_scale)!=null?L:.6),p&&(p.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var R,z;let M=Number(d.value);p&&(p.textContent=M.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{text_scale:M})}));let u=(x=this.root)==null?void 0:x.querySelector("#loading-enabled");u&&(u.checked=n.enabled!==!1,u.addEventListener("change",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{enabled:u.checked})}));let g=(S=this.root)==null?void 0:S.querySelector("#loading-blur-enabled");g&&(g.checked=n.blur_enabled!==!1,g.addEventListener("change",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{blur_enabled:g.checked})}));let h=(E=this.root)==null?void 0:E.querySelector("#loading-blur-strength"),f=(C=this.root)==null?void 0:C.querySelector("#loading-blur-strength-value");h&&(h.value=String((A=n.blur_strength)!=null?A:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var M,R;f&&(f.textContent=h.value),(R=(M=this.options)==null?void 0:M.onUpdateLoading)==null||R.call(M,{blur_strength:Number(h.value)})}));let m=(T=this.root)==null?void 0:T.querySelector("#loading-show-btn"),b=(O=this.root)==null?void 0:O.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onShowLoadingScreen)==null||R.call(M)}),b==null||b.addEventListener("click",()=>{var M,R;(R=(M=this.options)==null?void 0:M.onHideLoadingScreen)==null||R.call(M)}),this.updateFieldVisibility(n.type==="image"?"image":"color")}updateFieldVisibility(e){var n,a;let t=(n=this.root)==null?void 0:n.querySelector("#loading-color-field"),i=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),i&&(i.style.display="none")):(t&&(t.style.display=""),i&&(i.style.display=""))}refresh(){}};var Kt=require("pixi.js");var wa=require("pixi.js"),Ue=()=>window.debugConfig||{},Er=()=>window.resolveAnchorVec2||(r=>({x:.5,y:.5})),Cr=()=>window.resolveScreenAnchorPoint||(()=>new wa.Point),Ar=()=>window.resolveScreenRatioPoint||(()=>new wa.Point);function Lr(r){cn(r)&&(r.objectDebugRaf||(r.objectDebugRaf=window.requestAnimationFrame(()=>dn(r))))}function Tr(r){r.objectDebugRaf&&(window.cancelAnimationFrame(r.objectDebugRaf),r.objectDebugRaf=null),Wt(r)}function cn(r){return r.isDebugOpen}function dn(r){var a,s,o;if(!cn(r)){r.objectDebugRaf=null;return}r.objectDebugRaf=window.requestAnimationFrame(()=>dn(r));let e=xa(r);if(!e){Yt(r,null),Wt(r);return}let t=Sa(r,e);if(!t){Yt(r,null),Wt(r);return}let i=new Kt.Point;(a=t.getGlobalPosition)==null||a.call(t,i);let n=Ea(r,t);Yt(r,{instanceId:e,worldX:i.x,worldY:i.y,configX:(s=n==null?void 0:n.x)!=null?s:null,configY:(o=n==null?void 0:n.y)!=null?o:null}),r.highlightObject?Ta(r,t):ka(r),r.highlightAnchor&&n?Ia(r,n):Pa(r)}function xa(r){var n;let e=r.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return Array.isArray(i)&&i.length>0?i[0]:e}function Sa(r,e){var n,a;let t=window.gameObjectManager,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return i?((a=i.getDisplayObject)==null?void 0:a.call(i))||i.pixiObject||i:null}function Xt(r){let e=r.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Ea(r,e){var s,o;let t=Xt(r);if(!t)return null;let i=(s=t.transform)!=null?s:{},n=Ca(r);if(!n)return null;if(i.position_ratio!=null)return Ar()(n.width,n.height,i.position_ratio);let a=(o=i.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&i.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),Cr()(n.width,n.height,a)}function Ca(r){var a;let e=(a=r.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),i=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0)return{width:t,height:i};let n=window.gameApp;return n!=null&&n.renderer?{width:n.renderer.width,height:n.renderer.height}:null}function Aa(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectBoundsGfx&&r.objectBoundsGfx.parent!==e.stage&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectBoundsGfx||(r.objectBoundsGfx=new Kt.Graphics,r.objectBoundsGfx.zIndex=999999,e.stage.addChild(r.objectBoundsGfx)),r.objectBoundsGfx):null}function La(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectAnchorGfx&&r.objectAnchorGfx.parent!==e.stage&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null),r.objectAnchorGfx||(r.objectAnchorGfx=new Kt.Graphics,r.objectAnchorGfx.zIndex=1e6,e.stage.addChild(r.objectAnchorGfx)),r.objectAnchorGfx):null}function Ta(r,e){var n;let t=Aa(r);if(!t)return;let i=(n=e.getBounds)==null?void 0:n.call(e);i&&(t.clear(),t.rect(i.x,i.y,i.width,i.height).stroke({width:2,color:16726832,alpha:.9}))}function Ia(r,e){let t=La(r);if(!t)return;let i=6;t.clear(),t.moveTo(e.x-i,e.y),t.lineTo(e.x+i,e.y),t.moveTo(e.x,e.y-i),t.lineTo(e.x,e.y+i),t.stroke({width:2,color:3066993,alpha:.9})}function ka(r){r.objectBoundsGfx&&r.objectBoundsGfx.clear()}function Pa(r){r.objectAnchorGfx&&r.objectAnchorGfx.clear()}function Wt(r){r.objectBoundsGfx&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectAnchorGfx&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null)}function Yt(r,e){r.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Ir(r,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,r)}function kr(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i)a[o]=(s=a[o])!=null?s:{},a=a[o];a[n]=t}function Ma(r){var i,n,a,s,o;if(!r)return!1;if((i=r.transform)!=null&&i.offset)return!0;let e=((a=(n=r.identity)==null?void 0:n.category)!=null?a:"").toString().toLowerCase(),t=((o=(s=r.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function un(r){let e=Ue();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 Pr(r){window.location.reload()}function gn(r){let e=JSON.stringify(Ue(),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 Mr(r,e){var t,i,n;if(!(!r.configViewer||!r.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(e):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(Mi(),Xs)),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),pn(r,u),(i=r.configViewer)==null||i.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),pn(r,s),(n=r.configViewer)==null||n.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function pn(r,e){var u,g,h,f,m,b,y,w,v,P;if(!r.container)return;let t=r.container.querySelector("#config-pos-x"),i=r.container.querySelector("#config-pos-y"),n=r.container.querySelector("#config-scale"),a=r.container.querySelector("#config-anchor-preset"),s=r.container.querySelector("#config-anchor-x"),o=r.container.querySelector("#config-anchor-y"),c=Ma(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)),i&&(i.value=String((f=c==null?void 0:c.y)!=null?f:0)),n&&(n.value=String((b=(m=e.transform)==null?void 0:m.scale)!=null?b:1));let d=(P=(v=(y=e.transform)==null?void 0:y.anchor)!=null?v:(w=e.render)==null?void 0:w.anchor)!=null?P:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let I=r.container.querySelectorAll(".anchor-custom-field"),_=a.value==="custom";I.forEach(k=>k.style.display=_?"block":"none")}let p=Er()(d);s&&(s.value=String(p.x)),o&&(o.value=String(p.y))}function jr(r){var l,c,d,p,u,g,h,f,m,b;let e=r.selectedObjectId;if(!e||!r.container)return;let t=(c=(l=r.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",i=(p=(d=r.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",n=(g=(u=r.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(f=(h=r.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",s=(b=(m=r.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
1964
+ `}initialize(e,t){var y,w,v,j,T,O,M,_,C,x,S,E,I,L,A,P;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let n=(()=>{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=n.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 s=(w=this.root)==null?void 0:w.querySelector("#loading-background-color");s&&(s.value=n.background_color||"#160a17",s.addEventListener("input",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{background_color:s.value})}));let o=(v=this.root)==null?void 0:v.querySelector("#loading-overlay-alpha"),l=(j=this.root)==null?void 0:j.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((T=n.overlay_alpha)!=null?T: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=(O=this.root)==null?void 0:O.querySelector("#loading-text");c&&(c.value=n.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=(M=this.root)==null?void 0:M.querySelector("#loading-text-scale"),p=(_=this.root)==null?void 0:_.querySelector("#loading-text-scale-value");d&&(d.value=String((C=n.text_scale)!=null?C:.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=(x=this.root)==null?void 0:x.querySelector("#loading-enabled");u&&(u.checked=n.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=(S=this.root)==null?void 0:S.querySelector("#loading-blur-enabled");g&&(g.checked=n.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=(E=this.root)==null?void 0:E.querySelector("#loading-blur-strength"),f=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength-value");h&&(h.value=String((L=n.blur_strength)!=null?L: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=(A=this.root)==null?void 0:A.querySelector("#loading-show-btn"),b=(P=this.root)==null?void 0:P.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(n.type==="image"?"image":"color")}updateFieldVisibility(e){var n,a;let t=(n=this.root)==null?void 0:n.querySelector("#loading-color-field"),i=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),i&&(i.style.display="none")):(t&&(t.style.display=""),i&&(i.style.display=""))}refresh(){}};var Kt=require("pixi.js");var wa=require("pixi.js"),Ue=()=>window.debugConfig||{},Er=()=>window.resolveAnchorVec2||(r=>({x:.5,y:.5})),Cr=()=>window.resolveScreenAnchorPoint||(()=>new wa.Point),Ar=()=>window.resolveScreenRatioPoint||(()=>new wa.Point);function Lr(r){cn(r)&&(r.objectDebugRaf||(r.objectDebugRaf=window.requestAnimationFrame(()=>dn(r))))}function Tr(r){r.objectDebugRaf&&(window.cancelAnimationFrame(r.objectDebugRaf),r.objectDebugRaf=null),Wt(r)}function cn(r){return r.isDebugOpen}function dn(r){var a,s,o;if(!cn(r)){r.objectDebugRaf=null;return}r.objectDebugRaf=window.requestAnimationFrame(()=>dn(r));let e=xa(r);if(!e){Yt(r,null),Wt(r);return}let t=Sa(r,e);if(!t){Yt(r,null),Wt(r);return}let i=new Kt.Point;(a=t.getGlobalPosition)==null||a.call(t,i);let n=Ea(r,t);Yt(r,{instanceId:e,worldX:i.x,worldY:i.y,configX:(s=n==null?void 0:n.x)!=null?s:null,configY:(o=n==null?void 0:n.y)!=null?o:null}),r.highlightObject?Ta(r,t):ka(r),r.highlightAnchor&&n?Ia(r,n):Pa(r)}function xa(r){var n;let e=r.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return Array.isArray(i)&&i.length>0?i[0]:e}function Sa(r,e){var n,a;let t=window.gameObjectManager,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return i?((a=i.getDisplayObject)==null?void 0:a.call(i))||i.pixiObject||i:null}function Xt(r){let e=r.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Ea(r,e){var s,o;let t=Xt(r);if(!t)return null;let i=(s=t.transform)!=null?s:{},n=Ca(r);if(!n)return null;if(i.position_ratio!=null)return Ar()(n.width,n.height,i.position_ratio);let a=(o=i.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&i.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),Cr()(n.width,n.height,a)}function Ca(r){var a;let e=(a=r.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),i=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0)return{width:t,height:i};let n=window.gameApp;return n!=null&&n.renderer?{width:n.renderer.width,height:n.renderer.height}:null}function Aa(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectBoundsGfx&&r.objectBoundsGfx.parent!==e.stage&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectBoundsGfx||(r.objectBoundsGfx=new Kt.Graphics,r.objectBoundsGfx.zIndex=999999,e.stage.addChild(r.objectBoundsGfx)),r.objectBoundsGfx):null}function La(r){let e=window.gameApp;return e!=null&&e.stage?(r.objectAnchorGfx&&r.objectAnchorGfx.parent!==e.stage&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null),r.objectAnchorGfx||(r.objectAnchorGfx=new Kt.Graphics,r.objectAnchorGfx.zIndex=1e6,e.stage.addChild(r.objectAnchorGfx)),r.objectAnchorGfx):null}function Ta(r,e){var n;let t=Aa(r);if(!t)return;let i=(n=e.getBounds)==null?void 0:n.call(e);i&&(t.clear(),t.rect(i.x,i.y,i.width,i.height).stroke({width:2,color:16726832,alpha:.9}))}function Ia(r,e){let t=La(r);if(!t)return;let i=6;t.clear(),t.moveTo(e.x-i,e.y),t.lineTo(e.x+i,e.y),t.moveTo(e.x,e.y-i),t.lineTo(e.x,e.y+i),t.stroke({width:2,color:3066993,alpha:.9})}function ka(r){r.objectBoundsGfx&&r.objectBoundsGfx.clear()}function Pa(r){r.objectAnchorGfx&&r.objectAnchorGfx.clear()}function Wt(r){r.objectBoundsGfx&&(r.objectBoundsGfx.destroy(),r.objectBoundsGfx=null),r.objectAnchorGfx&&(r.objectAnchorGfx.destroy(),r.objectAnchorGfx=null)}function Yt(r,e){r.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Ir(r,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,r)}function kr(r,e,t){var s;let i=e.split("."),n=i.pop(),a=r;for(let o of i)a[o]=(s=a[o])!=null?s:{},a=a[o];a[n]=t}function Ma(r){var i,n,a,s,o;if(!r)return!1;if((i=r.transform)!=null&&i.offset)return!0;let e=((a=(n=r.identity)==null?void 0:n.category)!=null?a:"").toString().toLowerCase(),t=((o=(s=r.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function un(r){let e=Ue();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 Pr(r){window.location.reload()}function gn(r){let e=JSON.stringify(Ue(),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 Mr(r,e){var t,i,n;if(!(!r.configViewer||!r.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(e):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(Mi(),Xs)),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),pn(r,u),(i=r.configViewer)==null||i.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),pn(r,s),(n=r.configViewer)==null||n.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function pn(r,e){var u,g,h,f,m,b,y,w,v,j;if(!r.container)return;let t=r.container.querySelector("#config-pos-x"),i=r.container.querySelector("#config-pos-y"),n=r.container.querySelector("#config-scale"),a=r.container.querySelector("#config-anchor-preset"),s=r.container.querySelector("#config-anchor-x"),o=r.container.querySelector("#config-anchor-y"),c=Ma(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)),i&&(i.value=String((f=c==null?void 0:c.y)!=null?f:0)),n&&(n.value=String((b=(m=e.transform)==null?void 0:m.scale)!=null?b:1));let d=(j=(v=(y=e.transform)==null?void 0:y.anchor)!=null?v:(w=e.render)==null?void 0:w.anchor)!=null?j:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let T=r.container.querySelectorAll(".anchor-custom-field"),O=a.value==="custom";T.forEach(M=>M.style.display=O?"block":"none")}let p=Er()(d);s&&(s.value=String(p.x)),o&&(o.value=String(p.y))}function jr(r){var l,c,d,p,u,g,h,f,m,b;let e=r.selectedObjectId;if(!e||!r.container)return;let t=(c=(l=r.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",i=(p=(d=r.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",n=(g=(u=r.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(f=(h=r.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",s=(b=(m=r.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
1965
1965
  position: (${t}, ${i})
1966
1966
  scale: ${n}
1967
- anchor: (${a}, ${s})`;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 ja(r,e){var u,g,h,f,m,b,y,w,v,P,I,_;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!r.container)return;let t=r.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let i=Number((g=(u=r.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),n=Number((f=(h=r.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?f:0),a=Number((b=(m=r.container.querySelector("#config-scale"))==null?void 0:m.value)!=null?b:1),s=(w=(y=r.container.querySelector("#config-anchor-preset"))==null?void 0:y.value)!=null?w:"center",o=Number((P=(v=r.container.querySelector("#config-anchor-x"))==null?void 0:v.value)!=null?P:.5),l=Number((_=(I=r.container.querySelector("#config-anchor-y"))==null?void 0:I.value)!=null?_:.5),c=s==="custom"?{x:o,y:l}:s;console.log("[INSPECTOR] Applying config for:",t,{posX:i,posY:n,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(ae(),je));d({objectId:t,path:"transform.position",value:{x:i,y:n}},{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=Xt(r);Ma(p)&&d({objectId:t,path:"transform.offset",value:{x:i,y:n}},{silent:!0})}async function _r(r,e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(ae(),je));Object.entries(e.assets).forEach(([l,c])=>{i({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{i({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{i({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{i({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{i({path:`runtime.audio.${l}`,value:c},{silent:!0})});let n=window.applyEditableEngineConfig;if(typeof n=="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,n({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),s=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function Or(r){r.selectedObjectId&&(r.objectAutoApplyTimer&&window.clearTimeout(r.objectAutoApplyTimer),r.objectAutoApplyTimer=window.setTimeout(()=>{r.objectAutoApplyTimer=null,ja(r,{silent:!0})},150))}var xl=3e3;function nt(r,e,t){let i=t!=null?t:r.offsetParent;if(!i)return;e.style.cursor="move";let n=!1,a=0,s=0,o=0,l=0,c=0,d=0,p=g=>{if(!n)return;let h=i.getBoundingClientRect();r.style.left=`${g.clientX-h.left-c}px`,r.style.top=`${g.clientY-h.top-d}px`},u=()=>{n&&(n=!1,r.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=r.getBoundingClientRect(),m=i.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",i.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}),r.style.left=`${b}px`,r.style.top=`${y}px`,r.style.right="auto",r.style.bottom="auto",r.style.zIndex=String(++xl),n=!0,r.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function hn(r,e,t,i=280,n=200){e.style.cursor="nwse-resize";let a=0,s=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(i,a+g),m=Math.max(n,s+h);r.style.width=`${f}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.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=r.getBoundingClientRect();a=g.width,s=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function _a(r,e){var f,m,b,y;let t=(b=(m=(f=r.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:r.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=r.container)!=null&&y.classList.contains("layout-fixed"))return;let i=t.getBoundingClientRect(),n=e.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(i.width-a*2)),o=Math.max(200,Math.floor(i.height-a*2));n.width>s&&(e.style.width=`${s}px`),n.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-i.left,d=l.top-i.top,p=Math.max(a,i.width-l.width-a),u=Math.max(a,i.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 wt(r){var i,n;if(!r.container)return;let e=r.container.querySelector("#debug-workbench");if(!e)return;if(_a(r,e),(i=r.container)!=null&&i.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),s={activeTab:r.activeTab};if(a)try{s={...JSON.parse(a),activeTab:r.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(s));return}let t={activeTab:r.activeTab,width:e.style.width,height:(n=r.container)!=null&&n.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function fn(r){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(r.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var n,a;let i=(n=r.container)==null?void 0:n.querySelector("#debug-workbench");if(i){let s=(a=r.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(i.style.width=t.width),t.height&&!s?i.style.height=t.height:s&&(i.style.height=""),t.left&&(i.style.left=t.left,i.style.right="auto"),t.top&&(i.style.top=t.top,i.style.bottom="auto"),_a(r,i)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function Oa(r,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",_a(r,e),wt(r))}function Rr(r){var n,a,s;if(!r.container)return;let e=r.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=r.toggleDebug)==null||o.call(r)}),(n=e.querySelector("#debug-close"))==null||n.addEventListener("click",()=>{var o;return(o=r.toggleDebug)==null?void 0:o.call(r,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>un(r)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>gn(r)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;r.activeTab=l,Ra(r),wt(r)})}),$a(r,e),za(r,e)}function Ra(r){var n,a;if(!r.container)return;let e=r.container;e.querySelectorAll(".workbench-tab").forEach(s=>{let o=s.dataset.tab;s.classList.toggle("active",o===r.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(s=>{let o=s.dataset.tabPanel;s.classList.toggle("active",o===r.activeTab)}),r.activeTab==="library"&&r.libraryPanel&&((a=(n=r.libraryPanel).resetSearch)==null||a.call(n))}function za(r,e){be(r,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),be(r,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),be(r,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),be(r,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),be(r,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),be(r,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),be(r,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),be(r,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),be(r,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let n=Ue();n.layout&&(n.layout.debug_rect_visible=!!t.checked)});let i=e.querySelector("#debug-rect-color");i==null||i.addEventListener("input",()=>{let n=i.value.replace("#",""),a=parseInt(n,16),s=Ue();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function zr(r){if(!r.container||!r.debugOverlay)return;let e=r.container.querySelector("#debug-workbench"),t=r.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"),nt(e,t,r.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{wt(r),Oa(r,e)},10)}));let i=r.container.querySelector('[data-panel="scene-objects"]'),n=i==null?void 0:i.querySelector("[data-panel-handle]"),a=i==null?void 0:i.querySelector("[data-panel-resize-v]");i&&n&&(!i.style.left&&!i.style.right&&!i.style.top&&!i.style.bottom&&(i.style.left="16px",i.style.top="72px"),nt(i,n,r.debugOverlay),n.addEventListener("pointerup",()=>{setTimeout(()=>{Oa(r,i)},10)})),i&&a&&hn(i,a);let s=r.container.querySelector('[data-panel="scene-tools-corner"]'),o=s==null?void 0:s.querySelector("[data-panel-handle]");s&&o&&nt(s,o,r.debugOverlay);let l=r.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&nt(l,c,r.debugOverlay),fn(r)}function $a(r,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(i=>{i.addEventListener("click",()=>{let n=i.closest(".scene-panel");n&&n.classList.toggle("collapsed")})})}function be(r,e,t,i,n){let a=e.querySelector(`#${t}`),s=e.querySelector(n);if(!a||!s)return;let o=Ir(Ue(),i);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),kr(Ue(),i,l)})}ae();var mn=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=Fe(),{hasChanges:t,overrideCount:i,overrides:n}=e,a={};for(let d of n){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1967
+ anchor: (${a}, ${s})`;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 ja(r,e){var u,g,h,f,m,b,y,w,v,j,T,O;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!r.container)return;let t=r.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let i=Number((g=(u=r.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),n=Number((f=(h=r.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?f:0),a=Number((b=(m=r.container.querySelector("#config-scale"))==null?void 0:m.value)!=null?b:1),s=(w=(y=r.container.querySelector("#config-anchor-preset"))==null?void 0:y.value)!=null?w:"center",o=Number((j=(v=r.container.querySelector("#config-anchor-x"))==null?void 0:v.value)!=null?j:.5),l=Number((O=(T=r.container.querySelector("#config-anchor-y"))==null?void 0:T.value)!=null?O:.5),c=s==="custom"?{x:o,y:l}:s;console.log("[INSPECTOR] Applying config for:",t,{posX:i,posY:n,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(ae(),je));d({objectId:t,path:"transform.position",value:{x:i,y:n}},{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=Xt(r);Ma(p)&&d({objectId:t,path:"transform.offset",value:{x:i,y:n}},{silent:!0})}async function _r(r,e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(ae(),je));Object.entries(e.assets).forEach(([l,c])=>{i({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{i({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{i({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{i({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{i({path:`runtime.audio.${l}`,value:c},{silent:!0})});let n=window.applyEditableEngineConfig;if(typeof n=="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,n({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),s=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function Or(r){r.selectedObjectId&&(r.objectAutoApplyTimer&&window.clearTimeout(r.objectAutoApplyTimer),r.objectAutoApplyTimer=window.setTimeout(()=>{r.objectAutoApplyTimer=null,ja(r,{silent:!0})},150))}var xl=3e3;function nt(r,e,t){let i=t!=null?t:r.offsetParent;if(!i)return;e.style.cursor="move";let n=!1,a=0,s=0,o=0,l=0,c=0,d=0,p=g=>{if(!n)return;let h=i.getBoundingClientRect();r.style.left=`${g.clientX-h.left-c}px`,r.style.top=`${g.clientY-h.top-d}px`},u=()=>{n&&(n=!1,r.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=r.getBoundingClientRect(),m=i.getBoundingClientRect();console.log("[DRAG] Panel:",r.className),console.log("[DRAG] Container:",i.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}),r.style.left=`${b}px`,r.style.top=`${y}px`,r.style.right="auto",r.style.bottom="auto",r.style.zIndex=String(++xl),n=!0,r.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function hn(r,e,t,i=280,n=200){e.style.cursor="nwse-resize";let a=0,s=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(i,a+g),m=Math.max(n,s+h);r.style.width=`${f}px`,(y=r.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(r.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=r.getBoundingClientRect();a=g.width,s=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function _a(r,e){var f,m,b,y;let t=(b=(m=(f=r.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:r.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=r.container)!=null&&y.classList.contains("layout-fixed"))return;let i=t.getBoundingClientRect(),n=e.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(i.width-a*2)),o=Math.max(200,Math.floor(i.height-a*2));n.width>s&&(e.style.width=`${s}px`),n.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-i.left,d=l.top-i.top,p=Math.max(a,i.width-l.width-a),u=Math.max(a,i.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 wt(r){var i,n;if(!r.container)return;let e=r.container.querySelector("#debug-workbench");if(!e)return;if(_a(r,e),(i=r.container)!=null&&i.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),s={activeTab:r.activeTab};if(a)try{s={...JSON.parse(a),activeTab:r.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(s));return}let t={activeTab:r.activeTab,width:e.style.width,height:(n=r.container)!=null&&n.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function fn(r){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(r.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var n,a;let i=(n=r.container)==null?void 0:n.querySelector("#debug-workbench");if(i){let s=(a=r.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(i.style.width=t.width),t.height&&!s?i.style.height=t.height:s&&(i.style.height=""),t.left&&(i.style.left=t.left,i.style.right="auto"),t.top&&(i.style.top=t.top,i.style.bottom="auto"),_a(r,i)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function Oa(r,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",_a(r,e),wt(r))}function Rr(r){var n,a,s;if(!r.container)return;let e=r.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=r.toggleDebug)==null||o.call(r)}),(n=e.querySelector("#debug-close"))==null||n.addEventListener("click",()=>{var o;return(o=r.toggleDebug)==null?void 0:o.call(r,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>un(r)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>gn(r)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;r.activeTab=l,Ra(r),wt(r)})}),$a(r,e),za(r,e)}function Ra(r){var n,a;if(!r.container)return;let e=r.container;e.querySelectorAll(".workbench-tab").forEach(s=>{let o=s.dataset.tab;s.classList.toggle("active",o===r.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(s=>{let o=s.dataset.tabPanel;s.classList.toggle("active",o===r.activeTab)}),r.activeTab==="library"&&r.libraryPanel&&((a=(n=r.libraryPanel).resetSearch)==null||a.call(n))}function za(r,e){be(r,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),be(r,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),be(r,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),be(r,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),be(r,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),be(r,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),be(r,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),be(r,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),be(r,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let n=Ue();n.layout&&(n.layout.debug_rect_visible=!!t.checked)});let i=e.querySelector("#debug-rect-color");i==null||i.addEventListener("input",()=>{let n=i.value.replace("#",""),a=parseInt(n,16),s=Ue();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function zr(r){if(!r.container||!r.debugOverlay)return;let e=r.container.querySelector("#debug-workbench"),t=r.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"),nt(e,t,r.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{wt(r),Oa(r,e)},10)}));let i=r.container.querySelector('[data-panel="scene-objects"]'),n=i==null?void 0:i.querySelector("[data-panel-handle]"),a=i==null?void 0:i.querySelector("[data-panel-resize-v]");i&&n&&(!i.style.left&&!i.style.right&&!i.style.top&&!i.style.bottom&&(i.style.left="16px",i.style.top="72px"),nt(i,n,r.debugOverlay),n.addEventListener("pointerup",()=>{setTimeout(()=>{Oa(r,i)},10)})),i&&a&&hn(i,a);let s=r.container.querySelector('[data-panel="scene-tools-corner"]'),o=s==null?void 0:s.querySelector("[data-panel-handle]");s&&o&&nt(s,o,r.debugOverlay);let l=r.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&nt(l,c,r.debugOverlay),fn(r)}function $a(r,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(i=>{i.addEventListener("click",()=>{let n=i.closest(".scene-panel");n&&n.classList.toggle("collapsed")})})}function be(r,e,t,i,n){let a=e.querySelector(`#${t}`),s=e.querySelector(n);if(!a||!s)return;let o=Ir(Ue(),i);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),kr(Ue(),i,l)})}ae();var mn=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=Fe(),{hasChanges:t,overrideCount:i,overrides:n}=e,a={};for(let d of n){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1968
1968
  <div class="config-persistence-panel">
1969
1969
  <!-- Status Footer (Always Visible) -->
1970
1970
  <div class="persistence-status-footer">
@@ -2138,7 +2138,7 @@ This will:
2138
2138
 
2139
2139
  This will write all staged changes to ${u}.
2140
2140
 
2141
- After applying, staged overrides will be cleared.`))try{window.__handlerApplyCurrentInFlight=!0,i.textContent="\u23F3 Applying...",i.setAttribute("disabled","true");let h=Qe(),f={};for(let[y,w]of Object.entries(h.objects)){let v=w,P=y;/^(json\.|ui\.|effects\.|engine\.)/.test(P)||(P=`json.${y}`),v&&typeof v=="object"&&(v.identity||(v.identity={}),v.identity.id=P),f[`objects/${P}.json`]=v}h.engine&&(h.engine.runtime&&(f["engine/engine.runtime.json"]=h.engine.runtime),h.engine.assets&&(f["engine/engine.assets.json"]=h.engine.assets),h.engine.splash&&(f["engine/engine.splash.json"]=h.engine.splash),h.engine.loading&&(f["engine/engine.loading.json"]=h.engine.loading),h.engine.start&&(f["engine/engine.start.json"]=h.engine.start),h.engine.tutorial&&(f["engine/engine.tutorial.json"]=h.engine.tutorial),h.engine.endgame&&(f["engine/engine.endgame.json"]=h.engine.endgame),!h.engine.runtime&&!h.engine.assets&&(f["engine/engine.json"]=h.engine));for(let[y,w]of Object.entries(h.scenes)){let v=y.startsWith("scene.")?y:`scene.${y}`;f[`scenes/${v}.json`]=w}let m=this.currentVersion?"/api/apply-current":"/api/apply-direct",b=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:f,assets:{},hadCacheAtApply:!0})});if(!b.ok){let y=await b.json();throw new Error(y.error||"Apply to current source failed")}ge();try{let y=window.__editableConfig;y&&(window.__editableConfigBaseline=ee(y))}catch{}this.showSuccessNotification("Applied to current source"),await this.loadVersionsList(),this.refreshPanel(),await this.forceResyncAfterApply()}catch(h){console.error("[ConfigPersistence] Apply current failed:",h),alert(`\u274C Apply to current source failed: ${h.message}`),i.textContent="\u{1F4BE} APPLY TO CURRENT SOURCE",i.removeAttribute("disabled")}finally{window.__handlerApplyCurrentInFlight=!1}});let n=this.container.querySelector("#apply-base-btn");n==null||n.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
2141
+ After applying, staged overrides will be cleared.`))try{window.__handlerApplyCurrentInFlight=!0,i.textContent="\u23F3 Applying...",i.setAttribute("disabled","true");let h=Qe(),f={};for(let[y,w]of Object.entries(h.objects)){let v=w,j=y;/^(json\.|ui\.|effects\.|engine\.)/.test(j)||(j=`json.${y}`),v&&typeof v=="object"&&(v.identity||(v.identity={}),v.identity.id=j),f[`objects/${j}.json`]=v}h.engine&&(h.engine.runtime&&(f["engine/engine.runtime.json"]=h.engine.runtime),h.engine.assets&&(f["engine/engine.assets.json"]=h.engine.assets),h.engine.splash&&(f["engine/engine.splash.json"]=h.engine.splash),h.engine.loading&&(f["engine/engine.loading.json"]=h.engine.loading),h.engine.start&&(f["engine/engine.start.json"]=h.engine.start),h.engine.tutorial&&(f["engine/engine.tutorial.json"]=h.engine.tutorial),h.engine.endgame&&(f["engine/engine.endgame.json"]=h.engine.endgame),!h.engine.runtime&&!h.engine.assets&&(f["engine/engine.json"]=h.engine));for(let[y,w]of Object.entries(h.scenes)){let v=y.startsWith("scene.")?y:`scene.${y}`;f[`scenes/${v}.json`]=w}let m=this.currentVersion?"/api/apply-current":"/api/apply-direct",b=await fetch(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:f,assets:{},hadCacheAtApply:!0})});if(!b.ok){let y=await b.json();throw new Error(y.error||"Apply to current source failed")}ge();try{let y=window.__editableConfig;y&&(window.__editableConfigBaseline=ee(y))}catch{}this.showSuccessNotification("Applied to current source"),await this.loadVersionsList(),this.refreshPanel(),await this.forceResyncAfterApply()}catch(h){console.error("[ConfigPersistence] Apply current failed:",h),alert(`\u274C Apply to current source failed: ${h.message}`),i.textContent="\u{1F4BE} APPLY TO CURRENT SOURCE",i.removeAttribute("disabled")}finally{window.__handlerApplyCurrentInFlight=!1}});let n=this.container.querySelector("#apply-base-btn");n==null||n.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
2142
2142
 
2143
2143
  This will DIRECTLY MODIFY base configuration files.
2144
2144
 
@@ -2365,7 +2365,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
2365
2365
  <source src="${n}" type="audio/wav">
2366
2366
  Your browser does not support the audio element.
2367
2367
  </audio>
2368
- `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",i=>{let n=i.target;(n.dataset.action==="close"||n===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(ft(),Ut)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(r){new Ba().open(r)};ga();ae();var D=require("pixi.js");ae();var bn=class{constructor(e){this.app=null;this.camera=new D.Container;this.bgContainer=new D.Container;this.mainContainer=new D.Container;this.uiContainer=new D.Container;this.gizmoLayer=new D.Container;this.screenFrame=new D.Graphics;this.gameFrame=new D.Graphics;this.gridLayer=new D.Graphics;this.spawnPointLayer=new D.Container;this.objectMap=new Map;this.selectedId=null;this.selectedIds=new Set;this.dragMode=null;this.selectionBox=null;this.selectionBoxStart=null;this.isSelectionBoxActive=!1;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 D.Graphics;this.anchorVisualizationLayer=new D.Graphics;this.moveHandle=new D.Graphics;this.scaleHandle=new D.Graphics;this.rotateHandle=new D.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.snapToGrid=!1;this.alignmentGuidesEnabled=!0;this.alignmentGuideLayer=new D.Graphics;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.updateManager=new Ce;this.backgroundCoverEnabled=!0;this.backgroundLocked=!0;this.backgroundCoverRetries=new Map;this.backgroundCoverRaf=null;this.dropZoneActive=!1;this.dropZoneOverlay=null;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.playModeEnabled?this.schedulePostScreenSync({width:t,height:i}):this.syncFromConfig())};this.handleAnchorChanged=e=>{let t=e==null?void 0:e.detail,i=t==null?void 0:t.objectId;if(!i)return;let n=t==null?void 0:t.previousAnchor,a=t==null?void 0:t.nextAnchor;this.adjustPositionForAnchorChange(i,n,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 i=t.path,n=t.objectId;if(i==="transform.anchor"&&n){let s=t.value,o=t.oldValue;o!=null&&this.adjustPositionForAnchorChange(n,o,s)}let a=t.objectIds;if(n){this.syncFromConfig([n]);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:{},i=t.objectId,n=t.texture;if(!i||!n)return;let a=this.objectMap.get(i);if(!a)return;let s=a.displayObject;if(s!=null&&s.texture)s.texture=n;else if(s!=null&&s.children){let c=s.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=n)}let o=this.getEditableObjectConfig(i);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var s;if(!this.isVisible)return;let t=(s=e==null?void 0:e.detail)!=null?s:{},i=Number(t.width),n=Number(t.height),a=Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible)return;let t=this.getPointerButton(e);if(t===2){if(this.isGizmoTarget(e==null?void 0:e.target))return;let h=this.getEventGlobalPoint(e);if(!h)return;let f=new D.Point(h.x,h.y),m=this.getPickCandidates(f);if(m.length>0){let b=m[0];this.selectedIds.has(b)||(this.selectedIds.clear(),this.selectedIds.add(b),this.setSelected(b),this.updateGizmos()),this.showContextMenu(b,h.x,h.y)}return}if(t!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new D.Point(i.x,i.y),a=this.getPickCandidates(n),o=navigator.platform.toUpperCase().indexOf("MAC")>=0?e.metaKey:e.ctrlKey;if(a.length===0){o||(this.setSelected(null),this.selectedIds.clear()),this.selectionBoxStart=n,this.isSelectionBoxActive=!0,this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let l=performance.now(),c=this.areSameIds(a,this.lastPickIds),d=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,p=l-this.lastPickTime<1200,u=c&&d&&p?(this.lastPickIndex+1)%a.length:0,g=a[u];this.lastPickIds=a,this.lastPickIndex=u,this.lastPickPoint=n,this.lastPickTime=l,o?this.selectedIds.has(g)?(this.selectedIds.delete(g),this.selectedId===g&&(this.selectedId=this.selectedIds.size>0?Array.from(this.selectedIds)[0]:null)):(this.selectedIds.add(g),this.selectedId=g):(this.selectedIds.clear(),this.selectedIds.add(g),this.setSelected(g)),this.updateGizmos()};this.handleGridSettings=e=>{var a,s,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,i=(s=e==null?void 0:e.detail)==null?void 0:s.gap,n=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n),this.updateGrid()};this.handleBackgroundCover=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&(this.backgroundCoverEnabled=t,this.syncFromConfig(),this.updateGizmos())};this.handleBackgroundLock=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;if(typeof t=="boolean"&&(this.backgroundLocked=t,t&&this.selectedId)){let n=this.getEditableObjectConfig(this.selectedId),a=this.objectMap.get(this.selectedId);this.isBackgroundObject(this.selectedId,n,a==null?void 0:a.displayObject)&&this.setSelected(null)}};this.handlePlayModeChange=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.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 i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),le({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var n;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 i=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(i){if(this.dragMode==="move"){let a=this.dragPointerOffset;if(!a)return;let s=i.x+a.x,o=i.y+a.y;if(this.snapToGrid){let d=this.snapToGridPosition(s,o);s=d.x,o=d.y}let l=s-this.dragStartPos.x,c=o-this.dragStartPos.y;if(t.displayObject.position.set(s,o),this.updateAlignmentGuides(this.selectedId,new D.Point(s,o)),this.updateLiveConfigPosition(s,o),this.selectedIds.size>1){let d=new Map;if(!this.multiDragStartPositions){this.multiDragStartPositions=new Map;for(let p of this.selectedIds){if(p===this.selectedId)continue;let u=this.objectMap.get(p);u!=null&&u.displayObject&&this.multiDragStartPositions.set(p,new D.Point(u.displayObject.position.x,u.displayObject.position.y))}}for(let p of this.selectedIds){if(p===this.selectedId)continue;let u=this.objectMap.get(p);if(!(u!=null&&u.displayObject))continue;let g=this.multiDragStartPositions.get(p);if(g){let h=g.x+l,f=g.y+c;if(this.snapToGrid){let m=this.snapToGridPosition(h,f);h=m.x,f=m.y}u.displayObject.position.set(h,f),this.updateLiveConfigPositionForObject(p,h,f)}}}this.dragLastPointer=new D.Point(i.x,i.y),this.dragLogged||(this.dragLogged=!0,console.log("[SceneEditor][DragMove]",{objectId:this.selectedId,selectedCount:this.selectedIds.size,pointer:{x:i.x,y:i.y},nextPos:{x:s,y:o}}))}if(this.dragMode==="scale"&&this.dragAnchorLocal){let s=Math.max(1,this.distance(i,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*s);(n=t.displayObject.scale)!=null&&n.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(i.y-this.dragAnchorLocal.y,i.x-this.dragAnchorLocal.x),s=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=s,this.updateLiveConfigRotation(s)}this.updateGizmos()}};this.onDragEnd=()=>{if(this.dragMode){if(this.alignmentGuideLayer&&this.alignmentGuideLayer.clear(),this.selectedIds.size>0){let e=Array.from(this.selectedIds);window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectIds:e}})),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,this.multiDragStartPositions=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)}};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new D.Point(this.app.renderer.width/2,this.app.renderer.height/2),s=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(s);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){let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()}if(this.isSelectionBoxActive&&this.selectionBoxStart&&this.app){let t=this.getEventGlobalPoint(e);if(!t)return;let i=new D.Point(t.x,t.y);this.drawSelectionBox(this.selectionBoxStart,i)}};this.onPanEnd=e=>{if(this.isPanning&&(this.isPanning=!1,this.panStart=null,this.panStartCamera=null),this.isSelectionBoxActive&&this.selectionBoxStart&&this.app){let t=this.getEventGlobalPoint(e);if(t){let i=new D.Point(t.x,t.y);this.finalizeSelectionBox(this.selectionBoxStart,i)}this.isSelectionBoxActive=!1,this.selectionBoxStart=null,this.selectionBox&&this.selectionBox.clear()}this.multiDragStartPositions=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new D.Application,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.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.selectionBox=new D.Graphics,this.selectionBox.zIndex=99999,this.selectionBox.eventMode="none",this.gizmoLayer.addChild(this.selectionBox),this.dropZoneOverlay=new D.Graphics,this.dropZoneOverlay.zIndex=99998,this.dropZoneOverlay.eventMode="none",this.gizmoLayer.addChild(this.dropZoneOverlay),this.alignmentGuideLayer=new D.Graphics,this.alignmentGuideLayer.zIndex=99997,this.alignmentGuideLayer.eventMode="none",this.gizmoLayer.addChild(this.alignmentGuideLayer),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(),this.setupKeyboardShortcuts(),this.setupDragAndDrop()}setupKeyboardShortcuts(){window.addEventListener("keydown",e=>{if(!this.isVisible)return;let i=navigator.platform.toUpperCase().indexOf("MAC")>=0?e.metaKey:e.ctrlKey,n=e.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||(i&&e.key==="a"?(e.preventDefault(),this.selectAll()):i&&e.key==="d"?(e.preventDefault(),this.duplicateSelected()):i&&e.key==="c"?(e.preventDefault(),this.copySelected()):i&&e.key==="v"?(e.preventDefault(),this.pasteObjects()):e.key==="Escape"?(this.setSelected(null),this.selectedIds.clear(),this.updateGizmos()):(e.key==="Delete"||e.key==="Backspace")&&this.selectedIds.size>0?(e.preventDefault(),this.deleteSelectedObjects()):e.key==="g"||e.key==="G"?(e.preventDefault(),this.toggleGrid()):e.shiftKey&&(e.key==="g"||e.key==="G")&&(e.preventDefault(),this.toggleSnapToGrid()))})}async duplicateSelected(){if(this.selectedIds.size===0)return;let e=window.__HANDLER_ACTIVE_SCREEN,t=e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay",i=Array.from(this.selectedIds),n=[];for(let a of i)try{let s=`${a}_copy_${Date.now()}`,o=await fetch("/api/objects/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceId:a,newInstanceId:s,shareConfig:!1,screenId:t})}),l=await o.json();o.ok&&l.success&&n.push(l.newObjectId)}catch(s){console.error(`[SceneEditor] Failed to duplicate ${a}:`,s)}n.length>0&&(this.selectedIds=new Set(n),this.selectedId=n[0],this.updateGizmos(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")))}copySelected(){if(this.selectedIds.size===0)return;let e=[];for(let t of this.selectedIds){let i=this.getEditableObjectConfig(t);i&&e.push({id:t,config:i})}window.__sceneEditorClipboard={configs:e,timestamp:Date.now()},this.showToast(`\u{1F4CB} Copied ${e.length} object${e.length>1?"s":""}`,1500)}async pasteObjects(){var a,s;let e=window.__sceneEditorClipboard;if(!e||!e.configs||e.configs.length===0)return;let t=window.__HANDLER_ACTIVE_SCREEN,i=t==="loading"||t==="start"||t==="gameplay"||t==="tutorial"||t==="endgame"?t:"gameplay",n=[];for(let{id:o,config:l}of e.configs)try{let c=`${o}_paste_${Date.now()}_${Math.random().toString(36).substr(2,5)}`,d=`json.${c}`,p=JSON.parse(JSON.stringify(l));if(p.identity.id=d,p.instance_id=c,p.object_config=d,(a=p.transform)!=null&&a.position){let h=p.transform.position,f=Array.isArray(h)?h[0]:h.x||0,m=Array.isArray(h)?h[1]:h.y||0;Array.isArray(h)?p.transform.position=[f+20,m+20]:p.transform.position={x:f+20,y:m+20}}let u=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:c,objectConfigId:d,config:p,layer:((s=p.identity)==null?void 0:s.category)==="ui"?"ui":"world"})}),g=await u.json();u.ok&&g.success&&n.push(c)}catch(c){console.error(`[SceneEditor] Failed to paste ${o}:`,c)}n.length>0&&(this.selectedIds=new Set(n),this.selectedId=n[0],this.updateGizmos(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),this.showToast(`\u{1F4CB} Pasted ${n.length} object${n.length>1?"s":""}`,1500))}toggleGrid(){this.gridEnabled=!this.gridEnabled,this.updateGrid();try{window.localStorage.setItem(this.getSceneStorageKey("grid_enabled"),String(this.gridEnabled))}catch{}this.showToast(this.gridEnabled?"\u{1F4D0} Grid enabled":"\u{1F4D0} Grid disabled",1e3)}toggleSnapToGrid(){this.snapToGrid=!this.snapToGrid;try{window.localStorage.setItem(this.getSceneStorageKey("snap_to_grid"),String(this.snapToGrid))}catch{}this.showToast(this.snapToGrid?"\u{1F532} Snap to grid enabled":"\u{1F532} Snap to grid disabled",1e3)}snapToGridPosition(e,t){if(!this.snapToGrid)return{x:e,y:t};let i=this.gridGap;return{x:Math.round(e/i)*i,y:Math.round(t/i)*i}}updateAlignmentGuides(e,t){var d,p,u,g;if(!this.alignmentGuidesEnabled||!e||!this.alignmentGuideLayer){this.alignmentGuideLayer&&this.alignmentGuideLayer.clear();return}let i=this.objectMap.get(e);if(!(i!=null&&i.displayObject)){this.alignmentGuideLayer.clear();return}let n=(p=(d=i.displayObject).getBounds)==null?void 0:p.call(d);if(!n){this.alignmentGuideLayer.clear();return}this.alignmentGuideLayer.clear();let a=this.camera.toLocal(new D.Point(n.x,n.y)),s=this.camera.toLocal(new D.Point(n.x+n.width,n.y+n.height)),o=(a.x+s.x)/2,l=(a.y+s.y)/2,c=5;for(let[h,f]of this.objectMap.entries()){if(h===e||!(f!=null&&f.displayObject)||f.displayObject.visible===!1)continue;let m=(g=(u=f.displayObject).getBounds)==null?void 0:g.call(u);if(!m)continue;let b=this.camera.toLocal(new D.Point(m.x,m.y)),y=this.camera.toLocal(new D.Point(m.x+m.width,m.y+m.height)),w=(b.x+y.x)/2,v=(b.y+y.y)/2;if(Math.abs(o-w)<c){let E=Math.min(a.y,b.y),C=Math.max(s.y,y.y);this.alignmentGuideLayer.moveTo(w,E),this.alignmentGuideLayer.lineTo(w,C),this.alignmentGuideLayer.stroke({width:1,color:3900150,alpha:.6})}if(Math.abs(l-v)<c){let E=Math.min(a.x,b.x),C=Math.max(s.x,y.x);this.alignmentGuideLayer.moveTo(E,v),this.alignmentGuideLayer.lineTo(C,v),this.alignmentGuideLayer.stroke({width:1,color:3900150,alpha:.6})}let P=a.x,I=s.x,_=a.y,k=s.y,j=b.x,L=y.x,x=b.y,S=y.y;if(Math.abs(P-j)<c||Math.abs(P-L)<c||Math.abs(I-j)<c||Math.abs(I-L)<c){let E=Math.abs(P-j)<c?j:Math.abs(P-L)<c?L:Math.abs(I-j)<c?j:L,C=Math.min(_,x),A=Math.max(k,S);this.alignmentGuideLayer.moveTo(E,C),this.alignmentGuideLayer.lineTo(E,A),this.alignmentGuideLayer.stroke({width:1,color:1096065,alpha:.5})}if(Math.abs(_-x)<c||Math.abs(_-S)<c||Math.abs(k-x)<c||Math.abs(k-S)<c){let E=Math.abs(_-x)<c?x:Math.abs(_-S)<c?S:Math.abs(k-x)<c?x:S,C=Math.min(P,j),A=Math.max(I,L);this.alignmentGuideLayer.moveTo(C,E),this.alignmentGuideLayer.lineTo(A,E),this.alignmentGuideLayer.stroke({width:1,color:1096065,alpha:.5})}}}selectAll(){let e=Array.from(this.objectMap.keys()).filter(t=>{let i=this.getEditableObjectConfig(t),n=this.objectMap.get(t);return!(!(n!=null&&n.displayObject)||n.displayObject.visible===!1||this.backgroundLocked&&this.isBackgroundObject(t,i,n.displayObject))});this.selectedIds=new Set(e),e.length>0&&(this.selectedId=e[0],this.updateGizmos())}deleteSelectedObjects(){let e=Array.from(this.selectedIds);for(let t of e){let i=window.__deleteObjectRequest;typeof i=="function"&&i(t)}this.selectedIds.clear(),this.selectedId=null,this.updateGizmos()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}adjustPositionForAnchorChange(e,t,i){var L,x,S,E,C,A;if(t==null||i==null||t===i)return;let n=this.getEditableObjectConfig(e);if(!n)return;let a=(L=n.transform)!=null?L:{};if(a.position_ratio!=null)return;let s=(x=this.getRuntimeScreenSize())!=null?x:this.getScreen();if(!(s!=null&&s.width)||!(s!=null&&s.height))return;let o=this.objectMap.get(e);if(!(o!=null&&o.displayObject))return;let l=this.isBackgroundObject(e,n,o.displayObject),c=this.getRuntimeScale(),d=o.displayObject.position.x,p=o.displayObject.position.y,u=Ne(s.width,s.height,t),g=Ne(s.width,s.height,i),h=u.x,f=u.y,m=g.x,b=g.y;l||(h=(u.x-s.width/2)/c,f=(u.y-s.height/2)/c,m=(g.x-s.width/2)/c,b=(g.y-s.height/2)/c);let y={x:d-h,y:p-f},w={x:d-m,y:p-b},v=a.offset,P=Array.isArray(v)?Number((S=v[0])!=null?S:0):Number((E=v==null?void 0:v.x)!=null?E:0),I=Array.isArray(v)?Number((C=v[1])!=null?C:0):Number((A=v==null?void 0:v.y)!=null?A:0),_=w.x-P,k=w.y-I,j=this.buildPositionValue(a,{x:_,y:k});this.updateManager.updateProperty(e,"transform.position",j,{refreshInspector:!0})}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let s=a.displayObject;if(!s||s.visible===!1||this.backgroundLocked&&this.isBackgroundObject(n,this.getEditableObjectConfig(n),s))continue;let o=(i=s.getBounds)==null?void 0:i.call(s);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=s.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof s.zIndex=="number"?s.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(s):0,u=c*1e6+d*1e3+p;t.push({id:n,order:u})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha")),n=window.localStorage.getItem(this.getSceneStorageKey("snap_to_grid")),a=window.localStorage.getItem(this.getSceneStorageKey("background_cover")),s=window.localStorage.getItem(this.getSceneStorageKey("background_lock"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let o=Number(t);Number.isFinite(o)&&o>2&&(this.gridGap=o)}if(i!==null){let o=Number(i);Number.isFinite(o)&&o>=0&&o<=1&&(this.gridAlpha=o)}n!==null&&(this.snapToGrid=n==="true"),a!==null&&(this.backgroundCoverEnabled=a==="true"),s!==null&&(this.backgroundLocked=s==="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,s,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((s=u==null?void 0:u.height)!=null?s: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"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,P,I,_,k,j,L,x,S,E,C,A,T,O,M,R,z,F,q;let e=window.__screenManager;if(e){let N=["gameplay","start","tutorial","endgame","loading"];for(let H of N){let $=(a=e.get)==null?void 0:a.call(e,H);if($!=null&&$.visible){let U=(s=$.getContentLayer)==null?void 0:s.call($);if(U){let Y=(o=$.x)!=null?o:0,V=(l=$.y)!=null?l:0,G=(c=U.x)!=null?c:0,te=(d=U.y)!=null?d:0,W=(u=(p=U.scale)==null?void 0:p.x)!=null?u:1,J=(h=(g=U.scale)==null?void 0:g.y)!=null?h:W;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:H,contentLayerScale:{x:W,y:J},position:{x:Y+G,y:V+te}}),{scale:{x:W,y:J},position:{x:Y+G,y:V+te},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let H of N){let $=(f=e.get)==null?void 0:f.call(e,H);if($){if(!$.visible&&typeof $.updateLayout=="function"){let Y=window.gameApp;if((m=Y==null?void 0:Y.renderer)!=null&&m.screen){let V=Y.renderer.screen.width,G=Y.renderer.screen.height;V>0&&G>0&&$.updateLayout(V,G)}}let U=(b=$.getContentLayer)==null?void 0:b.call($);if(U){let Y=(y=$.x)!=null?y:0,V=(w=$.y)!=null?w:0,G=(v=U.x)!=null?v:0,te=(P=U.y)!=null?P:0,W=(_=(I=U.scale)==null?void 0:I.x)!=null?_:1,J=(j=(k=U.scale)==null?void 0:k.y)!=null?j:W;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:H,visible:$.visible,contentLayerScale:{x:W,y:J},position:{x:Y+G,y:V+te}}),{scale:{x:W,y:J},position:{x:Y+G,y:V+te},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let t=window.__mainContainer;if(t){let N=(x=(L=t.scale)==null?void 0:L.x)!=null?x:1,H=(E=(S=t.scale)==null?void 0:S.y)!=null?E:N;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:N,y:H},position:{x:(C=t.position)==null?void 0:C.x,y:(A=t.position)==null?void 0:A.y}}),t}let i=window.gameApp,n=(T=i==null?void 0:i.stage)!=null?T:null;if(n){let N=(M=(O=n.scale)==null?void 0:O.x)!=null?M:1,H=(z=(R=n.scale)==null?void 0:R.y)!=null?z:N;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:N,y:H},position:{x:(F=n.position)==null?void 0:F.x,y:(q=n.position)==null?void 0:q.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return n}getRuntimeScale(){var i,n;let e=this.getRuntimeLayoutReference(),t=Number((n=(i=e==null?void 0:e.scale)==null?void 0:i.x)!=null?n: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 i=t.get(e),n=((c=i==null?void 0:i.getDisplayObject)==null?void 0:c.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let s=window.__screenManager;if(s){let h=["gameplay","start","tutorial","endgame","loading"];for(let f of h){let m=(d=s.get)==null?void 0:d.call(s,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 s,o,l,c,d,p,u,g,h,f;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,i=1,n=Number((o=(s=e.position)==null?void 0:s.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(n)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:n,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:i},position:{x:n,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,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 n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let s=this.getEditableObjectConfig(a);if(!s){this.removeObject(a);continue}await this.upsertObject(a,s)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),s=this.playModeEnabled?this.getRuntimeParentContainer(e):null,l=this.isBackgroundObject(e,t)?this.bgContainer:a?this.uiContainer:this.mainContainer,c=s!=null?s:l;if(!n||n.assetKey!==i||n.isUi!==a){n&&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:i,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||!s)&&this.applyTransformFromConfig(e,d.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,f,m,b,y,w,v,P;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 Se.create(e,t,this.app);if(_ instanceof D.Container)return _}}catch(I){console.warn("[SceneEditor] ObjectFactory failed for",e,I)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let I=this.getScreen(),_=(p=I==null?void 0:I.width)!=null?p:0,k=(u=I==null?void 0:I.height)!=null?u:0,j=new D.Graphics,L=this.parseColor(n.background_color,0),x=typeof n.background_alpha=="number"?n.background_alpha:1;_>0&&k>0&&j.rect(0,0,_,k).fill({color:L,alpha:x});let S=new D.Container;return S.addChild(j),S}if(a){let I=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",_=new D.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(f=i==null?void 0:i.fontSize)!=null?f:16,fill:I,align:(m=i==null?void 0:i.align)!=null?m:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new D.Text({text:(y=i==null?void 0:i.text)!=null?y:"",style:_})}if((w=t==null?void 0:t.effects)!=null&&w.width||(v=t==null?void 0:t.effects)!=null&&v.height){let I=new D.Graphics,_=typeof t.effects.width=="number"?t.effects.width:100,k=typeof t.effects.height=="number"?t.effects.height:100,j=(P=t.effects.fill_color)!=null?P:"#ffffff",L=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,x=Number.parseInt(String(j).replace("#",""),16);return I.rect(0,0,_,k).fill({color:Number.isFinite(x)?x:16777215,alpha:L}),I}return new D.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new D.Rectangle(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,s;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((s=t==null?void 0:t.identity)==null?void 0:s.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}isBackgroundObject(e,t,i){var s,o;if((i==null?void 0:i.parent)===this.bgContainer)return!0;let n=(((s=t==null?void 0:t.identity)==null?void 0:s.category)||"").toString().toLowerCase(),a=(((o=t==null?void 0:t.identity)==null?void 0:o.id)||e||"").toString().toLowerCase();return!!(n.includes("bg")||n.includes("background")||a.startsWith("background_")||a.includes("background"))}queueBackgroundCoverRetry(e){var i;let t=(i=this.backgroundCoverRetries.get(e))!=null?i:0;t>=10||(this.backgroundCoverRetries.set(e,t+1),this.backgroundCoverRaf==null&&(this.backgroundCoverRaf=requestAnimationFrame(()=>{this.backgroundCoverRaf=null;let n=this.objectMap.get(e),a=this.getEditableObjectConfig(e);!(n!=null&&n.displayObject)||!a||this.applyTransformFromConfig(e,n.displayObject,a)})))}applyVisualConfig(e,t){var a,s,o;if(!e)return;let i=(a=t==null?void 0:t.render)!=null?a:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n={x:.5,y:.5};if((s=e.anchor)!=null&&s.set)e.anchor.set(n.x,n.y);else if(e.pivot){let l=(o=e.getLocalBounds)==null?void 0:o.call(e);l&&e.pivot.set(l.width*n.x,l.height*n.y)}}applyTransformFromConfig(e,t,i){var _,k,j,L,x,S,E,C,A,T,O,M,R,z,F,q,N,H,$,U,Y,V,G,te;if(!t)return;let n=this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return;let a=(_=i==null?void 0:i.transform)!=null?_:{},s=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((k=l[0])!=null?k:0):Number((j=l==null?void 0:l.x)!=null?j:0),p=Array.isArray(l)?Number((L=l[1])!=null?L:0):Number((x=l==null?void 0:l.y)!=null?x:0),u=Array.isArray(c)?Number((S=c[0])!=null?S:0):Number((E=c==null?void 0:c.x)!=null?E:0),g=Array.isArray(c)?Number((C=c[1])!=null?C:0):Number((A=c==null?void 0:c.y)!=null?A: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,i,t)){let W=Number((O=(T=t==null?void 0:t.texture)==null?void 0:T.width)!=null?O:0),J=Number((R=(M=t==null?void 0:t.texture)==null?void 0:M.height)!=null?R:0),Q=(z=t==null?void 0:t.getLocalBounds)==null?void 0:z.call(t),fe=Number((F=Q==null?void 0:Q.width)!=null?F:0),se=Number((q=Q==null?void 0:Q.height)!=null?q:0),Mt=Number((N=Q==null?void 0:Q.x)!=null?N:0),ve=Number((H=Q==null?void 0:Q.y)!=null?H:0);if((!Number.isFinite(W)||W<=0||!Number.isFinite(J)||J<=0)&&(W=fe,J=se),!Number.isFinite(W)||W<=0||!Number.isFinite(J)||J<=0){this.queueBackgroundCoverRetry(e);return}if(($=t.anchor)!=null&&$.set)t.anchor.set(.5,.5);else if((U=t.pivot)!=null&&U.set){let so=Number.isFinite(fe)&&fe>0?Mt+fe*.5:W*.5,ro=Number.isFinite(se)&&se>0?ve+se*.5:J*.5;t.pivot.set(so,ro)}(Y=t.position)!=null&&Y.set?t.position.set(n.width/2,n.height/2):t.position&&(t.position.x=n.width/2,t.position.y=n.height/2);let jt=n.width/W,Ye=n.height/J,rt=Math.max(jt,Ye);(V=t.scale)!=null&&V.set?t.scale.set(rt,rt):t.scale&&(t.scale.x=rt,t.scale.y=rt);let Tn=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(Tn);return}let m=o!=null?gt(n.width,n.height,o):Ne(n.width,n.height,s),b=this.getRuntimeScale(),y=(m.x-n.width/2)/b+h,w=(m.y-n.height/2)/b+f;(G=t.position)!=null&&G.set?t.position.set(y,w):t.position&&(t.position.x=y,t.position.y=w);let P=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*this.getRuntimeScale();(te=t.scale)!=null&&te.set?t.scale.set(P,P):t.scale&&(t.scale.x=P,t.scale.y=P);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 i=(d=this.getRuntimeScreenSize())!=null?d:this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),s=(e==null?void 0:e.position_ratio)!=null?gt(i.width,i.height,e.position_ratio):Ne(i.width,i.height,a!=null?a:n);if(t===this.bgContainer)return new D.Point(s.x,s.y);let o=this.getRuntimeScale(),l=(s.x-i.width/2)/o,c=(s.y-i.height/2)/o;return new D.Point(l,c)}getPositioningAnchor(e,t){var i,n,a,s,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=(n=(i=h==null?void 0:h.objects)==null?void 0:i.get)==null?void 0:n.call(i,e),m=(o=(a=f==null?void 0:f.transform)==null?void 0:a.anchor)!=null?o:(s=f==null?void 0:f.render)==null?void 0:s.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),w=(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(w!=null&&w!=="")return w}return"top-left"}getActiveScreenSize(e){var t,i;return this.playModeEnabled?(i=(t=this.getRuntimeScreenSize())!=null?t:e)!=null?i:this.getScreen():e!=null?e:this.getScreen()}updateLayout(e){var i,n,a,s,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((n=(i=u.position)==null?void 0:i.x)!=null?n:t.width/2),h=Number((s=(a=u.position)==null?void 0:a.y)!=null?s: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 D.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new D.Point(0,0)),n=this.camera.toLocal(new D.Point(t.width,t.height)),a=Math.min(i.x,n.x),s=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((s-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<=s;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(s,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 i=t.width,n=t.height,a=0,s=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,s,i,n),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var i,n,a,s,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=((i=h==null?void 0:h.getDisplayObject)==null?void 0:i.call(h))||(h==null?void 0:h.pixiObject)||h;if(!f)continue;let m=(a=(n=g.displayObject)==null?void 0:n.parent)!=null?a:this.mainContainer,b=new D.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=(s=m.scale)==null?void 0:s.x)!=null?o:1)||1,_=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,k=y.x/I,j=y.y/_;(d=g.displayObject.scale)!=null&&d.set?g.displayObject.scale.set(k,j):g.displayObject.scale&&(g.displayObject.scale.x=k,g.displayObject.scale.y=j)}let w=this.getWorldRotation(f);if(typeof w=="number"){let I=m?m.rotation:0,_=w-I;g.displayObject.rotation=_;let k=this.getEditableObjectConfig(u);if(k){let j=(p=k.transform)!=null?p:{};k.transform||(k.transform=j);let L=this.toDegrees(_),x=typeof j.rotation=="number"?j.rotation:0;if(Math.abs(L-x)>.01){let S=Math.round(L*100)/100;j.rotation=S}}}let v=f.parent,P=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(f):0;typeof f.zIndex=="number"?g.displayObject.zIndex=f.zIndex:Number.isFinite(P)&&(g.displayObject.zIndex=P)}this.updateGizmos()}getWorldScale(e){var a,s;let t=(s=e==null?void 0:e.worldTransform)!=null?s:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){if(!this.app)return;let e=this.getActiveScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var f,m,b,y,w,v;if(!this.selectedId&&this.selectedIds.size===0||!this.isVisible){this.clearGizmos();return}if(this.selectedIds.size>1){let P=1/0,I=1/0,_=-1/0,k=-1/0,j=!1;for(let L of this.selectedIds){let x=this.objectMap.get(L);if(!(x!=null&&x.displayObject))continue;let S=(m=(f=x.displayObject).getBounds)==null?void 0:m.call(f);if(!S||S.width<=0||S.height<=0)continue;let E=this.camera.toLocal(new D.Point(S.x,S.y)),C=this.camera.toLocal(new D.Point(S.x+S.width,S.y+S.height));P=Math.min(P,E.x,C.x),I=Math.min(I,E.y,C.y),_=Math.max(_,E.x,C.x),k=Math.max(k,E.y,C.y),j=!0}if(j){let L=_-P,x=k-I,S=P+L/2,E=I+x/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(P,I,L,x),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9});for(let T of this.selectedIds){let O=this.objectMap.get(T);if(!(O!=null&&O.displayObject))continue;let M=(y=(b=O.displayObject).getBounds)==null?void 0:y.call(b);if(!M||M.width<=0||M.height<=0)continue;let R=this.camera.toLocal(new D.Point(M.x,M.y)),z=this.camera.toLocal(new D.Point(M.x+M.width,M.y+M.height)),F=z.x-R.x,q=z.y-R.y;this.gizmoOutline.rect(R.x,R.y,F,q),this.gizmoOutline.stroke({width:1,color:16752394,alpha:.5})}let C=7,A={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(S,E,C).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(A),this.moveHandle.cursor="move",this.scaleHandle.clear(),this.rotateHandle.clear()}else this.clearGizmos();return}if(!this.selectedId){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(v=(w=e.displayObject).getBounds)==null?void 0:v.call(w);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new D.Point(t.x,t.y)),n=this.camera.toLocal(new D.Point(t.x+t.width,t.y+t.height)),a=n.x-i.x,s=n.y-i.y,o=i.x+a/2,l=i.y+s/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,s),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=i.x+a,u=i.y+s;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=i.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((i,n)=>{let a=new D.Graphics;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let s=this.toCameraFromMain(i);a.position.set(s.x,s.y),a.cursor="move",a.eventMode="static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var s,o;return{x:Number((s=a==null?void 0:a.x)!=null?s:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new D.Point(e.x,e.y)),i=new D.Point;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let s=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new D.Point(s.x-a.x,s.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let s=this.getSpawnPoints(a);if(!s||!s[t])return;let o=s.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(!(this.selectedId===e&&this.selectedIds.size===1&&this.selectedIds.has(e||""))&&(this.selectedId=e,e?(this.selectedIds.clear(),this.selectedIds.add(e)):this.selectedIds.clear(),this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var d,p,u,g,h,f,m;if(!this.selectedId)return;let i=this.objectMap.get(this.selectedId);if(!(i!=null&&i.displayObject))return;let n=this.getEditableObjectConfig(this.selectedId);if(!n||this.backgroundLocked&&this.isBackgroundObject(this.selectedId,n,i.displayObject))return;let a=(d=n.transform)!=null?d:{},s=(p=i.displayObject.parent)!=null?p:this.mainContainer,o=this.getEventLocalPoint(t,s);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=n==null?void 0:n.render)==null?void 0:h.anchor)==null||n.render.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"render.anchor",l),this.dragMode=e,this.dragContainer=s,this.dragStartPointer=new D.Point(o.x,o.y),this.dragStartPos=new D.Point(i.displayObject.position.x,i.displayObject.position.y),this.dragLastPointer=new D.Point(o.x,o.y),this.dragPointerOffset=new D.Point(i.displayObject.position.x-o.x,i.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,n,i.displayObject),screen:c,runtimeScale:this.getRuntimeScale(),pointer:{x:o.x,y:o.y},objectPos:{x:i.displayObject.position.x,y:i.displayObject.position.y},container:s===this.bgContainer?"bg":s===this.uiContainer?"ui":"main"}),this.dragStartScale=typeof((m=i.displayObject.scale)==null?void 0:m.x)=="number"?i.displayObject.scale.x:1,this.dragStartRotation=typeof i.displayObject.rotation=="number"?i.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,s),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 i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPositionForObject(e,t,i){var P,I,_,k,j,L,x,S;let n=this.getEditableObjectConfig(e);if(!n)return;let a=(P=n.transform)!=null?P:{};n.transform||(n.transform=a);let s=(I=this.getRuntimeScreenSize())!=null?I:this.getScreen();if(!(s!=null&&s.width)||!(s!=null&&s.height))return;let o=this.objectMap.get(e),l=((_=o==null?void 0:o.displayObject)==null?void 0:_.parent)===this.bgContainer,c=this.getPositioningAnchor(e,a),d=(a==null?void 0:a.position_ratio)!=null?gt(s.width,s.height,a.position_ratio):Ne(s.width,s.height,c),p=d.x,u=d.y,g=t,h=i;if(!l){let E=this.getRuntimeScale();p=(d.x-s.width/2)/E,u=(d.y-s.height/2)/E,g=t/E,h=i/E}let f=g-p,m=h-u,b=(k=a.offset)!=null?k:{x:0,y:0},y=Array.isArray(b)?Number((j=b[0])!=null?j:0):Number((L=b==null?void 0:b.x)!=null?L:0),w=Array.isArray(b)?Number((x=b[1])!=null?x:0):Number((S=b==null?void 0:b.y)!=null?S:0),v=this.buildPositionValue(a,{x:f-y,y:m-w});this.updateManager.updateProperty(e,"transform.position",v,{refreshInspector:!0})}updateLiveConfigPosition(e,t){this.selectedId&&this.updateLiveConfigPositionForObject(this.selectedId,e,t)}updateLiveConfigScale(e){var a;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(a=t.transform)!=null?a:{};t.transform||(t.transform=i);let n=Math.round(e*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.scale",n,{refreshInspector:!0})}updateLiveConfigRotation(e){var s;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(s=t.transform)!=null?s:{};t.transform||(t.transform=i);let n=this.toDegrees(e),a=typeof i.rotation=="number"?i.rotation:0;if(Math.abs(n-a)>.01){let o=Math.round(n*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.rotation",o,{refreshInspector:!0})}}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),le({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&(n(t,i),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let s=0;s<n.length-1;s+=1){let o=n[s];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position,n=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(i)?[n,a]:{x:n,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new D.Point(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),s=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new D.Point(s,o)}getEventLocalPoint(e,t=this.mainContainer){var a,s;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new D.Point(o.x,o.y)}let i=(s=e==null?void 0:e.global)!=null?s:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new D.Point;return t.toLocal(new D.Point(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),s=(t-n.top)*(this.app.renderer.height/n.height),o=new D.Point;return i.toLocal(new D.Point(a,s),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}drawSelectionBox(e,t){if(!this.selectionBox)return;this.selectionBox.clear();let i=Math.min(e.x,t.x),n=Math.max(e.x,t.x),a=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=n-i,l=s-a;this.selectionBox.rect(i,a,o,l),this.selectionBox.stroke({width:2,color:3900150,alpha:.8}),this.selectionBox.rect(i,a,o,l),this.selectionBox.fill({color:3900150,alpha:.1})}finalizeSelectionBox(e,t){var l;let i=Math.min(e.x,t.x),n=Math.max(e.x,t.x),a=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=[];for(let[c,d]of this.objectMap.entries()){let p=d.displayObject;if(!p||p.visible===!1||this.backgroundLocked&&this.isBackgroundObject(c,this.getEditableObjectConfig(c),p))continue;let u=(l=p.getBounds)==null?void 0:l.call(p);if(!u||u.width<=0||u.height<=0)continue;let g=u.x+u.width/2,h=u.y+u.height/2;g>=i&&g<=n&&h>=a&&h<=s&&o.push(c)}o.length>0&&(this.selectedIds=new Set(o),this.selectedId=o[0],this.updateGizmos())}setupDragAndDrop(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("dragover",t=>{t.preventDefault(),t.stopPropagation(),this.dropZoneActive||(this.dropZoneActive=!0,this.showDropZone())}),e.addEventListener("dragleave",t=>{e.contains(t.relatedTarget)||(this.dropZoneActive=!1,this.hideDropZone())}),e.addEventListener("drop",async t=>{var d;t.preventDefault(),t.stopPropagation(),this.dropZoneActive=!1,this.hideDropZone();let n=Array.from(((d=t.dataTransfer)==null?void 0:d.files)||[]).filter(p=>p.type.startsWith("image/"));if(n.length===0)return;let a=e.getBoundingClientRect(),s=t.clientX-a.left,o=t.clientY-a.top,l=new D.Point(s/a.width*this.app.renderer.width,o/a.height*this.app.renderer.height),c=this.camera.toLocal(l);await this.handleDroppedPNGs(n,c)})}showDropZone(){if(!this.dropZoneOverlay||!this.app)return;let e=this.camera.toLocal(new D.Point(0,0)),t=this.camera.toLocal(new D.Point(this.app.renderer.width,this.app.renderer.height)),i=t.x-e.x,n=t.y-e.y;this.dropZoneOverlay.clear(),this.dropZoneOverlay.rect(e.x,e.y,i,n),this.dropZoneOverlay.fill({color:3900150,alpha:.1}),this.dropZoneOverlay.rect(e.x,e.y,i,n),this.dropZoneOverlay.stroke({width:3,color:3900150,alpha:.6}),this.dropZoneOverlay.visible=!0}hideDropZone(){this.dropZoneOverlay&&(this.dropZoneOverlay.clear(),this.dropZoneOverlay.visible=!1)}async handleDroppedPNGs(e,t){let i=window.__HANDLER_ACTIVE_SCREEN,n=i==="loading"||i==="start"||i==="gameplay"||i==="tutorial"||i==="endgame"?i:"gameplay",a=this.showToast(`Processing ${e.length} PNG${e.length>1?"s":""}...`);try{for(let s=0;s<e.length;s++){let o=e[s];await this.processDroppedPNG(o,t,n,s)}this.hideToast(a),this.showToast(`\u2705 Added ${e.length} PNG${e.length>1?"s":""} to scene`,2e3),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh"))}catch(s){this.hideToast(a),this.showToast(`\u274C Error: ${s instanceof Error?s.message:String(s)}`,3e3),console.error("[SceneEditor] Failed to process dropped PNGs:",s)}}async processDroppedPNG(e,t,i,n){let a=await this.fileToDataUrl(e);if(!a)throw new Error(`Failed to read ${e.name}`);let s=e.name.replace(/\.[^/.]+$/,""),o=this.inferCategoryFromFilename(s),l=s.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase(),c=`${l}_${Date.now()}${n>0?`_${n}`:""}`,d=`json.${c}`,p=`${l}.png`,g=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:p,data:a,overwrite:!1})})).json();if(!g.success)throw new Error(`Failed to save ${e.name} to library: ${g.error}`);let h=this.getScreen(),f=this.getRuntimeScale(),m=(t.x-h.width/2)/f,b=(t.y-h.height/2)/f,y={identity:{id:d,category:o},transform:{anchor:"center",position:{x:m,y:b},scale:1,rotation:0},render:{z_index:0,alpha:1,visible:!0,anchor:{x:.5,y:.5},asset:{type:"image",path:g.path||`raw/library/${o}/${p}`}}},w=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:c,objectConfigId:d,config:y,layer:o==="ui"?"ui":"world"})}),v=await w.json();if(!w.ok||!v.success)throw new Error(`Failed to create object: ${v.error||"Unknown error"}`)}inferCategoryFromFilename(e){let t=e.toLowerCase();return t.startsWith("ui_")||t.includes("button")||t.includes("label")?"ui":t.startsWith("bg_")||t.includes("background")?"backgrounds":t.includes("character")||t.includes("player")?"character":"environment"}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}showToast(e,t=3e3){let i=document.createElement("div");return i.style.cssText=`
2368
+ `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",i=>{let n=i.target;(n.dataset.action==="close"||n===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(ft(),Ut)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(r){new Ba().open(r)};ga();ae();var D=require("pixi.js");ae();var bn=class{constructor(e){this.app=null;this.camera=new D.Container;this.bgContainer=new D.Container;this.mainContainer=new D.Container;this.uiContainer=new D.Container;this.gizmoLayer=new D.Container;this.screenFrame=new D.Graphics;this.gameFrame=new D.Graphics;this.gridLayer=new D.Graphics;this.spawnPointLayer=new D.Container;this.objectMap=new Map;this.selectedId=null;this.selectedIds=new Set;this.dragMode=null;this.selectionBox=null;this.selectionBoxStart=null;this.isSelectionBoxActive=!1;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 D.Graphics;this.anchorVisualizationLayer=new D.Graphics;this.moveHandle=new D.Graphics;this.scaleHandle=new D.Graphics;this.rotateHandle=new D.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.snapToGrid=!1;this.alignmentGuidesEnabled=!0;this.alignmentGuideLayer=new D.Graphics;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!0;this.playModeInitialized=!1;this.layoutScale=1;this.updateManager=new Ce;this.backgroundCoverEnabled=!0;this.backgroundLocked=!0;this.backgroundCoverRetries=new Map;this.backgroundCoverRaf=null;this.dropZoneActive=!1;this.dropZoneOverlay=null;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:i}=e.detail;!t||!i||(this.hasUserCamera=!1,this.updateLayout({width:t,height:i}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.playModeEnabled?this.schedulePostScreenSync({width:t,height:i}):this.syncFromConfig())};this.handleAnchorChanged=e=>{let t=e==null?void 0:e.detail,i=t==null?void 0:t.objectId;if(!i)return;let n=t==null?void 0:t.previousAnchor,a=t==null?void 0:t.nextAnchor;this.adjustPositionForAnchorChange(i,n,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 i=t.path,n=t.objectId;if(i==="transform.anchor"&&n){let s=t.value,o=t.oldValue;o!=null&&this.adjustPositionForAnchorChange(n,o,s)}let a=t.objectIds;if(n){this.syncFromConfig([n]);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:{},i=t.objectId,n=t.texture;if(!i||!n)return;let a=this.objectMap.get(i);if(!a)return;let s=a.displayObject;if(s!=null&&s.texture)s.texture=n;else if(s!=null&&s.children){let c=s.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=n)}let o=this.getEditableObjectConfig(i);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var s;if(!this.isVisible)return;let t=(s=e==null?void 0:e.detail)!=null?s:{},i=Number(t.width),n=Number(t.height),a=Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var i,n;let t=(n=(i=e==null?void 0:e.detail)==null?void 0:i.objectId)!=null?n:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible)return;let t=this.getPointerButton(e);if(t===2){if(this.isGizmoTarget(e==null?void 0:e.target))return;let h=this.getEventGlobalPoint(e);if(!h)return;let f=new D.Point(h.x,h.y),m=this.getPickCandidates(f);if(m.length>0){let b=m[0];this.selectedIds.has(b)||(this.selectedIds.clear(),this.selectedIds.add(b),this.setSelected(b),this.updateGizmos()),this.showContextMenu(b,h.x,h.y)}return}if(t!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let i=this.getEventGlobalPoint(e);if(!i)return;let n=new D.Point(i.x,i.y),a=this.getPickCandidates(n),o=navigator.platform.toUpperCase().indexOf("MAC")>=0?e.metaKey:e.ctrlKey;if(a.length===0){o||(this.setSelected(null),this.selectedIds.clear()),this.selectionBoxStart=n,this.isSelectionBoxActive=!0,this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=n,this.lastPickTime=performance.now();return}let l=performance.now(),c=this.areSameIds(a,this.lastPickIds),d=this.lastPickPoint&&this.distance(n,this.lastPickPoint)<=6,p=l-this.lastPickTime<1200,u=c&&d&&p?(this.lastPickIndex+1)%a.length:0,g=a[u];this.lastPickIds=a,this.lastPickIndex=u,this.lastPickPoint=n,this.lastPickTime=l,o?this.selectedIds.has(g)?(this.selectedIds.delete(g),this.selectedId===g&&(this.selectedId=this.selectedIds.size>0?Array.from(this.selectedIds)[0]:null)):(this.selectedIds.add(g),this.selectedId=g):(this.selectedIds.clear(),this.selectedIds.add(g),this.setSelected(g)),this.updateGizmos()};this.handleGridSettings=e=>{var a,s,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,i=(s=e==null?void 0:e.detail)==null?void 0:s.gap,n=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof i=="number"&&Number.isFinite(i)&&i>2&&(this.gridGap=i),typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1&&(this.gridAlpha=n),this.updateGrid()};this.handleBackgroundCover=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;typeof t=="boolean"&&(this.backgroundCoverEnabled=t,this.syncFromConfig(),this.updateGizmos())};this.handleBackgroundLock=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.enabled;if(typeof t=="boolean"&&(this.backgroundLocked=t,t&&this.selectedId)){let n=this.getEditableObjectConfig(this.selectedId),a=this.objectMap.get(this.selectedId);this.isBackgroundObject(this.selectedId,n,a==null?void 0:a.displayObject)&&this.setSelected(null)}};this.handlePlayModeChange=e=>{var i;let t=(i=e==null?void 0:e.detail)==null?void 0:i.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 i=t.x+this.spawnPointDrag.offset.x,n=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,i,n)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,i=this.getEditableObjectConfig(e),n=i?this.getSpawnPoints(i):null;i&&n&&(this.setNestedValue(i,"logic.props.spawnPoints",t),le({objectId:e,path:"logic.props.spawnPoints",value:n},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var n;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 i=this.getPointerInContainer(e.clientX,e.clientY,this.dragContainer);if(i){if(this.dragMode==="move"){let a=this.dragPointerOffset;if(!a)return;let s=i.x+a.x,o=i.y+a.y;if(this.snapToGrid){let d=this.snapToGridPosition(s,o);s=d.x,o=d.y}let l=s-this.dragStartPos.x,c=o-this.dragStartPos.y;if(t.displayObject.position.set(s,o),this.updateAlignmentGuides(this.selectedId,new D.Point(s,o)),this.updateLiveConfigPosition(s,o),this.selectedIds.size>1){let d=new Map;if(!this.multiDragStartPositions){this.multiDragStartPositions=new Map;for(let p of this.selectedIds){if(p===this.selectedId)continue;let u=this.objectMap.get(p);u!=null&&u.displayObject&&this.multiDragStartPositions.set(p,new D.Point(u.displayObject.position.x,u.displayObject.position.y))}}for(let p of this.selectedIds){if(p===this.selectedId)continue;let u=this.objectMap.get(p);if(!(u!=null&&u.displayObject))continue;let g=this.multiDragStartPositions.get(p);if(g){let h=g.x+l,f=g.y+c;if(this.snapToGrid){let m=this.snapToGridPosition(h,f);h=m.x,f=m.y}u.displayObject.position.set(h,f),this.updateLiveConfigPositionForObject(p,h,f)}}}this.dragLastPointer=new D.Point(i.x,i.y),this.dragLogged||(this.dragLogged=!0,console.log("[SceneEditor][DragMove]",{objectId:this.selectedId,selectedCount:this.selectedIds.size,pointer:{x:i.x,y:i.y},nextPos:{x:s,y:o}}))}if(this.dragMode==="scale"&&this.dragAnchorLocal){let s=Math.max(1,this.distance(i,this.dragAnchorLocal))/Math.max(1,this.dragStartDistance),o=Math.max(.01,this.dragStartScale*s);(n=t.displayObject.scale)!=null&&n.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(i.y-this.dragAnchorLocal.y,i.x-this.dragAnchorLocal.x),s=this.dragStartRotation+(a-this.dragStartAngle);t.displayObject.rotation=s,this.updateLiveConfigRotation(s)}this.updateGizmos()}};this.onDragEnd=()=>{if(this.dragMode){if(this.alignmentGuideLayer&&this.alignmentGuideLayer.clear(),this.selectedIds.size>0){let e=Array.from(this.selectedIds);window.dispatchEvent(new CustomEvent("config:changed",{detail:{objectIds:e}})),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,this.multiDragStartPositions=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)}};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let i=Math.sign(e.deltaY)<0?1.1:.9,n=Math.min(6,Math.max(.1,this.cameraScale*i)),a=new D.Point(this.app.renderer.width/2,this.app.renderer.height/2),s=this.camera.toLocal(a);this.cameraScale=n,this.camera.scale.set(n);let o=this.camera.toGlobal(s);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){let t=e.clientX-this.panStart.x,i=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+i),this.updateGrid()}if(this.isSelectionBoxActive&&this.selectionBoxStart&&this.app){let t=this.getEventGlobalPoint(e);if(!t)return;let i=new D.Point(t.x,t.y);this.drawSelectionBox(this.selectionBoxStart,i)}};this.onPanEnd=e=>{if(this.isPanning&&(this.isPanning=!1,this.panStart=null,this.panStartCamera=null),this.isSelectionBoxActive&&this.selectionBoxStart&&this.app){let t=this.getEventGlobalPoint(e);if(t){let i=new D.Point(t.x,t.y);this.finalizeSelectionBox(this.selectionBoxStart,i)}this.isSelectionBoxActive=!1,this.selectionBoxStart=null,this.selectionBox&&this.selectionBox.clear()}this.multiDragStartPositions=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){this.app||(this.app=new D.Application,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden",this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.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.selectionBox=new D.Graphics,this.selectionBox.zIndex=99999,this.selectionBox.eventMode="none",this.gizmoLayer.addChild(this.selectionBox),this.dropZoneOverlay=new D.Graphics,this.dropZoneOverlay.zIndex=99998,this.dropZoneOverlay.eventMode="none",this.gizmoLayer.addChild(this.dropZoneOverlay),this.alignmentGuideLayer=new D.Graphics,this.alignmentGuideLayer.zIndex=99997,this.alignmentGuideLayer.eventMode="none",this.gizmoLayer.addChild(this.alignmentGuideLayer),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(),this.setupKeyboardShortcuts(),this.setupDragAndDrop()}setupKeyboardShortcuts(){window.addEventListener("keydown",e=>{if(!this.isVisible)return;let i=navigator.platform.toUpperCase().indexOf("MAC")>=0?e.metaKey:e.ctrlKey,n=e.target;n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable||(i&&e.key==="a"?(e.preventDefault(),this.selectAll()):i&&e.key==="d"?(e.preventDefault(),this.duplicateSelected()):i&&e.key==="c"?(e.preventDefault(),this.copySelected()):i&&e.key==="v"?(e.preventDefault(),this.pasteObjects()):e.key==="Escape"?(this.setSelected(null),this.selectedIds.clear(),this.updateGizmos()):(e.key==="Delete"||e.key==="Backspace")&&this.selectedIds.size>0?(e.preventDefault(),this.deleteSelectedObjects()):e.key==="g"||e.key==="G"?(e.preventDefault(),this.toggleGrid()):e.shiftKey&&(e.key==="g"||e.key==="G")&&(e.preventDefault(),this.toggleSnapToGrid()))})}async duplicateSelected(){if(this.selectedIds.size===0)return;let e=window.__HANDLER_ACTIVE_SCREEN,t=e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay",i=Array.from(this.selectedIds),n=[];for(let a of i)try{let s=`${a}_copy_${Date.now()}`,o=await fetch("/api/objects/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceId:a,newInstanceId:s,shareConfig:!1,screenId:t})}),l=await o.json();o.ok&&l.success&&n.push(l.newObjectId)}catch(s){console.error(`[SceneEditor] Failed to duplicate ${a}:`,s)}n.length>0&&(this.selectedIds=new Set(n),this.selectedId=n[0],this.updateGizmos(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")))}copySelected(){if(this.selectedIds.size===0)return;let e=[];for(let t of this.selectedIds){let i=this.getEditableObjectConfig(t);i&&e.push({id:t,config:i})}window.__sceneEditorClipboard={configs:e,timestamp:Date.now()},this.showToast(`\u{1F4CB} Copied ${e.length} object${e.length>1?"s":""}`,1500)}async pasteObjects(){var a,s;let e=window.__sceneEditorClipboard;if(!e||!e.configs||e.configs.length===0)return;let t=window.__HANDLER_ACTIVE_SCREEN,i=t==="loading"||t==="start"||t==="gameplay"||t==="tutorial"||t==="endgame"?t:"gameplay",n=[];for(let{id:o,config:l}of e.configs)try{let c=`${o}_paste_${Date.now()}_${Math.random().toString(36).substr(2,5)}`,d=`json.${c}`,p=JSON.parse(JSON.stringify(l));if(p.identity.id=d,p.instance_id=c,p.object_config=d,(a=p.transform)!=null&&a.position){let h=p.transform.position,f=Array.isArray(h)?h[0]:h.x||0,m=Array.isArray(h)?h[1]:h.y||0;Array.isArray(h)?p.transform.position=[f+20,m+20]:p.transform.position={x:f+20,y:m+20}}let u=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:c,objectConfigId:d,config:p,layer:((s=p.identity)==null?void 0:s.category)==="ui"?"ui":"world"})}),g=await u.json();u.ok&&g.success&&n.push(c)}catch(c){console.error(`[SceneEditor] Failed to paste ${o}:`,c)}n.length>0&&(this.selectedIds=new Set(n),this.selectedId=n[0],this.updateGizmos(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),this.showToast(`\u{1F4CB} Pasted ${n.length} object${n.length>1?"s":""}`,1500))}toggleGrid(){this.gridEnabled=!this.gridEnabled,this.updateGrid();try{window.localStorage.setItem(this.getSceneStorageKey("grid_enabled"),String(this.gridEnabled))}catch{}this.showToast(this.gridEnabled?"\u{1F4D0} Grid enabled":"\u{1F4D0} Grid disabled",1e3)}toggleSnapToGrid(){this.snapToGrid=!this.snapToGrid;try{window.localStorage.setItem(this.getSceneStorageKey("snap_to_grid"),String(this.snapToGrid))}catch{}this.showToast(this.snapToGrid?"\u{1F532} Snap to grid enabled":"\u{1F532} Snap to grid disabled",1e3)}snapToGridPosition(e,t){if(!this.snapToGrid)return{x:e,y:t};let i=this.gridGap;return{x:Math.round(e/i)*i,y:Math.round(t/i)*i}}updateAlignmentGuides(e,t){var d,p,u,g;if(!this.alignmentGuidesEnabled||!e||!this.alignmentGuideLayer){this.alignmentGuideLayer&&this.alignmentGuideLayer.clear();return}let i=this.objectMap.get(e);if(!(i!=null&&i.displayObject)){this.alignmentGuideLayer.clear();return}let n=(p=(d=i.displayObject).getBounds)==null?void 0:p.call(d);if(!n){this.alignmentGuideLayer.clear();return}this.alignmentGuideLayer.clear();let a=this.camera.toLocal(new D.Point(n.x,n.y)),s=this.camera.toLocal(new D.Point(n.x+n.width,n.y+n.height)),o=(a.x+s.x)/2,l=(a.y+s.y)/2,c=5;for(let[h,f]of this.objectMap.entries()){if(h===e||!(f!=null&&f.displayObject)||f.displayObject.visible===!1)continue;let m=(g=(u=f.displayObject).getBounds)==null?void 0:g.call(u);if(!m)continue;let b=this.camera.toLocal(new D.Point(m.x,m.y)),y=this.camera.toLocal(new D.Point(m.x+m.width,m.y+m.height)),w=(b.x+y.x)/2,v=(b.y+y.y)/2;if(Math.abs(o-w)<c){let E=Math.min(a.y,b.y),I=Math.max(s.y,y.y);this.alignmentGuideLayer.moveTo(w,E),this.alignmentGuideLayer.lineTo(w,I),this.alignmentGuideLayer.stroke({width:1,color:3900150,alpha:.6})}if(Math.abs(l-v)<c){let E=Math.min(a.x,b.x),I=Math.max(s.x,y.x);this.alignmentGuideLayer.moveTo(E,v),this.alignmentGuideLayer.lineTo(I,v),this.alignmentGuideLayer.stroke({width:1,color:3900150,alpha:.6})}let j=a.x,T=s.x,O=a.y,M=s.y,_=b.x,C=y.x,x=b.y,S=y.y;if(Math.abs(j-_)<c||Math.abs(j-C)<c||Math.abs(T-_)<c||Math.abs(T-C)<c){let E=Math.abs(j-_)<c?_:Math.abs(j-C)<c?C:Math.abs(T-_)<c?_:C,I=Math.min(O,x),L=Math.max(M,S);this.alignmentGuideLayer.moveTo(E,I),this.alignmentGuideLayer.lineTo(E,L),this.alignmentGuideLayer.stroke({width:1,color:1096065,alpha:.5})}if(Math.abs(O-x)<c||Math.abs(O-S)<c||Math.abs(M-x)<c||Math.abs(M-S)<c){let E=Math.abs(O-x)<c?x:Math.abs(O-S)<c?S:Math.abs(M-x)<c?x:S,I=Math.min(j,_),L=Math.max(T,C);this.alignmentGuideLayer.moveTo(I,E),this.alignmentGuideLayer.lineTo(L,E),this.alignmentGuideLayer.stroke({width:1,color:1096065,alpha:.5})}}}selectAll(){let e=Array.from(this.objectMap.keys()).filter(t=>{let i=this.getEditableObjectConfig(t),n=this.objectMap.get(t);return!(!(n!=null&&n.displayObject)||n.displayObject.visible===!1||this.backgroundLocked&&this.isBackgroundObject(t,i,n.displayObject))});this.selectedIds=new Set(e),e.length>0&&(this.selectedId=e[0],this.updateGizmos())}deleteSelectedObjects(){let e=Array.from(this.selectedIds);for(let t of e){let i=window.__deleteObjectRequest;typeof i=="function"&&i(t)}this.selectedIds.clear(),this.selectedId=null,this.updateGizmos()}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}adjustPositionForAnchorChange(e,t,i){var C,x,S,E,I,L;if(t==null||i==null||t===i)return;let n=this.getEditableObjectConfig(e);if(!n)return;let a=(C=n.transform)!=null?C:{};if(a.position_ratio!=null)return;let s=(x=this.getRuntimeScreenSize())!=null?x:this.getScreen();if(!(s!=null&&s.width)||!(s!=null&&s.height))return;let o=this.objectMap.get(e);if(!(o!=null&&o.displayObject))return;let l=this.isBackgroundObject(e,n,o.displayObject),c=this.getRuntimeScale(),d=o.displayObject.position.x,p=o.displayObject.position.y,u=Ne(s.width,s.height,t),g=Ne(s.width,s.height,i),h=u.x,f=u.y,m=g.x,b=g.y;l||(h=(u.x-s.width/2)/c,f=(u.y-s.height/2)/c,m=(g.x-s.width/2)/c,b=(g.y-s.height/2)/c);let y={x:d-h,y:p-f},w={x:d-m,y:p-b},v=a.offset,j=Array.isArray(v)?Number((S=v[0])!=null?S:0):Number((E=v==null?void 0:v.x)!=null?E:0),T=Array.isArray(v)?Number((I=v[1])!=null?I:0):Number((L=v==null?void 0:v.y)!=null?L:0),O=w.x-j,M=w.y-T,_=this.buildPositionValue(a,{x:O,y:M});this.updateManager.updateProperty(e,"transform.position",_,{refreshInspector:!0})}getPickCandidates(e){var i;let t=[];for(let[n,a]of this.objectMap.entries()){let s=a.displayObject;if(!s||s.visible===!1||this.backgroundLocked&&this.isBackgroundObject(n,this.getEditableObjectConfig(n),s))continue;let o=(i=s.getBounds)==null?void 0:i.call(s);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=s.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof s.zIndex=="number"?s.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(s):0,u=c*1e6+d*1e3+p;t.push({id:n,order:u})}return t.sort((n,a)=>a.order-n.order),t.map(n=>n.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i+=1)if(e[i]!==t[i])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),i=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha")),n=window.localStorage.getItem(this.getSceneStorageKey("snap_to_grid")),a=window.localStorage.getItem(this.getSceneStorageKey("background_cover")),s=window.localStorage.getItem(this.getSceneStorageKey("background_lock"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let o=Number(t);Number.isFinite(o)&&o>2&&(this.gridGap=o)}if(i!==null){let o=Number(i);Number.isFinite(o)&&o>=0&&o<=1&&(this.gridAlpha=o)}n!==null&&(this.snapToGrid=n==="true"),a!==null&&(this.backgroundCoverEnabled=a==="true"),s!==null&&(this.backgroundLocked=s==="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,s,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((s=u==null?void 0:u.height)!=null?s: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"),i=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),n=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0?{width:i,height:n}:null}getRuntimeLayoutReference(){var a,s,o,l,c,d,p,u,g,h,f,m,b,y,w,v,j,T,O,M,_,C,x,S,E,I,L,A,P,k,R,z,F,q;let e=window.__screenManager;if(e){let N=["gameplay","start","tutorial","endgame","loading"];for(let H of N){let $=(a=e.get)==null?void 0:a.call(e,H);if($!=null&&$.visible){let U=(s=$.getContentLayer)==null?void 0:s.call($);if(U){let Y=(o=$.x)!=null?o:0,V=(l=$.y)!=null?l:0,G=(c=U.x)!=null?c:0,te=(d=U.y)!=null?d:0,W=(u=(p=U.scale)==null?void 0:p.x)!=null?u:1,J=(h=(g=U.scale)==null?void 0:g.y)!=null?h:W;return console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:H,contentLayerScale:{x:W,y:J},position:{x:Y+G,y:V+te}}),{scale:{x:W,y:J},position:{x:Y+G,y:V+te},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}for(let H of N){let $=(f=e.get)==null?void 0:f.call(e,H);if($){if(!$.visible&&typeof $.updateLayout=="function"){let Y=window.gameApp;if((m=Y==null?void 0:Y.renderer)!=null&&m.screen){let V=Y.renderer.screen.width,G=Y.renderer.screen.height;V>0&&G>0&&$.updateLayout(V,G)}}let U=(b=$.getContentLayer)==null?void 0:b.call($);if(U){let Y=(y=$.x)!=null?y:0,V=(w=$.y)!=null?w:0,G=(v=U.x)!=null?v:0,te=(j=U.y)!=null?j:0,W=(O=(T=U.scale)==null?void 0:T.x)!=null?O:1,J=(_=(M=U.scale)==null?void 0:M.y)!=null?_:W;return console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer",{screenId:H,visible:$.visible,contentLayerScale:{x:W,y:J},position:{x:Y+G,y:V+te}}),{scale:{x:W,y:J},position:{x:Y+G,y:V+te},pivot:U.pivot?{x:U.pivot.x,y:U.pivot.y}:void 0}}}}}let t=window.__mainContainer;if(t){let N=(x=(C=t.scale)==null?void 0:C.x)!=null?x:1,H=(E=(S=t.scale)==null?void 0:S.y)!=null?E:N;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:N,y:H},position:{x:(I=t.position)==null?void 0:I.x,y:(L=t.position)==null?void 0:L.y}}),t}let i=window.gameApp,n=(A=i==null?void 0:i.stage)!=null?A:null;if(n){let N=(k=(P=n.scale)==null?void 0:P.x)!=null?k:1,H=(z=(R=n.scale)==null?void 0:R.y)!=null?z:N;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:N,y:H},position:{x:(F=n.position)==null?void 0:F.x,y:(q=n.position)==null?void 0:q.y}})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return n}getRuntimeScale(){var i,n;let e=this.getRuntimeLayoutReference(),t=Number((n=(i=e==null?void 0:e.scale)==null?void 0:i.x)!=null?n: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 i=t.get(e),n=((c=i==null?void 0:i.getDisplayObject)==null?void 0:c.call(i))||(i==null?void 0:i.pixiObject)||i,a=n==null?void 0:n.parent;if(!a)return null;let s=window.__screenManager;if(s){let h=["gameplay","start","tutorial","endgame","loading"];for(let f of h){let m=(d=s.get)==null?void 0:d.call(s,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 s,o,l,c,d,p,u,g,h,f;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,i=1,n=Number((o=(s=e.position)==null?void 0:s.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(n)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:n,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{scale:{x:t,y:i},position:{x:n,y:a}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(n,a),this.uiContainer.position.set(n,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 n,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let i=this.getEditableConfig();return i!=null&&i.objects?typeof i.objects.get=="function"?(n=i.objects.get(e))!=null?n:null:(a=i.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let i=e();if(Array.isArray(i))return i}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let i=e!=null&&e.length?e:this.getEditableObjectIds(),n=new Set(i);if(!e)for(let a of Array.from(this.objectMap.keys()))n.has(a)||this.removeObject(a);for(let a of i){let s=this.getEditableObjectConfig(a);if(!s){this.removeObject(a);continue}await this.upsertObject(a,s)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var i,n;let t=this.objectMap.get(e);if(t){try{(n=(i=t.displayObject)==null?void 0:i.destroy)==null||n.call(i)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let i=this.getAssetKey(t),n=this.objectMap.get(e),a=this.isUiConfig(e,t),s=this.playModeEnabled?this.getRuntimeParentContainer(e):null,l=this.isBackgroundObject(e,t)?this.bgContainer:a?this.uiContainer:this.mainContainer,c=s!=null?s:l;if(!n||n.assetKey!==i||n.isUi!==a){n&&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:i,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||!s)&&this.applyTransformFromConfig(e,d.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,f,m,b,y,w,v,j;if((o=t==null?void 0:t.render)!=null&&o.asset)try{if(((c=(l=t==null?void 0:t.render)==null?void 0:l.asset)==null?void 0:c.type)!=="json"){let O=await Se.create(e,t,this.app);if(O instanceof D.Container)return O}}catch(T){console.warn("[SceneEditor] ObjectFactory failed for",e,T)}let i=t==null?void 0:t.ui,n=(d=t==null?void 0:t.render)!=null?d:{},a=(i==null?void 0:i.text)||(i==null?void 0:i.kind)==="text";if(!!n.background_color){let T=this.getScreen(),O=(p=T==null?void 0:T.width)!=null?p:0,M=(u=T==null?void 0:T.height)!=null?u:0,_=new D.Graphics,C=this.parseColor(n.background_color,0),x=typeof n.background_alpha=="number"?n.background_alpha:1;O>0&&M>0&&_.rect(0,0,O,M).fill({color:C,alpha:x});let S=new D.Container;return S.addChild(_),S}if(a){let T=(h=(g=i==null?void 0:i.color)!=null?g:n==null?void 0:n.tint)!=null?h:"#ffffff",O=new D.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(f=i==null?void 0:i.fontSize)!=null?f:16,fill:T,align:(m=i==null?void 0:i.align)!=null?m:"center",letterSpacing:(b=i==null?void 0:i.letterSpacing)!=null?b:0});return new D.Text({text:(y=i==null?void 0:i.text)!=null?y:"",style:O})}if((w=t==null?void 0:t.effects)!=null&&w.width||(v=t==null?void 0:t.effects)!=null&&v.height){let T=new D.Graphics,O=typeof t.effects.width=="number"?t.effects.width:100,M=typeof t.effects.height=="number"?t.effects.height:100,_=(j=t.effects.fill_color)!=null?j:"#ffffff",C=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,x=Number.parseInt(String(_).replace("#",""),16);return T.rect(0,0,O,M).fill({color:Number.isFinite(x)?x:16777215,alpha:C}),T}return new D.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let i=e.getLocalBounds();i&&i.width>0&&i.height>0&&(e.hitArea=new D.Rectangle(i.x,i.y,i.width,i.height))}}getAssetKey(e){var i;let t=(i=e==null?void 0:e.render)==null?void 0:i.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,s;let i=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),n=(((s=t==null?void 0:t.identity)==null?void 0:s.id)||e||"").toString().toLowerCase();return i.includes("ui")||n.startsWith("ui")||n.includes("label")}isBackgroundObject(e,t,i){var s,o;if((i==null?void 0:i.parent)===this.bgContainer)return!0;let n=(((s=t==null?void 0:t.identity)==null?void 0:s.category)||"").toString().toLowerCase(),a=(((o=t==null?void 0:t.identity)==null?void 0:o.id)||e||"").toString().toLowerCase();return!!(n.includes("bg")||n.includes("background")||a.startsWith("background_")||a.includes("background"))}queueBackgroundCoverRetry(e){var i;let t=(i=this.backgroundCoverRetries.get(e))!=null?i:0;t>=10||(this.backgroundCoverRetries.set(e,t+1),this.backgroundCoverRaf==null&&(this.backgroundCoverRaf=requestAnimationFrame(()=>{this.backgroundCoverRaf=null;let n=this.objectMap.get(e),a=this.getEditableObjectConfig(e);!(n!=null&&n.displayObject)||!a||this.applyTransformFromConfig(e,n.displayObject,a)})))}applyVisualConfig(e,t){var a,s,o;if(!e)return;let i=(a=t==null?void 0:t.render)!=null?a:{};typeof i.alpha=="number"&&(e.alpha=i.alpha),e.visible=i.visible!==!1,e.zIndex=typeof i.z_index=="number"?i.z_index:0;let n={x:.5,y:.5};if((s=e.anchor)!=null&&s.set)e.anchor.set(n.x,n.y);else if(e.pivot){let l=(o=e.getLocalBounds)==null?void 0:o.call(e);l&&e.pivot.set(l.width*n.x,l.height*n.y)}}applyTransformFromConfig(e,t,i){var O,M,_,C,x,S,E,I,L,A,P,k,R,z,F,q,N,H,$,U,Y,V,G,te;if(!t)return;let n=this.getScreen();if(!(n!=null&&n.width)||!(n!=null&&n.height))return;let a=(O=i==null?void 0:i.transform)!=null?O:{},s=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((M=l[0])!=null?M:0):Number((_=l==null?void 0:l.x)!=null?_:0),p=Array.isArray(l)?Number((C=l[1])!=null?C:0):Number((x=l==null?void 0:l.y)!=null?x:0),u=Array.isArray(c)?Number((S=c[0])!=null?S:0):Number((E=c==null?void 0:c.x)!=null?E:0),g=Array.isArray(c)?Number((I=c[1])!=null?I:0):Number((L=c==null?void 0:c.y)!=null?L: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,i,t)){let W=Number((P=(A=t==null?void 0:t.texture)==null?void 0:A.width)!=null?P:0),J=Number((R=(k=t==null?void 0:t.texture)==null?void 0:k.height)!=null?R:0),Q=(z=t==null?void 0:t.getLocalBounds)==null?void 0:z.call(t),fe=Number((F=Q==null?void 0:Q.width)!=null?F:0),se=Number((q=Q==null?void 0:Q.height)!=null?q:0),Mt=Number((N=Q==null?void 0:Q.x)!=null?N:0),ve=Number((H=Q==null?void 0:Q.y)!=null?H:0);if((!Number.isFinite(W)||W<=0||!Number.isFinite(J)||J<=0)&&(W=fe,J=se),!Number.isFinite(W)||W<=0||!Number.isFinite(J)||J<=0){this.queueBackgroundCoverRetry(e);return}if(($=t.anchor)!=null&&$.set)t.anchor.set(.5,.5);else if((U=t.pivot)!=null&&U.set){let so=Number.isFinite(fe)&&fe>0?Mt+fe*.5:W*.5,ro=Number.isFinite(se)&&se>0?ve+se*.5:J*.5;t.pivot.set(so,ro)}(Y=t.position)!=null&&Y.set?t.position.set(n.width/2,n.height/2):t.position&&(t.position.x=n.width/2,t.position.y=n.height/2);let jt=n.width/W,Ye=n.height/J,rt=Math.max(jt,Ye);(V=t.scale)!=null&&V.set?t.scale.set(rt,rt):t.scale&&(t.scale.x=rt,t.scale.y=rt);let Tn=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(Tn);return}let m=o!=null?gt(n.width,n.height,o):Ne(n.width,n.height,s),b=this.getRuntimeScale(),y=(m.x-n.width/2)/b+h,w=(m.y-n.height/2)/b+f;(G=t.position)!=null&&G.set?t.position.set(y,w):t.position&&(t.position.x=y,t.position.y=w);let j=(typeof(a==null?void 0:a.scale)=="number"?a.scale:1)*this.getRuntimeScale();(te=t.scale)!=null&&te.set?t.scale.set(j,j):t.scale&&(t.scale.x=j,t.scale.y=j);let T=typeof(a==null?void 0:a.rotation)=="number"?a.rotation:0;t.rotation=this.toRadians(T)}getAnchorLocalPoint(e,t=this.mainContainer){var d;let i=(d=this.getRuntimeScreenSize())!=null?d:this.getScreen();if(!(i!=null&&i.width)||!(i!=null&&i.height))return null;let n="top-right",a=this.getPositioningAnchor(this.selectedId,e!=null?e:{}),s=(e==null?void 0:e.position_ratio)!=null?gt(i.width,i.height,e.position_ratio):Ne(i.width,i.height,a!=null?a:n);if(t===this.bgContainer)return new D.Point(s.x,s.y);let o=this.getRuntimeScale(),l=(s.x-i.width/2)/o,c=(s.y-i.height/2)/o;return new D.Point(l,c)}getPositioningAnchor(e,t){var i,n,a,s,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=(n=(i=h==null?void 0:h.objects)==null?void 0:i.get)==null?void 0:n.call(i,e),m=(o=(a=f==null?void 0:f.transform)==null?void 0:a.anchor)!=null?o:(s=f==null?void 0:f.render)==null?void 0:s.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),w=(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(w!=null&&w!=="")return w}return"top-left"}getActiveScreenSize(e){var t,i;return this.playModeEnabled?(i=(t=this.getRuntimeScreenSize())!=null?t:e)!=null?i:this.getScreen():e!=null?e:this.getScreen()}updateLayout(e){var i,n,a,s,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((n=(i=u.position)==null?void 0:i.x)!=null?n:t.width/2),h=Number((s=(a=u.position)==null?void 0:a.y)!=null?s: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 D.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,i=this.camera.toLocal(new D.Point(0,0)),n=this.camera.toLocal(new D.Point(t.width,t.height)),a=Math.min(i.x,n.x),s=Math.max(i.x,n.x),o=Math.min(i.y,n.y),l=Math.max(i.y,n.y),c=400,d=Math.ceil((s-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<=s;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(s,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 i=t.width,n=t.height,a=0,s=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,s,i,n),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}syncFromGameObjectsInternal(){var i,n,a,s,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=((i=h==null?void 0:h.getDisplayObject)==null?void 0:i.call(h))||(h==null?void 0:h.pixiObject)||h;if(!f)continue;let m=(a=(n=g.displayObject)==null?void 0:n.parent)!=null?a:this.mainContainer,b=new D.Point;if(typeof f.getGlobalPosition=="function"){f.getGlobalPosition(b);let T=m.toLocal(b,this.camera);g.displayObject.position.set(T.x,T.y)}else if(f.worldTransform){b.set(f.worldTransform.tx,f.worldTransform.ty);let T=m.toLocal(b,this.camera);g.displayObject.position.set(T.x,T.y)}let y=this.getWorldScale(f);if(y){let T=Number((o=(s=m.scale)==null?void 0:s.x)!=null?o:1)||1,O=Number((c=(l=m.scale)==null?void 0:l.y)!=null?c:1)||1,M=y.x/T,_=y.y/O;(d=g.displayObject.scale)!=null&&d.set?g.displayObject.scale.set(M,_):g.displayObject.scale&&(g.displayObject.scale.x=M,g.displayObject.scale.y=_)}let w=this.getWorldRotation(f);if(typeof w=="number"){let T=m?m.rotation:0,O=w-T;g.displayObject.rotation=O;let M=this.getEditableObjectConfig(u);if(M){let _=(p=M.transform)!=null?p:{};M.transform||(M.transform=_);let C=this.toDegrees(O),x=typeof _.rotation=="number"?_.rotation:0;if(Math.abs(C-x)>.01){let S=Math.round(C*100)/100;_.rotation=S}}}let v=f.parent,j=typeof(v==null?void 0:v.getChildIndex)=="function"?v.getChildIndex(f):0;typeof f.zIndex=="number"?g.displayObject.zIndex=f.zIndex:Number.isFinite(j)&&(g.displayObject.zIndex=j)}this.updateGizmos()}getWorldScale(e){var a,s;let t=(s=e==null?void 0:e.worldTransform)!=null?s:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let i=Math.sqrt(t.a*t.a+t.b*t.b),n=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(i)||!Number.isFinite(n)?null:{x:i,y:n}}getWorldRotation(e){var i,n;let t=(n=e==null?void 0:e.worldTransform)!=null?n:(i=e==null?void 0:e.transform)==null?void 0:i.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){if(!this.app)return;let e=this.getActiveScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,i=this.app.renderer.height,n=Math.max(.01,Math.min(t/e.width,i/e.height));this.cameraScale=n,this.camera.scale.set(n),this.camera.position.set((t-e.width*n)/2,(i-e.height*n)/2)}updateGizmos(){var f,m,b,y,w,v;if(!this.selectedId&&this.selectedIds.size===0||!this.isVisible){this.clearGizmos();return}if(this.selectedIds.size>1){let j=1/0,T=1/0,O=-1/0,M=-1/0,_=!1;for(let C of this.selectedIds){let x=this.objectMap.get(C);if(!(x!=null&&x.displayObject))continue;let S=(m=(f=x.displayObject).getBounds)==null?void 0:m.call(f);if(!S||S.width<=0||S.height<=0)continue;let E=this.camera.toLocal(new D.Point(S.x,S.y)),I=this.camera.toLocal(new D.Point(S.x+S.width,S.y+S.height));j=Math.min(j,E.x,I.x),T=Math.min(T,E.y,I.y),O=Math.max(O,E.x,I.x),M=Math.max(M,E.y,I.y),_=!0}if(_){let C=O-j,x=M-T,S=j+C/2,E=T+x/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(j,T,C,x),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9});for(let A of this.selectedIds){let P=this.objectMap.get(A);if(!(P!=null&&P.displayObject))continue;let k=(y=(b=P.displayObject).getBounds)==null?void 0:y.call(b);if(!k||k.width<=0||k.height<=0)continue;let R=this.camera.toLocal(new D.Point(k.x,k.y)),z=this.camera.toLocal(new D.Point(k.x+k.width,k.y+k.height)),F=z.x-R.x,q=z.y-R.y;this.gizmoOutline.rect(R.x,R.y,F,q),this.gizmoOutline.stroke({width:1,color:16752394,alpha:.5})}let I=7,L={width:2,color:988970,alpha:.6};this.moveHandle.clear(),this.moveHandle.circle(S,E,I).fill({color:2278750,alpha:.95}),this.moveHandle.stroke(L),this.moveHandle.cursor="move",this.scaleHandle.clear(),this.rotateHandle.clear()}else this.clearGizmos();return}if(!this.selectedId){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(v=(w=e.displayObject).getBounds)==null?void 0:v.call(w);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let i=this.camera.toLocal(new D.Point(t.x,t.y)),n=this.camera.toLocal(new D.Point(t.x+t.width,t.y+t.height)),a=n.x-i.x,s=n.y-i.y,o=i.x+a/2,l=i.y+s/2;this.gizmoOutline.clear(),this.gizmoOutline.rect(i.x,i.y,a,s),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=i.x+a,u=i.y+s;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=i.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((i,n)=>{let a=new D.Graphics;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let s=this.toCameraFromMain(i);a.position.set(s.x,s.y),a.cursor="move",a.eventMode="static",a.on("pointerdown",o=>this.startSpawnPointDrag(n,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var i;(i=t.destroy)==null||i.call(t)})}isSpawnerConfig(e){var i,n;return((i=e==null?void 0:e.logic)==null?void 0:i.id)==="Spawner"?!0:String(((n=e==null?void 0:e.identity)==null?void 0:n.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var i,n;let t=(n=(i=e==null?void 0:e.logic)==null?void 0:i.props)==null?void 0:n.spawnPoints;return Array.isArray(t)?t.map(a=>{var s,o;return{x:Number((s=a==null?void 0:a.x)!=null?s:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new D.Point(e.x,e.y)),i=new D.Point;return this.camera.toLocal(t,void 0,i),i}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId)return;let i=this.getEditableObjectConfig(this.selectedId);if(!i)return;let n=this.getSpawnPoints(i);if(!n||!n[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let s=n[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new D.Point(s.x-a.x,s.y-a.y),startPoints:n.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,i,n){let a=this.getEditableObjectConfig(e);if(!a)return;let s=this.getSpawnPoints(a);if(!s||!s[t])return;let o=s.map((l,c)=>c===t?{x:i,y:n}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(!(this.selectedId===e&&this.selectedIds.size===1&&this.selectedIds.has(e||""))&&(this.selectedId=e,e?(this.selectedIds.clear(),this.selectedIds.add(e)):this.selectedIds.clear(),this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let i=window.__previewSelectObject;typeof i=="function"&&i(e)}}startDrag(e,t){var d,p,u,g,h,f,m;if(!this.selectedId)return;let i=this.objectMap.get(this.selectedId);if(!(i!=null&&i.displayObject))return;let n=this.getEditableObjectConfig(this.selectedId);if(!n||this.backgroundLocked&&this.isBackgroundObject(this.selectedId,n,i.displayObject))return;let a=(d=n.transform)!=null?d:{},s=(p=i.displayObject.parent)!=null?p:this.mainContainer,o=this.getEventLocalPoint(t,s);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=n==null?void 0:n.render)==null?void 0:h.anchor)==null||n.render.anchor==="")&&this.updateManager.updateProperty(this.selectedId,"render.anchor",l),this.dragMode=e,this.dragContainer=s,this.dragStartPointer=new D.Point(o.x,o.y),this.dragStartPos=new D.Point(i.displayObject.position.x,i.displayObject.position.y),this.dragLastPointer=new D.Point(o.x,o.y),this.dragPointerOffset=new D.Point(i.displayObject.position.x-o.x,i.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,n,i.displayObject),screen:c,runtimeScale:this.getRuntimeScale(),pointer:{x:o.x,y:o.y},objectPos:{x:i.displayObject.position.x,y:i.displayObject.position.y},container:s===this.bgContainer?"bg":s===this.uiContainer?"ui":"main"}),this.dragStartScale=typeof((m=i.displayObject.scale)==null?void 0:m.x)=="number"?i.displayObject.scale.x:1,this.dragStartRotation=typeof i.displayObject.rotation=="number"?i.displayObject.rotation:0,this.dragAnchorLocal=this.getAnchorLocalPoint(a,s),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 i,n,a;return e==="move"?(i=t==null?void 0:t.position)!=null?i:{x:0,y:0}:e==="scale"?(n=t==null?void 0:t.scale)!=null?n:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPositionForObject(e,t,i){var j,T,O,M,_,C,x,S;let n=this.getEditableObjectConfig(e);if(!n)return;let a=(j=n.transform)!=null?j:{};n.transform||(n.transform=a);let s=(T=this.getRuntimeScreenSize())!=null?T:this.getScreen();if(!(s!=null&&s.width)||!(s!=null&&s.height))return;let o=this.objectMap.get(e),l=((O=o==null?void 0:o.displayObject)==null?void 0:O.parent)===this.bgContainer,c=this.getPositioningAnchor(e,a),d=(a==null?void 0:a.position_ratio)!=null?gt(s.width,s.height,a.position_ratio):Ne(s.width,s.height,c),p=d.x,u=d.y,g=t,h=i;if(!l){let E=this.getRuntimeScale();p=(d.x-s.width/2)/E,u=(d.y-s.height/2)/E,g=t/E,h=i/E}let f=g-p,m=h-u,b=(M=a.offset)!=null?M:{x:0,y:0},y=Array.isArray(b)?Number((_=b[0])!=null?_:0):Number((C=b==null?void 0:b.x)!=null?C:0),w=Array.isArray(b)?Number((x=b[1])!=null?x:0):Number((S=b==null?void 0:b.y)!=null?S:0),v=this.buildPositionValue(a,{x:f-y,y:m-w});this.updateManager.updateProperty(e,"transform.position",v,{refreshInspector:!0})}updateLiveConfigPosition(e,t){this.selectedId&&this.updateLiveConfigPositionForObject(this.selectedId,e,t)}updateLiveConfigScale(e){var a;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(a=t.transform)!=null?a:{};t.transform||(t.transform=i);let n=Math.round(e*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.scale",n,{refreshInspector:!0})}updateLiveConfigRotation(e){var s;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let i=(s=t.transform)!=null?s:{};t.transform||(t.transform=i);let n=this.toDegrees(e),a=typeof i.rotation=="number"?i.rotation:0;if(Math.abs(n-a)>.01){let o=Math.round(n*100)/100;this.updateManager.updateProperty(this.selectedId,"transform.rotation",o,{refreshInspector:!0})}}applyFinalOverride(e,t,i,n){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),n),le({objectId:e,path:t,value:i},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let i=this.getEditableObjectConfig(t),n=window.applyEditableObjectConfig;typeof n=="function"&&i&&(n(t,i),window.dispatchEvent(new CustomEvent("inspector:refresh")))}))}setNestedValue(e,t,i){let n=t.split("."),a=e;for(let s=0;s<n.length-1;s+=1){let o=n[s];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[n[n.length-1]]=i}buildPositionValue(e,t){let i=e==null?void 0:e.position,n=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(i)?[n,a]:{x:n,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let i=e.x-t.x,n=e.y-t.y;return Math.sqrt(i*i+n*n)}getPointerButton(e){var t,i,n;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((n=(i=e==null?void 0:e.data)==null?void 0:i.originalEvent)==null?void 0:n.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new D.Point(t.x,t.y);if(!this.app)return null;let i=e==null?void 0:e.clientX,n=e==null?void 0:e.clientY;if(typeof i!="number"||typeof n!="number")return null;let a=this.app.canvas.getBoundingClientRect(),s=(i-a.left)*(this.app.renderer.width/a.width),o=(n-a.top)*(this.app.renderer.height/a.height);return new D.Point(s,o)}getEventLocalPoint(e,t=this.mainContainer){var a,s;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new D.Point(o.x,o.y)}let i=(s=e==null?void 0:e.global)!=null?s:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!i)return null;let n=new D.Point;return t.toLocal(new D.Point(i.x,i.y),void 0,n),n}getPointerInContainer(e,t,i){if(!this.app)return null;let n=this.app.canvas.getBoundingClientRect(),a=(e-n.left)*(this.app.renderer.width/n.width),s=(t-n.top)*(this.app.renderer.height/n.height),o=new D.Point;return i.toLocal(new D.Point(a,s),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let i=e.trim().replace("#",""),n=Number.parseInt(i,16);if(Number.isFinite(n))return n}return t}drawSelectionBox(e,t){if(!this.selectionBox)return;this.selectionBox.clear();let i=Math.min(e.x,t.x),n=Math.max(e.x,t.x),a=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=n-i,l=s-a;this.selectionBox.rect(i,a,o,l),this.selectionBox.stroke({width:2,color:3900150,alpha:.8}),this.selectionBox.rect(i,a,o,l),this.selectionBox.fill({color:3900150,alpha:.1})}finalizeSelectionBox(e,t){var l;let i=Math.min(e.x,t.x),n=Math.max(e.x,t.x),a=Math.min(e.y,t.y),s=Math.max(e.y,t.y),o=[];for(let[c,d]of this.objectMap.entries()){let p=d.displayObject;if(!p||p.visible===!1||this.backgroundLocked&&this.isBackgroundObject(c,this.getEditableObjectConfig(c),p))continue;let u=(l=p.getBounds)==null?void 0:l.call(p);if(!u||u.width<=0||u.height<=0)continue;let g=u.x+u.width/2,h=u.y+u.height/2;g>=i&&g<=n&&h>=a&&h<=s&&o.push(c)}o.length>0&&(this.selectedIds=new Set(o),this.selectedId=o[0],this.updateGizmos())}setupDragAndDrop(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("dragover",t=>{t.preventDefault(),t.stopPropagation(),this.dropZoneActive||(this.dropZoneActive=!0,this.showDropZone())}),e.addEventListener("dragleave",t=>{e.contains(t.relatedTarget)||(this.dropZoneActive=!1,this.hideDropZone())}),e.addEventListener("drop",async t=>{var d;t.preventDefault(),t.stopPropagation(),this.dropZoneActive=!1,this.hideDropZone();let n=Array.from(((d=t.dataTransfer)==null?void 0:d.files)||[]).filter(p=>p.type.startsWith("image/"));if(n.length===0)return;let a=e.getBoundingClientRect(),s=t.clientX-a.left,o=t.clientY-a.top,l=new D.Point(s/a.width*this.app.renderer.width,o/a.height*this.app.renderer.height),c=this.camera.toLocal(l);await this.handleDroppedPNGs(n,c)})}showDropZone(){if(!this.dropZoneOverlay||!this.app)return;let e=this.camera.toLocal(new D.Point(0,0)),t=this.camera.toLocal(new D.Point(this.app.renderer.width,this.app.renderer.height)),i=t.x-e.x,n=t.y-e.y;this.dropZoneOverlay.clear(),this.dropZoneOverlay.rect(e.x,e.y,i,n),this.dropZoneOverlay.fill({color:3900150,alpha:.1}),this.dropZoneOverlay.rect(e.x,e.y,i,n),this.dropZoneOverlay.stroke({width:3,color:3900150,alpha:.6}),this.dropZoneOverlay.visible=!0}hideDropZone(){this.dropZoneOverlay&&(this.dropZoneOverlay.clear(),this.dropZoneOverlay.visible=!1)}async handleDroppedPNGs(e,t){let i=window.__HANDLER_ACTIVE_SCREEN,n=i==="loading"||i==="start"||i==="gameplay"||i==="tutorial"||i==="endgame"?i:"gameplay",a=this.showToast(`Processing ${e.length} PNG${e.length>1?"s":""}...`);try{for(let s=0;s<e.length;s++){let o=e[s];await this.processDroppedPNG(o,t,n,s)}this.hideToast(a),this.showToast(`\u2705 Added ${e.length} PNG${e.length>1?"s":""} to scene`,2e3),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh"))}catch(s){this.hideToast(a),this.showToast(`\u274C Error: ${s instanceof Error?s.message:String(s)}`,3e3),console.error("[SceneEditor] Failed to process dropped PNGs:",s)}}async processDroppedPNG(e,t,i,n){let a=await this.fileToDataUrl(e);if(!a)throw new Error(`Failed to read ${e.name}`);let s=e.name.replace(/\.[^/.]+$/,""),o=this.inferCategoryFromFilename(s),l=s.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"").toLowerCase(),c=`${l}_${Date.now()}${n>0?`_${n}`:""}`,d=`json.${c}`,p=`${l}.png`,g=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:p,data:a,overwrite:!1})})).json();if(!g.success)throw new Error(`Failed to save ${e.name} to library: ${g.error}`);let h=this.getScreen(),f=this.getRuntimeScale(),m=(t.x-h.width/2)/f,b=(t.y-h.height/2)/f,y={identity:{id:d,category:o},transform:{anchor:"center",position:{x:m,y:b},scale:1,rotation:0},render:{z_index:0,alpha:1,visible:!0,anchor:{x:.5,y:.5},asset:{type:"image",path:g.path||`raw/library/${o}/${p}`}}},w=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:c,objectConfigId:d,config:y,layer:o==="ui"?"ui":"world"})}),v=await w.json();if(!w.ok||!v.success)throw new Error(`Failed to create object: ${v.error||"Unknown error"}`)}inferCategoryFromFilename(e){let t=e.toLowerCase();return t.startsWith("ui_")||t.includes("button")||t.includes("label")?"ui":t.startsWith("bg_")||t.includes("background")?"backgrounds":t.includes("character")||t.includes("player")?"character":"environment"}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}showToast(e,t=3e3){let i=document.createElement("div");return i.style.cssText=`
2369
2369
  position: fixed;
2370
2370
  top: 20px;
2371
2371
  right: 20px;
@@ -2573,7 +2573,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}c
2573
2573
  -->
2574
2574
 
2575
2575
  </div>
2576
- `,this.setupEventListeners(e),e}setupEventListeners(e){var w,v,P,I,_,k,j;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",L=>{if(this.viewMode==="compare")return;let x=L.target.value;this.setDevice(x)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",L=>{let x=L.target.value;this.setTheme(x)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(L=>{L.addEventListener("click",()=>{let x=L.dataset.viewToggle;x&&this.setViewMode(x)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(L=>{L.addEventListener("click",()=>{let x=L.dataset.layoutToggle;x&&this.setLayoutMode(x)})});let s=e.querySelector("#scene-toggle");s==null||s.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=L=>{let x=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${L}::${x}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(L,x,S)=>{L&&(L.textContent=x?`${S} On`:`${S} Off`,L.setAttribute("aria-pressed",x?"true":"false"))},u=()=>{let L=window.localStorage.getItem(l("grid_gap")),x=Number(L!=null?L:50);return Number.isFinite(x)?x:50},g=L=>{try{window.localStorage.setItem(l("grid_enabled"),L?"true":"false")}catch{}p(c,L,"Grid");let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:L,gap:x}}))},h=L=>{try{window.localStorage.setItem(l("play_mode"),L?"true":"false")}catch{}p(d,L,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:L}}))};try{let L=window.localStorage.getItem(l("grid_enabled"))==="true",x=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(p(c,L,"Grid"),p(d,x,"Play"),d&&(d.disabled=!0),c){let S=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:L,gap:S}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:x}}))}catch{}c==null||c.addEventListener("click",()=>{let L=c.getAttribute("aria-pressed")==="true";g(!L)}),d==null||d.addEventListener("click",()=>{let L=d.getAttribute("aria-pressed")==="true";h(!L)}),(w=e.querySelector("#rotate-btn"))==null||w.addEventListener("click",()=>this.toggleRotation()),(v=e.querySelector("#zoom-in-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(.1)),(P=e.querySelector("#zoom-out-btn"))==null||P.addEventListener("click",()=>this.adjustUserZoom(-.1)),(I=e.querySelector("#refresh-btn"))==null||I.addEventListener("click",()=>this.refresh()),(_=e.querySelector("#corner-zoom-in-btn"))==null||_.addEventListener("click",()=>this.adjustUserZoom(.1)),(k=e.querySelector("#corner-zoom-out-btn"))==null||k.addEventListener("click",()=>this.adjustUserZoom(-.1)),(j=e.querySelector("#corner-grab-btn"))==null||j.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let f=e.querySelector(".scene-panel.scene-objects"),m=f==null?void 0:f.querySelector("[data-panel-resize-v]");f&&m&&this.makeSidebarResizable(f,m,"left");let b=e.querySelector(".debug-workbench"),y=b==null?void 0:b.querySelector("#workbench-resize-v");b&&y&&this.makeSidebarResizable(b,y,"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`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,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(),i=this.getFitBounds(),n=Math.max(0,i.width),a=Math.max(0,i.height);if(n<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=n/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(s,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 i=this.gameViewPane||this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.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,i=e.ctrlKey||e.metaKey,n=e.shiftKey;if(i&&e.key==="s"&&!n){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(i&&e.key==="z"&&!n){e.preventDefault(),Ei();return}if(i&&(e.key==="z"&&n||e.key==="y"&&!n)){e.preventDefault(),Ci();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 i=document.querySelector("#apply-current-btn");i&&i.getAttribute("disabled")===null&&i.click()})}updateUnsavedChangesIndicator(){let t=Fe().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let i=this.container.querySelector("#preview-unsaved-star"),n=this.container.querySelector("#preview-save-btn");i&&(i.style.display=t?"inline-block":"none"),n&&(n.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,i;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(i=(t=this.options).onDeviceChange)==null||i.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 i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let s=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=s>0?`${s}!`:"0",a.classList.toggle("has-errors",s>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 i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),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;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 i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(p=>p.id===i);if(!n)return;let a=t.querySelector("[data-compare-slot]"),s=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||!s||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:a,ghost:s,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 i=this.container.querySelector("#rotate-btn");i&&(i.disabled=e==="compare");let n=this.container.querySelector("#scene-toggle");if(n&&(n.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,s;let t=this.compareViewports.get(e);if(!t)return;let i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),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:i}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,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 i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let a=i/e.preset.width,s=n/e.preset.height,o=Math.max(.01,Math.min(a,s));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/i.width,s/i.height),l=i.width*o,c=i.height*o,d=(a-l)/2,p=(s-c)/2;n.clearRect(0,0,a,s),n.drawImage(i,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 i=this.gameViewPane||this.previewContainer;return{width:i.clientWidth-40,height:i.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 Ga(r={}){let e=new yn(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ae();function Ua(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function Dr(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function Ll(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=i?"static":"none",r.interactive=i,i&&(r.cursor=t.draggable?"move":"pointer")}function Nr(r,e){var d,p,u;if(!r||!e)return;let t=e.transform||{};Ll(r,e);let i=t.position||{},n=t.offset||{},a=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),s=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0),o=333,l=111;a+=o,s+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,s,"(raw + 333, +111)"),(d=r.position)!=null&&d.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((p=r.scale)!=null&&p.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let c=t.anchor;if(c&&((u=r.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"&&r.anchor.set(g.x,g.y)}}function Hr(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=Ua(e),i=a=>{var s;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(s=l==null?void 0:l.screenToInstances)==null?void 0:s[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 n=new Map;t.forEach(a=>n.set(a,[a])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>Hr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return i(Ua((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Ua((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,f,m;let s=(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 s;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)?s:null;let d=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[a];return d&&d===o?s: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 s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function Tl(){if(typeof window=="undefined")return;let r=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var a,s,o;let n=r(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(ut(),Ds))]),d=Date.now(),p=/^(data:|blob:)/.test(n)?n:n+(n.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=(s=h==null?void 0:h.get)==null?void 0:s.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 i=oe();Array.isArray(i)&&i.length&&(window.__editableConfig=t,He(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=oe();Array.isArray(i)&&i.length&&(window.__editableConfig=t,He(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))n.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))n.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))n.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))n.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))n.push({path:`start.${a}`,value:s});n.length&&He(n,{silent:!0,persist:!0,emitEvent:!0})}}function vn(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=r;t&&(t.onObjectRebuildRequired=async(a,s)=>{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 Se.create(a,s,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"&&(Tl(),window.applyEditableObjectConfig=(a,s)=>{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,s),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(s);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=Dr(p);Nr(u,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let n={async applyObjectConfig(a,s){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,s),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(s);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=Dr(l);Nr(u,s)}let c=[a];i==null||i(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Hr(a))}};return n.rebuildIndexes(),n}ae();var Gr=lt(require("lottie-web"),1);On(jn);typeof window!="undefined"&&!window.lottie&&(window.lottie=Gr.default);var St=null,Il=async()=>{if(!St){let r=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(r==null?void 0:r["handler.config"])||(r==null?void 0:r["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);St=JSON.parse(i)}else St=JSON.parse(e);return St}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}St=await(await fetch("./handler.config.json")).json()}return St},Ya,ei,Ur,Et,qa,Va;function kl(r){Ya=r.initGame,ei=r.CustomAssets,Ur=r.updateScreenState,Et=r.globalResponsiveMultipliers,qa=r.layout,Va=r.clearResponsiveElements}var wn="web_embed",Qt="https://example.com",Fr={profile_id:wn},qe=null,Ae=null,Zt={width:0,height:0},Pl=!0,Ml=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let r=await Il();Fr={...r.ids||{},profile_id:wn},Qt=r.destination_url||((d=(c=r.export_profiles)==null?void 0:c[wn])==null?void 0:d.destination_url)||Qt,We.init({ids:Fr,profile:wn,destinationUrl:Qt});let e=We.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ae=Ga({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),Br()},onRefresh:Br});let g=Ae.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var w,v,P,I,_,k,j,L,x,S,E,C,A;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(Zt.width=b,Zt.height=y,Ur(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let T=f.view;T&&(T.style.width="100%",T.style.height="100%",T.style.display="block")}catch(T){console.warn("[SCREEN] Error resizing renderer:",T);return}if(t&&m&&qa)try{let T=(w=window.__mainContainer)!=null?w:f.stage,O=(j=(k=(I=window.__tutorialLabel)!=null?I:(P=(v=m.get("label_1"))==null?void 0:v.getDisplayObject)==null?void 0:P.call(v))!=null?k:(_=m.get("label_1"))==null?void 0:_.pixiObject)!=null?j:m.get("label_1"),M=m.get("background_1"),R=(E=(S=(x=window.__background)!=null?x:(L=M==null?void 0:M.getDisplayObject)==null?void 0:L.call(M))!=null?S:M==null?void 0:M.pixiObject)!=null?E:M;if(T){let z=T===f.stage;qa({mainContainer:T,label:O,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:f},t,0,Zt,m,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:Zt.width,height:Zt.height,presetId:(A=(C=h.detail)==null?void 0:C.presetId)!=null?A:null}}))}}catch(T){console.warn("[SCREEN] Error in layout:",T)}}})}let t=await _e("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=ee(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 _e("scene.main"));let i=await Ya(e,t,Qt,Ae);qe=i.app;let n=i.gameObjectManager;window.gameApp=qe,window.gameObjectManager=n;try{window.__liveEditBridge=vn({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:ei})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}Ae&&Ae.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(Et.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(qe,n);async function s(){try{let g=async y=>{let w=y.startsWith("/")?y:`/${y}`,v=await fetch(w,{cache:"no-cache"});if(!v.ok)return null;let P=await v.text();try{return JSON.parse(P)}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,w]of Object.entries(f)){let v=w==null?void 0:w.source;if(typeof v!="string")continue;let P=await g(v),I=P==null?void 0:P.elements;if(!Array.isArray(I))continue;let _=I.map(k=>k==null?void 0:k.instance_id).filter(k=>typeof k=="string");m[y]=_;for(let k of _)b[k]||(b[k]=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(Pl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${Et.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let w=" ".repeat(y);b.children.forEach((v,P)=>{if(v&&v.zIndex===9999){console.log(`${w}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(v&&v.scale){let I=v.scale.x||1,_=v.scale.y||1;v.__originalScale||(v.__originalScale={x:I,y:_},console.log(`${w}[RESPONSIVE] Stored original scale for child[${P}]: ${I.toFixed(3)}, ${_.toFixed(3)}`));let k=v.__originalScale.x*Et.scale,j=v.__originalScale.y*Et.scale;typeof v.scale.set=="function"?v.scale.set(k,j):(v.scale.x=k,v.scale.y=j),console.log(`${w}[RESPONSIVE] Child[${P}] scale: ${I.toFixed(3)}\u2192${v.scale.x.toFixed(3)} (type: ${v.constructor.name})`),m(v,y+1)}else v&&console.log(`${w}[RESPONSIVE] Child[${P}] has no scale (type: ${v.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){Et.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,We.start()},Br=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let r=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(r){let a=((t=r.getDisplayObject)==null?void 0:t.call(r))||r;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=a.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=a.scale.y)!=null?n:1).toFixed(3)}`)}if(Ae){Ae.notifyGameDestroyed();try{Va&&Va()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ae.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),qe){try{qe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}qe=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof ei.resetScene=="function"&&ei.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{_e("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=ee(o)),Ya(a,o,Qt).then(l=>{qe=l.app,window.gameApp=qe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=vn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:ei})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}Ae&&Ae.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{We.start()}catch{}})})},100)},1e3)}};Mi();ae();var Le={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},qr=1.25,Vr={fontFamily:"Inter, system-ui, sans-serif"};var xn=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=`
2576
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var w,v,j,T,O,M,_;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",C=>{if(this.viewMode==="compare")return;let x=C.target.value;this.setDevice(x)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",C=>{let x=C.target.value;this.setTheme(x)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let x=C.dataset.viewToggle;x&&this.setViewMode(x)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(C=>{C.addEventListener("click",()=>{let x=C.dataset.layoutToggle;x&&this.setLayoutMode(x)})});let s=e.querySelector("#scene-toggle");s==null||s.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=C=>{let x=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${C}::${x}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(C,x,S)=>{C&&(C.textContent=x?`${S} On`:`${S} Off`,C.setAttribute("aria-pressed",x?"true":"false"))},u=()=>{let C=window.localStorage.getItem(l("grid_gap")),x=Number(C!=null?C:50);return Number.isFinite(x)?x:50},g=C=>{try{window.localStorage.setItem(l("grid_enabled"),C?"true":"false")}catch{}p(c,C,"Grid");let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:x}}))},h=C=>{try{window.localStorage.setItem(l("play_mode"),C?"true":"false")}catch{}p(d,C,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:C}}))};try{let C=window.localStorage.getItem(l("grid_enabled"))==="true",x=!0;try{window.localStorage.setItem(l("play_mode"),"true")}catch{}if(p(c,C,"Grid"),p(d,x,"Play"),d&&(d.disabled=!0),c){let S=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:C,gap:S}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:x}}))}catch{}c==null||c.addEventListener("click",()=>{let C=c.getAttribute("aria-pressed")==="true";g(!C)}),d==null||d.addEventListener("click",()=>{let C=d.getAttribute("aria-pressed")==="true";h(!C)}),(w=e.querySelector("#rotate-btn"))==null||w.addEventListener("click",()=>this.toggleRotation()),(v=e.querySelector("#zoom-in-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(.1)),(j=e.querySelector("#zoom-out-btn"))==null||j.addEventListener("click",()=>this.adjustUserZoom(-.1)),(T=e.querySelector("#refresh-btn"))==null||T.addEventListener("click",()=>this.refresh()),(O=e.querySelector("#corner-zoom-in-btn"))==null||O.addEventListener("click",()=>this.adjustUserZoom(.1)),(M=e.querySelector("#corner-zoom-out-btn"))==null||M.addEventListener("click",()=>this.adjustUserZoom(-.1)),(_=e.querySelector("#corner-grab-btn"))==null||_.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let f=e.querySelector(".scene-panel.scene-objects"),m=f==null?void 0:f.querySelector("[data-panel-resize-v]");f&&m&&this.makeSidebarResizable(f,m,"left");let b=e.querySelector(".debug-workbench"),y=b==null?void 0:b.querySelector("#workbench-resize-v");b&&y&&this.makeSidebarResizable(b,y,"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`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,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(),i=this.getFitBounds(),n=Math.max(0,i.width),a=Math.max(0,i.height);if(n<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=n/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(s,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 i=this.gameViewPane||this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.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,i=e.ctrlKey||e.metaKey,n=e.shiftKey;if(i&&e.key==="s"&&!n){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(i&&e.key==="z"&&!n){e.preventDefault(),Ei();return}if(i&&(e.key==="z"&&n||e.key==="y"&&!n)){e.preventDefault(),Ci();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 i=document.querySelector("#apply-current-btn");i&&i.getAttribute("disabled")===null&&i.click()})}updateUnsavedChangesIndicator(){let t=Fe().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let i=this.container.querySelector("#preview-unsaved-star"),n=this.container.querySelector("#preview-save-btn");i&&(i.style.display=t?"inline-block":"none"),n&&(n.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,i;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(i=(t=this.options).onDeviceChange)==null||i.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 i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(s=>typeof s=="object"?this.safeStringify(s):String(s)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let s=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=s>0?`${s}!`:"0",a.classList.toggle("has-errors",s>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 i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),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;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 i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(p=>p.id===i);if(!n)return;let a=t.querySelector("[data-compare-slot]"),s=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||!s||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:a,ghost:s,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 i=this.container.querySelector("#rotate-btn");i&&(i.disabled=e==="compare");let n=this.container.querySelector("#scene-toggle");if(n&&(n.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,s;let t=this.compareViewports.get(e);if(!t)return;let i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),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:i}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,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 i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let a=i/e.preset.width,s=n/e.preset.height,o=Math.max(.01,Math.min(a,s));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let a=t.canvas.width,s=t.canvas.height,o=Math.min(a/i.width,s/i.height),l=i.width*o,c=i.height*o,d=(a-l)/2,p=(s-c)/2;n.clearRect(0,0,a,s),n.drawImage(i,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 i=this.gameViewPane||this.previewContainer;return{width:i.clientWidth-40,height:i.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 Ga(r={}){let e=new yn(r);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ae();function Ua(r){try{if(r&&typeof r.keys=="function")return Array.from(r.keys())}catch{}return[]}function Dr(r){var e;return r?((e=r.getDisplayObject)==null?void 0:e.call(r))||r.pixiObject||r:null}function Ll(r,e){if(!r||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);r.eventMode=i?"static":"none",r.interactive=i,i&&(r.cursor=t.draggable?"move":"pointer")}function Nr(r,e){var d,p,u;if(!r||!e)return;let t=e.transform||{};Ll(r,e);let i=t.position||{},n=t.offset||{},a=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),s=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0),o=333,l=111;a+=o,s+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,s,"(raw + 333, +111)"),(d=r.position)!=null&&d.set?r.position.set(a,s):(typeof r.x=="number"&&(r.x=a),typeof r.y=="number"&&(r.y=s)),typeof t.scale=="number"&&((p=r.scale)!=null&&p.set?r.scale.set(t.scale):r.scale&&(r.scale.x=t.scale,r.scale.y=t.scale));let c=t.anchor;if(c&&((u=r.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"&&r.anchor.set(g.x,g.y)}}function Hr(r){if(typeof window=="undefined")return;let e=r==null?void 0:r.objects,t=Ua(e),i=a=>{var s;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(s=l==null?void 0:l.screenToInstances)==null?void 0:s[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 n=new Map;t.forEach(a=>n.set(a,[a])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>Hr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return i(Ua((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Ua((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,f,m;let s=(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 s;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)?s:null;let d=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[a];return d&&d===o?s: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 s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function Tl(){if(typeof window=="undefined")return;let r=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var a,s,o;let n=r(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(ut(),Ds))]),d=Date.now(),p=/^(data:|blob:)/.test(n)?n:n+(n.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=(s=h==null?void 0:h.get)==null?void 0:s.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 i=oe();Array.isArray(i)&&i.length&&(window.__editableConfig=t,He(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=oe();Array.isArray(i)&&i.length&&(window.__editableConfig=t,He(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[a,s]of Object.entries(t.runtime))n.push({path:`runtime.${a}`,value:s});if(t.assets)for(let[a,s]of Object.entries(t.assets))n.push({path:`assets.${a}`,value:s}),typeof s=="string"&&e(a,s);if(t.splash)for(let[a,s]of Object.entries(t.splash))n.push({path:`splash.${a}`,value:s});if(t.loading)for(let[a,s]of Object.entries(t.loading))n.push({path:`loading.${a}`,value:s});if(t.start)for(let[a,s]of Object.entries(t.start))n.push({path:`start.${a}`,value:s});n.length&&He(n,{silent:!0,persist:!0,emitEvent:!0})}}function vn(r){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=r;t&&(t.onObjectRebuildRequired=async(a,s)=>{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 Se.create(a,s,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"&&(Tl(),window.applyEditableObjectConfig=(a,s)=>{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,s),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(s);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=Dr(p);Nr(u,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let n={async applyObjectConfig(a,s){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,s),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(s);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=Dr(l);Nr(u,s)}let c=[a];i==null||i(a,s,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Hr(a))}};return n.rebuildIndexes(),n}ae();var Gr=lt(require("lottie-web"),1);On(jn);typeof window!="undefined"&&!window.lottie&&(window.lottie=Gr.default);var St=null,Il=async()=>{if(!St){let r=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(r==null?void 0:r["handler.config"])||(r==null?void 0:r["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);St=JSON.parse(i)}else St=JSON.parse(e);return St}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}St=await(await fetch("./handler.config.json")).json()}return St},Ya,ei,Ur,Et,qa,Va;function kl(r){Ya=r.initGame,ei=r.CustomAssets,Ur=r.updateScreenState,Et=r.globalResponsiveMultipliers,qa=r.layout,Va=r.clearResponsiveElements}var wn="web_embed",Qt="https://example.com",Fr={profile_id:wn},qe=null,Ae=null,Zt={width:0,height:0},Pl=!0,Ml=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let r=await Il();Fr={...r.ids||{},profile_id:wn},Qt=r.destination_url||((d=(c=r.export_profiles)==null?void 0:c[wn])==null?void 0:d.destination_url)||Qt,We.init({ids:Fr,profile:wn,destinationUrl:Qt});let e=We.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ae=Ga({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),Br()},onRefresh:Br});let g=Ae.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var w,v,j,T,O,M,_,C,x,S,E,I,L;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(Zt.width=b,Zt.height=y,Ur(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let A=f.view;A&&(A.style.width="100%",A.style.height="100%",A.style.display="block")}catch(A){console.warn("[SCREEN] Error resizing renderer:",A);return}if(t&&m&&qa)try{let A=(w=window.__mainContainer)!=null?w:f.stage,P=(_=(M=(T=window.__tutorialLabel)!=null?T:(j=(v=m.get("label_1"))==null?void 0:v.getDisplayObject)==null?void 0:j.call(v))!=null?M:(O=m.get("label_1"))==null?void 0:O.pixiObject)!=null?_:m.get("label_1"),k=m.get("background_1"),R=(E=(S=(x=window.__background)!=null?x:(C=k==null?void 0:k.getDisplayObject)==null?void 0:C.call(k))!=null?S:k==null?void 0:k.pixiObject)!=null?E:k;if(A){let z=A===f.stage;qa({mainContainer:A,label:P,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:f},t,0,Zt,m,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:Zt.width,height:Zt.height,presetId:(L=(I=h.detail)==null?void 0:I.presetId)!=null?L:null}}))}}catch(A){console.warn("[SCREEN] Error in layout:",A)}}})}let t=await _e("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=ee(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 _e("scene.main"));let i=await Ya(e,t,Qt,Ae);qe=i.app;let n=i.gameObjectManager;window.gameApp=qe,window.gameObjectManager=n;try{window.__liveEditBridge=vn({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:ei})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}Ae&&Ae.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(Et.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(qe,n);async function s(){try{let g=async y=>{let w=y.startsWith("/")?y:`/${y}`,v=await fetch(w,{cache:"no-cache"});if(!v.ok)return null;let j=await v.text();try{return JSON.parse(j)}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,w]of Object.entries(f)){let v=w==null?void 0:w.source;if(typeof v!="string")continue;let j=await g(v),T=j==null?void 0:j.elements;if(!Array.isArray(T))continue;let O=T.map(M=>M==null?void 0:M.instance_id).filter(M=>typeof M=="string");m[y]=O;for(let M of O)b[M]||(b[M]=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(Pl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${Et.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let w=" ".repeat(y);b.children.forEach((v,j)=>{if(v&&v.zIndex===9999){console.log(`${w}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(v&&v.scale){let T=v.scale.x||1,O=v.scale.y||1;v.__originalScale||(v.__originalScale={x:T,y:O},console.log(`${w}[RESPONSIVE] Stored original scale for child[${j}]: ${T.toFixed(3)}, ${O.toFixed(3)}`));let M=v.__originalScale.x*Et.scale,_=v.__originalScale.y*Et.scale;typeof v.scale.set=="function"?v.scale.set(M,_):(v.scale.x=M,v.scale.y=_),console.log(`${w}[RESPONSIVE] Child[${j}] scale: ${T.toFixed(3)}\u2192${v.scale.x.toFixed(3)} (type: ${v.constructor.name})`),m(v,y+1)}else v&&console.log(`${w}[RESPONSIVE] Child[${j}] has no scale (type: ${v.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){Et.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,We.start()},Br=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let r=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(r){let a=((t=r.getDisplayObject)==null?void 0:t.call(r))||r;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=a.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=a.scale.y)!=null?n:1).toFixed(3)}`)}if(Ae){Ae.notifyGameDestroyed();try{Va&&Va()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ae.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),qe){try{qe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}qe=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof ei.resetScene=="function"&&ei.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{_e("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=ee(o)),Ya(a,o,Qt).then(l=>{qe=l.app,window.gameApp=qe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=vn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:ei})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}Ae&&Ae.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{We.start()}catch{}})})},100)},1e3)}};Mi();ae();var Le={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},qr=1.25,Vr={fontFamily:"Inter, system-ui, sans-serif"};var xn=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=`
2577
2577
  position: fixed;
2578
2578
  inset: 0;
2579
2579
  display: flex;