handler-playable-sdk 1.0.56 → 1.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{chunk-GQFFLZYV.js → chunk-UQJMU5JM.js} +64 -64
  2. package/dist/cli/brand-dna.mjs +1 -1
  3. package/dist/cli/canva-import.mjs +1 -1
  4. package/dist/cli/cleanup-assets.mjs +1 -1
  5. package/dist/cli/fix-scales.mjs +1 -1
  6. package/dist/cli/index.js +1 -1
  7. package/dist/cli/screen-helper.mjs +1 -1
  8. package/dist/cli/setup-library.mjs +1 -1
  9. package/dist/cli/student-helper/add-logic.mjs +1 -1
  10. package/dist/cli/student-helper/add-object.mjs +1 -1
  11. package/dist/cli/student-helper/arg-parsing.mjs +1 -1
  12. package/dist/cli/student-helper/asset-registry.mjs +1 -1
  13. package/dist/cli/student-helper/bullet-system.mjs +1 -1
  14. package/dist/cli/student-helper/collectable-system.mjs +1 -1
  15. package/dist/cli/student-helper/constants.mjs +1 -1
  16. package/dist/cli/student-helper/drag-snap-couples.mjs +1 -1
  17. package/dist/cli/student-helper/endgame-screen.mjs +1 -1
  18. package/dist/cli/student-helper/fs-io.mjs +1 -1
  19. package/dist/cli/student-helper/logic-defaults.mjs +1 -1
  20. package/dist/cli/student-helper/print-help.mjs +1 -1
  21. package/dist/cli/student-helper/prompts.mjs +1 -1
  22. package/dist/cli/student-helper/scratch-card.mjs +1 -1
  23. package/dist/cli/student-helper/screen-utils.mjs +1 -1
  24. package/dist/cli/student-helper/snippets.mjs +1 -1
  25. package/dist/cli/student-helper/start-screen.mjs +1 -1
  26. package/dist/cli/student-helper/swerve-collect.mjs +1 -1
  27. package/dist/cli/student-helper/tap-destroy.mjs +1 -1
  28. package/dist/cli/student-helper/template-packs.mjs +1 -1
  29. package/dist/cli/student-helper.mjs +1 -1
  30. package/dist/cli/sync-screens.mjs +1 -1
  31. package/dist/cli/validate-assets.mjs +1 -1
  32. package/dist/cli/validate.mjs +1 -1
  33. package/dist/index.cjs +92 -92
  34. package/dist/index.js +1 -1
  35. package/dist/pixi/index.cjs +6 -6
  36. package/dist/pixi/index.js +1 -1
  37. package/dist/three/index.cjs +1 -1
  38. package/dist/three/index.js +1 -1
  39. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var go=Object.create;var mn=Object.defineProperty;var ho=Object.getOwnPropertyDescriptor;var mo=Object.getOwnPropertyNames;var fo=Object.getPrototypeOf,yo=Object.prototype.hasOwnProperty;var Te=(s,e)=>()=>(s&&(e=s(s=0)),e);var Nt=(s,e)=>{for(var t in e)mn(s,t,{get:e[t],enumerable:!0})},ls=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of mo(e))!yo.call(s,i)&&i!==t&&mn(s,i,{get:()=>e[i],enumerable:!(n=ho(e,i))||n.enumerable});return s};var vt=(s,e,t)=>(t=s!=null?go(fo(s)):{},ls(e||!s||!s.__esModule?mn(t,"default",{value:s,enumerable:!0}):t,s)),bo=s=>ls(mn({},"__esModule",{value:!0}),s);var le,vn=Te(()=>{"use strict";le=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()}};le.store=new Map});function Lo(){var s,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(s=document.querySelector("script"))==null?void 0:s.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function To(){try{if(typeof window!="undefined"){let s=await fetch("./build-settings.json");if(s.ok){let e=await s.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function ko(){try{if(typeof window!="undefined"){let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Po(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${V}`),Object.keys(ke).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(ke)),ke;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),ke={...window.INLINE_ASSETS},ke;if(!(V==="publish"&&be!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ke;if(!Bi){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),Bi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ke=await Bi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ke)),ke}function Ui(s){return s===null||typeof s!="object"||(Object.freeze(s),Object.values(s).forEach(e=>Ui(e))),s}function Mo(s=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=s,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,s,e),i.strokeStyle="#000",i.strokeRect(0,0,s,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",s/2,e/2),Pe.Texture.from(n)}function Gi(s,e){Fs.set(s,e)}var Pe,Ns,Hs,at,V,be,He,ke,Bi,Fs,st,wn=Te(()=>{"use strict";Pe=require("pixi.js");vn();Ns=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",Hs=Lo(),at=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,V=Hs?"publish":Ns,be=at==null?void 0:at.assetsInlined;at!=null&&at.buildMode&&(V=at.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${V}`));He=ko();He!=null&&He.buildMode&&(V=He.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${V}`));(He==null?void 0:He.assetsInlined)!==void 0&&(be=He.assetsInlined);To().then(s=>{s!=null&&s.buildMode&&s.buildMode!==V&&(V=s.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${V}`)),(s==null?void 0:s.assetsInlined)!==void 0&&(be=s.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Ns}, Runtime: ${Hs?"publish":"dev"}, Effective: ${V}`);ke={},Bi=null;Fs=new Map;st=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,r=le.get(a);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${V}`),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 Po(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let p=t.path.split("/");if(p.length>=2){let u=p[p.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),V==="publish"&&be!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let d=Fs.get(t.type);if(d)try{let p=await d(t.path,l,e,n);return le.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=Ui(p);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return le.set(a,p),p}catch(p){return this.handleFailure(e,t.type,p)}}static async loadImage(e,t){let n=V==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${V}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await Pe.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 Pe.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Pe.Assets.load(e)}return await Pe.Assets.load(e)}static async loadJSON(e,t){let n=V==="publish",i=n&&be!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${V}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(V==="dev"){let a=t==="image"?Mo():Ui({__placeholder:!0,type:t});return le.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Gi("image",async(s,e)=>{let t=V==="publish",n=t&&be!==!1,i=V==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${V}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Pe.Assets.load(e)}let r=s;return(i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),Pe.Assets.load(e||r)});Gi("json",async(s,e)=>{let t=V==="publish",n=t&&be!==!1,i=V==="brand",a=t&&be===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${V}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=s;if((i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(r);if(!o.ok)throw new Error(`JSON fetch failed: ${s}`);return o.json()})});var Us={};Nt(Us,{AssetTextures:()=>we,initAssetTextures:()=>Wi});function Wi(s,e){Bs.init(s,e),typeof window!="undefined"&&(window.__AssetTextures=we)}var Vi,Bs,we,Et=Te(()=>{"use strict";wn();Vi=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var r;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let d=async()=>{var p;try{let u=(p=l.identity)==null?void 0:p.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await st.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(d()):a.push(d())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,d,p;try{let u=(d=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:d.call(c,o);return!!((p=u==null?void 0:u.render)!=null&&p.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),r>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},r)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},Bs=new Vi,we=new Proxy(Bs,{get(s,e){return e in s&&typeof s[e]=="function"?s[e].bind(s):s.get(e)},set(s,e,t){return s.set(e,t),!0}})});var Ue={};Nt(Ue,{applyConfigOverride:()=>se,applyConfigOverrides:()=>Fe,applyConfigsToDisk:()=>Rn,clearConfigOverrides:()=>de,clearConfigOverridesForObject:()=>Ks,configOverrideManager:()=>Xs,deepClone:()=>J,exportConfigsAsJSON:()=>ot,getConfigOverrides:()=>ie,getConfigStateSummary:()=>Be,getOverrideMode:()=>Vt,redoLastConfigChange:()=>On,removeConfigOverride:()=>Wt,resetToApplied:()=>Yt,resetToOriginal:()=>zn,setOverrideMode:()=>ta,trackObjectCreation:()=>Js,trackObjectDeletion:()=>Zs,undoLastConfigChange:()=>jn});function Mn(){return typeof window=="undefined"?null:window.__editableConfig||null}function Zi(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Ji(s,e){var t,n;if(!s)return null;try{if(s instanceof Map)return(t=s.get(e))!=null?t:null;if(typeof s=="object")return(n=s[e])!=null?n:null}catch{}return null}function il(s,e,t){if(s){if(s instanceof Map){s.set(e,t);return}typeof s=="object"&&(s[e]=t)}}function Vs(s,e){for(let t of e)qt(s,t.path,t.value)}function In(s){var o;if(typeof window=="undefined")return;let e=Mn();if(!e)return;let t=Zi(),n=(o=t?Ji(t.objects,s):null)!=null?o:Ji(e.objects,s);if(!n)return;let i=J(n),a=ie().filter(l=>l.objectId===s);try{Vs(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",s,l);return}il(e.objects,s,i);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(s,i)}catch{}}function Qi(){var i;if(typeof window=="undefined")return;let s=Mn();if(!(s!=null&&s.engine))return;let e=Zi(),t=J(((i=e==null?void 0:e.engine)!=null?i:s.engine)||{}),n=ie().filter(a=>!a.objectId&&!a.sceneId);try{Vs(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=s.engine;for(let r of Object.keys(a))r in t||delete a[r];for(let[r,o]of Object.entries(t))a[r]=o}catch{s.engine=t}}function al(){if(typeof window=="undefined")return"unknown";let s=window;return typeof s.__HANDLER_PROJECT_ID=="string"?s.__HANDLER_PROJECT_ID:"handler-default"}function Ws(){return`handler_preview_config_overrides::${al()}`}function sl(){if(typeof window=="undefined")return[];try{let s=window.localStorage.getItem(Ws());if(!s)return[];let e=JSON.parse(s);return Array.isArray(e)?e:[]}catch{return[]}}function _n(s){if(typeof window!="undefined")try{window.localStorage.setItem(Ws(),JSON.stringify(s))}catch{}}function Vt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function ta(s){if(typeof window!="undefined"){window.__enableConfigOverrides=s;try{window.localStorage.setItem(Ys,s?"true":"false")}catch{}}}function se(s,e={}){var u,g;let{objectId:t,path:n,value:i}=s,{silent:a=!1,persist:r=!0,emitEvent:o=!0}=e,l=Mn();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let d;try{d=Qs(c,n),qt(c,n,i)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:n,oldValue:d,newValue:i,ts:Date.now()}),h.length>ea&&h.shift(),window.__configChangeRedo=[]}if(r){let h=ie(),m=h.findIndex(f=>f.objectId===t&&f.sceneId===s.sceneId&&f.path===n);m>=0?h[m].value=i:h.push(s),window.__configOverrides=h,_n(h),Vt()||ta(!0)}a||console.log("[CONFIG] Applied override:",s),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:s}))}function Fe(s,e={}){let t=e.emitEvent!==!1,n=[];for(let i of s)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),se(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:s.length}}))}}function de(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],_n([]),console.log("[CONFIG] Cleared all overrides")}function Ks(s){let e=ie().filter(n=>n.objectId!==s);window.__configOverrides=e,_n(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==s),In(s),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:s}}))}function Wt(s,e){let t=ie().filter(i=>i.objectId!==s||i.path!==e);window.__configOverrides=t,_n(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==s||i.path!==e),s?In(s):Qi(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:s,path:e}}))}function ie(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=sl()),window.__configOverrides||[])}function jn(){var a;if(typeof window=="undefined")return!1;let s=window.__configChanges||[];if(s.length===0)return!1;let e=s.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:r}=e.metadata||{};return e.objectId&&r&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:r})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:r,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&r&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:r,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Zi(),i=!1;if(n){let r=e.objectId?Ji(n.objects,e.objectId):n.engine;if(r){let o=Qs(r,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?Wt(e.objectId,e.path):(se({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?In(e.objectId):Qi()),console.log("[CONFIG] Undo:",e.path),!0}function On(){var n;if(typeof window=="undefined")return!1;let s=window.__configChangeRedo||[];if(s.length===0)return!1;let e=s.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},r=e.newValue;return e.objectId&&i&&r&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=r==null?void 0:r.identity)==null?void 0:n.id),config:r})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(r=>console.error("[CONFIG] Failed to delete object on redo:",r)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),se({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?In(e.objectId):Qi(),console.log("[CONFIG] Redo:",e.path),!0}function Js(s,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>ea&&n.shift(),console.log("[CONFIG] Tracked object creation:",s)}function Zs(s,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>ea&&n.shift(),console.log("[CONFIG] Tracked object deletion:",s)}function qt(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(r=a[o])!=null?r:{},a=a[o]}a[i]=t}function Qs(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function J(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(s instanceof Set)return new Set([...s].map(t=>J(t)));if(ArrayBuffer.isView(s))return s.slice();if(s instanceof Array)return s.map(t=>J(t));if(s instanceof Map){let t=new Map;return s.forEach((n,i)=>t.set(i,J(n))),t}let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=J(s[t]));return e}function ot(){let s=window.__editableConfigBaseline;if(!s){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return qs(e)}return qs(s)}function qs(s){let e={objects:{},scenes:{},engine:J(s.engine||{})},t=s.objects;if(t instanceof Map)t.forEach((a,r)=>{e.objects[r]=J(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=J(t[a]);let n=s.scenes;if(n instanceof Map)n.forEach((a,r)=>{e.scenes[r]=J(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=J(n[a]);let i=ie();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),qt(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),qt(e.scenes[a.sceneId],a.path,a.value)):qt(e.engine,a.path,a.value);return e}function Be(){let s=ie(),e=new Set;for(let t of s)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:s.length,hasChanges:s.length>0,overrides:s}}async function Rn(s){let e=ot(),t={};for(let[i,a]of Object.entries(e.objects)){let r=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),r&&typeof r=="object"&&(r.identity||(r.identity={}),r.identity.id=o),t[`objects/${o}.json`]=r}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let r=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${r}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:ie().length>0,versionName:s})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}de();try{let i=Mn();i&&(window.__editableConfigBaseline=J(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Yt(){de(),window.location.reload()}async function zn(){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"}`)}de(),window.location.reload()}var Ys,ea,Xs,Z=Te(()=>{"use strict";Ys="handler_preview_override_mode";if(typeof window!="undefined"){let s=window.localStorage.getItem(Ys);window.__enableConfigOverrides=s===null?!0:s==="true"}ea=500;Xs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function rl(s,e){try{if(typeof s=="object"&&s!==null)return s;if(typeof s!="string")return null;if(s.startsWith("data:")){let n=s.indexOf(",");if(n===-1)return null;let i=s.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=s.slice(n+1),r=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(r)}let t=s.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(s):null}catch{return null}}function ol(s){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=s.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let r=e[a];if(r){let o=rl(r,a);if(o!==null)return o}}return null}async function Kt(s){if(na.has(s)&&!ia)return console.log(`[CONFIG] Using cached config for: "${s}"`),na.get(s);if(console.log(`[CONFIG] loadConfigFile called with: "${s}", MODE: ${U.toUpperCase()}, CACHE: ${ia?"DISABLED":"ENABLED"}`),U==="publish"){let n=ol(s);return n?(console.log(`[CONFIG] \u2713 Loaded ${s} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${s} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}U==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${s}"`);let e;U==="brand"?e=[`./${s.split("/").pop()||s}`,`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=ia?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let r=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${s} via ${i}`,r),r}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${U}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${s}; using defaults`),{}})();return na.set(s,t),t}async function $n(){console.log("[CONFIG] Loading component schemas...");let s=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of s)try{let n=U==="publish"||U==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await Kt(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${U==="publish"||U==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Ge(s){console.log(`[CONFIG] Loading object config: ${s}`);let e=U==="publish"||U==="brand"?`${s}.json`:`configs/objects/${s}.json`;return await Kt(e)}async function Dn(s){let e=new Map;if(s.objects&&Array.isArray(s.objects)){for(let t of s.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await Ge(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await Ge(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await Ge(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function Nn(){console.log("[CONFIG] Loading engine configs...");let s=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(s.map(n=>{let i=`engine.${n}.json`,a=U==="publish"||U==="brand"?i:`configs/engine/${i}`;return Kt(a)})),t=Object.fromEntries(s.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(s.map(n=>{var r;let i=(r=t[n])!=null?r:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function aa(){return await Kt(U==="publish"||U==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Hn(s="scene.main"){console.log(`[CONFIG] Loading scene config: ${s}`);let e=U==="publish"||U==="brand"?`${s}.json`:`configs/scenes/${s}.json`;return await Kt(e)}function Ct(s,e){let t=[];if(!s.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])s.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(s)){if(i==="identity")continue;let r=e.get(i);if(r&&a&&typeof a=="object"){let o=a;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let d=o[l];if(d!==void 0&&c&&typeof c=="object"){let p=c;typeof d=="number"&&(p.min!==void 0&&d<p.min&&t.push(`${i}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${i}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function lt(s,e){let t={...s},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function pe(s,e,t,n){return typeof s!="number"||!Number.isFinite(s)?e:Math.min(Math.max(s,t),n)}function tr(s,e){if(Array.isArray(s))return{x:pe(s[0],e.x,-2e3,2e3),y:pe(s[1],e.y,-2e3,2e3)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:pe(t,e.x,-2e3,2e3),y:pe(n,e.y,-2e3,2e3)}}function ll(s,e){if(Array.isArray(s))return{x:pe(s[0],e.x,0,1),y:pe(s[1],e.y,0,1)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:pe(t,e.x,0,1),y:pe(n,e.y,0,1)}}function cl(s){if(Array.isArray(s))return{x:pe(s[0],.5,-10,10),y:pe(s[1],.5,-10,10)};if(s&&typeof s=="object"){let{x:e,y:t}=s;return{x:pe(e,.5,-10,10),y:pe(t,.5,-10,10)}}return typeof s=="string"?s:null}async function Oe(s="scene.main",e){var l,c,d,p,u,g,h,m,f,y,b,v,S,L;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await $n(),n=ie();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await Hn(s);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await Nn();console.log("[CONFIG] Loading object configs...");let r=await Dn(i);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[M,O]of r.entries()){let w=lt(O,t),P=Ct(w,t);P.valid||console.warn(`Object ${M} validation errors:`,P.errors),(c=w.transform)!=null&&c.position&&(w.transform.position=tr(w.transform.position,{x:0,y:0})),(d=w.transform)!=null&&d.offset&&(w.transform.offset=tr(w.transform.offset,{x:0,y:0})),((p=w.transform)==null?void 0:p.anchor)!==void 0&&(w.transform.anchor=cl(w.transform.anchor)),((u=w.transform)==null?void 0:u.position_ratio)!==void 0&&w.transform.position_ratio!==null&&(w.transform.position_ratio=ll(w.transform.position_ratio,{x:.5,y:.5})),r.set(M,w)}if(e){if(e.objects)for(let[M,O]of e.objects.entries())r.set(M,O);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=lt(o,t))),n.length>0&&Vt()&&Fe(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((m=a.runtime)!=null?m:{}),assets:Object.keys((f=a.assets)!=null?f:{}),splash:Object.keys((y=a.splash)!=null?y:{}),loading:Object.keys((b=a.loading)!=null?b:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((S=a.tutorial)!=null?S:{}),endgame:Object.keys((L=a.endgame)!=null?L:{})},scene:i.scene_id||"unknown"}),o}function sa(s){var t,n,i,a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,S,L,M,O,w,P,_,T,I,C,A,E,x,j,k;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[R,z]of s.objects.entries()){let N=((t=z.identity)==null?void 0:t.id)||R;N.includes("character")&&(e.gameplay.character_pos=((n=z.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=z.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((r=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=z.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((d=(c=z.gameplay)==null?void 0:c.tuning)==null?void 0:d.relief_speed)||.22),(N.includes("gun")||N.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)||{}),N.includes("diamond")&&(e.gameplay.diamond=z),N.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=((m=z.transform)==null?void 0:m.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=z.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((y=z.effects)==null?void 0:y.physics_chunks)||{},e.gameplay.melting_particles=((b=z.effects)==null?void 0:b.melting_particles)||{},e.gameplay.hard_ice=z.hard_ice||{}),N.includes("water")&&(e.gameplay.water_drops=z),N.includes("crack")&&(e.gameplay.crack=z),N.includes("hand")&&(e.gameplay.hand=((v=z.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((S=z.transform)==null?void 0:S.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((L=z.transform)==null?void 0:L.scale)||1.5),N.includes("hazard")&&(e.gameplay.hazard=((M=z.gameplay)==null?void 0:M.tuning)||{},e.gameplay.danger_pos=((O=z.transform)==null?void 0:O.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((P=(w=z.gameplay)==null?void 0:w.tuning)==null?void 0:P.danger_pulse)||{},e.gameplay.hazard_height=((T=(_=z.gameplay)==null?void 0:_.tuning)==null?void 0:T.hazard_height)||140)}return e.gameplay.timeline=((I=s.engine.runtime)==null?void 0:I.timeline)||{},e.gameplay.drag_surface=((C=s.engine.runtime)==null?void 0:C.drag_surface)||{},e.gameplay.background=((A=s.engine.runtime)==null?void 0:A.background)||{},e.gameplay.ui_styles=((E=s.engine.runtime)==null?void 0:E.ui_styles)||{},e.gameplay.label_pulse=((x=s.engine.runtime)==null?void 0:x.label_pulse)||{},e.ui=((j=s.engine.runtime)==null?void 0:j.ui)||{},e.theme=((k=s.engine.runtime)==null?void 0:k.theme)||{},e.assets=s.engine.assets||{},e}var er,U,na,ia,ra=Te(()=>{"use strict";Z();er=null,U="dev";if(typeof window!="undefined"){let s=window.__BUILD_SETTINGS__;if(s!=null&&s.buildMode)er=s,U=s.buildMode,console.log("[CONFIG] Loaded inline build settings:",s,"buildMode:",U);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);er=t,U=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",U)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",U)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",U);na=new Map,ia=U==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function oa(s,e){let t=[];function n(i,a,r=""){if(i!==a){if(typeof i!=typeof a){t.push(`${r}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=r?`${r}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(s,e),t}function la(s,e,t,n){let i={...t};for(let[a,r]of n.entries())i[a]&&r.defaults&&(i[a]={...r.defaults,...i[a]});return i}var Xt,ct,ca=Te(()=>{"use strict";Xt=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},ct=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),r=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==r&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==r){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,r)}else o||this.fileHashes.set(e,r)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function pa(s){if(typeof window=="undefined")return;let e=typeof da!="undefined"&&!!da.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,r=null;if(t){r=new ct;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var y,b;if(!r)return;let m=new Set;m.add("configs/engine/engine.runtime.json"),m.add("configs/engine/engine.assets.json"),m.add("configs/engine/engine.splash.json"),m.add("configs/scenes/scene.main.json");let f=(b=(y=h.scene)==null?void 0:y.objects)!=null?b:[];for(let v of f)v!=null&&v.object_config&&m.add(`configs/objects/${v.object_config}.json`);for(let v of o)m.has(v)||r.unwatch(v);for(let v of m)o.has(v)||r.watch(v,S=>g(S));o=m},c=new Set,d=!1,p=async h=>{let m=await Ge(h),f=lt(m,s.activeConfig.schemas),y=Ct(f,s.activeConfig.schemas);y.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,y.errors),await s.liveEditBridge.applyObjectConfig(h,f)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){s.audioSystem.destroy();let m=await Oe("scene.main");s.setActiveConfig(m),s.gameObjectManager.updateConfig(m),s.CustomAssets.updateConfig(m),await s.CustomAssets.ready();let f=s.createAudioSystem(m);s.setAudioSystem(f),window.__audioSystem=f,await f.start(),s.liveEditBridge.rebuildIndexes(),l(m),console.log(`[GAME] Hot-reload complete (${h})`)}else{let m=Array.from(c);c.clear();for(let f of m)await p(f);console.log(`[GAME] Hot-reload updated objects: ${m.join(", ")}`)}}catch(m){console.warn("[GAME] Hot-reload failed:",m)}finally{a=!1,d=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):d=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(h.type)},120)}e&&da.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(s.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var da,nr=Te(()=>{"use strict";ca();ra();da={}});var ir={};Nt(ir,{ConfigWatcher:()=>ct,DefaultReloadStrategy:()=>Xt,applyDefaults:()=>lt,diffConfigs:()=>oa,loadAllObjectConfigs:()=>Dn,loadComponentSchemas:()=>$n,loadEngineConfig:()=>Nn,loadGamePromptConfig:()=>aa,loadObjectCentricConfig:()=>Oe,loadObjectConfig:()=>Ge,loadSceneConfig:()=>Hn,rehydrateObject:()=>la,setupHotReload:()=>pa,toLegacyFormat:()=>sa,validateObjectConfig:()=>Ct});var Fn=Te(()=>{"use strict";ra();ca();nr()});var Gr={};Nt(Gr,{AssetEditorModal:()=>Ga});var Ga,qa=Te(()=>{"use strict";Ga=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
1
+ "use strict";var ao=Object.create;var sn=Object.defineProperty;var so=Object.getOwnPropertyDescriptor;var ro=Object.getOwnPropertyNames;var oo=Object.getPrototypeOf,lo=Object.prototype.hasOwnProperty;var Te=(s,e)=>()=>(s&&(e=s(s=0)),e);var Pt=(s,e)=>{for(var t in e)sn(s,t,{get:e[t],enumerable:!0})},es=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ro(e))!lo.call(s,i)&&i!==t&&sn(s,i,{get:()=>e[i],enumerable:!(n=so(e,i))||n.enumerable});return s};var ct=(s,e,t)=>(t=s!=null?ao(oo(s)):{},es(e||!s||!s.__esModule?sn(t,"default",{value:s,enumerable:!0}):t,s)),co=s=>es(sn({},"__esModule",{value:!0}),s);var pe,cn=Te(()=>{"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 bo(){var s,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(s=document.querySelector("script"))==null?void 0:s.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function vo(){try{if(typeof window!="undefined"){let s=await fetch("./build-settings.json");if(s.ok){let e=await s.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function wo(){try{if(typeof window!="undefined"){let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function xo(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${q}`),Object.keys(ke).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(ke)),ke;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),ke={...window.INLINE_ASSETS},ke;if(!(q==="publish"&&we!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ke;if(!Oi){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),Oi=(async()=>{try{try{let a=await import(e+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let i=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(i)try{let a=i[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ke=await Oi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ke)),ke}function Ri(s){return s===null||typeof s!="object"||(Object.freeze(s),Object.values(s).forEach(e=>Ri(e))),s}function So(s=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=s,n.height=e;let i=n.getContext("2d");return i.fillStyle=`#${t.toString(16).padStart(6,"0")}`,i.fillRect(0,0,s,e),i.strokeStyle="#000",i.strokeRect(0,0,s,e),i.fillStyle="#fff",i.font="10px sans-serif",i.textAlign="center",i.fillText("MISSING",s/2,e/2),Pe.Texture.from(n)}function zi(s,e){js.set(s,e)}var Pe,Ms,_s,Je,q,we,Ne,ke,Oi,js,Ze,dn=Te(()=>{"use strict";Pe=require("pixi.js");cn();Ms=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",_s=bo(),Je=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,q=_s?"publish":Ms,we=Je==null?void 0:Je.assetsInlined;Je!=null&&Je.buildMode&&(q=Je.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${q}`));Ne=wo();Ne!=null&&Ne.buildMode&&(q=Ne.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${q}`));(Ne==null?void 0:Ne.assetsInlined)!==void 0&&(we=Ne.assetsInlined);vo().then(s=>{s!=null&&s.buildMode&&s.buildMode!==q&&(q=s.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${q}`)),(s==null?void 0:s.assetsInlined)!==void 0&&(we=s.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${Ms}, Runtime: ${_s?"publish":"dev"}, Effective: ${q}`);ke={},Oi=null;js=new Map;Ze=class{static async load(e,t,n,i){let a=`${e}:${t.path}`,r=pe.get(a);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${q}`),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 xo(),l=o[e];if(!l&&i&&(l=o[i],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${i}`)),!l&&t.path){let p=t.path.split("/");if(p.length>=2){let u=p[p.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),q==="publish"&&we!==!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=js.get(t.type);if(d)try{let p=await d(t.path,l,e,n);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=Ri(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 n=q==="publish",i=n&&we!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${q}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await Pe.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 Pe.Assets.load(t)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Pe.Assets.load(e)}return await Pe.Assets.load(e)}static async loadJSON(e,t){let n=q==="publish",i=n&&we!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${q}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}let a=await fetch(e);if(!a.ok)throw new Error(`JSON fetch failed: ${e}`);return a.json()}static handleFailure(e,t,n){if(q==="dev"){let a=t==="image"?So():Ri({__placeholder:!0,type:t});return pe.set(e+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};zi("image",async(s,e)=>{let t=q==="publish",n=t&&we!==!1,i=q==="brand",a=t&&we===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${q}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return Pe.Assets.load(e)}let r=s;return(i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),Pe.Assets.load(e||r)});zi("json",async(s,e)=>{let t=q==="publish",n=t&&we!==!1,i=q==="brand",a=t&&we===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${q}, isPublishMode: ${t}, isBrandMode: ${i}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${s}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=s;if((i||a)&&s&&!s.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=s,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${s}" as-is`)):(r=`assets/${s}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${s}" -> "${r}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(r);if(!o.ok)throw new Error(`JSON fetch failed: ${s}`);return o.json()})});var Rs={};Pt(Rs,{AssetTextures:()=>Se,initAssetTextures:()=>Ni});function Ni(s,e){Os.init(s,e),typeof window!="undefined"&&(window.__AssetTextures=Se)}var Di,Os,Se,gt=Te(()=>{"use strict";dn();Di=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var r;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),i=[],a=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let d=async()=>{var p;try{let u=(p=l.identity)==null?void 0:p.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await Ze.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?i.push(d()):a.push(d())}i.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(i),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let i=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,d,p;try{let u=(d=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:d.call(c,o);return!!((p=u==null?void 0:u.render)!=null&&p.asset)}catch{return!1}});if(i.length===0)return;this.ready().catch(()=>{});let a=()=>i.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),r>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:i}),o())},r)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},Os=new Di,Se=new Proxy(Os,{get(s,e){return e in s&&typeof s[e]=="function"?s[e].bind(s):s.get(e)},set(s,e,t){return s.set(e,t),!0}})});var Be={};Pt(Be,{applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>An,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Fs,configOverrideManager:()=>Bs,deepClone:()=>ee,exportConfigsAsJSON:()=>et,getConfigOverrides:()=>re,getConfigStateSummary:()=>Fe,getOverrideMode:()=>zt,redoLastConfigChange:()=>Cn,removeConfigOverride:()=>$t,resetToApplied:()=>Dt,resetToOriginal:()=>Ln,setOverrideMode:()=>Wi,trackObjectCreation:()=>Gs,trackObjectDeletion:()=>Us,undoLastConfigChange:()=>En});function wn(){return typeof window=="undefined"?null:window.__editableConfig||null}function Ui(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function Gi(s,e){var t,n;if(!s)return null;try{if(s instanceof Map)return(t=s.get(e))!=null?t:null;if(typeof s=="object")return(n=s[e])!=null?n:null}catch{}return null}function Ko(s,e,t){if(s){if(s instanceof Map){s.set(e,t);return}typeof s=="object"&&(s[e]=t)}}function Ds(s,e){for(let t of e)Rt(s,t.path,t.value)}function xn(s){var o;if(typeof window=="undefined")return;let e=wn();if(!e)return;let t=Ui(),n=(o=t?Gi(t.objects,s):null)!=null?o:Gi(e.objects,s);if(!n)return;let i=ee(n),a=re().filter(l=>l.objectId===s);try{Ds(i,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",s,l);return}Ko(e.objects,s,i);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(s,i)}catch{}}function qi(){var i;if(typeof window=="undefined")return;let s=wn();if(!(s!=null&&s.engine))return;let e=Ui(),t=ee(((i=e==null?void 0:e.engine)!=null?i:s.engine)||{}),n=re().filter(a=>!a.objectId&&!a.sceneId);try{Ds(t,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=s.engine;for(let r of Object.keys(a))r in t||delete a[r];for(let[r,o]of Object.entries(t))a[r]=o}catch{s.engine=t}}function Xo(){if(typeof window=="undefined")return"unknown";let s=window;return typeof s.__HANDLER_PROJECT_ID=="string"?s.__HANDLER_PROJECT_ID:"handler-default"}function Ns(){return`handler_preview_config_overrides::${Xo()}`}function Jo(){if(typeof window=="undefined")return[];try{let s=window.localStorage.getItem(Ns());if(!s)return[];let e=JSON.parse(s);return Array.isArray(e)?e:[]}catch{return[]}}function Sn(s){if(typeof window!="undefined")try{window.localStorage.setItem(Ns(),JSON.stringify(s))}catch{}}function zt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Wi(s){if(typeof window!="undefined"){window.__enableConfigOverrides=s;try{window.localStorage.setItem(Hs,s?"true":"false")}catch{}}}function le(s,e={}){var u,g;let{objectId:t,path:n,value:i}=s,{silent:a=!1,persist:r=!0,emitEvent:o=!0}=e,l=wn();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:i});let d;try{d=qs(c,n),Rt(c,n,i)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:i},h);return}if(e.trackHistory!==!1){window.__configChanges=window.__configChanges||[];let h=window.__configChanges;h.push({objectId:t,path:n,oldValue:d,newValue:i,ts:Date.now()}),h.length>Vi&&h.shift(),window.__configChangeRedo=[]}if(r){let h=re(),m=h.findIndex(f=>f.objectId===t&&f.sceneId===s.sceneId&&f.path===n);m>=0?h[m].value=i:h.push(s),window.__configOverrides=h,Sn(h),zt()||Wi(!0)}a||console.log("[CONFIG] Applied override:",s),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:s}))}function He(s,e={}){let t=e.emitEvent!==!1,n=[];for(let i of s)i!=null&&i.objectId&&typeof i.objectId=="string"&&n.push(i.objectId),le(i,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let i=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:i,count:s.length}}))}}function ge(){window.__configOverrides=[],window.__configChanges=[],window.__configChangeRedo=[],Sn([]),console.log("[CONFIG] Cleared all overrides")}function Fs(s){let e=re().filter(n=>n.objectId!==s);window.__configOverrides=e,Sn(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==s),xn(s),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:s}}))}function $t(s,e){let t=re().filter(i=>i.objectId!==s||i.path!==e);window.__configOverrides=t,Sn(t);let n=window.__configChanges||[];window.__configChanges=n.filter(i=>i.objectId!==s||i.path!==e),s?xn(s):qi(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:s,path:e}}))}function re(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Jo()),window.__configOverrides||[])}function En(){var a;if(typeof window=="undefined")return!1;let s=window.__configChanges||[];if(s.length===0)return!1;let e=s.pop();window.__configChangeRedo=window.__configChangeRedo||[];let t=window.__configChangeRedo;if(e.changeType==="object_create"){let{screenId:r}=e.metadata||{};return e.objectId&&r&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:r})}).catch(o=>console.error("[CONFIG] Failed to delete object on undo:",o)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Deleted object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:r,objectConfigId:o}=e.metadata||{},l=e.oldValue;return e.objectId&&r&&l&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:r,instanceId:e.objectId,objectConfigId:o||((a=l==null?void 0:l.identity)==null?void 0:a.id),config:l})}).catch(c=>console.error("[CONFIG] Failed to recreate object on undo:",c)),t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Undo: Recreated object",e.objectId),!0}t.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType});let n=Ui(),i=!1;if(n){let r=e.objectId?Gi(n.objects,e.objectId):n.engine;if(r){let o=qs(r,e.path);JSON.stringify(o)===JSON.stringify(e.oldValue)&&(i=!0)}}return i?$t(e.objectId,e.path):(le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xn(e.objectId):qi()),console.log("[CONFIG] Undo:",e.path),!0}function Cn(){var n;if(typeof window=="undefined")return!1;let s=window.__configChangeRedo||[];if(s.length===0)return!1;let e=s.pop();if(e.changeType==="object_create"){let{screenId:i,objectConfigId:a}=e.metadata||{},r=e.newValue;return e.objectId&&i&&r&&fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:i,instanceId:e.objectId,objectConfigId:a||((n=r==null?void 0:r.identity)==null?void 0:n.id),config:r})}).catch(l=>console.error("[CONFIG] Failed to recreate object on redo:",l)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Recreated object",e.objectId),!0}if(e.changeType==="object_delete"){let{screenId:i}=e.metadata||{};return e.objectId&&i&&fetch("/api/objects/delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e.objectId,screenId:i})}).catch(r=>console.error("[CONFIG] Failed to delete object on redo:",r)),window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType,metadata:e.metadata}),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[CONFIG] Redo: Deleted object",e.objectId),!0}return window.__configChanges=window.__configChanges||[],window.__configChanges.push({objectId:e.objectId,path:e.path,oldValue:e.newValue,newValue:e.oldValue,ts:Date.now(),changeType:e.changeType}),le({objectId:e.objectId,path:e.path,value:e.oldValue},{trackHistory:!1,persist:!0,emitEvent:!0}),e.objectId?xn(e.objectId):qi(),console.log("[CONFIG] Redo:",e.path),!0}function Gs(s,e,t){var i;if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_create__",oldValue:null,newValue:t,ts:Date.now(),changeType:"object_create",metadata:{screenId:e,objectConfigId:(i=t==null?void 0:t.identity)==null?void 0:i.id}}),window.__configChangeRedo=[],n.length>Vi&&n.shift(),console.log("[CONFIG] Tracked object creation:",s)}function Us(s,e,t){if(typeof window=="undefined")return;window.__configChanges=window.__configChanges||[];let n=window.__configChanges;n.push({objectId:s,path:"__object_delete__",oldValue:t,newValue:null,ts:Date.now(),changeType:"object_delete",metadata:{screenId:e}}),window.__configChangeRedo=[],n.length>Vi&&n.shift(),console.log("[CONFIG] Tracked object deletion:",s)}function Rt(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);a[o]=(r=a[o])!=null?r:{},a=a[o]}a[i]=t}function qs(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function ee(s){if(s===null||typeof s!="object")return s;if(s instanceof Date)return new Date(s.getTime());if(s instanceof Set)return new Set([...s].map(t=>ee(t)));if(ArrayBuffer.isView(s))return s.slice();if(s instanceof Array)return s.map(t=>ee(t));if(s instanceof Map){let t=new Map;return s.forEach((n,i)=>t.set(i,ee(n))),t}let e={};for(let t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=ee(s[t]));return e}function et(){let s=window.__editableConfigBaseline;if(!s){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return $s(e)}return $s(s)}function $s(s){let e={objects:{},scenes:{},engine:ee(s.engine||{})},t=s.objects;if(t instanceof Map)t.forEach((a,r)=>{e.objects[r]=ee(a)});else if(t&&typeof t=="object")for(let a in t)e.objects[a]=ee(t[a]);let n=s.scenes;if(n instanceof Map)n.forEach((a,r)=>{e.scenes[r]=ee(a)});else if(n&&typeof n=="object")for(let a in n)e.scenes[a]=ee(n[a]);let i=re();for(let a of i)a.objectId?(e.objects[a.objectId]||(e.objects[a.objectId]={}),Rt(e.objects[a.objectId],a.path,a.value)):a.sceneId?(e.scenes[a.sceneId]||(e.scenes[a.sceneId]={}),Rt(e.scenes[a.sceneId],a.path,a.value)):Rt(e.engine,a.path,a.value);return e}function Fe(){let s=re(),e=new Set;for(let t of s)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:s.length,hasChanges:s.length>0,overrides:s}}async function An(s){let e=et(),t={};for(let[i,a]of Object.entries(e.objects)){let r=a,o=i;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${i}`),r&&typeof r=="object"&&(r.identity||(r.identity={}),r.identity.id=o),t[`objects/${o}.json`]=r}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[i,a]of Object.entries(e.scenes)){let r=i.startsWith("scene.")?i:`scene.${i}`;t[`scenes/${r}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:re().length>0,versionName:s})});if(!n.ok){let i=await n.json();throw new Error(`Apply failed: ${i.error||"Unknown error"}`)}ge();try{let i=wn();i&&(window.__editableConfigBaseline=ee(i))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Dt(){ge(),window.location.reload()}async function Ln(){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 Hs,Vi,Bs,te=Te(()=>{"use strict";Hs="handler_preview_override_mode";if(typeof window!="undefined"){let s=window.localStorage.getItem(Hs);window.__enableConfigOverrides=s===null?!0:s==="true"}Vi=500;Bs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[],window.__configChangeRedo=[]}}});function Zo(s,e){try{if(typeof s=="object"&&s!==null)return s;if(typeof s!="string")return null;if(s.startsWith("data:")){let n=s.indexOf(",");if(n===-1)return null;let i=s.slice(0,n);if(!i.includes("application/json")&&!i.includes("text/plain"))return null;let a=s.slice(n+1),r=i.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(r)}let t=s.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(s):null}catch{return null}}function Qo(s){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=s.replace(/^\.\/+/,""),n=t.split("/").pop()||t,i=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of i){let r=e[a];if(r){let o=Zo(r,a);if(o!==null)return o}}return null}async function Nt(s){if(Yi.has(s)&&!Ki)return console.log(`[CONFIG] Using cached config for: "${s}"`),Yi.get(s);if(console.log(`[CONFIG] loadConfigFile called with: "${s}", MODE: ${G.toUpperCase()}, CACHE: ${Ki?"DISABLED":"ENABLED"}`),G==="publish"){let n=Qo(s);return n?(console.log(`[CONFIG] \u2713 Loaded ${s} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${s} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}G==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${s}"`);let e;G==="brand"?e=[`./${s.split("/").pop()||s}`,`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${s}`,`./${s.replace(/^configs\//,"")}`,`./${s.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=Ki?"no-store":"force-cache";for(let i of e)try{let a=await fetch(i,{cache:n});if(!a.ok)continue;let r=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${s} via ${i}`,r),r}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${i} (mode: ${G}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${s}; using defaults`),{}})();return Yi.set(s,t),t}async function Tn(){console.log("[CONFIG] Loading component schemas...");let s=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of s)try{let n=G==="publish"||G==="brand"?t.split("/").pop()||t:`configs/${t}`,i=await Nt(n);i.component&&(e.set(i.component,i),console.log(`[CONFIG] \u2713 Schema loaded: ${i.component} ${G==="publish"||G==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Ge(s){console.log(`[CONFIG] Loading object config: ${s}`);let e=G==="publish"||G==="brand"?`${s}.json`:`configs/objects/${s}.json`;return await Nt(e)}async function kn(s){let e=new Map;if(s.objects&&Array.isArray(s.objects)){for(let t of s.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let i=await Ge(n);(!i||Object.keys(i).length===0)&&n!==t.instance_id&&(i=await Ge(t.instance_id)),!i||Object.keys(i).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),i=await Ge(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...i,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function Pn(){console.log("[CONFIG] Loading engine configs...");let s=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(s.map(n=>{let i=`engine.${n}.json`,a=G==="publish"||G==="brand"?i:`configs/engine/${i}`;return Nt(a)})),t=Object.fromEntries(s.map((n,i)=>[n,e[i]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(s.map(n=>{var r;let i=(r=t[n])!=null?r:{},a=Object.keys(i);return[n,a.length>0?a:"empty"]}))),t}async function Xi(){return await Nt(G==="publish"||G==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function In(s="scene.main"){console.log(`[CONFIG] Loading scene config: ${s}`);let e=G==="publish"||G==="brand"?`${s}.json`:`configs/scenes/${s}.json`;return await Nt(e)}function ht(s,e){let t=[];if(!s.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let i of n.required||[])s.identity[i]||t.push(`Missing required identity field: ${i}`);for(let[i,a]of Object.entries(s)){if(i==="identity")continue;let r=e.get(i);if(r&&a&&typeof a=="object"){let o=a;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${i}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let d=o[l];if(d!==void 0&&c&&typeof c=="object"){let p=c;typeof d=="number"&&(p.min!==void 0&&d<p.min&&t.push(`${i}.${l} value ${d} is below minimum ${p.min}`),p.max!==void 0&&d>p.max&&t.push(`${i}.${l} value ${d} is above maximum ${p.max}`))}}}}return{valid:t.length===0,errors:t}}function tt(s,e){let t={...s},n=["identity","transform","render"];for(let[i,a]of e.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(i)||t[i])&&(t[i]||(t[i]={}),t[i]={...a.defaults,...t[i]});return t}function he(s,e,t,n){return typeof s!="number"||!Number.isFinite(s)?e:Math.min(Math.max(s,t),n)}function Ws(s,e){if(Array.isArray(s))return{x:he(s[0],e.x,-2e3,2e3),y:he(s[1],e.y,-2e3,2e3)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:he(t,e.x,-2e3,2e3),y:he(n,e.y,-2e3,2e3)}}function el(s,e){if(Array.isArray(s))return{x:he(s[0],e.x,0,1),y:he(s[1],e.y,0,1)};if(!s||typeof s!="object")return e;let{x:t,y:n}=s;return{x:he(t,e.x,0,1),y:he(n,e.y,0,1)}}function tl(s){if(Array.isArray(s))return{x:he(s[0],.5,-10,10),y:he(s[1],.5,-10,10)};if(s&&typeof s=="object"){let{x:e,y:t}=s;return{x:he(e,.5,-10,10),y:he(t,.5,-10,10)}}return typeof s=="string"?s:null}async function Oe(s="scene.main",e){var l,c,d,p,u,g,h,m,f,y,b,v,E,P;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await Tn(),n=re();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let i=await In(s);console.log(`[CONFIG] Scene config loaded: ${((l=i.objects)==null?void 0:l.length)||0} objects`);let a=await Pn();console.log("[CONFIG] Loading object configs...");let r=await kn(i);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[I,O]of r.entries()){let w=tt(O,t),k=ht(w,t);k.valid||console.warn(`Object ${I} validation errors:`,k.errors),(c=w.transform)!=null&&c.position&&(w.transform.position=Ws(w.transform.position,{x:0,y:0})),(d=w.transform)!=null&&d.offset&&(w.transform.offset=Ws(w.transform.offset,{x:0,y:0})),((p=w.transform)==null?void 0:p.anchor)!==void 0&&(w.transform.anchor=tl(w.transform.anchor)),((u=w.transform)==null?void 0:u.position_ratio)!==void 0&&w.transform.position_ratio!==null&&(w.transform.position_ratio=el(w.transform.position_ratio,{x:.5,y:.5})),r.set(I,w)}if(e){if(e.objects)for(let[I,O]of e.objects.entries())r.set(I,O);e.engine&&(a.runtime={...a.runtime,...e.engine.runtime},a.assets={...a.assets,...e.engine.assets},a.splash={...(g=a.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:a,scene:i,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=tt(o,t))),n.length>0&&zt()&&He(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((m=a.runtime)!=null?m:{}),assets:Object.keys((f=a.assets)!=null?f:{}),splash:Object.keys((y=a.splash)!=null?y:{}),loading:Object.keys((b=a.loading)!=null?b:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((E=a.tutorial)!=null?E:{}),endgame:Object.keys((P=a.endgame)!=null?P:{})},scene:i.scene_id||"unknown"}),o}function Ji(s){var t,n,i,a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,E,P,I,O,w,k,_,L,M,C,A,S,x,j,T;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[R,z]of s.objects.entries()){let N=((t=z.identity)==null?void 0:t.id)||R;N.includes("character")&&(e.gameplay.character_pos=((n=z.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((i=z.transform)==null?void 0:i.scale)||1,e.gameplay.character_anim_speed=((r=(a=z.gameplay)==null?void 0:a.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=z.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((d=(c=z.gameplay)==null?void 0:c.tuning)==null?void 0:d.relief_speed)||.22),(N.includes("gun")||N.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)||{}),N.includes("diamond")&&(e.gameplay.diamond=z),N.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=((m=z.transform)==null?void 0:m.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=z.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((y=z.effects)==null?void 0:y.physics_chunks)||{},e.gameplay.melting_particles=((b=z.effects)==null?void 0:b.melting_particles)||{},e.gameplay.hard_ice=z.hard_ice||{}),N.includes("water")&&(e.gameplay.water_drops=z),N.includes("crack")&&(e.gameplay.crack=z),N.includes("hand")&&(e.gameplay.hand=((v=z.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((E=z.transform)==null?void 0:E.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((P=z.transform)==null?void 0:P.scale)||1.5),N.includes("hazard")&&(e.gameplay.hazard=((I=z.gameplay)==null?void 0:I.tuning)||{},e.gameplay.danger_pos=((O=z.transform)==null?void 0:O.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((k=(w=z.gameplay)==null?void 0:w.tuning)==null?void 0:k.danger_pulse)||{},e.gameplay.hazard_height=((L=(_=z.gameplay)==null?void 0:_.tuning)==null?void 0:L.hazard_height)||140)}return e.gameplay.timeline=((M=s.engine.runtime)==null?void 0:M.timeline)||{},e.gameplay.drag_surface=((C=s.engine.runtime)==null?void 0:C.drag_surface)||{},e.gameplay.background=((A=s.engine.runtime)==null?void 0:A.background)||{},e.gameplay.ui_styles=((S=s.engine.runtime)==null?void 0:S.ui_styles)||{},e.gameplay.label_pulse=((x=s.engine.runtime)==null?void 0:x.label_pulse)||{},e.ui=((j=s.engine.runtime)==null?void 0:j.ui)||{},e.theme=((T=s.engine.runtime)==null?void 0:T.theme)||{},e.assets=s.engine.assets||{},e}var Vs,G,Yi,Ki,Zi=Te(()=>{"use strict";te();Vs=null,G="dev";if(typeof window!="undefined"){let s=window.__BUILD_SETTINGS__;if(s!=null&&s.buildMode)Vs=s,G=s.buildMode,console.log("[CONFIG] Loaded inline build settings:",s,"buildMode:",G);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);Vs=t,G=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",G)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",G)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",G);Yi=new Map,Ki=G==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Qi(s,e){let t=[];function n(i,a,r=""){if(i!==a){if(typeof i!=typeof a){t.push(`${r}: type changed`);return}if(typeof i=="object"&&i!==null&&a!==null){let o=new Set([...Object.keys(i),...Object.keys(a)]);for(let l of o){let c=r?`${r}.${l}`:l;l in i?l in a?n(i[l],a[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(s,e),t}function ea(s,e,t,n){let i={...t};for(let[a,r]of n.entries())i[a]&&r.defaults&&(i[a]={...r.defaults,...i[a]});return i}var Ht,nt,ta=Te(()=>{"use strict";Ht=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},nt=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,i=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(i.ok){let a=await i.text(),r=this.hashString(a),o=this.fileHashes.get(e);if(o&&o!==r&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==r){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,r)}else o||this.fileHashes.set(e,r)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let i=e.charCodeAt(n);t=(t<<5)-t+i,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function ia(s){if(typeof window=="undefined")return;let e=typeof na!="undefined"&&!!na.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let i=null,a=!1,r=null;if(t){r=new nt;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var y,b;if(!r)return;let m=new Set;m.add("configs/engine/engine.runtime.json"),m.add("configs/engine/engine.assets.json"),m.add("configs/engine/engine.splash.json"),m.add("configs/scenes/scene.main.json");let f=(b=(y=h.scene)==null?void 0:y.objects)!=null?b:[];for(let v of f)v!=null&&v.object_config&&m.add(`configs/objects/${v.object_config}.json`);for(let v of o)m.has(v)||r.unwatch(v);for(let v of m)o.has(v)||r.watch(v,E=>g(E));o=m},c=new Set,d=!1,p=async h=>{let m=await Ge(h),f=tt(m,s.activeConfig.schemas),y=ht(f,s.activeConfig.schemas);y.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,y.errors),await s.liveEditBridge.applyObjectConfig(h,f)};async function u(h){if(!a){a=!0;try{if(d||c.size===0){s.audioSystem.destroy();let m=await Oe("scene.main");s.setActiveConfig(m),s.gameObjectManager.updateConfig(m),s.CustomAssets.updateConfig(m),await s.CustomAssets.ready();let f=s.createAudioSystem(m);s.setAudioSystem(f),window.__audioSystem=f,await f.start(),s.liveEditBridge.rebuildIndexes(),l(m),console.log(`[GAME] Hot-reload complete (${h})`)}else{let m=Array.from(c);c.clear();for(let f of m)await p(f);console.log(`[GAME] Hot-reload updated objects: ${m.join(", ")}`)}}catch(m){console.warn("[GAME] Hot-reload failed:",m)}finally{a=!1,d=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):d=!0,i&&window.clearTimeout(i),i=window.setTimeout(()=>{u(h.type)},120)}e&&na.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(s.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var na,Ys=Te(()=>{"use strict";ta();Zi();na={}});var Ks={};Pt(Ks,{ConfigWatcher:()=>nt,DefaultReloadStrategy:()=>Ht,applyDefaults:()=>tt,diffConfigs:()=>Qi,loadAllObjectConfigs:()=>kn,loadComponentSchemas:()=>Tn,loadEngineConfig:()=>Pn,loadGamePromptConfig:()=>Xi,loadObjectCentricConfig:()=>Oe,loadObjectConfig:()=>Ge,loadSceneConfig:()=>In,rehydrateObject:()=>ea,setupHotReload:()=>ia,toLegacyFormat:()=>Ji,validateObjectConfig:()=>ht});var Mn=Te(()=>{"use strict";Zi();ta();Ys()});var zr={};Pt(zr,{AssetEditorModal:()=>za});var za,$a=Te(()=>{"use strict";za=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,i){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=i,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
2
2
  <div class="asset-editor-card">
3
3
  <div class="asset-editor-header">
4
4
  <div>
@@ -43,7 +43,7 @@
43
43
  <button class="debug-btn primary" data-modal-apply>Apply</button>
44
44
  </div>
45
45
  </div>
46
- `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(r=>{r.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var Wl={};Nt(Wl,{COLORS:()=>Se,ConfigWatcher:()=>ct,DebugPanel:()=>an,DefaultReloadStrategy:()=>Xt,Handler:()=>he,PlayableLoadingScreen:()=>Pi,PreviewShell:()=>Li,STROKE_WIDTH:()=>Zr,THEME:()=>Qr,applyConfigOverride:()=>se,applyConfigOverrides:()=>Fe,applyConfigsToDisk:()=>Rn,applyDefaults:()=>lt,baseLottie:()=>Ni,bootstrap:()=>zl,clearConfigOverrides:()=>de,clearConfigOverridesForObject:()=>Ks,configOverrideManager:()=>Xs,createPreviewShell:()=>Ya,deepClone:()=>J,default:()=>it,defaultPreset:()=>Bn,deviceGroups:()=>ha,devicePresets:()=>ga,diffConfigs:()=>oa,exportConfigsAsJSON:()=>ot,getConfigOverrides:()=>ie,getConfigStateSummary:()=>Be,getOverrideMode:()=>Vt,getPresetById:()=>dt,getPresetsByCategory:()=>dl,loadAllObjectConfigs:()=>Dn,loadComponentSchemas:()=>$n,loadEngineConfig:()=>Nn,loadGamePromptConfig:()=>aa,loadObjectCentricConfig:()=>Oe,loadObjectConfig:()=>Ge,loadSceneConfig:()=>Hn,redoLastConfigChange:()=>On,rehydrateObject:()=>la,removeConfigOverride:()=>Wt,resetToApplied:()=>Yt,resetToOriginal:()=>zn,setBootstrapDependencies:()=>Ol,setOverrideMode:()=>ta,setupHotReload:()=>pa,setupLiveEditBridge:()=>Ti,toLegacyFormat:()=>sa,trackObjectCreation:()=>Js,trackObjectDeletion:()=>Zs,undoLastConfigChange:()=>jn,validateObjectConfig:()=>Ct});module.exports=bo(Wl);var Ne={};function fn(s,e,t=!1){Ne[s]||(Ne[s]=[]),Ne[s].push({fn:e,once:t})}function Ri(s,e){if(Ne[s]){if(!e){delete Ne[s];return}Ne[s]=Ne[s].filter(t=>t.fn!==e)}}function yn(s,...e){let t=Ne[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Ri(s,n.fn)}function re(s,e){fn(s,e,!0)}var K=null,ue=[],wt=null;function ps(s){K=s,ue=[],wt!==null&&(clearTimeout(wt),wt=null)}function us(){var s,e,t;return{endpoint:(K==null?void 0:K.endpoint)||"",transport:(K==null?void 0:K.transport)||"beacon",batchSize:(s=K==null?void 0:K.batchSize)!=null?s:10,flushIntervalMs:(e=K==null?void 0:K.flushIntervalMs)!=null?e:300,maxQueue:(t=K==null?void 0:K.maxQueue)!=null?t:200,debug:!!(K!=null&&K.debug)}}async function cs(s,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function zi(s,e){let t=us();if(e&&t.endpoint){if(ue.push(s),ue.length>t.maxQueue&&(ue=ue.slice(ue.length-t.maxQueue)),ue.length>=t.batchSize){ds();return}wt===null&&(wt=window.setTimeout(()=>{wt=null,ds()},t.flushIntervalMs))}}async function ds(){let s=us();if(!s.endpoint||ue.length===0)return;let e=ue.splice(0,s.batchSize);await cs(s.endpoint,{events:e},s.transport,s.debug),ue.length>0&&await cs(s.endpoint,{events:ue.splice(0,s.batchSize)},s.transport,s.debug)}function gs(s){return Math.max(0,Math.min(1,s))}function vo(s){let e=String(s!=null?s:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function Ht(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function wo(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function hs(s,e,t){try{s[e]=t}catch{}}function xo(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function ms(s,e){let t=s==null?void 0:s.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function fs(s,e){let t=xo(s);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function ys(){let s=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&n()})},i=d=>{var u;s.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),n()},a=d=>{s.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},r=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=Ht();for(let g of Array.from(s)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=gs(m),y=g.repeat>=0?g.repeat+1:1,b=g.repeat>0?Math.min(Math.floor(m),y-1):0;if(g.repeat>0&&m>=1){let L=m-b;f=gs(L)}let v=g.ease(f);g.yoyo&&b%2===1&&(v=1-v);for(let L of g.props)hs(g.target,L.key,L.from+(L.to-L.from)*v);g.scaleFrom&&g.scaleTo&&ms(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(m>=y){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(d,p,u)=>{var L;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+((L=u==null?void 0:u.delayMsOverride)!=null?L:0)),m=vo(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,y=p.yoyo===!0,b=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let M of Object.keys(p)){if(b.has(M))continue;let O=p[M];typeof O=="number"&&v.push({key:M,from:wo(d,M),to:O})}let S=fs(d,p);return{target:d,startMs:Ht(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:S.from,scaleTo:S.to,repeat:f,yoyo:y,onUpdate:typeof p.onUpdate=="function"?p.onUpdate:void 0,onComplete:typeof p.onComplete=="function"?p.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,p){let u=l(d,p);return i(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=Ht())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:Ht(),h=Ht()-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"&&hs(d,g,h)}let u=fs(d,p);u.to&&ms(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))r(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],m=b=>{if(typeof b=="number")return Math.max(0,b*1e3);let v=typeof b=="string"?b.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=b=>{p.push(b);let v=Math.max(0,(typeof b.vars.duration=="number"?b.vars.duration:.5)*1e3);u=Math.max(u,b.atMs+v)},y={to(b,v,S){return f({kind:"to",target:b,vars:v,atMs:m(S)}),y},fromTo(b,v,S,L){return f({kind:"fromTo",target:b,vars:S,from:v,atMs:m(L)}),y},play(){var b,v;if(g)return y;g=!0,h=[];for(let S of p)S.kind==="fromTo"&&c.set(S.target,(b=S.from)!=null?b:{}),h.push(c.to(S.target,{...S.vars,delay:S.atMs/1e3+((v=S.vars.delay)!=null?v:0)}));return y},pause(){for(let b of h)b.pause();return y},kill(){for(let b of h)b.kill();h=[],g=!1}};return d.paused||y.play(),y}};return c}function bs(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=ys()}catch{}}var vs={name:"handler-playable-sdk",version:"1.0.56",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 oe=0,Eo=oe++,ws=oe++,xs=oe++,Ss=oe++,Es=oe++,Cs=oe++,As=oe++,Ls=oe++,Ts=oe++,ks=oe++,Ps=oe++,Ms=oe++,W=Eo;function Is(){return W===ws}function _s(){return W===xs}function js(){return W===Ss}function Os(){return W===Es}function xt(){return W===Cs}function St(){return W===As}function Rs(){return W===Ls}function zs(){return W===Ts}function $s(){return W===ks}function $i(){return W===Ps}function Di(){return W===Ms}function Ds(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),W=ws;return}catch{}else if(s==="dapi")try{dapi.isReady(),W=xs;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(W=Ss)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(W=Es)}catch{}else if(e==="mintegral")window.gameReady&&(W=Cs);else if(e==="tapjoy")window.TJ_API&&(W=As);else if(e==="tiktok")window.openAppStore&&(W=Ls);else if(e==="smadex")try{window.smxTracking&&(W=Ts)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(W=ks)}catch{}else e==="vungle"?W=Ps:(s==="nucleo"||e==="nucleo")&&(W=Ms)}var bn=vt(require("lottie-web"),1),Ni=bn.default;typeof window!="undefined"&&(window.lottie=bn.default,window.__baseLottie=bn.default);var Co=require("pixi.js");var Hi=require("pixi.js");var Ao=null;function Fi(s){Ao=s}wn();vn();var Ft=require("pixi.js");wn();var Io=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",qi=Io;if(typeof window!="undefined")try{let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);e!=null&&e.buildMode&&(qi=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${qi}`))}}catch{}function _o(s){var t,n,i,a,r;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(s);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(s))return{x:(t=s[0])!=null?t:.5,y:(n=s[1])!=null?n:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(i=s.x)!=null?i:.5,y:(a=s.y)!=null?a:.5};if(typeof s=="string"){let o=s.trim().toLowerCase();return(r=e[o])!=null?r:{x:.5,y:.5}}return null}var ve=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${qi}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new Ft.Container;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${i.type}, path: ${i.path}`);let r=await st.load(e,i,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=r==null?void 0:r.constructor)==null?void 0:d.name}`);let o;if(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new Ft.Sprite(r),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(i.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=r==null?void 0:r.constructor)==null?void 0:u.name,r),r&&(((g=r.constructor)==null?void 0:g.name)==="Container"||r instanceof Ft.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let y of m)try{let b=await fetch(y);if(b.ok){o=await b.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",y,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,n){var i,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((r=t.position.x)!=null?r:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=_o(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 Bt=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 Ro=vt(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Ro);Et();var xn=require("pixi.js");Et();var Yi=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new Bt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let r=this.registry.get(a);if(!r){console.warn("[Assets] No config found for object:",a);return}try{let l=await ve.create(a,r,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await ve.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},zo=new Yi,$o=new Proxy(zo,{get(s,e){if(e in s&&typeof s[e]=="function")return s[e].bind(s);if(s.get(e))return s.get(e)}});Et();var No=require("pixi.js"),Me={width:400,height:600,designWidth:400,scaleFactor:1},En={scale:1,position:1},Xi=[];function Ho(s,e,t,n,i,a,r){Xi.push({element:s,originalScale:a,positionHelper:e,heightPercent:i}),e(s,t,n,i,a,r,!1)}function Fo(){Xi.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*Me.scaleFactor;t(s,Me.width,Me.height,n,i,!0,!1)})}function Ki(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Me.width=s,Me.height=e,Me.scaleFactor=Math.min(s/Me.designWidth,1.15),En.scale=Me.scaleFactor,En.position=1,console.log(`[SCREEN] Global multipliers - scale: ${En.scale.toFixed(3)}`),Fo()}var Gt={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 Bo(s,e,t){let n=Gt[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function Uo(){return Gt}var Go={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 Sn(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Ie(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:Sn(s[0],e.x),y:Sn(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:Sn(n.x,e.x),y:Sn(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=Go[n])!=null?t:e}return e}function Cn(s,e,t,n={}){var g,h,m,f,y,b;let i=Ie(t),a=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((m=a.left)!=null?m:0)+r.x,l=((f=a.right)!=null?f:0)+r.x,c=((y=a.top)!=null?y:0)+r.y,d=((b=a.bottom)!=null?b:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*i.x,y:c+u*i.y}}function An(s,e,t,n={}){var m,f,y,b,v,S;let i=(m=n.inset)!=null?m:{},a=(f=n.padding)!=null?f:{x:0,y:0},r=((y=i.left)!=null?y:0)+a.x,o=((b=i.right)!=null?b:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((S=i.bottom)!=null?S:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Ie(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:r+d*g,y:l+p*h}}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==s||i!==e)&&(s=n,e=i,Ki(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Ki(window.innerWidth,window.innerHeight),window.updateDebugConfig=Bo,window.getDebugConfig=Uo,window.copyConfig=tl,window.applyConfig=Ut,window.applyConfigForRatio=nl,window.positionAtBottom=Gs,window.positionAtTop=Wo,window.positionAtCenter=Yo,window.positionAtLeft=Ko,window.positionAtRight=Xo,window.positionAtBottomLeft=Jo,window.positionAtBottomRight=Zo,window.positionAtTopLeft=Qo,window.positionAtTopRight=el,window.applyPositionContract=Vo,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 Ln(s,e,t=0){return s*e+t}function Tn(s,e,t=0){return s*(1-e)+t}function kn(s,e,t=0){return s*e+t}function Pn(s,e,t=0){return s*(1-e)+t}function ce(s,e=0){return s/2+e}function qo(s,e){return s*e}function Vo(s,e,t,n){var r,o,l,c,d,p,u,g,h,m,f,y,b,v,S,L,M,O,w,P;let i=0,a=0;switch(n.type){case"top":i=ce(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),a=Ln(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=ce(e,(p=(d=n.offset)==null?void 0:d.x)!=null?p:0),a=Tn(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=kn(e,n.percent,(m=(h=n.offset)==null?void 0:h.x)!=null?m:0),a=ce(t,(y=(f=n.offset)==null?void 0:f.y)!=null?y:0);break;case"right":i=Pn(e,n.percent,(v=(b=n.offset)==null?void 0:b.x)!=null?v:0),a=ce(t,(L=(S=n.offset)==null?void 0:S.y)!=null?L:0);break;case"center":i=ce(e,(O=(M=n.offset)==null?void 0:M.x)!=null?O:0),a=ce(t,(P=(w=n.offset)==null?void 0:w.y)!=null?P:0);break}s.position?s.position.set(i,a):(s.x=i,s.y=a),n.scale!==void 0&&n.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(n.scale,n.scale):(s.scale.x=n.scale,s.scale.y=n.scale))}function Gs(s,e,t,n=.2,i=1,a=!0,r=!1){let o=qo(t,n),l=Tn(t,n/2);_e(s,ce(e),l);let c=a?i*Me.scaleFactor:i;je(s,c),r&&!Xi.find(d=>d.element===s)&&Ho(s,Gs,e,t,n,i,a)}function Wo(s,e,t,n=.1,i=1){_e(s,ce(e),Ln(t,n)),je(s,i)}function Yo(s,e,t,n=0,i=0,a=1){_e(s,ce(e,n),ce(t,i)),je(s,a)}function Ko(s,e,t,n=.1,i=1){_e(s,kn(e,n),ce(t)),je(s,i)}function Xo(s,e,t,n=.1,i=1){_e(s,Pn(e,n),ce(t)),je(s,i)}function Jo(s,e,t,n=.05,i=.05,a=1){_e(s,kn(e,i),Tn(t,n)),je(s,a)}function Zo(s,e,t,n=.05,i=.05,a=1){_e(s,Pn(e,i),Tn(t,n)),je(s,a)}function Qo(s,e,t,n=.05,i=.05,a=1){_e(s,kn(e,i),Ln(t,n)),je(s,a)}function el(s,e,t,n=.05,i=.05,a=1){_e(s,Pn(e,i),Ln(t,n)),je(s,a)}function _e(s,e,t){s&&s.position?typeof s.position.set=="function"?s.position.set(e,t):(s.position.x=e,s.position.y=t):s&&(s.x=e,s.y=t)}function je(s,e){e!==1&&s&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(e,e):s.scale.x!==void 0&&s.scale.y!==void 0&&(s.scale.x=e,s.scale.y=e))}var rt={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 tl(s){return s&&rt[s]?JSON.parse(JSON.stringify(rt[s])):JSON.parse(JSON.stringify(Gt))}function Ut(s){Object.keys(s).forEach(e=>{let t=e;Gt[t]&&s[t]&&Object.assign(Gt[t],s[t])}),console.log("Config applied:",s)}function nl(s,e){let t=s/e;t>1.6?(Ut(rt.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(Ut(rt.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(Ut(rt.square),console.log("Applied SQUARE config for ratio:",t)):(Ut(rt.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=rt,s.resolveAnchorVec2=s.resolveAnchorVec2||Ie,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||Cn,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||An}Fn();function X(s,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(s,e);return`${s/n}:${e/n}`}var Sd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:X(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:X(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:X(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:X(360,780)}],Ed=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:X(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:X(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:X(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:X(412,915)}],Cd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:X(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:X(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:X(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:X(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:X(800,1280)}],ua=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:X(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:X(768,1024),mraidScale:.7}];var ga=[...ua],ha=[{category:"playable",label:"Playable Ad",devices:ua}],Bn=ua[0];function dt(s){return ga.find(e=>e.id===s)||Bn}function dl(s){return ga.filter(e=>e.category===s)}Z();var qe=class{async updateProperty(e,t,n,i={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,n);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=a(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(se({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let p=window.applyEditableObjectConfig;if(typeof p=="function"){let u=window.__editableConfig,g=(d=(c=(l=u==null?void 0:u.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await p(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function ma(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let r=i.result,o=s.category||"misc",c=`${(s.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:r,overwrite:!0})})).json();if(!(p!=null&&p.success)){alert(`Upload failed: ${(p==null?void 0:p.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await s.onApply(p.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},i.readAsDataURL(n)},e.click()}var Un=class{constructor(){this.updateManager=new qe}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,r);break;case"ai-edit":this.openAIEditor(t,n,r);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let r=((i=(n=t.transform)==null?void 0:n.scale)!=null?i:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",r),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",r)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),i.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),i.categories&&!i.categories.includes(d)&&i.categories.push(d),i.libraryAssets&&!i.libraryAssets[d]&&(i.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(i.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((r=i==null?void 0:i.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");ma({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let p=window.__debugContext;(h=(g=p==null?void 0:p.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let u=window.__highlightLibrarySlot;typeof u=="function"&&setTimeout(()=>{u(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(i):typeof r.schemas=="object"&&(o=r.schemas[i]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),i(e,r,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var pl=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],ul=["environment","ui","character","system","backgrounds"],gl=["bg","world","ui"],ar={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}}},Gn=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
46
+ `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(r=>{r.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let i=this.modal.querySelector("[data-ai-edit]");i==null||i.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(i=>{i.classList.toggle("active",i.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:i=>{this.onApplyCallback&&this.onApplyCallback(i),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var Nl={};Pt(Nl,{COLORS:()=>Ce,ConfigWatcher:()=>nt,DebugPanel:()=>Wt,DefaultReloadStrategy:()=>Ht,Handler:()=>be,PlayableLoadingScreen:()=>vi,PreviewShell:()=>fi,STROKE_WIDTH:()=>Ur,THEME:()=>qr,applyConfigOverride:()=>le,applyConfigOverrides:()=>He,applyConfigsToDisk:()=>An,applyDefaults:()=>tt,baseLottie:()=>Mi,bootstrap:()=>kl,clearConfigOverrides:()=>ge,clearConfigOverridesForObject:()=>Fs,configOverrideManager:()=>Bs,createPreviewShell:()=>Ha,deepClone:()=>ee,default:()=>Xe,defaultPreset:()=>_n,deviceGroups:()=>ra,devicePresets:()=>sa,diffConfigs:()=>Qi,exportConfigsAsJSON:()=>et,getConfigOverrides:()=>re,getConfigStateSummary:()=>Fe,getOverrideMode:()=>zt,getPresetById:()=>it,getPresetsByCategory:()=>nl,loadAllObjectConfigs:()=>kn,loadComponentSchemas:()=>Tn,loadEngineConfig:()=>Pn,loadGamePromptConfig:()=>Xi,loadObjectCentricConfig:()=>Oe,loadObjectConfig:()=>Ge,loadSceneConfig:()=>In,redoLastConfigChange:()=>Cn,rehydrateObject:()=>ea,removeConfigOverride:()=>$t,resetToApplied:()=>Dt,resetToOriginal:()=>Ln,setBootstrapDependencies:()=>Ll,setOverrideMode:()=>Wi,setupHotReload:()=>ia,setupLiveEditBridge:()=>yi,toLegacyFormat:()=>Ji,trackObjectCreation:()=>Gs,trackObjectDeletion:()=>Us,undoLastConfigChange:()=>En,validateObjectConfig:()=>ht});module.exports=co(Nl);var De={};function rn(s,e,t=!1){De[s]||(De[s]=[]),De[s].push({fn:e,once:t})}function Ti(s,e){if(De[s]){if(!e){delete De[s];return}De[s]=De[s].filter(t=>t.fn!==e)}}function on(s,...e){let t=De[s];if(t)for(let n of[...t])n.fn(...e),n.once&&Ti(s,n.fn)}function ce(s,e){rn(s,e,!0)}var K=null,fe=[],dt=null;function is(s){K=s,fe=[],dt!==null&&(clearTimeout(dt),dt=null)}function as(){var s,e,t;return{endpoint:(K==null?void 0:K.endpoint)||"",transport:(K==null?void 0:K.transport)||"beacon",batchSize:(s=K==null?void 0:K.batchSize)!=null?s:10,flushIntervalMs:(e=K==null?void 0:K.flushIntervalMs)!=null?e:300,maxQueue:(t=K==null?void 0:K.maxQueue)!=null?t:200,debug:!!(K!=null&&K.debug)}}async function ts(s,e,t,n){let i=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(s,new Blob([i],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,e);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:i,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function ki(s,e){let t=as();if(e&&t.endpoint){if(fe.push(s),fe.length>t.maxQueue&&(fe=fe.slice(fe.length-t.maxQueue)),fe.length>=t.batchSize){ns();return}dt===null&&(dt=window.setTimeout(()=>{dt=null,ns()},t.flushIntervalMs))}}async function ns(){let s=as();if(!s.endpoint||fe.length===0)return;let e=fe.splice(0,s.batchSize);await ts(s.endpoint,{events:e},s.transport,s.debug),fe.length>0&&await ts(s.endpoint,{events:fe.splice(0,s.batchSize)},s.transport,s.debug)}function ss(s){return Math.max(0,Math.min(1,s))}function po(s){let e=String(s!=null?s:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),n=t?Number(t[1]):1.8;return i=>1+(n+1)*Math.pow(i-1,3)+n*Math.pow(i-1,2)}return t=>1-(1-t)*(1-t)}function It(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function uo(s,e){let t=s==null?void 0:s[e];return typeof t=="number"?t:0}function rs(s,e,t){try{s[e]=t}catch{}}function go(s){let e=s==null?void 0:s.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function os(s,e){let t=s==null?void 0:s.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function ls(s,e){let t=go(s);if(!t)return{from:null,to:null};let n=null,i=null;return typeof e.scale=="number"?(n=e.scale,i=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(i=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(i=e.scaleY),n===null&&i===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:i!=null?i:t.y}}}function cs(){let s=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),s.size>0&&n()})},i=d=>{var u;s.add(d);let p=(u=e.get(d.target))!=null?u:new Set;p.add(d),e.set(d.target,p),n()},a=d=>{s.delete(d);let p=e.get(d.target);p&&(p.delete(d),p.size===0&&e.delete(d.target))},r=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var p,u;let d=It();for(let g of Array.from(s)){if(g.killed||g.paused)continue;let h=d-g.startMs-g.delayMs;if(h<0)continue;let m=g.durationMs>0?h/g.durationMs:1,f=ss(m),y=g.repeat>=0?g.repeat+1:1,b=g.repeat>0?Math.min(Math.floor(m),y-1):0;if(g.repeat>0&&m>=1){let P=m-b;f=ss(P)}let v=g.ease(f);g.yoyo&&b%2===1&&(v=1-v);for(let P of g.props)rs(g.target,P.key,P.from+(P.to-P.from)*v);g.scaleFrom&&g.scaleTo&&os(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});try{(p=g.onUpdate)==null||p.call(g)}catch{}if(m>=y){r(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)),m=po(p.ease),f=typeof p.repeat=="number"?Math.max(0,p.repeat|0):0,y=p.yoyo===!0,b=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let I of Object.keys(p)){if(b.has(I))continue;let O=p[I];typeof O=="number"&&v.push({key:I,from:uo(d,I),to:O})}let E=ls(d,p);return{target:d,startMs:It(),delayMs:h,durationMs:g,ease:m,props:v,scaleFrom:E.from,scaleTo:E.to,repeat:f,yoyo:y,onUpdate:typeof p.onUpdate=="function"?p.onUpdate:void 0,onComplete:typeof p.onComplete=="function"?p.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,p){let u=l(d,p);return i(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=It())},resume:()=>{var m;if(!u.paused)return;let g=(m=u.pauseAtMs)!=null?m:It(),h=It()-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"&&rs(d,g,h)}let u=ls(d,p);u.to&&os(d,u.to)},killTweensOf(d){let p=e.get(d);if(p)for(let u of Array.from(p))r(u)},timeline(d={}){let p=[],u=0,g=!1,h=[],m=b=>{if(typeof b=="number")return Math.max(0,b*1e3);let v=typeof b=="string"?b.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=b=>{p.push(b);let v=Math.max(0,(typeof b.vars.duration=="number"?b.vars.duration:.5)*1e3);u=Math.max(u,b.atMs+v)},y={to(b,v,E){return f({kind:"to",target:b,vars:v,atMs:m(E)}),y},fromTo(b,v,E,P){return f({kind:"fromTo",target:b,vars:E,from:v,atMs:m(P)}),y},play(){var b,v;if(g)return y;g=!0,h=[];for(let E of p)E.kind==="fromTo"&&c.set(E.target,(b=E.from)!=null?b:{}),h.push(c.to(E.target,{...E.vars,delay:E.atMs/1e3+((v=E.vars.delay)!=null?v:0)}));return y},pause(){for(let b of h)b.pause();return y},kill(){for(let b of h)b.kill();h=[],g=!1}};return d.paused||y.play(),y}};return c}function ds(){if(typeof window=="undefined")return;let s=window;if(!s.gsap)try{s.gsap=cs()}catch{}}var ps={name:"handler-playable-sdk",version:"1.0.57",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,mo=de++,us=de++,gs=de++,hs=de++,ms=de++,fs=de++,ys=de++,bs=de++,vs=de++,ws=de++,xs=de++,Ss=de++,W=mo;function Es(){return W===us}function Cs(){return W===gs}function As(){return W===hs}function Ls(){return W===ms}function pt(){return W===fs}function ut(){return W===ys}function Ts(){return W===bs}function ks(){return W===vs}function Ps(){return W===ws}function Pi(){return W===xs}function Ii(){return W===Ss}function Is(){let s=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(s==="mraid")try{mraid.getState(),W=us;return}catch{}else if(s==="dapi")try{dapi.isReady(),W=gs;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(W=hs)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(W=ms)}catch{}else if(e==="mintegral")window.gameReady&&(W=fs);else if(e==="tapjoy")window.TJ_API&&(W=ys);else if(e==="tiktok")window.openAppStore&&(W=bs);else if(e==="smadex")try{window.smxTracking&&(W=vs)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(W=ws)}catch{}else e==="vungle"?W=xs:(s==="nucleo"||e==="nucleo")&&(W=Ss)}var ln=ct(require("lottie-web"),1),Mi=ln.default;typeof window!="undefined"&&(window.lottie=ln.default,window.__baseLottie=ln.default);var fo=require("pixi.js");var _i=require("pixi.js");var yo=null;function ji(s){yo=s}dn();cn();var Mt=require("pixi.js");dn();var Eo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",$i=Eo;if(typeof window!="undefined")try{let s=new XMLHttpRequest;if(s.open("GET","./build-settings.json",!1),s.send(),s.status===200&&s.responseText){let e=JSON.parse(s.responseText);e!=null&&e.buildMode&&($i=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${$i}`))}}catch{}function Co(s){var t,n,i,a,r;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(s);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(s))return{x:(t=s[0])!=null?t:.5,y:(n=s[1])!=null?n:.5};if(s&&typeof s=="object"&&"x"in s&&"y"in s)return{x:(i=s.x)!=null?i:.5,y:(a=s.y)!=null?a:.5};if(typeof s=="string"){let o=s.trim().toLowerCase();return(r=e[o])!=null?r:{x:.5,y:.5}}return null}var xe=class{static async create(e,t,n){var l,c,d,p,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${$i}`);let i=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!i){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let m=new Mt.Container;return this.applyTransform(m,t==null?void 0:t.transform,t),m}let a=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${a}, type: ${i.type}, path: ${i.path}`);let r=await Ze.load(e,i,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(d=r==null?void 0:r.constructor)==null?void 0:d.name}`);let o;if(i.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new Mt.Sprite(r),console.log("[ObjectFactory] Created object:",o,"type:",(p=o==null?void 0:o.constructor)==null?void 0:p.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(i.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=r==null?void 0:r.constructor)==null?void 0:u.name,r),r&&(((g=r.constructor)==null?void 0:g.name)==="Container"||r instanceof Mt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let m=[i.path,`/assets/${i.path}`,`assets/${i.path}`,`../assets/${i.path}`],f=!1;for(let y of m)try{let b=await fetch(y);if(b.ok){o=await b.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",y,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,n){var i,a,r,o;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(i=t.position.x)!=null?i:0,e.y=(a=t.position.y)!=null?a:0):"position"in e&&e.position&&e.position.set((r=t.position.x)!=null?r:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Co(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 _t=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 To=ct(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=To);gt();var pn=require("pixi.js");gt();var Hi=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new _t}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(i=>!this.instanceCache.has(i));if(t.length===0)return;let n=async i=>{i.length&&(console.log("[Assets] Loading objects:",i),await Promise.all(i.map(async a=>{var o;let r=this.registry.get(a);if(!r){console.warn("[Assets] No config found for object:",a);return}try{let l=await xe.create(a,r,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(t);let i=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));i.length>0&&(console.warn("[Assets] Retrying missing assets:",i),await n(i)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await xe.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},ko=new Hi,Po=new Proxy(ko,{get(s,e){if(e in s&&typeof s[e]=="function")return s[e].bind(s);if(s.get(e))return s.get(e)}});gt();var Mo=require("pixi.js"),Ie={width:400,height:600,designWidth:400,scaleFactor:1},gn={scale:1,position:1},Bi=[];function _o(s,e,t,n,i,a,r){Bi.push({element:s,originalScale:a,positionHelper:e,heightPercent:i}),e(s,t,n,i,a,r,!1)}function jo(){Bi.forEach(({element:s,originalScale:e,positionHelper:t,heightPercent:n})=>{let i=e*Ie.scaleFactor;t(s,Ie.width,Ie.height,n,i,!0,!1)})}function Fi(s,e){console.log(`[SCREEN] updateScreenState called: ${s}x${e}`),Ie.width=s,Ie.height=e,Ie.scaleFactor=Math.min(s/Ie.designWidth,1.15),gn.scale=Ie.scaleFactor,gn.position=1,console.log(`[SCREEN] Global multipliers - scale: ${gn.scale.toFixed(3)}`),jo()}var Ot={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 Oo(s,e,t){let n=Ot[s];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${s}.${e} = ${t}`))}function Ro(){return Ot}var zo={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 un(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Me(s,e={x:.5,y:.5}){var t;if(Array.isArray(s))return{x:un(s[0],e.x),y:un(s[1],e.y)};if(s&&typeof s=="object"){let n=s;return{x:un(n.x,e.x),y:un(n.y,e.y)}}if(typeof s=="string"){let n=s.trim().toLowerCase();return(t=zo[n])!=null?t:e}return e}function hn(s,e,t,n={}){var g,h,m,f,y,b;let i=Me(t),a=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((m=a.left)!=null?m:0)+r.x,l=((f=a.right)!=null?f:0)+r.x,c=((y=a.top)!=null?y:0)+r.y,d=((b=a.bottom)!=null?b:0)+r.y,p=Math.max(0,s-o-l),u=Math.max(0,e-c-d);return{x:o+p*i.x,y:c+u*i.y}}function mn(s,e,t,n={}){var m,f,y,b,v,E;let i=(m=n.inset)!=null?m:{},a=(f=n.padding)!=null?f:{x:0,y:0},r=((y=i.left)!=null?y:0)+a.x,o=((b=i.right)!=null?b:0)+a.x,l=((v=i.top)!=null?v:0)+a.y,c=((E=i.bottom)!=null?E:0)+a.y,d=Math.max(0,s-r-o),p=Math.max(0,e-l-c),u=Me(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:r+d*g,y:l+p*h}}if(typeof window!="undefined"){let s=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,i=window.innerHeight;(n!==s||i!==e)&&(s=n,e=i,Fi(n,i))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),Fi(window.innerWidth,window.innerHeight),window.updateDebugConfig=Oo,window.getDebugConfig=Ro,window.copyConfig=Wo,window.applyConfig=jt,window.applyConfigForRatio=Yo,window.positionAtBottom=zs,window.positionAtTop=No,window.positionAtCenter=Ho,window.positionAtLeft=Fo,window.positionAtRight=Bo,window.positionAtBottomLeft=Go,window.positionAtBottomRight=Uo,window.positionAtTopLeft=qo,window.positionAtTopRight=Vo,window.applyPositionContract=Do,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 fn(s,e,t=0){return s*e+t}function yn(s,e,t=0){return s*(1-e)+t}function bn(s,e,t=0){return s*e+t}function vn(s,e,t=0){return s*(1-e)+t}function ue(s,e=0){return s/2+e}function $o(s,e){return s*e}function Do(s,e,t,n){var r,o,l,c,d,p,u,g,h,m,f,y,b,v,E,P,I,O,w,k;let i=0,a=0;switch(n.type){case"top":i=ue(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),a=fn(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":i=ue(e,(p=(d=n.offset)==null?void 0:d.x)!=null?p:0),a=yn(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":i=bn(e,n.percent,(m=(h=n.offset)==null?void 0:h.x)!=null?m:0),a=ue(t,(y=(f=n.offset)==null?void 0:f.y)!=null?y:0);break;case"right":i=vn(e,n.percent,(v=(b=n.offset)==null?void 0:b.x)!=null?v:0),a=ue(t,(P=(E=n.offset)==null?void 0:E.y)!=null?P:0);break;case"center":i=ue(e,(O=(I=n.offset)==null?void 0:I.x)!=null?O:0),a=ue(t,(k=(w=n.offset)==null?void 0:w.y)!=null?k:0);break}s.position?s.position.set(i,a):(s.x=i,s.y=a),n.scale!==void 0&&n.scale!==1&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(n.scale,n.scale):(s.scale.x=n.scale,s.scale.y=n.scale))}function zs(s,e,t,n=.2,i=1,a=!0,r=!1){let o=$o(t,n),l=yn(t,n/2);_e(s,ue(e),l);let c=a?i*Ie.scaleFactor:i;je(s,c),r&&!Bi.find(d=>d.element===s)&&_o(s,zs,e,t,n,i,a)}function No(s,e,t,n=.1,i=1){_e(s,ue(e),fn(t,n)),je(s,i)}function Ho(s,e,t,n=0,i=0,a=1){_e(s,ue(e,n),ue(t,i)),je(s,a)}function Fo(s,e,t,n=.1,i=1){_e(s,bn(e,n),ue(t)),je(s,i)}function Bo(s,e,t,n=.1,i=1){_e(s,vn(e,n),ue(t)),je(s,i)}function Go(s,e,t,n=.05,i=.05,a=1){_e(s,bn(e,i),yn(t,n)),je(s,a)}function Uo(s,e,t,n=.05,i=.05,a=1){_e(s,vn(e,i),yn(t,n)),je(s,a)}function qo(s,e,t,n=.05,i=.05,a=1){_e(s,bn(e,i),fn(t,n)),je(s,a)}function Vo(s,e,t,n=.05,i=.05,a=1){_e(s,vn(e,i),fn(t,n)),je(s,a)}function _e(s,e,t){s&&s.position?typeof s.position.set=="function"?s.position.set(e,t):(s.position.x=e,s.position.y=t):s&&(s.x=e,s.y=t)}function je(s,e){e!==1&&s&&s.scale&&(typeof s.scale.set=="function"?s.scale.set(e,e):s.scale.x!==void 0&&s.scale.y!==void 0&&(s.scale.x=e,s.scale.y=e))}var Qe={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 Wo(s){return s&&Qe[s]?JSON.parse(JSON.stringify(Qe[s])):JSON.parse(JSON.stringify(Ot))}function jt(s){Object.keys(s).forEach(e=>{let t=e;Ot[t]&&s[t]&&Object.assign(Ot[t],s[t])}),console.log("Config applied:",s)}function Yo(s,e){let t=s/e;t>1.6?(jt(Qe.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(jt(Qe.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(jt(Qe.square),console.log("Applied SQUARE config for ratio:",t)):(jt(Qe.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let s=window;s.configPresets=Qe,s.resolveAnchorVec2=s.resolveAnchorVec2||Me,s.resolveScreenAnchorPoint=s.resolveScreenAnchorPoint||hn,s.resolveScreenRatioPoint=s.resolveScreenRatioPoint||mn}Mn();function X(s,e){let t=(i,a)=>a===0?i:t(a,i%a),n=t(s,e);return`${s/n}:${e/n}`}var hd=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:X(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:X(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:X(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:X(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:X(360,780)}],md=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:X(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:X(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:X(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:X(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:X(412,915)}],fd=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:X(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:X(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:X(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:X(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:X(800,1280)}],aa=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:X(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:X(768,1024),mraidScale:.7}];var sa=[...aa],ra=[{category:"playable",label:"Playable Ad",devices:aa}],_n=aa[0];function it(s){return sa.find(e=>e.id===s)||_n}function nl(s){return sa.filter(e=>e.category===s)}te();var Ue=class{async updateProperty(e,t,n,i={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",e,t,n);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=a(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}if(le({objectId:e,path:t,value:n},{persist:!0}),t==="transform"||t.startsWith("transform."))console.log("[DEBUG FALLBACK] PropertyUpdateManager SKIP applyEditableObjectConfig (transform path)",t,e);else{let p=window.applyEditableObjectConfig;if(typeof p=="function"){let u=window.__editableConfig,g=(d=(c=(l=u==null?void 0:u.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?d:r;await p(e,g),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available")}this.triggerRefresh(e),i.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),i=e;for(let a of n)if(i&&typeof i=="object"&&a in i)i=i[a];else return;return i}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};function oa(s){let e=document.createElement("input");e.type="file",e.accept="image/*",e.onchange=async t=>{var a;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let i=new FileReader;i.onload=async()=>{let r=i.result,o=s.category||"misc",c=`${(s.objectId||"new_asset").replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")||"new_asset"}_uploaded`;try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:o,filename:`${c}.png`,data:r,overwrite:!0})})).json();if(!(p!=null&&p.success)){alert(`Upload failed: ${(p==null?void 0:p.error)||"Unknown error"}`);return}let u=window.addAssetToRegistry;typeof u=="function"&&u(o,`${c}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch{}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),await s.onApply(p.path)}catch(d){console.error("[QuickActionsBar] Upload error:",d),alert("Upload failed. Check console.")}},i.readAsDataURL(n)},e.click()}var jn=class{constructor(){this.updateManager=new Ue}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let i=window.getEditableObjectConfig;if(typeof i!="function")return;let a=i(t);if(!a)return;let r=this.updateManager.getNestedProperty(a,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,a),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,r);break;case"ai-edit":this.openAIEditor(t,n,r);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,i;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let r=((i=(n=t.transform)==null?void 0:n.scale)!=null?i:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",r),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",r)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let n=window.getEditableAssets;if(typeof n!="function")return;let i=n();if(!i||!i.slots)return;let a=e.startsWith("json.")?e.replace("json.",""):e;if(!i.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),i.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),i.categories&&!i.categories.includes(d)&&i.categories.push(d),i.libraryAssets&&!i.libraryAssets[d]&&(i.libraryAssets[d]=[]);let p=window.reRenderAssetLibrary;typeof p=="function"&&p()}}openLibrary(e,t,n){var a;let i=window.__debugContext;if(i){if(i.activeTab!=="library"){i.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(i.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),i.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let a=t.split(".").pop()||t;i(a,`Edit ${a} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){var r;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e),a=((r=i==null?void 0:i.identity)==null?void 0:r.category)||(t.split(".")[0]==="render"?"environment":"ui");oa({objectId:e,category:a,onApply:async o=>{var g,h;let l=window.applyAssetToSlot,c=this.getFilenameFromPath(o),d=/render\.asset\.path/i.test(t)||/\.(png|jpg|jpeg|gif|webp)$/i.test(o);typeof l=="function"&&c&&d&&await l(e,c,a),await this.updateManager.updateProperty(e,t,o);let p=window.__debugContext;(h=(g=p==null?void 0:p.options)==null?void 0:g.onPropertyChange)==null||h.call(g,e,t,o);let u=window.__highlightLibrarySlot;typeof u=="function"&&setTimeout(()=>{u(e,a)},500),window.dispatchEvent(new CustomEvent("inspector:refresh"))}})}getFilenameFromPath(e){if(!e)return"";let t=e.split("?")[0].replace(/\\/g,"/");return t.split("/").pop()||t}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let i=n[0],a=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(i):typeof r.schemas=="object"&&(o=r.schemas[i]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,n){let i=window.__openAiEditor;if(typeof i=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),i(e,r,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};var il=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],al=["environment","ui","character","system","backgrounds"],sl=["bg","world","ui"],Xs={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}}},On=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),window.__wizardAssetPicker=null,this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
47
47
  <div class="wizard-card">
48
48
  <div class="wizard-header">
49
49
  <div class="wizard-title">
@@ -95,19 +95,19 @@
95
95
  <div class="wizard-field-group">
96
96
  <label class="wizard-label required">Category</label>
97
97
  <select class="wizard-select" data-field="category">
98
- ${ul.map(e=>`<option value="${e}">${e}</option>`).join("")}
98
+ ${al.map(e=>`<option value="${e}">${e}</option>`).join("")}
99
99
  </select>
100
100
  </div>
101
101
  <div class="wizard-field-group">
102
102
  <label class="wizard-label required">Screen</label>
103
103
  <select class="wizard-select" data-field="screenId" required>
104
- ${pl.map(e=>`<option value="${e.value}">${e.label}</option>`).join("")}
104
+ ${il.map(e=>`<option value="${e.value}">${e.label}</option>`).join("")}
105
105
  </select>
106
106
  </div>
107
107
  <div class="wizard-field-group">
108
108
  <label class="wizard-label required">Layer</label>
109
109
  <select class="wizard-select" data-field="layer">
110
- ${gl.map(e=>`<option value="${e}">${e}</option>`).join("")}
110
+ ${sl.map(e=>`<option value="${e}">${e}</option>`).join("")}
111
111
  </select>
112
112
  </div>
113
113
  </div>
@@ -270,7 +270,7 @@
270
270
  <label class="wizard-label">Logic Component</label>
271
271
  <select class="wizard-select" data-field="logicId">
272
272
  <option value="">None</option>
273
- ${Object.keys(ar).map(e=>`<option value="${e}">${e}</option>`).join("")}
273
+ ${Object.keys(Xs).map(e=>`<option value="${e}">${e}</option>`).join("")}
274
274
  </select>
275
275
  </div>
276
276
  <div class="wizard-field-group">
@@ -297,14 +297,14 @@
297
297
  <div class="wizard-type-icon">${t}</div>
298
298
  <div class="wizard-type-name">${n}</div>
299
299
  </button>
300
- `}attachEventListeners(){if(!this.modal||!this.state)return;this.modal.addEventListener("click",t=>{var a;let n=t.target,i=n.dataset.action||((a=n.closest("[data-action]"))==null?void 0:a.getAttribute("data-action"));if(i)switch(i){case"close":case"cancel":this.close();break;case"back":this.goToStep(this.state.step-1);break;case"next":this.state.step<6?this.goToStep(this.state.step+1):this.submit();break}}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-asset-action]");if(!i)return;let a=i.dataset.assetAction;a&&(t.preventDefault(),this.handleAssetAction(a))}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-object-type]");if(!i)return;let a=i.dataset.objectType;a&&this.setObjectType(a)}),Array.from(this.modal.querySelectorAll("[data-field]")).forEach(t=>{let n=()=>this.handleFieldChange(t);t.addEventListener("input",n),t.addEventListener("change",n)}),this.modal.addEventListener("click",t=>{t.target===this.modal&&this.close()})}handleAssetAction(e){if(this.state)switch(e){case"library":this.openLibraryPicker();break;case"upload":this.openUploadPicker();break;case"ai":this.openAiPicker();break;default:break}}openLibraryPicker(){if(!this.state)return;this.setAssetPickerHint("Select an asset from the Library tab."),window.__wizardAssetPicker={onPick:t=>{this.state.assetPath=t,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__debugContext;if(e){e.activeTab="library";let t=window.__updateWorkbenchTabs;typeof t=="function"&&t()}}openUploadPicker(){if(!this.state)return;this.setAssetPickerHint("Upload an image to add it to the library.");let e=this.state.instanceId||"new_asset",t=this.state.category||"environment";ma({objectId:e,category:t,onApply:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}})}openAiPicker(){if(!this.state)return;this.setAssetPickerHint('Generate and click "Save to Library" to use it here.'),window.__wizardAssetPicker={onPick:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__openAiEditor;if(typeof e!="function"){alert("AI Editor is not available.");return}let t=this.state.displayName||this.state.instanceId||"new asset";e(this.state.instanceId||"new_asset",`Create an image for ${t}`,"",{})}setAssetPickerHint(e){if(!this.modal)return;let t=this.modal.querySelector("[data-asset-picker-hint]");if(t){if(!e){t.style.display="none",t.textContent="";return}t.textContent=e,t.style.display="block"}}handleFieldChange(e){if(!this.state)return;let t=e.dataset.field;if(t){if(e instanceof HTMLInputElement&&e.type==="checkbox")this.state[t]=e.checked;else if(e instanceof HTMLInputElement&&e.type==="number"){let n=e.value===""?0:Number(e.value);this.state[t]=Number.isNaN(n)?0:n}else this.state[t]=e.value;t==="anchorPreset"&&this.applyAnchorPreset(this.state.anchorPreset),t==="logicId"&&this.applyLogicDefaults(this.state.logicId),this.updateStepUI()}}setObjectType(e){this.state&&(this.state.objectType=e,this.state.scale=e==="sprite"||e==="ui-image"?.2:1,(e==="ui-text"||e==="ui-image")&&(this.state.category="ui",this.state.layer="ui"),this.updateStepUI())}applyAnchorPreset(e){if(!this.state)return;let t={"top-left":[0,0],"top-center":[.5,0],"top-right":[1,0],"left-center":[0,.5],center:[.5,.5],"right-center":[1,.5],"bottom-left":[0,1],"bottom-center":[.5,1],"bottom-right":[1,1]};if(e!=="custom"&&t[e]){let[n,i]=t[e];this.state.anchorX=n,this.state.anchorY=i}}applyLogicDefaults(e){if(!this.state)return;if(!e){this.state.logicPropsRaw="";return}let t=ar[e];t&&(this.state.logicPropsRaw=JSON.stringify(t,null,2))}goToStep(e){if(!this.state)return;let t=Math.max(1,Math.min(6,e));this.state.step=t,this.updateStepUI()}updateStepUI(){if(!this.modal||!this.state)return;Array.from(this.modal.querySelectorAll(".wizard-step")).forEach(t=>{let n=Number(t.dataset.step||"0");t.classList.toggle("active",n===this.state.step)}),this.updateProgressDots(),this.updateTypeSections(),this.syncFieldValues(),this.updatePreview(),this.updateActionButtons()}updateProgressDots(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-wizard-progress]");if(!e)return;let t=Array.from({length:6},(n,i)=>{let a=i+1;return`
300
+ `}attachEventListeners(){if(!this.modal||!this.state)return;this.modal.addEventListener("click",t=>{var a;let n=t.target,i=n.dataset.action||((a=n.closest("[data-action]"))==null?void 0:a.getAttribute("data-action"));if(i)switch(i){case"close":case"cancel":this.close();break;case"back":this.goToStep(this.state.step-1);break;case"next":this.state.step<6?this.goToStep(this.state.step+1):this.submit();break}}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-asset-action]");if(!i)return;let a=i.dataset.assetAction;a&&(t.preventDefault(),this.handleAssetAction(a))}),this.modal.addEventListener("click",t=>{let i=t.target.closest("[data-object-type]");if(!i)return;let a=i.dataset.objectType;a&&this.setObjectType(a)}),Array.from(this.modal.querySelectorAll("[data-field]")).forEach(t=>{let n=()=>this.handleFieldChange(t);t.addEventListener("input",n),t.addEventListener("change",n)}),this.modal.addEventListener("click",t=>{t.target===this.modal&&this.close()})}handleAssetAction(e){if(this.state)switch(e){case"library":this.openLibraryPicker();break;case"upload":this.openUploadPicker();break;case"ai":this.openAiPicker();break;default:break}}openLibraryPicker(){if(!this.state)return;this.setAssetPickerHint("Select an asset from the Library tab."),window.__wizardAssetPicker={onPick:t=>{this.state.assetPath=t,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__debugContext;if(e){e.activeTab="library";let t=window.__updateWorkbenchTabs;typeof t=="function"&&t()}}openUploadPicker(){if(!this.state)return;this.setAssetPickerHint("Upload an image to add it to the library.");let e=this.state.instanceId||"new_asset",t=this.state.category||"environment";oa({objectId:e,category:t,onApply:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}})}openAiPicker(){if(!this.state)return;this.setAssetPickerHint('Generate and click "Save to Library" to use it here.'),window.__wizardAssetPicker={onPick:n=>{this.state.assetPath=n,this.setAssetPickerHint(""),this.updateStepUI()}};let e=window.__openAiEditor;if(typeof e!="function"){alert("AI Editor is not available.");return}let t=this.state.displayName||this.state.instanceId||"new asset";e(this.state.instanceId||"new_asset",`Create an image for ${t}`,"",{})}setAssetPickerHint(e){if(!this.modal)return;let t=this.modal.querySelector("[data-asset-picker-hint]");if(t){if(!e){t.style.display="none",t.textContent="";return}t.textContent=e,t.style.display="block"}}handleFieldChange(e){if(!this.state)return;let t=e.dataset.field;if(t){if(e instanceof HTMLInputElement&&e.type==="checkbox")this.state[t]=e.checked;else if(e instanceof HTMLInputElement&&e.type==="number"){let n=e.value===""?0:Number(e.value);this.state[t]=Number.isNaN(n)?0:n}else this.state[t]=e.value;t==="anchorPreset"&&this.applyAnchorPreset(this.state.anchorPreset),t==="logicId"&&this.applyLogicDefaults(this.state.logicId),this.updateStepUI()}}setObjectType(e){this.state&&(this.state.objectType=e,this.state.scale=e==="sprite"||e==="ui-image"?.2:1,(e==="ui-text"||e==="ui-image")&&(this.state.category="ui",this.state.layer="ui"),this.updateStepUI())}applyAnchorPreset(e){if(!this.state)return;let t={"top-left":[0,0],"top-center":[.5,0],"top-right":[1,0],"left-center":[0,.5],center:[.5,.5],"right-center":[1,.5],"bottom-left":[0,1],"bottom-center":[.5,1],"bottom-right":[1,1]};if(e!=="custom"&&t[e]){let[n,i]=t[e];this.state.anchorX=n,this.state.anchorY=i}}applyLogicDefaults(e){if(!this.state)return;if(!e){this.state.logicPropsRaw="";return}let t=Xs[e];t&&(this.state.logicPropsRaw=JSON.stringify(t,null,2))}goToStep(e){if(!this.state)return;let t=Math.max(1,Math.min(6,e));this.state.step=t,this.updateStepUI()}updateStepUI(){if(!this.modal||!this.state)return;Array.from(this.modal.querySelectorAll(".wizard-step")).forEach(t=>{let n=Number(t.dataset.step||"0");t.classList.toggle("active",n===this.state.step)}),this.updateProgressDots(),this.updateTypeSections(),this.syncFieldValues(),this.updatePreview(),this.updateActionButtons()}updateProgressDots(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-wizard-progress]");if(!e)return;let t=Array.from({length:6},(n,i)=>{let a=i+1;return`
301
301
  <div class="wizard-step-indicator">
302
302
  <span class="wizard-step-dot ${a===this.state.step?"active":a<this.state.step?"completed":""}"></span>
303
303
  <span class="wizard-step-label">Step ${a}</span>
304
304
  </div>
305
305
  `});e.innerHTML=t.join("")}updateTypeSections(){if(!this.modal||!this.state)return;let e=this.state.objectType;Array.from(this.modal.querySelectorAll("[data-type-section]")).forEach(i=>{let a=i.dataset.typeSection,o=a==="sprite"&&(e==="sprite"||e==="ui-image")||a===e;i.style.display=o?"block":"none"});let n=this.modal.querySelector("[data-type-help]");if(n){let i=e==="ui-text"?"UI text uses the UI renderer with font settings.":e==="graphics"?"Graphics are simple shapes with width/height and fill.":e==="container"?"Containers are empty parents for grouping objects.":"Sprite/UI image uses image assets.";n.textContent=i}}syncFieldValues(){if(!this.modal||!this.state)return;let e=this.state;Array.from(this.modal.querySelectorAll("[data-field]")).forEach(i=>{let a=i.dataset.field;if(!a)return;let r=e[a];i instanceof HTMLInputElement&&i.type==="checkbox"?i.checked=!!r:typeof r!="undefined"&&(i.value=String(r))}),Array.from(this.modal.querySelectorAll("[data-object-type]")).forEach(i=>{i.classList.toggle("selected",i.dataset.objectType===this.state.objectType)})}updatePreview(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-preview-json]"),t=this.modal.querySelector("[data-validation-errors]");if(!e||!t)return;let n=this.buildPayload();e.textContent=JSON.stringify(n,null,2);let i=this.validate();i.length>0?(t.style.display="block",t.textContent=i.join(`
306
306
  `)):(t.style.display="none",t.textContent="")}updateActionButtons(){if(!this.modal||!this.state)return;let e=this.modal.querySelector('[data-action="back"]'),t=this.modal.querySelector('[data-action="next"]');e&&(e.disabled=this.state.step===1),t&&(t.textContent=this.state.step===6?"Create":"Next",t.disabled=this.state.step===6&&this.validate().length>0)}validate(){if(!this.state)return[];let e=[],t=this.state.instanceId.trim();return t||e.push("Object ID is required."),t.startsWith("json.")&&e.push('Object ID must not start with "json." (instance id only).'),t&&!/^[a-zA-Z0-9._-]+$/.test(t)&&e.push("Object ID must use letters, numbers, dot, dash, or underscore."),t&&!this.isInstanceIdUnique(t)&&e.push(`Object ID "${t}" already exists.`),(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&!this.state.assetPath.trim()&&e.push("Asset path is required for image-based objects."),this.state.objectType==="ui-text"&&!this.state.text.trim()&&e.push("Text content is required for UI Text."),e}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}buildPayload(){if(!this.state)return{};let e=this.state.instanceId.trim(),t=`json.${e}`;return{screenId:this.state.screenId,instanceId:e,objectConfigId:t,layer:this.state.layer,config:this.buildObjectConfig(t),forceSync:!0}}buildObjectConfig(e){if(!this.state)return{};let t=this.state.category||"environment",n={identity:{id:e,category:t},transform:{position:{x:this.state.positionX,y:this.state.positionY},offset:{x:this.state.offsetX,y:this.state.offsetY},scale:this.state.scale,rotation:this.state.rotation,anchor:this.state.anchorPreset==="custom"?{x:this.state.anchorX,y:this.state.anchorY}:this.state.anchorPreset,position_ratio:null,position_mode:this.state.positionMode},render:{alpha:this.state.alpha,visible:!0,tint:this.state.tint||null,z_index:this.state.zIndex},instance_id:this.state.instanceId.trim(),object_config:e};return(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&(n.render.asset={type:"image",path:this.normalizeAssetPath(this.state.assetPath.trim())}),this.state.objectType==="ui-text"&&(n.ui={kind:"text",renderMode:"text",text:this.state.text,font:this.state.font,fontSize:this.state.fontSize,letterSpacing:this.state.letterSpacing,align:this.state.align,color:this.state.tint||"#FFFFFF"},n.render.tint=null),this.state.objectType==="graphics"&&(n.effects={width:this.state.graphicsWidth,height:this.state.graphicsHeight,fill_color:this.state.graphicsFill,fill_alpha:this.state.graphicsAlpha}),this.state.interactionEnabled&&(n.interaction={enabled:!0,drag:{enabled:this.state.dragEnabled},hover:{enabled:this.state.hoverEnabled},click:{enabled:this.state.clickEnabled}}),this.state.logicId&&(n.logic={id:this.state.logicId,props:this.parseLogicProps(this.state.logicPropsRaw)}),n}parseLogicProps(e){if(!e||!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}normalizeAssetPath(e){return!e||e.startsWith("raw/")?e:e.startsWith("/raw/")?e.replace(/^\/raw\//,"raw/"):e}async submit(){var n;if(!this.state)return;if(this.validate().length>0){this.updatePreview();return}let t=this.buildPayload();try{let i=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),a=await i.json().catch(()=>({}));if(!i.ok||(a==null?void 0:a.success)===!1){let r=((n=a==null?void 0:a.errors)==null?void 0:n.join(`
307
- `))||(a==null?void 0:a.error)||"Failed to create object.";alert(r);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),this.close()}catch(i){alert(`Failed to create object: ${i instanceof Error?i.message:String(i)}`)}}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("[AddObjectWizard] Failed to sync screens:",e)}}};var qn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.options=e}open(e){this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=`
307
+ `))||(a==null?void 0:a.error)||"Failed to create object.";alert(r);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),this.close()}catch(i){alert(`Failed to create object: ${i instanceof Error?i.message:String(i)}`)}}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("[AddObjectWizard] Failed to sync screens:",e)}}};var Rn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.options=e}open(e){this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=`
308
308
  <div class="context-menu-item" data-action="duplicate">Duplicate</div>
309
309
  <div class="context-menu-item" data-action="rename">Rename</div>
310
310
  <div class="context-menu-item" data-action="move">Move to Screen</div>
@@ -317,7 +317,7 @@
317
317
  OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceId:this.options.objectId,newInstanceId:t,shareConfig:n,screenId:this.options.screenId})}),d=await c.json().catch(()=>({}));if(!c.ok||(d==null?void 0:d.success)===!1){let p=((i=d==null?void 0:d.errors)==null?void 0:i.join(`
318
318
  `))||(d==null?void 0:d.error)||"Duplicate failed.";alert(p);return}(r=(a=this.options).onRefresh)==null||r.call(a),(l=(o=this.options).onSelect)==null||l.call(o,t),this.close()}catch(c){alert(`Duplicate failed: ${c instanceof Error?c.message:String(c)}`)}}async handleRename(){var t,n,i,a,r;let e=window.prompt("New instance ID",this.options.objectId);if(!(!e||e===this.options.objectId)){if(!this.isInstanceIdUnique(e)){alert(`Instance ID "${e}" already exists.`);return}try{let o=await fetch("/api/objects/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,screenId:this.options.screenId,newInstanceId:e})}),l=await o.json().catch(()=>({}));if(!o.ok||(l==null?void 0:l.success)===!1){let c=((t=l==null?void 0:l.errors)==null?void 0:t.join(`
319
319
  `))||(l==null?void 0:l.error)||"Rename failed.";alert(c);return}(i=(n=this.options).onRefresh)==null||i.call(n),(r=(a=this.options).onSelect)==null||r.call(a,e),this.close()}catch(o){alert(`Rename failed: ${o instanceof Error?o.message:String(o)}`)}}}async handleMove(){var n,i,a;let e=window.prompt("Move to screen (loading/start/gameplay/tutorial/endgame)",this.options.screenId);if(!e)return;let t=e.trim();if(!["loading","start","gameplay","tutorial","endgame"].includes(t)){alert("Invalid screen. Use: loading, start, gameplay, tutorial, endgame.");return}if(t!==this.options.screenId){if(this.options.onMoveRequest){this.options.onMoveRequest(this.options.objectId,t),this.close();return}try{let r=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,fromScreenId:this.options.screenId,toScreenId:t})}),o=await r.json().catch(()=>({}));if(!r.ok||(o==null?void 0:o.success)===!1){let l=((n=o==null?void 0:o.errors)==null?void 0:n.join(`
320
- `))||(o==null?void 0:o.error)||"Move failed.";alert(l);return}(a=(i=this.options).onRefresh)==null||a.call(i),this.close()}catch(r){alert(`Move failed: ${r instanceof Error?r.message:String(r)}`)}}}handleCopyConfig(){var i,a;let e=window.getEditableObjectConfig,t=typeof e=="function"?e(this.options.objectId):null;if(!t){let r=window.__editableObjectConfigs;r&&typeof r.get=="function"&&(t=(i=r.get(this.options.objectId))!=null?i:null)}if(!t){alert("Config not found.");return}let n=JSON.stringify(t,null,2);(a=navigator.clipboard)==null||a.writeText(n).catch(()=>{alert("Failed to copy to clipboard.")}),this.close()}handleOpenInspector(){var t,n;let e=window.__previewSelectObject;typeof e=="function"&&e(this.options.objectId),(n=(t=this.options).onSelect)==null||n.call(t,this.options.objectId),this.close()}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}};var Jt=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],Vn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.templates=[];this.isLoadingTemplates=!1;this.targetScreen="gameplay";this.view="root";this.templateQuery="";this.templateGroup=null;this.options=e}getTargetScreenStorageKey(){return`handler_preview_add_menu_target_screen::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}async open(e){await this.loadTemplates(),this.loadTargetScreen(),this.view="root",this.templateQuery="",this.templateGroup=null,this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}async loadTemplates(){if(!this.isLoadingTemplates){this.isLoadingTemplates=!0;try{let e=await fetch("/api/objects/templates");if(e.ok){let t=await e.json();this.templates=Array.isArray(t.templates)?t.templates:[]}}catch(e){console.warn("[AddObjectMenu] Failed to load templates:",e),this.templates=[]}finally{this.isLoadingTemplates=!1}}}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=this.renderMenuHtml(),this.menu=e,this.updateTargetScreenUI()}positionMenu(e){if(!this.menu)return;let{x:t,y:n}=e;this.menu.style.left=`${t}px`,this.menu.style.top=`${n}px`;let i=this.menu.getBoundingClientRect(),a=i.right-window.innerWidth,r=i.bottom-window.innerHeight;a>0&&(this.menu.style.left=`${t-a-8}px`),r>0&&(this.menu.style.top=`${n-r-8}px`)}attachListeners(){this.menu&&(this.menu.addEventListener("click",e=>{let t=e.target,n=t==null?void 0:t.closest("[data-action]");if(!n||n.classList.contains("disabled"))return;let i=n.dataset.action;if(!i)return;if(e.preventDefault(),e.stopPropagation(),i==="set-screen"){let d=n.dataset.screenId;if(!d||!Jt.some(p=>p.value===d))return;this.setTargetScreen(d);return}if(i==="open-view"){let d=(n.dataset.view||"").trim();(d==="templates"||d==="templates-group"||d==="screens"||d==="systems"||d==="root")&&this.setView(d);return}if(i==="back"){this.setView("root");return}if(i==="open-template-group"){let d=(n.dataset.templateGroup||"").trim();if(!d)return;this.templateGroup=d,this.setView("templates-group");return}if(i==="template-pack"){let d=(n.dataset.templatePack||"").trim();(d==="ui"||d==="screen")&&this.handleInstallTemplatePack(d);return}let a=n.dataset.objectType,r=n.dataset.systemType,o=n.dataset.templateId,l=n.dataset.screenId,c=l!=null?l:this.targetScreen;i==="object"&&a?this.handleCreateObject(a,c):i==="system"&&r?this.handleCreateSystem(r,c):i==="template"&&o&&this.handleCreateFromTemplate(o,c)}),this.menu.addEventListener("input",e=>{if(!this.menu)return;let t=e.target,n=t&&t instanceof HTMLInputElement?t:null;n&&n.classList.contains("context-menu-search")&&(this.templateQuery=n.value||"",this.updateMenuContents({preserveTemplateSearchFocus:!0}))}),this.closeHandler=e=>{let t=e.target;this.menu&&t&&this.menu.contains(t)||this.close()},window.addEventListener("click",this.closeHandler),this.keyHandler=e=>{e.key==="Escape"&&this.close()},window.addEventListener("keydown",this.keyHandler))}async promptScreen(e="Select Screen"){return new Promise(t=>{var c,d,p;let n=document.createElement("div");n.className="add-menu-modal-overlay",n.innerHTML=`
320
+ `))||(o==null?void 0:o.error)||"Move failed.";alert(l);return}(a=(i=this.options).onRefresh)==null||a.call(i),this.close()}catch(r){alert(`Move failed: ${r instanceof Error?r.message:String(r)}`)}}}handleCopyConfig(){var i,a;let e=window.getEditableObjectConfig,t=typeof e=="function"?e(this.options.objectId):null;if(!t){let r=window.__editableObjectConfigs;r&&typeof r.get=="function"&&(t=(i=r.get(this.options.objectId))!=null?i:null)}if(!t){alert("Config not found.");return}let n=JSON.stringify(t,null,2);(a=navigator.clipboard)==null||a.writeText(n).catch(()=>{alert("Failed to copy to clipboard.")}),this.close()}handleOpenInspector(){var t,n;let e=window.__previewSelectObject;typeof e=="function"&&e(this.options.objectId),(n=(t=this.options).onSelect)==null||n.call(t,this.options.objectId),this.close()}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let a=t();if(Array.isArray(a))return!a.includes(e)}let n=window.__HANDLER_SCREEN_INDEX,i=n==null?void 0:n.instanceToScreen;return i&&typeof i=="object"?!Object.prototype.hasOwnProperty.call(i,e):!0}};var Ft=[{value:"loading",label:"Loading"},{value:"start",label:"Start"},{value:"gameplay",label:"Gameplay"},{value:"tutorial",label:"Tutorial"},{value:"endgame",label:"Endgame"}],zn=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.templates=[];this.isLoadingTemplates=!1;this.targetScreen="gameplay";this.view="root";this.templateQuery="";this.templateGroup=null;this.options=e}getTargetScreenStorageKey(){return`handler_preview_add_menu_target_screen::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}async open(e){await this.loadTemplates(),this.loadTargetScreen(),this.view="root",this.templateQuery="",this.templateGroup=null,this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}async loadTemplates(){if(!this.isLoadingTemplates){this.isLoadingTemplates=!0;try{let e=await fetch("/api/objects/templates");if(e.ok){let t=await e.json();this.templates=Array.isArray(t.templates)?t.templates:[]}}catch(e){console.warn("[AddObjectMenu] Failed to load templates:",e),this.templates=[]}finally{this.isLoadingTemplates=!1}}}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=this.renderMenuHtml(),this.menu=e,this.updateTargetScreenUI()}positionMenu(e){if(!this.menu)return;let{x:t,y:n}=e;this.menu.style.left=`${t}px`,this.menu.style.top=`${n}px`;let i=this.menu.getBoundingClientRect(),a=i.right-window.innerWidth,r=i.bottom-window.innerHeight;a>0&&(this.menu.style.left=`${t-a-8}px`),r>0&&(this.menu.style.top=`${n-r-8}px`)}attachListeners(){this.menu&&(this.menu.addEventListener("click",e=>{let t=e.target,n=t==null?void 0:t.closest("[data-action]");if(!n||n.classList.contains("disabled"))return;let i=n.dataset.action;if(!i)return;if(e.preventDefault(),e.stopPropagation(),i==="set-screen"){let d=n.dataset.screenId;if(!d||!Ft.some(p=>p.value===d))return;this.setTargetScreen(d);return}if(i==="open-view"){let d=(n.dataset.view||"").trim();(d==="templates"||d==="templates-group"||d==="screens"||d==="systems"||d==="root")&&this.setView(d);return}if(i==="back"){this.setView("root");return}if(i==="open-template-group"){let d=(n.dataset.templateGroup||"").trim();if(!d)return;this.templateGroup=d,this.setView("templates-group");return}if(i==="template-pack"){let d=(n.dataset.templatePack||"").trim();(d==="ui"||d==="screen")&&this.handleInstallTemplatePack(d);return}let a=n.dataset.objectType,r=n.dataset.systemType,o=n.dataset.templateId,l=n.dataset.screenId,c=l!=null?l:this.targetScreen;i==="object"&&a?this.handleCreateObject(a,c):i==="system"&&r?this.handleCreateSystem(r,c):i==="template"&&o&&this.handleCreateFromTemplate(o,c)}),this.menu.addEventListener("input",e=>{if(!this.menu)return;let t=e.target,n=t&&t instanceof HTMLInputElement?t:null;n&&n.classList.contains("context-menu-search")&&(this.templateQuery=n.value||"",this.updateMenuContents({preserveTemplateSearchFocus:!0}))}),this.closeHandler=e=>{let t=e.target;this.menu&&t&&this.menu.contains(t)||this.close()},window.addEventListener("click",this.closeHandler),this.keyHandler=e=>{e.key==="Escape"&&this.close()},window.addEventListener("keydown",this.keyHandler))}async promptScreen(e="Select Screen"){return new Promise(t=>{var c,d,p;let n=document.createElement("div");n.className="add-menu-modal-overlay",n.innerHTML=`
321
321
  <div class="add-menu-modal">
322
322
  <div class="add-menu-modal-header">
323
323
  <div class="add-menu-modal-title">${this.escapeHtml(e)}</div>
@@ -326,7 +326,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
326
326
  <div class="add-menu-modal-body">
327
327
  <label class="add-menu-modal-label">Screen:</label>
328
328
  <select class="add-menu-modal-select" id="screen-select" required>
329
- ${Jt.map((u,g)=>`<option value="${this.escapeHtml(u.value)}" ${g===2?"selected":""}>${this.escapeHtml(u.label)}</option>`).join("")}
329
+ ${Ft.map((u,g)=>`<option value="${this.escapeHtml(u.value)}" ${g===2?"selected":""}>${this.escapeHtml(u.label)}</option>`).join("")}
330
330
  </select>
331
331
  </div>
332
332
  <div class="add-menu-modal-footer">
@@ -334,7 +334,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
334
334
  <button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Confirm</button>
335
335
  </div>
336
336
  </div>
337
- `;let i=()=>{n.parentNode&&n.parentNode.removeChild(n)},a=()=>{let g=n.querySelector("#screen-select").value.trim();if(!g||!Jt.some(h=>h.value===g)){alert("Please select a valid screen.");return}i(),t(g)},r=()=>{i(),t(null)};n.querySelector(".add-menu-modal").addEventListener("click",u=>{u.stopPropagation()}),(c=n.querySelector('[data-action="confirm"]'))==null||c.addEventListener("click",a),(d=n.querySelector('[data-action="cancel"]'))==null||d.addEventListener("click",r),(p=n.querySelector(".add-menu-modal-close"))==null||p.addEventListener("click",r),n.addEventListener("click",u=>{u.target===n&&r()});let l=n.querySelector("#screen-select");l.addEventListener("keydown",u=>{u.key==="Enter"?(u.preventDefault(),a()):u.key==="Escape"&&(u.preventDefault(),r())}),document.body.appendChild(n),l.focus()})}loadTargetScreen(){try{let t=(window.localStorage.getItem(this.getTargetScreenStorageKey())||"").trim();Jt.some(n=>n.value===t)?this.targetScreen=t:this.targetScreen="gameplay"}catch{this.targetScreen="gameplay"}}setTargetScreen(e){this.targetScreen=e;try{window.localStorage.setItem(this.getTargetScreenStorageKey(),e)}catch{}this.updateTargetScreenUI()}updateTargetScreenUI(){let e=this.menu;if(!e)return;Array.from(e.querySelectorAll(".context-menu-screen-chip[data-screen-id]")).forEach(n=>{let i=n.dataset.screenId;n.classList.toggle("active",i===this.targetScreen)})}setView(e){var t;if(this.view=e,e!=="templates-group"&&(this.templateGroup=null),this.updateMenuContents(),e==="templates"||e==="templates-group"){let n=(t=this.menu)==null?void 0:t.querySelector(".context-menu-search");n&&n.focus()}}updateMenuContents(e){if(!this.menu)return;let t=!!(e!=null&&e.preserveTemplateSearchFocus)&&document.activeElement===this.menu.querySelector(".context-menu-search");if(this.menu.innerHTML=this.renderMenuHtml(),this.updateTargetScreenUI(),t){let n=this.menu.querySelector(".context-menu-search");n==null||n.focus(),n&&(n.selectionStart=n.selectionEnd=n.value.length)}}renderMenuHtml(){return this.view==="templates"?this.renderTemplatesView():this.view==="templates-group"?this.renderTemplatesGroupView():this.view==="screens"?this.renderScreensView():this.view==="systems"?this.renderSystemsView():this.renderRootView()}getPackTemplateIds(e){return e==="ui"?["template.ui.rotating_logo","template.ui.floating_cta_badge","template.ui.bottom_cta_button","template.ui.hand_pointer","template.ui.title_banner","template.ui.instruction_text","template.ui.score_hud"]:["template.screen.rotating_coin","template.screen.rotating_gem","template.screen.tap_destroy_target","template.screen.draggable_piece","template.screen.snap_slot","template.screen.collectable_coin","template.screen.player_swerve","template.screen.enemy_damageable"]}getMissingPackTemplateIds(e){let t=new Set(this.templates.map(n=>String(n.id||"").toLowerCase()));return this.getPackTemplateIds(e).filter(n=>!t.has(n.toLowerCase()))}async handleInstallTemplatePack(e){var t;try{let i=await fetch(e==="ui"?"/api/templates/ui":"/api/templates/screen",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),a=await i.json().catch(()=>({}));if(!i.ok||(a==null?void 0:a.success)===!1){let r=((t=a==null?void 0:a.errors)==null?void 0:t.join(`
337
+ `;let i=()=>{n.parentNode&&n.parentNode.removeChild(n)},a=()=>{let g=n.querySelector("#screen-select").value.trim();if(!g||!Ft.some(h=>h.value===g)){alert("Please select a valid screen.");return}i(),t(g)},r=()=>{i(),t(null)};n.querySelector(".add-menu-modal").addEventListener("click",u=>{u.stopPropagation()}),(c=n.querySelector('[data-action="confirm"]'))==null||c.addEventListener("click",a),(d=n.querySelector('[data-action="cancel"]'))==null||d.addEventListener("click",r),(p=n.querySelector(".add-menu-modal-close"))==null||p.addEventListener("click",r),n.addEventListener("click",u=>{u.target===n&&r()});let l=n.querySelector("#screen-select");l.addEventListener("keydown",u=>{u.key==="Enter"?(u.preventDefault(),a()):u.key==="Escape"&&(u.preventDefault(),r())}),document.body.appendChild(n),l.focus()})}loadTargetScreen(){try{let t=(window.localStorage.getItem(this.getTargetScreenStorageKey())||"").trim();Ft.some(n=>n.value===t)?this.targetScreen=t:this.targetScreen="gameplay"}catch{this.targetScreen="gameplay"}}setTargetScreen(e){this.targetScreen=e;try{window.localStorage.setItem(this.getTargetScreenStorageKey(),e)}catch{}this.updateTargetScreenUI()}updateTargetScreenUI(){let e=this.menu;if(!e)return;Array.from(e.querySelectorAll(".context-menu-screen-chip[data-screen-id]")).forEach(n=>{let i=n.dataset.screenId;n.classList.toggle("active",i===this.targetScreen)})}setView(e){var t;if(this.view=e,e!=="templates-group"&&(this.templateGroup=null),this.updateMenuContents(),e==="templates"||e==="templates-group"){let n=(t=this.menu)==null?void 0:t.querySelector(".context-menu-search");n&&n.focus()}}updateMenuContents(e){if(!this.menu)return;let t=!!(e!=null&&e.preserveTemplateSearchFocus)&&document.activeElement===this.menu.querySelector(".context-menu-search");if(this.menu.innerHTML=this.renderMenuHtml(),this.updateTargetScreenUI(),t){let n=this.menu.querySelector(".context-menu-search");n==null||n.focus(),n&&(n.selectionStart=n.selectionEnd=n.value.length)}}renderMenuHtml(){return this.view==="templates"?this.renderTemplatesView():this.view==="templates-group"?this.renderTemplatesGroupView():this.view==="screens"?this.renderScreensView():this.view==="systems"?this.renderSystemsView():this.renderRootView()}getPackTemplateIds(e){return e==="ui"?["template.ui.rotating_logo","template.ui.floating_cta_badge","template.ui.bottom_cta_button","template.ui.hand_pointer","template.ui.title_banner","template.ui.instruction_text","template.ui.score_hud"]:["template.screen.rotating_coin","template.screen.rotating_gem","template.screen.tap_destroy_target","template.screen.draggable_piece","template.screen.snap_slot","template.screen.collectable_coin","template.screen.player_swerve","template.screen.enemy_damageable"]}getMissingPackTemplateIds(e){let t=new Set(this.templates.map(n=>String(n.id||"").toLowerCase()));return this.getPackTemplateIds(e).filter(n=>!t.has(n.toLowerCase()))}async handleInstallTemplatePack(e){var t;try{let i=await fetch(e==="ui"?"/api/templates/ui":"/api/templates/screen",{method:"POST",headers:{"Content-Type":"application/json"},body:"{}"}),a=await i.json().catch(()=>({}));if(!i.ok||(a==null?void 0:a.success)===!1){let r=((t=a==null?void 0:a.errors)==null?void 0:t.join(`
338
338
  `))||(a==null?void 0:a.error)||"Failed to install templates.";alert(r);return}await this.loadTemplates(),this.updateMenuContents()}catch(n){alert(`Failed to install templates: ${n instanceof Error?n.message:String(n)}`)}}renderRootView(){let e=this.templates.length;return`
339
339
  ${this.renderTargetScreenSection()}
340
340
  <div class="context-menu-section-title">Objects</div>
@@ -383,7 +383,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
383
383
  `}renderTargetScreenSection(){return`
384
384
  <div class="context-menu-section-title">Target Screen</div>
385
385
  <div class="context-menu-screen-grid">
386
- ${Jt.map(e=>`
386
+ ${Ft.map(e=>`
387
387
  <button class="context-menu-screen-chip ${e.value===this.targetScreen?"active":""}" type="button" data-action="set-screen" data-screen-id="${this.escapeHtml(e.value)}">
388
388
  ${this.escapeHtml(e.label)}
389
389
  </button>
@@ -536,18 +536,18 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
536
536
  <button class="add-menu-modal-btn add-menu-modal-btn-primary" type="button" data-action="confirm">Create Spawner</button>
537
537
  </div>
538
538
  </div>
539
- `;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},d=t.querySelectorAll(".add-menu-modal-tab"),p=t.querySelectorAll(".add-menu-modal-tab-content");d.forEach(v=>{v.addEventListener("click",()=>{var L;let S=v.dataset.tab;d.forEach(M=>M.classList.remove("active")),p.forEach(M=>M.classList.remove("active")),v.classList.add("active"),(L=t.querySelector(`[data-tab-content="${S}"]`))==null||L.classList.add("active")})});let u=v=>{let S=v.trim();if(!S)return null;try{return JSON.parse(S)}catch{return null}},g=()=>{var G;let v=t.querySelector("#spawner-instance-id").value.trim(),S=t.querySelector("#spawner-template-id").value.trim(),L=t.querySelector("#spawner-spawn-templates").value,M=t.querySelector("#spawner-position-source").value.trim(),O=t.querySelector("#spawner-point-mode").value.trim(),w=t.querySelector("#spawner-spawn-points").value,P=t.querySelector("#spawner-pattern").value.trim(),_=Number(t.querySelector("#spawner-rate").value.trim()),T=Number(t.querySelector("#spawner-pool").value.trim()),I=Number(t.querySelector("#spawner-lifetime").value.trim()),C=t.querySelector("#spawner-return-on-invisible").checked,A=t.querySelector("#spawner-movement").value.trim(),E=Number(t.querySelector("#spawner-vel-x").value.trim()),x=Number(t.querySelector("#spawner-vel-y").value.trim()),j=t.querySelector("#spawner-velocity-range").value,k=u(L),R=Array.isArray(k)&&k.length?k:null,z=typeof((G=R==null?void 0:R[0])==null?void 0:G.templateId)=="string"?String(R[0].templateId):S;if(!v){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let N={templateId:z,spawnPattern:P,spawnRate:Number.isFinite(_)?_:650,poolSize:Number.isFinite(T)?T:18,returnOnInvisible:C,positionSource:M,spawnPointMode:O,movementMode:A,lifetime:Number.isFinite(I)?I:5e3};R&&(N.spawnTemplates=R);let Y=u(w);Array.isArray(Y)&&(N.spawnPoints=Y),Number.isFinite(E)&&Number.isFinite(x)&&(N.velocity={x:E,y:x});let B=u(j);B&&typeof B=="object"&&(N.velocityRange=B),c(),e({templateId:z,instanceId:v,spawnerProps:N})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",v=>v.stopPropagation()),(f=t.querySelector('[data-action="confirm"]'))==null||f.addEventListener("click",g),(y=t.querySelector('[data-action="cancel"]'))==null||y.addEventListener("click",h),(b=t.querySelector(".add-menu-modal-close"))==null||b.addEventListener("click",h),t.addEventListener("click",v=>{v.target===t&&h()}),document.body.appendChild(t),t.querySelector("#spawner-instance-id").focus()})}sanitizeInstanceId(e){let t=e.trim();return!t||!/^[a-zA-Z0-9._-]+$/.test(t)?null:t}buildDefaultConfig(e,t,n){let i=`json.${t}`,a={identity:{id:i,category:e==="ui-image"||e==="ui-text"?"ui":"environment"},transform:{position:{x:0,y:0},offset:{x:0,y:0},scale:e==="sprite"||e==="ui-image"?.2:1,rotation:0,anchor:"center",position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0},instance_id:t,object_config:i};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${n}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:n,font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",color:"#FFFFFF"}),e==="graphics"&&(a.effects={width:200,height:200,fill_color:"#FFFFFF",fill_alpha:1}),a}async handleCreateObject(e,t){var l,c,d;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(i);if(!a)return;let r=a,o=this.buildDefaultConfig(e,r,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:r,objectConfigId:o.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:o,forceSync:!0})}),u=await p.json().catch(()=>({}));if(!p.ok||(u==null?void 0:u.success)===!1){let h=((l=u==null?void 0:u.errors)==null?void 0:l.join(`
540
- `))||(u==null?void 0:u.error)||"Failed to create object.";alert(h);return}let{trackObjectCreation:g}=await Promise.resolve().then(()=>(Z(),Ue));g(r,n,o),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed")),(d=(c=this.options).onRefresh)==null||d.call(c)}catch(p){alert(`Failed to create object: ${p instanceof Error?p.message:String(p)}`)}}async handleCreateFromTemplate(e,t){var r,o,l;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",a=await this.promptName(i);if(a)try{let c=await fetch("/api/objects/create-from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e,instanceId:a,screenId:n,forceSync:!0})}),d=await c.json().catch(()=>({}));if(!c.ok||(d==null?void 0:d.success)===!1){let p=((r=d==null?void 0:d.errors)==null?void 0:r.join(`
541
- `))||(d==null?void 0:d.error)||"Failed to create from template.";alert(p);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(l=(o=this.options).onRefresh)==null||l.call(o)}catch(c){alert(`Failed to create from template: ${c instanceof Error?c.message:String(c)}`)}}async handleCreateSystem(e,t){var i,a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,S,L,M,O,w,P,_,T,I,C,A;this.close();let n=t!=null?t:await this.promptScreen();if(n){if(e==="collectable-system")try{let E=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((i=x==null?void 0:x.errors)==null?void 0:i.join(`
542
- `))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(r=(a=this.options).onRefresh)==null||r.call(a)}catch(E){alert(`Failed to create collectable system: ${E instanceof Error?E.message:String(E)}`)}if(e==="drag-snap-couples")try{let E=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((o=x==null?void 0:x.errors)==null?void 0:o.join(`
543
- `))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(E){alert(`Failed to create drag-snap system: ${E instanceof Error?E.message:String(E)}`)}if(e==="swerve-collect")try{let E=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((d=x==null?void 0:x.errors)==null?void 0:d.join(`
544
- `))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(u=(p=this.options).onRefresh)==null||u.call(p)}catch(E){alert(`Failed to create swerve collect system: ${E instanceof Error?E.message:String(E)}`)}if(e==="tap-destroy")try{let E=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((g=x==null?void 0:x.errors)==null?void 0:g.join(`
545
- `))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(m=(h=this.options).onRefresh)==null||m.call(h)}catch(E){alert(`Failed to create tap destroy system: ${E instanceof Error?E.message:String(E)}`)}if(e==="scratch-card")try{let E=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((f=x==null?void 0:x.errors)==null?void 0:f.join(`
546
- `))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(b=(y=this.options).onRefresh)==null||b.call(y)}catch(E){alert(`Failed to create scratch card system: ${E instanceof Error?E.message:String(E)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let x=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="start-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let k=((v=j==null?void 0:j.errors)==null?void 0:v.join(`
547
- `))||(j==null?void 0:j.error)||"Failed to create start screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(L=(S=this.options).onRefresh)==null||L.call(S)}catch(E){alert(`Failed to create start screen template: ${E instanceof Error?E.message:String(E)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let x=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="endgame-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let k=((M=j==null?void 0:j.errors)==null?void 0:M.join(`
548
- `))||(j==null?void 0:j.error)||"Failed to create endgame screen template.";alert(k);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(w=(O=this.options).onRefresh)==null||w.call(O)}catch(E){alert(`Failed to create endgame screen template: ${E instanceof Error?E.message:String(E)}`)}if(e==="bullet-system")try{let E=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await E.json().catch(()=>({}));if(!E.ok||(x==null?void 0:x.success)===!1){let j=((P=x==null?void 0:x.errors)==null?void 0:P.join(`
549
- `))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(T=(_=this.options).onRefresh)==null||T.call(_)}catch(E){alert(`Failed to create bullet system: ${E instanceof Error?E.message:String(E)}`)}if(e==="spawner"){let E=await this.promptSpawnerConfig();if(!E)return;let{templateId:x,instanceId:j,spawnerProps:k}=E;try{let R=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,templateId:x,instanceId:j,spawnerProps:k,forceSync:!0})}),z=await R.json().catch(()=>({}));if(!R.ok||(z==null?void 0:z.success)===!1){let N=((I=z==null?void 0:z.errors)==null?void 0:I.join(`
550
- `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(N);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(A=(C=this.options).onRefresh)==null||A.call(C)}catch(R){alert(`Failed to create spawner: ${R instanceof Error?R.message:String(R)}`)}}}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[AddObjectMenu] Failed to sync screens:",e)}}};var Wn=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.selectedIds=new Set;this.lastSelectedIndex=-1;this.objectEntries=[];this.options=null;this.retryTimer=null;this.screenFilter="all";this.isContextMenuOpen=!1;this.systemBundles=new Map;this.collapsedGroups=new Set}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getCollapseStorageKey(){return`handler_preview_scene_collapsed::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}loadCollapsedGroups(){try{let e=window.localStorage.getItem(this.getCollapseStorageKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.collapsedGroups=new Set(t.filter(n=>typeof n=="string")))}catch{}}persistCollapsedGroups(){try{window.localStorage.setItem(this.getCollapseStorageKey(),JSON.stringify(Array.from(this.collapsedGroups)))}catch{}}isCollapsed(e){return this.collapsedGroups.has(e)}setCollapsed(e,t){t?this.collapsedGroups.add(e):this.collapsedGroups.delete(e),this.persistCollapsedGroups()}getCollapseKey(e){return encodeURIComponent(e)}getSystemBundleKey(e,t){return this.getCollapseKey(`bundle:${e}::${t}`)}render(){return`
539
+ `;let c=()=>{t.parentNode&&t.parentNode.removeChild(t)},d=t.querySelectorAll(".add-menu-modal-tab"),p=t.querySelectorAll(".add-menu-modal-tab-content");d.forEach(v=>{v.addEventListener("click",()=>{var P;let E=v.dataset.tab;d.forEach(I=>I.classList.remove("active")),p.forEach(I=>I.classList.remove("active")),v.classList.add("active"),(P=t.querySelector(`[data-tab-content="${E}"]`))==null||P.classList.add("active")})});let u=v=>{let E=v.trim();if(!E)return null;try{return JSON.parse(E)}catch{return null}},g=()=>{var U;let v=t.querySelector("#spawner-instance-id").value.trim(),E=t.querySelector("#spawner-template-id").value.trim(),P=t.querySelector("#spawner-spawn-templates").value,I=t.querySelector("#spawner-position-source").value.trim(),O=t.querySelector("#spawner-point-mode").value.trim(),w=t.querySelector("#spawner-spawn-points").value,k=t.querySelector("#spawner-pattern").value.trim(),_=Number(t.querySelector("#spawner-rate").value.trim()),L=Number(t.querySelector("#spawner-pool").value.trim()),M=Number(t.querySelector("#spawner-lifetime").value.trim()),C=t.querySelector("#spawner-return-on-invisible").checked,A=t.querySelector("#spawner-movement").value.trim(),S=Number(t.querySelector("#spawner-vel-x").value.trim()),x=Number(t.querySelector("#spawner-vel-y").value.trim()),j=t.querySelector("#spawner-velocity-range").value,T=u(P),R=Array.isArray(T)&&T.length?T:null,z=typeof((U=R==null?void 0:R[0])==null?void 0:U.templateId)=="string"?String(R[0].templateId):E;if(!v){alert("Instance ID is required.");return}if(!z){alert("Template ID is required.");return}let N={templateId:z,spawnPattern:k,spawnRate:Number.isFinite(_)?_:650,poolSize:Number.isFinite(L)?L:18,returnOnInvisible:C,positionSource:I,spawnPointMode:O,movementMode:A,lifetime:Number.isFinite(M)?M:5e3};R&&(N.spawnTemplates=R);let Y=u(w);Array.isArray(Y)&&(N.spawnPoints=Y),Number.isFinite(S)&&Number.isFinite(x)&&(N.velocity={x:S,y:x});let F=u(j);F&&typeof F=="object"&&(N.velocityRange=F),c(),e({templateId:z,instanceId:v,spawnerProps:N})},h=()=>{c(),e(null)};t.querySelector(".add-menu-modal").addEventListener("click",v=>v.stopPropagation()),(f=t.querySelector('[data-action="confirm"]'))==null||f.addEventListener("click",g),(y=t.querySelector('[data-action="cancel"]'))==null||y.addEventListener("click",h),(b=t.querySelector(".add-menu-modal-close"))==null||b.addEventListener("click",h),t.addEventListener("click",v=>{v.target===t&&h()}),document.body.appendChild(t),t.querySelector("#spawner-instance-id").focus()})}sanitizeInstanceId(e){let t=e.trim();return!t||!/^[a-zA-Z0-9._-]+$/.test(t)?null:t}buildDefaultConfig(e,t,n){let i=`json.${t}`,a={identity:{id:i,category:e==="ui-image"||e==="ui-text"?"ui":"environment"},transform:{position:{x:0,y:0},offset:{x:0,y:0},scale:e==="sprite"||e==="ui-image"?.2:1,rotation:0,anchor:"center",position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0},instance_id:t,object_config:i};return(e==="sprite"||e==="ui-image")&&(a.render.asset={type:"image",path:`raw/${n}.png`}),e==="ui-text"&&(a.ui={kind:"text",renderMode:"text",text:n,font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",color:"#FFFFFF"}),e==="graphics"&&(a.effects={width:200,height:200,fill_color:"#FFFFFF",fill_alpha:1}),a}async handleCreateObject(e,t){var l,c,d;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e==="ui-text"?"text_1":e==="graphics"?"graphics_1":"sprite_1",a=await this.promptName(i);if(!a)return;let r=a,o=this.buildDefaultConfig(e,r,a);try{let p=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,instanceId:r,objectConfigId:o.identity.id,layer:e==="ui-image"||e==="ui-text"?"ui":"world",config:o,forceSync:!0})}),u=await p.json().catch(()=>({}));if(!p.ok||(u==null?void 0:u.success)===!1){let h=((l=u==null?void 0:u.errors)==null?void 0:l.join(`
540
+ `))||(u==null?void 0:u.error)||"Failed to create object.";alert(h);return}let{trackObjectCreation:g}=await Promise.resolve().then(()=>(te(),Be));g(r,n,o),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed")),(d=(c=this.options).onRefresh)==null||d.call(c)}catch(p){alert(`Failed to create object: ${p instanceof Error?p.message:String(p)}`)}}async handleCreateFromTemplate(e,t){var r,o,l;this.close();let n=t!=null?t:await this.promptScreen();if(!n)return;let i=e.replace(/\.template$/,"").replace(/^json\./,"").replace(/[._]/g,"_")+"_1",a=await this.promptName(i);if(a)try{let c=await fetch("/api/objects/create-from-template",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({templateId:e,instanceId:a,screenId:n,forceSync:!0})}),d=await c.json().catch(()=>({}));if(!c.ok||(d==null?void 0:d.success)===!1){let p=((r=d==null?void 0:d.errors)==null?void 0:r.join(`
541
+ `))||(d==null?void 0:d.error)||"Failed to create from template.";alert(p);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(l=(o=this.options).onRefresh)==null||l.call(o)}catch(c){alert(`Failed to create from template: ${c instanceof Error?c.message:String(c)}`)}}async handleCreateSystem(e,t){var i,a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,E,P,I,O,w,k,_,L,M,C,A;this.close();let n=t!=null?t:await this.promptScreen();if(n){if(e==="collectable-system")try{let S=await fetch("/api/systems/collectable-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((i=x==null?void 0:x.errors)==null?void 0:i.join(`
542
+ `))||(x==null?void 0:x.error)||"Failed to create collectable system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(r=(a=this.options).onRefresh)==null||r.call(a)}catch(S){alert(`Failed to create collectable system: ${S instanceof Error?S.message:String(S)}`)}if(e==="drag-snap-couples")try{let S=await fetch("/api/systems/drag-snap-couples",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((o=x==null?void 0:x.errors)==null?void 0:o.join(`
543
+ `))||(x==null?void 0:x.error)||"Failed to create drag-snap system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(c=(l=this.options).onRefresh)==null||c.call(l)}catch(S){alert(`Failed to create drag-snap system: ${S instanceof Error?S.message:String(S)}`)}if(e==="swerve-collect")try{let S=await fetch("/api/systems/swerve-collect",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((d=x==null?void 0:x.errors)==null?void 0:d.join(`
544
+ `))||(x==null?void 0:x.error)||"Failed to create swerve collect system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(u=(p=this.options).onRefresh)==null||u.call(p)}catch(S){alert(`Failed to create swerve collect system: ${S instanceof Error?S.message:String(S)}`)}if(e==="tap-destroy")try{let S=await fetch("/api/systems/tap-destroy",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((g=x==null?void 0:x.errors)==null?void 0:g.join(`
545
+ `))||(x==null?void 0:x.error)||"Failed to create tap destroy system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(m=(h=this.options).onRefresh)==null||m.call(h)}catch(S){alert(`Failed to create tap destroy system: ${S instanceof Error?S.message:String(S)}`)}if(e==="scratch-card")try{let S=await fetch("/api/systems/scratch-card",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((f=x==null?void 0:x.errors)==null?void 0:f.join(`
546
+ `))||(x==null?void 0:x.error)||"Failed to create scratch card system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(b=(y=this.options).onRefresh)==null||b.call(y)}catch(S){alert(`Failed to create scratch card system: ${S instanceof Error?S.message:String(S)}`)}if(e==="start-screen"||e==="start-screen-no-hand")try{let x=await fetch("/api/systems/start-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="start-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let T=((v=j==null?void 0:j.errors)==null?void 0:v.join(`
547
+ `))||(j==null?void 0:j.error)||"Failed to create start screen template.";alert(T);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(P=(E=this.options).onRefresh)==null||P.call(E)}catch(S){alert(`Failed to create start screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="endgame-screen"||e==="endgame-screen-no-hand")try{let x=await fetch("/api/systems/endgame-screen",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,withHand:e==="endgame-screen"})}),j=await x.json().catch(()=>({}));if(!x.ok||(j==null?void 0:j.success)===!1){let T=((I=j==null?void 0:j.errors)==null?void 0:I.join(`
548
+ `))||(j==null?void 0:j.error)||"Failed to create endgame screen template.";alert(T);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(w=(O=this.options).onRefresh)==null||w.call(O)}catch(S){alert(`Failed to create endgame screen template: ${S instanceof Error?S.message:String(S)}`)}if(e==="bullet-system")try{let S=await fetch("/api/systems/bullet-system",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n})}),x=await S.json().catch(()=>({}));if(!S.ok||(x==null?void 0:x.success)===!1){let j=((k=x==null?void 0:x.errors)==null?void 0:k.join(`
549
+ `))||(x==null?void 0:x.error)||"Failed to create bullet system.";alert(j);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(L=(_=this.options).onRefresh)==null||L.call(_)}catch(S){alert(`Failed to create bullet system: ${S instanceof Error?S.message:String(S)}`)}if(e==="spawner"){let S=await this.promptSpawnerConfig();if(!S)return;let{templateId:x,instanceId:j,spawnerProps:T}=S;try{let R=await fetch("/api/systems/spawner",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({screenId:n,templateId:x,instanceId:j,spawnerProps:T,forceSync:!0})}),z=await R.json().catch(()=>({}));if(!R.ok||(z==null?void 0:z.success)===!1){let N=((M=z==null?void 0:z.errors)==null?void 0:M.join(`
550
+ `))||(z==null?void 0:z.error)||"Failed to create spawner.";alert(N);return}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),(A=(C=this.options).onRefresh)==null||A.call(C)}catch(R){alert(`Failed to create spawner: ${R instanceof Error?R.message:String(R)}`)}}}}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN;await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[AddObjectMenu] Failed to sync screens:",e)}}};var $n=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.selectedIds=new Set;this.lastSelectedIndex=-1;this.objectEntries=[];this.options=null;this.retryTimer=null;this.screenFilter="all";this.isContextMenuOpen=!1;this.systemBundles=new Map;this.collapsedGroups=new Set}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getCollapseStorageKey(){return`handler_preview_scene_collapsed::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}loadCollapsedGroups(){try{let e=window.localStorage.getItem(this.getCollapseStorageKey());if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.collapsedGroups=new Set(t.filter(n=>typeof n=="string")))}catch{}}persistCollapsedGroups(){try{window.localStorage.setItem(this.getCollapseStorageKey(),JSON.stringify(Array.from(this.collapsedGroups)))}catch{}}isCollapsed(e){return this.collapsedGroups.has(e)}setCollapsed(e,t){t?this.collapsedGroups.add(e):this.collapsedGroups.delete(e),this.persistCollapsedGroups()}getCollapseKey(e){return encodeURIComponent(e)}getSystemBundleKey(e,t){return this.getCollapseKey(`bundle:${e}::${t}`)}render(){return`
551
551
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
552
552
  <div class="scene-panel-header" data-panel-handle>
553
553
  <div class="panel-title">
@@ -582,7 +582,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
582
582
  </div>
583
583
  <div class="panel-resize-handle-v" data-panel-resize-v></div>
584
584
  </div>
585
- `}initialize(e,t){var a,r,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(r=this.root)==null?void 0:r.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var S;let h=g.target,m=h==null?void 0:h.closest("[data-collapse-key]");if(m){let L=m.dataset.collapseKey||"";if(!L)return;let M=(S=this.listContainer)==null?void 0:S.querySelector(`[data-collapse-content="${L}"]`),O=this.isCollapsed(L);M&&(M.style.display=O?"":"none"),m.textContent=O?"\u25BE":"\u25B8",this.setCollapsed(L,!O),g.preventDefault(),g.stopPropagation();return}let f=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(f){let L=f.dataset.objectId;if(!L)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(L);return}let y=h==null?void 0:h.closest("[data-system-bundle-action][data-system-bundle-id]");if(!y)return;g.preventDefault(),g.stopPropagation();let b=y.dataset.systemBundleAction,v=y.dataset.systemBundleId;if(!(!b||!v)){if(b==="toggle-visibility"){this.toggleSystemBundleVisibility(v);return}b==="delete"&&this.deleteSystemBundle(v)}});let n=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");n==null||n.addEventListener("click",g=>{g.stopPropagation();let h=n.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let i=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(i){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let g=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof g=="function"&&g().catch(()=>{})}catch{}i.addEventListener("change",()=>{let g=i.value||"all";this.screenFilter=g;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let h=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof h=="function"&&h().catch(()=>{})}catch{}this.refreshObjects()})}(p=this.root)==null||p.addEventListener("click",g=>{let h=g.target;if(!h||h.closest("[data-context-menu]"))return;if(h.tagName==="INPUT"&&h.classList.contains("scene-object-checkbox")){let S=h.dataset.objectId;if(!S)return;g.stopPropagation(),this.toggleBatchSelect(S);return}let m=h.closest(".scene-object-item[data-object-id]");if(!m)return;let f=m.dataset.objectId;if(!f)return;let y=g.ctrlKey||g.metaKey;g.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,f):y?this.toggleBatchSelect(f):this.select(f)}),(u=this.listContainer)==null||u.addEventListener("contextmenu",g=>{var S;let h=g.target,m=h==null?void 0:h.closest("[data-object-id]");if(!m)return;let f=m.dataset.objectId;if(!f)return;g.preventDefault();let y=window.getEditableObjectConfig,b=typeof y=="function"?y(f):null;if(!b){let L=window.__editableObjectConfigs;L&&typeof L.get=="function"&&(b=(S=L.get(f))!=null?S:null)}let v=this.inferScreen(f,b);this.showContextMenu(f,v,g.clientX,g.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){e?(this.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=e):(this.selectedIds.clear(),this.selectedId=null),this.updateSelectionUI()}getSelectedIds(){return Array.from(this.selectedIds)}updateSelectionUI(){var a,r,o,l,c;if(!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{let p=d.dataset.objectId,u=p?this.selectedIds.has(p):!1,g=p===this.selectedId;d.classList.toggle("selected",u),d.classList.toggle("active",g);let h=d.closest(".scene-object-item-wrapper"),m=h==null?void 0:h.querySelector(".scene-object-checkbox");m&&(m.checked=u)});let t=(a=this.root)==null?void 0:a.querySelector("[data-breadcrumbs]"),n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumb-screen]"),i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&n&&i){let d=this.selectedIds.size===1?this.selectedId:null;if(d){let p=window.getEditableObjectConfig,u=typeof p=="function"?p(d):null;if(!u){let y=window.__editableObjectConfigs;y&&typeof y.get=="function"&&(u=(l=y.get(d))!=null?l:null)}let g=this.inferScreen(d,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},m=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||d).toString(),f=this.formatDisplayName(m);n.textContent=h[g]||g,i.textContent=f,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var u;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectListAll,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let i=typeof t=="function"?t():e();if(!Array.isArray(i)||i.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(i=Array.from(g.keys()))}if(!Array.isArray(i)||i.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o={loading:{templates:[],systems:[],objects:[],bundles:new Map},start:{templates:[],systems:[],objects:[],bundles:new Map},gameplay:{templates:[],systems:[],objects:[],bundles:new Map},tutorial:{templates:[],systems:[],objects:[],bundles:new Map},endgame:{templates:[],systems:[],objects:[],bundles:new Map}};this.systemBundles=new Map;let l=g=>{var f,y,b,v,S;let h=(v=(b=(y=(f=window.__editableConfig)==null?void 0:f.objects)==null?void 0:y.get)==null?void 0:b.call(y,g))!=null?v:null;if(h)return h;let m=window.__editableObjectConfigs;return m&&typeof m.get=="function"&&(S=m.get(g))!=null?S:null};i.forEach(g=>{var A,E,x,j,k,R,z;let h=l(g),m=(((A=h==null?void 0:h.identity)==null?void 0:A.category)||"scene").toString(),f=(((E=h==null?void 0:h.identity)==null?void 0:E.id)||g).toString(),y=m.toLowerCase(),b=f.toLowerCase(),v=y.includes("ui")||b.startsWith("ui")||b.includes("label"),S=y==="system",L=((x=h==null?void 0:h.identity)==null?void 0:x.is_template)===!0||b.includes(".template")||g.toLowerCase().includes(".template"),M=typeof((j=h==null?void 0:h.identity)==null?void 0:j.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:M?this.formatDisplayName(M):null,w=this.formatDisplayName(f||g),P=((R=h==null?void 0:h.render)==null?void 0:R.visible)===!1||(h==null?void 0:h.enabled)===!1,_=this.getObjectType(h),T={id:g,label:w,category:m,isUi:v,isTemplate:L,isUnused:P,objectType:_,systemGroupId:M,systemLabel:O},I=this.inferScreen(T.id,h);if(!(this.screenFilter!=="all"&&I!==this.screenFilter||!(!a||T.id.toLowerCase().includes(a)||T.label.toLowerCase().includes(a)))){if(M){let N=this.getSystemBundleKey(I,M),Y=O!=null?O:M,B=o[I],G=B.bundles.get(N);G?(G.entries.push(T),G.objectIds.push(g)):B.bundles.set(N,{key:N,label:Y,objectIds:[g],entries:[T]});let Q=(z=this.systemBundles.get(N))!=null?z:{label:Y,objectIds:[]};Q.label=Y,Q.objectIds.push(g),this.systemBundles.set(N,Q);return}if(L){o[I].templates.push(T);return}S?o[I].systems.push(T):o[I].objects.push(T)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?r:[this.screenFilter],p=d.map(g=>this.renderScreenGroup(g,c[g],o[g])).join("");this.listContainer.innerHTML=p,this.objectEntries=[];for(let g of d){let h=o[g];this.objectEntries.push(...h.templates),h.bundles.forEach(m=>this.objectEntries.push(...m.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 m=this.listContainer.querySelector(`[data-delete-system-group="${g}"]`);m==null||m.addEventListener("click",f=>{f.stopPropagation(),this.deleteSystemGroup(h.systems)})}this.updateSelectionUI()}renderSystemBundle(e,t,n,i){let a=this.isBundleAllHidden(n),r=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=i.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
585
+ `}initialize(e,t){var a,r,o,l,c,d,p,u;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(r=this.root)==null?void 0:r.querySelector("#scene-object-search"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects()),this.loadCollapsedGroups(),(l=this.listContainer)==null||l.addEventListener("click",g=>{var E;let h=g.target,m=h==null?void 0:h.closest("[data-collapse-key]");if(m){let P=m.dataset.collapseKey||"";if(!P)return;let I=(E=this.listContainer)==null?void 0:E.querySelector(`[data-collapse-content="${P}"]`),O=this.isCollapsed(P);I&&(I.style.display=O?"":"none"),m.textContent=O?"\u25BE":"\u25B8",this.setCollapsed(P,!O),g.preventDefault(),g.stopPropagation();return}let f=h==null?void 0:h.closest("[data-object-visibility-toggle][data-object-id]");if(f){let P=f.dataset.objectId;if(!P)return;g.preventDefault(),g.stopPropagation(),this.toggleObjectVisibility(P);return}let y=h==null?void 0:h.closest("[data-system-bundle-action][data-system-bundle-id]");if(!y)return;g.preventDefault(),g.stopPropagation();let b=y.dataset.systemBundleAction,v=y.dataset.systemBundleId;if(!(!b||!v)){if(b==="toggle-visibility"){this.toggleSystemBundleVisibility(v);return}b==="delete"&&this.deleteSystemBundle(v)}});let n=(c=this.root)==null?void 0:c.querySelector("[data-add-object]");n==null||n.addEventListener("click",g=>{g.stopPropagation();let h=n.getBoundingClientRect();this.openAddObjectMenu({x:h.left,y:h.bottom+4})});let i=(d=this.root)==null?void 0:d.querySelector("#scene-screen-filter");if(i){try{let g=window.localStorage.getItem(this.getScreenFilterStorageKey());g&&(this.screenFilter=g)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let g=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof g=="function"&&g().catch(()=>{})}catch{}i.addEventListener("change",()=>{let g=i.value||"all";this.screenFilter=g;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}try{let h=window.__HANDLER_REFRESH_SCREEN_INDEX;typeof h=="function"&&h().catch(()=>{})}catch{}this.refreshObjects()})}(p=this.root)==null||p.addEventListener("click",g=>{let h=g.target;if(!h||h.closest("[data-context-menu]"))return;if(h.tagName==="INPUT"&&h.classList.contains("scene-object-checkbox")){let E=h.dataset.objectId;if(!E)return;g.stopPropagation(),this.toggleBatchSelect(E);return}let m=h.closest(".scene-object-item[data-object-id]");if(!m)return;let f=m.dataset.objectId;if(!f)return;let y=g.ctrlKey||g.metaKey;g.shiftKey&&this.lastSelectedIndex>=0?this.selectRange(this.lastSelectedIndex,f):y?this.toggleBatchSelect(f):this.select(f)}),(u=this.listContainer)==null||u.addEventListener("contextmenu",g=>{var E;let h=g.target,m=h==null?void 0:h.closest("[data-object-id]");if(!m)return;let f=m.dataset.objectId;if(!f)return;g.preventDefault();let y=window.getEditableObjectConfig,b=typeof y=="function"?y(f):null;if(!b){let P=window.__editableObjectConfigs;P&&typeof P.get=="function"&&(b=(E=P.get(f))!=null?E:null)}let v=this.inferScreen(f,b);this.showContextMenu(f,v,g.clientX,g.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){e?(this.selectedIds.clear(),this.selectedIds.add(e),this.selectedId=e):(this.selectedIds.clear(),this.selectedId=null),this.updateSelectionUI()}getSelectedIds(){return Array.from(this.selectedIds)}updateSelectionUI(){var a,r,o,l,c;if(!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{let p=d.dataset.objectId,u=p?this.selectedIds.has(p):!1,g=p===this.selectedId;d.classList.toggle("selected",u),d.classList.toggle("active",g);let h=d.closest(".scene-object-item-wrapper"),m=h==null?void 0:h.querySelector(".scene-object-checkbox");m&&(m.checked=u)});let t=(a=this.root)==null?void 0:a.querySelector("[data-breadcrumbs]"),n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumb-screen]"),i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-object]");if(t&&n&&i){let d=this.selectedIds.size===1?this.selectedId:null;if(d){let p=window.getEditableObjectConfig,u=typeof p=="function"?p(d):null;if(!u){let y=window.__editableObjectConfigs;y&&typeof y.get=="function"&&(u=(l=y.get(d))!=null?l:null)}let g=this.inferScreen(d,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},m=(((c=u==null?void 0:u.identity)==null?void 0:c.id)||d).toString(),f=this.formatDisplayName(m);n.textContent=h[g]||g,i.textContent=f,t.style.display="flex"}else t.style.display="none"}}refreshObjects(){var u;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectListAll,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"&&typeof t!="function"){this.scheduleRetry();return}let i=typeof t=="function"?t():e();if(!Array.isArray(i)||i.length===0){let g=window.__editableObjectConfigs;g&&typeof g.keys=="function"&&(i=Array.from(g.keys()))}if(!Array.isArray(i)||i.length===0){this.scheduleRetry();return}let a=(((u=this.searchInput)==null?void 0:u.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o={loading:{templates:[],systems:[],objects:[],bundles:new Map},start:{templates:[],systems:[],objects:[],bundles:new Map},gameplay:{templates:[],systems:[],objects:[],bundles:new Map},tutorial:{templates:[],systems:[],objects:[],bundles:new Map},endgame:{templates:[],systems:[],objects:[],bundles:new Map}};this.systemBundles=new Map;let l=g=>{var f,y,b,v,E;let h=(v=(b=(y=(f=window.__editableConfig)==null?void 0:f.objects)==null?void 0:y.get)==null?void 0:b.call(y,g))!=null?v:null;if(h)return h;let m=window.__editableObjectConfigs;return m&&typeof m.get=="function"&&(E=m.get(g))!=null?E:null};i.forEach(g=>{var A,S,x,j,T,R,z;let h=l(g),m=(((A=h==null?void 0:h.identity)==null?void 0:A.category)||"scene").toString(),f=(((S=h==null?void 0:h.identity)==null?void 0:S.id)||g).toString(),y=m.toLowerCase(),b=f.toLowerCase(),v=y.includes("ui")||b.startsWith("ui")||b.includes("label"),E=y==="system",P=((x=h==null?void 0:h.identity)==null?void 0:x.is_template)===!0||b.includes(".template")||g.toLowerCase().includes(".template"),I=typeof((j=h==null?void 0:h.identity)==null?void 0:j.system_group)=="string"?h.identity.system_group:null,O=typeof((T=h==null?void 0:h.identity)==null?void 0:T.system_label)=="string"?h.identity.system_label:I?this.formatDisplayName(I):null,w=this.formatDisplayName(f||g),k=((R=h==null?void 0:h.render)==null?void 0:R.visible)===!1||(h==null?void 0:h.enabled)===!1,_=this.getObjectType(h),L={id:g,label:w,category:m,isUi:v,isTemplate:P,isUnused:k,objectType:_,systemGroupId:I,systemLabel:O},M=this.inferScreen(L.id,h);if(!(this.screenFilter!=="all"&&M!==this.screenFilter||!(!a||L.id.toLowerCase().includes(a)||L.label.toLowerCase().includes(a)))){if(I){let N=this.getSystemBundleKey(M,I),Y=O!=null?O:I,F=o[M],U=F.bundles.get(N);U?(U.entries.push(L),U.objectIds.push(g)):F.bundles.set(N,{key:N,label:Y,objectIds:[g],entries:[L]});let ne=(z=this.systemBundles.get(N))!=null?z:{label:Y,objectIds:[]};ne.label=Y,ne.objectIds.push(g),this.systemBundles.set(N,ne);return}if(P){o[M].templates.push(L);return}E?o[M].systems.push(L):o[M].objects.push(L)}});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},d=this.screenFilter==="all"?r:[this.screenFilter],p=d.map(g=>this.renderScreenGroup(g,c[g],o[g])).join("");this.listContainer.innerHTML=p,this.objectEntries=[];for(let g of d){let h=o[g];this.objectEntries.push(...h.templates),h.bundles.forEach(m=>this.objectEntries.push(...m.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 m=this.listContainer.querySelector(`[data-delete-system-group="${g}"]`);m==null||m.addEventListener("click",f=>{f.stopPropagation(),this.deleteSystemGroup(h.systems)})}this.updateSelectionUI()}renderSystemBundle(e,t,n,i){let a=this.isBundleAllHidden(n),r=a?"Show all objects in this system":"Hide all objects in this system",o=a?"is-hidden":"",l=i.map(g=>this.renderEntryItem(g)).join(""),c=this.escapeHtml(e),d=this.getCollapseKey(`system:${e}`),p=this.isCollapsed(d);return`
586
586
  <div class="scene-object-group scene-object-group-bundle" data-system-bundle="${c}">
587
587
  <div class="scene-object-group-title">
588
588
  <button class="scene-object-group-toggle" type="button" data-collapse-key="${d}">${p?"\u25B8":"\u25BE"}</button>
@@ -618,7 +618,7 @@ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{
618
618
  ${e.content}
619
619
  </div>
620
620
  </div>
621
- `}renderScreenGroup(e,t,n){let i=this.getCollapseKey(`screen:${e}`),a=[];if(n.templates.length){let o=this.getCollapseKey(`screen:${e}:templates`);a.push(this.renderCollapsibleGroup({key:o,title:"Templates",count:n.templates.length,content:this.renderEntriesList(n.templates),className:"scene-object-group-sub"}))}if(n.bundles.size||n.systems.length){let o=this.getCollapseKey(`screen:${e}:systems`),l=Array.from(n.bundles.values()).sort((p,u)=>p.label.localeCompare(u.label)).map(p=>this.renderSystemBundle(p.key,p.label,p.objectIds,p.entries)).join(""),c=n.systems.length?this.renderEntriesList(n.systems):"",d=n.systems.length?`<button class="scene-object-group-delete" data-delete-system-group="${e}" type="button" title="Delete all system objects">\u{1F5D1}\uFE0F</button>`:"";a.push(this.renderCollapsibleGroup({key:o,title:"Systems",count:n.bundles.size+n.systems.length,content:`${l}${c}`,className:"scene-object-group-system",actionsHtml:d}))}if(n.objects.length){let o=this.getCollapseKey(`screen:${e}:objects`);a.push(this.renderCollapsibleGroup({key:o,title:"Objects",count:n.objects.length,content:this.renderEntriesList(n.objects),className:"scene-object-group"}))}let r=a.join("");return r?this.renderCollapsibleGroup({key:i,title:t,count:n.templates.length+n.systems.length+n.objects.length+n.bundles.size,content:r,className:"scene-object-group-screen"}):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t,n,i;this.selectedId=e,this.selectedIds.has(e)||this.selectedIds.add(e),this.updateLastSelectedIndex(e),this.updateSelectionUI(),(t=this.options)==null||t.onSelect(e),(i=(n=this.options)==null?void 0:n.onMultiSelect)==null||i.call(n,Array.from(this.selectedIds))}toggleBatchSelect(e){var t,n;this.selectedIds.has(e)?this.selectedIds.delete(e):this.selectedIds.add(e),this.updateSelectionUI(),(n=(t=this.options)==null?void 0:t.onMultiSelect)==null||n.call(t,Array.from(this.selectedIds))}toggleSelect(e){this.toggleBatchSelect(e)}selectRange(e,t){var r,o,l;let n=this.objectEntries.findIndex(c=>c.id===t);if(n===-1)return;let i=Math.min(e,n),a=Math.max(e,n);for(let c=i;c<=a;c++)c>=0&&c<this.objectEntries.length&&this.selectedIds.add(this.objectEntries[c].id);this.selectedId=t,this.updateLastSelectedIndex(t),this.updateSelectionUI(),(r=this.options)==null||r.onSelect(this.selectedId),(l=(o=this.options)==null?void 0:o.onMultiSelect)==null||l.call(o,Array.from(this.selectedIds))}updateLastSelectedIndex(e){this.lastSelectedIndex=this.objectEntries.findIndex(t=>t.id===e)}getDefaultScreenForCreate(){if(this.screenFilter!=="all")return this.screenFilter;let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"}async openAddObjectMenu(e){try{await new Vn({onRefresh:()=>this.refreshObjects(),onClose:()=>{}}).open(e)}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectMenu:",t)}}async openAddObjectWizard(e){try{new Gn().open({screenId:e})}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectWizard:",t)}}async showContextMenu(e,t,n,i){if(!this.isContextMenuOpen){this.isContextMenuOpen=!0,this.selectedIds.has(e)||this.select(e);try{new qn({objectId:e,screenId:t,onSelect:r=>{r&&this.select(r)},onRefresh:()=>this.refreshObjects(),onClose:()=>{this.isContextMenuOpen=!1},onDeleteRequest:r=>this.deleteObject(r),onMoveRequest:(r,o)=>this.moveObject(r,o)}).open({x:n,y:i})}catch(a){this.isContextMenuOpen=!1,console.warn("[SceneObjectsPanel] Failed to open context menu:",a)}}}async deleteObject(e){var a;let t=this.getSelectedIds(),n=t.length>1&&t.includes(e),i=this.getActiveScreenForSync();if(n){if(!window.confirm(`Delete ${t.length} selected object${t.length!==1?"s":""}? This removes them from the screen configuration.`))return;await this.deleteMultipleObjects(t)}else{if(!window.confirm(`Delete "${e}"? This removes it from the screen configuration.`))return;try{let o=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e,screenId:i,forceSync:!0})}),l=await o.json().catch(()=>null);if(!o.ok||(l==null?void 0:l.success)===!1){let c=((a=l==null?void 0:l.errors)==null?void 0:a.join(`
621
+ `}renderScreenGroup(e,t,n){let i=this.getCollapseKey(`screen:${e}`),a=[];if(n.templates.length){let o=this.getCollapseKey(`screen:${e}:templates`);a.push(this.renderCollapsibleGroup({key:o,title:"Templates",count:n.templates.length,content:this.renderEntriesList(n.templates),className:"scene-object-group-sub"}))}if(n.bundles.size||n.systems.length){let o=this.getCollapseKey(`screen:${e}:systems`),l=Array.from(n.bundles.values()).sort((p,u)=>p.label.localeCompare(u.label)).map(p=>this.renderSystemBundle(p.key,p.label,p.objectIds,p.entries)).join(""),c=n.systems.length?this.renderEntriesList(n.systems):"",d=n.systems.length?`<button class="scene-object-group-delete" data-delete-system-group="${e}" type="button" title="Delete all system objects">\u{1F5D1}\uFE0F</button>`:"";a.push(this.renderCollapsibleGroup({key:o,title:"Systems",count:n.bundles.size+n.systems.length,content:`${l}${c}`,className:"scene-object-group-system",actionsHtml:d}))}if(n.objects.length){let o=this.getCollapseKey(`screen:${e}:objects`);a.push(this.renderCollapsibleGroup({key:o,title:"Objects",count:n.objects.length,content:this.renderEntriesList(n.objects),className:"scene-object-group"}))}let r=a.join("");return r?this.renderCollapsibleGroup({key:i,title:t,count:n.templates.length+n.systems.length+n.objects.length+n.bundles.size,content:r,className:"scene-object-group-screen"}):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t,n,i;this.selectedId=e,this.selectedIds.has(e)||this.selectedIds.add(e),this.updateLastSelectedIndex(e),this.updateSelectionUI(),(t=this.options)==null||t.onSelect(e),(i=(n=this.options)==null?void 0:n.onMultiSelect)==null||i.call(n,Array.from(this.selectedIds))}toggleBatchSelect(e){var t,n;this.selectedIds.has(e)?this.selectedIds.delete(e):this.selectedIds.add(e),this.updateSelectionUI(),(n=(t=this.options)==null?void 0:t.onMultiSelect)==null||n.call(t,Array.from(this.selectedIds))}toggleSelect(e){this.toggleBatchSelect(e)}selectRange(e,t){var r,o,l;let n=this.objectEntries.findIndex(c=>c.id===t);if(n===-1)return;let i=Math.min(e,n),a=Math.max(e,n);for(let c=i;c<=a;c++)c>=0&&c<this.objectEntries.length&&this.selectedIds.add(this.objectEntries[c].id);this.selectedId=t,this.updateLastSelectedIndex(t),this.updateSelectionUI(),(r=this.options)==null||r.onSelect(this.selectedId),(l=(o=this.options)==null?void 0:o.onMultiSelect)==null||l.call(o,Array.from(this.selectedIds))}updateLastSelectedIndex(e){this.lastSelectedIndex=this.objectEntries.findIndex(t=>t.id===e)}getDefaultScreenForCreate(){if(this.screenFilter!=="all")return this.screenFilter;let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"}async openAddObjectMenu(e){try{await new zn({onRefresh:()=>this.refreshObjects(),onClose:()=>{}}).open(e)}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectMenu:",t)}}async openAddObjectWizard(e){try{new On().open({screenId:e})}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectWizard:",t)}}async showContextMenu(e,t,n,i){if(!this.isContextMenuOpen){this.isContextMenuOpen=!0,this.selectedIds.has(e)||this.select(e);try{new Rn({objectId:e,screenId:t,onSelect:r=>{r&&this.select(r)},onRefresh:()=>this.refreshObjects(),onClose:()=>{this.isContextMenuOpen=!1},onDeleteRequest:r=>this.deleteObject(r),onMoveRequest:(r,o)=>this.moveObject(r,o)}).open({x:n,y:i})}catch(a){this.isContextMenuOpen=!1,console.warn("[SceneObjectsPanel] Failed to open context menu:",a)}}}async deleteObject(e){var a;let t=this.getSelectedIds(),n=t.length>1&&t.includes(e),i=this.getActiveScreenForSync();if(n){if(!window.confirm(`Delete ${t.length} selected object${t.length!==1?"s":""}? This removes them from the screen configuration.`))return;await this.deleteMultipleObjects(t)}else{if(!window.confirm(`Delete "${e}"? This removes it from the screen configuration.`))return;try{let o=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e,screenId:i,forceSync:!0})}),l=await o.json().catch(()=>null);if(!o.ok||(l==null?void 0:l.success)===!1){let c=((a=l==null?void 0:l.errors)==null?void 0:a.join(`
622
622
  `))||(l==null?void 0:l.error)||"Delete failed.";alert(c);return}l!=null&&l.failedDeletions&&l.failedDeletions.length>0&&alert(`Warning: Some files could not be deleted:
623
623
  ${l.failedDeletions.join(`
624
624
  `)}`),l!=null&&l.deletedFiles&&l.deletedFiles.length>0&&console.log(`[SceneObjectsPanel] Successfully deleted files: ${l.deletedFiles.join(", ")}`),await this.syncScreens(),this.selectedIds.delete(e),this.selectedId===e&&(this.selectedId=null),this.refreshObjects()}catch(o){alert(`Delete failed: ${o instanceof Error?o.message:String(o)}`)}}}async deleteMultipleObjects(e){var r;let t=0,n=0,i=[],a=this.getActiveScreenForSync();for(let o of e)try{let l=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:o,skipSync:!0,screenId:a,forceSync:!0})}),c=await l.json().catch(()=>null);if(l.ok&&(c==null?void 0:c.success)!==!1)t++,this.selectedIds.delete(o);else{n++;let d=((r=c==null?void 0:c.errors)==null?void 0:r.join(`
@@ -631,7 +631,7 @@ ${d}`)}await this.syncScreens(),this.refreshObjects()}async moveObject(e,t){var
631
631
  `))||(l==null?void 0:l.error)||"Move failed.";alert(c);return}this.refreshObjects()}catch(o){alert(`Move failed: ${o instanceof Error?o.message:String(o)}`)}}}async moveMultipleObjects(e,t){var r;let n=0,i=0,a=[];for(let o of e){let l=this.inferScreen(o,null);if(t===l){n++;continue}try{let c=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:o,fromScreenId:l,toScreenId:t})}),d=await c.json().catch(()=>({}));if(c.ok&&(d==null?void 0:d.success)!==!1)n++;else{i++;let p=((r=d==null?void 0:d.errors)==null?void 0:r.join(`
632
632
  `))||(d==null?void 0:d.error)||"Move failed.";a.push(`${o}: ${p}`)}}catch(c){i++,a.push(`${o}: ${c instanceof Error?c.message:String(c)}`)}}if(i>0){let o=a.length>0?a.join(`
633
633
  `):`${i} object(s) failed to move.`;alert(`Moved ${n} object(s). Errors:
634
- ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenForSync();await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}getActiveScreenForSync(){let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:this.screenFilter!=="all"?this.screenFilter:"gameplay"}};var Yn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}render(){return`
634
+ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenForSync();await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})})}catch(e){console.warn("[SceneObjectsPanel] Failed to sync screens:",e)}}getActiveScreenForSync(){let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:this.screenFilter!=="all"?this.screenFilter:"gameplay"}};var Dn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}render(){return`
635
635
  <div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
636
636
  <div class="scene-tools-header" data-tools-header data-panel-handle>
637
637
  <span class="scene-tools-title">Scene Tools</span>
@@ -706,7 +706,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
706
706
  </div>
707
707
  </div>
708
708
  </div>
709
- `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var w;this.isCollapsed=!this.isCollapsed,(w=this.root)==null||w.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(w,P)=>{var T;let _=(T=this.root)==null?void 0:T.querySelector(`[data-status="${w}"]`);_&&_.classList.toggle("active",P)},r=this.root.querySelector("#debug-highlight-object");r==null||r.addEventListener("change",()=>{var w;(w=this.options)==null||w.onHighlightObject(!!r.checked),a("bounds",r.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var w;(w=this.options)==null||w.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("[data-grid-toggle-btn]"),m=this.root.querySelector("[data-play-toggle-btn]"),f=()=>{if(!p)return .25;let w=Number(p.value),P=Number.isFinite(w)?Math.min(1,Math.max(0,w)):.25;return p.value=String(P),u&&(u.textContent=`${Math.round(P*100)}%`),P},y=(w,P,_)=>{var I,C;let T=_!==void 0?_:f();(C=(I=this.options)==null?void 0:I.onGridToggle)==null||C.call(I,w,P,T),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:w,gap:P,alpha:T}}))},b=w=>{var _,T;let P=f();(T=(_=this.options)==null?void 0:_.onGridGapChange)==null||T.call(_,w),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:w,alpha:P}}))},v=w=>{var P,_;(_=(P=this.options)==null?void 0:P.onGridAlphaChange)==null||_.call(P,w),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:L(),alpha:w}}))},S=w=>{var P,_;(_=(P=this.options)==null?void 0:P.onPlayModeChange)==null||_.call(P,w),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:w}}))},L=()=>{if(!d)return 50;let w=Number(d.value),P=Number.isFinite(w)?Math.min(200,Math.max(4,w)):50;return d.value=String(P),P},M=w=>{c&&(c.checked=w),d&&(d.disabled=!w),p&&(p.disabled=!w),h==null||h.classList.toggle("active",w)},O=w=>{g&&(g.checked=w),m==null||m.classList.toggle("active",w)};try{let w=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),P=localStorage.getItem(this.getSceneStorageKey("grid_gap")),_=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),T=localStorage.getItem(this.getSceneStorageKey("play_mode")),I=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),C=w?w==="true":!1;M(C),d&&(d.value=P||"50",d.disabled=!C),p&&(p.value=_||"0.25",p.disabled=!C,f()),o&&(o.checked=I==="true",a("anchor",o.checked)),O(T==="true"),y(C,L(),f()),S(T==="true"),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let w=L(),P=f();d&&(d.disabled=!c.checked),p&&(p.disabled=!c.checked),h==null||h.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(P))}catch{}y(c.checked,w,P)}),d==null||d.addEventListener("input",()=>{let w=L(),P=f();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(P))}catch{}b(w)}),p==null||p.addEventListener("input",()=>{let w=f(),P=L();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(P))}catch{}v(w)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}m==null||m.classList.toggle("active",g.checked),S(g.checked)}),h==null||h.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),m==null||m.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var Kn=class{constructor(){this.root=null;this.options=null}render(){return`
709
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let i=this.root.querySelector("[data-tools-collapse]");i==null||i.addEventListener("click",()=>{var w;this.isCollapsed=!this.isCollapsed,(w=this.root)==null||w.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let a=(w,k)=>{var L;let _=(L=this.root)==null?void 0:L.querySelector(`[data-status="${w}"]`);_&&_.classList.toggle("active",k)},r=this.root.querySelector("#debug-highlight-object");r==null||r.addEventListener("change",()=>{var w;(w=this.options)==null||w.onHighlightObject(!!r.checked),a("bounds",r.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var w;(w=this.options)==null||w.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("[data-grid-toggle-btn]"),m=this.root.querySelector("[data-play-toggle-btn]"),f=()=>{if(!p)return .25;let w=Number(p.value),k=Number.isFinite(w)?Math.min(1,Math.max(0,w)):.25;return p.value=String(k),u&&(u.textContent=`${Math.round(k*100)}%`),k},y=(w,k,_)=>{var M,C;let L=_!==void 0?_:f();(C=(M=this.options)==null?void 0:M.onGridToggle)==null||C.call(M,w,k,L),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:w,gap:k,alpha:L}}))},b=w=>{var _,L;let k=f();(L=(_=this.options)==null?void 0:_.onGridGapChange)==null||L.call(_,w),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:w,alpha:k}}))},v=w=>{var k,_;(_=(k=this.options)==null?void 0:k.onGridAlphaChange)==null||_.call(k,w),window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:!!(c!=null&&c.checked),gap:P(),alpha:w}}))},E=w=>{var k,_;(_=(k=this.options)==null?void 0:k.onPlayModeChange)==null||_.call(k,w),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:w}}))},P=()=>{if(!d)return 50;let w=Number(d.value),k=Number.isFinite(w)?Math.min(200,Math.max(4,w)):50;return d.value=String(k),k},I=w=>{c&&(c.checked=w),d&&(d.disabled=!w),p&&(p.disabled=!w),h==null||h.classList.toggle("active",w)},O=w=>{g&&(g.checked=w),m==null||m.classList.toggle("active",w)};try{let w=localStorage.getItem(this.getSceneStorageKey("grid_enabled")),k=localStorage.getItem(this.getSceneStorageKey("grid_gap")),_=localStorage.getItem(this.getSceneStorageKey("grid_alpha")),L=localStorage.getItem(this.getSceneStorageKey("play_mode")),M=localStorage.getItem(this.getSceneStorageKey("highlight_anchor")),C=w?w==="true":!1;I(C),d&&(d.value=k||"50",d.disabled=!C),p&&(p.value=_||"0.25",p.disabled=!C,f()),o&&(o.checked=M==="true",a("anchor",o.checked)),O(L==="true"),y(C,P(),f()),E(L==="true"),o&&window.dispatchEvent(new CustomEvent("scene-editor:highlight-anchor",{detail:{enabled:o.checked}}))}catch{}c==null||c.addEventListener("change",()=>{let w=P(),k=f();d&&(d.disabled=!c.checked),p&&(p.disabled=!c.checked),h==null||h.classList.toggle("active",c.checked);try{localStorage.setItem(this.getSceneStorageKey("grid_enabled"),c.checked?"true":"false"),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(k))}catch{}y(c.checked,w,k)}),d==null||d.addEventListener("input",()=>{let w=P(),k=f();try{localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(k))}catch{}b(w)}),p==null||p.addEventListener("input",()=>{let w=f(),k=P();try{localStorage.setItem(this.getSceneStorageKey("grid_alpha"),String(w)),localStorage.setItem(this.getSceneStorageKey("grid_gap"),String(k))}catch{}v(w)}),g==null||g.addEventListener("change",()=>{try{localStorage.setItem(this.getSceneStorageKey("play_mode"),g.checked?"true":"false")}catch{}m==null||m.classList.toggle("active",g.checked),E(g.checked)}),h==null||h.addEventListener("click",()=>{c&&(c.checked=!c.checked,c.dispatchEvent(new Event("change")))}),m==null||m.addEventListener("click",()=>{g&&(g.checked=!g.checked,g.dispatchEvent(new Event("change")))})}updateInfo(e){}};var Nn=class{constructor(){this.root=null;this.options=null}render(){return`
710
710
  <div class="nudge-panel hidden" data-panel="nudge-panel">
711
711
  <div class="nudge-panel-header" data-panel-handle>
712
712
  <span class="nudge-panel-title">Nudge Controls</span>
@@ -763,7 +763,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
763
763
  </div>
764
764
  </div>
765
765
  </div>
766
- `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="nudge-panel"]'),!this.root)return;Array.from(this.root.querySelectorAll(".nudge-arrow-btn")).forEach(a=>{a.addEventListener("click",()=>{var l,c,d,p;let r=a.dataset.nudge,o=this.getNudgeStep();switch(r){case"up":(l=this.options)==null||l.onNudge(0,-o);break;case"down":(c=this.options)==null||c.onNudge(0,o);break;case"left":(d=this.options)==null||d.onNudge(-o,0);break;case"right":(p=this.options)==null||p.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(a=>{a.addEventListener("click",()=>{var l;let o=a.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(o)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var n,i;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((i=e==null?void 0:e.value)!=null?i:10);return Number.isFinite(t)&&t>0?t:10}};var Zt=class{constructor(){this.root=null;this.slotsContainer=null;this.assetsContainer=null;this.assetSearchInput=null;this.slotSearchInput=null;this.options=null;this.registry=null;this.selectedSlotId=null;this.cachedAssets={};this.pendingAssetFetches={};this.cacheBust=0;this.missingPreviewPaths=new Set;this.slotSearchDebounce=null;this.assetSearchDebounce=null}mergeRegistries(e,t){let n=e||{},i=t||{},a={slots:Array.isArray(i.slots)?[...i.slots]:[],libraryAssets:typeof i.libraryAssets=="object"&&i.libraryAssets?{...i.libraryAssets}:{},categories:Array.isArray(i.categories)?[...i.categories]:[]},r=Array.isArray(n.slots)?n.slots:[];if(r.length>0&&a.slots.length>0)for(let c of a.slots){let d=r.find(p=>(p==null?void 0:p.slotId)&&p.slotId===(c==null?void 0:c.slotId));d!=null&&d.currentAsset&&d.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=d.currentAsset)}let o=n.libraryAssets||{};for(let[c,d]of Object.entries(o)){if(!Array.isArray(d))continue;a.libraryAssets[c]||(a.libraryAssets[c]=[]);let p=new Set((a.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of d){let g=u==null?void 0:u.filename;!g||p.has(g)||(a.libraryAssets[c].unshift(u),p.add(g))}}let l=new Set(a.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return a.categories=Array.from(l),a}render(){return`
766
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="nudge-panel"]'),!this.root)return;Array.from(this.root.querySelectorAll(".nudge-arrow-btn")).forEach(a=>{a.addEventListener("click",()=>{var l,c,d,p;let r=a.dataset.nudge,o=this.getNudgeStep();switch(r){case"up":(l=this.options)==null||l.onNudge(0,-o);break;case"down":(c=this.options)==null||c.onNudge(0,o);break;case"left":(d=this.options)==null||d.onNudge(-o,0);break;case"right":(p=this.options)==null||p.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(a=>{a.addEventListener("click",()=>{var l;let o=a.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(o)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var n,i;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((i=e==null?void 0:e.value)!=null?i:10);return Number.isFinite(t)&&t>0?t:10}};var Bt=class{constructor(){this.root=null;this.slotsContainer=null;this.assetsContainer=null;this.assetSearchInput=null;this.slotSearchInput=null;this.options=null;this.registry=null;this.selectedSlotId=null;this.cachedAssets={};this.pendingAssetFetches={};this.cacheBust=0;this.missingPreviewPaths=new Set;this.slotSearchDebounce=null;this.assetSearchDebounce=null}mergeRegistries(e,t){let n=e||{},i=t||{},a={slots:Array.isArray(i.slots)?[...i.slots]:[],libraryAssets:typeof i.libraryAssets=="object"&&i.libraryAssets?{...i.libraryAssets}:{},categories:Array.isArray(i.categories)?[...i.categories]:[]},r=Array.isArray(n.slots)?n.slots:[];if(r.length>0&&a.slots.length>0)for(let c of a.slots){let d=r.find(p=>(p==null?void 0:p.slotId)&&p.slotId===(c==null?void 0:c.slotId));d!=null&&d.currentAsset&&d.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=d.currentAsset)}let o=n.libraryAssets||{};for(let[c,d]of Object.entries(o)){if(!Array.isArray(d))continue;a.libraryAssets[c]||(a.libraryAssets[c]=[]);let p=new Set((a.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of d){let g=u==null?void 0:u.filename;!g||p.has(g)||(a.libraryAssets[c].unshift(u),p.add(g))}}let l=new Set(a.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return a.categories=Array.from(l),a}render(){return`
767
767
  <div class="scene-panel library-panel panel-accent-purple" data-panel="library">
768
768
  <div class="scene-panel-header" data-panel-handle>
769
769
  <div class="panel-title">
@@ -791,7 +791,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
791
791
  </div>
792
792
  <div class="panel-resize-handle" data-panel-resize></div>
793
793
  </div>
794
- `}initialize(e,t){var a,r,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=(r=this.root)==null?void 0:r.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 n=(c=this.root)==null?void 0:c.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let i=(d=this.root)==null?void 0:d.querySelector("[data-refresh-library]");i==null||i.addEventListener("click",()=>{i.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>i.classList.remove("pulse-anim"),500)}),(p=this.assetSearchInput)==null||p.addEventListener("input",()=>this.scheduleRenderAssets()),(u=this.slotSearchInput)==null||u.addEventListener("input",()=>this.scheduleRenderSlots()),this.loadAssetRegistry()}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,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let i=await n.json(),a=this.mergeRegistries(t,i);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){var n,i;let t=window.getEditableAssets;if(typeof t=="function"){let a=t();if(a!=null&&a.slots&&Array.isArray(a.slots)&&a.slots.length>0){this.registry=a,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(o=>o.slotId===this.selectedSlotId)||(this.selectedSlotId=(i=(n=this.registry.slots[0])==null?void 0:n.slotId)!=null?i: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 i;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(),n=(((i=this.slotSearchInput)==null?void 0:i.value)||"").trim().toLowerCase();this.slotsContainer.innerHTML="";for(let a of this.getCategories()){let r=(e[a]||[]).filter(d=>n?`${d.displayName} ${d.slotId} ${d.objectId} ${d.currentAsset}`.toLowerCase().includes(n):!0);if(r.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 r){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=n?"No slots match your search":"No editable slots available",this.slotsContainer.appendChild(a)}}createSlotElement(e,t){var m,f;let n=this.selectedSlotId===e.slotId,i=document.createElement("div");i.className=`library-slot ${n?"expanded":""}`,i.dataset.slotId=e.slotId;let a=document.createElement("div");a.className="slot-header";let r=document.createElement("div");if(r.className="slot-current",(m=e.currentAsset)==null?void 0:m.toLowerCase().endsWith(".json")){let y=document.createElement("div");y.className="slot-thumbnail slot-thumbnail-json",y.textContent="\u{1F3AC}",y.title="Lottie/JSON Animation",r.appendChild(y)}else{let y=document.createElement("img"),b=this.resolveSlotPreviewPaths(e),v=b.primary,S=(f=b.fallback)!=null?f:null;if(!v)y.style.display="none";else if(this.missingPreviewPaths.has(v.key)&&(!S||this.missingPreviewPaths.has(S.key)))y.style.display="none";else{y.src=v.src(t),y.alt=e.displayName,y.className="slot-thumbnail",y.loading="lazy";let L=!1;y.onerror=()=>{if(L){y.onerror=null,y.style.display="none";return}if(this.missingPreviewPaths.add(v.key),S&&!this.missingPreviewPaths.has(S.key)){L=!0,y.src=S.src(t);return}S&&this.missingPreviewPaths.add(S.key),y.style.display="none"}}r.appendChild(y)}a.appendChild(r);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let d=document.createElement("div");d.className="slot-asset",d.textContent=e.currentAsset,l.appendChild(c),l.appendChild(d),a.appendChild(l);let p=document.createElement("div");p.className="slot-actions";let u=document.createElement("button");u.className="slot-ai-edit",u.title="Edit with AI",u.textContent="\u2728 AI",u.addEventListener("click",async y=>{y.stopPropagation(),await this.handleAIEdit(e)}),p.appendChild(u);let g=document.createElement("button");g.className="slot-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async y=>{y.stopPropagation(),await this.handleUpload(e)}),p.appendChild(g);let h=document.createElement("button");return h.className="slot-reset",h.title="Reset to default",h.textContent="\u21BA",h.addEventListener("click",async y=>{y.stopPropagation(),await this.handleReset(e)}),p.appendChild(h),a.appendChild(p),a.addEventListener("click",()=>{this.selectedSlotId=e.slotId,this.renderSlots(),this.renderAssets()}),i.appendChild(a),i}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(),n=this.getSelectedSlot();this.assetsContainer.innerHTML="";let i=document.createElement("div");i.className="library-selected",i.textContent=n?`Selected slot: ${n.displayName} (${n.currentAsset||"no asset"})`:"Select a slot to apply assets",i.style.gridColumn="1 / -1",this.assetsContainer.appendChild(i);let a=this.getCategories(),r=!1,o=!1;for(let c of a){let d=this.getCategoryAssets(c,e);if(!d){let m=document.createElement("div");m.className="library-empty",m.textContent=`Loading ${this.formatCategoryName(c)} assets...`,this.assetsContainer.appendChild(m),o=!0;continue}let p=d.filter(m=>t?`${m.displayName} ${m.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 m of p){let f=document.createElement("div");f.className="library-item",n&&n.currentAsset===m.filename&&n.libraryFolder===c&&f.classList.add("selected");let y=document.createElement("img"),b=this.resolveLibraryAssetPath(c,m.filename);this.missingPreviewPaths.has(b.key)?y.style.display="none":y.src=b.src(e),y.alt=m.displayName,y.className="library-thumbnail",y.loading="lazy",y.onerror=()=>{this.missingPreviewPaths.add(b.key),y.style.opacity="0.3"},f.appendChild(y);let v=document.createElement("div");v.className="library-label",v.textContent=m.displayName,f.appendChild(v),f.addEventListener("click",async()=>{if(!n){alert("Select a slot first to apply an asset.");return}await this.handleApply(n,m.filename,c)}),h.appendChild(f),r=!0}u.appendChild(h),this.assetsContainer.appendChild(u)}if(!r&&!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 n;if(this.cachedAssets[e])return this.cachedAssets[e];if(!this.pendingAssetFetches[e]){let i=((n=this.registry)==null?void 0:n.libraryAssets[e])||[];this.pendingAssetFetches[e]=this.fetchFolderAssets(e,t).then(a=>{let r=new Map;for(let o of i)r.set(o.filename,o);for(let o of a)r.has(o.filename)||r.set(o.filename,o);return this.cachedAssets[e]=Array.from(r.values()),delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]}).catch(()=>(this.cachedAssets[e]=i,delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]))}return null}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let i=await n.text(),a=[],r=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=r.exec(i))!==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,n){var i;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let a=window.__wizardAssetPicker;if(a!=null&&a.onPick){let l=`raw/library/${n||e.libraryFolder||e.category}/${t}`;a.onPick(l),window.__wizardAssetPicker=null;return}let r=n||e.libraryFolder||e.category;await((i=this.options)==null?void 0:i.onApply(e.objectId,t,r)),e.currentAsset=t,e.libraryFolder=r,this.renderSlots(),this.renderAssets()}catch(a){console.error("[LIBRARY] Failed to apply asset:",a)}}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(n){console.error("[LIBRARY] Failed to reset slot:",n)}}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 n=t.replace(/^\/+/,""),i=null,a=null;return n.startsWith("raw/")?i=n:n.startsWith("library/")?i=`raw/${n}`:n.includes("/")?i=n:e.libraryFolder?(i=`raw/library/${e.libraryFolder}/${n}`,a=`raw/${n}`):i=`raw/${n}`,{primary:i?{key:i,src:l=>`/${i}?t=${l}`}:null,fallback:a?{key:a,src:l=>`/${a}?t=${l}`}:null}}resolveLibraryAssetPath(e,t){let n=t.replace(/^\/+/,""),i="";return n.startsWith("raw/")?i=n:n.startsWith("library/")?i=`raw/${n}`:n.includes("/")?i=n:i=`raw/library/${e}/${n}`,{key:i,src:a=>`/${i}?t=${a}`}}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let n=e.slotId||e.objectId,i="render.texture";e.category==="ui"&&(i="ui.image"),e.category==="audio"&&(i="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:i})}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 i;let n=(i=t.files)==null?void 0:i[0];if(n){console.log("[Library] File selected:",n.name);try{let a=await this.fileToDataUrl(n);if(!a){alert("Failed to read file");return}let o=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",o,"to category:",l);let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${o}.png`,data:a,overwrite:!0})})).json();if(d.success){console.log("[Library] \u2705 Upload saved:",d.path);let p=window.addAssetToRegistry;typeof p=="function"&&p(l,`${o}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${o}.png`,e.category),e.currentAsset=`${o}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",d.error),alert(`Upload failed: ${d.error}`)}catch(a){console.error("[Library] \u274C Upload error:",a),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>t(null),n.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 n=e.startsWith("json.")?e.replace("json.",""):e,i=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!t||a.category===t));i?(console.log("[LIBRARY] Highlighting slot:",i.slotId),this.selectedSlotId=i.slotId,this.renderSlots(),this.renderAssets(),setTimeout(()=>{var r;let a=(r=this.slotsContainer)==null?void 0:r.querySelector(`[data-slot-id="${i.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 Xn=class{detectType(e,t,n){let i=e.toLowerCase();return i==="logic_id"||i==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":i.includes("color")||i.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 Jn=class{render(e,t,n,i){let a=this.formatLabel(t),r=n?this.getThumbnailUrl(n):"";return`
794
+ `}initialize(e,t){var a,r,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=(r=this.root)==null?void 0:r.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 n=(c=this.root)==null?void 0:c.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let i=(d=this.root)==null?void 0:d.querySelector("[data-refresh-library]");i==null||i.addEventListener("click",()=>{i.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>i.classList.remove("pulse-anim"),500)}),(p=this.assetSearchInput)==null||p.addEventListener("input",()=>this.scheduleRenderAssets()),(u=this.slotSearchInput)==null||u.addEventListener("input",()=>this.scheduleRenderSlots()),this.loadAssetRegistry()}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,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let i=await n.json(),a=this.mergeRegistries(t,i);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){var n,i;let t=window.getEditableAssets;if(typeof t=="function"){let a=t();if(a!=null&&a.slots&&Array.isArray(a.slots)&&a.slots.length>0){this.registry=a,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(o=>o.slotId===this.selectedSlotId)||(this.selectedSlotId=(i=(n=this.registry.slots[0])==null?void 0:n.slotId)!=null?i: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 i;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(),n=(((i=this.slotSearchInput)==null?void 0:i.value)||"").trim().toLowerCase();this.slotsContainer.innerHTML="";for(let a of this.getCategories()){let r=(e[a]||[]).filter(d=>n?`${d.displayName} ${d.slotId} ${d.objectId} ${d.currentAsset}`.toLowerCase().includes(n):!0);if(r.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 r){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=n?"No slots match your search":"No editable slots available",this.slotsContainer.appendChild(a)}}createSlotElement(e,t){var m,f;let n=this.selectedSlotId===e.slotId,i=document.createElement("div");i.className=`library-slot ${n?"expanded":""}`,i.dataset.slotId=e.slotId;let a=document.createElement("div");a.className="slot-header";let r=document.createElement("div");if(r.className="slot-current",(m=e.currentAsset)==null?void 0:m.toLowerCase().endsWith(".json")){let y=document.createElement("div");y.className="slot-thumbnail slot-thumbnail-json",y.textContent="\u{1F3AC}",y.title="Lottie/JSON Animation",r.appendChild(y)}else{let y=document.createElement("img"),b=this.resolveSlotPreviewPaths(e),v=b.primary,E=(f=b.fallback)!=null?f:null;if(!v)y.style.display="none";else if(this.missingPreviewPaths.has(v.key)&&(!E||this.missingPreviewPaths.has(E.key)))y.style.display="none";else{y.src=v.src(t),y.alt=e.displayName,y.className="slot-thumbnail",y.loading="lazy";let P=!1;y.onerror=()=>{if(P){y.onerror=null,y.style.display="none";return}if(this.missingPreviewPaths.add(v.key),E&&!this.missingPreviewPaths.has(E.key)){P=!0,y.src=E.src(t);return}E&&this.missingPreviewPaths.add(E.key),y.style.display="none"}}r.appendChild(y)}a.appendChild(r);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let d=document.createElement("div");d.className="slot-asset",d.textContent=e.currentAsset,l.appendChild(c),l.appendChild(d),a.appendChild(l);let p=document.createElement("div");p.className="slot-actions";let u=document.createElement("button");u.className="slot-ai-edit",u.title="Edit with AI",u.textContent="\u2728 AI",u.addEventListener("click",async y=>{y.stopPropagation(),await this.handleAIEdit(e)}),p.appendChild(u);let g=document.createElement("button");g.className="slot-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async y=>{y.stopPropagation(),await this.handleUpload(e)}),p.appendChild(g);let h=document.createElement("button");return h.className="slot-reset",h.title="Reset to default",h.textContent="\u21BA",h.addEventListener("click",async y=>{y.stopPropagation(),await this.handleReset(e)}),p.appendChild(h),a.appendChild(p),a.addEventListener("click",()=>{this.selectedSlotId=e.slotId,this.renderSlots(),this.renderAssets()}),i.appendChild(a),i}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(),n=this.getSelectedSlot();this.assetsContainer.innerHTML="";let i=document.createElement("div");i.className="library-selected",i.textContent=n?`Selected slot: ${n.displayName} (${n.currentAsset||"no asset"})`:"Select a slot to apply assets",i.style.gridColumn="1 / -1",this.assetsContainer.appendChild(i);let a=this.getCategories(),r=!1,o=!1;for(let c of a){let d=this.getCategoryAssets(c,e);if(!d){let m=document.createElement("div");m.className="library-empty",m.textContent=`Loading ${this.formatCategoryName(c)} assets...`,this.assetsContainer.appendChild(m),o=!0;continue}let p=d.filter(m=>t?`${m.displayName} ${m.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 m of p){let f=document.createElement("div");f.className="library-item",n&&n.currentAsset===m.filename&&n.libraryFolder===c&&f.classList.add("selected");let y=document.createElement("img"),b=this.resolveLibraryAssetPath(c,m.filename);this.missingPreviewPaths.has(b.key)?y.style.display="none":y.src=b.src(e),y.alt=m.displayName,y.className="library-thumbnail",y.loading="lazy",y.onerror=()=>{this.missingPreviewPaths.add(b.key),y.style.opacity="0.3"},f.appendChild(y);let v=document.createElement("div");v.className="library-label",v.textContent=m.displayName,f.appendChild(v),f.addEventListener("click",async()=>{if(!n){alert("Select a slot first to apply an asset.");return}await this.handleApply(n,m.filename,c)}),h.appendChild(f),r=!0}u.appendChild(h),this.assetsContainer.appendChild(u)}if(!r&&!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 n;if(this.cachedAssets[e])return this.cachedAssets[e];if(!this.pendingAssetFetches[e]){let i=((n=this.registry)==null?void 0:n.libraryAssets[e])||[];this.pendingAssetFetches[e]=this.fetchFolderAssets(e,t).then(a=>{let r=new Map;for(let o of i)r.set(o.filename,o);for(let o of a)r.has(o.filename)||r.set(o.filename,o);return this.cachedAssets[e]=Array.from(r.values()),delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]}).catch(()=>(this.cachedAssets[e]=i,delete this.pendingAssetFetches[e],this.renderAssets(),this.cachedAssets[e]))}return null}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let i=await n.text(),a=[],r=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=r.exec(i))!==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,n){var i;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{let a=window.__wizardAssetPicker;if(a!=null&&a.onPick){let l=`raw/library/${n||e.libraryFolder||e.category}/${t}`;a.onPick(l),window.__wizardAssetPicker=null;return}let r=n||e.libraryFolder||e.category;await((i=this.options)==null?void 0:i.onApply(e.objectId,t,r)),e.currentAsset=t,e.libraryFolder=r,this.renderSlots(),this.renderAssets()}catch(a){console.error("[LIBRARY] Failed to apply asset:",a)}}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(n){console.error("[LIBRARY] Failed to reset slot:",n)}}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 n=t.replace(/^\/+/,""),i=null,a=null;return n.startsWith("raw/")?i=n:n.startsWith("library/")?i=`raw/${n}`:n.includes("/")?i=n:e.libraryFolder?(i=`raw/library/${e.libraryFolder}/${n}`,a=`raw/${n}`):i=`raw/${n}`,{primary:i?{key:i,src:l=>`/${i}?t=${l}`}:null,fallback:a?{key:a,src:l=>`/${a}?t=${l}`}:null}}resolveLibraryAssetPath(e,t){let n=t.replace(/^\/+/,""),i="";return n.startsWith("raw/")?i=n:n.startsWith("library/")?i=`raw/${n}`:n.includes("/")?i=n:i=`raw/library/${e}/${n}`,{key:i,src:a=>`/${i}?t=${a}`}}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let n=e.slotId||e.objectId,i="render.texture";e.category==="ui"&&(i="ui.image"),e.category==="audio"&&(i="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:i})}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 i;let n=(i=t.files)==null?void 0:i[0];if(n){console.log("[Library] File selected:",n.name);try{let a=await this.fileToDataUrl(n);if(!a){alert("Failed to read file");return}let o=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",o,"to category:",l);let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${o}.png`,data:a,overwrite:!0})})).json();if(d.success){console.log("[Library] \u2705 Upload saved:",d.path);let p=window.addAssetToRegistry;typeof p=="function"&&p(l,`${o}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${o}.png`,e.category),e.currentAsset=`${o}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",d.error),alert(`Upload failed: ${d.error}`)}catch(a){console.error("[Library] \u274C Upload error:",a),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>t(null),n.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 n=e.startsWith("json.")?e.replace("json.",""):e,i=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!t||a.category===t));i?(console.log("[LIBRARY] Highlighting slot:",i.slotId),this.selectedSlotId=i.slotId,this.renderSlots(),this.renderAssets(),setTimeout(()=>{var r;let a=(r=this.slotsContainer)==null?void 0:r.querySelector(`[data-slot-id="${i.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 Hn=class{detectType(e,t,n){let i=e.toLowerCase();return i==="logic_id"||i==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":i.includes("color")||i.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 Fn=class{render(e,t,n,i){let a=this.formatLabel(t),r=n?this.getThumbnailUrl(n):"";return`
795
795
  <div class="inspector-property" data-property-type="image">
796
796
  <div class="inspector-property-header">
797
797
  <label class="inspector-label">${a}</label>
@@ -813,7 +813,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
813
813
  </div>
814
814
  `}
815
815
  </div>
816
- `}getThumbnailUrl(e){if(e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http"))return e;let t=`t=${Date.now()}`,n=e.replace(/^\.?\//,"");if(n.startsWith("raw/")||n.startsWith("assets/")||n.startsWith("library/")){let i=`/${n}`;return i.includes("?")?`${i}&${t}`:`${i}?${t}`}return`/raw/${n}?${t}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Zn=class{render(e,t,n,i){let a=n||"#000000";return`
816
+ `}getThumbnailUrl(e){if(e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http"))return e;let t=`t=${Date.now()}`,n=e.replace(/^\.?\//,"");if(n.startsWith("raw/")||n.startsWith("assets/")||n.startsWith("library/")){let i=`/${n}`;return i.includes("?")?`${i}&${t}`:`${i}?${t}`}return`/raw/${n}?${t}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Bn=class{render(e,t,n,i){let a=n||"#000000";return`
817
817
  <div class="inspector-property inspector-property-color">
818
818
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
819
819
  <div class="inspector-color-group">
@@ -829,7 +829,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
829
829
  data-object-id="${e}" />
830
830
  </div>
831
831
  </div>
832
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Qn=class{render(e,t,n,i){return`
832
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Gn=class{render(e,t,n,i){return`
833
833
  <div class="inspector-property inspector-property-number">
834
834
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
835
835
  <input type="number"
@@ -839,7 +839,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
839
839
  data-object-id="${e}"
840
840
  step="any" />
841
841
  </div>
842
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ei=class{render(e,t,n,i){let a=String(n||"");return`
842
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Un=class{render(e,t,n,i){let a=String(n||"");return`
843
843
  <div class="inspector-property inspector-property-text">
844
844
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
845
845
  <div class="inspector-input-group">
@@ -850,7 +850,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
850
850
  data-object-id="${e}" />
851
851
  </div>
852
852
  </div>
853
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ti=class{render(e,t,n,i){return`
853
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var qn=class{render(e,t,n,i){return`
854
854
  <div class="inspector-property inspector-property-boolean">
855
855
  <label class="inspector-property-label">
856
856
  <input type="checkbox"
@@ -861,7 +861,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
861
861
  <span>${this.formatLabel(t)}</span>
862
862
  </label>
863
863
  </div>
864
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ni=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&this.registry){let r=this.registry,o=Array.isArray(n)?n:[],l=o.map((d,p)=>{let u=`${i}.${p}`,g=`
864
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Vn=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&this.registry){let r=this.registry,o=Array.isArray(n)?n:[],l=o.map((d,p)=>{let u=`${i}.${p}`,g=`
865
865
  <button class="inspector-button inspector-button-small"
866
866
  data-logic-remove="true"
867
867
  data-object-id="${e}"
@@ -925,7 +925,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
925
925
  ${a}
926
926
  </div>
927
927
  </div>
928
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ii=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&n&&typeof n=="object"&&!Array.isArray(n))return this.renderLogic(e,t,n,i);let a=[];for(let o in n){let l=n[o],c=`${i}.${o}`,d=this.registry.renderProperty(e,o,l,c);d&&a.push(d)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
928
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Wn=class{constructor(e){this.registry=e}render(e,t,n,i){if(t==="logic"&&n&&typeof n=="object"&&!Array.isArray(n))return this.renderLogic(e,t,n,i);let a=[];for(let o in n){let l=n[o],c=`${i}.${o}`,d=this.registry.renderProperty(e,o,l,c);d&&a.push(d)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
929
929
  <div class="inspector-subsection">
930
930
  <div class="inspector-subsection-title">${this.formatLabel(t)}</div>
931
931
  <div class="inspector-subsection-content">
@@ -952,30 +952,30 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
952
952
  </select>
953
953
  </div>
954
954
  </div>
955
- `);for(let u in n){if(u==="id")continue;let g=n[u],h=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let f=[];for(let y in g){let b=g[y],v=`${h}.${y}`,S=o[y];if(y==="targetId"||y==="inputId"){let L=this.registry.getObjectIds(),M=typeof b=="string"?b:"",O=M&&!L.includes(M)?[M,...L]:L;f.push(`
955
+ `);for(let u in n){if(u==="id")continue;let g=n[u],h=`${i}.${u}`;if(u==="props"&&g&&typeof g=="object"){let f=[];for(let y in g){let b=g[y],v=`${h}.${y}`,E=o[y];if(y==="targetId"||y==="inputId"){let P=this.registry.getObjectIds(),I=typeof b=="string"?b:"",O=I&&!P.includes(I)?[I,...P]:P;f.push(`
956
956
  <div class="inspector-property inspector-property-text">
957
957
  <label class="inspector-property-label">${this.formatLabel(y)}</label>
958
958
  <div class="inspector-input-group">
959
959
  <select class="inspector-component-select inspector-input"
960
960
  data-property-path="${v}"
961
961
  data-object-id="${e}">
962
- <option value="" ${M?"":"selected"}>None</option>
963
- ${O.map(w=>`<option value="${w}" ${w===M?"selected":""}>${w}</option>`).join("")}
962
+ <option value="" ${I?"":"selected"}>None</option>
963
+ ${O.map(w=>`<option value="${w}" ${w===I?"selected":""}>${w}</option>`).join("")}
964
964
  </select>
965
965
  </div>
966
966
  </div>
967
- `);continue}if(Array.isArray(S)&&S.length)f.push(`
967
+ `);continue}if(Array.isArray(E)&&E.length)f.push(`
968
968
  <div class="inspector-property inspector-property-text">
969
969
  <label class="inspector-property-label">${this.formatLabel(y)}</label>
970
970
  <div class="inspector-input-group">
971
971
  <select class="inspector-component-select inspector-input"
972
972
  data-property-path="${v}"
973
973
  data-object-id="${e}">
974
- ${S.map(L=>`<option value="${String(L)}" ${String(L)===String(b)?"selected":""}>${String(L)}</option>`).join("")}
974
+ ${E.map(P=>`<option value="${String(P)}" ${String(P)===String(b)?"selected":""}>${String(P)}</option>`).join("")}
975
975
  </select>
976
976
  </div>
977
977
  </div>
978
- `);else{let L=this.registry.renderProperty(e,y,b,v);L&&f.push(L)}}f.length&&a.push(`
978
+ `);else{let P=this.registry.renderProperty(e,y,b,v);P&&f.push(P)}}f.length&&a.push(`
979
979
  <div class="inspector-property inspector-property-object">
980
980
  <div class="inspector-object-header">Props</div>
981
981
  <div class="inspector-object-body">
@@ -1000,7 +1000,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1000
1000
  ${p}
1001
1001
  </div>
1002
1002
  </div>
1003
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ai=class{render(e,t,n,i,a){let r=n==null?"":String(n),o=Array.from(new Set(a.map(c=>String(c)))),l=r&&!o.includes(r)?[r,...o]:o;return`
1003
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Yn=class{render(e,t,n,i,a){let r=n==null?"":String(n),o=Array.from(new Set(a.map(c=>String(c)))),l=r&&!o.includes(r)?[r,...o]:o;return`
1004
1004
  <div class="inspector-property inspector-property-text">
1005
1005
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
1006
1006
  <div class="inspector-input-group">
@@ -1011,7 +1011,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1011
1011
  </select>
1012
1012
  </div>
1013
1013
  </div>
1014
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var si=class{render(e,t,n,i){let a=this.safeStringify(n);return`
1014
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Kn=class{render(e,t,n,i){let a=this.safeStringify(n);return`
1015
1015
  <div class="inspector-property inspector-property-text">
1016
1016
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
1017
1017
  <div class="inspector-input-group">
@@ -1022,7 +1022,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1022
1022
  rows="6">${a}</textarea>
1023
1023
  </div>
1024
1024
  </div>
1025
- `}safeStringify(e){try{return JSON.stringify(e!=null?e:[],null,2)}catch{return"[]"}}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var ri=class{render(e,t,n,i){let r=(Array.isArray(n)?n:[]).map((o,l)=>{let c=typeof(o==null?void 0:o.x)=="number"?o.x:0,d=typeof(o==null?void 0:o.y)=="number"?o.y:0;return`
1025
+ `}safeStringify(e){try{return JSON.stringify(e!=null?e:[],null,2)}catch{return"[]"}}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Xn=class{render(e,t,n,i){let r=(Array.isArray(n)?n:[]).map((o,l)=>{let c=typeof(o==null?void 0:o.x)=="number"?o.x:0,d=typeof(o==null?void 0:o.y)=="number"?o.y:0;return`
1026
1026
  <div class="inspector-row" style="gap:8px; align-items:center;">
1027
1027
  <input type="number"
1028
1028
  class="inspector-input"
@@ -1055,7 +1055,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1055
1055
  </div>
1056
1056
  </div>
1057
1057
  </div>
1058
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var oi=class{constructor(e){this.registry=e}render(e,t,n,i){let a=Array.isArray(n)?n:[],o=["",...this.registry.getObjectIds()],l=a.map((c,d)=>{let p=typeof(c==null?void 0:c.templateId)=="string"?c.templateId:"",u=typeof(c==null?void 0:c.weight)=="number"?c.weight:1,g=o.map(h=>`<option value="${h}"${h===p?" selected":""}>${h||"(none)"}</option>`).join("");return`
1058
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Jn=class{constructor(e){this.registry=e}render(e,t,n,i){let a=Array.isArray(n)?n:[],o=["",...this.registry.getObjectIds()],l=a.map((c,d)=>{let p=typeof(c==null?void 0:c.templateId)=="string"?c.templateId:"",u=typeof(c==null?void 0:c.weight)=="number"?c.weight:1,g=o.map(h=>`<option value="${h}"${h===p?" selected":""}>${h||"(none)"}</option>`).join("");return`
1059
1059
  <div class="inspector-row" style="gap:8px; align-items:center;">
1060
1060
  <select class="inspector-select inspector-input"
1061
1061
  data-property-path="${i}.${d}.templateId"
@@ -1090,7 +1090,7 @@ ${o}`)}this.refreshObjects()}async syncScreens(){try{let e=this.getActiveScreenF
1090
1090
  </div>
1091
1091
  </div>
1092
1092
  </div>
1093
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var li=class{constructor(){this.typeDetector=new Xn,this.imageRenderer=new Jn,this.colorRenderer=new Zn,this.numberRenderer=new Qn,this.textRenderer=new ei,this.booleanRenderer=new ti,this.arrayRenderer=new ni(this),this.objectRenderer=new ii(this),this.selectRenderer=new ai,this.jsonRenderer=new si,this.spawnPointsRenderer=new ri,this.spawnTemplatesRenderer=new oi(this)}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let n=[];if(t.objects instanceof Map)for(let i of t.objects.keys())n.push(i);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,i=n==null?void 0:n.__editableConfig,a=i==null?void 0:i.schemas;if(!a)return null;let r=String(e||"").split(".").filter(Boolean);if(r.length<2)return null;let o=r[0],l=r.slice(1).join("."),c=a instanceof Map?a.get(o):a==null?void 0:a[o];if(!c)return null;let d=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof d!="string"||!d.startsWith("enum:"))return null;let u=d.slice(5).split("|").map(g=>g.trim()).filter(Boolean);return u.length?u:null}catch{return null}}getLogicOptions(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],i=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(a=>String(a)).filter(a=>a.trim().length>0);return Array.from(new Set(i)).sort((a,r)=>a.localeCompare(r))}catch{return[]}}renderProperty(e,t,n,i){let a=t.toLowerCase(),r=a==="logic"||a==="logic_id"||a==="logicid",o=a==="id"&&i.toLowerCase().includes("logic");if((r||o)&&typeof n=="string"){let h=this.getLogicOptions(),m=this.selectRenderer.render(e,t,n,i,h);return r?`
1093
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Zn=class{constructor(){this.typeDetector=new Hn,this.imageRenderer=new Fn,this.colorRenderer=new Bn,this.numberRenderer=new Gn,this.textRenderer=new Un,this.booleanRenderer=new qn,this.arrayRenderer=new Vn(this),this.objectRenderer=new Wn(this),this.selectRenderer=new Yn,this.jsonRenderer=new Kn,this.spawnPointsRenderer=new Xn,this.spawnTemplatesRenderer=new Jn(this)}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let n=[];if(t.objects instanceof Map)for(let i of t.objects.keys())n.push(i);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,i=n==null?void 0:n.__editableConfig,a=i==null?void 0:i.schemas;if(!a)return null;let r=String(e||"").split(".").filter(Boolean);if(r.length<2)return null;let o=r[0],l=r.slice(1).join("."),c=a instanceof Map?a.get(o):a==null?void 0:a[o];if(!c)return null;let d=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof d!="string"||!d.startsWith("enum:"))return null;let u=d.slice(5).split("|").map(g=>g.trim()).filter(Boolean);return u.length?u:null}catch{return null}}getLogicOptions(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],i=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(a=>String(a)).filter(a=>a.trim().length>0);return Array.from(new Set(i)).sort((a,r)=>a.localeCompare(r))}catch{return[]}}renderProperty(e,t,n,i){let a=t.toLowerCase(),r=a==="logic"||a==="logic_id"||a==="logicid",o=a==="id"&&i.toLowerCase().includes("logic");if((r||o)&&typeof n=="string"){let h=this.getLogicOptions(),m=this.selectRenderer.render(e,t,n,i,h);return r?`
1094
1094
  ${m}
1095
1095
  <div class="inspector-array-actions">
1096
1096
  <button class="inspector-button"
@@ -1100,7 +1100,7 @@ ${m}
1100
1100
  Add Logic
1101
1101
  </button>
1102
1102
  </div>
1103
- `:m}let l={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"],direction:["any","horizontal","vertical"],spawnPattern:["continuous","onClick","wave","burst"],positionSource:["spawner","target","custom","random","points"],spawnPointMode:["cycle","random"],movementMode:["none","velocity"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"],hitEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroyEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroySound:["","click_4.wav","click_6.wav","success_4.wav"]},c={anchor:["center","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]},d=l[t];if(d&&i.includes("logic.props"))return this.selectRenderer.render(e,t,n,i,d);let p=c[t];if(p&&(i.includes("transform")||i.includes("render"))){let h;if(typeof n=="string")h=n;else if(n==null)h="center";else{let f=Ie(n);h=p.find(b=>{let v=Ie(b);return Math.abs(v.x-f.x)<.001&&Math.abs(v.y-f.y)<.001})||"custom"}let m=[...p];return h==="custom"&&!m.includes("custom")&&m.push("custom"),this.selectRenderer.render(e,t,h,i,m)}if(t==="spawnPoints"&&i.includes("logic.props"))return this.spawnPointsRenderer.render(e,t,n,i);if(t==="spawnTemplates"&&i.includes("logic.props"))return this.spawnTemplatesRenderer.render(e,t,n,i);if((t==="targetId"||t==="inputId"||t==="hitTemplateId"||t==="hpLabelId"||t==="hitPopupTemplateId")&&(n==null||typeof n=="string")){let h=this.getObjectIds(),m=this.selectRenderer.render(e,t,n!=null?n:"",i,["",...h]);return t==="hitTemplateId"&&i.includes("logic.props")?m+'<div class="inspector-text-sm" style="opacity:0.7; margin-top:4px;">Use template id (e.g. bullet_template), not spawner.</div>':m}if(i.includes("motion.")){if(t==="enabled")return this.booleanRenderer.render(e,t,!!n,i);if(t==="direction"&&(i.includes("continuousMove")||i.includes("continuousRotate")||i.includes("orbit"))){let m=["1","-1"],f=n==null?"1":String(n);return this.selectRenderer.render(e,t,f,i,m)}if(["speed","amplitude","intensity","minScale","maxScale","radius","lifetime","pivotOffsetX","pivotOffsetY","duration","delay","startScale","startAlpha","startYOffset","startXOffset"].includes(t)){let m=typeof n=="number"&&!Number.isNaN(n)?n:0;return this.numberRenderer.render(e,t,m,i)}}let u=this.getEnumOptionsFromSchemas(i);if(u)return this.selectRenderer.render(e,t,n,i,u);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,i);case"color":return this.colorRenderer.render(e,t,n,i);case"number":return this.numberRenderer.render(e,t,n,i);case"boolean":return this.booleanRenderer.render(e,t,n,i);case"array":return this.arrayRenderer.render(e,t,n,i);case"object":return this.objectRenderer.render(e,t,n,i);case"select":return this.selectRenderer.render(e,t,n,i,[]);default:return this.textRenderer.render(e,t,n,i)}}getTypeDetector(){return this.typeDetector}};function hl(s,e){let t;return function(...i){let a=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(a,e)}}var ci=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.motionSimpleMode=!0;this.expandMotionOnNextRender=!1;this.rendererRegistry=new li,this.updateManager=new qe,this.quickActions=new Un;try{let e=localStorage.getItem("inspector:motionSimple");e!==null&&(this.motionSimpleMode=e==="true")}catch{}window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
1103
+ `:m}let l={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"],direction:["any","horizontal","vertical"],spawnPattern:["continuous","onClick","wave","burst"],positionSource:["spawner","target","custom","random","points"],spawnPointMode:["cycle","random"],movementMode:["none","velocity"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"],hitEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroyEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],destroySound:["","click_4.wav","click_6.wav","success_4.wav"]},c={anchor:["center","top-left","top-center","top-right","left-center","right-center","bottom-left","bottom-center","bottom-right"]},d=l[t];if(d&&i.includes("logic.props"))return this.selectRenderer.render(e,t,n,i,d);let p=c[t];if(p&&(i.includes("transform")||i.includes("render"))){let h;if(typeof n=="string")h=n;else if(n==null)h="center";else{let f=Me(n);h=p.find(b=>{let v=Me(b);return Math.abs(v.x-f.x)<.001&&Math.abs(v.y-f.y)<.001})||"custom"}let m=[...p];return h==="custom"&&!m.includes("custom")&&m.push("custom"),this.selectRenderer.render(e,t,h,i,m)}if(t==="spawnPoints"&&i.includes("logic.props"))return this.spawnPointsRenderer.render(e,t,n,i);if(t==="spawnTemplates"&&i.includes("logic.props"))return this.spawnTemplatesRenderer.render(e,t,n,i);if((t==="targetId"||t==="inputId"||t==="hitTemplateId"||t==="hpLabelId"||t==="hitPopupTemplateId")&&(n==null||typeof n=="string")){let h=this.getObjectIds(),m=this.selectRenderer.render(e,t,n!=null?n:"",i,["",...h]);return t==="hitTemplateId"&&i.includes("logic.props")?m+'<div class="inspector-text-sm" style="opacity:0.7; margin-top:4px;">Use template id (e.g. bullet_template), not spawner.</div>':m}if(i.includes("motion.")){if(t==="enabled")return this.booleanRenderer.render(e,t,!!n,i);if(t==="direction"&&(i.includes("continuousMove")||i.includes("continuousRotate")||i.includes("orbit"))){let m=["1","-1"],f=n==null?"1":String(n);return this.selectRenderer.render(e,t,f,i,m)}if(["speed","amplitude","intensity","minScale","maxScale","radius","lifetime","pivotOffsetX","pivotOffsetY","duration","delay","startScale","startAlpha","startYOffset","startXOffset"].includes(t)){let m=typeof n=="number"&&!Number.isNaN(n)?n:0;return this.numberRenderer.render(e,t,m,i)}}let u=this.getEnumOptionsFromSchemas(i);if(u)return this.selectRenderer.render(e,t,n,i,u);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,i);case"color":return this.colorRenderer.render(e,t,n,i);case"number":return this.numberRenderer.render(e,t,n,i);case"boolean":return this.booleanRenderer.render(e,t,n,i);case"array":return this.arrayRenderer.render(e,t,n,i);case"object":return this.objectRenderer.render(e,t,n,i);case"select":return this.selectRenderer.render(e,t,n,i,[]);default:return this.textRenderer.render(e,t,n,i)}}getTypeDetector(){return this.typeDetector}};function rl(s,e){let t;return function(...i){let a=()=>{clearTimeout(t),s(...i)};clearTimeout(t),t=setTimeout(a,e)}}var Qn=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.motionSimpleMode=!0;this.expandMotionOnNextRender=!1;this.rendererRegistry=new Zn,this.updateManager=new Ue,this.quickActions=new jn;try{let e=localStorage.getItem("inspector:motionSimple");e!==null&&(this.motionSimpleMode=e==="true")}catch{}window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
1104
1104
  <div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector">
1105
1105
  <div class="scene-panel-header" data-panel-handle>
1106
1106
  <div class="panel-title">
@@ -1189,7 +1189,7 @@ ${m}
1189
1189
  <button class="debug-btn debug-btn-sm ${this.motionSimpleMode?"primary":""}" data-motion-simple-toggle>
1190
1190
  ${this.motionSimpleMode?"Simple":"Advanced"}
1191
1191
  </button>
1192
- `,p='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=m=>{let f=m.split(".").filter(Boolean),y=r;for(let S of f)y=y==null?void 0:y[S];let b=f[f.length-1],v=`${n}.${m}`;return this.rendererRegistry.renderProperty(e,b,y,v)};if(this.motionSimpleMode){let m=u("enabled");m&&i.push(m);let f=[],y=u("intro.enabled"),b=u("intro.type"),v=u("intro.duration"),S=u("intro.easing");y&&f.push(y),b&&f.push(b),v&&f.push(v),S&&f.push(S),f.length&&i.push(`
1192
+ `,p='<button class="debug-btn debug-btn-sm success" data-motion-preview>Preview Intro</button>',u=m=>{let f=m.split(".").filter(Boolean),y=r;for(let E of f)y=y==null?void 0:y[E];let b=f[f.length-1],v=`${n}.${m}`;return this.rendererRegistry.renderProperty(e,b,y,v)};if(this.motionSimpleMode){let m=u("enabled");m&&i.push(m);let f=[],y=u("intro.enabled"),b=u("intro.type"),v=u("intro.duration"),E=u("intro.easing");y&&f.push(y),b&&f.push(b),v&&f.push(v),E&&f.push(E),f.length&&i.push(`
1193
1193
  <div class="inspector-subsection">
1194
1194
  <div class="inspector-subsection-title">Intro</div>
1195
1195
  <div class="inspector-subsection-content">
@@ -1198,15 +1198,15 @@ ${m}
1198
1198
  ${f.join("")}
1199
1199
  </div>
1200
1200
  </div>
1201
- `);let L=[u("pulse.enabled"),u("pulse.speed"),u("pulse.intensity")].filter(Boolean),M=[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),w=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),P=[u("orbit.enabled"),u("orbit.radius"),u("orbit.speed"),u("orbit.direction"),u("orbit.pivotOffsetX"),u("orbit.pivotOffsetY")].filter(Boolean);if(L.length||M.length||O.length||w.length||P.length){let T=(C,A)=>A.length?`
1201
+ `);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),O=[u("continuousMove.enabled"),u("continuousMove.axis"),u("continuousMove.speed"),u("continuousMove.direction"),u("continuousMove.lifetime")].filter(Boolean),w=[u("continuousRotate.enabled"),u("continuousRotate.speed"),u("continuousRotate.direction")].filter(Boolean),k=[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||O.length||w.length||k.length){let L=(C,A)=>A.length?`
1202
1202
  <div class="inspector-motion-continuous-group">
1203
1203
  <div class="inspector-subsection-title">${C}</div>
1204
1204
  <div class="inspector-subsection-content">${A.join("")}</div>
1205
- </div>`:"",I=[T("Pulse",L),T("Swing",M),T("Move forever",O),T("Rotate (pivoting itself)",w),T("Rotate around",P)].filter(Boolean).join("");i.push(`
1205
+ </div>`:"",M=[L("Pulse",P),L("Swing",I),L("Move forever",O),L("Rotate (pivoting itself)",w),L("Rotate around",k)].filter(Boolean).join("");i.push(`
1206
1206
  <div class="inspector-subsection inspector-subsection-continuous">
1207
1207
  <div class="inspector-subsection-title">Continuous</div>
1208
1208
  <div class="inspector-subsection-content inspector-motion-continuous-groups">
1209
- ${I}
1209
+ ${M}
1210
1210
  </div>
1211
1211
  </div>
1212
1212
  `)}}else for(let m in r){let f=r[m],y=`${n}.${m}`,b=this.rendererRegistry.renderProperty(e,m,f,y);b&&i.push(b)}return i.length===0?"":`
@@ -1222,7 +1222,7 @@ ${m}
1222
1222
  ${i.join("")}
1223
1223
  </div>
1224
1224
  </div>
1225
- `}attachEventListeners(){var S,L,M,O;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=hl((w,P,_)=>{var T,I;this.updateManager.updateProperty(w,P,_),(I=(T=this.options)==null?void 0:T.onPropertyChange)==null||I.call(T,w,P,_)},300),n=w=>w?/(^|\.)logic(\.\d+)?\.id$/.test(w):!1;e.forEach(w=>{let P=I=>{var x,j;let C=I.target,A=C.dataset.propertyPath,E=C.dataset.objectId;if(A&&E){let k=C.value;if(C.type==="checkbox")k=C.checked;else if(C.type==="number"){if(k=parseFloat(C.value),isNaN(k))return}else if(C.dataset.json==="true")try{k=JSON.parse(C.value)}catch{return}C.type==="text"||C.type==="range"||C.tagName==="TEXTAREA"?t(E,A,k):(this.updateManager.updateProperty(E,A,k),(j=(x=this.options)==null?void 0:x.onPropertyChange)==null||j.call(x,E,A,k))}},_=w.dataset.propertyPath;_&&(_.includes("transform.anchor")||_.includes("render.anchor"))&&w.tagName==="SELECT"?w.addEventListener("change",async I=>{var j,k;let C=I.target,A=C.dataset.propertyPath,E=C.dataset.objectId,x=C.value;!A||!E||x!=="custom"&&(await this.updateManager.updateProperty(E,A,x),(k=(j=this.options)==null?void 0:j.onPropertyChange)==null||k.call(j,E,A,x))}):n(_)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",_),w.addEventListener("change",async I=>{var N;let C=I.target,A=C.dataset.propertyPath,E=C.dataset.objectId,x=C.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!A||!E)return;await this.updateManager.updateProperty(E,A,x),console.log("[Inspector v1.0.0] Logic ID updated");let j=window,k=(N=j==null?void 0:j.__HANDLER_LOGIC_META)==null?void 0:N[x],R=this.getDefaultPropsForLogic(x,k);console.log("[Inspector v1.0.0] New logic default props:",R);let z=A.replace(/\.id$/,".props");await this.updateManager.updateProperty(E,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(E)})):(w.addEventListener("change",P),(w.tagName==="INPUT"||w.tagName==="TEXTAREA")&&w.addEventListener("input",P))}),this.contentContainer.querySelectorAll("[data-action]").forEach(w=>{w.addEventListener("click",P=>{let _=P.target,T=_.dataset.action,I=_.dataset.path,C=_.dataset.object;T&&I&&C&&this.quickActions.handleAction(T,C,I)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(w=>{w.addEventListener("click",P=>{var I,C;let _=P.target,T=_.dataset.sectionToggle||((I=_.closest("[data-section-toggle]"))==null?void 0:I.getAttribute("data-section-toggle"));if(T){let A=(C=this.contentContainer)==null?void 0:C.querySelector(`[data-section="${T}"]`);A==null||A.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(w=>{w.addEventListener("click",async P=>{let T=P.currentTarget.dataset.motionPreset;!T||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,T)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(w=>{w.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(w=>{w.addEventListener("click",async P=>{let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath;if(!T||!I)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(T);if(!A)return;let E=this.updateManager.getNestedProperty(A,I),x=Array.isArray(E)?[...E]:[];x.push({x:0,y:0}),await this.updateManager.updateProperty(T,I,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(w=>{w.addEventListener("click",async P=>{let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath,C=Number(_.dataset.index||"-1");if(!T||!I||C<0)return;let A=window.getEditableObjectConfig,E=A==null?void 0:A(T);if(!E)return;let x=this.updateManager.getNestedProperty(E,I);if(!Array.isArray(x))return;let j=x.filter((k,R)=>R!==C);await this.updateManager.updateProperty(T,I,j),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(w=>{w.addEventListener("click",async P=>{let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath;if(!T||!I)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(T);if(!A)return;let E=this.updateManager.getNestedProperty(A,I),x=Array.isArray(E)?[...E]:[];x.push({templateId:"",weight:1}),await this.updateManager.updateProperty(T,I,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(w=>{w.addEventListener("click",async P=>{var k;let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath,C=Number((k=_.dataset.index)!=null?k:-1);if(!T||!I||C<0)return;let A=window.getEditableObjectConfig,E=A==null?void 0:A(T);if(!E)return;let x=this.updateManager.getNestedProperty(E,I);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(T,I,j),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(w=>{w.addEventListener("click",async P=>{var N;let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath;if(!T||!I)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(T);if(!A)return;let E=this.updateManager.getNestedProperty(A,I),x;Array.isArray(E)?x=[...E]:E!=null?typeof E=="string"?x=[{id:E,props:{}}]:typeof E=="object"?x=[E]:x=[]:x=[];let j=this.getDefaultLogicId(),k=window,R=(N=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:N[j],z=this.getDefaultPropsForLogic(j,R);x.push({id:j,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:T,path:I,current:E,next:x}),await this.updateManager.updateProperty(T,I,x),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(w=>{w.addEventListener("click",async P=>{var k;let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath,C=Number((k=_.dataset.index)!=null?k:-1);if(!T||!I||C<0)return;let A=window.getEditableObjectConfig,E=A==null?void 0:A(T);if(!E)return;let x=this.updateManager.getNestedProperty(E,I);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(T,I,j),this.loadObject(T)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(w=>{w.addEventListener("click",async P=>{var Y,B;let _=P.target,T=_.dataset.objectId,I=_.dataset.propertyPath,C=Number((Y=_.dataset.index)!=null?Y:-1);if(!T||!I||C<0)return;let A=window.getEditableObjectConfig,E=A==null?void 0:A(T);if(!E)return;let x=this.updateManager.getNestedProperty(E,I);if(!Array.isArray(x))return;let j=x[C];if(typeof j!="string")return;let k=window,R=(B=k==null?void 0:k.__HANDLER_LOGIC_META)==null?void 0:B[j],z=this.getDefaultPropsForLogic(j,R),N=[...x];N[C]={id:j,props:z},await this.updateManager.updateProperty(T,I,N),this.loadObject(T)})});let f=(S=this.root)==null?void 0:S.querySelector("[data-inspector-advanced]");f==null||f.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let y=(L=this.root)==null?void 0:L.querySelector("[data-convert-toggle]");y==null||y.addEventListener("click",()=>{var P;let w=(P=this.root)==null?void 0:P.querySelector("[data-convert-menu]");w==null||w.classList.toggle("hidden")});let b=(M=this.contentContainer)==null?void 0:M.querySelector("[data-inspector-add-component-btn]"),v=(O=this.contentContainer)==null?void 0:O.querySelector("[data-inspector-component-select]");b==null||b.addEventListener("click",async()=>{let w=v.value;w&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,w)})}getMotionDefaults(){var n,i,a,r;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(r=(a=t.motion)==null?void 0:a.defaults)!=null?r:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),r={...(l=i.motion)!=null?l:a},o={...(c=r.intro)!=null?c:{}};r.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",r.intro=o,await this.updateManager.updateProperty(e,"motion",r),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},r={...(l=a.intro)!=null?l:{}};a.enabled=!0,r.enabled=!0,a.intro=r,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,r=a==null?void 0:a.schemas,o=null;r instanceof Map?o=r.get(t):r&&typeof r=="object"&&(o=r[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(a=n.render)==null?void 0:a.asset)==null?void 0:r.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1225
+ `}attachEventListeners(){var E,P,I,O;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=rl((w,k,_)=>{var L,M;this.updateManager.updateProperty(w,k,_),(M=(L=this.options)==null?void 0:L.onPropertyChange)==null||M.call(L,w,k,_)},300),n=w=>w?/(^|\.)logic(\.\d+)?\.id$/.test(w):!1;e.forEach(w=>{let k=M=>{var x,j;let C=M.target,A=C.dataset.propertyPath,S=C.dataset.objectId;if(A&&S){let T=C.value;if(C.type==="checkbox")T=C.checked;else if(C.type==="number"){if(T=parseFloat(C.value),isNaN(T))return}else if(C.dataset.json==="true")try{T=JSON.parse(C.value)}catch{return}C.type==="text"||C.type==="range"||C.tagName==="TEXTAREA"?t(S,A,T):(this.updateManager.updateProperty(S,A,T),(j=(x=this.options)==null?void 0:x.onPropertyChange)==null||j.call(x,S,A,T))}},_=w.dataset.propertyPath;_&&(_.includes("transform.anchor")||_.includes("render.anchor"))&&w.tagName==="SELECT"?w.addEventListener("change",async M=>{var j,T;let C=M.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;!A||!S||x!=="custom"&&(await this.updateManager.updateProperty(S,A,x),(T=(j=this.options)==null?void 0:j.onPropertyChange)==null||T.call(j,S,A,x))}):n(_)?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",_),w.addEventListener("change",async M=>{var N;let C=M.target,A=C.dataset.propertyPath,S=C.dataset.objectId,x=C.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!A||!S)return;await this.updateManager.updateProperty(S,A,x),console.log("[Inspector v1.0.0] Logic ID updated");let j=window,T=(N=j==null?void 0:j.__HANDLER_LOGIC_META)==null?void 0:N[x],R=this.getDefaultPropsForLogic(x,T);console.log("[Inspector v1.0.0] New logic default props:",R);let z=A.replace(/\.id$/,".props");await this.updateManager.updateProperty(S,z,R),console.log("[Inspector v1.0.0] Logic props updated to:",R),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(S)})):(w.addEventListener("change",k),(w.tagName==="INPUT"||w.tagName==="TEXTAREA")&&w.addEventListener("input",k))}),this.contentContainer.querySelectorAll("[data-action]").forEach(w=>{w.addEventListener("click",k=>{let _=k.target,L=_.dataset.action,M=_.dataset.path,C=_.dataset.object;L&&M&&C&&this.quickActions.handleAction(L,C,M)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(w=>{w.addEventListener("click",k=>{var M,C;let _=k.target,L=_.dataset.sectionToggle||((M=_.closest("[data-section-toggle]"))==null?void 0:M.getAttribute("data-section-toggle"));if(L){let A=(C=this.contentContainer)==null?void 0:C.querySelector(`[data-section="${L}"]`);A==null||A.classList.toggle("collapsed")}})}),this.contentContainer.querySelectorAll("[data-motion-preset]").forEach(w=>{w.addEventListener("click",async k=>{let L=k.currentTarget.dataset.motionPreset;!L||!this.selectedObjectId||await this.applyMotionPreset(this.selectedObjectId,L)})}),this.contentContainer.querySelectorAll("[data-motion-preview]").forEach(w=>{w.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(w=>{w.addEventListener("click",async k=>{let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath;if(!L||!M)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(L);if(!A)return;let S=this.updateManager.getNestedProperty(A,M),x=Array.isArray(S)?[...S]:[];x.push({x:0,y:0}),await this.updateManager.updateProperty(L,M,x),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-spawnpoints-remove]").forEach(w=>{w.addEventListener("click",async k=>{let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath,C=Number(_.dataset.index||"-1");if(!L||!M||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(L);if(!S)return;let x=this.updateManager.getNestedProperty(S,M);if(!Array.isArray(x))return;let j=x.filter((T,R)=>R!==C);await this.updateManager.updateProperty(L,M,j),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-add]").forEach(w=>{w.addEventListener("click",async k=>{let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath;if(!L||!M)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(L);if(!A)return;let S=this.updateManager.getNestedProperty(A,M),x=Array.isArray(S)?[...S]:[];x.push({templateId:"",weight:1}),await this.updateManager.updateProperty(L,M,x),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-spawntemplates-remove]").forEach(w=>{w.addEventListener("click",async k=>{var T;let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath,C=Number((T=_.dataset.index)!=null?T:-1);if(!L||!M||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(L);if(!S)return;let x=this.updateManager.getNestedProperty(S,M);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(L,M,j),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-logic-add]").forEach(w=>{w.addEventListener("click",async k=>{var N;let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath;if(!L||!M)return;let C=window.getEditableObjectConfig,A=C==null?void 0:C(L);if(!A)return;let S=this.updateManager.getNestedProperty(A,M),x;Array.isArray(S)?x=[...S]:S!=null?typeof S=="string"?x=[{id:S,props:{}}]:typeof S=="object"?x=[S]:x=[]:x=[];let j=this.getDefaultLogicId(),T=window,R=(N=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:N[j],z=this.getDefaultPropsForLogic(j,R);x.push({id:j,props:z}),console.log("[InspectorPanel] Adding logic to array:",{objectId:L,path:M,current:S,next:x}),await this.updateManager.updateProperty(L,M,x),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-logic-remove]").forEach(w=>{w.addEventListener("click",async k=>{var T;let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath,C=Number((T=_.dataset.index)!=null?T:-1);if(!L||!M||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(L);if(!S)return;let x=this.updateManager.getNestedProperty(S,M);if(!Array.isArray(x))return;let j=x.filter((R,z)=>z!==C);await this.updateManager.updateProperty(L,M,j),this.loadObject(L)})}),this.contentContainer.querySelectorAll("[data-logic-convert]").forEach(w=>{w.addEventListener("click",async k=>{var Y,F;let _=k.target,L=_.dataset.objectId,M=_.dataset.propertyPath,C=Number((Y=_.dataset.index)!=null?Y:-1);if(!L||!M||C<0)return;let A=window.getEditableObjectConfig,S=A==null?void 0:A(L);if(!S)return;let x=this.updateManager.getNestedProperty(S,M);if(!Array.isArray(x))return;let j=x[C];if(typeof j!="string")return;let T=window,R=(F=T==null?void 0:T.__HANDLER_LOGIC_META)==null?void 0:F[j],z=this.getDefaultPropsForLogic(j,R),N=[...x];N[C]={id:j,props:z},await this.updateManager.updateProperty(L,M,N),this.loadObject(L)})});let f=(E=this.root)==null?void 0:E.querySelector("[data-inspector-advanced]");f==null||f.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let y=(P=this.root)==null?void 0:P.querySelector("[data-convert-toggle]");y==null||y.addEventListener("click",()=>{var k;let w=(k=this.root)==null?void 0:k.querySelector("[data-convert-menu]");w==null||w.classList.toggle("hidden")});let b=(I=this.contentContainer)==null?void 0:I.querySelector("[data-inspector-add-component-btn]"),v=(O=this.contentContainer)==null?void 0:O.querySelector("[data-inspector-component-select]");b==null||b.addEventListener("click",async()=>{let w=v.value;w&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,w)})}getMotionDefaults(){var n,i,a,r;let e=window.__editableConfig,t=e==null?void 0:e.schemas;return t instanceof Map?(i=(n=t.get("motion"))==null?void 0:n.defaults)!=null?i:{enabled:!0}:t&&typeof t=="object"?(r=(a=t.motion)==null?void 0:a.defaults)!=null?r:{enabled:!0}:{enabled:!0}}async applyMotionPreset(e,t){var l,c;let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i)return;let a=this.getMotionDefaults(),r={...(l=i.motion)!=null?l:a},o={...(c=r.intro)!=null?c:{}};r.enabled=!0,o.enabled=!0,o.type=t,o.duration=typeof o.duration=="number"&&o.duration>0?o.duration:500,o.delay=typeof o.delay=="number"?o.delay:0,o.easing=typeof o.easing=="string"?o.easing:"easeOut",r.intro=o,await this.updateManager.updateProperty(e,"motion",r),this.expandMotionOnNextRender=!0,this.loadObject(e)}async previewMotionIntro(e){var o,l;let t=window.getEditableObjectConfig,n=t==null?void 0:t(e);if(!n)return;let i=this.getMotionDefaults(),a={...(o=n.motion)!=null?o:i},r={...(l=a.intro)!=null?l:{}};a.enabled=!0,r.enabled=!0,a.intro=r,await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!1}}),await this.updateManager.updateProperty(e,"motion",{...a,intro:{...r,enabled:!0}}),this.loadObject(e)}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,i=n==null?void 0:n(e);if(!i){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};i[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}t==="motion"&&(this.expandMotionOnNextRender=!0);let a=window.__editableConfig,r=a==null?void 0:a.schemas,o=null;r instanceof Map?o=r.get(t):r&&typeof r=="object"&&(o=r[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};i[t]={...l},await this.updateManager.updateProperty(e,t,i[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var a,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(a=n.render)==null?void 0:a.asset)==null?void 0:r.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let i=Object.keys(t);return i.length===0||i.length===1&&i[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
1226
1226
  <div class="inspector-empty">
1227
1227
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
1228
1228
  <span class="inspector-empty-text">${e}</span>
@@ -1232,7 +1232,7 @@ ${m}
1232
1232
  <span class="inspector-empty-icon">\u{1F3AF}</span>
1233
1233
  <span class="inspector-empty-text">Select an object to inspect</span>
1234
1234
  </div>
1235
- `)}};function fa(s){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(s)})}function sr(s){var i;let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}async function rr(s){return await new Promise(e=>{let t=new Image;t.onload=()=>e({width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}),t.onerror=()=>e(null),t.src=s})}async function di(s){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",s);let n=await fetch(s);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,s),null;let i=await n.blob();console.log("[ImageUtils] Blob received, size:",i.size,"type:",i.type);let a=await fa(i),r=await rr(a),o=sr(a);return console.log("[ImageUtils] Success resolution:",r==null?void 0:r.width,"x",r==null?void 0:r.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(e=r==null?void 0:r.width)!=null?e:0,height:(t=r==null?void 0:r.height)!=null?t:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Ve(s){var e,t;try{let n=await fa(s),i=await rr(n),a=sr(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(e=i==null?void 0:i.width)!=null?e:0,height:(t=i==null?void 0:i.height)!=null?t:0}}catch{return null}}function ya(s){return fa(s).then(e=>e).catch(()=>null)}function ba(s,e){var t;try{let[n,i]=s.split(","),a=n.match(/data:(.*?);base64/),r=(t=a==null?void 0:a[1])!=null?t:"image/png",o=atob(i),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],e,{type:r})}catch{return null}}async function At(s,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((p,u)=>{let g=new Image;g.onload=()=>p(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=s}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let i=n.getContext("2d");if(!i)return console.error("[ImageUtils] Failed to get canvas context"),s;i.drawImage(t,0,0);let a=i.getImageData(0,0,n.width,n.height),r=a.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(p=>({r:r[p.offset],g:r[p.offset+1],b:r[p.offset+2]})),c=0;for(let p=0;p<r.length;p+=4){let u=r[p],g=r[p+1],h=r[p+2],m=!1;for(let f of l)if(Math.sqrt(Math.pow(u-f.r,2)+Math.pow(g-f.g,2)+Math.pow(h-f.b,2))<e){m=!0;break}m&&(r[p+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),i.putImageData(a,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),s}}function va(s,e){if(!s||!e)return"1:1";let t=s/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function Re(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function te(s){return typeof s=="string"?s:void 0}function or(s){return s.toLowerCase().endsWith(".png")?s.slice(0,-4):s}function ml(s){var n,i,a;let e=(n=te(s.id))!=null?n:te(s.name);if(e)return e;let t=(i=te(s.file))!=null?i:te(s.asset);return t?or((a=t.split("/").pop())!=null?a:t):void 0}function fl(s,e,t){var n,i,a;if(typeof e=="string")return{id:s,file:e,role:t};if(Re(e)){let r=(n=te(e.file))!=null?n:te(e.asset);return r?{id:(i=te(e.id))!=null?i:s,file:r,role:(a=te(e.role))!=null?a:t,dataUrl:te(e.dataUrl),layout:e.layout}:null}return null}function wa(s,e){var t,n,i;if(!s)return[];if(Array.isArray(s)){let a=[];for(let r of s){if(typeof r=="string"){let o=or((t=r.split("/").pop())!=null?t:r);a.push({id:o,file:r,role:e});continue}if(Re(r)){let o=ml(r),l=(n=te(r.file))!=null?n:te(r.asset);if(!o||!l)continue;a.push({id:o,file:l,role:(i=te(r.role))!=null?i:e,dataUrl:te(r.dataUrl),layout:r.layout})}}return a}if(Re(s)){let a=[];for(let[r,o]of Object.entries(s)){let l=fl(r,o,e);l&&a.push(l)}return a}return[]}function yl(s){var e,t;return(t=(e=te(s.brand_name))!=null?e:te(s.brandName))!=null?t:te(s.name)}function bl(s){if(Re(s.brand_dna)&&Re(s.brand_dna.colors))return s.brand_dna;if(Re(s.colors)){let e={colors:s.colors};return typeof s.style=="string"&&(e.style=s.style),Re(s.fonts)&&(e.fonts=s.fonts),e}}function vl(s){var t;let e=new Map;for(let n of s){let i=e.get(n.id);if(!i){e.set(n.id,n);continue}e.set(n.id,{...i,...n,file:n.file||i.file,role:n.role||i.role,dataUrl:n.dataUrl||i.dataUrl,layout:(t=n.layout)!=null?t:i.layout})}return Array.from(e.values())}function lr(s,e={}){var r,o,l;let t=s.filter(Re),n=(o=(r=t.map(yl).find(Boolean))!=null?r:e.defaultBrandName)!=null?o:"Imported Brand",i=(l=t.map(bl).find(Boolean))!=null?l:{colors:{}},a=[];for(let c of t)"layers"in c&&a.push(...wa(c.layers,"visual element")),"assets"in c&&a.push(...wa(c.assets,"visual element")),Re(c.endgame)&&"assets"in c.endgame&&a.push(...wa(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:i,assets:vl(a)}}var cr=require("@google/genai");async function pi(s,e,t=[],n={}){var i,a,r,o,l,c,d;try{if(!(s!=null&&s.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let y=0;y<t.length;y++){let b=t[y];if(!b.base64||!b.mimeType)throw new Error(`Image ${y+1} is missing required data`);if(b.base64.length<1e3&&console.warn(`Image ${y+1} data appears very small, may be corrupted`),!b.mimeType.startsWith("image/"))throw new Error(`Image ${y+1} has invalid MIME type: ${b.mimeType}`)}let p=new cr.GoogleGenAI({apiKey:s}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((y,b)=>{g.push({inlineData:{data:y.base64,mimeType:y.mimeType}}),console.log(`[Gemini] Added image ${b+1}: ${y.mimeType}, size: ${Math.round(y.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let h=await p.models.generateContent({model:u,contents:g}),m="",f=(r=(a=(i=h.candidates)==null?void 0:i[0])==null?void 0:a.content)==null?void 0:r.parts;if(f)for(let y of f)y.text&&(m+=y.text);if(!m.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${m.length}`),m}catch(p){throw console.error("[Gemini] API error:",p),(o=p.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(l=p.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=p.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(d=p.message)!=null&&d.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):p}}var dr=require("@google/genai");async function Lt(s,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let i=new dr.GoogleGenAI({apiKey:s}),a=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let r=await i.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!r.candidates||!r.candidates[0]||!r.candidates[0].content||!r.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of r.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let l=o.inlineData.data,c=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${c};base64,${l}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(i){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(i,Object.getOwnPropertyNames(i),2)),i}}function pr(s){let e=s.brandAssets.map(a=>{let r=`- ${a.id}: ${a.role}`;return a.layout&&(r+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),r}).join(`
1235
+ `)}};function la(s){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(s)})}function Js(s){var i;let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}async function Zs(s){return await new Promise(e=>{let t=new Image;t.onload=()=>e({width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}),t.onerror=()=>e(null),t.src=s})}async function ei(s){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",s);let n=await fetch(s);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,s),null;let i=await n.blob();console.log("[ImageUtils] Blob received, size:",i.size,"type:",i.type);let a=await la(i),r=await Zs(a),o=Js(a);return console.log("[ImageUtils] Success resolution:",r==null?void 0:r.width,"x",r==null?void 0:r.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(e=r==null?void 0:r.width)!=null?e:0,height:(t=r==null?void 0:r.height)!=null?t:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function qe(s){var e,t;try{let n=await la(s),i=await Zs(n),a=Js(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(e=i==null?void 0:i.width)!=null?e:0,height:(t=i==null?void 0:i.height)!=null?t:0}}catch{return null}}function ca(s){return la(s).then(e=>e).catch(()=>null)}function da(s,e){var t;try{let[n,i]=s.split(","),a=n.match(/data:(.*?);base64/),r=(t=a==null?void 0:a[1])!=null?t:"image/png",o=atob(i),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],e,{type:r})}catch{return null}}async function mt(s,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((p,u)=>{let g=new Image;g.onload=()=>p(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=s}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let i=n.getContext("2d");if(!i)return console.error("[ImageUtils] Failed to get canvas context"),s;i.drawImage(t,0,0);let a=i.getImageData(0,0,n.width,n.height),r=a.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(p=>({r:r[p.offset],g:r[p.offset+1],b:r[p.offset+2]})),c=0;for(let p=0;p<r.length;p+=4){let u=r[p],g=r[p+1],h=r[p+2],m=!1;for(let f of l)if(Math.sqrt(Math.pow(u-f.r,2)+Math.pow(g-f.g,2)+Math.pow(h-f.b,2))<e){m=!0;break}m&&(r[p+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),i.putImageData(a,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),s}}function pa(s,e){if(!s||!e)return"1:1";let t=s/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function Re(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function ie(s){return typeof s=="string"?s:void 0}function Qs(s){return s.toLowerCase().endsWith(".png")?s.slice(0,-4):s}function ol(s){var n,i,a;let e=(n=ie(s.id))!=null?n:ie(s.name);if(e)return e;let t=(i=ie(s.file))!=null?i:ie(s.asset);return t?Qs((a=t.split("/").pop())!=null?a:t):void 0}function ll(s,e,t){var n,i,a;if(typeof e=="string")return{id:s,file:e,role:t};if(Re(e)){let r=(n=ie(e.file))!=null?n:ie(e.asset);return r?{id:(i=ie(e.id))!=null?i:s,file:r,role:(a=ie(e.role))!=null?a:t,dataUrl:ie(e.dataUrl),layout:e.layout}:null}return null}function ua(s,e){var t,n,i;if(!s)return[];if(Array.isArray(s)){let a=[];for(let r of s){if(typeof r=="string"){let o=Qs((t=r.split("/").pop())!=null?t:r);a.push({id:o,file:r,role:e});continue}if(Re(r)){let o=ol(r),l=(n=ie(r.file))!=null?n:ie(r.asset);if(!o||!l)continue;a.push({id:o,file:l,role:(i=ie(r.role))!=null?i:e,dataUrl:ie(r.dataUrl),layout:r.layout})}}return a}if(Re(s)){let a=[];for(let[r,o]of Object.entries(s)){let l=ll(r,o,e);l&&a.push(l)}return a}return[]}function cl(s){var e,t;return(t=(e=ie(s.brand_name))!=null?e:ie(s.brandName))!=null?t:ie(s.name)}function dl(s){if(Re(s.brand_dna)&&Re(s.brand_dna.colors))return s.brand_dna;if(Re(s.colors)){let e={colors:s.colors};return typeof s.style=="string"&&(e.style=s.style),Re(s.fonts)&&(e.fonts=s.fonts),e}}function pl(s){var t;let e=new Map;for(let n of s){let i=e.get(n.id);if(!i){e.set(n.id,n);continue}e.set(n.id,{...i,...n,file:n.file||i.file,role:n.role||i.role,dataUrl:n.dataUrl||i.dataUrl,layout:(t=n.layout)!=null?t:i.layout})}return Array.from(e.values())}function er(s,e={}){var r,o,l;let t=s.filter(Re),n=(o=(r=t.map(cl).find(Boolean))!=null?r:e.defaultBrandName)!=null?o:"Imported Brand",i=(l=t.map(dl).find(Boolean))!=null?l:{colors:{}},a=[];for(let c of t)"layers"in c&&a.push(...ua(c.layers,"visual element")),"assets"in c&&a.push(...ua(c.assets,"visual element")),Re(c.endgame)&&"assets"in c.endgame&&a.push(...ua(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:i,assets:pl(a)}}var tr=require("@google/genai");async function ti(s,e,t=[],n={}){var i,a,r,o,l,c,d;try{if(!(s!=null&&s.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let y=0;y<t.length;y++){let b=t[y];if(!b.base64||!b.mimeType)throw new Error(`Image ${y+1} is missing required data`);if(b.base64.length<1e3&&console.warn(`Image ${y+1} data appears very small, may be corrupted`),!b.mimeType.startsWith("image/"))throw new Error(`Image ${y+1} has invalid MIME type: ${b.mimeType}`)}let p=new tr.GoogleGenAI({apiKey:s}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((y,b)=>{g.push({inlineData:{data:y.base64,mimeType:y.mimeType}}),console.log(`[Gemini] Added image ${b+1}: ${y.mimeType}, size: ${Math.round(y.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let h=await p.models.generateContent({model:u,contents:g}),m="",f=(r=(a=(i=h.candidates)==null?void 0:i[0])==null?void 0:a.content)==null?void 0:r.parts;if(f)for(let y of f)y.text&&(m+=y.text);if(!m.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${m.length}`),m}catch(p){throw console.error("[Gemini] API error:",p),(o=p.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(l=p.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=p.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(d=p.message)!=null&&d.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):p}}var nr=require("@google/genai");async function ft(s,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let i=new nr.GoogleGenAI({apiKey:s}),a=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let r=await i.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!r.candidates||!r.candidates[0]||!r.candidates[0].content||!r.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of r.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let l=o.inlineData.data,c=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${c};base64,${l}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(i){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(i,Object.getOwnPropertyNames(i),2)),i}}function ir(s){let e=s.brandAssets.map(a=>{let r=`- ${a.id}: ${a.role}`;return a.layout&&(r+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),r}).join(`
1236
1236
  `)||"None",t=s.brandDna?`Colors: ${JSON.stringify(s.brandDna.colors)}, Style: ${s.brandDna.style||"not specified"}`:"Not provided",n=s.gameObjects.map(a=>typeof a=="string"?`- id: ${a}`:`- id: ${a.id}${a.category?`, category: ${a.category}`:""}${a.type?`, type: ${a.type}`:""}`).join(`
1237
1237
  `),i="";if(s.brandConfig){let a=s.brandConfig,r=[];a.splash&&r.push(`SPLASH: title="${a.splash.title||""}", subtitle="${a.splash.subtitle||""}", button="${a.splash.button_label||""}"`),a.endgame&&r.push(`ENDGAME: title="${a.endgame.title||""}", subtitle="${a.endgame.subtitle||""}", cta="${a.endgame.cta_label||""}"`),a.tutorial&&r.push(`TUTORIAL: text="${a.tutorial.label_text||""}", helper="${a.tutorial.helper_text||""}"`),r.length>0&&(i=`
1238
1238
  BRAND CONTENT:
@@ -1296,7 +1296,7 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
1296
1296
  }
1297
1297
  ]
1298
1298
  }
1299
- `.trim()}function ur(s){var i,a;let e=(i=s.brandDna)!=null&&i.colors?`Primary: ${s.brandDna.colors.primary}, Secondary: ${s.brandDna.colors.secondary||"N/A"}, Accent: ${s.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((a=s.brandDna)==null?void 0:a.style)||"modern gaming style",n=s.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
1299
+ `.trim()}function ar(s){var i,a;let e=(i=s.brandDna)!=null&&i.colors?`Primary: ${s.brandDna.colors.primary}, Secondary: ${s.brandDna.colors.secondary||"N/A"}, Accent: ${s.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((a=s.brandDna)==null?void 0:a.style)||"modern gaming style",n=s.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
1300
1300
  TASK: ${s.prompt}
1301
1301
 
1302
1302
  BRAND STYLE:
@@ -1317,7 +1317,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
1317
1317
 
1318
1318
  OUTPUT:
1319
1319
  Generate the requested asset matching the brand style.${s.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
1320
- `.trim()}function gr(s){return s.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function hr(s,e){return!(s.includes("background")&&(s.includes("_1")||s.includes("splash")||s.includes("endgame")||s.includes("main"))||e==="text"||e==="effects"&&s.includes("particle"))}async function mr(s){var r,o;let e=gr(s.gameObjects),t={gamePrompt:s.gamePrompt,gameObjects:e,brandAssets:s.manifest.assets,brandDna:s.manifest.brand_dna,brandName:s.manifest.brand_name},n=pr(t),i=[];if(s.flatDesignDataUrl)try{let l=fr(s.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await pi(s.apiKey,n,i,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(r=l.message)!=null&&r.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return wl(a,s.gameObjects)}function wl(s,e){try{let t=s,n=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let a=s.match(/\{[\s\S]*\}/);a&&(t=a[0])}let i=JSON.parse(t);return i.mappings&&Array.isArray(i.mappings)?{mappingResult:i,rawResponse:s,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:s,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:s,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function xa(s,e,t={}){var i;let n=e.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let r=n[a];(i=t.onProgress)==null||i.call(t,a+1,n.length,r.game_object);try{let o=await xl(s,r);r.output_dataUrl=o,r.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${r.game_object}:`,o),r.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function xl(s,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&s.manifest){let o=s.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=s.assetFiles.get(o.file);if(l){let c=await Ve(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(s.flatDesignDataUrl){let o=fr(s.flatDesignDataUrl);o&&t.push(o)}let n=hr(e.game_object),i={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:s.manifest.brand_dna,needsTransparency:n},a=ur(i);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await Lt(s.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await At(r)||r}function fr(s){let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function yr(s,e){let t=s.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([i,a])=>({id:i,file:String(a),role:"visual element"})):n=[],s.assets=n;for(let i of n){let a=e.get(i.file);if(a){let r=await Ve(a);r&&(i.dataUrl=r.dataUrl)}}}function br(s){var t,n;let e=new Map;if(!s)return console.warn("[CanvaZip] No position data provided"),e;if(typeof s=="string")try{s=JSON.parse(s)}catch(i){return console.error("[CanvaZip] Failed to parse position data JSON:",i),e}if(s!=null&&s.layers&&Array.isArray(s.layers)){console.log(`[CanvaZip] Parsing ${s.layers.length} layers from position data`);for(let i of s.layers){let a=i.asset;if(!a||!i.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",i);continue}let r=i.layout,o={x:typeof r.x=="number"?r.x:0,y:typeof r.y=="number"?r.y:0},l=typeof r.scaleX=="number"?r.scaleX:1,c=typeof r.scaleY=="number"?r.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof r.rotation=="number"?r.rotation:0;e.set(a,{position:o,scale:d,rotation:p}),console.log(`[CanvaZip] Parsed position for ${a}:`,{position:o,scale:d,rotation:p})}console.log(`[CanvaZip] Successfully parsed ${e.size} assets from position data`)}else console.warn("[CanvaZip] Position data does not have layers array:",s);if(e.size===0&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(a&&typeof a=="object"&&"layout"in a){let r=a.layout,o={x:0,y:0},l=1,c=0;if(r.position&&typeof r.position=="object"?o={x:r.position.x||0,y:r.position.y||0}:(typeof r.x=="number"||typeof r.y=="number")&&(o={x:r.x||0,y:r.y||0}),typeof r.scale=="number")l=r.scale;else if(typeof r.scaleX=="number"||typeof r.scaleY=="number"){let d=(t=r.scaleX)!=null?t:1,p=(n=r.scaleY)!=null?n:1;l=(d+p)/2}typeof r.rotation=="number"&&(c=r.rotation),e.set(i,{position:o,scale:l,rotation:c})}}return e}function vr(s,e){if(!s)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",s),null;if(e.has(s))return console.log(`[CanvaZip] Exact match found for ${s}`),e.get(s);let t=s.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${s} -> ${t}`),e.get(t);let n=t.toLowerCase();for(let[i,a]of e.entries()){let r=i.toLowerCase();if(r===n||r.includes(n)||n.includes(r))return console.log(`[CanvaZip] Partial match found for ${s} -> ${i}`),a}return console.warn(`[CanvaZip] No match found for ${s}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function Sl(s){return s.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function wr(){let s=window.getEditableAssets;if(typeof s!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=s();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let n of e.slots)n.assetType==="image"&&n.objectId&&t.push({id:n.objectId,name:n.displayName||Sl(n.slotId||n.objectId),type:"sprite"});return t.sort((n,i)=>n.name.localeCompare(i.name))}var Tt=require("pixi.js");Et();vn();Z();async function Sr(s,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Tt.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)we[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let p=window.gameObjectManager;if(p)for(let u of d){let g=p.get(u);if(g){let h=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function Er(s,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,r=typeof a=="function"?a():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(f=>f.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 Tt.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(f=>f.startsWith(g)||f.includes(g));for(let f of h)we[f]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(n=u[f])!=null&&n.texture&&(u[f].texture=p,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let m=window.gameObjectManager;if(m)for(let f of h){let y=m.get(f);if(y){let b=((i=y.getDisplayObject)==null?void 0:i.call(y))||y.pixiObject||y;b!=null&&b.texture&&(b.texture=p,console.log("[LIBRARY] \u2705 Reset display object:",f))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function ui(s,e,t,n){var i,a,r,o,l,c,d,p,u,g,h,m,f,y,b;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let S=Ar(v),L=Date.now(),M=`/raw/library/${n}/${t}?t=${L}`;console.log("[LIBRARY] Loading texture from:",M);let O=await Tt.Assets.load(M);if(!O){console.error("[LIBRARY] Failed to load texture:",M);return}console.log("[LIBRARY] \u2705 Texture loaded"),we[v]=O,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let w=window.CustomAssets;w!=null&&w[v]&&(w[v].texture=O,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let P=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!P),P){let T=Array.from(((i=P.keys)==null?void 0:i.call(P))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",T);let I=P.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!I),I){let C=((a=I.getDisplayObject)==null?void 0:a.call(I))||I.pixiObject||I.pixi||I,A=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",A),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=O,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(A==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:E}=await import("pixi.js"),x=C.parent,j=(l=(o=x==null?void 0:x.getChildIndex)==null?void 0:o.call(x,C))!=null?l:0,k={x:C.x,y:C.y},R={x:(d=(c=C.anchor)==null?void 0:c.x)!=null?d:.5,y:(u=(p=C.anchor)==null?void 0:p.y)!=null?u:.5},z={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(f=(m=C.scale)==null?void 0:m.y)!=null?f:1},N=(y=C.alpha)!=null?y:1,Y=(b=C.visible)!=null?b:!0,B=new E(O);B.anchor.set(R.x,R.y),B.position.set(k.x,k.y),B.scale.set(z.x,z.y),B.alpha=N,B.visible=Y,x&&(x.removeChild(C),x.addChildAt(B,j),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),I.pixiObject&&(I.pixiObject=B),I.pixi&&(I.pixi=B),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let E=C.children.find(x=>x.texture);E?(E.texture=O,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let _=`raw/library/${n}/${t}`;Lr(v,_,O,S),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:v,texture:O,assetPath:_}})),se({objectId:v,path:"render.asset.path",value:_}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",_)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Cr(s,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,r=Ar(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await Tt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}we[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let d=window.CustomAssets;d!=null&&d[a]&&(d[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let u=p.get(a);if(u){let g=((i=u.getDisplayObject)==null?void 0:i.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}Lr(a,t,c,r),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),se({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function Ar(s){var e,t,n;try{let i=window.getEditableObjectConfig,a=typeof i=="function"?i(s):null;return(n=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?n:null}catch{return null}}function Lr(s,e,t,n){if(e){try{let i=`${s}:${e}`;le.set(i,t)}catch{}if(n&&n!==e)try{let i=le.store;i!=null&&i.delete&&i.delete(`${s}:${n}`)}catch{}xr(e,t),n&&n!==e&&xr(n,null)}}function xr(s,e){if(!s)return;let t=Tt.Assets.cache;if(!t)return;let n=s.replace(/^\.?\//,""),i=[n,`/${n}`];for(let a of i)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var gi=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`
1320
+ `.trim()}function sr(s){return s.map(e=>{if(typeof e=="string"){let t=e,n,i;return t.includes("background")?(n="background",i="background"):t.includes("button")||t.includes("cta")?(n="ui",i="button"):t.includes("logo")?(n="ui",i="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",i="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",i="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",i="image"):(n="environment",i="interactive"),{id:t,category:n,type:i}}return e})}function rr(s,e){return!(s.includes("background")&&(s.includes("_1")||s.includes("splash")||s.includes("endgame")||s.includes("main"))||e==="text"||e==="effects"&&s.includes("particle"))}async function or(s){var r,o;let e=sr(s.gameObjects),t={gamePrompt:s.gamePrompt,gameObjects:e,brandAssets:s.manifest.assets,brandDna:s.manifest.brand_dna,brandName:s.manifest.brand_name},n=ir(t),i=[];if(s.flatDesignDataUrl)try{let l=lr(s.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(i.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",i.length,"images...");let a;try{a=await ti(s.apiKey,n,i,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(r=l.message)!=null&&r.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return ul(a,s.gameObjects)}function ul(s,e){try{let t=s,n=s.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let a=s.match(/\{[\s\S]*\}/);a&&(t=a[0])}let i=JSON.parse(t);return i.mappings&&Array.isArray(i.mappings)?{mappingResult:i,rawResponse:s,parsed:!0}:{mappingResult:{mappings:e.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:s,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:s,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function ga(s,e,t={}){var i;let n=e.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let r=n[a];(i=t.onProgress)==null||i.call(t,a+1,n.length,r.game_object);try{let o=await gl(s,r);r.output_dataUrl=o,r.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${r.game_object}:`,o),r.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function gl(s,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&s.manifest){let o=s.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=s.assetFiles.get(o.file);if(l){let c=await qe(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(s.flatDesignDataUrl){let o=lr(s.flatDesignDataUrl);o&&t.push(o)}let n=rr(e.game_object),i={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:s.manifest.brand_dna,needsTransparency:n},a=ar(i);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await ft(s.apiKey,a,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await mt(r)||r}function lr(s){let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function cr(s,e){let t=s.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([i,a])=>({id:i,file:String(a),role:"visual element"})):n=[],s.assets=n;for(let i of n){let a=e.get(i.file);if(a){let r=await qe(a);r&&(i.dataUrl=r.dataUrl)}}}function dr(s){var t,n;let e=new Map;if(!s)return console.warn("[CanvaZip] No position data provided"),e;if(typeof s=="string")try{s=JSON.parse(s)}catch(i){return console.error("[CanvaZip] Failed to parse position data JSON:",i),e}if(s!=null&&s.layers&&Array.isArray(s.layers)){console.log(`[CanvaZip] Parsing ${s.layers.length} layers from position data`);for(let i of s.layers){let a=i.asset;if(!a||!i.layout){console.warn("[CanvaZip] Skipping layer without asset or layout:",i);continue}let r=i.layout,o={x:typeof r.x=="number"?r.x:0,y:typeof r.y=="number"?r.y:0},l=typeof r.scaleX=="number"?r.scaleX:1,c=typeof r.scaleY=="number"?r.scaleY:1,d=(l+c)/2;d>1&&(d=d/13.33);let p=typeof r.rotation=="number"?r.rotation:0;e.set(a,{position:o,scale:d,rotation:p}),console.log(`[CanvaZip] Parsed position for ${a}:`,{position:o,scale:d,rotation:p})}console.log(`[CanvaZip] Successfully parsed ${e.size} assets from position data`)}else console.warn("[CanvaZip] Position data does not have layers array:",s);if(e.size===0&&typeof s=="object"&&!Array.isArray(s)){for(let[i,a]of Object.entries(s))if(a&&typeof a=="object"&&"layout"in a){let r=a.layout,o={x:0,y:0},l=1,c=0;if(r.position&&typeof r.position=="object"?o={x:r.position.x||0,y:r.position.y||0}:(typeof r.x=="number"||typeof r.y=="number")&&(o={x:r.x||0,y:r.y||0}),typeof r.scale=="number")l=r.scale;else if(typeof r.scaleX=="number"||typeof r.scaleY=="number"){let d=(t=r.scaleX)!=null?t:1,p=(n=r.scaleY)!=null?n:1;l=(d+p)/2}typeof r.rotation=="number"&&(c=r.rotation),e.set(i,{position:o,scale:l,rotation:c})}}return e}function pr(s,e){if(!s)return console.warn("[CanvaZip] No filename provided for matching"),null;if(e.size===0)return console.warn("[CanvaZip] Position map is empty, cannot match:",s),null;if(e.has(s))return console.log(`[CanvaZip] Exact match found for ${s}`),e.get(s);let t=s.replace(/\.png$/i,"").replace(/\.jpg$/i,"").replace(/\.jpeg$/i,"");if(e.has(t))return console.log(`[CanvaZip] Match found (without extension) for ${s} -> ${t}`),e.get(t);let n=t.toLowerCase();for(let[i,a]of e.entries()){let r=i.toLowerCase();if(r===n||r.includes(n)||n.includes(r))return console.log(`[CanvaZip] Partial match found for ${s} -> ${i}`),a}return console.warn(`[CanvaZip] No match found for ${s}. Available keys:`,Array.from(e.keys()).slice(0,5)),null}function hl(s){return s.replace(/^json\./,"").replace(/_/g," ").replace(/\b\w/g,e=>e.toUpperCase())}function ur(){let s=window.getEditableAssets;if(typeof s!="function")return console.warn("[CanvaZip] getEditableAssets not available"),[];let e=s();if(!(e!=null&&e.slots)||!Array.isArray(e.slots))return console.warn("[CanvaZip] No slots found in registry"),[];let t=[];for(let n of e.slots)n.assetType==="image"&&n.objectId&&t.push({id:n.objectId,name:n.displayName||hl(n.slotId||n.objectId),type:"sprite"});return t.sort((n,i)=>n.name.localeCompare(i.name))}var yt=require("pixi.js");gt();cn();te();async function hr(s,e,t){var n,i;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let a=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await yt.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)Se[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let p=window.gameObjectManager;if(p)for(let u of d){let g=p.get(u);if(g){let h=((i=g.getDisplayObject)==null?void 0:i.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function mr(s,e){var t,n,i;console.log("[LIBRARY] resetAsset called for:",e);try{let a=window.getEditableAssets,r=typeof a=="function"?a():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(f=>f.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 yt.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(f=>f.startsWith(g)||f.includes(g));for(let f of h)Se[f]=p,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(n=u[f])!=null&&n.texture&&(u[f].texture=p,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let m=window.gameObjectManager;if(m)for(let f of h){let y=m.get(f);if(y){let b=((i=y.getDisplayObject)==null?void 0:i.call(y))||y.pixiObject||y;b!=null&&b.texture&&(b.texture=p,console.log("[LIBRARY] \u2705 Reset display object:",f))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function ni(s,e,t,n){var i,a,r,o,l,c,d,p,u,g,h,m,f,y,b;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let E=yr(v),P=Date.now(),I=`/raw/library/${n}/${t}?t=${P}`;console.log("[LIBRARY] Loading texture from:",I);let O=await yt.Assets.load(I);if(!O){console.error("[LIBRARY] Failed to load texture:",I);return}console.log("[LIBRARY] \u2705 Texture loaded"),Se[v]=O,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let w=window.CustomAssets;w!=null&&w[v]&&(w[v].texture=O,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let k=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!k),k){let L=Array.from(((i=k.keys)==null?void 0:i.call(k))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",L);let M=k.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!M),M){let C=((a=M.getDisplayObject)==null?void 0:a.call(M))||M.pixiObject||M.pixi||M,A=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",A),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=O,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(A==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:S}=await import("pixi.js"),x=C.parent,j=(l=(o=x==null?void 0:x.getChildIndex)==null?void 0:o.call(x,C))!=null?l:0,T={x:C.x,y:C.y},R={x:(d=(c=C.anchor)==null?void 0:c.x)!=null?d:.5,y:(u=(p=C.anchor)==null?void 0:p.y)!=null?u:.5},z={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(f=(m=C.scale)==null?void 0:m.y)!=null?f:1},N=(y=C.alpha)!=null?y:1,Y=(b=C.visible)!=null?b:!0,F=new S(O);F.anchor.set(R.x,R.y),F.position.set(T.x,T.y),F.scale.set(z.x,z.y),F.alpha=N,F.visible=Y,x&&(x.removeChild(C),x.addChildAt(F,j),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),M.pixiObject&&(M.pixiObject=F),M.pixi&&(M.pixi=F),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let S=C.children.find(x=>x.texture);S?(S.texture=O,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let _=`raw/library/${n}/${t}`;br(v,_,O,E),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:v,texture:O,assetPath:_}})),le({objectId:v,path:"render.asset.path",value:_}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",_)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function fr(s,e,t,n){var i;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let a=e.startsWith("json.")?e.replace("json.",""):e,r=yr(a),o=Date.now(),l=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",l);let c=await yt.Assets.load(l);if(!c){console.error("[LIBRARY] Failed to load default texture:",l);return}Se[a]=c,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let d=window.CustomAssets;d!=null&&d[a]&&(d[a].texture=c,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let p=window.gameObjectManager;if(p){let u=p.get(a);if(u){let g=((i=u.getDisplayObject)==null?void 0:i.call(u))||u.pixiObject||u;g!=null&&g.texture&&(g.texture=c,console.log("[LIBRARY] \u2705 Reset display object:",a))}}br(a,t,c,r),window.dispatchEvent(new CustomEvent("scene-editor:asset-updated",{detail:{objectId:a,texture:c,assetPath:t}})),le({objectId:a,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}function yr(s){var e,t,n;try{let i=window.getEditableObjectConfig,a=typeof i=="function"?i(s):null;return(n=(t=(e=a==null?void 0:a.render)==null?void 0:e.asset)==null?void 0:t.path)!=null?n:null}catch{return null}}function br(s,e,t,n){if(e){try{let i=`${s}:${e}`;pe.set(i,t)}catch{}if(n&&n!==e)try{let i=pe.store;i!=null&&i.delete&&i.delete(`${s}:${n}`)}catch{}gr(e,t),n&&n!==e&&gr(n,null)}}function gr(s,e){if(!s)return;let t=yt.Assets.cache;if(!t)return;let n=s.replace(/^\.?\//,""),i=[n,`/${n}`];for(let a of i)typeof t.remove=="function"?t.remove(a):typeof t.delete=="function"&&t.delete(a),e&&typeof t.set=="function"&&t.set(a,e)}var ii=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`
1321
1321
  <div class="canva-wizard-overlay" data-canva-wizard>
1322
1322
  <div class="canva-wizard-modal">
1323
1323
  <div class="canva-wizard-header">
@@ -1423,8 +1423,8 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1423
1423
  ${this.replaceableObjects.map(n=>`<option value="${n.id}" ${e.targetObjectId===n.id?"selected":""}>${n.name}</option>`).join("")}
1424
1424
  </select>
1425
1425
  </div>
1426
- `}initialize(e,t,n,i){this.options=i,this.positionMap=br(n),this.replaceableObjects=wr(),this.assets=t.map(a=>{let r=vr(a.filename,this.positionMap);return{filename:a.filename,dataUrl:a.dataUrl,category:this.inferCategory(a.filename),position:r==null?void 0:r.position,scale:r==null?void 0:r.scale,rotation:r==null?void 0:r.rotation,action:void 0,targetObjectId:void 0}}),e.innerHTML=this.render(),this.root=e.querySelector("[data-canva-wizard]"),this.attachEventListeners()}attachEventListeners(){var e,t,n;this.root&&((e=this.root.querySelector("[data-canva-wizard-close]"))==null||e.addEventListener("click",()=>{this.close()}),(t=this.root.querySelector("[data-canva-wizard-cancel]"))==null||t.addEventListener("click",()=>{this.close()}),(n=this.root.querySelector("[data-canva-wizard-apply-all]"))==null||n.addEventListener("click",()=>{this.applyAll()}),this.root.querySelectorAll("[data-asset-action]").forEach(i=>{i.addEventListener("click",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-action")||"0"),l=r.getAttribute("data-action");this.handleAction(o,l)})}),this.root.querySelectorAll("[data-asset-category]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-category")||"0"),l=r.value;this.assets[o]&&(this.assets[o].category=l)})}),this.root.querySelectorAll("[data-asset-target]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-target")||"0"),l=r.value;this.assets[o]&&(this.assets[o].targetObjectId=l)})}),this.root.querySelectorAll("[data-asset-screen]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-screen")||"0"),l=r.value;this.assets[o]&&(this.assets[o].screen=l)})}),this.root.querySelectorAll("[data-asset-type]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-type")||"0"),l=r.value;this.assets[o]&&(this.assets[o].objectType=l)})}),this.root.addEventListener("click",i=>{i.target===this.root&&this.close()}))}handleAction(e,t){this.assets[e]&&(this.assets[e].action=t,t==="add"&&(this.assets[e].screen||(this.assets[e].screen="gameplay"),this.assets[e].objectType||(this.assets[e].objectType="sprite")),t==="replace"?this.updateAssetCard(e):(this.assets[e].targetObjectId=void 0,this.updateAssetCard(e)))}updateAssetCard(e){var n,i,a,r;if(!this.root)return;let t=this.root.querySelector(`[data-asset-index="${e}"]`);if(t&&this.assets[e]){let o=this.assets[e],l=this.renderAssetCard(o,e);t.outerHTML=l;let c=this.root.querySelector(`[data-asset-index="${e}"]`);c&&(c.querySelectorAll("[data-asset-action]").forEach(d=>{d.addEventListener("click",p=>{let u=p.target,g=parseInt(u.getAttribute("data-asset-action")||"0"),h=u.getAttribute("data-action");this.handleAction(g,h)})}),(n=c.querySelector("[data-asset-category]"))==null||n.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].category=u)}),(i=c.querySelector("[data-asset-target]"))==null||i.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].targetObjectId=u)}),(a=c.querySelector("[data-asset-screen]"))==null||a.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].screen=u)}),(r=c.querySelector("[data-asset-type]"))==null||r.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].objectType=u)}))}}async applyAll(){if(!this.options)return;for(let n of this.assets)n.action||(n.action="skip");this.processedCount=0,this.updateProgress();let e=[],t=[];for(let n=0;n<this.assets.length;n++){let i=this.assets[n];try{let a=await this.saveAssetToLibrary(i);i.libraryPath=a,i.action==="add"?e.push(i):i.action==="replace"&&i.targetObjectId&&t.push({asset:i,targetId:i.targetObjectId}),this.processedCount++,this.updateProgress()}catch(a){console.error(`[CanvaZip] Failed to save ${i.filename} to library:`,a)}}if(e.length>0)try{await this.batchAddToScene(e)}catch(n){console.error("[CanvaZip] Batch add to scene failed:",n)}if(t.length>0)for(let{asset:n,targetId:i}of t)try{await this.replaceObject(n,i)}catch(a){console.error(`[CanvaZip] Replace failed for ${i}:`,a)}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),this.options.onComplete&&this.options.onComplete(this.assets),this.close()}async batchAddToScene(e){var a;let t=e.map(r=>{let o=r.filename.replace(/\.(png|jpg|jpeg)$/i,"").replace(/[^a-zA-Z0-9._-]/g,"_").toLowerCase(),l=`json.${o}`,c={identity:{id:l,category:r.category||"environment"},transform:{position:r.position||{x:0,y:0},offset:{x:0,y:0},scale:.3,rotation:r.rotation||0,anchor:{x:.5,y:.5},position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0,asset:{type:"image",path:r.libraryPath}},instance_id:o,object_config:l};return{screenId:r.screen,instanceId:o,objectConfigId:l,layer:r.objectType==="ui-image"?"ui":"world",config:c}}),n=await fetch("/api/objects/batch-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:t})}),i=await n.json().catch(()=>({}));if(!n.ok||(i==null?void 0:i.success)===!1){let r=((a=i==null?void 0:i.errors)==null?void 0:a.join(`
1427
- `))||(i==null?void 0:i.error)||"Batch create failed.";throw new Error(r)}try{let{trackObjectCreation:r}=await Promise.resolve().then(()=>(Z(),Ue));for(let o of t)r(o.instanceId,o.screenId,o.config)}catch(r){console.warn("[CanvaZip] Failed to track batch creation in history:",r)}console.log(`[CanvaZip] \u2705 Batch added ${e.length} objects to scene`)}async saveAssetToLibrary(e){try{let n=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:e.category,filename:e.filename,data:e.dataUrl,overwrite:!0})})).json();if(n.success&&n.path)return console.log(`[CanvaZip] \u2705 Saved ${e.filename} to library: ${n.path}`),n.path;throw new Error(n.error||"Failed to save to library")}catch(t){throw console.error(`[CanvaZip] Failed to save ${e.filename} to library:`,t),t}}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN,t=await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error((n==null?void 0:n.error)||"Failed to sync screens")}}catch(e){console.warn("[CanvaZip] Screen sync failed:",e)}}async replaceObject(e,t){let n=window.__debugContext;if(!n){console.warn("[CanvaZip] No debug context available for replace");return}try{await ui(n,t,e.filename,e.category),console.log(`[CanvaZip] \u2705 Replaced ${t} with ${e.filename}`)}catch(i){throw console.error(`[CanvaZip] Failed to replace ${t}:`,i),i}}updateProgress(){if(!this.root)return;let e=this.root.querySelector(".canva-wizard-progress-fill"),t=this.root.querySelector(".canva-wizard-progress-text");if(e){let n=this.processedCount/this.assets.length*100;e.style.width=`${n}%`}t&&(t.textContent=`${this.processedCount} of ${this.assets.length} assets processed`)}inferCategory(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":"environment"}close(){var e;(e=this.options)!=null&&e.onCancel&&this.options.onCancel(),this.root&&this.root.remove()}};var hi=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.wizardProcessedAssets=new Set;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
1426
+ `}initialize(e,t,n,i){this.options=i,this.positionMap=dr(n),this.replaceableObjects=ur(),this.assets=t.map(a=>{let r=pr(a.filename,this.positionMap);return{filename:a.filename,dataUrl:a.dataUrl,category:this.inferCategory(a.filename),position:r==null?void 0:r.position,scale:r==null?void 0:r.scale,rotation:r==null?void 0:r.rotation,action:void 0,targetObjectId:void 0}}),e.innerHTML=this.render(),this.root=e.querySelector("[data-canva-wizard]"),this.attachEventListeners()}attachEventListeners(){var e,t,n;this.root&&((e=this.root.querySelector("[data-canva-wizard-close]"))==null||e.addEventListener("click",()=>{this.close()}),(t=this.root.querySelector("[data-canva-wizard-cancel]"))==null||t.addEventListener("click",()=>{this.close()}),(n=this.root.querySelector("[data-canva-wizard-apply-all]"))==null||n.addEventListener("click",()=>{this.applyAll()}),this.root.querySelectorAll("[data-asset-action]").forEach(i=>{i.addEventListener("click",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-action")||"0"),l=r.getAttribute("data-action");this.handleAction(o,l)})}),this.root.querySelectorAll("[data-asset-category]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-category")||"0"),l=r.value;this.assets[o]&&(this.assets[o].category=l)})}),this.root.querySelectorAll("[data-asset-target]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-target")||"0"),l=r.value;this.assets[o]&&(this.assets[o].targetObjectId=l)})}),this.root.querySelectorAll("[data-asset-screen]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-screen")||"0"),l=r.value;this.assets[o]&&(this.assets[o].screen=l)})}),this.root.querySelectorAll("[data-asset-type]").forEach(i=>{i.addEventListener("change",a=>{let r=a.target,o=parseInt(r.getAttribute("data-asset-type")||"0"),l=r.value;this.assets[o]&&(this.assets[o].objectType=l)})}),this.root.addEventListener("click",i=>{i.target===this.root&&this.close()}))}handleAction(e,t){this.assets[e]&&(this.assets[e].action=t,t==="add"&&(this.assets[e].screen||(this.assets[e].screen="gameplay"),this.assets[e].objectType||(this.assets[e].objectType="sprite")),t==="replace"?this.updateAssetCard(e):(this.assets[e].targetObjectId=void 0,this.updateAssetCard(e)))}updateAssetCard(e){var n,i,a,r;if(!this.root)return;let t=this.root.querySelector(`[data-asset-index="${e}"]`);if(t&&this.assets[e]){let o=this.assets[e],l=this.renderAssetCard(o,e);t.outerHTML=l;let c=this.root.querySelector(`[data-asset-index="${e}"]`);c&&(c.querySelectorAll("[data-asset-action]").forEach(d=>{d.addEventListener("click",p=>{let u=p.target,g=parseInt(u.getAttribute("data-asset-action")||"0"),h=u.getAttribute("data-action");this.handleAction(g,h)})}),(n=c.querySelector("[data-asset-category]"))==null||n.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].category=u)}),(i=c.querySelector("[data-asset-target]"))==null||i.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].targetObjectId=u)}),(a=c.querySelector("[data-asset-screen]"))==null||a.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].screen=u)}),(r=c.querySelector("[data-asset-type]"))==null||r.addEventListener("change",d=>{let u=d.target.value;this.assets[e]&&(this.assets[e].objectType=u)}))}}async applyAll(){if(!this.options)return;for(let n of this.assets)n.action||(n.action="skip");this.processedCount=0,this.updateProgress();let e=[],t=[];for(let n=0;n<this.assets.length;n++){let i=this.assets[n];try{let a=await this.saveAssetToLibrary(i);i.libraryPath=a,i.action==="add"?e.push(i):i.action==="replace"&&i.targetObjectId&&t.push({asset:i,targetId:i.targetObjectId}),this.processedCount++,this.updateProgress()}catch(a){console.error(`[CanvaZip] Failed to save ${i.filename} to library:`,a)}}if(e.length>0)try{await this.batchAddToScene(e)}catch(n){console.error("[CanvaZip] Batch add to scene failed:",n)}if(t.length>0)for(let{asset:n,targetId:i}of t)try{await this.replaceObject(n,i)}catch(a){console.error(`[CanvaZip] Replace failed for ${i}:`,a)}await this.syncScreens(),window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch"}})),this.options.onComplete&&this.options.onComplete(this.assets),this.close()}async batchAddToScene(e){var a;let t=e.map(r=>{let o=r.filename.replace(/\.(png|jpg|jpeg)$/i,"").replace(/[^a-zA-Z0-9._-]/g,"_").toLowerCase(),l=`json.${o}`,c={identity:{id:l,category:r.category||"environment"},transform:{position:r.position||{x:0,y:0},offset:{x:0,y:0},scale:.3,rotation:r.rotation||0,anchor:{x:.5,y:.5},position_ratio:null,position_mode:"static"},render:{alpha:1,visible:!0,tint:null,z_index:0,asset:{type:"image",path:r.libraryPath}},instance_id:o,object_config:l};return{screenId:r.screen,instanceId:o,objectConfigId:l,layer:r.objectType==="ui-image"?"ui":"world",config:c}}),n=await fetch("/api/objects/batch-create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:t})}),i=await n.json().catch(()=>({}));if(!n.ok||(i==null?void 0:i.success)===!1){let r=((a=i==null?void 0:i.errors)==null?void 0:a.join(`
1427
+ `))||(i==null?void 0:i.error)||"Batch create failed.";throw new Error(r)}try{let{trackObjectCreation:r}=await Promise.resolve().then(()=>(te(),Be));for(let o of t)r(o.instanceId,o.screenId,o.config)}catch(r){console.warn("[CanvaZip] Failed to track batch creation in history:",r)}console.log(`[CanvaZip] \u2705 Batch added ${e.length} objects to scene`)}async saveAssetToLibrary(e){try{let n=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:e.category,filename:e.filename,data:e.dataUrl,overwrite:!0})})).json();if(n.success&&n.path)return console.log(`[CanvaZip] \u2705 Saved ${e.filename} to library: ${n.path}`),n.path;throw new Error(n.error||"Failed to save to library")}catch(t){throw console.error(`[CanvaZip] Failed to save ${e.filename} to library:`,t),t}}async syncScreens(){try{let e=window.__HANDLER_ACTIVE_SCREEN,t=await fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e})});if(!t.ok){let n=await t.json().catch(()=>({}));throw new Error((n==null?void 0:n.error)||"Failed to sync screens")}}catch(e){console.warn("[CanvaZip] Screen sync failed:",e)}}async replaceObject(e,t){let n=window.__debugContext;if(!n){console.warn("[CanvaZip] No debug context available for replace");return}try{await ni(n,t,e.filename,e.category),console.log(`[CanvaZip] \u2705 Replaced ${t} with ${e.filename}`)}catch(i){throw console.error(`[CanvaZip] Failed to replace ${t}:`,i),i}}updateProgress(){if(!this.root)return;let e=this.root.querySelector(".canva-wizard-progress-fill"),t=this.root.querySelector(".canva-wizard-progress-text");if(e){let n=this.processedCount/this.assets.length*100;e.style.width=`${n}%`}t&&(t.textContent=`${this.processedCount} of ${this.assets.length} assets processed`)}inferCategory(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":"environment"}close(){var e;(e=this.options)!=null&&e.onCancel&&this.options.onCancel(),this.root&&this.root.remove()}};var ai=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.wizardProcessedAssets=new Set;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
1428
1428
  <div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
1429
1429
  <div class="scene-panel-header" data-panel-handle>
1430
1430
  <div class="panel-title">
@@ -1539,15 +1539,15 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1539
1539
  </div>
1540
1540
  <div class="panel-resize-handle" data-panel-resize></div>
1541
1541
  </div>
1542
- `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,i,a,r,o,l,c,d,p,u,g;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let m=h.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let m=h.target.value;this.switchUploadMethod(m)}),(i=this.root.querySelector("[data-vision-upload-manifest]"))==null||i.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||m.click()}),(r=this.root.querySelector("[data-vision-zip-input]"))==null||r.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(d=this.root.querySelector("[data-vision-upload-flat]"))==null||d.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||m.click()}),(p=this.root.querySelector("[data-vision-flat-input]"))==null||p.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(u=this.root.querySelector("[data-vision-generate-all]"))==null||u.addEventListener("click",()=>{this.generateAllMissing()}),(g=this.root.querySelector("[data-vision-apply-all]"))==null||g.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let m=h.target;if(!m)return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;y&&(m.closest("[data-mapping-apply-one]")&&this.applyOne(y),m.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),m.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),m.closest("[data-mapping-generate-one]")&&this.generateOne(y),m.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let m=h.target;if(!m||!this.mappingResult)return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;if(!y)return;let b=this.mappingResult.mappings.find(v=>v.game_object===y);b&&(m.matches("[data-mapping-action]")&&(b.action=String(m.value||"KEEP"),b.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(b.brand_asset=String(m.value||""),b.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",h=>{let m=h.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;if(!y)return;let b=this.mappingResult.mappings.find(v=>v.game_object===y);b&&(b.generation_prompt=String(m.value||""),b.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(i=>i.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(i=>i.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${e}"]`))==null||n.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var i;let n=(i=e.target.files)==null?void 0:i[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}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 n=await t.loadAsync(e),i=[],a=[];n.forEach((c,d)=>{let p=c.toLowerCase();p.endsWith(".json")?i.push({name:c,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:c,file:d})});for(let c of i)try{let d=await((l=n.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 r=[];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}r.push({filename:u,dataUrl:g})}catch(d){console.warn(`Failed to extract ${c.name}:`,d)}let o=null;for(let c of i){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:",i.map(c=>c.name)),r.length>0){await this.showCanvaZipWizard(r,o),this.setStatus("zip",`\u2705 Wizard completed - ${r.length} assets processed`);return}else{this.setStatus("zip","\u26A0\uFE0F No PNG files found in ZIP");return}}async fileToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=n,i.readAsDataURL(e)})}async showCanvaZipWizard(e,t){return new Promise(n=>{let i=e.filter(o=>!this.wizardProcessedAssets.has(o.filename));if(i.length===0){console.log("[BrandVision] All assets already processed by wizard"),n();return}let a=document.createElement("div");document.body.appendChild(a),new gi().initialize(a,i,t,{onComplete:o=>{console.log("[BrandVision] Wizard completed, processed assets:",o),o.forEach(l=>{this.wizardProcessedAssets.add(l.filename)}),a.remove(),n()},onCancel:()=>{console.log("[BrandVision] Wizard cancelled"),a.remove(),n()}})})}async blobToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>{let a=i.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),t(a)},i.onerror=a=>{console.error("FileReader error:",a),n(a)},i.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 n=t();if(!(n!=null&&n.libraryAssets))return;let i={};for(let a of e){let r=a.category||"misc";i[r]||(i[r]=[]),n.libraryAssets[r]||(n.libraryAssets[r]=[]),n.libraryAssets[r].some(l=>l.filename===a.filename)||(n.libraryAssets[r].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 ${r}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var r;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let i="";for(let o of Array.from(n))try{let l=await o.text(),c=JSON.parse(l);this.uploadedJsons.set(o.name,c),c.layers?i+=`\u2705 Layers: ${o.name}
1542
+ `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,i,a,r,o,l,c,d,p,u,g;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let m=h.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let m=h.target.value;this.switchUploadMethod(m)}),(i=this.root.querySelector("[data-vision-upload-manifest]"))==null||i.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||m.click()}),(r=this.root.querySelector("[data-vision-zip-input]"))==null||r.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(d=this.root.querySelector("[data-vision-upload-flat]"))==null||d.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||m.click()}),(p=this.root.querySelector("[data-vision-flat-input]"))==null||p.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(u=this.root.querySelector("[data-vision-generate-all]"))==null||u.addEventListener("click",()=>{this.generateAllMissing()}),(g=this.root.querySelector("[data-vision-apply-all]"))==null||g.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let m=h.target;if(!m)return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;y&&(m.closest("[data-mapping-apply-one]")&&this.applyOne(y),m.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),m.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),m.closest("[data-mapping-generate-one]")&&this.generateOne(y),m.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let m=h.target;if(!m||!this.mappingResult)return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;if(!y)return;let b=this.mappingResult.mappings.find(v=>v.game_object===y);b&&(m.matches("[data-mapping-action]")&&(b.action=String(m.value||"KEEP"),b.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(b.brand_asset=String(m.value||""),b.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",h=>{let m=h.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let f=m.closest("[data-mapping-item]"),y=f==null?void 0:f.dataset.mappingItem;if(!y)return;let b=this.mappingResult.mappings.find(v=>v.game_object===y);b&&(b.generation_prompt=String(m.value||""),b.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(i=>i.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(i=>i.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${e}"]`))==null||n.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var i;let n=(i=e.target.files)==null?void 0:i[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}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 n=await t.loadAsync(e),i=[],a=[];n.forEach((c,d)=>{let p=c.toLowerCase();p.endsWith(".json")?i.push({name:c,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:c,file:d})});for(let c of i)try{let d=await((l=n.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 r=[];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}r.push({filename:u,dataUrl:g})}catch(d){console.warn(`Failed to extract ${c.name}:`,d)}let o=null;for(let c of i){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:",i.map(c=>c.name)),r.length>0){await this.showCanvaZipWizard(r,o),this.setStatus("zip",`\u2705 Wizard completed - ${r.length} assets processed`);return}else{this.setStatus("zip","\u26A0\uFE0F No PNG files found in ZIP");return}}async fileToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=n,i.readAsDataURL(e)})}async showCanvaZipWizard(e,t){return new Promise(n=>{let i=e.filter(o=>!this.wizardProcessedAssets.has(o.filename));if(i.length===0){console.log("[BrandVision] All assets already processed by wizard"),n();return}let a=document.createElement("div");document.body.appendChild(a),new ii().initialize(a,i,t,{onComplete:o=>{console.log("[BrandVision] Wizard completed, processed assets:",o),o.forEach(l=>{this.wizardProcessedAssets.add(l.filename)}),a.remove(),n()},onCancel:()=>{console.log("[BrandVision] Wizard cancelled"),a.remove(),n()}})})}async blobToDataUrl(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>{let a=i.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),t(a)},i.onerror=a=>{console.error("FileReader error:",a),n(a)},i.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 n=t();if(!(n!=null&&n.libraryAssets))return;let i={};for(let a of e){let r=a.category||"misc";i[r]||(i[r]=[]),n.libraryAssets[r]||(n.libraryAssets[r]=[]),n.libraryAssets[r].some(l=>l.filename===a.filename)||(n.libraryAssets[r].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 ${r}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var r;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let i="";for(let o of Array.from(n))try{let l=await o.text(),c=JSON.parse(l);this.uploadedJsons.set(o.name,c),c.layers?i+=`\u2705 Layers: ${o.name}
1543
1543
  `:c.brand_dna||c.colors?i+=`\u2705 Brand: ${o.name}
1544
1544
  `:i+=`\u2705 Loaded: ${o.name}
1545
1545
  `}catch{i+=`\u274C Error in ${o.name}
1546
- `}try{this.normalizedManifest=lr(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let o=Array.isArray((r=this.normalizedManifest)==null?void 0:r.assets)?this.normalizedManifest.assets.length:0;i+=`
1546
+ `}try{this.normalizedManifest=er(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let o=Array.isArray((r=this.normalizedManifest)==null?void 0:r.assets)?this.normalizedManifest.assets.length:0;i+=`
1547
1547
  \u{1F4E6} Normalized manifest: ${o} assets`,i+=`
1548
1548
  \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:o,brandName:this.normalizedManifest.brand_name})}catch(o){console.error("[BrandVision] Failed to normalize manifest:",o),this.normalizedManifest=null,i+=`
1549
1549
  \u274C Failed to normalize manifest`}t.value="";let a=i.trim();this.uploadedJsons.size>0?this.setStatus("manifest",`${a}
1550
- \u2705 JSONs ready - now upload PNGs to open wizard`):this.setStatus("manifest",a)}async handleAssetsUpload(e){console.log("[BrandVision] handleAssetsUpload called",e);let t=e.target,n=t.files;if(console.log("[BrandVision] Files object:",n),!n||n.length===0){console.log("[BrandVision] No files selected");return}console.log(`[BrandVision] handleAssetsUpload: ${n.length} files selected`);for(let o=0;o<n.length;o++)console.log(`[BrandVision] File ${o}: ${n[o].name}, type: ${n[o].type}, size: ${n[o].size}`);let i=[];for(let o of Array.from(n)){if(console.log(`[BrandVision] Processing file: ${o.name}, type: ${o.type}`),!o.type.startsWith("image/")){console.log(`[BrandVision] Skipping non-image file: ${o.name}`),this.assetFiles.set(o.name,o);continue}try{let l=await this.fileToDataUrl(o);i.push({filename:o.name,dataUrl:l}),console.log(`[BrandVision] \u2705 Converted ${o.name} to data URL (length: ${l.length})`)}catch(l){console.error(`[BrandVision] Failed to process ${o.name}:`,l),this.assetFiles.set(o.name,o)}}console.log(`[BrandVision] Extracted ${i.length} image assets`);let a=this.uploadedJsons.size>0,r=i.length>0;if(console.log(`[BrandVision] Individual upload check: JSONs=${a}, Images=${r}`),a&&r){console.log("[BrandVision] Both JSONs and images present - showing wizard"),this.setStatus("assets",`Processing ${i.length} images...`);let o=null;console.log("[BrandVision] Checking uploaded JSONs for position data:",Array.from(this.uploadedJsons.keys()));for(let[l,c]of this.uploadedJsons.entries()){let d=l.toLowerCase();if(console.log(`[BrandVision] Checking JSON: ${l} (lowercase: ${d})`),d.includes("positionnormalizedpack")||d.includes("positionnormalized")){o=c,console.log("[BrandVision] \u2705 Found position data in:",l,{hasContent:!!o,isString:typeof o=="string",isObject:typeof o=="object",hasLayers:o!=null&&o.layers?o.layers.length:0,contentPreview:typeof o=="object"?JSON.stringify(o).substring(0,200):String(o).substring(0,200)});break}}o||console.warn("[BrandVision] \u26A0\uFE0F No position data found. Uploaded JSON files:",Array.from(this.uploadedJsons.keys())),console.log("[BrandVision] Opening wizard with assets:",i.map(l=>l.filename)),await this.showCanvaZipWizard(i,o),console.log("[BrandVision] Wizard completed successfully"),this.setStatus("assets",`\u2705 Wizard completed - ${i.length} assets processed`)}else console.log("[BrandVision] Waiting for both JSONs and images. Current state:",{jsons:this.uploadedJsons.size,images:i.length}),a?this.setStatus("assets",`Uploaded ${i.length} images. JSONs ready - wizard should open now.`):this.setStatus("assets","\u26A0\uFE0F Upload JSONs first, then PNGs to open wizard");t.value=""}async handleFlatDesignUpload(e){var a,r;let n=(a=e.target.files)==null?void 0:a[0];if(!n)return;let i=await Ve(n);if(i){this.flatDesignDataUrl=i.dataUrl,this.setStatus("flat",`\u{1F3A8} ${n.name}`);let o=(r=this.root)==null?void 0:r.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${i.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,i,a,r,o,l,c;if(this.isAnalyzing)return;let e=(a=(i=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:i.value)==null?void 0:a.trim();if(!e){this.setStatus("upload","Missing API key");return}let t=this.manifest;if(!t){this.setStatus("upload","Upload manifest first");return}Array.isArray(t.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:t.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await yr(t,this.assetFiles);let d={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},p=await mr(d);this.mappingResult=p.mappingResult,this.analysisRawResponse=p.rawResponse,this.analysisParsedOk=p.parsed,this.analysisParseError=(r=p.parseError)!=null?r:null,this.renderMappings(),p.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:l.length)!=null?c:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${p.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(d){console.error("[BrandVision] Analysis failed:",d),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,i;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(i=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:i.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await xa(a,this.mappingResult,{onProgress:(r,o,l)=>{this.setStatus("apply",`Generating ${r}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let e=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,n=this.getEngineAssets(),i=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),r=i?`
1550
+ \u2705 JSONs ready - now upload PNGs to open wizard`):this.setStatus("manifest",a)}async handleAssetsUpload(e){console.log("[BrandVision] handleAssetsUpload called",e);let t=e.target,n=t.files;if(console.log("[BrandVision] Files object:",n),!n||n.length===0){console.log("[BrandVision] No files selected");return}console.log(`[BrandVision] handleAssetsUpload: ${n.length} files selected`);for(let o=0;o<n.length;o++)console.log(`[BrandVision] File ${o}: ${n[o].name}, type: ${n[o].type}, size: ${n[o].size}`);let i=[];for(let o of Array.from(n)){if(console.log(`[BrandVision] Processing file: ${o.name}, type: ${o.type}`),!o.type.startsWith("image/")){console.log(`[BrandVision] Skipping non-image file: ${o.name}`),this.assetFiles.set(o.name,o);continue}try{let l=await this.fileToDataUrl(o);i.push({filename:o.name,dataUrl:l}),console.log(`[BrandVision] \u2705 Converted ${o.name} to data URL (length: ${l.length})`)}catch(l){console.error(`[BrandVision] Failed to process ${o.name}:`,l),this.assetFiles.set(o.name,o)}}console.log(`[BrandVision] Extracted ${i.length} image assets`);let a=this.uploadedJsons.size>0,r=i.length>0;if(console.log(`[BrandVision] Individual upload check: JSONs=${a}, Images=${r}`),a&&r){console.log("[BrandVision] Both JSONs and images present - showing wizard"),this.setStatus("assets",`Processing ${i.length} images...`);let o=null;console.log("[BrandVision] Checking uploaded JSONs for position data:",Array.from(this.uploadedJsons.keys()));for(let[l,c]of this.uploadedJsons.entries()){let d=l.toLowerCase();if(console.log(`[BrandVision] Checking JSON: ${l} (lowercase: ${d})`),d.includes("positionnormalizedpack")||d.includes("positionnormalized")){o=c,console.log("[BrandVision] \u2705 Found position data in:",l,{hasContent:!!o,isString:typeof o=="string",isObject:typeof o=="object",hasLayers:o!=null&&o.layers?o.layers.length:0,contentPreview:typeof o=="object"?JSON.stringify(o).substring(0,200):String(o).substring(0,200)});break}}o||console.warn("[BrandVision] \u26A0\uFE0F No position data found. Uploaded JSON files:",Array.from(this.uploadedJsons.keys())),console.log("[BrandVision] Opening wizard with assets:",i.map(l=>l.filename)),await this.showCanvaZipWizard(i,o),console.log("[BrandVision] Wizard completed successfully"),this.setStatus("assets",`\u2705 Wizard completed - ${i.length} assets processed`)}else console.log("[BrandVision] Waiting for both JSONs and images. Current state:",{jsons:this.uploadedJsons.size,images:i.length}),a?this.setStatus("assets",`Uploaded ${i.length} images. JSONs ready - wizard should open now.`):this.setStatus("assets","\u26A0\uFE0F Upload JSONs first, then PNGs to open wizard");t.value=""}async handleFlatDesignUpload(e){var a,r;let n=(a=e.target.files)==null?void 0:a[0];if(!n)return;let i=await qe(n);if(i){this.flatDesignDataUrl=i.dataUrl,this.setStatus("flat",`\u{1F3A8} ${n.name}`);let o=(r=this.root)==null?void 0:r.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${i.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,i,a,r,o,l,c;if(this.isAnalyzing)return;let e=(a=(i=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:i.value)==null?void 0:a.trim();if(!e){this.setStatus("upload","Missing API key");return}let t=this.manifest;if(!t){this.setStatus("upload","Upload manifest first");return}Array.isArray(t.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:t.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await cr(t,this.assetFiles);let d={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},p=await or(d);this.mappingResult=p.mappingResult,this.analysisRawResponse=p.rawResponse,this.analysisParsedOk=p.parsed,this.analysisParseError=(r=p.parseError)!=null?r:null,this.renderMappings(),p.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:l.length)!=null?c:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${p.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(d){console.error("[BrandVision] Analysis failed:",d),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,i;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(i=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:i.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ga(a,this.mappingResult,{onProgress:(r,o,l)=>{this.setStatus("apply",`Generating ${r}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let e=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,n=this.getEngineAssets(),i=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),r=i?`
1551
1551
  <div class="vision-raw-block">
1552
1552
  <div class="inspector-text-sm" style="white-space: pre-wrap;">
1553
1553
  \u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
@@ -1609,8 +1609,8 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1609
1609
  </div>
1610
1610
  </div>
1611
1611
  `}).join("")}
1612
- `}async applyAll(){let e=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",e>0?`Staged ${e} asset overrides`:"No assets to stage")}getEngineAssets(){let e=window.getEditableEngineConfig;if(typeof e!="function")return{};let t=e();return t!=null&&t.assets&&typeof t.assets=="object"?t.assets:{}}getPreviewValueForMapping(e){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let t=this.mappingResult.mappings.find(n=>n.game_object===e);if(!t)return{value:null,source:"none"};if(t.action==="GENERATE"&&t.output_dataUrl)return{value:t.output_dataUrl,source:"generated"};if(t.action==="APPLY"&&t.brand_asset){let n=this.manifest.assets.find(i=>i.id===t.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let i=n.game_object,a=this.getPreviewValueForMapping(i);if(!a.value)continue;let r=e.saveToLibrary?await this.saveToLibraryAndReturnPath(i,a.value):a.value;r&&(await this.stageEngineAssetOverride(i,r),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var i;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to apply for ${e}`);return}await this.stageEngineAssetOverride(e,t.value);let n=(i=this.mappingResult)==null?void 0:i.mappings.find(a=>a.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var a;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to save for ${e}`);return}let n=await this.saveToLibraryAndReturnPath(e,t.value);if(!n){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,n);let i=(a=this.mappingResult)==null?void 0:a.mappings.find(r=>r.game_object===e);i&&(i.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(r=>r.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),i=window.__openAiEditor;if(typeof i!="function"){this.setStatus("apply","AI editor not available");return}let a=t.action==="GENERATE"?t.generation_prompt:void 0;i(e,a,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var i,a,r;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let n=(r=(a=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:r.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await xa(o,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(Z(),Ue));n({path:`assets.${e}`,value:t},{silent:!0});let i=window.applyEditableEngineConfig;typeof i=="function"&&i({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),i=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let r=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:i,data:t,overwrite:!0})})).json();if(!(r!=null&&r.success)||!(r!=null&&r.path))return console.error("[BrandVision] Save to library failed:",(r==null?void 0:r.error)||r),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,i);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(r.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)){let r=i.slots.find(o=>o.slotId===e||o.currentAsset===e);if(r!=null&&r.category)return String(r.category)}let a=i==null?void 0:i.categories;if(Array.isArray(a)&&a.length>0){let r=e.toLowerCase(),o=l=>a.find(c=>c.toLowerCase().includes(l));return r.includes("bg")||r.includes("background")?o("background")||a[0]:(r.includes("cta")||r.includes("button")||r.includes("ui")||r.includes("logo"))&&o("ui")||a[0]}}let n=e.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(e,t){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},i=(a=this.root)==null?void 0:a.querySelector(n[e]);i&&(i.textContent=t)}getGameObjects(){let e=window.getEditableObjectList;return typeof e=="function"?e():[]}async getGamePrompt(){try{let e=await fetch("./configs/engine/game.prompt.json");if(e.ok)return(await e.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");e&&e.addEventListener("pointerdown",t=>{let n=t.clientX,i=this.root.getBoundingClientRect().width,a=o=>{let l=Math.max(300,i+(o.clientX-n));this.root.style.width=`${l}px`},r=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",r)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",r)})}refresh(){}};function Tr(s,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:i=5}=e;return[`TASK: ${s}`,`CHANGE_STRENGTH: ${i}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
1613
- `)}var El=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],Cl=["cta_hint","cta_label_end"],kr=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],Al=["brand.primary","brand.heading","brand.body","brand.warning"],mi=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=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.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
1612
+ `}async applyAll(){let e=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",e>0?`Staged ${e} asset overrides`:"No assets to stage")}getEngineAssets(){let e=window.getEditableEngineConfig;if(typeof e!="function")return{};let t=e();return t!=null&&t.assets&&typeof t.assets=="object"?t.assets:{}}getPreviewValueForMapping(e){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let t=this.mappingResult.mappings.find(n=>n.game_object===e);if(!t)return{value:null,source:"none"};if(t.action==="GENERATE"&&t.output_dataUrl)return{value:t.output_dataUrl,source:"generated"};if(t.action==="APPLY"&&t.brand_asset){let n=this.manifest.assets.find(i=>i.id===t.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let i=n.game_object,a=this.getPreviewValueForMapping(i);if(!a.value)continue;let r=e.saveToLibrary?await this.saveToLibraryAndReturnPath(i,a.value):a.value;r&&(await this.stageEngineAssetOverride(i,r),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var i;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to apply for ${e}`);return}await this.stageEngineAssetOverride(e,t.value);let n=(i=this.mappingResult)==null?void 0:i.mappings.find(a=>a.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var a;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to save for ${e}`);return}let n=await this.saveToLibraryAndReturnPath(e,t.value);if(!n){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,n);let i=(a=this.mappingResult)==null?void 0:a.mappings.find(r=>r.game_object===e);i&&(i.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(r=>r.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),i=window.__openAiEditor;if(typeof i!="function"){this.setStatus("apply","AI editor not available");return}let a=t.action==="GENERATE"?t.generation_prompt:void 0;i(e,a,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var i,a,r;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let n=(r=(a=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:r.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ga(o,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(te(),Be));n({path:`assets.${e}`,value:t},{silent:!0});let i=window.applyEditableEngineConfig;typeof i=="function"&&i({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),i=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let r=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:i,data:t,overwrite:!0})})).json();if(!(r!=null&&r.success)||!(r!=null&&r.path))return console.error("[BrandVision] Save to library failed:",(r==null?void 0:r.error)||r),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,i);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(r.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)){let r=i.slots.find(o=>o.slotId===e||o.currentAsset===e);if(r!=null&&r.category)return String(r.category)}let a=i==null?void 0:i.categories;if(Array.isArray(a)&&a.length>0){let r=e.toLowerCase(),o=l=>a.find(c=>c.toLowerCase().includes(l));return r.includes("bg")||r.includes("background")?o("background")||a[0]:(r.includes("cta")||r.includes("button")||r.includes("ui")||r.includes("logo"))&&o("ui")||a[0]}}let n=e.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(e,t){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},i=(a=this.root)==null?void 0:a.querySelector(n[e]);i&&(i.textContent=t)}getGameObjects(){let e=window.getEditableObjectList;return typeof e=="function"?e():[]}async getGamePrompt(){try{let e=await fetch("./configs/engine/game.prompt.json");if(e.ok)return(await e.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");e&&e.addEventListener("pointerdown",t=>{let n=t.clientX,i=this.root.getBoundingClientRect().width,a=o=>{let l=Math.max(300,i+(o.clientX-n));this.root.style.width=`${l}px`},r=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",r)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",r)})}refresh(){}};function vr(s,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:i=5}=e;return[`TASK: ${s}`,`CHANGE_STRENGTH: ${i}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
1613
+ `)}var ml=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],fl=["cta_hint","cta_label_end"],wr=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],yl=["brand.primary","brand.heading","brand.body","brand.warning"],si=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=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.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
1614
1614
  <div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
1615
1615
  <div class="scene-panel-header" data-panel-handle>
1616
1616
  <div class="panel-title">
@@ -1678,7 +1678,7 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1678
1678
  <path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
1679
1679
  <path d="M5 14v4h14v-4h2v6H3v-6h2z" />
1680
1680
  </svg>
1681
- `;let p=document.createElement("input");p.type="file",p.accept="image/*,audio/*,application/json",p.className="customize-file",p.addEventListener("change",()=>{var h;let g=(h=p.files)==null?void 0:h[0];g&&this.handleAssetUpload(g,o,n)}),d.addEventListener("click",()=>p.click()),l.appendChild(c),l.appendChild(d),l.appendChild(p),a.appendChild(r),a.appendChild(o),a.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(a)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",El.forEach(t=>{var l,c,d;let n=(l=e==null?void 0:e[t])!=null?l:"#ffffff";if(t.includes("_text_color")||t.includes("_color")){let u={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];u&&(n=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let i=document.createElement("label");i.className="customize-color-field";let a=document.createElement("span");a.textContent=t.replace(/_/g," ");let r=document.createElement("input");r.type="color",r.value=n,r.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,r.addEventListener("input",()=>{o.value=r.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(r.value=o.value)}),i.appendChild(a),i.appendChild(r),i.appendChild(o),(d=this.colorsContainer)==null||d.appendChild(i)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Al.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(r=e==null?void 0:e[t])!=null?r:t,a.className="customize-input",a.dataset.fontKey=t,n.appendChild(i),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Cl.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(r=this.readUiValue(e,t))!=null?r:"",a.className="customize-input",a.dataset.textKey=t,n.appendChild(i),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),kr.forEach(({key:t,objectId:n})=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=this.getObjectTextValue(n))!=null?o:"",r.className="customize-input",r.dataset.objectTextKey=t,i.appendChild(a),i.appendChild(r),(l=this.textsContainer)==null||l.appendChild(i)}))}renderAudio(e){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let r=document.createElement("input");r.type=n.includes("volume")?"number":"text",r.min="0",r.max="1",r.step="0.1",r.value=String((o=e==null?void 0:e[n])!=null?o:""),r.className="customize-input",r.dataset.audioKey=n,n.includes("file")&&(r.placeholder="audio file path"),i.appendChild(a),i.appendChild(r),(l=this.audioContainer)==null||l.appendChild(i)})}readUiValue(e,t){if(t.includes(".")){let i=t.split("."),a=e;for(let r of i){if(a==null)return null;a=a[r]}return typeof a=="string"?a:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(a=(i=n==null?void 0:n.ui)==null?void 0:i.text)!=null?a:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let i=n(e);if(!i)return null;let a=t.split("."),r=i;for(let o of a){if(r==null)return null;r=r[o]}return typeof r=="string"?r:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(e){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${e}`),!this.root||!this.options)return;let t={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(t[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(t).length,"total"),console.log("[CustomizePanel] Asset values:",t);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let i={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(i[c]=l.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(a[c]=l.value)});let r={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let d=parseFloat(l.value);r[c]=isNaN(d)?0:d}else r[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let d=kr.find(p=>p.key===c);d&&this.applyObjectPropertyValue(d.objectId,d.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:a,fonts:i,audio:r}},{source:e})}setupAiPanel(){}setAiStatus(e){this.aiStatusEl&&(this.aiStatusEl.textContent=e)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let e=this.getSelectedAssetKey();return!this.root||!e?null:this.root.querySelector(`input[data-asset-key="${e}"]`)}async getImageDataFromAsset(e){let t=this.resolveAssetUrls(e);console.log("[CustomizePanel] Resolving asset urls for AI:",e,t);for(let n of t)try{let i=await di(n);if(i)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:i.base64,mimeType:i.mimeType},dataUrl:i.dataUrl,width:i.width,height:i.height}}catch(i){console.warn("[CustomizePanel] Failed to fetch image data from:",n,i)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var i,a,r;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(a=(i=o==null?void 0:o.value)==null?void 0:i.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(r=n==null?void 0:n.dataUrl)!=null?r:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let e=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!e){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=e}updateAiModalPreview(e,t){if(!e)return;let n=t!=null?t:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){e.classList.add("hidden");return}let i=e.querySelector(".asset-preview-ai-image");i&&(i.src=this.aiOutputDataUrl),e.classList.remove("hidden")}setAiLoading(e){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",e),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=e)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let e=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=e?"Gallery":"Hide Gallery",e||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let e=this.getAiGalleryEntries();if(!e.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",e.forEach(({key:t,value:n})=>{var l;let i=document.createElement("button");i.type="button",i.className="ai-gallery-item",t===this.aiTargetKey&&i.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=t;let r=this.resolveAssetUrls(n);r[0]&&(a.src=r[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,i.appendChild(a),i.appendChild(o),i.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(i)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var r,o;let n=t,i=n.dataset.assetKey,a=(o=(r=n.value)==null?void 0:r.trim())!=null?o:"";!i||!a||this.isAiGalleryImage(a)&&e.push({key:i,value:a})}),e}isAiGalleryImage(e){let t=e.trim();if(!t)return!1;if(/^(data:image|blob:)/.test(t))return!0;let n=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(i=>n.endsWith(i))}selectAiGalleryAsset(e){this.aiTargetKey!==e&&(this.aiTargetKey=e,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=e),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(e,t,n){var o,l,c,d,p,u,g,h,m,f;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let i=document.createElement("div");i.className="ai-modal",i.innerHTML=`
1681
+ `;let p=document.createElement("input");p.type="file",p.accept="image/*,audio/*,application/json",p.className="customize-file",p.addEventListener("change",()=>{var h;let g=(h=p.files)==null?void 0:h[0];g&&this.handleAssetUpload(g,o,n)}),d.addEventListener("click",()=>p.click()),l.appendChild(c),l.appendChild(d),l.appendChild(p),a.appendChild(r),a.appendChild(o),a.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(a)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",ml.forEach(t=>{var l,c,d;let n=(l=e==null?void 0:e[t])!=null?l:"#ffffff";if(t.includes("_text_color")||t.includes("_color")){let u={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];u&&(n=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let i=document.createElement("label");i.className="customize-color-field";let a=document.createElement("span");a.textContent=t.replace(/_/g," ");let r=document.createElement("input");r.type="color",r.value=n,r.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,r.addEventListener("input",()=>{o.value=r.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(r.value=o.value)}),i.appendChild(a),i.appendChild(r),i.appendChild(o),(d=this.colorsContainer)==null||d.appendChild(i)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",yl.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(r=e==null?void 0:e[t])!=null?r:t,a.className="customize-input",a.dataset.fontKey=t,n.appendChild(i),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",fl.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let i=document.createElement("span");i.className="customize-key",i.textContent=t;let a=document.createElement("input");a.type="text",a.value=(r=this.readUiValue(e,t))!=null?r:"",a.className="customize-input",a.dataset.textKey=t,n.appendChild(i),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),wr.forEach(({key:t,objectId:n})=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=this.getObjectTextValue(n))!=null?o:"",r.className="customize-input",r.dataset.objectTextKey=t,i.appendChild(a),i.appendChild(r),(l=this.textsContainer)==null||l.appendChild(i)}))}renderAudio(e){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let r=document.createElement("input");r.type=n.includes("volume")?"number":"text",r.min="0",r.max="1",r.step="0.1",r.value=String((o=e==null?void 0:e[n])!=null?o:""),r.className="customize-input",r.dataset.audioKey=n,n.includes("file")&&(r.placeholder="audio file path"),i.appendChild(a),i.appendChild(r),(l=this.audioContainer)==null||l.appendChild(i)})}readUiValue(e,t){if(t.includes(".")){let i=t.split("."),a=e;for(let r of i){if(a==null)return null;a=a[r]}return typeof a=="string"?a:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(a=(i=n==null?void 0:n.ui)==null?void 0:i.text)!=null?a:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let i=n(e);if(!i)return null;let a=t.split("."),r=i;for(let o of a){if(r==null)return null;r=r[o]}return typeof r=="string"?r:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(e){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${e}`),!this.root||!this.options)return;let t={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(t[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(t).length,"total"),console.log("[CustomizePanel] Asset values:",t);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let i={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(i[c]=l.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(a[c]=l.value)});let r={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let d=parseFloat(l.value);r[c]=isNaN(d)?0:d}else r[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let d=wr.find(p=>p.key===c);d&&this.applyObjectPropertyValue(d.objectId,d.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:a,fonts:i,audio:r}},{source:e})}setupAiPanel(){}setAiStatus(e){this.aiStatusEl&&(this.aiStatusEl.textContent=e)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let e=this.getSelectedAssetKey();return!this.root||!e?null:this.root.querySelector(`input[data-asset-key="${e}"]`)}async getImageDataFromAsset(e){let t=this.resolveAssetUrls(e);console.log("[CustomizePanel] Resolving asset urls for AI:",e,t);for(let n of t)try{let i=await ei(n);if(i)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:i.base64,mimeType:i.mimeType},dataUrl:i.dataUrl,width:i.width,height:i.height}}catch(i){console.warn("[CustomizePanel] Failed to fetch image data from:",n,i)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var i,a,r;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(a=(i=o==null?void 0:o.value)==null?void 0:i.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(r=n==null?void 0:n.dataUrl)!=null?r:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let e=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!e){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=e}updateAiModalPreview(e,t){if(!e)return;let n=t!=null?t:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){e.classList.add("hidden");return}let i=e.querySelector(".asset-preview-ai-image");i&&(i.src=this.aiOutputDataUrl),e.classList.remove("hidden")}setAiLoading(e){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",e),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=e)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let e=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=e?"Gallery":"Hide Gallery",e||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let e=this.getAiGalleryEntries();if(!e.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",e.forEach(({key:t,value:n})=>{var l;let i=document.createElement("button");i.type="button",i.className="ai-gallery-item",t===this.aiTargetKey&&i.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=t;let r=this.resolveAssetUrls(n);r[0]&&(a.src=r[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,i.appendChild(a),i.appendChild(o),i.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(i)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var r,o;let n=t,i=n.dataset.assetKey,a=(o=(r=n.value)==null?void 0:r.trim())!=null?o:"";!i||!a||this.isAiGalleryImage(a)&&e.push({key:i,value:a})}),e}isAiGalleryImage(e){let t=e.trim();if(!t)return!1;if(/^(data:image|blob:)/.test(t))return!0;let n=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(i=>n.endsWith(i))}selectAiGalleryAsset(e){this.aiTargetKey!==e&&(this.aiTargetKey=e,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=e),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(e,t,n){var o,l,c,d,p,u,g,h,m,f;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let i=document.createElement("div");i.className="ai-modal",i.innerHTML=`
1682
1682
  <div class="ai-modal-card">
1683
1683
  <div class="ai-modal-header">
1684
1684
  <div>
@@ -1749,7 +1749,7 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1749
1749
  </div>
1750
1750
  </div>
1751
1751
  </div>
1752
- `;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",y=>{y.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=i.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var y;return(y=this.aiReferenceInput)==null?void 0:y.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var b,v;let y=(v=(b=this.aiStrengthInput)==null?void 0:b.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=y)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var b,v;let y=(v=(b=this.aiBgToleranceInput)==null?void 0:b.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=y),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var b,v,S;let y=(S=(v=(b=this.aiReferenceInput)==null?void 0:b.files)==null?void 0:v[0])!=null?S:null;this.aiReferenceFile=y,this.aiReferenceName&&(this.aiReferenceName.textContent=y?`${y.name} (loaded)`:"Optional"),y&&this.setAiStatus(`Reference attached: ${y.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()}),(m=this.aiCropBtn)==null||m.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,p,u,g,h,m,f,y,b,v,S,L,M,O,w,P,_,T,I,C;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(p=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:p.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(y=(f=(m=this.aiPromptInput)==null?void 0:m.value)==null?void 0:f.trim())!=null?y:"",i=(v=(b=this.aiRemoveBgToggle)==null?void 0:b.checked)!=null?v:!1,a=i,r=i,o=Number((L=(S=this.aiStrengthInput)==null?void 0:S.value)!=null?L:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((M=l==null?void 0:l.value)==null?void 0:M.trim())||((O=this.aiBaseValue)==null?void 0:O.trim())||"";this.setAiLoading(!0),this.setAiStatus(c?"Generating...":"Generating from scratch...");try{let A=null,E=null,x=(w=this.getSelectedAssetKey())!=null?w:"unknown",j=(P=this.aiUseOutputToggle)!=null&&P.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((_=this.aiUseOutputToggle)!=null&&_.checked&&this.aiOutputDataUrl){let G=ba(this.aiOutputDataUrl,"ai-output.png");if(G){let Q=await Ve(G);Q&&(A={input:{base64:Q.base64,mimeType:Q.mimeType},dataUrl:Q.dataUrl,width:Q.width,height:Q.height})}}!A&&c&&(A=await this.getImageDataFromAsset(c));let k=[];A&&k.push(A.input);let R=!1;if(this.aiReferenceFile){let G=await Ve(this.aiReferenceFile);G?(E={input:{base64:G.base64,mimeType:G.mimeType},dataUrl:G.dataUrl,width:G.width,height:G.height},k.push(E.input),R=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=Tr(n,{includeReference:R,includeMagenta:a,changeLevel:o}),N=(I=(T=this.aiReferenceFile)==null?void 0:T.name)!=null?I:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:x,base:j,reference:N});let Y=A?va(A.width,A.height):E?va(E.width,E.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let B=await Lt(e,z,k,{aspectRatio:Y,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",B==null?void 0:B.length),this.aiRawOutputDataUrl=B,await this.refreshAiOutputFromRaw()}catch(A){console.error("[CustomizePanel] AI Generate Error:",A),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((C=this.aiStatusEl)==null?void 0:C.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,r,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await At(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&r)console.log("[CustomizePanel] Applying AI output directly to object:",a,r),this.applyObjectPropertyValue(a,r,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,r,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),d(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(y){console.warn("[CustomizePanel] Setup-library endpoint not available:",y)}let p=window.refreshAssetLibrary;typeof p=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await p());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),h=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),m=this.getSelectedAssetInput();if(m&&(m.value=c.path,this.handleAssetValueChange((o=m.dataset.assetKey)!=null?o:"",m)),g&&h){console.log("[CustomizePanel] Applying saved asset to object:",g,h);let y=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof y=="function"&&b){let v=this.getFilenameFromPath(c.path);await y(g,v,i)}else this.applyObjectPropertyValue(g,h,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{f(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var r;let t=(r=this.aiContext)==null?void 0:r.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=ba(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let r=await ya(a);r&&this.setAiOutput(r)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let d=await this.getImageDimensions(i);if(d){let p=await this.showManualCropModal(e,d,i);if(!p)return;a=p}}let r=await ya(a);if(!r){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",p.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(y){console.warn("[CustomizePanel] Setup-library not available:",y)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=p.path,this.handleAssetValueChange(n,t);let h=this.inferObjectIdFromAssetKey(n),m=this.inferPathFromAssetKey(n);if(h&&m){let y=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(m)||/\\.(png|jpg|jpeg)$/i.test(String(p.path||""));if(typeof y=="function"&&b){let v=this.getFilenameFromPath(p.path);await y(h,v,c)}else this.applyObjectPropertyValue(h,m,p.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&h&&setTimeout(()=>{f(h,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",p.error),alert(`Failed to save uploaded file: ${p.error}`)}catch(d){console.error("[CustomizePanel] \u274C Upload error:",d),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,r)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1752
+ `;let a=i.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),i.addEventListener("click",y=>{y.target===i&&this.closeAiModal()}),this.aiModal=i,this.aiKeyInput=i.querySelector("[data-ai-key]"),this.aiModelSelect=i.querySelector("[data-ai-model]"),this.aiPromptInput=i.querySelector("[data-ai-prompt]"),this.aiStrengthInput=i.querySelector("[data-ai-strength]"),this.aiStrengthValue=i.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=i.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=i.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=i.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=i.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=i.querySelector("[data-ai-ref-input]"),this.aiReferenceName=i.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=i.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=i.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=i.querySelector("[data-ai-generate]"),this.aiApplyBtn=i.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=i.querySelector("[data-ai-save-library]"),this.aiCropBtn=i.querySelector("[data-ai-crop]"),this.aiDownloadBtn=i.querySelector("[data-ai-download]"),this.aiPreviewImg=i.querySelector("[data-ai-preview]"),this.aiStatusEl=i.querySelector("[data-ai-status]"),this.aiLoadingEl=i.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=i.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=i.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=i.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var y;return(y=this.aiReferenceInput)==null?void 0:y.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var b,v;let y=(v=(b=this.aiStrengthInput)==null?void 0:b.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=y)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var b,v;let y=(v=(b=this.aiBgToleranceInput)==null?void 0:b.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=y),this.refreshAiOutputFromRaw()}),(p=this.aiReferenceInput)==null||p.addEventListener("change",()=>{var b,v,E;let y=(E=(v=(b=this.aiReferenceInput)==null?void 0:b.files)==null?void 0:v[0])!=null?E:null;this.aiReferenceFile=y,this.aiReferenceName&&(this.aiReferenceName.textContent=y?`${y.name} (loaded)`:"Optional"),y&&this.setAiStatus(`Reference attached: ${y.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()}),(m=this.aiCropBtn)==null||m.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(i),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,p,u,g,h,m,f,y,b,v,E,P,I,O,w,k,_,L,M,C;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(p=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:p.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(y=(f=(m=this.aiPromptInput)==null?void 0:m.value)==null?void 0:f.trim())!=null?y:"",i=(v=(b=this.aiRemoveBgToggle)==null?void 0:b.checked)!=null?v:!1,a=i,r=i,o=Number((P=(E=this.aiStrengthInput)==null?void 0:E.value)!=null?P:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((I=l==null?void 0:l.value)==null?void 0:I.trim())||((O=this.aiBaseValue)==null?void 0:O.trim())||"";this.setAiLoading(!0),this.setAiStatus(c?"Generating...":"Generating from scratch...");try{let A=null,S=null,x=(w=this.getSelectedAssetKey())!=null?w:"unknown",j=(k=this.aiUseOutputToggle)!=null&&k.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((_=this.aiUseOutputToggle)!=null&&_.checked&&this.aiOutputDataUrl){let U=da(this.aiOutputDataUrl,"ai-output.png");if(U){let ne=await qe(U);ne&&(A={input:{base64:ne.base64,mimeType:ne.mimeType},dataUrl:ne.dataUrl,width:ne.width,height:ne.height})}}!A&&c&&(A=await this.getImageDataFromAsset(c));let T=[];A&&T.push(A.input);let R=!1;if(this.aiReferenceFile){let U=await qe(this.aiReferenceFile);U?(S={input:{base64:U.base64,mimeType:U.mimeType},dataUrl:U.dataUrl,width:U.width,height:U.height},T.push(S.input),R=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let z=vr(n,{includeReference:R,includeMagenta:a,changeLevel:o}),N=(M=(L=this.aiReferenceFile)==null?void 0:L.name)!=null?M:"none";console.info("[AI] Final prompt:",z),console.info("[AI] Image sources:",{assetKey:x,base:j,reference:N});let Y=A?pa(A.width,A.height):S?pa(S.width,S.height):"1:1";console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let F=await ft(e,z,T,{aspectRatio:Y,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",F==null?void 0:F.length),this.aiRawOutputDataUrl=F,await this.refreshAiOutputFromRaw()}catch(A){console.error("[CustomizePanel] AI Generate Error:",A),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((C=this.aiStatusEl)==null?void 0:C.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var i,a,r,o;if(!this.aiRawOutputDataUrl)return;let e=(a=(i=this.aiRemoveBgToggle)==null?void 0:i.checked)!=null?a:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await mt(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,i;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(i=this.activePreviewKey)!=null?i:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,i;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((i=this.aiContext)==null?void 0:i.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&r)console.log("[CustomizePanel] Applying AI output directly to object:",a,r),this.applyObjectPropertyValue(a,r,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,r,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,i=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}.png. Refreshing library...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Adding to registry category:",i),d(i,`${n}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(y){console.warn("[CustomizePanel] Setup-library endpoint not available:",y)}let p=window.refreshAssetLibrary;typeof p=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await p());let u=window.__wizardAssetPicker;if(u!=null&&u.onPick){u.onPick(c.path),window.__wizardAssetPicker=null,this.setAiStatus("Saved to library and applied to wizard.");return}let g=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),h=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),m=this.getSelectedAssetInput();if(m&&(m.value=c.path,this.handleAssetValueChange((o=m.dataset.assetKey)!=null?o:"",m)),g&&h){console.log("[CustomizePanel] Applying saved asset to object:",g,h);let y=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof y=="function"&&b){let v=this.getFilenameFromPath(c.path);await y(g,v,i)}else this.applyObjectPropertyValue(g,h,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&g&&(console.log("[CustomizePanel] Highlighting slot in library:",g,i),setTimeout(()=>{f(g,i)},500)),this.setAiStatus(`\u2705 Saved and applied ${n}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var r;let t=(r=this.aiContext)==null?void 0:r.objectId,n=e||this.aiTargetKey||"",i=window.getEditableAssets;if(typeof i=="function"){let o=i();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(a=>a.currentAsset===e||a.slotId===e);return(i==null?void 0:i.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let i=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!i)return null;let a=i.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let i=da(this.aiOutputDataUrl,"ai-output.png");if(!i)return;let a=await this.showManualCropModal(i,n,t);if(!a)return;let r=await ca(a);r&&this.setAiOutput(r)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){console.log("[CustomizePanel] Handling asset upload for:",n);let i=t.value,a=e;if(e.type.startsWith("image/")){let d=await this.getImageDimensions(i);if(d){let p=await this.showManualCropModal(e,d,i);if(!p)return;a=p}}let r=await ca(a);if(!r){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${n.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(n);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",p.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(y){console.warn("[CustomizePanel] Setup-library not available:",y)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=p.path,this.handleAssetValueChange(n,t);let h=this.inferObjectIdFromAssetKey(n),m=this.inferPathFromAssetKey(n);if(h&&m){let y=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(m)||/\\.(png|jpg|jpeg)$/i.test(String(p.path||""));if(typeof y=="function"&&b){let v=this.getFilenameFromPath(p.path);await y(h,v,c)}else this.applyObjectPropertyValue(h,m,p.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&h&&setTimeout(()=>{f(h,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",p.error),alert(`Failed to save uploaded file: ${p.error}`)}catch(d){console.error("[CustomizePanel] \u274C Upload error:",d),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,i){if(!t)return;let a=this.resolveAssetUrls(t);if(a.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=i!=null?i:null,this.openPreviewModal(e,t,a,r)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),i=[];return n.startsWith("raw/")?i=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?i=[`/${n}`]:i=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",i),i}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,i){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1753
1753
  <div class="asset-preview-card">
1754
1754
  <div class="asset-preview-header">
1755
1755
  <div class="asset-preview-title">${e}</div>
@@ -1795,7 +1795,7 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1795
1795
  <button class="asset-crop-apply" type="button">Apply Crop</button>
1796
1796
  </div>
1797
1797
  </div>
1798
- `;let b=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),S=c.querySelector(".asset-crop-zoom"),L=c.querySelector(".asset-crop-zoom-value"),M=c.querySelector(".asset-crop-close"),O=c.querySelector(".asset-crop-cancel"),w=c.querySelector(".asset-crop-apply"),P=c.querySelector(".asset-crop-reset");if(!b||!v||!S||!L){l(null);return}let _=b.getContext("2d"),T=v.getContext("2d");if(!_||!T){l(null);return}let I=r.naturalWidth,C=r.naturalHeight,A=Math.max(b.width/I,b.height/C),E=1,x=0,j=0,k=!1,R=0,z=0,N=0,Y=0,B=()=>{let H=A*E,me=Math.max(0,(I*H-b.width)/2),Ee=Math.max(0,(C*H-b.height)/2);x=Math.min(me,Math.max(-me,x)),j=Math.min(Ee,Math.max(-Ee,j))},G=()=>{let H=A*E;_.clearRect(0,0,b.width,b.height);let me=b.width/2-I*H/2+x,Ee=b.height/2-C*H/2+j;if(_.drawImage(r,me,Ee,I*H,C*H),T.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Ae=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),bt=v.width/2-o.naturalWidth*Ae/2,ee=v.height/2-o.naturalHeight*Ae/2;T.drawImage(o,bt,ee,o.naturalWidth*Ae,o.naturalHeight*Ae)}else T.fillStyle="rgba(255, 255, 255, 0.04)",T.fillRect(0,0,v.width,v.height),T.strokeStyle="rgba(255, 255, 255, 0.08)",T.strokeRect(4,4,v.width-8,v.height-8);let De=v.width/b.width*(A*E),Ce=x*(v.width/b.width),Xe=j*(v.height/b.height),ft=v.width/2-I*De/2+Ce,yt=v.height/2-C*De/2+Xe;T.save(),T.globalAlpha=.7,T.drawImage(r,ft,yt,I*De,C*De),T.restore()},Q=()=>{x=0,j=0,B(),G()};S.addEventListener("input",()=>{E=Number(S.value),L.textContent=`${E.toFixed(2)}\xD7`,B(),G()}),b.addEventListener("pointerdown",H=>{k=!0,R=H.clientX,z=H.clientY,N=x,Y=j,b.setPointerCapture(H.pointerId)}),b.addEventListener("pointermove",H=>{k&&(x=N+(H.clientX-R),j=Y+(H.clientY-z),B(),G())}),b.addEventListener("pointerup",H=>{k=!1,b.releasePointerCapture(H.pointerId)}),b.addEventListener("pointerleave",()=>{k=!1});let ht=()=>{c.remove()},mt=()=>{ht(),l(null)},hn=async()=>{let H=document.createElement("canvas");H.width=t.width,H.height=t.height;let me=H.getContext("2d");if(!me){ht(),l(null);return}let Ee=E,Ce=Math.max(H.width/I,H.height/C)*Ee,Xe=H.width/b.width,ft=x*Xe,yt=j*Xe,Ae=H.width/2-I*Ce/2+ft,bt=H.height/2-C*Ce/2+yt;me.drawImage(r,Ae,bt,I*Ce,C*Ce);let ee=await new Promise(ne=>{H.toBlob(F=>ne(F),e.type||"image/png")});if(ht(),!ee){l(null);return}l(new File([ee],e.name,{type:ee.type}))};M==null||M.addEventListener("click",mt),O==null||O.addEventListener("click",mt),P==null||P.addEventListener("click",Q),w==null||w.addEventListener("click",()=>{hn()}),c.addEventListener("click",H=>{H.target===c&&mt()}),document.body.appendChild(c),Q()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let i=await this.loadImage(n);if(i)return i}return null}};var fi=class{constructor(){this.root=null;this.options=null}render(){return`
1798
+ `;let b=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),E=c.querySelector(".asset-crop-zoom"),P=c.querySelector(".asset-crop-zoom-value"),I=c.querySelector(".asset-crop-close"),O=c.querySelector(".asset-crop-cancel"),w=c.querySelector(".asset-crop-apply"),k=c.querySelector(".asset-crop-reset");if(!b||!v||!E||!P){l(null);return}let _=b.getContext("2d"),L=v.getContext("2d");if(!_||!L){l(null);return}let M=r.naturalWidth,C=r.naturalHeight,A=Math.max(b.width/M,b.height/C),S=1,x=0,j=0,T=!1,R=0,z=0,N=0,Y=0,F=()=>{let H=A*S,ve=Math.max(0,(M*H-b.width)/2),ae=Math.max(0,(C*H-b.height)/2);x=Math.min(ve,Math.max(-ve,x)),j=Math.min(ae,Math.max(-ae,j))},U=()=>{let H=A*S;_.clearRect(0,0,b.width,b.height);let ve=b.width/2-M*H/2+x,ae=b.height/2-C*H/2+j;if(_.drawImage(r,ve,ae,M*H,C*H),L.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Q=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),me=v.width/2-o.naturalWidth*Q/2,se=v.height/2-o.naturalHeight*Q/2;L.drawImage(o,me,se,o.naturalWidth*Q,o.naturalHeight*Q)}else L.fillStyle="rgba(255, 255, 255, 0.04)",L.fillRect(0,0,v.width,v.height),L.strokeStyle="rgba(255, 255, 255, 0.08)",L.strokeRect(4,4,v.width-8,v.height-8);let J=v.width/b.width*(A*S),B=x*(v.width/b.width),V=j*(v.height/b.height),Z=v.width/2-M*J/2+B,oe=v.height/2-C*J/2+V;L.save(),L.globalAlpha=.7,L.drawImage(r,Z,oe,M*J,C*J),L.restore()},ne=()=>{x=0,j=0,F(),U()};E.addEventListener("input",()=>{S=Number(E.value),P.textContent=`${S.toFixed(2)}\xD7`,F(),U()}),b.addEventListener("pointerdown",H=>{T=!0,R=H.clientX,z=H.clientY,N=x,Y=j,b.setPointerCapture(H.pointerId)}),b.addEventListener("pointermove",H=>{T&&(x=N+(H.clientX-R),j=Y+(H.clientY-z),F(),U())}),b.addEventListener("pointerup",H=>{T=!1,b.releasePointerCapture(H.pointerId)}),b.addEventListener("pointerleave",()=>{T=!1});let ot=()=>{c.remove()},lt=()=>{ot(),l(null)},an=async()=>{let H=document.createElement("canvas");H.width=t.width,H.height=t.height;let ve=H.getContext("2d");if(!ve){ot(),l(null);return}let ae=S,B=Math.max(H.width/M,H.height/C)*ae,V=H.width/b.width,Z=x*V,oe=j*V,Q=H.width/2-M*B/2+Z,me=H.height/2-C*B/2+oe;ve.drawImage(r,Q,me,M*B,C*B);let se=await new Promise(Ae=>{H.toBlob(Le=>Ae(Le),e.type||"image/png")});if(ot(),!se){l(null);return}l(new File([se],e.name,{type:se.type}))};I==null||I.addEventListener("click",lt),O==null||O.addEventListener("click",lt),k==null||k.addEventListener("click",ne),w==null||w.addEventListener("click",()=>{an()}),c.addEventListener("click",H=>{H.target===c&&lt()}),document.body.appendChild(c),ne()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let i=await this.loadImage(n);if(i)return i}return null}};var ri=class{constructor(){this.root=null;this.options=null}render(){return`
1799
1799
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
1800
1800
  <div class="scene-panel-header" data-panel-handle>
1801
1801
  <div class="panel-title">
@@ -1861,10 +1861,10 @@ Generate the requested asset matching the brand style.${s.needsTransparency?" Ba
1861
1861
  </div>
1862
1862
  </div>
1863
1863
  </div>
1864
- `}initialize(e,t){var b,v,S,L,M,O,w,P,_,T,I,C,A,E,x,j;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var R;let k=window.getEditableEngineConfig;if(typeof k=="function"){let z=k();return(R=z==null?void 0:z.loading)!=null?R:{}}return{}})(),a=(b=this.root)==null?void 0:b.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{type:a.value}),this.updateFieldVisibility(a.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=i.background_color||"#160a17",r.addEventListener("input",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{background_color:r.value})}));let o=(S=this.root)==null?void 0:S.querySelector("#loading-overlay-alpha"),l=(L=this.root)==null?void 0:L.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((M=i.overlay_alpha)!=null?M: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=i.text||"",c.addEventListener("input",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{text:c.value})}));let d=(w=this.root)==null?void 0:w.querySelector("#loading-text-scale"),p=(P=this.root)==null?void 0:P.querySelector("#loading-text-scale-value");d&&(d.value=String((_=i.text_scale)!=null?_:.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=(T=this.root)==null?void 0:T.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{enabled:u.checked})}));let g=(I=this.root)==null?void 0:I.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{blur_enabled:g.checked})}));let h=(C=this.root)==null?void 0:C.querySelector("#loading-blur-strength"),m=(A=this.root)==null?void 0:A.querySelector("#loading-blur-strength-value");h&&(h.value=String((E=i.blur_strength)!=null?E:8),m&&(m.textContent=h.value),h.addEventListener("input",()=>{var k,R;m&&(m.textContent=h.value),(R=(k=this.options)==null?void 0:k.onUpdateLoading)==null||R.call(k,{blur_strength:Number(h.value)})}));let f=(x=this.root)==null?void 0:x.querySelector("#loading-show-btn"),y=(j=this.root)==null?void 0:j.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onShowLoadingScreen)==null||R.call(k)}),y==null||y.addEventListener("click",()=>{var k,R;(R=(k=this.options)==null?void 0:k.onHideLoadingScreen)==null||R.call(k)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var tn=require("pixi.js");var Sa=require("pixi.js"),We=()=>window.debugConfig||{},Pr=()=>window.resolveAnchorVec2||(s=>({x:.5,y:.5})),Mr=()=>window.resolveScreenAnchorPoint||(()=>new Sa.Point),Ir=()=>window.resolveScreenRatioPoint||(()=>new Sa.Point);function _r(s){yi(s)&&(s.objectDebugRaf||(s.objectDebugRaf=window.requestAnimationFrame(()=>bi(s))))}function jr(s){s.objectDebugRaf&&(window.cancelAnimationFrame(s.objectDebugRaf),s.objectDebugRaf=null),en(s)}function yi(s){return s.isDebugOpen}function bi(s){var a,r,o;if(!yi(s)){s.objectDebugRaf=null;return}s.objectDebugRaf=window.requestAnimationFrame(()=>bi(s));let e=Ea(s);if(!e){Qt(s,null),en(s);return}let t=Ca(s,e);if(!t){Qt(s,null),en(s);return}let n=new tn.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=Aa(s,t);Qt(s,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=i==null?void 0:i.x)!=null?r:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),s.highlightObject?Pa(s,t):Ia(s),s.highlightAnchor&&i?Ma(s,i):_a(s)}function Ea(s){var i;let e=s.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function Ca(s,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function nn(s){let e=s.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Aa(s,e){var r,o;let t=nn(s);if(!t)return null;let n=(r=t.transform)!=null?r:{},i=La(s);if(!i)return null;if(n.position_ratio!=null)return Ir()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&n.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),Mr()(i.width,i.height,a)}function La(s){var a;let e=(a=s.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function Ta(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectBoundsGfx&&s.objectBoundsGfx.parent!==e.stage&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectBoundsGfx||(s.objectBoundsGfx=new tn.Graphics,s.objectBoundsGfx.zIndex=999999,e.stage.addChild(s.objectBoundsGfx)),s.objectBoundsGfx):null}function ka(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectAnchorGfx&&s.objectAnchorGfx.parent!==e.stage&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null),s.objectAnchorGfx||(s.objectAnchorGfx=new tn.Graphics,s.objectAnchorGfx.zIndex=1e6,e.stage.addChild(s.objectAnchorGfx)),s.objectAnchorGfx):null}function Pa(s,e){var i;let t=Ta(s);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Ma(s,e){let t=ka(s);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function Ia(s){s.objectBoundsGfx&&s.objectBoundsGfx.clear()}function _a(s){s.objectAnchorGfx&&s.objectAnchorGfx.clear()}function en(s){s.objectBoundsGfx&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectAnchorGfx&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null)}function Qt(s,e){s.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Or(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Rr(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n)a[o]=(r=a[o])!=null?r:{},a=a[o];a[i]=t}function ja(s){var n,i,a,r,o;if(!s)return!1;if((n=s.transform)!=null&&n.offset)return!0;let e=((a=(i=s.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(r=s.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function wi(s){let e=We();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 zr(s){window.location.reload()}function xi(s){let e=JSON.stringify(We(),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 $r(s,e){var t,n,i;if(!(!s.configViewer||!s.container))try{let a=window.getEditableObjectConfig,r=typeof a=="function"?a(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(Fn(),ir)),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),vi(s,u),(n=s.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),vi(s,r),(i=s.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function vi(s,e){var u,g,h,m,f,y,b,v,S,L;if(!s.container)return;let t=s.container.querySelector("#config-pos-x"),n=s.container.querySelector("#config-pos-y"),i=s.container.querySelector("#config-scale"),a=s.container.querySelector("#config-anchor-preset"),r=s.container.querySelector("#config-anchor-x"),o=s.container.querySelector("#config-anchor-y"),c=ja(e)?(u=e.transform)==null?void 0:u.offset:(g=e.transform)==null?void 0:g.position;t&&(t.value=String((h=c==null?void 0:c.x)!=null?h:0)),n&&(n.value=String((m=c==null?void 0:c.y)!=null?m:0)),i&&(i.value=String((y=(f=e.transform)==null?void 0:f.scale)!=null?y:1));let d=(L=(S=(b=e.transform)==null?void 0:b.anchor)!=null?S:(v=e.render)==null?void 0:v.anchor)!=null?L:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let M=s.container.querySelectorAll(".anchor-custom-field"),O=a.value==="custom";M.forEach(w=>w.style.display=O?"block":"none")}let p=Pr()(d);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function Dr(s){var l,c,d,p,u,g,h,m,f,y;let e=s.selectedObjectId;if(!e||!s.container)return;let t=(c=(l=s.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(p=(d=s.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",i=(g=(u=s.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(m=(h=s.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?m:"0.5",r=(y=(f=s.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?y:"0.5",o=`${e}:
1864
+ `}initialize(e,t){var b,v,E,P,I,O,w,k,_,L,M,C,A,S,x,j;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let i=(()=>{var R;let T=window.getEditableEngineConfig;if(typeof T=="function"){let z=T();return(R=z==null?void 0:z.loading)!=null?R:{}}return{}})(),a=(b=this.root)==null?void 0:b.querySelector("#loading-screen-type");a&&(a.value=i.type==="image"?"image":"color",a.addEventListener("change",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{type:a.value}),this.updateFieldVisibility(a.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=i.background_color||"#160a17",r.addEventListener("input",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{background_color:r.value})}));let o=(E=this.root)==null?void 0:E.querySelector("#loading-overlay-alpha"),l=(P=this.root)==null?void 0:P.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((I=i.overlay_alpha)!=null?I:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var R,z;let T=Number(o.value);l&&(l.textContent=T.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{overlay_alpha:T})}));let c=(O=this.root)==null?void 0:O.querySelector("#loading-text");c&&(c.value=i.text||"",c.addEventListener("input",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{text:c.value})}));let d=(w=this.root)==null?void 0:w.querySelector("#loading-text-scale"),p=(k=this.root)==null?void 0:k.querySelector("#loading-text-scale-value");d&&(d.value=String((_=i.text_scale)!=null?_:.6),p&&(p.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var R,z;let T=Number(d.value);p&&(p.textContent=T.toFixed(2)),(z=(R=this.options)==null?void 0:R.onUpdateLoading)==null||z.call(R,{text_scale:T})}));let u=(L=this.root)==null?void 0:L.querySelector("#loading-enabled");u&&(u.checked=i.enabled!==!1,u.addEventListener("change",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{enabled:u.checked})}));let g=(M=this.root)==null?void 0:M.querySelector("#loading-blur-enabled");g&&(g.checked=i.blur_enabled!==!1,g.addEventListener("change",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{blur_enabled:g.checked})}));let h=(C=this.root)==null?void 0:C.querySelector("#loading-blur-strength"),m=(A=this.root)==null?void 0:A.querySelector("#loading-blur-strength-value");h&&(h.value=String((S=i.blur_strength)!=null?S:8),m&&(m.textContent=h.value),h.addEventListener("input",()=>{var T,R;m&&(m.textContent=h.value),(R=(T=this.options)==null?void 0:T.onUpdateLoading)==null||R.call(T,{blur_strength:Number(h.value)})}));let f=(x=this.root)==null?void 0:x.querySelector("#loading-show-btn"),y=(j=this.root)==null?void 0:j.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onShowLoadingScreen)==null||R.call(T)}),y==null||y.addEventListener("click",()=>{var T,R;(R=(T=this.options)==null?void 0:T.onHideLoadingScreen)==null||R.call(T)}),this.updateFieldVisibility(i.type==="image"?"image":"color")}updateFieldVisibility(e){var i,a;let t=(i=this.root)==null?void 0:i.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var qt=require("pixi.js");var ha=require("pixi.js"),Ve=()=>window.debugConfig||{},xr=()=>window.resolveAnchorVec2||(s=>({x:.5,y:.5})),Sr=()=>window.resolveScreenAnchorPoint||(()=>new ha.Point),Er=()=>window.resolveScreenRatioPoint||(()=>new ha.Point);function Cr(s){oi(s)&&(s.objectDebugRaf||(s.objectDebugRaf=window.requestAnimationFrame(()=>li(s))))}function Ar(s){s.objectDebugRaf&&(window.cancelAnimationFrame(s.objectDebugRaf),s.objectDebugRaf=null),Ut(s)}function oi(s){return s.isDebugOpen}function li(s){var a,r,o;if(!oi(s)){s.objectDebugRaf=null;return}s.objectDebugRaf=window.requestAnimationFrame(()=>li(s));let e=ma(s);if(!e){Gt(s,null),Ut(s);return}let t=fa(s,e);if(!t){Gt(s,null),Ut(s);return}let n=new qt.Point;(a=t.getGlobalPosition)==null||a.call(t,n);let i=ya(s,t);Gt(s,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=i==null?void 0:i.x)!=null?r:null,configY:(o=i==null?void 0:i.y)!=null?o:null}),s.highlightObject?xa(s,t):Ea(s),s.highlightAnchor&&i?Sa(s,i):Ca(s)}function ma(s){var i;let e=s.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function fa(s,e){var i,a;let t=window.gameObjectManager,n=(i=t==null?void 0:t.get)==null?void 0:i.call(t,e);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function Vt(s){let e=s.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function ya(s,e){var r,o;let t=Vt(s);if(!t)return null;let n=(r=t.transform)!=null?r:{},i=ba(s);if(!i)return null;if(n.position_ratio!=null)return Er()(i.width,i.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"bottom-center";return a==="bottom-center"&&n.anchor==null&&console.log("[DEBUG FALLBACK] objectVisuals transform.anchor \u2192 bottom-center"),Sr()(i.width,i.height,a)}function ba(s){var a;let e=(a=s.container)==null?void 0:a.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let i=window.gameApp;return i!=null&&i.renderer?{width:i.renderer.width,height:i.renderer.height}:null}function va(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectBoundsGfx&&s.objectBoundsGfx.parent!==e.stage&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectBoundsGfx||(s.objectBoundsGfx=new qt.Graphics,s.objectBoundsGfx.zIndex=999999,e.stage.addChild(s.objectBoundsGfx)),s.objectBoundsGfx):null}function wa(s){let e=window.gameApp;return e!=null&&e.stage?(s.objectAnchorGfx&&s.objectAnchorGfx.parent!==e.stage&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null),s.objectAnchorGfx||(s.objectAnchorGfx=new qt.Graphics,s.objectAnchorGfx.zIndex=1e6,e.stage.addChild(s.objectAnchorGfx)),s.objectAnchorGfx):null}function xa(s,e){var i;let t=va(s);if(!t)return;let n=(i=e.getBounds)==null?void 0:i.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Sa(s,e){let t=wa(s);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function Ea(s){s.objectBoundsGfx&&s.objectBoundsGfx.clear()}function Ca(s){s.objectAnchorGfx&&s.objectAnchorGfx.clear()}function Ut(s){s.objectBoundsGfx&&(s.objectBoundsGfx.destroy(),s.objectBoundsGfx=null),s.objectAnchorGfx&&(s.objectAnchorGfx.destroy(),s.objectAnchorGfx=null)}function Gt(s,e){s.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Lr(s,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,s)}function Tr(s,e,t){var r;let n=e.split("."),i=n.pop(),a=s;for(let o of n)a[o]=(r=a[o])!=null?r:{},a=a[o];a[i]=t}function Aa(s){var n,i,a,r,o;if(!s)return!1;if((n=s.transform)!=null&&n.offset)return!0;let e=((a=(i=s.identity)==null?void 0:i.category)!=null?a:"").toString().toLowerCase(),t=((o=(r=s.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function di(s){let e=Ve();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 kr(s){window.location.reload()}function pi(s){let e=JSON.stringify(Ve(),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 Pr(s,e){var t,n,i;if(!(!s.configViewer||!s.container))try{let a=window.getEditableObjectConfig,r=typeof a=="function"?a(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(Mn(),Ks)),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),ci(s,u),(n=s.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),ci(s,r),(i=s.configViewer)==null||i.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function ci(s,e){var u,g,h,m,f,y,b,v,E,P;if(!s.container)return;let t=s.container.querySelector("#config-pos-x"),n=s.container.querySelector("#config-pos-y"),i=s.container.querySelector("#config-scale"),a=s.container.querySelector("#config-anchor-preset"),r=s.container.querySelector("#config-anchor-x"),o=s.container.querySelector("#config-anchor-y"),c=Aa(e)?(u=e.transform)==null?void 0:u.offset:(g=e.transform)==null?void 0:g.position;t&&(t.value=String((h=c==null?void 0:c.x)!=null?h:0)),n&&(n.value=String((m=c==null?void 0:c.y)!=null?m:0)),i&&(i.value=String((y=(f=e.transform)==null?void 0:f.scale)!=null?y:1));let d=(P=(E=(b=e.transform)==null?void 0:b.anchor)!=null?E:(v=e.render)==null?void 0:v.anchor)!=null?P:"center";if(a){typeof d=="string"?a.value=d:a.value="custom";let I=s.container.querySelectorAll(".anchor-custom-field"),O=a.value==="custom";I.forEach(w=>w.style.display=O?"block":"none")}let p=xr()(d);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function Ir(s){var l,c,d,p,u,g,h,m,f,y;let e=s.selectedObjectId;if(!e||!s.container)return;let t=(c=(l=s.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(p=(d=s.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?p:"0",i=(g=(u=s.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",a=(m=(h=s.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?m:"0.5",r=(y=(f=s.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?y:"0.5",o=`${e}:
1865
1865
  position: (${t}, ${n})
1866
1866
  scale: ${i}
1867
- anchor: (${a}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(b=>console.error("[DEBUG] Failed to copy config values:",b))}async function Oa(s,e){var u,g,h,m,f,y,b,v,S,L,M,O;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!s.container)return;let t=s.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((g=(u=s.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),i=Number((m=(h=s.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?m:0),a=Number((y=(f=s.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?y:1),r=(v=(b=s.container.querySelector("#config-anchor-preset"))==null?void 0:b.value)!=null?v:"center",o=Number((L=(S=s.container.querySelector("#config-anchor-x"))==null?void 0:S.value)!=null?L:.5),l=Number((O=(M=s.container.querySelector("#config-anchor-y"))==null?void 0:M.value)!=null?O:.5),c=r==="custom"?{x:o,y:l}:r;console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(Z(),Ue));d({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.anchor",value:c},{silent:e==null?void 0:e.silent});let p=nn(s);ja(p)&&d({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0})}async function Nr(s,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(Z(),Ue));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([d,p])=>{var u;if(d)if(d.includes(".")){let g=d.split("."),h=c;for(let m=0;m<g.length-1;m++){let f=g[m];h[f]=(u=h[f])!=null?u:{},h=h[f]}h[g[g.length-1]]=p}else c[d]=p}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function Hr(s){s.selectedObjectId&&(s.objectAutoApplyTimer&&window.clearTimeout(s.objectAutoApplyTimer),s.objectAutoApplyTimer=window.setTimeout(()=>{s.objectAutoApplyTimer=null,Oa(s,{silent:!0})},150))}var Ll=3e3;function pt(s,e,t){let n=t!=null?t:s.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,r=0,o=0,l=0,c=0,d=0,p=g=>{if(!i)return;let h=n.getBoundingClientRect();s.style.left=`${g.clientX-h.left-c}px`,s.style.top=`${g.clientY-h.top-d}px`},u=()=>{i&&(i=!1,s.classList.remove("dragging"),window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let h=g.target;if(h!=null&&h.closest("button, input, select, textarea"))return;g.preventDefault();let m=s.getBoundingClientRect(),f=n.getBoundingClientRect();console.log("[DRAG] Panel:",s.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:m.left,top:m.top,width:m.width,height:m.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-m.left,d=g.clientY-m.top,console.log("[DRAG] offset:",{x:c,y:d});let y=m.left-f.left,b=m.top-f.top;console.log("[DRAG] targetPosition:",{left:y,top:b}),s.style.left=`${y}px`,s.style.top=`${b}px`,s.style.right="auto",s.style.bottom="auto",s.style.zIndex=String(++Ll),i=!0,s.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function Si(s,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,r=0,o=0,l=0,c=!1,d=u=>{var b;if(!c)return;let g=u.clientX-o,h=u.clientY-l,m=Math.max(n,a+g),f=Math.max(i,r+h);s.style.width=`${m}px`,(b=s.closest(".preview-shell"))!=null&&b.classList.contains("layout-fixed")||(s.style.height=`${f}px`),t==null||t(m,f)},p=()=>{c&&(c=!1,window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=s.getBoundingClientRect();a=g.width,r=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function Ra(s,e){var m,f,y,b;let t=(y=(f=(m=s.container)==null?void 0:m.querySelector("#debug-overlay"))!=null?f:s.debugOverlay)!=null?y:e.offsetParent;if(!t||(b=s.container)!=null&&b.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,r=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>r&&(e.style.width=`${r}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,d=l.top-n.top,p=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),p),h=Math.min(Math.max(d,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function kt(s){var n,i;if(!s.container)return;let e=s.container.querySelector("#debug-workbench");if(!e)return;if(Ra(s,e),(n=s.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),r={activeTab:s.activeTab};if(a)try{r={...JSON.parse(a),activeTab:s.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(r));return}let t={activeTab:s.activeTab,width:e.style.width,height:(i=s.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function Ei(s){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(s.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=s.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let r=(a=s.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!r?n.style.height=t.height:r&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Ra(s,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function za(s,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",Ra(s,e),kt(s))}function Fr(s){var i,a,r;if(!s.container)return;let e=s.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=s.toggleDebug)==null||o.call(s)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=s.toggleDebug)==null?void 0:o.call(s,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>wi(s)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>xi(s)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;s.activeTab=l,$a(s),kt(s)})}),Na(s,e),Da(s,e)}function $a(s){if(!s.container)return;let e=s.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===s.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===s.activeTab)})}function Da(s,e){ge(s,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),ge(s,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),ge(s,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),ge(s,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),ge(s,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),ge(s,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),ge(s,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),ge(s,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),ge(s,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=We();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),r=We();r.layout&&(r.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Br(s){if(!s.container||!s.debugOverlay)return;let e=s.container.querySelector("#debug-workbench"),t=s.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),pt(e,t,s.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{kt(s),za(s,e)},10)}));let n=s.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),pt(n,i,s.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{za(s,n)},10)})),n&&a&&Si(n,a);let r=s.container.querySelector('[data-panel="scene-tools-corner"]'),o=r==null?void 0:r.querySelector("[data-panel-handle]");r&&o&&pt(r,o,s.debugOverlay);let l=s.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&pt(l,c,s.debugOverlay),Ei(s)}function Na(s,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function ge(s,e,t,n,i){let a=e.querySelector(`#${t}`),r=e.querySelector(i);if(!a||!r)return;let o=Or(We(),n);typeof o=="number"&&(a.value=String(o),r.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);r.textContent=String(l),Rr(We(),n,l)})}Z();var Ci=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=Be(),{hasChanges:t,overrideCount:n,overrides:i}=e,a={};for(let d of i){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1867
+ anchor: (${a}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(b=>console.error("[DEBUG] Failed to copy config values:",b))}async function La(s,e){var u,g,h,m,f,y,b,v,E,P,I,O;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!s.container)return;let t=s.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((g=(u=s.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?g:0),i=Number((m=(h=s.container.querySelector("#config-pos-y"))==null?void 0:h.value)!=null?m:0),a=Number((y=(f=s.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?y:1),r=(v=(b=s.container.querySelector("#config-anchor-preset"))==null?void 0:b.value)!=null?v:"center",o=Number((P=(E=s.container.querySelector("#config-anchor-x"))==null?void 0:E.value)!=null?P:.5),l=Number((O=(I=s.container.querySelector("#config-anchor-y"))==null?void 0:I.value)!=null?O:.5),c=r==="custom"?{x:o,y:l}:r;console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:i,scale:a,anchor:c});let{applyConfigOverride:d}=await Promise.resolve().then(()=>(te(),Be));d({objectId:t,path:"transform.position",value:{x:n,y:i}},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.scale",value:a},{silent:e==null?void 0:e.silent}),d({objectId:t,path:"transform.anchor",value:c},{silent:e==null?void 0:e.silent});let p=Vt(s);Aa(p)&&d({objectId:t,path:"transform.offset",value:{x:n,y:i}},{silent:!0})}async function Mr(s,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(te(),Be));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let i=window.applyEditableEngineConfig;if(typeof i=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([d,p])=>{var u;if(d)if(d.includes(".")){let g=d.split("."),h=c;for(let m=0;m<g.length-1;m++){let f=g[m];h[f]=(u=h[f])!=null?u:{},h=h[f]}h[g[g.length-1]]=p}else c[d]=p}),l.ui=c,i({runtime:l,assets:e.assets})}let a=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!a,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function _r(s){s.selectedObjectId&&(s.objectAutoApplyTimer&&window.clearTimeout(s.objectAutoApplyTimer),s.objectAutoApplyTimer=window.setTimeout(()=>{s.objectAutoApplyTimer=null,La(s,{silent:!0})},150))}var bl=3e3;function at(s,e,t){let n=t!=null?t:s.offsetParent;if(!n)return;e.style.cursor="move";let i=!1,a=0,r=0,o=0,l=0,c=0,d=0,p=g=>{if(!i)return;let h=n.getBoundingClientRect();s.style.left=`${g.clientX-h.left-c}px`,s.style.top=`${g.clientY-h.top-d}px`},u=()=>{i&&(i=!1,s.classList.remove("dragging"),window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let h=g.target;if(h!=null&&h.closest("button, input, select, textarea"))return;g.preventDefault();let m=s.getBoundingClientRect(),f=n.getBoundingClientRect();console.log("[DRAG] Panel:",s.className),console.log("[DRAG] Container:",n.className),console.log("[DRAG] panelRect:",{left:m.left,top:m.top,width:m.width,height:m.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-m.left,d=g.clientY-m.top,console.log("[DRAG] offset:",{x:c,y:d});let y=m.left-f.left,b=m.top-f.top;console.log("[DRAG] targetPosition:",{left:y,top:b}),s.style.left=`${y}px`,s.style.top=`${b}px`,s.style.right="auto",s.style.bottom="auto",s.style.zIndex=String(++bl),i=!0,s.classList.add("dragging"),window.addEventListener("pointermove",p),window.addEventListener("pointerup",u)})}function ui(s,e,t,n=280,i=200){e.style.cursor="nwse-resize";let a=0,r=0,o=0,l=0,c=!1,d=u=>{var b;if(!c)return;let g=u.clientX-o,h=u.clientY-l,m=Math.max(n,a+g),f=Math.max(i,r+h);s.style.width=`${m}px`,(b=s.closest(".preview-shell"))!=null&&b.classList.contains("layout-fixed")||(s.style.height=`${f}px`),t==null||t(m,f)},p=()=>{c&&(c=!1,window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=s.getBoundingClientRect();a=g.width,r=g.height,o=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",d),window.addEventListener("pointerup",p)})}function Ta(s,e){var m,f,y,b;let t=(y=(f=(m=s.container)==null?void 0:m.querySelector("#debug-overlay"))!=null?f:s.debugOverlay)!=null?y:e.offsetParent;if(!t||(b=s.container)!=null&&b.classList.contains("layout-fixed"))return;let n=t.getBoundingClientRect(),i=e.getBoundingClientRect(),a=12,r=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));i.width>r&&(e.style.width=`${r}px`),i.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,d=l.top-n.top,p=Math.max(a,n.width-l.width-a),u=Math.max(a,n.height-l.height-a),g=Math.min(Math.max(c,a),p),h=Math.min(Math.max(d,a),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function bt(s){var n,i;if(!s.container)return;let e=s.container.querySelector("#debug-workbench");if(!e)return;if(Ta(s,e),(n=s.container)!=null&&n.classList.contains("layout-fixed")){let a=localStorage.getItem("preview_workbench_state"),r={activeTab:s.activeTab};if(a)try{r={...JSON.parse(a),activeTab:s.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(r));return}let t={activeTab:s.activeTab,width:e.style.width,height:(i=s.container)!=null&&i.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function gi(s){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(s.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var i,a;let n=(i=s.container)==null?void 0:i.querySelector("#debug-workbench");if(n){let r=(a=s.container)==null?void 0:a.classList.contains("layout-fixed");t.width&&(n.style.width=t.width),t.height&&!r?n.style.height=t.height:r&&(n.style.height=""),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Ta(s,n)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function ka(s,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",Ta(s,e),bt(s))}function jr(s){var i,a,r;if(!s.container)return;let e=s.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=s.toggleDebug)==null||o.call(s)}),(i=e.querySelector("#debug-close"))==null||i.addEventListener("click",()=>{var o;return(o=s.toggleDebug)==null?void 0:o.call(s,!1)}),(a=e.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>di(s)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>pi(s)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;s.activeTab=l,Pa(s),bt(s)})}),Ma(s,e),Ia(s,e)}function Pa(s){if(!s.container)return;let e=s.container;e.querySelectorAll(".workbench-tab").forEach(i=>{let a=i.dataset.tab;i.classList.toggle("active",a===s.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(i=>{let a=i.dataset.tabPanel;i.classList.toggle("active",a===s.activeTab)})}function Ia(s,e){ye(s,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),ye(s,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),ye(s,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),ye(s,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),ye(s,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),ye(s,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),ye(s,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),ye(s,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),ye(s,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let i=Ve();i.layout&&(i.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let i=n.value.replace("#",""),a=parseInt(i,16),r=Ve();r.layout&&(r.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Or(s){if(!s.container||!s.debugOverlay)return;let e=s.container.querySelector("#debug-workbench"),t=s.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),at(e,t,s.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{bt(s),ka(s,e)},10)}));let n=s.container.querySelector('[data-panel="scene-objects"]'),i=n==null?void 0:n.querySelector("[data-panel-handle]"),a=n==null?void 0:n.querySelector("[data-panel-resize-v]");n&&i&&(!n.style.left&&!n.style.right&&!n.style.top&&!n.style.bottom&&(n.style.left="16px",n.style.top="72px"),at(n,i,s.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{ka(s,n)},10)})),n&&a&&ui(n,a);let r=s.container.querySelector('[data-panel="scene-tools-corner"]'),o=r==null?void 0:r.querySelector("[data-panel-handle]");r&&o&&at(r,o,s.debugOverlay);let l=s.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&at(l,c,s.debugOverlay),gi(s)}function Ma(s,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let i=n.closest(".scene-panel");i&&i.classList.toggle("collapsed")})})}function ye(s,e,t,n,i){let a=e.querySelector(`#${t}`),r=e.querySelector(i);if(!a||!r)return;let o=Lr(Ve(),n);typeof o=="number"&&(a.value=String(o),r.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);r.textContent=String(l),Tr(Ve(),n,l)})}te();var hi=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:n,overrides:i}=e,a={};for(let d of i){let p=d.objectId||"Engine";a[p]||(a[p]=[]),a[p].push(d)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never",l=this.currentVersion?`Version: ${this.currentVersion} (Active)`:"Original",c=this.currentVersion?`Versioned (${this.currentVersion})`:"Global";return`
1868
1868
  <div class="config-persistence-panel">
1869
1869
  <!-- Status Footer (Always Visible) -->
1870
1870
  <div class="persistence-status-footer">
@@ -2028,17 +2028,17 @@ This will delete generated config JSON files in configs/objects that are not ref
2028
2028
 
2029
2029
  It will NOT touch library/base configs.
2030
2030
 
2031
- Continue?`))try{e.textContent="\u23F3 Pruning...",e.setAttribute("disabled","true");let g=await fetch("/api/objects/prune-unused",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dryRun:!1})}),h=await g.json().catch(()=>({}));if(!g.ok||(h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Prune failed");await this.forceResyncAfterApply();let m=Array.isArray(h.deletedFiles)?h.deletedFiles.length:0,f=Array.isArray(h.removedAssetSlots)?h.removedAssetSlots.length:0;this.showSuccessNotification(`Pruned ${m} configs, ${f} asset slots`),this.refreshPanel()}catch(g){console.error("[ConfigPersistence] Prune unused failed:",g),alert(`\u274C Prune failed: ${g.message}`)}finally{e.textContent="\u{1F9F9} PRUNE UNUSED OBJECT CONFIGS",e.removeAttribute("disabled")}});let t=this.container.querySelector("#create-version-btn");t==null||t.addEventListener("click",async()=>{var h;if(t.getAttribute("disabled")!==null)return;if(!Be().hasChanges){alert("No changes to save. Make some edits first.");return}if(confirm(`Save As New Version?
2031
+ Continue?`))try{e.textContent="\u23F3 Pruning...",e.setAttribute("disabled","true");let g=await fetch("/api/objects/prune-unused",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dryRun:!1})}),h=await g.json().catch(()=>({}));if(!g.ok||(h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Prune failed");await this.forceResyncAfterApply();let m=Array.isArray(h.deletedFiles)?h.deletedFiles.length:0,f=Array.isArray(h.removedAssetSlots)?h.removedAssetSlots.length:0;this.showSuccessNotification(`Pruned ${m} configs, ${f} asset slots`),this.refreshPanel()}catch(g){console.error("[ConfigPersistence] Prune unused failed:",g),alert(`\u274C Prune failed: ${g.message}`)}finally{e.textContent="\u{1F9F9} PRUNE UNUSED OBJECT CONFIGS",e.removeAttribute("disabled")}});let t=this.container.querySelector("#create-version-btn");t==null||t.addEventListener("click",async()=>{var h;if(t.getAttribute("disabled")!==null)return;if(!Fe().hasChanges){alert("No changes to save. Make some edits first.");return}if(confirm(`Save As New Version?
2032
2032
 
2033
2033
  This will:
2034
2034
  \u2022 Create a new version snapshot
2035
2035
  \u2022 Include all current changes
2036
2036
  \u2022 Clear staged overrides after save
2037
- \u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",y=((h=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?h:"").trim();if(!y){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",y),t.textContent="\u23F3 Creating version...",t.setAttribute("disabled","true"),await Rn(y),de(),await this.forceResyncAfterApply(),this.showSuccessNotification("Version created and set as active"),await this.loadVersionsList(),this.refreshPanel()}catch(m){console.error("[ConfigPersistence] Create version failed:",m),alert(`\u274C Failed to create version: ${m.message}`),t.textContent="\u{1F4DD} SAVE AS NEW VERSION",t.removeAttribute("disabled")}});let n=this.container.querySelector("#apply-current-btn");n==null||n.addEventListener("click",async()=>{if(n.getAttribute("disabled")!==null)return;let u=this.currentVersion?`version "${this.currentVersion}"`:"Original configs";if(confirm(`Apply to Current Source?
2037
+ \u2022 Set the new version as active`))try{let m=localStorage.getItem("handler_last_version_name")||"",y=((h=prompt("Version name (e.g. v1.2.0, test_2024):",m))!=null?h:"").trim();if(!y){alert("Version name is required.");return}localStorage.setItem("handler_last_version_name",y),t.textContent="\u23F3 Creating version...",t.setAttribute("disabled","true"),await An(y),ge(),await this.forceResyncAfterApply(),this.showSuccessNotification("Version created and set as active"),await this.loadVersionsList(),this.refreshPanel()}catch(m){console.error("[ConfigPersistence] Create version failed:",m),alert(`\u274C Failed to create version: ${m.message}`),t.textContent="\u{1F4DD} SAVE AS NEW VERSION",t.removeAttribute("disabled")}});let n=this.container.querySelector("#apply-current-btn");n==null||n.addEventListener("click",async()=>{if(n.getAttribute("disabled")!==null)return;let u=this.currentVersion?`version "${this.currentVersion}"`:"Original configs";if(confirm(`Apply to Current Source?
2038
2038
 
2039
2039
  This will write all staged changes to ${u}.
2040
2040
 
2041
- After applying, staged overrides will be cleared.`))try{n.textContent="\u23F3 Applying...",n.setAttribute("disabled","true");let h=ot(),m={};for(let[b,v]of Object.entries(h.objects)){let S=v,L=b;/^(json\.|ui\.|effects\.|engine\.)/.test(L)||(L=`json.${b}`),S&&typeof S=="object"&&(S.identity||(S.identity={}),S.identity.id=L),m[`objects/${L}.json`]=S}h.engine&&(h.engine.runtime&&(m["engine/engine.runtime.json"]=h.engine.runtime),h.engine.assets&&(m["engine/engine.assets.json"]=h.engine.assets),h.engine.splash&&(m["engine/engine.splash.json"]=h.engine.splash),h.engine.loading&&(m["engine/engine.loading.json"]=h.engine.loading),h.engine.start&&(m["engine/engine.start.json"]=h.engine.start),h.engine.tutorial&&(m["engine/engine.tutorial.json"]=h.engine.tutorial),h.engine.endgame&&(m["engine/engine.endgame.json"]=h.engine.endgame),!h.engine.runtime&&!h.engine.assets&&(m["engine/engine.json"]=h.engine));for(let[b,v]of Object.entries(h.scenes)){let S=b.startsWith("scene.")?b:`scene.${b}`;m[`scenes/${S}.json`]=v}let f=this.currentVersion?"/api/apply-current":"/api/apply-direct",y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:m,assets:{},hadCacheAtApply:!0})});if(!y.ok){let b=await y.json();throw new Error(b.error||"Apply to current source failed")}de(),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}`),n.textContent="\u{1F4BE} APPLY TO CURRENT SOURCE",n.removeAttribute("disabled")}});let i=this.container.querySelector("#apply-base-btn");i==null||i.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
2041
+ After applying, staged overrides will be cleared.`))try{n.textContent="\u23F3 Applying...",n.setAttribute("disabled","true");let h=et(),m={};for(let[b,v]of Object.entries(h.objects)){let E=v,P=b;/^(json\.|ui\.|effects\.|engine\.)/.test(P)||(P=`json.${b}`),E&&typeof E=="object"&&(E.identity||(E.identity={}),E.identity.id=P),m[`objects/${P}.json`]=E}h.engine&&(h.engine.runtime&&(m["engine/engine.runtime.json"]=h.engine.runtime),h.engine.assets&&(m["engine/engine.assets.json"]=h.engine.assets),h.engine.splash&&(m["engine/engine.splash.json"]=h.engine.splash),h.engine.loading&&(m["engine/engine.loading.json"]=h.engine.loading),h.engine.start&&(m["engine/engine.start.json"]=h.engine.start),h.engine.tutorial&&(m["engine/engine.tutorial.json"]=h.engine.tutorial),h.engine.endgame&&(m["engine/engine.endgame.json"]=h.engine.endgame),!h.engine.runtime&&!h.engine.assets&&(m["engine/engine.json"]=h.engine));for(let[b,v]of Object.entries(h.scenes)){let E=b.startsWith("scene.")?b:`scene.${b}`;m[`scenes/${E}.json`]=v}let f=this.currentVersion?"/api/apply-current":"/api/apply-direct",y=await fetch(f,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:m,assets:{},hadCacheAtApply:!0})});if(!y.ok){let b=await y.json();throw new Error(b.error||"Apply to current source failed")}ge(),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}`),n.textContent="\u{1F4BE} APPLY TO CURRENT SOURCE",n.removeAttribute("disabled")}});let i=this.container.querySelector("#apply-base-btn");i==null||i.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
2042
2042
 
2043
2043
  This will DIRECTLY MODIFY base configuration files.
2044
2044
 
@@ -2048,25 +2048,25 @@ This is ONLY for active development.
2048
2048
 
2049
2049
  Make sure your project is under Git version control.
2050
2050
 
2051
- Continue?`))try{i.textContent="\u23F3 Writing to base...",i.setAttribute("disabled","true");let g=ot(),h={};for(let[f,y]of Object.entries(g.objects)){let b=y,v=f;/^(json\.|ui\.|effects\.|engine\.)/.test(v)||(v=`json.${f}`),b&&typeof b=="object"&&(b.identity||(b.identity={}),b.identity.id=v),h[`objects/${v}.json`]=b}g.engine&&(g.engine.runtime&&(h["engine/engine.runtime.json"]=g.engine.runtime),g.engine.assets&&(h["engine/engine.assets.json"]=g.engine.assets),g.engine.splash&&(h["engine/engine.splash.json"]=g.engine.splash),g.engine.loading&&(h["engine/engine.loading.json"]=g.engine.loading),g.engine.start&&(h["engine/engine.start.json"]=g.engine.start),g.engine.tutorial&&(h["engine/engine.tutorial.json"]=g.engine.tutorial),g.engine.endgame&&(h["engine/engine.endgame.json"]=g.engine.endgame),!g.engine.runtime&&!g.engine.assets&&(h["engine/engine.json"]=g.engine));for(let[f,y]of Object.entries(g.scenes)){let b=f.startsWith("scene.")?f:`scene.${f}`;h[`scenes/${b}.json`]=y}let m=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:h,assets:{}})});if(!m.ok){let f=await m.json();throw new Error(f.error||"Apply to base failed")}de(),this.showSuccessNotification(),this.refreshPanel(),await this.forceResyncAfterApply()}catch(g){console.error("[ConfigPersistence] Apply to base failed:",g),alert(`\u274C Apply to base failed: ${g.message}`),i.textContent="\u{1F527} APPLY TO BASE (No Version)",i.removeAttribute("disabled")}});let a=this.container.querySelector("#version-selector");a==null||a.addEventListener("change",async u=>{let h=u.target.value;await this.switchVersion(h)}),this.container.querySelectorAll(".item-remove").forEach(u=>{u.addEventListener("click",()=>{let g=u.dataset.removePath,h=u.dataset.removeId;Wt(h||void 0,g)})});let o=this.container.querySelector("#clear-all-overrides"),l=this.container.querySelector("#discard-all-overrides-btn"),c=()=>{confirm("Discard all staged changes? This will clear all overrides and reload from current Source.")&&(de(),Yt(),this.refreshPanel())};o==null||o.addEventListener("click",c),l==null||l.addEventListener("click",c);let d=this.container.querySelector("#reset-to-applied-btn");d==null||d.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Yt()});let p=this.container.querySelector("#reset-to-original-btn");p==null||p.addEventListener("click",async()=>{await zn()})}showSuccessNotification(e){let t=document.createElement("div");t.className="persistence-notification success";let n=e&&e.trim().length>0?e.trim():"Changes Applied!";t.innerHTML=`
2051
+ Continue?`))try{i.textContent="\u23F3 Writing to base...",i.setAttribute("disabled","true");let g=et(),h={};for(let[f,y]of Object.entries(g.objects)){let b=y,v=f;/^(json\.|ui\.|effects\.|engine\.)/.test(v)||(v=`json.${f}`),b&&typeof b=="object"&&(b.identity||(b.identity={}),b.identity.id=v),h[`objects/${v}.json`]=b}g.engine&&(g.engine.runtime&&(h["engine/engine.runtime.json"]=g.engine.runtime),g.engine.assets&&(h["engine/engine.assets.json"]=g.engine.assets),g.engine.splash&&(h["engine/engine.splash.json"]=g.engine.splash),g.engine.loading&&(h["engine/engine.loading.json"]=g.engine.loading),g.engine.start&&(h["engine/engine.start.json"]=g.engine.start),g.engine.tutorial&&(h["engine/engine.tutorial.json"]=g.engine.tutorial),g.engine.endgame&&(h["engine/engine.endgame.json"]=g.engine.endgame),!g.engine.runtime&&!g.engine.assets&&(h["engine/engine.json"]=g.engine));for(let[f,y]of Object.entries(g.scenes)){let b=f.startsWith("scene.")?f:`scene.${f}`;h[`scenes/${b}.json`]=y}let m=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:h,assets:{}})});if(!m.ok){let f=await m.json();throw new Error(f.error||"Apply to base failed")}ge(),this.showSuccessNotification(),this.refreshPanel(),await this.forceResyncAfterApply()}catch(g){console.error("[ConfigPersistence] Apply to base failed:",g),alert(`\u274C Apply to base failed: ${g.message}`),i.textContent="\u{1F527} APPLY TO BASE (No Version)",i.removeAttribute("disabled")}});let a=this.container.querySelector("#version-selector");a==null||a.addEventListener("change",async u=>{let h=u.target.value;await this.switchVersion(h)}),this.container.querySelectorAll(".item-remove").forEach(u=>{u.addEventListener("click",()=>{let g=u.dataset.removePath,h=u.dataset.removeId;$t(h||void 0,g)})});let o=this.container.querySelector("#clear-all-overrides"),l=this.container.querySelector("#discard-all-overrides-btn"),c=()=>{confirm("Discard all staged changes? This will clear all overrides and reload from current Source.")&&(ge(),Dt(),this.refreshPanel())};o==null||o.addEventListener("click",c),l==null||l.addEventListener("click",c);let d=this.container.querySelector("#reset-to-applied-btn");d==null||d.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Dt()});let p=this.container.querySelector("#reset-to-original-btn");p==null||p.addEventListener("click",async()=>{await Ln()})}showSuccessNotification(e){let t=document.createElement("div");t.className="persistence-notification success";let n=e&&e.trim().length>0?e.trim():"Changes Applied!";t.innerHTML=`
2052
2052
  <div class="notify-icon">\u2705</div>
2053
2053
  <div class="notify-content">
2054
2054
  <strong>${n}</strong>
2055
2055
  <span>Project files updated.</span>
2056
2056
  </div>
2057
- `,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){var i,a,r;let t=Be();if(t.hasChanges){if(!confirm(`Switch to version "${e||"original"}"?
2057
+ `,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){var i,a,r;let t=Fe();if(t.hasChanges){if(!confirm(`Switch to version "${e||"original"}"?
2058
2058
 
2059
2059
  You have ${t.overrideCount} staged changes that will be discarded.
2060
2060
 
2061
2061
  Options:
2062
2062
  OK = Discard staged overrides and switch
2063
- Cancel = Stay on current version`)){let l=(i=this.container)==null?void 0:i.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}}else if(!confirm(`Switch to version "${e||"original"}"?`)){let l=(a=this.container)==null?void 0:a.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}try{let o=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!o.ok){let l=await o.json();throw new Error(l.error||"Failed to switch version")}de(),localStorage.removeItem("handler_config_overrides"),localStorage.setItem("handler_preview_override_mode","false"),window.location.reload()}catch(o){alert(`\u274C Failed to switch version: ${o.message}`);let l=(r=this.container)==null?void 0:r.querySelector("#version-selector");l&&(l.value=this.currentVersion||"")}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
2063
+ Cancel = Stay on current version`)){let l=(i=this.container)==null?void 0:i.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}}else if(!confirm(`Switch to version "${e||"original"}"?`)){let l=(a=this.container)==null?void 0:a.querySelector("#version-selector");l&&(l.value=this.currentVersion||"");return}try{let o=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!o.ok){let l=await o.json();throw new Error(l.error||"Failed to switch version")}ge(),localStorage.removeItem("handler_config_overrides"),localStorage.setItem("handler_preview_override_mode","false"),window.location.reload()}catch(o){alert(`\u274C Failed to switch version: ${o.message}`);let l=(r=this.container)==null?void 0:r.querySelector("#version-selector");l&&(l.value=this.currentVersion||"")}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
2064
2064
 
2065
2065
  This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snapshot.
2066
2066
 
2067
2067
  This cannot be undone unless you have git commits or backups.
2068
2068
 
2069
- Are you absolutely sure?`))try{let t=ot(),n={};for(let[a,r]of Object.entries(t.objects)){let o=r,l=a;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${a}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=l),n[`objects/${l}.json`]=o}t.engine&&(t.engine.runtime&&(n["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(n["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(n["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(n["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(n["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(n["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(n["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(n["engine/engine.json"]=t.engine));for(let[a,r]of Object.entries(t.scenes)){let o=a.startsWith("scene.")?a:`scene.${a}`;n[`scenes/${o}.json`]=r}let i=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!i.ok){let a=await i.json();throw new Error(a.error||"Direct apply failed")}de(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var an=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new Wn;this.sceneToolsPanel=new Yn;this.nudgePanel=new Kn;this.inspectorPanel=new ci;this.libraryPanel=new Zt;this.libraryPanelDocked=new Zt;this.brandVisionPanel=new hi;this.customizeSettingsPanel=new mi;this.configPersistencePanel=new Ci;this.loadingScreenPanel=new fi}applyAssetChange(e,t){return Sr(this,e,t)}resetAsset(e){return Er(this,e)}applySlotAsset(e,t,n){return ui(this,e,t,n)}resetSlotAsset(e,t,n){return Cr(this,e,t,n)}startObjectVisuals(){return _r(this)}stopObjectVisuals(){return jr(this)}shouldRunObjectVisuals(){return yi(this)}updateObjectVisuals(){return bi(this)}getSelectedInstanceId(){return Ea(this)}getDisplayObjectById(e){return Ca(this,e)}getSelectedObjectConfig(){return nn(this)}getConfigAnchorWorldPoint(e){return Aa(this,e)}getScreenSize(){return La(this)}ensureBoundsGfx(){return Ta(this)}ensureAnchorGfx(){return ka(this)}drawBounds(e){return Pa(this,e)}drawAnchor(e){return Ma(this,e)}clearBounds(){return Ia(this)}clearAnchor(){return _a(this)}clearObjectVisuals(){return en(this)}updateObjectInfo(e){return Qt(this,e)}resetDebugConfig(){return wi(this)}applyDebugConfig(){return zr(this)}exportDebugConfig(){return xi(this)}loadObjectConfig(e){return $r(this,e)}fillConfigViewer(e){return vi(this,e)}copyConfigValues(){return Dr(this)}applyObjectConfig(e){return Oa(this,e)}applyCustomizeSettings(e,t){return Nr(this,e,t)}scheduleObjectAutoApply(){return Hr(this)}setupDebugEventListeners(){return Fr(this)}setupDebugInputListeners(e){return Da(this,e)}setupPanelLayout(){return Br(this)}setupCollapsiblePanels(e){return Na(this,e)}setupRangeInput(e,t,n,i){return ge(this,e,t,n,i)}updateWorkbenchTabs(){return $a(this)}saveWorkbenchState(){return kt(this)}loadWorkbenchState(){return Ei(this)}initialize(e){var i;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let a=localStorage.getItem("preview_workbench_state");if(a){let r=JSON.parse(a);r.activeTab&&(this.activeTab=r.activeTab)}}catch(a){console.warn("[PREVIEW] Failed to load workbench tab state",a)}this.sceneObjectsPanel.initialize(e,{onSelect:a=>this.handleObjectSelect(a)}),this.libraryPanel.initialize(e,{onApply:(a,r,o)=>this.applySlotAsset(a,r,o),onReset:(a,r,o)=>this.resetSlotAsset(a,r,o)});let t=e.querySelector("#dock-library-content");t&&(t.innerHTML=this.libraryPanelDocked.render(),this.libraryPanelDocked.initialize(t,{onApply:(a,r,o)=>this.applySlotAsset(a,r,o),onReset:(a,r,o)=>this.resetSlotAsset(a,r,o)})),this.inspectorPanel.initialize(e,{onPropertyChange:(a,r,o)=>{console.log("[Inspector] Property changed:",a,r,o)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let a="/dashboard";window.location.pathname!==a&&(window.location.href=a)}),this.customizeSettingsPanel.initialize(e,{onApply:(a,r)=>this.applyCustomizeSettings(a,r)}),this.sceneToolsPanel.initialize(e,{onHighlightObject:a=>{this.highlightObject=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:a=>{this.highlightAnchor=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(a,r)=>this.nudgeSelectedObject(a,r),onShowSplash:()=>{let a=window;typeof a.__previewShowSplash=="function"&&a.__previewShowSplash()},onUpdateSplash:a=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({splash:a})}}),this.nudgePanel.initialize(e,{onNudge:async(a,r)=>{var u,g,h;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let l=(u=o.transform)==null?void 0:u.position,c=((g=l==null?void 0:l.x)!=null?g:0)+a,d=((h=l==null?void 0:l.y)!=null?h:0)+r,{applyConfigOverride:p}=await Promise.resolve().then(()=>(Z(),Ue));p({objectId:this.selectedObjectId,path:"transform.position",value:{x:c,y:d}},{silent:!0,emitEvent:!0}),window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async a=>{var d,p;if(!this.selectedObjectId)return;let r=this.getSelectedObjectConfig();if(!r)return;let o=(p=(d=r.transform)==null?void 0:d.scale)!=null?p:1,l=Math.max(.1,o+a),{applyConfigOverride:c}=await Promise.resolve().then(()=>(Z(),Ue));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0}),window.dispatchEvent(new CustomEvent("inspector:refresh"))}});let n=e.querySelector("#debug-nudge-enabled");n==null||n.addEventListener("change",()=>{n.checked?this.nudgePanel.show():this.nudgePanel.hide()}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let a=window;typeof a.__previewShowLoading=="function"?a.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let a=window;typeof a.__previewHideLoading=="function"?a.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:a=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({loading:a}),typeof r.__previewUpdateLoading=="function"?r.__previewUpdateLoading(a):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(a,r,o,l)=>{this.customizeSettingsPanel.openAiEditor(a,r,o,l)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=a=>this.selectObject(a),window.addEventListener("config:changed",a=>{var r,o;((r=a.detail)==null?void 0:r.action)!=="remove"&&((o=a.detail)==null?void 0:o.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(a,r,o)=>this.applySlotAsset(a,r,o),window.refreshAssetLibrary=()=>Promise.all([this.libraryPanel.refresh(),this.libraryPanelDocked.refresh()]),window.reRenderAssetLibrary=()=>{this.libraryPanel.reRender(),this.libraryPanelDocked.reRender()},window.getEngineSplashConfig=()=>{var r;let a=window.getActiveConfig;if(typeof a=="function"){let o=a();return((r=o==null?void 0:o.engine)==null?void 0:r.splash)||null}return null},window.addAssetToRegistry=(a,r)=>{let o=window.getEditableAssets;if(typeof o=="function"){let l=o();if(l!=null&&l.libraryAssets&&(l.libraryAssets[a]||(l.libraryAssets[a]=[]),!l.libraryAssets[a].some(d=>d.filename===r))){let d=r.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");l.libraryAssets[a].unshift({filename:r,displayName:d}),console.log(`[DEBUG] Added ${r} to registry category ${a}`)}}},window.__highlightLibrarySlot=(a,r)=>{this.libraryPanel.highlightSlot(a,r),this.libraryPanelDocked.highlightSlot(a,r)}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&this.activeTab!=="ai"&&this.setActiveTab("inspector")}setActiveTab(e){this.activeTab=e,this.updateWorkbenchTabs(),this.saveWorkbenchState()}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
2069
+ Are you absolutely sure?`))try{let t=et(),n={};for(let[a,r]of Object.entries(t.objects)){let o=r,l=a;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${a}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=l),n[`objects/${l}.json`]=o}t.engine&&(t.engine.runtime&&(n["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(n["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(n["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(n["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(n["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(n["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(n["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(n["engine/engine.json"]=t.engine));for(let[a,r]of Object.entries(t.scenes)){let o=a.startsWith("scene.")?a:`scene.${a}`;n[`scenes/${o}.json`]=r}let i=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!i.ok){let a=await i.json();throw new Error(a.error||"Direct apply failed")}ge(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Wt=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new $n;this.sceneToolsPanel=new Dn;this.nudgePanel=new Nn;this.inspectorPanel=new Qn;this.libraryPanel=new Bt;this.libraryPanelDocked=new Bt;this.brandVisionPanel=new ai;this.customizeSettingsPanel=new si;this.configPersistencePanel=new hi;this.loadingScreenPanel=new ri}applyAssetChange(e,t){return hr(this,e,t)}resetAsset(e){return mr(this,e)}applySlotAsset(e,t,n){return ni(this,e,t,n)}resetSlotAsset(e,t,n){return fr(this,e,t,n)}startObjectVisuals(){return Cr(this)}stopObjectVisuals(){return Ar(this)}shouldRunObjectVisuals(){return oi(this)}updateObjectVisuals(){return li(this)}getSelectedInstanceId(){return ma(this)}getDisplayObjectById(e){return fa(this,e)}getSelectedObjectConfig(){return Vt(this)}getConfigAnchorWorldPoint(e){return ya(this,e)}getScreenSize(){return ba(this)}ensureBoundsGfx(){return va(this)}ensureAnchorGfx(){return wa(this)}drawBounds(e){return xa(this,e)}drawAnchor(e){return Sa(this,e)}clearBounds(){return Ea(this)}clearAnchor(){return Ca(this)}clearObjectVisuals(){return Ut(this)}updateObjectInfo(e){return Gt(this,e)}resetDebugConfig(){return di(this)}applyDebugConfig(){return kr(this)}exportDebugConfig(){return pi(this)}loadObjectConfig(e){return Pr(this,e)}fillConfigViewer(e){return ci(this,e)}copyConfigValues(){return Ir(this)}applyObjectConfig(e){return La(this,e)}applyCustomizeSettings(e,t){return Mr(this,e,t)}scheduleObjectAutoApply(){return _r(this)}setupDebugEventListeners(){return jr(this)}setupDebugInputListeners(e){return Ia(this,e)}setupPanelLayout(){return Or(this)}setupCollapsiblePanels(e){return Ma(this,e)}setupRangeInput(e,t,n,i){return ye(this,e,t,n,i)}updateWorkbenchTabs(){return Pa(this)}saveWorkbenchState(){return bt(this)}loadWorkbenchState(){return gi(this)}initialize(e){var i;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let a=localStorage.getItem("preview_workbench_state");if(a){let r=JSON.parse(a);r.activeTab&&(this.activeTab=r.activeTab)}}catch(a){console.warn("[PREVIEW] Failed to load workbench tab state",a)}this.sceneObjectsPanel.initialize(e,{onSelect:a=>this.handleObjectSelect(a)}),this.libraryPanel.initialize(e,{onApply:(a,r,o)=>this.applySlotAsset(a,r,o),onReset:(a,r,o)=>this.resetSlotAsset(a,r,o)});let t=e.querySelector("#dock-library-content");t&&(t.innerHTML=this.libraryPanelDocked.render(),this.libraryPanelDocked.initialize(t,{onApply:(a,r,o)=>this.applySlotAsset(a,r,o),onReset:(a,r,o)=>this.resetSlotAsset(a,r,o)})),this.inspectorPanel.initialize(e,{onPropertyChange:(a,r,o)=>{console.log("[Inspector] Property changed:",a,r,o)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let a="/dashboard";window.location.pathname!==a&&(window.location.href=a)}),this.customizeSettingsPanel.initialize(e,{onApply:(a,r)=>this.applyCustomizeSettings(a,r)}),this.sceneToolsPanel.initialize(e,{onHighlightObject:a=>{this.highlightObject=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:a=>{this.highlightAnchor=a,a?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(a,r)=>this.nudgeSelectedObject(a,r),onShowSplash:()=>{let a=window;typeof a.__previewShowSplash=="function"&&a.__previewShowSplash()},onUpdateSplash:a=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({splash:a})}}),this.nudgePanel.initialize(e,{onNudge:async(a,r)=>{var u,g,h;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let l=(u=o.transform)==null?void 0:u.position,c=((g=l==null?void 0:l.x)!=null?g:0)+a,d=((h=l==null?void 0:l.y)!=null?h:0)+r,{applyConfigOverride:p}=await Promise.resolve().then(()=>(te(),Be));p({objectId:this.selectedObjectId,path:"transform.position",value:{x:c,y:d}},{silent:!0,emitEvent:!0}),window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async a=>{var d,p;if(!this.selectedObjectId)return;let r=this.getSelectedObjectConfig();if(!r)return;let o=(p=(d=r.transform)==null?void 0:d.scale)!=null?p:1,l=Math.max(.1,o+a),{applyConfigOverride:c}=await Promise.resolve().then(()=>(te(),Be));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0}),window.dispatchEvent(new CustomEvent("inspector:refresh"))}});let n=e.querySelector("#debug-nudge-enabled");n==null||n.addEventListener("change",()=>{n.checked?this.nudgePanel.show():this.nudgePanel.hide()}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let a=window;typeof a.__previewShowLoading=="function"?a.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let a=window;typeof a.__previewHideLoading=="function"?a.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:a=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({loading:a}),typeof r.__previewUpdateLoading=="function"?r.__previewUpdateLoading(a):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(a,r,o,l)=>{this.customizeSettingsPanel.openAiEditor(a,r,o,l)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=a=>this.selectObject(a),window.addEventListener("config:changed",a=>{var r,o;((r=a.detail)==null?void 0:r.action)!=="remove"&&((o=a.detail)==null?void 0:o.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(a,r,o)=>this.applySlotAsset(a,r,o),window.refreshAssetLibrary=()=>Promise.all([this.libraryPanel.refresh(),this.libraryPanelDocked.refresh()]),window.reRenderAssetLibrary=()=>{this.libraryPanel.reRender(),this.libraryPanelDocked.reRender()},window.getEngineSplashConfig=()=>{var r;let a=window.getActiveConfig;if(typeof a=="function"){let o=a();return((r=o==null?void 0:o.engine)==null?void 0:r.splash)||null}return null},window.addAssetToRegistry=(a,r)=>{let o=window.getEditableAssets;if(typeof o=="function"){let l=o();if(l!=null&&l.libraryAssets&&(l.libraryAssets[a]||(l.libraryAssets[a]=[]),!l.libraryAssets[a].some(d=>d.filename===r))){let d=r.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");l.libraryAssets[a].unshift({filename:r,displayName:d}),console.log(`[DEBUG] Added ${r} to registry category ${a}`)}}},window.__highlightLibrarySlot=(a,r)=>{this.libraryPanel.highlightSlot(a,r),this.libraryPanelDocked.highlightSlot(a,r)}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&this.activeTab!=="ai"&&this.setActiveTab("inspector")}setActiveTab(e){this.activeTab=e,this.updateWorkbenchTabs(),this.saveWorkbenchState()}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
2070
2070
  <div class="debug-overlay hidden" id="debug-overlay">
2071
2071
  <div class="debug-workbench" id="debug-workbench">
2072
2072
  <div class="workbench-header" id="workbench-handle">
@@ -2113,7 +2113,7 @@ Are you absolutely sure?`))try{let t=ot(),n={};for(let[a,r]of Object.entries(t.o
2113
2113
  ${this.sceneToolsPanel.render()}
2114
2114
  ${this.nudgePanel.render()}
2115
2115
  </div>
2116
- `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals(),window.dispatchEvent(new CustomEvent("preview:select",{detail:{objectId:e}}))}async nudgeSelectedObject(e,t){var o,l,c,d;let n=this.sceneObjectsPanel.getSelectedIds();if(n.length===0)return;let i=this.nudgePanel.getNudgeStep();if(n.length===1&&this.container){let p=this.container.querySelector("#config-pos-x"),u=this.container.querySelector("#config-pos-y");if(p&&u){let g=Number((o=p.value)!=null?o:0),h=Number((l=u.value)!=null?l:0),m=g+e*i,f=h+t*i;p.value=String(m),u.value=String(f),(c=this.configViewer)==null||c.style.setProperty("display","block"),this.scheduleObjectAutoApply();return}}let a=window.getEditableObjectConfig;if(typeof a!="function")return;let r=new qe;for(let p of n){let u=a(p);if(!u)continue;let g=((d=u.transform)==null?void 0:d.position)||[0,0],h=Array.isArray(g)?g[0]:g.x||0,m=Array.isArray(g)?g[1]:g.y||0,f=h+e*i,y=m+t*i;await r.updateProperty(p,"transform.position",[f,y])}n.length===1&&this.selectedObjectId===n[0]&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}};function Tl(s){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(s)})}function kl(s){var i;let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}function Pl(s){return`
2116
+ `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals(),window.dispatchEvent(new CustomEvent("preview:select",{detail:{objectId:e}}))}async nudgeSelectedObject(e,t){var o,l,c,d;let n=this.sceneObjectsPanel.getSelectedIds();if(n.length===0)return;let i=this.nudgePanel.getNudgeStep();if(n.length===1&&this.container){let p=this.container.querySelector("#config-pos-x"),u=this.container.querySelector("#config-pos-y");if(p&&u){let g=Number((o=p.value)!=null?o:0),h=Number((l=u.value)!=null?l:0),m=g+e*i,f=h+t*i;p.value=String(m),u.value=String(f),(c=this.configViewer)==null||c.style.setProperty("display","block"),this.scheduleObjectAutoApply();return}}let a=window.getEditableObjectConfig;if(typeof a!="function")return;let r=new Ue;for(let p of n){let u=a(p);if(!u)continue;let g=((d=u.transform)==null?void 0:d.position)||[0,0],h=Array.isArray(g)?g[0]:g.x||0,m=Array.isArray(g)?g[1]:g.y||0,f=h+e*i,y=m+t*i;await r.updateProperty(p,"transform.position",[f,y])}n.length===1&&this.selectedObjectId===n[0]&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}};function vl(s){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(s)})}function wl(s){var i;let[e,t]=s.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(i=n==null?void 0:n[1])!=null?i:"image/png"}}function xl(s){return`
2117
2117
  Analyze these screenshots of a brand or game and extract its "Brand DNA".
2118
2118
 
2119
2119
  Provide a concise summary (2-3 sentences) covering:
@@ -2130,9 +2130,9 @@ Palette: [#RRGGBB, #RRGGBB, ...]
2130
2130
  ${s?`
2131
2131
  ADDITIONAL RULES/NOTES:
2132
2132
  ${s}`:""}
2133
- `.trim()}function Ur(){let s=[],e="",t=null;return{async addSources(n){let i=[];for(let a of n){let r=await Tl(a),o=kl(r),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:r};s.push(l),i.push(l)}return i},getSources(){return s.slice()},async analyze(n,i,a){if(s.length===0)throw new Error("No screenshots to analyze.");let r=Pl(i),o=s.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await pi(n,r,o,{model:a}),c=e,d=[],p=l.split(`
2133
+ `.trim()}function Rr(){let s=[],e="",t=null;return{async addSources(n){let i=[];for(let a of n){let r=await vl(a),o=wl(r),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:r};s.push(l),i.push(l)}return i},getSources(){return s.slice()},async analyze(n,i,a){if(s.length===0)throw new Error("No screenshots to analyze.");let r=xl(i),o=s.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await ti(n,r,o,{model:a}),c=e,d=[],p=l.split(`
2134
2134
  `);for(let u of p)if(u.toLowerCase().startsWith("summary:"))c=u.slice(8).trim();else if(u.toLowerCase().includes("palette:")){let g=u.match(/#[0-9A-Fa-f]{6}/g);g&&g.forEach(h=>{d.includes(h.toUpperCase())||d.push(h.toUpperCase())})}return(!c||c===e)&&(c=l.split(`
2135
- Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:d.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var ut="handler_api_key_";var Pt=class{static setKey(e,t,n){try{let i={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},a=`${ut}${e}`;localStorage.setItem(a,JSON.stringify(i))}catch(i){console.error("[ApiKeyStorage] Failed to store API key:",i)}}static getKey(e){try{let t=`${ut}${e}`,n=localStorage.getItem(t);if(!n)return null;let i=JSON.parse(n);return i.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(i)),this.decryptKey(i.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${ut}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${ut}${e}`;localStorage.removeItem(t)}catch(t){console.error("[ApiKeyStorage] Failed to remove API key:",t)}}static getStoredServices(){let e=[];try{for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(ut)){let i=n.substring(ut.length),a=localStorage.getItem(n);if(a){let r=JSON.parse(a);e.push({service:i,label:r.label,created:r.created,lastUsed:r.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,n)=>n.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(ut)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let n="handler_preview_salt_2024"+e;return btoa(n)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),n="handler_preview_salt_2024";return t.startsWith(n)?t.substring(n.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},Ha=()=>Pt.getKey("gemini"),Fa=(s,e)=>Pt.setKey("gemini",s,e),Ml=()=>Pt.hasKey("gemini");window.ApiKeyStorage=Pt;window.getGeminiApiKey=Ha;window.setGeminiApiKey=Fa;window.hasGeminiApiKey=Ml;var Ua=class{constructor(){this.modal=null;this.options=null;this.analyzer=Ur();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(e){this.options=e,this.currentPrompt=e.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var t,n;(t=this.promptInput)==null||t.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
2135
+ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:d.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var st="handler_api_key_";var vt=class{static setKey(e,t,n){try{let i={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},a=`${st}${e}`;localStorage.setItem(a,JSON.stringify(i))}catch(i){console.error("[ApiKeyStorage] Failed to store API key:",i)}}static getKey(e){try{let t=`${st}${e}`,n=localStorage.getItem(t);if(!n)return null;let i=JSON.parse(n);return i.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(i)),this.decryptKey(i.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${st}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${st}${e}`;localStorage.removeItem(t)}catch(t){console.error("[ApiKeyStorage] Failed to remove API key:",t)}}static getStoredServices(){let e=[];try{for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(st)){let i=n.substring(st.length),a=localStorage.getItem(n);if(a){let r=JSON.parse(a);e.push({service:i,label:r.label,created:r.created,lastUsed:r.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,n)=>n.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(st)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let n="handler_preview_salt_2024"+e;return btoa(n)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),n="handler_preview_salt_2024";return t.startsWith(n)?t.substring(n.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},_a=()=>vt.getKey("gemini"),ja=(s,e)=>vt.setKey("gemini",s,e),Sl=()=>vt.hasKey("gemini");window.ApiKeyStorage=vt;window.getGeminiApiKey=_a;window.setGeminiApiKey=ja;window.hasGeminiApiKey=Sl;var Ra=class{constructor(){this.modal=null;this.options=null;this.analyzer=Rr();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(e){this.options=e,this.currentPrompt=e.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var t,n;(t=this.promptInput)==null||t.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
2136
2136
  <div class="ai-modal-card">
2137
2137
  <div class="ai-modal-header">
2138
2138
  <div class="ai-modal-actions">
@@ -2213,12 +2213,12 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:d.slice(0
2213
2213
  </div>
2214
2214
  `,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var n;if(!this.modal)return;this.promptInput=this.modal.querySelector(".ai-textarea"),this.generateBtn=this.modal.querySelector('[data-action="generate"]'),this.loadingEl=this.modal.querySelector("[data-loading]"),this.galleryEl=this.modal.querySelector("[data-gallery]"),this.previewEl=this.modal.querySelector("[data-preview]"),(n=this.promptInput)==null||n.addEventListener("input",()=>{var i;this.currentPrompt=((i=this.promptInput)==null?void 0:i.value)||"",this.updateGenerateButton()});let e=this.modal.querySelector('[data-strength="creativity"]'),t=this.modal.querySelector(".ai-strength-value");e==null||e.addEventListener("input",()=>{t.textContent=e.value}),this.modal.addEventListener("click",i=>{var o;let a=i.target;switch(a.dataset.action||((o=a.closest("[data-action]"))==null?void 0:o.getAttribute("data-action"))){case"generate":this.generateImage();break;case"apply":this.applySelectedImage();break;case"gallery":this.toggleGallery();break;case"close":case"cancel":this.close();break}}),this.modal.addEventListener("click",i=>{let a=i.target;if(a.classList.contains("ai-gallery-item")||a.closest(".ai-gallery-item")){let r=a.closest(".ai-gallery-item"),o=parseInt(r.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.updateGenerateButton()}updateGenerateButton(){if(!this.generateBtn)return;let e=this.currentPrompt.trim().length>0;this.generateBtn.disabled=!e||this.isGenerating}async updatePromptFromDna(){var t;let e=(t=this.modal)==null?void 0:t.querySelector("#ai-use-dna");if(e!=null&&e.checked)try{let n=this.analyzer.getResult();if(n!=null&&n.summary&&this.promptInput){let i=`${this.currentPrompt}
2215
2215
 
2216
- Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,i;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(e=this.loadingEl)==null||e.classList.remove("hidden"),(t=this.previewEl)==null||t.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let r=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await di(this.options.currentValue);c&&(r=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await Lt(a,this.currentPrompt,r,{aspectRatio:"1:1"}),l=await At(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(i=this.previewEl)==null||i.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let e=this.galleryEl.querySelector("[data-gallery-grid]");e&&(e.innerHTML=this.generatedImages.map((t,n)=>`
2216
+ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,i;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(e=this.loadingEl)==null||e.classList.remove("hidden"),(t=this.previewEl)==null||t.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let r=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await ei(this.options.currentValue);c&&(r=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await ft(a,this.currentPrompt,r,{aspectRatio:"1:1"}),l=await mt(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(i=this.previewEl)==null||i.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let e=this.galleryEl.querySelector("[data-gallery-grid]");e&&(e.innerHTML=this.generatedImages.map((t,n)=>`
2217
2217
  <div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
2218
2218
  <img class="ai-gallery-thumb" src="${t}" alt="Generated ${n+1}" />
2219
2219
  <div class="ai-gallery-label">#${n+1}</div>
2220
2220
  </div>
2221
- `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let e=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${e}" alt="Selected image" />`}selectImage(e){e<0||e>=this.generatedImages.length||(this.selectedImageIndex=e,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var t;let e=(t=this.modal)==null?void 0:t.querySelector('[data-action="apply"]');e&&(e.disabled=this.selectedImageIndex<0)}applySelectedImage(){var t;if(this.selectedImageIndex<0||!((t=this.options)!=null&&t.onApply))return;let e=this.generatedImages[this.selectedImageIndex];this.options.onApply(e),this.close()}getApiKey(){let e=Ha();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return Fa(t.apiKey,"From Brand DNA"),t.apiKey}catch(t){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",t)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},Ba=null;window.__openAiEditor=function(s,e,t,n){Ba||(Ba=new Ua),Ba.open({objectId:s,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:i=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(s,n.path,i);else{let r=window.getEditableObjectConfig,o=r==null?void 0:r(s);if(o){let l=n.path.split("."),c=o;for(let d=0;d<l.length-1;d++)c[l[d]]||(c[l[d]]={}),c=c[l[d]];c[l[l.length-1]]=i}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};qa();var Va=class{constructor(){this.modal=null;this.options=null}open(e){this.options=e,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:e,assetType:t,objectId:n}=this.options,i=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
2221
+ `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let e=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${e}" alt="Selected image" />`}selectImage(e){e<0||e>=this.generatedImages.length||(this.selectedImageIndex=e,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var t;let e=(t=this.modal)==null?void 0:t.querySelector('[data-action="apply"]');e&&(e.disabled=this.selectedImageIndex<0)}applySelectedImage(){var t;if(this.selectedImageIndex<0||!((t=this.options)!=null&&t.onApply))return;let e=this.generatedImages[this.selectedImageIndex];this.options.onApply(e),this.close()}getApiKey(){let e=_a();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return ja(t.apiKey,"From Brand DNA"),t.apiKey}catch(t){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",t)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},Oa=null;window.__openAiEditor=function(s,e,t,n){Oa||(Oa=new Ra),Oa.open({objectId:s,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:i=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(s,n.path,i);else{let r=window.getEditableObjectConfig,o=r==null?void 0:r(s);if(o){let l=n.path.split("."),c=o;for(let d=0;d<l.length-1;d++)c[l[d]]||(c[l[d]]={}),c=c[l[d]];c[l[l.length-1]]=i}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};$a();var Da=class{constructor(){this.modal=null;this.options=null}open(e){this.options=e,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:e,assetType:t,objectId:n}=this.options,i=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
2222
2222
  <div class="asset-preview-card">
2223
2223
  <div class="asset-preview-header">
2224
2224
  <div class="asset-preview-title">${i}</div>
@@ -2245,7 +2245,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2245
2245
  <source src="${i}" type="audio/wav">
2246
2246
  Your browser does not support the audio element.
2247
2247
  </audio>
2248
- `;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",n=>{let i=n.target;(i.dataset.action==="close"||i===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(()=>(qa(),Gr)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(n),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 n;(n=this.options)!=null&&n.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(s){new Va().open(s)};var Wa=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(e){this.options=e,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let e=document.createElement("div");e.className="asset-crop-modal",e.innerHTML=`
2248
+ `;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",n=>{let i=n.target;(i.dataset.action==="close"||i===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(()=>($a(),zr)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(n),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 n;(n=this.options)!=null&&n.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(s){new Da().open(s)};var Na=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(e){this.options=e,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let e=document.createElement("div");e.className="asset-crop-modal",e.innerHTML=`
2249
2249
  <div class="asset-crop-card">
2250
2250
  <div class="asset-crop-header">
2251
2251
  <div>
@@ -2296,7 +2296,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2296
2296
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
2297
2297
  </div>
2298
2298
  </div>
2299
- `,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,n=this.cropWidth*this.scale,i=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,r=Math.min(i,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,d=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var i;if(!this.image||!((i=this.options)!=null&&i.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=e.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(s){new Wa().open(s)};Z();var $=require("pixi.js");Z();var Ai=class{constructor(e){this.app=null;this.camera=new $.Container;this.mainContainer=new $.Container;this.uiContainer=new $.Container;this.gizmoLayer=new $.Container;this.screenFrame=new $.Graphics;this.gameFrame=new $.Graphics;this.gridLayer=new $.Graphics;this.spawnPointLayer=new $.Container;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new $.Graphics;this.anchorVisualizationLayer=new $.Graphics;this.moveHandle=new $.Graphics;this.scaleHandle=new $.Graphics;this.rotateHandle=new $.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!1;this.runtimeLayoutActive=!1;this.scalePollInterval=null;this.scalePollActive=!1;this.forcedScale=null;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:n}=e.detail;!t||!n||(this.hasUserCamera=!1,this.updateLayout({width:t,height:n}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:n}))};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let n=t.objectId,i=t.objectIds;if(n){this.syncFromConfig([n]);return}if(Array.isArray(i)&&i.length>0){this.syncFromConfig(i);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},n=t.objectId,i=t.texture;if(!n||!i)return;let a=this.objectMap.get(n);if(!a)return;let r=a.displayObject;if(r!=null&&r.texture)r.texture=i;else if(r!=null&&r.children){let c=r.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=i)}let o=this.getEditableObjectConfig(n);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var r;if(!this.isVisible)return;let t=(r=e==null?void 0:e.detail)!=null?r:{},n=Number(t.width),i=Number(t.height),a=Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var n,i;let t=(i=(n=e==null?void 0:e.detail)==null?void 0:n.objectId)!=null?i:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let n=this.getEventGlobalPoint(e);if(!n)return;let i=new $.Point(n.x,n.y),a=this.getPickCandidates(i);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=i,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(i,this.lastPickPoint)<=6,c=r-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,p=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=i,this.lastPickTime=r,this.setSelected(p),this.playModeEnabled||this.startDrag("move",e)};this.handleGridSettings=e=>{var a,r,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,n=(r=e==null?void 0:e.detail)==null?void 0:r.gap,i=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof n=="number"&&Number.isFinite(n)&&n>2&&(this.gridGap=n),typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i),this.updateGrid()};this.handlePlayMode=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&this.setPlayMode(t)};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal(!1)};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let n=t.x+this.spawnPointDrag.offset.x,i=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,n,i)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,n=this.getEditableObjectConfig(e),i=n?this.getSpawnPoints(n):null;n&&i&&(this.setNestedValue(n,"logic.props.spawnPoints",t),se({objectId:e,path:"logic.props.spawnPoints",value:i},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var a;if(!this.dragMode||!this.selectedId||!this.app||this.playModeEnabled)return;let t=this.objectMap.get(this.selectedId);if(!t)return;let n=(a=this.dragContainer)!=null?a:this.mainContainer,i=this.getPointerInContainer(e.clientX,e.clientY,n);if(!(!i||!this.dragStartPointer||!this.dragStartPos)){if(this.dragMode==="move"){let r=i.x-this.dragStartPointer.x,o=i.y-this.dragStartPointer.y,l=this.dragStartPos.x+r,c=this.dragStartPos.y+o;t.displayObject.position.set(l,c),this.updateLiveConfigPosition(l,c)}else if(this.dragMode==="scale"){let r=new $.Point(this.dragStartPos.x,this.dragStartPos.y),o=Math.max(1,this.distance(i,r)),l=Math.max(.05,this.dragStartScale*(o/this.dragStartDistance));t.displayObject.scale.set(l),this.updateLiveConfigScale(l)}else if(this.dragMode==="rotate"){let r=new $.Point(this.dragStartPos.x,this.dragStartPos.y),l=Math.atan2(i.y-r.y,i.x-r.x)-this.dragStartAngle,c=this.dragStartRotation+l;t.displayObject.rotation=c,this.updateLiveConfigRotation(c)}this.updateGizmos()}};this.onDragEnd=()=>{var n,i,a,r,o,l,c;if(!this.dragMode||!this.selectedId)return;let e=this.selectedId,t=this.getEditableObjectConfig(e);if(t){let d=(n=t.transform)!=null?n:{};if(t.transform||(t.transform=d),this.dragMode==="move"&&this.dragStartValue){let p=d.position,u=Array.isArray(p)?[Number((i=p[0])!=null?i:0),Number((a=p[1])!=null?a:0)]:{x:Number((r=p==null?void 0:p.x)!=null?r:0),y:Number((o=p==null?void 0:p.y)!=null?o:0)};this.applyFinalOverride(e,"transform.position",u,this.dragStartValue)}else this.dragMode==="scale"?this.applyFinalOverride(e,"transform.scale",(l=d.scale)!=null?l:1,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(e,"transform.rotation",(c=d.rotation)!=null?c:0,this.dragStartValue)}window.dispatchEvent(new CustomEvent("inspector:refresh")),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let n=Math.sign(e.deltaY)<0?1.1:.9,i=Math.min(6,Math.max(.1,this.cameraScale*n)),a=new $.Point(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=i,this.camera.scale.set(i);let o=this.camera.toGlobal(r);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,n=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+n),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){if(this.app)return;this.app=new $.Application,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden";let e=document.createElement("button");e.textContent="Force Play Mode Scale",e.style.position="absolute",e.style.top="10px",e.style.right="10px",e.style.zIndex="1000000",e.style.padding="8px 12px",e.style.backgroundColor="#3b82f6",e.style.color="white",e.style.border="none",e.style.borderRadius="4px",e.style.cursor="pointer",e.style.fontSize="12px",e.style.fontWeight="500",e.style.boxShadow="0 2px 4px rgba(0,0,0,0.2)",e.onmouseover=()=>{e.style.backgroundColor="#2563eb"},e.onmouseout=()=>{e.style.backgroundColor="#3b82f6"},e.onclick=()=>{this.forcePlayModeScale()},this.root.appendChild(e);let t=document.createElement("div");t.style.position="absolute",t.style.top="50px",t.style.right="10px",t.style.zIndex="1000000",t.style.backgroundColor="rgba(0, 0, 0, 0.7)",t.style.padding="12px",t.style.borderRadius="4px",t.style.minWidth="200px";let n=document.createElement("label");n.textContent="Force Scale:",n.style.display="block",n.style.color="white",n.style.fontSize="12px",n.style.marginBottom="8px",n.style.fontWeight="500",t.appendChild(n);let i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="10px";let a=document.createElement("input");a.type="range",a.min="0.1",a.max="5",a.step="0.01",a.value="1",a.style.flex="1",a.style.cursor="pointer";let r=document.createElement("span");r.textContent="1.00",r.style.color="white",r.style.fontSize="12px",r.style.minWidth="40px",r.style.textAlign="right",r.style.fontFamily="monospace";let o=document.createElement("button");o.textContent="Reset",o.style.padding="4px 8px",o.style.fontSize="11px",o.style.backgroundColor="#6b7280",o.style.color="white",o.style.border="none",o.style.borderRadius="3px",o.style.cursor="pointer",o.onmouseover=()=>{o.style.backgroundColor="#4b5563"},o.onmouseout=()=>{o.style.backgroundColor="#6b7280"},o.onclick=()=>{this.forcedScale=null,a.value="1",r.textContent="1.00";let l=this.getScreen();l!=null&&l.width&&(l!=null&&l.height)&&(this.updateLayout(l),this.syncFromConfig())},a.oninput=()=>{let l=parseFloat(a.value);this.forcedScale=l,r.textContent=l.toFixed(2);let c=this.getScreen();c!=null&&c.width&&(c!=null&&c.height)&&(this.updateLayout(c),this.syncFromConfig())},i.appendChild(a),i.appendChild(r),i.appendChild(o),t.appendChild(i),this.root.appendChild(t),window.__sceneEditorForcePlayModeScale=()=>{this.forcePlayModeScale()},window.__sceneEditorSetForcedScale=l=>{this.forcedScale=l,l!==null?(a.value=String(l),r.textContent=l.toFixed(2)):(a.value="1",r.textContent="1.00");let c=this.getScreen();c!=null&&c.width&&(c!=null&&c.height)&&(this.updateLayout(c),this.syncFromConfig())},this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),!this.isVisible&&this.app.ticker&&this.app.ticker.stop()}destroy(){var e;this.stopScalePolling(),delete window.__sceneEditorForcePlayModeScale,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("handler:layout-applied",this.handleLayoutApplied),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:play-mode",this.handlePlayMode),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}forcePlayModeScale(){console.log("[SceneEditor] forcePlayModeScale: forcing scale to match play mode");let e=this.getRuntimeLayoutReference();if(e)if(this.applyRuntimeTransform(e)){this.runtimeLayoutActive=!0,console.log("[SceneEditor] forcePlayModeScale: SUCCESS - scale applied",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y},runtimeLayoutActive:this.runtimeLayoutActive}),this.stopScalePolling();let n=this.getScreen();n!=null&&n.width&&(n!=null&&n.height)&&this.updateLayout(n)}else{console.log("[SceneEditor] forcePlayModeScale: FAILED - could not apply runtime transform");let n=this.getScreen();if(n!=null&&n.width&&(n!=null&&n.height)){let{designW:i,designH:a,scale:r}=this.getDesignDimensionsAndScale(n.width,n.height);console.log("[SceneEditor] forcePlayModeScale: using calculated scale fallback",{screen:{width:n.width,height:n.height},design:{width:i,height:a},scale:r}),this.mainContainer.position.set(n.width/2,n.height/2),this.uiContainer.position.set(n.width/2,n.height/2),this.mainContainer.scale.set(r),this.uiContainer.scale.set(r),this.mainContainer.pivot.set(0,0),this.uiContainer.pivot.set(0,0),this.mainContainer.rotation=0,this.uiContainer.rotation=0,this.runtimeLayoutActive=!1}}else{console.log("[SceneEditor] forcePlayModeScale: FAILED - no runtime reference found");let t=this.getScreen();if(t!=null&&t.width&&(t!=null&&t.height)){let{designW:n,designH:i,scale:a}=this.getDesignDimensionsAndScale(t.width,t.height);console.log("[SceneEditor] forcePlayModeScale: no runtime reference, using calculated scale",{screen:{width:t.width,height:t.height},design:{width:n,height:i},scale:a}),this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(a),this.uiContainer.scale.set(a),this.mainContainer.pivot.set(0,0),this.uiContainer.pivot.set(0,0),this.mainContainer.rotation=0,this.uiContainer.rotation=0,this.runtimeLayoutActive=!1}}this.updateGizmos()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("handler:layout-applied",this.handleLayoutApplied),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:play-mode",this.handlePlayMode),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.eventMode="static",this.moveHandle.cursor="move",this.scaleHandle.eventMode="static",this.scaleHandle.cursor="nwse-resize",this.rotateHandle.eventMode="static",this.rotateHandle.cursor="crosshair",this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t))}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(n=r.getBounds)==null?void 0:n.call(r);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=r.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof r.zIndex=="number"?r.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(r):0,u=c*1e6+d*1e3+p;t.push({id:i,order:u})}return t.sort((i,a)=>a.order-i.order),t.map(i=>i.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),n=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha")),i=window.localStorage.getItem(this.getSceneStorageKey("play_mode"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let a=Number(t);Number.isFinite(a)&&a>2&&(this.gridGap=a)}if(n!==null){let a=Number(n);Number.isFinite(a)&&a>=0&&a<=1&&(this.gridAlpha=a)}i!==null&&this.setPlayMode(i==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.playModeEnabled&&this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,r,o,l,c,d,p;let e=window.gameApp;if(e!=null&&e.renderer){let u=e.renderer.screen,g=Number((a=u==null?void 0:u.width)!=null?a:0),h=Number((r=u==null?void 0:u.height)!=null?r:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,y=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(y)&&y>0)return{width:f,height:y}}let t=document.querySelector(".game-container"),n=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),i=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:null}getRuntimeLayoutReference(){var a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,S,L,M,O,w,P,_,T,I,C,A,E,x,j,k,R,z,N,Y,B,G,Q,ht,mt,hn,H,me,Ee,De,Ce,Xe,ft,yt,Ae,bt;let e=window.__mainContainer;if(e){let ee=(r=(a=e.scale)==null?void 0:a.x)!=null?r:1,ne=(l=(o=e.scale)==null?void 0:o.y)!=null?l:ee,F=this.forcedScale!==null?this.forcedScale:ee,q=this.forcedScale!==null?this.forcedScale:ne;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{baseScale:{x:ee,y:ne},forcedScale:this.forcedScale,finalScale:{x:F,y:q},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y}}),this.forcedScale!==null?{scale:{x:F,y:q},position:{x:(u=(p=e.position)==null?void 0:p.x)!=null?u:0,y:(h=(g=e.position)==null?void 0:g.y)!=null?h:0},pivot:e.pivot?{x:e.pivot.x,y:e.pivot.y}:void 0}:e}let t=window.__screenManager;if(t){let ee=["gameplay","start","tutorial","endgame","loading"];for(let ne of ee){let F=(m=t.get)==null?void 0:m.call(t,ne);if(F!=null&&F.visible){let q=(f=F.getContentLayer)==null?void 0:f.call(F);if(q){let ae=(y=F.x)!=null?y:0,fe=(b=F.y)!=null?b:0,ye=(v=q.x)!=null?v:0,Je=(S=q.y)!=null?S:0,Le=(M=(L=q.scale)==null?void 0:L.x)!=null?M:1,Ze=(w=(O=q.scale)==null?void 0:O.y)!=null?w:Le,Qe=this.forcedScale!==null?this.forcedScale:Le,et=this.forcedScale!==null?this.forcedScale:Ze,tt=(_=(P=F.scale)==null?void 0:P.x)!=null?_:1,nt=(I=(T=F.scale)==null?void 0:T.y)!=null?I:1;return(tt!==1||nt!==1)&&console.warn("[SceneEditor] getRuntimeLayoutReference: WARNING - screen has scale!",{screenId:ne,screenScale:{x:tt,y:nt},contentLayerScale:{x:Le,y:Ze},forcedScale:this.forcedScale,finalScale:{x:Qe,y:et}}),console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:ne,contentLayerScale:{x:Le,y:Ze},forcedScale:this.forcedScale,finalScale:{x:Qe,y:et},screenScale:{x:tt,y:nt},position:{x:ae+ye,y:fe+Je},screenPos:{x:ae,y:fe},contentPos:{x:ye,y:Je}}),{scale:{x:Qe,y:et},position:{x:ae+ye,y:fe+Je},pivot:q.pivot?{x:q.pivot.x,y:q.pivot.y}:void 0}}}}for(let ne of ee){let F=(C=t.get)==null?void 0:C.call(t,ne);if(F){if(!F.visible&&typeof F.updateLayout=="function"){let ae=window.gameApp;if((A=ae==null?void 0:ae.renderer)!=null&&A.screen){let fe=ae.renderer.screen.width,ye=ae.renderer.screen.height;fe>0&&ye>0&&F.updateLayout(fe,ye)}}let q=(E=F.getContentLayer)==null?void 0:E.call(F);if(q){let ae=(x=F.x)!=null?x:0,fe=(j=F.y)!=null?j:0,ye=(k=q.x)!=null?k:0,Je=(R=q.y)!=null?R:0,Le=(N=(z=q.scale)==null?void 0:z.x)!=null?N:1,Ze=(B=(Y=q.scale)==null?void 0:Y.y)!=null?B:Le,Qe=this.forcedScale!==null?this.forcedScale:Le,et=this.forcedScale!==null?this.forcedScale:Ze,tt=(Q=(G=F.scale)==null?void 0:G.x)!=null?Q:1,nt=(mt=(ht=F.scale)==null?void 0:ht.y)!=null?mt:1;return(tt!==1||nt!==1)&&console.warn("[SceneEditor] getRuntimeLayoutReference: WARNING - screen has scale!",{screenId:ne,screenScale:{x:tt,y:nt},contentLayerScale:{x:Le,y:Ze},forcedScale:this.forcedScale,finalScale:{x:Qe,y:et}}),console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer (not visible)",{screenId:ne,visible:F.visible,contentLayerScale:{x:Le,y:Ze},forcedScale:this.forcedScale,finalScale:{x:Qe,y:et},screenScale:{x:tt,y:nt},position:{x:ae+ye,y:fe+Je},screenPos:{x:ae,y:fe},contentPos:{x:ye,y:Je}}),{scale:{x:Qe,y:et},position:{x:ae+ye,y:fe+Je},pivot:q.pivot?{x:q.pivot.x,y:q.pivot.y}:void 0}}}}}let n=window.gameApp,i=(hn=n==null?void 0:n.stage)!=null?hn:null;if(i){let ee=(me=(H=i.scale)==null?void 0:H.x)!=null?me:1,ne=(De=(Ee=i.scale)==null?void 0:Ee.y)!=null?De:ee,F=this.forcedScale!==null?this.forcedScale:ee,q=this.forcedScale!==null?this.forcedScale:ne;if(console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{baseScale:{x:ee,y:ne},forcedScale:this.forcedScale,finalScale:{x:F,y:q},position:{x:(Ce=i.position)==null?void 0:Ce.x,y:(Xe=i.position)==null?void 0:Xe.y}}),this.forcedScale!==null)return{scale:{x:F,y:q},position:{x:(yt=(ft=i.position)==null?void 0:ft.x)!=null?yt:0,y:(bt=(Ae=i.position)==null?void 0:Ae.y)!=null?bt:0},pivot:i.pivot?{x:i.pivot.x,y:i.pivot.y}:void 0}}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((l=n==null?void 0:n.getDisplayObject)==null?void 0:l.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.parent;if(!a)return null;let r=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return r&&o&&r===o?this.mainContainer:r&&typeof r.contains=="function"&&r.contains(a)?this.mainContainer:a===r||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,m,f,y,b,v;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=Number((o=(r=e.scale)==null?void 0:r.x)!=null?o:1),n=Number((c=(l=e.scale)==null?void 0:l.y)!=null?c:t),i=Number((p=(d=e.position)==null?void 0:d.x)!=null?p:0),a=Number((g=(u=e.position)==null?void 0:u.y)!=null?g:0);if(!Number.isFinite(t)||!Number.isFinite(n))return console.log("[SceneEditor] applyRuntimeTransform: invalid scale",{scaleX:t,scaleY:n}),!1;if(!Number.isFinite(i)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:i,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying",{playMode:this.playModeEnabled,scale:{x:t,y:n},position:{x:i,y:a},beforeScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.mainContainer.scale.set(t,n),this.uiContainer.scale.set(t,n),this.mainContainer.position.set(i,a),this.uiContainer.position.set(i,a),e.pivot&&((h=this.mainContainer.pivot)!=null&&h.set)&&((m=this.uiContainer.pivot)!=null&&m.set)){let S=Number((y=(f=e.pivot)==null?void 0:f.x)!=null?y:0),L=Number((v=(b=e.pivot)==null?void 0:b.y)!=null?v:0);Number.isFinite(S)&&Number.isFinite(L)&&(this.mainContainer.pivot.set(S,L),this.uiContainer.pivot.set(S,L))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getDesignDimensionsAndScale(e,t){var c,d,p,u;let n=this.getEditableConfig(),i=((d=(c=n==null?void 0:n.engine)==null?void 0:c.runtime)==null?void 0:d.layout)||{},a=t>e,r=(p=i.design_width_portrait)!=null?p:a?320:480,o=(u=i.design_height_portrait)!=null?u:a?480:320,l=Math.min(e/r,t/o);return{designW:r,designH:o,scale:l}}getEditableObjectConfig(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let n=this.getEditableConfig();return n!=null&&n.objects?typeof n.objects.get=="function"?(i=n.objects.get(e))!=null?i:null:(a=n.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let n=e();if(Array.isArray(n))return n}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let n=e!=null&&e.length?e:this.getEditableObjectIds(),i=new Set(n);if(!e)for(let a of Array.from(this.objectMap.keys()))i.has(a)||this.removeObject(a);for(let a of n){let r=this.getEditableObjectConfig(a);if(!r){this.removeObject(a);continue}await this.upsertObject(a,r)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var n,i;let t=this.objectMap.get(e);if(t){try{(i=(n=t.displayObject)==null?void 0:n.destroy)==null||i.call(n)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let n=this.getAssetKey(t),i=this.objectMap.get(e),a=this.isUiConfig(e,t),r=this.getRuntimeParentContainer(e),o=a?this.uiContainer:this.mainContainer,l=r!=null?r:o;if(!i||i.assetKey!==n||i.isUi!==a){i&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:n,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.updateObjectTransform(c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,y,b,v,S,L;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 ve.create(e,t,this.app);if(O instanceof $.Container)return O}}catch(M){console.warn("[SceneEditor] ObjectFactory failed for",e,M)}let n=t==null?void 0:t.ui,i=(d=t==null?void 0:t.render)!=null?d:{},a=(n==null?void 0:n.text)||(n==null?void 0:n.kind)==="text";if(!!i.background_color){let M=this.getScreen(),O=(p=M==null?void 0:M.width)!=null?p:0,w=(u=M==null?void 0:M.height)!=null?u:0,P=new $.Graphics,_=this.parseColor(i.background_color,0),T=typeof i.background_alpha=="number"?i.background_alpha:1;O>0&&w>0&&P.rect(0,0,O,w).fill({color:_,alpha:T});let I=new $.Container;return I.addChild(P),I}if(a){let M=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",O=new $.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(m=n==null?void 0:n.fontSize)!=null?m:16,fill:M,align:(f=n==null?void 0:n.align)!=null?f:"center",letterSpacing:(y=n==null?void 0:n.letterSpacing)!=null?y:0});return new $.Text({text:(b=n==null?void 0:n.text)!=null?b:"",style:O})}if((v=t==null?void 0:t.effects)!=null&&v.width||(S=t==null?void 0:t.effects)!=null&&S.height){let M=new $.Graphics,O=typeof t.effects.width=="number"?t.effects.width:100,w=typeof t.effects.height=="number"?t.effects.height:100,P=(L=t.effects.fill_color)!=null?L:"#ffffff",_=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,T=Number.parseInt(String(P).replace("#",""),16);return M.rect(0,0,O,w).fill({color:Number.isFinite(T)?T:16777215,alpha:_}),M}return new $.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let n=e.getLocalBounds();n&&n.width>0&&n.height>0&&(e.hitArea=new $.Rectangle(n.x,n.y,n.width,n.height))}}getAssetKey(e){var n;let t=(n=e==null?void 0:e.render)==null?void 0:n.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let n=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),i=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return n.includes("ui")||i.startsWith("ui")||i.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u,g,h;if(!e)return;let n=(r=t==null?void 0:t.render)!=null?r:{};typeof n.alpha=="number"&&(e.alpha=n.alpha),e.visible=n.visible!==!1,e.zIndex=typeof n.z_index=="number"?n.z_index:0;let i=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"bottom-right";i==="bottom-right"&&!((p=t==null?void 0:t.render)!=null&&p.anchor)&&!((u=t==null?void 0:t.transform)!=null&&u.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 bottom-right");let a=Ie(i,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}updateObjectTransform(e,t){var d;if(!e||this.playModeEnabled)return;let n=(d=t==null?void 0:t.transform)!=null?d:{},i=e.parent===this.uiContainer?this.uiContainer:this.mainContainer,a=this.getAnchorLocalPoint(n,i),r=this.getPositionOffset(n),o=this.getDynamicScaleMultiplier();a&&e.position.set(a.x+r.x,a.y+r.y);let l=typeof n.scale=="number"?n.scale:void 0;typeof l=="number"&&e.scale&&e.scale.set(l*o);let c=this.toRadians(typeof n.rotation=="number"?n.rotation:0);typeof e.rotation=="number"&&(e.rotation=c)}getAnchorLocalPoint(e,t=this.mainContainer){var p,u;let n=(p=this.getScreen())!=null?p:this.getRuntimeScreenSize();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let a=(e==null?void 0:e.position_ratio)!=null?An(n.width,n.height,e.position_ratio):Cn(n.width,n.height,(u=e==null?void 0:e.anchor)!=null?u:"top-right"),r=t.scale.x,o=t.position.x,l=t.position.y,c=(a.x-o)/r,d=(a.y-l)/r;return new $.Point(c,d)}getRuntimeWorldContainer(){let e=window.__contentContainer,t=window.__mainContainer,n=window.__worldLayer;if(n)return n;let i=e||t;if(i&&i.children){for(let a of i.children)if(a.__isWorldLayer||a.label==="worldLayer")return a}return null}getPositionOffset(e){var l,c,d,p,u,g,h,m;let t=e==null?void 0:e.position,n=e==null?void 0:e.offset,i=Array.isArray(t)?Number((l=t[0])!=null?l:0):Number((c=t==null?void 0:t.x)!=null?c:0),a=Array.isArray(t)?Number((d=t[1])!=null?d:0):Number((p=t==null?void 0:t.y)!=null?p:0),r=Array.isArray(n)?Number((u=n[0])!=null?u:0):Number((g=n==null?void 0:n.x)!=null?g:0),o=Array.isArray(n)?Number((h=n[1])!=null?h:0):Number((m=n==null?void 0:n.y)!=null?m:0);return{x:i+r,y:a+o}}updateLayout(e){var i;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;console.log("[SceneEditor] updateLayout: called",{playMode:this.playModeEnabled,screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},runtimeLayoutActive:this.runtimeLayoutActive}),this.startScalePolling();let n=this.getRuntimeLayoutReference();if(this.playModeEnabled){console.log("[SceneEditor] updateLayout: Play Mode ON - applying runtime transform");let a=this.applyRuntimeTransform(n);this.runtimeLayoutActive=a||this.runtimeLayoutActive,console.log("[SceneEditor] updateLayout: Play Mode ON - result",{appliedRuntime:a,runtimeLayoutActive:this.runtimeLayoutActive,finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})}else{console.log("[SceneEditor] updateLayout: Play Mode OFF - trying runtime transform");let a=this.runtimeLayoutActive;if(a&&n){let o=this.applyRuntimeTransform(n);if(o){console.log("[SceneEditor] updateLayout: Play Mode OFF - refreshed runtime layout",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.runtimeLayoutActive=!0;return}if(!o){console.log("[SceneEditor] updateLayout: Play Mode OFF - runtime refresh failed, keeping current scale");return}}let r=this.applyRuntimeTransform(n);if(this.runtimeLayoutActive=r,!r&&!a){let{designW:o,designH:l,scale:c}=this.getDesignDimensionsAndScale(t.width,t.height);console.log("[SceneEditor] updateLayout: Play Mode OFF - using calculated scale",{screen:{width:t.width,height:t.height},design:{width:o,height:l},scale:c}),this.mainContainer.position.set(t.width/2,t.height/2),this.uiContainer.position.set(t.width/2,t.height/2),this.mainContainer.scale.set(c),this.uiContainer.scale.set(c),this.mainContainer.pivot.set(0,0),this.uiContainer.pivot.set(0,0),this.mainContainer.rotation=0,this.uiContainer.rotation=0,this.runtimeLayoutActive=!1}else r&&console.log("[SceneEditor] updateLayout: Play Mode OFF - applied runtime",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.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),(i=this.app)!=null&&i.stage&&(this.app.stage.hitArea=new $.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}startScalePolling(){if(this.playModeEnabled||this.scalePollActive||this.runtimeLayoutActive){console.log("[SceneEditor] startScalePolling: skipped",{playMode:this.playModeEnabled,pollActive:this.scalePollActive,runtimeLayoutActive:this.runtimeLayoutActive});return}console.log("[SceneEditor] startScalePolling: starting polling"),this.scalePollActive=!0,this.scalePollInterval=window.setInterval(()=>{this.checkAndUpdateScale()},1e3)}stopScalePolling(){this.scalePollInterval!==null&&(console.log("[SceneEditor] stopScalePolling: stopping polling"),clearInterval(this.scalePollInterval),this.scalePollInterval=null),this.scalePollActive=!1}checkAndUpdateScale(){var a,r,o,l,c,d,p,u,g;if(this.playModeEnabled){console.log("[SceneEditor] checkAndUpdateScale: Play Mode ON, stopping polling"),this.stopScalePolling();return}let e=this.getRuntimeLayoutReference();if(!e){console.log("[SceneEditor] checkAndUpdateScale: no runtime reference, will retry in 1 second");return}let t=Number((r=(a=e.scale)==null?void 0:a.x)!=null?r:1),n=Number((l=(o=e.scale)==null?void 0:o.y)!=null?l:t);if(!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1&&e===((c=window.gameApp)==null?void 0:c.stage)){console.log("[SceneEditor] checkAndUpdateScale: invalid runtime scale (stage fallback), will retry in 1 second");return}if(this.applyRuntimeTransform(e)){console.log("[SceneEditor] checkAndUpdateScale: SUCCESS - runtime transform applied, stopping polling"),this.runtimeLayoutActive=!0,this.stopScalePolling();return}if(this.runtimeLayoutActive){let h=Number((p=(d=this.mainContainer.scale)==null?void 0:d.x)!=null?p:1),m=Number((g=(u=this.mainContainer.scale)==null?void 0:u.y)!=null?g:1);console.log("[SceneEditor] checkAndUpdateScale: comparing",{currentScale:{x:h,y:m},runtimeScale:{x:t,y:n},diff:{x:Math.abs(h-t),y:Math.abs(m-n)}}),Math.abs(h-t)>.001||Math.abs(m-n)>.001?(console.log("[SceneEditor] checkAndUpdateScale: SCALE CHANGED! Updating"),this.applyRuntimeTransform(e)):console.log("[SceneEditor] checkAndUpdateScale: no change, continuing polling")}else console.log("[SceneEditor] checkAndUpdateScale: runtime transform not applied yet, will retry in 1 second")}getDynamicScaleMultiplier(){var n,i,a,r,o,l;let e=this.getRuntimeLayoutReference();if(e&&e.scale)return Number((i=(n=e.scale.x)!=null?n:e.scale.y)!=null?i:1);let t=this.getRuntimeWorldContainer();if(t&&t.scale){let c=Number((r=(a=t.scale.x)!=null?a:t.scale.y)!=null?r:1),d=window.__contentContainer;if(d&&d.scale){let p=Number((l=(o=d.scale.x)!=null?o:d.scale.y)!=null?l:1);return c*p}return c}return 1}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,n=this.camera.toLocal(new $.Point(0,0)),i=this.camera.toLocal(new $.Point(t.width,t.height)),a=Math.min(n.x,i.x),r=Math.max(n.x,i.x),o=Math.min(n.y,i.y),l=Math.max(n.y,i.y),c=400,d=Math.ceil((r-a)/e),p=Math.ceil((l-o)/e),u=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(p/c)),h=Math.floor(a/u)*u,m=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let f=h;f<=r;f+=u)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(r,f);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){var n;let t=(n=e!=null?e:this.getScreen())!=null?n:this.getRuntimeScreenSize();!(t!=null&&t.width)||!(t!=null&&t.height)||this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height||(this.lastGameFrameSize={width:t.width,height:t.height},this.gameFrame.clear(),this.gameFrame.rect(0,0,t.width,t.height),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}setPlayMode(e){var n;if(this.playModeEnabled===e)return;console.log("[SceneEditor] setPlayMode: changing",{from:this.playModeEnabled,to:e,currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},runtimeLayoutActive:this.runtimeLayoutActive});let t=this.playModeEnabled;if(this.playModeEnabled=e,(n=this.app)!=null&&n.ticker)if(this.app.ticker.remove(this.syncFromGameObjects),e)this.app.ticker.add(this.syncFromGameObjects),this.stopScalePolling();else{let i=this.getRuntimeLayoutReference();i?this.applyRuntimeTransform(i)?(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserved runtime scale",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})):t&&this.mainContainer.scale.x!==1&&(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserving current scale (runtime apply failed)",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})):t&&this.mainContainer.scale.x!==1&&(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserving current scale (no runtime reference)",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})),this.startScalePolling()}e?(this.moveHandle.eventMode="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none",this.syncFromGameObjectsInternal(!0)):(this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static",this.syncFromConfig()),this.updateGizmos(),this.updateSpawnPointHandles()}syncFromGameObjectsInternal(e){var i,a,r,o,l,c,d,p;if(!this.app||!this.isVisible||!this.playModeEnabled&&!e)return;let t=window.gameObjectManager;if(!(t!=null&&t.get))return;let n=this.dragMode?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(n&&u===n)continue;let h=t.get(u),m=((i=h==null?void 0:h.getDisplayObject)==null?void 0:i.call(h))||(h==null?void 0:h.pixiObject)||h;if(!m)continue;let f=(r=(a=g.displayObject)==null?void 0:a.parent)!=null?r:this.mainContainer,y=new $.Point;if(typeof m.getGlobalPosition=="function"){m.getGlobalPosition(y);let M=f.toLocal(y,this.camera);g.displayObject.position.set(M.x,M.y)}else if(m.worldTransform){y.set(m.worldTransform.tx,m.worldTransform.ty);let M=f.toLocal(y,this.camera);g.displayObject.position.set(M.x,M.y)}let b=this.getWorldScale(m);if(b){let M=Number((l=(o=f.scale)==null?void 0:o.x)!=null?l:1)||1,O=Number((d=(c=f.scale)==null?void 0:c.y)!=null?d:1)||1,w=b.x/M,P=b.y/O;(p=g.displayObject.scale)!=null&&p.set?g.displayObject.scale.set(w,P):g.displayObject.scale&&(g.displayObject.scale.x=w,g.displayObject.scale.y=P)}let v=this.getWorldRotation(m);if(typeof v=="number"){let M=f?f.rotation:0;g.displayObject.rotation=v-M}let S=m.parent,L=typeof(S==null?void 0:S.getChildIndex)=="function"?S.getChildIndex(m):0;typeof m.zIndex=="number"?g.displayObject.zIndex=m.zIndex:Number.isFinite(L)&&(g.displayObject.zIndex=L)}this.updateGizmos()}getWorldScale(e){var a,r;let t=(r=e==null?void 0:e.worldTransform)!=null?r:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let n=Math.sqrt(t.a*t.a+t.b*t.b),i=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(n)||!Number.isFinite(i)?null:{x:n,y:i}}getWorldRotation(e){var n,i;let t=(i=e==null?void 0:e.worldTransform)!=null?i:(n=e==null?void 0:e.transform)==null?void 0:n.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=(a=this.getScreen())!=null?a:this.getRuntimeScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,n=this.app.renderer.height,i=Math.max(.01,Math.min(t/e.width,n/e.height));this.cameraScale=i,this.camera.scale.set(i),this.camera.position.set((t-e.width*i)/2,(n-e.height*i)/2)}updateGizmos(){var d,p;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(p=(d=e.displayObject).getBounds)==null?void 0:p.call(d);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new $.Point(t.x,t.y)),i=this.camera.toLocal(new $.Point(t.x+t.width,t.y+t.height)),a=i.x-n.x,r=i.y-n.y,o=n.x+a/2,l=n.y+r/2;if(this.gizmoOutline.clear(),this.gizmoOutline.rect(n.x,n.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.playModeEnabled){this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear();return}let c=10;this.moveHandle.clear(),this.moveHandle.circle(0,0,c/2),this.moveHandle.fill({color:16752394,alpha:.9}),this.moveHandle.position.set(o,l),this.scaleHandle.clear(),this.scaleHandle.rect(-c/2,-c/2,c,c),this.scaleHandle.fill({color:3900150,alpha:.9}),this.scaleHandle.position.set(i.x,i.y),this.rotateHandle.clear(),this.rotateHandle.circle(0,0,c/2),this.rotateHandle.fill({color:1096065,alpha:.9}),this.rotateHandle.position.set(o,n.y-20)}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((n,i)=>{let a=new $.Graphics;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let r=this.toCameraFromMain(n);a.position.set(r.x,r.y),a.cursor="move",a.eventMode=this.playModeEnabled?"none":"static",a.on("pointerdown",o=>this.startSpawnPointDrag(i,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var n;(n=t.destroy)==null||n.call(t)})}isSpawnerConfig(e){var n,i;return((n=e==null?void 0:e.logic)==null?void 0:n.id)==="Spawner"?!0:String(((i=e==null?void 0:e.identity)==null?void 0:i.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var n,i;let t=(i=(n=e==null?void 0:e.logic)==null?void 0:n.props)==null?void 0:i.spawnPoints;return Array.isArray(t)?t.map(a=>{var r,o;return{x:Number((r=a==null?void 0:a.x)!=null?r:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new $.Point(e.x,e.y)),n=new $.Point;return this.camera.toLocal(t,void 0,n),n}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId||this.playModeEnabled)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=this.getSpawnPoints(n);if(!i||!i[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let r=i[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new $.Point(r.x-a.x,r.y-a.y),startPoints:i.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,n,i){let a=this.getEditableObjectConfig(e);if(!a)return;let r=this.getSpawnPoints(a);if(!r||!r[t])return;let o=r.map((l,c)=>c===t?{x:n,y:i}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let n=window.__previewSelectObject;typeof n=="function"&&n(e)}}startDrag(e,t){var d,p,u,g;if(!this.selectedId||!e||!this.app||this.playModeEnabled||this.getPointerButton(t)!==0)return;let i=this.objectMap.get(this.selectedId);if(!i)return;this.dragContainer=(p=(d=i.displayObject)==null?void 0:d.parent)!=null?p:this.mainContainer;let a=this.getEventLocalPoint(t,this.dragContainer);if(!a)return;let r=i.displayObject;this.dragMode=e,this.dragStartPointer=new $.Point(a.x,a.y),this.dragStartPos=new $.Point(r.position.x,r.position.y),this.dragStartScale=typeof((u=r.scale)==null?void 0:u.x)=="number"?r.scale.x:1;let o=this.getEditableObjectConfig(this.selectedId),l=(g=o==null?void 0:o.transform)!=null?g:{};this.dragStartRotation=this.toRadians(typeof l.rotation=="number"?l.rotation:0),this.dragAnchorLocal=this.getAnchorLocalPoint(l,this.dragContainer),this.dragStartValue=this.getDragStartValue(e,l);let c=new $.Point(r.position.x,r.position.y);this.dragStartAngle=Math.atan2(a.y-c.y,a.x-c.x),this.dragStartDistance=Math.max(1,this.distance(a,c)),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}getDragStartValue(e,t){var n,i,a;return e==="move"?(n=t==null?void 0:t.position)!=null?n:{x:0,y:0}:e==="scale"?(i=t==null?void 0:t.scale)!=null?i:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var p,u,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let n=e-this.dragAnchorLocal.x,i=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let r=(p=a.transform)!=null?p:{};a.transform||(a.transform=r);let o=(u=r.offset)!=null?u:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(r,{x:n-l,y:i-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.getDynamicScaleMultiplier(),a=i>0?e/i:e;n.scale=Math.round(a*100)/100}updateLiveConfigRotation(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.toDegrees(e),a=typeof n.rotation=="number"?n.rotation:0;Math.abs(i-a)>.01&&(n.rotation=Math.round(i*100)/100)}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),se({objectId:e,path:t,value:n},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let n=this.getEditableObjectConfig(t),i=window.applyEditableObjectConfig;typeof i=="function"&&n&&i(t,n)}))}setNestedValue(e,t,n){let i=t.split("."),a=e;for(let r=0;r<i.length-1;r+=1){let o=i[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[i[i.length-1]]=n}buildPositionValue(e,t){let n=e==null?void 0:e.position,i=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(n)?[i,a]:{x:i,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}getPointerButton(e){var t,n,i;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((i=(n=e==null?void 0:e.data)==null?void 0:n.originalEvent)==null?void 0:i.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new $.Point(t.x,t.y);if(!this.app)return null;let n=e==null?void 0:e.clientX,i=e==null?void 0:e.clientY;if(typeof n!="number"||typeof i!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(n-a.left)*(this.app.renderer.width/a.width),o=(i-a.top)*(this.app.renderer.height/a.height);return new $.Point(r,o)}getEventLocalPoint(e,t=this.mainContainer){var a,r;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new $.Point(o.x,o.y)}let n=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!n)return null;let i=new $.Point;return t.toLocal(new $.Point(n.x,n.y),void 0,i),i}getPointerInContainer(e,t,n){if(!this.app)return null;let i=this.app.canvas.getBoundingClientRect(),a=(e-i.left)*(this.app.renderer.width/i.width),r=(t-i.top)*(this.app.renderer.height/i.height),o=new $.Point;return n.toLocal(new $.Point(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim().replace("#",""),i=Number.parseInt(n,16);if(Number.isFinite(i))return i}return t}};var Li=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[dt("playable-portrait"),dt("iphone-14"),dt("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.hasForceSynced=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=dt(e.defaultDevice||Bn.id),this.debugPanel=new an,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let n=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=n===null?!0:n==="true"}catch{}let t="dark";try{let n=window.localStorage.getItem(this.getThemeStorageKey());(n==="light"||n==="dark")&&(t=n)}catch{}this.setTheme(t),this.sceneEditor=new Ai({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0,this.scheduleForceSync()}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(n=>{console.warn("[PreviewShell] Force sync on refresh failed:",n)})},250))}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var i,a;let n=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=dt(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},r=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",r),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,r=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let p=c.getBoundingClientRect().width,u=n==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=u?u.offsetWidth:n==="left"?350:300,m=p-g-200;return Math.max(200,m)},o=c=>{let d=n==="left"?c.clientX-i:i-c.clientX,p=r(),u=Math.max(200,Math.min(p,a+d));e.style.width=`${u}px`;let g=this.container.querySelector(".preview-main");if(g){let m=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",y=400;g.style.gridTemplateColumns=`${m} minmax(${y}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),i=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getThemeStorageKey(){return`handler_preview_theme::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),n=this.container.querySelector("[data-preview-split]");e&&pt(this.scenePane,e,n!=null?n:this.previewContainer),t&&Si(this.scenePane,t,void 0,260,200);let i=this.getStoredSceneWidth();i&&(this.scenePane.style.width=`${i}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let r=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=p=>{let u=p.clientX-r,g=Math.max(240,Math.min(l,o+u));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var n;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(n=this.sceneEditor)==null||n.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
2299
+ `,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,i=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,i-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,n=this.cropWidth*this.scale,i=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,n,i),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,i),this.ctx.fillStyle="#ffffff";let a=8;[[e,t],[e+n-a,t],[e,t+i-a],[e+n-a,t+i-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let n=150;e.width=n,e.height=n;let i=n/this.cropWidth,a=n/this.cropHeight,r=Math.min(i,a),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,d=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",n=>{let i=parseFloat(n.target.value);this.setZoom(i)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let i=n.target.value;this.setAspectRatio(i)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var i;if(!this.image||!((i=this.options)!=null&&i.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=e.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(s){new Na().open(s)};te();var $=require("pixi.js");te();var mi=class{constructor(e){this.app=null;this.camera=new $.Container;this.mainContainer=new $.Container;this.uiContainer=new $.Container;this.gizmoLayer=new $.Container;this.screenFrame=new $.Graphics;this.gameFrame=new $.Graphics;this.gridLayer=new $.Graphics;this.spawnPointLayer=new $.Container;this.objectMap=new Map;this.selectedId=null;this.dragMode=null;this.dragStartPointer=null;this.dragStartPos=null;this.dragStartScale=1;this.dragStartRotation=0;this.dragStartAngle=0;this.dragStartDistance=1;this.dragAnchorLocal=null;this.dragStartValue=null;this.dragContainer=null;this.spawnPointDrag=null;this.lastGameFrameSize=null;this.cameraScale=1;this.isPanning=!1;this.panStart=null;this.panStartCamera=null;this.hasUserCamera=!1;this.resizeObserver=null;this.screenSyncRaf=null;this.gizmoOutline=new $.Graphics;this.anchorVisualizationLayer=new $.Graphics;this.moveHandle=new $.Graphics;this.scaleHandle=new $.Graphics;this.rotateHandle=new $.Graphics;this.isVisible=!0;this.applyQueued=!1;this.applyQueuedId=null;this.gridEnabled=!1;this.gridGap=50;this.gridAlpha=.25;this.lastPickPoint=null;this.lastPickIds=[];this.lastPickIndex=0;this.lastPickTime=0;this.playModeEnabled=!1;this.runtimeLayoutActive=!1;this.scalePollInterval=null;this.scalePollActive=!1;this.forcedScale=null;this.handleScreenChange=e=>{if(!(e!=null&&e.detail))return;let{width:t,height:n}=e.detail;!t||!n||(this.hasUserCamera=!1,this.updateLayout({width:t,height:n}),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid(),this.schedulePostScreenSync({width:t,height:n}))};this.handleActiveScreenChanged=()=>{this.isVisible&&this.syncFromConfig()};this.handleConfigChanged=e=>{if(!this.isVisible)return;this.updateLayout(),this.updateGrid();let t=e==null?void 0:e.detail;if(!t){this.syncFromConfig();return}let n=t.objectId,i=t.objectIds;if(n){this.syncFromConfig([n]);return}if(Array.isArray(i)&&i.length>0){this.syncFromConfig(i);return}this.syncFromConfig()};this.handleSceneRefresh=()=>{this.isVisible&&this.syncFromConfig()};this.handleAssetUpdated=e=>{var l;let t=(l=e==null?void 0:e.detail)!=null?l:{},n=t.objectId,i=t.texture;if(!n||!i)return;let a=this.objectMap.get(n);if(!a)return;let r=a.displayObject;if(r!=null&&r.texture)r.texture=i;else if(r!=null&&r.children){let c=r.children.find(d=>d==null?void 0:d.texture);c&&(c.texture=i)}let o=this.getEditableObjectConfig(n);o&&(a.assetKey=this.getAssetKey(o))};this.handleLayoutApplied=e=>{var r;if(!this.isVisible)return;let t=(r=e==null?void 0:e.detail)!=null?r:{},n=Number(t.width),i=Number(t.height),a=Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:this.getScreen();this.updateLayout(a),this.hasUserCamera||this.centerCamera(),this.syncFromConfig().then(()=>{this.playModeEnabled&&this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid()})};this.handlePreviewSelect=e=>{var n,i;let t=(i=(n=e==null?void 0:e.detail)==null?void 0:n.objectId)!=null?i:null;this.setSelected(t,{silent:!0})};this.onStagePointerDown=e=>{if(!this.app||!this.isVisible||this.getPointerButton(e)!==0||this.isGizmoTarget(e==null?void 0:e.target))return;let n=this.getEventGlobalPoint(e);if(!n)return;let i=new $.Point(n.x,n.y),a=this.getPickCandidates(i);if(a.length===0){this.setSelected(null),this.lastPickIds=[],this.lastPickIndex=0,this.lastPickPoint=i,this.lastPickTime=performance.now();return}let r=performance.now(),o=this.areSameIds(a,this.lastPickIds),l=this.lastPickPoint&&this.distance(i,this.lastPickPoint)<=6,c=r-this.lastPickTime<1200,d=o&&l&&c?(this.lastPickIndex+1)%a.length:0,p=a[d];this.lastPickIds=a,this.lastPickIndex=d,this.lastPickPoint=i,this.lastPickTime=r,this.setSelected(p),this.playModeEnabled||this.startDrag("move",e)};this.handleGridSettings=e=>{var a,r,o;let t=(a=e==null?void 0:e.detail)==null?void 0:a.enabled,n=(r=e==null?void 0:e.detail)==null?void 0:r.gap,i=(o=e==null?void 0:e.detail)==null?void 0:o.alpha;typeof t=="boolean"&&(this.gridEnabled=t),typeof n=="number"&&Number.isFinite(n)&&n>2&&(this.gridGap=n),typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=1&&(this.gridAlpha=i),this.updateGrid()};this.handlePlayMode=e=>{var n;let t=(n=e==null?void 0:e.detail)==null?void 0:n.enabled;typeof t=="boolean"&&this.setPlayMode(t)};this.syncFromGameObjects=()=>{this.syncFromGameObjectsInternal(!1)};this.onSpawnPointDragMove=e=>{if(!this.spawnPointDrag)return;let t=this.getPointerInContainer(e.clientX,e.clientY,this.mainContainer);if(!t)return;let n=t.x+this.spawnPointDrag.offset.x,i=t.y+this.spawnPointDrag.offset.y;this.updateLiveSpawnPoint(this.spawnPointDrag.objectId,this.spawnPointDrag.index,n,i)};this.onSpawnPointDragEnd=()=>{if(!this.spawnPointDrag)return;let{objectId:e,startPoints:t}=this.spawnPointDrag,n=this.getEditableObjectConfig(e),i=n?this.getSpawnPoints(n):null;n&&i&&(this.setNestedValue(n,"logic.props.spawnPoints",t),le({objectId:e,path:"logic.props.spawnPoints",value:i},{persist:!0,emitEvent:!0,trackHistory:!0}),this.queueLiveApply(e)),this.spawnPointDrag=null,window.dispatchEvent(new CustomEvent("inspector:refresh")),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd)};this.onDragMove=e=>{var a;if(!this.dragMode||!this.selectedId||!this.app||this.playModeEnabled)return;let t=this.objectMap.get(this.selectedId);if(!t)return;let n=(a=this.dragContainer)!=null?a:this.mainContainer,i=this.getPointerInContainer(e.clientX,e.clientY,n);if(!(!i||!this.dragStartPointer||!this.dragStartPos)){if(this.dragMode==="move"){let r=i.x-this.dragStartPointer.x,o=i.y-this.dragStartPointer.y,l=this.dragStartPos.x+r,c=this.dragStartPos.y+o;t.displayObject.position.set(l,c),this.updateLiveConfigPosition(l,c)}else if(this.dragMode==="scale"){let r=new $.Point(this.dragStartPos.x,this.dragStartPos.y),o=Math.max(1,this.distance(i,r)),l=Math.max(.05,this.dragStartScale*(o/this.dragStartDistance));t.displayObject.scale.set(l),this.updateLiveConfigScale(l)}else if(this.dragMode==="rotate"){let r=new $.Point(this.dragStartPos.x,this.dragStartPos.y),l=Math.atan2(i.y-r.y,i.x-r.x)-this.dragStartAngle,c=this.dragStartRotation+l;t.displayObject.rotation=c,this.updateLiveConfigRotation(c)}this.updateGizmos()}};this.onDragEnd=()=>{var n,i,a,r,o,l,c;if(!this.dragMode||!this.selectedId)return;let e=this.selectedId,t=this.getEditableObjectConfig(e);if(t){let d=(n=t.transform)!=null?n:{};if(t.transform||(t.transform=d),this.dragMode==="move"&&this.dragStartValue){let p=d.position,u=Array.isArray(p)?[Number((i=p[0])!=null?i:0),Number((a=p[1])!=null?a:0)]:{x:Number((r=p==null?void 0:p.x)!=null?r:0),y:Number((o=p==null?void 0:p.y)!=null?o:0)};this.applyFinalOverride(e,"transform.position",u,this.dragStartValue)}else this.dragMode==="scale"?this.applyFinalOverride(e,"transform.scale",(l=d.scale)!=null?l:1,this.dragStartValue):this.dragMode==="rotate"&&this.applyFinalOverride(e,"transform.rotation",(c=d.rotation)!=null?c:0,this.dragStartValue)}window.dispatchEvent(new CustomEvent("inspector:refresh")),this.dragMode=null,this.dragStartPointer=null,this.dragStartPos=null,this.dragAnchorLocal=null,this.dragStartValue=null,this.dragContainer=null,window.removeEventListener("pointermove",this.onDragMove),window.removeEventListener("pointerup",this.onDragEnd)};this.onWheel=e=>{if(!this.app||!this.isVisible)return;e.preventDefault();let n=Math.sign(e.deltaY)<0?1.1:.9,i=Math.min(6,Math.max(.1,this.cameraScale*n)),a=new $.Point(this.app.renderer.width/2,this.app.renderer.height/2),r=this.camera.toLocal(a);this.cameraScale=i,this.camera.scale.set(i);let o=this.camera.toGlobal(r);this.camera.position.set(this.camera.position.x+(a.x-o.x),this.camera.position.y+(a.y-o.y)),this.hasUserCamera=!0,this.updateGizmos(),this.updateGrid()};this.onPanStart=e=>{e.button===2&&(this.isPanning=!0,this.panStart={x:e.clientX,y:e.clientY},this.panStartCamera={x:this.camera.position.x,y:this.camera.position.y},this.hasUserCamera=!0)};this.onPanMove=e=>{if(!this.isPanning||!this.panStart||!this.panStartCamera)return;let t=e.clientX-this.panStart.x,n=e.clientY-this.panStart.y;this.camera.position.set(this.panStartCamera.x+t,this.panStartCamera.y+n),this.updateGrid()};this.onPanEnd=()=>{this.isPanning=!1,this.panStart=null,this.panStartCamera=null};this.root=e.root,this.getScreen=e.getScreen}async mount(){if(this.app)return;this.app=new $.Application,await this.app.init({resizeTo:this.root,autoDensity:!0,resolution:window.devicePixelRatio||1,antialias:!0,backgroundAlpha:0}),this.root.innerHTML="",this.root.appendChild(this.app.canvas),this.root.style.position="relative",this.root.style.overflow="hidden";let e=document.createElement("button");e.textContent="Force Play Mode Scale",e.style.position="absolute",e.style.top="10px",e.style.right="10px",e.style.zIndex="1000000",e.style.padding="8px 12px",e.style.backgroundColor="#3b82f6",e.style.color="white",e.style.border="none",e.style.borderRadius="4px",e.style.cursor="pointer",e.style.fontSize="12px",e.style.fontWeight="500",e.style.boxShadow="0 2px 4px rgba(0,0,0,0.2)",e.onmouseover=()=>{e.style.backgroundColor="#2563eb"},e.onmouseout=()=>{e.style.backgroundColor="#3b82f6"},e.onclick=()=>{this.forcePlayModeScale()},this.root.appendChild(e);let t=document.createElement("div");t.style.position="absolute",t.style.top="50px",t.style.right="10px",t.style.zIndex="1000000",t.style.backgroundColor="rgba(0, 0, 0, 0.7)",t.style.padding="12px",t.style.borderRadius="4px",t.style.minWidth="200px";let n=document.createElement("label");n.textContent="Force Scale:",n.style.display="block",n.style.color="white",n.style.fontSize="12px",n.style.marginBottom="8px",n.style.fontWeight="500",t.appendChild(n);let i=document.createElement("div");i.style.display="flex",i.style.alignItems="center",i.style.gap="10px";let a=document.createElement("input");a.type="range",a.min="0.1",a.max="5",a.step="0.01",a.value="1",a.style.flex="1",a.style.cursor="pointer";let r=document.createElement("span");r.textContent="1.00",r.style.color="white",r.style.fontSize="12px",r.style.minWidth="40px",r.style.textAlign="right",r.style.fontFamily="monospace";let o=document.createElement("button");o.textContent="Reset",o.style.padding="4px 8px",o.style.fontSize="11px",o.style.backgroundColor="#6b7280",o.style.color="white",o.style.border="none",o.style.borderRadius="3px",o.style.cursor="pointer",o.onmouseover=()=>{o.style.backgroundColor="#4b5563"},o.onmouseout=()=>{o.style.backgroundColor="#6b7280"},o.onclick=()=>{this.forcedScale=null,a.value="1",r.textContent="1.00";let l=this.getScreen();l!=null&&l.width&&(l!=null&&l.height)&&this.updateGameFrame(l)},a.oninput=()=>{let l=parseFloat(a.value);this.forcedScale=l,r.textContent=l.toFixed(2);let c=this.getScreen();c!=null&&c.width&&(c!=null&&c.height)&&this.updateGameFrame(c)},i.appendChild(a),i.appendChild(r),i.appendChild(o),t.appendChild(i),this.root.appendChild(t),window.__sceneEditorForcePlayModeScale=()=>{this.forcePlayModeScale()},window.__sceneEditorSetForcedScale=l=>{this.forcedScale=l,l!==null?(a.value=String(l),r.textContent=l.toFixed(2)):(a.value="1",r.textContent="1.00");let c=this.getScreen();c!=null&&c.width&&(c!=null&&c.height)&&this.updateGameFrame(c)},this.app.stage.sortableChildren=!0,this.app.stage.eventMode="static",this.camera.sortableChildren=!0,this.mainContainer.sortableChildren=!0,this.uiContainer.sortableChildren=!0,this.spawnPointLayer.sortableChildren=!0,this.gizmoLayer.sortableChildren=!0,this.app.stage.addChild(this.camera),this.camera.addChild(this.screenFrame),this.camera.addChild(this.mainContainer),this.camera.addChild(this.gridLayer),this.camera.addChild(this.uiContainer),this.camera.addChild(this.spawnPointLayer),this.camera.addChild(this.gameFrame),this.camera.addChild(this.gizmoLayer),this.screenFrame.zIndex=-1,this.screenFrame.eventMode="none",this.mainContainer.zIndex=0,this.gridLayer.zIndex=2e4,this.gridLayer.eventMode="none",this.gridLayer.visible=!0,this.uiContainer.zIndex=5e4,this.spawnPointLayer.zIndex=8e4,this.spawnPointLayer.eventMode="passive",this.gameFrame.zIndex=85e3,this.gameFrame.eventMode="none",this.gizmoLayer.zIndex=1e5,this.gizmoLayer.addChild(this.gizmoOutline),this.gizmoLayer.addChild(this.anchorVisualizationLayer),this.gizmoLayer.addChild(this.moveHandle),this.gizmoLayer.addChild(this.scaleHandle),this.gizmoLayer.addChild(this.rotateHandle),this.gizmoOutline.eventMode="none",this.anchorVisualizationLayer.eventMode="none",this.setupInteractions(),this.setupObservers(),this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.restoreScenePreferences(),this.refresh(),!this.isVisible&&this.app.ticker&&this.app.ticker.stop()}destroy(){var e;this.stopScalePolling(),delete window.__sceneEditorForcePlayModeScale,this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.screenSyncRaf&&(cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=null),window.removeEventListener("handler-preview:screen",this.handleScreenChange),window.removeEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.removeEventListener("config:changed",this.handleConfigChanged),window.removeEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.removeEventListener("handler:layout-applied",this.handleLayoutApplied),window.removeEventListener("preview:select",this.handlePreviewSelect),window.removeEventListener("scene-editor:grid",this.handleGridSettings),window.removeEventListener("scene-editor:play-mode",this.handlePlayMode),window.removeEventListener("scene-editor:asset-updated",this.handleAssetUpdated),window.removeEventListener("pointermove",this.onSpawnPointDragMove),window.removeEventListener("pointerup",this.onSpawnPointDragEnd),this.app&&((e=this.app.ticker)==null||e.remove(this.syncFromGameObjects),this.app.stage.off("pointerdown",this.onStagePointerDown),this.app.destroy(!0),this.app=null)}setVisible(e){this.isVisible=e,!(!this.app||!this.app.ticker)&&(e?(this.app.ticker.start(),this.refresh(),this.updateGrid()):this.app.ticker.stop())}refresh(){this.syncFromConfig()}forcePlayModeScale(){console.log("[SceneEditor] forcePlayModeScale: updating blue frame to match play mode scale");let e=this.getScreen();e!=null&&e.width&&(e!=null&&e.height)&&(this.forcedScale=null,this.updateGameFrame(e),console.log("[SceneEditor] forcePlayModeScale: blue frame updated to show runtime scale")),this.updateGizmos()}setupObservers(){window.addEventListener("handler-preview:screen",this.handleScreenChange),window.addEventListener("handler:active-screen-changed",this.handleActiveScreenChanged),window.addEventListener("config:changed",this.handleConfigChanged),window.addEventListener("handler:scene-objects-refresh",this.handleSceneRefresh),window.addEventListener("handler:layout-applied",this.handleLayoutApplied),window.addEventListener("preview:select",this.handlePreviewSelect),window.addEventListener("scene-editor:grid",this.handleGridSettings),window.addEventListener("scene-editor:play-mode",this.handlePlayMode),window.addEventListener("scene-editor:asset-updated",this.handleAssetUpdated),this.resizeObserver=new ResizeObserver(()=>{this.handleResize()}),this.resizeObserver.observe(this.root)}setupInteractions(){if(!this.app)return;let e=this.app.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("wheel",this.onWheel,{passive:!1}),e.addEventListener("pointerdown",this.onPanStart),window.addEventListener("pointermove",this.onPanMove),window.addEventListener("pointerup",this.onPanEnd),this.app.stage.on("pointerdown",this.onStagePointerDown),this.moveHandle.eventMode="static",this.moveHandle.cursor="move",this.scaleHandle.eventMode="static",this.scaleHandle.cursor="nwse-resize",this.rotateHandle.eventMode="static",this.rotateHandle.cursor="crosshair",this.moveHandle.on("pointerdown",t=>this.startDrag("move",t)),this.scaleHandle.on("pointerdown",t=>this.startDrag("scale",t)),this.rotateHandle.on("pointerdown",t=>this.startDrag("rotate",t))}handleResize(){this.app&&(this.updateLayout(),this.hasUserCamera||this.centerCamera(),this.updateGizmos(),this.updateGrid())}getPickCandidates(e){var n;let t=[];for(let[i,a]of this.objectMap.entries()){let r=a.displayObject;if(!r||r.visible===!1)continue;let o=(n=r.getBounds)==null?void 0:n.call(r);if(!o||o.width<=0||o.height<=0||e.x<o.x||e.x>o.x+o.width||e.y<o.y||e.y>o.y+o.height)continue;let l=r.parent,c=typeof(l==null?void 0:l.zIndex)=="number"?l.zIndex:0,d=typeof r.zIndex=="number"?r.zIndex:0,p=typeof(l==null?void 0:l.getChildIndex)=="function"?l.getChildIndex(r):0,u=c*1e6+d*1e3+p;t.push({id:i,order:u})}return t.sort((i,a)=>a.order-i.order),t.map(i=>i.id)}areSameIds(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}isGizmoTarget(e){return e&&this.spawnPointLayer.children.indexOf(e)!==-1?!0:e===this.moveHandle||e===this.scaleHandle||e===this.rotateHandle||e===this.gizmoOutline}restoreScenePreferences(){if(typeof window!="undefined"){try{let e=window.localStorage.getItem(this.getSceneStorageKey("grid_enabled")),t=window.localStorage.getItem(this.getSceneStorageKey("grid_gap")),n=window.localStorage.getItem(this.getSceneStorageKey("grid_alpha")),i=window.localStorage.getItem(this.getSceneStorageKey("play_mode"));if(e!==null&&(this.gridEnabled=e==="true"),t!==null){let a=Number(t);Number.isFinite(a)&&a>2&&(this.gridGap=a)}if(n!==null){let a=Number(n);Number.isFinite(a)&&a>=0&&a<=1&&(this.gridAlpha=a)}i!==null&&this.setPlayMode(i==="true")}catch{}this.updateGrid()}}getSceneStorageKey(e){let t=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${e}::${t}`}schedulePostScreenSync(e){this.screenSyncRaf&&cancelAnimationFrame(this.screenSyncRaf),this.screenSyncRaf=requestAnimationFrame(()=>{this.runPostScreenSync(e)})}async runPostScreenSync(e){this.screenSyncRaf=null,this.isVisible&&(this.updateLayout(e),this.hasUserCamera||this.centerCamera(),await this.syncFromConfig(),this.playModeEnabled&&this.syncFromGameObjectsInternal(!0),this.updateGizmos(),this.updateGrid())}getRuntimeScreenSize(){var a,r,o,l,c,d,p;let e=window.gameApp;if(e!=null&&e.renderer){let u=e.renderer.screen,g=Number((a=u==null?void 0:u.width)!=null?a:0),h=Number((r=u==null?void 0:u.height)!=null?r:0);if(Number.isFinite(g)&&g>0&&Number.isFinite(h)&&h>0)return{width:g,height:h};let m=Number((o=e.renderer.resolution)!=null?o:1)||1,f=Number((l=e.renderer.width)!=null?l:0)/m,y=Number((c=e.renderer.height)!=null?c:0)/m;if(Number.isFinite(f)&&f>0&&Number.isFinite(y)&&y>0)return{width:f,height:y}}let t=document.querySelector(".game-container"),n=Number((d=t==null?void 0:t.dataset)==null?void 0:d.screenWidth),i=Number((p=t==null?void 0:t.dataset)==null?void 0:p.screenHeight);return Number.isFinite(n)&&n>0&&Number.isFinite(i)&&i>0?{width:n,height:i}:null}getRuntimeLayoutReference(){var a,r,o,l,c,d,p,u,g,h,m,f,y,b,v,E,P,I,O,w,k,_,L,M,C,A,S,x,j,T,R,z,N,Y,F,U,ne,ot,lt,an,H,ve;let e=window.__mainContainer;if(e){let ae=(r=(a=e.scale)==null?void 0:a.x)!=null?r:1,J=(l=(o=e.scale)==null?void 0:o.y)!=null?l:ae;return console.log("[SceneEditor] getRuntimeLayoutReference: using __mainContainer",{scale:{x:ae,y:J},position:{x:(c=e.position)==null?void 0:c.x,y:(d=e.position)==null?void 0:d.y},note:"forcedScale only affects blue frame, containers always use scale 1"}),e}let t=window.__screenManager;if(t){let ae=["gameplay","start","tutorial","endgame","loading"];for(let J of ae){let B=(p=t.get)==null?void 0:p.call(t,J);if(B!=null&&B.visible){let V=(u=B.getContentLayer)==null?void 0:u.call(B);if(V){let Z=(g=B.x)!=null?g:0,oe=(h=B.y)!=null?h:0,Q=(m=V.x)!=null?m:0,me=(f=V.y)!=null?f:0,se=(b=(y=V.scale)==null?void 0:y.x)!=null?b:1,Ae=(E=(v=V.scale)==null?void 0:v.y)!=null?E:se,Le=this.forcedScale!==null?this.forcedScale:se,Ke=this.forcedScale!==null?this.forcedScale:Ae,Ai=(I=(P=B.scale)==null?void 0:P.x)!=null?I:1,Li=(w=(O=B.scale)==null?void 0:O.y)!=null?w:1;return(Ai!==1||Li!==1)&&console.warn("[SceneEditor] getRuntimeLayoutReference: WARNING - screen has scale!",{screenId:J,screenScale:{x:Ai,y:Li},contentLayerScale:{x:se,y:Ae},forcedScale:this.forcedScale,finalScale:{x:Le,y:Ke}}),console.log("[SceneEditor] getRuntimeLayoutReference: using visible screen contentLayer",{screenId:J,contentLayerScale:{x:se,y:Ae},forcedScale:this.forcedScale,finalScale:{x:Le,y:Ke},screenScale:{x:Ai,y:Li},position:{x:Z+Q,y:oe+me},screenPos:{x:Z,y:oe},contentPos:{x:Q,y:me}}),{scale:{x:Le,y:Ke},position:{x:Z+Q,y:oe+me},pivot:V.pivot?{x:V.pivot.x,y:V.pivot.y}:void 0}}}}for(let J of ae){let B=(k=t.get)==null?void 0:k.call(t,J);if(B){if(!B.visible&&typeof B.updateLayout=="function"){let Z=window.gameApp;if((_=Z==null?void 0:Z.renderer)!=null&&_.screen){let oe=Z.renderer.screen.width,Q=Z.renderer.screen.height;oe>0&&Q>0&&B.updateLayout(oe,Q)}}let V=(L=B.getContentLayer)==null?void 0:L.call(B);if(V){let Z=(M=B.x)!=null?M:0,oe=(C=B.y)!=null?C:0,Q=(A=V.x)!=null?A:0,me=(S=V.y)!=null?S:0,se=(j=(x=V.scale)==null?void 0:x.x)!=null?j:1,Ae=(R=(T=V.scale)==null?void 0:T.y)!=null?R:se,Le=(N=(z=B.scale)==null?void 0:z.x)!=null?N:1,Ke=(F=(Y=B.scale)==null?void 0:Y.y)!=null?F:1;return(Le!==1||Ke!==1)&&console.warn("[SceneEditor] getRuntimeLayoutReference: WARNING - screen has scale!",{screenId:J,screenScale:{x:Le,y:Ke},contentLayerScale:{x:se,y:Ae}}),console.log("[SceneEditor] getRuntimeLayoutReference: using any screen contentLayer (not visible)",{screenId:J,visible:B.visible,contentLayerScale:{x:se,y:Ae},screenScale:{x:Le,y:Ke},position:{x:Z+Q,y:oe+me},screenPos:{x:Z,y:oe},contentPos:{x:Q,y:me},note:"forcedScale only affects blue frame, containers always use scale 1"}),{scale:{x:se,y:Ae},position:{x:Z+Q,y:oe+me},pivot:V.pivot?{x:V.pivot.x,y:V.pivot.y}:void 0}}}}}let n=window.gameApp,i=(U=n==null?void 0:n.stage)!=null?U:null;if(i){let ae=(ot=(ne=i.scale)==null?void 0:ne.x)!=null?ot:1,J=(an=(lt=i.scale)==null?void 0:lt.y)!=null?an:ae;console.log("[SceneEditor] getRuntimeLayoutReference: using gameApp.stage (fallback)",{scale:{x:ae,y:J},position:{x:(H=i.position)==null?void 0:H.x,y:(ve=i.position)==null?void 0:ve.y},note:"forcedScale only affects blue frame, containers always use scale 1"})}else console.log("[SceneEditor] getRuntimeLayoutReference: no reference found");return i}getRuntimeParentContainer(e){var l,c;let t=window.gameObjectManager;if(!(t!=null&&t.get))return null;let n=t.get(e),i=((l=n==null?void 0:n.getDisplayObject)==null?void 0:l.call(n))||(n==null?void 0:n.pixiObject)||n,a=i==null?void 0:i.parent;if(!a)return null;let r=this.getRuntimeLayoutReference(),o=(c=window.gameApp)==null?void 0:c.stage;return r&&o&&r===o?this.mainContainer:r&&typeof r.contains=="function"&&r.contains(a)?this.mainContainer:a===r||a===o?this.mainContainer:this.uiContainer}applyRuntimeTransform(e){var r,o,l,c,d,p,u,g,h,m;if(!e)return console.log("[SceneEditor] applyRuntimeTransform: no reference"),!1;let t=1,n=1,i=Number((o=(r=e.position)==null?void 0:r.x)!=null?o:0),a=Number((c=(l=e.position)==null?void 0:l.y)!=null?c:0);if(!Number.isFinite(i)||!Number.isFinite(a))return console.log("[SceneEditor] applyRuntimeTransform: invalid position",{posX:i,posY:a}),!1;if(console.log("[SceneEditor] applyRuntimeTransform: applying (scale always 1)",{playMode:this.playModeEnabled,scale:{x:t,y:n},position:{x:i,y:a},beforeScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.mainContainer.position.set(i,a),this.uiContainer.position.set(i,a),e.pivot&&((d=this.mainContainer.pivot)!=null&&d.set)&&((p=this.uiContainer.pivot)!=null&&p.set)){let f=Number((g=(u=e.pivot)==null?void 0:u.x)!=null?g:0),y=Number((m=(h=e.pivot)==null?void 0:h.y)!=null?m:0);Number.isFinite(f)&&Number.isFinite(y)&&(this.mainContainer.pivot.set(f,y),this.uiContainer.pivot.set(f,y))}return typeof e.rotation=="number"&&(this.mainContainer.rotation=e.rotation,this.uiContainer.rotation=e.rotation),!0}getEditableConfig(){return window.__editableConfig||null}getDesignDimensionsAndScale(e,t){var c,d,p,u;let n=this.getEditableConfig(),i=((d=(c=n==null?void 0:n.engine)==null?void 0:c.runtime)==null?void 0:d.layout)||{},a=t>e,r=(p=i.design_width_portrait)!=null?p:a?320:480,o=(u=i.design_height_portrait)!=null?u:a?480:320,l=Math.min(e/r,t/o);return{designW:r,designH:o,scale:l}}getEditableObjectConfig(e){var i,a;let t=window.getEditableObjectConfig;if(typeof t=="function")return t(e);let n=this.getEditableConfig();return n!=null&&n.objects?typeof n.objects.get=="function"?(i=n.objects.get(e))!=null?i:null:(a=n.objects[e])!=null?a:null:null}getEditableObjectIds(){let e=window.getEditableObjectList;if(typeof e=="function"){let n=e();if(Array.isArray(n))return n}let t=this.getEditableConfig();return t!=null&&t.objects?typeof t.objects.keys=="function"?Array.from(t.objects.keys()):Object.keys(t.objects):[]}async syncFromConfig(e){if(!this.app)return;let t=this.getEditableConfig();if(!(t!=null&&t.objects))return;let n=e!=null&&e.length?e:this.getEditableObjectIds(),i=new Set(n);if(!e)for(let a of Array.from(this.objectMap.keys()))i.has(a)||this.removeObject(a);for(let a of n){let r=this.getEditableObjectConfig(a);if(!r){this.removeObject(a);continue}await this.upsertObject(a,r)}this.updateGizmos(),this.updateSpawnPointHandles(),this.updateGameFrame(this.getScreen())}removeObject(e){var n,i;let t=this.objectMap.get(e);if(t){try{(i=(n=t.displayObject)==null?void 0:n.destroy)==null||i.call(n)}catch{}this.objectMap.delete(e),this.selectedId===e&&this.setSelected(null,{silent:!0})}}async upsertObject(e,t){let n=this.getAssetKey(t),i=this.objectMap.get(e),a=this.isUiConfig(e,t),r=this.getRuntimeParentContainer(e),o=a?this.uiContainer:this.mainContainer,l=r!=null?r:o;if(!i||i.assetKey!==n||i.isUi!==a){i&&this.removeObject(e);let d=await this.createDisplayObject(e,t);if(!d)return;l.addChild(d),this.objectMap.set(e,{id:e,displayObject:d,assetKey:n,isUi:a}),this.attachObjectInteraction(d,e)}let c=this.objectMap.get(e);c&&(c.displayObject.parent!==l&&l.addChild(c.displayObject),this.applyVisualConfig(c.displayObject,t),this.updateObjectTransform(c.displayObject,t))}async createDisplayObject(e,t){var o,l,c,d,p,u,g,h,m,f,y,b,v,E,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 O=await xe.create(e,t,this.app);if(O instanceof $.Container)return O}}catch(I){console.warn("[SceneEditor] ObjectFactory failed for",e,I)}let n=t==null?void 0:t.ui,i=(d=t==null?void 0:t.render)!=null?d:{},a=(n==null?void 0:n.text)||(n==null?void 0:n.kind)==="text";if(!!i.background_color){let I=this.getScreen(),O=(p=I==null?void 0:I.width)!=null?p:0,w=(u=I==null?void 0:I.height)!=null?u:0,k=new $.Graphics,_=this.parseColor(i.background_color,0),L=typeof i.background_alpha=="number"?i.background_alpha:1;O>0&&w>0&&k.rect(0,0,O,w).fill({color:_,alpha:L});let M=new $.Container;return M.addChild(k),M}if(a){let I=(h=(g=n==null?void 0:n.color)!=null?g:i==null?void 0:i.tint)!=null?h:"#ffffff",O=new $.TextStyle({fontFamily:"Arial, sans-serif",fontSize:(m=n==null?void 0:n.fontSize)!=null?m:16,fill:I,align:(f=n==null?void 0:n.align)!=null?f:"center",letterSpacing:(y=n==null?void 0:n.letterSpacing)!=null?y:0});return new $.Text({text:(b=n==null?void 0:n.text)!=null?b:"",style:O})}if((v=t==null?void 0:t.effects)!=null&&v.width||(E=t==null?void 0:t.effects)!=null&&E.height){let I=new $.Graphics,O=typeof t.effects.width=="number"?t.effects.width:100,w=typeof t.effects.height=="number"?t.effects.height:100,k=(P=t.effects.fill_color)!=null?P:"#ffffff",_=typeof t.effects.fill_alpha=="number"?t.effects.fill_alpha:1,L=Number.parseInt(String(k).replace("#",""),16);return I.rect(0,0,O,w).fill({color:Number.isFinite(L)?L:16777215,alpha:_}),I}return new $.Container}attachObjectInteraction(e,t){if(e&&(e.eventMode="static",e.cursor="pointer",!e.hitArea&&typeof e.getLocalBounds=="function")){let n=e.getLocalBounds();n&&n.width>0&&n.height>0&&(e.hitArea=new $.Rectangle(n.x,n.y,n.width,n.height))}}getAssetKey(e){var n;let t=(n=e==null?void 0:e.render)==null?void 0:n.asset;return t?`${t.type||"asset"}::${t.path||""}`:null}isUiConfig(e,t){var a,r;let n=(((a=t==null?void 0:t.identity)==null?void 0:a.category)||"").toString().toLowerCase(),i=(((r=t==null?void 0:t.identity)==null?void 0:r.id)||e||"").toString().toLowerCase();return n.includes("ui")||i.startsWith("ui")||i.includes("label")}applyVisualConfig(e,t){var r,o,l,c,d,p,u,g,h;if(!e)return;let n=(r=t==null?void 0:t.render)!=null?r:{};typeof n.alpha=="number"&&(e.alpha=n.alpha),e.visible=n.visible!==!1,e.zIndex=typeof n.z_index=="number"?n.z_index:0;let i=(d=(c=(o=t==null?void 0:t.render)==null?void 0:o.anchor)!=null?c:(l=t==null?void 0:t.transform)==null?void 0:l.anchor)!=null?d:"bottom-right";i==="bottom-right"&&!((p=t==null?void 0:t.render)!=null&&p.anchor)&&!((u=t==null?void 0:t.transform)!=null&&u.anchor)&&console.log("[DEBUG FALLBACK] applyVisualConfig (SceneEditor) \u2192 bottom-right");let a=Me(i,{x:.5,y:.5});if((g=e.anchor)!=null&&g.set)e.anchor.set(a.x,a.y);else if(e.pivot){let m=(h=e.getLocalBounds)==null?void 0:h.call(e);m&&e.pivot.set(m.width*a.x,m.height*a.y)}}updateObjectTransform(e,t){var d;if(!e||this.playModeEnabled)return;let n=(d=t==null?void 0:t.transform)!=null?d:{},i=e.parent===this.uiContainer?this.uiContainer:this.mainContainer,a=this.getAnchorLocalPoint(n,i),r=this.getPositionOffset(n),o=this.getDynamicScaleMultiplier();a&&e.position.set(a.x+r.x,a.y+r.y);let l=typeof n.scale=="number"?n.scale:void 0;typeof l=="number"&&e.scale&&e.scale.set(l*o);let c=this.toRadians(typeof n.rotation=="number"?n.rotation:0);typeof e.rotation=="number"&&(e.rotation=c)}getAnchorLocalPoint(e,t=this.mainContainer){var d,p;let n=(d=this.getScreen())!=null?d:this.getRuntimeScreenSize();if(!(n!=null&&n.width)||!(n!=null&&n.height))return null;let a=(e==null?void 0:e.position_ratio)!=null?mn(n.width,n.height,e.position_ratio):hn(n.width,n.height,(p=e==null?void 0:e.anchor)!=null?p:"top-right"),r=t.position.x,o=t.position.y,l=a.x-r,c=a.y-o;return new $.Point(l,c)}getRuntimeWorldContainer(){let e=window.__contentContainer,t=window.__mainContainer,n=window.__worldLayer;if(n)return n;let i=e||t;if(i&&i.children){for(let a of i.children)if(a.__isWorldLayer||a.label==="worldLayer")return a}return null}getPositionOffset(e){var l,c,d,p,u,g,h,m;let t=e==null?void 0:e.position,n=e==null?void 0:e.offset,i=Array.isArray(t)?Number((l=t[0])!=null?l:0):Number((c=t==null?void 0:t.x)!=null?c:0),a=Array.isArray(t)?Number((d=t[1])!=null?d:0):Number((p=t==null?void 0:t.y)!=null?p:0),r=Array.isArray(n)?Number((u=n[0])!=null?u:0):Number((g=n==null?void 0:n.x)!=null?g:0),o=Array.isArray(n)?Number((h=n[1])!=null?h:0):Number((m=n==null?void 0:n.y)!=null?m:0);return{x:i+r,y:a+o}}updateLayout(e){var i,a,r,o,l;let t=e!=null?e:this.getScreen();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;console.log("[SceneEditor] updateLayout: called",{playMode:this.playModeEnabled,screen:{width:t.width,height:t.height},currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},runtimeLayoutActive:this.runtimeLayoutActive}),this.startScalePolling();let n=this.getRuntimeLayoutReference();if(this.playModeEnabled){if(console.log("[SceneEditor] updateLayout: Play Mode ON - using scale 1 (containers always scale 1)"),n){let c=Number((a=(i=n.position)==null?void 0:i.x)!=null?a:t.width/2),d=Number((o=(r=n.position)==null?void 0:r.y)!=null?o:t.height/2);this.mainContainer.position.set(c,d),this.uiContainer.position.set(c,d)}this.mainContainer.scale.set(1,1),this.uiContainer.scale.set(1,1),this.runtimeLayoutActive=!0,console.log("[SceneEditor] updateLayout: Play Mode ON - result",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},position:{x:this.mainContainer.position.x,y:this.mainContainer.position.y}})}else{console.log("[SceneEditor] updateLayout: Play Mode OFF - trying runtime transform");let c=this.runtimeLayoutActive;if(c&&n){let p=this.applyRuntimeTransform(n);if(p){console.log("[SceneEditor] updateLayout: Play Mode OFF - refreshed runtime layout",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}}),this.runtimeLayoutActive=!0;return}if(!p){console.log("[SceneEditor] updateLayout: Play Mode OFF - runtime refresh failed, keeping current scale");return}}let d=this.applyRuntimeTransform(n);this.runtimeLayoutActive=d,!d&&!c?(console.log("[SceneEditor] updateLayout: Play Mode OFF - using scale 1 (containers always scale 1)",{screen:{width:t.width,height:t.height}}),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.pivot.set(0,0),this.uiContainer.pivot.set(0,0),this.mainContainer.rotation=0,this.uiContainer.rotation=0,this.runtimeLayoutActive=!1):d&&console.log("[SceneEditor] updateLayout: Play Mode OFF - applied runtime",{finalScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})}this.screenFrame.clear(),this.screenFrame.rect(0,0,t.width,t.height),this.screenFrame.stroke({width:2,color:2894892,alpha:.5}),this.updateGameFrame(t),(l=this.app)!=null&&l.stage&&(this.app.stage.hitArea=new $.Rectangle(0,0,this.app.renderer.width,this.app.renderer.height)),this.updateSpawnPointHandles()}startScalePolling(){if(this.playModeEnabled||this.scalePollActive||this.runtimeLayoutActive){console.log("[SceneEditor] startScalePolling: skipped",{playMode:this.playModeEnabled,pollActive:this.scalePollActive,runtimeLayoutActive:this.runtimeLayoutActive});return}console.log("[SceneEditor] startScalePolling: starting polling"),this.scalePollActive=!0,this.scalePollInterval=window.setInterval(()=>{this.checkAndUpdateScale()},1e3)}stopScalePolling(){this.scalePollInterval!==null&&(console.log("[SceneEditor] stopScalePolling: stopping polling"),clearInterval(this.scalePollInterval),this.scalePollInterval=null),this.scalePollActive=!1}checkAndUpdateScale(){var a,r,o,l,c,d,p,u,g;if(this.playModeEnabled){console.log("[SceneEditor] checkAndUpdateScale: Play Mode ON, stopping polling"),this.stopScalePolling();return}let e=this.getRuntimeLayoutReference();if(!e){console.log("[SceneEditor] checkAndUpdateScale: no runtime reference, will retry in 1 second");return}let t=Number((r=(a=e.scale)==null?void 0:a.x)!=null?r:1),n=Number((l=(o=e.scale)==null?void 0:o.y)!=null?l:t);if(!Number.isFinite(t)||!Number.isFinite(n)||t===1&&n===1&&e===((c=window.gameApp)==null?void 0:c.stage)){console.log("[SceneEditor] checkAndUpdateScale: invalid runtime scale (stage fallback), will retry in 1 second");return}if(this.applyRuntimeTransform(e)){console.log("[SceneEditor] checkAndUpdateScale: SUCCESS - runtime transform applied, stopping polling"),this.runtimeLayoutActive=!0,this.stopScalePolling();return}if(this.runtimeLayoutActive){let h=Number((p=(d=this.mainContainer.scale)==null?void 0:d.x)!=null?p:1),m=Number((g=(u=this.mainContainer.scale)==null?void 0:u.y)!=null?g:1);console.log("[SceneEditor] checkAndUpdateScale: comparing",{currentScale:{x:h,y:m},runtimeScale:{x:t,y:n},diff:{x:Math.abs(h-t),y:Math.abs(m-n)}}),Math.abs(h-t)>.001||Math.abs(m-n)>.001?(console.log("[SceneEditor] checkAndUpdateScale: SCALE CHANGED! Updating"),this.applyRuntimeTransform(e)):console.log("[SceneEditor] checkAndUpdateScale: no change, continuing polling")}else console.log("[SceneEditor] checkAndUpdateScale: runtime transform not applied yet, will retry in 1 second")}getDynamicScaleMultiplier(){return 1}updateGrid(){if(!this.app)return;if(!this.gridEnabled){this.gridLayer.clear(),this.gridLayer.visible=!0;return}let e=Math.max(4,this.gridGap),t=this.app.renderer,n=this.camera.toLocal(new $.Point(0,0)),i=this.camera.toLocal(new $.Point(t.width,t.height)),a=Math.min(n.x,i.x),r=Math.max(n.x,i.x),o=Math.min(n.y,i.y),l=Math.max(n.y,i.y),c=400,d=Math.ceil((r-a)/e),p=Math.ceil((l-o)/e),u=e*Math.max(1,Math.ceil(d/c)),g=e*Math.max(1,Math.ceil(p/c)),h=Math.floor(a/u)*u,m=Math.floor(o/g)*g;this.gridLayer.clear(),this.gridLayer.visible=!0;for(let f=h;f<=r;f+=u)this.gridLayer.moveTo(f,o),this.gridLayer.lineTo(f,l);for(let f=m;f<=l;f+=g)this.gridLayer.moveTo(a,f),this.gridLayer.lineTo(r,f);this.gridLayer.stroke({width:1,color:16777215,alpha:this.gridAlpha})}updateGameFrame(e){var p,u,g;let t=(p=e!=null?e:this.getScreen())!=null?p:this.getRuntimeScreenSize();if(!(t!=null&&t.width)||!(t!=null&&t.height))return;let n=this.getRuntimeLayoutReference(),i=(g=(u=n==null?void 0:n.scale)==null?void 0:u.x)!=null?g:1,a=this.forcedScale!==null?this.forcedScale:i,r=a>0?1/a:1,o=t.width*r,l=t.height*r,c=(t.width-o)/2,d=(t.height-l)/2;this.lastGameFrameSize&&this.lastGameFrameSize.width===t.width&&this.lastGameFrameSize.height===t.height&&this.lastGameFrameSize.frameScale===a||(this.lastGameFrameSize={width:t.width,height:t.height,frameScale:a},this.gameFrame.clear(),this.gameFrame.rect(c,d,o,l),this.gameFrame.stroke({width:2,color:6333946,alpha:.35}))}setPlayMode(e){var n;if(this.playModeEnabled===e)return;console.log("[SceneEditor] setPlayMode: changing",{from:this.playModeEnabled,to:e,currentScale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y},runtimeLayoutActive:this.runtimeLayoutActive});let t=this.playModeEnabled;if(this.playModeEnabled=e,(n=this.app)!=null&&n.ticker)if(this.app.ticker.remove(this.syncFromGameObjects),e)this.app.ticker.add(this.syncFromGameObjects),this.stopScalePolling();else{let i=this.getRuntimeLayoutReference();i?this.applyRuntimeTransform(i)?(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserved runtime scale",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})):t&&this.mainContainer.scale.x!==1&&(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserving current scale (runtime apply failed)",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})):t&&this.mainContainer.scale.x!==1&&(this.runtimeLayoutActive=!0,console.log("[SceneEditor] setPlayMode: Play Mode OFF - preserving current scale (no runtime reference)",{scale:{x:this.mainContainer.scale.x,y:this.mainContainer.scale.y}})),this.startScalePolling()}e?(this.moveHandle.eventMode="none",this.scaleHandle.eventMode="none",this.rotateHandle.eventMode="none",this.syncFromGameObjectsInternal(!0)):(this.moveHandle.eventMode="static",this.scaleHandle.eventMode="static",this.rotateHandle.eventMode="static",this.syncFromConfig()),this.updateGizmos(),this.updateSpawnPointHandles()}syncFromGameObjectsInternal(e){var i,a,r,o,l,c,d,p;if(!this.app||!this.isVisible||!this.playModeEnabled&&!e)return;let t=window.gameObjectManager;if(!(t!=null&&t.get))return;let n=this.dragMode?this.selectedId:null;for(let[u,g]of this.objectMap.entries()){if(n&&u===n)continue;let h=t.get(u),m=((i=h==null?void 0:h.getDisplayObject)==null?void 0:i.call(h))||(h==null?void 0:h.pixiObject)||h;if(!m)continue;let f=(r=(a=g.displayObject)==null?void 0:a.parent)!=null?r:this.mainContainer,y=new $.Point;if(typeof m.getGlobalPosition=="function"){m.getGlobalPosition(y);let I=f.toLocal(y,this.camera);g.displayObject.position.set(I.x,I.y)}else if(m.worldTransform){y.set(m.worldTransform.tx,m.worldTransform.ty);let I=f.toLocal(y,this.camera);g.displayObject.position.set(I.x,I.y)}let b=this.getWorldScale(m);if(b){let I=Number((l=(o=f.scale)==null?void 0:o.x)!=null?l:1)||1,O=Number((d=(c=f.scale)==null?void 0:c.y)!=null?d:1)||1,w=b.x/I,k=b.y/O;(p=g.displayObject.scale)!=null&&p.set?g.displayObject.scale.set(w,k):g.displayObject.scale&&(g.displayObject.scale.x=w,g.displayObject.scale.y=k)}let v=this.getWorldRotation(m);if(typeof v=="number"){let I=f?f.rotation:0;g.displayObject.rotation=v-I}let E=m.parent,P=typeof(E==null?void 0:E.getChildIndex)=="function"?E.getChildIndex(m):0;typeof m.zIndex=="number"?g.displayObject.zIndex=m.zIndex:Number.isFinite(P)&&(g.displayObject.zIndex=P)}this.updateGizmos()}getWorldScale(e){var a,r;let t=(r=e==null?void 0:e.worldTransform)!=null?r:(a=e==null?void 0:e.transform)==null?void 0:a.worldTransform;if(!t)return null;let n=Math.sqrt(t.a*t.a+t.b*t.b),i=Math.sqrt(t.c*t.c+t.d*t.d);return!Number.isFinite(n)||!Number.isFinite(i)?null:{x:n,y:i}}getWorldRotation(e){var n,i;let t=(i=e==null?void 0:e.worldTransform)!=null?i:(n=e==null?void 0:e.transform)==null?void 0:n.worldTransform;if(t){let a=Math.atan2(t.b,t.a);return Number.isFinite(a)?a:null}return typeof(e==null?void 0:e.rotation)=="number"?e.rotation:null}centerCamera(){var a;if(!this.app)return;let e=(a=this.getScreen())!=null?a:this.getRuntimeScreenSize();if(!(e!=null&&e.width)||!(e!=null&&e.height))return;let t=this.app.renderer.width,n=this.app.renderer.height,i=Math.max(.01,Math.min(t/e.width,n/e.height));this.cameraScale=i,this.camera.scale.set(i),this.camera.position.set((t-e.width*i)/2,(n-e.height*i)/2)}updateGizmos(){var d,p;if(!this.selectedId||!this.isVisible){this.clearGizmos();return}let e=this.objectMap.get(this.selectedId);if(!(e!=null&&e.displayObject)){this.clearGizmos();return}let t=(p=(d=e.displayObject).getBounds)==null?void 0:p.call(d);if(!t||t.width<=0||t.height<=0){this.clearGizmos();return}let n=this.camera.toLocal(new $.Point(t.x,t.y)),i=this.camera.toLocal(new $.Point(t.x+t.width,t.y+t.height)),a=i.x-n.x,r=i.y-n.y,o=n.x+a/2,l=n.y+r/2;if(this.gizmoOutline.clear(),this.gizmoOutline.rect(n.x,n.y,a,r),this.gizmoOutline.stroke({width:2,color:16752394,alpha:.9}),this.playModeEnabled){this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear();return}let c=10;this.moveHandle.clear(),this.moveHandle.circle(0,0,c/2),this.moveHandle.fill({color:16752394,alpha:.9}),this.moveHandle.position.set(o,l),this.scaleHandle.clear(),this.scaleHandle.rect(-c/2,-c/2,c,c),this.scaleHandle.fill({color:3900150,alpha:.9}),this.scaleHandle.position.set(i.x,i.y),this.rotateHandle.clear(),this.rotateHandle.circle(0,0,c/2),this.rotateHandle.fill({color:1096065,alpha:.9}),this.rotateHandle.position.set(o,n.y-20)}clearGizmos(){this.gizmoOutline.clear(),this.moveHandle.clear(),this.scaleHandle.clear(),this.rotateHandle.clear()}updateSpawnPointHandles(){if(this.clearSpawnPointHandles(),!this.selectedId)return;let e=this.getEditableObjectConfig(this.selectedId);if(!e||!this.isSpawnerConfig(e))return;let t=this.getSpawnPoints(e);!t||t.length===0||t.forEach((n,i)=>{let a=new $.Graphics;a.circle(0,0,5).fill({color:16096779,alpha:.9}),a.circle(0,0,9).stroke({width:1,color:16096779,alpha:.45});let r=this.toCameraFromMain(n);a.position.set(r.x,r.y),a.cursor="move",a.eventMode=this.playModeEnabled?"none":"static",a.on("pointerdown",o=>this.startSpawnPointDrag(i,o)),this.spawnPointLayer.addChild(a)})}clearSpawnPointHandles(){this.spawnPointLayer.removeChildren().forEach(t=>{var n;(n=t.destroy)==null||n.call(t)})}isSpawnerConfig(e){var n,i;return((n=e==null?void 0:e.logic)==null?void 0:n.id)==="Spawner"?!0:String(((i=e==null?void 0:e.identity)==null?void 0:i.system_role)||"").toLowerCase().includes("spawner")}getSpawnPoints(e){var n,i;let t=(i=(n=e==null?void 0:e.logic)==null?void 0:n.props)==null?void 0:i.spawnPoints;return Array.isArray(t)?t.map(a=>{var r,o;return{x:Number((r=a==null?void 0:a.x)!=null?r:0),y:Number((o=a==null?void 0:a.y)!=null?o:0)}}):null}toCameraFromMain(e){let t=this.mainContainer.toGlobal(new $.Point(e.x,e.y)),n=new $.Point;return this.camera.toLocal(t,void 0,n),n}startSpawnPointDrag(e,t){var o,l;if(!this.selectedId||this.playModeEnabled)return;let n=this.getEditableObjectConfig(this.selectedId);if(!n)return;let i=this.getSpawnPoints(n);if(!i||!i[e])return;(o=t==null?void 0:t.stopPropagation)==null||o.call(t),(l=t==null?void 0:t.stopImmediatePropagation)==null||l.call(t);let a=this.getEventLocalPoint(t,this.mainContainer);if(!a)return;let r=i[e];this.spawnPointDrag={objectId:this.selectedId,index:e,offset:new $.Point(r.x-a.x,r.y-a.y),startPoints:i.map(c=>({x:c.x,y:c.y}))},window.addEventListener("pointermove",this.onSpawnPointDragMove),window.addEventListener("pointerup",this.onSpawnPointDragEnd)}updateLiveSpawnPoint(e,t,n,i){let a=this.getEditableObjectConfig(e);if(!a)return;let r=this.getSpawnPoints(a);if(!r||!r[t])return;let o=r.map((l,c)=>c===t?{x:n,y:i}:{x:l.x,y:l.y});this.setNestedValue(a,"logic.props.spawnPoints",o),this.queueLiveApply(e),this.updateSpawnPointHandles()}setSelected(e,t={}){if(this.selectedId!==e&&(this.selectedId=e,this.updateGizmos(),this.updateSpawnPointHandles(),!t.silent&&e)){let n=window.__previewSelectObject;typeof n=="function"&&n(e)}}startDrag(e,t){var d,p,u,g;if(!this.selectedId||!e||!this.app||this.playModeEnabled||this.getPointerButton(t)!==0)return;let i=this.objectMap.get(this.selectedId);if(!i)return;this.dragContainer=(p=(d=i.displayObject)==null?void 0:d.parent)!=null?p:this.mainContainer;let a=this.getEventLocalPoint(t,this.dragContainer);if(!a)return;let r=i.displayObject;this.dragMode=e,this.dragStartPointer=new $.Point(a.x,a.y),this.dragStartPos=new $.Point(r.position.x,r.position.y),this.dragStartScale=typeof((u=r.scale)==null?void 0:u.x)=="number"?r.scale.x:1;let o=this.getEditableObjectConfig(this.selectedId),l=(g=o==null?void 0:o.transform)!=null?g:{};this.dragStartRotation=this.toRadians(typeof l.rotation=="number"?l.rotation:0),this.dragAnchorLocal=this.getAnchorLocalPoint(l,this.dragContainer),this.dragStartValue=this.getDragStartValue(e,l);let c=new $.Point(r.position.x,r.position.y);this.dragStartAngle=Math.atan2(a.y-c.y,a.x-c.x),this.dragStartDistance=Math.max(1,this.distance(a,c)),window.addEventListener("pointermove",this.onDragMove),window.addEventListener("pointerup",this.onDragEnd)}getDragStartValue(e,t){var n,i,a;return e==="move"?(n=t==null?void 0:t.position)!=null?n:{x:0,y:0}:e==="scale"?(i=t==null?void 0:t.scale)!=null?i:1:e==="rotate"?(a=t==null?void 0:t.rotation)!=null?a:0:null}updateLiveConfigPosition(e,t){var p,u,g,h,m,f;if(!this.selectedId||!this.dragAnchorLocal)return;let n=e-this.dragAnchorLocal.x,i=t-this.dragAnchorLocal.y,a=this.getEditableObjectConfig(this.selectedId);if(!a)return;let r=(p=a.transform)!=null?p:{};a.transform||(a.transform=r);let o=(u=r.offset)!=null?u:{x:0,y:0},l=Array.isArray(o)?Number((g=o[0])!=null?g:0):Number((h=o==null?void 0:o.x)!=null?h:0),c=Array.isArray(o)?Number((m=o[1])!=null?m:0):Number((f=o==null?void 0:o.y)!=null?f:0),d=this.buildPositionValue(r,{x:n-l,y:i-c});this.setNestedValue(r,"position",d)}updateLiveConfigScale(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.getDynamicScaleMultiplier(),a=i>0?e/i:e;n.scale=Math.round(a*100)/100}updateLiveConfigRotation(e){var r;if(!this.selectedId)return;let t=this.getEditableObjectConfig(this.selectedId);if(!t)return;let n=(r=t.transform)!=null?r:{};t.transform||(t.transform=n);let i=this.toDegrees(e),a=typeof n.rotation=="number"?n.rotation:0;Math.abs(i-a)>.01&&(n.rotation=Math.round(i*100)/100)}applyFinalOverride(e,t,n,i){let a=this.getEditableObjectConfig(e);a!=null&&a.transform&&this.setNestedValue(a.transform,t.replace("transform.",""),i),le({objectId:e,path:t,value:n},{persist:!0,emitEvent:!0,trackHistory:!0})}queueLiveApply(e){this.applyQueuedId=e,!this.applyQueued&&(this.applyQueued=!0,requestAnimationFrame(()=>{this.applyQueued=!1;let t=this.applyQueuedId;if(!t)return;let n=this.getEditableObjectConfig(t),i=window.applyEditableObjectConfig;typeof i=="function"&&n&&i(t,n)}))}setNestedValue(e,t,n){let i=t.split("."),a=e;for(let r=0;r<i.length-1;r+=1){let o=i[r];(!a[o]||typeof a[o]!="object")&&(a[o]={}),a=a[o]}a[i[i.length-1]]=n}buildPositionValue(e,t){let n=e==null?void 0:e.position,i=Math.round(t.x*100)/100,a=Math.round(t.y*100)/100;return Array.isArray(n)?[i,a]:{x:i,y:a}}toRadians(e){return e*Math.PI/180}toDegrees(e){return e*180/Math.PI}distance(e,t){let n=e.x-t.x,i=e.y-t.y;return Math.sqrt(n*n+i*i)}getPointerButton(e){var t,n,i;return typeof(e==null?void 0:e.button)=="number"?e.button:typeof((t=e==null?void 0:e.data)==null?void 0:t.button)=="number"?e.data.button:typeof((i=(n=e==null?void 0:e.data)==null?void 0:n.originalEvent)==null?void 0:i.button)=="number"?e.data.originalEvent.button:0}getEventGlobalPoint(e){var l,c;let t=(c=e==null?void 0:e.global)!=null?c:(l=e==null?void 0:e.data)==null?void 0:l.global;if(t)return new $.Point(t.x,t.y);if(!this.app)return null;let n=e==null?void 0:e.clientX,i=e==null?void 0:e.clientY;if(typeof n!="number"||typeof i!="number")return null;let a=this.app.canvas.getBoundingClientRect(),r=(n-a.left)*(this.app.renderer.width/a.width),o=(i-a.top)*(this.app.renderer.height/a.height);return new $.Point(r,o)}getEventLocalPoint(e,t=this.mainContainer){var a,r;if(!this.app)return null;if(typeof(e==null?void 0:e.getLocalPosition)=="function"){let o=e.getLocalPosition(t);return new $.Point(o.x,o.y)}let n=(r=e==null?void 0:e.global)!=null?r:(a=e==null?void 0:e.data)==null?void 0:a.global;if(!n)return null;let i=new $.Point;return t.toLocal(new $.Point(n.x,n.y),void 0,i),i}getPointerInContainer(e,t,n){if(!this.app)return null;let i=this.app.canvas.getBoundingClientRect(),a=(e-i.left)*(this.app.renderer.width/i.width),r=(t-i.top)*(this.app.renderer.height/i.height),o=new $.Point;return n.toLocal(new $.Point(a,r),void 0,o),o}parseColor(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let n=e.trim().replace("#",""),i=Number.parseInt(n,16);if(Number.isFinite(i))return i}return t}};var fi=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[it("playable-portrait"),it("iphone-14"),it("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.sceneEditor=null;this.sceneVisiblePreference=!0;this.sceneVisible=!0;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.hasUnsavedChanges=!1;this.hasForceSynced=!1;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=it(e.defaultDevice||_n.id),this.debugPanel=new Wt,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.scenePane=this.mustQuery("[data-scene-pane]"),this.sceneRoot=this.mustQuery("#scene-editor-root"),this.sceneSplitter=this.mustQuery("[data-scene-splitter]"),this.gameViewPane=this.mustQuery("[data-game-pane]"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners();try{let n=window.localStorage.getItem(this.getSceneVisibilityStorageKey());this.sceneVisiblePreference=n===null?!0:n==="true"}catch{}let t="dark";try{let n=window.localStorage.getItem(this.getThemeStorageKey());(n==="light"||n==="dark")&&(t=n)}catch{}this.setTheme(t),this.sceneEditor=new mi({root:this.sceneRoot,getScreen:()=>this.getScreen()}),this.sceneEditor.mount(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setupShortcutListeners(),this.setupUnsavedChangesIndicator(),this.setupScenePaneInteractions(),this.updateSceneVisibility(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.updateDockState(),this.isInitialized=!0,this.scheduleForceSync()}getShortcutKey(){return typeof navigator!="undefined"&&navigator.platform.toUpperCase().indexOf("MAC")>=0?"CMD":"CTRL"}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}scheduleForceSync(){this.hasForceSynced||(this.hasForceSynced=!0,window.setTimeout(()=>{let e=window.__HANDLER_ACTIVE_SCREEN;fetch("/api/sync-screens",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:!0,screenId:e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"})}).catch(n=>{console.warn("[PreviewShell] Force sync on refresh failed:",n)})},250))}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1,this.sceneEditor&&(this.sceneEditor.destroy(),this.sceneEditor=null)}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){var e;this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh(),(e=this.sceneEditor)==null||e.refresh(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var i,a;let n=this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=it(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:n}),t.suppressCallback||(a=(i=this.options).onDeviceChange)==null||a.call(i,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark");try{window.localStorage.setItem(this.getThemeStorageKey(),e)}catch{}let t=this.container.querySelector("#theme-select");t&&(t.value=e),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(i=>i.classList.toggle("active",i.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(i=>{i.style.left="",i.style.top="",i.style.width="",i.style.height="",i.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),this.updateSceneVisibility(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),n=this.container.querySelector("#dock-console-content");t&&n&&t.parentElement!==n&&n.appendChild(t)}makeBottomDockResizable(e,t){let n,i,a=o=>{let l=o.clientY-n,c=Math.max(100,Math.min(800,i-l));e.style.height=`${c}px`;let d=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:d})},r=()=>{document.removeEventListener("pointermove",a),document.removeEventListener("pointerup",r),e.classList.remove("resizing")};t.addEventListener("pointerdown",o=>{o.preventDefault(),n=o.clientY,i=e.offsetHeight,document.addEventListener("pointermove",a),document.addEventListener("pointerup",r),e.classList.add("resizing")})}makeSidebarResizable(e,t,n){let i,a,r=()=>{let c=this.container.querySelector(".preview-main");if(!c)return 600;let p=c.getBoundingClientRect().width,u=n==="left"?this.container.querySelector(".debug-workbench"):this.container.querySelector(".scene-panel.scene-objects"),g=u?u.offsetWidth:n==="left"?350:300,m=p-g-200;return Math.max(200,m)},o=c=>{let d=n==="left"?c.clientX-i:i-c.clientX,p=r(),u=Math.max(200,Math.min(p,a+d));e.style.width=`${u}px`;let g=this.container.querySelector(".preview-main");if(g){let m=n==="left"?`${u}px`:g.style.gridTemplateColumns.split(" ")[0]||"300px",f=n==="right"?`${u}px`:g.style.gridTemplateColumns.split(" ")[2]||"350px",y=400;g.style.gridTemplateColumns=`${m} minmax(${y}px, 1fr) ${f}`}let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},l=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",l),e.classList.remove("resizing")};t.addEventListener("pointerdown",c=>{c.preventDefault(),i=c.clientX,a=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",l),e.classList.add("resizing")})}getSceneVisibilityStorageKey(){return`handler_preview_scene_visible::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getSceneWidthStorageKey(){return`handler_preview_scene_width::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}getThemeStorageKey(){return`handler_preview_theme::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}setupScenePaneInteractions(){let e=this.scenePane.querySelector("[data-scene-drag-handle]"),t=this.scenePane.querySelector("[data-scene-resize]"),n=this.container.querySelector("[data-preview-split]");e&&at(this.scenePane,e,n!=null?n:this.previewContainer),t&&ui(this.scenePane,t,void 0,260,200);let i=this.getStoredSceneWidth();i&&(this.scenePane.style.width=`${i}px`),this.sceneSplitter.addEventListener("pointerdown",a=>{if(this.layoutMode!=="fixed"||!this.sceneVisible)return;a.preventDefault();let r=a.clientX,o=this.scenePane.offsetWidth,l=Math.max(260,Math.min(720,this.previewContainer.clientWidth*.6)),c=p=>{let u=p.clientX-r,g=Math.max(240,Math.min(l,o+u));this.scenePane.style.width=`${g}px`;let h=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:h})},d=()=>{document.removeEventListener("pointermove",c),document.removeEventListener("pointerup",d),this.storeSceneWidth(this.scenePane.offsetWidth)};document.addEventListener("pointermove",c),document.addEventListener("pointerup",d)})}storeSceneWidth(e){try{window.localStorage.setItem(this.getSceneWidthStorageKey(),String(e))}catch{}}getStoredSceneWidth(){try{let e=window.localStorage.getItem(this.getSceneWidthStorageKey()),t=e?Number(e):null;return Number.isFinite(t)&&t?t:null}catch{return null}}updateSceneVisibility(){let e=this.viewMode==="single"&&this.sceneVisiblePreference;this.setSceneVisible(e,{persist:!1});let t=this.container.querySelector("#scene-toggle");t&&(t.classList.toggle("active",this.sceneVisiblePreference),t.setAttribute("aria-pressed",String(this.sceneVisiblePreference)))}setSceneVisible(e,t={}){var n;if(this.sceneVisible=e,this.container.classList.toggle("scene-hidden",!e),(n=this.sceneEditor)==null||n.setVisible(e),t.persist!==!1){this.sceneVisiblePreference=e;try{window.localStorage.setItem(this.getSceneVisibilityStorageKey(),String(e))}catch{}}this.scheduleFit()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
2300
2300
  <div class="preview-toolbar">
2301
2301
  <div class="preview-toolbar-left">
2302
2302
  <span class="preview-logo">PREVIEWER</span>
@@ -2305,7 +2305,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2305
2305
  <div class="preview-toolbar-center">
2306
2306
  <div class="device-selector-wrapper">
2307
2307
  <select class="device-dropdown" id="device-select">
2308
- ${ha.map(n=>`
2308
+ ${ra.map(n=>`
2309
2309
  <optgroup label="${n.label}">
2310
2310
  ${n.devices.map(i=>`
2311
2311
  <option value="${i.id}" ${i.id===this.currentPreset.id?"selected":""}>
@@ -2488,7 +2488,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2488
2488
  </div>
2489
2489
 
2490
2490
  </div>
2491
- `,this.setupEventListeners(e),e}setupEventListeners(e){var M,O,w,P,_,T,I,C;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",A=>{if(this.viewMode==="compare")return;let E=A.target.value;this.setDevice(E)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",A=>{let E=A.target.value;this.setTheme(E)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let E=A.dataset.viewToggle;E&&this.setViewMode(E)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let E=A.dataset.layoutToggle;E&&this.setLayoutMode(E)})});let r=e.querySelector("#scene-toggle");r==null||r.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=A=>{let E=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${A}::${E}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(A,E,x)=>{A&&(A.textContent=E?`${x} On`:`${x} Off`,A.setAttribute("aria-pressed",E?"true":"false"))},u=()=>{let A=window.localStorage.getItem(l("grid_gap")),E=Number(A!=null?A:50);return Number.isFinite(E)?E:50},g=A=>{try{window.localStorage.setItem(l("grid_enabled"),A?"true":"false")}catch{}p(c,A,"Grid");let E=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:E}}))},h=A=>{try{window.localStorage.setItem(l("play_mode"),A?"true":"false")}catch{}p(d,A,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:A}}))};try{let A=window.localStorage.getItem(l("grid_enabled"))==="true",E=window.localStorage.getItem(l("play_mode"))==="true";if(p(c,A,"Grid"),p(d,E,"Play"),c){let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:E}}))}catch{}c==null||c.addEventListener("click",()=>{let A=c.getAttribute("aria-pressed")==="true";g(!A)}),d==null||d.addEventListener("click",()=>{let A=d.getAttribute("aria-pressed")==="true";h(!A)}),(M=e.querySelector("#rotate-btn"))==null||M.addEventListener("click",()=>this.toggleRotation()),(O=e.querySelector("#zoom-in-btn"))==null||O.addEventListener("click",()=>this.adjustUserZoom(.1)),(w=e.querySelector("#zoom-out-btn"))==null||w.addEventListener("click",()=>this.adjustUserZoom(-.1)),(P=e.querySelector("#refresh-btn"))==null||P.addEventListener("click",()=>this.refresh());let m=e.querySelector("#bottom-dock"),f=e.querySelector("#bottom-dock-resize");m&&f&&this.makeBottomDockResizable(m,f);let y=Array.from(e.querySelectorAll(".bottom-dock-tab"));y.forEach(A=>{A.addEventListener("click",()=>{let E=A.dataset.dockTab;if(!E)return;y.forEach(j=>j.classList.remove("active")),A.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(j=>{let k=j.dataset.dockPanel;j.classList.toggle("active",k===E)})})}),(_=e.querySelector("#console-clear"))==null||_.addEventListener("click",()=>this.clearConsole()),(T=e.querySelector("#corner-zoom-in-btn"))==null||T.addEventListener("click",()=>this.adjustUserZoom(.1)),(I=e.querySelector("#corner-zoom-out-btn"))==null||I.addEventListener("click",()=>this.adjustUserZoom(-.1)),(C=e.querySelector("#corner-grab-btn"))==null||C.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let b=e.querySelector(".scene-panel.scene-objects"),v=b==null?void 0:b.querySelector("[data-panel-resize-v]");b&&v&&this.makeSidebarResizable(b,v,"left");let S=e.querySelector(".debug-workbench"),L=S==null?void 0:S.querySelector("#workbench-resize-v");S&&L&&this.makeSidebarResizable(S,L,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=i/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(r,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let n=this.gameViewPane||this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),jn();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),On();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=Be().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,n;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(n=(t=this.options).onDeviceChange)==null||n.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(r=>typeof r=="object"?this.safeStringify(r):String(r)).join(" ");this.consoleMessages.push({type:t,message:i,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let r=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=r>0?`${r}!`:"0",a.classList.toggle("has-errors",r>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(p=>p.id===n);if(!i)return;let a=t.querySelector("[data-compare-slot]"),r=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!r||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:r,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let n=this.container.querySelector("#rotate-btn");n&&(n.disabled=e==="compare");let i=this.container.querySelector("#scene-toggle");if(i&&(i.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,r=i/e.preset.height,o=Math.max(.01,Math.min(a,r));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,r=t.canvas.height,o=Math.min(a/n.width,r/n.height),l=n.width*o,c=n.height*o,d=(a-l)/2,p=(r-c)/2;i.clearRect(0,0,a,r),i.drawImage(n,d,p,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let n=this.gameViewPane||this.previewContainer;return{width:n.clientWidth-40,height:n.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function Ya(s={}){let e=new Li(s);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}Z();function Ka(s){try{if(s&&typeof s.keys=="function")return Array.from(s.keys())}catch{}return[]}function qr(s){var e;return s?((e=s.getDisplayObject)==null?void 0:e.call(s))||s.pixiObject||s:null}function Il(s,e){if(!s||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);s.eventMode=n?"static":"none",s.interactive=n,n&&(s.cursor=t.draggable?"move":"pointer")}function Vr(s,e){var d,p,u;if(!s||!e)return;let t=e.transform||{};Il(s,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0),o=333,l=111;a+=o,r+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,r,"(raw + 333, +111)"),(d=s.position)!=null&&d.set?s.position.set(a,r):(typeof s.x=="number"&&(s.x=a),typeof s.y=="number"&&(s.y=r)),typeof t.scale=="number"&&((p=s.scale)!=null&&p.set?s.scale.set(t.scale):s.scale&&(s.scale.x=t.scale,s.scale.y=t.scale));let c=t.anchor;if(c&&((u=s.anchor)!=null&&u.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&s.anchor.set(g.x,g.y)}}function Wr(s){if(typeof window=="undefined")return;let e=s==null?void 0:s.objects,t=Ka(e),n=a=>{var r;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(r=l==null?void 0:l.screenToInstances)==null?void 0:r[o];if(Array.isArray(c)&&c.length>0){let p=new Set(c);return a.filter(u=>p.has(u))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(p=>d[p]===o):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Wr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(Ka((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Ka((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,m,f;let r=(h=(g=(u=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:u.get)==null?void 0:g.call(u,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.screenToInstances)==null?void 0:m[o];if(Array.isArray(c))return c.includes(a)?r:null;let d=(f=l==null?void 0:l.instanceToScreen)==null?void 0:f[a];return d&&d===o?r:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return a}}function _l(){if(typeof window=="undefined")return;let s=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,r,o;let i=s(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Et(),Us))]),d=Date.now(),p=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${d}`:`?t=${d}`),u=await l.load(p);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let h=window.gameObjectManager,m=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(m){let f=((o=m.getDisplayObject)==null?void 0:o.call(m))||m.pixiObject||m.pixi||m;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let y=f.children.find(b=>b==null?void 0:b.texture);y!=null&&y.texture&&(y.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=ie();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Fe(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=ie();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Fe(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,r]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:r});if(t.assets)for(let[a,r]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:r}),typeof r=="string"&&e(a,r);if(t.splash)for(let[a,r]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:r});if(t.loading)for(let[a,r]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:r});if(t.start)for(let[a,r]of Object.entries(t.start))i.push({path:`start.${a}`,value:r});i.length&&Fe(i,{silent:!0,persist:!0,emitEvent:!0})}}function Ti(s){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=s;t&&(t.onObjectRebuildRequired=async(a,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let p=window.gameApp,u=await ve.create(a,r,p);c&&(d!==void 0&&d!==-1?c.addChildAt(u,d):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(_l(),window.applyEditableObjectConfig=(a,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let p=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!p),p&&(console.log("[LIVE-EDIT] gameObject type:",(c=p.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof p.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof p.onConfigUpdate=="function")),p&&typeof p.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),p.updateConfig(r);else if(p&&typeof p.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),p.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=qr(p);Vr(u,r)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let i={async applyObjectConfig(a,r){var d,p;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(p=t==null?void 0:t.get)==null?void 0:p.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(r);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=qr(l);Vr(u,r)}let c=[a];n==null||n(a,r,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Wr(a))}};return i.rebuildIndexes(),i}Z();var Xr=vt(require("lottie-web"),1);Fi(Ni);typeof window!="undefined"&&!window.lottie&&(window.lottie=Xr.default);var Mt=null,jl=async()=>{if(!Mt){let s=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(s==null?void 0:s["handler.config"])||(s==null?void 0:s["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);Mt=JSON.parse(n)}else Mt=JSON.parse(e);return Mt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}Mt=await(await fetch("./handler.config.json")).json()}return Mt},Za,on,Jr,It,Xa,Ja;function Ol(s){Za=s.initGame,on=s.CustomAssets,Jr=s.updateScreenState,It=s.globalResponsiveMultipliers,Xa=s.layout,Ja=s.clearResponsiveElements}var ki="web_embed",rn="https://example.com",Yr={profile_id:ki},Ye=null,xe=null,sn={width:0,height:0},Rl=!0,zl=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let s=await jl();Yr={...s.ids||{},profile_id:ki},rn=s.destination_url||((d=(c=s.export_profiles)==null?void 0:c[ki])==null?void 0:d.destination_url)||rn,it.init({ids:Yr,profile:ki,destinationUrl:rn});let e=it.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),xe=Ya({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),Kr()},onRefresh:Kr});let g=xe.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,S,L,M,O,w,P,_,T,I,C,A,E;let m=window.gameApp,f=window.gameObjectManager,{width:y,height:b}=h.detail;if(sn.width=y,sn.height=b,Jr(y,b),!(!m||!m.renderer)){f&&o(m,f);try{m.renderer.resize(y,b);let x=m.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&f&&Xa)try{let x=(v=window.__mainContainer)!=null?v:m.stage,j=(P=(w=(M=window.__tutorialLabel)!=null?M:(L=(S=f.get("label_1"))==null?void 0:S.getDisplayObject)==null?void 0:L.call(S))!=null?w:(O=f.get("label_1"))==null?void 0:O.pixiObject)!=null?P:f.get("label_1"),k=f.get("background_1"),R=(C=(I=(T=window.__background)!=null?T:(_=k==null?void 0:k.getDisplayObject)==null?void 0:_.call(k))!=null?I:k==null?void 0:k.pixiObject)!=null?C:k;if(x){let z=x===m.stage;Xa({mainContainer:x,label:j,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:m},t,0,sn,f,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:sn.width,height:sn.height,presetId:(E=(A=h.detail)==null?void 0:A.presetId)!=null?E:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Oe("scene.main");window.__editableConfig=t,r(),window.__editableConfigBaseline||(window.__editableConfigBaseline=J(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 Oe("scene.main"));let n=await Za(e,t,rn,xe);Ye=n.app;let i=n.gameObjectManager;window.gameApp=Ye,window.gameObjectManager=i;try{window.__liveEditBridge=Ti({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:on})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}xe&&xe.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(It.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Ye,i);async function r(){try{let g=async b=>{let v=b.startsWith("/")?b:`/${b}`,S=await fetch(v,{cache:"no-cache"});if(!S.ok)return null;let L=await S.text();try{return JSON.parse(L)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let m=h.screens;if(!m||typeof m!="object")return;let f={},y={};for(let[b,v]of Object.entries(m)){let S=v==null?void 0:v.source;if(typeof S!="string")continue;let L=await g(S),M=L==null?void 0:L.elements;if(!Array.isArray(M))continue;let O=M.map(w=>w==null?void 0:w.instance_id).filter(w=>typeof w=="string");f[b]=O;for(let w of O)y[w]||(y[w]=b)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:y},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Rl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${It.scale.toFixed(3)}`),g.stage){let f=function(y,b=0){if(!y||!y.children)return;let v=" ".repeat(b);y.children.forEach((S,L)=>{if(S&&S.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(S&&S.scale){let M=S.scale.x||1,O=S.scale.y||1;S.__originalScale||(S.__originalScale={x:M,y:O},console.log(`${v}[RESPONSIVE] Stored original scale for child[${L}]: ${M.toFixed(3)}, ${O.toFixed(3)}`));let w=S.__originalScale.x*It.scale,P=S.__originalScale.y*It.scale;typeof S.scale.set=="function"?S.scale.set(w,P):(S.scale.x=w,S.scale.y=P),console.log(`${v}[RESPONSIVE] Child[${L}] scale: ${M.toFixed(3)}\u2192${S.scale.x.toFixed(3)} (type: ${S.constructor.name})`),f(S,b+1)}else S&&console.log(`${v}[RESPONSIVE] Child[${L}] has no scale (type: ${S.constructor.name})`)})};var m=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(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){It.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,m=window.gameObjectManager;h&&m?(o(h,m),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!m}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,it.start()},Kr=async()=>{var e,t,n,i;console.log("[PREVIEW] Restarting game in 1 seconds...");let s=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(s){let a=((t=s.getDisplayObject)==null?void 0:t.call(s))||s;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(xe){xe.notifyGameDestroyed();try{Ja&&Ja()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=xe.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),Ye){try{Ye.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Ye=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof on.resetScene=="function"&&on.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Oe("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=J(o)),Za(a,o,rn).then(l=>{Ye=l.app,window.gameApp=Ye,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Ti({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:on})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}xe&&xe.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{it.start()}catch{}})})},100)},1e3)}};Fn();Z();var Se={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Zr=1.25,Qr={fontFamily:"Inter, system-ui, sans-serif"};var Pi=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=`
2491
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var I,O,w,k,_,L,M,C;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",A=>{if(this.viewMode==="compare")return;let S=A.target.value;this.setDevice(S)});let n=e.querySelector("#theme-select");n==null||n.addEventListener("change",A=>{let S=A.target.value;this.setTheme(S)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.viewToggle;S&&this.setViewMode(S)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.layoutToggle;S&&this.setLayoutMode(S)})});let r=e.querySelector("#scene-toggle");r==null||r.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!this.sceneVisiblePreference),this.updateSceneVisibility())});let o=e.querySelector("#scene-hide-btn");o==null||o.addEventListener("click",()=>{this.viewMode!=="compare"&&(this.setSceneVisible(!1),this.updateSceneVisibility())});let l=A=>{let S=typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default";return`handler_preview_scene_${A}::${S}`},c=e.querySelector("#scene-grid-btn"),d=e.querySelector("#scene-play-btn"),p=(A,S,x)=>{A&&(A.textContent=S?`${x} On`:`${x} Off`,A.setAttribute("aria-pressed",S?"true":"false"))},u=()=>{let A=window.localStorage.getItem(l("grid_gap")),S=Number(A!=null?A:50);return Number.isFinite(S)?S:50},g=A=>{try{window.localStorage.setItem(l("grid_enabled"),A?"true":"false")}catch{}p(c,A,"Grid");let S=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:S}}))},h=A=>{try{window.localStorage.setItem(l("play_mode"),A?"true":"false")}catch{}p(d,A,"Play"),window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:A}}))};try{let A=window.localStorage.getItem(l("grid_enabled"))==="true",S=window.localStorage.getItem(l("play_mode"))==="true";if(p(c,A,"Grid"),p(d,S,"Play"),c){let x=u();window.dispatchEvent(new CustomEvent("scene-editor:grid",{detail:{enabled:A,gap:x}}))}d&&window.dispatchEvent(new CustomEvent("scene-editor:play-mode",{detail:{enabled:S}}))}catch{}c==null||c.addEventListener("click",()=>{let A=c.getAttribute("aria-pressed")==="true";g(!A)}),d==null||d.addEventListener("click",()=>{let A=d.getAttribute("aria-pressed")==="true";h(!A)}),(I=e.querySelector("#rotate-btn"))==null||I.addEventListener("click",()=>this.toggleRotation()),(O=e.querySelector("#zoom-in-btn"))==null||O.addEventListener("click",()=>this.adjustUserZoom(.1)),(w=e.querySelector("#zoom-out-btn"))==null||w.addEventListener("click",()=>this.adjustUserZoom(-.1)),(k=e.querySelector("#refresh-btn"))==null||k.addEventListener("click",()=>this.refresh());let m=e.querySelector("#bottom-dock"),f=e.querySelector("#bottom-dock-resize");m&&f&&this.makeBottomDockResizable(m,f);let y=Array.from(e.querySelectorAll(".bottom-dock-tab"));y.forEach(A=>{A.addEventListener("click",()=>{let S=A.dataset.dockTab;if(!S)return;y.forEach(j=>j.classList.remove("active")),A.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(j=>{let T=j.dataset.dockPanel;j.classList.toggle("active",T===S)})})}),(_=e.querySelector("#console-clear"))==null||_.addEventListener("click",()=>this.clearConsole()),(L=e.querySelector("#corner-zoom-in-btn"))==null||L.addEventListener("click",()=>this.adjustUserZoom(.1)),(M=e.querySelector("#corner-zoom-out-btn"))==null||M.addEventListener("click",()=>this.adjustUserZoom(-.1)),(C=e.querySelector("#corner-grab-btn"))==null||C.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let b=e.querySelector(".scene-panel.scene-objects"),v=b==null?void 0:b.querySelector("[data-panel-resize-v]");b&&v&&this.makeSidebarResizable(b,v,"left");let E=e.querySelector(".debug-workbench"),P=E==null?void 0:E.querySelector("#workbench-resize-v");E&&P&&this.makeSidebarResizable(E,P,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),n=this.getFitBounds(),i=Math.max(0,n.width),a=Math.max(0,n.height);if(i<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=i/t.width,o=a/t.height;if(this.autoScale=Math.max(.01,Math.min(r,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}(e==null?void 0:e.keepUserScaleMultiplier)!==void 0&&e.keepUserScaleMultiplier>0?this.userScaleMultiplier=e.keepUserScaleMultiplier:e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let n=this.gameViewPane||this.container.querySelector(".preview-container");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}else{let n=this.container.querySelector(".preview-main");n&&(e&&e.parentElement!==n&&n.appendChild(e),t&&t.parentElement!==n&&n.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}setupShortcutListeners(){window.addEventListener("keydown",e=>{if(this.isInputFocused())return;let t=navigator.platform.toUpperCase().indexOf("MAC")>=0,n=e.ctrlKey||e.metaKey,i=e.shiftKey;if(n&&e.key==="s"&&!i){e.preventDefault();let a=document.querySelector("#apply-current-btn");a&&a.getAttribute("disabled")===null&&a.click();return}if(n&&e.key==="z"&&!i){e.preventDefault(),En();return}if(n&&(e.key==="z"&&i||e.key==="y"&&!i)){e.preventDefault(),Cn();return}})}setupUnsavedChangesIndicator(){let e=this.container.querySelector("#preview-save-shortcut-text");e&&(e.textContent=`(${this.getShortcutKey()} + S)`),window.addEventListener("config:changed",()=>{this.updateUnsavedChangesIndicator()}),this.updateUnsavedChangesIndicator();let t=this.container.querySelector("#preview-save-btn");t==null||t.addEventListener("click",()=>{let n=document.querySelector("#apply-current-btn");n&&n.getAttribute("disabled")===null&&n.click()})}updateUnsavedChangesIndicator(){let t=Fe().hasChanges;if(t!==this.hasUnsavedChanges){this.hasUnsavedChanges=t;let n=this.container.querySelector("#preview-unsaved-star"),i=this.container.querySelector("#preview-save-btn");n&&(n.style.display=t?"inline-block":"none"),i&&(i.style.display=t?"inline-flex":"none")}}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,n;if(this.viewMode==="compare")return;let e=this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepUserScaleMultiplier:e}),(n=(t=this.options).onDeviceChange)==null||n.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(i,a)=>{if(typeof a=="object"&&a!==null){if(t.has(a))return"[Circular]";t.add(a)}return a},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...n)=>{let i=n.map(r=>typeof r=="object"?this.safeStringify(r):String(r)).join(" ");this.consoleMessages.push({type:t,message:i,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let a=this.container.querySelector("#console-badge");if(a){let r=this.consoleMessages.filter(o=>o.type==="error").length;a.textContent=r>0?`${r}!`:"0",a.classList.toggle("has-errors",r>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let n=document.createElement("div");n.className=`console-msg type-${e.type}`;let i=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(i)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let n=this.container.querySelector('[data-dock-tab="console"]');if(n){n.click();let i=this.container.querySelector("#bottom-dock");i==null||i.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let n=t.dataset.viewport;if(!n)return;let i=this.comparePresets.find(p=>p.id===n);if(!i)return;let a=t.querySelector("[data-compare-slot]"),r=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),d=t.querySelector("[data-compare-focus]");!a||!r||!o||!l||(t.addEventListener("click",p=>{let u=p.target;if(u!=null&&u.closest("[data-compare-focus]")){p.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:i,root:t,slot:a,ghost:r,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let n=this.container.querySelector("#rotate-btn");n&&(n.disabled=e==="compare");let i=this.container.querySelector("#scene-toggle");if(i&&(i.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots(),this.updateSceneVisibility();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen(),this.updateSceneVisibility()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var a,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,i=this.activeCompareId;i&&i!==e&&this.captureCompareSnapshot(i),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,i=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=i,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let n=Math.max(0,t.clientWidth-24),i=Math.max(0,t.clientHeight-24);if(n<=0||i<=0)return;let a=n/e.preset.width,r=i/e.preset.height,o=Math.max(.01,Math.min(a,r));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let i=t.canvas.getContext("2d");if(!i)return;let a=t.canvas.width,r=t.canvas.height,o=Math.min(a/n.width,r/n.height),l=n.width*o,c=n.height*o,d=(a-l)/2,p=(r-c)/2;i.clearRect(0,0,a,r),i.drawImage(n,d,p,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare"){let n=this.gameViewPane||this.previewContainer;return{width:n.clientWidth-40,height:n.clientHeight-40}}let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function Ha(s={}){let e=new fi(s);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}te();function Fa(s){try{if(s&&typeof s.keys=="function")return Array.from(s.keys())}catch{}return[]}function $r(s){var e;return s?((e=s.getDisplayObject)==null?void 0:e.call(s))||s.pixiObject||s:null}function El(s,e){if(!s||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);s.eventMode=n?"static":"none",s.interactive=n,n&&(s.cursor=t.draggable?"move":"pointer")}function Dr(s,e){var d,p,u;if(!s||!e)return;let t=e.transform||{};El(s,e);let n=t.position||{},i=t.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof i.x=="number"?i.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof i.y=="number"?i.y:0),o=333,l=111;a+=o,r+=l,console.log("[DEBUG FALLBACK] tryApplyTransform (live-edit) position.set",a,r,"(raw + 333, +111)"),(d=s.position)!=null&&d.set?s.position.set(a,r):(typeof s.x=="number"&&(s.x=a),typeof s.y=="number"&&(s.y=r)),typeof t.scale=="number"&&((p=s.scale)!=null&&p.set?s.scale.set(t.scale):s.scale&&(s.scale.x=t.scale,s.scale.y=t.scale));let c=t.anchor;if(c&&((u=s.anchor)!=null&&u.set)){let g=null;typeof window!="undefined"&&window.resolveAnchorVec2?g=window.resolveAnchorVec2(c):typeof c=="object"&&c.x!==void 0&&c.y!==void 0?g=c:Array.isArray(c)&&c.length===2&&(g={x:c[0],y:c[1]}),g&&typeof g.x=="number"&&typeof g.y=="number"&&s.anchor.set(g.x,g.y)}}function Nr(s){if(typeof window=="undefined")return;let e=s==null?void 0:s.objects,t=Fa(e),n=a=>{var r;try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return a;let l=window.__HANDLER_SCREEN_INDEX,c=(r=l==null?void 0:l.screenToInstances)==null?void 0:r[o];if(Array.isArray(c)&&c.length>0){let p=new Set(c);return a.filter(u=>p.has(u))}let d=l==null?void 0:l.instanceToScreen;return d?a.filter(p=>d[p]===o):a}catch{return a}};window.__editableObjectConfigs=e;let i=new Map;t.forEach(a=>i.set(a,[a])),window.__editableObjectInstances=i,window.refreshEditableConfigIndex=()=>Nr(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(Fa((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return Fa((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var p,u,g,h,m,f;let r=(h=(g=(u=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:u.get)==null?void 0:g.call(u,a))!=null?h:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.screenToInstances)==null?void 0:m[o];if(Array.isArray(c))return c.includes(a)?r:null;let d=(f=l==null?void 0:l.instanceToScreen)==null?void 0:f[a];return d&&d===o?r:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return a}}function Cl(){if(typeof window=="undefined")return;let s=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var a,r,o;let i=s(n);if(i)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(gt(),Rs))]),d=Date.now(),p=/^(data:|blob:)/.test(i)?i:i+(i.includes("?")?`&t=${d}`:`?t=${d}`),u=await l.load(p);if(!u)return;c[t]=u;let g=window.CustomAssets;(a=g==null?void 0:g[t])!=null&&a.texture&&(g[t].texture=u);let h=window.gameObjectManager,m=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(m){let f=((o=m.getDisplayObject)==null?void 0:o.call(m))||m.pixiObject||m.pixi||m;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let y=f.children.find(b=>b==null?void 0:b.texture);y!=null&&y.texture&&(y.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=re();Array.isArray(n)&&n.length&&(window.__editableConfig=t,He(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=re();Array.isArray(n)&&n.length&&(window.__editableConfig=t,He(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let i=[];if(t.runtime)for(let[a,r]of Object.entries(t.runtime))i.push({path:`runtime.${a}`,value:r});if(t.assets)for(let[a,r]of Object.entries(t.assets))i.push({path:`assets.${a}`,value:r}),typeof r=="string"&&e(a,r);if(t.splash)for(let[a,r]of Object.entries(t.splash))i.push({path:`splash.${a}`,value:r});if(t.loading)for(let[a,r]of Object.entries(t.loading))i.push({path:`loading.${a}`,value:r});if(t.start)for(let[a,r]of Object.entries(t.start))i.push({path:`start.${a}`,value:r});i.length&&He(i,{silent:!0,persist:!0,emitEvent:!0})}}function yi(s){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=s;t&&(t.onObjectRebuildRequired=async(a,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=t.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?t.remove(a):l&&l.destroy();let p=window.gameApp,u=await xe.create(a,r,p);c&&(d!==void 0&&d!==-1?c.addChildAt(u,d):c.addChild(u));let g=t.create(a,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),g}),typeof window!="undefined"&&(Cl(),window.applyEditableObjectConfig=(a,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let p=(l=t==null?void 0:t.get)==null?void 0:l.call(t,a);if(console.log("[LIVE-EDIT] gameObject found?",!!p),p&&(console.log("[LIVE-EDIT] gameObject type:",(c=p.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof p.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof p.onConfigUpdate=="function")),p&&typeof p.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),p.updateConfig(r);else if(p&&typeof p.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),p.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=$r(p);Dr(u,r)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let i={async applyObjectConfig(a,r){var d,p;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=e();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(p=t==null?void 0:t.get)==null?void 0:p.call(t,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(r);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=$r(l);Dr(u,r)}let c=[a];n==null||n(a,r,c)},rebuildIndexes(){let a=e();typeof window!="undefined"&&(window.__editableConfig=a,Nr(a))}};return i.rebuildIndexes(),i}te();var Br=ct(require("lottie-web"),1);ji(Mi);typeof window!="undefined"&&!window.lottie&&(window.lottie=Br.default);var wt=null,Al=async()=>{if(!wt){let s=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(s==null?void 0:s["handler.config"])||(s==null?void 0:s["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);wt=JSON.parse(n)}else wt=JSON.parse(e);return wt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}wt=await(await fetch("./handler.config.json")).json()}return wt},Ua,Xt,Gr,xt,Ba,Ga;function Ll(s){Ua=s.initGame,Xt=s.CustomAssets,Gr=s.updateScreenState,xt=s.globalResponsiveMultipliers,Ba=s.layout,Ga=s.clearResponsiveElements}var bi="web_embed",Kt="https://example.com",Hr={profile_id:bi},We=null,Ee=null,Yt={width:0,height:0},Tl=!0,kl=async()=>{var c,d,p,u;document.title="Handler Pixi Game";let s=await Al();Hr={...s.ids||{},profile_id:bi},Kt=s.destination_url||((d=(c=s.export_profiles)==null?void 0:c[bi])==null?void 0:d.destination_url)||Kt,Xe.init({ids:Hr,profile:bi,destinationUrl:Kt});let e=Xe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ee=Ha({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),Fr()},onRefresh:Fr});let g=Ee.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,E,P,I,O,w,k,_,L,M,C,A,S;let m=window.gameApp,f=window.gameObjectManager,{width:y,height:b}=h.detail;if(Yt.width=y,Yt.height=b,Gr(y,b),!(!m||!m.renderer)){f&&o(m,f);try{m.renderer.resize(y,b);let x=m.view;x&&(x.style.width="100%",x.style.height="100%",x.style.display="block")}catch(x){console.warn("[SCREEN] Error resizing renderer:",x);return}if(t&&f&&Ba)try{let x=(v=window.__mainContainer)!=null?v:m.stage,j=(k=(w=(I=window.__tutorialLabel)!=null?I:(P=(E=f.get("label_1"))==null?void 0:E.getDisplayObject)==null?void 0:P.call(E))!=null?w:(O=f.get("label_1"))==null?void 0:O.pixiObject)!=null?k:f.get("label_1"),T=f.get("background_1"),R=(C=(M=(L=window.__background)!=null?L:(_=T==null?void 0:T.getDisplayObject)==null?void 0:_.call(T))!=null?M:T==null?void 0:T.pixiObject)!=null?C:T;if(x){let z=x===m.stage;Ba({mainContainer:x,label:j,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:m},t,0,Yt,f,{skipMainContainerTransform:z}),window.dispatchEvent(new CustomEvent("handler:layout-applied",{detail:{width:Yt.width,height:Yt.height,presetId:(S=(A=h.detail)==null?void 0:A.presetId)!=null?S:null}}))}}catch(x){console.warn("[SCREEN] Error in layout:",x)}}})}let t=await Oe("scene.main");window.__editableConfig=t,r(),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 Oe("scene.main"));let n=await Ua(e,t,Kt,Ee);We=n.app;let i=n.gameObjectManager;window.gameApp=We,window.gameObjectManager=i;try{window.__liveEditBridge=yi({getConfig:()=>window.__editableConfig,gameObjectManager:i,assets:Xt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}Ee&&Ee.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(xt.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(We,i);async function r(){try{let g=async b=>{let v=b.startsWith("/")?b:`/${b}`,E=await fetch(v,{cache:"no-cache"});if(!E.ok)return null;let P=await E.text();try{return JSON.parse(P)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let m=h.screens;if(!m||typeof m!="object")return;let f={},y={};for(let[b,v]of Object.entries(m)){let E=v==null?void 0:v.source;if(typeof E!="string")continue;let P=await g(E),I=P==null?void 0:P.elements;if(!Array.isArray(I))continue;let O=I.map(w=>w==null?void 0:w.instance_id).filter(w=>typeof w=="string");f[b]=O;for(let w of O)y[w]||(y[w]=b)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:y},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Tl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${xt.scale.toFixed(3)}`),g.stage){let f=function(y,b=0){if(!y||!y.children)return;let v=" ".repeat(b);y.children.forEach((E,P)=>{if(E&&E.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(E&&E.scale){let I=E.scale.x||1,O=E.scale.y||1;E.__originalScale||(E.__originalScale={x:I,y:O},console.log(`${v}[RESPONSIVE] Stored original scale for child[${P}]: ${I.toFixed(3)}, ${O.toFixed(3)}`));let w=E.__originalScale.x*xt.scale,k=E.__originalScale.y*xt.scale;typeof E.scale.set=="function"?E.scale.set(w,k):(E.scale.x=w,E.scale.y=k),console.log(`${v}[RESPONSIVE] Child[${P}] scale: ${I.toFixed(3)}\u2192${E.scale.x.toFixed(3)} (type: ${E.constructor.name})`),f(E,b+1)}else E&&console.log(`${v}[RESPONSIVE] Child[${P}] has no scale (type: ${E.constructor.name})`)})};var m=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(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){xt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,m=window.gameObjectManager;h&&m?(o(h,m),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!m}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Xe.start()},Fr=async()=>{var e,t,n,i;console.log("[PREVIEW] Restarting game in 1 seconds...");let s=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(s){let a=((t=s.getDisplayObject)==null?void 0:t.call(s))||s;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((i=a.scale.y)!=null?i:1).toFixed(3)}`)}if(Ee){Ee.notifyGameDestroyed();try{Ga&&Ga()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ee.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),We){try{We.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}We=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof Xt.resetScene=="function"&&Xt.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{Oe("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=ee(o)),Ua(a,o,Kt).then(l=>{We=l.app,window.gameApp=We,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=yi({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Xt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}Ee&&Ee.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Xe.start()}catch{}})})},100)},1e3)}};Mn();te();var Ce={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},Ur=1.25,qr={fontFamily:"Inter, system-ui, sans-serif"};var vi=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=`
2492
2492
  position: fixed;
2493
2493
  inset: 0;
2494
2494
  display: flex;
@@ -2497,7 +2497,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2497
2497
  z-index: 50;
2498
2498
  user-select: none;
2499
2499
  overflow: hidden;
2500
- background-color: ${Se.background};
2500
+ background-color: ${Ce.background};
2501
2501
  `;let t=document.createElement("div");t.style.cssText=`
2502
2502
  position: relative;
2503
2503
  width: 288px;
@@ -2527,12 +2527,12 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2527
2527
  font-size: 12px;
2528
2528
  font-weight: 900;
2529
2529
  letter-spacing: 0.15em;
2530
- color: ${Se.ink};
2530
+ color: ${Ce.ink};
2531
2531
  `,r.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
2532
2532
  font-size: 10px;
2533
2533
  font-family: monospace;
2534
2534
  font-weight: bold;
2535
- color: ${Se.primaryAccent};
2535
+ color: ${Ce.primaryAccent};
2536
2536
  `,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,a.appendChild(r),a.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
2537
2537
  height: 4px;
2538
2538
  width: 100%;
@@ -2547,7 +2547,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2547
2547
  border-radius: 9999px;
2548
2548
  position: relative;
2549
2549
  width: ${this.currentProgress}%;
2550
- background-color: ${Se.primaryAccent};
2550
+ background-color: ${Ce.primaryAccent};
2551
2551
  `;let l=document.createElement("div");l.style.cssText=`
2552
2552
  position: absolute;
2553
2553
  inset: 0;
@@ -2586,7 +2586,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2586
2586
  font-size: 24px;
2587
2587
  letter-spacing: -0.05em;
2588
2588
  animation: handlerMove 2.5s linear infinite;
2589
- color: ${Se.ink};
2589
+ color: ${Ce.ink};
2590
2590
  display: flex;
2591
2591
  align-items: center;
2592
2592
  justify-content: center;
@@ -2599,7 +2599,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2599
2599
  letter-spacing: 0.3em;
2600
2600
  opacity: 0.2;
2601
2601
  text-transform: uppercase;
2602
- color: ${Se.ink};
2602
+ color: ${Ce.ink};
2603
2603
  `,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`,e.appendChild(t),e.appendChild(this.authSeq),this.injectStyles(),e}injectStyles(){if(document.getElementById("handler-loading-screen-styles"))return;let e=document.createElement("style");e.id="handler-loading-screen-styles",e.textContent=`
2604
2604
  /* Box Loading Styles */
2605
2605
  .boxLoading {
@@ -2630,7 +2630,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2630
2630
  content: '';
2631
2631
  width: 50px;
2632
2632
  height: 50px;
2633
- background: ${Se.primaryAccent};
2633
+ background: ${Ce.primaryAccent};
2634
2634
  animation: animate 0.5s linear infinite;
2635
2635
  position: absolute;
2636
2636
  top: 0;
@@ -2687,7 +2687,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=i,this.currentPrompt=i}}c
2687
2687
  0%, 100% { opacity: 1; }
2688
2688
  50% { opacity: 0.3; }
2689
2689
  }
2690
- `,document.head.appendChild(e)}setProgress(e){this.currentProgress=Math.max(0,Math.min(100,e)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(e=document.body){e.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var Qa=vs.version,$l=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);bs();var ro={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},oo=Math.random().toString(36).slice(2),Ot=null,_t={...ro},lo="web_embed",is={},cn,es=!1,ln=!1,pn=!1,co=!1,os=1,Ii=0,Oi=!1,ze=!1,jt="",Rt=Math.floor(window.innerWidth),zt=Math.floor(window.innerHeight),as=Rt>zt,$e=!1,dn=!1,eo=!1,to=!1,ts=!1,_i=null,gt=null,ss=!1,rs=!1,Mi=new Map;function po(){if(!gt)return null;let s=Date.now()-gt;return!Number.isFinite(s)||s<0?null:s}function ns(s){if(ss)return;let e=po();e!==null&&(ss=!0,D("session_time",{duration_ms:e,reason:s}))}function no(){if(Ot)return Ot;let s=document.createElement("div");return s.id="handler-root",s.setAttribute("data-handler-root","true"),document.body.appendChild(s),Ot=s,s}function ji(s){switch(s){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return s}}function uo(s,e){return{event_name:s,ts:Date.now(),session_id:oo,deployment_id:_t.deployment_id,variant_id:_t.variant_id,export_profile_id:_t.profile_id,instance_id:_t.instance_id||"default",env:lo==="mraid"?"mraid":"web",attribution:cn,payload:e}}function D(s,e){let t=ji(s),n=uo(t,e);zi(n,!!is.analytics),yn(t,n),t!==s&&yn(s,n)}function un(){_i&&(_i(Rt,zt),_i=null)}function $t(s){os=s,D("volume",s)}function Dt(s){s&&(co=!0),!pn&&(pn=!0,D("pause"),$t(0))}function gn(s){!s&&co||pn&&(pn=!1,D("resume"),$t(os))}function Ke(s,e){Rt=Math.floor(s||window.innerWidth),zt=Math.floor(e||window.innerHeight),as=Rt>zt,D("resize",{width:Rt,height:zt})}function Dl(){if(Is())try{let s=mraid.getMaxSize();Ke(s.width,s.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?gn():Dt()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Ke(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();$t(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&$t(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),Oi=!0,mraid.isViewable()&&mraid.getState()!=="hidden")$e=!0,D("boot"),D("view"),D("ready"),ze=!0,un();else{let t=()=>{$e=!0,D("boot"),D("view"),D("ready"),ze=!0,un()};mraid.addEventListener("ready",t)}}catch(s){console.warn("MRAID hook skipped",s)}}function Nl(){if(_s())try{let s=dapi.getScreenSize();Ke(s.width,s.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?gn():Dt()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Ke(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if($t(e?1:0),dapi.addEventListener("audioVolumeChange",t=>$t(t?1:0)),Oi=!0,dapi.isViewable())$e=!0,D("boot"),D("view"),D("ready"),ze=!0,un();else{let t=()=>{$e=!0,D("boot"),D("view"),D("ready"),ze=!0,un()};dapi.addEventListener("ready",t)}}catch(s){console.warn("DAPI hook skipped",s)}}function io(){let s=()=>{$e||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&($e=!0,D("boot"),D("view"),D("ready"),ze=!0,un(),dn&&(dn=!1,he.start()))};window.addEventListener("resize",()=>Ke()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(gn(),s()):Dt()}),document.readyState==="complete"||document.readyState==="interactive"?s():window.addEventListener("load",s),Oi=!0}function Hl(){let s=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(eo=!0),!(eo&&e instanceof MouseEvent)&&(Ii+=1,rs||(rs=!0,D("first_interaction",{count:Ii})),D("interaction",Ii))};document.addEventListener("mousedown",s),document.addEventListener("touchstart",s)}function ao(s){var n,i,a,r,o,l,c,d,p,u,g,h;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(s||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(St())(a=(i=window.TJ_API)==null?void 0:i.click)==null||a.call(i);else if(js())(o=(r=window.FbPlayableAd)==null?void 0:r.onCTAClick)==null||o.call(r);else if($s())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(zs())try{(p=(d=window.smxTracking)==null?void 0:d.redirect)==null||p.call(d)}catch(m){console.warn("Smadex redirect failed",m)}else if(Os()){let m=window.ExitApi;m&&typeof m.exit=="function"?m.exit(s||jt||""):s&&window.open(s)}else xt()?(u=window.install)==null||u.call(window):Rs()?(g=window.openAppStore)==null||g.call(window):$i()?(h=parent==null?void 0:parent.postMessage)==null||h.call(parent,"download","*"):s&&window.open(s)}function Fl(){let s=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(s==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;re("view",()=>e(t.mraid_viewable)),re("start",()=>e(t.game_viewable)),re("engagement",()=>e(t.engagement));let n=()=>e(t.complete);re("complete",n),fn("engagement",i=>{var a;((a=i==null?void 0:i.payload)==null?void 0:a.count)>3&&n()}),re("cta_click",()=>e(t.click))}else if(s==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;re("view",()=>e(t.Ad_Load_Start)),re("start",()=>e(t.Ad_Viewable)),re("engagement",()=>e(t.First_Engagement)),re("complete",()=>e(t.Gameplay_Complete)),re("cta_click",()=>e(t.DSP_Click)),re("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function Bl(){if(!St())return;let s=window.TJ_API;s&&s.setPlayableAPI&&s.setPlayableAPI({skipAd:()=>{try{he.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function so(){var e,t,n;let s=window.TJ_API;(e=s==null?void 0:s.objectiveComplete)==null||e.call(s),(t=s==null?void 0:s.playableFinished)==null||t.call(s),(n=s==null?void 0:s.gameplayFinished)==null||n.call(s)}function Ul(){xt()&&(window.mintGameStart=()=>{gn(!0),Ke()},window.mintGameClose=()=>{Dt(!0)})}function Gl(){if(!Di())return;let s=window.NUC;!s||!s.trigger||(he.on("cta_click",()=>{var e,t;return(t=(e=s.trigger).convert)==null?void 0:t.call(e,jt)}),he.on("complete",()=>{var e,t;return(t=(e=s.trigger).tryAgain)==null?void 0:t.call(e)}))}var he={init(s={},e){var t;if(lo=s.profile||"web_embed",is=s.consent||{},_t={...ro,...s.ids||{}},Ot=s.rootEl||Ot,cn=void 0,ps((t=s.telemetry)!=null&&t.endpoint?s.telemetry:null),gt=null,ss=!1,rs=!1,Mi.clear(),jt=s.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(_i=e),D("init"),document.body.oncontextmenu=()=>!1,no(),Vl(Ot),Ds(),Dl(),Nl(),!Oi){if(document.readyState==="complete")io();else if(!to){to=!0;let n=()=>{io(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}Hl(),Fl(),Bl(),Ul(),Gl(),console.log(`%c @handler/playable-sdk %c v${Qa} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),$e&&!ze&&(D("boot"),D("view"),D("ready"),dn&&(dn=!1,he.start()),ze=!0),ze=$e},getRoot(){return no()},get version(){return Qa},get maxWidth(){return Rt},get maxHeight(){return zt},get isLandscape(){return as},get isReady(){return ze},get isStarted(){return es},get isPaused(){return pn},get isFinished(){return ln},get volume(){return os},get interactions(){return Ii},on(s,e){fn(ji(s),e)},off(s,e){Ri(ji(s),e)},start(){var s,e;if(!es){if(!$e){dn=!0;return}if(es=!0,gt||(gt=Date.now()),D("start"),Ke(),xt())Dt(),(s=window.gameReady)==null||s.call(window);else if(St()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:as?"landscape":"portrait",buildID:Qa})}}},finish(){var s,e;ln||(ln=!0,D("complete"),ns("complete"),xt()?(s=window.gameEnd)==null||s.call(window):$i()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):St()&&so())},install(s){if(!ln){ln=!0,St()?(so(),setTimeout(()=>he.install(s),300)):(D("complete"),setTimeout(()=>he.install(s),0));return}ts||(ts=!0,setTimeout(()=>ts=!1,500),D("cta_click"),D("conversion"),ns("cta"),ao(s||jt))},emit(s,e){let t=ji(s);if(!$l.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${s} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=uo(t,e);zi(n,!!is.analytics),yn(t,n)},gameStart(){he.start()},gameEnd(){he.finish()},ctaClick(s,e){D("cta_click",{url:s||jt,manual:!0}),(e==null?void 0:e.open)!==!1&&ao(s||jt)},ctaShow(s){D("cta_show",s)},ctaDismiss(s){D("cta_dismiss",s)},getGameTimeMs(){return po()},endSession(s="manual"){ns(s)},setAttribution(s){cn=s},abTest(s,e){if(!s)throw new Error("abTest requires experimentId");if(!Array.isArray(e)||e.length<2)throw new Error("abTest requires at least 2 variants");let t=Math.abs(ql(`${oo}:${s}`))%e.length,n=e[t];return cn={...cn||{},experiment_id:s},_t.variant_id=n,D("ab_assign",{experiment_id:s,variant_id:n}),n},levelStart(s,e){gt||(gt=Date.now()),D("level_start",{level_id:s,...e})},levelComplete(s,e){D("level_complete",{level_id:s,...e})},levelFail(s,e){D("level_fail",{level_id:s,...e})},checkpoint(s,e){D("checkpoint",{checkpoint_id:s,...e})},reward(s,e){D("reward",{reward_id:s,...e})},tutorialStart(s,e){D("tutorial_start",{step_id:s,...e})},tutorialComplete(s,e){D("tutorial_complete",{step_id:s,...e})},tutorialSkip(s,e){D("tutorial_skip",{step_id:s,...e})},timerStart(s){s&&Mi.set(s,Date.now())},timerEnd(s,e="custom",t){if(!s)return;let n=Mi.get(s);if(!n)return;Mi.delete(s);let i=Date.now()-n;if(!(!Number.isFinite(i)||i<0)){if(e==="custom"){D("engagement",{action:"timer",key:s,duration_ms:i,...t});return}D(e,{key:s,duration_ms:i,...t})}},fps(s,e){D("fps",{value:s,...e})},memory(s,e){D("memory",{bytes:s,...e})},assetLoadStart(s,e){D("asset_load_start",{asset_id:s,...e})},assetLoadComplete(s,e){D("asset_load_complete",{asset_id:s,...e})},reportError(s,e,t){D("error",{code:s,message:e,...t})},retry(){var s,e,t;if(xt())(s=window.gameRetry)==null||s.call(window);else if(Di()){let n=window.NUC;(t=(e=n==null?void 0:n.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}D("engagement",{action:"retry"})},pause(){Dt(!0)},resume(){gn(!0)},resize(s,e){Ke(s,e)}},it=he;function ql(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function Vl(s){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
2690
+ `,document.head.appendChild(e)}setProgress(e){this.currentProgress=Math.max(0,Math.min(100,e)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(e=document.body){e.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var qa=ps.version,Pl=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);ds();var Zr={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},Qr=Math.random().toString(36).slice(2),Ct=null,St={...Zr},eo="web_embed",Ka={},Zt,Va=!1,Jt=!1,en=!1,to=!1,Qa=1,xi=0,Ci=!1,ze=!1,Et="",At=Math.floor(window.innerWidth),Lt=Math.floor(window.innerHeight),Xa=At>Lt,$e=!1,Qt=!1,Vr=!1,Wr=!1,Wa=!1,Si=null,rt=null,Ja=!1,Za=!1,wi=new Map;function no(){if(!rt)return null;let s=Date.now()-rt;return!Number.isFinite(s)||s<0?null:s}function Ya(s){if(Ja)return;let e=no();e!==null&&(Ja=!0,D("session_time",{duration_ms:e,reason:s}))}function Yr(){if(Ct)return Ct;let s=document.createElement("div");return s.id="handler-root",s.setAttribute("data-handler-root","true"),document.body.appendChild(s),Ct=s,s}function Ei(s){switch(s){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return s}}function io(s,e){return{event_name:s,ts:Date.now(),session_id:Qr,deployment_id:St.deployment_id,variant_id:St.variant_id,export_profile_id:St.profile_id,instance_id:St.instance_id||"default",env:eo==="mraid"?"mraid":"web",attribution:Zt,payload:e}}function D(s,e){let t=Ei(s),n=io(t,e);ki(n,!!Ka.analytics),on(t,n),t!==s&&on(s,n)}function tn(){Si&&(Si(At,Lt),Si=null)}function Tt(s){Qa=s,D("volume",s)}function kt(s){s&&(to=!0),!en&&(en=!0,D("pause"),Tt(0))}function nn(s){!s&&to||en&&(en=!1,D("resume"),Tt(Qa))}function Ye(s,e){At=Math.floor(s||window.innerWidth),Lt=Math.floor(e||window.innerHeight),Xa=At>Lt,D("resize",{width:At,height:Lt})}function Il(){if(Es())try{let s=mraid.getMaxSize();Ye(s.width,s.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?nn():kt()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Ye(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();Tt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&Tt(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),Ci=!0,mraid.isViewable()&&mraid.getState()!=="hidden")$e=!0,D("boot"),D("view"),D("ready"),ze=!0,tn();else{let t=()=>{$e=!0,D("boot"),D("view"),D("ready"),ze=!0,tn()};mraid.addEventListener("ready",t)}}catch(s){console.warn("MRAID hook skipped",s)}}function Ml(){if(Cs())try{let s=dapi.getScreenSize();Ye(s.width,s.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?nn():kt()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Ye(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(Tt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>Tt(t?1:0)),Ci=!0,dapi.isViewable())$e=!0,D("boot"),D("view"),D("ready"),ze=!0,tn();else{let t=()=>{$e=!0,D("boot"),D("view"),D("ready"),ze=!0,tn()};dapi.addEventListener("ready",t)}}catch(s){console.warn("DAPI hook skipped",s)}}function Kr(){let s=()=>{$e||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&($e=!0,D("boot"),D("view"),D("ready"),ze=!0,tn(),Qt&&(Qt=!1,be.start()))};window.addEventListener("resize",()=>Ye()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(nn(),s()):kt()}),document.readyState==="complete"||document.readyState==="interactive"?s():window.addEventListener("load",s),Ci=!0}function _l(){let s=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(Vr=!0),!(Vr&&e instanceof MouseEvent)&&(xi+=1,Za||(Za=!0,D("first_interaction",{count:xi})),D("interaction",xi))};document.addEventListener("mousedown",s),document.addEventListener("touchstart",s)}function Xr(s){var n,i,a,r,o,l,c,d,p,u,g,h;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(s||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(ut())(a=(i=window.TJ_API)==null?void 0:i.click)==null||a.call(i);else if(As())(o=(r=window.FbPlayableAd)==null?void 0:r.onCTAClick)==null||o.call(r);else if(Ps())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(ks())try{(p=(d=window.smxTracking)==null?void 0:d.redirect)==null||p.call(d)}catch(m){console.warn("Smadex redirect failed",m)}else if(Ls()){let m=window.ExitApi;m&&typeof m.exit=="function"?m.exit(s||Et||""):s&&window.open(s)}else pt()?(u=window.install)==null||u.call(window):Ts()?(g=window.openAppStore)==null||g.call(window):Pi()?(h=parent==null?void 0:parent.postMessage)==null||h.call(parent,"download","*"):s&&window.open(s)}function jl(){let s=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(s==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;ce("view",()=>e(t.mraid_viewable)),ce("start",()=>e(t.game_viewable)),ce("engagement",()=>e(t.engagement));let n=()=>e(t.complete);ce("complete",n),rn("engagement",i=>{var a;((a=i==null?void 0:i.payload)==null?void 0:a.count)>3&&n()}),ce("cta_click",()=>e(t.click))}else if(s==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;ce("view",()=>e(t.Ad_Load_Start)),ce("start",()=>e(t.Ad_Viewable)),ce("engagement",()=>e(t.First_Engagement)),ce("complete",()=>e(t.Gameplay_Complete)),ce("cta_click",()=>e(t.DSP_Click)),ce("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function Ol(){if(!ut())return;let s=window.TJ_API;s&&s.setPlayableAPI&&s.setPlayableAPI({skipAd:()=>{try{be.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Jr(){var e,t,n;let s=window.TJ_API;(e=s==null?void 0:s.objectiveComplete)==null||e.call(s),(t=s==null?void 0:s.playableFinished)==null||t.call(s),(n=s==null?void 0:s.gameplayFinished)==null||n.call(s)}function Rl(){pt()&&(window.mintGameStart=()=>{nn(!0),Ye()},window.mintGameClose=()=>{kt(!0)})}function zl(){if(!Ii())return;let s=window.NUC;!s||!s.trigger||(be.on("cta_click",()=>{var e,t;return(t=(e=s.trigger).convert)==null?void 0:t.call(e,Et)}),be.on("complete",()=>{var e,t;return(t=(e=s.trigger).tryAgain)==null?void 0:t.call(e)}))}var be={init(s={},e){var t;if(eo=s.profile||"web_embed",Ka=s.consent||{},St={...Zr,...s.ids||{}},Ct=s.rootEl||Ct,Zt=void 0,is((t=s.telemetry)!=null&&t.endpoint?s.telemetry:null),rt=null,Ja=!1,Za=!1,wi.clear(),Et=s.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(Si=e),D("init"),document.body.oncontextmenu=()=>!1,Yr(),Dl(Ct),Is(),Il(),Ml(),!Ci){if(document.readyState==="complete")Kr();else if(!Wr){Wr=!0;let n=()=>{Kr(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}_l(),jl(),Ol(),Rl(),zl(),console.log(`%c @handler/playable-sdk %c v${qa} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),$e&&!ze&&(D("boot"),D("view"),D("ready"),Qt&&(Qt=!1,be.start()),ze=!0),ze=$e},getRoot(){return Yr()},get version(){return qa},get maxWidth(){return At},get maxHeight(){return Lt},get isLandscape(){return Xa},get isReady(){return ze},get isStarted(){return Va},get isPaused(){return en},get isFinished(){return Jt},get volume(){return Qa},get interactions(){return xi},on(s,e){rn(Ei(s),e)},off(s,e){Ti(Ei(s),e)},start(){var s,e;if(!Va){if(!$e){Qt=!0;return}if(Va=!0,rt||(rt=Date.now()),D("start"),Ye(),pt())kt(),(s=window.gameReady)==null||s.call(window);else if(ut()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:Xa?"landscape":"portrait",buildID:qa})}}},finish(){var s,e;Jt||(Jt=!0,D("complete"),Ya("complete"),pt()?(s=window.gameEnd)==null||s.call(window):Pi()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):ut()&&Jr())},install(s){if(!Jt){Jt=!0,ut()?(Jr(),setTimeout(()=>be.install(s),300)):(D("complete"),setTimeout(()=>be.install(s),0));return}Wa||(Wa=!0,setTimeout(()=>Wa=!1,500),D("cta_click"),D("conversion"),Ya("cta"),Xr(s||Et))},emit(s,e){let t=Ei(s);if(!Pl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${s} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=io(t,e);ki(n,!!Ka.analytics),on(t,n)},gameStart(){be.start()},gameEnd(){be.finish()},ctaClick(s,e){D("cta_click",{url:s||Et,manual:!0}),(e==null?void 0:e.open)!==!1&&Xr(s||Et)},ctaShow(s){D("cta_show",s)},ctaDismiss(s){D("cta_dismiss",s)},getGameTimeMs(){return no()},endSession(s="manual"){Ya(s)},setAttribution(s){Zt=s},abTest(s,e){if(!s)throw new Error("abTest requires experimentId");if(!Array.isArray(e)||e.length<2)throw new Error("abTest requires at least 2 variants");let t=Math.abs($l(`${Qr}:${s}`))%e.length,n=e[t];return Zt={...Zt||{},experiment_id:s},St.variant_id=n,D("ab_assign",{experiment_id:s,variant_id:n}),n},levelStart(s,e){rt||(rt=Date.now()),D("level_start",{level_id:s,...e})},levelComplete(s,e){D("level_complete",{level_id:s,...e})},levelFail(s,e){D("level_fail",{level_id:s,...e})},checkpoint(s,e){D("checkpoint",{checkpoint_id:s,...e})},reward(s,e){D("reward",{reward_id:s,...e})},tutorialStart(s,e){D("tutorial_start",{step_id:s,...e})},tutorialComplete(s,e){D("tutorial_complete",{step_id:s,...e})},tutorialSkip(s,e){D("tutorial_skip",{step_id:s,...e})},timerStart(s){s&&wi.set(s,Date.now())},timerEnd(s,e="custom",t){if(!s)return;let n=wi.get(s);if(!n)return;wi.delete(s);let i=Date.now()-n;if(!(!Number.isFinite(i)||i<0)){if(e==="custom"){D("engagement",{action:"timer",key:s,duration_ms:i,...t});return}D(e,{key:s,duration_ms:i,...t})}},fps(s,e){D("fps",{value:s,...e})},memory(s,e){D("memory",{bytes:s,...e})},assetLoadStart(s,e){D("asset_load_start",{asset_id:s,...e})},assetLoadComplete(s,e){D("asset_load_complete",{asset_id:s,...e})},reportError(s,e,t){D("error",{code:s,message:e,...t})},retry(){var s,e,t;if(pt())(s=window.gameRetry)==null||s.call(window);else if(Ii()){let n=window.NUC;(t=(e=n==null?void 0:n.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}D("engagement",{action:"retry"})},pause(){kt(!0)},resume(){nn(!0)},resize(s,e){Ye(s,e)}},Xe=be;function $l(s){let e=2166136261;for(let t=0;t<s.length;t++)e^=s.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function Dl(s){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
2691
2691
  (function(){
2692
2692
  var events = ['touchstart','touchend','mousedown','keydown'];
2693
2693
  function unlock(){