handler-playable-sdk 0.3.42 → 0.3.43

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.
package/dist/index.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Or=Object.create;var Ht=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var jr=Object.getPrototypeOf,Dr=Object.prototype.hasOwnProperty;var ce=(i,e)=>()=>(i&&(e=i(i=0)),e);var ut=(i,e)=>{for(var t in e)Ht(i,t,{get:e[t],enumerable:!0})},Aa=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Rr(e))!Dr.call(i,a)&&a!==t&&Ht(i,a,{get:()=>e[a],enumerable:!(n=Ir(e,a))||n.enumerable});return i};var qe=(i,e,t)=>(t=i!=null?Or(jr(i)):{},Aa(e||!i||!i.__esModule?Ht(t,"default",{value:i,enumerable:!0}):t,i)),$r=i=>Aa(Ht({},"__esModule",{value:!0}),i);var de,oi=ce(()=>{"use strict";de=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()}};de.store=new Map});function qr(){var i,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(i=document.querySelector("script"))==null?void 0:i.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 Vr(){try{if(typeof window!="undefined"){let i=await fetch("./build-settings.json");if(i.ok){let e=await i.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Wr(){try{if(typeof window!="undefined"){let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Yr(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${N}`),Object.keys(pe).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(pe)),pe;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),pe={...window.INLINE_ASSETS},pe;if(!(N==="publish"&&se!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),pe;if(!li){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),li=(async()=>{try{try{let s=await import(e+"?t="+Date.now());if(s.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(s.INLINE_ASSETS)),s.INLINE_ASSETS}catch(s){console.warn("[AssetLoader] ES module import failed, trying text parse:",s)}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 a=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(a)try{let s=a[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+s)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(s){return console.warn("[AssetLoader] Failed to parse inline assets:",s),{}}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 pe=await li,console.log("[AssetLoader] Final inline assets cache:",Object.keys(pe)),pe}function ci(i){return i===null||typeof i!="object"||(Object.freeze(i),Object.values(i).forEach(e=>ci(e))),i}function Kr(i=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=i,n.height=e;let a=n.getContext("2d");return a.fillStyle=`#${t.toString(16).padStart(6,"0")}`,a.fillRect(0,0,i,e),a.strokeStyle="#000",a.strokeRect(0,0,i,e),a.fillStyle="#fff",a.font="10px sans-serif",a.textAlign="center",a.fillText("MISSING",i/2,e/2),ue.Texture.from(n)}function di(i,e){ns.set(i,e)}var ue,es,ts,Ie,N,se,we,pe,li,ns,Re,Gt=ce(()=>{"use strict";ue=require("pixi.js");oi();es=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ts=qr(),Ie=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,N=ts?"publish":es,se=Ie==null?void 0:Ie.assetsInlined;Ie!=null&&Ie.buildMode&&(N=Ie.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${N}`));we=Wr();we!=null&&we.buildMode&&(N=we.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${N}`));(we==null?void 0:we.assetsInlined)!==void 0&&(se=we.assetsInlined);Vr().then(i=>{i!=null&&i.buildMode&&i.buildMode!==N&&(N=i.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${N}`)),(i==null?void 0:i.assetsInlined)!==void 0&&(se=i.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${es}, Runtime: ${ts?"publish":"dev"}, Effective: ${N}`);pe={},li=null;ns=new Map;Re=class{static async load(e,t,n,a){let s=`${e}:${t.path}`,r=de.get(s);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${N}`),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 Yr(),l=o[e];if(!l&&a&&(l=o[a],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${a}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.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"),N==="publish"&&se!==!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 p=ns.get(t.type);if(p)try{let d=await p(t.path,l,e,n);return de.set(s,d),d}catch(d){return this.handleFailure(e,t.type,d)}try{let d;switch(t.type){case"image":d=await this.loadImage(t.path,l);break;case"json":d=await this.loadJSON(t.path,l),d=ci(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return de.set(s,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let n=N==="publish",a=n&&se!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){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 ue.Assets.load(t)}catch(s){throw console.error("[AssetLoader] Failed to load texture from data URI:",s),s}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await ue.Assets.load(t)}catch(s){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",s),await ue.Assets.load(e)}return await ue.Assets.load(e)}static async loadJSON(e,t){let n=N==="publish",a=n&&se!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){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 s=await fetch(e);if(!s.ok)throw new Error(`JSON fetch failed: ${e}`);return s.json()}static handleFailure(e,t,n){if(N==="dev"){let s=t==="image"?Kr():ci({__placeholder:!0,type:t});return de.set(e+":"+((n==null?void 0:n.path)||"missing"),s),s}throw n}};di("image",async(i,e)=>{let t=N==="publish",n=t&&se!==!1,a=N==="brand",s=t&&se===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, 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: ${i}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return ue.Assets.load(e)}let r=i;return(a||s)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(r=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${r}"`))),ue.Assets.load(e||r)});di("json",async(i,e)=>{let t=N==="publish",n=t&&se!==!1,a=N==="brand",s=t&&se===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, 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: ${i}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=i;if((a||s)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(r=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${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: ${i}`);return o.json()})});var as={};ut(as,{AssetTextures:()=>re,initAssetTextures:()=>gi});function gi(i,e){is.init(i,e),typeof window!="undefined"&&(window.__AssetTextures=re)}var ui,is,re,Ke=ce(()=>{"use strict";Gt();ui=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"]),a=[],s=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let p=async()=>{var d;try{let u=(d=l.identity)==null?void 0:d.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await Re.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)?a.push(p()):s.push(p())}a.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(a),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(s),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 a=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,p,d;try{let u=(p=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:p.call(c,o);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(a.length===0)return;this.ready().catch(()=>{});let s=()=>a.every(o=>this.textures.has(o)||this.attempted.has(o));if(s())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||s()&&(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:a}),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())}},is=new ui,re=new Proxy(is,{get(i,e){return e in i&&typeof i[e]=="function"?i[e].bind(i):i.get(e)},set(i,e,t){return i.set(e,t),!0}})});var sn={};ut(sn,{applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>ms,configOverrideManager:()=>bs,deepClone:()=>G,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setOverrideMode:()=>bi});function Qt(){return typeof window=="undefined"?null:window.__editableConfig||null}function ps(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function cs(i,e){var t,n;if(!i)return null;try{if(i instanceof Map)return(t=i.get(e))!=null?t:null;if(typeof i=="object")return(n=i[e])!=null?n:null}catch{}return null}function wo(i,e,t){if(i){if(i instanceof Map){i.set(e,t);return}typeof i=="object"&&(i[e]=t)}}function us(i,e){for(let t of e)yt(i,t.path,t.value)}function gs(i){var o;if(typeof window=="undefined")return;let e=Qt();if(!e)return;let t=ps(),n=(o=t?cs(t.objects,i):null)!=null?o:cs(e.objects,i);if(!n)return;let a=G(n),s=Y().filter(l=>l.objectId===i);try{us(a,s)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",i,l);return}wo(e.objects,i,a);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(i,a)}catch{}}function Eo(){var a;if(typeof window=="undefined")return;let i=Qt();if(!(i!=null&&i.engine))return;let e=ps(),t=G(((a=e==null?void 0:e.engine)!=null?a:i.engine)||{}),n=Y().filter(s=>!s.objectId&&!s.sceneId);try{us(t,n)}catch(s){console.error("[CONFIG] Failed to reapply engine overrides",s);return}try{let s=i.engine;for(let r of Object.keys(s))r in t||delete s[r];for(let[r,o]of Object.entries(t))s[r]=o}catch{i.engine=t}}function Ao(){if(typeof window=="undefined")return"unknown";let i=window;return typeof i.__HANDLER_PROJECT_ID=="string"?i.__HANDLER_PROJECT_ID:"handler-default"}function fs(){return`handler_preview_config_overrides::${Ao()}`}function So(){if(typeof window=="undefined")return[];try{let i=window.localStorage.getItem(fs());if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}function en(i){if(typeof window!="undefined")try{window.localStorage.setItem(fs(),JSON.stringify(i))}catch{}}function vt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function bi(i){if(typeof window!="undefined"){window.__enableConfigOverrides=i;try{window.localStorage.setItem(hs,i?"true":"false")}catch{}}}function Ae(i,e={}){var u,g;let{objectId:t,path:n,value:a}=i,{silent:s=!1,persist:r=!0,emitEvent:o=!0}=e,l=Qt();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}s||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:a});let p;try{p=Lo(c,n),yt(c,n,a)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:a},h);return}window.__configChanges=window.__configChanges||[];let d=window.__configChanges;if(d.push({objectId:t,path:n,oldValue:p,newValue:a,ts:Date.now()}),d.length>Co&&d.shift(),r){let h=Y(),f=h.findIndex(m=>m.objectId===t&&m.sceneId===i.sceneId&&m.path===n);f>=0?h[f].value=a:h.push(i),window.__configOverrides=h,en(h),vt()||bi(!0)}s||console.log("[CONFIG] Applied override:",i),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:i}))}function Se(i,e={}){let t=e.emitEvent!==!1,n=[];for(let a of i)a!=null&&a.objectId&&typeof a.objectId=="string"&&n.push(a.objectId),Ae(a,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let a=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:a,count:i.length}}))}}function Ce(){window.__configOverrides=[],window.__configChanges=[],en([]),console.log("[CONFIG] Cleared all overrides")}function ms(i){let e=Y().filter(n=>n.objectId!==i);window.__configOverrides=e,en(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==i),gs(i),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:i}}))}function tn(i,e){let t=Y().filter(a=>a.objectId!==i||a.path!==e);window.__configOverrides=t,en(t);let n=window.__configChanges||[];window.__configChanges=n.filter(a=>a.objectId!==i||a.path!==e),i?gs(i):Eo(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:i,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=So()),window.__configOverrides||[])}function yt(i,e,t){var r;let n=e.split("."),a=n.pop(),s=i;for(let o of n){if(s[o]!==void 0&&typeof s[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);s[o]=(r=s[o])!=null?r:{},s=s[o]}s[a]=t}function Lo(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function G(i){if(i===null||typeof i!="object")return i;if(i instanceof Date)return new Date(i.getTime());if(i instanceof Set)return new Set([...i].map(t=>G(t)));if(ArrayBuffer.isView(i))return i.slice();if(i instanceof Array)return i.map(t=>G(t));if(i instanceof Map){let t=new Map;return i.forEach((n,a)=>t.set(a,G(n))),t}let e={};for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(e[t]=G(i[t]));return e}function xt(){let i=window.__editableConfigBaseline;if(!i){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return ds(e)}return ds(i)}function ds(i){let e={objects:{},scenes:{},engine:G(i.engine||{})},t=i.objects;if(t instanceof Map)t.forEach((s,r)=>{e.objects[r]=G(s)});else if(t&&typeof t=="object")for(let s in t)e.objects[s]=G(t[s]);let n=i.scenes;if(n instanceof Map)n.forEach((s,r)=>{e.scenes[r]=G(s)});else if(n&&typeof n=="object")for(let s in n)e.scenes[s]=G(n[s]);let a=Y();for(let s of a)s.objectId?(e.objects[s.objectId]||(e.objects[s.objectId]={}),yt(e.objects[s.objectId],s.path,s.value)):s.sceneId?(e.scenes[s.sceneId]||(e.scenes[s.sceneId]={}),yt(e.scenes[s.sceneId],s.path,s.value)):yt(e.engine,s.path,s.value);return e}function nn(){let i=Y(),e=new Set;for(let t of i)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:i.length,hasChanges:i.length>0,overrides:i}}async function wt(i){let e=xt(),t={};for(let[a,s]of Object.entries(e.objects)){let r=s,o=a;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${a}`),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[a,s]of Object.entries(e.scenes)){let r=a.startsWith("scene.")?a:`scene.${a}`;t[`scenes/${r}.json`]=s}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:i})});if(!n.ok){let a=await n.json();throw new Error(`Apply failed: ${a.error||"Unknown error"}`)}Ce();try{let a=Qt();a&&(window.__editableConfigBaseline=G(a))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Et(){Ce(),window.location.reload()}async function an(){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"}`)}Ce(),window.location.reload()}var hs,Co,bs,ee=ce(()=>{"use strict";hs="handler_preview_override_mode";if(typeof window!="undefined"){let i=window.localStorage.getItem(hs);window.__enableConfigOverrides=i===null?!0:i==="true"}Co=500;bs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function To(i,e){try{if(typeof i=="object"&&i!==null)return i;if(typeof i!="string")return null;if(i.startsWith("data:")){let n=i.indexOf(",");if(n===-1)return null;let a=i.slice(0,n);if(!a.includes("application/json")&&!a.includes("text/plain"))return null;let s=i.slice(n+1),r=a.includes("base64")?typeof atob=="function"?atob(s):s:decodeURIComponent(s);return JSON.parse(r)}let t=i.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(i):null}catch{return null}}function _o(i){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=i.replace(/^\.\/+/,""),n=t.split("/").pop()||t,a=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let s of a){let r=e[s];if(r){let o=To(r,s);if(o!==null)return o}}return null}async function At(i){if(yi.has(i)&&!vi)return console.log(`[CONFIG] Using cached config for: "${i}"`),yi.get(i);if(console.log(`[CONFIG] loadConfigFile called with: "${i}", MODE: ${z.toUpperCase()}, CACHE: ${vi?"DISABLED":"ENABLED"}`),z==="publish"){let n=_o(i);return n?(console.log(`[CONFIG] \u2713 Loaded ${i} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${i} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}z==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${i}"`);let e;z==="brand"?e=[`./${i.split("/").pop()||i}`,`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.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=vi?"no-store":"force-cache";for(let a of e)try{let s=await fetch(a,{cache:n});if(!s.ok)continue;let r=await s.json();return console.log(`[CONFIG] \u2713 Loaded ${i} via ${a}`,r),r}catch(s){console.warn(`[CONFIG] \u2717 Failed to load ${a} (mode: ${z}):`,s)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${i}; using defaults`),{}})();return yi.set(i,t),t}async function rn(){console.log("[CONFIG] Loading component schemas...");let i=["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 i)try{let n=z==="publish"||z==="brand"?t.split("/").pop()||t:`configs/${t}`,a=await At(n);a.component&&(e.set(a.component,a),console.log(`[CONFIG] \u2713 Schema loaded: ${a.component} ${z==="publish"||z==="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 Le(i){console.log(`[CONFIG] Loading object config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/objects/${i}.json`;return await At(e)}async function on(i){let e=new Map;if(i.objects&&Array.isArray(i.objects)){for(let t of i.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let a=await Le(n);(!a||Object.keys(a).length===0)&&n!==t.instance_id&&(a=await Le(t.instance_id)),!a||Object.keys(a).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),a=await Le(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...a,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 ln(){console.log("[CONFIG] Loading engine configs...");let i=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(i.map(n=>{let a=`engine.${n}.json`,s=z==="publish"||z==="brand"?a:`configs/engine/${a}`;return At(s)})),t=Object.fromEntries(i.map((n,a)=>[n,e[a]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(i.map(n=>{var r;let a=(r=t[n])!=null?r:{},s=Object.keys(a);return[n,s.length>0?s:"empty"]}))),t}async function xi(){return await At(z==="publish"||z==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function cn(i="scene.main"){console.log(`[CONFIG] Loading scene config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/scenes/${i}.json`;return await At(e)}function Xe(i,e){let t=[];if(!i.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let a of n.required||[])i.identity[a]||t.push(`Missing required identity field: ${a}`);for(let[a,s]of Object.entries(i)){if(a==="identity")continue;let r=e.get(a);if(r&&s&&typeof s=="object"){let o=s;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${a}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let p=o[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${a}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${a}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function De(i,e){let t={...i},n=["identity","transform","render"];for(let[a,s]of e.entries())s.defaults&&Object.keys(s.defaults).length>0&&(n.includes(a)||t[a])&&(t[a]||(t[a]={}),t[a]={...s.defaults,...t[a]});return t}function Z(i,e,t,n){return typeof i!="number"||!Number.isFinite(i)?e:Math.min(Math.max(i,t),n)}function vs(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,-2e3,2e3),y:Z(i[1],e.y,-2e3,2e3)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,-2e3,2e3),y:Z(n,e.y,-2e3,2e3)}}function Po(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,0,1),y:Z(i[1],e.y,0,1)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,0,1),y:Z(n,e.y,0,1)}}function Mo(i){if(Array.isArray(i))return{x:Z(i[0],.5,-10,10),y:Z(i[1],.5,-10,10)};if(i&&typeof i=="object"){let{x:e,y:t}=i;return{x:Z(e,.5,-10,10),y:Z(t,.5,-10,10)}}return typeof i=="string"?i:null}async function me(i="scene.main",e){var l,c,p,d,u,g,h,f,m,b,y,v,x,E;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await rn(),n=Y();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let a=await cn(i);console.log(`[CONFIG] Scene config loaded: ${((l=a.objects)==null?void 0:l.length)||0} objects`);let s=await ln();console.log("[CONFIG] Loading object configs...");let r=await on(a);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[w,T]of r.entries()){let S=De(T,t),O=Xe(S,t);O.valid||console.warn(`Object ${w} validation errors:`,O.errors),(c=S.transform)!=null&&c.position&&(S.transform.position=vs(S.transform.position,{x:0,y:0})),(p=S.transform)!=null&&p.offset&&(S.transform.offset=vs(S.transform.offset,{x:0,y:0})),((d=S.transform)==null?void 0:d.anchor)!==void 0&&(S.transform.anchor=Mo(S.transform.anchor)),((u=S.transform)==null?void 0:u.position_ratio)!==void 0&&S.transform.position_ratio!==null&&(S.transform.position_ratio=Po(S.transform.position_ratio,{x:.5,y:.5})),r.set(w,S)}if(e){if(e.objects)for(let[w,T]of e.objects.entries())r.set(w,T);e.engine&&(s.runtime={...s.runtime,...e.engine.runtime},s.assets={...s.assets,...e.engine.assets},s.splash={...(g=s.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:s,scene:a,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=De(o,t))),n.length>0&&vt()&&Se(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((f=s.runtime)!=null?f:{}),assets:Object.keys((m=s.assets)!=null?m:{}),splash:Object.keys((b=s.splash)!=null?b:{}),loading:Object.keys((y=s.loading)!=null?y:{}),start:Object.keys((v=s.start)!=null?v:{}),tutorial:Object.keys((x=s.tutorial)!=null?x:{}),endgame:Object.keys((E=s.endgame)!=null?E:{})},scene:a.scene_id||"unknown"}),o}function wi(i){var t,n,a,s,r,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$,A;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[_,P]of i.objects.entries()){let q=((t=P.identity)==null?void 0:t.id)||_;q.includes("character")&&(e.gameplay.character_pos=((n=P.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((a=P.transform)==null?void 0:a.scale)||1,e.gameplay.character_anim_speed=((r=(s=P.gameplay)==null?void 0:s.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=P.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=P.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(q.includes("gun")||q.includes("flame"))&&(e.gameplay.gun=P.gun||{},e.gameplay.gunmuzzle=((d=P.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=P.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=P.effects)==null?void 0:g.flame)||{}),q.includes("diamond")&&(e.gameplay.diamond=P),q.includes("ice")&&(e.gameplay.melt=P.melt||{},e.gameplay.melt_anchor=((h=P.transform)==null?void 0:h.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((f=P.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((m=P.effects)==null?void 0:m.hybrid_melting)||{},e.gameplay.physics_chunks=((b=P.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=P.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=P.hard_ice||{}),q.includes("water")&&(e.gameplay.water_drops=P),q.includes("crack")&&(e.gameplay.crack=P),q.includes("hand")&&(e.gameplay.hand=((v=P.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((x=P.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((E=P.transform)==null?void 0:E.scale)||1.5),q.includes("hazard")&&(e.gameplay.hazard=((w=P.gameplay)==null?void 0:w.tuning)||{},e.gameplay.danger_pos=((T=P.transform)==null?void 0:T.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((O=(S=P.gameplay)==null?void 0:S.tuning)==null?void 0:O.danger_pulse)||{},e.gameplay.hazard_height=((M=(B=P.gameplay)==null?void 0:B.tuning)==null?void 0:M.hazard_height)||140)}return e.gameplay.timeline=((C=i.engine.runtime)==null?void 0:C.timeline)||{},e.gameplay.drag_surface=((I=i.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((k=i.engine.runtime)==null?void 0:k.background)||{},e.gameplay.ui_styles=((D=i.engine.runtime)==null?void 0:D.ui_styles)||{},e.gameplay.label_pulse=((R=i.engine.runtime)==null?void 0:R.label_pulse)||{},e.ui=(($=i.engine.runtime)==null?void 0:$.ui)||{},e.theme=((A=i.engine.runtime)==null?void 0:A.theme)||{},e.assets=i.engine.assets||{},e}var ys,z,yi,vi,Ei=ce(()=>{"use strict";ee();ys=null,z="dev";if(typeof window!="undefined"){let i=window.__BUILD_SETTINGS__;if(i!=null&&i.buildMode)ys=i,z=i.buildMode,console.log("[CONFIG] Loaded inline build settings:",i,"buildMode:",z);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);ys=t,z=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",z)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",z)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",z);yi=new Map,vi=z==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Ai(i,e){let t=[];function n(a,s,r=""){if(a!==s){if(typeof a!=typeof s){t.push(`${r}: type changed`);return}if(typeof a=="object"&&a!==null&&s!==null){let o=new Set([...Object.keys(a),...Object.keys(s)]);for(let l of o){let c=r?`${r}.${l}`:l;l in a?l in s?n(a[l],s[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(i,e),t}function Si(i,e,t,n){let a={...t};for(let[s,r]of n.entries())a[s]&&r.defaults&&(a[s]={...r.defaults,...a[s]});return a}var St,$e,Ci=ce(()=>{"use strict";St=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},$e=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()}`,a=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(a.ok){let s=await a.text(),r=this.hashString(s),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 a=e.charCodeAt(n);t=(t<<5)-t+a,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 Ti(i){if(typeof window=="undefined")return;let e=typeof Li!="undefined"&&!!Li.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let a=null,s=!1,r=null;if(t){r=new $e;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var b,y;if(!r)return;let f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let m=(y=(b=h.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||r.unwatch(v);for(let v of f)o.has(v)||r.watch(v,x=>g(x));o=f},c=new Set,p=!1,d=async h=>{let f=await Le(h),m=De(f,i.activeConfig.schemas),b=Xe(m,i.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await i.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!s){s=!0;try{if(p||c.size===0){i.audioSystem.destroy();let f=await me("scene.main");i.setActiveConfig(f),i.gameObjectManager.updateConfig(f),i.CustomAssets.updateConfig(f),await i.CustomAssets.ready();let m=i.createAudioSystem(f);i.setAudioSystem(m),window.__audioSystem=m,await m.start(),i.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${h})`)}else{let f=Array.from(c);c.clear();for(let m of f)await d(m);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{s=!1,p=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):p=!0,a&&window.clearTimeout(a),a=window.setTimeout(()=>{u(h.type)},120)}e&&Li.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(i.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Li,xs=ce(()=>{"use strict";Ci();Ei();Li={}});var ws={};ut(ws,{ConfigWatcher:()=>$e,DefaultReloadStrategy:()=>St,applyDefaults:()=>De,diffConfigs:()=>Ai,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>rn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>xi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Si,setupHotReload:()=>Ti,toLegacyFormat:()=>wi,validateObjectConfig:()=>Xe});var dn=ce(()=>{"use strict";Ei();Ci();xs()});var or={};ut(or,{AssetEditorModal:()=>ia});var ia,aa=ce(()=>{"use strict";ia=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,a){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=a,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 Os=Object.create;var Ht=Object.defineProperty;var Is=Object.getOwnPropertyDescriptor;var Rs=Object.getOwnPropertyNames;var js=Object.getPrototypeOf,Ds=Object.prototype.hasOwnProperty;var ce=(i,e)=>()=>(i&&(e=i(i=0)),e);var ut=(i,e)=>{for(var t in e)Ht(i,t,{get:e[t],enumerable:!0})},Aa=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Rs(e))!Ds.call(i,a)&&a!==t&&Ht(i,a,{get:()=>e[a],enumerable:!(n=Is(e,a))||n.enumerable});return i};var qe=(i,e,t)=>(t=i!=null?Os(js(i)):{},Aa(e||!i||!i.__esModule?Ht(t,"default",{value:i,enumerable:!0}):t,i)),$s=i=>Aa(Ht({},"__esModule",{value:!0}),i);var de,oi=ce(()=>{"use strict";de=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()}};de.store=new Map});function qs(){var i,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(i=document.querySelector("script"))==null?void 0:i.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 Vs(){try{if(typeof window!="undefined"){let i=await fetch("./build-settings.json");if(i.ok){let e=await i.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Ws(){try{if(typeof window!="undefined"){let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Ys(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${N}`),Object.keys(pe).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(pe)),pe;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),pe={...window.INLINE_ASSETS},pe;if(!(N==="publish"&&re!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),pe;if(!li){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),li=(async()=>{try{try{let r=await import(e+"?t="+Date.now());if(r.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(r.INLINE_ASSETS)),r.INLINE_ASSETS}catch(r){console.warn("[AssetLoader] ES module import failed, trying text parse:",r)}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 a=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(a)try{let r=a[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+r)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}catch(r){return console.warn("[AssetLoader] Failed to parse inline assets:",r),{}}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 pe=await li,console.log("[AssetLoader] Final inline assets cache:",Object.keys(pe)),pe}function ci(i){return i===null||typeof i!="object"||(Object.freeze(i),Object.values(i).forEach(e=>ci(e))),i}function Ks(i=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=i,n.height=e;let a=n.getContext("2d");return a.fillStyle=`#${t.toString(16).padStart(6,"0")}`,a.fillRect(0,0,i,e),a.strokeStyle="#000",a.strokeRect(0,0,i,e),a.fillStyle="#fff",a.font="10px sans-serif",a.textAlign="center",a.fillText("MISSING",i/2,e/2),ue.Texture.from(n)}function di(i,e){nr.set(i,e)}var ue,er,tr,Ie,N,re,we,pe,li,nr,Re,Gt=ce(()=>{"use strict";ue=require("pixi.js");oi();er=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",tr=qs(),Ie=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,N=tr?"publish":er,re=Ie==null?void 0:Ie.assetsInlined;Ie!=null&&Ie.buildMode&&(N=Ie.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${N}`));we=Ws();we!=null&&we.buildMode&&(N=we.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${N}`));(we==null?void 0:we.assetsInlined)!==void 0&&(re=we.assetsInlined);Vs().then(i=>{i!=null&&i.buildMode&&i.buildMode!==N&&(N=i.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${N}`)),(i==null?void 0:i.assetsInlined)!==void 0&&(re=i.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${er}, Runtime: ${tr?"publish":"dev"}, Effective: ${N}`);pe={},li=null;nr=new Map;Re=class{static async load(e,t,n,a){let r=`${e}:${t.path}`,s=de.get(r);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${N}`),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 Ys(),l=o[e];if(!l&&a&&(l=o[a],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${a}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.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"),N==="publish"&&re!==!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 p=nr.get(t.type);if(p)try{let d=await p(t.path,l,e,n);return de.set(r,d),d}catch(d){return this.handleFailure(e,t.type,d)}try{let d;switch(t.type){case"image":d=await this.loadImage(t.path,l);break;case"json":d=await this.loadJSON(t.path,l),d=ci(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return de.set(r,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let n=N==="publish",a=n&&re!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){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 ue.Assets.load(t)}catch(r){throw console.error("[AssetLoader] Failed to load texture from data URI:",r),r}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await ue.Assets.load(t)}catch(r){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",r),await ue.Assets.load(e)}return await ue.Assets.load(e)}static async loadJSON(e,t){let n=N==="publish",a=n&&re!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let s=atob(t.split(",")[1]);return JSON.parse(s)}return JSON.parse(t)}let r=await fetch(e);if(!r.ok)throw new Error(`JSON fetch failed: ${e}`);return r.json()}static handleFailure(e,t,n){if(N==="dev"){let r=t==="image"?Ks():ci({__placeholder:!0,type:t});return de.set(e+":"+((n==null?void 0:n.path)||"missing"),r),r}throw n}};di("image",async(i,e)=>{let t=N==="publish",n=t&&re!==!1,a=N==="brand",r=t&&re===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, 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: ${i}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return ue.Assets.load(e)}let s=i;return(a||r)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(s=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${s}"`))),ue.Assets.load(e||s)});di("json",async(i,e)=>{let t=N==="publish",n=t&&re!==!1,a=N==="brand",r=t&&re===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, 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: ${i}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let s=i;if((a||r)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(s=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${s}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(s);if(!o.ok)throw new Error(`JSON fetch failed: ${i}`);return o.json()})});var ar={};ut(ar,{AssetTextures:()=>se,initAssetTextures:()=>gi});function gi(i,e){ir.init(i,e),typeof window!="undefined"&&(window.__AssetTextures=se)}var ui,ir,se,Ke=ce(()=>{"use strict";Gt();ui=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 s;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),a=[],r=[];for(let[o,l]of e.objects.entries()){let c=(s=l.render)==null?void 0:s.asset;if(!c)continue;let p=async()=>{var d;try{let u=(d=l.identity)==null?void 0:d.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await Re.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)?a.push(p()):r.push(p())}a.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(a),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(r),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 a=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,p,d;try{let u=(p=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:p.call(c,o);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(a.length===0)return;this.ready().catch(()=>{});let r=()=>a.every(o=>this.textures.has(o)||this.attempted.has(o));if(r())return;let s=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||r()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:a}),o())},s)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},ir=new ui,se=new Proxy(ir,{get(i,e){return e in i&&typeof i[e]=="function"?i[e].bind(i):i.get(e)},set(i,e,t){return i.set(e,t),!0}})});var rn={};ut(rn,{applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>mr,configOverrideManager:()=>br,deepClone:()=>G,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setOverrideMode:()=>bi});function Qt(){return typeof window=="undefined"?null:window.__editableConfig||null}function pr(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function cr(i,e){var t,n;if(!i)return null;try{if(i instanceof Map)return(t=i.get(e))!=null?t:null;if(typeof i=="object")return(n=i[e])!=null?n:null}catch{}return null}function wo(i,e,t){if(i){if(i instanceof Map){i.set(e,t);return}typeof i=="object"&&(i[e]=t)}}function ur(i,e){for(let t of e)yt(i,t.path,t.value)}function gr(i){var o;if(typeof window=="undefined")return;let e=Qt();if(!e)return;let t=pr(),n=(o=t?cr(t.objects,i):null)!=null?o:cr(e.objects,i);if(!n)return;let a=G(n),r=Y().filter(l=>l.objectId===i);try{ur(a,r)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",i,l);return}wo(e.objects,i,a);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(i,a)}catch{}}function Eo(){var a;if(typeof window=="undefined")return;let i=Qt();if(!(i!=null&&i.engine))return;let e=pr(),t=G(((a=e==null?void 0:e.engine)!=null?a:i.engine)||{}),n=Y().filter(r=>!r.objectId&&!r.sceneId);try{ur(t,n)}catch(r){console.error("[CONFIG] Failed to reapply engine overrides",r);return}try{let r=i.engine;for(let s of Object.keys(r))s in t||delete r[s];for(let[s,o]of Object.entries(t))r[s]=o}catch{i.engine=t}}function Ao(){if(typeof window=="undefined")return"unknown";let i=window;return typeof i.__HANDLER_PROJECT_ID=="string"?i.__HANDLER_PROJECT_ID:"handler-default"}function fr(){return`handler_preview_config_overrides::${Ao()}`}function So(){if(typeof window=="undefined")return[];try{let i=window.localStorage.getItem(fr());if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}function en(i){if(typeof window!="undefined")try{window.localStorage.setItem(fr(),JSON.stringify(i))}catch{}}function vt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function bi(i){if(typeof window!="undefined"){window.__enableConfigOverrides=i;try{window.localStorage.setItem(hr,i?"true":"false")}catch{}}}function Ae(i,e={}){var u,g;let{objectId:t,path:n,value:a}=i,{silent:r=!1,persist:s=!0,emitEvent:o=!0}=e,l=Qt();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}r||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:a});let p;try{p=Lo(c,n),yt(c,n,a)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:a},h);return}window.__configChanges=window.__configChanges||[];let d=window.__configChanges;if(d.push({objectId:t,path:n,oldValue:p,newValue:a,ts:Date.now()}),d.length>Co&&d.shift(),s){let h=Y(),f=h.findIndex(m=>m.objectId===t&&m.sceneId===i.sceneId&&m.path===n);f>=0?h[f].value=a:h.push(i),window.__configOverrides=h,en(h),vt()||bi(!0)}r||console.log("[CONFIG] Applied override:",i),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:i}))}function Se(i,e={}){let t=e.emitEvent!==!1,n=[];for(let a of i)a!=null&&a.objectId&&typeof a.objectId=="string"&&n.push(a.objectId),Ae(a,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let a=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:a,count:i.length}}))}}function Ce(){window.__configOverrides=[],window.__configChanges=[],en([]),console.log("[CONFIG] Cleared all overrides")}function mr(i){let e=Y().filter(n=>n.objectId!==i);window.__configOverrides=e,en(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==i),gr(i),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:i}}))}function tn(i,e){let t=Y().filter(a=>a.objectId!==i||a.path!==e);window.__configOverrides=t,en(t);let n=window.__configChanges||[];window.__configChanges=n.filter(a=>a.objectId!==i||a.path!==e),i?gr(i):Eo(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:i,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=So()),window.__configOverrides||[])}function yt(i,e,t){var s;let n=e.split("."),a=n.pop(),r=i;for(let o of n){if(r[o]!==void 0&&typeof r[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);r[o]=(s=r[o])!=null?s:{},r=r[o]}r[a]=t}function Lo(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function G(i){if(i===null||typeof i!="object")return i;if(i instanceof Date)return new Date(i.getTime());if(i instanceof Set)return new Set([...i].map(t=>G(t)));if(ArrayBuffer.isView(i))return i.slice();if(i instanceof Array)return i.map(t=>G(t));if(i instanceof Map){let t=new Map;return i.forEach((n,a)=>t.set(a,G(n))),t}let e={};for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(e[t]=G(i[t]));return e}function xt(){let i=window.__editableConfigBaseline;if(!i){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return dr(e)}return dr(i)}function dr(i){let e={objects:{},scenes:{},engine:G(i.engine||{})},t=i.objects;if(t instanceof Map)t.forEach((r,s)=>{e.objects[s]=G(r)});else if(t&&typeof t=="object")for(let r in t)e.objects[r]=G(t[r]);let n=i.scenes;if(n instanceof Map)n.forEach((r,s)=>{e.scenes[s]=G(r)});else if(n&&typeof n=="object")for(let r in n)e.scenes[r]=G(n[r]);let a=Y();for(let r of a)r.objectId?(e.objects[r.objectId]||(e.objects[r.objectId]={}),yt(e.objects[r.objectId],r.path,r.value)):r.sceneId?(e.scenes[r.sceneId]||(e.scenes[r.sceneId]={}),yt(e.scenes[r.sceneId],r.path,r.value)):yt(e.engine,r.path,r.value);return e}function nn(){let i=Y(),e=new Set;for(let t of i)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:i.length,hasChanges:i.length>0,overrides:i}}async function wt(i){let e=xt(),t={};for(let[a,r]of Object.entries(e.objects)){let s=r,o=a;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${a}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),t[`objects/${o}.json`]=s}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[a,r]of Object.entries(e.scenes)){let s=a.startsWith("scene.")?a:`scene.${a}`;t[`scenes/${s}.json`]=r}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:i})});if(!n.ok){let a=await n.json();throw new Error(`Apply failed: ${a.error||"Unknown error"}`)}Ce();try{let a=Qt();a&&(window.__editableConfigBaseline=G(a))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Et(){Ce(),window.location.reload()}async function an(){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"}`)}Ce(),window.location.reload()}var hr,Co,br,ee=ce(()=>{"use strict";hr="handler_preview_override_mode";if(typeof window!="undefined"){let i=window.localStorage.getItem(hr);window.__enableConfigOverrides=i===null?!0:i==="true"}Co=500;br={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function To(i,e){try{if(typeof i=="object"&&i!==null)return i;if(typeof i!="string")return null;if(i.startsWith("data:")){let n=i.indexOf(",");if(n===-1)return null;let a=i.slice(0,n);if(!a.includes("application/json")&&!a.includes("text/plain"))return null;let r=i.slice(n+1),s=a.includes("base64")?typeof atob=="function"?atob(r):r:decodeURIComponent(r);return JSON.parse(s)}let t=i.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(i):null}catch{return null}}function _o(i){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=i.replace(/^\.\/+/,""),n=t.split("/").pop()||t,a=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let r of a){let s=e[r];if(s){let o=To(s,r);if(o!==null)return o}}return null}async function At(i){if(yi.has(i)&&!vi)return console.log(`[CONFIG] Using cached config for: "${i}"`),yi.get(i);if(console.log(`[CONFIG] loadConfigFile called with: "${i}", MODE: ${z.toUpperCase()}, CACHE: ${vi?"DISABLED":"ENABLED"}`),z==="publish"){let n=_o(i);return n?(console.log(`[CONFIG] \u2713 Loaded ${i} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${i} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}z==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${i}"`);let e;z==="brand"?e=[`./${i.split("/").pop()||i}`,`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.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=vi?"no-store":"force-cache";for(let a of e)try{let r=await fetch(a,{cache:n});if(!r.ok)continue;let s=await r.json();return console.log(`[CONFIG] \u2713 Loaded ${i} via ${a}`,s),s}catch(r){console.warn(`[CONFIG] \u2717 Failed to load ${a} (mode: ${z}):`,r)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${i}; using defaults`),{}})();return yi.set(i,t),t}async function sn(){console.log("[CONFIG] Loading component schemas...");let i=["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 i)try{let n=z==="publish"||z==="brand"?t.split("/").pop()||t:`configs/${t}`,a=await At(n);a.component&&(e.set(a.component,a),console.log(`[CONFIG] \u2713 Schema loaded: ${a.component} ${z==="publish"||z==="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 Le(i){console.log(`[CONFIG] Loading object config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/objects/${i}.json`;return await At(e)}async function on(i){let e=new Map;if(i.objects&&Array.isArray(i.objects)){for(let t of i.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let a=await Le(n);(!a||Object.keys(a).length===0)&&n!==t.instance_id&&(a=await Le(t.instance_id)),!a||Object.keys(a).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),a=await Le(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...a,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 ln(){console.log("[CONFIG] Loading engine configs...");let i=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(i.map(n=>{let a=`engine.${n}.json`,r=z==="publish"||z==="brand"?a:`configs/engine/${a}`;return At(r)})),t=Object.fromEntries(i.map((n,a)=>[n,e[a]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(i.map(n=>{var s;let a=(s=t[n])!=null?s:{},r=Object.keys(a);return[n,r.length>0?r:"empty"]}))),t}async function xi(){return await At(z==="publish"||z==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function cn(i="scene.main"){console.log(`[CONFIG] Loading scene config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/scenes/${i}.json`;return await At(e)}function Xe(i,e){let t=[];if(!i.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let a of n.required||[])i.identity[a]||t.push(`Missing required identity field: ${a}`);for(let[a,r]of Object.entries(i)){if(a==="identity")continue;let s=e.get(a);if(s&&r&&typeof r=="object"){let o=r;for(let l of s.required||[])o[l]===void 0&&t.push(`Missing required field in ${a}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.constraints)){let p=o[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${a}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${a}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function De(i,e){let t={...i},n=["identity","transform","render"];for(let[a,r]of e.entries())r.defaults&&Object.keys(r.defaults).length>0&&(n.includes(a)||t[a])&&(t[a]||(t[a]={}),t[a]={...r.defaults,...t[a]});return t}function Z(i,e,t,n){return typeof i!="number"||!Number.isFinite(i)?e:Math.min(Math.max(i,t),n)}function vr(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,-2e3,2e3),y:Z(i[1],e.y,-2e3,2e3)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,-2e3,2e3),y:Z(n,e.y,-2e3,2e3)}}function Po(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,0,1),y:Z(i[1],e.y,0,1)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,0,1),y:Z(n,e.y,0,1)}}function Mo(i){if(Array.isArray(i))return{x:Z(i[0],.5,-10,10),y:Z(i[1],.5,-10,10)};if(i&&typeof i=="object"){let{x:e,y:t}=i;return{x:Z(e,.5,-10,10),y:Z(t,.5,-10,10)}}return typeof i=="string"?i:null}async function me(i="scene.main",e){var l,c,p,d,u,g,h,f,m,b,y,v,x,E;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await sn(),n=Y();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let a=await cn(i);console.log(`[CONFIG] Scene config loaded: ${((l=a.objects)==null?void 0:l.length)||0} objects`);let r=await ln();console.log("[CONFIG] Loading object configs...");let s=await on(a);console.log(`[CONFIG] Loaded ${s.size} object configs:`,Array.from(s.keys()));for(let[w,T]of s.entries()){let S=De(T,t),O=Xe(S,t);O.valid||console.warn(`Object ${w} validation errors:`,O.errors),(c=S.transform)!=null&&c.position&&(S.transform.position=vr(S.transform.position,{x:0,y:0})),(p=S.transform)!=null&&p.offset&&(S.transform.offset=vr(S.transform.offset,{x:0,y:0})),((d=S.transform)==null?void 0:d.anchor)!==void 0&&(S.transform.anchor=Mo(S.transform.anchor)),((u=S.transform)==null?void 0:u.position_ratio)!==void 0&&S.transform.position_ratio!==null&&(S.transform.position_ratio=Po(S.transform.position_ratio,{x:.5,y:.5})),s.set(w,S)}if(e){if(e.objects)for(let[w,T]of e.objects.entries())s.set(w,T);e.engine&&(r.runtime={...r.runtime,...e.engine.runtime},r.assets={...r.assets,...e.engine.assets},r.splash={...(g=r.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:s,engine:r,scene:a,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=De(o,t))),n.length>0&&vt()&&Se(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(s.keys()),engine:{runtime:Object.keys((f=r.runtime)!=null?f:{}),assets:Object.keys((m=r.assets)!=null?m:{}),splash:Object.keys((b=r.splash)!=null?b:{}),loading:Object.keys((y=r.loading)!=null?y:{}),start:Object.keys((v=r.start)!=null?v:{}),tutorial:Object.keys((x=r.tutorial)!=null?x:{}),endgame:Object.keys((E=r.endgame)!=null?E:{})},scene:a.scene_id||"unknown"}),o}function wi(i){var t,n,a,r,s,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$,A;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[_,P]of i.objects.entries()){let q=((t=P.identity)==null?void 0:t.id)||_;q.includes("character")&&(e.gameplay.character_pos=((n=P.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((a=P.transform)==null?void 0:a.scale)||1,e.gameplay.character_anim_speed=((s=(r=P.gameplay)==null?void 0:r.tuning)==null?void 0:s.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=P.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=P.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(q.includes("gun")||q.includes("flame"))&&(e.gameplay.gun=P.gun||{},e.gameplay.gunmuzzle=((d=P.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=P.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=P.effects)==null?void 0:g.flame)||{}),q.includes("diamond")&&(e.gameplay.diamond=P),q.includes("ice")&&(e.gameplay.melt=P.melt||{},e.gameplay.melt_anchor=((h=P.transform)==null?void 0:h.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((f=P.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((m=P.effects)==null?void 0:m.hybrid_melting)||{},e.gameplay.physics_chunks=((b=P.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=P.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=P.hard_ice||{}),q.includes("water")&&(e.gameplay.water_drops=P),q.includes("crack")&&(e.gameplay.crack=P),q.includes("hand")&&(e.gameplay.hand=((v=P.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((x=P.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((E=P.transform)==null?void 0:E.scale)||1.5),q.includes("hazard")&&(e.gameplay.hazard=((w=P.gameplay)==null?void 0:w.tuning)||{},e.gameplay.danger_pos=((T=P.transform)==null?void 0:T.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((O=(S=P.gameplay)==null?void 0:S.tuning)==null?void 0:O.danger_pulse)||{},e.gameplay.hazard_height=((M=(B=P.gameplay)==null?void 0:B.tuning)==null?void 0:M.hazard_height)||140)}return e.gameplay.timeline=((C=i.engine.runtime)==null?void 0:C.timeline)||{},e.gameplay.drag_surface=((I=i.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((k=i.engine.runtime)==null?void 0:k.background)||{},e.gameplay.ui_styles=((D=i.engine.runtime)==null?void 0:D.ui_styles)||{},e.gameplay.label_pulse=((R=i.engine.runtime)==null?void 0:R.label_pulse)||{},e.ui=(($=i.engine.runtime)==null?void 0:$.ui)||{},e.theme=((A=i.engine.runtime)==null?void 0:A.theme)||{},e.assets=i.engine.assets||{},e}var yr,z,yi,vi,Ei=ce(()=>{"use strict";ee();yr=null,z="dev";if(typeof window!="undefined"){let i=window.__BUILD_SETTINGS__;if(i!=null&&i.buildMode)yr=i,z=i.buildMode,console.log("[CONFIG] Loaded inline build settings:",i,"buildMode:",z);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);yr=t,z=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",z)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",z)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",z);yi=new Map,vi=z==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Ai(i,e){let t=[];function n(a,r,s=""){if(a!==r){if(typeof a!=typeof r){t.push(`${s}: type changed`);return}if(typeof a=="object"&&a!==null&&r!==null){let o=new Set([...Object.keys(a),...Object.keys(r)]);for(let l of o){let c=s?`${s}.${l}`:l;l in a?l in r?n(a[l],r[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${s}: changed`)}}return n(i,e),t}function Si(i,e,t,n){let a={...t};for(let[r,s]of n.entries())a[r]&&s.defaults&&(a[r]={...s.defaults,...a[r]});return a}var St,$e,Ci=ce(()=>{"use strict";St=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},$e=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()}`,a=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(a.ok){let r=await a.text(),s=this.hashString(r),o=this.fileHashes.get(e);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,s)}else o||this.fileHashes.set(e,s)}}catch(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 a=e.charCodeAt(n);t=(t<<5)-t+a,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 Ti(i){if(typeof window=="undefined")return;let e=typeof Li!="undefined"&&!!Li.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let a=null,r=!1,s=null;if(t){s=new $e;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=s}let o=new Set,l=h=>{var b,y;if(!s)return;let f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let m=(y=(b=h.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||s.unwatch(v);for(let v of f)o.has(v)||s.watch(v,x=>g(x));o=f},c=new Set,p=!1,d=async h=>{let f=await Le(h),m=De(f,i.activeConfig.schemas),b=Xe(m,i.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await i.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!r){r=!0;try{if(p||c.size===0){i.audioSystem.destroy();let f=await me("scene.main");i.setActiveConfig(f),i.gameObjectManager.updateConfig(f),i.CustomAssets.updateConfig(f),await i.CustomAssets.ready();let m=i.createAudioSystem(f);i.setAudioSystem(m),window.__audioSystem=m,await m.start(),i.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${h})`)}else{let f=Array.from(c);c.clear();for(let m of f)await d(m);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{r=!1,p=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):p=!0,a&&window.clearTimeout(a),a=window.setTimeout(()=>{u(h.type)},120)}e&&Li.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(i.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Li,xr=ce(()=>{"use strict";Ci();Ei();Li={}});var wr={};ut(wr,{ConfigWatcher:()=>$e,DefaultReloadStrategy:()=>St,applyDefaults:()=>De,diffConfigs:()=>Ai,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>sn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>xi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Si,setupHotReload:()=>Ti,toLegacyFormat:()=>wi,validateObjectConfig:()=>Xe});var dn=ce(()=>{"use strict";Ei();Ci();xr()});var os={};ut(os,{AssetEditorModal:()=>ia});var ia,aa=ce(()=>{"use strict";ia=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,a){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=a,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 a=this.modal.querySelector("[data-ai-edit]");a==null||a.addEventListener("click",()=>{this.openAiEditor("edit")});let s=this.modal.querySelector("[data-modal-apply]");s==null||s.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(a=>{a.classList.toggle("active",a.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(a=>{a.classList.toggle("active",a.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:a=>{this.onApplyCallback&&this.onApplyCallback(a),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 dl={};ut(dl,{COLORS:()=>le,ConfigWatcher:()=>$e,DebugPanel:()=>Mt,DefaultReloadStrategy:()=>St,Handler:()=>ne,PlayableLoadingScreen:()=>Un,PreviewShell:()=>Hn,STROKE_WIDTH:()=>hr,THEME:()=>mr,applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,applyDefaults:()=>De,baseLottie:()=>ai,bootstrap:()=>Qo,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>ms,configOverrideManager:()=>bs,createPreviewShell:()=>oa,deepClone:()=>G,default:()=>Oe,defaultPreset:()=>pn,deviceGroups:()=>Mi,devicePresets:()=>Pi,diffConfigs:()=>Ai,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,getPresetById:()=>ze,getPresetsByCategory:()=>ko,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>rn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>xi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Si,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setBootstrapDependencies:()=>Jo,setOverrideMode:()=>bi,setupHotReload:()=>Ti,setupLiveEditBridge:()=>Bn,toLegacyFormat:()=>wi,validateObjectConfig:()=>Xe});module.exports=$r(dl);var xe={};function Bt(i,e,t=!1){xe[i]||(xe[i]=[]),xe[i].push({fn:e,once:t})}function ei(i,e){if(xe[i]){if(!e){delete xe[i];return}xe[i]=xe[i].filter(t=>t.fn!==e)}}function Ft(i,...e){let t=xe[i];if(t)for(let n of[...t])n.fn(...e),n.once&&ei(i,n.fn)}function K(i,e){Bt(i,e,!0)}var F=null,Q=[],Ve=null;function La(i){F=i,Q=[],Ve!==null&&(clearTimeout(Ve),Ve=null)}function Ta(){var i,e,t;return{endpoint:(F==null?void 0:F.endpoint)||"",transport:(F==null?void 0:F.transport)||"beacon",batchSize:(i=F==null?void 0:F.batchSize)!=null?i:10,flushIntervalMs:(e=F==null?void 0:F.flushIntervalMs)!=null?e:300,maxQueue:(t=F==null?void 0:F.maxQueue)!=null?t:200,debug:!!(F!=null&&F.debug)}}async function Sa(i,e,t,n){let a=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let s=navigator.sendBeacon(i,new Blob([a],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",s,e);return}catch(s){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",s)}try{await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:a,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(s){n&&console.warn("[handler.telemetry] fetch failed",s)}}function ti(i,e){let t=Ta();if(e&&t.endpoint){if(Q.push(i),Q.length>t.maxQueue&&(Q=Q.slice(Q.length-t.maxQueue)),Q.length>=t.batchSize){Ca();return}Ve===null&&(Ve=window.setTimeout(()=>{Ve=null,Ca()},t.flushIntervalMs))}}async function Ca(){let i=Ta();if(!i.endpoint||Q.length===0)return;let e=Q.splice(0,i.batchSize);await Sa(i.endpoint,{events:e},i.transport,i.debug),Q.length>0&&await Sa(i.endpoint,{events:Q.splice(0,i.batchSize)},i.transport,i.debug)}function _a(i){return Math.max(0,Math.min(1,i))}function zr(i){let e=String(i!=null?i:"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 a=>1+(n+1)*Math.pow(a-1,3)+n*Math.pow(a-1,2)}return t=>1-(1-t)*(1-t)}function gt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Nr(i,e){let t=i==null?void 0:i[e];return typeof t=="number"?t:0}function Pa(i,e,t){try{i[e]=t}catch{}}function Hr(i){let e=i==null?void 0:i.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 Ma(i,e){let t=i==null?void 0:i.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 ka(i,e){let t=Hr(i);if(!t)return{from:null,to:null};let n=null,a=null;return typeof e.scale=="number"?(n=e.scale,a=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(a=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(a=e.scaleY),n===null&&a===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:a!=null?a:t.y}}}function Oa(){let i=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),i.size>0&&n()})},a=p=>{var u;i.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),n()},s=p=>{i.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},r=p=>{p.killed||(p.killed=!0,s(p))},o=()=>{var d,u;let p=gt();for(let g of Array.from(i)){if(g.killed||g.paused)continue;let h=p-g.startMs-g.delayMs;if(h<0)continue;let f=g.durationMs>0?h/g.durationMs:1,m=_a(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let E=f-y;m=_a(E)}let v=g.ease(m);g.yoyo&&y%2===1&&(v=1-v);for(let E of g.props)Pa(g.target,E.key,E.from+(E.to-E.from)*v);g.scaleFrom&&g.scaleTo&&Ma(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{(d=g.onUpdate)==null||d.call(g)}catch{}if(f>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var E;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),h=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((E=u==null?void 0:u.delayMsOverride)!=null?E:0)),f=zr(d.ease),m=typeof d.repeat=="number"?Math.max(0,d.repeat|0):0,b=d.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let w of Object.keys(d)){if(y.has(w))continue;let T=d[w];typeof T=="number"&&v.push({key:w,from:Nr(p,w),to:T})}let x=ka(p,d);return{target:p,startMs:gt(),delayMs:h,durationMs:g,ease:f,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:m,yoyo:b,onUpdate:typeof d.onUpdate=="function"?d.onUpdate:void 0,onComplete:typeof d.onComplete=="function"?d.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(p,d){let u=l(p,d);return a(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=gt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:gt(),h=gt()-g;u.startMs+=h,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(p,d,u){return c.set(p,d),c.to(p,u)},set(p,d){if(!p||!d)return;for(let g of Object.keys(d)){let h=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Pa(p,g,h)}let u=ka(p,d);u.to&&Ma(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))r(u)},timeline(p={}){let d=[],u=0,g=!1,h=[],f=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},m=y=>{d.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,x){return m({kind:"to",target:y,vars:v,atMs:f(x)}),b},fromTo(y,v,x,E){return m({kind:"fromTo",target:y,vars:x,from:v,atMs:f(E)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let x of d)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),h.push(c.to(x.target,{...x.vars,delay:x.atMs/1e3+((v=x.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return p.paused||b.play(),b}};return c}function Ia(){if(typeof window=="undefined")return;let i=window;if(!i.gsap)try{i.gsap=Oa()}catch{}}var Ra={name:"handler-playable-sdk",version:"0.3.42",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 && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var X=0,Fr=X++,ja=X++,Da=X++,$a=X++,za=X++,Na=X++,Ha=X++,Ba=X++,Fa=X++,Ua=X++,Ga=X++,qa=X++,H=Fr;function Va(){return H===ja}function Wa(){return H===Da}function Ya(){return H===$a}function Ka(){return H===za}function We(){return H===Na}function Ye(){return H===Ha}function Xa(){return H===Ba}function Ja(){return H===Fa}function Za(){return H===Ua}function ni(){return H===Ga}function ii(){return H===qa}function Qa(){let i=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(i==="mraid")try{mraid.getState(),H=ja;return}catch{}else if(i==="dapi")try{dapi.isReady(),H=Da;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(H=$a)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(H=za)}catch{}else if(e==="mintegral")window.gameReady&&(H=Na);else if(e==="tapjoy")window.TJ_API&&(H=Ha);else if(e==="tiktok")window.openAppStore&&(H=Ba);else if(e==="smadex")try{window.smxTracking&&(H=Fa)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(H=Ua)}catch{}else e==="vungle"?H=Ga:(i==="nucleo"||e==="nucleo")&&(H=qa)}var Ut=qe(require("lottie-web"),1),ai=Ut.default;typeof window!="undefined"&&(window.lottie=Ut.default,window.__baseLottie=Ut.default);var Ur=require("pixi.js");var si=require("pixi.js");var Gr=null;function ri(i){Gr=i}Gt();oi();var ft=require("pixi.js");Gt();var Xr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",pi=Xr;if(typeof window!="undefined")try{let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);e!=null&&e.buildMode&&(pi=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${pi}`))}}catch{}var Ee=class{static async create(e,t,n){var l,c,p,d,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${pi}`);let a=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!a){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new ft.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}let s=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${s}, type: ${a.type}, path: ${a.path}`);let r=await Re.load(e,a,n,s);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=r==null?void 0:r.constructor)==null?void 0:p.name}`);let o;if(a.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:",(d=o==null?void 0:o.constructor)==null?void 0:d.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(a.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 f=[a.path,`/assets/${a.path}`,`assets/${a.path}`,`../assets/${a.path}`],m=!1;for(let b of f)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),m=!0;break}}catch{continue}m||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,n){var a,s,r,o;!t||!e||(t.position&&("x"in e&&"y"in e?(e.x=(a=t.position.x)!=null?a:0,e.y=(s=t.position.y)!=null?s: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&&Array.isArray(t.anchor)&&("set"in e.anchor?e.anchor.set(t.anchor[0],t.anchor[1]):(e.anchor.x=t.anchor[0],e.anchor.y=t.anchor[1])))}};var ht=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 Qr=qe(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Qr);Ke();var qt=require("pixi.js");Ke();var fi=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new ht}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(a=>!this.instanceCache.has(a));if(t.length===0)return;let n=async a=>{a.length&&(console.log("[Assets] Loading objects:",a),await Promise.all(a.map(async s=>{var o;let r=this.registry.get(s);if(!r){console.warn("[Assets] No config found for object:",s);return}try{let l=await Ee.create(s,r,this.app);this.instanceCache.set(s,l),console.log("[Assets] Loaded object:",s,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",s,l)}})))};return this.readyPromise=(async()=>{await n(t);let a=this.registry.getAllIds().filter(s=>!this.instanceCache.has(s));a.length>0&&(console.warn("[Assets] Retrying missing assets:",a),await n(a)),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 Ee.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},eo=new fi,to=new Proxy(eo,{get(i,e){if(e in i&&typeof i[e]=="function")return i[e].bind(i);if(i.get(e))return i.get(e)}});Ke();var ss=require("pixi.js"),ge={width:400,height:600,designWidth:400,scaleFactor:1},Wt={scale:1,position:1},mi=[];function io(i,e,t,n,a,s,r){mi.push({element:i,originalScale:s,positionHelper:e,heightPercent:a}),e(i,t,n,a,s,r,!1)}function ao(){mi.forEach(({element:i,originalScale:e,positionHelper:t,heightPercent:n})=>{let a=e*ge.scaleFactor;t(i,ge.width,ge.height,n,a,!0,!1)})}function hi(i,e){console.log(`[SCREEN] updateScreenState called: ${i}x${e}`),ge.width=i,ge.height=e,ge.scaleFactor=Math.min(i/ge.designWidth,1.15),Wt.scale=ge.scaleFactor,Wt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Wt.scale.toFixed(3)}`),ao()}var bt={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 so(i,e,t){let n=bt[i];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${i}.${e} = ${t}`))}function ro(){return bt}var oo={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 Vt(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function Yt(i,e={x:.5,y:.5}){var t;if(Array.isArray(i))return{x:Vt(i[0],e.x),y:Vt(i[1],e.y)};if(i&&typeof i=="object"){let n=i;return{x:Vt(n.x,e.x),y:Vt(n.y,e.y)}}if(typeof i=="string"){let n=i.trim().toLowerCase();return(t=oo[n])!=null?t:e}return e}function rs(i,e,t,n={}){var g,h,f,m,b,y;let a=Yt(t),s=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((f=s.left)!=null?f:0)+r.x,l=((m=s.right)!=null?m:0)+r.x,c=((b=s.top)!=null?b:0)+r.y,p=((y=s.bottom)!=null?y:0)+r.y,d=Math.max(0,i-o-l),u=Math.max(0,e-c-p);return{x:o+d*a.x,y:c+u*a.y}}function os(i,e,t,n={}){var f,m,b,y,v,x;let a=(f=n.inset)!=null?f:{},s=(m=n.padding)!=null?m:{x:0,y:0},r=((b=a.left)!=null?b:0)+s.x,o=((y=a.right)!=null?y:0)+s.x,l=((v=a.top)!=null?v:0)+s.y,c=((x=a.bottom)!=null?x:0)+s.y,p=Math.max(0,i-r-o),d=Math.max(0,e-l-c),u=Yt(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+p*g,y:l+d*h}}if(typeof window!="undefined"){let i=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,a=window.innerHeight;(n!==i||a!==e)&&(i=n,e=a,hi(n,a))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),hi(window.innerWidth,window.innerHeight),window.updateDebugConfig=so,window.getDebugConfig=ro,window.copyConfig=vo,window.applyConfig=mt,window.applyConfigForRatio=xo,window.positionAtBottom=ls,window.positionAtTop=po,window.positionAtCenter=uo,window.positionAtLeft=go,window.positionAtRight=fo,window.positionAtBottomLeft=ho,window.positionAtBottomRight=mo,window.positionAtTopLeft=bo,window.positionAtTopRight=yo,window.applyPositionContract=co,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 Kt(i,e,t=0){return i*e+t}function Xt(i,e,t=0){return i*(1-e)+t}function Jt(i,e,t=0){return i*e+t}function Zt(i,e,t=0){return i*(1-e)+t}function J(i,e=0){return i/2+e}function lo(i,e){return i*e}function co(i,e,t,n){var r,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O;let a=0,s=0;switch(n.type){case"top":a=J(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),s=Kt(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":a=J(e,(d=(p=n.offset)==null?void 0:p.x)!=null?d:0),s=Xt(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":a=Jt(e,n.percent,(f=(h=n.offset)==null?void 0:h.x)!=null?f:0),s=J(t,(b=(m=n.offset)==null?void 0:m.y)!=null?b:0);break;case"right":a=Zt(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),s=J(t,(E=(x=n.offset)==null?void 0:x.y)!=null?E:0);break;case"center":a=J(e,(T=(w=n.offset)==null?void 0:w.x)!=null?T:0),s=J(t,(O=(S=n.offset)==null?void 0:S.y)!=null?O:0);break}i.position?i.position.set(a,s):(i.x=a,i.y=s),n.scale!==void 0&&n.scale!==1&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(n.scale,n.scale):(i.scale.x=n.scale,i.scale.y=n.scale))}function ls(i,e,t,n=.2,a=1,s=!0,r=!1){let o=lo(t,n),l=Xt(t,n/2);fe(i,J(e),l);let c=s?a*ge.scaleFactor:a;he(i,c),r&&!mi.find(p=>p.element===i)&&io(i,ls,e,t,n,a,s)}function po(i,e,t,n=.1,a=1){fe(i,J(e),Kt(t,n)),he(i,a)}function uo(i,e,t,n=0,a=0,s=1){fe(i,J(e,n),J(t,a)),he(i,s)}function go(i,e,t,n=.1,a=1){fe(i,Jt(e,n),J(t)),he(i,a)}function fo(i,e,t,n=.1,a=1){fe(i,Zt(e,n),J(t)),he(i,a)}function ho(i,e,t,n=.05,a=.05,s=1){fe(i,Jt(e,a),Xt(t,n)),he(i,s)}function mo(i,e,t,n=.05,a=.05,s=1){fe(i,Zt(e,a),Xt(t,n)),he(i,s)}function bo(i,e,t,n=.05,a=.05,s=1){fe(i,Jt(e,a),Kt(t,n)),he(i,s)}function yo(i,e,t,n=.05,a=.05,s=1){fe(i,Zt(e,a),Kt(t,n)),he(i,s)}function fe(i,e,t){i&&i.position?typeof i.position.set=="function"?i.position.set(e,t):(i.position.x=e,i.position.y=t):i&&(i.x=e,i.y=t)}function he(i,e){e!==1&&i&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(e,e):i.scale.x!==void 0&&i.scale.y!==void 0&&(i.scale.x=e,i.scale.y=e))}var je={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function vo(i){return i&&je[i]?JSON.parse(JSON.stringify(je[i])):JSON.parse(JSON.stringify(bt))}function mt(i){Object.keys(i).forEach(e=>{let t=e;bt[t]&&i[t]&&Object.assign(bt[t],i[t])}),console.log("Config applied:",i)}function xo(i,e){let t=i/e;t>1.6?(mt(je.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(mt(je.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(mt(je.square),console.log("Applied SQUARE config for ratio:",t)):(mt(je.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let i=window;i.configPresets=je,i.resolveAnchorVec2=i.resolveAnchorVec2||Yt,i.resolveScreenAnchorPoint=i.resolveScreenAnchorPoint||rs,i.resolveScreenRatioPoint=i.resolveScreenRatioPoint||os}dn();function U(i,e){let t=(a,s)=>s===0?a:t(s,a%s),n=t(i,e);return`${i/n}:${e/n}`}var zc=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:U(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:U(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:U(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:U(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:U(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:U(360,780)}],Nc=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:U(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:U(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:U(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:U(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:U(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:U(412,915)}],Hc=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:U(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:U(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:U(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:U(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:U(800,1280)}],_i=[{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:U(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:U(768,1024),mraidScale:.7}];var Pi=[..._i],Mi=[{category:"playable",label:"Playable Ad",devices:_i}],pn=_i[0];function ze(i){return Pi.find(e=>e.id===i)||pn}function ko(i){return Pi.filter(e=>e.category===i)}var un=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
46
+ `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(s=>{s.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(s=>{s.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 a=this.modal.querySelector("[data-ai-edit]");a==null||a.addEventListener("click",()=>{this.openAiEditor("edit")});let r=this.modal.querySelector("[data-modal-apply]");r==null||r.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",s=>{s.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(a=>{a.classList.toggle("active",a.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(a=>{a.classList.toggle("active",a.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:a=>{this.onApplyCallback&&this.onApplyCallback(a),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 dl={};ut(dl,{COLORS:()=>le,ConfigWatcher:()=>$e,DebugPanel:()=>Mt,DefaultReloadStrategy:()=>St,Handler:()=>ne,PlayableLoadingScreen:()=>Un,PreviewShell:()=>Hn,STROKE_WIDTH:()=>hs,THEME:()=>ms,applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,applyDefaults:()=>De,baseLottie:()=>ai,bootstrap:()=>Qo,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>mr,configOverrideManager:()=>br,createPreviewShell:()=>oa,deepClone:()=>G,default:()=>Oe,defaultPreset:()=>pn,deviceGroups:()=>Mi,devicePresets:()=>Pi,diffConfigs:()=>Ai,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,getPresetById:()=>ze,getPresetsByCategory:()=>ko,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>sn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>xi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Si,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setBootstrapDependencies:()=>Jo,setOverrideMode:()=>bi,setupHotReload:()=>Ti,setupLiveEditBridge:()=>Bn,toLegacyFormat:()=>wi,validateObjectConfig:()=>Xe});module.exports=$s(dl);var xe={};function Bt(i,e,t=!1){xe[i]||(xe[i]=[]),xe[i].push({fn:e,once:t})}function ei(i,e){if(xe[i]){if(!e){delete xe[i];return}xe[i]=xe[i].filter(t=>t.fn!==e)}}function Ft(i,...e){let t=xe[i];if(t)for(let n of[...t])n.fn(...e),n.once&&ei(i,n.fn)}function K(i,e){Bt(i,e,!0)}var F=null,Q=[],Ve=null;function La(i){F=i,Q=[],Ve!==null&&(clearTimeout(Ve),Ve=null)}function Ta(){var i,e,t;return{endpoint:(F==null?void 0:F.endpoint)||"",transport:(F==null?void 0:F.transport)||"beacon",batchSize:(i=F==null?void 0:F.batchSize)!=null?i:10,flushIntervalMs:(e=F==null?void 0:F.flushIntervalMs)!=null?e:300,maxQueue:(t=F==null?void 0:F.maxQueue)!=null?t:200,debug:!!(F!=null&&F.debug)}}async function Sa(i,e,t,n){let a=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let r=navigator.sendBeacon(i,new Blob([a],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",r,e);return}catch(r){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",r)}try{await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:a,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(r){n&&console.warn("[handler.telemetry] fetch failed",r)}}function ti(i,e){let t=Ta();if(e&&t.endpoint){if(Q.push(i),Q.length>t.maxQueue&&(Q=Q.slice(Q.length-t.maxQueue)),Q.length>=t.batchSize){Ca();return}Ve===null&&(Ve=window.setTimeout(()=>{Ve=null,Ca()},t.flushIntervalMs))}}async function Ca(){let i=Ta();if(!i.endpoint||Q.length===0)return;let e=Q.splice(0,i.batchSize);await Sa(i.endpoint,{events:e},i.transport,i.debug),Q.length>0&&await Sa(i.endpoint,{events:Q.splice(0,i.batchSize)},i.transport,i.debug)}function _a(i){return Math.max(0,Math.min(1,i))}function zs(i){let e=String(i!=null?i:"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 a=>1+(n+1)*Math.pow(a-1,3)+n*Math.pow(a-1,2)}return t=>1-(1-t)*(1-t)}function gt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Ns(i,e){let t=i==null?void 0:i[e];return typeof t=="number"?t:0}function Pa(i,e,t){try{i[e]=t}catch{}}function Hs(i){let e=i==null?void 0:i.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 Ma(i,e){let t=i==null?void 0:i.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 ka(i,e){let t=Hs(i);if(!t)return{from:null,to:null};let n=null,a=null;return typeof e.scale=="number"?(n=e.scale,a=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(a=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(a=e.scaleY),n===null&&a===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:a!=null?a:t.y}}}function Oa(){let i=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),i.size>0&&n()})},a=p=>{var u;i.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),n()},r=p=>{i.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},s=p=>{p.killed||(p.killed=!0,r(p))},o=()=>{var d,u;let p=gt();for(let g of Array.from(i)){if(g.killed||g.paused)continue;let h=p-g.startMs-g.delayMs;if(h<0)continue;let f=g.durationMs>0?h/g.durationMs:1,m=_a(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let E=f-y;m=_a(E)}let v=g.ease(m);g.yoyo&&y%2===1&&(v=1-v);for(let E of g.props)Pa(g.target,E.key,E.from+(E.to-E.from)*v);g.scaleFrom&&g.scaleTo&&Ma(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{(d=g.onUpdate)==null||d.call(g)}catch{}if(f>=b){s(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var E;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),h=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((E=u==null?void 0:u.delayMsOverride)!=null?E:0)),f=zs(d.ease),m=typeof d.repeat=="number"?Math.max(0,d.repeat|0):0,b=d.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let w of Object.keys(d)){if(y.has(w))continue;let T=d[w];typeof T=="number"&&v.push({key:w,from:Ns(p,w),to:T})}let x=ka(p,d);return{target:p,startMs:gt(),delayMs:h,durationMs:g,ease:f,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:m,yoyo:b,onUpdate:typeof d.onUpdate=="function"?d.onUpdate:void 0,onComplete:typeof d.onComplete=="function"?d.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(p,d){let u=l(p,d);return a(u),{kill:()=>s(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=gt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:gt(),h=gt()-g;u.startMs+=h,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(p,d,u){return c.set(p,d),c.to(p,u)},set(p,d){if(!p||!d)return;for(let g of Object.keys(d)){let h=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Pa(p,g,h)}let u=ka(p,d);u.to&&Ma(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))s(u)},timeline(p={}){let d=[],u=0,g=!1,h=[],f=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},m=y=>{d.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,x){return m({kind:"to",target:y,vars:v,atMs:f(x)}),b},fromTo(y,v,x,E){return m({kind:"fromTo",target:y,vars:x,from:v,atMs:f(E)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let x of d)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),h.push(c.to(x.target,{...x.vars,delay:x.atMs/1e3+((v=x.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return p.paused||b.play(),b}};return c}function Ia(){if(typeof window=="undefined")return;let i=window;if(!i.gsap)try{i.gsap=Oa()}catch{}}var Ra={name:"handler-playable-sdk",version:"0.3.43",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 && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var X=0,Fs=X++,ja=X++,Da=X++,$a=X++,za=X++,Na=X++,Ha=X++,Ba=X++,Fa=X++,Ua=X++,Ga=X++,qa=X++,H=Fs;function Va(){return H===ja}function Wa(){return H===Da}function Ya(){return H===$a}function Ka(){return H===za}function We(){return H===Na}function Ye(){return H===Ha}function Xa(){return H===Ba}function Ja(){return H===Fa}function Za(){return H===Ua}function ni(){return H===Ga}function ii(){return H===qa}function Qa(){let i=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(i==="mraid")try{mraid.getState(),H=ja;return}catch{}else if(i==="dapi")try{dapi.isReady(),H=Da;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(H=$a)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(H=za)}catch{}else if(e==="mintegral")window.gameReady&&(H=Na);else if(e==="tapjoy")window.TJ_API&&(H=Ha);else if(e==="tiktok")window.openAppStore&&(H=Ba);else if(e==="smadex")try{window.smxTracking&&(H=Fa)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(H=Ua)}catch{}else e==="vungle"?H=Ga:(i==="nucleo"||e==="nucleo")&&(H=qa)}var Ut=qe(require("lottie-web"),1),ai=Ut.default;typeof window!="undefined"&&(window.lottie=Ut.default,window.__baseLottie=Ut.default);var Us=require("pixi.js");var ri=require("pixi.js");var Gs=null;function si(i){Gs=i}Gt();oi();var ft=require("pixi.js");Gt();var Xs=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",pi=Xs;if(typeof window!="undefined")try{let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);e!=null&&e.buildMode&&(pi=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${pi}`))}}catch{}var Ee=class{static async create(e,t,n){var l,c,p,d,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${pi}`);let a=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!a){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new ft.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}let r=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${r}, type: ${a.type}, path: ${a.path}`);let s=await Re.load(e,a,n,r);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=s==null?void 0:s.constructor)==null?void 0:p.name}`);let o;if(a.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",e),o=new ft.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(d=o==null?void 0:o.constructor)==null?void 0:d.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(a.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=s==null?void 0:s.constructor)==null?void 0:u.name,s),s&&(((g=s.constructor)==null?void 0:g.name)==="Container"||s instanceof ft.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[a.path,`/assets/${a.path}`,`assets/${a.path}`,`../assets/${a.path}`],m=!1;for(let b of f)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),m=!0;break}}catch{continue}m||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,n){var a,r,s,o;!t||!e||(t.position&&("x"in e&&"y"in e?(e.x=(a=t.position.x)!=null?a:0,e.y=(r=t.position.y)!=null?r:0):"position"in e&&e.position&&e.position.set((s=t.position.x)!=null?s:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor&&Array.isArray(t.anchor)&&("set"in e.anchor?e.anchor.set(t.anchor[0],t.anchor[1]):(e.anchor.x=t.anchor[0],e.anchor.y=t.anchor[1])))}};var ht=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 Qs=qe(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=Qs);Ke();var qt=require("pixi.js");Ke();var fi=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new ht}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(a=>!this.instanceCache.has(a));if(t.length===0)return;let n=async a=>{a.length&&(console.log("[Assets] Loading objects:",a),await Promise.all(a.map(async r=>{var o;let s=this.registry.get(r);if(!s){console.warn("[Assets] No config found for object:",r);return}try{let l=await Ee.create(r,s,this.app);this.instanceCache.set(r,l),console.log("[Assets] Loaded object:",r,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",r,l)}})))};return this.readyPromise=(async()=>{await n(t);let a=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));a.length>0&&(console.warn("[Assets] Retrying missing assets:",a),await n(a)),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 Ee.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},eo=new fi,to=new Proxy(eo,{get(i,e){if(e in i&&typeof i[e]=="function")return i[e].bind(i);if(i.get(e))return i.get(e)}});Ke();var rr=require("pixi.js"),ge={width:400,height:600,designWidth:400,scaleFactor:1},Wt={scale:1,position:1},mi=[];function io(i,e,t,n,a,r,s){mi.push({element:i,originalScale:r,positionHelper:e,heightPercent:a}),e(i,t,n,a,r,s,!1)}function ao(){mi.forEach(({element:i,originalScale:e,positionHelper:t,heightPercent:n})=>{let a=e*ge.scaleFactor;t(i,ge.width,ge.height,n,a,!0,!1)})}function hi(i,e){console.log(`[SCREEN] updateScreenState called: ${i}x${e}`),ge.width=i,ge.height=e,ge.scaleFactor=Math.min(i/ge.designWidth,1.15),Wt.scale=ge.scaleFactor,Wt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Wt.scale.toFixed(3)}`),ao()}var bt={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 ro(i,e,t){let n=bt[i];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${i}.${e} = ${t}`))}function so(){return bt}var oo={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 Vt(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function Yt(i,e={x:.5,y:.5}){var t;if(Array.isArray(i))return{x:Vt(i[0],e.x),y:Vt(i[1],e.y)};if(i&&typeof i=="object"){let n=i;return{x:Vt(n.x,e.x),y:Vt(n.y,e.y)}}if(typeof i=="string"){let n=i.trim().toLowerCase();return(t=oo[n])!=null?t:e}return e}function sr(i,e,t,n={}){var g,h,f,m,b,y;let a=Yt(t),r=(g=n.inset)!=null?g:{},s=(h=n.padding)!=null?h:{x:0,y:0},o=((f=r.left)!=null?f:0)+s.x,l=((m=r.right)!=null?m:0)+s.x,c=((b=r.top)!=null?b:0)+s.y,p=((y=r.bottom)!=null?y:0)+s.y,d=Math.max(0,i-o-l),u=Math.max(0,e-c-p);return{x:o+d*a.x,y:c+u*a.y}}function or(i,e,t,n={}){var f,m,b,y,v,x;let a=(f=n.inset)!=null?f:{},r=(m=n.padding)!=null?m:{x:0,y:0},s=((b=a.left)!=null?b:0)+r.x,o=((y=a.right)!=null?y:0)+r.x,l=((v=a.top)!=null?v:0)+r.y,c=((x=a.bottom)!=null?x:0)+r.y,p=Math.max(0,i-s-o),d=Math.max(0,e-l-c),u=Yt(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:s+p*g,y:l+d*h}}if(typeof window!="undefined"){let i=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,a=window.innerHeight;(n!==i||a!==e)&&(i=n,e=a,hi(n,a))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),hi(window.innerWidth,window.innerHeight),window.updateDebugConfig=ro,window.getDebugConfig=so,window.copyConfig=vo,window.applyConfig=mt,window.applyConfigForRatio=xo,window.positionAtBottom=lr,window.positionAtTop=po,window.positionAtCenter=uo,window.positionAtLeft=go,window.positionAtRight=fo,window.positionAtBottomLeft=ho,window.positionAtBottomRight=mo,window.positionAtTopLeft=bo,window.positionAtTopRight=yo,window.applyPositionContract=co,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 Kt(i,e,t=0){return i*e+t}function Xt(i,e,t=0){return i*(1-e)+t}function Jt(i,e,t=0){return i*e+t}function Zt(i,e,t=0){return i*(1-e)+t}function J(i,e=0){return i/2+e}function lo(i,e){return i*e}function co(i,e,t,n){var s,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O;let a=0,r=0;switch(n.type){case"top":a=J(e,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),r=Kt(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":a=J(e,(d=(p=n.offset)==null?void 0:p.x)!=null?d:0),r=Xt(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":a=Jt(e,n.percent,(f=(h=n.offset)==null?void 0:h.x)!=null?f:0),r=J(t,(b=(m=n.offset)==null?void 0:m.y)!=null?b:0);break;case"right":a=Zt(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),r=J(t,(E=(x=n.offset)==null?void 0:x.y)!=null?E:0);break;case"center":a=J(e,(T=(w=n.offset)==null?void 0:w.x)!=null?T:0),r=J(t,(O=(S=n.offset)==null?void 0:S.y)!=null?O:0);break}i.position?i.position.set(a,r):(i.x=a,i.y=r),n.scale!==void 0&&n.scale!==1&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(n.scale,n.scale):(i.scale.x=n.scale,i.scale.y=n.scale))}function lr(i,e,t,n=.2,a=1,r=!0,s=!1){let o=lo(t,n),l=Xt(t,n/2);fe(i,J(e),l);let c=r?a*ge.scaleFactor:a;he(i,c),s&&!mi.find(p=>p.element===i)&&io(i,lr,e,t,n,a,r)}function po(i,e,t,n=.1,a=1){fe(i,J(e),Kt(t,n)),he(i,a)}function uo(i,e,t,n=0,a=0,r=1){fe(i,J(e,n),J(t,a)),he(i,r)}function go(i,e,t,n=.1,a=1){fe(i,Jt(e,n),J(t)),he(i,a)}function fo(i,e,t,n=.1,a=1){fe(i,Zt(e,n),J(t)),he(i,a)}function ho(i,e,t,n=.05,a=.05,r=1){fe(i,Jt(e,a),Xt(t,n)),he(i,r)}function mo(i,e,t,n=.05,a=.05,r=1){fe(i,Zt(e,a),Xt(t,n)),he(i,r)}function bo(i,e,t,n=.05,a=.05,r=1){fe(i,Jt(e,a),Kt(t,n)),he(i,r)}function yo(i,e,t,n=.05,a=.05,r=1){fe(i,Zt(e,a),Kt(t,n)),he(i,r)}function fe(i,e,t){i&&i.position?typeof i.position.set=="function"?i.position.set(e,t):(i.position.x=e,i.position.y=t):i&&(i.x=e,i.y=t)}function he(i,e){e!==1&&i&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(e,e):i.scale.x!==void 0&&i.scale.y!==void 0&&(i.scale.x=e,i.scale.y=e))}var je={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function vo(i){return i&&je[i]?JSON.parse(JSON.stringify(je[i])):JSON.parse(JSON.stringify(bt))}function mt(i){Object.keys(i).forEach(e=>{let t=e;bt[t]&&i[t]&&Object.assign(bt[t],i[t])}),console.log("Config applied:",i)}function xo(i,e){let t=i/e;t>1.6?(mt(je.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(mt(je.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(mt(je.square),console.log("Applied SQUARE config for ratio:",t)):(mt(je.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let i=window;i.configPresets=je,i.resolveAnchorVec2=i.resolveAnchorVec2||Yt,i.resolveScreenAnchorPoint=i.resolveScreenAnchorPoint||sr,i.resolveScreenRatioPoint=i.resolveScreenRatioPoint||or}dn();function U(i,e){let t=(a,r)=>r===0?a:t(r,a%r),n=t(i,e);return`${i/n}:${e/n}`}var zc=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:U(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:U(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:U(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:U(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:U(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:U(360,780)}],Nc=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:U(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:U(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:U(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:U(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:U(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:U(412,915)}],Hc=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:U(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:U(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:U(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:U(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:U(800,1280)}],_i=[{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:U(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:U(768,1024),mraidScale:.7}];var Pi=[..._i],Mi=[{category:"playable",label:"Playable Ad",devices:_i}],pn=_i[0];function ze(i){return Pi.find(e=>e.id===i)||pn}function ko(i){return Pi.filter(e=>e.category===i)}var un=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
47
47
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects" style="left:16px; top:72px;">
48
48
  <div class="scene-panel-header" data-panel-handle>
49
49
  <div class="panel-title">
@@ -76,13 +76,13 @@
76
76
  <div class="scene-object-list" data-object-list></div>
77
77
  </div>
78
78
  </div>
79
- `}initialize(e,t){var a,s,r,o,l;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(s=this.root)==null?void 0:s.querySelector("#scene-object-search"),(r=this.searchInput)==null||r.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let c=window.localStorage.getItem(this.getScreenFilterStorageKey());c&&(this.screenFilter=c)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let c=n.value||"all";this.screenFilter=c;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{}this.refreshObjects()})}(l=this.root)==null||l.addEventListener("click",c=>{let p=c.target;if(!p)return;let d=p.closest("[data-object-id]");if(!d)return;let u=d.dataset.objectId;u&&this.select(u)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(e){var r,o,l,c,p;if(this.selectedId=e,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{d.classList.toggle("selected",d.dataset.objectId===e)});let n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumbs]"),a=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-screen]"),s=(l=this.root)==null?void 0:l.querySelector("[data-breadcrumb-object]");if(n&&a&&s)if(e){let d=window.getEditableObjectConfig,u=typeof d=="function"?d(e):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(c=b.get(e))!=null?c:null)}let g=this.inferScreen(e,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},f=(((p=u==null?void 0:u.identity)==null?void 0:p.id)||e).toString(),m=this.formatDisplayName(f);a.textContent=h[g]||g,s.textContent=m,n.style.display="flex"}else n.style.display="none"}refreshObjects(){var p;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"){this.scheduleRetry();return}let a=e();if(!Array.isArray(a)||a.length===0){let d=window.__editableObjectConfigs;d&&typeof d.keys=="function"&&(a=Array.from(d.keys()))}if(!Array.isArray(a)||a.length===0){this.scheduleRetry();return}let s=(((p=this.searchInput)==null?void 0:p.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(r.map(d=>[d,[]])),l=Object.fromEntries(r.map(d=>[d,[]]));a.forEach(d=>{var O,B,M,C;let u=typeof t=="function"?t(d):null;if(!u){let I=window.__editableObjectConfigs;I&&typeof I.get=="function"&&(u=(O=I.get(d))!=null?O:null)}let g=(((B=u==null?void 0:u.identity)==null?void 0:B.category)||"scene").toString(),h=(((M=u==null?void 0:u.identity)==null?void 0:M.id)||d).toString(),f=g.toLowerCase(),m=h.toLowerCase(),b=f.includes("ui")||m.startsWith("ui")||m.includes("label"),y=this.formatDisplayName(h||d),v=((C=u==null?void 0:u.render)==null?void 0:C.visible)===!1||(u==null?void 0:u.enabled)===!1,x=this.getObjectType(u),E={id:d,label:y,category:g,isUi:b,isUnused:v,objectType:x},w=this.inferScreen(E.id,u);if(this.screenFilter!=="all"&&w!==this.screenFilter||!(!s||E.id.toLowerCase().includes(s)||E.label.toLowerCase().includes(s)))return;(E.isUnused?l:o)[w].push(E)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
80
- ${r.map(d=>this.renderGroup(c[d],[...o[d],...l[d]])).join("")}
81
- `,this.setSelected(this.selectedId)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var o,l;let n=window.__HANDLER_SCREEN_INDEX,a=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[e];if(a==="loading"||a==="start"||a==="gameplay"||a==="tutorial"||a==="endgame")return a;let s=(((l=t==null?void 0:t.identity)==null?void 0:l.id)||"").toString(),r=`${e} ${s}`.toLowerCase();return r.includes("loading")?"loading":r.includes("start")?"start":r.includes("tutorial")?"tutorial":r.includes("endgame")||r.includes("end_card")||r.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,n,a,s,r,o,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(s=(a=(n=e.render)==null?void 0:n.asset)==null?void 0:a.path)!=null&&s.endsWith(".json")?"animation":((o=(r=e.render)==null?void 0:r.asset)==null?void 0:o.type)==="image"||(l=e.render)!=null&&l.texture?"sprite":(p=(c=e.gameplay)==null?void 0:c.tuning)!=null&&p.panel_width?"graphics":"container":"container"}renderGroup(e,t){if(!t.length)return"";let n=window.getEditableObjectConfig,a=t.map(s=>{var p,d;let r=typeof n=="function"?n(s.id):null;if(!r){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(r=(p=u.get(s.id))!=null?p:null)}let o=this.getTypeIconByType(s.objectType),l=this.getAssetPreview(r),c=(d=r==null?void 0:r.ui)!=null&&d.text?`"${r.ui.text.substring(0,12)}${r.ui.text.length>12?"...":""}"`:"";return`
82
- <button class="scene-object-item ${s.isUnused?"unused":""}" data-object-id="${s.id}">
83
- <span class="scene-object-label">${s.label}</span>
79
+ `}initialize(e,t){var a,r,s,o,l;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"),(s=this.searchInput)==null||s.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let c=window.localStorage.getItem(this.getScreenFilterStorageKey());c&&(this.screenFilter=c)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let c=n.value||"all";this.screenFilter=c;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{}this.refreshObjects()})}(l=this.root)==null||l.addEventListener("click",c=>{let p=c.target;if(!p)return;let d=p.closest("[data-object-id]");if(!d)return;let u=d.dataset.objectId;u&&this.select(u)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(e){var s,o,l,c,p;if(this.selectedId=e,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{d.classList.toggle("selected",d.dataset.objectId===e)});let n=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumbs]"),a=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-screen]"),r=(l=this.root)==null?void 0:l.querySelector("[data-breadcrumb-object]");if(n&&a&&r)if(e){let d=window.getEditableObjectConfig,u=typeof d=="function"?d(e):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(c=b.get(e))!=null?c:null)}let g=this.inferScreen(e,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},f=(((p=u==null?void 0:u.identity)==null?void 0:p.id)||e).toString(),m=this.formatDisplayName(f);a.textContent=h[g]||g,r.textContent=m,n.style.display="flex"}else n.style.display="none"}refreshObjects(){var p;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"){this.scheduleRetry();return}let a=e();if(!Array.isArray(a)||a.length===0){let d=window.__editableObjectConfigs;d&&typeof d.keys=="function"&&(a=Array.from(d.keys()))}if(!Array.isArray(a)||a.length===0){this.scheduleRetry();return}let r=(((p=this.searchInput)==null?void 0:p.value)||"").trim().toLowerCase(),s=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(s.map(d=>[d,[]])),l=Object.fromEntries(s.map(d=>[d,[]]));a.forEach(d=>{var O,B,M,C;let u=typeof t=="function"?t(d):null;if(!u){let I=window.__editableObjectConfigs;I&&typeof I.get=="function"&&(u=(O=I.get(d))!=null?O:null)}let g=(((B=u==null?void 0:u.identity)==null?void 0:B.category)||"scene").toString(),h=(((M=u==null?void 0:u.identity)==null?void 0:M.id)||d).toString(),f=g.toLowerCase(),m=h.toLowerCase(),b=f.includes("ui")||m.startsWith("ui")||m.includes("label"),y=this.formatDisplayName(h||d),v=((C=u==null?void 0:u.render)==null?void 0:C.visible)===!1||(u==null?void 0:u.enabled)===!1,x=this.getObjectType(u),E={id:d,label:y,category:g,isUi:b,isUnused:v,objectType:x},w=this.inferScreen(E.id,u);if(this.screenFilter!=="all"&&w!==this.screenFilter||!(!r||E.id.toLowerCase().includes(r)||E.label.toLowerCase().includes(r)))return;(E.isUnused?l:o)[w].push(E)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
80
+ ${s.map(d=>this.renderGroup(c[d],[...o[d],...l[d]])).join("")}
81
+ `,this.setSelected(this.selectedId)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var o,l;let n=window.__HANDLER_SCREEN_INDEX,a=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[e];if(a==="loading"||a==="start"||a==="gameplay"||a==="tutorial"||a==="endgame")return a;let r=(((l=t==null?void 0:t.identity)==null?void 0:l.id)||"").toString(),s=`${e} ${r}`.toLowerCase();return s.includes("loading")?"loading":s.includes("start")?"start":s.includes("tutorial")?"tutorial":s.includes("endgame")||s.includes("end_card")||s.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,n,a,r,s,o,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(r=(a=(n=e.render)==null?void 0:n.asset)==null?void 0:a.path)!=null&&r.endsWith(".json")?"animation":((o=(s=e.render)==null?void 0:s.asset)==null?void 0:o.type)==="image"||(l=e.render)!=null&&l.texture?"sprite":(p=(c=e.gameplay)==null?void 0:c.tuning)!=null&&p.panel_width?"graphics":"container":"container"}renderGroup(e,t){if(!t.length)return"";let n=window.getEditableObjectConfig,a=t.map(r=>{var p,d;let s=typeof n=="function"?n(r.id):null;if(!s){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(s=(p=u.get(r.id))!=null?p:null)}let o=this.getTypeIconByType(r.objectType),l=this.getAssetPreview(s),c=(d=s==null?void 0:s.ui)!=null&&d.text?`"${s.ui.text.substring(0,12)}${s.ui.text.length>12?"...":""}"`:"";return`
82
+ <button class="scene-object-item ${r.isUnused?"unused":""}" data-object-id="${r.id}">
83
+ <span class="scene-object-label">${r.label}</span>
84
84
  ${c?`<span class="scene-object-text-preview">${c}</span>`:""}
85
- <span class="scene-object-badge ${s.isUi?"ui":"scene"}">${s.category}</span>
85
+ <span class="scene-object-badge ${r.isUi?"ui":"scene"}">${r.category}</span>
86
86
  </button>
87
87
  `}).join("");return`
88
88
  <div class="scene-object-group">
@@ -91,7 +91,7 @@
91
91
  ${a}
92
92
  </div>
93
93
  </div>
94
- `}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var n,a,s,r,o,l;if(!e)return"\u{1F4E6}";if((n=e.render)!=null&&n.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((a=e.ui)!=null&&a.text)return"\u{1F4DD}";if(((s=e.identity)==null?void 0:s.category)==="ui")return"\u{1F3A8}";if(e.effects||(o=(r=e.identity)==null?void 0:r.id)!=null&&o.includes("effect"))return"\u2728";if(e.audio)return"\u{1F50A}";let t=((l=e.identity)==null?void 0:l.id)||"";return t.includes("background")?"\u{1F5BC}\uFE0F":t.includes("character")?"\u{1F464}":t.includes("key")?"\u{1F511}":t.includes("draggable")?"\u{1F3AF}":t.includes("machine")?"\u2699\uFE0F":t.includes("tutorial")||t.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(e){var n;if(!e)return null;let t=(n=e.render)==null?void 0:n.texture;return t&&(t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg"))?t.startsWith("library/")||t.startsWith("/raw/")?`/raw/${t.replace(/^\/raw\//,"")}`:`/raw/${t}`:null}getColorIndicator(e){var n,a,s,r;if(!e)return"";let t=((n=e.render)==null?void 0:n.background_color)||((s=(a=e.gameplay)==null?void 0:a.tuning)==null?void 0:s.panel_bg_color)||((r=e.ui)==null?void 0:r.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var n,a,s,r;if(!e)return"";let t=[];return((n=e.render)==null?void 0:n.visible)===!1&&t.push("hidden"),((a=e.render)==null?void 0:a.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((s=e.interaction)!=null&&s.clickable||(r=e.ui)!=null&&r.button)&&t.push("clickable"),t.length>0?t.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t;this.selectedId=e,this.setSelected(e),(t=this.options)==null||t.onSelect(e)}};var gn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
94
+ `}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var n,a,r,s,o,l;if(!e)return"\u{1F4E6}";if((n=e.render)!=null&&n.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((a=e.ui)!=null&&a.text)return"\u{1F4DD}";if(((r=e.identity)==null?void 0:r.category)==="ui")return"\u{1F3A8}";if(e.effects||(o=(s=e.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(e.audio)return"\u{1F50A}";let t=((l=e.identity)==null?void 0:l.id)||"";return t.includes("background")?"\u{1F5BC}\uFE0F":t.includes("character")?"\u{1F464}":t.includes("key")?"\u{1F511}":t.includes("draggable")?"\u{1F3AF}":t.includes("machine")?"\u2699\uFE0F":t.includes("tutorial")||t.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(e){var n;if(!e)return null;let t=(n=e.render)==null?void 0:n.texture;return t&&(t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg"))?t.startsWith("library/")||t.startsWith("/raw/")?`/raw/${t.replace(/^\/raw\//,"")}`:`/raw/${t}`:null}getColorIndicator(e){var n,a,r,s;if(!e)return"";let t=((n=e.render)==null?void 0:n.background_color)||((r=(a=e.gameplay)==null?void 0:a.tuning)==null?void 0:r.panel_bg_color)||((s=e.ui)==null?void 0:s.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var n,a,r,s;if(!e)return"";let t=[];return((n=e.render)==null?void 0:n.visible)===!1&&t.push("hidden"),((a=e.render)==null?void 0:a.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((r=e.interaction)!=null&&r.clickable||(s=e.ui)!=null&&s.button)&&t.push("clickable"),t.length>0?t.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t;this.selectedId=e,this.setSelected(e),(t=this.options)==null||t.onSelect(e)}};var gn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
95
95
  <div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
96
96
  <div class="scene-tools-header" data-tools-header data-panel-handle>
97
97
  <span class="scene-tools-title">Scene Tools</span>
@@ -136,7 +136,7 @@
136
136
  </div>
137
137
  </div>
138
138
  </div>
139
- `}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 a=this.root.querySelector("[data-tools-collapse]");a==null||a.addEventListener("click",()=>{var c;this.isCollapsed=!this.isCollapsed,(c=this.root)==null||c.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let s=(c,p)=>{var u;let d=(u=this.root)==null?void 0:u.querySelector(`[data-status="${c}"]`);d&&d.classList.toggle("active",p)},r=this.root.querySelector("#debug-highlight-object");r==null||r.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!r.checked),s("bounds",r.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!o.checked),s("anchor",o.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{s("nudge",l.checked)})}updateInfo(e){}};var fn=class{constructor(){this.root=null;this.options=null}render(){return`
139
+ `}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 a=this.root.querySelector("[data-tools-collapse]");a==null||a.addEventListener("click",()=>{var c;this.isCollapsed=!this.isCollapsed,(c=this.root)==null||c.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let r=(c,p)=>{var u;let d=(u=this.root)==null?void 0:u.querySelector(`[data-status="${c}"]`);d&&d.classList.toggle("active",p)},s=this.root.querySelector("#debug-highlight-object");s==null||s.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!s.checked),r("bounds",s.checked)});let o=this.root.querySelector("#debug-highlight-anchor");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!o.checked),r("anchor",o.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{r("nudge",l.checked)})}updateInfo(e){}};var fn=class{constructor(){this.root=null;this.options=null}render(){return`
140
140
  <div class="nudge-panel hidden" data-panel="nudge-panel">
141
141
  <div class="nudge-panel-header">
142
142
  <span class="nudge-panel-title">Nudge Controls</span>
@@ -193,7 +193,7 @@
193
193
  </div>
194
194
  </div>
195
195
  </div>
196
- `}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(s=>{s.addEventListener("click",()=>{var l,c,p,d;let r=s.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":(p=this.options)==null||p.onNudge(-o,0);break;case"right":(d=this.options)==null||d.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(s=>{s.addEventListener("click",()=>{var l;let o=s.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,a;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((a=e==null?void 0:e.value)!=null?a:10);return Number.isFinite(t)&&t>0?t:10}};var hn=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let n=e||{},a=t||{},s={slots:Array.isArray(a.slots)?[...a.slots]:[],libraryAssets:typeof a.libraryAssets=="object"&&a.libraryAssets?{...a.libraryAssets}:{},categories:Array.isArray(a.categories)?[...a.categories]:[]},r=Array.isArray(n.slots)?n.slots:[];if(r.length>0&&s.slots.length>0)for(let c of s.slots){let p=r.find(d=>(d==null?void 0:d.slotId)&&d.slotId===(c==null?void 0:c.slotId));p!=null&&p.currentAsset&&p.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=p.currentAsset)}let o=n.libraryAssets||{};for(let[c,p]of Object.entries(o)){if(!Array.isArray(p))continue;s.libraryAssets[c]||(s.libraryAssets[c]=[]);let d=new Set((s.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of p){let g=u==null?void 0:u.filename;!g||d.has(g)||(s.libraryAssets[c].unshift(u),d.add(g))}}let l=new Set(s.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return s.categories=Array.from(l),s}render(){return`
196
+ `}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(r=>{r.addEventListener("click",()=>{var l,c,p,d;let s=r.dataset.nudge,o=this.getNudgeStep();switch(s){case"up":(l=this.options)==null||l.onNudge(0,-o);break;case"down":(c=this.options)==null||c.onNudge(0,o);break;case"left":(p=this.options)==null||p.onNudge(-o,0);break;case"right":(d=this.options)==null||d.onNudge(o,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(r=>{r.addEventListener("click",()=>{var l;let o=r.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,a;let e=(n=this.root)==null?void 0:n.querySelector("#nudge-step-input"),t=Number((a=e==null?void 0:e.value)!=null?a:10);return Number.isFinite(t)&&t>0?t:10}};var hn=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let n=e||{},a=t||{},r={slots:Array.isArray(a.slots)?[...a.slots]:[],libraryAssets:typeof a.libraryAssets=="object"&&a.libraryAssets?{...a.libraryAssets}:{},categories:Array.isArray(a.categories)?[...a.categories]:[]},s=Array.isArray(n.slots)?n.slots:[];if(s.length>0&&r.slots.length>0)for(let c of r.slots){let p=s.find(d=>(d==null?void 0:d.slotId)&&d.slotId===(c==null?void 0:c.slotId));p!=null&&p.currentAsset&&p.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=p.currentAsset)}let o=n.libraryAssets||{};for(let[c,p]of Object.entries(o)){if(!Array.isArray(p))continue;r.libraryAssets[c]||(r.libraryAssets[c]=[]);let d=new Set((r.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of p){let g=u==null?void 0:u.filename;!g||d.has(g)||(r.libraryAssets[c].unshift(u),d.add(g))}}let l=new Set(r.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return r.categories=Array.from(l),r}render(){return`
197
197
  <div class="scene-panel library-panel panel-accent-purple" data-panel="library">
198
198
  <div class="scene-panel-header" data-panel-handle>
199
199
  <div class="panel-title">
@@ -212,7 +212,7 @@
212
212
  </div>
213
213
  <div class="panel-resize-handle" data-panel-resize></div>
214
214
  </div>
215
- `}initialize(e,t){var s,r,o;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(s=this.root)==null?void 0:s.querySelector("[data-library-slots]");let n=(r=this.root)==null?void 0:r.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let a=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");a==null||a.addEventListener("click",()=>{a.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>a.classList.remove("pulse-anim"),500)}),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 a=await n.json(),s=this.mergeRegistries(t,a);window.getEditableAssets=()=>s,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();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(){if(!this.slotsContainer||!this.registry)return;let e={};for(let n of this.registry.slots)e[n.category]||(e[n.category]=[]),e[n.category].push(n);let t=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let a=e[n]||[];if(a.length===0)continue;let s=document.createElement("div");s.className="library-category";let r=document.createElement("div");r.className="library-category-header",r.textContent=this.formatCategoryName(n),s.appendChild(r);let o=document.createElement("div");o.className="library-category-slots";for(let l of a){let c=this.createSlotElement(l,t);o.appendChild(c)}s.appendChild(o),this.slotsContainer.appendChild(s)}}createSlotElement(e,t){let n=this.expandedSlot===e.slotId,a=document.createElement("div");a.className=`library-slot ${n?"expanded":""}`,a.dataset.slotId=e.slotId;let s=document.createElement("div");s.className="slot-header";let r=document.createElement("div");r.className="slot-current";let o=document.createElement("img");o.src=`/raw/${e.currentAsset}?t=${t}`,o.alt=e.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},r.appendChild(o),s.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 p=document.createElement("div");p.className="slot-asset",p.textContent=e.currentAsset,l.appendChild(c),l.appendChild(p),s.appendChild(l);let d=document.createElement("div");d.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 f=>{f.stopPropagation(),await this.handleAIEdit(e)}),d.appendChild(u);let g=document.createElement("button");g.className="slot-reset",g.title="Reset to default",g.textContent="\u21BA",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(g);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=n?"\u25BC":"\u25B6",d.appendChild(h),s.appendChild(d),s.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),a.appendChild(s),n){let f=this.createLibraryElement(e,t);a.appendChild(f)}return a}createLibraryElement(e,t){var s;let n=document.createElement("div");n.className="slot-library";let a=((s=this.registry)==null?void 0:s.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(r=>{let o=new Map;for(let c of a)o.set(c.filename,c);for(let c of r)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let p=document.createElement("div");p.className="library-item";let d=document.createElement("img");d.src=`/raw/library/${e.libraryFolder}/${c.filename}?t=${t}`,d.alt=c.displayName,d.className="library-thumbnail",d.onerror=()=>{d.style.opacity="0.3"},p.appendChild(d);let u=document.createElement("div");u.className="library-label",u.textContent=c.displayName,p.appendChild(u),p.addEventListener("click",async()=>{await this.handleApply(e,c.filename)}),n.appendChild(p)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let a=await n.text(),s=[],r=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=r.exec(a))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");s.push({filename:l,displayName:c})}}return s}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t){var n;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{await((n=this.options)==null?void 0:n.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}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()}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(" ")}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,a="render.texture";e.category==="ui"&&(a="ui.image"),e.category==="audio"&&(a="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:a})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}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,a=this.registry.slots.find(s=>(s.objectId===n||s.slotId===n)&&(!t||s.category===t));a?(console.log("[LIBRARY] Highlighting slot:",a.slotId),this.expandedSlot=a.slotId,this.renderSlots(),setTimeout(()=>{var r;let s=(r=this.slotsContainer)==null?void 0:r.querySelector(`[data-slot-id="${a.slotId}"]`);s&&(s.scrollIntoView({behavior:"smooth",block:"center"}),s.classList.add("highlight-pulse"),setTimeout(()=>s.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var mn=class{detectType(e,t,n){let a=e.toLowerCase();return a==="logic_id"||a==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":a.includes("color")||a.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 bn=class{render(e,t,n,a){let s=n&&n.trim(),r=s?`/raw/${n}`:"";return`
215
+ `}initialize(e,t){var r,s,o;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(r=this.root)==null?void 0:r.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let a=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");a==null||a.addEventListener("click",()=>{a.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>a.classList.remove("pulse-anim"),500)}),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 a=await n.json(),r=this.mergeRegistries(t,a);window.getEditableAssets=()=>r,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();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(){if(!this.slotsContainer||!this.registry)return;let e={};for(let n of this.registry.slots)e[n.category]||(e[n.category]=[]),e[n.category].push(n);let t=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let a=e[n]||[];if(a.length===0)continue;let r=document.createElement("div");r.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),r.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let l of a){let c=this.createSlotElement(l,t);o.appendChild(c)}r.appendChild(o),this.slotsContainer.appendChild(r)}}createSlotElement(e,t){let n=this.expandedSlot===e.slotId,a=document.createElement("div");a.className=`library-slot ${n?"expanded":""}`,a.dataset.slotId=e.slotId;let r=document.createElement("div");r.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${e.currentAsset}?t=${t}`,o.alt=e.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),r.appendChild(s);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let p=document.createElement("div");p.className="slot-asset",p.textContent=e.currentAsset,l.appendChild(c),l.appendChild(p),r.appendChild(l);let d=document.createElement("div");d.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 f=>{f.stopPropagation(),await this.handleAIEdit(e)}),d.appendChild(u);let g=document.createElement("button");g.className="slot-reset",g.title="Reset to default",g.textContent="\u21BA",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(g);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=n?"\u25BC":"\u25B6",d.appendChild(h),r.appendChild(d),r.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),a.appendChild(r),n){let f=this.createLibraryElement(e,t);a.appendChild(f)}return a}createLibraryElement(e,t){var r;let n=document.createElement("div");n.className="slot-library";let a=((r=this.registry)==null?void 0:r.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(s=>{let o=new Map;for(let c of a)o.set(c.filename,c);for(let c of s)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let p=document.createElement("div");p.className="library-item";let d=document.createElement("img");d.src=`/raw/library/${e.libraryFolder}/${c.filename}?t=${t}`,d.alt=c.displayName,d.className="library-thumbnail",d.onerror=()=>{d.style.opacity="0.3"},p.appendChild(d);let u=document.createElement("div");u.className="library-label",u.textContent=c.displayName,p.appendChild(u),p.addEventListener("click",async()=>{await this.handleApply(e,c.filename)}),n.appendChild(p)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let a=await n.text(),r=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(a))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");r.push({filename:l,displayName:c})}}return r}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t){var n;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{await((n=this.options)==null?void 0:n.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}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()}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(" ")}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,a="render.texture";e.category==="ui"&&(a="ui.image"),e.category==="audio"&&(a="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:a})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}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,a=this.registry.slots.find(r=>(r.objectId===n||r.slotId===n)&&(!t||r.category===t));a?(console.log("[LIBRARY] Highlighting slot:",a.slotId),this.expandedSlot=a.slotId,this.renderSlots(),setTimeout(()=>{var s;let r=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${a.slotId}"]`);r&&(r.scrollIntoView({behavior:"smooth",block:"center"}),r.classList.add("highlight-pulse"),setTimeout(()=>r.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var mn=class{detectType(e,t,n){let a=e.toLowerCase();return a==="logic_id"||a==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":a.includes("color")||a.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 bn=class{render(e,t,n,a){let r=n&&n.trim(),s=r?`/raw/${n}`:"";return`
216
216
  <div class="inspector-property inspector-property-image">
217
217
  <div class="property-header">
218
218
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
@@ -222,9 +222,9 @@
222
222
  </div>
223
223
 
224
224
  <div class="inspector-image-container">
225
- ${s?`
225
+ ${r?`
226
226
  <div class="inspector-image-preview">
227
- <img src="${r}" alt="${t}" onclick="window.open('${r}', '_blank')" />
227
+ <img src="${s}" alt="${t}" onclick="window.open('${s}', '_blank')" />
228
228
  <div class="preview-overlay">
229
229
  <span class="preview-resolution" id="res-${e}-${t}">- x -</span>
230
230
  </div>
@@ -262,18 +262,18 @@
262
262
  </div>
263
263
  </div>
264
264
  </div>
265
- `}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,a){let s=n||"#000000";return`
265
+ `}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,a){let r=n||"#000000";return`
266
266
  <div class="inspector-property inspector-property-color">
267
267
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
268
268
  <div class="inspector-color-group">
269
269
  <input type="color"
270
270
  class="inspector-color-picker"
271
- value="${s}"
271
+ value="${r}"
272
272
  data-property-path="${a}"
273
273
  data-object-id="${e}" />
274
274
  <input type="text"
275
275
  class="inspector-input inspector-color-text"
276
- value="${s}"
276
+ value="${r}"
277
277
  data-property-path="${a}"
278
278
  data-object-id="${e}" />
279
279
  </div>
@@ -288,13 +288,13 @@
288
288
  data-object-id="${e}"
289
289
  step="any" />
290
290
  </div>
291
- `}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,a){let s=String(n||"");return`
291
+ `}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,a){let r=String(n||"");return`
292
292
  <div class="inspector-property inspector-property-text">
293
293
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
294
294
  <div class="inspector-input-group">
295
295
  <input type="text"
296
296
  class="inspector-input"
297
- value="${s}"
297
+ value="${r}"
298
298
  data-property-path="${a}"
299
299
  data-object-id="${e}" />
300
300
  </div>
@@ -315,28 +315,28 @@
315
315
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
316
316
  <div class="inspector-array-empty">Empty array</div>
317
317
  </div>
318
- `;let s=n.map((r,o)=>typeof r=="string"?`<div class="inspector-array-item">\u2022 ${r}</div>`:typeof r=="object"?`<div class="inspector-array-item">\u2022 ${JSON.stringify(r)}</div>`:`<div class="inspector-array-item">\u2022 ${String(r)}</div>`).join("");return`
318
+ `;let r=n.map((s,o)=>typeof s=="string"?`<div class="inspector-array-item">\u2022 ${s}</div>`:typeof s=="object"?`<div class="inspector-array-item">\u2022 ${JSON.stringify(s)}</div>`:`<div class="inspector-array-item">\u2022 ${String(s)}</div>`).join("");return`
319
319
  <div class="inspector-property inspector-property-array">
320
320
  <label class="inspector-property-label">${this.formatLabel(t)} (${n.length} items)</label>
321
321
  <div class="inspector-array-list">
322
- ${s}
322
+ ${r}
323
323
  </div>
324
324
  </div>
325
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var An=class{constructor(e){this.registry=e}render(e,t,n,a){if(t==="logic"&&n&&typeof n=="object")return this.renderLogic(e,t,n,a);let s=[];for(let o in n){let l=n[o],c=`${a}.${o}`,p=this.registry.renderProperty(e,o,l,c);p&&s.push(p)}return s.length===0?"":s.length<=4&&s.every(o=>o.includes("inspector-property"))?`
325
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var An=class{constructor(e){this.registry=e}render(e,t,n,a){if(t==="logic"&&n&&typeof n=="object")return this.renderLogic(e,t,n,a);let r=[];for(let o in n){let l=n[o],c=`${a}.${o}`,p=this.registry.renderProperty(e,o,l,c);p&&r.push(p)}return r.length===0?"":r.length<=4&&r.every(o=>o.includes("inspector-property"))?`
326
326
  <div class="inspector-subsection">
327
327
  <div class="inspector-subsection-title">${this.formatLabel(t)}</div>
328
328
  <div class="inspector-subsection-content">
329
- ${s.join("")}
329
+ ${r.join("")}
330
330
  </div>
331
331
  </div>
332
332
  `:`
333
333
  <div class="inspector-property inspector-property-object">
334
334
  <div class="inspector-object-header">${this.formatLabel(t)}</div>
335
335
  <div class="inspector-object-body">
336
- ${s.join("")}
336
+ ${r.join("")}
337
337
  </div>
338
338
  </div>
339
- `}renderLogic(e,t,n,a){let s=[],r=typeof(n==null?void 0:n.id)=="string"?n.id:"",o={zone:["bottom-left","bottom-right","top-left","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]},l=(()=>{let p=window,d=Array.isArray(p==null?void 0:p.__HANDLER_LOGIC_OPTIONS)?p.__HANDLER_LOGIC_OPTIONS:[],g=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...d].map(h=>String(h)).filter(h=>h.trim().length>0);return Array.from(new Set(g)).sort((h,f)=>h.localeCompare(f))})(),c=r&&!l.includes(r)?[r,...l]:l;s.push(`
339
+ `}renderLogic(e,t,n,a){let r=[],s=typeof(n==null?void 0:n.id)=="string"?n.id:"",o={zone:["bottom-left","bottom-right","top-left","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]},l=(()=>{let p=window,d=Array.isArray(p==null?void 0:p.__HANDLER_LOGIC_OPTIONS)?p.__HANDLER_LOGIC_OPTIONS:[],g=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...d].map(h=>String(h)).filter(h=>h.trim().length>0);return Array.from(new Set(g)).sort((h,f)=>h.localeCompare(f))})(),c=s&&!l.includes(s)?[s,...l]:l;r.push(`
340
340
  <div class="inspector-property inspector-property-text">
341
341
  <label class="inspector-property-label">Id</label>
342
342
  <div class="inspector-input-group">
@@ -344,8 +344,8 @@
344
344
  data-property-path="${a}.id"
345
345
  data-object-id="${e}"
346
346
  data-logic-id-selector="true">
347
- <option value="" ${r?"":"selected"}>None</option>
348
- ${c.map(p=>`<option value="${p}" ${p===r?"selected":""}>${p}</option>`).join("")}
347
+ <option value="" ${s?"":"selected"}>None</option>
348
+ ${c.map(p=>`<option value="${p}" ${p===s?"selected":""}>${p}</option>`).join("")}
349
349
  </select>
350
350
  </div>
351
351
  </div>
@@ -372,32 +372,32 @@
372
372
  </select>
373
373
  </div>
374
374
  </div>
375
- `);else{let v=this.registry.renderProperty(e,f,m,b);v&&h.push(v)}}h.length&&s.push(`
375
+ `);else{let v=this.registry.renderProperty(e,f,m,b);v&&h.push(v)}}h.length&&r.push(`
376
376
  <div class="inspector-property inspector-property-object">
377
377
  <div class="inspector-object-header">Props</div>
378
378
  <div class="inspector-object-body">
379
379
  ${h.join("")}
380
380
  </div>
381
381
  </div>
382
- `);continue}let g=this.registry.renderProperty(e,p,d,u);g&&s.push(g)}return s.length===0?"":`
382
+ `);continue}let g=this.registry.renderProperty(e,p,d,u);g&&r.push(g)}return r.length===0?"":`
383
383
  <div class="inspector-property inspector-property-object">
384
384
  <div class="inspector-object-header">${this.formatLabel(t)}</div>
385
385
  <div class="inspector-object-body">
386
- ${s.join("")}
386
+ ${r.join("")}
387
387
  </div>
388
388
  </div>
389
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Sn=class{render(e,t,n,a,s){let r=n==null?"":String(n),o=Array.from(new Set(s.map(c=>String(c)))),l=r&&!o.includes(r)?[r,...o]:o;return`
389
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Sn=class{render(e,t,n,a,r){let s=n==null?"":String(n),o=Array.from(new Set(r.map(c=>String(c)))),l=s&&!o.includes(s)?[s,...o]:o;return`
390
390
  <div class="inspector-property inspector-property-text">
391
391
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
392
392
  <div class="inspector-input-group">
393
393
  <select class="inspector-component-select inspector-input"
394
394
  data-property-path="${a}"
395
395
  data-object-id="${e}">
396
- ${l.map(c=>`<option value="${c}" ${c===r?"selected":""}>${c}</option>`).join("")}
396
+ ${l.map(c=>`<option value="${c}" ${c===s?"selected":""}>${c}</option>`).join("")}
397
397
  </select>
398
398
  </div>
399
399
  </div>
400
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Cn=class{constructor(){this.typeDetector=new mn,this.imageRenderer=new bn,this.colorRenderer=new yn,this.numberRenderer=new vn,this.textRenderer=new xn,this.booleanRenderer=new wn,this.arrayRenderer=new En,this.objectRenderer=new An(this),this.selectRenderer=new Sn}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 a of t.objects.keys())n.push(a);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,a=n==null?void 0:n.__editableConfig,s=a==null?void 0:a.schemas;if(!s)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=s instanceof Map?s.get(o):s==null?void 0:s[o];if(!c)return null;let p=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof p!="string"||!p.startsWith("enum:"))return null;let u=p.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:[],a=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(s=>String(s)).filter(s=>s.trim().length>0);return Array.from(new Set(a)).sort((s,r)=>s.localeCompare(r))}catch{return[]}}renderProperty(e,t,n,a){let s=t.toLowerCase(),r=s==="logic"||s==="logic_id"||s==="logicid",o=s==="id"&&a.toLowerCase().includes("logic");if((r||o)&&typeof n=="string"){let u=this.getLogicOptions();return this.selectRenderer.render(e,t,n,a,u)}let c={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"]}[t];if(c&&a.includes("logic.props"))return this.selectRenderer.render(e,t,n,a,c);if((t==="targetId"||t==="inputId")&&typeof n=="string"){let u=this.getObjectIds();return this.selectRenderer.render(e,t,n,a,["",...u])}let p=this.getEnumOptionsFromSchemas(a);if(p)return this.selectRenderer.render(e,t,n,a,p);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,a);case"color":return this.colorRenderer.render(e,t,n,a);case"number":return this.numberRenderer.render(e,t,n,a);case"boolean":return this.booleanRenderer.render(e,t,n,a);case"array":return this.arrayRenderer.render(e,t,n,a);case"object":return this.objectRenderer.render(e,t,n,a);case"select":return this.selectRenderer.render(e,t,n,a,[]);default:return this.textRenderer.render(e,t,n,a)}}getTypeDetector(){return this.typeDetector}};ee();var Je=class{async updateProperty(e,t,n,a={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,n);let s=window.getEditableObjectConfig;if(typeof s!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=s(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}Ae({objectId:e,path:t,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let d=window.__editableConfig,u=(p=(c=(l=d==null?void 0:d.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?p:r;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),a.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),a=e;for(let s of n)if(a&&typeof a=="object"&&s in a)a=a[s];else return;return a}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};var Ln=class{constructor(){this.updateManager=new Je}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let a=window.getEditableObjectConfig;if(typeof a!="function")return;let s=a(t);if(!s)return;let r=this.updateManager.getNestedProperty(s,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,s),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,a;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=((a=(n=t.transform)==null?void 0:n.scale)!=null?a: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 a=n();if(!a||!a.slots)return;let s=e.startsWith("json.")?e.replace("json.",""):e;if(!a.slots.some(p=>p.objectId===s||p.slotId===s)){let p=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",s),a.slots.push({slotId:s,displayName:s.replace(/_/g," "),objectId:s,category:p,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:p,assetType:"image"}),a.categories&&!a.categories.includes(p)&&a.categories.push(p),a.libraryAssets&&!a.libraryAssets[p]&&(a.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,n){var s;let a=window.__debugContext;if(a){if(a.activeTab!=="library"){a.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(a.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(s=o==null?void 0:o.identity)==null?void 0:s.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),a.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let a=window.__openAiEditor;if(typeof a=="function"){let s=t.split(".").pop()||t;a(s,`Edit ${s} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async a=>{var o;let s=(o=a.target.files)==null?void 0:o[0];if(!s)return;console.log("[QuickActionsBar] Preparing upload for:",s.name);let r=new FileReader;r.onload=async()=>{var c,p,d;let l=r.result;try{let u=window.getEditableObjectConfig,g=u==null?void 0:u(e),h=((c=g==null?void 0:g.identity)==null?void 0:c.category)||(t.split(".")[0]==="render"?"environment":"ui"),m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:h,filename:s.name,data:l,overwrite:!0})})).json();if(m.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",m.path),this.updateManager.updateProperty(e,t,m.path);let b=window.__debugContext;(d=(p=b==null?void 0:b.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,m.path);let y=window.addAssetToRegistry;typeof y=="function"&&y(h,s.name);let v=window.reRenderAssetLibrary;typeof v=="function"&&v(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(u){console.error("[QuickActionsBar] \u274C Upload error:",u),alert("Upload failed. Check console.")}},r.readAsDataURL(s)},n.click()}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 a=n[0],s=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(a):typeof r.schemas=="object"&&(o=r.schemas[a]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of s)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,n){let a=window.__openAiEditor;if(typeof a=="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),a(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")}};function Oo(i,e){let t;return function(...a){let s=()=>{clearTimeout(t),i(...a)};clearTimeout(t),t=setTimeout(s,e)}}var Tn=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Cn,this.updateManager=new Je,this.quickActions=new Ln,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
400
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Cn=class{constructor(){this.typeDetector=new mn,this.imageRenderer=new bn,this.colorRenderer=new yn,this.numberRenderer=new vn,this.textRenderer=new xn,this.booleanRenderer=new wn,this.arrayRenderer=new En,this.objectRenderer=new An(this),this.selectRenderer=new Sn}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 a of t.objects.keys())n.push(a);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,a=n==null?void 0:n.__editableConfig,r=a==null?void 0:a.schemas;if(!r)return null;let s=String(e||"").split(".").filter(Boolean);if(s.length<2)return null;let o=s[0],l=s.slice(1).join("."),c=r instanceof Map?r.get(o):r==null?void 0:r[o];if(!c)return null;let p=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof p!="string"||!p.startsWith("enum:"))return null;let u=p.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:[],a=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(r=>String(r)).filter(r=>r.trim().length>0);return Array.from(new Set(a)).sort((r,s)=>r.localeCompare(s))}catch{return[]}}renderProperty(e,t,n,a){let r=t.toLowerCase(),s=r==="logic"||r==="logic_id"||r==="logicid",o=r==="id"&&a.toLowerCase().includes("logic");if((s||o)&&typeof n=="string"){let u=this.getLogicOptions();return this.selectRenderer.render(e,t,n,a,u)}let c={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"]}[t];if(c&&a.includes("logic.props"))return this.selectRenderer.render(e,t,n,a,c);if((t==="targetId"||t==="inputId")&&typeof n=="string"){let u=this.getObjectIds();return this.selectRenderer.render(e,t,n,a,["",...u])}let p=this.getEnumOptionsFromSchemas(a);if(p)return this.selectRenderer.render(e,t,n,a,p);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,a);case"color":return this.colorRenderer.render(e,t,n,a);case"number":return this.numberRenderer.render(e,t,n,a);case"boolean":return this.booleanRenderer.render(e,t,n,a);case"array":return this.arrayRenderer.render(e,t,n,a);case"object":return this.objectRenderer.render(e,t,n,a);case"select":return this.selectRenderer.render(e,t,n,a,[]);default:return this.textRenderer.render(e,t,n,a)}}getTypeDetector(){return this.typeDetector}};ee();var Je=class{async updateProperty(e,t,n,a={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,n);let r=window.getEditableObjectConfig;if(typeof r!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=r(e);if(!s){console.error("[PropertyUpdateManager] Config not found for:",e);return}Ae({objectId:e,path:t,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let d=window.__editableConfig,u=(p=(c=(l=d==null?void 0:d.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?p:s;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),a.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),a=e;for(let r of n)if(a&&typeof a=="object"&&r in a)a=a[r];else return;return a}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};var Ln=class{constructor(){this.updateManager=new Je}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let a=window.getEditableObjectConfig;if(typeof a!="function")return;let r=a(t);if(!r)return;let s=this.updateManager.getNestedProperty(r,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,r),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,s);break;case"ai-edit":this.openAIEditor(t,n,s);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,a;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let s=((a=(n=t.transform)==null?void 0:n.scale)!=null?a:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let n=window.getEditableAssets;if(typeof n!="function")return;let a=n();if(!a||!a.slots)return;let r=e.startsWith("json.")?e.replace("json.",""):e;if(!a.slots.some(p=>p.objectId===r||p.slotId===r)){let p=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",r),a.slots.push({slotId:r,displayName:r.replace(/_/g," "),objectId:r,category:p,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:p,assetType:"image"}),a.categories&&!a.categories.includes(p)&&a.categories.push(p),a.libraryAssets&&!a.libraryAssets[p]&&(a.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,n){var r;let a=window.__debugContext;if(a){if(a.activeTab!=="library"){a.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(a.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(e),l=(r=o==null?void 0:o.identity)==null?void 0:r.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),a.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let a=window.__openAiEditor;if(typeof a=="function"){let r=t.split(".").pop()||t;a(r,`Edit ${r} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async a=>{var o;let r=(o=a.target.files)==null?void 0:o[0];if(!r)return;console.log("[QuickActionsBar] Preparing upload for:",r.name);let s=new FileReader;s.onload=async()=>{var c,p,d;let l=s.result;try{let u=window.getEditableObjectConfig,g=u==null?void 0:u(e),h=((c=g==null?void 0:g.identity)==null?void 0:c.category)||(t.split(".")[0]==="render"?"environment":"ui"),m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:h,filename:r.name,data:l,overwrite:!0})})).json();if(m.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",m.path),this.updateManager.updateProperty(e,t,m.path);let b=window.__debugContext;(d=(p=b==null?void 0:b.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,m.path);let y=window.addAssetToRegistry;typeof y=="function"&&y(h,r.name);let v=window.reRenderAssetLibrary;typeof v=="function"&&v(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(u){console.error("[QuickActionsBar] \u274C Upload error:",u),alert("Upload failed. Check console.")}},s.readAsDataURL(r)},n.click()}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 a=n[0],r=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(a):typeof s.schemas=="object"&&(o=s.schemas[a]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of r)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,n){let a=window.__openAiEditor;if(typeof a=="function"){let s=`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),a(e,s,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};function Oo(i,e){let t;return function(...a){let r=()=>{clearTimeout(t),i(...a)};clearTimeout(t),t=setTimeout(r,e)}}var Tn=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Cn,this.updateManager=new Je,this.quickActions=new Ln,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
401
401
  <div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector" style="right:16px; top:72px;">
402
402
  <div class="scene-panel-header" data-panel-handle>
403
403
  <div class="panel-title">
@@ -418,36 +418,36 @@
418
418
  </div>
419
419
  </div>
420
420
  </div>
421
- `}initialize(e,t){var n;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(n=this.root)==null?void 0:n.querySelector("[data-inspector-content]")}loadObject(e){this.selectedObjectId=e;let t=window.getEditableObjectConfig;if(typeof t!="function"){this.showError("Config system not ready");return}let n=t(e);if(!n){this.showError("Object not found");return}this.renderProperties(e,n)}renderProperties(e,t){if(!this.contentContainer)return;let n=[],a=t.identity||{},s=a.id||e,r=a.category||"unknown";n.push(`
421
+ `}initialize(e,t){var n;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(n=this.root)==null?void 0:n.querySelector("[data-inspector-content]")}loadObject(e){this.selectedObjectId=e;let t=window.getEditableObjectConfig;if(typeof t!="function"){this.showError("Config system not ready");return}let n=t(e);if(!n){this.showError("Object not found");return}this.renderProperties(e,n)}renderProperties(e,t){if(!this.contentContainer)return;let n=[],a=t.identity||{},r=a.id||e,s=a.category||"unknown";n.push(`
422
422
  <div class="inspector-header">
423
423
  <div class="inspector-header-info">
424
- <div class="inspector-object-name">${s}</div>
425
- <div class="inspector-object-category">${r}</div>
424
+ <div class="inspector-object-name">${r}</div>
425
+ <div class="inspector-object-category">${s}</div>
426
426
  </div>
427
427
  ${this.renderConversionButtons(e,t)}
428
428
  </div>
429
- `);let o=["ui","transform","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;n.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!o.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;n.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=n.join("")+this.renderFooter(t),this.attachEventListeners()}renderConversionButtons(e,t){var o,l,c,p;let n=!!t.ui,a=((o=t.ui)==null?void 0:o.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(n||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||a)return"";let r=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
429
+ `);let o=["ui","transform","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;n.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!o.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;n.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=n.join("")+this.renderFooter(t),this.attachEventListeners()}renderConversionButtons(e,t){var o,l,c,p;let n=!!t.ui,a=((o=t.ui)==null?void 0:o.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(n||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||a)return"";let s=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
430
430
  <div class="inspector-quick-actions">
431
431
  <button class="debug-btn debug-btn-sm success ai-simple-btn" type="button" data-convert-toggle>
432
432
  \u2728 Convert to PNG
433
433
  </button>
434
434
  <div class="inspector-convert-menu hidden" data-convert-menu>
435
435
  <button class="debug-btn debug-btn-sm" data-action="library" data-path="render.asset.path" data-object="${e}">\u{1F3A8} Library</button>
436
- <button class="debug-btn debug-btn-sm" data-action="ai-convert" data-path="${r}" data-object="${e}">\u2728 AI</button>
436
+ <button class="debug-btn debug-btn-sm" data-action="ai-convert" data-path="${s}" data-object="${e}">\u2728 AI</button>
437
437
  <button class="debug-btn debug-btn-sm" data-action="upload" data-path="render.asset.path" data-object="${e}">\u{1F4E4} Upload</button>
438
438
  </div>
439
439
  </div>
440
- `}renderFooter(e){let t=["motion","effects","ui","audio","physics","interaction","gameplay","visibility"],n=Object.keys(e),a=t.filter(s=>!n.includes(s));return a.length===0?"":`
440
+ `}renderFooter(e){let t=["motion","effects","ui","audio","physics","interaction","gameplay","visibility"],n=Object.keys(e),a=t.filter(r=>!n.includes(r));return a.length===0?"":`
441
441
  <div class="inspector-footer">
442
442
  <div class="inspector-add-component">
443
443
  <select class="inspector-component-select" data-inspector-component-select>
444
444
  <option value="" disabled selected>Add Component...</option>
445
- ${a.map(s=>`<option value="${s}">${this.formatLabel(s)}</option>`).join("")}
445
+ ${a.map(r=>`<option value="${r}">${this.formatLabel(r)}</option>`).join("")}
446
446
  </select>
447
447
  <button class="debug-btn debug-btn-sm primary" data-inspector-add-component-btn>Add</button>
448
448
  </div>
449
449
  </div>
450
- `}renderSection(e,t,n,a){let s=[],r=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let o in n){if(!this.showAdvanced&&r.includes(o))continue;let l=n[o],c=`${a}.${o}`,p=this.rendererRegistry.renderProperty(e,o,l,c);p&&s.push(p)}return s.length===0?"":`
450
+ `}renderSection(e,t,n,a){let r=[],s=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let o in n){if(!this.showAdvanced&&s.includes(o))continue;let l=n[o],c=`${a}.${o}`,p=this.rendererRegistry.renderProperty(e,o,l,c);p&&r.push(p)}return r.length===0?"":`
451
451
  <div class="inspector-section" data-section="${t}">
452
452
  <div class="inspector-section-header" data-section-toggle="${t}">
453
453
  <span class="inspector-section-arrow">\u25BC</span>
@@ -455,10 +455,10 @@
455
455
  <span class="inspector-section-title">${this.formatLabel(t)}</span>
456
456
  </div>
457
457
  <div class="inspector-section-body" data-section-body="${t}">
458
- ${s.join("")}
458
+ ${r.join("")}
459
459
  </div>
460
460
  </div>
461
- `}attachEventListeners(){var c,p,d,u;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Oo((g,h,f)=>{var m,b;this.updateManager.updateProperty(g,h,f),(b=(m=this.options)==null?void 0:m.onPropertyChange)==null||b.call(m,g,h,f)},300);e.forEach(g=>{let h=m=>{var x,E;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let w=b.value;if(b.type==="checkbox")w=b.checked;else if(b.type==="number"&&(w=parseFloat(b.value),isNaN(w)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?t(v,y,w):(this.updateManager.updateProperty(v,y,w),(E=(x=this.options)==null?void 0:x.onPropertyChange)==null||E.call(x,v,y,w))}},f=g.dataset.propertyPath;f==="logic.id"||f!=null&&f.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",f),g.addEventListener("change",async m=>{var O;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId,x=b.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!y||!v)return;await this.updateManager.updateProperty(v,y,x),console.log("[Inspector v1.0.0] Logic ID updated");let E=window,w=(O=E==null?void 0:E.__HANDLER_LOGIC_META)==null?void 0:O[x],T=this.getDefaultPropsForLogic(x,w);console.log("[Inspector v1.0.0] New logic default props:",T);let S=y.replace(".id",".props");await this.updateManager.updateProperty(v,S,T),console.log("[Inspector v1.0.0] Logic props updated to:",T),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(g.addEventListener("change",h),(g.tagName==="INPUT"||g.tagName==="TEXTAREA")&&g.addEventListener("input",h))}),this.contentContainer.querySelectorAll("[data-action]").forEach(g=>{g.addEventListener("click",h=>{let f=h.target,m=f.dataset.action,b=f.dataset.path,y=f.dataset.object;m&&b&&y&&this.quickActions.handleAction(m,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(g=>{g.addEventListener("click",h=>{var b,y;let f=h.target,m=f.dataset.sectionToggle||((b=f.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(m){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${m}"]`);v==null||v.classList.toggle("collapsed")}})});let s=(c=this.root)==null?void 0:c.querySelector("[data-inspector-advanced]");s==null||s.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let r=(p=this.root)==null?void 0:p.querySelector("[data-convert-toggle]");r==null||r.addEventListener("click",()=>{var h;let g=(h=this.root)==null?void 0:h.querySelector("[data-convert-menu]");g==null||g.classList.toggle("hidden")});let o=(d=this.contentContainer)==null?void 0:d.querySelector("[data-inspector-add-component-btn]"),l=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let g=l.value;g&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,g)})}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,a=n==null?void 0:n(e);if(!a){console.error("[InspectorPanel] Failed to get config for:",e);return}let s=window.__editableConfig,r=s==null?void 0:s.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};a[t]={...l},await this.updateManager.updateProperty(e,t,a[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var s,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(s=n.render)==null?void 0:s.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 a=Object.keys(t);return a.length===0||a.length===1&&a[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
461
+ `}attachEventListeners(){var c,p,d,u;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Oo((g,h,f)=>{var m,b;this.updateManager.updateProperty(g,h,f),(b=(m=this.options)==null?void 0:m.onPropertyChange)==null||b.call(m,g,h,f)},300);e.forEach(g=>{let h=m=>{var x,E;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let w=b.value;if(b.type==="checkbox")w=b.checked;else if(b.type==="number"&&(w=parseFloat(b.value),isNaN(w)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?t(v,y,w):(this.updateManager.updateProperty(v,y,w),(E=(x=this.options)==null?void 0:x.onPropertyChange)==null||E.call(x,v,y,w))}},f=g.dataset.propertyPath;f==="logic.id"||f!=null&&f.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",f),g.addEventListener("change",async m=>{var O;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId,x=b.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!y||!v)return;await this.updateManager.updateProperty(v,y,x),console.log("[Inspector v1.0.0] Logic ID updated");let E=window,w=(O=E==null?void 0:E.__HANDLER_LOGIC_META)==null?void 0:O[x],T=this.getDefaultPropsForLogic(x,w);console.log("[Inspector v1.0.0] New logic default props:",T);let S=y.replace(".id",".props");await this.updateManager.updateProperty(v,S,T),console.log("[Inspector v1.0.0] Logic props updated to:",T),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(g.addEventListener("change",h),(g.tagName==="INPUT"||g.tagName==="TEXTAREA")&&g.addEventListener("input",h))}),this.contentContainer.querySelectorAll("[data-action]").forEach(g=>{g.addEventListener("click",h=>{let f=h.target,m=f.dataset.action,b=f.dataset.path,y=f.dataset.object;m&&b&&y&&this.quickActions.handleAction(m,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(g=>{g.addEventListener("click",h=>{var b,y;let f=h.target,m=f.dataset.sectionToggle||((b=f.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(m){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${m}"]`);v==null||v.classList.toggle("collapsed")}})});let r=(c=this.root)==null?void 0:c.querySelector("[data-inspector-advanced]");r==null||r.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let s=(p=this.root)==null?void 0:p.querySelector("[data-convert-toggle]");s==null||s.addEventListener("click",()=>{var h;let g=(h=this.root)==null?void 0:h.querySelector("[data-convert-menu]");g==null||g.classList.toggle("hidden")});let o=(d=this.contentContainer)==null?void 0:d.querySelector("[data-inspector-add-component-btn]"),l=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let g=l.value;g&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,g)})}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,a=n==null?void 0:n(e);if(!a){console.error("[InspectorPanel] Failed to get config for:",e);return}let r=window.__editableConfig,s=r==null?void 0:r.schemas,o=null;s instanceof Map?o=s.get(t):s&&typeof s=="object"&&(o=s[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};a[t]={...l},await this.updateManager.updateProperty(e,t,a[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var r,s;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((s=(r=n.render)==null?void 0:r.asset)==null?void 0:s.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let a=Object.keys(t);return a.length===0||a.length===1&&a[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
462
462
  <div class="inspector-empty">
463
463
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
464
464
  <span class="inspector-empty-text">${e}</span>
@@ -468,11 +468,11 @@
468
468
  <span class="inspector-empty-icon">\u{1F3AF}</span>
469
469
  <span class="inspector-empty-text">Select an object to inspect</span>
470
470
  </div>
471
- `)}};var Ds=qe(require("jszip"),1);function ki(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function Es(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}async function As(i){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=i})}async function _n(i){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",i);let n=await fetch(i);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,i),null;let a=await n.blob();console.log("[ImageUtils] Blob received, size:",a.size,"type:",a.type);let s=await ki(a),r=await As(s),o=Es(s);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:s,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 Te(i){var e,t;try{let n=await ki(i),a=await As(n),s=Es(n);return{base64:s.base64,mimeType:s.mimeType,dataUrl:n,width:(e=a==null?void 0:a.width)!=null?e:0,height:(t=a==null?void 0:a.height)!=null?t:0}}catch{return null}}function Ss(i){return ki(i).then(e=>e).catch(()=>null)}function Oi(i,e){var t;try{let[n,a]=i.split(","),s=n.match(/data:(.*?);base64/),r=(t=s==null?void 0:s[1])!=null?t:"image/png",o=atob(a),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 Ze(i,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((d,u)=>{let g=new Image;g.onload=()=>d(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=i}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let a=n.getContext("2d");if(!a)return console.error("[ImageUtils] Failed to get canvas context"),i;a.drawImage(t,0,0);let s=a.getImageData(0,0,n.width,n.height),r=s.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(d=>({r:r[d.offset],g:r[d.offset+1],b:r[d.offset+2]})),c=0;for(let d=0;d<r.length;d+=4){let u=r[d],g=r[d+1],h=r[d+2],f=!1;for(let m of l)if(Math.sqrt(Math.pow(u-m.r,2)+Math.pow(g-m.g,2)+Math.pow(h-m.b,2))<e){f=!0;break}f&&(r[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),a.putImageData(s,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),i}}function Cs(i,e){if(!i||!e)return"1:1";let t=i/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function be(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function W(i){return typeof i=="string"?i:void 0}function Ls(i){return i.toLowerCase().endsWith(".png")?i.slice(0,-4):i}function Io(i){var n,a,s;let e=(n=W(i.id))!=null?n:W(i.name);if(e)return e;let t=(a=W(i.file))!=null?a:W(i.asset);return t?Ls((s=t.split("/").pop())!=null?s:t):void 0}function Ro(i,e,t){var n,a,s;if(typeof e=="string")return{id:i,file:e,role:t};if(be(e)){let r=(n=W(e.file))!=null?n:W(e.asset);return r?{id:(a=W(e.id))!=null?a:i,file:r,role:(s=W(e.role))!=null?s:t,dataUrl:W(e.dataUrl),layout:e.layout}:null}return null}function Ii(i,e){var t,n,a;if(!i)return[];if(Array.isArray(i)){let s=[];for(let r of i){if(typeof r=="string"){let o=Ls((t=r.split("/").pop())!=null?t:r);s.push({id:o,file:r,role:e});continue}if(be(r)){let o=Io(r),l=(n=W(r.file))!=null?n:W(r.asset);if(!o||!l)continue;s.push({id:o,file:l,role:(a=W(r.role))!=null?a:e,dataUrl:W(r.dataUrl),layout:r.layout})}}return s}if(be(i)){let s=[];for(let[r,o]of Object.entries(i)){let l=Ro(r,o,e);l&&s.push(l)}return s}return[]}function jo(i){var e,t;return(t=(e=W(i.brand_name))!=null?e:W(i.brandName))!=null?t:W(i.name)}function Do(i){if(be(i.brand_dna)&&be(i.brand_dna.colors))return i.brand_dna;if(be(i.colors)){let e={colors:i.colors};return typeof i.style=="string"&&(e.style=i.style),be(i.fonts)&&(e.fonts=i.fonts),e}}function $o(i){var t;let e=new Map;for(let n of i){let a=e.get(n.id);if(!a){e.set(n.id,n);continue}e.set(n.id,{...a,...n,file:n.file||a.file,role:n.role||a.role,dataUrl:n.dataUrl||a.dataUrl,layout:(t=n.layout)!=null?t:a.layout})}return Array.from(e.values())}function Ri(i,e={}){var r,o,l;let t=i.filter(be),n=(o=(r=t.map(jo).find(Boolean))!=null?r:e.defaultBrandName)!=null?o:"Imported Brand",a=(l=t.map(Do).find(Boolean))!=null?l:{colors:{}},s=[];for(let c of t)"layers"in c&&s.push(...Ii(c.layers,"visual element")),"assets"in c&&s.push(...Ii(c.assets,"visual element")),be(c.endgame)&&"assets"in c.endgame&&s.push(...Ii(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:a,assets:$o(s)}}var Ts=require("@google/genai");async function Pn(i,e,t=[],n={}){var a,s,r,o,l,c,p;try{if(!(i!=null&&i.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let b=0;b<t.length;b++){let y=t[b];if(!y.base64||!y.mimeType)throw new Error(`Image ${b+1} is missing required data`);if(y.base64.length<1e3&&console.warn(`Image ${b+1} data appears very small, may be corrupted`),!y.mimeType.startsWith("image/"))throw new Error(`Image ${b+1} has invalid MIME type: ${y.mimeType}`)}let d=new Ts.GoogleGenAI({apiKey:i}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((b,y)=>{g.push({inlineData:{data:b.base64,mimeType:b.mimeType}}),console.log(`[Gemini] Added image ${y+1}: ${b.mimeType}, size: ${Math.round(b.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let h=await d.models.generateContent({model:u,contents:g}),f="",m=(r=(s=(a=h.candidates)==null?void 0:a[0])==null?void 0:s.content)==null?void 0:r.parts;if(m)for(let b of m)b.text&&(f+=b.text);if(!f.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${f.length}`),f}catch(d){throw console.error("[Gemini] API error:",d),(o=d.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=d.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=d.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(p=d.message)!=null&&p.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):d}}var _s=require("@google/genai");async function Qe(i,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let a=new _s.GoogleGenAI({apiKey:i}),s=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),s.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 a.models.generateContent({model:"gemini-2.5-flash-image",contents:s});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(a){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(a,Object.getOwnPropertyNames(a),2)),a}}function Ps(i){let e=i.brandAssets.map(s=>{let r=`- ${s.id}: ${s.role}`;return s.layout&&(r+=` [pos: ${s.layout.x.toFixed(0)},${s.layout.y.toFixed(0)}, size: ${s.layout.w.toFixed(0)}x${s.layout.h.toFixed(0)}, z: ${s.layout.z}, opacity: ${s.layout.opacity}]`),r}).join(`
472
- `)||"None",t=i.brandDna?`Colors: ${JSON.stringify(i.brandDna.colors)}, Style: ${i.brandDna.style||"not specified"}`:"Not provided",n=i.gameObjects.map(s=>typeof s=="string"?`- id: ${s}`:`- id: ${s.id}${s.category?`, category: ${s.category}`:""}${s.type?`, type: ${s.type}`:""}`).join(`
473
- `),a="";if(i.brandConfig){let s=i.brandConfig,r=[];s.splash&&r.push(`SPLASH: title="${s.splash.title||""}", subtitle="${s.splash.subtitle||""}", button="${s.splash.button_label||""}"`),s.endgame&&r.push(`ENDGAME: title="${s.endgame.title||""}", subtitle="${s.endgame.subtitle||""}", cta="${s.endgame.cta_label||""}"`),s.tutorial&&r.push(`TUTORIAL: text="${s.tutorial.label_text||""}", helper="${s.tutorial.helper_text||""}"`),r.length>0&&(a=`
471
+ `)}};var Dr=qe(require("jszip"),1);function ki(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function Er(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}async function Ar(i){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=i})}async function _n(i){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",i);let n=await fetch(i);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,i),null;let a=await n.blob();console.log("[ImageUtils] Blob received, size:",a.size,"type:",a.type);let r=await ki(a),s=await Ar(r),o=Er(r);return console.log("[ImageUtils] Success resolution:",s==null?void 0:s.width,"x",s==null?void 0:s.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:r,width:(e=s==null?void 0:s.width)!=null?e:0,height:(t=s==null?void 0:s.height)!=null?t:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Te(i){var e,t;try{let n=await ki(i),a=await Ar(n),r=Er(n);return{base64:r.base64,mimeType:r.mimeType,dataUrl:n,width:(e=a==null?void 0:a.width)!=null?e:0,height:(t=a==null?void 0:a.height)!=null?t:0}}catch{return null}}function Sr(i){return ki(i).then(e=>e).catch(()=>null)}function Oi(i,e){var t;try{let[n,a]=i.split(","),r=n.match(/data:(.*?);base64/),s=(t=r==null?void 0:r[1])!=null?t:"image/png",o=atob(a),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],e,{type:s})}catch{return null}}async function Ze(i,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((d,u)=>{let g=new Image;g.onload=()=>d(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=i}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let a=n.getContext("2d");if(!a)return console.error("[ImageUtils] Failed to get canvas context"),i;a.drawImage(t,0,0);let r=a.getImageData(0,0,n.width,n.height),s=r.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(d=>({r:s[d.offset],g:s[d.offset+1],b:s[d.offset+2]})),c=0;for(let d=0;d<s.length;d+=4){let u=s[d],g=s[d+1],h=s[d+2],f=!1;for(let m of l)if(Math.sqrt(Math.pow(u-m.r,2)+Math.pow(g-m.g,2)+Math.pow(h-m.b,2))<e){f=!0;break}f&&(s[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),a.putImageData(r,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),i}}function Cr(i,e){if(!i||!e)return"1:1";let t=i/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function be(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function W(i){return typeof i=="string"?i:void 0}function Lr(i){return i.toLowerCase().endsWith(".png")?i.slice(0,-4):i}function Io(i){var n,a,r;let e=(n=W(i.id))!=null?n:W(i.name);if(e)return e;let t=(a=W(i.file))!=null?a:W(i.asset);return t?Lr((r=t.split("/").pop())!=null?r:t):void 0}function Ro(i,e,t){var n,a,r;if(typeof e=="string")return{id:i,file:e,role:t};if(be(e)){let s=(n=W(e.file))!=null?n:W(e.asset);return s?{id:(a=W(e.id))!=null?a:i,file:s,role:(r=W(e.role))!=null?r:t,dataUrl:W(e.dataUrl),layout:e.layout}:null}return null}function Ii(i,e){var t,n,a;if(!i)return[];if(Array.isArray(i)){let r=[];for(let s of i){if(typeof s=="string"){let o=Lr((t=s.split("/").pop())!=null?t:s);r.push({id:o,file:s,role:e});continue}if(be(s)){let o=Io(s),l=(n=W(s.file))!=null?n:W(s.asset);if(!o||!l)continue;r.push({id:o,file:l,role:(a=W(s.role))!=null?a:e,dataUrl:W(s.dataUrl),layout:s.layout})}}return r}if(be(i)){let r=[];for(let[s,o]of Object.entries(i)){let l=Ro(s,o,e);l&&r.push(l)}return r}return[]}function jo(i){var e,t;return(t=(e=W(i.brand_name))!=null?e:W(i.brandName))!=null?t:W(i.name)}function Do(i){if(be(i.brand_dna)&&be(i.brand_dna.colors))return i.brand_dna;if(be(i.colors)){let e={colors:i.colors};return typeof i.style=="string"&&(e.style=i.style),be(i.fonts)&&(e.fonts=i.fonts),e}}function $o(i){var t;let e=new Map;for(let n of i){let a=e.get(n.id);if(!a){e.set(n.id,n);continue}e.set(n.id,{...a,...n,file:n.file||a.file,role:n.role||a.role,dataUrl:n.dataUrl||a.dataUrl,layout:(t=n.layout)!=null?t:a.layout})}return Array.from(e.values())}function Ri(i,e={}){var s,o,l;let t=i.filter(be),n=(o=(s=t.map(jo).find(Boolean))!=null?s:e.defaultBrandName)!=null?o:"Imported Brand",a=(l=t.map(Do).find(Boolean))!=null?l:{colors:{}},r=[];for(let c of t)"layers"in c&&r.push(...Ii(c.layers,"visual element")),"assets"in c&&r.push(...Ii(c.assets,"visual element")),be(c.endgame)&&"assets"in c.endgame&&r.push(...Ii(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:a,assets:$o(r)}}var Tr=require("@google/genai");async function Pn(i,e,t=[],n={}){var a,r,s,o,l,c,p;try{if(!(i!=null&&i.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let b=0;b<t.length;b++){let y=t[b];if(!y.base64||!y.mimeType)throw new Error(`Image ${b+1} is missing required data`);if(y.base64.length<1e3&&console.warn(`Image ${b+1} data appears very small, may be corrupted`),!y.mimeType.startsWith("image/"))throw new Error(`Image ${b+1} has invalid MIME type: ${y.mimeType}`)}let d=new Tr.GoogleGenAI({apiKey:i}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((b,y)=>{g.push({inlineData:{data:b.base64,mimeType:b.mimeType}}),console.log(`[Gemini] Added image ${y+1}: ${b.mimeType}, size: ${Math.round(b.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let h=await d.models.generateContent({model:u,contents:g}),f="",m=(s=(r=(a=h.candidates)==null?void 0:a[0])==null?void 0:r.content)==null?void 0:s.parts;if(m)for(let b of m)b.text&&(f+=b.text);if(!f.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${f.length}`),f}catch(d){throw console.error("[Gemini] API error:",d),(o=d.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=d.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=d.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(p=d.message)!=null&&p.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):d}}var _r=require("@google/genai");async function Qe(i,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let a=new _r.GoogleGenAI({apiKey:i}),r=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),r.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let s=await a.models.generateContent({model:"gemini-2.5-flash-image",contents:r});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!s.candidates||!s.candidates[0]||!s.candidates[0].content||!s.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of s.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(a){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(a,Object.getOwnPropertyNames(a),2)),a}}function Pr(i){let e=i.brandAssets.map(r=>{let s=`- ${r.id}: ${r.role}`;return r.layout&&(s+=` [pos: ${r.layout.x.toFixed(0)},${r.layout.y.toFixed(0)}, size: ${r.layout.w.toFixed(0)}x${r.layout.h.toFixed(0)}, z: ${r.layout.z}, opacity: ${r.layout.opacity}]`),s}).join(`
472
+ `)||"None",t=i.brandDna?`Colors: ${JSON.stringify(i.brandDna.colors)}, Style: ${i.brandDna.style||"not specified"}`:"Not provided",n=i.gameObjects.map(r=>typeof r=="string"?`- id: ${r}`:`- id: ${r.id}${r.category?`, category: ${r.category}`:""}${r.type?`, type: ${r.type}`:""}`).join(`
473
+ `),a="";if(i.brandConfig){let r=i.brandConfig,s=[];r.splash&&s.push(`SPLASH: title="${r.splash.title||""}", subtitle="${r.splash.subtitle||""}", button="${r.splash.button_label||""}"`),r.endgame&&s.push(`ENDGAME: title="${r.endgame.title||""}", subtitle="${r.endgame.subtitle||""}", cta="${r.endgame.cta_label||""}"`),r.tutorial&&s.push(`TUTORIAL: text="${r.tutorial.label_text||""}", helper="${r.tutorial.helper_text||""}"`),s.length>0&&(a=`
474
474
  BRAND CONTENT:
475
- ${r.join(`
475
+ ${s.join(`
476
476
  `)}
477
477
  `)}return`
478
478
  You are analyzing a brand's visual design for use in a playable ad game.
@@ -532,7 +532,7 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
532
532
  }
533
533
  ]
534
534
  }
535
- `.trim()}function Ms(i){var a,s;let e=(a=i.brandDna)!=null&&a.colors?`Primary: ${i.brandDna.colors.primary}, Secondary: ${i.brandDna.colors.secondary||"N/A"}, Accent: ${i.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((s=i.brandDna)==null?void 0:s.style)||"modern gaming style",n=i.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
535
+ `.trim()}function Mr(i){var a,r;let e=(a=i.brandDna)!=null&&a.colors?`Primary: ${i.brandDna.colors.primary}, Secondary: ${i.brandDna.colors.secondary||"N/A"}, Accent: ${i.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((r=i.brandDna)==null?void 0:r.style)||"modern gaming style",n=i.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
536
536
  TASK: ${i.prompt}
537
537
 
538
538
  BRAND STYLE:
@@ -553,7 +553,7 @@ OUTPUT CONSTRAINTS (MUST FOLLOW):
553
553
 
554
554
  OUTPUT:
555
555
  Generate the requested asset matching the brand style.${i.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
556
- `.trim()}function ks(i){return i.map(e=>{if(typeof e=="string"){let t=e,n,a;return t.includes("background")?(n="background",a="background"):t.includes("button")||t.includes("cta")?(n="ui",a="button"):t.includes("logo")?(n="ui",a="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",a="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",a="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",a="image"):(n="environment",a="interactive"),{id:t,category:n,type:a}}return e})}function Os(i,e){return!(i.includes("background")&&(i.includes("_1")||i.includes("splash")||i.includes("endgame")||i.includes("main"))||e==="text"||e==="effects"&&i.includes("particle"))}async function Is(i){var r,o;let e=ks(i.gameObjects),t={gamePrompt:i.gamePrompt,gameObjects:e,brandAssets:i.manifest.assets,brandDna:i.manifest.brand_dna,brandName:i.manifest.brand_name},n=Ps(t),a=[];if(i.flatDesignDataUrl)try{let l=Rs(i.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(a.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",a.length,"images...");let s;try{s=await Pn(i.apiKey,n,a,{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 zo(s,i.gameObjects)}function zo(i,e){try{let t=i,n=i.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let s=i.match(/\{[\s\S]*\}/);s&&(t=s[0])}let a=JSON.parse(t);return a.mappings&&Array.isArray(a.mappings)?{mappingResult:a,rawResponse:i,parsed:!0}:{mappingResult:{mappings:e.map(s=>({game_object:s,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:i,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:i,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function ji(i,e,t={}){var a;let n=e.mappings.filter(s=>s.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let s=0;s<n.length;s++){let r=n[s];(a=t.onProgress)==null||a.call(t,s+1,n.length,r.game_object);try{let o=await No(i,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 No(i,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&i.manifest){let o=i.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=i.assetFiles.get(o.file);if(l){let c=await Te(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(i.flatDesignDataUrl){let o=Rs(i.flatDesignDataUrl);o&&t.push(o)}let n=Os(e.game_object),a={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:i.manifest.brand_dna,needsTransparency:n},s=Ms(a);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await Qe(i.apiKey,s,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await Ze(r)||r}function Rs(i){let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function js(i,e){let t=i.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([a,s])=>({id:a,file:String(s),role:"visual element"})):n=[],i.assets=n;for(let a of n){let s=e.get(a.file);if(s){let r=await Te(s);r&&(a.dataUrl=r.dataUrl)}}}var Mn=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.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
556
+ `.trim()}function kr(i){return i.map(e=>{if(typeof e=="string"){let t=e,n,a;return t.includes("background")?(n="background",a="background"):t.includes("button")||t.includes("cta")?(n="ui",a="button"):t.includes("logo")?(n="ui",a="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",a="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",a="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",a="image"):(n="environment",a="interactive"),{id:t,category:n,type:a}}return e})}function Or(i,e){return!(i.includes("background")&&(i.includes("_1")||i.includes("splash")||i.includes("endgame")||i.includes("main"))||e==="text"||e==="effects"&&i.includes("particle"))}async function Ir(i){var s,o;let e=kr(i.gameObjects),t={gamePrompt:i.gamePrompt,gameObjects:e,brandAssets:i.manifest.assets,brandDna:i.manifest.brand_dna,brandName:i.manifest.brand_name},n=Pr(t),a=[];if(i.flatDesignDataUrl)try{let l=Rr(i.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(a.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",a.length,"images...");let r;try{r=await Pn(i.apiKey,n,a,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(s=l.message)!=null&&s.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return zo(r,i.gameObjects)}function zo(i,e){try{let t=i,n=i.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let r=i.match(/\{[\s\S]*\}/);r&&(t=r[0])}let a=JSON.parse(t);return a.mappings&&Array.isArray(a.mappings)?{mappingResult:a,rawResponse:i,parsed:!0}:{mappingResult:{mappings:e.map(r=>({game_object:r,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:i,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:i,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function ji(i,e,t={}){var a;let n=e.mappings.filter(r=>r.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let r=0;r<n.length;r++){let s=n[r];(a=t.onProgress)==null||a.call(t,r+1,n.length,s.game_object);try{let o=await No(i,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function No(i,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&i.manifest){let o=i.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=i.assetFiles.get(o.file);if(l){let c=await Te(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(i.flatDesignDataUrl){let o=Rr(i.flatDesignDataUrl);o&&t.push(o)}let n=Or(e.game_object),a={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:i.manifest.brand_dna,needsTransparency:n},r=Mr(a);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let s=await Qe(i.apiKey,r,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await Ze(s)||s}function Rr(i){let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function jr(i,e){let t=i.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([a,r])=>({id:a,file:String(r),role:"visual element"})):n=[],i.assets=n;for(let a of n){let r=e.get(a.file);if(r){let s=await Te(r);s&&(a.dataUrl=s.dataUrl)}}}var Mn=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.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
557
557
  <div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
558
558
  <div class="scene-panel-header" data-panel-handle>
559
559
  <div class="panel-title">
@@ -669,15 +669,15 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
669
669
  </div>
670
670
  <div class="panel-resize-handle" data-panel-resize></div>
671
671
  </div>
672
- `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,a,s,r,o,l,c,p,d,u,g,h;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let f="/dashboard";window.location.pathname!==f&&(window.location.href=f)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(f=>{f.addEventListener("click",()=>{let m=f.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",f=>{let m=f.target.value;this.switchUploadMethod(m)}),(a=this.root.querySelector("[data-vision-upload-manifest]"))==null||a.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(s=this.root.querySelector("[data-vision-upload-zip]"))==null||s.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-zip-input]"))==null||m.click()}),(r=this.root.querySelector("[data-vision-zip-input]"))==null||r.addEventListener("change",f=>{this.handleZipUpload(f)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",f=>{this.handleManifestUpload(f)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",f=>{this.handleAssetsUpload(f)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-flat-input]"))==null||m.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",f=>{this.handleFlatDesignUpload(f)}),(u=this.root.querySelector("[data-vision-analyze]"))==null||u.addEventListener("click",()=>{this.runAnalysis()}),(g=this.root.querySelector("[data-vision-generate-all]"))==null||g.addEventListener("click",()=>{this.generateAllMissing()}),(h=this.root.querySelector("[data-vision-apply-all]"))==null||h.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",f=>{let m=f.target;if(!m)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.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",f=>{let m=f.target;if(!m||!this.mappingResult)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(m.matches("[data-mapping-action]")&&(v.action=String(m.value||"KEEP"),v.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(m.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",f=>{let m=f.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(v.generation_prompt=String(m.value||""),v.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(a=>a.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(a=>a.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 a;let n=(a=e.target.files)==null?void 0:a[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(s){console.error("[BrandVision] ZIP processing failed:",s),this.setStatus("zip",`Error: ${s instanceof Error?s.message:"Unknown error"}`)}}}async processZipFile(e){var r,o;let t=await Ds.loadAsync(e),n=[],a=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?n.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:l,file:c})});for(let l of n)try{let c=await((r=t.file(l.name))==null?void 0:r.async("text"));c&&(l.content=JSON.parse(c))}catch(c){console.warn(`Failed to parse ${l.name}:`,c)}let s=new Map;for(let l of a)try{let c=await l.file.async("uint8array"),p=new Blob([c],{type:"image/png"}),d=l.name.split("/").pop()||l.name;console.log(`Processing ${d}, uint8array length: ${c.length}, blob size: ${p.size}`);let u;try{u=await this.blobToDataUrl(p)}catch(m){console.warn(`FileReader failed for ${d}, using fallback:`,m),u=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(c)))}`}if(console.log(`Data URL length: ${u.length}, starts with: ${u.substring(0,50)}...`),!u.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${d}:`,u.substring(0,100));continue}let g=this.inferAssetCategory(d.replace(".png",""));console.log(`Saving ${d} to category: ${g}`);let f=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:g,filename:d,data:u,overwrite:!0})})).json();if(console.log(`Save result for ${d}:`,f),f.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${f.path}`);let m=new File([p],d,{type:"image/png"});s.set(d,m)}else console.warn(`\u274C Failed to save ${d}:`,f.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),n.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=s;try{this.normalizedManifest=Ri(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let l=[];for(let[p,d]of s){let u=await this.fileToDataUrl(d);l.push({id:p.replace(".png",""),filename:p,dataUrl:u,category:this.inferAssetCategory(p.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=l);let c=l.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${c} PNGs
673
- \u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(l),this.refreshLibrary()}catch(l){console.error("[BrandVision] Failed to normalize ZIP manifest:",l),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=n,a.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>{let s=a.result;console.log("FileReader result type:",typeof s,"length:",s.length),console.log("Data URL prefix:",s.substring(0,30)),t(s)},a.onerror=s=>{console.error("FileReader error:",s),n(s)},a.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 a={};for(let s of e){let r=s.category||"misc";a[r]||(a[r]=[]),n.libraryAssets[r]||(n.libraryAssets[r]=[]),n.libraryAssets[r].some(l=>l.filename===s.filename)||(n.libraryAssets[r].unshift({filename:s.filename,displayName:s.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${s.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 s;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let a="";for(let r of Array.from(n))try{let o=await r.text(),l=JSON.parse(o);this.uploadedJsons.set(r.name,l),l.layers?a+=`\u2705 Layers: ${r.name}
674
- `:l.brand_dna||l.colors?a+=`\u2705 Brand: ${r.name}
675
- `:a+=`\u2705 Loaded: ${r.name}
676
- `}catch{a+=`\u274C Error in ${r.name}
677
- `}try{this.normalizedManifest=Ri(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let r=Array.isArray((s=this.normalizedManifest)==null?void 0:s.assets)?this.normalizedManifest.assets.length:0;a+=`
678
- \u{1F4E6} Normalized manifest: ${r} assets`,a+=`
679
- \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:r,brandName:this.normalizedManifest.brand_name})}catch(r){console.error("[BrandVision] Failed to normalize manifest:",r),this.normalizedManifest=null,a+=`
680
- \u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",a.trim())}async handleAssetsUpload(e){let n=e.target.files;if(!(!n||n.length===0)){for(let a of Array.from(n))this.assetFiles.set(a.name,a);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var s,r;let n=(s=e.target.files)==null?void 0:s[0];if(!n)return;let a=await Te(n);if(a){this.flatDesignDataUrl=a.dataUrl,this.setStatus("flat",n.name);let o=(r=this.root)==null?void 0:r.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${a.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,a,s,r,o,l,c;if(this.isAnalyzing)return;let e=(s=(a=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.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 js(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await Is(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(r=d.parseError)!=null?r:null,this.renderMappings(),d.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: ${d.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(p){console.error("[BrandVision] Analysis failed:",p),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,a;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(a=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:a.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let s={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ji(s,this.mappingResult,{onProgress:(r,o,l)=>{this.setStatus("apply",`Generating ${r}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(s){console.error("[BrandVision] Generation failed:",s),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(),a=!!this.analysisRawResponse&&this.analysisParsedOk===!1,s=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),r=a?`
672
+ `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,a,r,s,o,l,c,p,d,u,g,h;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let f="/dashboard";window.location.pathname!==f&&(window.location.href=f)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(f=>{f.addEventListener("click",()=>{let m=f.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",f=>{let m=f.target.value;this.switchUploadMethod(m)}),(a=this.root.querySelector("[data-vision-upload-manifest]"))==null||a.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(r=this.root.querySelector("[data-vision-upload-zip]"))==null||r.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-zip-input]"))==null||m.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",f=>{this.handleZipUpload(f)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",f=>{this.handleManifestUpload(f)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",f=>{this.handleAssetsUpload(f)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-flat-input]"))==null||m.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",f=>{this.handleFlatDesignUpload(f)}),(u=this.root.querySelector("[data-vision-analyze]"))==null||u.addEventListener("click",()=>{this.runAnalysis()}),(g=this.root.querySelector("[data-vision-generate-all]"))==null||g.addEventListener("click",()=>{this.generateAllMissing()}),(h=this.root.querySelector("[data-vision-apply-all]"))==null||h.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",f=>{let m=f.target;if(!m)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.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",f=>{let m=f.target;if(!m||!this.mappingResult)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(m.matches("[data-mapping-action]")&&(v.action=String(m.value||"KEEP"),v.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(m.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",f=>{let m=f.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(v.generation_prompt=String(m.value||""),v.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(a=>a.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(a=>a.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 a;let n=(a=e.target.files)==null?void 0:a[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(r){console.error("[BrandVision] ZIP processing failed:",r),this.setStatus("zip",`Error: ${r instanceof Error?r.message:"Unknown error"}`)}}}async processZipFile(e){var s,o;let t=await Dr.loadAsync(e),n=[],a=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?n.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:l,file:c})});for(let l of n)try{let c=await((s=t.file(l.name))==null?void 0:s.async("text"));c&&(l.content=JSON.parse(c))}catch(c){console.warn(`Failed to parse ${l.name}:`,c)}let r=new Map;for(let l of a)try{let c=await l.file.async("uint8array"),p=new Blob([c],{type:"image/png"}),d=l.name.split("/").pop()||l.name;console.log(`Processing ${d}, uint8array length: ${c.length}, blob size: ${p.size}`);let u;try{u=await this.blobToDataUrl(p)}catch(m){console.warn(`FileReader failed for ${d}, using fallback:`,m),u=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(c)))}`}if(console.log(`Data URL length: ${u.length}, starts with: ${u.substring(0,50)}...`),!u.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${d}:`,u.substring(0,100));continue}let g=this.inferAssetCategory(d.replace(".png",""));console.log(`Saving ${d} to category: ${g}`);let f=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:g,filename:d,data:u,overwrite:!0})})).json();if(console.log(`Save result for ${d}:`,f),f.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${f.path}`);let m=new File([p],d,{type:"image/png"});r.set(d,m)}else console.warn(`\u274C Failed to save ${d}:`,f.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),n.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=r;try{this.normalizedManifest=Ri(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let l=[];for(let[p,d]of r){let u=await this.fileToDataUrl(d);l.push({id:p.replace(".png",""),filename:p,dataUrl:u,category:this.inferAssetCategory(p.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=l);let c=l.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${c} PNGs
673
+ \u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(l),this.refreshLibrary()}catch(l){console.error("[BrandVision] Failed to normalize ZIP manifest:",l),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=n,a.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>{let r=a.result;console.log("FileReader result type:",typeof r,"length:",r.length),console.log("Data URL prefix:",r.substring(0,30)),t(r)},a.onerror=r=>{console.error("FileReader error:",r),n(r)},a.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 a={};for(let r of e){let s=r.category||"misc";a[s]||(a[s]=[]),n.libraryAssets[s]||(n.libraryAssets[s]=[]),n.libraryAssets[s].some(l=>l.filename===r.filename)||(n.libraryAssets[s].unshift({filename:r.filename,displayName:r.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${r.filename} to registry category ${s}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var r;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let a="";for(let s of Array.from(n))try{let o=await s.text(),l=JSON.parse(o);this.uploadedJsons.set(s.name,l),l.layers?a+=`\u2705 Layers: ${s.name}
674
+ `:l.brand_dna||l.colors?a+=`\u2705 Brand: ${s.name}
675
+ `:a+=`\u2705 Loaded: ${s.name}
676
+ `}catch{a+=`\u274C Error in ${s.name}
677
+ `}try{this.normalizedManifest=Ri(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let s=Array.isArray((r=this.normalizedManifest)==null?void 0:r.assets)?this.normalizedManifest.assets.length:0;a+=`
678
+ \u{1F4E6} Normalized manifest: ${s} assets`,a+=`
679
+ \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:s,brandName:this.normalizedManifest.brand_name})}catch(s){console.error("[BrandVision] Failed to normalize manifest:",s),this.normalizedManifest=null,a+=`
680
+ \u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",a.trim())}async handleAssetsUpload(e){let n=e.target.files;if(!(!n||n.length===0)){for(let a of Array.from(n))this.assetFiles.set(a.name,a);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var r,s;let n=(r=e.target.files)==null?void 0:r[0];if(!n)return;let a=await Te(n);if(a){this.flatDesignDataUrl=a.dataUrl,this.setStatus("flat",n.name);let o=(s=this.root)==null?void 0:s.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${a.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,a,r,s,o,l,c;if(this.isAnalyzing)return;let e=(r=(a=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:r.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 jr(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await Ir(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(s=d.parseError)!=null?s:null,this.renderMappings(),d.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: ${d.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(p){console.error("[BrandVision] Analysis failed:",p),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,a;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(a=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:a.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let r={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await ji(r,this.mappingResult,{onProgress:(s,o,l)=>{this.setStatus("apply",`Generating ${s}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(r){console.error("[BrandVision] Generation failed:",r),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(),a=!!this.analysisRawResponse&&this.analysisParsedOk===!1,r=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),s=a?`
681
681
  <div class="vision-raw-block">
682
682
  <div class="inspector-text-sm" style="white-space: pre-wrap;">
683
683
  \u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
@@ -686,11 +686,11 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
686
686
  <textarea class="inspector-input vision-raw-textarea" readonly>${this.analysisRawResponse||""}</textarea>
687
687
  </div>
688
688
  `:"";e.innerHTML=`
689
- ${r}
689
+ ${s}
690
690
  ${this.mappingResult.mappings.map(l=>{var b;let c=n[l.game_object]||"",p=l.brand_asset||"",d=(b=t==null?void 0:t.assets)==null?void 0:b.find(y=>y.id===p),u=(d==null?void 0:d.dataUrl)||"",g=l.output_dataUrl||"",h=l.action==="GENERATE"?g:l.action==="APPLY"?u:"",f=!!h,m=`
691
691
  <select class="inspector-input" data-mapping-brand-asset style="flex:1; padding:6px 8px;">
692
692
  <option value="">Select brand asset\u2026</option>
693
- ${s.replace(`value="${p}"`,`value="${p}" selected`)}
693
+ ${r.replace(`value="${p}"`,`value="${p}" selected`)}
694
694
  </select>
695
695
  `;return`
696
696
  <div class="vision-mapping-item" data-mapping-item="${l.game_object}">
@@ -739,8 +739,8 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
739
739
  </div>
740
740
  </div>
741
741
  `}).join("")}
742
- `}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(a=>a.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 a=n.game_object,s=this.getPreviewValueForMapping(a);if(!s.value)continue;let r=e.saveToLibrary?await this.saveToLibraryAndReturnPath(a,s.value):s.value;r&&(await this.stageEngineAssetOverride(a,r),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var a;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=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var s;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 a=(s=this.mappingResult)==null?void 0:s.mappings.find(r=>r.game_object===e);a&&(a.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),a=window.__openAiEditor;if(typeof a!="function"){this.setStatus("apply","AI editor not available");return}let s=t.action==="GENERATE"?t.generation_prompt:void 0;a(e,s,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var a,s,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=(s=(a=this.root)==null?void 0:a.querySelector("[data-vision-api-key]"))==null?void 0:s.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 ji(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(()=>(ee(),sn));n({path:`assets.${e}`,value:t},{silent:!0});let a=window.applyEditableEngineConfig;typeof a=="function"&&a({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),a=`${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:a,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,a);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(r.path)}catch(s){return console.error("[BrandVision] Save to library error:",s),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let a=t();if(a!=null&&a.slots&&Array.isArray(a.slots)){let r=a.slots.find(o=>o.slotId===e||o.currentAsset===e);if(r!=null&&r.category)return String(r.category)}let s=a==null?void 0:a.categories;if(Array.isArray(s)&&s.length>0){let r=e.toLowerCase(),o=l=>s.find(c=>c.toLowerCase().includes(l));return r.includes("bg")||r.includes("background")?o("background")||s[0]:(r.includes("cta")||r.includes("button")||r.includes("ui")||r.includes("logo"))&&o("ui")||s[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 s;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]"},a=(s=this.root)==null?void 0:s.querySelector(n[e]);a&&(a.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,a=this.root.getBoundingClientRect().width,s=o=>{let l=Math.max(300,a+(o.clientX-n));this.root.style.width=`${l}px`},r=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",r)};window.addEventListener("pointermove",s),window.addEventListener("pointerup",r)})}refresh(){}};function $s(i,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:a=5}=e;return[`TASK: ${i}`,`CHANGE_STRENGTH: ${a}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
743
- `)}var Ho=["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"],Bo=["cta_hint","cta_label_end"],zs=[{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"}],Fo=["brand.primary","brand.heading","brand.body","brand.warning"],kn=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`
742
+ `}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(a=>a.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 a=n.game_object,r=this.getPreviewValueForMapping(a);if(!r.value)continue;let s=e.saveToLibrary?await this.saveToLibraryAndReturnPath(a,r.value):r.value;s&&(await this.stageEngineAssetOverride(a,s),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var a;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=(a=this.mappingResult)==null?void 0:a.mappings.find(r=>r.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var r;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 a=(r=this.mappingResult)==null?void 0:r.mappings.find(s=>s.game_object===e);a&&(a.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(s=>s.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),a=window.__openAiEditor;if(typeof a!="function"){this.setStatus("apply","AI editor not available");return}let r=t.action==="GENERATE"?t.generation_prompt:void 0;a(e,r,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var a,r,s;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=(s=(r=(a=this.root)==null?void 0:a.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:s.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 ji(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(()=>(ee(),rn));n({path:`assets.${e}`,value:t},{silent:!0});let a=window.applyEditableEngineConfig;typeof a=="function"&&a({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),a=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let s=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:a,data:t,overwrite:!0})})).json();if(!(s!=null&&s.success)||!(s!=null&&s.path))return console.error("[BrandVision] Save to library failed:",(s==null?void 0:s.error)||s),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,a);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(s.path)}catch(r){return console.error("[BrandVision] Save to library error:",r),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let a=t();if(a!=null&&a.slots&&Array.isArray(a.slots)){let s=a.slots.find(o=>o.slotId===e||o.currentAsset===e);if(s!=null&&s.category)return String(s.category)}let r=a==null?void 0:a.categories;if(Array.isArray(r)&&r.length>0){let s=e.toLowerCase(),o=l=>r.find(c=>c.toLowerCase().includes(l));return s.includes("bg")||s.includes("background")?o("background")||r[0]:(s.includes("cta")||s.includes("button")||s.includes("ui")||s.includes("logo"))&&o("ui")||r[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 r;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]"},a=(r=this.root)==null?void 0:r.querySelector(n[e]);a&&(a.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,a=this.root.getBoundingClientRect().width,r=o=>{let l=Math.max(300,a+(o.clientX-n));this.root.style.width=`${l}px`},s=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",s)};window.addEventListener("pointermove",r),window.addEventListener("pointerup",s)})}refresh(){}};function $r(i,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:a=5}=e;return[`TASK: ${i}`,`CHANGE_STRENGTH: ${a}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
743
+ `)}var Ho=["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"],Bo=["cta_hint","cta_label_end"],zr=[{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"}],Fo=["brand.primary","brand.heading","brand.body","brand.warning"],kn=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`
744
744
  <div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
745
745
  <div class="scene-panel-header" data-panel-handle>
746
746
  <div class="panel-title">
@@ -798,7 +798,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
798
798
  </div>
799
799
  <div class="panel-resize-handle" data-panel-resize></div>
800
800
  </div>
801
- `}initialize(e,t){var a,s,r,o,l,c;this.options=t,this.root=e.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(a=this.root)==null?void 0:a.querySelector("[data-customize-assets]"),this.colorsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-colors]"),this.fontsContainer=(r=this.root)==null?void 0:r.querySelector("[data-customize-fonts]"),this.textsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let n=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");n==null||n.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var n,a;let e=(n=this.root)==null?void 0:n.querySelector('[data-render-mode="endgame-png"]'),t=(a=this.root)==null?void 0:a.querySelector('[data-render-mode="splash-png"]');e==null||e.addEventListener("change",()=>{this.applyEndgamePngMode(e.checked)}),t==null||t.addEventListener("change",()=>{this.applySplashPngMode(t.checked)})}applyEndgamePngMode(e){let t=window.getEditableObjectConfig,n=window.applyEditableObjectConfig;if(typeof t!="function"||typeof n!="function")return;let a=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let s of a){let r=t(s);r&&(r.ui||(r.ui={}),r.ui.renderMode=e?"png":"text",e&&(r.render||(r.render={}),r.render.asset||(r.render.asset={type:"image",path:""}),r.render.asset.type="image"),n(s,r))}console.log("[CustomizePanel] EndGame PNG mode:",e?"enabled":"disabled")}applySplashPngMode(e){let t=window.applyEditableEngineConfig;typeof t=="function"&&(t({splash:{type:e?"image":"text",image_path:e?"library/splash/splash.png":""}}),console.log("[CustomizePanel] Splash PNG mode:",e?"enabled":"disabled"))}openAiEditor(e,t,n,a){this.openAiModal(e,n,a),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,n,a,s,r,o,l,c;let e=this.getEngineSnapshot();if(console.log("[CustomizePanel] Refreshing with snapshot:",!!e),!e){this.scheduleRetry();return}console.log("[CustomizePanel] Snapshot assets count:",Object.keys(e.assets||{}).length),this.renderAssets(e.assets),this.renderColors((n=(t=e.runtime)==null?void 0:t.theme)!=null?n:{}),this.renderFonts((s=(a=e.runtime)==null?void 0:a.fonts)!=null?s:{}),this.renderTexts((o=(r=e.runtime)==null?void 0:r.ui)!=null?o:{}),this.renderAudio((c=(l=e.runtime)==null?void 0:l.audio)!=null?c:{})}getEngineSnapshot(){let e=window.getEditableEngineConfig;return typeof e!="function"?null:e()}renderAssets(e){if(!this.assetsContainer)return;this.assetsContainer.innerHTML="";let t=Object.entries(e!=null?e:{});if(!t.length){this.assetsContainer.innerHTML='<div class="customize-empty">No assets found.</div>',this.scheduleRetry();return}this.clearRetry(),t.forEach(([n,a])=>{var u;let s=document.createElement("div");s.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=n;let o=document.createElement("input");o.type="text",o.value=a!=null?a:"",o.className="customize-input",o.dataset.assetKey=n,o.addEventListener("input",()=>{this.handleAssetValueChange(n,o)});let l=document.createElement("div");l.className="customize-actions";let c=document.createElement("button");c.type="button",c.className="customize-icon-btn",c.title="Preview asset",c.innerHTML=`
801
+ `}initialize(e,t){var a,r,s,o,l,c;this.options=t,this.root=e.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(a=this.root)==null?void 0:a.querySelector("[data-customize-assets]"),this.colorsContainer=(r=this.root)==null?void 0:r.querySelector("[data-customize-colors]"),this.fontsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-fonts]"),this.textsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let n=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");n==null||n.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var n,a;let e=(n=this.root)==null?void 0:n.querySelector('[data-render-mode="endgame-png"]'),t=(a=this.root)==null?void 0:a.querySelector('[data-render-mode="splash-png"]');e==null||e.addEventListener("change",()=>{this.applyEndgamePngMode(e.checked)}),t==null||t.addEventListener("change",()=>{this.applySplashPngMode(t.checked)})}applyEndgamePngMode(e){let t=window.getEditableObjectConfig,n=window.applyEditableObjectConfig;if(typeof t!="function"||typeof n!="function")return;let a=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let r of a){let s=t(r);s&&(s.ui||(s.ui={}),s.ui.renderMode=e?"png":"text",e&&(s.render||(s.render={}),s.render.asset||(s.render.asset={type:"image",path:""}),s.render.asset.type="image"),n(r,s))}console.log("[CustomizePanel] EndGame PNG mode:",e?"enabled":"disabled")}applySplashPngMode(e){let t=window.applyEditableEngineConfig;typeof t=="function"&&(t({splash:{type:e?"image":"text",image_path:e?"library/splash/splash.png":""}}),console.log("[CustomizePanel] Splash PNG mode:",e?"enabled":"disabled"))}openAiEditor(e,t,n,a){this.openAiModal(e,n,a),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,n,a,r,s,o,l,c;let e=this.getEngineSnapshot();if(console.log("[CustomizePanel] Refreshing with snapshot:",!!e),!e){this.scheduleRetry();return}console.log("[CustomizePanel] Snapshot assets count:",Object.keys(e.assets||{}).length),this.renderAssets(e.assets),this.renderColors((n=(t=e.runtime)==null?void 0:t.theme)!=null?n:{}),this.renderFonts((r=(a=e.runtime)==null?void 0:a.fonts)!=null?r:{}),this.renderTexts((o=(s=e.runtime)==null?void 0:s.ui)!=null?o:{}),this.renderAudio((c=(l=e.runtime)==null?void 0:l.audio)!=null?c:{})}getEngineSnapshot(){let e=window.getEditableEngineConfig;return typeof e!="function"?null:e()}renderAssets(e){if(!this.assetsContainer)return;this.assetsContainer.innerHTML="";let t=Object.entries(e!=null?e:{});if(!t.length){this.assetsContainer.innerHTML='<div class="customize-empty">No assets found.</div>',this.scheduleRetry();return}this.clearRetry(),t.forEach(([n,a])=>{var u;let r=document.createElement("div");r.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.textContent=n;let o=document.createElement("input");o.type="text",o.value=a!=null?a:"",o.className="customize-input",o.dataset.assetKey=n,o.addEventListener("input",()=>{this.handleAssetValueChange(n,o)});let l=document.createElement("div");l.className="customize-actions";let c=document.createElement("button");c.type="button",c.className="customize-icon-btn",c.title="Preview asset",c.innerHTML=`
802
802
  <svg viewBox="0 0 24 24" aria-hidden="true">
803
803
  <path d="M12 5c5.2 0 9.2 3.7 10 6.8-.8 3.1-4.8 6.8-10 6.8S2.8 14.9 2 11.8C2.8 8.7 6.8 5 12 5z" />
804
804
  <circle cx="12" cy="12" r="3.2" />
@@ -808,7 +808,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
808
808
  <path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
809
809
  <path d="M5 14v4h14v-4h2v6H3v-6h2z" />
810
810
  </svg>
811
- `;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var h;let g=(h=d.files)==null?void 0:h[0];g&&this.handleAssetUpload(g,o,n)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),s.appendChild(r),s.appendChild(o),s.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(s)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",Ho.forEach(t=>{var l,c,p;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 a=document.createElement("label");a.className="customize-color-field";let s=document.createElement("span");s.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)}),a.appendChild(s),a.appendChild(r),a.appendChild(o),(p=this.colorsContainer)==null||p.appendChild(a)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Fo.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(r=e==null?void 0:e[t])!=null?r:t,s.className="customize-input",s.dataset.fontKey=t,n.appendChild(a),n.appendChild(s),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Bo.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(r=this.readUiValue(e,t))!=null?r:"",s.className="customize-input",s.dataset.textKey=t,n.appendChild(a),n.appendChild(s),(o=this.textsContainer)==null||o.appendChild(n)}),zs.forEach(({key:t,objectId:n})=>{var o,l;let a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.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,a.appendChild(s),a.appendChild(r),(l=this.textsContainer)==null||l.appendChild(a)}))}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 a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.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"),a.appendChild(s),a.appendChild(r),(l=this.audioContainer)==null||l.appendChild(a)})}readUiValue(e,t){if(t.includes(".")){let a=t.split("."),s=e;for(let r of a){if(s==null)return null;s=s[r]}return typeof s=="string"?s:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var a,s;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(s=(a=n==null?void 0:n.ui)==null?void 0:a.text)!=null?s:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let a=n(e);if(!a)return null;let s=t.split("."),r=a;for(let o of s){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 a={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(a[c]=l.value)});let s={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(s[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 p=parseFloat(l.value);r[c]=isNaN(p)?0:p}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 p=zs.find(d=>d.key===c);p&&this.applyObjectPropertyValue(p.objectId,p.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:s,fonts:a,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 a=await _n(n);if(a)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:a.base64,mimeType:a.mimeType},dataUrl:a.dataUrl,width:a.width,height:a.height}}catch(a){console.warn("[CustomizePanel] Failed to fetch image data from:",n,a)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var a,s,r;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(s=(a=o==null?void 0:o.value)==null?void 0:a.trim())!=null?s:""}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 a=e.querySelector(".asset-preview-ai-image");a&&(a.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 a=document.createElement("button");a.type="button",a.className="ai-gallery-item",t===this.aiTargetKey&&a.classList.add("active");let s=document.createElement("img");s.className="ai-gallery-thumb",s.alt=t;let r=this.resolveAssetUrls(n);r[0]&&(s.src=r[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,a.appendChild(s),a.appendChild(o),a.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(a)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var r,o;let n=t,a=n.dataset.assetKey,s=(o=(r=n.value)==null?void 0:r.trim())!=null?o:"";!a||!s||this.isAiGalleryImage(s)&&e.push({key:a,value:s})}),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(a=>n.endsWith(a))}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,p,d,u,g,h,f,m;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 a=document.createElement("div");a.className="ai-modal",a.innerHTML=`
811
+ `;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var h;let g=(h=d.files)==null?void 0:h[0];g&&this.handleAssetUpload(g,o,n)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),r.appendChild(s),r.appendChild(o),r.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(r)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",Ho.forEach(t=>{var l,c,p;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 a=document.createElement("label");a.className="customize-color-field";let r=document.createElement("span");r.textContent=t.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),a.appendChild(r),a.appendChild(s),a.appendChild(o),(p=this.colorsContainer)==null||p.appendChild(a)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Fo.forEach(t=>{var s,o;let n=document.createElement("div");n.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=(s=e==null?void 0:e[t])!=null?s:t,r.className="customize-input",r.dataset.fontKey=t,n.appendChild(a),n.appendChild(r),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Bo.forEach(t=>{var s,o;let n=document.createElement("div");n.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=(s=this.readUiValue(e,t))!=null?s:"",r.className="customize-input",r.dataset.textKey=t,n.appendChild(a),n.appendChild(r),(o=this.textsContainer)==null||o.appendChild(n)}),zr.forEach(({key:t,objectId:n})=>{var o,l;let a=document.createElement("div");a.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=t;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=t,a.appendChild(r),a.appendChild(s),(l=this.textsContainer)==null||l.appendChild(a)}))}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 a=document.createElement("div");a.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=e==null?void 0:e[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),a.appendChild(r),a.appendChild(s),(l=this.audioContainer)==null||l.appendChild(a)})}readUiValue(e,t){if(t.includes(".")){let a=t.split("."),r=e;for(let s of a){if(r==null)return null;r=r[s]}return typeof r=="string"?r:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var a,r;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(r=(a=n==null?void 0:n.ui)==null?void 0:a.text)!=null?r:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let a=n(e);if(!a)return null;let r=t.split("."),s=a;for(let o of r){if(s==null)return null;s=s[o]}return typeof s=="string"?s: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 a={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(a[c]=l.value)});let r={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(r[c]=l.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);s[c]=isNaN(p)?0:p}else s[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let p=zr.find(d=>d.key===c);p&&this.applyObjectPropertyValue(p.objectId,p.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:r,fonts:a,audio:s}},{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 a=await _n(n);if(a)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:a.base64,mimeType:a.mimeType},dataUrl:a.dataUrl,width:a.width,height:a.height}}catch(a){console.warn("[CustomizePanel] Failed to fetch image data from:",n,a)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var a,r,s;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(r=(a=o==null?void 0:o.value)==null?void 0:a.trim())!=null?r:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(s=n==null?void 0:n.dataUrl)!=null?s: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 a=e.querySelector(".asset-preview-ai-image");a&&(a.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 a=document.createElement("button");a.type="button",a.className="ai-gallery-item",t===this.aiTargetKey&&a.classList.add("active");let r=document.createElement("img");r.className="ai-gallery-thumb",r.alt=t;let s=this.resolveAssetUrls(n);s[0]&&(r.src=s[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,a.appendChild(r),a.appendChild(o),a.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(a)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var s,o;let n=t,a=n.dataset.assetKey,r=(o=(s=n.value)==null?void 0:s.trim())!=null?o:"";!a||!r||this.isAiGalleryImage(r)&&e.push({key:a,value:r})}),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(a=>n.endsWith(a))}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,p,d,u,g,h,f,m;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 a=document.createElement("div");a.className="ai-modal",a.innerHTML=`
812
812
  <div class="ai-modal-card">
813
813
  <div class="ai-modal-header">
814
814
  <div>
@@ -879,7 +879,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
879
879
  </div>
880
880
  </div>
881
881
  </div>
882
- `;let s=a.querySelector(".ai-modal-close");s==null||s.addEventListener("click",()=>this.closeAiModal()),a.addEventListener("click",b=>{b.target===a&&this.closeAiModal()}),this.aiModal=a,this.aiKeyInput=a.querySelector("[data-ai-key]"),this.aiModelSelect=a.querySelector("[data-ai-model]"),this.aiPromptInput=a.querySelector("[data-ai-prompt]"),this.aiStrengthInput=a.querySelector("[data-ai-strength]"),this.aiStrengthValue=a.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=a.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=a.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=a.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=a.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=a.querySelector("[data-ai-ref-input]"),this.aiReferenceName=a.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=a.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=a.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=a.querySelector("[data-ai-generate]"),this.aiApplyBtn=a.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=a.querySelector("[data-ai-save-library]"),this.aiCropBtn=a.querySelector("[data-ai-crop]"),this.aiDownloadBtn=a.querySelector("[data-ai-download]"),this.aiPreviewImg=a.querySelector("[data-ai-preview]"),this.aiStatusEl=a.querySelector("[data-ai-status]"),this.aiLoadingEl=a.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=a.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=a.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=a.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(p=this.aiBgToleranceInput)==null||p.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(d=this.aiReferenceInput)==null||d.addEventListener("change",()=>{var y,v,x;let b=(x=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?x:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(h=this.aiSaveLibraryBtn)==null||h.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(a),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 p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(d=(p=this.aiKeyInput)==null?void 0:p.value)==null?void 0:d.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",a=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,s=a,r=a,o=Number((E=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?E:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((w=l==null?void 0:l.value)==null?void 0:w.trim())||((T=this.aiBaseValue)==null?void 0:T.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let k=null,D=(S=this.getSelectedAssetKey())!=null?S:"unknown",R=(O=this.aiUseOutputToggle)!=null&&O.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((B=this.aiUseOutputToggle)!=null&&B.checked&&this.aiOutputDataUrl){let ie=Oi(this.aiOutputDataUrl,"ai-output.png");if(ie){let ae=await Te(ie);ae&&(k={input:{base64:ae.base64,mimeType:ae.mimeType},dataUrl:ae.dataUrl,width:ae.width,height:ae.height})}}if(k||(k=await this.getImageDataFromAsset(c)),!k){this.setAiStatus("Unable to load the base image.");return}let $=[k.input],A=!1;if(this.aiReferenceFile){let ie=await Te(this.aiReferenceFile);ie?($.push({base64:ie.base64,mimeType:ie.mimeType}),A=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let _=$s(n,{includeReference:A,includeMagenta:s,changeLevel:o}),P=(C=(M=this.aiReferenceFile)==null?void 0:M.name)!=null?C:"none";console.info("[AI] Final prompt:",_),console.info("[AI] Image sources:",{assetKey:D,base:R,reference:P});let q=Cs(k.width,k.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await Qe(e,_,$,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(k){console.error("[CustomizePanel] AI Generate Error:",k),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((I=this.aiStatusEl)==null?void 0:I.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var a,s,r,o;if(!this.aiRawOutputDataUrl)return;let e=(s=(a=this.aiRemoveBgToggle)==null?void 0:a.checked)!=null?s:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await Ze(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,a;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,(a=this.activePreviewKey)!=null?a: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,a;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 s=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((a=this.aiContext)==null?void 0:a.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(s&&r)console.log("[CustomizePanel] Applying AI output directly to object:",s,r),this.applyObjectPropertyValue(s,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 s,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,"_")}_ai_${Date.now()}`,a=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:a,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}. Applying...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",a),p(a,`${n}.png`));let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),d());let u=((s=this.aiContext)==null?void 0:s.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),g=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),h=this.getSelectedAssetInput();if(h&&(h.value=c.path,this.handleAssetValueChange((o=h.dataset.assetKey)!=null?o:"",h)),u&&g){console.log("[CustomizePanel] Saved and applying directly to object:",u,g);let f=window.applyAssetToSlot,m=/texture|image|sprite|asset\\.path/i.test(g)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof f=="function"&&m){let b=this.getFilenameFromPath(c.path);f(u,b,a)}else this.applyObjectPropertyValue(u,g,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}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||"",a=window.getEditableAssets;if(typeof a=="function"){let o=a();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 s=n.toLowerCase();return s.includes("background")?"backgrounds":s.includes("character")?"characters":s.includes("key")?"collectedkeys":s.includes("draggable")?"draggables":s.includes("environment")||s.includes("env")||s.includes("hand")||s.includes("prop")||s.includes("item")||s.includes("decor")||s.includes("object")?"environment":s.includes("machine")?"machines":s.includes("tutorial")?"tutorial":s.includes("ui")||s.includes("button")||s.includes("label")||s.includes("icon")||s.includes("logo")||s.includes("cta")||s.includes("menu")||s.includes("overlay")?"ui":s.includes("effect")||s.includes("confetti")||s.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 a=n.slots.find(s=>s.currentAsset===e||s.slotId===e);return(a==null?void 0:a.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 a=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!a)return null;let s=a.category;return s==="render"||s==="backgrounds"||s==="characters"?"render.texture":s==="ui"?"ui.image":s==="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 a=Oi(this.aiOutputDataUrl,"ai-output.png");if(!a)return;let s=await this.showManualCropModal(a,n,t);if(!s)return;let r=await Ss(s);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){let a=t.value,s=e;if(e.type.startsWith("image/")){let l=await this.getImageDimensions(a);if(l){let c=await this.showManualCropModal(e,l,a);if(!c)return;s=c}}let r=URL.createObjectURL(s),o=t.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}t.dataset.objectUrl=r,t.dataset.assetType=s.type,t.value=r,this.handleAssetValueChange(n,t)}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,a){if(!t)return;let s=this.resolveAssetUrls(t);if(s.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=a!=null?a:null,this.openPreviewModal(e,t,s,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(/^\.?\//,""),a=[];return n.startsWith("raw/")?a=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?a=[`/${n}`]:a=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",a),a}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,a){this.closePreviewModal(!0);let s=document.createElement("div");s.className="asset-preview-modal",s.innerHTML=`
882
+ `;let r=a.querySelector(".ai-modal-close");r==null||r.addEventListener("click",()=>this.closeAiModal()),a.addEventListener("click",b=>{b.target===a&&this.closeAiModal()}),this.aiModal=a,this.aiKeyInput=a.querySelector("[data-ai-key]"),this.aiModelSelect=a.querySelector("[data-ai-model]"),this.aiPromptInput=a.querySelector("[data-ai-prompt]"),this.aiStrengthInput=a.querySelector("[data-ai-strength]"),this.aiStrengthValue=a.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=a.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=a.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=a.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=a.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=a.querySelector("[data-ai-ref-input]"),this.aiReferenceName=a.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=a.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=a.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=a.querySelector("[data-ai-generate]"),this.aiApplyBtn=a.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=a.querySelector("[data-ai-save-library]"),this.aiCropBtn=a.querySelector("[data-ai-crop]"),this.aiDownloadBtn=a.querySelector("[data-ai-download]"),this.aiPreviewImg=a.querySelector("[data-ai-preview]"),this.aiStatusEl=a.querySelector("[data-ai-status]"),this.aiLoadingEl=a.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=a.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=a.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=a.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(p=this.aiBgToleranceInput)==null||p.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(d=this.aiReferenceInput)==null||d.addEventListener("change",()=>{var y,v,x;let b=(x=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?x:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(h=this.aiSaveLibraryBtn)==null||h.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(a),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 p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(d=(p=this.aiKeyInput)==null?void 0:p.value)==null?void 0:d.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",a=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,r=a,s=a,o=Number((E=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?E:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((w=l==null?void 0:l.value)==null?void 0:w.trim())||((T=this.aiBaseValue)==null?void 0:T.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let k=null,D=(S=this.getSelectedAssetKey())!=null?S:"unknown",R=(O=this.aiUseOutputToggle)!=null&&O.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((B=this.aiUseOutputToggle)!=null&&B.checked&&this.aiOutputDataUrl){let ie=Oi(this.aiOutputDataUrl,"ai-output.png");if(ie){let ae=await Te(ie);ae&&(k={input:{base64:ae.base64,mimeType:ae.mimeType},dataUrl:ae.dataUrl,width:ae.width,height:ae.height})}}if(k||(k=await this.getImageDataFromAsset(c)),!k){this.setAiStatus("Unable to load the base image.");return}let $=[k.input],A=!1;if(this.aiReferenceFile){let ie=await Te(this.aiReferenceFile);ie?($.push({base64:ie.base64,mimeType:ie.mimeType}),A=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let _=$r(n,{includeReference:A,includeMagenta:r,changeLevel:o}),P=(C=(M=this.aiReferenceFile)==null?void 0:M.name)!=null?C:"none";console.info("[AI] Final prompt:",_),console.info("[AI] Image sources:",{assetKey:D,base:R,reference:P});let q=Cr(k.width,k.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await Qe(e,_,$,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(k){console.error("[CustomizePanel] AI Generate Error:",k),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((I=this.aiStatusEl)==null?void 0:I.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var a,r,s,o;if(!this.aiRawOutputDataUrl)return;let e=(r=(a=this.aiRemoveBgToggle)==null?void 0:a.checked)!=null?r:!1,t=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await Ze(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,a;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,(a=this.activePreviewKey)!=null?a: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,a;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 r=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((a=this.aiContext)==null?void 0:a.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(r&&s)console.log("[CustomizePanel] Applying AI output directly to object:",r,s),this.applyObjectPropertyValue(r,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var r,s,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,"_")}_ai_${Date.now()}`,a=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:a,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}. Applying...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",a),p(a,`${n}.png`));let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),d());let u=((r=this.aiContext)==null?void 0:r.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),g=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),h=this.getSelectedAssetInput();if(h&&(h.value=c.path,this.handleAssetValueChange((o=h.dataset.assetKey)!=null?o:"",h)),u&&g){console.log("[CustomizePanel] Saved and applying directly to object:",u,g);let f=window.applyAssetToSlot,m=/texture|image|sprite|asset\\.path/i.test(g)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof f=="function"&&m){let b=this.getFilenameFromPath(c.path);f(u,b,a)}else this.applyObjectPropertyValue(u,g,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var s;let t=(s=this.aiContext)==null?void 0:s.objectId,n=e||this.aiTargetKey||"",a=window.getEditableAssets;if(typeof a=="function"){let o=a();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 r=n.toLowerCase();return r.includes("background")?"backgrounds":r.includes("character")?"characters":r.includes("key")?"collectedkeys":r.includes("draggable")?"draggables":r.includes("environment")||r.includes("env")||r.includes("hand")||r.includes("prop")||r.includes("item")||r.includes("decor")||r.includes("object")?"environment":r.includes("machine")?"machines":r.includes("tutorial")?"tutorial":r.includes("ui")||r.includes("button")||r.includes("label")||r.includes("icon")||r.includes("logo")||r.includes("cta")||r.includes("menu")||r.includes("overlay")?"ui":r.includes("effect")||r.includes("confetti")||r.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 a=n.slots.find(r=>r.currentAsset===e||r.slotId===e);return(a==null?void 0:a.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 a=n.slots.find(s=>s.currentAsset===e||s.slotId===e);if(!a)return null;let r=a.category;return r==="render"||r==="backgrounds"||r==="characters"?"render.texture":r==="ui"?"ui.image":r==="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 a=Oi(this.aiOutputDataUrl,"ai-output.png");if(!a)return;let r=await this.showManualCropModal(a,n,t);if(!r)return;let s=await Sr(r);s&&this.setAiOutput(s)}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){let a=t.value,r=e;if(e.type.startsWith("image/")){let l=await this.getImageDimensions(a);if(l){let c=await this.showManualCropModal(e,l,a);if(!c)return;r=c}}let s=URL.createObjectURL(r),o=t.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}t.dataset.objectUrl=s,t.dataset.assetType=r.type,t.value=s,this.handleAssetValueChange(n,t)}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,a){if(!t)return;let r=this.resolveAssetUrls(t);if(r.length===0)return;let s=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=a!=null?a:null,this.openPreviewModal(e,t,r,s)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),a=[];return n.startsWith("raw/")?a=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?a=[`/${n}`]:a=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",a),a}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,a){this.closePreviewModal(!0);let r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
883
883
  <div class="asset-preview-card">
884
884
  <div class="asset-preview-header">
885
885
  <div class="asset-preview-title">${e}</div>
@@ -895,7 +895,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
895
895
  <img class="asset-preview-ai-image" alt="AI output preview">
896
896
  </div>
897
897
  </div>
898
- `;let r=s.querySelector(".asset-preview-body"),o=s.querySelector(".asset-preview-close"),l=s.querySelector(".asset-preview-change"),c=s.querySelector(".asset-preview-ai"),p=s.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",e),this.openAiModal(e,t)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",e),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),s.addEventListener("click",d=>{d.target===s&&this.closePreviewModal()}),r)if(a==="image"){let d=document.createElement("img");this.loadWithFallback(d,n),r.appendChild(d)}else if(a==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,n),r.appendChild(d)}else if(a==="json"){let d=document.createElement("pre");this.fetchWithFallback(n).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),r.appendChild(d)}else{let d=document.createElement("a");d.href=n[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",r.appendChild(d)}document.body.appendChild(s),this.previewModal=s,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let n=0,a=()=>{n>=t.length||(e.src=t[n],n+=1)};e.addEventListener("error",a),a()}async fetchWithFallback(e){for(let t of e)try{let n=await fetch(t);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(e,t,n){let a=window.getEditableObjectConfig,s=window.applyEditableObjectConfig;if(typeof a!="function"||typeof s!="function")return;let r=a(e);if(!r)return;let o=JSON.parse(JSON.stringify(r)),l=t.split("."),c=o;for(let p=0;p<l.length-1;p++){let d=l[p];c[d]=c[d]||{},c=c[d]}c[l[l.length-1]]=n,s(e,o)}applyTextColorToObject(e,t){let a={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"}}[e];a&&this.applyObjectPropertyValue(a.objectId,a.property,t)}closePreviewModal(e){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),e||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(e,t,n){var s;if(!this.previewModal||this.activePreviewKey!==e)return;let a=t!=null?t:"";this.activePreviewValue!==a&&this.previewAsset(e,a,n,(s=this.activePreviewFileInput)!=null?s:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");if(!e)return;let t=window.localStorage.getItem("customizePanelWidth"),n=t?Number(t):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let a=s=>{var u,g;s.preventDefault();let r=s.clientX,o=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=h=>{let f=h.clientX-r,m=Math.min(c,Math.max(l,o+f));this.root&&(this.root.style.width=`${m}px`)},d=()=>{var f,m;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let h=(m=(f=this.root)==null?void 0:f.getBoundingClientRect().width)!=null?m:0;h>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(h)))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)};e.addEventListener("pointerdown",a)}async getImageDimensions(e){let t=this.resolveAssetUrls(e);if(t.length===0)return null;for(let n of t){let a=await this.loadImage(n);if(a!=null&&a.naturalWidth&&(a!=null&&a.naturalHeight))return{width:a.naturalWidth,height:a.naturalHeight}}return null}async loadImage(e){return await new Promise(t=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>t(null),n.src=e})}async showManualCropModal(e,t,n){let a=t.width/t.height,s=URL.createObjectURL(e),r=await this.loadImage(s);try{URL.revokeObjectURL(s)}catch{}if(!(r!=null&&r.naturalWidth)||!(r!=null&&r.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),h=Math.max(220,Math.floor((p-32-16)/2)),f=Math.min(520,window.innerHeight-240),m=h,b=m/a;b>f&&(b=f,m=b*a),c.innerHTML=`
898
+ `;let s=r.querySelector(".asset-preview-body"),o=r.querySelector(".asset-preview-close"),l=r.querySelector(".asset-preview-change"),c=r.querySelector(".asset-preview-ai"),p=r.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",e),this.openAiModal(e,t)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",e),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),r.addEventListener("click",d=>{d.target===r&&this.closePreviewModal()}),s)if(a==="image"){let d=document.createElement("img");this.loadWithFallback(d,n),s.appendChild(d)}else if(a==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,n),s.appendChild(d)}else if(a==="json"){let d=document.createElement("pre");this.fetchWithFallback(n).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),s.appendChild(d)}else{let d=document.createElement("a");d.href=n[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",s.appendChild(d)}document.body.appendChild(r),this.previewModal=r,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let n=0,a=()=>{n>=t.length||(e.src=t[n],n+=1)};e.addEventListener("error",a),a()}async fetchWithFallback(e){for(let t of e)try{let n=await fetch(t);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(e,t,n){let a=window.getEditableObjectConfig,r=window.applyEditableObjectConfig;if(typeof a!="function"||typeof r!="function")return;let s=a(e);if(!s)return;let o=JSON.parse(JSON.stringify(s)),l=t.split("."),c=o;for(let p=0;p<l.length-1;p++){let d=l[p];c[d]=c[d]||{},c=c[d]}c[l[l.length-1]]=n,r(e,o)}applyTextColorToObject(e,t){let a={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"}}[e];a&&this.applyObjectPropertyValue(a.objectId,a.property,t)}closePreviewModal(e){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),e||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(e,t,n){var r;if(!this.previewModal||this.activePreviewKey!==e)return;let a=t!=null?t:"";this.activePreviewValue!==a&&this.previewAsset(e,a,n,(r=this.activePreviewFileInput)!=null?r:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");if(!e)return;let t=window.localStorage.getItem("customizePanelWidth"),n=t?Number(t):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let a=r=>{var u,g;r.preventDefault();let s=r.clientX,o=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=h=>{let f=h.clientX-s,m=Math.min(c,Math.max(l,o+f));this.root&&(this.root.style.width=`${m}px`)},d=()=>{var f,m;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let h=(m=(f=this.root)==null?void 0:f.getBoundingClientRect().width)!=null?m:0;h>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(h)))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)};e.addEventListener("pointerdown",a)}async getImageDimensions(e){let t=this.resolveAssetUrls(e);if(t.length===0)return null;for(let n of t){let a=await this.loadImage(n);if(a!=null&&a.naturalWidth&&(a!=null&&a.naturalHeight))return{width:a.naturalWidth,height:a.naturalHeight}}return null}async loadImage(e){return await new Promise(t=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>t(null),n.src=e})}async showManualCropModal(e,t,n){let a=t.width/t.height,r=URL.createObjectURL(e),s=await this.loadImage(r);try{URL.revokeObjectURL(r)}catch{}if(!(s!=null&&s.naturalWidth)||!(s!=null&&s.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),h=Math.max(220,Math.floor((p-32-16)/2)),f=Math.min(520,window.innerHeight-240),m=h,b=m/a;b>f&&(b=f,m=b*a),c.innerHTML=`
899
899
  <div class="asset-crop-card" style="width:${p}px;">
900
900
  <div class="asset-crop-header">
901
901
  <div>
@@ -925,7 +925,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
925
925
  <button class="asset-crop-apply" type="button">Apply Crop</button>
926
926
  </div>
927
927
  </div>
928
- `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),E=c.querySelector(".asset-crop-zoom-value"),w=c.querySelector(".asset-crop-close"),T=c.querySelector(".asset-crop-cancel"),S=c.querySelector(".asset-crop-apply"),O=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!E){l(null);return}let B=y.getContext("2d"),M=v.getContext("2d");if(!B||!M){l(null);return}let C=r.naturalWidth,I=r.naturalHeight,k=Math.max(y.width/C,y.height/I),D=1,R=0,$=0,A=!1,_=0,P=0,q=0,V=0,ie=()=>{let j=k*D,ke=Math.max(0,(C*j-y.width)/2),Fe=Math.max(0,(I*j-y.height)/2);R=Math.min(ke,Math.max(-ke,R)),$=Math.min(Fe,Math.max(-Fe,$))},ae=()=>{let j=k*D;B.clearRect(0,0,y.width,y.height);let ke=y.width/2-C*j/2+R,Fe=y.height/2-I*j/2+$;if(B.drawImage(r,ke,Fe,C*j,I*j),M.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Ge=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),Qn=v.width/2-o.naturalWidth*Ge/2,pt=v.height/2-o.naturalHeight*Ge/2;M.drawImage(o,Qn,pt,o.naturalWidth*Ge,o.naturalHeight*Ge)}else M.fillStyle="rgba(255, 255, 255, 0.04)",M.fillRect(0,0,v.width,v.height),M.strokeStyle="rgba(255, 255, 255, 0.08)",M.strokeRect(4,4,v.width-8,v.height-8);let dt=v.width/y.width*(k*D),Ue=R*(v.width/y.width),Nt=$*(v.height/y.height),Jn=v.width/2-C*dt/2+Ue,Zn=v.height/2-I*dt/2+Nt;M.save(),M.globalAlpha=.7,M.drawImage(r,Jn,Zn,C*dt,I*dt),M.restore()},Ea=()=>{R=0,$=0,ie(),ae()};x.addEventListener("input",()=>{D=Number(x.value),E.textContent=`${D.toFixed(2)}\xD7`,ie(),ae()}),y.addEventListener("pointerdown",j=>{A=!0,_=j.clientX,P=j.clientY,q=R,V=$,y.setPointerCapture(j.pointerId)}),y.addEventListener("pointermove",j=>{A&&(R=q+(j.clientX-_),$=V+(j.clientY-P),ie(),ae())}),y.addEventListener("pointerup",j=>{A=!1,y.releasePointerCapture(j.pointerId)}),y.addEventListener("pointerleave",()=>{A=!1});let Kn=()=>{c.remove()},Xn=()=>{Kn(),l(null)},Pr=async()=>{let j=document.createElement("canvas");j.width=t.width,j.height=t.height;let ke=j.getContext("2d");if(!ke){Kn(),l(null);return}let Fe=D,Ue=Math.max(j.width/C,j.height/I)*Fe,Nt=j.width/y.width,Jn=R*Nt,Zn=$*Nt,Ge=j.width/2-C*Ue/2+Jn,Qn=j.height/2-I*Ue/2+Zn;ke.drawImage(r,Ge,Qn,C*Ue,I*Ue);let pt=await new Promise(Mr=>{j.toBlob(kr=>Mr(kr),e.type||"image/png")});if(Kn(),!pt){l(null);return}l(new File([pt],e.name,{type:pt.type}))};w==null||w.addEventListener("click",Xn),T==null||T.addEventListener("click",Xn),O==null||O.addEventListener("click",Ea),S==null||S.addEventListener("click",()=>{Pr()}),c.addEventListener("click",j=>{j.target===c&&Xn()}),document.body.appendChild(c),Ea()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let a=await this.loadImage(n);if(a)return a}return null}};var On=class{constructor(){this.root=null;this.options=null}render(){return`
928
+ `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),E=c.querySelector(".asset-crop-zoom-value"),w=c.querySelector(".asset-crop-close"),T=c.querySelector(".asset-crop-cancel"),S=c.querySelector(".asset-crop-apply"),O=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!E){l(null);return}let B=y.getContext("2d"),M=v.getContext("2d");if(!B||!M){l(null);return}let C=s.naturalWidth,I=s.naturalHeight,k=Math.max(y.width/C,y.height/I),D=1,R=0,$=0,A=!1,_=0,P=0,q=0,V=0,ie=()=>{let j=k*D,ke=Math.max(0,(C*j-y.width)/2),Fe=Math.max(0,(I*j-y.height)/2);R=Math.min(ke,Math.max(-ke,R)),$=Math.min(Fe,Math.max(-Fe,$))},ae=()=>{let j=k*D;B.clearRect(0,0,y.width,y.height);let ke=y.width/2-C*j/2+R,Fe=y.height/2-I*j/2+$;if(B.drawImage(s,ke,Fe,C*j,I*j),M.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Ge=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),Qn=v.width/2-o.naturalWidth*Ge/2,pt=v.height/2-o.naturalHeight*Ge/2;M.drawImage(o,Qn,pt,o.naturalWidth*Ge,o.naturalHeight*Ge)}else M.fillStyle="rgba(255, 255, 255, 0.04)",M.fillRect(0,0,v.width,v.height),M.strokeStyle="rgba(255, 255, 255, 0.08)",M.strokeRect(4,4,v.width-8,v.height-8);let dt=v.width/y.width*(k*D),Ue=R*(v.width/y.width),Nt=$*(v.height/y.height),Jn=v.width/2-C*dt/2+Ue,Zn=v.height/2-I*dt/2+Nt;M.save(),M.globalAlpha=.7,M.drawImage(s,Jn,Zn,C*dt,I*dt),M.restore()},Ea=()=>{R=0,$=0,ie(),ae()};x.addEventListener("input",()=>{D=Number(x.value),E.textContent=`${D.toFixed(2)}\xD7`,ie(),ae()}),y.addEventListener("pointerdown",j=>{A=!0,_=j.clientX,P=j.clientY,q=R,V=$,y.setPointerCapture(j.pointerId)}),y.addEventListener("pointermove",j=>{A&&(R=q+(j.clientX-_),$=V+(j.clientY-P),ie(),ae())}),y.addEventListener("pointerup",j=>{A=!1,y.releasePointerCapture(j.pointerId)}),y.addEventListener("pointerleave",()=>{A=!1});let Kn=()=>{c.remove()},Xn=()=>{Kn(),l(null)},Ps=async()=>{let j=document.createElement("canvas");j.width=t.width,j.height=t.height;let ke=j.getContext("2d");if(!ke){Kn(),l(null);return}let Fe=D,Ue=Math.max(j.width/C,j.height/I)*Fe,Nt=j.width/y.width,Jn=R*Nt,Zn=$*Nt,Ge=j.width/2-C*Ue/2+Jn,Qn=j.height/2-I*Ue/2+Zn;ke.drawImage(s,Ge,Qn,C*Ue,I*Ue);let pt=await new Promise(Ms=>{j.toBlob(ks=>Ms(ks),e.type||"image/png")});if(Kn(),!pt){l(null);return}l(new File([pt],e.name,{type:pt.type}))};w==null||w.addEventListener("click",Xn),T==null||T.addEventListener("click",Xn),O==null||O.addEventListener("click",Ea),S==null||S.addEventListener("click",()=>{Ps()}),c.addEventListener("click",j=>{j.target===c&&Xn()}),document.body.appendChild(c),Ea()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let a=await this.loadImage(n);if(a)return a}return null}};var On=class{constructor(){this.root=null;this.options=null}render(){return`
929
929
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
930
930
  <div class="scene-panel-header" data-panel-handle>
931
931
  <div class="panel-title">
@@ -991,10 +991,10 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
991
991
  </div>
992
992
  </div>
993
993
  </div>
994
- `}initialize(e,t){var y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let a=(()=>{var _;let A=window.getEditableEngineConfig;if(typeof A=="function"){let P=A();return(_=P==null?void 0:P.loading)!=null?_:{}}return{}})(),s=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");s&&(s.value=a.type==="image"?"image":"color",s.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{type:s.value}),this.updateFieldVisibility(s.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=a.background_color||"#160a17",r.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{background_color:r.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(E=this.root)==null?void 0:E.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((w=a.overlay_alpha)!=null?w:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var _,P;let A=Number(o.value);l&&(l.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{overlay_alpha:A})}));let c=(T=this.root)==null?void 0:T.querySelector("#loading-text");c&&(c.value=a.text||"",c.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{text:c.value})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-text-scale"),d=(O=this.root)==null?void 0:O.querySelector("#loading-text-scale-value");p&&(p.value=String((B=a.text_scale)!=null?B:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var _,P;let A=Number(p.value);d&&(d.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{text_scale:A})}));let u=(M=this.root)==null?void 0:M.querySelector("#loading-enabled");u&&(u.checked=a.enabled!==!1,u.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{enabled:u.checked})}));let g=(C=this.root)==null?void 0:C.querySelector("#loading-blur-enabled");g&&(g.checked=a.blur_enabled!==!1,g.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_enabled:g.checked})}));let h=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),f=(k=this.root)==null?void 0:k.querySelector("#loading-blur-strength-value");h&&(h.value=String((D=a.blur_strength)!=null?D:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var A,_;f&&(f.textContent=h.value),(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_strength:Number(h.value)})}));let m=(R=this.root)==null?void 0:R.querySelector("#loading-show-btn"),b=($=this.root)==null?void 0:$.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onShowLoadingScreen)==null||_.call(A)}),b==null||b.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onHideLoadingScreen)==null||_.call(A)}),this.updateFieldVisibility(a.type==="image"?"image":"color")}updateFieldVisibility(e){var a,s;let t=(a=this.root)==null?void 0:a.querySelector("#loading-color-field"),n=(s=this.root)==null?void 0:s.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 Ct=require("pixi.js");Ke();ee();async function Ns(i,e,t){var n,a;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let s=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${s}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,p=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of p)re[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 d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let h=((a=g.getDisplayObject)==null?void 0:a.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(s){console.error("[LIBRARY] Error applying asset change:",s)}}async function Hs(i,e){var t,n,a;console.log("[LIBRARY] resetAsset called for:",e);try{let s=window.getEditableAssets,r=typeof s=="function"?s():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(m=>m.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),p=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",p);let d=await Ct.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),h=Object.keys(u||{}).filter(m=>m.startsWith(g)||m.includes(g));for(let m of h)re[m]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=u[m])!=null&&n.texture&&(u[m].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let f=window.gameObjectManager;if(f)for(let m of h){let b=f.get(m);if(b){let y=((a=b.getDisplayObject)==null?void 0:a.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(s){console.error("[LIBRARY] Error resetting asset:",s)}}async function Bs(i,e,t,n){var a,s,r,o,l,c,p,d,u,g,h,f,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),E=`/raw/library/${n}/${t}?t=${x}`;console.log("[LIBRARY] Loading texture from:",E);let w=await Ct.Assets.load(E);if(!w){console.error("[LIBRARY] Failed to load texture:",E);return}console.log("[LIBRARY] \u2705 Texture loaded"),re[v]=w,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let T=window.CustomAssets;T!=null&&T[v]&&(T[v].texture=w,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let S=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!S),S){let B=Array.from(((a=S.keys)==null?void 0:a.call(S))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",B);let M=S.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!M),M){let C=((s=M.getDisplayObject)==null?void 0:s.call(M))||M.pixiObject||M.pixi||M,I=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=w,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:k}=await import("pixi.js"),D=C.parent,R=(l=(o=D==null?void 0:D.getChildIndex)==null?void 0:o.call(D,C))!=null?l:0,$={x:C.x,y:C.y},A={x:(p=(c=C.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=C.anchor)==null?void 0:d.y)!=null?u:.5},_={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(m=(f=C.scale)==null?void 0:f.y)!=null?m:1},P=(b=C.alpha)!=null?b:1,q=(y=C.visible)!=null?y:!0,V=new k(w);V.anchor.set(A.x,A.y),V.position.set($.x,$.y),V.scale.set(_.x,_.y),V.alpha=P,V.visible=q,D&&(D.removeChild(C),D.addChildAt(V,R),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),M.pixiObject&&(M.pixiObject=V),M.pixi&&(M.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let k=C.children.find(D=>D.texture);k?(k.texture=w,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let O=`raw/library/${n}/${t}`;Ae({objectId:v,path:"render.asset.path",value:O}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",O)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Fs(i,e,t,n){var a;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let s=e.startsWith("json.")?e.replace("json.",""):e,r=Date.now(),o=`/raw/${t}?t=${r}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}re[s]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+s);let c=window.CustomAssets;c!=null&&c[s]&&(c[s].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+s+" to default"));let p=window.gameObjectManager;if(p){let d=p.get(s);if(d){let u=((a=d.getDisplayObject)==null?void 0:a.call(d))||d.pixiObject||d;u!=null&&u.texture&&(u.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",s))}}Ae({objectId:s,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",s)}catch(s){console.error("[LIBRARY] Error resetting slot asset:",s)}}var _t=require("pixi.js");var Di=require("pixi.js"),_e=()=>window.debugConfig||{},Us=()=>window.resolveAnchorVec2||(i=>({x:.5,y:.5})),Gs=()=>window.resolveScreenAnchorPoint||(()=>new Di.Point),qs=()=>window.resolveScreenRatioPoint||(()=>new Di.Point);function Vs(i){In(i)&&(i.objectDebugRaf||(i.objectDebugRaf=window.requestAnimationFrame(()=>Rn(i))))}function Ws(i){i.objectDebugRaf&&(window.cancelAnimationFrame(i.objectDebugRaf),i.objectDebugRaf=null),Tt(i)}function In(i){return i.isDebugOpen}function Rn(i){var s,r,o;if(!In(i)){i.objectDebugRaf=null;return}i.objectDebugRaf=window.requestAnimationFrame(()=>Rn(i));let e=$i(i);if(!e){Lt(i,null),Tt(i);return}let t=zi(i,e);if(!t){Lt(i,null),Tt(i);return}let n=new _t.Point;(s=t.getGlobalPosition)==null||s.call(t,n);let a=Ni(i,t);Lt(i,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=a==null?void 0:a.x)!=null?r:null,configY:(o=a==null?void 0:a.y)!=null?o:null}),i.highlightObject?Ui(i,t):qi(i),i.highlightAnchor&&a?Gi(i,a):Vi(i)}function $i(i){var a;let e=i.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function zi(i,e){var a,s;let t=window.gameObjectManager,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return n?((s=n.getDisplayObject)==null?void 0:s.call(n))||n.pixiObject||n:null}function Pt(i){let e=i.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Ni(i,e){var r,o;let t=Pt(i);if(!t)return null;let n=(r=t.transform)!=null?r:{},a=Hi(i);if(!a)return null;if(n.position_ratio!=null)return qs()(a.width,a.height,n.position_ratio);let s=(o=n.anchor)!=null?o:"center";return Gs()(a.width,a.height,s)}function Hi(i){var s;let e=(s=i.container)==null?void 0:s.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 a=window.gameApp;return a!=null&&a.renderer?{width:a.renderer.width,height:a.renderer.height}:null}function Bi(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectBoundsGfx&&i.objectBoundsGfx.parent!==e.stage&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectBoundsGfx||(i.objectBoundsGfx=new _t.Graphics,i.objectBoundsGfx.zIndex=999999,e.stage.addChild(i.objectBoundsGfx)),i.objectBoundsGfx):null}function Fi(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectAnchorGfx&&i.objectAnchorGfx.parent!==e.stage&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null),i.objectAnchorGfx||(i.objectAnchorGfx=new _t.Graphics,i.objectAnchorGfx.zIndex=1e6,e.stage.addChild(i.objectAnchorGfx)),i.objectAnchorGfx):null}function Ui(i,e){var a;let t=Bi(i);if(!t)return;let n=(a=e.getBounds)==null?void 0:a.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Gi(i,e){let t=Fi(i);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 qi(i){i.objectBoundsGfx&&i.objectBoundsGfx.clear()}function Vi(i){i.objectAnchorGfx&&i.objectAnchorGfx.clear()}function Tt(i){i.objectBoundsGfx&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectAnchorGfx&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null)}function Lt(i,e){i.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Ys(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function Ks(i,e,t){var r;let n=e.split("."),a=n.pop(),s=i;for(let o of n)s[o]=(r=s[o])!=null?r:{},s=s[o];s[a]=t}function Wi(i){var n,a,s,r,o;if(!i)return!1;if((n=i.transform)!=null&&n.offset)return!0;let e=((s=(a=i.identity)==null?void 0:a.category)!=null?s:"").toString().toLowerCase(),t=((o=(r=i.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function Dn(i){let e=_e();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 Xs(i){window.location.reload()}function $n(i){let e=JSON.stringify(_e(),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 Js(i,e){var t,n,a;if(!(!i.configViewer||!i.container))try{let s=window.getEditableObjectConfig,r=typeof s=="function"?s(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(dn(),ws)),d=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!d)return;let u=await l(d.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),jn(i,u),(n=i.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),jn(i,r),(a=i.configViewer)==null||a.style.setProperty("display","block");return}catch(s){console.error("[DEBUG] Failed to load object config:",s)}}function jn(i,e){var d,u,g,h,f,m,b,y,v,x;if(!i.container)return;let t=i.container.querySelector("#config-pos-x"),n=i.container.querySelector("#config-pos-y"),a=i.container.querySelector("#config-scale"),s=i.container.querySelector("#config-anchor-x"),r=i.container.querySelector("#config-anchor-y"),l=Wi(e)?(d=e.transform)==null?void 0:d.offset:(u=e.transform)==null?void 0:u.position;t&&(t.value=String((g=l==null?void 0:l.x)!=null?g:0)),n&&(n.value=String((h=l==null?void 0:l.y)!=null?h:0)),a&&(a.value=String((m=(f=e.transform)==null?void 0:f.scale)!=null?m:1));let c=(x=(v=(b=e.transform)==null?void 0:b.anchor)!=null?v:(y=e.render)==null?void 0:y.anchor)!=null?x:{x:.5,y:.5},p=Us()(c);s&&(s.value=String(p.x)),r&&(r.value=String(p.y))}function Zs(i){var l,c,p,d,u,g,h,f,m,b;let e=i.selectedObjectId;if(!e||!i.container)return;let t=(c=(l=i.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(d=(p=i.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",a=(g=(u=i.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",s=(f=(h=i.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",r=(b=(m=i.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
994
+ `}initialize(e,t){var y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let a=(()=>{var _;let A=window.getEditableEngineConfig;if(typeof A=="function"){let P=A();return(_=P==null?void 0:P.loading)!=null?_:{}}return{}})(),r=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");r&&(r.value=a.type==="image"?"image":"color",r.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{type:r.value}),this.updateFieldVisibility(r.value)}));let s=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");s&&(s.value=a.background_color||"#160a17",s.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{background_color:s.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(E=this.root)==null?void 0:E.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((w=a.overlay_alpha)!=null?w:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var _,P;let A=Number(o.value);l&&(l.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{overlay_alpha:A})}));let c=(T=this.root)==null?void 0:T.querySelector("#loading-text");c&&(c.value=a.text||"",c.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{text:c.value})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-text-scale"),d=(O=this.root)==null?void 0:O.querySelector("#loading-text-scale-value");p&&(p.value=String((B=a.text_scale)!=null?B:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var _,P;let A=Number(p.value);d&&(d.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{text_scale:A})}));let u=(M=this.root)==null?void 0:M.querySelector("#loading-enabled");u&&(u.checked=a.enabled!==!1,u.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{enabled:u.checked})}));let g=(C=this.root)==null?void 0:C.querySelector("#loading-blur-enabled");g&&(g.checked=a.blur_enabled!==!1,g.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_enabled:g.checked})}));let h=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),f=(k=this.root)==null?void 0:k.querySelector("#loading-blur-strength-value");h&&(h.value=String((D=a.blur_strength)!=null?D:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var A,_;f&&(f.textContent=h.value),(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_strength:Number(h.value)})}));let m=(R=this.root)==null?void 0:R.querySelector("#loading-show-btn"),b=($=this.root)==null?void 0:$.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onShowLoadingScreen)==null||_.call(A)}),b==null||b.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onHideLoadingScreen)==null||_.call(A)}),this.updateFieldVisibility(a.type==="image"?"image":"color")}updateFieldVisibility(e){var a,r;let t=(a=this.root)==null?void 0:a.querySelector("#loading-color-field"),n=(r=this.root)==null?void 0:r.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 Ct=require("pixi.js");Ke();ee();async function Nr(i,e,t){var n,a;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let r=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${r}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,p=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of p)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 d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let h=((a=g.getDisplayObject)==null?void 0:a.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(r){console.error("[LIBRARY] Error applying asset change:",r)}}async function Hr(i,e){var t,n,a;console.log("[LIBRARY] resetAsset called for:",e);try{let r=window.getEditableAssets,s=typeof r=="function"?r():null,o=(t=s==null?void 0:s.slots)==null?void 0:t.find(m=>m.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),p=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",p);let d=await Ct.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),h=Object.keys(u||{}).filter(m=>m.startsWith(g)||m.includes(g));for(let m of h)se[m]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=u[m])!=null&&n.texture&&(u[m].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let f=window.gameObjectManager;if(f)for(let m of h){let b=f.get(m);if(b){let y=((a=b.getDisplayObject)==null?void 0:a.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(r){console.error("[LIBRARY] Error resetting asset:",r)}}async function Br(i,e,t,n){var a,r,s,o,l,c,p,d,u,g,h,f,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),E=`/raw/library/${n}/${t}?t=${x}`;console.log("[LIBRARY] Loading texture from:",E);let w=await Ct.Assets.load(E);if(!w){console.error("[LIBRARY] Failed to load texture:",E);return}console.log("[LIBRARY] \u2705 Texture loaded"),se[v]=w,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let T=window.CustomAssets;T!=null&&T[v]&&(T[v].texture=w,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let S=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!S),S){let B=Array.from(((a=S.keys)==null?void 0:a.call(S))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",B);let M=S.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!M),M){let C=((r=M.getDisplayObject)==null?void 0:r.call(M))||M.pixiObject||M.pixi||M,I=(s=C==null?void 0:C.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=w,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:k}=await import("pixi.js"),D=C.parent,R=(l=(o=D==null?void 0:D.getChildIndex)==null?void 0:o.call(D,C))!=null?l:0,$={x:C.x,y:C.y},A={x:(p=(c=C.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=C.anchor)==null?void 0:d.y)!=null?u:.5},_={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(m=(f=C.scale)==null?void 0:f.y)!=null?m:1},P=(b=C.alpha)!=null?b:1,q=(y=C.visible)!=null?y:!0,V=new k(w);V.anchor.set(A.x,A.y),V.position.set($.x,$.y),V.scale.set(_.x,_.y),V.alpha=P,V.visible=q,D&&(D.removeChild(C),D.addChildAt(V,R),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),M.pixiObject&&(M.pixiObject=V),M.pixi&&(M.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let k=C.children.find(D=>D.texture);k?(k.texture=w,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let O=`raw/library/${n}/${t}`;Ae({objectId:v,path:"render.asset.path",value:O}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",O)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Fr(i,e,t,n){var a;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let r=e.startsWith("json.")?e.replace("json.",""):e,s=Date.now(),o=`/raw/${t}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}se[r]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+r);let c=window.CustomAssets;c!=null&&c[r]&&(c[r].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+r+" to default"));let p=window.gameObjectManager;if(p){let d=p.get(r);if(d){let u=((a=d.getDisplayObject)==null?void 0:a.call(d))||d.pixiObject||d;u!=null&&u.texture&&(u.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",r))}}Ae({objectId:r,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",r)}catch(r){console.error("[LIBRARY] Error resetting slot asset:",r)}}var _t=require("pixi.js");var Di=require("pixi.js"),_e=()=>window.debugConfig||{},Ur=()=>window.resolveAnchorVec2||(i=>({x:.5,y:.5})),Gr=()=>window.resolveScreenAnchorPoint||(()=>new Di.Point),qr=()=>window.resolveScreenRatioPoint||(()=>new Di.Point);function Vr(i){In(i)&&(i.objectDebugRaf||(i.objectDebugRaf=window.requestAnimationFrame(()=>Rn(i))))}function Wr(i){i.objectDebugRaf&&(window.cancelAnimationFrame(i.objectDebugRaf),i.objectDebugRaf=null),Tt(i)}function In(i){return i.isDebugOpen}function Rn(i){var r,s,o;if(!In(i)){i.objectDebugRaf=null;return}i.objectDebugRaf=window.requestAnimationFrame(()=>Rn(i));let e=$i(i);if(!e){Lt(i,null),Tt(i);return}let t=zi(i,e);if(!t){Lt(i,null),Tt(i);return}let n=new _t.Point;(r=t.getGlobalPosition)==null||r.call(t,n);let a=Ni(i,t);Lt(i,{instanceId:e,worldX:n.x,worldY:n.y,configX:(s=a==null?void 0:a.x)!=null?s:null,configY:(o=a==null?void 0:a.y)!=null?o:null}),i.highlightObject?Ui(i,t):qi(i),i.highlightAnchor&&a?Gi(i,a):Vi(i)}function $i(i){var a;let e=i.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function zi(i,e){var a,r;let t=window.gameObjectManager,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return n?((r=n.getDisplayObject)==null?void 0:r.call(n))||n.pixiObject||n:null}function Pt(i){let e=i.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Ni(i,e){var s,o;let t=Pt(i);if(!t)return null;let n=(s=t.transform)!=null?s:{},a=Hi(i);if(!a)return null;if(n.position_ratio!=null)return qr()(a.width,a.height,n.position_ratio);let r=(o=n.anchor)!=null?o:"center";return Gr()(a.width,a.height,r)}function Hi(i){var r;let e=(r=i.container)==null?void 0:r.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 a=window.gameApp;return a!=null&&a.renderer?{width:a.renderer.width,height:a.renderer.height}:null}function Bi(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectBoundsGfx&&i.objectBoundsGfx.parent!==e.stage&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectBoundsGfx||(i.objectBoundsGfx=new _t.Graphics,i.objectBoundsGfx.zIndex=999999,e.stage.addChild(i.objectBoundsGfx)),i.objectBoundsGfx):null}function Fi(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectAnchorGfx&&i.objectAnchorGfx.parent!==e.stage&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null),i.objectAnchorGfx||(i.objectAnchorGfx=new _t.Graphics,i.objectAnchorGfx.zIndex=1e6,e.stage.addChild(i.objectAnchorGfx)),i.objectAnchorGfx):null}function Ui(i,e){var a;let t=Bi(i);if(!t)return;let n=(a=e.getBounds)==null?void 0:a.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Gi(i,e){let t=Fi(i);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 qi(i){i.objectBoundsGfx&&i.objectBoundsGfx.clear()}function Vi(i){i.objectAnchorGfx&&i.objectAnchorGfx.clear()}function Tt(i){i.objectBoundsGfx&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectAnchorGfx&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null)}function Lt(i,e){i.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Yr(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function Kr(i,e,t){var s;let n=e.split("."),a=n.pop(),r=i;for(let o of n)r[o]=(s=r[o])!=null?s:{},r=r[o];r[a]=t}function Wi(i){var n,a,r,s,o;if(!i)return!1;if((n=i.transform)!=null&&n.offset)return!0;let e=((r=(a=i.identity)==null?void 0:a.category)!=null?r:"").toString().toLowerCase(),t=((o=(s=i.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function Dn(i){let e=_e();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 Xr(i){window.location.reload()}function $n(i){let e=JSON.stringify(_e(),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 Jr(i,e){var t,n,a;if(!(!i.configViewer||!i.container))try{let r=window.getEditableObjectConfig,s=typeof r=="function"?r(e):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(dn(),wr)),d=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!d)return;let u=await l(d.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),jn(i,u),(n=i.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,s),jn(i,s),(a=i.configViewer)==null||a.style.setProperty("display","block");return}catch(r){console.error("[DEBUG] Failed to load object config:",r)}}function jn(i,e){var d,u,g,h,f,m,b,y,v,x;if(!i.container)return;let t=i.container.querySelector("#config-pos-x"),n=i.container.querySelector("#config-pos-y"),a=i.container.querySelector("#config-scale"),r=i.container.querySelector("#config-anchor-x"),s=i.container.querySelector("#config-anchor-y"),l=Wi(e)?(d=e.transform)==null?void 0:d.offset:(u=e.transform)==null?void 0:u.position;t&&(t.value=String((g=l==null?void 0:l.x)!=null?g:0)),n&&(n.value=String((h=l==null?void 0:l.y)!=null?h:0)),a&&(a.value=String((m=(f=e.transform)==null?void 0:f.scale)!=null?m:1));let c=(x=(v=(b=e.transform)==null?void 0:b.anchor)!=null?v:(y=e.render)==null?void 0:y.anchor)!=null?x:{x:.5,y:.5},p=Ur()(c);r&&(r.value=String(p.x)),s&&(s.value=String(p.y))}function Zr(i){var l,c,p,d,u,g,h,f,m,b;let e=i.selectedObjectId;if(!e||!i.container)return;let t=(c=(l=i.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(d=(p=i.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",a=(g=(u=i.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",r=(f=(h=i.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",s=(b=(m=i.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
995
995
  position: (${t}, ${n})
996
996
  scale: ${a}
997
- anchor: (${s}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function Yi(i,e){var d,u,g,h,f,m,b,y,v,x,E;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!i.container)return;let t=i.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((u=(d=i.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),a=Number((h=(g=i.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?h:0),s=Number((m=(f=i.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?m:1),r=Number((y=(b=i.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((x=(v=i.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:a,scale:s,anchorX:r,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(ee(),sn));l({objectId:t,path:"transform.position",value:{x:n,y:a}},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.scale",value:s},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.anchor",value:{x:r,y:o}},{silent:e==null?void 0:e.silent});let c=Pt(i);Wi(c)&&l({objectId:t,path:"transform.offset",value:{x:n,y:a}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let w=(E=window.getEditableObjectConfig)==null?void 0:E.call(window,t);w?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,w)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function Qs(i,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),sn));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 a=window.applyEditableEngineConfig;if(typeof a=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),h=c;for(let f=0;f<g.length-1;f++){let m=g[f];h[m]=(u=h[m])!=null?u:{},h=h[m]}h[g[g.length-1]]=d}else c[p]=d}),l.ui=c,a({runtime:l,assets:e.assets})}let s=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!s,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function er(i){i.selectedObjectId&&(i.objectAutoApplyTimer&&window.clearTimeout(i.objectAutoApplyTimer),i.objectAutoApplyTimer=window.setTimeout(()=>{i.objectAutoApplyTimer=null,Yi(i,{silent:!0})},150))}var Uo=3e3;function tr(i,e,t){let n=t!=null?t:i.offsetParent;if(!n)return;e.style.cursor="move";let a=0,s=0,r=0,o=0,l=!1,c=d=>{if(!l)return;let u=d.clientX-a,g=d.clientY-s;i.style.left=`${r+u}px`,i.style.top=`${o+g}px`},p=()=>{l&&(l=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",d=>{if(d.button!==0)return;let u=d.target;if(u!=null&&u.closest("button, input, select, textarea"))return;d.preventDefault();let g=i.getBoundingClientRect(),h=n.getBoundingClientRect();r=Math.max(0,g.left-h.left),o=Math.max(0,g.top-h.top);let f=g.width,m=g.height,b=h.width,y=h.height;r=Math.min(r,b-f),o=Math.min(o,y-m),a=d.clientX,s=d.clientY,i.style.left=`${r}px`,i.style.top=`${o}px`,i.style.right="auto",i.style.bottom="auto",i.style.zIndex=String(++Uo);let v=i.getBoundingClientRect();(v.left<0||v.top<0||v.right>window.innerWidth||v.bottom>window.innerHeight)&&(i.style.left="16px",i.style.top="72px",i.style.right="auto",i.style.bottom="auto"),l=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",p)})}function nr(i,e,t){e.style.cursor="nwse-resize";let n=0,a=0,s=0,r=0,o=!1,l=p=>{if(!o)return;let d=p.clientX-s,u=p.clientY-r,g=Math.max(100,n+d),h=Math.max(100,a+u);i.style.width=`${g}px`,i.style.height=`${h}px`,t==null||t(g,h)},c=()=>{o&&(o=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c))};e.addEventListener("pointerdown",p=>{if(p.button!==0)return;p.preventDefault(),p.stopPropagation();let d=i.getBoundingClientRect();n=d.width,a=d.height,s=p.clientX,r=p.clientY,o=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",c)})}function Ki(i,e){var f,m,b;let t=(b=(m=(f=i.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:i.debugOverlay)!=null?b:e.offsetParent;if(!t)return;let n=t.getBoundingClientRect(),a=e.getBoundingClientRect(),s=12,r=Math.max(250,Math.floor(n.width-s*2)),o=Math.max(200,Math.floor(n.height-s*2));a.width>r&&(e.style.width=`${r}px`),a.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,p=l.top-n.top,d=Math.max(s,n.width-l.width-s),u=Math.max(s,n.height-l.height-s),g=Math.min(Math.max(c,s),d),h=Math.min(Math.max(p,s),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function Ne(i){if(!i.container)return;let e=i.container.querySelector("#debug-workbench");if(!e)return;Ki(i,e);let t={activeTab:i.activeTab,width:e.style.width,height:e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function zn(i){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(i.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var a;let n=(a=i.container)==null?void 0:a.querySelector("#debug-workbench");n&&(t.width&&(n.style.width=t.width),t.height&&(n.style.height=t.height),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Ki(i,n))})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function ir(i,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",Ki(i,e),Ne(i))}function ar(i){var a,s,r;if(!i.container)return;let e=i.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=i.toggleDebug)==null||o.call(i)}),(a=e.querySelector("#debug-close"))==null||a.addEventListener("click",()=>{var o;return(o=i.toggleDebug)==null?void 0:o.call(i,!1)}),(s=e.querySelector("#debug-reset"))==null||s.addEventListener("click",()=>Dn(i)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>$n(i)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;i.activeTab=l,Xi(i),Ne(i)})}),Zi(i,e),Ji(i,e)}function Xi(i){if(!i.container)return;let e=i.container;e.querySelectorAll(".workbench-tab").forEach(a=>{let s=a.dataset.tab;a.classList.toggle("active",s===i.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(a=>{let s=a.dataset.tabPanel;a.classList.toggle("active",s===i.activeTab)})}function Ji(i,e){te(i,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),te(i,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),te(i,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),te(i,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),te(i,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),te(i,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),te(i,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),te(i,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),te(i,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let a=_e();a.layout&&(a.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let a=n.value.replace("#",""),s=parseInt(a,16),r=_e();r.layout&&(r.layout.debug_rect_color=Number.isFinite(s)?s:16711680)})}function sr(i){if(!i.container||!i.debugOverlay)return;let e=i.container.querySelector("#debug-workbench"),t=i.container.querySelector("#workbench-handle"),n=i.container.querySelector("#workbench-resize");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),tr(e,t,i.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{Ne(i),ir(i,e)},10)})),e&&n&&nr(e,n,()=>Ne(i)),zn(i)}function Zi(i,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let a=n.closest(".scene-panel");a&&a.classList.toggle("collapsed")})})}function te(i,e,t,n,a){let s=e.querySelector(`#${t}`),r=e.querySelector(a);if(!s||!r)return;let o=Ys(_e(),n);typeof o=="number"&&(s.value=String(o),r.textContent=String(o)),s.addEventListener("input",()=>{let l=Number(s.value);r.textContent=String(l),Ks(_e(),n,l)})}ee();var Nn=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}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=nn(),{hasChanges:t,overrideCount:n,overrides:a}=e,s={};for(let l of a){let c=l.objectId||"Engine";s[c]||(s[c]=[]),s[c].push(l)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never";return`
997
+ anchor: (${r}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function Yi(i,e){var d,u,g,h,f,m,b,y,v,x,E;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!i.container)return;let t=i.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((u=(d=i.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),a=Number((h=(g=i.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?h:0),r=Number((m=(f=i.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?m:1),s=Number((y=(b=i.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((x=(v=i.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:a,scale:r,anchorX:s,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(ee(),rn));l({objectId:t,path:"transform.position",value:{x:n,y:a}},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.scale",value:r},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.anchor",value:{x:s,y:o}},{silent:e==null?void 0:e.silent});let c=Pt(i);Wi(c)&&l({objectId:t,path:"transform.offset",value:{x:n,y:a}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let w=(E=window.getEditableObjectConfig)==null?void 0:E.call(window,t);w?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,w)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function Qr(i,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),rn));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 a=window.applyEditableEngineConfig;if(typeof a=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),h=c;for(let f=0;f<g.length-1;f++){let m=g[f];h[m]=(u=h[m])!=null?u:{},h=h[m]}h[g[g.length-1]]=d}else c[p]=d}),l.ui=c,a({runtime:l,assets:e.assets})}let r=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),s=(t==null?void 0:t.source)!=="auto"&&!r,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function es(i){i.selectedObjectId&&(i.objectAutoApplyTimer&&window.clearTimeout(i.objectAutoApplyTimer),i.objectAutoApplyTimer=window.setTimeout(()=>{i.objectAutoApplyTimer=null,Yi(i,{silent:!0})},150))}var Uo=3e3;function ts(i,e,t){let n=t!=null?t:i.offsetParent;if(!n)return;e.style.cursor="move";let a=0,r=0,s=0,o=0,l=!1,c=d=>{if(!l)return;let u=d.clientX-a,g=d.clientY-r;i.style.left=`${s+u}px`,i.style.top=`${o+g}px`},p=()=>{l&&(l=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",d=>{if(d.button!==0)return;let u=d.target;if(u!=null&&u.closest("button, input, select, textarea"))return;d.preventDefault();let g=i.getBoundingClientRect(),h=n.getBoundingClientRect();s=Math.max(0,g.left-h.left),o=Math.max(0,g.top-h.top);let f=g.width,m=g.height,b=h.width,y=h.height;s=Math.min(s,b-f),o=Math.min(o,y-m),a=d.clientX,r=d.clientY,i.style.left=`${s}px`,i.style.top=`${o}px`,i.style.right="auto",i.style.bottom="auto",i.style.zIndex=String(++Uo);let v=i.getBoundingClientRect();(v.left<0||v.top<0||v.right>window.innerWidth||v.bottom>window.innerHeight)&&(i.style.left="16px",i.style.top="72px",i.style.right="auto",i.style.bottom="auto"),l=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",p)})}function ns(i,e,t){e.style.cursor="nwse-resize";let n=0,a=0,r=0,s=0,o=!1,l=p=>{if(!o)return;let d=p.clientX-r,u=p.clientY-s,g=Math.max(100,n+d),h=Math.max(100,a+u);i.style.width=`${g}px`,i.style.height=`${h}px`,t==null||t(g,h)},c=()=>{o&&(o=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c))};e.addEventListener("pointerdown",p=>{if(p.button!==0)return;p.preventDefault(),p.stopPropagation();let d=i.getBoundingClientRect();n=d.width,a=d.height,r=p.clientX,s=p.clientY,o=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",c)})}function Ki(i,e){var f,m,b;let t=(b=(m=(f=i.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:i.debugOverlay)!=null?b:e.offsetParent;if(!t)return;let n=t.getBoundingClientRect(),a=e.getBoundingClientRect(),r=12,s=Math.max(250,Math.floor(n.width-r*2)),o=Math.max(200,Math.floor(n.height-r*2));a.width>s&&(e.style.width=`${s}px`),a.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,p=l.top-n.top,d=Math.max(r,n.width-l.width-r),u=Math.max(r,n.height-l.height-r),g=Math.min(Math.max(c,r),d),h=Math.min(Math.max(p,r),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function Ne(i){if(!i.container)return;let e=i.container.querySelector("#debug-workbench");if(!e)return;Ki(i,e);let t={activeTab:i.activeTab,width:e.style.width,height:e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function zn(i){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(i.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var a;let n=(a=i.container)==null?void 0:a.querySelector("#debug-workbench");n&&(t.width&&(n.style.width=t.width),t.height&&(n.style.height=t.height),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Ki(i,n))})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function is(i,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",Ki(i,e),Ne(i))}function as(i){var a,r,s;if(!i.container)return;let e=i.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=i.toggleDebug)==null||o.call(i)}),(a=e.querySelector("#debug-close"))==null||a.addEventListener("click",()=>{var o;return(o=i.toggleDebug)==null?void 0:o.call(i,!1)}),(r=e.querySelector("#debug-reset"))==null||r.addEventListener("click",()=>Dn(i)),(s=e.querySelector("#debug-export"))==null||s.addEventListener("click",()=>$n(i)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;i.activeTab=l,Xi(i),Ne(i)})}),Zi(i,e),Ji(i,e)}function Xi(i){if(!i.container)return;let e=i.container;e.querySelectorAll(".workbench-tab").forEach(a=>{let r=a.dataset.tab;a.classList.toggle("active",r===i.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(a=>{let r=a.dataset.tabPanel;a.classList.toggle("active",r===i.activeTab)})}function Ji(i,e){te(i,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),te(i,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),te(i,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),te(i,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),te(i,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),te(i,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),te(i,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),te(i,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),te(i,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let a=_e();a.layout&&(a.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let a=n.value.replace("#",""),r=parseInt(a,16),s=_e();s.layout&&(s.layout.debug_rect_color=Number.isFinite(r)?r:16711680)})}function rs(i){if(!i.container||!i.debugOverlay)return;let e=i.container.querySelector("#debug-workbench"),t=i.container.querySelector("#workbench-handle"),n=i.container.querySelector("#workbench-resize");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),ts(e,t,i.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{Ne(i),is(i,e)},10)})),e&&n&&ns(e,n,()=>Ne(i)),zn(i)}function Zi(i,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let a=n.closest(".scene-panel");a&&a.classList.toggle("collapsed")})})}function te(i,e,t,n,a){let r=e.querySelector(`#${t}`),s=e.querySelector(a);if(!r||!s)return;let o=Yr(_e(),n);typeof o=="number"&&(r.value=String(o),s.textContent=String(o)),r.addEventListener("input",()=>{let l=Number(r.value);s.textContent=String(l),Kr(_e(),n,l)})}ee();var Nn=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}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=nn(),{hasChanges:t,overrideCount:n,overrides:a}=e,r={};for(let l of a){let c=l.objectId||"Engine";r[c]||(r[c]=[]),r[c].push(l)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never";return`
998
998
  <div class="config-persistence-panel">
999
999
  <div class="persistence-status-bar ${t?"has-changes":"no-changes"}">
1000
1000
  ${t?`
@@ -1066,7 +1066,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
1066
1066
  <button class="staging-clear-all" id="clear-all-overrides">Discard All</button>
1067
1067
  </div>
1068
1068
  <div class="staging-list">
1069
- ${Object.entries(s).map(([l,c])=>`
1069
+ ${Object.entries(r).map(([l,c])=>`
1070
1070
  <div class="staging-group">
1071
1071
  <div class="staging-group-title">
1072
1072
  <span class="group-icon">${l==="Engine"?"\u2699\uFE0F":"\u{1F4E6}"}</span>
@@ -1110,7 +1110,7 @@ Generate the requested asset matching the brand style.${i.needsTransparency?" Ba
1110
1110
  <p><strong>Apply to Project</strong> writes the current preview state to your local .json files in /configs/ folder. This state will be used for the dashboard build.</p>
1111
1111
  </div>
1112
1112
  </div>
1113
- `}formatValue(e){return e===null?"null":typeof e=="string"?e.length>25?e.substring(0,22)+"...":e:typeof e=="object"?"{...}":String(e)}setupEventListeners(){if(!this.container)return;let e=this.container.querySelector("#apply-to-project-btn");e==null||e.addEventListener("click",async()=>{var p;if(!(e.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",d))!=null?p:"").trim();if(!g){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),e.textContent="\u23F3 Writing to disk...",e.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Apply failed:",d),alert(`\u274C Apply failed: ${d.message}`),e.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",e.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let p=c.dataset.removePath,d=c.dataset.removeId;tn(d||void 0,p)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Et()});let a=this.container.querySelector("#reset-to-applied-btn");a==null||a.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Et()});let s=this.container.querySelector("#reset-to-original-btn");s==null||s.addEventListener("click",async()=>{await an()});let r=this.container.querySelector("#version-selector");r==null||r.addEventListener("change",async c=>{let d=c.target.value;await this.switchVersion(d)});let o=this.container.querySelector("#create-version-btn");o==null||o.addEventListener("click",async()=>{var p;if(!(o.getAttribute("disabled")!==null||!confirm("This will create a new version snapshot and save your changes. Continue?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name (e.g. v1, test_2024):",d))!=null?p:"").trim();if(!g){alert("Version name is required. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),o.textContent="\u23F3 Creating version...",o.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),await this.loadVersionsList(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Create version failed:",d),alert(`\u274C Failed to create version: ${d.message}`),o.textContent="\u{1F4DD} Create New Version",o.removeAttribute("disabled")}});let l=this.container.querySelector("#direct-apply-btn");l==null||l.addEventListener("click",async()=>{await this.directApply()})}showSuccessNotification(){let e=document.createElement("div");e.className="persistence-notification success",e.innerHTML=`
1113
+ `}formatValue(e){return e===null?"null":typeof e=="string"?e.length>25?e.substring(0,22)+"...":e:typeof e=="object"?"{...}":String(e)}setupEventListeners(){if(!this.container)return;let e=this.container.querySelector("#apply-to-project-btn");e==null||e.addEventListener("click",async()=>{var p;if(!(e.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",d))!=null?p:"").trim();if(!g){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),e.textContent="\u23F3 Writing to disk...",e.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Apply failed:",d),alert(`\u274C Apply failed: ${d.message}`),e.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",e.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let p=c.dataset.removePath,d=c.dataset.removeId;tn(d||void 0,p)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Et()});let a=this.container.querySelector("#reset-to-applied-btn");a==null||a.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Et()});let r=this.container.querySelector("#reset-to-original-btn");r==null||r.addEventListener("click",async()=>{await an()});let s=this.container.querySelector("#version-selector");s==null||s.addEventListener("change",async c=>{let d=c.target.value;await this.switchVersion(d)});let o=this.container.querySelector("#create-version-btn");o==null||o.addEventListener("click",async()=>{var p;if(!(o.getAttribute("disabled")!==null||!confirm("This will create a new version snapshot and save your changes. Continue?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name (e.g. v1, test_2024):",d))!=null?p:"").trim();if(!g){alert("Version name is required. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),o.textContent="\u23F3 Creating version...",o.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),await this.loadVersionsList(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Create version failed:",d),alert(`\u274C Failed to create version: ${d.message}`),o.textContent="\u{1F4DD} Create New Version",o.removeAttribute("disabled")}});let l=this.container.querySelector("#direct-apply-btn");l==null||l.addEventListener("click",async()=>{await this.directApply()})}showSuccessNotification(){let e=document.createElement("div");e.className="persistence-notification success",e.innerHTML=`
1114
1114
  <div class="notify-icon">\u2705</div>
1115
1115
  <div class="notify-content">
1116
1116
  <strong>Changes Applied!</strong>
@@ -1124,7 +1124,7 @@ This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snaps
1124
1124
 
1125
1125
  This cannot be undone unless you have git commits or backups.
1126
1126
 
1127
- Are you absolutely sure?`))try{let t=xt(),n={};for(let[s,r]of Object.entries(t.objects)){let o=r,l=s;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${s}`),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[s,r]of Object.entries(t.scenes)){let o=s.startsWith("scene.")?s:`scene.${s}`;n[`scenes/${o}.json`]=r}let a=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!a.ok){let s=await a.json();throw new Error(s.error||"Direct apply failed")}Ce(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Mt=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 un;this.sceneToolsPanel=new gn;this.nudgePanel=new fn;this.inspectorPanel=new Tn;this.libraryPanel=new hn;this.brandVisionPanel=new Mn;this.customizeSettingsPanel=new kn;this.configPersistencePanel=new Nn;this.loadingScreenPanel=new On}applyAssetChange(e,t){return Ns(this,e,t)}resetAsset(e){return Hs(this,e)}applySlotAsset(e,t,n){return Bs(this,e,t,n)}resetSlotAsset(e,t,n){return Fs(this,e,t,n)}startObjectVisuals(){return Vs(this)}stopObjectVisuals(){return Ws(this)}shouldRunObjectVisuals(){return In(this)}updateObjectVisuals(){return Rn(this)}getSelectedInstanceId(){return $i(this)}getDisplayObjectById(e){return zi(this,e)}getSelectedObjectConfig(){return Pt(this)}getConfigAnchorWorldPoint(e){return Ni(this,e)}getScreenSize(){return Hi(this)}ensureBoundsGfx(){return Bi(this)}ensureAnchorGfx(){return Fi(this)}drawBounds(e){return Ui(this,e)}drawAnchor(e){return Gi(this,e)}clearBounds(){return qi(this)}clearAnchor(){return Vi(this)}clearObjectVisuals(){return Tt(this)}updateObjectInfo(e){return Lt(this,e)}resetDebugConfig(){return Dn(this)}applyDebugConfig(){return Xs(this)}exportDebugConfig(){return $n(this)}loadObjectConfig(e){return Js(this,e)}fillConfigViewer(e){return jn(this,e)}copyConfigValues(){return Zs(this)}applyObjectConfig(e){return Yi(this,e)}applyCustomizeSettings(e,t){return Qs(this,e,t)}scheduleObjectAutoApply(){return er(this)}setupDebugEventListeners(){return ar(this)}setupDebugInputListeners(e){return Ji(this,e)}setupPanelLayout(){return sr(this)}setupCollapsiblePanels(e){return Zi(this,e)}setupRangeInput(e,t,n,a){return te(this,e,t,n,a)}updateWorkbenchTabs(){return Xi(this)}saveWorkbenchState(){return Ne(this)}loadWorkbenchState(){return zn(this)}initialize(e){var s;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let r=localStorage.getItem("preview_workbench_state");if(r){let o=JSON.parse(r);o.activeTab&&(this.activeTab=o.activeTab)}}catch(r){console.warn("[PREVIEW] Failed to load workbench tab state",r)}this.sceneObjectsPanel.initialize(e,{onSelect:r=>this.handleObjectSelect(r)}),this.libraryPanel.initialize(e,{onApply:(r,o,l)=>this.applySlotAsset(r,o,l),onReset:(r,o,l)=>this.resetSlotAsset(r,o,l)}),this.inspectorPanel.initialize(e,{onPropertyChange:(r,o,l)=>{console.log("[Inspector] Property changed:",r,o,l)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let r="/dashboard";window.location.pathname!==r&&(window.location.href=r)}),this.customizeSettingsPanel.initialize(e,{onApply:(r,o)=>this.applyCustomizeSettings(r,o)});let t=e.querySelector("#scene-tools-container");t&&(t.innerHTML=this.sceneToolsPanel.render());let n=e.querySelector("#nudge-panel-container");n&&(n.innerHTML=this.nudgePanel.render()),this.sceneToolsPanel.initialize(t||e,{onHighlightObject:r=>{this.highlightObject=r,r?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:r=>{this.highlightAnchor=r,r?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(r,o)=>this.nudgeSelectedObject(r,o),onShowSplash:()=>{let r=window;typeof r.__previewShowSplash=="function"&&r.__previewShowSplash()},onUpdateSplash:r=>{let o=window;typeof o.applyEditableEngineConfig=="function"&&o.applyEditableEngineConfig({splash:r})}}),this.nudgePanel.initialize(n||e,{onNudge:(r,o)=>{let l=this.nudgePanel.getNudgeStep();this.nudgeSelectedObject(r*l,o*l)},onScale:r=>{var d,u;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let l=(u=(d=o.render)==null?void 0:d.scale)!=null?u:1,c=Math.max(.1,l+r),p=window;typeof p.applyEditableObjectConfig=="function"&&p.applyEditableObjectConfig(this.selectedObjectId,{render:{...o.render,scale:c}})}});let a=t==null?void 0:t.querySelector("#debug-nudge-enabled");a==null||a.addEventListener("change",()=>{a.checked?this.nudgePanel.show():this.nudgePanel.hide()}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let r=window;typeof r.__previewShowLoading=="function"?r.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let r=window;typeof r.__previewHideLoading=="function"?r.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:r=>{let o=window;typeof o.applyEditableEngineConfig=="function"&&o.applyEditableEngineConfig({loading:r}),typeof o.__previewUpdateLoading=="function"?o.__previewUpdateLoading(r):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(r,o,l,c)=>{this.customizeSettingsPanel.openAiEditor(r,o,l,c)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(s=this.debugOverlay)==null||s.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=r=>this.selectObject(r),window.addEventListener("config:changed",r=>{var o,l;((o=r.detail)==null?void 0:o.action)!=="remove"&&((l=r.detail)==null?void 0:l.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(r,o,l)=>this.applySlotAsset(r,o,l),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var o;let r=window.getActiveConfig;if(typeof r=="function"){let l=r();return((o=l==null?void 0:l.engine)==null?void 0:o.splash)||null}return null},window.addAssetToRegistry=(r,o)=>{let l=window.getEditableAssets;if(typeof l=="function"){let c=l();if(c!=null&&c.libraryAssets&&(c.libraryAssets[r]||(c.libraryAssets[r]=[]),!c.libraryAssets[r].some(d=>d.filename===o))){let d=o.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");c.libraryAssets[r].unshift({filename:o,displayName:d}),console.log(`[DEBUG] Added ${o} to registry category ${r}`)}}}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}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`
1127
+ Are you absolutely sure?`))try{let t=xt(),n={};for(let[r,s]of Object.entries(t.objects)){let o=s,l=r;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${r}`),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[r,s]of Object.entries(t.scenes)){let o=r.startsWith("scene.")?r:`scene.${r}`;n[`scenes/${o}.json`]=s}let a=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!a.ok){let r=await a.json();throw new Error(r.error||"Direct apply failed")}Ce(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Mt=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 un;this.sceneToolsPanel=new gn;this.nudgePanel=new fn;this.inspectorPanel=new Tn;this.libraryPanel=new hn;this.brandVisionPanel=new Mn;this.customizeSettingsPanel=new kn;this.configPersistencePanel=new Nn;this.loadingScreenPanel=new On}applyAssetChange(e,t){return Nr(this,e,t)}resetAsset(e){return Hr(this,e)}applySlotAsset(e,t,n){return Br(this,e,t,n)}resetSlotAsset(e,t,n){return Fr(this,e,t,n)}startObjectVisuals(){return Vr(this)}stopObjectVisuals(){return Wr(this)}shouldRunObjectVisuals(){return In(this)}updateObjectVisuals(){return Rn(this)}getSelectedInstanceId(){return $i(this)}getDisplayObjectById(e){return zi(this,e)}getSelectedObjectConfig(){return Pt(this)}getConfigAnchorWorldPoint(e){return Ni(this,e)}getScreenSize(){return Hi(this)}ensureBoundsGfx(){return Bi(this)}ensureAnchorGfx(){return Fi(this)}drawBounds(e){return Ui(this,e)}drawAnchor(e){return Gi(this,e)}clearBounds(){return qi(this)}clearAnchor(){return Vi(this)}clearObjectVisuals(){return Tt(this)}updateObjectInfo(e){return Lt(this,e)}resetDebugConfig(){return Dn(this)}applyDebugConfig(){return Xr(this)}exportDebugConfig(){return $n(this)}loadObjectConfig(e){return Jr(this,e)}fillConfigViewer(e){return jn(this,e)}copyConfigValues(){return Zr(this)}applyObjectConfig(e){return Yi(this,e)}applyCustomizeSettings(e,t){return Qr(this,e,t)}scheduleObjectAutoApply(){return es(this)}setupDebugEventListeners(){return as(this)}setupDebugInputListeners(e){return Ji(this,e)}setupPanelLayout(){return rs(this)}setupCollapsiblePanels(e){return Zi(this,e)}setupRangeInput(e,t,n,a){return te(this,e,t,n,a)}updateWorkbenchTabs(){return Xi(this)}saveWorkbenchState(){return Ne(this)}loadWorkbenchState(){return zn(this)}initialize(e){var r;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let s=localStorage.getItem("preview_workbench_state");if(s){let o=JSON.parse(s);o.activeTab&&(this.activeTab=o.activeTab)}}catch(s){console.warn("[PREVIEW] Failed to load workbench tab state",s)}this.sceneObjectsPanel.initialize(e,{onSelect:s=>this.handleObjectSelect(s)}),this.libraryPanel.initialize(e,{onApply:(s,o,l)=>this.applySlotAsset(s,o,l),onReset:(s,o,l)=>this.resetSlotAsset(s,o,l)}),this.inspectorPanel.initialize(e,{onPropertyChange:(s,o,l)=>{console.log("[Inspector] Property changed:",s,o,l)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let s="/dashboard";window.location.pathname!==s&&(window.location.href=s)}),this.customizeSettingsPanel.initialize(e,{onApply:(s,o)=>this.applyCustomizeSettings(s,o)});let t=e.querySelector("#scene-tools-container");t&&(t.innerHTML=this.sceneToolsPanel.render());let n=e.querySelector("#nudge-panel-container");n&&(n.innerHTML=this.nudgePanel.render()),this.sceneToolsPanel.initialize(t||e,{onHighlightObject:s=>{this.highlightObject=s,s?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:s=>{this.highlightAnchor=s,s?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(s,o)=>this.nudgeSelectedObject(s,o),onShowSplash:()=>{let s=window;typeof s.__previewShowSplash=="function"&&s.__previewShowSplash()},onUpdateSplash:s=>{let o=window;typeof o.applyEditableEngineConfig=="function"&&o.applyEditableEngineConfig({splash:s})}}),this.nudgePanel.initialize(n||e,{onNudge:(s,o)=>{let l=this.nudgePanel.getNudgeStep();this.nudgeSelectedObject(s*l,o*l)},onScale:s=>{var d,u;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let l=(u=(d=o.render)==null?void 0:d.scale)!=null?u:1,c=Math.max(.1,l+s),p=window;typeof p.applyEditableObjectConfig=="function"&&p.applyEditableObjectConfig(this.selectedObjectId,{render:{...o.render,scale:c}})}});let a=t==null?void 0:t.querySelector("#debug-nudge-enabled");a==null||a.addEventListener("change",()=>{a.checked?this.nudgePanel.show():this.nudgePanel.hide()}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let s=window;typeof s.__previewShowLoading=="function"?s.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let s=window;typeof s.__previewHideLoading=="function"?s.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:s=>{let o=window;typeof o.applyEditableEngineConfig=="function"&&o.applyEditableEngineConfig({loading:s}),typeof o.__previewUpdateLoading=="function"?o.__previewUpdateLoading(s):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(s,o,l,c)=>{this.customizeSettingsPanel.openAiEditor(s,o,l,c)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(r=this.debugOverlay)==null||r.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=s=>this.selectObject(s),window.addEventListener("config:changed",s=>{var o,l;((o=s.detail)==null?void 0:o.action)!=="remove"&&((l=s.detail)==null?void 0:l.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(s,o,l)=>this.applySlotAsset(s,o,l),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var o;let s=window.getActiveConfig;if(typeof s=="function"){let l=s();return((o=l==null?void 0:l.engine)==null?void 0:o.splash)||null}return null},window.addAssetToRegistry=(s,o)=>{let l=window.getEditableAssets;if(typeof l=="function"){let c=l();if(c!=null&&c.libraryAssets&&(c.libraryAssets[s]||(c.libraryAssets[s]=[]),!c.libraryAssets[s].some(d=>d.filename===o))){let d=o.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");c.libraryAssets[s].unshift({filename:o,displayName:d}),console.log(`[DEBUG] Added ${o} to registry category ${s}`)}}}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}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`
1128
1128
  <div class="debug-overlay hidden" id="debug-overlay">
1129
1129
  <div class="debug-workbench" id="debug-workbench">
1130
1130
  <div class="workbench-header" id="workbench-handle">
@@ -1167,7 +1167,7 @@ Are you absolutely sure?`))try{let t=xt(),n={};for(let[s,r]of Object.entries(t.o
1167
1167
  <!-- Standalone Hierarchy Panel -->
1168
1168
  ${this.sceneObjectsPanel.render()}
1169
1169
  </div>
1170
- `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.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()}nudgeSelectedObject(e,t){var p,d,u;if(!this.selectedObjectId||!this.container)return;let n=this.nudgePanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),s=this.container.querySelector("#config-pos-y");if(!a||!s)return;let r=Number((p=a.value)!=null?p:0),o=Number((d=s.value)!=null?d:0),l=r+e*n,c=o+t*n;a&&(a.value=String(l)),s&&(s.value=String(c)),(u=this.configViewer)==null||u.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function Go(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function qo(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}function Vo(i){return`
1170
+ `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.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()}nudgeSelectedObject(e,t){var p,d,u;if(!this.selectedObjectId||!this.container)return;let n=this.nudgePanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),r=this.container.querySelector("#config-pos-y");if(!a||!r)return;let s=Number((p=a.value)!=null?p:0),o=Number((d=r.value)!=null?d:0),l=s+e*n,c=o+t*n;a&&(a.value=String(l)),r&&(r.value=String(c)),(u=this.configViewer)==null||u.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function Go(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function qo(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}function Vo(i){return`
1171
1171
  Analyze these screenshots of a brand or game and extract its "Brand DNA".
1172
1172
 
1173
1173
  Provide a concise summary (2-3 sentences) covering:
@@ -1184,9 +1184,9 @@ Palette: [#RRGGBB, #RRGGBB, ...]
1184
1184
  ${i?`
1185
1185
  ADDITIONAL RULES/NOTES:
1186
1186
  ${i}`:""}
1187
- `.trim()}function rr(){let i=[],e="",t=null;return{async addSources(n){let a=[];for(let s of n){let r=await Go(s),o=qo(r),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:s.name,base64:o.base64,mimeType:o.mimeType,dataUrl:r};i.push(l),a.push(l)}return a},getSources(){return i.slice()},async analyze(n,a,s){if(i.length===0)throw new Error("No screenshots to analyze.");let r=Vo(a),o=i.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await Pn(n,r,o,{model:s}),c=e,p=[],d=l.split(`
1187
+ `.trim()}function ss(){let i=[],e="",t=null;return{async addSources(n){let a=[];for(let r of n){let s=await Go(r),o=qo(s),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:r.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};i.push(l),a.push(l)}return a},getSources(){return i.slice()},async analyze(n,a,r){if(i.length===0)throw new Error("No screenshots to analyze.");let s=Vo(a),o=i.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await Pn(n,s,o,{model:r}),c=e,p=[],d=l.split(`
1188
1188
  `);for(let u of d)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=>{p.includes(h.toUpperCase())||p.push(h.toUpperCase())})}return(!c||c===e)&&(c=l.split(`
1189
- Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var He="handler_api_key_";var et=class{static setKey(e,t,n){try{let a={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},s=`${He}${e}`;localStorage.setItem(s,JSON.stringify(a))}catch(a){console.error("[ApiKeyStorage] Failed to store API key:",a)}}static getKey(e){try{let t=`${He}${e}`,n=localStorage.getItem(t);if(!n)return null;let a=JSON.parse(n);return a.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(a)),this.decryptKey(a.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${He}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${He}${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(He)){let a=n.substring(He.length),s=localStorage.getItem(n);if(s){let r=JSON.parse(s);e.push({service:a,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(He)&&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}}},Qi=()=>et.getKey("gemini"),ea=(i,e)=>et.setKey("gemini",i,e),Wo=()=>et.hasKey("gemini");window.ApiKeyStorage=et;window.getGeminiApiKey=Qi;window.setGeminiApiKey=ea;window.hasGeminiApiKey=Wo;var na=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=`
1189
+ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var He="handler_api_key_";var et=class{static setKey(e,t,n){try{let a={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},r=`${He}${e}`;localStorage.setItem(r,JSON.stringify(a))}catch(a){console.error("[ApiKeyStorage] Failed to store API key:",a)}}static getKey(e){try{let t=`${He}${e}`,n=localStorage.getItem(t);if(!n)return null;let a=JSON.parse(n);return a.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(a)),this.decryptKey(a.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${He}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${He}${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(He)){let a=n.substring(He.length),r=localStorage.getItem(n);if(r){let s=JSON.parse(r);e.push({service:a,label:s.label,created:s.created,lastUsed:s.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(He)&&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}}},Qi=()=>et.getKey("gemini"),ea=(i,e)=>et.setKey("gemini",i,e),Wo=()=>et.hasKey("gemini");window.ApiKeyStorage=et;window.getGeminiApiKey=Qi;window.setGeminiApiKey=ea;window.hasGeminiApiKey=Wo;var na=class{constructor(){this.modal=null;this.options=null;this.analyzer=ss();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=`
1190
1190
  <div class="ai-modal-card">
1191
1191
  <div class="ai-modal-header">
1192
1192
  <div class="ai-modal-actions">
@@ -1265,14 +1265,14 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0
1265
1265
  <button class="ai-btn primary" data-action="apply" disabled>Apply</button>
1266
1266
  </div>
1267
1267
  </div>
1268
- `,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 a;this.currentPrompt=((a=this.promptInput)==null?void 0:a.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",a=>{var o;let s=a.target;switch(s.dataset.action||((o=s.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",a=>{let s=a.target;if(s.classList.contains("ai-gallery-item")||s.closest(".ai-gallery-item")){let r=s.closest(".ai-gallery-item"),o=parseInt(r.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",a=>{a.target===this.modal&&this.close()}),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 a=`${this.currentPrompt}
1268
+ `,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 a;this.currentPrompt=((a=this.promptInput)==null?void 0:a.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",a=>{var o;let r=a.target;switch(r.dataset.action||((o=r.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",a=>{let r=a.target;if(r.classList.contains("ai-gallery-item")||r.closest(".ai-gallery-item")){let s=r.closest(".ai-gallery-item"),o=parseInt(s.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",a=>{a.target===this.modal&&this.close()}),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 a=`${this.currentPrompt}
1269
1269
 
1270
- Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,a;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 s=this.getApiKey();if(!s){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 _n(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 Qe(s,this.currentPrompt,r,{aspectRatio:"1:1"}),l=await Ze(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(s){console.error("[AiEditorModal] Generation failed:",s),alert(`Generation failed: ${s instanceof Error?s.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(a=this.previewEl)==null||a.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)=>`
1270
+ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,a;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 r=this.getApiKey();if(!r){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await _n(this.options.currentValue);c&&(s=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await Qe(r,this.currentPrompt,s,{aspectRatio:"1:1"}),l=await Ze(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(r){console.error("[AiEditorModal] Generation failed:",r),alert(`Generation failed: ${r instanceof Error?r.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(a=this.previewEl)==null||a.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)=>`
1271
1271
  <div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
1272
1272
  <img class="ai-gallery-thumb" src="${t}" alt="Generated ${n+1}" />
1273
1273
  <div class="ai-gallery-label">#${n+1}</div>
1274
1274
  </div>
1275
- `).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=Qi();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return ea(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}},ta=null;window.__openAiEditor=function(i,e,t,n){ta||(ta=new na),ta.open({objectId:i,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:a=>{if(n!=null&&n.path){let s=window.updateManager;if(s)s.updateProperty(i,n.path,a);else{let r=window.getEditableObjectConfig,o=r==null?void 0:r(i);if(o){let l=n.path.split("."),c=o;for(let p=0;p<l.length-1;p++)c[l[p]]||(c[l[p]]={}),c=c[l[p]];c[l[l.length-1]]=a}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};aa();var sa=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,a=n||"Asset Preview",s=document.createElement("div");s.className="asset-preview-modal",s.innerHTML=`
1275
+ `).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=Qi();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return ea(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}},ta=null;window.__openAiEditor=function(i,e,t,n){ta||(ta=new na),ta.open({objectId:i,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:a=>{if(n!=null&&n.path){let r=window.updateManager;if(r)r.updateProperty(i,n.path,a);else{let s=window.getEditableObjectConfig,o=s==null?void 0:s(i);if(o){let l=n.path.split("."),c=o;for(let p=0;p<l.length-1;p++)c[l[p]]||(c[l[p]]={}),c=c[l[p]];c[l[l.length-1]]=a}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};aa();var ra=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,a=n||"Asset Preview",r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
1276
1276
  <div class="asset-preview-card">
1277
1277
  <div class="asset-preview-header">
1278
1278
  <div class="asset-preview-title">${a}</div>
@@ -1293,13 +1293,13 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1293
1293
  ${t==="image"?'<button class="asset-preview-ai" data-action="edit">\u2728 AI Edit</button>':""}
1294
1294
  </div>
1295
1295
  </div>
1296
- `,this.modal=s,this.attachEventListeners()}renderAssetContent(e,t){if(!e)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(t){case"image":return`<img src="${this.resolveAssetUrl(e)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let a=this.resolveAssetUrl(e);return`
1296
+ `,this.modal=r,this.attachEventListeners()}renderAssetContent(e,t){if(!e)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(t){case"image":return`<img src="${this.resolveAssetUrl(e)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let a=this.resolveAssetUrl(e);return`
1297
1297
  <audio controls style="width: 100%;">
1298
1298
  <source src="${a}" type="audio/mpeg">
1299
1299
  <source src="${a}" type="audio/wav">
1300
1300
  Your browser does not support the audio element.
1301
1301
  </audio>
1302
- `;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 a=n.target;(a.dataset.action==="close"||a===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(()=>(aa(),or)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var a;(a=this.options)!=null&&a.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(i){new sa().open(i)};var ra=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=`
1302
+ `;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 a=n.target;(a.dataset.action==="close"||a===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(()=>(aa(),os)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var a;(a=this.options)!=null&&a.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(i){new ra().open(i)};var sa=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=`
1303
1303
  <div class="asset-crop-card">
1304
1304
  <div class="asset-crop-header">
1305
1305
  <div>
@@ -1350,7 +1350,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1350
1350
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
1351
1351
  </div>
1352
1352
  </div>
1353
- `,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,a=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,a-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,a=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,a),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,a),this.ctx.fillStyle="#ffffff";let s=8;[[e,t],[e+n-s,t],[e,t+a-s],[e+n-s,t+a-s]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,s,s)})}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 a=n/this.cropWidth,s=n/this.cropHeight,r=Math.min(a,s),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,p=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,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 a=parseFloat(n.target.value);this.setZoom(a)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let a=n.target.value;this.setAspectRatio(a)}),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 a;if(!this.image||!((a=this.options)!=null&&a.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(i){new ra().open(i)};var Hn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[ze("playable-portrait"),ze("iphone-14"),ze("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.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;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=ze(e.defaultDevice||pn.id),this.debugPanel=new Mt,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.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}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(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}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 a,s;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ze(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),t.suppressCallback||(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell",e.innerHTML=`
1353
+ `,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,a=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,a-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,a=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,a),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,a),this.ctx.fillStyle="#ffffff";let r=8;[[e,t],[e+n-r,t],[e,t+a-r],[e+n-r,t+a-r]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,r,r)})}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 a=n/this.cropWidth,r=n/this.cropHeight,s=Math.min(a,r),o=this.cropWidth*s,l=this.cropHeight*s,c=(n-o)/2,p=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,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 a=parseFloat(n.target.value);this.setZoom(a)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let a=n.target.value;this.setAspectRatio(a)}),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 a;if(!this.image||!((a=this.options)!=null&&a.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(i){new sa().open(i)};var Hn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[ze("playable-portrait"),ze("iphone-14"),ze("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.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;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=ze(e.defaultDevice||pn.id),this.debugPanel=new Mt,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.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}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(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}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 a,r;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ze(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),t.suppressCallback||(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell",e.innerHTML=`
1354
1354
  <div class="preview-toolbar">
1355
1355
  <div class="preview-toolbar-left">
1356
1356
  <span class="preview-logo">PREVIEWER</span>
@@ -1491,7 +1491,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1491
1491
  <div class="console-messages" id="console-messages"></div>
1492
1492
  </div>
1493
1493
  </div>
1494
- `,this.setupEventListeners(e),e}setupEventListeners(e){var a,s,r,o,l,c,p,d,u,g;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",h=>{if(this.viewMode==="compare")return;let f=h.target.value;this.setDevice(f)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.viewToggle;f&&this.setViewMode(f)})}),(a=e.querySelector("#rotate-btn"))==null||a.addEventListener("click",()=>this.toggleRotation()),(s=e.querySelector("#zoom-in-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(.1)),(r=e.querySelector("#zoom-out-btn"))==null||r.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=e.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(l=e.querySelector("#console-toggle"))==null||l.addEventListener("click",()=>this.toggleConsole()),(c=e.querySelector("#console-close"))==null||c.addEventListener("click",()=>this.toggleConsole(!1)),(p=e.querySelector("#console-clear"))==null||p.addEventListener("click",()=>this.clearConsole()),(d=e.querySelector("#corner-zoom-in-btn"))==null||d.addEventListener("click",()=>this.adjustUserZoom(.1)),(u=e.querySelector("#corner-zoom-out-btn"))==null||u.addEventListener("click",()=>this.adjustUserZoom(-.1)),(g=e.querySelector("#corner-grab-btn"))==null||g.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)})}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:"0 20px 50px rgba(0,0,0,0.5)",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.gameReady||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(),a=Math.max(0,n.width),s=Math.max(0,n.height);if(a<=0||s<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=a/t.width,o=s/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&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),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)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}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}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.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale: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,(a,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=console.log.bind(console),t=console.warn.bind(console),n=console.error.bind(console),a=console.info.bind(console),s=(r,...o)=>{let l=o.map(p=>typeof p=="object"?this.safeStringify(p):String(p)).join(" ");this.consoleMessages.push({type:r,message:l,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let c=this.container.querySelector("#console-badge");if(c){let p=this.consoleMessages.filter(d=>d.type==="error").length;c.textContent=p>0?`${p}!`:"0",c.classList.toggle("has-errors",p>0)}};console.log=(...r)=>{e(...r),s("log",...r)},console.warn=(...r)=>{t(...r),s("warn",...r)},console.error=(...r)=>{n(...r),s("error",...r)},console.info=(...r)=>{a(...r),s("info",...r)}}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 a=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(a)}</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;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 a=this.comparePresets.find(d=>d.id===n);if(!a)return;let s=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]"),p=t.querySelector("[data-compare-focus]");!s||!r||!o||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:a,root:t,slot:s,ghost:r,wrapper:o,frame:l,canvas:c,focus:p}))})}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");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var s,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,a=this.activeCompareId;a&&a!==e&&this.captureCompareSnapshot(a),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=(s=this.options).onDeviceChange)==null||r.call(s,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,a=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=a,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),a=Math.max(0,t.clientHeight-24);if(n<=0||a<=0)return;let s=n/e.preset.width,r=a/e.preset.height,o=Math.max(.01,Math.min(s,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 a=t.canvas.getContext("2d");if(!a)return;let s=t.canvas.width,r=t.canvas.height,o=Math.min(s/n.width,r/n.height),l=n.width*o,c=n.height*o,p=(s-l)/2,d=(r-c)/2;a.clearRect(0,0,s,r),a.drawImage(n,p,d,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")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.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 oa(i={}){let e=new Hn(i);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ee();function la(i){try{if(i&&typeof i.keys=="function")return Array.from(i.keys())}catch{}return[]}function lr(i){var e;return i?((e=i.getDisplayObject)==null?void 0:e.call(i))||i.pixiObject||i:null}function Yo(i,e){if(!i||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);i.eventMode=n?"static":"none",i.interactive=n,n&&(i.cursor=t.draggable?"move":"pointer")}function cr(i,e){var l,c,p,d,u;if(!i||!e)return;let t=e.transform||{};Yo(i,e);let n=t.position||{},a=t.offset||{},s=(typeof n.x=="number"?n.x:0)+(typeof a.x=="number"?a.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof a.y=="number"?a.y:0);(l=i.position)!=null&&l.set?i.position.set(s,r):(typeof i.x=="number"&&(i.x=s),typeof i.y=="number"&&(i.y=r)),typeof t.scale=="number"&&((c=i.scale)!=null&&c.set?i.scale.set(t.scale):i.scale&&(i.scale.x=t.scale,i.scale.y=t.scale));let o=(d=t.anchor)!=null?d:(p=e.render)==null?void 0:p.anchor;o&&((u=i.anchor)!=null&&u.set)&&typeof o.x=="number"&&typeof o.y=="number"&&i.anchor.set(o.x,o.y)}function dr(i){if(typeof window=="undefined")return;let e=i==null?void 0:i.objects,t=la(e),n=s=>{try{let r=window.__HANDLER_ACTIVE_SCREEN;if(!r||r==="all")return s;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?s.filter(c=>l[c]===r):s}catch{return s}};window.__editableObjectConfigs=e;let a=new Map;t.forEach(s=>a.set(s,[s])),window.__editableObjectInstances=a,window.refreshEditableConfigIndex=()=>dr(window.__editableConfig),window.getEditableObjectList=()=>{var s;return n(la((s=window.__editableConfig)==null?void 0:s.objects))},window.getEditableObjectListAll=()=>{var s;return la((s=window.__editableConfig)==null?void 0:s.objects)},window.getEditableObjectConfig=s=>{var p,d,u,g,h;let r=(g=(u=(d=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:d.get)==null?void 0:u.call(d,s))!=null?g:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(h=l==null?void 0:l.instanceToScreen)==null?void 0:h[s];return c&&c===o?r:null},window.getEditableEngineConfig=()=>{let s=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!s),!s)return null;if(s.engine&&s.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...s.engine,objects:s.objects,scene:s.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return s}}function Ko(){if(typeof window=="undefined")return;let i=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var s,r,o;let a=i(n);if(a)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Ke(),as))]),p=Date.now(),d=/^(data:|blob:)/.test(a)?a:a+(a.includes("?")?`&t=${p}`:`?t=${p}`),u=await l.load(d);if(!u)return;c[t]=u;let g=window.CustomAssets;(s=g==null?void 0:g[t])!=null&&s.texture&&(g[t].texture=u);let h=window.gameObjectManager,f=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(f){let m=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(m!=null&&m.texture)m.texture=u;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let a=[];if(t.runtime)for(let[s,r]of Object.entries(t.runtime))a.push({path:`runtime.${s}`,value:r});if(t.assets)for(let[s,r]of Object.entries(t.assets))a.push({path:`assets.${s}`,value:r}),typeof r=="string"&&e(s,r);if(t.splash)for(let[s,r]of Object.entries(t.splash))a.push({path:`splash.${s}`,value:r});if(t.loading)for(let[s,r]of Object.entries(t.loading))a.push({path:`loading.${s}`,value:r});if(t.start)for(let[s,r]of Object.entries(t.start))a.push({path:`start.${s}`,value:r});a.length&&Se(a,{silent:!0,persist:!0,emitEvent:!0})}}function Bn(i){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=i;t&&(t.onObjectRebuildRequired=async(s,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${s} due to type change...`);let o=t.get(s),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,p=c==null?void 0:c.children.indexOf(l);o?t.remove(s):l&&l.destroy();let d=window.gameApp,u=await Ee.create(s,r,d);c&&(p!==void 0&&p!==-1?c.addChildAt(u,p):c.addChild(u));let g=t.create(s,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${s}`),g}),typeof window!="undefined"&&(Ko(),window.applyEditableObjectConfig=(s,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",s);try{let p=window.__editableConfig;(o=p==null?void 0:p.objects)!=null&&o.set&&(p.objects.set(s,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let d=(l=t==null?void 0:t.get)==null?void 0:l.call(t,s);if(console.log("[LIVE-EDIT] gameObject found?",!!d),d&&(console.log("[LIVE-EDIT] gameObject type:",(c=d.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof d.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof d.onConfigUpdate=="function")),d&&typeof d.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),d.updateConfig(r);else if(d&&typeof d.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),d.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=lr(d);cr(u,r)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let a={async applyObjectConfig(s,r){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",s);let o=e();(p=o==null?void 0:o.objects)!=null&&p.set&&(o.objects.set(s,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(d=t==null?void 0:t.get)==null?void 0:d.call(t,s);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=lr(l);cr(u,r)}let c=[s];n==null||n(s,r,c)},rebuildIndexes(){let s=e();typeof window!="undefined"&&(window.__editableConfig=s,dr(s))}};return a.rebuildIndexes(),a}ee();var gr=qe(require("lottie-web"),1);ri(ai);typeof window!="undefined"&&!window.lottie&&(window.lottie=gr.default);var tt=null,Xo=async()=>{if(!tt){let i=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(i==null?void 0:i["handler.config"])||(i==null?void 0:i["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);tt=JSON.parse(n)}else tt=JSON.parse(e);return tt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}tt=await(await fetch("./handler.config.json")).json()}return tt},ua,Ot,fr,nt,da,pa;function Jo(i){ua=i.initGame,Ot=i.CustomAssets,fr=i.updateScreenState,nt=i.globalResponsiveMultipliers,da=i.layout,pa=i.clearResponsiveElements}var Fn="web_embed",kt="https://example.com",pr={profile_id:Fn},Pe=null,oe=null,ca={width:0,height:0},Zo=!0,Qo=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let i=await Xo();pr={...i.ids||{},profile_id:Fn},kt=i.destination_url||((p=(c=i.export_profiles)==null?void 0:c[Fn])==null?void 0:p.destination_url)||kt,Oe.init({ids:pr,profile:Fn,destinationUrl:kt});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),oe=oa({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),ur()},onRefresh:ur});let g=oe.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,x,E,w,T,S,O,B,M,C,I;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(ca.width=b,ca.height=y,fr(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let k=f.view;k&&(k.style.width="100%",k.style.height="100%",k.style.display="block")}catch(k){console.warn("[SCREEN] Error resizing renderer:",k);return}if(t&&m&&da)try{let k=(v=window.__mainContainer)!=null?v:f.stage,D=(O=(S=(w=window.__tutorialLabel)!=null?w:(E=(x=m.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:E.call(x))!=null?S:(T=m.get("label_1"))==null?void 0:T.pixiObject)!=null?O:m.get("label_1"),R=m.get("background_1"),$=(I=(C=(M=window.__background)!=null?M:(B=R==null?void 0:R.getDisplayObject)==null?void 0:B.call(R))!=null?C:R==null?void 0:R.pixiObject)!=null?I:R;if(k){let A=k===f.stage;da({mainContainer:k,label:D,background:$,backgroundTexture:($==null?void 0:$.texture)||null,app:f},t,0,ca,m,{skipMainContainerTransform:A})}}catch(k){console.warn("[SCREEN] Error in layout:",k)}}})}let t=await me("scene.main");window.__editableConfig=t,r(),window.__editableConfigBaseline||(window.__editableConfigBaseline=G(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(d=t.engine.runtime)==null?void 0:d.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await me("scene.main"));let n=await ua(e,t,kt,oe);Pe=n.app;let a=n.gameObjectManager;window.gameApp=Pe,window.gameObjectManager=a;try{window.__liveEditBridge=Bn({getConfig:()=>window.__editableConfig,gameObjectManager:a,assets:Ot})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}oe&&oe.notifyGameLoaded();let s=window.__debugScale;s&&typeof s=="number"&&(nt.scale=s,console.log(`[DEBUG] Applied persisted debug scale: ${s}`)),o(Pe,a);async function r(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let E=await x.text();try{return JSON.parse(E)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let f=h.screens;if(!f||typeof f!="object")return;let m={},b={};for(let[y,v]of Object.entries(f)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let E=await g(x),w=E==null?void 0:E.elements;if(!Array.isArray(w))continue;let T=w.map(S=>S==null?void 0:S.instance_id).filter(S=>typeof S=="string");m[y]=T;for(let S of T)b[S]||(b[S]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Zo){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${nt.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,E)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let w=x.scale.x||1,T=x.scale.y||1;x.__originalScale||(x.__originalScale={x:w,y:T},console.log(`${v}[RESPONSIVE] Stored original scale for child[${E}]: ${w.toFixed(3)}, ${T.toFixed(3)}`));let S=x.__originalScale.x*nt.scale,O=x.__originalScale.y*nt.scale;typeof x.scale.set=="function"?x.scale.set(S,O):(x.scale.x=S,x.scale.y=O),console.log(`${v}[RESPONSIVE] Child[${E}] scale: ${w.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),m(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${E}] has no scale (type: ${x.constructor.name})`)})};var f=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){nt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,f=window.gameObjectManager;h&&f?(o(h,f),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},ur=async()=>{var e,t,n,a;console.log("[PREVIEW] Restarting game in 1 seconds...");let i=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(i){let s=((t=i.getDisplayObject)==null?void 0:t.call(i))||i;s&&s.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=s.scale.x)!=null?n:1).toFixed(3)}, y: ${((a=s.scale.y)!=null?a:1).toFixed(3)}`)}if(oe){oe.notifyGameDestroyed();try{pa&&pa()}catch(s){console.warn("Failed to clear responsive elements",s)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let s=oe.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),Pe){try{Pe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Pe=null}window.gameApp=null,window.gameObjectManager=null,s&&(s.innerHTML="");try{typeof Ot.resetScene=="function"&&Ot.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{me("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=G(o)),ua(s,o,kt).then(l=>{Pe=l.app,window.gameApp=Pe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Bn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Ot})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}oe&&oe.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};dn();ee();var le={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},hr=1.25,mr={fontFamily:"Inter, system-ui, sans-serif"};var Un=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=`
1494
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var a,r,s,o,l,c,p,d,u,g;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",h=>{if(this.viewMode==="compare")return;let f=h.target.value;this.setDevice(f)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.viewToggle;f&&this.setViewMode(f)})}),(a=e.querySelector("#rotate-btn"))==null||a.addEventListener("click",()=>this.toggleRotation()),(r=e.querySelector("#zoom-in-btn"))==null||r.addEventListener("click",()=>this.adjustUserZoom(.1)),(s=e.querySelector("#zoom-out-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=e.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(l=e.querySelector("#console-toggle"))==null||l.addEventListener("click",()=>this.toggleConsole()),(c=e.querySelector("#console-close"))==null||c.addEventListener("click",()=>this.toggleConsole(!1)),(p=e.querySelector("#console-clear"))==null||p.addEventListener("click",()=>this.clearConsole()),(d=e.querySelector("#corner-zoom-in-btn"))==null||d.addEventListener("click",()=>this.adjustUserZoom(.1)),(u=e.querySelector("#corner-zoom-out-btn"))==null||u.addEventListener("click",()=>this.adjustUserZoom(-.1)),(g=e.querySelector("#corner-grab-btn"))==null||g.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)})}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:"0 20px 50px rgba(0,0,0,0.5)",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.gameReady||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(),a=Math.max(0,n.width),r=Math.max(0,n.height);if(a<=0||r<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=a/t.width,o=r/t.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),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)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}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}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.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale: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,(a,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=console.log.bind(console),t=console.warn.bind(console),n=console.error.bind(console),a=console.info.bind(console),r=(s,...o)=>{let l=o.map(p=>typeof p=="object"?this.safeStringify(p):String(p)).join(" ");this.consoleMessages.push({type:s,message:l,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let c=this.container.querySelector("#console-badge");if(c){let p=this.consoleMessages.filter(d=>d.type==="error").length;c.textContent=p>0?`${p}!`:"0",c.classList.toggle("has-errors",p>0)}};console.log=(...s)=>{e(...s),r("log",...s)},console.warn=(...s)=>{t(...s),r("warn",...s)},console.error=(...s)=>{n(...s),r("error",...s)},console.info=(...s)=>{a(...s),r("info",...s)}}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 a=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(a)}</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;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 a=this.comparePresets.find(d=>d.id===n);if(!a)return;let r=t.querySelector("[data-compare-slot]"),s=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),p=t.querySelector("[data-compare-focus]");!r||!s||!o||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:a,root:t,slot:r,ghost:s,wrapper:o,frame:l,canvas:c,focus:p}))})}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");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var r,s;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,a=this.activeCompareId;a&&a!==e&&this.captureCompareSnapshot(a),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}),(s=(r=this.options).onDeviceChange)==null||s.call(r,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,a=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=a,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),a=Math.max(0,t.clientHeight-24);if(n<=0||a<=0)return;let r=n/e.preset.width,s=a/e.preset.height,o=Math.max(.01,Math.min(r,s));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 a=t.canvas.getContext("2d");if(!a)return;let r=t.canvas.width,s=t.canvas.height,o=Math.min(r/n.width,s/n.height),l=n.width*o,c=n.height*o,p=(r-l)/2,d=(s-c)/2;a.clearRect(0,0,r,s),a.drawImage(n,p,d,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")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.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 oa(i={}){let e=new Hn(i);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ee();function la(i){try{if(i&&typeof i.keys=="function")return Array.from(i.keys())}catch{}return[]}function ls(i){var e;return i?((e=i.getDisplayObject)==null?void 0:e.call(i))||i.pixiObject||i:null}function Yo(i,e){if(!i||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);i.eventMode=n?"static":"none",i.interactive=n,n&&(i.cursor=t.draggable?"move":"pointer")}function cs(i,e){var l,c,p,d,u;if(!i||!e)return;let t=e.transform||{};Yo(i,e);let n=t.position||{},a=t.offset||{},r=(typeof n.x=="number"?n.x:0)+(typeof a.x=="number"?a.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof a.y=="number"?a.y:0);(l=i.position)!=null&&l.set?i.position.set(r,s):(typeof i.x=="number"&&(i.x=r),typeof i.y=="number"&&(i.y=s)),typeof t.scale=="number"&&((c=i.scale)!=null&&c.set?i.scale.set(t.scale):i.scale&&(i.scale.x=t.scale,i.scale.y=t.scale));let o=(d=t.anchor)!=null?d:(p=e.render)==null?void 0:p.anchor;o&&((u=i.anchor)!=null&&u.set)&&typeof o.x=="number"&&typeof o.y=="number"&&i.anchor.set(o.x,o.y)}function ds(i){if(typeof window=="undefined")return;let e=i==null?void 0:i.objects,t=la(e),n=r=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return r;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?r.filter(c=>l[c]===s):r}catch{return r}};window.__editableObjectConfigs=e;let a=new Map;t.forEach(r=>a.set(r,[r])),window.__editableObjectInstances=a,window.refreshEditableConfigIndex=()=>ds(window.__editableConfig),window.getEditableObjectList=()=>{var r;return n(la((r=window.__editableConfig)==null?void 0:r.objects))},window.getEditableObjectListAll=()=>{var r;return la((r=window.__editableConfig)==null?void 0:r.objects)},window.getEditableObjectConfig=r=>{var p,d,u,g,h;let s=(g=(u=(d=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:d.get)==null?void 0:u.call(d,r))!=null?g:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let l=window.__HANDLER_SCREEN_INDEX,c=(h=l==null?void 0:l.instanceToScreen)==null?void 0:h[r];return c&&c===o?s:null},window.getEditableEngineConfig=()=>{let r=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!r),!r)return null;if(r.engine&&r.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...r.engine,objects:r.objects,scene:r.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return r}}function Ko(){if(typeof window=="undefined")return;let i=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var r,s,o;let a=i(n);if(a)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Ke(),ar))]),p=Date.now(),d=/^(data:|blob:)/.test(a)?a:a+(a.includes("?")?`&t=${p}`:`?t=${p}`),u=await l.load(d);if(!u)return;c[t]=u;let g=window.CustomAssets;(r=g==null?void 0:g[t])!=null&&r.texture&&(g[t].texture=u);let h=window.gameObjectManager,f=(s=h==null?void 0:h.get)==null?void 0:s.call(h,t);if(f){let m=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(m!=null&&m.texture)m.texture=u;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let a=[];if(t.runtime)for(let[r,s]of Object.entries(t.runtime))a.push({path:`runtime.${r}`,value:s});if(t.assets)for(let[r,s]of Object.entries(t.assets))a.push({path:`assets.${r}`,value:s}),typeof s=="string"&&e(r,s);if(t.splash)for(let[r,s]of Object.entries(t.splash))a.push({path:`splash.${r}`,value:s});if(t.loading)for(let[r,s]of Object.entries(t.loading))a.push({path:`loading.${r}`,value:s});if(t.start)for(let[r,s]of Object.entries(t.start))a.push({path:`start.${r}`,value:s});a.length&&Se(a,{silent:!0,persist:!0,emitEvent:!0})}}function Bn(i){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=i;t&&(t.onObjectRebuildRequired=async(r,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${r} due to type change...`);let o=t.get(r),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,p=c==null?void 0:c.children.indexOf(l);o?t.remove(r):l&&l.destroy();let d=window.gameApp,u=await Ee.create(r,s,d);c&&(p!==void 0&&p!==-1?c.addChildAt(u,p):c.addChild(u));let g=t.create(r,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${r}`),g}),typeof window!="undefined"&&(Ko(),window.applyEditableObjectConfig=(r,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",r);try{let p=window.__editableConfig;(o=p==null?void 0:p.objects)!=null&&o.set&&(p.objects.set(r,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let d=(l=t==null?void 0:t.get)==null?void 0:l.call(t,r);if(console.log("[LIVE-EDIT] gameObject found?",!!d),d&&(console.log("[LIVE-EDIT] gameObject type:",(c=d.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof d.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof d.onConfigUpdate=="function")),d&&typeof d.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),d.updateConfig(s);else if(d&&typeof d.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),d.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=ls(d);cs(u,s)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let a={async applyObjectConfig(r,s){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",r);let o=e();(p=o==null?void 0:o.objects)!=null&&p.set&&(o.objects.set(r,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(d=t==null?void 0:t.get)==null?void 0:d.call(t,r);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(s);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=ls(l);cs(u,s)}let c=[r];n==null||n(r,s,c)},rebuildIndexes(){let r=e();typeof window!="undefined"&&(window.__editableConfig=r,ds(r))}};return a.rebuildIndexes(),a}ee();var gs=qe(require("lottie-web"),1);si(ai);typeof window!="undefined"&&!window.lottie&&(window.lottie=gs.default);var tt=null,Xo=async()=>{if(!tt){let i=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(i==null?void 0:i["handler.config"])||(i==null?void 0:i["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);tt=JSON.parse(n)}else tt=JSON.parse(e);return tt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}tt=await(await fetch("./handler.config.json")).json()}return tt},ua,Ot,fs,nt,da,pa;function Jo(i){ua=i.initGame,Ot=i.CustomAssets,fs=i.updateScreenState,nt=i.globalResponsiveMultipliers,da=i.layout,pa=i.clearResponsiveElements}var Fn="web_embed",kt="https://example.com",ps={profile_id:Fn},Pe=null,oe=null,ca={width:0,height:0},Zo=!0,Qo=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let i=await Xo();ps={...i.ids||{},profile_id:Fn},kt=i.destination_url||((p=(c=i.export_profiles)==null?void 0:c[Fn])==null?void 0:p.destination_url)||kt,Oe.init({ids:ps,profile:Fn,destinationUrl:kt});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),oe=oa({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),us()},onRefresh:us});let g=oe.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,x,E,w,T,S,O,B,M,C,I;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(ca.width=b,ca.height=y,fs(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let k=f.view;k&&(k.style.width="100%",k.style.height="100%",k.style.display="block")}catch(k){console.warn("[SCREEN] Error resizing renderer:",k);return}if(t&&m&&da)try{let k=(v=window.__mainContainer)!=null?v:f.stage,D=(O=(S=(w=window.__tutorialLabel)!=null?w:(E=(x=m.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:E.call(x))!=null?S:(T=m.get("label_1"))==null?void 0:T.pixiObject)!=null?O:m.get("label_1"),R=m.get("background_1"),$=(I=(C=(M=window.__background)!=null?M:(B=R==null?void 0:R.getDisplayObject)==null?void 0:B.call(R))!=null?C:R==null?void 0:R.pixiObject)!=null?I:R;if(k){let A=k===f.stage;da({mainContainer:k,label:D,background:$,backgroundTexture:($==null?void 0:$.texture)||null,app:f},t,0,ca,m,{skipMainContainerTransform:A})}}catch(k){console.warn("[SCREEN] Error in layout:",k)}}})}let t=await me("scene.main");window.__editableConfig=t,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=G(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(d=t.engine.runtime)==null?void 0:d.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await me("scene.main"));let n=await ua(e,t,kt,oe);Pe=n.app;let a=n.gameObjectManager;window.gameApp=Pe,window.gameObjectManager=a;try{window.__liveEditBridge=Bn({getConfig:()=>window.__editableConfig,gameObjectManager:a,assets:Ot})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}oe&&oe.notifyGameLoaded();let r=window.__debugScale;r&&typeof r=="number"&&(nt.scale=r,console.log(`[DEBUG] Applied persisted debug scale: ${r}`)),o(Pe,a);async function s(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let E=await x.text();try{return JSON.parse(E)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let f=h.screens;if(!f||typeof f!="object")return;let m={},b={};for(let[y,v]of Object.entries(f)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let E=await g(x),w=E==null?void 0:E.elements;if(!Array.isArray(w))continue;let T=w.map(S=>S==null?void 0:S.instance_id).filter(S=>typeof S=="string");m[y]=T;for(let S of T)b[S]||(b[S]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Zo){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${nt.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,E)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let w=x.scale.x||1,T=x.scale.y||1;x.__originalScale||(x.__originalScale={x:w,y:T},console.log(`${v}[RESPONSIVE] Stored original scale for child[${E}]: ${w.toFixed(3)}, ${T.toFixed(3)}`));let S=x.__originalScale.x*nt.scale,O=x.__originalScale.y*nt.scale;typeof x.scale.set=="function"?x.scale.set(S,O):(x.scale.x=S,x.scale.y=O),console.log(`${v}[RESPONSIVE] Child[${E}] scale: ${w.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),m(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${E}] has no scale (type: ${x.constructor.name})`)})};var f=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){nt.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,f=window.gameObjectManager;h&&f?(o(h,f),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},us=async()=>{var e,t,n,a;console.log("[PREVIEW] Restarting game in 1 seconds...");let i=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(i){let r=((t=i.getDisplayObject)==null?void 0:t.call(i))||i;r&&r.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=r.scale.x)!=null?n:1).toFixed(3)}, y: ${((a=r.scale.y)!=null?a:1).toFixed(3)}`)}if(oe){oe.notifyGameDestroyed();try{pa&&pa()}catch(r){console.warn("Failed to clear responsive elements",r)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let r=oe.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Pe){try{Pe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Pe=null}window.gameApp=null,window.gameObjectManager=null,r&&(r.innerHTML="");try{typeof Ot.resetScene=="function"&&Ot.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{me("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=G(o)),ua(r,o,kt).then(l=>{Pe=l.app,window.gameApp=Pe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Bn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Ot})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}oe&&oe.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};dn();ee();var le={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},hs=1.25,ms={fontFamily:"Inter, system-ui, sans-serif"};var Un=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=`
1495
1495
  position: fixed;
1496
1496
  inset: 0;
1497
1497
  display: flex;
@@ -1520,23 +1520,23 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1520
1520
  display: flex;
1521
1521
  flex-direction: column;
1522
1522
  align-items: center;
1523
- `;let s=document.createElement("div");s.style.cssText=`
1523
+ `;let r=document.createElement("div");r.style.cssText=`
1524
1524
  width: 100%;
1525
1525
  display: flex;
1526
1526
  justify-content: space-between;
1527
1527
  align-items: flex-end;
1528
1528
  margin-bottom: 8px;
1529
- `;let r=document.createElement("span");r.style.cssText=`
1529
+ `;let s=document.createElement("span");s.style.cssText=`
1530
1530
  font-size: 12px;
1531
1531
  font-weight: 900;
1532
1532
  letter-spacing: 0.15em;
1533
1533
  color: ${le.ink};
1534
- `,r.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
1534
+ `,s.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
1535
1535
  font-size: 10px;
1536
1536
  font-family: monospace;
1537
1537
  font-weight: bold;
1538
1538
  color: ${le.primaryAccent};
1539
- `,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,s.appendChild(r),s.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
1539
+ `,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,r.appendChild(s),r.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
1540
1540
  height: 4px;
1541
1541
  width: 100%;
1542
1542
  background-color: #E0DDD8;
@@ -1570,7 +1570,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1570
1570
  width: 1.5px;
1571
1571
  background-color: black;
1572
1572
  height: ${u%4===0?"6px":"2px"};
1573
- `,c.appendChild(g)}a.appendChild(s),a.appendChild(o),a.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
1573
+ `,c.appendChild(g)}a.appendChild(r),a.appendChild(o),a.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
1574
1574
  position: absolute;
1575
1575
  top: 48px;
1576
1576
  width: 600px;
@@ -1690,7 +1690,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1690
1690
  0%, 100% { opacity: 1; }
1691
1691
  50% { opacity: 0.3; }
1692
1692
  }
1693
- `,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 ga=Ra.version,el=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"]);Ia();var Ar={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"},Sr=Math.random().toString(36).slice(2),st=null,it={...Ar},Cr="web_embed",ba={},Rt,fa=!1,It=!1,Dt=!1,Lr=!1,wa=1,qn=0,Yn=!1,ye=!1,at="",rt=Math.floor(window.innerWidth),ot=Math.floor(window.innerHeight),ya=rt>ot,ve=!1,jt=!1,br=!1,yr=!1,ha=!1,Vn=null,Be=null,va=!1,xa=!1,Gn=new Map;function Tr(){if(!Be)return null;let i=Date.now()-Be;return!Number.isFinite(i)||i<0?null:i}function ma(i){if(va)return;let e=Tr();e!==null&&(va=!0,L("session_time",{duration_ms:e,reason:i}))}function vr(){if(st)return st;let i=document.createElement("div");return i.id="handler-root",i.setAttribute("data-handler-root","true"),document.body.appendChild(i),st=i,i}function Wn(i){switch(i){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return i}}function _r(i,e){return{event_name:i,ts:Date.now(),session_id:Sr,deployment_id:it.deployment_id,variant_id:it.variant_id,export_profile_id:it.profile_id,instance_id:it.instance_id||"default",env:Cr==="mraid"?"mraid":"web",attribution:Rt,payload:e}}function L(i,e){let t=Wn(i),n=_r(t,e);ti(n,!!ba.analytics),Ft(t,n),t!==i&&Ft(i,n)}function $t(){Vn&&(Vn(rt,ot),Vn=null)}function lt(i){wa=i,L("volume",i)}function ct(i){i&&(Lr=!0),!Dt&&(Dt=!0,L("pause"),lt(0))}function zt(i){!i&&Lr||Dt&&(Dt=!1,L("resume"),lt(wa))}function Me(i,e){rt=Math.floor(i||window.innerWidth),ot=Math.floor(e||window.innerHeight),ya=rt>ot,L("resize",{width:rt,height:ot})}function tl(){if(Va())try{let i=mraid.getMaxSize();Me(i.width,i.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?zt():ct()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Me(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();lt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&lt(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),Yn=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};mraid.addEventListener("ready",t)}}catch(i){console.warn("MRAID hook skipped",i)}}function nl(){if(Wa())try{let i=dapi.getScreenSize();Me(i.width,i.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?zt():ct()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Me(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(lt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>lt(t?1:0)),Yn=!0,dapi.isViewable())ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};dapi.addEventListener("ready",t)}}catch(i){console.warn("DAPI hook skipped",i)}}function xr(){let i=()=>{ve||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t(),jt&&(jt=!1,ne.start()))};window.addEventListener("resize",()=>Me()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(zt(),i()):ct()}),document.readyState==="complete"||document.readyState==="interactive"?i():window.addEventListener("load",i),Yn=!0}function il(){let i=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(br=!0),!(br&&e instanceof MouseEvent)&&(qn+=1,xa||(xa=!0,L("first_interaction",{count:qn})),L("interaction",qn))};document.addEventListener("mousedown",i),document.addEventListener("touchstart",i)}function wr(i){var n,a,s,r,o,l,c,p,d,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(i||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Ye())(s=(a=window.TJ_API)==null?void 0:a.click)==null||s.call(a);else if(Ya())(o=(r=window.FbPlayableAd)==null?void 0:r.onCTAClick)==null||o.call(r);else if(Za())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(Ja())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(f){console.warn("Smadex redirect failed",f)}else if(Ka()){let f=window.ExitApi;f&&typeof f.exit=="function"?f.exit(i||at||""):i&&window.open(i)}else We()?(u=window.install)==null||u.call(window):Xa()?(g=window.openAppStore)==null||g.call(window):ni()?(h=parent==null?void 0:parent.postMessage)==null||h.call(parent,"download","*"):i&&window.open(i)}function al(){let i=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(i==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;K("view",()=>e(t.mraid_viewable)),K("start",()=>e(t.game_viewable)),K("engagement",()=>e(t.engagement));let n=()=>e(t.complete);K("complete",n),Bt("engagement",a=>{var s;((s=a==null?void 0:a.payload)==null?void 0:s.count)>3&&n()}),K("cta_click",()=>e(t.click))}else if(i==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;K("view",()=>e(t.Ad_Load_Start)),K("start",()=>e(t.Ad_Viewable)),K("engagement",()=>e(t.First_Engagement)),K("complete",()=>e(t.Gameplay_Complete)),K("cta_click",()=>e(t.DSP_Click)),K("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function sl(){if(!Ye())return;let i=window.TJ_API;i&&i.setPlayableAPI&&i.setPlayableAPI({skipAd:()=>{try{ne.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Er(){var e,t,n;let i=window.TJ_API;(e=i==null?void 0:i.objectiveComplete)==null||e.call(i),(t=i==null?void 0:i.playableFinished)==null||t.call(i),(n=i==null?void 0:i.gameplayFinished)==null||n.call(i)}function rl(){We()&&(window.mintGameStart=()=>{zt(!0),Me()},window.mintGameClose=()=>{ct(!0)})}function ol(){if(!ii())return;let i=window.NUC;!i||!i.trigger||(ne.on("cta_click",()=>{var e,t;return(t=(e=i.trigger).convert)==null?void 0:t.call(e,at)}),ne.on("complete",()=>{var e,t;return(t=(e=i.trigger).tryAgain)==null?void 0:t.call(e)}))}var ne={init(i={},e){var t;if(Cr=i.profile||"web_embed",ba=i.consent||{},it={...Ar,...i.ids||{}},st=i.rootEl||st,Rt=void 0,La((t=i.telemetry)!=null&&t.endpoint?i.telemetry:null),Be=null,va=!1,xa=!1,Gn.clear(),at=i.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(Vn=e),L("init"),document.body.oncontextmenu=()=>!1,vr(),cl(st),Qa(),tl(),nl(),!Yn){if(document.readyState==="complete")xr();else if(!yr){yr=!0;let n=()=>{xr(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}il(),al(),sl(),rl(),ol(),console.log(`%c @handler/playable-sdk %c v${ga} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ve&&!ye&&(L("boot"),L("view"),L("ready"),jt&&(jt=!1,ne.start()),ye=!0),ye=ve},getRoot(){return vr()},get version(){return ga},get maxWidth(){return rt},get maxHeight(){return ot},get isLandscape(){return ya},get isReady(){return ye},get isStarted(){return fa},get isPaused(){return Dt},get isFinished(){return It},get volume(){return wa},get interactions(){return qn},on(i,e){Bt(Wn(i),e)},off(i,e){ei(Wn(i),e)},start(){var i,e;if(!fa){if(!ve){jt=!0;return}if(fa=!0,Be||(Be=Date.now()),L("start"),Me(),We())ct(),(i=window.gameReady)==null||i.call(window);else if(Ye()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:ya?"landscape":"portrait",buildID:ga})}}},finish(){var i,e;It||(It=!0,L("complete"),ma("complete"),We()?(i=window.gameEnd)==null||i.call(window):ni()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Ye()&&Er())},install(i){if(!It){It=!0,Ye()?(Er(),setTimeout(()=>ne.install(i),300)):(L("complete"),setTimeout(()=>ne.install(i),0));return}ha||(ha=!0,setTimeout(()=>ha=!1,500),L("cta_click"),L("conversion"),ma("cta"),wr(i||at))},emit(i,e){let t=Wn(i);if(!el.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${i} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=_r(t,e);ti(n,!!ba.analytics),Ft(t,n)},gameStart(){ne.start()},gameEnd(){ne.finish()},ctaClick(i,e){L("cta_click",{url:i||at,manual:!0}),(e==null?void 0:e.open)!==!1&&wr(i||at)},ctaShow(i){L("cta_show",i)},ctaDismiss(i){L("cta_dismiss",i)},getGameTimeMs(){return Tr()},endSession(i="manual"){ma(i)},setAttribution(i){Rt=i},abTest(i,e){if(!i)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(ll(`${Sr}:${i}`))%e.length,n=e[t];return Rt={...Rt||{},experiment_id:i},it.variant_id=n,L("ab_assign",{experiment_id:i,variant_id:n}),n},levelStart(i,e){Be||(Be=Date.now()),L("level_start",{level_id:i,...e})},levelComplete(i,e){L("level_complete",{level_id:i,...e})},levelFail(i,e){L("level_fail",{level_id:i,...e})},checkpoint(i,e){L("checkpoint",{checkpoint_id:i,...e})},reward(i,e){L("reward",{reward_id:i,...e})},tutorialStart(i,e){L("tutorial_start",{step_id:i,...e})},tutorialComplete(i,e){L("tutorial_complete",{step_id:i,...e})},tutorialSkip(i,e){L("tutorial_skip",{step_id:i,...e})},timerStart(i){i&&Gn.set(i,Date.now())},timerEnd(i,e="custom",t){if(!i)return;let n=Gn.get(i);if(!n)return;Gn.delete(i);let a=Date.now()-n;if(!(!Number.isFinite(a)||a<0)){if(e==="custom"){L("engagement",{action:"timer",key:i,duration_ms:a,...t});return}L(e,{key:i,duration_ms:a,...t})}},fps(i,e){L("fps",{value:i,...e})},memory(i,e){L("memory",{bytes:i,...e})},assetLoadStart(i,e){L("asset_load_start",{asset_id:i,...e})},assetLoadComplete(i,e){L("asset_load_complete",{asset_id:i,...e})},reportError(i,e,t){L("error",{code:i,message:e,...t})},retry(){var i,e,t;if(We())(i=window.gameRetry)==null||i.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)}L("engagement",{action:"retry"})},pause(){ct(!0)},resume(){zt(!0)},resize(i,e){Me(i,e)}},Oe=ne;function ll(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function cl(i){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
1693
+ `,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 ga=Ra.version,el=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"]);Ia();var As={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"},Ss=Math.random().toString(36).slice(2),rt=null,it={...As},Cs="web_embed",ba={},Rt,fa=!1,It=!1,Dt=!1,Ls=!1,wa=1,qn=0,Yn=!1,ye=!1,at="",st=Math.floor(window.innerWidth),ot=Math.floor(window.innerHeight),ya=st>ot,ve=!1,jt=!1,bs=!1,ys=!1,ha=!1,Vn=null,Be=null,va=!1,xa=!1,Gn=new Map;function Ts(){if(!Be)return null;let i=Date.now()-Be;return!Number.isFinite(i)||i<0?null:i}function ma(i){if(va)return;let e=Ts();e!==null&&(va=!0,L("session_time",{duration_ms:e,reason:i}))}function vs(){if(rt)return rt;let i=document.createElement("div");return i.id="handler-root",i.setAttribute("data-handler-root","true"),document.body.appendChild(i),rt=i,i}function Wn(i){switch(i){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return i}}function _s(i,e){return{event_name:i,ts:Date.now(),session_id:Ss,deployment_id:it.deployment_id,variant_id:it.variant_id,export_profile_id:it.profile_id,instance_id:it.instance_id||"default",env:Cs==="mraid"?"mraid":"web",attribution:Rt,payload:e}}function L(i,e){let t=Wn(i),n=_s(t,e);ti(n,!!ba.analytics),Ft(t,n),t!==i&&Ft(i,n)}function $t(){Vn&&(Vn(st,ot),Vn=null)}function lt(i){wa=i,L("volume",i)}function ct(i){i&&(Ls=!0),!Dt&&(Dt=!0,L("pause"),lt(0))}function zt(i){!i&&Ls||Dt&&(Dt=!1,L("resume"),lt(wa))}function Me(i,e){st=Math.floor(i||window.innerWidth),ot=Math.floor(e||window.innerHeight),ya=st>ot,L("resize",{width:st,height:ot})}function tl(){if(Va())try{let i=mraid.getMaxSize();Me(i.width,i.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?zt():ct()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Me(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();lt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&lt(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),Yn=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};mraid.addEventListener("ready",t)}}catch(i){console.warn("MRAID hook skipped",i)}}function nl(){if(Wa())try{let i=dapi.getScreenSize();Me(i.width,i.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?zt():ct()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Me(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(lt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>lt(t?1:0)),Yn=!0,dapi.isViewable())ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};dapi.addEventListener("ready",t)}}catch(i){console.warn("DAPI hook skipped",i)}}function xs(){let i=()=>{ve||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t(),jt&&(jt=!1,ne.start()))};window.addEventListener("resize",()=>Me()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(zt(),i()):ct()}),document.readyState==="complete"||document.readyState==="interactive"?i():window.addEventListener("load",i),Yn=!0}function il(){let i=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(bs=!0),!(bs&&e instanceof MouseEvent)&&(qn+=1,xa||(xa=!0,L("first_interaction",{count:qn})),L("interaction",qn))};document.addEventListener("mousedown",i),document.addEventListener("touchstart",i)}function ws(i){var n,a,r,s,o,l,c,p,d,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(i||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Ye())(r=(a=window.TJ_API)==null?void 0:a.click)==null||r.call(a);else if(Ya())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(Za())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(Ja())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(f){console.warn("Smadex redirect failed",f)}else if(Ka()){let f=window.ExitApi;f&&typeof f.exit=="function"?f.exit(i||at||""):i&&window.open(i)}else We()?(u=window.install)==null||u.call(window):Xa()?(g=window.openAppStore)==null||g.call(window):ni()?(h=parent==null?void 0:parent.postMessage)==null||h.call(parent,"download","*"):i&&window.open(i)}function al(){let i=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(i==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;K("view",()=>e(t.mraid_viewable)),K("start",()=>e(t.game_viewable)),K("engagement",()=>e(t.engagement));let n=()=>e(t.complete);K("complete",n),Bt("engagement",a=>{var r;((r=a==null?void 0:a.payload)==null?void 0:r.count)>3&&n()}),K("cta_click",()=>e(t.click))}else if(i==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;K("view",()=>e(t.Ad_Load_Start)),K("start",()=>e(t.Ad_Viewable)),K("engagement",()=>e(t.First_Engagement)),K("complete",()=>e(t.Gameplay_Complete)),K("cta_click",()=>e(t.DSP_Click)),K("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function rl(){if(!Ye())return;let i=window.TJ_API;i&&i.setPlayableAPI&&i.setPlayableAPI({skipAd:()=>{try{ne.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Es(){var e,t,n;let i=window.TJ_API;(e=i==null?void 0:i.objectiveComplete)==null||e.call(i),(t=i==null?void 0:i.playableFinished)==null||t.call(i),(n=i==null?void 0:i.gameplayFinished)==null||n.call(i)}function sl(){We()&&(window.mintGameStart=()=>{zt(!0),Me()},window.mintGameClose=()=>{ct(!0)})}function ol(){if(!ii())return;let i=window.NUC;!i||!i.trigger||(ne.on("cta_click",()=>{var e,t;return(t=(e=i.trigger).convert)==null?void 0:t.call(e,at)}),ne.on("complete",()=>{var e,t;return(t=(e=i.trigger).tryAgain)==null?void 0:t.call(e)}))}var ne={init(i={},e){var t;if(Cs=i.profile||"web_embed",ba=i.consent||{},it={...As,...i.ids||{}},rt=i.rootEl||rt,Rt=void 0,La((t=i.telemetry)!=null&&t.endpoint?i.telemetry:null),Be=null,va=!1,xa=!1,Gn.clear(),at=i.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(Vn=e),L("init"),document.body.oncontextmenu=()=>!1,vs(),cl(rt),Qa(),tl(),nl(),!Yn){if(document.readyState==="complete")xs();else if(!ys){ys=!0;let n=()=>{xs(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}il(),al(),rl(),sl(),ol(),console.log(`%c @handler/playable-sdk %c v${ga} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ve&&!ye&&(L("boot"),L("view"),L("ready"),jt&&(jt=!1,ne.start()),ye=!0),ye=ve},getRoot(){return vs()},get version(){return ga},get maxWidth(){return st},get maxHeight(){return ot},get isLandscape(){return ya},get isReady(){return ye},get isStarted(){return fa},get isPaused(){return Dt},get isFinished(){return It},get volume(){return wa},get interactions(){return qn},on(i,e){Bt(Wn(i),e)},off(i,e){ei(Wn(i),e)},start(){var i,e;if(!fa){if(!ve){jt=!0;return}if(fa=!0,Be||(Be=Date.now()),L("start"),Me(),We())ct(),(i=window.gameReady)==null||i.call(window);else if(Ye()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:ya?"landscape":"portrait",buildID:ga})}}},finish(){var i,e;It||(It=!0,L("complete"),ma("complete"),We()?(i=window.gameEnd)==null||i.call(window):ni()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Ye()&&Es())},install(i){if(!It){It=!0,Ye()?(Es(),setTimeout(()=>ne.install(i),300)):(L("complete"),setTimeout(()=>ne.install(i),0));return}ha||(ha=!0,setTimeout(()=>ha=!1,500),L("cta_click"),L("conversion"),ma("cta"),ws(i||at))},emit(i,e){let t=Wn(i);if(!el.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${i} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=_s(t,e);ti(n,!!ba.analytics),Ft(t,n)},gameStart(){ne.start()},gameEnd(){ne.finish()},ctaClick(i,e){L("cta_click",{url:i||at,manual:!0}),(e==null?void 0:e.open)!==!1&&ws(i||at)},ctaShow(i){L("cta_show",i)},ctaDismiss(i){L("cta_dismiss",i)},getGameTimeMs(){return Ts()},endSession(i="manual"){ma(i)},setAttribution(i){Rt=i},abTest(i,e){if(!i)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(ll(`${Ss}:${i}`))%e.length,n=e[t];return Rt={...Rt||{},experiment_id:i},it.variant_id=n,L("ab_assign",{experiment_id:i,variant_id:n}),n},levelStart(i,e){Be||(Be=Date.now()),L("level_start",{level_id:i,...e})},levelComplete(i,e){L("level_complete",{level_id:i,...e})},levelFail(i,e){L("level_fail",{level_id:i,...e})},checkpoint(i,e){L("checkpoint",{checkpoint_id:i,...e})},reward(i,e){L("reward",{reward_id:i,...e})},tutorialStart(i,e){L("tutorial_start",{step_id:i,...e})},tutorialComplete(i,e){L("tutorial_complete",{step_id:i,...e})},tutorialSkip(i,e){L("tutorial_skip",{step_id:i,...e})},timerStart(i){i&&Gn.set(i,Date.now())},timerEnd(i,e="custom",t){if(!i)return;let n=Gn.get(i);if(!n)return;Gn.delete(i);let a=Date.now()-n;if(!(!Number.isFinite(a)||a<0)){if(e==="custom"){L("engagement",{action:"timer",key:i,duration_ms:a,...t});return}L(e,{key:i,duration_ms:a,...t})}},fps(i,e){L("fps",{value:i,...e})},memory(i,e){L("memory",{bytes:i,...e})},assetLoadStart(i,e){L("asset_load_start",{asset_id:i,...e})},assetLoadComplete(i,e){L("asset_load_complete",{asset_id:i,...e})},reportError(i,e,t){L("error",{code:i,message:e,...t})},retry(){var i,e,t;if(We())(i=window.gameRetry)==null||i.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)}L("engagement",{action:"retry"})},pause(){ct(!0)},resume(){zt(!0)},resize(i,e){Me(i,e)}},Oe=ne;function ll(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function cl(i){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
1694
1694
  (function(){
1695
1695
  var events = ['touchstart','touchend','mousedown','keydown'];
1696
1696
  function unlock(){