handler-playable-sdk 0.4.62 → 0.4.73

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 Io=Object.create;var Ft=Object.defineProperty;var jo=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var Do=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var de=(n,e)=>()=>(n&&(e=n(n=0)),e);var ht=(n,e)=>{for(var t in e)Ft(n,t,{get:e[t],enumerable:!0})},La=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ro(e))!$o.call(n,a)&&a!==t&&Ft(n,a,{get:()=>e[a],enumerable:!(i=jo(e,a))||i.enumerable});return n};var qe=(n,e,t)=>(t=n!=null?Io(Do(n)):{},La(e||!n||!n.__esModule?Ft(t,"default",{value:n,enumerable:!0}):t,n)),zo=n=>La(Ft({},"__esModule",{value:!0}),n);var pe,ln=de(()=>{"use strict";pe=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};pe.store=new Map});function Vo(){var n,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(n=document.querySelector("script"))==null?void 0:n.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),i=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!i)}catch{return!1}}async function Wo(){try{if(typeof window!="undefined"){let n=await fetch("./build-settings.json");if(n.ok){let e=await n.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Yo(){try{if(typeof window!="undefined"){let n=new XMLHttpRequest;if(n.open("GET","./build-settings.json",!1),n.send(),n.status===200&&n.responseText){let e=JSON.parse(n.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Ko(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${N}`),Object.keys(ue).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(ue)),ue;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),ue={...window.INLINE_ASSETS},ue;if(!(N==="publish"&&re!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ue;if(!cn){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),cn=(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 i=await t.text();console.log("[AssetLoader] Received JS code, length:",i.length);let a=i.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 o=new Function("return "+r)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(o)),o}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:",i.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ue=await cn,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ue)),ue}function dn(n){return n===null||typeof n!="object"||(Object.freeze(n),Object.values(n).forEach(e=>dn(e))),n}function Xo(n=64,e=64,t=16711680){let i=document.createElement("canvas");i.width=n,i.height=e;let a=i.getContext("2d");return a.fillStyle=`#${t.toString(16).padStart(6,"0")}`,a.fillRect(0,0,n,e),a.strokeStyle="#000",a.strokeRect(0,0,n,e),a.fillStyle="#fff",a.font="10px sans-serif",a.textAlign="center",a.fillText("MISSING",n/2,e/2),ge.Texture.from(i)}function pn(n,e){rr.set(n,e)}var ge,nr,ar,Ie,N,re,Ee,ue,cn,rr,je,Vt=de(()=>{"use strict";ge=require("pixi.js");ln();nr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ar=Vo(),Ie=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,N=ar?"publish":nr,re=Ie==null?void 0:Ie.assetsInlined;Ie!=null&&Ie.buildMode&&(N=Ie.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${N}`));Ee=Yo();Ee!=null&&Ee.buildMode&&(N=Ee.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${N}`));(Ee==null?void 0:Ee.assetsInlined)!==void 0&&(re=Ee.assetsInlined);Wo().then(n=>{n!=null&&n.buildMode&&n.buildMode!==N&&(N=n.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${N}`)),(n==null?void 0:n.assetsInlined)!==void 0&&(re=n.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${nr}, Runtime: ${ar?"publish":"dev"}, Effective: ${N}`);ue={},cn=null;rr=new Map;je=class{static async load(e,t,i,a){let r=`${e}:${t.path}`,o=pe.get(r);if(o!==void 0)return o;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 s=await Ko(),l=s[e];if(!l&&a&&(l=s[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];s[u]&&(l=s[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=rr.get(t.type);if(p)try{let d=await p(t.path,l,e,i);return pe.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=dn(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return pe.set(r,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let i=N==="publish",a=i&&re!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${N}, isPublishMode: ${i}, 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 ge.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 ge.Assets.load(t)}catch(r){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",r),await ge.Assets.load(e)}return await ge.Assets.load(e)}static async loadJSON(e,t){let i=N==="publish",a=i&&re!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${N}, isPublishMode: ${i}, 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 o=atob(t.split(",")[1]);return JSON.parse(o)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let o=atob(t.split(",")[1]);return JSON.parse(o)}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,i){if(N==="dev"){let r=t==="image"?Xo():dn({__placeholder:!0,type:t});return pe.set(e+":"+((i==null?void 0:i.path)||"missing"),r),r}throw i}};pn("image",async(n,e)=>{let t=N==="publish",i=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"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${n}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return ge.Assets.load(e)}let o=n;return(a||r)&&n&&!n.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(o=n,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${n}" as-is`)):(o=`assets/${n}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${n}" -> "${o}"`))),ge.Assets.load(e||o)});pn("json",async(n,e)=>{let t=N==="publish",i=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"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${n}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let o=n;if((a||r)&&n&&!n.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(o=n,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${n}" as-is`)):(o=`assets/${n}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${n}" -> "${o}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let s=await fetch(o);if(!s.ok)throw new Error(`JSON fetch failed: ${n}`);return s.json()})});var sr={};ht(sr,{AssetTextures:()=>oe,initAssetTextures:()=>hn});function hn(n,e){or.init(n,e),typeof window!="undefined"&&(window.__AssetTextures=oe)}var gn,or,oe,Ke=de(()=>{"use strict";Vt();gn=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(i=>{this.priorityReadyResolve=i}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var o;console.log("[AssetTextures] Loading all assets...");let i=new Set(["background_loading_1"]),a=[],r=[];for(let[s,l]of e.objects.entries()){let c=(o=l.render)==null?void 0:o.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}: ${s} (${u})`);let g=await je.load(s,c,t,u);this.textures.set(s,g),console.log(`[AssetTextures] \u2713 Loaded: ${s}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${s}`,u)}finally{this.attempted.add(s);try{for(let u of Array.from(this.waiters))u()}catch{}}};i.has(s)?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(s=>typeof s=="string"&&s))).filter(s=>{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,s);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(s=>this.textures.has(s)||this.attempted.has(s));if(r())return;let o=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(s=>{let l=!1,c=()=>{l||r()&&(l=!0,this.waiters.delete(c),s())};this.waiters.add(c),c(),o>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:a}),s())},o)})}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())}},or=new gn,oe=new Proxy(or,{get(n,e){return e in n&&typeof n[e]=="function"?n[e].bind(n):n.get(e)},set(n,e,t){return n.set(e,t),!0}})});var Xe={};ht(Xe,{applyConfigOverride:()=>Se,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>ri,clearConfigOverrides:()=>se,clearConfigOverridesForObject:()=>vr,configOverrideManager:()=>xr,deepClone:()=>G,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>Y,getConfigStateSummary:()=>ai,getOverrideMode:()=>wt,removeConfigOverride:()=>ni,resetToApplied:()=>Et,resetToOriginal:()=>oi,setOverrideMode:()=>yn});function ti(){return typeof window=="undefined"?null:window.__editableConfig||null}function hr(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function ur(n,e){var t,i;if(!n)return null;try{if(n instanceof Map)return(t=n.get(e))!=null?t:null;if(typeof n=="object")return(i=n[e])!=null?i:null}catch{}return null}function Es(n,e,t){if(n){if(n instanceof Map){n.set(e,t);return}typeof n=="object"&&(n[e]=t)}}function fr(n,e){for(let t of e)xt(n,t.path,t.value)}function mr(n){var s;if(typeof window=="undefined")return;let e=ti();if(!e)return;let t=hr(),i=(s=t?ur(t.objects,n):null)!=null?s:ur(e.objects,n);if(!i)return;let a=G(i),r=Y().filter(l=>l.objectId===n);try{fr(a,r)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",n,l);return}Es(e.objects,n,a);let o=window.applyEditableObjectConfig;if(typeof o=="function")try{o(n,a)}catch{}}function As(){var a;if(typeof window=="undefined")return;let n=ti();if(!(n!=null&&n.engine))return;let e=hr(),t=G(((a=e==null?void 0:e.engine)!=null?a:n.engine)||{}),i=Y().filter(r=>!r.objectId&&!r.sceneId);try{fr(t,i)}catch(r){console.error("[CONFIG] Failed to reapply engine overrides",r);return}try{let r=n.engine;for(let o of Object.keys(r))o in t||delete r[o];for(let[o,s]of Object.entries(t))r[o]=s}catch{n.engine=t}}function Ss(){if(typeof window=="undefined")return"unknown";let n=window;return typeof n.__HANDLER_PROJECT_ID=="string"?n.__HANDLER_PROJECT_ID:"handler-default"}function br(){return`handler_preview_config_overrides::${Ss()}`}function Cs(){if(typeof window=="undefined")return[];try{let n=window.localStorage.getItem(br());if(!n)return[];let e=JSON.parse(n);return Array.isArray(e)?e:[]}catch{return[]}}function ii(n){if(typeof window!="undefined")try{window.localStorage.setItem(br(),JSON.stringify(n))}catch{}}function wt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function yn(n){if(typeof window!="undefined"){window.__enableConfigOverrides=n;try{window.localStorage.setItem(yr,n?"true":"false")}catch{}}}function Se(n,e={}){var u,g;let{objectId:t,path:i,value:a}=n,{silent:r=!1,persist:o=!0,emitEvent:s=!0}=e,l=ti();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:i,hasObjects:!!l.objects});return}r||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:i,value:a});let p;try{p=Ts(c,i),xt(c,i,a)}catch(m){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:i,value:a},m);return}window.__configChanges=window.__configChanges||[];let d=window.__configChanges;if(d.push({objectId:t,path:i,oldValue:p,newValue:a,ts:Date.now()}),d.length>Ls&&d.shift(),o){let m=Y(),h=m.findIndex(f=>f.objectId===t&&f.sceneId===n.sceneId&&f.path===i);h>=0?m[h].value=a:m.push(n),window.__configOverrides=m,ii(m),wt()||yn(!0)}r||console.log("[CONFIG] Applied override:",n),s&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:n}))}function Ce(n,e={}){let t=e.emitEvent!==!1,i=[];for(let a of n)a!=null&&a.objectId&&typeof a.objectId=="string"&&i.push(a.objectId),Se(a,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let a=Array.from(new Set(i));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:a,count:n.length}}))}}function se(){window.__configOverrides=[],window.__configChanges=[],ii([]),console.log("[CONFIG] Cleared all overrides")}function vr(n){let e=Y().filter(i=>i.objectId!==n);window.__configOverrides=e,ii(e);let t=window.__configChanges||[];window.__configChanges=t.filter(i=>i.objectId!==n),mr(n),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:n}}))}function ni(n,e){let t=Y().filter(a=>a.objectId!==n||a.path!==e);window.__configOverrides=t,ii(t);let i=window.__configChanges||[];window.__configChanges=i.filter(a=>a.objectId!==n||a.path!==e),n?mr(n):As(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:n,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Cs()),window.__configOverrides||[])}function xt(n,e,t){var o;let i=e.split("."),a=i.pop(),r=n;for(let s of i){if(r[s]!==void 0&&typeof r[s]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${s})`);r[s]=(o=r[s])!=null?o:{},r=r[s]}r[a]=t}function Ts(n,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,n)}function G(n){if(n===null||typeof n!="object")return n;if(n instanceof Date)return new Date(n.getTime());if(n instanceof Set)return new Set([...n].map(t=>G(t)));if(ArrayBuffer.isView(n))return n.slice();if(n instanceof Array)return n.map(t=>G(t));if(n instanceof Map){let t=new Map;return n.forEach((i,a)=>t.set(a,G(i))),t}let e={};for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(e[t]=G(n[t]));return e}function De(){let n=window.__editableConfigBaseline;if(!n){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return gr(e)}return gr(n)}function gr(n){let e={objects:{},scenes:{},engine:G(n.engine||{})},t=n.objects;if(t instanceof Map)t.forEach((r,o)=>{e.objects[o]=G(r)});else if(t&&typeof t=="object")for(let r in t)e.objects[r]=G(t[r]);let i=n.scenes;if(i instanceof Map)i.forEach((r,o)=>{e.scenes[o]=G(r)});else if(i&&typeof i=="object")for(let r in i)e.scenes[r]=G(i[r]);let a=Y();for(let r of a)r.objectId?(e.objects[r.objectId]||(e.objects[r.objectId]={}),xt(e.objects[r.objectId],r.path,r.value)):r.sceneId?(e.scenes[r.sceneId]||(e.scenes[r.sceneId]={}),xt(e.scenes[r.sceneId],r.path,r.value)):xt(e.engine,r.path,r.value);return e}function ai(){let n=Y(),e=new Set;for(let t of n)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:n.length,hasChanges:n.length>0,overrides:n}}async function ri(n){let e=De(),t={};for(let[a,r]of Object.entries(e.objects)){let o=r,s=a;/^(json\.|ui\.|effects\.|engine\.)/.test(s)||(s=`json.${a}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=s),t[`objects/${s}.json`]=o}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 o=a.startsWith("scene.")?a:`scene.${a}`;t[`scenes/${o}.json`]=r}let i=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:n})});if(!i.ok){let a=await i.json();throw new Error(`Apply failed: ${a.error||"Unknown error"}`)}se();try{let a=ti();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(){se(),window.location.reload()}async function oi(){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"}`)}se(),window.location.reload()}var yr,Ls,xr,K=de(()=>{"use strict";yr="handler_preview_override_mode";if(typeof window!="undefined"){let n=window.localStorage.getItem(yr);window.__enableConfigOverrides=n===null?!0:n==="true"}Ls=500;xr={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function ks(n,e){try{if(typeof n=="object"&&n!==null)return n;if(typeof n!="string")return null;if(n.startsWith("data:")){let i=n.indexOf(",");if(i===-1)return null;let a=n.slice(0,i);if(!a.includes("application/json")&&!a.includes("text/plain"))return null;let r=n.slice(i+1),o=a.includes("base64")?typeof atob=="function"?atob(r):r:decodeURIComponent(r);return JSON.parse(o)}let t=n.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(n):null}catch{return null}}function _s(n){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=n.replace(/^\.\/+/,""),i=t.split("/").pop()||t,a=[t,i,t.replace(/\.json$/,""),i.replace(/\.json$/,"")];for(let r of a){let o=e[r];if(o){let s=ks(o,r);if(s!==null)return s}}return null}async function At(n){if(vn.has(n)&&!xn)return console.log(`[CONFIG] Using cached config for: "${n}"`),vn.get(n);if(console.log(`[CONFIG] loadConfigFile called with: "${n}", MODE: ${z.toUpperCase()}, CACHE: ${xn?"DISABLED":"ENABLED"}`),z==="publish"){let i=_s(n);return i?(console.log(`[CONFIG] \u2713 Loaded ${n} via INLINE_ASSETS`),i):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${n} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}z==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${n}"`);let e;z==="brand"?e=[`./${n.split("/").pop()||n}`,`./${n}`,`./${n.replace(/^configs\//,"")}`,`./${n.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${n}`,`./${n.replace(/^configs\//,"")}`,`./${n.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(i=>i.startsWith("./")?[i,`/${i.slice(2)}`]:i.startsWith("/")?[i]:[i,`/${i}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let i=xn?"no-store":"force-cache";for(let a of e)try{let r=await fetch(a,{cache:i});if(!r.ok)continue;let o=await r.json();return console.log(`[CONFIG] \u2713 Loaded ${n} via ${a}`,o),o}catch(r){console.warn(`[CONFIG] \u2717 Failed to load ${a} (mode: ${z}):`,r)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${n}; using defaults`),{}})();return vn.set(n,t),t}async function si(){console.log("[CONFIG] Loading component schemas...");let n=["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 n)try{let i=z==="publish"||z==="brand"?t.split("/").pop()||t:`configs/${t}`,a=await At(i);a.component&&(e.set(a.component,a),console.log(`[CONFIG] \u2713 Schema loaded: ${a.component} ${z==="publish"||z==="brand"?"(flattened)":"(nested)"}`))}catch(i){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,i)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Le(n){console.log(`[CONFIG] Loading object config: ${n}`);let e=z==="publish"||z==="brand"?`${n}.json`:`configs/objects/${n}.json`;return await At(e)}async function li(n){let e=new Map;if(n.objects&&Array.isArray(n.objects)){for(let t of n.objects)if(t.enabled&&t.object_config)try{let i=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(i)||(i=`json.${i}`);let a=await Le(i);(!a||Object.keys(a).length===0)&&i!==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(i){console.warn(`Failed to load object ${t.object_config}:`,i)}}return e}async function ci(){console.log("[CONFIG] Loading engine configs...");let n=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(n.map(i=>{let a=`engine.${i}.json`,r=z==="publish"||z==="brand"?a:`configs/engine/${a}`;return At(r)})),t=Object.fromEntries(n.map((i,a)=>[i,e[a]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(n.map(i=>{var o;let a=(o=t[i])!=null?o:{},r=Object.keys(a);return[i,r.length>0?r:"empty"]}))),t}async function wn(){return await At(z==="publish"||z==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function di(n="scene.main"){console.log(`[CONFIG] Loading scene config: ${n}`);let e=z==="publish"||z==="brand"?`${n}.json`:`configs/scenes/${n}.json`;return await At(e)}function Je(n,e){let t=[];if(!n.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let i=e.get("identity");if(i)for(let a of i.required||[])n.identity[a]||t.push(`Missing required identity field: ${a}`);for(let[a,r]of Object.entries(n)){if(a==="identity")continue;let o=e.get(a);if(o&&r&&typeof r=="object"){let s=r;for(let l of o.required||[])s[l]===void 0&&t.push(`Missing required field in ${a}: ${l}`);if(o.constraints&&typeof o.constraints=="object")for(let[l,c]of Object.entries(o.constraints)){let p=s[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 $e(n,e){let t={...n},i=["identity","transform","render"];for(let[a,r]of e.entries())r.defaults&&Object.keys(r.defaults).length>0&&(i.includes(a)||t[a])&&(t[a]||(t[a]={}),t[a]={...r.defaults,...t[a]});return t}function Q(n,e,t,i){return typeof n!="number"||!Number.isFinite(n)?e:Math.min(Math.max(n,t),i)}function Er(n,e){if(Array.isArray(n))return{x:Q(n[0],e.x,-2e3,2e3),y:Q(n[1],e.y,-2e3,2e3)};if(!n||typeof n!="object")return e;let{x:t,y:i}=n;return{x:Q(t,e.x,-2e3,2e3),y:Q(i,e.y,-2e3,2e3)}}function Ps(n,e){if(Array.isArray(n))return{x:Q(n[0],e.x,0,1),y:Q(n[1],e.y,0,1)};if(!n||typeof n!="object")return e;let{x:t,y:i}=n;return{x:Q(t,e.x,0,1),y:Q(i,e.y,0,1)}}function Ms(n){if(Array.isArray(n))return{x:Q(n[0],.5,-10,10),y:Q(n[1],.5,-10,10)};if(n&&typeof n=="object"){let{x:e,y:t}=n;return{x:Q(e,.5,-10,10),y:Q(t,.5,-10,10)}}return typeof n=="string"?n:null}async function be(n="scene.main",e){var l,c,p,d,u,g,m,h,f,b,y,v,x,w;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await si(),i=Y();i.length>0&&console.log(`[CONFIG] Applying ${i.length} active overrides`);let a=await di(n);console.log(`[CONFIG] Scene config loaded: ${((l=a.objects)==null?void 0:l.length)||0} objects`);let r=await ci();console.log("[CONFIG] Loading object configs...");let o=await li(a);console.log(`[CONFIG] Loaded ${o.size} object configs:`,Array.from(o.keys()));for(let[E,C]of o.entries()){let A=$e(C,t),M=Je(A,t);M.valid||console.warn(`Object ${E} validation errors:`,M.errors),(c=A.transform)!=null&&c.position&&(A.transform.position=Er(A.transform.position,{x:0,y:0})),(p=A.transform)!=null&&p.offset&&(A.transform.offset=Er(A.transform.offset,{x:0,y:0})),((d=A.transform)==null?void 0:d.anchor)!==void 0&&(A.transform.anchor=Ms(A.transform.anchor)),((u=A.transform)==null?void 0:u.position_ratio)!==void 0&&A.transform.position_ratio!==null&&(A.transform.position_ratio=Ps(A.transform.position_ratio,{x:.5,y:.5})),o.set(E,A)}if(e){if(e.objects)for(let[E,C]of e.objects.entries())o.set(E,C);e.engine&&(r.runtime={...r.runtime,...e.engine.runtime},r.assets={...r.assets,...e.engine.assets},r.splash={...(g=r.splash)!=null?g:{},...(m=e.engine.splash)!=null?m:{}})}let s={objects:o,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=s,window.__editableConfigBaseline||(window.__editableConfigBaseline=$e(s,t))),i.length>0&&wt()&&Ce(i,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(o.keys()),engine:{runtime:Object.keys((h=r.runtime)!=null?h:{}),assets:Object.keys((f=r.assets)!=null?f:{}),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((w=r.endgame)!=null?w:{})},scene:a.scene_id||"unknown"}),s}function En(n){var t,i,a,r,o,s,l,c,p,d,u,g,m,h,f,b,y,v,x,w,E,C,A,M,B,P,L,I,O,D,j,$,S;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[k,_]of n.objects.entries()){let q=((t=_.identity)==null?void 0:t.id)||k;q.includes("character")&&(e.gameplay.character_pos=((i=_.transform)==null?void 0:i.position)||{x:0,y:0},e.gameplay.character_scale=((a=_.transform)==null?void 0:a.scale)||1,e.gameplay.character_anim_speed=((o=(r=_.gameplay)==null?void 0:r.tuning)==null?void 0:o.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(s=_.gameplay)==null?void 0:s.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=_.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(q.includes("gun")||q.includes("flame"))&&(e.gameplay.gun=_.gun||{},e.gameplay.gunmuzzle=((d=_.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=_.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=_.effects)==null?void 0:g.flame)||{}),q.includes("diamond")&&(e.gameplay.diamond=_),q.includes("ice")&&(e.gameplay.melt=_.melt||{},e.gameplay.melt_anchor=((m=_.transform)==null?void 0:m.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((h=_.transform)==null?void 0:h.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=_.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((b=_.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=_.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=_.hard_ice||{}),q.includes("water")&&(e.gameplay.water_drops=_),q.includes("crack")&&(e.gameplay.crack=_),q.includes("hand")&&(e.gameplay.hand=((v=_.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((x=_.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((w=_.transform)==null?void 0:w.scale)||1.5),q.includes("hazard")&&(e.gameplay.hazard=((E=_.gameplay)==null?void 0:E.tuning)||{},e.gameplay.danger_pos=((C=_.transform)==null?void 0:C.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((M=(A=_.gameplay)==null?void 0:A.tuning)==null?void 0:M.danger_pulse)||{},e.gameplay.hazard_height=((P=(B=_.gameplay)==null?void 0:B.tuning)==null?void 0:P.hazard_height)||140)}return e.gameplay.timeline=((L=n.engine.runtime)==null?void 0:L.timeline)||{},e.gameplay.drag_surface=((I=n.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((O=n.engine.runtime)==null?void 0:O.background)||{},e.gameplay.ui_styles=((D=n.engine.runtime)==null?void 0:D.ui_styles)||{},e.gameplay.label_pulse=((j=n.engine.runtime)==null?void 0:j.label_pulse)||{},e.ui=(($=n.engine.runtime)==null?void 0:$.ui)||{},e.theme=((S=n.engine.runtime)==null?void 0:S.theme)||{},e.assets=n.engine.assets||{},e}var wr,z,vn,xn,An=de(()=>{"use strict";K();wr=null,z="dev";if(typeof window!="undefined"){let n=window.__BUILD_SETTINGS__;if(n!=null&&n.buildMode)wr=n,z=n.buildMode,console.log("[CONFIG] Loaded inline build settings:",n,"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);wr=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);vn=new Map,xn=z==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Sn(n,e){let t=[];function i(a,r,o=""){if(a!==r){if(typeof a!=typeof r){t.push(`${o}: type changed`);return}if(typeof a=="object"&&a!==null&&r!==null){let s=new Set([...Object.keys(a),...Object.keys(r)]);for(let l of s){let c=o?`${o}.${l}`:l;l in a?l in r?i(a[l],r[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${o}: changed`)}}return i(n,e),t}function Cn(n,e,t,i){let a={...t};for(let[r,o]of i.entries())a[r]&&o.defaults&&(a[r]={...o.defaults,...a[r]});return a}var St,ze,Ln=de(()=>{"use strict";St=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},ze=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let i=`${e}?t=${Date.now()}&r=${Math.random()}`,a=await fetch(i,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(a.ok){let r=await a.text(),o=this.hashString(r),s=this.fileHashes.get(e);if(s&&s!==o&&console.log(`[HOT-RELOAD] File changed: ${e}`),s&&s!==o){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,o)}else s||this.fileHashes.set(e,o)}}catch(i){console.warn(`Failed to check ${e}:`,i)}}determineEventType(e){var t,i;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(i=e.split("/").pop())==null?void 0:i.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let i=0;i<e.length;i++){let a=e.charCodeAt(i);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 kn(n){if(typeof window=="undefined")return;let e=typeof Tn!="undefined"&&!!Tn.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let a=null,r=!1,o=null;if(t){o=new ze;let m=window.__configWatcher;m!=null&&m.stop&&m.stop(),window.__configWatcher=o}let s=new Set,l=m=>{var b,y;if(!o)return;let h=new Set;h.add("configs/engine/engine.runtime.json"),h.add("configs/engine/engine.assets.json"),h.add("configs/engine/engine.splash.json"),h.add("configs/scenes/scene.main.json");let f=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of f)v!=null&&v.object_config&&h.add(`configs/objects/${v.object_config}.json`);for(let v of s)h.has(v)||o.unwatch(v);for(let v of h)s.has(v)||o.watch(v,x=>g(x));s=h},c=new Set,p=!1,d=async m=>{let h=await Le(m),f=$e(h,n.activeConfig.schemas),b=Je(f,n.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await n.liveEditBridge.applyObjectConfig(m,f)};async function u(m){if(!r){r=!0;try{if(p||c.size===0){n.audioSystem.destroy();let h=await be("scene.main");n.setActiveConfig(h),n.gameObjectManager.updateConfig(h),n.CustomAssets.updateConfig(h),await n.CustomAssets.ready();let f=n.createAudioSystem(h);n.setAudioSystem(f),window.__audioSystem=f,await f.start(),n.liveEditBridge.rebuildIndexes(),l(h),console.log(`[GAME] Hot-reload complete (${m})`)}else{let h=Array.from(c);c.clear();for(let f of h)await d(f);console.log(`[GAME] Hot-reload updated objects: ${h.join(", ")}`)}}catch(h){console.warn("[GAME] Hot-reload failed:",h)}finally{r=!1,p=!1,c.clear()}}}function g(m){m.type==="object"&&m.objectId?c.add(m.objectId):p=!0,a&&window.clearTimeout(a),a=window.setTimeout(()=>{u(m.type)},120)}e&&Tn.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(n.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${s.size} files)`))}var Tn,Ar=de(()=>{"use strict";Ln();An();Tn={}});var Sr={};ht(Sr,{ConfigWatcher:()=>ze,DefaultReloadStrategy:()=>St,applyDefaults:()=>$e,diffConfigs:()=>Sn,loadAllObjectConfigs:()=>li,loadComponentSchemas:()=>si,loadEngineConfig:()=>ci,loadGamePromptConfig:()=>wn,loadObjectCentricConfig:()=>be,loadObjectConfig:()=>Le,loadSceneConfig:()=>di,rehydrateObject:()=>Cn,setupHotReload:()=>kn,toLegacyFormat:()=>En,validateObjectConfig:()=>Je});var pi=de(()=>{"use strict";An();Ln();Ar()});var so={};ht(so,{AssetEditorModal:()=>oa});var oa,sa=de(()=>{"use strict";oa=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,i,a){this.currentObjectId=e,this.currentPath=t,this.currentAsset=i,this.onApplyCallback=a,this.createModal(e,i),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let i=document.createElement("div");i.className="asset-editor-modal",i.innerHTML=`
1
+ "use strict";var zo=Object.create;var Bt=Object.defineProperty;var Do=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var Ho=Object.getPrototypeOf,No=Object.prototype.hasOwnProperty;var de=(a,e)=>()=>(a&&(e=a(a=0)),e);var ht=(a,e)=>{for(var t in e)Bt(a,t,{get:e[t],enumerable:!0})},ka=(a,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $o(e))!No.call(a,n)&&n!==t&&Bt(a,n,{get:()=>e[n],enumerable:!(i=Do(e,n))||i.enumerable});return a};var qe=(a,e,t)=>(t=a!=null?zo(Ho(a)):{},ka(e||!a||!a.__esModule?Bt(t,"default",{value:a,enumerable:!0}):t,a)),Fo=a=>ka(Bt({},"__esModule",{value:!0}),a);var pe,dn=de(()=>{"use strict";pe=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};pe.store=new Map});function Ko(){var a,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(a=document.querySelector("script"))==null?void 0:a.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),i=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!i)}catch{return!1}}async function Xo(){try{if(typeof window!="undefined"){let a=await fetch("./build-settings.json");if(a.ok){let e=await a.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Jo(){try{if(typeof window!="undefined"){let a=new XMLHttpRequest;if(a.open("GET","./build-settings.json",!1),a.send(),a.status===200&&a.responseText){let e=JSON.parse(a.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Zo(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${H}`),Object.keys(ue).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(ue)),ue;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),ue={...window.INLINE_ASSETS},ue;if(!(H==="publish"&&re!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),ue;if(!pn){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),pn=(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 i=await t.text();console.log("[AssetLoader] Received JS code, length:",i.length);let n=i.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(n)try{let r=n[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let o=new Function("return "+r)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(o)),o}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:",i.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return ue=await pn,console.log("[AssetLoader] Final inline assets cache:",Object.keys(ue)),ue}function un(a){return a===null||typeof a!="object"||(Object.freeze(a),Object.values(a).forEach(e=>un(e))),a}function Qo(a=64,e=64,t=16711680){let i=document.createElement("canvas");i.width=a,i.height=e;let n=i.getContext("2d");return n.fillStyle=`#${t.toString(16).padStart(6,"0")}`,n.fillRect(0,0,a,e),n.strokeStyle="#000",n.strokeRect(0,0,a,e),n.fillStyle="#fff",n.font="10px sans-serif",n.textAlign="center",n.fillText("MISSING",a/2,e/2),ge.Texture.from(i)}function gn(a,e){sr.set(a,e)}var ge,rr,or,Ie,H,re,Ee,ue,pn,sr,je,Vt=de(()=>{"use strict";ge=require("pixi.js");dn();rr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",or=Ko(),Ie=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,H=or?"publish":rr,re=Ie==null?void 0:Ie.assetsInlined;Ie!=null&&Ie.buildMode&&(H=Ie.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${H}`));Ee=Jo();Ee!=null&&Ee.buildMode&&(H=Ee.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${H}`));(Ee==null?void 0:Ee.assetsInlined)!==void 0&&(re=Ee.assetsInlined);Xo().then(a=>{a!=null&&a.buildMode&&a.buildMode!==H&&(H=a.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${H}`)),(a==null?void 0:a.assetsInlined)!==void 0&&(re=a.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${rr}, Runtime: ${or?"publish":"dev"}, Effective: ${H}`);ue={},pn=null;sr=new Map;je=class{static async load(e,t,i,n){let r=`${e}:${t.path}`,o=pe.get(r);if(o!==void 0)return o;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${H}`),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 s=await Zo(),l=s[e];if(!l&&n&&(l=s[n],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${n}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.length-1].split(".")[0];s[u]&&(l=s[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),H==="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=sr.get(t.type);if(p)try{let d=await p(t.path,l,e,i);return pe.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=un(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return pe.set(r,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let i=H==="publish",n=i&&re!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${H}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await ge.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 ge.Assets.load(t)}catch(r){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",r),await ge.Assets.load(e)}return await ge.Assets.load(e)}static async loadJSON(e,t){let i=H==="publish",n=i&&re!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${H}, isPublishMode: ${i}, inlineData: ${t?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let o=atob(t.split(",")[1]);return JSON.parse(o)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let o=atob(t.split(",")[1]);return JSON.parse(o)}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,i){if(H==="dev"){let r=t==="image"?Qo():un({__placeholder:!0,type:t});return pe.set(e+":"+((i==null?void 0:i.path)||"missing"),r),r}throw i}};gn("image",async(a,e)=>{let t=H==="publish",i=t&&re!==!1,n=H==="brand",r=t&&re===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${H}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${a}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return ge.Assets.load(e)}let o=a;return(n||r)&&a&&!a.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(o=a,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${a}" as-is`)):(o=`assets/${a}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${a}" -> "${o}"`))),ge.Assets.load(e||o)});gn("json",async(a,e)=>{let t=H==="publish",i=t&&re!==!1,n=H==="brand",r=t&&re===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${H}, isPublishMode: ${t}, isBrandMode: ${n}, inlineData: ${e?"EXISTS":"MISSING"}`),i){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${a}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let o=a;if((n||r)&&a&&!a.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(o=a,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${a}" as-is`)):(o=`assets/${a}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${a}" -> "${o}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let s=await fetch(o);if(!s.ok)throw new Error(`JSON fetch failed: ${a}`);return s.json()})});var cr={};ht(cr,{AssetTextures:()=>oe,initAssetTextures:()=>mn});function mn(a,e){lr.init(a,e),typeof window!="undefined"&&(window.__AssetTextures=oe)}var fn,lr,oe,Ke=de(()=>{"use strict";Vt();fn=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(i=>{this.priorityReadyResolve=i}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var o;console.log("[AssetTextures] Loading all assets...");let i=new Set(["background_loading_1"]),n=[],r=[];for(let[s,l]of e.objects.entries()){let c=(o=l.render)==null?void 0:o.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}: ${s} (${u})`);let g=await je.load(s,c,t,u);this.textures.set(s,g),console.log(`[AssetTextures] \u2713 Loaded: ${s}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${s}`,u)}finally{this.attempted.add(s);try{for(let u of Array.from(this.waiters))u()}catch{}}};i.has(s)?n.push(p()):r.push(p())}n.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(n),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(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 n=Array.from(new Set((e||[]).filter(s=>typeof s=="string"&&s))).filter(s=>{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,s);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(n.length===0)return;this.ready().catch(()=>{});let r=()=>n.every(s=>this.textures.has(s)||this.attempted.has(s));if(r())return;let o=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(s=>{let l=!1,c=()=>{l||r()&&(l=!0,this.waiters.delete(c),s())};this.waiters.add(c),c(),o>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:n}),s())},o)})}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())}},lr=new fn,oe=new Proxy(lr,{get(a,e){return e in a&&typeof a[e]=="function"?a[e].bind(a):a.get(e)},set(a,e,t){return a.set(e,t),!0}})});var Xe={};ht(Xe,{applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>ri,clearConfigOverrides:()=>se,clearConfigOverridesForObject:()=>wr,configOverrideManager:()=>Er,deepClone:()=>G,exportConfigsAsJSON:()=>ze,getConfigOverrides:()=>Y,getConfigStateSummary:()=>ai,getOverrideMode:()=>wt,removeConfigOverride:()=>ni,resetToApplied:()=>Et,resetToOriginal:()=>oi,setOverrideMode:()=>xn});function ti(){return typeof window=="undefined"?null:window.__editableConfig||null}function mr(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function hr(a,e){var t,i;if(!a)return null;try{if(a instanceof Map)return(t=a.get(e))!=null?t:null;if(typeof a=="object")return(i=a[e])!=null?i:null}catch{}return null}function Cs(a,e,t){if(a){if(a instanceof Map){a.set(e,t);return}typeof a=="object"&&(a[e]=t)}}function br(a,e){for(let t of e)xt(a,t.path,t.value)}function yr(a){var s;if(typeof window=="undefined")return;let e=ti();if(!e)return;let t=mr(),i=(s=t?hr(t.objects,a):null)!=null?s:hr(e.objects,a);if(!i)return;let n=G(i),r=Y().filter(l=>l.objectId===a);try{br(n,r)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",a,l);return}Cs(e.objects,a,n);let o=window.applyEditableObjectConfig;if(typeof o=="function")try{o(a,n)}catch{}}function Ts(){var n;if(typeof window=="undefined")return;let a=ti();if(!(a!=null&&a.engine))return;let e=mr(),t=G(((n=e==null?void 0:e.engine)!=null?n:a.engine)||{}),i=Y().filter(r=>!r.objectId&&!r.sceneId);try{br(t,i)}catch(r){console.error("[CONFIG] Failed to reapply engine overrides",r);return}try{let r=a.engine;for(let o of Object.keys(r))o in t||delete r[o];for(let[o,s]of Object.entries(t))r[o]=s}catch{a.engine=t}}function Ls(){if(typeof window=="undefined")return"unknown";let a=window;return typeof a.__HANDLER_PROJECT_ID=="string"?a.__HANDLER_PROJECT_ID:"handler-default"}function vr(){return`handler_preview_config_overrides::${Ls()}`}function ks(){if(typeof window=="undefined")return[];try{let a=window.localStorage.getItem(vr());if(!a)return[];let e=JSON.parse(a);return Array.isArray(e)?e:[]}catch{return[]}}function ii(a){if(typeof window!="undefined")try{window.localStorage.setItem(vr(),JSON.stringify(a))}catch{}}function wt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function xn(a){if(typeof window!="undefined"){window.__enableConfigOverrides=a;try{window.localStorage.setItem(xr,a?"true":"false")}catch{}}}function Ae(a,e={}){var u,g;let{objectId:t,path:i,value:n}=a,{silent:r=!1,persist:o=!0,emitEvent:s=!0}=e,l=ti();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:i,hasObjects:!!l.objects});return}r||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:i,value:n});let p;try{p=Ms(c,i),xt(c,i,n)}catch(m){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:i,value:n},m);return}window.__configChanges=window.__configChanges||[];let d=window.__configChanges;if(d.push({objectId:t,path:i,oldValue:p,newValue:n,ts:Date.now()}),d.length>_s&&d.shift(),o){let m=Y(),h=m.findIndex(f=>f.objectId===t&&f.sceneId===a.sceneId&&f.path===i);h>=0?m[h].value=n:m.push(a),window.__configOverrides=m,ii(m),wt()||xn(!0)}r||console.log("[CONFIG] Applied override:",a),s&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:a}))}function Ce(a,e={}){let t=e.emitEvent!==!1,i=[];for(let n of a)n!=null&&n.objectId&&typeof n.objectId=="string"&&i.push(n.objectId),Ae(n,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let n=Array.from(new Set(i));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:n,count:a.length}}))}}function se(){window.__configOverrides=[],window.__configChanges=[],ii([]),console.log("[CONFIG] Cleared all overrides")}function wr(a){let e=Y().filter(i=>i.objectId!==a);window.__configOverrides=e,ii(e);let t=window.__configChanges||[];window.__configChanges=t.filter(i=>i.objectId!==a),yr(a),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:a}}))}function ni(a,e){let t=Y().filter(n=>n.objectId!==a||n.path!==e);window.__configOverrides=t,ii(t);let i=window.__configChanges||[];window.__configChanges=i.filter(n=>n.objectId!==a||n.path!==e),a?yr(a):Ts(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:a,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=ks()),window.__configOverrides||[])}function xt(a,e,t){var o;let i=e.split("."),n=i.pop(),r=a;for(let s of i){if(r[s]!==void 0&&typeof r[s]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${s})`);r[s]=(o=r[s])!=null?o:{},r=r[s]}r[n]=t}function Ms(a,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,a)}function G(a){if(a===null||typeof a!="object")return a;if(a instanceof Date)return new Date(a.getTime());if(a instanceof Set)return new Set([...a].map(t=>G(t)));if(ArrayBuffer.isView(a))return a.slice();if(a instanceof Array)return a.map(t=>G(t));if(a instanceof Map){let t=new Map;return a.forEach((i,n)=>t.set(n,G(i))),t}let e={};for(let t in a)Object.prototype.hasOwnProperty.call(a,t)&&(e[t]=G(a[t]));return e}function ze(){let a=window.__editableConfigBaseline;if(!a){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return fr(e)}return fr(a)}function fr(a){let e={objects:{},scenes:{},engine:G(a.engine||{})},t=a.objects;if(t instanceof Map)t.forEach((r,o)=>{e.objects[o]=G(r)});else if(t&&typeof t=="object")for(let r in t)e.objects[r]=G(t[r]);let i=a.scenes;if(i instanceof Map)i.forEach((r,o)=>{e.scenes[o]=G(r)});else if(i&&typeof i=="object")for(let r in i)e.scenes[r]=G(i[r]);let n=Y();for(let r of n)r.objectId?(e.objects[r.objectId]||(e.objects[r.objectId]={}),xt(e.objects[r.objectId],r.path,r.value)):r.sceneId?(e.scenes[r.sceneId]||(e.scenes[r.sceneId]={}),xt(e.scenes[r.sceneId],r.path,r.value)):xt(e.engine,r.path,r.value);return e}function ai(){let a=Y(),e=new Set;for(let t of a)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:a.length,hasChanges:a.length>0,overrides:a}}async function ri(a){let e=ze(),t={};for(let[n,r]of Object.entries(e.objects)){let o=r,s=n;/^(json\.|ui\.|effects\.|engine\.)/.test(s)||(s=`json.${n}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=s),t[`objects/${s}.json`]=o}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[n,r]of Object.entries(e.scenes)){let o=n.startsWith("scene.")?n:`scene.${n}`;t[`scenes/${o}.json`]=r}let i=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:a})});if(!i.ok){let n=await i.json();throw new Error(`Apply failed: ${n.error||"Unknown error"}`)}se();try{let n=ti();n&&(window.__editableConfigBaseline=G(n))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Et(){se(),window.location.reload()}async function oi(){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"}`)}se(),window.location.reload()}var xr,_s,Er,K=de(()=>{"use strict";xr="handler_preview_override_mode";if(typeof window!="undefined"){let a=window.localStorage.getItem(xr);window.__enableConfigOverrides=a===null?!0:a==="true"}_s=500;Er={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function Ps(a,e){try{if(typeof a=="object"&&a!==null)return a;if(typeof a!="string")return null;if(a.startsWith("data:")){let i=a.indexOf(",");if(i===-1)return null;let n=a.slice(0,i);if(!n.includes("application/json")&&!n.includes("text/plain"))return null;let r=a.slice(i+1),o=n.includes("base64")?typeof atob=="function"?atob(r):r:decodeURIComponent(r);return JSON.parse(o)}let t=a.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(a):null}catch{return null}}function Os(a){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=a.replace(/^\.\/+/,""),i=t.split("/").pop()||t,n=[t,i,t.replace(/\.json$/,""),i.replace(/\.json$/,"")];for(let r of n){let o=e[r];if(o){let s=Ps(o,r);if(s!==null)return s}}return null}async function St(a){if(wn.has(a)&&!En)return console.log(`[CONFIG] Using cached config for: "${a}"`),wn.get(a);if(console.log(`[CONFIG] loadConfigFile called with: "${a}", MODE: ${$.toUpperCase()}, CACHE: ${En?"DISABLED":"ENABLED"}`),$==="publish"){let i=Os(a);return i?(console.log(`[CONFIG] \u2713 Loaded ${a} via INLINE_ASSETS`),i):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${a} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}$==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${a}"`);let e;$==="brand"?e=[`./${a.split("/").pop()||a}`,`./${a}`,`./${a.replace(/^configs\//,"")}`,`./${a.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${a}`,`./${a.replace(/^configs\//,"")}`,`./${a.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(i=>i.startsWith("./")?[i,`/${i.slice(2)}`]:i.startsWith("/")?[i]:[i,`/${i}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let i=En?"no-store":"force-cache";for(let n of e)try{let r=await fetch(n,{cache:i});if(!r.ok)continue;let o=await r.json();return console.log(`[CONFIG] \u2713 Loaded ${a} via ${n}`,o),o}catch(r){console.warn(`[CONFIG] \u2717 Failed to load ${n} (mode: ${$}):`,r)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${a}; using defaults`),{}})();return wn.set(a,t),t}async function si(){console.log("[CONFIG] Loading component schemas...");let a=["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 a)try{let i=$==="publish"||$==="brand"?t.split("/").pop()||t:`configs/${t}`,n=await St(i);n.component&&(e.set(n.component,n),console.log(`[CONFIG] \u2713 Schema loaded: ${n.component} ${$==="publish"||$==="brand"?"(flattened)":"(nested)"}`))}catch(i){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,i)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Te(a){console.log(`[CONFIG] Loading object config: ${a}`);let e=$==="publish"||$==="brand"?`${a}.json`:`configs/objects/${a}.json`;return await St(e)}async function li(a){let e=new Map;if(a.objects&&Array.isArray(a.objects)){for(let t of a.objects)if(t.enabled&&t.object_config)try{let i=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(i)||(i=`json.${i}`);let n=await Te(i);(!n||Object.keys(n).length===0)&&i!==t.instance_id&&(n=await Te(t.instance_id)),!n||Object.keys(n).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),n=await Te(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...n,instance_id:t.instance_id,object_config:t.object_config})}catch(i){console.warn(`Failed to load object ${t.object_config}:`,i)}}return e}async function ci(){console.log("[CONFIG] Loading engine configs...");let a=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(a.map(i=>{let n=`engine.${i}.json`,r=$==="publish"||$==="brand"?n:`configs/engine/${n}`;return St(r)})),t=Object.fromEntries(a.map((i,n)=>[i,e[n]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(a.map(i=>{var o;let n=(o=t[i])!=null?o:{},r=Object.keys(n);return[i,r.length>0?r:"empty"]}))),t}async function Sn(){return await St($==="publish"||$==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function di(a="scene.main"){console.log(`[CONFIG] Loading scene config: ${a}`);let e=$==="publish"||$==="brand"?`${a}.json`:`configs/scenes/${a}.json`;return await St(e)}function Je(a,e){let t=[];if(!a.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let i=e.get("identity");if(i)for(let n of i.required||[])a.identity[n]||t.push(`Missing required identity field: ${n}`);for(let[n,r]of Object.entries(a)){if(n==="identity")continue;let o=e.get(n);if(o&&r&&typeof r=="object"){let s=r;for(let l of o.required||[])s[l]===void 0&&t.push(`Missing required field in ${n}: ${l}`);if(o.constraints&&typeof o.constraints=="object")for(let[l,c]of Object.entries(o.constraints)){let p=s[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${n}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${n}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function De(a,e){let t={...a},i=["identity","transform","render"];for(let[n,r]of e.entries())r.defaults&&Object.keys(r.defaults).length>0&&(i.includes(n)||t[n])&&(t[n]||(t[n]={}),t[n]={...r.defaults,...t[n]});return t}function Q(a,e,t,i){return typeof a!="number"||!Number.isFinite(a)?e:Math.min(Math.max(a,t),i)}function Ar(a,e){if(Array.isArray(a))return{x:Q(a[0],e.x,-2e3,2e3),y:Q(a[1],e.y,-2e3,2e3)};if(!a||typeof a!="object")return e;let{x:t,y:i}=a;return{x:Q(t,e.x,-2e3,2e3),y:Q(i,e.y,-2e3,2e3)}}function Is(a,e){if(Array.isArray(a))return{x:Q(a[0],e.x,0,1),y:Q(a[1],e.y,0,1)};if(!a||typeof a!="object")return e;let{x:t,y:i}=a;return{x:Q(t,e.x,0,1),y:Q(i,e.y,0,1)}}function js(a){if(Array.isArray(a))return{x:Q(a[0],.5,-10,10),y:Q(a[1],.5,-10,10)};if(a&&typeof a=="object"){let{x:e,y:t}=a;return{x:Q(e,.5,-10,10),y:Q(t,.5,-10,10)}}return typeof a=="string"?a:null}async function be(a="scene.main",e){var l,c,p,d,u,g,m,h,f,b,y,v,x,w;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await si(),i=Y();i.length>0&&console.log(`[CONFIG] Applying ${i.length} active overrides`);let n=await di(a);console.log(`[CONFIG] Scene config loaded: ${((l=n.objects)==null?void 0:l.length)||0} objects`);let r=await ci();console.log("[CONFIG] Loading object configs...");let o=await li(n);console.log(`[CONFIG] Loaded ${o.size} object configs:`,Array.from(o.keys()));for(let[E,C]of o.entries()){let S=De(C,t),P=Je(S,t);P.valid||console.warn(`Object ${E} validation errors:`,P.errors),(c=S.transform)!=null&&c.position&&(S.transform.position=Ar(S.transform.position,{x:0,y:0})),(p=S.transform)!=null&&p.offset&&(S.transform.offset=Ar(S.transform.offset,{x:0,y:0})),((d=S.transform)==null?void 0:d.anchor)!==void 0&&(S.transform.anchor=js(S.transform.anchor)),((u=S.transform)==null?void 0:u.position_ratio)!==void 0&&S.transform.position_ratio!==null&&(S.transform.position_ratio=Is(S.transform.position_ratio,{x:.5,y:.5})),o.set(E,S)}if(e){if(e.objects)for(let[E,C]of e.objects.entries())o.set(E,C);e.engine&&(r.runtime={...r.runtime,...e.engine.runtime},r.assets={...r.assets,...e.engine.assets},r.splash={...(g=r.splash)!=null?g:{},...(m=e.engine.splash)!=null?m:{}})}let s={objects:o,engine:r,scene:n,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=s,window.__editableConfigBaseline||(window.__editableConfigBaseline=De(s,t))),i.length>0&&wt()&&Ce(i,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(o.keys()),engine:{runtime:Object.keys((h=r.runtime)!=null?h:{}),assets:Object.keys((f=r.assets)!=null?f:{}),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((w=r.endgame)!=null?w:{})},scene:n.scene_id||"unknown"}),s}function An(a){var t,i,n,r,o,s,l,c,p,d,u,g,m,h,f,b,y,v,x,w,E,C,S,P,F,M,T,I,O,z,j,D,A;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[k,_]of a.objects.entries()){let q=((t=_.identity)==null?void 0:t.id)||k;q.includes("character")&&(e.gameplay.character_pos=((i=_.transform)==null?void 0:i.position)||{x:0,y:0},e.gameplay.character_scale=((n=_.transform)==null?void 0:n.scale)||1,e.gameplay.character_anim_speed=((o=(r=_.gameplay)==null?void 0:r.tuning)==null?void 0:o.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(s=_.gameplay)==null?void 0:s.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=_.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(q.includes("gun")||q.includes("flame"))&&(e.gameplay.gun=_.gun||{},e.gameplay.gunmuzzle=((d=_.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=_.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=_.effects)==null?void 0:g.flame)||{}),q.includes("diamond")&&(e.gameplay.diamond=_),q.includes("ice")&&(e.gameplay.melt=_.melt||{},e.gameplay.melt_anchor=((m=_.transform)==null?void 0:m.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((h=_.transform)==null?void 0:h.position)||{x:0,y:0},e.gameplay.hybrid_melting=((f=_.effects)==null?void 0:f.hybrid_melting)||{},e.gameplay.physics_chunks=((b=_.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=_.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=_.hard_ice||{}),q.includes("water")&&(e.gameplay.water_drops=_),q.includes("crack")&&(e.gameplay.crack=_),q.includes("hand")&&(e.gameplay.hand=((v=_.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((x=_.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((w=_.transform)==null?void 0:w.scale)||1.5),q.includes("hazard")&&(e.gameplay.hazard=((E=_.gameplay)==null?void 0:E.tuning)||{},e.gameplay.danger_pos=((C=_.transform)==null?void 0:C.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((P=(S=_.gameplay)==null?void 0:S.tuning)==null?void 0:P.danger_pulse)||{},e.gameplay.hazard_height=((M=(F=_.gameplay)==null?void 0:F.tuning)==null?void 0:M.hazard_height)||140)}return e.gameplay.timeline=((T=a.engine.runtime)==null?void 0:T.timeline)||{},e.gameplay.drag_surface=((I=a.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((O=a.engine.runtime)==null?void 0:O.background)||{},e.gameplay.ui_styles=((z=a.engine.runtime)==null?void 0:z.ui_styles)||{},e.gameplay.label_pulse=((j=a.engine.runtime)==null?void 0:j.label_pulse)||{},e.ui=((D=a.engine.runtime)==null?void 0:D.ui)||{},e.theme=((A=a.engine.runtime)==null?void 0:A.theme)||{},e.assets=a.engine.assets||{},e}var Sr,$,wn,En,Cn=de(()=>{"use strict";K();Sr=null,$="dev";if(typeof window!="undefined"){let a=window.__BUILD_SETTINGS__;if(a!=null&&a.buildMode)Sr=a,$=a.buildMode,console.log("[CONFIG] Loaded inline build settings:",a,"buildMode:",$);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);Sr=t,$=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",$)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",$)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",$);wn=new Map,En=$==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Tn(a,e){let t=[];function i(n,r,o=""){if(n!==r){if(typeof n!=typeof r){t.push(`${o}: type changed`);return}if(typeof n=="object"&&n!==null&&r!==null){let s=new Set([...Object.keys(n),...Object.keys(r)]);for(let l of s){let c=o?`${o}.${l}`:l;l in n?l in r?i(n[l],r[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${o}: changed`)}}return i(a,e),t}function Ln(a,e,t,i){let n={...t};for(let[r,o]of i.entries())n[r]&&o.defaults&&(n[r]={...o.defaults,...n[r]});return n}var At,$e,kn=de(()=>{"use strict";At=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 i=`${e}?t=${Date.now()}&r=${Math.random()}`,n=await fetch(i,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(n.ok){let r=await n.text(),o=this.hashString(r),s=this.fileHashes.get(e);if(s&&s!==o&&console.log(`[HOT-RELOAD] File changed: ${e}`),s&&s!==o){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,o)}else s||this.fileHashes.set(e,o)}}catch(i){console.warn(`Failed to check ${e}:`,i)}}determineEventType(e){var t,i;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(i=e.split("/").pop())==null?void 0:i.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let i=0;i<e.length;i++){let n=e.charCodeAt(i);t=(t<<5)-t+n,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Mn(a){if(typeof window=="undefined")return;let e=typeof _n!="undefined"&&!!_n.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let n=null,r=!1,o=null;if(t){o=new $e;let m=window.__configWatcher;m!=null&&m.stop&&m.stop(),window.__configWatcher=o}let s=new Set,l=m=>{var b,y;if(!o)return;let h=new Set;h.add("configs/engine/engine.runtime.json"),h.add("configs/engine/engine.assets.json"),h.add("configs/engine/engine.splash.json"),h.add("configs/scenes/scene.main.json");let f=(y=(b=m.scene)==null?void 0:b.objects)!=null?y:[];for(let v of f)v!=null&&v.object_config&&h.add(`configs/objects/${v.object_config}.json`);for(let v of s)h.has(v)||o.unwatch(v);for(let v of h)s.has(v)||o.watch(v,x=>g(x));s=h},c=new Set,p=!1,d=async m=>{let h=await Te(m),f=De(h,a.activeConfig.schemas),b=Je(f,a.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${m} validation errors:`,b.errors),await a.liveEditBridge.applyObjectConfig(m,f)};async function u(m){if(!r){r=!0;try{if(p||c.size===0){a.audioSystem.destroy();let h=await be("scene.main");a.setActiveConfig(h),a.gameObjectManager.updateConfig(h),a.CustomAssets.updateConfig(h),await a.CustomAssets.ready();let f=a.createAudioSystem(h);a.setAudioSystem(f),window.__audioSystem=f,await f.start(),a.liveEditBridge.rebuildIndexes(),l(h),console.log(`[GAME] Hot-reload complete (${m})`)}else{let h=Array.from(c);c.clear();for(let f of h)await d(f);console.log(`[GAME] Hot-reload updated objects: ${h.join(", ")}`)}}catch(h){console.warn("[GAME] Hot-reload failed:",h)}finally{r=!1,p=!1,c.clear()}}}function g(m){m.type==="object"&&m.objectId?c.add(m.objectId):p=!0,n&&window.clearTimeout(n),n=window.setTimeout(()=>{u(m.type)},120)}e&&_n.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(a.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${s.size} files)`))}var _n,Cr=de(()=>{"use strict";kn();Cn();_n={}});var Tr={};ht(Tr,{ConfigWatcher:()=>$e,DefaultReloadStrategy:()=>At,applyDefaults:()=>De,diffConfigs:()=>Tn,loadAllObjectConfigs:()=>li,loadComponentSchemas:()=>si,loadEngineConfig:()=>ci,loadGamePromptConfig:()=>Sn,loadObjectCentricConfig:()=>be,loadObjectConfig:()=>Te,loadSceneConfig:()=>di,rehydrateObject:()=>Ln,setupHotReload:()=>Mn,toLegacyFormat:()=>An,validateObjectConfig:()=>Je});var pi=de(()=>{"use strict";Cn();kn();Cr()});var po={};ht(po,{AssetEditorModal:()=>la});var la,ca=de(()=>{"use strict";la=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,i,n){this.currentObjectId=e,this.currentPath=t,this.currentAsset=i,this.onApplyCallback=n,this.createModal(e,i),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let i=document.createElement("div");i.className="asset-editor-modal",i.innerHTML=`
2
2
  <div class="asset-editor-card">
3
3
  <div class="asset-editor-header">
4
4
  <div>
@@ -43,7 +43,271 @@
43
43
  <button class="debug-btn primary" data-modal-apply>Apply</button>
44
44
  </div>
45
45
  </div>
46
- `,this.modal=i}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(o=>{o.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(o=>{o.addEventListener("click",s=>{let c=s.target.dataset.tab;c&&this.switchTab(c)})});let i=this.modal.querySelector("[data-ai-generate]");i==null||i.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",o=>{o.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 i="";e==="edit"&&this.currentAsset?i=`Edit this image: ${this.currentObjectId}`:i=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",i,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 pl={};ht(pl,{COLORS:()=>ce,ConfigWatcher:()=>ze,DebugPanel:()=>Ot,DefaultReloadStrategy:()=>St,Handler:()=>ie,PlayableLoadingScreen:()=>Ui,PreviewShell:()=>Hi,STROKE_WIDTH:()=>mo,THEME:()=>bo,applyConfigOverride:()=>Se,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>ri,applyDefaults:()=>$e,baseLottie:()=>rn,bootstrap:()=>el,clearConfigOverrides:()=>se,clearConfigOverridesForObject:()=>vr,configOverrideManager:()=>xr,createPreviewShell:()=>da,deepClone:()=>G,default:()=>Oe,defaultPreset:()=>ui,deviceGroups:()=>Mn,devicePresets:()=>Pn,diffConfigs:()=>Sn,exportConfigsAsJSON:()=>De,getConfigOverrides:()=>Y,getConfigStateSummary:()=>ai,getOverrideMode:()=>wt,getPresetById:()=>Ne,getPresetsByCategory:()=>Os,loadAllObjectConfigs:()=>li,loadComponentSchemas:()=>si,loadEngineConfig:()=>ci,loadGamePromptConfig:()=>wn,loadObjectCentricConfig:()=>be,loadObjectConfig:()=>Le,loadSceneConfig:()=>di,rehydrateObject:()=>Cn,removeConfigOverride:()=>ni,resetToApplied:()=>Et,resetToOriginal:()=>oi,setBootstrapDependencies:()=>Zs,setOverrideMode:()=>yn,setupHotReload:()=>kn,setupLiveEditBridge:()=>Bi,toLegacyFormat:()=>En,validateObjectConfig:()=>Je});module.exports=zo(pl);var we={};function Ut(n,e,t=!1){we[n]||(we[n]=[]),we[n].push({fn:e,once:t})}function en(n,e){if(we[n]){if(!e){delete we[n];return}we[n]=we[n].filter(t=>t.fn!==e)}}function Gt(n,...e){let t=we[n];if(t)for(let i of[...t])i.fn(...e),i.once&&en(n,i.fn)}function X(n,e){Ut(n,e,!0)}var F=null,ee=[],Ve=null;function _a(n){F=n,ee=[],Ve!==null&&(clearTimeout(Ve),Ve=null)}function Pa(){var n,e,t;return{endpoint:(F==null?void 0:F.endpoint)||"",transport:(F==null?void 0:F.transport)||"beacon",batchSize:(n=F==null?void 0:F.batchSize)!=null?n: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 Ta(n,e,t,i){let a=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let r=navigator.sendBeacon(n,new Blob([a],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",r,e);return}catch(r){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",r)}try{await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:a,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(r){i&&console.warn("[handler.telemetry] fetch failed",r)}}function tn(n,e){let t=Pa();if(e&&t.endpoint){if(ee.push(n),ee.length>t.maxQueue&&(ee=ee.slice(ee.length-t.maxQueue)),ee.length>=t.batchSize){ka();return}Ve===null&&(Ve=window.setTimeout(()=>{Ve=null,ka()},t.flushIntervalMs))}}async function ka(){let n=Pa();if(!n.endpoint||ee.length===0)return;let e=ee.splice(0,n.batchSize);await Ta(n.endpoint,{events:e},n.transport,n.debug),ee.length>0&&await Ta(n.endpoint,{events:ee.splice(0,n.batchSize)},n.transport,n.debug)}function Ma(n){return Math.max(0,Math.min(1,n))}function No(n){let e=String(n!=null?n:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return a=>1+(i+1)*Math.pow(a-1,3)+i*Math.pow(a-1,2)}return t=>1-(1-t)*(1-t)}function ft(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Ho(n,e){let t=n==null?void 0:n[e];return typeof t=="number"?t:0}function Oa(n,e,t){try{n[e]=t}catch{}}function Bo(n){let e=n==null?void 0:n.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function Ia(n,e){let t=n==null?void 0:n.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 ja(n,e){let t=Bo(n);if(!t)return{from:null,to:null};let i=null,a=null;return typeof e.scale=="number"?(i=e.scale,a=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(a=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(a=e.scaleY),i===null&&a===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:a!=null?a:t.y}}}function Ra(){let n=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,s(),n.size>0&&i()})},a=p=>{var u;n.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),i()},r=p=>{n.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},o=p=>{p.killed||(p.killed=!0,r(p))},s=()=>{var d,u;let p=ft();for(let g of Array.from(n)){if(g.killed||g.paused)continue;let m=p-g.startMs-g.delayMs;if(m<0)continue;let h=g.durationMs>0?m/g.durationMs:1,f=Ma(h),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(h),b-1):0;if(g.repeat>0&&h>=1){let w=h-y;f=Ma(w)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let w of g.props)Oa(g.target,w.key,w.from+(w.to-w.from)*v);g.scaleFrom&&g.scaleTo&&Ia(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(h>=b){o(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var w;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),m=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((w=u==null?void 0:u.delayMsOverride)!=null?w:0)),h=No(d.ease),f=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 E of Object.keys(d)){if(y.has(E))continue;let C=d[E];typeof C=="number"&&v.push({key:E,from:Ho(p,E),to:C})}let x=ja(p,d);return{target:p,startMs:ft(),delayMs:m,durationMs:g,ease:h,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:f,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:()=>o(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=ft())},resume:()=>{var h;if(!u.paused)return;let g=(h=u.pauseAtMs)!=null?h:ft(),m=ft()-g;u.startMs+=m,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 m=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof m=="number"&&Oa(p,g,m)}let u=ja(p,d);u.to&&Ia(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))o(u)},timeline(p={}){let d=[],u=0,g=!1,m=[],h=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{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 f({kind:"to",target:y,vars:v,atMs:h(x)}),b},fromTo(y,v,x,w){return f({kind:"fromTo",target:y,vars:x,from:v,atMs:h(w)}),b},play(){var y,v;if(g)return b;g=!0,m=[];for(let x of d)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),m.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 m)y.pause();return b},kill(){for(let y of m)y.kill();m=[],g=!1}};return p.paused||b.play(),b}};return c}function Da(){if(typeof window=="undefined")return;let n=window;if(!n.gsap)try{n.gsap=Ra()}catch{}}var $a={name:"handler-playable-sdk",version:"0.4.62",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 J=0,Uo=J++,za=J++,Na=J++,Ha=J++,Ba=J++,Fa=J++,Ua=J++,Ga=J++,qa=J++,Va=J++,Wa=J++,Ya=J++,H=Uo;function Ka(){return H===za}function Xa(){return H===Na}function Ja(){return H===Ha}function Za(){return H===Ba}function We(){return H===Fa}function Ye(){return H===Ua}function Qa(){return H===Ga}function er(){return H===qa}function tr(){return H===Va}function nn(){return H===Wa}function an(){return H===Ya}function ir(){let n=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(n==="mraid")try{mraid.getState(),H=za;return}catch{}else if(n==="dapi")try{dapi.isReady(),H=Na;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(H=Ha)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(H=Ba)}catch{}else if(e==="mintegral")window.gameReady&&(H=Fa);else if(e==="tapjoy")window.TJ_API&&(H=Ua);else if(e==="tiktok")window.openAppStore&&(H=Ga);else if(e==="smadex")try{window.smxTracking&&(H=qa)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(H=Va)}catch{}else e==="vungle"?H=Wa:(n==="nucleo"||e==="nucleo")&&(H=Ya)}var qt=qe(require("lottie-web"),1),rn=qt.default;typeof window!="undefined"&&(window.lottie=qt.default,window.__baseLottie=qt.default);var Go=require("pixi.js");var on=require("pixi.js");var qo=null;function sn(n){qo=n}Vt();ln();var mt=require("pixi.js");Vt();var Jo=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",un=Jo;if(typeof window!="undefined")try{let n=new XMLHttpRequest;if(n.open("GET","./build-settings.json",!1),n.send(),n.status===200&&n.responseText){let e=JSON.parse(n.responseText);e!=null&&e.buildMode&&(un=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${un}`))}}catch{}function Zo(n){var t,i,a,r,o;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(n);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(n))return{x:(t=n[0])!=null?t:.5,y:(i=n[1])!=null?i:.5};if(n&&typeof n=="object"&&"x"in n&&"y"in n)return{x:(a=n.x)!=null?a:.5,y:(r=n.y)!=null?r:.5};if(typeof n=="string"){let s=n.trim().toLowerCase();return(o=e[s])!=null?o:{x:.5,y:.5}}return null}var Ae=class{static async create(e,t,i){var l,c,p,d,u,g,m;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${un}`);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 h=new mt.Container;return this.applyTransform(h,t==null?void 0:t.transform,t),h}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 o=await je.load(e,a,i,r);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=o==null?void 0:o.constructor)==null?void 0:p.name}`);let s;if(a.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",o,"for object:",e),s=new mt.Sprite(o),console.log("[ObjectFactory] Created object:",s,"type:",(d=s==null?void 0:s.constructor)==null?void 0:d.name),this.applyTransform(s,t==null?void 0:t.transform,t);else if(a.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name,o),o&&(((g=o.constructor)==null?void 0:g.name)==="Container"||o instanceof mt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[a.path,`/assets/${a.path}`,`assets/${a.path}`,`../assets/${a.path}`],f=!1;for(let b of h)try{let y=await fetch(b);if(y.ok){s=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(m=s==null?void 0:s.constructor)==null?void 0:m.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),s=o)}else s=o;else s=o,s&&typeof s=="object"&&("x"in s||"position"in s)&&this.applyTransform(s,t==null?void 0:t.transform,t);return s}static applyTransform(e,t,i){var a,r,o,s;if(!(!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((o=t.position.x)!=null?o:0,(s=t.position.y)!=null?s:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=Zo(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var bt=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var ts=qe(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=ts);Ke();var Wt=require("pixi.js");Ke();var fn=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new bt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));if(t.length===0)return;let i=async a=>{a.length&&(console.log("[Assets] Loading objects:",a),await Promise.all(a.map(async r=>{var s;let o=this.registry.get(r);if(!o){console.warn("[Assets] No config found for object:",r);return}try{let l=await Ae.create(r,o,this.app);this.instanceCache.set(r,l),console.log("[Assets] Loaded object:",r,(s=l==null?void 0:l.constructor)==null?void 0:s.name)}catch(l){console.error("[Assets] Failed to load object:",r,l)}})))};return this.readyPromise=(async()=>{await i(t);let a=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));a.length>0&&(console.warn("[Assets] Retrying missing assets:",a),await i(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 i=await Ae.create(e,t,this.app);this.instanceCache.set(e,i)}}get(e){return this.instanceCache.get(e)}},is=new fn,ns=new Proxy(is,{get(n,e){if(e in n&&typeof n[e]=="function")return n[e].bind(n);if(n.get(e))return n.get(e)}});Ke();var lr=require("pixi.js"),he={width:400,height:600,designWidth:400,scaleFactor:1},Kt={scale:1,position:1},bn=[];function rs(n,e,t,i,a,r,o){bn.push({element:n,originalScale:r,positionHelper:e,heightPercent:a}),e(n,t,i,a,r,o,!1)}function os(){bn.forEach(({element:n,originalScale:e,positionHelper:t,heightPercent:i})=>{let a=e*he.scaleFactor;t(n,he.width,he.height,i,a,!0,!1)})}function mn(n,e){console.log(`[SCREEN] updateScreenState called: ${n}x${e}`),he.width=n,he.height=e,he.scaleFactor=Math.min(n/he.designWidth,1.15),Kt.scale=he.scaleFactor,Kt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Kt.scale.toFixed(3)}`),os()}var vt={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 ss(n,e,t){let i=vt[n];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${n}.${e} = ${t}`))}function ls(){return vt}var cs={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 Yt(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function Xt(n,e={x:.5,y:.5}){var t;if(Array.isArray(n))return{x:Yt(n[0],e.x),y:Yt(n[1],e.y)};if(n&&typeof n=="object"){let i=n;return{x:Yt(i.x,e.x),y:Yt(i.y,e.y)}}if(typeof n=="string"){let i=n.trim().toLowerCase();return(t=cs[i])!=null?t:e}return e}function cr(n,e,t,i={}){var g,m,h,f,b,y;let a=Xt(t),r=(g=i.inset)!=null?g:{},o=(m=i.padding)!=null?m:{x:0,y:0},s=((h=r.left)!=null?h:0)+o.x,l=((f=r.right)!=null?f:0)+o.x,c=((b=r.top)!=null?b:0)+o.y,p=((y=r.bottom)!=null?y:0)+o.y,d=Math.max(0,n-s-l),u=Math.max(0,e-c-p);return{x:s+d*a.x,y:c+u*a.y}}function dr(n,e,t,i={}){var h,f,b,y,v,x;let a=(h=i.inset)!=null?h:{},r=(f=i.padding)!=null?f:{x:0,y:0},o=((b=a.left)!=null?b:0)+r.x,s=((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,n-o-s),d=Math.max(0,e-l-c),u=Xt(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),m=Math.min(Math.max(u.y,0),1);return{x:o+p*g,y:l+d*m}}if(typeof window!="undefined"){let n=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,a=window.innerHeight;(i!==n||a!==e)&&(n=i,e=a,mn(i,a))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),mn(window.innerWidth,window.innerHeight),window.updateDebugConfig=ss,window.getDebugConfig=ls,window.copyConfig=xs,window.applyConfig=yt,window.applyConfigForRatio=ws,window.positionAtBottom=pr,window.positionAtTop=us,window.positionAtCenter=gs,window.positionAtLeft=hs,window.positionAtRight=fs,window.positionAtBottomLeft=ms,window.positionAtBottomRight=bs,window.positionAtTopLeft=ys,window.positionAtTopRight=vs,window.applyPositionContract=ps,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 Jt(n,e,t=0){return n*e+t}function Zt(n,e,t=0){return n*(1-e)+t}function Qt(n,e,t=0){return n*e+t}function ei(n,e,t=0){return n*(1-e)+t}function Z(n,e=0){return n/2+e}function ds(n,e){return n*e}function ps(n,e,t,i){var o,s,l,c,p,d,u,g,m,h,f,b,y,v,x,w,E,C,A,M;let a=0,r=0;switch(i.type){case"top":a=Z(e,(s=(o=i.offset)==null?void 0:o.x)!=null?s:0),r=Jt(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":a=Z(e,(d=(p=i.offset)==null?void 0:p.x)!=null?d:0),r=Zt(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":a=Qt(e,i.percent,(h=(m=i.offset)==null?void 0:m.x)!=null?h:0),r=Z(t,(b=(f=i.offset)==null?void 0:f.y)!=null?b:0);break;case"right":a=ei(e,i.percent,(v=(y=i.offset)==null?void 0:y.x)!=null?v:0),r=Z(t,(w=(x=i.offset)==null?void 0:x.y)!=null?w:0);break;case"center":a=Z(e,(C=(E=i.offset)==null?void 0:E.x)!=null?C:0),r=Z(t,(M=(A=i.offset)==null?void 0:A.y)!=null?M:0);break}n.position?n.position.set(a,r):(n.x=a,n.y=r),i.scale!==void 0&&i.scale!==1&&n.scale&&(typeof n.scale.set=="function"?n.scale.set(i.scale,i.scale):(n.scale.x=i.scale,n.scale.y=i.scale))}function pr(n,e,t,i=.2,a=1,r=!0,o=!1){let s=ds(t,i),l=Zt(t,i/2);fe(n,Z(e),l);let c=r?a*he.scaleFactor:a;me(n,c),o&&!bn.find(p=>p.element===n)&&rs(n,pr,e,t,i,a,r)}function us(n,e,t,i=.1,a=1){fe(n,Z(e),Jt(t,i)),me(n,a)}function gs(n,e,t,i=0,a=0,r=1){fe(n,Z(e,i),Z(t,a)),me(n,r)}function hs(n,e,t,i=.1,a=1){fe(n,Qt(e,i),Z(t)),me(n,a)}function fs(n,e,t,i=.1,a=1){fe(n,ei(e,i),Z(t)),me(n,a)}function ms(n,e,t,i=.05,a=.05,r=1){fe(n,Qt(e,a),Zt(t,i)),me(n,r)}function bs(n,e,t,i=.05,a=.05,r=1){fe(n,ei(e,a),Zt(t,i)),me(n,r)}function ys(n,e,t,i=.05,a=.05,r=1){fe(n,Qt(e,a),Jt(t,i)),me(n,r)}function vs(n,e,t,i=.05,a=.05,r=1){fe(n,ei(e,a),Jt(t,i)),me(n,r)}function fe(n,e,t){n&&n.position?typeof n.position.set=="function"?n.position.set(e,t):(n.position.x=e,n.position.y=t):n&&(n.x=e,n.y=t)}function me(n,e){e!==1&&n&&n.scale&&(typeof n.scale.set=="function"?n.scale.set(e,e):n.scale.x!==void 0&&n.scale.y!==void 0&&(n.scale.x=e,n.scale.y=e))}var Re={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 xs(n){return n&&Re[n]?JSON.parse(JSON.stringify(Re[n])):JSON.parse(JSON.stringify(vt))}function yt(n){Object.keys(n).forEach(e=>{let t=e;vt[t]&&n[t]&&Object.assign(vt[t],n[t])}),console.log("Config applied:",n)}function ws(n,e){let t=n/e;t>1.6?(yt(Re.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(yt(Re.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(yt(Re.square),console.log("Applied SQUARE config for ratio:",t)):(yt(Re.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let n=window;n.configPresets=Re,n.resolveAnchorVec2=n.resolveAnchorVec2||Xt,n.resolveScreenAnchorPoint=n.resolveScreenAnchorPoint||cr,n.resolveScreenRatioPoint=n.resolveScreenRatioPoint||dr}pi();function U(n,e){let t=(a,r)=>r===0?a:t(r,a%r),i=t(n,e);return`${n/i}:${e/i}`}var Nc=[{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)}],Hc=[{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)}],Bc=[{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)}],_n=[{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 Pn=[..._n],Mn=[{category:"playable",label:"Playable Ad",devices:_n}],ui=_n[0];function Ne(n){return Pn.find(e=>e.id===n)||ui}function Os(n){return Pn.filter(e=>e.category===n)}var gi=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=i}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(o=>{o.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(o=>{o.addEventListener("click",s=>{let c=s.target.dataset.tab;c&&this.switchTab(c)})});let i=this.modal.querySelector("[data-ai-generate]");i==null||i.addEventListener("click",()=>{this.openAiEditor("generate")});let n=this.modal.querySelector("[data-ai-edit]");n==null||n.addEventListener("click",()=>{this.openAiEditor("edit")});let r=this.modal.querySelector("[data-modal-apply]");r==null||r.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",o=>{o.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(n=>{n.classList.toggle("active",n.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(n=>{n.classList.toggle("active",n.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 i="";e==="edit"&&this.currentAsset?i=`Edit this image: ${this.currentObjectId}`:i=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",i,this.currentAsset,{path:this.currentPath,onApply:n=>{this.onApplyCallback&&this.onApplyCallback(n),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 bl={};ht(bl,{COLORS:()=>ce,ConfigWatcher:()=>$e,DebugPanel:()=>Ot,DefaultReloadStrategy:()=>At,Handler:()=>ie,PlayableLoadingScreen:()=>qi,PreviewShell:()=>Bi,STROKE_WIDTH:()=>vo,THEME:()=>xo,applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Ce,applyConfigsToDisk:()=>ri,applyDefaults:()=>De,baseLottie:()=>sn,bootstrap:()=>ol,clearConfigOverrides:()=>se,clearConfigOverridesForObject:()=>wr,configOverrideManager:()=>Er,createPreviewShell:()=>ua,deepClone:()=>G,default:()=>Oe,defaultPreset:()=>ui,deviceGroups:()=>In,devicePresets:()=>On,diffConfigs:()=>Tn,exportConfigsAsJSON:()=>ze,getConfigOverrides:()=>Y,getConfigStateSummary:()=>ai,getOverrideMode:()=>wt,getPresetById:()=>He,getPresetsByCategory:()=>Rs,loadAllObjectConfigs:()=>li,loadComponentSchemas:()=>si,loadEngineConfig:()=>ci,loadGamePromptConfig:()=>Sn,loadObjectCentricConfig:()=>be,loadObjectConfig:()=>Te,loadSceneConfig:()=>di,rehydrateObject:()=>Ln,removeConfigOverride:()=>ni,resetToApplied:()=>Et,resetToOriginal:()=>oi,setBootstrapDependencies:()=>al,setOverrideMode:()=>xn,setupHotReload:()=>Mn,setupLiveEditBridge:()=>Ui,toLegacyFormat:()=>An,validateObjectConfig:()=>Je});module.exports=Fo(bl);var we={};function Ut(a,e,t=!1){we[a]||(we[a]=[]),we[a].push({fn:e,once:t})}function nn(a,e){if(we[a]){if(!e){delete we[a];return}we[a]=we[a].filter(t=>t.fn!==e)}}function Gt(a,...e){let t=we[a];if(t)for(let i of[...t])i.fn(...e),i.once&&nn(a,i.fn)}function X(a,e){Ut(a,e,!0)}var B=null,ee=[],Ve=null;function Pa(a){B=a,ee=[],Ve!==null&&(clearTimeout(Ve),Ve=null)}function Oa(){var a,e,t;return{endpoint:(B==null?void 0:B.endpoint)||"",transport:(B==null?void 0:B.transport)||"beacon",batchSize:(a=B==null?void 0:B.batchSize)!=null?a:10,flushIntervalMs:(e=B==null?void 0:B.flushIntervalMs)!=null?e:300,maxQueue:(t=B==null?void 0:B.maxQueue)!=null?t:200,debug:!!(B!=null&&B.debug)}}async function _a(a,e,t,i){let n=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let r=navigator.sendBeacon(a,new Blob([n],{type:"application/json"}));i&&console.log("[handler.telemetry] beacon",r,e);return}catch(r){i&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",r)}try{await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:n,keepalive:!0}),i&&console.log("[handler.telemetry] fetch",e)}catch(r){i&&console.warn("[handler.telemetry] fetch failed",r)}}function an(a,e){let t=Oa();if(e&&t.endpoint){if(ee.push(a),ee.length>t.maxQueue&&(ee=ee.slice(ee.length-t.maxQueue)),ee.length>=t.batchSize){Ma();return}Ve===null&&(Ve=window.setTimeout(()=>{Ve=null,Ma()},t.flushIntervalMs))}}async function Ma(){let a=Oa();if(!a.endpoint||ee.length===0)return;let e=ee.splice(0,a.batchSize);await _a(a.endpoint,{events:e},a.transport,a.debug),ee.length>0&&await _a(a.endpoint,{events:ee.splice(0,a.batchSize)},a.transport,a.debug)}function Ia(a){return Math.max(0,Math.min(1,a))}function Bo(a){let e=String(a!=null?a:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),i=t?Number(t[1]):1.8;return n=>1+(i+1)*Math.pow(n-1,3)+i*Math.pow(n-1,2)}return t=>1-(1-t)*(1-t)}function ft(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Uo(a,e){let t=a==null?void 0:a[e];return typeof t=="number"?t:0}function ja(a,e,t){try{a[e]=t}catch{}}function Go(a){let e=a==null?void 0:a.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,i=typeof e.y=="number"?e.y:1;return{x:t,y:i}}function Ra(a,e){let t=a==null?void 0:a.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 za(a,e){let t=Go(a);if(!t)return{from:null,to:null};let i=null,n=null;return typeof e.scale=="number"?(i=e.scale,n=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(i=e.scale.x),typeof e.scale.y=="number"&&(n=e.scale.y)),typeof e.scaleX=="number"&&(i=e.scaleX),typeof e.scaleY=="number"&&(n=e.scaleY),i===null&&n===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:i!=null?i:t.x,y:n!=null?n:t.y}}}function Da(){let a=new Set,e=new WeakMap,t=null,i=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,s(),a.size>0&&i()})},n=p=>{var u;a.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),i()},r=p=>{a.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},o=p=>{p.killed||(p.killed=!0,r(p))},s=()=>{var d,u;let p=ft();for(let g of Array.from(a)){if(g.killed||g.paused)continue;let m=p-g.startMs-g.delayMs;if(m<0)continue;let h=g.durationMs>0?m/g.durationMs:1,f=Ia(h),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(h),b-1):0;if(g.repeat>0&&h>=1){let w=h-y;f=Ia(w)}let v=g.ease(f);g.yoyo&&y%2===1&&(v=1-v);for(let w of g.props)ja(g.target,w.key,w.from+(w.to-w.from)*v);g.scaleFrom&&g.scaleTo&&Ra(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(h>=b){o(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var w;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),m=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((w=u==null?void 0:u.delayMsOverride)!=null?w:0)),h=Bo(d.ease),f=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 E of Object.keys(d)){if(y.has(E))continue;let C=d[E];typeof C=="number"&&v.push({key:E,from:Uo(p,E),to:C})}let x=za(p,d);return{target:p,startMs:ft(),delayMs:m,durationMs:g,ease:h,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:f,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 n(u),{kill:()=>o(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=ft())},resume:()=>{var h;if(!u.paused)return;let g=(h=u.pauseAtMs)!=null?h:ft(),m=ft()-g;u.startMs+=m,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 m=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof m=="number"&&ja(p,g,m)}let u=za(p,d);u.to&&Ra(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))o(u)},timeline(p={}){let d=[],u=0,g=!1,m=[],h=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},f=y=>{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 f({kind:"to",target:y,vars:v,atMs:h(x)}),b},fromTo(y,v,x,w){return f({kind:"fromTo",target:y,vars:x,from:v,atMs:h(w)}),b},play(){var y,v;if(g)return b;g=!0,m=[];for(let x of d)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),m.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 m)y.pause();return b},kill(){for(let y of m)y.kill();m=[],g=!1}};return p.paused||b.play(),b}};return c}function $a(){if(typeof window=="undefined")return;let a=window;if(!a.gsap)try{a.gsap=Da()}catch{}}var Ha={name:"handler-playable-sdk",version:"0.4.73",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 J=0,Vo=J++,Na=J++,Fa=J++,Ba=J++,Ua=J++,Ga=J++,qa=J++,Va=J++,Wa=J++,Ya=J++,Ka=J++,Xa=J++,N=Vo;function Ja(){return N===Na}function Za(){return N===Fa}function Qa(){return N===Ba}function er(){return N===Ua}function We(){return N===Ga}function Ye(){return N===qa}function tr(){return N===Va}function ir(){return N===Wa}function nr(){return N===Ya}function rn(){return N===Ka}function on(){return N===Xa}function ar(){let a=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(a==="mraid")try{mraid.getState(),N=Na;return}catch{}else if(a==="dapi")try{dapi.isReady(),N=Fa;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(N=Ba)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(N=Ua)}catch{}else if(e==="mintegral")window.gameReady&&(N=Ga);else if(e==="tapjoy")window.TJ_API&&(N=qa);else if(e==="tiktok")window.openAppStore&&(N=Va);else if(e==="smadex")try{window.smxTracking&&(N=Wa)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(N=Ya)}catch{}else e==="vungle"?N=Ka:(a==="nucleo"||e==="nucleo")&&(N=Xa)}var qt=qe(require("lottie-web"),1),sn=qt.default;typeof window!="undefined"&&(window.lottie=qt.default,window.__baseLottie=qt.default);var Wo=require("pixi.js");var ln=require("pixi.js");var Yo=null;function cn(a){Yo=a}Vt();dn();var mt=require("pixi.js");Vt();var es=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",hn=es;if(typeof window!="undefined")try{let a=new XMLHttpRequest;if(a.open("GET","./build-settings.json",!1),a.send(),a.status===200&&a.responseText){let e=JSON.parse(a.responseText);e!=null&&e.buildMode&&(hn=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${hn}`))}}catch{}function ts(a){var t,i,n,r,o;if(typeof window!="undefined"&&window.resolveAnchorVec2)return window.resolveAnchorVec2(a);let e={center:{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};if(Array.isArray(a))return{x:(t=a[0])!=null?t:.5,y:(i=a[1])!=null?i:.5};if(a&&typeof a=="object"&&"x"in a&&"y"in a)return{x:(n=a.x)!=null?n:.5,y:(r=a.y)!=null?r:.5};if(typeof a=="string"){let s=a.trim().toLowerCase();return(o=e[s])!=null?o:{x:.5,y:.5}}return null}var Se=class{static async create(e,t,i){var l,c,p,d,u,g,m;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${hn}`);let n=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!n){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let h=new mt.Container;return this.applyTransform(h,t==null?void 0:t.transform,t),h}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: ${n.type}, path: ${n.path}`);let o=await je.load(e,n,i,r);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=o==null?void 0:o.constructor)==null?void 0:p.name}`);let s;if(n.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",o,"for object:",e),s=new mt.Sprite(o),console.log("[ObjectFactory] Created object:",s,"type:",(d=s==null?void 0:s.constructor)==null?void 0:d.name),this.applyTransform(s,t==null?void 0:t.transform,t);else if(n.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name,o),o&&(((g=o.constructor)==null?void 0:g.name)==="Container"||o instanceof mt.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[n.path,`/assets/${n.path}`,`assets/${n.path}`,`../assets/${n.path}`],f=!1;for(let b of h)try{let y=await fetch(b);if(y.ok){s=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(m=s==null?void 0:s.constructor)==null?void 0:m.name),f=!0;break}}catch{continue}f||(console.error("[ObjectFactory] Failed to reload JSON from any path"),s=o)}else s=o;else s=o,s&&typeof s=="object"&&("x"in s||"position"in s)&&this.applyTransform(s,t==null?void 0:t.transform,t);return s}static applyTransform(e,t,i){var n,r,o,s;if(!(!t||!e)&&(t.position&&("x"in e&&"y"in e?(e.x=(n=t.position.x)!=null?n:0,e.y=(r=t.position.y)!=null?r:0):"position"in e&&e.position&&e.position.set((o=t.position.x)!=null?o:0,(s=t.position.y)!=null?s:0)),t.scale!==void 0&&"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(t.scale):e.scale=t.scale),t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor)){let l=ts(t.anchor);l&&("set"in e.anchor?e.anchor.set(l.x,l.y):(e.anchor.x=l.x,e.anchor.y=l.y))}}};var bt=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var as=qe(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=as);Ke();var Wt=require("pixi.js");Ke();var bn=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new bt}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(n=>!this.instanceCache.has(n));if(t.length===0)return;let i=async n=>{n.length&&(console.log("[Assets] Loading objects:",n),await Promise.all(n.map(async r=>{var s;let o=this.registry.get(r);if(!o){console.warn("[Assets] No config found for object:",r);return}try{let l=await Se.create(r,o,this.app);this.instanceCache.set(r,l),console.log("[Assets] Loaded object:",r,(s=l==null?void 0:l.constructor)==null?void 0:s.name)}catch(l){console.error("[Assets] Failed to load object:",r,l)}})))};return this.readyPromise=(async()=>{await i(t);let n=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));n.length>0&&(console.warn("[Assets] Retrying missing assets:",n),await i(n)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let i=await Se.create(e,t,this.app);this.instanceCache.set(e,i)}}get(e){return this.instanceCache.get(e)}},rs=new bn,os=new Proxy(rs,{get(a,e){if(e in a&&typeof a[e]=="function")return a[e].bind(a);if(a.get(e))return a.get(e)}});Ke();var dr=require("pixi.js"),he={width:400,height:600,designWidth:400,scaleFactor:1},Kt={scale:1,position:1},vn=[];function ls(a,e,t,i,n,r,o){vn.push({element:a,originalScale:r,positionHelper:e,heightPercent:n}),e(a,t,i,n,r,o,!1)}function cs(){vn.forEach(({element:a,originalScale:e,positionHelper:t,heightPercent:i})=>{let n=e*he.scaleFactor;t(a,he.width,he.height,i,n,!0,!1)})}function yn(a,e){console.log(`[SCREEN] updateScreenState called: ${a}x${e}`),he.width=a,he.height=e,he.scaleFactor=Math.min(a/he.designWidth,1.15),Kt.scale=he.scaleFactor,Kt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Kt.scale.toFixed(3)}`),cs()}var vt={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 ds(a,e,t){let i=vt[a];i&&i[e]!==void 0&&(i[e]=t,console.log(`Updated ${a}.${e} = ${t}`))}function ps(){return vt}var us={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 Yt(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function Xt(a,e={x:.5,y:.5}){var t;if(Array.isArray(a))return{x:Yt(a[0],e.x),y:Yt(a[1],e.y)};if(a&&typeof a=="object"){let i=a;return{x:Yt(i.x,e.x),y:Yt(i.y,e.y)}}if(typeof a=="string"){let i=a.trim().toLowerCase();return(t=us[i])!=null?t:e}return e}function pr(a,e,t,i={}){var g,m,h,f,b,y;let n=Xt(t),r=(g=i.inset)!=null?g:{},o=(m=i.padding)!=null?m:{x:0,y:0},s=((h=r.left)!=null?h:0)+o.x,l=((f=r.right)!=null?f:0)+o.x,c=((b=r.top)!=null?b:0)+o.y,p=((y=r.bottom)!=null?y:0)+o.y,d=Math.max(0,a-s-l),u=Math.max(0,e-c-p);return{x:s+d*n.x,y:c+u*n.y}}function ur(a,e,t,i={}){var h,f,b,y,v,x;let n=(h=i.inset)!=null?h:{},r=(f=i.padding)!=null?f:{x:0,y:0},o=((b=n.left)!=null?b:0)+r.x,s=((y=n.right)!=null?y:0)+r.x,l=((v=n.top)!=null?v:0)+r.y,c=((x=n.bottom)!=null?x:0)+r.y,p=Math.max(0,a-o-s),d=Math.max(0,e-l-c),u=Xt(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),m=Math.min(Math.max(u.y,0),1);return{x:o+p*g,y:l+d*m}}if(typeof window!="undefined"){let a=window.innerWidth,e=window.innerHeight,t=()=>{let i=window.innerWidth,n=window.innerHeight;(i!==a||n!==e)&&(a=i,e=n,yn(i,n))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),yn(window.innerWidth,window.innerHeight),window.updateDebugConfig=ds,window.getDebugConfig=ps,window.copyConfig=Ss,window.applyConfig=yt,window.applyConfigForRatio=As,window.positionAtBottom=gr,window.positionAtTop=fs,window.positionAtCenter=ms,window.positionAtLeft=bs,window.positionAtRight=ys,window.positionAtBottomLeft=vs,window.positionAtBottomRight=xs,window.positionAtTopLeft=ws,window.positionAtTopRight=Es,window.applyPositionContract=hs,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 Jt(a,e,t=0){return a*e+t}function Zt(a,e,t=0){return a*(1-e)+t}function Qt(a,e,t=0){return a*e+t}function ei(a,e,t=0){return a*(1-e)+t}function Z(a,e=0){return a/2+e}function gs(a,e){return a*e}function hs(a,e,t,i){var o,s,l,c,p,d,u,g,m,h,f,b,y,v,x,w,E,C,S,P;let n=0,r=0;switch(i.type){case"top":n=Z(e,(s=(o=i.offset)==null?void 0:o.x)!=null?s:0),r=Jt(t,i.percent,(c=(l=i.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":n=Z(e,(d=(p=i.offset)==null?void 0:p.x)!=null?d:0),r=Zt(t,i.percent,(g=(u=i.offset)==null?void 0:u.y)!=null?g:0);break;case"left":n=Qt(e,i.percent,(h=(m=i.offset)==null?void 0:m.x)!=null?h:0),r=Z(t,(b=(f=i.offset)==null?void 0:f.y)!=null?b:0);break;case"right":n=ei(e,i.percent,(v=(y=i.offset)==null?void 0:y.x)!=null?v:0),r=Z(t,(w=(x=i.offset)==null?void 0:x.y)!=null?w:0);break;case"center":n=Z(e,(C=(E=i.offset)==null?void 0:E.x)!=null?C:0),r=Z(t,(P=(S=i.offset)==null?void 0:S.y)!=null?P:0);break}a.position?a.position.set(n,r):(a.x=n,a.y=r),i.scale!==void 0&&i.scale!==1&&a.scale&&(typeof a.scale.set=="function"?a.scale.set(i.scale,i.scale):(a.scale.x=i.scale,a.scale.y=i.scale))}function gr(a,e,t,i=.2,n=1,r=!0,o=!1){let s=gs(t,i),l=Zt(t,i/2);fe(a,Z(e),l);let c=r?n*he.scaleFactor:n;me(a,c),o&&!vn.find(p=>p.element===a)&&ls(a,gr,e,t,i,n,r)}function fs(a,e,t,i=.1,n=1){fe(a,Z(e),Jt(t,i)),me(a,n)}function ms(a,e,t,i=0,n=0,r=1){fe(a,Z(e,i),Z(t,n)),me(a,r)}function bs(a,e,t,i=.1,n=1){fe(a,Qt(e,i),Z(t)),me(a,n)}function ys(a,e,t,i=.1,n=1){fe(a,ei(e,i),Z(t)),me(a,n)}function vs(a,e,t,i=.05,n=.05,r=1){fe(a,Qt(e,n),Zt(t,i)),me(a,r)}function xs(a,e,t,i=.05,n=.05,r=1){fe(a,ei(e,n),Zt(t,i)),me(a,r)}function ws(a,e,t,i=.05,n=.05,r=1){fe(a,Qt(e,n),Jt(t,i)),me(a,r)}function Es(a,e,t,i=.05,n=.05,r=1){fe(a,ei(e,n),Jt(t,i)),me(a,r)}function fe(a,e,t){a&&a.position?typeof a.position.set=="function"?a.position.set(e,t):(a.position.x=e,a.position.y=t):a&&(a.x=e,a.y=t)}function me(a,e){e!==1&&a&&a.scale&&(typeof a.scale.set=="function"?a.scale.set(e,e):a.scale.x!==void 0&&a.scale.y!==void 0&&(a.scale.x=e,a.scale.y=e))}var Re={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 Ss(a){return a&&Re[a]?JSON.parse(JSON.stringify(Re[a])):JSON.parse(JSON.stringify(vt))}function yt(a){Object.keys(a).forEach(e=>{let t=e;vt[t]&&a[t]&&Object.assign(vt[t],a[t])}),console.log("Config applied:",a)}function As(a,e){let t=a/e;t>1.6?(yt(Re.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(yt(Re.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(yt(Re.square),console.log("Applied SQUARE config for ratio:",t)):(yt(Re.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let a=window;a.configPresets=Re,a.resolveAnchorVec2=a.resolveAnchorVec2||Xt,a.resolveScreenAnchorPoint=a.resolveScreenAnchorPoint||pr,a.resolveScreenRatioPoint=a.resolveScreenRatioPoint||ur}pi();function U(a,e){let t=(n,r)=>r===0?n:t(r,n%r),i=t(a,e);return`${a/i}:${e/i}`}var qc=[{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)}],Vc=[{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)}],Wc=[{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)}],Pn=[{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 On=[...Pn],In=[{category:"playable",label:"Playable Ad",devices:Pn}],ui=Pn[0];function He(a){return On.find(e=>e.id===a)||ui}function Rs(a){return On.filter(e=>e.category===a)}var zs=["loading","start","gameplay","tutorial","endgame"],Ds=["environment","ui","character","system","backgrounds"],$s=["bg","world","ui"],Lr={SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},DragToWin:{targetId:"",successDistance:80},DragSnap:{snapTargetId:"",snapDistance:40},JoystickMove:{speed:6,bounds:{left:-400,right:400,top:-300,bottom:300}}},gi=class{constructor(){this.modal=null;this.state=null}open(e){this.state=this.createInitialState(e),this.createModal(),document.body.appendChild(this.modal),this.attachEventListeners(),this.updateStepUI()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.state=null}createInitialState(e){return{step:1,objectType:"sprite",instanceId:"",displayName:"",category:"environment",screenId:e.screenId,layer:"world",positionMode:"static",anchorPreset:"center",anchorX:.5,anchorY:.5,positionX:0,positionY:0,offsetX:0,offsetY:0,scale:.2,rotation:0,zIndex:0,assetPath:"",tint:"",alpha:1,text:"",font:"brand.primary",fontSize:18,letterSpacing:0,align:"center",graphicsWidth:200,graphicsHeight:200,graphicsFill:"#FFFFFF",graphicsAlpha:1,interactionEnabled:!1,dragEnabled:!1,hoverEnabled:!1,clickEnabled:!1,logicId:"",logicPropsRaw:""}}createModal(){let e=document.createElement("div");e.className="wizard-modal",e.innerHTML=`
47
+ <div class="wizard-card">
48
+ <div class="wizard-header">
49
+ <div class="wizard-title">
50
+ <div class="wizard-title-text">Add Game Object</div>
51
+ <div class="wizard-subtitle">Create new scene object</div>
52
+ </div>
53
+ <button class="wizard-close" type="button" data-action="close">\xD7</button>
54
+ </div>
55
+ <div class="wizard-progress" data-wizard-progress></div>
56
+ <div class="wizard-body">
57
+ ${this.renderSteps()}
58
+ </div>
59
+ <div class="wizard-footer">
60
+ <div class="wizard-footer-actions">
61
+ <button class="wizard-btn wizard-btn-secondary" type="button" data-action="back">Back</button>
62
+ </div>
63
+ <div class="wizard-footer-actions">
64
+ <button class="wizard-btn wizard-btn-secondary" type="button" data-action="cancel">Cancel</button>
65
+ <button class="wizard-btn wizard-btn-primary" type="button" data-action="next">Next</button>
66
+ </div>
67
+ </div>
68
+ </div>
69
+ `,this.modal=e}renderSteps(){return`
70
+ <div class="wizard-step" data-step="1">
71
+ <div class="wizard-section">
72
+ <div class="wizard-section-title">Select Object Type</div>
73
+ <div class="wizard-type-grid">
74
+ ${this.renderTypeCard("sprite","\u{1F5BC}\uFE0F","Sprite")}
75
+ ${this.renderTypeCard("ui-image","\u{1F9E9}","UI Image")}
76
+ ${this.renderTypeCard("ui-text","\u{1F4DD}","UI Text")}
77
+ ${this.renderTypeCard("graphics","\u2B1C","Graphics")}
78
+ ${this.renderTypeCard("container","\u{1F4E6}","Container")}
79
+ </div>
80
+ <div class="wizard-help-text">Sprites and UI Images use assets from the library.</div>
81
+ </div>
82
+ </div>
83
+ <div class="wizard-step" data-step="2">
84
+ <div class="wizard-section">
85
+ <div class="wizard-section-title">Basic Properties</div>
86
+ <div class="wizard-field-group">
87
+ <label class="wizard-label required">Object ID</label>
88
+ <input class="wizard-input" type="text" data-field="instanceId" placeholder="e.g. car_1" />
89
+ <div class="wizard-help-text">Must be globally unique. Use snake_case or dot.notation.</div>
90
+ </div>
91
+ <div class="wizard-field-group">
92
+ <label class="wizard-label">Display Name</label>
93
+ <input class="wizard-input" type="text" data-field="displayName" placeholder="Optional label for UI" />
94
+ </div>
95
+ <div class="wizard-field-group">
96
+ <label class="wizard-label required">Category</label>
97
+ <select class="wizard-select" data-field="category">
98
+ ${Ds.map(e=>`<option value="${e}">${e}</option>`).join("")}
99
+ </select>
100
+ </div>
101
+ <div class="wizard-field-group">
102
+ <label class="wizard-label required">Screen</label>
103
+ <select class="wizard-select" data-field="screenId">
104
+ ${zs.map(e=>`<option value="${e}">${e}</option>`).join("")}
105
+ </select>
106
+ </div>
107
+ <div class="wizard-field-group">
108
+ <label class="wizard-label required">Layer</label>
109
+ <select class="wizard-select" data-field="layer">
110
+ ${$s.map(e=>`<option value="${e}">${e}</option>`).join("")}
111
+ </select>
112
+ </div>
113
+ </div>
114
+ </div>
115
+ <div class="wizard-step" data-step="3">
116
+ <div class="wizard-section">
117
+ <div class="wizard-section-title">Transform & Position</div>
118
+ <div class="wizard-field-group">
119
+ <label class="wizard-label">Position Mode</label>
120
+ <select class="wizard-select" data-field="positionMode">
121
+ <option value="static">static</option>
122
+ <option value="dynamic">dynamic</option>
123
+ <option value="interactive">interactive</option>
124
+ </select>
125
+ </div>
126
+ <div class="wizard-field-group">
127
+ <label class="wizard-label">Anchor Preset</label>
128
+ <select class="wizard-select" data-field="anchorPreset">
129
+ <option value="center">center</option>
130
+ <option value="top-left">top-left</option>
131
+ <option value="top-right">top-right</option>
132
+ <option value="bottom-left">bottom-left</option>
133
+ <option value="bottom-right">bottom-right</option>
134
+ <option value="custom">custom</option>
135
+ </select>
136
+ <div class="wizard-help-text">Custom enables explicit anchor X/Y.</div>
137
+ </div>
138
+ <div class="wizard-field-group">
139
+ <label class="wizard-label">Anchor X</label>
140
+ <input class="wizard-input" type="number" step="0.01" data-field="anchorX" />
141
+ </div>
142
+ <div class="wizard-field-group">
143
+ <label class="wizard-label">Anchor Y</label>
144
+ <input class="wizard-input" type="number" step="0.01" data-field="anchorY" />
145
+ </div>
146
+ <div class="wizard-field-group">
147
+ <label class="wizard-label">Position X</label>
148
+ <input class="wizard-input" type="number" step="1" data-field="positionX" />
149
+ </div>
150
+ <div class="wizard-field-group">
151
+ <label class="wizard-label">Position Y</label>
152
+ <input class="wizard-input" type="number" step="1" data-field="positionY" />
153
+ </div>
154
+ <div class="wizard-field-group">
155
+ <label class="wizard-label">Offset X</label>
156
+ <input class="wizard-input" type="number" step="1" data-field="offsetX" />
157
+ </div>
158
+ <div class="wizard-field-group">
159
+ <label class="wizard-label">Offset Y</label>
160
+ <input class="wizard-input" type="number" step="1" data-field="offsetY" />
161
+ </div>
162
+ <div class="wizard-field-group">
163
+ <label class="wizard-label">Scale</label>
164
+ <input class="wizard-input" type="number" step="0.01" data-field="scale" />
165
+ </div>
166
+ <div class="wizard-field-group">
167
+ <label class="wizard-label">Rotation (deg)</label>
168
+ <input class="wizard-input" type="number" step="1" data-field="rotation" />
169
+ </div>
170
+ <div class="wizard-field-group">
171
+ <label class="wizard-label">Z-Index</label>
172
+ <input class="wizard-input" type="number" step="1" data-field="zIndex" />
173
+ </div>
174
+ </div>
175
+ </div>
176
+ <div class="wizard-step" data-step="4">
177
+ <div class="wizard-section">
178
+ <div class="wizard-section-title">Type-Specific Properties</div>
179
+ <div class="wizard-section" data-type-section="sprite">
180
+ <div class="wizard-field-group">
181
+ <label class="wizard-label required">Asset Path</label>
182
+ <input class="wizard-input" type="text" data-field="assetPath" placeholder="raw/your_asset.png" />
183
+ </div>
184
+ <div class="wizard-field-group">
185
+ <label class="wizard-label">Tint</label>
186
+ <input class="wizard-input" type="text" data-field="tint" placeholder="#FFFFFF" />
187
+ </div>
188
+ <div class="wizard-field-group">
189
+ <label class="wizard-label">Alpha</label>
190
+ <input class="wizard-input" type="number" step="0.01" data-field="alpha" />
191
+ </div>
192
+ </div>
193
+ <div class="wizard-section" data-type-section="ui-text">
194
+ <div class="wizard-field-group">
195
+ <label class="wizard-label required">Text</label>
196
+ <textarea class="wizard-textarea" data-field="text" rows="3"></textarea>
197
+ </div>
198
+ <div class="wizard-field-group">
199
+ <label class="wizard-label">Font</label>
200
+ <input class="wizard-input" type="text" data-field="font" />
201
+ </div>
202
+ <div class="wizard-field-group">
203
+ <label class="wizard-label">Font Size</label>
204
+ <input class="wizard-input" type="number" step="1" data-field="fontSize" />
205
+ </div>
206
+ <div class="wizard-field-group">
207
+ <label class="wizard-label">Letter Spacing</label>
208
+ <input class="wizard-input" type="number" step="1" data-field="letterSpacing" />
209
+ </div>
210
+ <div class="wizard-field-group">
211
+ <label class="wizard-label">Alignment</label>
212
+ <select class="wizard-select" data-field="align">
213
+ <option value="left">left</option>
214
+ <option value="center">center</option>
215
+ <option value="right">right</option>
216
+ </select>
217
+ </div>
218
+ </div>
219
+ <div class="wizard-section" data-type-section="graphics">
220
+ <div class="wizard-field-group">
221
+ <label class="wizard-label">Width</label>
222
+ <input class="wizard-input" type="number" step="1" data-field="graphicsWidth" />
223
+ </div>
224
+ <div class="wizard-field-group">
225
+ <label class="wizard-label">Height</label>
226
+ <input class="wizard-input" type="number" step="1" data-field="graphicsHeight" />
227
+ </div>
228
+ <div class="wizard-field-group">
229
+ <label class="wizard-label">Fill Color</label>
230
+ <input class="wizard-input" type="text" data-field="graphicsFill" placeholder="#FFFFFF" />
231
+ </div>
232
+ <div class="wizard-field-group">
233
+ <label class="wizard-label">Fill Alpha</label>
234
+ <input class="wizard-input" type="number" step="0.01" data-field="graphicsAlpha" />
235
+ </div>
236
+ </div>
237
+ <div class="wizard-help-text" data-type-help></div>
238
+ </div>
239
+ </div>
240
+ <div class="wizard-step" data-step="5">
241
+ <div class="wizard-section">
242
+ <div class="wizard-section-title">Interaction & Logic</div>
243
+ <div class="wizard-field-group">
244
+ <label class="wizard-label">Interaction Enabled</label>
245
+ <input type="checkbox" data-field="interactionEnabled" />
246
+ </div>
247
+ <div class="wizard-field-group">
248
+ <label class="wizard-label">Drag Enabled</label>
249
+ <input type="checkbox" data-field="dragEnabled" />
250
+ </div>
251
+ <div class="wizard-field-group">
252
+ <label class="wizard-label">Hover Enabled</label>
253
+ <input type="checkbox" data-field="hoverEnabled" />
254
+ </div>
255
+ <div class="wizard-field-group">
256
+ <label class="wizard-label">Click Enabled</label>
257
+ <input type="checkbox" data-field="clickEnabled" />
258
+ </div>
259
+ <div class="wizard-field-group">
260
+ <label class="wizard-label">Logic Component</label>
261
+ <select class="wizard-select" data-field="logicId">
262
+ <option value="">None</option>
263
+ ${Object.keys(Lr).map(e=>`<option value="${e}">${e}</option>`).join("")}
264
+ </select>
265
+ </div>
266
+ <div class="wizard-field-group">
267
+ <label class="wizard-label">Logic Props (JSON)</label>
268
+ <textarea class="wizard-textarea" data-field="logicPropsRaw" rows="6" placeholder="{ }"></textarea>
269
+ <div class="wizard-help-text">Defaults are inserted when selecting a logic component.</div>
270
+ </div>
271
+ </div>
272
+ </div>
273
+ <div class="wizard-step" data-step="6">
274
+ <div class="wizard-section">
275
+ <div class="wizard-section-title">Preview & Confirm</div>
276
+ <div class="wizard-preview">
277
+ <div class="wizard-preview-title">Generated Config</div>
278
+ <pre class="wizard-preview-json" data-preview-json></pre>
279
+ </div>
280
+ <div class="wizard-field-group">
281
+ <div class="wizard-error" data-validation-errors style="display:none;"></div>
282
+ </div>
283
+ </div>
284
+ </div>
285
+ `}renderTypeCard(e,t,i){return`
286
+ <button class="wizard-type-card" type="button" data-object-type="${e}">
287
+ <div class="wizard-type-icon">${t}</div>
288
+ <div class="wizard-type-name">${i}</div>
289
+ </button>
290
+ `}attachEventListeners(){if(!this.modal||!this.state)return;this.modal.addEventListener("click",t=>{var r;let i=t.target,n=i.dataset.action||((r=i.closest("[data-action]"))==null?void 0:r.getAttribute("data-action"));if(n)switch(n){case"close":case"cancel":this.close();break;case"back":this.goToStep(this.state.step-1);break;case"next":this.state.step<6?this.goToStep(this.state.step+1):this.submit();break}}),this.modal.addEventListener("click",t=>{let n=t.target.closest("[data-object-type]");if(!n)return;let r=n.dataset.objectType;r&&this.setObjectType(r)}),Array.from(this.modal.querySelectorAll("[data-field]")).forEach(t=>{let i=()=>this.handleFieldChange(t);t.addEventListener("input",i),t.addEventListener("change",i)}),this.modal.addEventListener("click",t=>{t.target===this.modal&&this.close()})}handleFieldChange(e){if(!this.state)return;let t=e.dataset.field;if(t){if(e instanceof HTMLInputElement&&e.type==="checkbox")this.state[t]=e.checked;else if(e instanceof HTMLInputElement&&e.type==="number"){let i=e.value===""?0:Number(e.value);this.state[t]=Number.isNaN(i)?0:i}else this.state[t]=e.value;t==="anchorPreset"&&this.applyAnchorPreset(this.state.anchorPreset),t==="logicId"&&this.applyLogicDefaults(this.state.logicId),this.updateStepUI()}}setObjectType(e){this.state&&(this.state.objectType=e,this.state.scale=e==="sprite"||e==="ui-image"?.2:1,(e==="ui-text"||e==="ui-image")&&(this.state.category="ui",this.state.layer="ui"),this.updateStepUI())}applyAnchorPreset(e){if(!this.state)return;let t={center:[.5,.5],"top-left":[0,0],"top-right":[1,0],"bottom-left":[0,1],"bottom-right":[1,1]};if(e!=="custom"&&t[e]){let[i,n]=t[e];this.state.anchorX=i,this.state.anchorY=n}}applyLogicDefaults(e){if(!this.state)return;if(!e){this.state.logicPropsRaw="";return}let t=Lr[e];t&&(this.state.logicPropsRaw=JSON.stringify(t,null,2))}goToStep(e){if(!this.state)return;let t=Math.max(1,Math.min(6,e));this.state.step=t,this.updateStepUI()}updateStepUI(){if(!this.modal||!this.state)return;Array.from(this.modal.querySelectorAll(".wizard-step")).forEach(t=>{let i=Number(t.dataset.step||"0");t.classList.toggle("active",i===this.state.step)}),this.updateProgressDots(),this.updateTypeSections(),this.syncFieldValues(),this.updatePreview(),this.updateActionButtons()}updateProgressDots(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-wizard-progress]");if(!e)return;let t=Array.from({length:6},(i,n)=>{let r=n+1;return`
291
+ <div class="wizard-step-indicator">
292
+ <span class="wizard-step-dot ${r===this.state.step?"active":r<this.state.step?"completed":""}"></span>
293
+ <span class="wizard-step-label">Step ${r}</span>
294
+ </div>
295
+ `});e.innerHTML=t.join("")}updateTypeSections(){if(!this.modal||!this.state)return;let e=this.state.objectType;Array.from(this.modal.querySelectorAll("[data-type-section]")).forEach(n=>{let r=n.dataset.typeSection,s=r==="sprite"&&(e==="sprite"||e==="ui-image")||r===e;n.style.display=s?"block":"none"});let i=this.modal.querySelector("[data-type-help]");if(i){let n=e==="ui-text"?"UI text uses the UI renderer with font settings.":e==="graphics"?"Graphics are simple shapes with width/height and fill.":e==="container"?"Containers are empty parents for grouping objects.":"Sprite/UI image uses image assets.";i.textContent=n}}syncFieldValues(){if(!this.modal||!this.state)return;let e=this.state;Array.from(this.modal.querySelectorAll("[data-field]")).forEach(n=>{let r=n.dataset.field;if(!r)return;let o=e[r];n instanceof HTMLInputElement&&n.type==="checkbox"?n.checked=!!o:typeof o!="undefined"&&(n.value=String(o))}),Array.from(this.modal.querySelectorAll("[data-object-type]")).forEach(n=>{n.classList.toggle("selected",n.dataset.objectType===this.state.objectType)})}updatePreview(){if(!this.modal||!this.state)return;let e=this.modal.querySelector("[data-preview-json]"),t=this.modal.querySelector("[data-validation-errors]");if(!e||!t)return;let i=this.buildPayload();e.textContent=JSON.stringify(i,null,2);let n=this.validate();n.length>0?(t.style.display="block",t.textContent=n.join(`
296
+ `)):(t.style.display="none",t.textContent="")}updateActionButtons(){if(!this.modal||!this.state)return;let e=this.modal.querySelector('[data-action="back"]'),t=this.modal.querySelector('[data-action="next"]');e&&(e.disabled=this.state.step===1),t&&(t.textContent=this.state.step===6?"Create":"Next",t.disabled=this.state.step===6&&this.validate().length>0)}validate(){if(!this.state)return[];let e=[],t=this.state.instanceId.trim();return t||e.push("Object ID is required."),t.startsWith("json.")&&e.push('Object ID must not start with "json." (instance id only).'),t&&!/^[a-zA-Z0-9._-]+$/.test(t)&&e.push("Object ID must use letters, numbers, dot, dash, or underscore."),t&&!this.isInstanceIdUnique(t)&&e.push(`Object ID "${t}" already exists.`),(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&!this.state.assetPath.trim()&&e.push("Asset path is required for image-based objects."),this.state.objectType==="ui-text"&&!this.state.text.trim()&&e.push("Text content is required for UI Text."),e}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let r=t();if(Array.isArray(r))return!r.includes(e)}let i=window.__HANDLER_SCREEN_INDEX,n=i==null?void 0:i.instanceToScreen;return n&&typeof n=="object"?!Object.prototype.hasOwnProperty.call(n,e):!0}buildPayload(){if(!this.state)return{};let e=this.state.instanceId.trim(),t=`json.${e}`;return{screenId:this.state.screenId,instanceId:e,objectConfigId:t,layer:this.state.layer,config:this.buildObjectConfig(t)}}buildObjectConfig(e){if(!this.state)return{};let t={identity:{id:e,category:this.state.category},transform:{position:{x:this.state.positionX,y:this.state.positionY},offset:{x:this.state.offsetX,y:this.state.offsetY},scale:this.state.scale,rotation:this.state.rotation,anchor:{x:this.state.anchorX,y:this.state.anchorY},position_ratio:null,position_mode:this.state.positionMode},render:{alpha:this.state.alpha,visible:!0,tint:this.state.tint||null,z_index:this.state.zIndex},instance_id:this.state.instanceId.trim(),object_config:e};return(this.state.objectType==="sprite"||this.state.objectType==="ui-image")&&(t.render.asset={type:"image",path:this.normalizeAssetPath(this.state.assetPath.trim())}),this.state.objectType==="ui-text"&&(t.ui={kind:"text",renderMode:"text",text:this.state.text,font:this.state.font,fontSize:this.state.fontSize,letterSpacing:this.state.letterSpacing,align:this.state.align,color:this.state.tint||"#FFFFFF"},t.render.tint=null),this.state.objectType==="graphics"&&(t.render.background_color=this.state.graphicsFill,t.render.background_alpha=this.state.graphicsAlpha,t.gameplay={tuning:{panel_width:this.state.graphicsWidth,panel_height:this.state.graphicsHeight}}),this.state.interactionEnabled&&(t.interaction={enabled:!0,drag:{enabled:this.state.dragEnabled},hover:{enabled:this.state.hoverEnabled},click:{enabled:this.state.clickEnabled}}),this.state.logicId&&(t.logic={id:this.state.logicId,props:this.parseLogicProps(this.state.logicPropsRaw)}),t}parseLogicProps(e){if(!e||!e.trim())return{};try{return JSON.parse(e)}catch{return{}}}normalizeAssetPath(e){return!e||e.startsWith("raw/")?e:e.startsWith("/raw/")?e.replace(/^\/raw\//,"raw/"):e}async submit(){var i;if(!this.state)return;if(this.validate().length>0){this.updatePreview();return}let t=this.buildPayload();try{let n=await fetch("/api/objects/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok||(r==null?void 0:r.success)===!1){let o=((i=r==null?void 0:r.errors)==null?void 0:i.join(`
297
+ `))||(r==null?void 0:r.error)||"Failed to create object.";alert(o);return}window.dispatchEvent(new CustomEvent("handler:scene-objects-refresh")),window.dispatchEvent(new CustomEvent("inspector:refresh")),this.close()}catch(n){alert(`Failed to create object: ${n instanceof Error?n.message:String(n)}`)}}};var hi=class{constructor(e){this.menu=null;this.closeHandler=null;this.keyHandler=null;this.options=e}open(e){this.createMenu(),document.body.appendChild(this.menu),this.positionMenu(e),this.attachListeners()}close(){var e,t;this.menu&&this.menu.parentNode&&this.menu.parentNode.removeChild(this.menu),this.closeHandler&&(window.removeEventListener("click",this.closeHandler),this.closeHandler=null),this.keyHandler&&(window.removeEventListener("keydown",this.keyHandler),this.keyHandler=null),this.menu=null,(t=(e=this.options).onClose)==null||t.call(e)}createMenu(){let e=document.createElement("div");e.className="context-menu",e.setAttribute("data-context-menu","true"),e.innerHTML=`
298
+ <div class="context-menu-item" data-action="duplicate">Duplicate</div>
299
+ <div class="context-menu-item" data-action="rename">Rename</div>
300
+ <div class="context-menu-item" data-action="move">Move to Screen</div>
301
+ <div class="context-menu-separator"></div>
302
+ <div class="context-menu-item" data-action="copy">Copy Config</div>
303
+ <div class="context-menu-item" data-action="inspect">Open in Inspector</div>
304
+ <div class="context-menu-separator"></div>
305
+ <div class="context-menu-item danger" data-action="delete">Delete</div>
306
+ `,this.menu=e}positionMenu(e){if(!this.menu)return;let{x:t,y:i}=e;this.menu.style.left=`${t}px`,this.menu.style.top=`${i}px`;let n=this.menu.getBoundingClientRect(),r=n.right-window.innerWidth,o=n.bottom-window.innerHeight;r>0&&(this.menu.style.left=`${t-r-8}px`),o>0&&(this.menu.style.top=`${i-o-8}px`)}attachListeners(){this.menu&&(this.menu.addEventListener("click",e=>{let i=e.target.dataset.action;i&&(e.stopPropagation(),this.handleAction(i))}),this.closeHandler=e=>{let t=e.target;this.menu&&t&&this.menu.contains(t)||this.close()},window.addEventListener("click",this.closeHandler),this.keyHandler=e=>{e.key==="Escape"&&this.close()},window.addEventListener("keydown",this.keyHandler))}handleAction(e){var t,i;switch(e){case"duplicate":this.handleDuplicate();break;case"rename":this.handleRename();break;case"move":this.handleMove();break;case"copy":this.handleCopyConfig();break;case"inspect":this.handleOpenInspector();break;case"delete":(i=(t=this.options).onDeleteRequest)==null||i.call(t,this.options.objectId),this.close();break}}async handleDuplicate(){var n,r,o,s,l;let e=`${this.options.objectId}_copy`,t=window.prompt("New instance ID",e);if(!t)return;if(!this.isInstanceIdUnique(t)){alert(`Instance ID "${t}" already exists.`);return}let i=window.confirm(`Share config with original?
307
+ OK = Share, Cancel = Snapshot`);try{let c=await fetch("/api/objects/duplicate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sourceId:this.options.objectId,newInstanceId:t,shareConfig:i,screenId:this.options.screenId})}),p=await c.json().catch(()=>({}));if(!c.ok||(p==null?void 0:p.success)===!1){let d=((n=p==null?void 0:p.errors)==null?void 0:n.join(`
308
+ `))||(p==null?void 0:p.error)||"Duplicate failed.";alert(d);return}(o=(r=this.options).onRefresh)==null||o.call(r),(l=(s=this.options).onSelect)==null||l.call(s,t),this.close()}catch(c){alert(`Duplicate failed: ${c instanceof Error?c.message:String(c)}`)}}async handleRename(){var t,i,n,r,o;let e=window.prompt("New instance ID",this.options.objectId);if(!(!e||e===this.options.objectId)){if(!this.isInstanceIdUnique(e)){alert(`Instance ID "${e}" already exists.`);return}try{let s=await fetch("/api/objects/rename",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,screenId:this.options.screenId,newInstanceId:e})}),l=await s.json().catch(()=>({}));if(!s.ok||(l==null?void 0:l.success)===!1){let c=((t=l==null?void 0:l.errors)==null?void 0:t.join(`
309
+ `))||(l==null?void 0:l.error)||"Rename failed.";alert(c);return}(n=(i=this.options).onRefresh)==null||n.call(i),(o=(r=this.options).onSelect)==null||o.call(r,e),this.close()}catch(s){alert(`Rename failed: ${s instanceof Error?s.message:String(s)}`)}}}async handleMove(){var i,n,r;let e=window.prompt("Move to screen (loading/start/gameplay/tutorial/endgame)",this.options.screenId);if(!e)return;let t=e.trim();if(!["loading","start","gameplay","tutorial","endgame"].includes(t)){alert("Invalid screen. Use: loading, start, gameplay, tutorial, endgame.");return}if(t!==this.options.screenId)try{let o=await fetch("/api/objects/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:this.options.objectId,fromScreenId:this.options.screenId,toScreenId:t})}),s=await o.json().catch(()=>({}));if(!o.ok||(s==null?void 0:s.success)===!1){let l=((i=s==null?void 0:s.errors)==null?void 0:i.join(`
310
+ `))||(s==null?void 0:s.error)||"Move failed.";alert(l);return}(r=(n=this.options).onRefresh)==null||r.call(n),this.close()}catch(o){alert(`Move failed: ${o instanceof Error?o.message:String(o)}`)}}handleCopyConfig(){var n,r;let e=window.getEditableObjectConfig,t=typeof e=="function"?e(this.options.objectId):null;if(!t){let o=window.__editableObjectConfigs;o&&typeof o.get=="function"&&(t=(n=o.get(this.options.objectId))!=null?n:null)}if(!t){alert("Config not found.");return}let i=JSON.stringify(t,null,2);(r=navigator.clipboard)==null||r.writeText(i).catch(()=>{alert("Failed to copy to clipboard.")}),this.close()}handleOpenInspector(){var t,i;let e=window.__previewSelectObject;typeof e=="function"&&e(this.options.objectId),(i=(t=this.options).onSelect)==null||i.call(t,this.options.objectId),this.close()}isInstanceIdUnique(e){let t=window.getEditableObjectList;if(typeof t=="function"){let r=t();if(Array.isArray(r))return!r.includes(e)}let i=window.__HANDLER_SCREEN_INDEX,n=i==null?void 0:i.instanceToScreen;return n&&typeof n=="object"?!Object.prototype.hasOwnProperty.call(n,e):!0}};var fi=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all";this.isContextMenuOpen=!1}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
47
311
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects">
48
312
  <div class="scene-panel-header" data-panel-handle>
49
313
  <div class="panel-title">
@@ -51,6 +315,7 @@
51
315
  <span class="panel-title-text">Scene Objects</span>
52
316
  </div>
53
317
  <div class="scene-panel-actions">
318
+ <button class="debug-btn debug-btn-sm success" type="button" data-add-object title="Add Game Object">\uFF0B Add</button>
54
319
  <button class="scene-panel-toggle" type="button" data-panel-toggle>\u25BE</button>
55
320
  </div>
56
321
  </div>
@@ -77,9 +342,9 @@
77
342
  </div>
78
343
  <div class="panel-resize-handle-v" data-panel-resize-v></div>
79
344
  </div>
80
- `}initialize(e,t){var a,r,o,s,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"),(o=this.searchInput)==null||o.addEventListener("input",()=>this.refreshObjects());let i=(s=this.root)==null?void 0:s.querySelector("#scene-screen-filter");if(i){try{let c=window.localStorage.getItem(this.getScreenFilterStorageKey());c&&(this.screenFilter=c)}catch{}i.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}i.addEventListener("change",()=>{let c=i.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 o,s,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 i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumbs]"),a=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumb-screen]"),r=(l=this.root)==null?void 0:l.querySelector("[data-breadcrumb-object]");if(i&&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),m={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},h=(((p=u==null?void 0:u.identity)==null?void 0:p.id)||e).toString(),f=this.formatDisplayName(h);a.textContent=m[g]||g,r.textContent=f,i.style.display="flex"}else i.style.display="none"}refreshObjects(){var p;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,i=window.refreshEditableConfigIndex;if(typeof i=="function"&&i(),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(),o=["loading","start","gameplay","tutorial","endgame"],s=Object.fromEntries(o.map(d=>[d,[]])),l=Object.fromEntries(o.map(d=>[d,[]]));a.forEach(d=>{var M,B,P,L;let u=typeof t=="function"?t(d):null;if(!u){let I=window.__editableObjectConfigs;I&&typeof I.get=="function"&&(u=(M=I.get(d))!=null?M:null)}let g=(((B=u==null?void 0:u.identity)==null?void 0:B.category)||"scene").toString(),m=(((P=u==null?void 0:u.identity)==null?void 0:P.id)||d).toString(),h=g.toLowerCase(),f=m.toLowerCase(),b=h.includes("ui")||f.startsWith("ui")||f.includes("label"),y=this.formatDisplayName(m||d),v=((L=u==null?void 0:u.render)==null?void 0:L.visible)===!1||(u==null?void 0:u.enabled)===!1,x=this.getObjectType(u),w={id:d,label:y,category:g,isUi:b,isUnused:v,objectType:x},E=this.inferScreen(w.id,u);if(this.screenFilter!=="all"&&E!==this.screenFilter||!(!r||w.id.toLowerCase().includes(r)||w.label.toLowerCase().includes(r)))return;(w.isUnused?l:s)[E].push(w)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
345
+ `}initialize(e,t){var r,o,s,l,c,p,d;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(r=this.root)==null?void 0:r.querySelector("[data-object-list]"),this.searchInput=(o=this.root)==null?void 0:o.querySelector("#scene-object-search"),(s=this.searchInput)==null||s.addEventListener("input",()=>this.refreshObjects());let i=(l=this.root)==null?void 0:l.querySelector("[data-add-object]");i==null||i.addEventListener("click",()=>{let u=this.getDefaultScreenForCreate();this.openAddObjectWizard(u)});let n=(c=this.root)==null?void 0:c.querySelector("#scene-screen-filter");if(n){try{let u=window.localStorage.getItem(this.getScreenFilterStorageKey());u&&(this.screenFilter=u)}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 u=n.value||"all";this.screenFilter=u;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()})}(p=this.root)==null||p.addEventListener("click",u=>{let g=u.target;if(!g||g.closest("[data-context-menu]"))return;let m=g.closest("[data-object-id]");if(!m)return;let h=m.dataset.objectId;h&&this.select(h)}),(d=this.listContainer)==null||d.addEventListener("contextmenu",u=>{var v;let g=u.target,m=g==null?void 0:g.closest("[data-object-id]");if(!m)return;let h=m.dataset.objectId;if(!h)return;u.preventDefault();let f=window.getEditableObjectConfig,b=typeof f=="function"?f(h):null;if(!b){let x=window.__editableObjectConfigs;x&&typeof x.get=="function"&&(b=(v=x.get(h))!=null?v:null)}let y=this.inferScreen(h,b);this.showContextMenu(h,y,u.clientX,u.clientY)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects()),window.addEventListener("handler:scene-objects-refresh",()=>this.refreshObjects())}setSelected(e){var o,s,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 i=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumbs]"),n=(s=this.root)==null?void 0:s.querySelector("[data-breadcrumb-screen]"),r=(l=this.root)==null?void 0:l.querySelector("[data-breadcrumb-object]");if(i&&n&&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),m={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},h=(((p=u==null?void 0:u.identity)==null?void 0:p.id)||e).toString(),f=this.formatDisplayName(h);n.textContent=m[g]||g,r.textContent=f,i.style.display="flex"}else i.style.display="none"}refreshObjects(){var p;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,i=window.refreshEditableConfigIndex;if(typeof i=="function"&&i(),typeof e!="function"){this.scheduleRetry();return}let n=e();if(!Array.isArray(n)||n.length===0){let d=window.__editableObjectConfigs;d&&typeof d.keys=="function"&&(n=Array.from(d.keys()))}if(!Array.isArray(n)||n.length===0){this.scheduleRetry();return}let r=(((p=this.searchInput)==null?void 0:p.value)||"").trim().toLowerCase(),o=["loading","start","gameplay","tutorial","endgame"],s=Object.fromEntries(o.map(d=>[d,[]])),l=Object.fromEntries(o.map(d=>[d,[]]));n.forEach(d=>{var P,F,M,T;let u=typeof t=="function"?t(d):null;if(!u){let I=window.__editableObjectConfigs;I&&typeof I.get=="function"&&(u=(P=I.get(d))!=null?P:null)}let g=(((F=u==null?void 0:u.identity)==null?void 0:F.category)||"scene").toString(),m=(((M=u==null?void 0:u.identity)==null?void 0:M.id)||d).toString(),h=g.toLowerCase(),f=m.toLowerCase(),b=h.includes("ui")||f.startsWith("ui")||f.includes("label"),y=this.formatDisplayName(m||d),v=((T=u==null?void 0:u.render)==null?void 0:T.visible)===!1||(u==null?void 0:u.enabled)===!1,x=this.getObjectType(u),w={id:d,label:y,category:g,isUi:b,isUnused:v,objectType:x},E=this.inferScreen(w.id,u);if(this.screenFilter!=="all"&&E!==this.screenFilter||!(!r||w.id.toLowerCase().includes(r)||w.label.toLowerCase().includes(r)))return;(w.isUnused?l:s)[E].push(w)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
81
346
  ${o.map(d=>this.renderGroup(c[d],[...s[d],...l[d]])).join("")}
82
- `,this.setSelected(this.selectedId)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var s,l;let i=window.__HANDLER_SCREEN_INDEX,a=(s=i==null?void 0:i.instanceToScreen)==null?void 0:s[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(),o=`${e} ${r}`.toLowerCase();return o.includes("loading")?"loading":o.includes("start")?"start":o.includes("tutorial")?"tutorial":o.includes("endgame")||o.includes("end_card")||o.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,i,a,r,o,s,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(r=(a=(i=e.render)==null?void 0:i.asset)==null?void 0:a.path)!=null&&r.endsWith(".json")?"animation":((s=(o=e.render)==null?void 0:o.asset)==null?void 0:s.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 i=window.getEditableObjectConfig,a=t.map(r=>{var p,d;let o=typeof i=="function"?i(r.id):null;if(!o){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(o=(p=u.get(r.id))!=null?p:null)}let s=this.getTypeIconByType(r.objectType),l=this.getAssetPreview(o),c=(d=o==null?void 0:o.ui)!=null&&d.text?`"${o.ui.text.substring(0,12)}${o.ui.text.length>12?"...":""}"`:"";return`
347
+ `,this.setSelected(this.selectedId)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var s,l;let i=window.__HANDLER_SCREEN_INDEX,n=(s=i==null?void 0:i.instanceToScreen)==null?void 0:s[e];if(n==="loading"||n==="start"||n==="gameplay"||n==="tutorial"||n==="endgame")return n;let r=(((l=t==null?void 0:t.identity)==null?void 0:l.id)||"").toString(),o=`${e} ${r}`.toLowerCase();return o.includes("loading")?"loading":o.includes("start")?"start":o.includes("tutorial")?"tutorial":o.includes("endgame")||o.includes("end_card")||o.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,i,n,r,o,s,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(r=(n=(i=e.render)==null?void 0:i.asset)==null?void 0:n.path)!=null&&r.endsWith(".json")?"animation":((s=(o=e.render)==null?void 0:o.asset)==null?void 0:s.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 i=window.getEditableObjectConfig,n=t.map(r=>{var p,d;let o=typeof i=="function"?i(r.id):null;if(!o){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(o=(p=u.get(r.id))!=null?p:null)}let s=this.getTypeIconByType(r.objectType),l=this.getAssetPreview(o),c=(d=o==null?void 0:o.ui)!=null&&d.text?`"${o.ui.text.substring(0,12)}${o.ui.text.length>12?"...":""}"`:"";return`
83
348
  <button class="scene-object-item ${r.isUnused?"unused":""}" data-object-id="${r.id}">
84
349
  <span class="scene-object-label">${r.label}</span>
85
350
  ${c?`<span class="scene-object-text-preview">${c}</span>`:""}
@@ -89,10 +354,11 @@
89
354
  <div class="scene-object-group">
90
355
  <div class="scene-object-group-title">${e} <span class="scene-object-count">${t.length}</span></div>
91
356
  <div class="scene-object-group-items">
92
- ${a}
357
+ ${n}
93
358
  </div>
94
359
  </div>
95
- `}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var i,a,r,o,s,l;if(!e)return"\u{1F4E6}";if((i=e.render)!=null&&i.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||(s=(o=e.identity)==null?void 0:o.id)!=null&&s.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 i;if(!e)return null;let t=(i=e.render)==null?void 0:i.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 i,a,r,o;if(!e)return"";let t=((i=e.render)==null?void 0:i.background_color)||((r=(a=e.gameplay)==null?void 0:a.tuning)==null?void 0:r.panel_bg_color)||((o=e.ui)==null?void 0:o.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var i,a,r,o;if(!e)return"";let t=[];return((i=e.render)==null?void 0:i.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||(o=e.ui)!=null&&o.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 hi=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
360
+ `}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var i,n,r,o,s,l;if(!e)return"\u{1F4E6}";if((i=e.render)!=null&&i.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((n=e.ui)!=null&&n.text)return"\u{1F4DD}";if(((r=e.identity)==null?void 0:r.category)==="ui")return"\u{1F3A8}";if(e.effects||(s=(o=e.identity)==null?void 0:o.id)!=null&&s.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 i;if(!e)return null;let t=(i=e.render)==null?void 0:i.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 i,n,r,o;if(!e)return"";let t=((i=e.render)==null?void 0:i.background_color)||((r=(n=e.gameplay)==null?void 0:n.tuning)==null?void 0:r.panel_bg_color)||((o=e.ui)==null?void 0:o.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var i,n,r,o;if(!e)return"";let t=[];return((i=e.render)==null?void 0:i.visible)===!1&&t.push("hidden"),((n=e.render)==null?void 0:n.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((r=e.interaction)!=null&&r.clickable||(o=e.ui)!=null&&o.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)}getDefaultScreenForCreate(){if(this.screenFilter!=="all")return this.screenFilter;let e=window.__HANDLER_ACTIVE_SCREEN;return e==="loading"||e==="start"||e==="gameplay"||e==="tutorial"||e==="endgame"?e:"gameplay"}async openAddObjectWizard(e){try{new gi().open({screenId:e})}catch(t){console.warn("[SceneObjectsPanel] Failed to open AddObjectWizard:",t)}}async showContextMenu(e,t,i,n){if(!this.isContextMenuOpen){this.isContextMenuOpen=!0;try{new hi({objectId:e,screenId:t,onSelect:o=>{o&&this.select(o)},onRefresh:()=>this.refreshObjects(),onClose:()=>{this.isContextMenuOpen=!1},onDeleteRequest:o=>this.deleteObject(o)}).open({x:i,y:n})}catch(r){this.isContextMenuOpen=!1,console.warn("[SceneObjectsPanel] Failed to open context menu:",r)}}}async deleteObject(e){var i;if(window.confirm(`Delete "${e}"? This removes it from the screen configuration.`))try{let n=await fetch("/api/objects/delete",{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({objectId:e})}),r=await n.json().catch(()=>null);if(!n.ok||(r==null?void 0:r.success)===!1){let o=((i=r==null?void 0:r.errors)==null?void 0:i.join(`
361
+ `))||(r==null?void 0:r.error)||"Delete failed.";alert(o);return}this.refreshObjects()}catch(n){alert(`Delete failed: ${n instanceof Error?n.message:String(n)}`)}}};var mi=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
96
362
  <div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
97
363
  <div class="scene-tools-header" data-tools-header data-panel-handle>
98
364
  <span class="scene-tools-title">Scene Tools</span>
@@ -137,7 +403,7 @@
137
403
  </div>
138
404
  </div>
139
405
  </div>
140
- `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let 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)},o=this.root.querySelector("#debug-highlight-object");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!o.checked),r("bounds",o.checked)});let s=this.root.querySelector("#debug-highlight-anchor");s==null||s.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!s.checked),r("anchor",s.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{r("nudge",l.checked)})}updateInfo(e){}};var fi=class{constructor(){this.root=null;this.options=null}render(){return`
406
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let i=localStorage.getItem("scene-tools-collapsed");i!==null&&(this.isCollapsed=i==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let n=this.root.querySelector("[data-tools-collapse]");n==null||n.addEventListener("click",()=>{var 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)},o=this.root.querySelector("#debug-highlight-object");o==null||o.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightObject(!!o.checked),r("bounds",o.checked)});let s=this.root.querySelector("#debug-highlight-anchor");s==null||s.addEventListener("change",()=>{var c;(c=this.options)==null||c.onHighlightAnchor(!!s.checked),r("anchor",s.checked)});let l=this.root.querySelector("#debug-nudge-enabled");l==null||l.addEventListener("change",()=>{r("nudge",l.checked)})}updateInfo(e){}};var bi=class{constructor(){this.root=null;this.options=null}render(){return`
141
407
  <div class="nudge-panel hidden" data-panel="nudge-panel">
142
408
  <div class="nudge-panel-header" data-panel-handle>
143
409
  <span class="nudge-panel-title">Nudge Controls</span>
@@ -194,7 +460,7 @@
194
460
  </div>
195
461
  </div>
196
462
  </div>
197
- `}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 o=r.dataset.nudge,s=this.getNudgeStep();switch(o){case"up":(l=this.options)==null||l.onNudge(0,-s);break;case"down":(c=this.options)==null||c.onNudge(0,s);break;case"left":(p=this.options)==null||p.onNudge(-s,0);break;case"right":(d=this.options)==null||d.onNudge(s,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(r=>{r.addEventListener("click",()=>{var l;let s=r.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(s)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var i,a;let e=(i=this.root)==null?void 0:i.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 Ct=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let i=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]:[]},o=Array.isArray(i.slots)?i.slots:[];if(o.length>0&&r.slots.length>0)for(let c of r.slots){let p=o.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 s=i.libraryAssets||{};for(let[c,p]of Object.entries(s)){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 i.categories||[])typeof c=="string"&&l.add(c);return r.categories=Array.from(l),r}render(){return`
463
+ `}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 o=r.dataset.nudge,s=this.getNudgeStep();switch(o){case"up":(l=this.options)==null||l.onNudge(0,-s);break;case"down":(c=this.options)==null||c.onNudge(0,s);break;case"left":(p=this.options)==null||p.onNudge(-s,0);break;case"right":(d=this.options)==null||d.onNudge(s,0);break}})}),Array.from(this.root.querySelectorAll(".nudge-scale-btn")).forEach(r=>{r.addEventListener("click",()=>{var l;let s=r.dataset.scale==="up"?.1:-.1;(l=this.options)==null||l.onScale(s)})})}show(){var e;(e=this.root)==null||e.classList.remove("hidden")}hide(){var e;(e=this.root)==null||e.classList.add("hidden")}getNudgeStep(){var i,n;let e=(i=this.root)==null?void 0:i.querySelector("#nudge-step-input"),t=Number((n=e==null?void 0:e.value)!=null?n:10);return Number.isFinite(t)&&t>0?t:10}};var Ct=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let i=e||{},n=t||{},r={slots:Array.isArray(n.slots)?[...n.slots]:[],libraryAssets:typeof n.libraryAssets=="object"&&n.libraryAssets?{...n.libraryAssets}:{},categories:Array.isArray(n.categories)?[...n.categories]:[]},o=Array.isArray(i.slots)?i.slots:[];if(o.length>0&&r.slots.length>0)for(let c of r.slots){let p=o.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 s=i.libraryAssets||{};for(let[c,p]of Object.entries(s)){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 i.categories||[])typeof c=="string"&&l.add(c);return r.categories=Array.from(l),r}render(){return`
198
464
  <div class="scene-panel library-panel panel-accent-purple" data-panel="library">
199
465
  <div class="scene-panel-header" data-panel-handle>
200
466
  <div class="panel-title">
@@ -213,15 +479,15 @@
213
479
  </div>
214
480
  <div class="panel-resize-handle" data-panel-resize></div>
215
481
  </div>
216
- `}initialize(e,t){var r,o,s;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(r=this.root)==null?void 0:r.querySelector("[data-library-slots]");let i=(o=this.root)==null?void 0:o.querySelector("[data-create-ai]");i==null||i.addEventListener("click",()=>{this.handleCreateWithAI()});let a=(s=this.root)==null?void 0:s.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,i=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(i.ok){let a=await i.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 i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)&&i.slots.length>0){this.registry=i,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 i of this.registry.slots)e[i.category]||(e[i.category]=[]),e[i.category].push(i);let t=Date.now();this.slotsContainer.innerHTML="";for(let i of this.registry.categories){let a=e[i]||[];if(a.length===0)continue;let r=document.createElement("div");r.className="library-category";let o=document.createElement("div");o.className="library-category-header",o.textContent=this.formatCategoryName(i),r.appendChild(o);let s=document.createElement("div");s.className="library-category-slots";for(let l of a){let c=this.createSlotElement(l,t);s.appendChild(c)}r.appendChild(s),this.slotsContainer.appendChild(r)}}createSlotElement(e,t){let i=this.expandedSlot===e.slotId,a=document.createElement("div");a.className=`library-slot ${i?"expanded":""}`,a.dataset.slotId=e.slotId;let r=document.createElement("div");r.className="slot-header";let o=document.createElement("div");o.className="slot-current";let s=document.createElement("img");s.src=`/raw/${e.currentAsset}?t=${t}`,s.alt=e.displayName,s.className="slot-thumbnail",s.onerror=()=>{s.style.display="none"},o.appendChild(s),r.appendChild(o);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-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleUpload(e)}),d.appendChild(g);let m=document.createElement("button");m.className="slot-reset",m.title="Reset to default",m.textContent="\u21BA",m.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=i?"\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),i){let f=this.createLibraryElement(e,t);a.appendChild(f)}return a}createLibraryElement(e,t){var r;let i=document.createElement("div");i.className="slot-library";let a=((r=this.registry)==null?void 0:r.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(o=>{let s=new Map;for(let c of a)s.set(c.filename,c);for(let c of o)s.has(c.filename)||s.set(c.filename,c);let l=Array.from(s.values());if(l.length===0){i.innerHTML='<div class="library-empty">No alternative assets</div>';return}i.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)}),i.appendChild(p)}}),i.innerHTML='<div class="library-loading">Loading assets...</div>',i}async fetchFolderAssets(e,t){try{let i=await fetch(`/raw/library/${e}/?t=${t}`);if(!i.ok)return[];let a=await i.text(),r=[],o=/href="([^"]+\.(png|jpg|jpeg))"/gi,s;for(;(s=o.exec(a))!==null;){let l=s[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 i;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{await((i=this.options)==null?void 0:i.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(i){console.error("[LIBRARY] Failed to reset slot:",i)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let i=e.slotId||e.objectId,a="render.texture";e.category==="ui"&&(a="ui.image"),e.category==="audio"&&(a="audio.src"),t(i,`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.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var a;let i=(a=t.files)==null?void 0:a[0];if(i){console.log("[Library] File selected:",i.name);try{let r=await this.fileToDataUrl(i);if(!r){alert("Failed to read file");return}let s=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",s,"to category:",l);let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${s}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[Library] \u2705 Upload saved:",p.path);let d=window.addAssetToRegistry;typeof d=="function"&&d(l,`${s}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${s}.png`),e.currentAsset=`${s}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",p.error),alert(`Upload failed: ${p.error}`)}catch(r){console.error("[Library] \u274C Upload error:",r),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let i=e.startsWith("json.")?e.replace("json.",""):e,a=this.registry.slots.find(r=>(r.objectId===i||r.slotId===i)&&(!t||r.category===t));a?(console.log("[LIBRARY] Highlighting slot:",a.slotId),this.expandedSlot=a.slotId,this.renderSlots(),setTimeout(()=>{var o;let r=(o=this.slotsContainer)==null?void 0:o.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 mi=class{detectType(e,t,i){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 bi=class{render(e,t,i,a){let r=this.formatLabel(t),o=i?this.getThumbnailUrl(i):"";return`
482
+ `}initialize(e,t){var r,o,s;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(r=this.root)==null?void 0:r.querySelector("[data-library-slots]");let i=(o=this.root)==null?void 0:o.querySelector("[data-create-ai]");i==null||i.addEventListener("click",()=>{this.handleCreateWithAI()});let n=(s=this.root)==null?void 0:s.querySelector("[data-refresh-library]");n==null||n.addEventListener("click",()=>{n.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>n.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,i=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(i.ok){let n=await i.json(),r=this.mergeRegistries(t,n);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 i=t();if(i!=null&&i.slots&&Array.isArray(i.slots)&&i.slots.length>0){this.registry=i,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 i of this.registry.slots)e[i.category]||(e[i.category]=[]),e[i.category].push(i);let t=Date.now();this.slotsContainer.innerHTML="";for(let i of this.registry.categories){let n=e[i]||[];if(n.length===0)continue;let r=document.createElement("div");r.className="library-category";let o=document.createElement("div");o.className="library-category-header",o.textContent=this.formatCategoryName(i),r.appendChild(o);let s=document.createElement("div");s.className="library-category-slots";for(let l of n){let c=this.createSlotElement(l,t);s.appendChild(c)}r.appendChild(s),this.slotsContainer.appendChild(r)}}createSlotElement(e,t){let i=this.expandedSlot===e.slotId,n=document.createElement("div");n.className=`library-slot ${i?"expanded":""}`,n.dataset.slotId=e.slotId;let r=document.createElement("div");r.className="slot-header";let o=document.createElement("div");o.className="slot-current";let s=document.createElement("img");s.src=`/raw/${e.currentAsset}?t=${t}`,s.alt=e.displayName,s.className="slot-thumbnail",s.onerror=()=>{s.style.display="none"},o.appendChild(s),r.appendChild(o);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-upload",g.title="Upload new asset",g.textContent="\u{1F4E4}",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleUpload(e)}),d.appendChild(g);let m=document.createElement("button");m.className="slot-reset",m.title="Reset to default",m.textContent="\u21BA",m.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(m);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=i?"\u25BC":"\u25B6",d.appendChild(h),r.appendChild(d),r.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),n.appendChild(r),i){let f=this.createLibraryElement(e,t);n.appendChild(f)}return n}createLibraryElement(e,t){var r;let i=document.createElement("div");i.className="slot-library";let n=((r=this.registry)==null?void 0:r.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(o=>{let s=new Map;for(let c of n)s.set(c.filename,c);for(let c of o)s.has(c.filename)||s.set(c.filename,c);let l=Array.from(s.values());if(l.length===0){i.innerHTML='<div class="library-empty">No alternative assets</div>';return}i.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)}),i.appendChild(p)}}),i.innerHTML='<div class="library-loading">Loading assets...</div>',i}async fetchFolderAssets(e,t){try{let i=await fetch(`/raw/library/${e}/?t=${t}`);if(!i.ok)return[];let n=await i.text(),r=[],o=/href="([^"]+\.(png|jpg|jpeg))"/gi,s;for(;(s=o.exec(n))!==null;){let l=s[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 i;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{await((i=this.options)==null?void 0:i.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to apply asset:",n)}}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(i){console.error("[LIBRARY] Failed to reset slot:",i)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let i=e.slotId||e.objectId,n="render.texture";e.category==="ui"&&(n="ui.image"),e.category==="audio"&&(n="audio.src"),t(i,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:n})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}async handleUpload(e){console.log("[Library] Opening file upload for slot:",e);let t=document.createElement("input");t.type="file",t.accept="image/*",t.style.display="none",t.addEventListener("change",async()=>{var n;let i=(n=t.files)==null?void 0:n[0];if(i){console.log("[Library] File selected:",i.name);try{let r=await this.fileToDataUrl(i);if(!r){alert("Failed to read file");return}let s=`${e.displayName.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,l=e.category;console.log("[Library] Saving uploaded file:",s,"to category:",l);let p=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:l,filename:`${s}.png`,data:r,overwrite:!0})})).json();if(p.success){console.log("[Library] \u2705 Upload saved:",p.path);let d=window.addAssetToRegistry;typeof d=="function"&&d(l,`${s}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(u){console.warn("[Library] Setup-library not available:",u)}await this.handleApply(e,`${s}.png`),e.currentAsset=`${s}.png`,await this.refresh(),setTimeout(()=>{this.highlightSlot(e.objectId,l)},500),console.log("[Library] \u2705 Upload complete and applied")}else console.error("[Library] \u274C Upload failed:",p.error),alert(`Upload failed: ${p.error}`)}catch(r){console.error("[Library] \u274C Upload error:",r),alert("Upload failed. Check console for details.")}finally{t.remove()}}}),document.body.appendChild(t),t.click()}fileToDataUrl(e){return new Promise(t=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>t(null),i.readAsDataURL(e)})}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let i=e.startsWith("json.")?e.replace("json.",""):e,n=this.registry.slots.find(r=>(r.objectId===i||r.slotId===i)&&(!t||r.category===t));n?(console.log("[LIBRARY] Highlighting slot:",n.slotId),this.expandedSlot=n.slotId,this.renderSlots(),setTimeout(()=>{var o;let r=(o=this.slotsContainer)==null?void 0:o.querySelector(`[data-slot-id="${n.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 yi=class{detectType(e,t,i){let n=e.toLowerCase();return n==="logic_id"||n==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":n.includes("color")||n.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var vi=class{render(e,t,i,n){let r=this.formatLabel(t),o=i?this.getThumbnailUrl(i):"";return`
217
483
  <div class="inspector-property" data-property-type="image">
218
484
  <div class="inspector-property-header">
219
485
  <label class="inspector-label">${r}</label>
220
486
  <div class="inspector-quick-actions">
221
- <button class="debug-btn debug-btn-sm" data-action="library" data-path="${a}" data-object="${e}" title="Choose from Library">\u{1F3A8}</button>
222
- <button class="debug-btn debug-btn-sm" data-action="ai-edit" data-path="${a}" data-object="${e}" title="Edit with AI">\u2728</button>
223
- <button class="debug-btn debug-btn-sm" data-action="upload" data-path="${a}" data-object="${e}" title="Upload">\u{1F4E4}</button>
224
- <button class="debug-btn debug-btn-sm" data-action="reset" data-path="${a}" data-object="${e}" title="Reset">\u21BA</button>
487
+ <button class="debug-btn debug-btn-sm" data-action="library" data-path="${n}" data-object="${e}" title="Choose from Library">\u{1F3A8}</button>
488
+ <button class="debug-btn debug-btn-sm" data-action="ai-edit" data-path="${n}" data-object="${e}" title="Edit with AI">\u2728</button>
489
+ <button class="debug-btn debug-btn-sm" data-action="upload" data-path="${n}" data-object="${e}" title="Upload">\u{1F4E4}</button>
490
+ <button class="debug-btn debug-btn-sm" data-action="reset" data-path="${n}" data-object="${e}" title="Reset">\u21BA</button>
225
491
  </div>
226
492
  </div>
227
493
  ${o?`
@@ -235,55 +501,55 @@
235
501
  </div>
236
502
  `}
237
503
  </div>
238
- `}getThumbnailUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")?e:`/raw/${e}?t=${Date.now()}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var yi=class{render(e,t,i,a){let r=i||"#000000";return`
504
+ `}getThumbnailUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")?e:`/raw/${e}?t=${Date.now()}`}escapeHtml(e){let t=document.createElement("div");return t.textContent=e,t.innerHTML}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var xi=class{render(e,t,i,n){let r=i||"#000000";return`
239
505
  <div class="inspector-property inspector-property-color">
240
506
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
241
507
  <div class="inspector-color-group">
242
508
  <input type="color"
243
509
  class="inspector-color-picker"
244
510
  value="${r}"
245
- data-property-path="${a}"
511
+ data-property-path="${n}"
246
512
  data-object-id="${e}" />
247
513
  <input type="text"
248
514
  class="inspector-input inspector-color-text"
249
515
  value="${r}"
250
- data-property-path="${a}"
516
+ data-property-path="${n}"
251
517
  data-object-id="${e}" />
252
518
  </div>
253
519
  </div>
254
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var vi=class{render(e,t,i,a){return`
520
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var wi=class{render(e,t,i,n){return`
255
521
  <div class="inspector-property inspector-property-number">
256
522
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
257
523
  <input type="number"
258
524
  class="inspector-input"
259
525
  value="${i}"
260
- data-property-path="${a}"
526
+ data-property-path="${n}"
261
527
  data-object-id="${e}"
262
528
  step="any" />
263
529
  </div>
264
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var xi=class{render(e,t,i,a){let r=String(i||"");return`
530
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ei=class{render(e,t,i,n){let r=String(i||"");return`
265
531
  <div class="inspector-property inspector-property-text">
266
532
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
267
533
  <div class="inspector-input-group">
268
534
  <input type="text"
269
535
  class="inspector-input"
270
536
  value="${r}"
271
- data-property-path="${a}"
537
+ data-property-path="${n}"
272
538
  data-object-id="${e}" />
273
539
  </div>
274
540
  </div>
275
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var wi=class{render(e,t,i,a){return`
541
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Si=class{render(e,t,i,n){return`
276
542
  <div class="inspector-property inspector-property-boolean">
277
543
  <label class="inspector-property-label">
278
544
  <input type="checkbox"
279
545
  class="inspector-checkbox"
280
546
  ${i?"checked":""}
281
- data-property-path="${a}"
547
+ data-property-path="${n}"
282
548
  data-object-id="${e}" />
283
549
  <span>${this.formatLabel(t)}</span>
284
550
  </label>
285
551
  </div>
286
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ei=class{render(e,t,i,a){if(!Array.isArray(i)||i.length===0)return`
552
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ai=class{render(e,t,i,n){if(!Array.isArray(i)||i.length===0)return`
287
553
  <div class="inspector-property inspector-property-array">
288
554
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
289
555
  <div class="inspector-array-empty">Empty array</div>
@@ -295,7 +561,7 @@
295
561
  ${r}
296
562
  </div>
297
563
  </div>
298
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ai=class{constructor(e){this.registry=e}render(e,t,i,a){if(t==="logic"&&i&&typeof i=="object")return this.renderLogic(e,t,i,a);let r=[];for(let s in i){let l=i[s],c=`${a}.${s}`,p=this.registry.renderProperty(e,s,l,c);p&&r.push(p)}return r.length===0?"":r.length<=4&&r.every(s=>s.includes("inspector-property"))?`
564
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ci=class{constructor(e){this.registry=e}render(e,t,i,n){if(t==="logic"&&i&&typeof i=="object")return this.renderLogic(e,t,i,n);let r=[];for(let s in i){let l=i[s],c=`${n}.${s}`,p=this.registry.renderProperty(e,s,l,c);p&&r.push(p)}return r.length===0?"":r.length<=4&&r.every(s=>s.includes("inspector-property"))?`
299
565
  <div class="inspector-subsection">
300
566
  <div class="inspector-subsection-title">${this.formatLabel(t)}</div>
301
567
  <div class="inspector-subsection-content">
@@ -309,12 +575,12 @@
309
575
  ${r.join("")}
310
576
  </div>
311
577
  </div>
312
- `}renderLogic(e,t,i,a){let r=[],o=typeof(i==null?void 0:i.id)=="string"?i.id:"",s={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(m=>String(m)).filter(m=>m.trim().length>0);return Array.from(new Set(g)).sort((m,h)=>m.localeCompare(h))})(),c=o&&!l.includes(o)?[o,...l]:l;r.push(`
578
+ `}renderLogic(e,t,i,n){let r=[],o=typeof(i==null?void 0:i.id)=="string"?i.id:"",s={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(m=>String(m)).filter(m=>m.trim().length>0);return Array.from(new Set(g)).sort((m,h)=>m.localeCompare(h))})(),c=o&&!l.includes(o)?[o,...l]:l;r.push(`
313
579
  <div class="inspector-property inspector-property-text">
314
580
  <label class="inspector-property-label">Id</label>
315
581
  <div class="inspector-input-group">
316
582
  <select class="inspector-component-select inspector-input"
317
- data-property-path="${a}.id"
583
+ data-property-path="${n}.id"
318
584
  data-object-id="${e}"
319
585
  data-logic-id-selector="true">
320
586
  <option value="" ${o?"":"selected"}>None</option>
@@ -322,7 +588,7 @@
322
588
  </select>
323
589
  </div>
324
590
  </div>
325
- `);for(let p in i){if(p==="id")continue;let d=i[p],u=`${a}.${p}`;if(p==="props"&&d&&typeof d=="object"){let m=[];for(let h in d){let f=d[h],b=`${u}.${h}`,y=s[h];if((h==="targetId"||h==="inputId")&&typeof f=="string"){let v=(()=>{try{let E=window,C=E==null?void 0:E.__editableConfig;if(!(C!=null&&C.objects))return[];let A=[];if(C.objects instanceof Map)for(let M of C.objects.keys())A.push(M);else typeof C.objects=="object"&&A.push(...Object.keys(C.objects));return A.sort()}catch{return[]}})(),x=f||"",w=x&&!v.includes(x)?[x,...v]:v;m.push(`
591
+ `);for(let p in i){if(p==="id")continue;let d=i[p],u=`${n}.${p}`;if(p==="props"&&d&&typeof d=="object"){let m=[];for(let h in d){let f=d[h],b=`${u}.${h}`,y=s[h];if((h==="targetId"||h==="inputId")&&typeof f=="string"){let v=(()=>{try{let E=window,C=E==null?void 0:E.__editableConfig;if(!(C!=null&&C.objects))return[];let S=[];if(C.objects instanceof Map)for(let P of C.objects.keys())S.push(P);else typeof C.objects=="object"&&S.push(...Object.keys(C.objects));return S.sort()}catch{return[]}})(),x=f||"",w=x&&!v.includes(x)?[x,...v]:v;m.push(`
326
592
  <div class="inspector-property inspector-property-text">
327
593
  <label class="inspector-property-label">${this.formatLabel(h)}</label>
328
594
  <div class="inspector-input-group">
@@ -359,18 +625,18 @@
359
625
  ${r.join("")}
360
626
  </div>
361
627
  </div>
362
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Si=class{render(e,t,i,a,r){let o=i==null?"":String(i),s=Array.from(new Set(r.map(c=>String(c)))),l=o&&!s.includes(o)?[o,...s]:s;return`
628
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ti=class{render(e,t,i,n,r){let o=i==null?"":String(i),s=Array.from(new Set(r.map(c=>String(c)))),l=o&&!s.includes(o)?[o,...s]:s;return`
363
629
  <div class="inspector-property inspector-property-text">
364
630
  <label class="inspector-property-label">${this.formatLabel(t)}</label>
365
631
  <div class="inspector-input-group">
366
632
  <select class="inspector-component-select inspector-input"
367
- data-property-path="${a}"
633
+ data-property-path="${n}"
368
634
  data-object-id="${e}">
369
635
  ${l.map(c=>`<option value="${c}" ${c===o?"selected":""}>${c}</option>`).join("")}
370
636
  </select>
371
637
  </div>
372
638
  </div>
373
- `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Ci=class{constructor(){this.typeDetector=new mi,this.imageRenderer=new bi,this.colorRenderer=new yi,this.numberRenderer=new vi,this.textRenderer=new xi,this.booleanRenderer=new wi,this.arrayRenderer=new Ei,this.objectRenderer=new Ai(this),this.selectRenderer=new Si}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let i=[];if(t.objects instanceof Map)for(let a of t.objects.keys())i.push(a);else typeof t.objects=="object"&&i.push(...Object.keys(t.objects));return i.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let i=window,a=i==null?void 0:i.__editableConfig,r=a==null?void 0:a.schemas;if(!r)return null;let o=String(e||"").split(".").filter(Boolean);if(o.length<2)return null;let s=o[0],l=o.slice(1).join("."),c=r instanceof Map?r.get(s):r==null?void 0:r[s];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,o)=>r.localeCompare(o))}catch{return[]}}renderProperty(e,t,i,a){let r=t.toLowerCase(),o=r==="logic"||r==="logic_id"||r==="logicid",s=r==="id"&&a.toLowerCase().includes("logic");if((o||s)&&typeof i=="string"){let u=this.getLogicOptions();return this.selectRenderer.render(e,t,i,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"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"]}[t];if(c&&a.includes("logic.props"))return this.selectRenderer.render(e,t,i,a,c);if((t==="targetId"||t==="inputId")&&typeof i=="string"){let u=this.getObjectIds();return this.selectRenderer.render(e,t,i,a,["",...u])}let p=this.getEnumOptionsFromSchemas(a);if(p)return this.selectRenderer.render(e,t,i,a,p);switch(this.typeDetector.detectType(t,i)){case"image":return this.imageRenderer.render(e,t,i,a);case"color":return this.colorRenderer.render(e,t,i,a);case"number":return this.numberRenderer.render(e,t,i,a);case"boolean":return this.booleanRenderer.render(e,t,i,a);case"array":return this.arrayRenderer.render(e,t,i,a);case"object":return this.objectRenderer.render(e,t,i,a);case"select":return this.selectRenderer.render(e,t,i,a,[]);default:return this.textRenderer.render(e,t,i,a)}}getTypeDetector(){return this.typeDetector}};K();var Ze=class{async updateProperty(e,t,i,a={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,i);let r=window.getEditableObjectConfig;if(typeof r!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let o=r(e);if(!o){console.error("[PropertyUpdateManager] Config not found for:",e);return}Se({objectId:e,path:t,value:i},{persist:!0});let s=window.applyEditableObjectConfig;if(typeof s=="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:o;await s(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 i=t.split("."),a=e;for(let r of i)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 Li=class{constructor(){this.updateManager=new Ze}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let a=window.getEditableObjectConfig;if(typeof a!="function")return;let r=a(t);if(!r)return;let o=this.updateManager.getNestedProperty(r,i);if(e==="ai-convert"||e==="upload"||e==="library"){let s=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";s&&(await this.prepareForImageConversion(t,r),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,o);break;case"ai-edit":this.openAIEditor(t,i,o);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,o);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,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 o=((a=(i=t.transform)==null?void 0:i.scale)!=null?a:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",o),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",o)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var s,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let a=i();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=((s=t.identity)==null?void 0:s.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,i){var r;let a=window.__debugContext;if(a){if(a.activeTab!=="library"){a.activeTab="library";let o=window.__updateWorkbenchTabs;typeof o=="function"&&o()}if(a.libraryPanel){let o=window.getEditableObjectConfig,s=o==null?void 0:o(e),l=(r=s==null?void 0:s.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,i){let a=window.__openAiEditor;if(typeof a=="function"){let r=t.split(".").pop()||t;a(r,`Edit ${r} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){let i=document.createElement("input");i.type="file",i.accept="image/*",i.onchange=async a=>{var s;let r=(s=a.target.files)==null?void 0:s[0];if(!r)return;console.log("[QuickActionsBar] Preparing upload for:",r.name);let o=new FileReader;o.onload=async()=>{var c,p,d;let l=o.result;try{let u=window.getEditableObjectConfig,g=u==null?void 0:u(e),m=((c=g==null?void 0:g.identity)==null?void 0:c.category)||(t.split(".")[0]==="render"?"environment":"ui"),f=`${e.replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`;console.log("[QuickActionsBar] Saving uploaded file:",f,"to category:",m);let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:m,filename:`${f}.png`,data:l,overwrite:!0})})).json();if(y.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",y.path);let v=window.addAssetToRegistry;typeof v=="function"&&v(m,`${f}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}}),console.log("[QuickActionsBar] \u2705 Library setup completed")}catch(C){console.warn("[QuickActionsBar] Setup-library not available:",C)}let x=window.refreshAssetLibrary;typeof x=="function"&&await x(),await this.updateManager.updateProperty(e,t,y.path);let w=window.__debugContext;(d=(p=w==null?void 0:w.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,y.path);let E=window.__highlightLibrarySlot;typeof E=="function"&&setTimeout(()=>{E(e,m)},500),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[QuickActionsBar] \u2705 Upload complete and applied")}else console.error("[QuickActionsBar] \u274C Upload failed:",y.error),alert(`Upload failed: ${y.error}`)}catch(u){console.error("[QuickActionsBar] \u274C Upload error:",u),alert("Upload failed. Check console.")}},o.readAsDataURL(r)},i.click()}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let a=i[0],r=i.slice(1),o=window.__editableConfig;if(!(o!=null&&o.schemas))return;let s=null;if(o.schemas instanceof Map?s=o.schemas.get(a):typeof o.schemas=="object"&&(s=o.schemas[a]),!(s!=null&&s.defaults))return;let l=s.defaults;for(let c of r)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let a=window.__openAiEditor;if(typeof a=="function"){let o=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,s="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",s),a(e,o,"",{objectId:e,path:s});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 Is(n,e){let t;return function(...a){let r=()=>{clearTimeout(t),n(...a)};clearTimeout(t),t=setTimeout(r,e)}}var Ti=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Ci,this.updateManager=new Ze,this.quickActions=new Li,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
639
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Li=class{constructor(){this.typeDetector=new yi,this.imageRenderer=new vi,this.colorRenderer=new xi,this.numberRenderer=new wi,this.textRenderer=new Ei,this.booleanRenderer=new Si,this.arrayRenderer=new Ai,this.objectRenderer=new Ci(this),this.selectRenderer=new Ti}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let i=[];if(t.objects instanceof Map)for(let n of t.objects.keys())i.push(n);else typeof t.objects=="object"&&i.push(...Object.keys(t.objects));return i.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let i=window,n=i==null?void 0:i.__editableConfig,r=n==null?void 0:n.schemas;if(!r)return null;let o=String(e||"").split(".").filter(Boolean);if(o.length<2)return null;let s=o[0],l=o.slice(1).join("."),c=r instanceof Map?r.get(s):r==null?void 0:r[s];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:[],n=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(r=>String(r)).filter(r=>r.trim().length>0);return Array.from(new Set(n)).sort((r,o)=>r.localeCompare(o))}catch{return[]}}renderProperty(e,t,i,n){let r=t.toLowerCase(),o=r==="logic"||r==="logic_id"||r==="logicid",s=r==="id"&&n.toLowerCase().includes("logic");if((o||s)&&typeof i=="string"){let u=this.getLogicOptions();return this.selectRenderer.render(e,t,i,n,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"],particleEffect:["","sparkle","gem","fire","heart","stars","smoke","magic","coin"],collectSound:["","click_4.wav","click_6.wav","success_4.wav"]}[t];if(c&&n.includes("logic.props"))return this.selectRenderer.render(e,t,i,n,c);if((t==="targetId"||t==="inputId")&&typeof i=="string"){let u=this.getObjectIds();return this.selectRenderer.render(e,t,i,n,["",...u])}let p=this.getEnumOptionsFromSchemas(n);if(p)return this.selectRenderer.render(e,t,i,n,p);switch(this.typeDetector.detectType(t,i)){case"image":return this.imageRenderer.render(e,t,i,n);case"color":return this.colorRenderer.render(e,t,i,n);case"number":return this.numberRenderer.render(e,t,i,n);case"boolean":return this.booleanRenderer.render(e,t,i,n);case"array":return this.arrayRenderer.render(e,t,i,n);case"object":return this.objectRenderer.render(e,t,i,n);case"select":return this.selectRenderer.render(e,t,i,n,[]);default:return this.textRenderer.render(e,t,i,n)}}getTypeDetector(){return this.typeDetector}};K();var Ze=class{async updateProperty(e,t,i,n={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,i);let r=window.getEditableObjectConfig;if(typeof r!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let o=r(e);if(!o){console.error("[PropertyUpdateManager] Config not found for:",e);return}Ae({objectId:e,path:t,value:i},{persist:!0});let s=window.applyEditableObjectConfig;if(typeof s=="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:o;await s(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),n.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let i=t.split("."),n=e;for(let r of i)if(n&&typeof n=="object"&&r in n)n=n[r];else return;return n}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};var ki=class{constructor(){this.updateManager=new Ze}async handleAction(e,t,i){console.log("[QuickActionsBar] Action:",e,t,i);let n=window.getEditableObjectConfig;if(typeof n!="function")return;let r=n(t);if(!r)return;let o=this.updateManager.getNestedProperty(r,i);if(e==="ai-convert"||e==="upload"||e==="library"){let s=i==="ui.text"||i==="render.asset.path",l=i==="render.asset.path";s&&(await this.prepareForImageConversion(t,r),e==="ai-convert"&&i!=="render.asset.path"&&(i="render.asset.path"))}switch(e){case"library":this.openLibrary(t,i,o);break;case"ai-edit":this.openAIEditor(t,i,o);break;case"upload":this.openUpload(t,i);break;case"reset":await this.resetToDefault(t,i);break;case"ai-convert":this.handleAiConvert(t,i,o);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var i,n;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let o=((n=(i=t.transform)==null?void 0:i.scale)!=null?n:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",o),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",o)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var s,l,c;let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!n||!n.slots)return;let r=e.startsWith("json.")?e.replace("json.",""):e;if(!n.slots.some(p=>p.objectId===r||p.slotId===r)){let p=((s=t.identity)==null?void 0:s.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",r),n.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"}),n.categories&&!n.categories.includes(p)&&n.categories.push(p),n.libraryAssets&&!n.libraryAssets[p]&&(n.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,i){var r;let n=window.__debugContext;if(n){if(n.activeTab!=="library"){n.activeTab="library";let o=window.__updateWorkbenchTabs;typeof o=="function"&&o()}if(n.libraryPanel){let o=window.getEditableObjectConfig,s=o==null?void 0:o(e),l=(r=s==null?void 0:s.identity)==null?void 0:r.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),n.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let r=t.split(".").pop()||t;n(r,`Edit ${r} for ${e}`,i,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){let i=document.createElement("input");i.type="file",i.accept="image/*",i.onchange=async n=>{var s;let r=(s=n.target.files)==null?void 0:s[0];if(!r)return;console.log("[QuickActionsBar] Preparing upload for:",r.name);let o=new FileReader;o.onload=async()=>{var c,p,d;let l=o.result;try{let u=window.getEditableObjectConfig,g=u==null?void 0:u(e),m=((c=g==null?void 0:g.identity)==null?void 0:c.category)||(t.split(".")[0]==="render"?"environment":"ui"),f=`${e.replace(/^json\./,"").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`;console.log("[QuickActionsBar] Saving uploaded file:",f,"to category:",m);let y=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:m,filename:`${f}.png`,data:l,overwrite:!0})})).json();if(y.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",y.path);let v=window.addAssetToRegistry;typeof v=="function"&&v(m,`${f}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}}),console.log("[QuickActionsBar] \u2705 Library setup completed")}catch(C){console.warn("[QuickActionsBar] Setup-library not available:",C)}let x=window.refreshAssetLibrary;typeof x=="function"&&await x(),await this.updateManager.updateProperty(e,t,y.path);let w=window.__debugContext;(d=(p=w==null?void 0:w.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,y.path);let E=window.__highlightLibrarySlot;typeof E=="function"&&setTimeout(()=>{E(e,m)},500),window.dispatchEvent(new CustomEvent("inspector:refresh")),console.log("[QuickActionsBar] \u2705 Upload complete and applied")}else console.error("[QuickActionsBar] \u274C Upload failed:",y.error),alert(`Upload failed: ${y.error}`)}catch(u){console.error("[QuickActionsBar] \u274C Upload error:",u),alert("Upload failed. Check console.")}},o.readAsDataURL(r)},i.click()}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let i=await this.getDefaultValue(e,t);i!==void 0?(await this.updateManager.updateProperty(e,t,i),console.log("[QuickActionsBar] Reset to default value:",i)):alert("No default value found for this property.")}catch(i){console.error("[QuickActionsBar] Failed to reset to default:",i),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let i=t.split(".");if(i.length<2)return;let n=i[0],r=i.slice(1),o=window.__editableConfig;if(!(o!=null&&o.schemas))return;let s=null;if(o.schemas instanceof Map?s=o.schemas.get(n):typeof o.schemas=="object"&&(s=o.schemas[n]),!(s!=null&&s.defaults))return;let l=s.defaults;for(let c of r)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,i){let n=window.__openAiEditor;if(typeof n=="function"){let o=`A single, high-quality, high-detail game UI icon/asset representing "${String(i||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,s="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",s),n(e,o,"",{objectId:e,path:s});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 Hs(a,e){let t;return function(...n){let r=()=>{clearTimeout(t),a(...n)};clearTimeout(t),t=setTimeout(r,e)}}var _i=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Li,this.updateManager=new Ze,this.quickActions=new ki,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
374
640
  <div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector">
375
641
  <div class="scene-panel-header" data-panel-handle>
376
642
  <div class="panel-title">
@@ -391,7 +657,7 @@
391
657
  </div>
392
658
  </div>
393
659
  </div>
394
- `}initialize(e,t){var i;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(i=this.root)==null?void 0:i.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 i=t(e);if(!i){console.error("[InspectorPanel] Object not found in config system:",e),this.showError(`Object not found: ${e}`);return}this.renderProperties(e,i)}renderProperties(e,t){if(!this.contentContainer)return;let i=[],a=t.identity||{},r=a.id||e,o=a.category||"unknown";i.push(`
660
+ `}initialize(e,t){var i;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(i=this.root)==null?void 0:i.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 i=t(e);if(!i){console.error("[InspectorPanel] Object not found in config system:",e),this.showError(`Object not found: ${e}`);return}this.renderProperties(e,i)}renderProperties(e,t){if(!this.contentContainer)return;let i=[],n=t.identity||{},r=n.id||e,o=n.category||"unknown";i.push(`
395
661
  <div class="inspector-header">
396
662
  <div class="inspector-header-info">
397
663
  <div class="inspector-object-name">${r}</div>
@@ -399,7 +665,7 @@
399
665
  </div>
400
666
  ${this.renderConversionButtons(e,t)}
401
667
  </div>
402
- `);let s=["transform","ui","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of s){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;i.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!s.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;i.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=i.join("")+this.renderFooter(t),this.attachEventListeners()}renderConversionButtons(e,t){var s,l,c,p;let i=!!t.ui,a=((s=t.ui)==null?void 0:s.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(i||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||a)return"";let o=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
668
+ `);let s=["transform","ui","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of s){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;i.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!s.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;i.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=i.join("")+this.renderFooter(t),this.attachEventListeners()}renderConversionButtons(e,t){var s,l,c,p;let i=!!t.ui,n=((s=t.ui)==null?void 0:s.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(i||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||n)return"";let o=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
403
669
  <div class="inspector-quick-actions">
404
670
  <button class="debug-btn debug-btn-sm success ai-simple-btn" type="button" data-convert-toggle>
405
671
  \u2728 Convert to PNG
@@ -410,17 +676,17 @@
410
676
  <button class="debug-btn debug-btn-sm" data-action="upload" data-path="render.asset.path" data-object="${e}">\u{1F4E4} Upload</button>
411
677
  </div>
412
678
  </div>
413
- `}renderFooter(e){let t=["logic","motion","effects","ui","audio","physics","interaction","gameplay","visibility"],i=Object.keys(e),a=t.filter(r=>!i.includes(r));return a.length===0?"":`
679
+ `}renderFooter(e){let t=["logic","motion","effects","ui","audio","physics","interaction","gameplay","visibility"],i=Object.keys(e),n=t.filter(r=>!i.includes(r));return n.length===0?"":`
414
680
  <div class="inspector-footer">
415
681
  <div class="inspector-add-component">
416
682
  <select class="inspector-component-select" data-inspector-component-select>
417
683
  <option value="" disabled selected>Add Component...</option>
418
- ${a.map(r=>`<option value="${r}">${this.formatLabel(r)}</option>`).join("")}
684
+ ${n.map(r=>`<option value="${r}">${this.formatLabel(r)}</option>`).join("")}
419
685
  </select>
420
686
  <button class="debug-btn debug-btn-sm primary" data-inspector-add-component-btn>Add</button>
421
687
  </div>
422
688
  </div>
423
- `}renderSection(e,t,i,a){let r=[],o=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let c in i){if(!this.showAdvanced&&o.includes(c))continue;let p=i[c],d=`${a}.${c}`,u=this.rendererRegistry.renderProperty(e,c,p,d);u&&r.push(u)}return r.length===0?"":`
689
+ `}renderSection(e,t,i,n){let r=[],o=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let c in i){if(!this.showAdvanced&&o.includes(c))continue;let p=i[c],d=`${n}.${c}`,u=this.rendererRegistry.renderProperty(e,c,p,d);u&&r.push(u)}return r.length===0?"":`
424
690
  <div class="inspector-section ${t==="transform"?"":"collapsed"}" data-section="${t}">
425
691
  <div class="inspector-section-header" data-section-toggle="${t}">
426
692
  <span class="inspector-section-arrow">\u25BC</span>
@@ -431,7 +697,7 @@
431
697
  ${r.join("")}
432
698
  </div>
433
699
  </div>
434
- `}attachEventListeners(){var c,p,d,u;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Is((g,m,h)=>{var f,b;this.updateManager.updateProperty(g,m,h),(b=(f=this.options)==null?void 0:f.onPropertyChange)==null||b.call(f,g,m,h)},300);e.forEach(g=>{let m=f=>{var x,w;let b=f.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let E=b.value;if(b.type==="checkbox")E=b.checked;else if(b.type==="number"&&(E=parseFloat(b.value),isNaN(E)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?t(v,y,E):(this.updateManager.updateProperty(v,y,E),(w=(x=this.options)==null?void 0:x.onPropertyChange)==null||w.call(x,v,y,E))}},h=g.dataset.propertyPath;h==="logic.id"||h!=null&&h.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",h),g.addEventListener("change",async f=>{var M;let b=f.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 w=window,E=(M=w==null?void 0:w.__HANDLER_LOGIC_META)==null?void 0:M[x],C=this.getDefaultPropsForLogic(x,E);console.log("[Inspector v1.0.0] New logic default props:",C);let A=y.replace(".id",".props");await this.updateManager.updateProperty(v,A,C),console.log("[Inspector v1.0.0] Logic props updated to:",C),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(g.addEventListener("change",m),(g.tagName==="INPUT"||g.tagName==="TEXTAREA")&&g.addEventListener("input",m))}),this.contentContainer.querySelectorAll("[data-action]").forEach(g=>{g.addEventListener("click",m=>{let h=m.target,f=h.dataset.action,b=h.dataset.path,y=h.dataset.object;f&&b&&y&&this.quickActions.handleAction(f,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(g=>{g.addEventListener("click",m=>{var b,y;let h=m.target,f=h.dataset.sectionToggle||((b=h.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(f){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${f}"]`);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 o=(p=this.root)==null?void 0:p.querySelector("[data-convert-toggle]");o==null||o.addEventListener("click",()=>{var m;let g=(m=this.root)==null?void 0:m.querySelector("[data-convert-menu]");g==null||g.classList.toggle("hidden")});let s=(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]");s==null||s.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 i=window.getEditableObjectConfig,a=i==null?void 0:i(e);if(!a){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};a[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}let r=window.__editableConfig,o=r==null?void 0:r.schemas,s=null;o instanceof Map?s=o.get(t):o&&typeof o=="object"&&(s=o[t]),s||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(s==null?void 0:s.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,i){var r,o;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((o=(r=i.render)==null?void 0:r.asset)==null?void 0:o.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=`
700
+ `}attachEventListeners(){var c,p,d,u;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Hs((g,m,h)=>{var f,b;this.updateManager.updateProperty(g,m,h),(b=(f=this.options)==null?void 0:f.onPropertyChange)==null||b.call(f,g,m,h)},300);e.forEach(g=>{let m=f=>{var x,w;let b=f.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let E=b.value;if(b.type==="checkbox")E=b.checked;else if(b.type==="number"&&(E=parseFloat(b.value),isNaN(E)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?t(v,y,E):(this.updateManager.updateProperty(v,y,E),(w=(x=this.options)==null?void 0:x.onPropertyChange)==null||w.call(x,v,y,E))}},h=g.dataset.propertyPath;h==="logic.id"||h!=null&&h.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",h),g.addEventListener("change",async f=>{var P;let b=f.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 w=window,E=(P=w==null?void 0:w.__HANDLER_LOGIC_META)==null?void 0:P[x],C=this.getDefaultPropsForLogic(x,E);console.log("[Inspector v1.0.0] New logic default props:",C);let S=y.replace(".id",".props");await this.updateManager.updateProperty(v,S,C),console.log("[Inspector v1.0.0] Logic props updated to:",C),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(g.addEventListener("change",m),(g.tagName==="INPUT"||g.tagName==="TEXTAREA")&&g.addEventListener("input",m))}),this.contentContainer.querySelectorAll("[data-action]").forEach(g=>{g.addEventListener("click",m=>{let h=m.target,f=h.dataset.action,b=h.dataset.path,y=h.dataset.object;f&&b&&y&&this.quickActions.handleAction(f,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(g=>{g.addEventListener("click",m=>{var b,y;let h=m.target,f=h.dataset.sectionToggle||((b=h.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(f){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${f}"]`);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 o=(p=this.root)==null?void 0:p.querySelector("[data-convert-toggle]");o==null||o.addEventListener("click",()=>{var m;let g=(m=this.root)==null?void 0:m.querySelector("[data-convert-menu]");g==null||g.classList.toggle("hidden")});let s=(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]");s==null||s.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 i=window.getEditableObjectConfig,n=i==null?void 0:i(e);if(!n){console.error("[InspectorPanel] Failed to get config for:",e);return}if(t==="logic"){let c={id:"SwerveMove",props:this.getDefaultPropsForLogic("SwerveMove",null)};n[t]=c,await this.updateManager.updateProperty(e,t,c),this.loadObject(e),console.log("[InspectorPanel] Logic component added with default SwerveMove");return}let r=window.__editableConfig,o=r==null?void 0:r.schemas,s=null;o instanceof Map?s=o.get(t):o&&typeof o=="object"&&(s=o[t]),s||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(s==null?void 0:s.defaults)||{enabled:!0};n[t]={...l},await this.updateManager.updateProperty(e,t,n[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,i){var r,o;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((o=(r=i.render)==null?void 0:r.asset)==null?void 0:o.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let n=Object.keys(t);return n.length===0||n.length===1&&n[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
435
701
  <div class="inspector-empty">
436
702
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
437
703
  <span class="inspector-empty-text">${e}</span>
@@ -441,9 +707,9 @@
441
707
  <span class="inspector-empty-icon">\u{1F3AF}</span>
442
708
  <span class="inspector-empty-text">Select an object to inspect</span>
443
709
  </div>
444
- `)}};var zr=qe(require("jszip"),1);function On(n){return new Promise((e,t)=>{let i=new FileReader;i.onerror=()=>t(new Error("FileReader failed")),i.onload=()=>e(String(i.result||"")),i.readAsDataURL(n)})}function Cr(n){var a;let[e,t]=n.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=i==null?void 0:i[1])!=null?a:"image/png"}}async function Lr(n){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=n})}async function ki(n){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",n);let i=await fetch(n);if(!i.ok)return console.warn("[ImageUtils] Fetch failed with status:",i.status,n),null;let a=await i.blob();console.log("[ImageUtils] Blob received, size:",a.size,"type:",a.type);let r=await On(a),o=await Lr(r),s=Cr(r);return console.log("[ImageUtils] Success resolution:",o==null?void 0:o.width,"x",o==null?void 0:o.height,"mime:",s.mimeType),{base64:s.base64,mimeType:s.mimeType,dataUrl:r,width:(e=o==null?void 0:o.width)!=null?e:0,height:(t=o==null?void 0:o.height)!=null?t:0}}catch(i){return console.error("[ImageUtils] Error fetching image data:",i),null}}async function Te(n){var e,t;try{let i=await On(n),a=await Lr(i),r=Cr(i);return{base64:r.base64,mimeType:r.mimeType,dataUrl:i,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 In(n){return On(n).then(e=>e).catch(()=>null)}function jn(n,e){var t;try{let[i,a]=n.split(","),r=i.match(/data:(.*?);base64/),o=(t=r==null?void 0:r[1])!=null?t:"image/png",s=atob(a),l=new Uint8Array(s.length);for(let c=0;c<s.length;c++)l[c]=s.charCodeAt(c);return new File([l],e,{type:o})}catch{return null}}async function Qe(n,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=n}),i=document.createElement("canvas");i.width=t.width,i.height=t.height;let a=i.getContext("2d");if(!a)return console.error("[ImageUtils] Failed to get canvas context"),n;a.drawImage(t,0,0);let r=a.getImageData(0,0,i.width,i.height),o=r.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(i.width-1)*4},{name:"bottom-left",offset:(i.height-1)*i.width*4},{name:"bottom-right",offset:((i.height-1)*i.width+(i.width-1))*4}].map(d=>({r:o[d.offset],g:o[d.offset+1],b:o[d.offset+2]})),c=0;for(let d=0;d<o.length;d+=4){let u=o[d],g=o[d+1],m=o[d+2],h=!1;for(let f of l)if(Math.sqrt(Math.pow(u-f.r,2)+Math.pow(g-f.g,2)+Math.pow(m-f.b,2))<e){h=!0;break}h&&(o[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),a.putImageData(r,0,0),i.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),n}}function Tr(n,e){if(!n||!e)return"1:1";let t=n/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function ye(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function W(n){return typeof n=="string"?n:void 0}function kr(n){return n.toLowerCase().endsWith(".png")?n.slice(0,-4):n}function js(n){var i,a,r;let e=(i=W(n.id))!=null?i:W(n.name);if(e)return e;let t=(a=W(n.file))!=null?a:W(n.asset);return t?kr((r=t.split("/").pop())!=null?r:t):void 0}function Rs(n,e,t){var i,a,r;if(typeof e=="string")return{id:n,file:e,role:t};if(ye(e)){let o=(i=W(e.file))!=null?i:W(e.asset);return o?{id:(a=W(e.id))!=null?a:n,file:o,role:(r=W(e.role))!=null?r:t,dataUrl:W(e.dataUrl),layout:e.layout}:null}return null}function Rn(n,e){var t,i,a;if(!n)return[];if(Array.isArray(n)){let r=[];for(let o of n){if(typeof o=="string"){let s=kr((t=o.split("/").pop())!=null?t:o);r.push({id:s,file:o,role:e});continue}if(ye(o)){let s=js(o),l=(i=W(o.file))!=null?i:W(o.asset);if(!s||!l)continue;r.push({id:s,file:l,role:(a=W(o.role))!=null?a:e,dataUrl:W(o.dataUrl),layout:o.layout})}}return r}if(ye(n)){let r=[];for(let[o,s]of Object.entries(n)){let l=Rs(o,s,e);l&&r.push(l)}return r}return[]}function Ds(n){var e,t;return(t=(e=W(n.brand_name))!=null?e:W(n.brandName))!=null?t:W(n.name)}function $s(n){if(ye(n.brand_dna)&&ye(n.brand_dna.colors))return n.brand_dna;if(ye(n.colors)){let e={colors:n.colors};return typeof n.style=="string"&&(e.style=n.style),ye(n.fonts)&&(e.fonts=n.fonts),e}}function zs(n){var t;let e=new Map;for(let i of n){let a=e.get(i.id);if(!a){e.set(i.id,i);continue}e.set(i.id,{...a,...i,file:i.file||a.file,role:i.role||a.role,dataUrl:i.dataUrl||a.dataUrl,layout:(t=i.layout)!=null?t:a.layout})}return Array.from(e.values())}function Dn(n,e={}){var o,s,l;let t=n.filter(ye),i=(s=(o=t.map(Ds).find(Boolean))!=null?o:e.defaultBrandName)!=null?s:"Imported Brand",a=(l=t.map($s).find(Boolean))!=null?l:{colors:{}},r=[];for(let c of t)"layers"in c&&r.push(...Rn(c.layers,"visual element")),"assets"in c&&r.push(...Rn(c.assets,"visual element")),ye(c.endgame)&&"assets"in c.endgame&&r.push(...Rn(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:i,brand_dna:a,assets:zs(r)}}var _r=require("@google/genai");async function _i(n,e,t=[],i={}){var a,r,o,s,l,c,p;try{if(!(n!=null&&n.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 _r.GoogleGenAI({apiKey:n}),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 m=await d.models.generateContent({model:u,contents:g}),h="",f=(o=(r=(a=m.candidates)==null?void 0:a[0])==null?void 0:r.content)==null?void 0:o.parts;if(f)for(let b of f)b.text&&(h+=b.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(d){throw console.error("[Gemini] API error:",d),(s=d.message)!=null&&s.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 Pr=require("@google/genai");async function et(n,e,t=[],i={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let a=new Pr.GoogleGenAI({apiKey:n}),r=[{text:e}];t.length>0&&t.forEach((s,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),r.push({inlineData:{mimeType:s.mimeType,data:s.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let o=await a.models.generateContent({model:"gemini-2.5-flash-image",contents:r});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!o.candidates||!o.candidates[0]||!o.candidates[0].content||!o.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let s of o.candidates[0].content.parts)if(s.text)console.log(s.text);else if(s.inlineData){let l=s.inlineData.data,c=s.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 Mr(n){let e=n.brandAssets.map(r=>{let o=`- ${r.id}: ${r.role}`;return r.layout&&(o+=` [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}]`),o}).join(`
445
- `)||"None",t=n.brandDna?`Colors: ${JSON.stringify(n.brandDna.colors)}, Style: ${n.brandDna.style||"not specified"}`:"Not provided",i=n.gameObjects.map(r=>typeof r=="string"?`- id: ${r}`:`- id: ${r.id}${r.category?`, category: ${r.category}`:""}${r.type?`, type: ${r.type}`:""}`).join(`
446
- `),a="";if(n.brandConfig){let r=n.brandConfig,o=[];r.splash&&o.push(`SPLASH: title="${r.splash.title||""}", subtitle="${r.splash.subtitle||""}", button="${r.splash.button_label||""}"`),r.endgame&&o.push(`ENDGAME: title="${r.endgame.title||""}", subtitle="${r.endgame.subtitle||""}", cta="${r.endgame.cta_label||""}"`),r.tutorial&&o.push(`TUTORIAL: text="${r.tutorial.label_text||""}", helper="${r.tutorial.helper_text||""}"`),o.length>0&&(a=`
710
+ `)}};var Fr=qe(require("jszip"),1);function jn(a){return new Promise((e,t)=>{let i=new FileReader;i.onerror=()=>t(new Error("FileReader failed")),i.onload=()=>e(String(i.result||"")),i.readAsDataURL(a)})}function kr(a){var n;let[e,t]=a.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(n=i==null?void 0:i[1])!=null?n:"image/png"}}async function _r(a){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=a})}async function Mi(a){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",a);let i=await fetch(a);if(!i.ok)return console.warn("[ImageUtils] Fetch failed with status:",i.status,a),null;let n=await i.blob();console.log("[ImageUtils] Blob received, size:",n.size,"type:",n.type);let r=await jn(n),o=await _r(r),s=kr(r);return console.log("[ImageUtils] Success resolution:",o==null?void 0:o.width,"x",o==null?void 0:o.height,"mime:",s.mimeType),{base64:s.base64,mimeType:s.mimeType,dataUrl:r,width:(e=o==null?void 0:o.width)!=null?e:0,height:(t=o==null?void 0:o.height)!=null?t:0}}catch(i){return console.error("[ImageUtils] Error fetching image data:",i),null}}async function Le(a){var e,t;try{let i=await jn(a),n=await _r(i),r=kr(i);return{base64:r.base64,mimeType:r.mimeType,dataUrl:i,width:(e=n==null?void 0:n.width)!=null?e:0,height:(t=n==null?void 0:n.height)!=null?t:0}}catch{return null}}function Rn(a){return jn(a).then(e=>e).catch(()=>null)}function zn(a,e){var t;try{let[i,n]=a.split(","),r=i.match(/data:(.*?);base64/),o=(t=r==null?void 0:r[1])!=null?t:"image/png",s=atob(n),l=new Uint8Array(s.length);for(let c=0;c<s.length;c++)l[c]=s.charCodeAt(c);return new File([l],e,{type:o})}catch{return null}}async function Qe(a,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=a}),i=document.createElement("canvas");i.width=t.width,i.height=t.height;let n=i.getContext("2d");if(!n)return console.error("[ImageUtils] Failed to get canvas context"),a;n.drawImage(t,0,0);let r=n.getImageData(0,0,i.width,i.height),o=r.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(i.width-1)*4},{name:"bottom-left",offset:(i.height-1)*i.width*4},{name:"bottom-right",offset:((i.height-1)*i.width+(i.width-1))*4}].map(d=>({r:o[d.offset],g:o[d.offset+1],b:o[d.offset+2]})),c=0;for(let d=0;d<o.length;d+=4){let u=o[d],g=o[d+1],m=o[d+2],h=!1;for(let f of l)if(Math.sqrt(Math.pow(u-f.r,2)+Math.pow(g-f.g,2)+Math.pow(m-f.b,2))<e){h=!0;break}h&&(o[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),n.putImageData(r,0,0),i.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),a}}function Mr(a,e){if(!a||!e)return"1:1";let t=a/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function ye(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function W(a){return typeof a=="string"?a:void 0}function Pr(a){return a.toLowerCase().endsWith(".png")?a.slice(0,-4):a}function Ns(a){var i,n,r;let e=(i=W(a.id))!=null?i:W(a.name);if(e)return e;let t=(n=W(a.file))!=null?n:W(a.asset);return t?Pr((r=t.split("/").pop())!=null?r:t):void 0}function Fs(a,e,t){var i,n,r;if(typeof e=="string")return{id:a,file:e,role:t};if(ye(e)){let o=(i=W(e.file))!=null?i:W(e.asset);return o?{id:(n=W(e.id))!=null?n:a,file:o,role:(r=W(e.role))!=null?r:t,dataUrl:W(e.dataUrl),layout:e.layout}:null}return null}function Dn(a,e){var t,i,n;if(!a)return[];if(Array.isArray(a)){let r=[];for(let o of a){if(typeof o=="string"){let s=Pr((t=o.split("/").pop())!=null?t:o);r.push({id:s,file:o,role:e});continue}if(ye(o)){let s=Ns(o),l=(i=W(o.file))!=null?i:W(o.asset);if(!s||!l)continue;r.push({id:s,file:l,role:(n=W(o.role))!=null?n:e,dataUrl:W(o.dataUrl),layout:o.layout})}}return r}if(ye(a)){let r=[];for(let[o,s]of Object.entries(a)){let l=Fs(o,s,e);l&&r.push(l)}return r}return[]}function Bs(a){var e,t;return(t=(e=W(a.brand_name))!=null?e:W(a.brandName))!=null?t:W(a.name)}function Us(a){if(ye(a.brand_dna)&&ye(a.brand_dna.colors))return a.brand_dna;if(ye(a.colors)){let e={colors:a.colors};return typeof a.style=="string"&&(e.style=a.style),ye(a.fonts)&&(e.fonts=a.fonts),e}}function Gs(a){var t;let e=new Map;for(let i of a){let n=e.get(i.id);if(!n){e.set(i.id,i);continue}e.set(i.id,{...n,...i,file:i.file||n.file,role:i.role||n.role,dataUrl:i.dataUrl||n.dataUrl,layout:(t=i.layout)!=null?t:n.layout})}return Array.from(e.values())}function $n(a,e={}){var o,s,l;let t=a.filter(ye),i=(s=(o=t.map(Bs).find(Boolean))!=null?o:e.defaultBrandName)!=null?s:"Imported Brand",n=(l=t.map(Us).find(Boolean))!=null?l:{colors:{}},r=[];for(let c of t)"layers"in c&&r.push(...Dn(c.layers,"visual element")),"assets"in c&&r.push(...Dn(c.assets,"visual element")),ye(c.endgame)&&"assets"in c.endgame&&r.push(...Dn(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:i,brand_dna:n,assets:Gs(r)}}var Or=require("@google/genai");async function Pi(a,e,t=[],i={}){var n,r,o,s,l,c,p;try{if(!(a!=null&&a.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 Or.GoogleGenAI({apiKey:a}),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 m=await d.models.generateContent({model:u,contents:g}),h="",f=(o=(r=(n=m.candidates)==null?void 0:n[0])==null?void 0:r.content)==null?void 0:o.parts;if(f)for(let b of f)b.text&&(h+=b.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(d){throw console.error("[Gemini] API error:",d),(s=d.message)!=null&&s.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 Ir=require("@google/genai");async function et(a,e,t=[],i={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let n=new Ir.GoogleGenAI({apiKey:a}),r=[{text:e}];t.length>0&&t.forEach((s,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),r.push({inlineData:{mimeType:s.mimeType,data:s.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let o=await n.models.generateContent({model:"gemini-2.5-flash-image",contents:r});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!o.candidates||!o.candidates[0]||!o.candidates[0].content||!o.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let s of o.candidates[0].content.parts)if(s.text)console.log(s.text);else if(s.inlineData){let l=s.inlineData.data,c=s.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(n){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(n,Object.getOwnPropertyNames(n),2)),n}}function jr(a){let e=a.brandAssets.map(r=>{let o=`- ${r.id}: ${r.role}`;return r.layout&&(o+=` [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}]`),o}).join(`
711
+ `)||"None",t=a.brandDna?`Colors: ${JSON.stringify(a.brandDna.colors)}, Style: ${a.brandDna.style||"not specified"}`:"Not provided",i=a.gameObjects.map(r=>typeof r=="string"?`- id: ${r}`:`- id: ${r.id}${r.category?`, category: ${r.category}`:""}${r.type?`, type: ${r.type}`:""}`).join(`
712
+ `),n="";if(a.brandConfig){let r=a.brandConfig,o=[];r.splash&&o.push(`SPLASH: title="${r.splash.title||""}", subtitle="${r.splash.subtitle||""}", button="${r.splash.button_label||""}"`),r.endgame&&o.push(`ENDGAME: title="${r.endgame.title||""}", subtitle="${r.endgame.subtitle||""}", cta="${r.endgame.cta_label||""}"`),r.tutorial&&o.push(`TUTORIAL: text="${r.tutorial.label_text||""}", helper="${r.tutorial.helper_text||""}"`),o.length>0&&(n=`
447
713
  BRAND CONTENT:
448
714
  ${o.join(`
449
715
  `)}
@@ -451,7 +717,7 @@ ${o.join(`
451
717
  You are analyzing a brand's visual design for use in a playable ad game.
452
718
 
453
719
  GAME CONTEXT:
454
- ${n.gamePrompt||"Simple game"}
720
+ ${a.gamePrompt||"Simple game"}
455
721
 
456
722
  GAME OBJECTS (need assets):
457
723
  ${i}
@@ -461,7 +727,7 @@ ${e}
461
727
 
462
728
  BRAND DNA:
463
729
  ${t}
464
- ${a}
730
+ ${n}
465
731
  VISUAL REFERENCE: [See attached flat design image]
466
732
 
467
733
  TASK:
@@ -505,28 +771,28 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
505
771
  }
506
772
  ]
507
773
  }
508
- `.trim()}function Or(n){var a,r;let e=(a=n.brandDna)!=null&&a.colors?`Primary: ${n.brandDna.colors.primary}, Secondary: ${n.brandDna.colors.secondary||"N/A"}, Accent: ${n.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((r=n.brandDna)==null?void 0:r.style)||"modern gaming style",i=n.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
509
- TASK: ${n.prompt}
774
+ `.trim()}function Rr(a){var n,r;let e=(n=a.brandDna)!=null&&n.colors?`Primary: ${a.brandDna.colors.primary}, Secondary: ${a.brandDna.colors.secondary||"N/A"}, Accent: ${a.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((r=a.brandDna)==null?void 0:r.style)||"modern gaming style",i=a.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
775
+ TASK: ${a.prompt}
510
776
 
511
777
  BRAND STYLE:
512
778
  - Colors: ${e}
513
779
  - Style: ${t}
514
780
 
515
781
  CHANGE_STRENGTH: 8/10
516
- REFERENCE: ${n.hasReference?"provided (use as style guide for colors and aesthetics)":"none"}
782
+ REFERENCE: ${a.hasReference?"provided (use as style guide for colors and aesthetics)":"none"}
517
783
  ${i}
518
784
 
519
785
  OUTPUT CONSTRAINTS (MUST FOLLOW):
520
786
  - Do NOT add extra text unless specifically requested
521
- - Preserve aspect ratio${n.aspectRatio?` (target: ${n.aspectRatio})`:""}
787
+ - Preserve aspect ratio${a.aspectRatio?` (target: ${a.aspectRatio})`:""}
522
788
  - Keep padding under 5% of asset size
523
789
  - No drop shadows unless explicitly requested
524
- - No gradients on the background (solid ${n.needsTransparency?"magenta":"colors"} only)
790
+ - No gradients on the background (solid ${a.needsTransparency?"magenta":"colors"} only)
525
791
  - Center the subject in frame
526
792
 
527
793
  OUTPUT:
528
- Generate the requested asset matching the brand style.${n.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
529
- `.trim()}function Ir(n){return n.map(e=>{if(typeof e=="string"){let t=e,i,a;return t.includes("background")?(i="background",a="background"):t.includes("button")||t.includes("cta")?(i="ui",a="button"):t.includes("logo")?(i="ui",a="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(i="text",a="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(i="effects",a="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(i="ui",a="image"):(i="environment",a="interactive"),{id:t,category:i,type:a}}return e})}function jr(n,e){return!(n.includes("background")&&(n.includes("_1")||n.includes("splash")||n.includes("endgame")||n.includes("main"))||e==="text"||e==="effects"&&n.includes("particle"))}async function Rr(n){var o,s;let e=Ir(n.gameObjects),t={gamePrompt:n.gamePrompt,gameObjects:e,brandAssets:n.manifest.assets,brandDna:n.manifest.brand_dna,brandName:n.manifest.brand_name},i=Mr(t),a=[];if(n.flatDesignDataUrl)try{let l=Dr(n.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 _i(n.apiKey,i,a,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(o=l.message)!=null&&o.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."):(s=l.message)!=null&&s.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return Ns(r,n.gameObjects)}function Ns(n,e){try{let t=n,i=n.match(/```(?:json)?\s*([\s\S]*?)```/);if(i)t=i[1].trim();else{let r=n.match(/\{[\s\S]*\}/);r&&(t=r[0])}let a=JSON.parse(t);return a.mappings&&Array.isArray(a.mappings)?{mappingResult:a,rawResponse:n,parsed:!0}:{mappingResult:{mappings:e.map(r=>({game_object:r,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:n,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(i=>({game_object:i,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:n,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function $n(n,e,t={}){var a;let i=e.mappings.filter(r=>r.action==="GENERATE");if(i.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${i.length} assets...`);for(let r=0;r<i.length;r++){let o=i[r];(a=t.onProgress)==null||a.call(t,r+1,i.length,o.game_object);try{let s=await Hs(n,o);o.output_dataUrl=s,o.status="Generated \u2713"}catch(s){console.error(`[Pipeline] Failed to generate ${o.game_object}:`,s),o.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function Hs(n,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&n.manifest){let s=n.manifest.assets.find(l=>l.id===e.reference_asset);if(s){let l=n.assetFiles.get(s.file);if(l){let c=await Te(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(n.flatDesignDataUrl){let s=Dr(n.flatDesignDataUrl);s&&t.push(s)}let i=jr(e.game_object),a={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:n.manifest.brand_dna,needsTransparency:i},r=Or(a);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${i})`);let o=await et(n.apiKey,r,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return i&&await Qe(o)||o}function Dr(n){let[e,t]=n.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return t&&i?{base64:t,mimeType:i[1]}:null}async function $r(n,e){let t=n.assets,i=[];Array.isArray(t)?i=t:t&&typeof t=="object"?i=Object.entries(t).map(([a,r])=>({id:a,file:String(r),role:"visual element"})):i=[],n.assets=i;for(let a of i){let r=e.get(a.file);if(r){let o=await Te(r);o&&(a.dataUrl=o.dataUrl)}}}var Pi=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`
794
+ Generate the requested asset matching the brand style.${a.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
795
+ `.trim()}function zr(a){return a.map(e=>{if(typeof e=="string"){let t=e,i,n;return t.includes("background")?(i="background",n="background"):t.includes("button")||t.includes("cta")?(i="ui",n="button"):t.includes("logo")?(i="ui",n="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(i="text",n="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(i="effects",n="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(i="ui",n="image"):(i="environment",n="interactive"),{id:t,category:i,type:n}}return e})}function Dr(a,e){return!(a.includes("background")&&(a.includes("_1")||a.includes("splash")||a.includes("endgame")||a.includes("main"))||e==="text"||e==="effects"&&a.includes("particle"))}async function $r(a){var o,s;let e=zr(a.gameObjects),t={gamePrompt:a.gamePrompt,gameObjects:e,brandAssets:a.manifest.assets,brandDna:a.manifest.brand_dna,brandName:a.manifest.brand_name},i=jr(t),n=[];if(a.flatDesignDataUrl)try{let l=Hr(a.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(n.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",n.length,"images...");let r;try{r=await Pi(a.apiKey,i,n,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(o=l.message)!=null&&o.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."):(s=l.message)!=null&&s.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return qs(r,a.gameObjects)}function qs(a,e){try{let t=a,i=a.match(/```(?:json)?\s*([\s\S]*?)```/);if(i)t=i[1].trim();else{let r=a.match(/\{[\s\S]*\}/);r&&(t=r[0])}let n=JSON.parse(t);return n.mappings&&Array.isArray(n.mappings)?{mappingResult:n,rawResponse:a,parsed:!0}:{mappingResult:{mappings:e.map(r=>({game_object:r,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:a,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(i=>({game_object:i,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:a,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function Hn(a,e,t={}){var n;let i=e.mappings.filter(r=>r.action==="GENERATE");if(i.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${i.length} assets...`);for(let r=0;r<i.length;r++){let o=i[r];(n=t.onProgress)==null||n.call(t,r+1,i.length,o.game_object);try{let s=await Vs(a,o);o.output_dataUrl=s,o.status="Generated \u2713"}catch(s){console.error(`[Pipeline] Failed to generate ${o.game_object}:`,s),o.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function Vs(a,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&a.manifest){let s=a.manifest.assets.find(l=>l.id===e.reference_asset);if(s){let l=a.assetFiles.get(s.file);if(l){let c=await Le(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(a.flatDesignDataUrl){let s=Hr(a.flatDesignDataUrl);s&&t.push(s)}let i=Dr(e.game_object),n={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:a.manifest.brand_dna,needsTransparency:i},r=Rr(n);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${i})`);let o=await et(a.apiKey,r,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return i&&await Qe(o)||o}function Hr(a){let[e,t]=a.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return t&&i?{base64:t,mimeType:i[1]}:null}async function Nr(a,e){let t=a.assets,i=[];Array.isArray(t)?i=t:t&&typeof t=="object"?i=Object.entries(t).map(([n,r])=>({id:n,file:String(r),role:"visual element"})):i=[],a.assets=i;for(let n of i){let r=e.get(n.file);if(r){let o=await Le(r);o&&(n.dataUrl=o.dataUrl)}}}var Oi=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`
530
796
  <div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
531
797
  <div class="scene-panel-header" data-panel-handle>
532
798
  <div class="panel-title">
@@ -642,15 +908,15 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
642
908
  </div>
643
909
  <div class="panel-resize-handle" data-panel-resize></div>
644
910
  </div>
645
- `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,i,a,r,o,s,l,c,p,d,u,g,m;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.visionTab;this.switchTab(f)})}),(i=this.root.querySelector("[data-vision-upload-method]"))==null||i.addEventListener("change",h=>{let f=h.target.value;this.switchUploadMethod(f)}),(a=this.root.querySelector("[data-vision-upload-manifest]"))==null||a.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||f.click()}),(r=this.root.querySelector("[data-vision-upload-zip]"))==null||r.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||f.click()}),(o=this.root.querySelector("[data-vision-zip-input]"))==null||o.addEventListener("change",h=>{this.handleZipUpload(h)}),(s=this.root.querySelector("[data-vision-manifest-input]"))==null||s.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||f.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||f.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(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()}),(m=this.root.querySelector("[data-vision-apply-all]"))==null||m.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let f=h.target;if(!f)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(f.closest("[data-mapping-apply-one]")&&this.applyOne(y),f.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),f.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),f.closest("[data-mapping-generate-one]")&&this.generateOne(y),f.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let f=h.target;if(!f||!this.mappingResult)return;let b=f.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&&(f.matches("[data-mapping-action]")&&(v.action=String(f.value||"KEEP"),v.status="Edited",this.renderMappings()),f.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(f.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",h=>{let f=h.target;if(!f||!this.mappingResult||!f.matches("[data-mapping-prompt]"))return;let b=f.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(f.value||""),v.status="Edited")})}switchTab(e){var t,i;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"),(i=this.root.querySelector(`[data-vision-content="${e}"]`))==null||i.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(i=>{i.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var a;let i=(a=e.target.files)==null?void 0:a[0];if(i){this.zipFile=i,this.setStatus("zip",`Selected: ${i.name} (${(i.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(i)}catch(r){console.error("[BrandVision] ZIP processing failed:",r),this.setStatus("zip",`Error: ${r instanceof Error?r.message:"Unknown error"}`)}}}async processZipFile(e){var o,s;let t=await zr.loadAsync(e),i=[],a=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?i.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:l,file:c})});for(let l of i)try{let c=await((o=t.file(l.name))==null?void 0:o.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(f){console.warn(`FileReader failed for ${d}, using fallback:`,f),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 h=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}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${h.path}`);let f=new File([p],d,{type:"image/png"});r.set(d,f)}else console.warn(`\u274C Failed to save ${d}:`,h.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),i.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=r;try{this.normalizedManifest=Dn(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: ${i.length} JSONs, ${c} PNGs
646
- \u{1F3F7}\uFE0F Brand: ${((s=this.normalizedManifest)==null?void 0:s.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,i)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=i,a.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,i)=>{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),i(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 i=t();if(!(i!=null&&i.libraryAssets))return;let a={};for(let r of e){let o=r.category||"misc";a[o]||(a[o]=[]),i.libraryAssets[o]||(i.libraryAssets[o]=[]),i.libraryAssets[o].some(l=>l.filename===r.filename)||(i.libraryAssets[o].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 ${o}`))}}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,i=t.files;if(!i||i.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let a="";for(let o of Array.from(i))try{let s=await o.text(),l=JSON.parse(s);this.uploadedJsons.set(o.name,l),l.layers?a+=`\u2705 Layers: ${o.name}
647
- `:l.brand_dna||l.colors?a+=`\u2705 Brand: ${o.name}
648
- `:a+=`\u2705 Loaded: ${o.name}
649
- `}catch{a+=`\u274C Error in ${o.name}
650
- `}try{this.normalizedManifest=Dn(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let o=Array.isArray((r=this.normalizedManifest)==null?void 0:r.assets)?this.normalizedManifest.assets.length:0;a+=`
651
- \u{1F4E6} Normalized manifest: ${o} assets`,a+=`
652
- \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:o,brandName:this.normalizedManifest.brand_name})}catch(o){console.error("[BrandVision] Failed to normalize manifest:",o),this.normalizedManifest=null,a+=`
653
- \u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",a.trim())}async handleAssetsUpload(e){let i=e.target.files;if(!(!i||i.length===0)){for(let a of Array.from(i))this.assetFiles.set(a.name,a);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var r,o;let i=(r=e.target.files)==null?void 0:r[0];if(!i)return;let a=await Te(i);if(a){this.flatDesignDataUrl=a.dataUrl,this.setStatus("flat",i.name);let s=(o=this.root)==null?void 0:o.querySelector("[data-vision-flat-preview]");s&&(s.innerHTML=`<img src="${a.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var i,a,r,o,s,l,c;if(this.isAnalyzing)return;let e=(r=(a=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:r.trim();if(!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 $r(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await Rr(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(o=d.parseError)!=null?o:null,this.renderMappings(),d.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(s=this.mappingResult)==null?void 0:s.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,i,a;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(a=(i=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:i.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 $n(r,this.mappingResult,{onProgress:(o,s,l)=>{this.setStatus("apply",`Generating ${o}/${s}: ${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 s;let e=(s=this.root)==null?void 0:s.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,i=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(""),o=a?`
911
+ `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,i,n,r,o,s,l,c,p,d,u,g,m;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.visionTab;this.switchTab(f)})}),(i=this.root.querySelector("[data-vision-upload-method]"))==null||i.addEventListener("change",h=>{let f=h.target.value;this.switchUploadMethod(f)}),(n=this.root.querySelector("[data-vision-upload-manifest]"))==null||n.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||f.click()}),(r=this.root.querySelector("[data-vision-upload-zip]"))==null||r.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||f.click()}),(o=this.root.querySelector("[data-vision-zip-input]"))==null||o.addEventListener("change",h=>{this.handleZipUpload(h)}),(s=this.root.querySelector("[data-vision-manifest-input]"))==null||s.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||f.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var h,f;(f=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||f.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(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()}),(m=this.root.querySelector("[data-vision-apply-all]"))==null||m.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",h=>{let f=h.target;if(!f)return;let b=f.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(f.closest("[data-mapping-apply-one]")&&this.applyOne(y),f.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),f.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),f.closest("[data-mapping-generate-one]")&&this.generateOne(y),f.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",h=>{let f=h.target;if(!f||!this.mappingResult)return;let b=f.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&&(f.matches("[data-mapping-action]")&&(v.action=String(f.value||"KEEP"),v.status="Edited",this.renderMappings()),f.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(f.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",h=>{let f=h.target;if(!f||!this.mappingResult||!f.matches("[data-mapping-prompt]"))return;let b=f.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(f.value||""),v.status="Edited")})}switchTab(e){var t,i;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(n=>n.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(n=>n.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(i=this.root.querySelector(`[data-vision-content="${e}"]`))==null||i.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(i=>{i.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var n;let i=(n=e.target.files)==null?void 0:n[0];if(i){this.zipFile=i,this.setStatus("zip",`Selected: ${i.name} (${(i.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(i)}catch(r){console.error("[BrandVision] ZIP processing failed:",r),this.setStatus("zip",`Error: ${r instanceof Error?r.message:"Unknown error"}`)}}}async processZipFile(e){var o,s;let t=await Fr.loadAsync(e),i=[],n=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?i.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&n.push({name:l,file:c})});for(let l of i)try{let c=await((o=t.file(l.name))==null?void 0:o.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 n)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(f){console.warn(`FileReader failed for ${d}, using fallback:`,f),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 h=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}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${h.path}`);let f=new File([p],d,{type:"image/png"});r.set(d,f)}else console.warn(`\u274C Failed to save ${d}:`,h.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),i.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=r;try{this.normalizedManifest=$n(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: ${i.length} JSONs, ${c} PNGs
912
+ \u{1F3F7}\uFE0F Brand: ${((s=this.normalizedManifest)==null?void 0:s.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,i)=>{let n=new FileReader;n.onload=()=>t(n.result),n.onerror=i,n.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,i)=>{let n=new FileReader;n.onload=()=>{let r=n.result;console.log("FileReader result type:",typeof r,"length:",r.length),console.log("Data URL prefix:",r.substring(0,30)),t(r)},n.onerror=r=>{console.error("FileReader error:",r),i(r)},n.readAsDataURL(e)})}inferAssetCategory(e){let t=e.toLowerCase();return t.includes("background")||t.includes("bg")?"backgrounds":t.includes("ui")||t.includes("button")||t.includes("cta")||t.includes("logo")||t.includes("text")?"ui":t.includes("sparkle")||t.includes("effect")||t.includes("particle")?"effects":t.includes("bottle")||t.includes("product")||t.includes("item")?"products":"misc"}addAssetsToRegistry(e){let t=window.getEditableAssets;if(typeof t!="function")return;let i=t();if(!(i!=null&&i.libraryAssets))return;let n={};for(let r of e){let o=r.category||"misc";n[o]||(n[o]=[]),i.libraryAssets[o]||(i.libraryAssets[o]=[]),i.libraryAssets[o].some(l=>l.filename===r.filename)||(i.libraryAssets[o].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 ${o}`))}}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,i=t.files;if(!i||i.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let n="";for(let o of Array.from(i))try{let s=await o.text(),l=JSON.parse(s);this.uploadedJsons.set(o.name,l),l.layers?n+=`\u2705 Layers: ${o.name}
913
+ `:l.brand_dna||l.colors?n+=`\u2705 Brand: ${o.name}
914
+ `:n+=`\u2705 Loaded: ${o.name}
915
+ `}catch{n+=`\u274C Error in ${o.name}
916
+ `}try{this.normalizedManifest=$n(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let o=Array.isArray((r=this.normalizedManifest)==null?void 0:r.assets)?this.normalizedManifest.assets.length:0;n+=`
917
+ \u{1F4E6} Normalized manifest: ${o} assets`,n+=`
918
+ \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:o,brandName:this.normalizedManifest.brand_name})}catch(o){console.error("[BrandVision] Failed to normalize manifest:",o),this.normalizedManifest=null,n+=`
919
+ \u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",n.trim())}async handleAssetsUpload(e){let i=e.target.files;if(!(!i||i.length===0)){for(let n of Array.from(i))this.assetFiles.set(n.name,n);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var r,o;let i=(r=e.target.files)==null?void 0:r[0];if(!i)return;let n=await Le(i);if(n){this.flatDesignDataUrl=n.dataUrl,this.setStatus("flat",i.name);let s=(o=this.root)==null?void 0:o.querySelector("[data-vision-flat-preview]");s&&(s.innerHTML=`<img src="${n.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var i,n,r,o,s,l,c;if(this.isAnalyzing)return;let e=(r=(n=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:n.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 Nr(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await $r(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(o=d.parseError)!=null?o:null,this.renderMappings(),d.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(s=this.mappingResult)==null?void 0:s.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,i,n;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(n=(i=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:i.value)==null?void 0:n.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 Hn(r,this.mappingResult,{onProgress:(o,s,l)=>{this.setStatus("apply",`Generating ${o}/${s}: ${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 s;let e=(s=this.root)==null?void 0:s.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,i=this.getEngineAssets(),n=!!this.analysisRawResponse&&this.analysisParsedOk===!1,r=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),o=n?`
654
920
  <div class="vision-raw-block">
655
921
  <div class="inspector-text-sm" style="white-space: pre-wrap;">
656
922
  \u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
@@ -712,8 +978,8 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
712
978
  </div>
713
979
  </div>
714
980
  `}).join("")}
715
- `}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(i=>i.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 i=this.manifest.assets.find(a=>a.id===t.brand_asset);if(i!=null&&i.dataUrl)return{value:i.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let i of this.mappingResult.mappings){if(i.action==="KEEP"||i.action==="APPLY"&&!i.brand_asset||i.action==="GENERATE"&&!i.output_dataUrl)continue;let a=i.game_object,r=this.getPreviewValueForMapping(a);if(!r.value)continue;let o=e.saveToLibrary?await this.saveToLibraryAndReturnPath(a,r.value):r.value;o&&(await this.stageEngineAssetOverride(a,o),i.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 i=(a=this.mappingResult)==null?void 0:a.mappings.find(r=>r.game_object===e);i&&(i.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 i=await this.saveToLibraryAndReturnPath(e,t.value);if(!i){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,i);let a=(r=this.mappingResult)==null?void 0:r.mappings.find(o=>o.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(o=>o.game_object===e);if(!t)return;let i=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,i.value||void 0,{path:`assets.${e}`})}async generateOne(e){var a,r,o;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(s=>s.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let i=(o=(r=(a=this.root)==null?void 0:a.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:o.trim();if(!i||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let s={apiKey:i,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await $n(s,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(s){console.error("[BrandVision] generateOne failed:",s),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(K(),Xe));i({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 i=this.inferCategoryFromAssetKey(e),a=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let o=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:a,data:t,overwrite:!0})})).json();if(!(o!=null&&o.success)||!(o!=null&&o.path))return console.error("[BrandVision] Save to library failed:",(o==null?void 0:o.error)||o),null;let s=window.addAssetToRegistry;typeof s=="function"&&s(i,a);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(o.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 o=a.slots.find(s=>s.slotId===e||s.currentAsset===e);if(o!=null&&o.category)return String(o.category)}let r=a==null?void 0:a.categories;if(Array.isArray(r)&&r.length>0){let o=e.toLowerCase(),s=l=>r.find(c=>c.toLowerCase().includes(l));return o.includes("bg")||o.includes("background")?s("background")||r[0]:(o.includes("cta")||o.includes("button")||o.includes("ui")||o.includes("logo"))&&s("ui")||r[0]}}let i=e.toLowerCase();return i.includes("bg")||i.includes("background")?"backgrounds":i.includes("cta")||i.includes("button")||i.includes("ui")||i.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 i={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(i[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 i=t.clientX,a=this.root.getBoundingClientRect().width,r=s=>{let l=Math.max(300,a+(s.clientX-i));this.root.style.width=`${l}px`},o=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o)};window.addEventListener("pointermove",r),window.addEventListener("pointerup",o)})}refresh(){}};function Nr(n,e={}){let{includeReference:t=!1,includeMagenta:i=!0,changeLevel:a=5}=e;return[`TASK: ${n}`,`CHANGE_STRENGTH: ${a}/10`,t?"REFERENCE: provided":"REFERENCE: none",i?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
716
- `)}var Bs=["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"],Fs=["cta_hint","cta_label_end"],Hr=[{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"}],Us=["brand.primary","brand.heading","brand.body","brand.warning"],Mi=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
981
+ `}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(i=>i.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 i=this.manifest.assets.find(n=>n.id===t.brand_asset);if(i!=null&&i.dataUrl)return{value:i.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let i of this.mappingResult.mappings){if(i.action==="KEEP"||i.action==="APPLY"&&!i.brand_asset||i.action==="GENERATE"&&!i.output_dataUrl)continue;let n=i.game_object,r=this.getPreviewValueForMapping(n);if(!r.value)continue;let o=e.saveToLibrary?await this.saveToLibraryAndReturnPath(n,r.value):r.value;o&&(await this.stageEngineAssetOverride(n,o),i.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var n;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 i=(n=this.mappingResult)==null?void 0:n.mappings.find(r=>r.game_object===e);i&&(i.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 i=await this.saveToLibraryAndReturnPath(e,t.value);if(!i){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,i);let n=(r=this.mappingResult)==null?void 0:r.mappings.find(o=>o.game_object===e);n&&(n.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;let i=this.getPreviewValueForMapping(e),n=window.__openAiEditor;if(typeof n!="function"){this.setStatus("apply","AI editor not available");return}let r=t.action==="GENERATE"?t.generation_prompt:void 0;n(e,r,i.value||void 0,{path:`assets.${e}`})}async generateOne(e){var n,r,o;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(s=>s.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let i=(o=(r=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:o.trim();if(!i||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let s={apiKey:i,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await Hn(s,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(s){console.error("[BrandVision] generateOne failed:",s),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(K(),Xe));i({path:`assets.${e}`,value:t},{silent:!0});let n=window.applyEditableEngineConfig;typeof n=="function"&&n({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let i=this.inferCategoryFromAssetKey(e),n=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let o=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:i,filename:n,data:t,overwrite:!0})})).json();if(!(o!=null&&o.success)||!(o!=null&&o.path))return console.error("[BrandVision] Save to library failed:",(o==null?void 0:o.error)||o),null;let s=window.addAssetToRegistry;typeof s=="function"&&s(i,n);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(o.path)}catch(r){return console.error("[BrandVision] Save to library error:",r),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)){let o=n.slots.find(s=>s.slotId===e||s.currentAsset===e);if(o!=null&&o.category)return String(o.category)}let r=n==null?void 0:n.categories;if(Array.isArray(r)&&r.length>0){let o=e.toLowerCase(),s=l=>r.find(c=>c.toLowerCase().includes(l));return o.includes("bg")||o.includes("background")?s("background")||r[0]:(o.includes("cta")||o.includes("button")||o.includes("ui")||o.includes("logo"))&&s("ui")||r[0]}}let i=e.toLowerCase();return i.includes("bg")||i.includes("background")?"backgrounds":i.includes("cta")||i.includes("button")||i.includes("ui")||i.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 i={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]"},n=(r=this.root)==null?void 0:r.querySelector(i[e]);n&&(n.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 i=t.clientX,n=this.root.getBoundingClientRect().width,r=s=>{let l=Math.max(300,n+(s.clientX-i));this.root.style.width=`${l}px`},o=()=>{window.removeEventListener("pointermove",r),window.removeEventListener("pointerup",o)};window.addEventListener("pointermove",r),window.addEventListener("pointerup",o)})}refresh(){}};function Br(a,e={}){let{includeReference:t=!1,includeMagenta:i=!0,changeLevel:n=5}=e;return[`TASK: ${a}`,`CHANGE_STRENGTH: ${n}/10`,t?"REFERENCE: provided":"REFERENCE: none",i?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
982
+ `)}var Ws=["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"],Ys=["cta_hint","cta_label_end"],Ur=[{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"}],Ks=["brand.primary","brand.heading","brand.body","brand.warning"],Ii=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`
717
983
  <div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
718
984
  <div class="scene-panel-header" data-panel-handle>
719
985
  <div class="panel-title">
@@ -771,7 +1037,7 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
771
1037
  </div>
772
1038
  <div class="panel-resize-handle" data-panel-resize></div>
773
1039
  </div>
774
- `}initialize(e,t){var a,r,o,s,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=(o=this.root)==null?void 0:o.querySelector("[data-customize-fonts]"),this.textsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let i=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");i==null||i.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var i,a;let e=(i=this.root)==null?void 0:i.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,i=window.applyEditableObjectConfig;if(typeof t!="function"||typeof i!="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 o=t(r);o&&(o.ui||(o.ui={}),o.ui.renderMode=e?"png":"text",e&&(o.render||(o.render={}),o.render.asset||(o.render.asset={type:"image",path:""}),o.render.asset.type="image"),i(r,o))}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,i,a){this.openAiModal(e,i,a),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,i,a,r,o,s,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((i=(t=e.runtime)==null?void 0:t.theme)!=null?i:{}),this.renderFonts((r=(a=e.runtime)==null?void 0:a.fonts)!=null?r:{}),this.renderTexts((s=(o=e.runtime)==null?void 0:o.ui)!=null?s:{}),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(([i,a])=>{var u;let r=document.createElement("div");r.className="customize-row";let o=document.createElement("span");o.className="customize-key",o.textContent=i;let s=document.createElement("input");s.type="text",s.value=a!=null?a:"",s.className="customize-input",s.dataset.assetKey=i,s.addEventListener("input",()=>{this.handleAssetValueChange(i,s)});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=`
1040
+ `}initialize(e,t){var n,r,o,s,l,c;this.options=t,this.root=e.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(n=this.root)==null?void 0:n.querySelector("[data-customize-assets]"),this.colorsContainer=(r=this.root)==null?void 0:r.querySelector("[data-customize-colors]"),this.fontsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-fonts]"),this.textsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let i=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");i==null||i.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var i,n;let e=(i=this.root)==null?void 0:i.querySelector('[data-render-mode="endgame-png"]'),t=(n=this.root)==null?void 0:n.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,i=window.applyEditableObjectConfig;if(typeof t!="function"||typeof i!="function")return;let n=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let r of n){let o=t(r);o&&(o.ui||(o.ui={}),o.ui.renderMode=e?"png":"text",e&&(o.render||(o.render={}),o.render.asset||(o.render.asset={type:"image",path:""}),o.render.asset.type="image"),i(r,o))}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,i,n){this.openAiModal(e,i,n),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,i,n,r,o,s,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((i=(t=e.runtime)==null?void 0:t.theme)!=null?i:{}),this.renderFonts((r=(n=e.runtime)==null?void 0:n.fonts)!=null?r:{}),this.renderTexts((s=(o=e.runtime)==null?void 0:o.ui)!=null?s:{}),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(([i,n])=>{var u;let r=document.createElement("div");r.className="customize-row";let o=document.createElement("span");o.className="customize-key",o.textContent=i;let s=document.createElement("input");s.type="text",s.value=n!=null?n:"",s.className="customize-input",s.dataset.assetKey=i,s.addEventListener("input",()=>{this.handleAssetValueChange(i,s)});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=`
775
1041
  <svg viewBox="0 0 24 24" aria-hidden="true">
776
1042
  <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" />
777
1043
  <circle cx="12" cy="12" r="3.2" />
@@ -781,7 +1047,7 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
781
1047
  <path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
782
1048
  <path d="M5 14v4h14v-4h2v6H3v-6h2z" />
783
1049
  </svg>
784
- `;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var m;let g=(m=d.files)==null?void 0:m[0];g&&this.handleAssetUpload(g,s,i)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),r.appendChild(o),r.appendChild(s),r.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(r)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",Bs.forEach(t=>{var l,c,p;let i=(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&&(i=(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 o=document.createElement("input");o.type="color",o.value=i,o.dataset.colorKey=t;let s=document.createElement("input");s.type="text",s.value=i,s.className="customize-color-text",s.dataset.colorTextKey=t,o.addEventListener("input",()=>{s.value=o.value}),s.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(s.value)&&(o.value=s.value)}),a.appendChild(r),a.appendChild(o),a.appendChild(s),(p=this.colorsContainer)==null||p.appendChild(a)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Us.forEach(t=>{var o,s;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=e==null?void 0:e[t])!=null?o:t,r.className="customize-input",r.dataset.fontKey=t,i.appendChild(a),i.appendChild(r),(s=this.fontsContainer)==null||s.appendChild(i)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Fs.forEach(t=>{var o,s;let i=document.createElement("div");i.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=this.readUiValue(e,t))!=null?o:"",r.className="customize-input",r.dataset.textKey=t,i.appendChild(a),i.appendChild(r),(s=this.textsContainer)==null||s.appendChild(i)}),Hr.forEach(({key:t,objectId:i})=>{var s,l;let a=document.createElement("div");a.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=t;let o=document.createElement("input");o.type="text",o.value=(s=this.getObjectTextValue(i))!=null?s:"",o.className="customize-input",o.dataset.objectTextKey=t,a.appendChild(r),a.appendChild(o),(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(i=>{var s,l;let a=document.createElement("div");a.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i.replace("_"," ");let o=document.createElement("input");o.type=i.includes("volume")?"number":"text",o.min="0",o.max="1",o.step="0.1",o.value=String((s=e==null?void 0:e[i])!=null?s:""),o.className="customize-input",o.dataset.audioKey=i,i.includes("file")&&(o.placeholder="audio file path"),a.appendChild(r),a.appendChild(o),(l=this.audioContainer)==null||l.appendChild(a)})}readUiValue(e,t){if(t.includes(".")){let a=t.split("."),r=e;for(let o of a){if(r==null)return null;r=r[o]}return typeof r=="string"?r:null}let i=e==null?void 0:e[t];return typeof i=="string"?i:null}getObjectTextValue(e){var a,r;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let i=t(e);return(r=(a=i==null?void 0:i.ui)==null?void 0:a.text)!=null?r:null}getObjectPropertyValue(e,t){let i=window.getEditableObjectConfig;if(typeof i!="function")return null;let a=i(e);if(!a)return null;let r=t.split("."),o=a;for(let s of r){if(o==null)return null;o=o[s]}return typeof o=="string"?o: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(s=>{let l=s;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 i={};this.root.querySelectorAll("[data-color-text-key]").forEach(s=>{let l=s,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):i[c]=l.value)});let a={};this.root.querySelectorAll("[data-font-key]").forEach(s=>{let l=s,c=l.dataset.fontKey;c&&(a[c]=l.value)});let r={};this.root.querySelectorAll("[data-text-key]").forEach(s=>{let l=s,c=l.dataset.textKey;c&&(r[c]=l.value)});let o={};this.root.querySelectorAll("[data-audio-key]").forEach(s=>{let l=s,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);o[c]=isNaN(p)?0:p}else o[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(s=>{let l=s,c=l.dataset.objectTextKey;if(!c)return;let p=Hr.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:i,ui:r,fonts:a,audio:o}},{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 i of t)try{let a=await ki(i);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:",i,a)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var a,r,o;let t=(e==null?void 0:e.trim())||"";if(!t){let s=this.getSelectedAssetInput();t=(r=(a=s==null?void 0:s.value)==null?void 0:a.trim())!=null?r:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let i=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(o=i==null?void 0:i.dataUrl)!=null?o: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 i=t!=null?t:this.activePreviewKey;if(!i||!this.aiOutputDataUrl||this.aiOutputKey!==i){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:i})=>{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 o=this.resolveAssetUrls(i);o[0]&&(r.src=o[0]);let s=document.createElement("span");s.className="ai-gallery-label",s.textContent=t,a.appendChild(r),a.appendChild(s),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 o,s;let i=t,a=i.dataset.assetKey,r=(s=(o=i.value)==null?void 0:o.trim())!=null?s:"";!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 i=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(a=>i.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,i){var s,l,c,p,d,u,g,m,h,f;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=i||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let a=document.createElement("div");a.className="ai-modal",a.innerHTML=`
1050
+ `;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var m;let g=(m=d.files)==null?void 0:m[0];g&&this.handleAssetUpload(g,s,i)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),r.appendChild(o),r.appendChild(s),r.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(r)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",Ws.forEach(t=>{var l,c,p;let i=(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&&(i=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let n=document.createElement("label");n.className="customize-color-field";let r=document.createElement("span");r.textContent=t.replace(/_/g," ");let o=document.createElement("input");o.type="color",o.value=i,o.dataset.colorKey=t;let s=document.createElement("input");s.type="text",s.value=i,s.className="customize-color-text",s.dataset.colorTextKey=t,o.addEventListener("input",()=>{s.value=o.value}),s.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(s.value)&&(o.value=s.value)}),n.appendChild(r),n.appendChild(o),n.appendChild(s),(p=this.colorsContainer)==null||p.appendChild(n)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Ks.forEach(t=>{var o,s;let i=document.createElement("div");i.className="customize-row";let n=document.createElement("span");n.className="customize-key",n.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=e==null?void 0:e[t])!=null?o:t,r.className="customize-input",r.dataset.fontKey=t,i.appendChild(n),i.appendChild(r),(s=this.fontsContainer)==null||s.appendChild(i)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Ys.forEach(t=>{var o,s;let i=document.createElement("div");i.className="customize-row";let n=document.createElement("span");n.className="customize-key",n.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=this.readUiValue(e,t))!=null?o:"",r.className="customize-input",r.dataset.textKey=t,i.appendChild(n),i.appendChild(r),(s=this.textsContainer)==null||s.appendChild(i)}),Ur.forEach(({key:t,objectId:i})=>{var s,l;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=t;let o=document.createElement("input");o.type="text",o.value=(s=this.getObjectTextValue(i))!=null?s:"",o.className="customize-input",o.dataset.objectTextKey=t,n.appendChild(r),n.appendChild(o),(l=this.textsContainer)==null||l.appendChild(n)}))}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(i=>{var s,l;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i.replace("_"," ");let o=document.createElement("input");o.type=i.includes("volume")?"number":"text",o.min="0",o.max="1",o.step="0.1",o.value=String((s=e==null?void 0:e[i])!=null?s:""),o.className="customize-input",o.dataset.audioKey=i,i.includes("file")&&(o.placeholder="audio file path"),n.appendChild(r),n.appendChild(o),(l=this.audioContainer)==null||l.appendChild(n)})}readUiValue(e,t){if(t.includes(".")){let n=t.split("."),r=e;for(let o of n){if(r==null)return null;r=r[o]}return typeof r=="string"?r:null}let i=e==null?void 0:e[t];return typeof i=="string"?i:null}getObjectTextValue(e){var n,r;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let i=t(e);return(r=(n=i==null?void 0:i.ui)==null?void 0:n.text)!=null?r:null}getObjectPropertyValue(e,t){let i=window.getEditableObjectConfig;if(typeof i!="function")return null;let n=i(e);if(!n)return null;let r=t.split("."),o=n;for(let s of r){if(o==null)return null;o=o[s]}return typeof o=="string"?o: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(s=>{let l=s;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 i={};this.root.querySelectorAll("[data-color-text-key]").forEach(s=>{let l=s,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):i[c]=l.value)});let n={};this.root.querySelectorAll("[data-font-key]").forEach(s=>{let l=s,c=l.dataset.fontKey;c&&(n[c]=l.value)});let r={};this.root.querySelectorAll("[data-text-key]").forEach(s=>{let l=s,c=l.dataset.textKey;c&&(r[c]=l.value)});let o={};this.root.querySelectorAll("[data-audio-key]").forEach(s=>{let l=s,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);o[c]=isNaN(p)?0:p}else o[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(s=>{let l=s,c=l.dataset.objectTextKey;if(!c)return;let p=Ur.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:i,ui:r,fonts:n,audio:o}},{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 i of t)try{let n=await Mi(i);if(n)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:n.base64,mimeType:n.mimeType},dataUrl:n.dataUrl,width:n.width,height:n.height}}catch(n){console.warn("[CustomizePanel] Failed to fetch image data from:",i,n)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var n,r,o;let t=(e==null?void 0:e.trim())||"";if(!t){let s=this.getSelectedAssetInput();t=(r=(n=s==null?void 0:s.value)==null?void 0:n.trim())!=null?r:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let i=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(o=i==null?void 0:i.dataUrl)!=null?o: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 i=t!=null?t:this.activePreviewKey;if(!i||!this.aiOutputDataUrl||this.aiOutputKey!==i){e.classList.add("hidden");return}let n=e.querySelector(".asset-preview-ai-image");n&&(n.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:i})=>{var l;let n=document.createElement("button");n.type="button",n.className="ai-gallery-item",t===this.aiTargetKey&&n.classList.add("active");let r=document.createElement("img");r.className="ai-gallery-thumb",r.alt=t;let o=this.resolveAssetUrls(i);o[0]&&(r.src=o[0]);let s=document.createElement("span");s.className="ai-gallery-label",s.textContent=t,n.appendChild(r),n.appendChild(s),n.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(n)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var o,s;let i=t,n=i.dataset.assetKey,r=(s=(o=i.value)==null?void 0:o.trim())!=null?s:"";!n||!r||this.isAiGalleryImage(r)&&e.push({key:n,value:r})}),e}isAiGalleryImage(e){let t=e.trim();if(!t)return!1;if(/^(data:image|blob:)/.test(t))return!0;let i=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(n=>i.endsWith(n))}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,i){var s,l,c,p,d,u,g,m,h,f;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=i||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let n=document.createElement("div");n.className="ai-modal",n.innerHTML=`
785
1051
  <div class="ai-modal-card">
786
1052
  <div class="ai-modal-header">
787
1053
  <div>
@@ -852,7 +1118,7 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
852
1118
  </div>
853
1119
  </div>
854
1120
  </div>
855
- `;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]"),(s=this.aiRemoveBgToggle)==null||s.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let o=a.querySelector("[data-ai-ref-button]");o==null||o.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()),(m=this.aiSaveLibraryBtn)==null||m.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.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,m,h,f,b,y,v,x,w,E,C,A,M,B,P,L,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=(m=(g=this.aiModelSelect)==null?void 0:g.value)!=null?m:"gemini-2.5-flash-image",i=(b=(f=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:f.trim())!=null?b:"",a=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,r=a,o=a,s=Number((w=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?w:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!i){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((E=l==null?void 0:l.value)==null?void 0:E.trim())||((C=this.aiBaseValue)==null?void 0:C.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let O=null,D=(A=this.getSelectedAssetKey())!=null?A:"unknown",j=(M=this.aiUseOutputToggle)!=null&&M.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((B=this.aiUseOutputToggle)!=null&&B.checked&&this.aiOutputDataUrl){let ne=jn(this.aiOutputDataUrl,"ai-output.png");if(ne){let ae=await Te(ne);ae&&(O={input:{base64:ae.base64,mimeType:ae.mimeType},dataUrl:ae.dataUrl,width:ae.width,height:ae.height})}}if(O||(O=await this.getImageDataFromAsset(c)),!O){this.setAiStatus("Unable to load the base image.");return}let $=[O.input],S=!1;if(this.aiReferenceFile){let ne=await Te(this.aiReferenceFile);ne?($.push({base64:ne.base64,mimeType:ne.mimeType}),S=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let k=Nr(i,{includeReference:S,includeMagenta:r,changeLevel:s}),_=(L=(P=this.aiReferenceFile)==null?void 0:P.name)!=null?L:"none";console.info("[AI] Final prompt:",k),console.info("[AI] Image sources:",{assetKey:D,base:j,reference:_});let q=Tr(O.width,O.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await et(e,k,$,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(O){console.error("[CustomizePanel] AI Generate Error:",O),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,o,s;if(!this.aiRawOutputDataUrl)return;let e=(r=(a=this.aiRemoveBgToggle)==null?void 0:a.checked)!=null?r:!1,t=Number((s=(o=this.aiBgToleranceInput)==null?void 0:o.value)!=null?s:"30"),i=this.aiRawOutputDataUrl;if(e){let l=await Qe(this.aiRawOutputDataUrl,t);l&&(i=l)}this.setAiOutput(i),this.setAiStatus("Ready.")}setAiOutput(e){var i,a;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(i=this.previewModal)==null?void 0:i.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(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,i,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=((i=this.aiContext)==null?void 0:i.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),o=((a=this.aiContext)==null?void 0:a.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(r&&o)console.log("[CustomizePanel] Applying AI output directly to object:",r,o),this.applyObjectPropertyValue(r,o,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,o,s;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let i=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,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:`${i}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${i}.png. Refreshing library...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Adding to registry category:",a),p(a,`${i}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(f){console.warn("[CustomizePanel] Setup-library endpoint not available:",f)}let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await d());let u=((r=this.aiContext)==null?void 0:r.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),g=((o=this.aiContext)==null?void 0:o.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),m=this.getSelectedAssetInput();if(m&&(m.value=c.path,this.handleAssetValueChange((s=m.dataset.assetKey)!=null?s:"",m)),u&&g){console.log("[CustomizePanel] Applying saved asset to object:",u,g);let f=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(g)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof f=="function"&&b){let y=this.getFilenameFromPath(c.path);await f(u,y,a)}else this.applyObjectPropertyValue(u,g,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let h=window.__highlightLibrarySlot;typeof h=="function"&&u&&(console.log("[CustomizePanel] Highlighting slot in library:",u,a),setTimeout(()=>{h(u,a)},500)),this.setAiStatus(`\u2705 Saved and applied ${i}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var o;let t=(o=this.aiContext)==null?void 0:o.objectId,i=e||this.aiTargetKey||"",a=window.getEditableAssets;if(typeof a=="function"){let s=a();if(s!=null&&s.slots){let l=s.slots.find(c=>t&&c.objectId===t||c.currentAsset===i||c.slotId===i||c.currentAsset&&c.currentAsset.includes(i)||i.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let r=i.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 i=t();if(!(i!=null&&i.slots))return null;let a=i.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 i=t();if(!(i!=null&&i.slots))return null;let a=i.slots.find(o=>o.currentAsset===e||o.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 s;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(s=e==null?void 0:e.value)!=null?s:"",i=await this.getImageDimensions(t);if(!i){this.setAiStatus("Unable to read target dimensions.");return}let a=jn(this.aiOutputDataUrl,"ai-output.png");if(!a)return;let r=await this.showManualCropModal(a,i,t);if(!r)return;let o=await In(r);o&&this.setAiOutput(o)}handleAiDownload(){var i;if(!this.aiOutputDataUrl)return;let e=(i=this.getSelectedAssetKey())!=null?i:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,i){console.log("[CustomizePanel] Handling asset upload for:",i);let a=t.value,r=e;if(e.type.startsWith("image/")){let p=await this.getImageDimensions(a);if(p){let d=await this.showManualCropModal(e,p,a);if(!d)return;r=d}}let o=await In(r);if(!o){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${i.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(i);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:o,overwrite:!0})})).json();if(d.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",d.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=d.path,this.handleAssetValueChange(i,t);let m=this.inferObjectIdFromAssetKey(i),h=this.inferPathFromAssetKey(i);if(m&&h){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(d.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(d.path);await b(m,v,c)}else this.applyObjectPropertyValue(m,h,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&m&&setTimeout(()=>{f(m,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",d.error),alert(`Failed to save uploaded file: ${d.error}`)}catch(p){console.error("[CustomizePanel] \u274C Upload error:",p),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,i,a){if(!t)return;let r=this.resolveAssetUrls(t);if(r.length===0)return;let o=i||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=a!=null?a:null,this.openPreviewModal(e,t,r,o)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let i=t.replace(/^\.?\//,""),a=[];return i.startsWith("raw/")?a=[`/${i}`,`/assets/${i}`]:i.startsWith("assets/")?a=[`/${i}`]:a=[`/raw/${i}`,`/assets/raw/${i}`,`/assets/${i}`,`/${i}`],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,i,a){this.closePreviewModal(!0);let r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
1121
+ `;let r=n.querySelector(".ai-modal-close");r==null||r.addEventListener("click",()=>this.closeAiModal()),n.addEventListener("click",b=>{b.target===n&&this.closeAiModal()}),this.aiModal=n,this.aiKeyInput=n.querySelector("[data-ai-key]"),this.aiModelSelect=n.querySelector("[data-ai-model]"),this.aiPromptInput=n.querySelector("[data-ai-prompt]"),this.aiStrengthInput=n.querySelector("[data-ai-strength]"),this.aiStrengthValue=n.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=n.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=n.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=n.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=n.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=n.querySelector("[data-ai-ref-input]"),this.aiReferenceName=n.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=n.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=n.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=n.querySelector("[data-ai-generate]"),this.aiApplyBtn=n.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=n.querySelector("[data-ai-save-library]"),this.aiCropBtn=n.querySelector("[data-ai-crop]"),this.aiDownloadBtn=n.querySelector("[data-ai-download]"),this.aiPreviewImg=n.querySelector("[data-ai-preview]"),this.aiStatusEl=n.querySelector("[data-ai-status]"),this.aiLoadingEl=n.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=n.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=n.querySelector("[data-ai-bg-tolerance-value]"),(s=this.aiRemoveBgToggle)==null||s.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let o=n.querySelector("[data-ai-ref-button]");o==null||o.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()),(m=this.aiSaveLibraryBtn)==null||m.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(f=this.aiDownloadBtn)==null||f.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(n),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var p,d,u,g,m,h,f,b,y,v,x,w,E,C,S,P,F,M,T,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=(m=(g=this.aiModelSelect)==null?void 0:g.value)!=null?m:"gemini-2.5-flash-image",i=(b=(f=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:f.trim())!=null?b:"",n=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,r=n,o=n,s=Number((w=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?w:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!i){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((E=l==null?void 0:l.value)==null?void 0:E.trim())||((C=this.aiBaseValue)==null?void 0:C.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let O=null,z=(S=this.getSelectedAssetKey())!=null?S:"unknown",j=(P=this.aiUseOutputToggle)!=null&&P.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((F=this.aiUseOutputToggle)!=null&&F.checked&&this.aiOutputDataUrl){let ne=zn(this.aiOutputDataUrl,"ai-output.png");if(ne){let ae=await Le(ne);ae&&(O={input:{base64:ae.base64,mimeType:ae.mimeType},dataUrl:ae.dataUrl,width:ae.width,height:ae.height})}}if(O||(O=await this.getImageDataFromAsset(c)),!O){this.setAiStatus("Unable to load the base image.");return}let D=[O.input],A=!1;if(this.aiReferenceFile){let ne=await Le(this.aiReferenceFile);ne?(D.push({base64:ne.base64,mimeType:ne.mimeType}),A=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let k=Br(i,{includeReference:A,includeMagenta:r,changeLevel:s}),_=(T=(M=this.aiReferenceFile)==null?void 0:M.name)!=null?T:"none";console.info("[AI] Final prompt:",k),console.info("[AI] Image sources:",{assetKey:z,base:j,reference:_});let q=Mr(O.width,O.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await et(e,k,D,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(O){console.error("[CustomizePanel] AI Generate Error:",O),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 n,r,o,s;if(!this.aiRawOutputDataUrl)return;let e=(r=(n=this.aiRemoveBgToggle)==null?void 0:n.checked)!=null?r:!1,t=Number((s=(o=this.aiBgToleranceInput)==null?void 0:o.value)!=null?s:"30"),i=this.aiRawOutputDataUrl;if(e){let l=await Qe(this.aiRawOutputDataUrl,t);l&&(i=l)}this.setAiOutput(i),this.setAiStatus("Ready.")}setAiOutput(e){var i,n;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(i=this.previewModal)==null?void 0:i.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(n=this.activePreviewKey)!=null?n:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,i,n;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let r=((i=this.aiContext)==null?void 0:i.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),o=((n=this.aiContext)==null?void 0:n.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(r&&o)console.log("[CustomizePanel] Applying AI output directly to object:",r,o),this.applyObjectPropertyValue(r,o,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,o,s;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let i=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_ai_generated`,n=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:`${i}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${i}.png. Refreshing library...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Adding to registry category:",n),p(n,`${i}.png`));try{console.log("[CustomizePanel] Triggering setup-library..."),(await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})).ok?console.log("[CustomizePanel] \u2705 Library setup completed"):console.warn("[CustomizePanel] Setup-library returned non-OK status")}catch(f){console.warn("[CustomizePanel] Setup-library endpoint not available:",f)}let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Refreshing library panel..."),await d());let u=((r=this.aiContext)==null?void 0:r.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),g=((o=this.aiContext)==null?void 0:o.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),m=this.getSelectedAssetInput();if(m&&(m.value=c.path,this.handleAssetValueChange((s=m.dataset.assetKey)!=null?s:"",m)),u&&g){console.log("[CustomizePanel] Applying saved asset to object:",u,g);let f=window.applyAssetToSlot,b=/texture|image|sprite|asset\\.path/i.test(g)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof f=="function"&&b){let y=this.getFilenameFromPath(c.path);await f(u,y,n)}else this.applyObjectPropertyValue(u,g,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let h=window.__highlightLibrarySlot;typeof h=="function"&&u&&(console.log("[CustomizePanel] Highlighting slot in library:",u,n),setTimeout(()=>{h(u,n)},500)),this.setAiStatus(`\u2705 Saved and applied ${i}.png`),setTimeout(()=>{this.closeAiModal()},1500)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var o;let t=(o=this.aiContext)==null?void 0:o.objectId,i=e||this.aiTargetKey||"",n=window.getEditableAssets;if(typeof n=="function"){let s=n();if(s!=null&&s.slots){let l=s.slots.find(c=>t&&c.objectId===t||c.currentAsset===i||c.slotId===i||c.currentAsset&&c.currentAsset.includes(i)||i.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let r=i.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 i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(r=>r.currentAsset===e||r.slotId===e);return(n==null?void 0:n.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let i=t();if(!(i!=null&&i.slots))return null;let n=i.slots.find(o=>o.currentAsset===e||o.slotId===e);if(!n)return null;let r=n.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 s;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(s=e==null?void 0:e.value)!=null?s:"",i=await this.getImageDimensions(t);if(!i){this.setAiStatus("Unable to read target dimensions.");return}let n=zn(this.aiOutputDataUrl,"ai-output.png");if(!n)return;let r=await this.showManualCropModal(n,i,t);if(!r)return;let o=await Rn(r);o&&this.setAiOutput(o)}handleAiDownload(){var i;if(!this.aiOutputDataUrl)return;let e=(i=this.getSelectedAssetKey())!=null?i:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,i){console.log("[CustomizePanel] Handling asset upload for:",i);let n=t.value,r=e;if(e.type.startsWith("image/")){let p=await this.getImageDimensions(n);if(p){let d=await this.showManualCropModal(e,p,n);if(!d)return;r=d}}let o=await Rn(r);if(!o){console.error("[CustomizePanel] Failed to convert file to data URL");return}let l=`${i.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,"")}_uploaded`,c=this.inferCategoryFromAssetKey(i);console.log("[CustomizePanel] Saving uploaded file to library:",l,"category:",c);try{let d=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:c,filename:`${l}.png`,data:o,overwrite:!0})})).json();if(d.success){console.log("[CustomizePanel] \u2705 Uploaded file saved to library:",d.path);let u=window.addAssetToRegistry;typeof u=="function"&&u(c,`${l}.png`);try{await fetch("/api/setup-library",{method:"POST",headers:{"Content-Type":"application/json"}})}catch(b){console.warn("[CustomizePanel] Setup-library not available:",b)}let g=window.refreshAssetLibrary;typeof g=="function"&&await g(),t.value=d.path,this.handleAssetValueChange(i,t);let m=this.inferObjectIdFromAssetKey(i),h=this.inferPathFromAssetKey(i);if(m&&h){let b=window.applyAssetToSlot,y=/texture|image|sprite|asset\\.path/i.test(h)||/\\.(png|jpg|jpeg)$/i.test(String(d.path||""));if(typeof b=="function"&&y){let v=this.getFilenameFromPath(d.path);await b(m,v,c)}else this.applyObjectPropertyValue(m,h,d.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}let f=window.__highlightLibrarySlot;typeof f=="function"&&m&&setTimeout(()=>{f(m,c)},500),console.log("[CustomizePanel] \u2705 Upload complete:",l)}else console.error("[CustomizePanel] \u274C Upload save failed:",d.error),alert(`Failed to save uploaded file: ${d.error}`)}catch(p){console.error("[CustomizePanel] \u274C Upload error:",p),alert("Failed to save uploaded file. Check console for details.")}}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,i,n){if(!t)return;let r=this.resolveAssetUrls(t);if(r.length===0)return;let o=i||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=n!=null?n:null,this.openPreviewModal(e,t,r,o)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let i=t.replace(/^\.?\//,""),n=[];return i.startsWith("raw/")?n=[`/${i}`,`/assets/${i}`]:i.startsWith("assets/")?n=[`/${i}`]:n=[`/raw/${i}`,`/assets/raw/${i}`,`/assets/${i}`,`/${i}`],console.log("[CustomizePanel] Resolved to possible paths:",n),n}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,i,n){this.closePreviewModal(!0);let r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
856
1122
  <div class="asset-preview-card">
857
1123
  <div class="asset-preview-header">
858
1124
  <div class="asset-preview-title">${e}</div>
@@ -868,12 +1134,12 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
868
1134
  <img class="asset-preview-ai-image" alt="AI output preview">
869
1135
  </div>
870
1136
  </div>
871
- `;let o=r.querySelector(".asset-preview-body"),s=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(s==null||s.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()}),o)if(a==="image"){let d=document.createElement("img");this.loadWithFallback(d,i),o.appendChild(d)}else if(a==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,i),o.appendChild(d)}else if(a==="json"){let d=document.createElement("pre");this.fetchWithFallback(i).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),o.appendChild(d)}else{let d=document.createElement("a");d.href=i[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",o.appendChild(d)}document.body.appendChild(r),this.previewModal=r,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let i=0,a=()=>{i>=t.length||(e.src=t[i],i+=1)};e.addEventListener("error",a),a()}async fetchWithFallback(e){for(let t of e)try{let i=await fetch(t);if(!i.ok)continue;return await i.text()}catch{}return null}applyObjectPropertyValue(e,t,i){let a=window.getEditableObjectConfig,r=window.applyEditableObjectConfig;if(typeof a!="function"||typeof r!="function")return;let o=a(e);if(!o)return;let s=JSON.parse(JSON.stringify(o)),l=t.split("."),c=s;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]]=i,r(e,s)}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,i){var r;if(!this.previewModal||this.activePreviewKey!==e)return;let a=t!=null?t:"";this.activePreviewValue!==a&&this.previewAsset(e,a,i,(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"),i=t?Number(t):NaN;Number.isFinite(i)&&i>0&&(this.root.style.width=`${i}px`);let a=r=>{var u,g;r.preventDefault();let o=r.clientX,s=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=m=>{let h=m.clientX-o,f=Math.min(c,Math.max(l,s+h));this.root&&(this.root.style.width=`${f}px`)},d=()=>{var h,f;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let m=(f=(h=this.root)==null?void 0:h.getBoundingClientRect().width)!=null?f:0;m>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(m)))};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 i of t){let a=await this.loadImage(i);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 i=new Image;i.onload=()=>t(i),i.onerror=()=>t(null),i.src=e})}async showManualCropModal(e,t,i){let a=t.width/t.height,r=URL.createObjectURL(e),o=await this.loadImage(r);try{URL.revokeObjectURL(r)}catch{}if(!(o!=null&&o.naturalWidth)||!(o!=null&&o.naturalHeight))return null;let s=await this.loadImageForValue(i);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),m=Math.max(220,Math.floor((p-32-16)/2)),h=Math.min(520,window.innerHeight-240),f=m,b=f/a;b>h&&(b=h,f=b*a),c.innerHTML=`
1137
+ `;let o=r.querySelector(".asset-preview-body"),s=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(s==null||s.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()}),o)if(n==="image"){let d=document.createElement("img");this.loadWithFallback(d,i),o.appendChild(d)}else if(n==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,i),o.appendChild(d)}else if(n==="json"){let d=document.createElement("pre");this.fetchWithFallback(i).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),o.appendChild(d)}else{let d=document.createElement("a");d.href=i[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",o.appendChild(d)}document.body.appendChild(r),this.previewModal=r,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let i=0,n=()=>{i>=t.length||(e.src=t[i],i+=1)};e.addEventListener("error",n),n()}async fetchWithFallback(e){for(let t of e)try{let i=await fetch(t);if(!i.ok)continue;return await i.text()}catch{}return null}applyObjectPropertyValue(e,t,i){let n=window.getEditableObjectConfig,r=window.applyEditableObjectConfig;if(typeof n!="function"||typeof r!="function")return;let o=n(e);if(!o)return;let s=JSON.parse(JSON.stringify(o)),l=t.split("."),c=s;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]]=i,r(e,s)}applyTextColorToObject(e,t){let n={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];n&&this.applyObjectPropertyValue(n.objectId,n.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,i){var r;if(!this.previewModal||this.activePreviewKey!==e)return;let n=t!=null?t:"";this.activePreviewValue!==n&&this.previewAsset(e,n,i,(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"),i=t?Number(t):NaN;Number.isFinite(i)&&i>0&&(this.root.style.width=`${i}px`);let n=r=>{var u,g;r.preventDefault();let o=r.clientX,s=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=m=>{let h=m.clientX-o,f=Math.min(c,Math.max(l,s+h));this.root&&(this.root.style.width=`${f}px`)},d=()=>{var h,f;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let m=(f=(h=this.root)==null?void 0:h.getBoundingClientRect().width)!=null?f:0;m>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(m)))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)};e.addEventListener("pointerdown",n)}async getImageDimensions(e){let t=this.resolveAssetUrls(e);if(t.length===0)return null;for(let i of t){let n=await this.loadImage(i);if(n!=null&&n.naturalWidth&&(n!=null&&n.naturalHeight))return{width:n.naturalWidth,height:n.naturalHeight}}return null}async loadImage(e){return await new Promise(t=>{let i=new Image;i.onload=()=>t(i),i.onerror=()=>t(null),i.src=e})}async showManualCropModal(e,t,i){let n=t.width/t.height,r=URL.createObjectURL(e),o=await this.loadImage(r);try{URL.revokeObjectURL(r)}catch{}if(!(o!=null&&o.naturalWidth)||!(o!=null&&o.naturalHeight))return null;let s=await this.loadImageForValue(i);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),m=Math.max(220,Math.floor((p-32-16)/2)),h=Math.min(520,window.innerHeight-240),f=m,b=f/n;b>h&&(b=h,f=b*n),c.innerHTML=`
872
1138
  <div class="asset-crop-card" style="width:${p}px;">
873
1139
  <div class="asset-crop-header">
874
1140
  <div>
875
1141
  <div class="asset-crop-title">Crop to match current asset</div>
876
- <div class="asset-crop-subtitle">${t.width}\xD7${t.height}px \u2022 ${a.toFixed(3)} ratio</div>
1142
+ <div class="asset-crop-subtitle">${t.width}\xD7${t.height}px \u2022 ${n.toFixed(3)} ratio</div>
877
1143
  </div>
878
1144
  <button class="asset-crop-close" type="button">Close</button>
879
1145
  </div>
@@ -898,7 +1164,7 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
898
1164
  <button class="asset-crop-apply" type="button">Apply Crop</button>
899
1165
  </div>
900
1166
  </div>
901
- `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),w=c.querySelector(".asset-crop-zoom-value"),E=c.querySelector(".asset-crop-close"),C=c.querySelector(".asset-crop-cancel"),A=c.querySelector(".asset-crop-apply"),M=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!w){l(null);return}let B=y.getContext("2d"),P=v.getContext("2d");if(!B||!P){l(null);return}let L=o.naturalWidth,I=o.naturalHeight,O=Math.max(y.width/L,y.height/I),D=1,j=0,$=0,S=!1,k=0,_=0,q=0,V=0,ne=()=>{let R=O*D,Me=Math.max(0,(L*R-y.width)/2),Fe=Math.max(0,(I*R-y.height)/2);j=Math.min(Me,Math.max(-Me,j)),$=Math.min(Fe,Math.max(-Fe,$))},ae=()=>{let R=O*D;B.clearRect(0,0,y.width,y.height);let Me=y.width/2-L*R/2+j,Fe=y.height/2-I*R/2+$;if(B.drawImage(o,Me,Fe,L*R,I*R),P.clearRect(0,0,v.width,v.height),s!=null&&s.naturalWidth&&(s!=null&&s.naturalHeight)){let Ge=Math.max(v.width/s.naturalWidth,v.height/s.naturalHeight),Qi=v.width/2-s.naturalWidth*Ge/2,gt=v.height/2-s.naturalHeight*Ge/2;P.drawImage(s,Qi,gt,s.naturalWidth*Ge,s.naturalHeight*Ge)}else P.fillStyle="rgba(255, 255, 255, 0.04)",P.fillRect(0,0,v.width,v.height),P.strokeStyle="rgba(255, 255, 255, 0.08)",P.strokeRect(4,4,v.width-8,v.height-8);let ut=v.width/y.width*(O*D),Ue=j*(v.width/y.width),Bt=$*(v.height/y.height),Ji=v.width/2-L*ut/2+Ue,Zi=v.height/2-I*ut/2+Bt;P.save(),P.globalAlpha=.7,P.drawImage(o,Ji,Zi,L*ut,I*ut),P.restore()},Ca=()=>{j=0,$=0,ne(),ae()};x.addEventListener("input",()=>{D=Number(x.value),w.textContent=`${D.toFixed(2)}\xD7`,ne(),ae()}),y.addEventListener("pointerdown",R=>{S=!0,k=R.clientX,_=R.clientY,q=j,V=$,y.setPointerCapture(R.pointerId)}),y.addEventListener("pointermove",R=>{S&&(j=q+(R.clientX-k),$=V+(R.clientY-_),ne(),ae())}),y.addEventListener("pointerup",R=>{S=!1,y.releasePointerCapture(R.pointerId)}),y.addEventListener("pointerleave",()=>{S=!1});let Ki=()=>{c.remove()},Xi=()=>{Ki(),l(null)},Po=async()=>{let R=document.createElement("canvas");R.width=t.width,R.height=t.height;let Me=R.getContext("2d");if(!Me){Ki(),l(null);return}let Fe=D,Ue=Math.max(R.width/L,R.height/I)*Fe,Bt=R.width/y.width,Ji=j*Bt,Zi=$*Bt,Ge=R.width/2-L*Ue/2+Ji,Qi=R.height/2-I*Ue/2+Zi;Me.drawImage(o,Ge,Qi,L*Ue,I*Ue);let gt=await new Promise(Mo=>{R.toBlob(Oo=>Mo(Oo),e.type||"image/png")});if(Ki(),!gt){l(null);return}l(new File([gt],e.name,{type:gt.type}))};E==null||E.addEventListener("click",Xi),C==null||C.addEventListener("click",Xi),M==null||M.addEventListener("click",Ca),A==null||A.addEventListener("click",()=>{Po()}),c.addEventListener("click",R=>{R.target===c&&Xi()}),document.body.appendChild(c),Ca()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let i of t){let a=await this.loadImage(i);if(a)return a}return null}};var Oi=class{constructor(){this.root=null;this.options=null}render(){return`
1167
+ `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),w=c.querySelector(".asset-crop-zoom-value"),E=c.querySelector(".asset-crop-close"),C=c.querySelector(".asset-crop-cancel"),S=c.querySelector(".asset-crop-apply"),P=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!w){l(null);return}let F=y.getContext("2d"),M=v.getContext("2d");if(!F||!M){l(null);return}let T=o.naturalWidth,I=o.naturalHeight,O=Math.max(y.width/T,y.height/I),z=1,j=0,D=0,A=!1,k=0,_=0,q=0,V=0,ne=()=>{let R=O*z,Pe=Math.max(0,(T*R-y.width)/2),Be=Math.max(0,(I*R-y.height)/2);j=Math.min(Pe,Math.max(-Pe,j)),D=Math.min(Be,Math.max(-Be,D))},ae=()=>{let R=O*z;F.clearRect(0,0,y.width,y.height);let Pe=y.width/2-T*R/2+j,Be=y.height/2-I*R/2+D;if(F.drawImage(o,Pe,Be,T*R,I*R),M.clearRect(0,0,v.width,v.height),s!=null&&s.naturalWidth&&(s!=null&&s.naturalHeight)){let Ge=Math.max(v.width/s.naturalWidth,v.height/s.naturalHeight),tn=v.width/2-s.naturalWidth*Ge/2,gt=v.height/2-s.naturalHeight*Ge/2;M.drawImage(s,tn,gt,s.naturalWidth*Ge,s.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 ut=v.width/y.width*(O*z),Ue=j*(v.width/y.width),Ft=D*(v.height/y.height),Qi=v.width/2-T*ut/2+Ue,en=v.height/2-I*ut/2+Ft;M.save(),M.globalAlpha=.7,M.drawImage(o,Qi,en,T*ut,I*ut),M.restore()},La=()=>{j=0,D=0,ne(),ae()};x.addEventListener("input",()=>{z=Number(x.value),w.textContent=`${z.toFixed(2)}\xD7`,ne(),ae()}),y.addEventListener("pointerdown",R=>{A=!0,k=R.clientX,_=R.clientY,q=j,V=D,y.setPointerCapture(R.pointerId)}),y.addEventListener("pointermove",R=>{A&&(j=q+(R.clientX-k),D=V+(R.clientY-_),ne(),ae())}),y.addEventListener("pointerup",R=>{A=!1,y.releasePointerCapture(R.pointerId)}),y.addEventListener("pointerleave",()=>{A=!1});let Ji=()=>{c.remove()},Zi=()=>{Ji(),l(null)},Io=async()=>{let R=document.createElement("canvas");R.width=t.width,R.height=t.height;let Pe=R.getContext("2d");if(!Pe){Ji(),l(null);return}let Be=z,Ue=Math.max(R.width/T,R.height/I)*Be,Ft=R.width/y.width,Qi=j*Ft,en=D*Ft,Ge=R.width/2-T*Ue/2+Qi,tn=R.height/2-I*Ue/2+en;Pe.drawImage(o,Ge,tn,T*Ue,I*Ue);let gt=await new Promise(jo=>{R.toBlob(Ro=>jo(Ro),e.type||"image/png")});if(Ji(),!gt){l(null);return}l(new File([gt],e.name,{type:gt.type}))};E==null||E.addEventListener("click",Zi),C==null||C.addEventListener("click",Zi),P==null||P.addEventListener("click",La),S==null||S.addEventListener("click",()=>{Io()}),c.addEventListener("click",R=>{R.target===c&&Zi()}),document.body.appendChild(c),La()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let i of t){let n=await this.loadImage(i);if(n)return n}return null}};var ji=class{constructor(){this.root=null;this.options=null}render(){return`
902
1168
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
903
1169
  <div class="scene-panel-header" data-panel-handle>
904
1170
  <div class="panel-title">
@@ -964,10 +1230,10 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
964
1230
  </div>
965
1231
  </div>
966
1232
  </div>
967
- `}initialize(e,t){var y,v,x,w,E,C,A,M,B,P,L,I,O,D,j,$;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let a=(()=>{var k;let S=window.getEditableEngineConfig;if(typeof S=="function"){let _=S();return(k=_==null?void 0:_.loading)!=null?k:{}}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 S,k;(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{type:r.value}),this.updateFieldVisibility(r.value)}));let o=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");o&&(o.value=a.background_color||"#160a17",o.addEventListener("input",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{background_color:o.value})}));let s=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha-value");s&&(s.value=String((E=a.overlay_alpha)!=null?E:1),l&&(l.textContent=Number(s.value).toFixed(2)),s.addEventListener("input",()=>{var k,_;let S=Number(s.value);l&&(l.textContent=S.toFixed(2)),(_=(k=this.options)==null?void 0:k.onUpdateLoading)==null||_.call(k,{overlay_alpha:S})}));let c=(C=this.root)==null?void 0:C.querySelector("#loading-text");c&&(c.value=a.text||"",c.addEventListener("input",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{text:c.value})}));let p=(A=this.root)==null?void 0:A.querySelector("#loading-text-scale"),d=(M=this.root)==null?void 0:M.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 k,_;let S=Number(p.value);d&&(d.textContent=S.toFixed(2)),(_=(k=this.options)==null?void 0:k.onUpdateLoading)==null||_.call(k,{text_scale:S})}));let u=(P=this.root)==null?void 0:P.querySelector("#loading-enabled");u&&(u.checked=a.enabled!==!1,u.addEventListener("change",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{enabled:u.checked})}));let g=(L=this.root)==null?void 0:L.querySelector("#loading-blur-enabled");g&&(g.checked=a.blur_enabled!==!1,g.addEventListener("change",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{blur_enabled:g.checked})}));let m=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),h=(O=this.root)==null?void 0:O.querySelector("#loading-blur-strength-value");m&&(m.value=String((D=a.blur_strength)!=null?D:8),h&&(h.textContent=m.value),m.addEventListener("input",()=>{var S,k;h&&(h.textContent=m.value),(k=(S=this.options)==null?void 0:S.onUpdateLoading)==null||k.call(S,{blur_strength:Number(m.value)})}));let f=(j=this.root)==null?void 0:j.querySelector("#loading-show-btn"),b=($=this.root)==null?void 0:$.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onShowLoadingScreen)==null||k.call(S)}),b==null||b.addEventListener("click",()=>{var S,k;(k=(S=this.options)==null?void 0:S.onHideLoadingScreen)==null||k.call(S)}),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"),i=(r=this.root)==null?void 0:r.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),i&&(i.style.display="none")):(t&&(t.style.display=""),i&&(i.style.display=""))}refresh(){}};var Lt=require("pixi.js");Ke();K();async function Br(n,e,t){var i,a;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let r=Date.now(),s=`/${`raw/library/${e}/${t}`}?t=${r}`;console.log("[LIBRARY] Loading texture from:",s);let l=await Lt.Assets.load(s);if(!l){console.error("[LIBRARY] Failed to load texture:",s);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)oe[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(i=c[u])!=null&&i.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let m=((a=g.getDisplayObject)==null?void 0:a.call(g))||g.pixiObject||g;m!=null&&m.texture&&(m.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(r){console.error("[LIBRARY] Error applying asset change:",r)}}async function Fr(n,e){var t,i,a;console.log("[LIBRARY] resetAsset called for:",e);try{let r=window.getEditableAssets,o=typeof r=="function"?r():null,s=(t=o==null?void 0:o.slots)==null?void 0:t.find(f=>f.category===e),l=s==null?void 0:s.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 Lt.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),m=Object.keys(u||{}).filter(f=>f.startsWith(g)||f.includes(g));for(let f of m)oe[f]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(i=u[f])!=null&&i.texture&&(u[f].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let h=window.gameObjectManager;if(h)for(let f of m){let b=h.get(f);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:",f))}}}catch(r){console.error("[LIBRARY] Error resetting asset:",r)}}async function Ur(n,e,t,i){var a,r,o,s,l,c,p,d,u,g,m,h,f,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:i});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),w=`/raw/library/${i}/${t}?t=${x}`;console.log("[LIBRARY] Loading texture from:",w);let E=await Lt.Assets.load(w);if(!E){console.error("[LIBRARY] Failed to load texture:",w);return}console.log("[LIBRARY] \u2705 Texture loaded"),oe[v]=E,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let C=window.CustomAssets;C!=null&&C[v]&&(C[v].texture=E,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let A=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!A),A){let B=Array.from(((a=A.keys)==null?void 0:a.call(A))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",B);let P=A.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!P),P){let L=((r=P.getDisplayObject)==null?void 0:r.call(P))||P.pixiObject||P.pixi||P,I=(o=L==null?void 0:L.constructor)==null?void 0:o.name;if(console.log("[LIBRARY] displayObject:",L),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(L!=null&&L.texture)),L!=null&&L.texture)L.texture=E,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:O}=await import("pixi.js"),D=L.parent,j=(l=(s=D==null?void 0:D.getChildIndex)==null?void 0:s.call(D,L))!=null?l:0,$={x:L.x,y:L.y},S={x:(p=(c=L.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=L.anchor)==null?void 0:d.y)!=null?u:.5},k={x:(m=(g=L.scale)==null?void 0:g.x)!=null?m:1,y:(f=(h=L.scale)==null?void 0:h.y)!=null?f:1},_=(b=L.alpha)!=null?b:1,q=(y=L.visible)!=null?y:!0,V=new O(E);V.anchor.set(S.x,S.y),V.position.set($.x,$.y),V.scale.set(k.x,k.y),V.alpha=_,V.visible=q,D&&(D.removeChild(L),D.addChildAt(V,j),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),P.pixiObject&&(P.pixiObject=V),P.pixi&&(P.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(L!=null&&L.children){let O=L.children.find(D=>D.texture);O?(O.texture=E,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let M=`raw/library/${i}/${t}`;Se({objectId:v,path:"render.asset.path",value:M}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",M)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Gr(n,e,t,i){var a;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:i});try{let r=e.startsWith("json.")?e.replace("json.",""):e,o=Date.now(),s=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",s);let l=await Lt.Assets.load(s);if(!l){console.error("[LIBRARY] Failed to load default texture:",s);return}oe[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))}}Se({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 zn=require("pixi.js"),ke=()=>window.debugConfig||{},qr=()=>window.resolveAnchorVec2||(n=>({x:.5,y:.5})),Vr=()=>window.resolveScreenAnchorPoint||(()=>new zn.Point),Wr=()=>window.resolveScreenRatioPoint||(()=>new zn.Point);function Yr(n){Ii(n)&&(n.objectDebugRaf||(n.objectDebugRaf=window.requestAnimationFrame(()=>ji(n))))}function Kr(n){n.objectDebugRaf&&(window.cancelAnimationFrame(n.objectDebugRaf),n.objectDebugRaf=null),kt(n)}function Ii(n){return n.isDebugOpen}function ji(n){var r,o,s;if(!Ii(n)){n.objectDebugRaf=null;return}n.objectDebugRaf=window.requestAnimationFrame(()=>ji(n));let e=Nn(n);if(!e){Tt(n,null),kt(n);return}let t=Hn(n,e);if(!t){Tt(n,null),kt(n);return}let i=new _t.Point;(r=t.getGlobalPosition)==null||r.call(t,i);let a=Bn(n,t);Tt(n,{instanceId:e,worldX:i.x,worldY:i.y,configX:(o=a==null?void 0:a.x)!=null?o:null,configY:(s=a==null?void 0:a.y)!=null?s:null}),n.highlightObject?qn(n,t):Wn(n),n.highlightAnchor&&a?Vn(n,a):Yn(n)}function Nn(n){var a;let e=n.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,i=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return Array.isArray(i)&&i.length>0?i[0]:e}function Hn(n,e){var a,r;let t=window.gameObjectManager,i=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return i?((r=i.getDisplayObject)==null?void 0:r.call(i))||i.pixiObject||i:null}function Pt(n){let e=n.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Bn(n,e){var o,s;let t=Pt(n);if(!t)return null;let i=(o=t.transform)!=null?o:{},a=Fn(n);if(!a)return null;if(i.position_ratio!=null)return Wr()(a.width,a.height,i.position_ratio);let r=(s=i.anchor)!=null?s:"center";return Vr()(a.width,a.height,r)}function Fn(n){var r;let e=(r=n.container)==null?void 0:r.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),i=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0)return{width:t,height:i};let a=window.gameApp;return a!=null&&a.renderer?{width:a.renderer.width,height:a.renderer.height}:null}function Un(n){let e=window.gameApp;return e!=null&&e.stage?(n.objectBoundsGfx&&n.objectBoundsGfx.parent!==e.stage&&(n.objectBoundsGfx.destroy(),n.objectBoundsGfx=null),n.objectBoundsGfx||(n.objectBoundsGfx=new _t.Graphics,n.objectBoundsGfx.zIndex=999999,e.stage.addChild(n.objectBoundsGfx)),n.objectBoundsGfx):null}function Gn(n){let e=window.gameApp;return e!=null&&e.stage?(n.objectAnchorGfx&&n.objectAnchorGfx.parent!==e.stage&&(n.objectAnchorGfx.destroy(),n.objectAnchorGfx=null),n.objectAnchorGfx||(n.objectAnchorGfx=new _t.Graphics,n.objectAnchorGfx.zIndex=1e6,e.stage.addChild(n.objectAnchorGfx)),n.objectAnchorGfx):null}function qn(n,e){var a;let t=Un(n);if(!t)return;let i=(a=e.getBounds)==null?void 0:a.call(e);i&&(t.clear(),t.rect(i.x,i.y,i.width,i.height).stroke({width:2,color:16726832,alpha:.9}))}function Vn(n,e){let t=Gn(n);if(!t)return;let i=6;t.clear(),t.moveTo(e.x-i,e.y),t.lineTo(e.x+i,e.y),t.moveTo(e.x,e.y-i),t.lineTo(e.x,e.y+i),t.stroke({width:2,color:3066993,alpha:.9})}function Wn(n){n.objectBoundsGfx&&n.objectBoundsGfx.clear()}function Yn(n){n.objectAnchorGfx&&n.objectAnchorGfx.clear()}function kt(n){n.objectBoundsGfx&&(n.objectBoundsGfx.destroy(),n.objectBoundsGfx=null),n.objectAnchorGfx&&(n.objectAnchorGfx.destroy(),n.objectAnchorGfx=null)}function Tt(n,e){n.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Xr(n,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,n)}function Jr(n,e,t){var o;let i=e.split("."),a=i.pop(),r=n;for(let s of i)r[s]=(o=r[s])!=null?o:{},r=r[s];r[a]=t}function Kn(n){var i,a,r,o,s;if(!n)return!1;if((i=n.transform)!=null&&i.offset)return!0;let e=((r=(a=n.identity)==null?void 0:a.category)!=null?r:"").toString().toLowerCase(),t=((s=(o=n.identity)==null?void 0:o.id)!=null?s:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function Di(n){let e=ke();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function Zr(n){window.location.reload()}function $i(n){let e=JSON.stringify(ke(),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 Qr(n,e){var t,i,a;if(!(!n.configViewer||!n.container))try{let r=window.getEditableObjectConfig,o=typeof r=="function"?r(e):null;if(!o){let{loadObjectCentricConfig:s,loadObjectConfig:l}=await Promise.resolve().then(()=>(pi(),Sr)),d=(((t=(await s("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),Ri(n,u),(i=n.configViewer)==null||i.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,o),Ri(n,o),(a=n.configViewer)==null||a.style.setProperty("display","block");return}catch(r){console.error("[DEBUG] Failed to load object config:",r)}}function Ri(n,e){var d,u,g,m,h,f,b,y,v,x;if(!n.container)return;let t=n.container.querySelector("#config-pos-x"),i=n.container.querySelector("#config-pos-y"),a=n.container.querySelector("#config-scale"),r=n.container.querySelector("#config-anchor-x"),o=n.container.querySelector("#config-anchor-y"),l=Kn(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)),i&&(i.value=String((m=l==null?void 0:l.y)!=null?m:0)),a&&(a.value=String((f=(h=e.transform)==null?void 0:h.scale)!=null?f: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=qr()(c);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function eo(n){var l,c,p,d,u,g,m,h,f,b;let e=n.selectedObjectId;if(!e||!n.container)return;let t=(c=(l=n.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",i=(d=(p=n.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",a=(g=(u=n.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",r=(h=(m=n.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?h:"0.5",o=(b=(f=n.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?b:"0.5",s=`${e}:
1233
+ `}initialize(e,t){var y,v,x,w,E,C,S,P,F,M,T,I,O,z,j,D;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let n=(()=>{var k;let A=window.getEditableEngineConfig;if(typeof A=="function"){let _=A();return(k=_==null?void 0:_.loading)!=null?k:{}}return{}})(),r=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");r&&(r.value=n.type==="image"?"image":"color",r.addEventListener("change",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{type:r.value}),this.updateFieldVisibility(r.value)}));let o=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");o&&(o.value=n.background_color||"#160a17",o.addEventListener("input",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{background_color:o.value})}));let s=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha-value");s&&(s.value=String((E=n.overlay_alpha)!=null?E:1),l&&(l.textContent=Number(s.value).toFixed(2)),s.addEventListener("input",()=>{var k,_;let A=Number(s.value);l&&(l.textContent=A.toFixed(2)),(_=(k=this.options)==null?void 0:k.onUpdateLoading)==null||_.call(k,{overlay_alpha:A})}));let c=(C=this.root)==null?void 0:C.querySelector("#loading-text");c&&(c.value=n.text||"",c.addEventListener("input",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{text:c.value})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-text-scale"),d=(P=this.root)==null?void 0:P.querySelector("#loading-text-scale-value");p&&(p.value=String((F=n.text_scale)!=null?F:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var k,_;let A=Number(p.value);d&&(d.textContent=A.toFixed(2)),(_=(k=this.options)==null?void 0:k.onUpdateLoading)==null||_.call(k,{text_scale:A})}));let u=(M=this.root)==null?void 0:M.querySelector("#loading-enabled");u&&(u.checked=n.enabled!==!1,u.addEventListener("change",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{enabled:u.checked})}));let g=(T=this.root)==null?void 0:T.querySelector("#loading-blur-enabled");g&&(g.checked=n.blur_enabled!==!1,g.addEventListener("change",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{blur_enabled:g.checked})}));let m=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),h=(O=this.root)==null?void 0:O.querySelector("#loading-blur-strength-value");m&&(m.value=String((z=n.blur_strength)!=null?z:8),h&&(h.textContent=m.value),m.addEventListener("input",()=>{var A,k;h&&(h.textContent=m.value),(k=(A=this.options)==null?void 0:A.onUpdateLoading)==null||k.call(A,{blur_strength:Number(m.value)})}));let f=(j=this.root)==null?void 0:j.querySelector("#loading-show-btn"),b=(D=this.root)==null?void 0:D.querySelector("#loading-hide-btn");f==null||f.addEventListener("click",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onShowLoadingScreen)==null||k.call(A)}),b==null||b.addEventListener("click",()=>{var A,k;(k=(A=this.options)==null?void 0:A.onHideLoadingScreen)==null||k.call(A)}),this.updateFieldVisibility(n.type==="image"?"image":"color")}updateFieldVisibility(e){var n,r;let t=(n=this.root)==null?void 0:n.querySelector("#loading-color-field"),i=(r=this.root)==null?void 0:r.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),i&&(i.style.display="none")):(t&&(t.style.display=""),i&&(i.style.display=""))}refresh(){}};var Tt=require("pixi.js");Ke();K();async function Gr(a,e,t){var i,n;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let r=Date.now(),s=`/${`raw/library/${e}/${t}`}?t=${r}`;console.log("[LIBRARY] Loading texture from:",s);let l=await Tt.Assets.load(s);if(!l){console.error("[LIBRARY] Failed to load texture:",s);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)oe[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(i=c[u])!=null&&i.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let m=((n=g.getDisplayObject)==null?void 0:n.call(g))||g.pixiObject||g;m!=null&&m.texture&&(m.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(r){console.error("[LIBRARY] Error applying asset change:",r)}}async function qr(a,e){var t,i,n;console.log("[LIBRARY] resetAsset called for:",e);try{let r=window.getEditableAssets,o=typeof r=="function"?r():null,s=(t=o==null?void 0:o.slots)==null?void 0:t.find(f=>f.category===e),l=s==null?void 0:s.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 Tt.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),m=Object.keys(u||{}).filter(f=>f.startsWith(g)||f.includes(g));for(let f of m)oe[f]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+f),(i=u[f])!=null&&i.texture&&(u[f].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+f+" to default"));let h=window.gameObjectManager;if(h)for(let f of m){let b=h.get(f);if(b){let y=((n=b.getDisplayObject)==null?void 0:n.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",f))}}}catch(r){console.error("[LIBRARY] Error resetting asset:",r)}}async function Vr(a,e,t,i){var n,r,o,s,l,c,p,d,u,g,m,h,f,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:i});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),w=`/raw/library/${i}/${t}?t=${x}`;console.log("[LIBRARY] Loading texture from:",w);let E=await Tt.Assets.load(w);if(!E){console.error("[LIBRARY] Failed to load texture:",w);return}console.log("[LIBRARY] \u2705 Texture loaded"),oe[v]=E,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let C=window.CustomAssets;C!=null&&C[v]&&(C[v].texture=E,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let S=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!S),S){let F=Array.from(((n=S.keys)==null?void 0:n.call(S))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",F);let M=S.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!M),M){let T=((r=M.getDisplayObject)==null?void 0:r.call(M))||M.pixiObject||M.pixi||M,I=(o=T==null?void 0:T.constructor)==null?void 0:o.name;if(console.log("[LIBRARY] displayObject:",T),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(T!=null&&T.texture)),T!=null&&T.texture)T.texture=E,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:O}=await import("pixi.js"),z=T.parent,j=(l=(s=z==null?void 0:z.getChildIndex)==null?void 0:s.call(z,T))!=null?l:0,D={x:T.x,y:T.y},A={x:(p=(c=T.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=T.anchor)==null?void 0:d.y)!=null?u:.5},k={x:(m=(g=T.scale)==null?void 0:g.x)!=null?m:1,y:(f=(h=T.scale)==null?void 0:h.y)!=null?f:1},_=(b=T.alpha)!=null?b:1,q=(y=T.visible)!=null?y:!0,V=new O(E);V.anchor.set(A.x,A.y),V.position.set(D.x,D.y),V.scale.set(k.x,k.y),V.alpha=_,V.visible=q,z&&(z.removeChild(T),z.addChildAt(V,j),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(T!=null&&T.children){let O=T.children.find(z=>z.texture);O?(O.texture=E,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let P=`raw/library/${i}/${t}`;Ae({objectId:v,path:"render.asset.path",value:P}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",P)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Wr(a,e,t,i){var n;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:i});try{let r=e.startsWith("json.")?e.replace("json.",""):e,o=Date.now(),s=`/raw/${t}?t=${o}`;console.log("[LIBRARY] Loading default texture from:",s);let l=await Tt.Assets.load(s);if(!l){console.error("[LIBRARY] Failed to load default texture:",s);return}oe[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=((n=d.getDisplayObject)==null?void 0:n.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 Nn=require("pixi.js"),ke=()=>window.debugConfig||{},Yr=()=>window.resolveAnchorVec2||(a=>({x:.5,y:.5})),Kr=()=>window.resolveScreenAnchorPoint||(()=>new Nn.Point),Xr=()=>window.resolveScreenRatioPoint||(()=>new Nn.Point);function Jr(a){Ri(a)&&(a.objectDebugRaf||(a.objectDebugRaf=window.requestAnimationFrame(()=>zi(a))))}function Zr(a){a.objectDebugRaf&&(window.cancelAnimationFrame(a.objectDebugRaf),a.objectDebugRaf=null),kt(a)}function Ri(a){return a.isDebugOpen}function zi(a){var r,o,s;if(!Ri(a)){a.objectDebugRaf=null;return}a.objectDebugRaf=window.requestAnimationFrame(()=>zi(a));let e=Fn(a);if(!e){Lt(a,null),kt(a);return}let t=Bn(a,e);if(!t){Lt(a,null),kt(a);return}let i=new _t.Point;(r=t.getGlobalPosition)==null||r.call(t,i);let n=Un(a,t);Lt(a,{instanceId:e,worldX:i.x,worldY:i.y,configX:(o=n==null?void 0:n.x)!=null?o:null,configY:(s=n==null?void 0:n.y)!=null?s:null}),a.highlightObject?Wn(a,t):Kn(a),a.highlightAnchor&&n?Yn(a,n):Xn(a)}function Fn(a){var n;let e=a.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return Array.isArray(i)&&i.length>0?i[0]:e}function Bn(a,e){var n,r;let t=window.gameObjectManager,i=(n=t==null?void 0:t.get)==null?void 0:n.call(t,e);return i?((r=i.getDisplayObject)==null?void 0:r.call(i))||i.pixiObject||i:null}function Mt(a){let e=a.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Un(a,e){var o,s;let t=Mt(a);if(!t)return null;let i=(o=t.transform)!=null?o:{},n=Gn(a);if(!n)return null;if(i.position_ratio!=null)return Xr()(n.width,n.height,i.position_ratio);let r=(s=i.anchor)!=null?s:"center";return Kr()(n.width,n.height,r)}function Gn(a){var r;let e=(r=a.container)==null?void 0:r.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),i=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(i)&&i>0)return{width:t,height:i};let n=window.gameApp;return n!=null&&n.renderer?{width:n.renderer.width,height:n.renderer.height}:null}function qn(a){let e=window.gameApp;return e!=null&&e.stage?(a.objectBoundsGfx&&a.objectBoundsGfx.parent!==e.stage&&(a.objectBoundsGfx.destroy(),a.objectBoundsGfx=null),a.objectBoundsGfx||(a.objectBoundsGfx=new _t.Graphics,a.objectBoundsGfx.zIndex=999999,e.stage.addChild(a.objectBoundsGfx)),a.objectBoundsGfx):null}function Vn(a){let e=window.gameApp;return e!=null&&e.stage?(a.objectAnchorGfx&&a.objectAnchorGfx.parent!==e.stage&&(a.objectAnchorGfx.destroy(),a.objectAnchorGfx=null),a.objectAnchorGfx||(a.objectAnchorGfx=new _t.Graphics,a.objectAnchorGfx.zIndex=1e6,e.stage.addChild(a.objectAnchorGfx)),a.objectAnchorGfx):null}function Wn(a,e){var n;let t=qn(a);if(!t)return;let i=(n=e.getBounds)==null?void 0:n.call(e);i&&(t.clear(),t.rect(i.x,i.y,i.width,i.height).stroke({width:2,color:16726832,alpha:.9}))}function Yn(a,e){let t=Vn(a);if(!t)return;let i=6;t.clear(),t.moveTo(e.x-i,e.y),t.lineTo(e.x+i,e.y),t.moveTo(e.x,e.y-i),t.lineTo(e.x,e.y+i),t.stroke({width:2,color:3066993,alpha:.9})}function Kn(a){a.objectBoundsGfx&&a.objectBoundsGfx.clear()}function Xn(a){a.objectAnchorGfx&&a.objectAnchorGfx.clear()}function kt(a){a.objectBoundsGfx&&(a.objectBoundsGfx.destroy(),a.objectBoundsGfx=null),a.objectAnchorGfx&&(a.objectAnchorGfx.destroy(),a.objectAnchorGfx=null)}function Lt(a,e){a.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Qr(a,e){return e.split(".").reduce((t,i)=>t?t[i]:void 0,a)}function eo(a,e,t){var o;let i=e.split("."),n=i.pop(),r=a;for(let s of i)r[s]=(o=r[s])!=null?o:{},r=r[s];r[n]=t}function Jn(a){var i,n,r,o,s;if(!a)return!1;if((i=a.transform)!=null&&i.offset)return!0;let e=((r=(n=a.identity)==null?void 0:n.category)!=null?r:"").toString().toLowerCase(),t=((s=(o=a.identity)==null?void 0:o.id)!=null?s:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function $i(a){let e=ke();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 to(a){window.location.reload()}function Hi(a){let e=JSON.stringify(ke(),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 io(a,e){var t,i,n;if(!(!a.configViewer||!a.container))try{let r=window.getEditableObjectConfig,o=typeof r=="function"?r(e):null;if(!o){let{loadObjectCentricConfig:s,loadObjectConfig:l}=await Promise.resolve().then(()=>(pi(),Tr)),d=(((t=(await s("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),Di(a,u),(i=a.configViewer)==null||i.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,o),Di(a,o),(n=a.configViewer)==null||n.style.setProperty("display","block");return}catch(r){console.error("[DEBUG] Failed to load object config:",r)}}function Di(a,e){var d,u,g,m,h,f,b,y,v,x;if(!a.container)return;let t=a.container.querySelector("#config-pos-x"),i=a.container.querySelector("#config-pos-y"),n=a.container.querySelector("#config-scale"),r=a.container.querySelector("#config-anchor-x"),o=a.container.querySelector("#config-anchor-y"),l=Jn(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)),i&&(i.value=String((m=l==null?void 0:l.y)!=null?m:0)),n&&(n.value=String((f=(h=e.transform)==null?void 0:h.scale)!=null?f: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=Yr()(c);r&&(r.value=String(p.x)),o&&(o.value=String(p.y))}function no(a){var l,c,p,d,u,g,m,h,f,b;let e=a.selectedObjectId;if(!e||!a.container)return;let t=(c=(l=a.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",i=(d=(p=a.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",n=(g=(u=a.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",r=(h=(m=a.container.querySelector("#config-anchor-x"))==null?void 0:m.value)!=null?h:"0.5",o=(b=(f=a.container.querySelector("#config-anchor-y"))==null?void 0:f.value)!=null?b:"0.5",s=`${e}:
968
1234
  position: (${t}, ${i})
969
- scale: ${a}
970
- anchor: (${r}, ${o})`;navigator.clipboard.writeText(s).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function Xn(n,e){var d,u,g,m,h,f,b,y,v,x,w;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!n.container)return;let t=n.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let i=Number((u=(d=n.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),a=Number((m=(g=n.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?m:0),r=Number((f=(h=n.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?f:1),o=Number((y=(b=n.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),s=Number((x=(v=n.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:i,posY:a,scale:r,anchorX:o,anchorY:s});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(K(),Xe));l({objectId:t,path:"transform.position",value:{x:i,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:o,y:s}},{silent:e==null?void 0:e.silent});let c=Pt(n);Kn(c)&&l({objectId:t,path:"transform.offset",value:{x:i,y:a}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let E=(w=window.getEditableObjectConfig)==null?void 0:w.call(window,t);E?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,E)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function to(n,e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(K(),Xe));Object.entries(e.assets).forEach(([l,c])=>{i({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{i({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{i({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{i({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{i({path:`runtime.audio.${l}`,value:c},{silent:!0})});let 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("."),m=c;for(let h=0;h<g.length-1;h++){let f=g[h];m[f]=(u=m[f])!=null?u:{},m=m[f]}m[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)),o=(t==null?void 0:t.source)!=="auto"&&!r,s=window.__previewShell;o&&(s!=null&&s.refresh)&&s.refresh()}function io(n){n.selectedObjectId&&(n.objectAutoApplyTimer&&window.clearTimeout(n.objectAutoApplyTimer),n.objectAutoApplyTimer=window.setTimeout(()=>{n.objectAutoApplyTimer=null,Xn(n,{silent:!0})},150))}var Gs=3e3;function Mt(n,e,t){let i=t!=null?t:n.offsetParent;if(!i)return;e.style.cursor="move";let a=!1,r=0,o=0,s=0,l=0,c=0,p=0,d=g=>{if(!a)return;let m=i.getBoundingClientRect();n.style.left=`${g.clientX-m.left-c}px`,n.style.top=`${g.clientY-m.top-p}px`},u=()=>{a&&(a=!1,n.classList.remove("dragging"),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let m=g.target;if(m!=null&&m.closest("button, input, select, textarea"))return;g.preventDefault();let h=n.getBoundingClientRect(),f=i.getBoundingClientRect();console.log("[DRAG] Panel:",n.className),console.log("[DRAG] Container:",i.className),console.log("[DRAG] panelRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-h.left,p=g.clientY-h.top,console.log("[DRAG] offset:",{x:c,y:p});let b=h.left-f.left,y=h.top-f.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),n.style.left=`${b}px`,n.style.top=`${y}px`,n.style.right="auto",n.style.bottom="auto",n.style.zIndex=String(++Gs),a=!0,n.classList.add("dragging"),window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)})}function no(n,e,t,i=280,a=200){e.style.cursor="nwse-resize";let r=0,o=0,s=0,l=0,c=!1,p=u=>{var y;if(!c)return;let g=u.clientX-s,m=u.clientY-l,h=Math.max(i,r+g),f=Math.max(a,o+m);n.style.width=`${h}px`,(y=n.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(n.style.height=`${f}px`),t==null||t(h,f)},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=n.getBoundingClientRect();r=g.width,o=g.height,s=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)})}function Jn(n,e){var h,f,b,y;let t=(b=(f=(h=n.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?f:n.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=n.container)!=null&&y.classList.contains("layout-fixed"))return;let i=t.getBoundingClientRect(),a=e.getBoundingClientRect(),r=12,o=Math.max(250,Math.floor(i.width-r*2)),s=Math.max(200,Math.floor(i.height-r*2));a.width>o&&(e.style.width=`${o}px`),a.height>s&&(e.style.height=`${s}px`);let l=e.getBoundingClientRect(),c=l.left-i.left,p=l.top-i.top,d=Math.max(r,i.width-l.width-r),u=Math.max(r,i.height-l.height-r),g=Math.min(Math.max(c,r),d),m=Math.min(Math.max(p,r),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(m)}px`,e.style.right="auto",e.style.bottom="auto"}function tt(n){var i,a;if(!n.container)return;let e=n.container.querySelector("#debug-workbench");if(!e)return;if(Jn(n,e),(i=n.container)!=null&&i.classList.contains("layout-fixed")){let r=localStorage.getItem("preview_workbench_state"),o={activeTab:n.activeTab};if(r)try{o={...JSON.parse(r),activeTab:n.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(o));return}let t={activeTab:n.activeTab,width:e.style.width,height:(a=n.container)!=null&&a.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function zi(n){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(n.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var a,r;let i=(a=n.container)==null?void 0:a.querySelector("#debug-workbench");if(i){let o=(r=n.container)==null?void 0:r.classList.contains("layout-fixed");t.width&&(i.style.width=t.width),t.height&&!o?i.style.height=t.height:o&&(i.style.height=""),t.left&&(i.style.left=t.left,i.style.right="auto"),t.top&&(i.style.top=t.top,i.style.bottom="auto"),Jn(n,i)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function Zn(n,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",Jn(n,e),tt(n))}function ao(n){var a,r,o;if(!n.container)return;let e=n.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var s;console.log("[PREVIEW] Debug toggle clicked"),(s=n.toggleDebug)==null||s.call(n)}),(a=e.querySelector("#debug-close"))==null||a.addEventListener("click",()=>{var s;return(s=n.toggleDebug)==null?void 0:s.call(n,!1)}),(r=e.querySelector("#debug-reset"))==null||r.addEventListener("click",()=>Di(n)),(o=e.querySelector("#debug-export"))==null||o.addEventListener("click",()=>$i(n)),e.querySelectorAll(".workbench-tab").forEach(s=>{s.addEventListener("click",()=>{let l=s.dataset.tab;n.activeTab=l,Qn(n),tt(n)})}),ta(n,e),ea(n,e)}function Qn(n){if(!n.container)return;let e=n.container;e.querySelectorAll(".workbench-tab").forEach(a=>{let r=a.dataset.tab;a.classList.toggle("active",r===n.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(a=>{let r=a.dataset.tabPanel;a.classList.toggle("active",r===n.activeTab)})}function ea(n,e){te(n,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),te(n,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),te(n,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),te(n,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),te(n,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),te(n,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),te(n,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),te(n,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),te(n,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=ke();a.layout&&(a.layout.debug_rect_visible=!!t.checked)});let i=e.querySelector("#debug-rect-color");i==null||i.addEventListener("input",()=>{let a=i.value.replace("#",""),r=parseInt(a,16),o=ke();o.layout&&(o.layout.debug_rect_color=Number.isFinite(r)?r:16711680)})}function ro(n){if(!n.container||!n.debugOverlay)return;let e=n.container.querySelector("#debug-workbench"),t=n.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),Mt(e,t,n.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{tt(n),Zn(n,e)},10)}));let i=n.container.querySelector('[data-panel="scene-objects"]'),a=i==null?void 0:i.querySelector("[data-panel-handle]"),r=i==null?void 0:i.querySelector("[data-panel-resize-v]");i&&a&&(!i.style.left&&!i.style.right&&!i.style.top&&!i.style.bottom&&(i.style.left="16px",i.style.top="72px"),Mt(i,a,n.debugOverlay),a.addEventListener("pointerup",()=>{setTimeout(()=>{Zn(n,i)},10)})),i&&r&&no(i,r);let o=n.container.querySelector('[data-panel="scene-tools-corner"]'),s=o==null?void 0:o.querySelector("[data-panel-handle]");o&&s&&Mt(o,s,n.debugOverlay);let l=n.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&Mt(l,c,n.debugOverlay),zi(n)}function ta(n,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(i=>{i.addEventListener("click",()=>{let a=i.closest(".scene-panel");a&&a.classList.toggle("collapsed")})})}function te(n,e,t,i,a){let r=e.querySelector(`#${t}`),o=e.querySelector(a);if(!r||!o)return;let s=Xr(ke(),i);typeof s=="number"&&(r.value=String(s),o.textContent=String(s)),r.addEventListener("input",()=>{let l=Number(r.value);o.textContent=String(l),Jr(ke(),i,l)})}K();var Ni=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=ai(),{hasChanges:t,overrideCount:i,overrides:a}=e,r={};for(let l of a){let c=l.objectId||"Engine";r[c]||(r[c]=[]),r[c].push(l)}let o=localStorage.getItem("handler_last_applied"),s=o?new Date(parseInt(o)).toLocaleString():"Never";return`
1235
+ scale: ${n}
1236
+ anchor: (${r}, ${o})`;navigator.clipboard.writeText(s).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function Zn(a,e){var d,u,g,m,h,f,b,y,v,x,w;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!a.container)return;let t=a.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let i=Number((u=(d=a.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),n=Number((m=(g=a.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?m:0),r=Number((f=(h=a.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?f:1),o=Number((y=(b=a.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),s=Number((x=(v=a.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:i,posY:n,scale:r,anchorX:o,anchorY:s});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(K(),Xe));l({objectId:t,path:"transform.position",value:{x:i,y:n}},{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:o,y:s}},{silent:e==null?void 0:e.silent});let c=Mt(a);Jn(c)&&l({objectId:t,path:"transform.offset",value:{x:i,y:n}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let E=(w=window.getEditableObjectConfig)==null?void 0:w.call(window,t);E?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,E)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function ao(a,e,t){let{applyConfigOverride:i}=await Promise.resolve().then(()=>(K(),Xe));Object.entries(e.assets).forEach(([l,c])=>{i({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{i({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{i({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{i({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{i({path:`runtime.audio.${l}`,value:c},{silent:!0})});let n=window.applyEditableEngineConfig;if(typeof n=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),m=c;for(let h=0;h<g.length-1;h++){let f=g[h];m[f]=(u=m[f])!=null?u:{},m=m[f]}m[g[g.length-1]]=d}else c[p]=d}),l.ui=c,n({runtime:l,assets:e.assets})}let r=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),o=(t==null?void 0:t.source)!=="auto"&&!r,s=window.__previewShell;o&&(s!=null&&s.refresh)&&s.refresh()}function ro(a){a.selectedObjectId&&(a.objectAutoApplyTimer&&window.clearTimeout(a.objectAutoApplyTimer),a.objectAutoApplyTimer=window.setTimeout(()=>{a.objectAutoApplyTimer=null,Zn(a,{silent:!0})},150))}var Xs=3e3;function Pt(a,e,t){let i=t!=null?t:a.offsetParent;if(!i)return;e.style.cursor="move";let n=!1,r=0,o=0,s=0,l=0,c=0,p=0,d=g=>{if(!n)return;let m=i.getBoundingClientRect();a.style.left=`${g.clientX-m.left-c}px`,a.style.top=`${g.clientY-m.top-p}px`},u=()=>{n&&(n=!1,a.classList.remove("dragging"),window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u))};e.addEventListener("pointerdown",g=>{if(g.button!==0)return;let m=g.target;if(m!=null&&m.closest("button, input, select, textarea"))return;g.preventDefault();let h=a.getBoundingClientRect(),f=i.getBoundingClientRect();console.log("[DRAG] Panel:",a.className),console.log("[DRAG] Container:",i.className),console.log("[DRAG] panelRect:",{left:h.left,top:h.top,width:h.width,height:h.height}),console.log("[DRAG] containerRect:",{left:f.left,top:f.top,width:f.width,height:f.height}),console.log("[DRAG] mouse:",{x:g.clientX,y:g.clientY}),c=g.clientX-h.left,p=g.clientY-h.top,console.log("[DRAG] offset:",{x:c,y:p});let b=h.left-f.left,y=h.top-f.top;console.log("[DRAG] targetPosition:",{left:b,top:y}),a.style.left=`${b}px`,a.style.top=`${y}px`,a.style.right="auto",a.style.bottom="auto",a.style.zIndex=String(++Xs),n=!0,a.classList.add("dragging"),window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)})}function oo(a,e,t,i=280,n=200){e.style.cursor="nwse-resize";let r=0,o=0,s=0,l=0,c=!1,p=u=>{var y;if(!c)return;let g=u.clientX-s,m=u.clientY-l,h=Math.max(i,r+g),f=Math.max(n,o+m);a.style.width=`${h}px`,(y=a.closest(".preview-shell"))!=null&&y.classList.contains("layout-fixed")||(a.style.height=`${f}px`),t==null||t(h,f)},d=()=>{c&&(c=!1,window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d))};e.addEventListener("pointerdown",u=>{if(u.button!==0)return;u.preventDefault(),u.stopPropagation();let g=a.getBoundingClientRect();r=g.width,o=g.height,s=u.clientX,l=u.clientY,c=!0,window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)})}function Qn(a,e){var h,f,b,y;let t=(b=(f=(h=a.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?f:a.debugOverlay)!=null?b:e.offsetParent;if(!t||(y=a.container)!=null&&y.classList.contains("layout-fixed"))return;let i=t.getBoundingClientRect(),n=e.getBoundingClientRect(),r=12,o=Math.max(250,Math.floor(i.width-r*2)),s=Math.max(200,Math.floor(i.height-r*2));n.width>o&&(e.style.width=`${o}px`),n.height>s&&(e.style.height=`${s}px`);let l=e.getBoundingClientRect(),c=l.left-i.left,p=l.top-i.top,d=Math.max(r,i.width-l.width-r),u=Math.max(r,i.height-l.height-r),g=Math.min(Math.max(c,r),d),m=Math.min(Math.max(p,r),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(m)}px`,e.style.right="auto",e.style.bottom="auto"}function tt(a){var i,n;if(!a.container)return;let e=a.container.querySelector("#debug-workbench");if(!e)return;if(Qn(a,e),(i=a.container)!=null&&i.classList.contains("layout-fixed")){let r=localStorage.getItem("preview_workbench_state"),o={activeTab:a.activeTab};if(r)try{o={...JSON.parse(r),activeTab:a.activeTab}}catch{}localStorage.setItem("preview_workbench_state",JSON.stringify(o));return}let t={activeTab:a.activeTab,width:e.style.width,height:(n=a.container)!=null&&n.classList.contains("layout-fixed")?"":e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function Ni(a){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(a.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var n,r;let i=(n=a.container)==null?void 0:n.querySelector("#debug-workbench");if(i){let o=(r=a.container)==null?void 0:r.classList.contains("layout-fixed");t.width&&(i.style.width=t.width),t.height&&!o?i.style.height=t.height:o&&(i.style.height=""),t.left&&(i.style.left=t.left,i.style.right="auto"),t.top&&(i.style.top=t.top,i.style.bottom="auto"),Qn(a,i)}})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function ea(a,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",Qn(a,e),tt(a))}function so(a){var n,r,o;if(!a.container)return;let e=a.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var s;console.log("[PREVIEW] Debug toggle clicked"),(s=a.toggleDebug)==null||s.call(a)}),(n=e.querySelector("#debug-close"))==null||n.addEventListener("click",()=>{var s;return(s=a.toggleDebug)==null?void 0:s.call(a,!1)}),(r=e.querySelector("#debug-reset"))==null||r.addEventListener("click",()=>$i(a)),(o=e.querySelector("#debug-export"))==null||o.addEventListener("click",()=>Hi(a)),e.querySelectorAll(".workbench-tab").forEach(s=>{s.addEventListener("click",()=>{let l=s.dataset.tab;a.activeTab=l,ta(a),tt(a)})}),na(a,e),ia(a,e)}function ta(a){if(!a.container)return;let e=a.container;e.querySelectorAll(".workbench-tab").forEach(n=>{let r=n.dataset.tab;n.classList.toggle("active",r===a.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(n=>{let r=n.dataset.tabPanel;n.classList.toggle("active",r===a.activeTab)})}function ia(a,e){te(a,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),te(a,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),te(a,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),te(a,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),te(a,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),te(a,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),te(a,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),te(a,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),te(a,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let n=ke();n.layout&&(n.layout.debug_rect_visible=!!t.checked)});let i=e.querySelector("#debug-rect-color");i==null||i.addEventListener("input",()=>{let n=i.value.replace("#",""),r=parseInt(n,16),o=ke();o.layout&&(o.layout.debug_rect_color=Number.isFinite(r)?r:16711680)})}function lo(a){if(!a.container||!a.debugOverlay)return;let e=a.container.querySelector("#debug-workbench"),t=a.container.querySelector("#workbench-handle");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),Pt(e,t,a.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{tt(a),ea(a,e)},10)}));let i=a.container.querySelector('[data-panel="scene-objects"]'),n=i==null?void 0:i.querySelector("[data-panel-handle]"),r=i==null?void 0:i.querySelector("[data-panel-resize-v]");i&&n&&(!i.style.left&&!i.style.right&&!i.style.top&&!i.style.bottom&&(i.style.left="16px",i.style.top="72px"),Pt(i,n,a.debugOverlay),n.addEventListener("pointerup",()=>{setTimeout(()=>{ea(a,i)},10)})),i&&r&&oo(i,r);let o=a.container.querySelector('[data-panel="scene-tools-corner"]'),s=o==null?void 0:o.querySelector("[data-panel-handle]");o&&s&&Pt(o,s,a.debugOverlay);let l=a.container.querySelector('[data-panel="nudge-panel"]'),c=l==null?void 0:l.querySelector("[data-panel-handle]");l&&c&&Pt(l,c,a.debugOverlay),Ni(a)}function na(a,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(i=>{i.addEventListener("click",()=>{let n=i.closest(".scene-panel");n&&n.classList.toggle("collapsed")})})}function te(a,e,t,i,n){let r=e.querySelector(`#${t}`),o=e.querySelector(n);if(!r||!o)return;let s=Qr(ke(),i);typeof s=="number"&&(r.value=String(s),o.textContent=String(s)),r.addEventListener("input",()=>{let l=Number(r.value);o.textContent=String(l),eo(ke(),i,l)})}K();var Fi=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=ai(),{hasChanges:t,overrideCount:i,overrides:n}=e,r={};for(let l of n){let c=l.objectId||"Engine";r[c]||(r[c]=[]),r[c].push(l)}let o=localStorage.getItem("handler_last_applied"),s=o?new Date(parseInt(o)).toLocaleString():"Never";return`
971
1237
  <div class="config-persistence-panel">
972
1238
  <div class="persistence-status-bar ${t?"has-changes":"no-changes"}">
973
1239
  ${t?`
@@ -1096,7 +1362,7 @@ Generate the requested asset matching the brand style.${n.needsTransparency?" Ba
1096
1362
  </ul>
1097
1363
  </div>
1098
1364
  </div>
1099
- `}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("#create-version-btn");e==null||e.addEventListener("click",async()=>{var p;if(!(e.getAttribute("disabled")!==null||!confirm("Create a new version snapshot? This will save all changes with backup.")))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.");return}localStorage.setItem("handler_last_version_name",g),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await ri(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}`),e.textContent="\u{1F4DD} CREATE NEW VERSION",e.removeAttribute("disabled")}});let t=this.container.querySelector("#apply-current-btn");t==null||t.addEventListener("click",async()=>{if(!(t.getAttribute("disabled")!==null||!confirm(`Update current version "${this.currentVersion}"? This will overwrite the existing version.`)))try{t.textContent="\u23F3 Updating version...",t.setAttribute("disabled","true");let p=De(),d={};for(let[g,m]of Object.entries(p.objects)){let h=m,f=g;/^(json\.|ui\.|effects\.|engine\.)/.test(f)||(f=`json.${g}`),h&&typeof h=="object"&&(h.identity||(h.identity={}),h.identity.id=f),d[`objects/${f}.json`]=h}p.engine&&(p.engine.runtime&&(d["engine/engine.runtime.json"]=p.engine.runtime),p.engine.assets&&(d["engine/engine.assets.json"]=p.engine.assets),p.engine.splash&&(d["engine/engine.splash.json"]=p.engine.splash),p.engine.loading&&(d["engine/engine.loading.json"]=p.engine.loading),p.engine.start&&(d["engine/engine.start.json"]=p.engine.start),p.engine.tutorial&&(d["engine/engine.tutorial.json"]=p.engine.tutorial),p.engine.endgame&&(d["engine/engine.endgame.json"]=p.engine.endgame),!p.engine.runtime&&!p.engine.assets&&(d["engine/engine.json"]=p.engine));for(let[g,m]of Object.entries(p.scenes)){let h=g.startsWith("scene.")?g:`scene.${g}`;d[`scenes/${h}.json`]=m}let u=await fetch("/api/apply-current",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:d,assets:{},hadCacheAtApply:!0})});if(!u.ok){let g=await u.json();throw new Error(g.error||"Apply to current version failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(p){console.error("[ConfigPersistence] Apply current failed:",p),alert(`\u274C Apply to current version failed: ${p.message}`),t.textContent=`\u{1F4BE} APPLY TO CURRENT VERSION (${this.currentVersion})`,t.removeAttribute("disabled")}});let i=this.container.querySelector("#apply-base-btn");i==null||i.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
1365
+ `}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("#create-version-btn");e==null||e.addEventListener("click",async()=>{var p;if(!(e.getAttribute("disabled")!==null||!confirm("Create a new version snapshot? This will save all changes with backup.")))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.");return}localStorage.setItem("handler_last_version_name",g),e.textContent="\u23F3 Creating version...",e.setAttribute("disabled","true"),await ri(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}`),e.textContent="\u{1F4DD} CREATE NEW VERSION",e.removeAttribute("disabled")}});let t=this.container.querySelector("#apply-current-btn");t==null||t.addEventListener("click",async()=>{if(!(t.getAttribute("disabled")!==null||!confirm(`Update current version "${this.currentVersion}"? This will overwrite the existing version.`)))try{t.textContent="\u23F3 Updating version...",t.setAttribute("disabled","true");let p=ze(),d={};for(let[g,m]of Object.entries(p.objects)){let h=m,f=g;/^(json\.|ui\.|effects\.|engine\.)/.test(f)||(f=`json.${g}`),h&&typeof h=="object"&&(h.identity||(h.identity={}),h.identity.id=f),d[`objects/${f}.json`]=h}p.engine&&(p.engine.runtime&&(d["engine/engine.runtime.json"]=p.engine.runtime),p.engine.assets&&(d["engine/engine.assets.json"]=p.engine.assets),p.engine.splash&&(d["engine/engine.splash.json"]=p.engine.splash),p.engine.loading&&(d["engine/engine.loading.json"]=p.engine.loading),p.engine.start&&(d["engine/engine.start.json"]=p.engine.start),p.engine.tutorial&&(d["engine/engine.tutorial.json"]=p.engine.tutorial),p.engine.endgame&&(d["engine/engine.endgame.json"]=p.engine.endgame),!p.engine.runtime&&!p.engine.assets&&(d["engine/engine.json"]=p.engine));for(let[g,m]of Object.entries(p.scenes)){let h=g.startsWith("scene.")?g:`scene.${g}`;d[`scenes/${h}.json`]=m}let u=await fetch("/api/apply-current",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:d,assets:{},hadCacheAtApply:!0})});if(!u.ok){let g=await u.json();throw new Error(g.error||"Apply to current version failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(p){console.error("[ConfigPersistence] Apply current failed:",p),alert(`\u274C Apply to current version failed: ${p.message}`),t.textContent=`\u{1F4BE} APPLY TO CURRENT VERSION (${this.currentVersion})`,t.removeAttribute("disabled")}});let i=this.container.querySelector("#apply-base-btn");i==null||i.addEventListener("click",async()=>{if(confirm(`\u26A0\uFE0F DANGER: APPLY TO BASE
1100
1366
 
1101
1367
  This will DIRECTLY MODIFY base configuration files.
1102
1368
 
@@ -1106,7 +1372,7 @@ This is ONLY for active development.
1106
1372
 
1107
1373
  Make sure your project is under Git version control.
1108
1374
 
1109
- Continue?`))try{i.textContent="\u23F3 Writing to base...",i.setAttribute("disabled","true");let p=De(),d={};for(let[g,m]of Object.entries(p.objects)){let h=m,f=g;/^(json\.|ui\.|effects\.|engine\.)/.test(f)||(f=`json.${g}`),h&&typeof h=="object"&&(h.identity||(h.identity={}),h.identity.id=f),d[`objects/${f}.json`]=h}p.engine&&(p.engine.runtime&&(d["engine/engine.runtime.json"]=p.engine.runtime),p.engine.assets&&(d["engine/engine.assets.json"]=p.engine.assets),p.engine.splash&&(d["engine/engine.splash.json"]=p.engine.splash),p.engine.loading&&(d["engine/engine.loading.json"]=p.engine.loading),p.engine.start&&(d["engine/engine.start.json"]=p.engine.start),p.engine.tutorial&&(d["engine/engine.tutorial.json"]=p.engine.tutorial),p.engine.endgame&&(d["engine/engine.endgame.json"]=p.engine.endgame),!p.engine.runtime&&!p.engine.assets&&(d["engine/engine.json"]=p.engine));for(let[g,m]of Object.entries(p.scenes)){let h=g.startsWith("scene.")?g:`scene.${g}`;d[`scenes/${h}.json`]=m}let u=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:d,assets:{}})});if(!u.ok){let g=await u.json();throw new Error(g.error||"Apply to base failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(p){console.error("[ConfigPersistence] Apply to base failed:",p),alert(`\u274C Apply to base failed: ${p.message}`),i.textContent="\u{1F527} APPLY TO BASE (No Version)",i.removeAttribute("disabled")}});let a=this.container.querySelector("#version-selector");a==null||a.addEventListener("change",async c=>{let d=c.target.value;await this.switchVersion(d)}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let p=c.dataset.removePath,d=c.dataset.removeId;ni(d||void 0,p)})});let o=this.container.querySelector("#clear-all-overrides");o==null||o.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Et()});let s=this.container.querySelector("#reset-to-applied-btn");s==null||s.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Et()});let l=this.container.querySelector("#reset-to-original-btn");l==null||l.addEventListener("click",async()=>{await oi()})}showSuccessNotification(){let e=document.createElement("div");e.className="persistence-notification success",e.innerHTML=`
1375
+ Continue?`))try{i.textContent="\u23F3 Writing to base...",i.setAttribute("disabled","true");let p=ze(),d={};for(let[g,m]of Object.entries(p.objects)){let h=m,f=g;/^(json\.|ui\.|effects\.|engine\.)/.test(f)||(f=`json.${g}`),h&&typeof h=="object"&&(h.identity||(h.identity={}),h.identity.id=f),d[`objects/${f}.json`]=h}p.engine&&(p.engine.runtime&&(d["engine/engine.runtime.json"]=p.engine.runtime),p.engine.assets&&(d["engine/engine.assets.json"]=p.engine.assets),p.engine.splash&&(d["engine/engine.splash.json"]=p.engine.splash),p.engine.loading&&(d["engine/engine.loading.json"]=p.engine.loading),p.engine.start&&(d["engine/engine.start.json"]=p.engine.start),p.engine.tutorial&&(d["engine/engine.tutorial.json"]=p.engine.tutorial),p.engine.endgame&&(d["engine/engine.endgame.json"]=p.engine.endgame),!p.engine.runtime&&!p.engine.assets&&(d["engine/engine.json"]=p.engine));for(let[g,m]of Object.entries(p.scenes)){let h=g.startsWith("scene.")?g:`scene.${g}`;d[`scenes/${h}.json`]=m}let u=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:d,assets:{}})});if(!u.ok){let g=await u.json();throw new Error(g.error||"Apply to base failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(p){console.error("[ConfigPersistence] Apply to base failed:",p),alert(`\u274C Apply to base failed: ${p.message}`),i.textContent="\u{1F527} APPLY TO BASE (No Version)",i.removeAttribute("disabled")}});let n=this.container.querySelector("#version-selector");n==null||n.addEventListener("change",async c=>{let d=c.target.value;await this.switchVersion(d)}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let p=c.dataset.removePath,d=c.dataset.removeId;ni(d||void 0,p)})});let o=this.container.querySelector("#clear-all-overrides");o==null||o.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Et()});let s=this.container.querySelector("#reset-to-applied-btn");s==null||s.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Et()});let l=this.container.querySelector("#reset-to-original-btn");l==null||l.addEventListener("click",async()=>{await oi()})}showSuccessNotification(){let e=document.createElement("div");e.className="persistence-notification success",e.innerHTML=`
1110
1376
  <div class="notify-icon">\u2705</div>
1111
1377
  <div class="notify-content">
1112
1378
  <strong>Changes Applied!</strong>
@@ -1114,13 +1380,13 @@ Continue?`))try{i.textContent="\u23F3 Writing to base...",i.setAttribute("disabl
1114
1380
  </div>
1115
1381
  `,document.body.appendChild(e),setTimeout(()=>{e.classList.add("out"),setTimeout(()=>e.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){if(confirm(`Switch to version "${e||"original"}"?
1116
1382
 
1117
- All unsaved changes in the current version will be lost.`))try{let i=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!i.ok){let a=await i.json();throw new Error(a.error||"Failed to switch version")}se(),window.location.reload()}catch(i){alert(`\u274C Failed to switch version: ${i.message}`)}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
1383
+ All unsaved changes in the current version will be lost.`))try{let i=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!i.ok){let n=await i.json();throw new Error(n.error||"Failed to switch version")}se(),window.location.reload()}catch(i){alert(`\u274C Failed to switch version: ${i.message}`)}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
1118
1384
 
1119
1385
  This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snapshot.
1120
1386
 
1121
1387
  This cannot be undone unless you have git commits or backups.
1122
1388
 
1123
- Are you absolutely sure?`))try{let t=De(),i={};for(let[r,o]of Object.entries(t.objects)){let s=o,l=r;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${r}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=l),i[`objects/${l}.json`]=s}t.engine&&(t.engine.runtime&&(i["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(i["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(i["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(i["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(i["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(i["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(i["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(i["engine/engine.json"]=t.engine));for(let[r,o]of Object.entries(t.scenes)){let s=r.startsWith("scene.")?r:`scene.${r}`;i[`scenes/${s}.json`]=o}let a=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:i,assets:{}})});if(!a.ok){let r=await a.json();throw new Error(r.error||"Direct apply failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Ot=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 gi;this.sceneToolsPanel=new hi;this.nudgePanel=new fi;this.inspectorPanel=new Ti;this.libraryPanel=new Ct;this.libraryPanelDocked=new Ct;this.brandVisionPanel=new Pi;this.customizeSettingsPanel=new Mi;this.configPersistencePanel=new Ni;this.loadingScreenPanel=new Oi}applyAssetChange(e,t){return Br(this,e,t)}resetAsset(e){return Fr(this,e)}applySlotAsset(e,t,i){return Ur(this,e,t,i)}resetSlotAsset(e,t,i){return Gr(this,e,t,i)}startObjectVisuals(){return Yr(this)}stopObjectVisuals(){return Kr(this)}shouldRunObjectVisuals(){return Ii(this)}updateObjectVisuals(){return ji(this)}getSelectedInstanceId(){return Nn(this)}getDisplayObjectById(e){return Hn(this,e)}getSelectedObjectConfig(){return Pt(this)}getConfigAnchorWorldPoint(e){return Bn(this,e)}getScreenSize(){return Fn(this)}ensureBoundsGfx(){return Un(this)}ensureAnchorGfx(){return Gn(this)}drawBounds(e){return qn(this,e)}drawAnchor(e){return Vn(this,e)}clearBounds(){return Wn(this)}clearAnchor(){return Yn(this)}clearObjectVisuals(){return kt(this)}updateObjectInfo(e){return Tt(this,e)}resetDebugConfig(){return Di(this)}applyDebugConfig(){return Zr(this)}exportDebugConfig(){return $i(this)}loadObjectConfig(e){return Qr(this,e)}fillConfigViewer(e){return Ri(this,e)}copyConfigValues(){return eo(this)}applyObjectConfig(e){return Xn(this,e)}applyCustomizeSettings(e,t){return to(this,e,t)}scheduleObjectAutoApply(){return io(this)}setupDebugEventListeners(){return ao(this)}setupDebugInputListeners(e){return ea(this,e)}setupPanelLayout(){return ro(this)}setupCollapsiblePanels(e){return ta(this,e)}setupRangeInput(e,t,i,a){return te(this,e,t,i,a)}updateWorkbenchTabs(){return Qn(this)}saveWorkbenchState(){return tt(this)}loadWorkbenchState(){return zi(this)}initialize(e){var a;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,s)=>this.applySlotAsset(r,o,s),onReset:(r,o,s)=>this.resetSlotAsset(r,o,s)});let t=e.querySelector("#dock-library-content");t&&(t.innerHTML=this.libraryPanelDocked.render(),this.libraryPanelDocked.initialize(t,{onApply:(r,o,s)=>this.applySlotAsset(r,o,s),onReset:(r,o,s)=>this.resetSlotAsset(r,o,s)})),this.inspectorPanel.initialize(e,{onPropertyChange:(r,o,s)=>{console.log("[Inspector] Property changed:",r,o,s)}}),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)}),this.sceneToolsPanel.initialize(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(e,{onNudge:async(r,o)=>{var g,m,h,f,b,y;if(!this.selectedObjectId)return;let s=this.getSelectedObjectConfig();if(!s)return;let l=(g=s.transform)==null?void 0:g.position,c=((m=l==null?void 0:l.x)!=null?m:0)+r,p=((h=l==null?void 0:l.y)!=null?h:0)+o,{applyConfigOverride:d}=await Promise.resolve().then(()=>(K(),Xe));d({objectId:this.selectedObjectId,path:"transform.position",value:{x:c,y:p}},{silent:!0,emitEvent:!0});let u=window.applyEditableObjectConfig;if(typeof u=="function"){let v=window.__editableConfig,x=(y=(b=(f=v==null?void 0:v.objects)==null?void 0:f.get)==null?void 0:b.call(f,this.selectedObjectId))!=null?y:s;await u(this.selectedObjectId,x)}window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async r=>{var d,u,g,m,h;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let s=(u=(d=o.transform)==null?void 0:d.scale)!=null?u:1,l=Math.max(.1,s+r),{applyConfigOverride:c}=await Promise.resolve().then(()=>(K(),Xe));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0});let p=window.applyEditableObjectConfig;if(typeof p=="function"){let f=window.__editableConfig,b=(h=(m=(g=f==null?void 0:f.objects)==null?void 0:g.get)==null?void 0:m.call(g,this.selectedObjectId))!=null?h:o;await p(this.selectedObjectId,b)}window.dispatchEvent(new CustomEvent("inspector:refresh"))}});let i=e.querySelector("#debug-nudge-enabled");i==null||i.addEventListener("change",()=>{i.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,s,l)=>{this.customizeSettingsPanel.openAiEditor(r,o,s,l)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(a=this.debugOverlay)==null||a.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=r=>this.selectObject(r),window.addEventListener("config:changed",r=>{var o,s;((o=r.detail)==null?void 0:o.action)!=="remove"&&((s=r.detail)==null?void 0:s.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(r,o,s)=>this.applySlotAsset(r,o,s),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var o;let r=window.getActiveConfig;if(typeof r=="function"){let s=r();return((o=s==null?void 0:s.engine)==null?void 0:o.splash)||null}return null},window.addAssetToRegistry=(r,o)=>{let s=window.getEditableAssets;if(typeof s=="function"){let l=s();if(l!=null&&l.libraryAssets&&(l.libraryAssets[r]||(l.libraryAssets[r]=[]),!l.libraryAssets[r].some(p=>p.filename===o))){let p=o.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");l.libraryAssets[r].unshift({filename:o,displayName:p}),console.log(`[DEBUG] Added ${o} to registry category ${r}`)}}},window.__highlightLibrarySlot=(r,o)=>{this.libraryPanel.highlightSlot(r,o)}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&this.activeTab!=="ai"&&this.setActiveTab("inspector")}setActiveTab(e){this.activeTab=e,this.updateWorkbenchTabs(),this.saveWorkbenchState()}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1389
+ Are you absolutely sure?`))try{let t=ze(),i={};for(let[r,o]of Object.entries(t.objects)){let s=o,l=r;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${r}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=l),i[`objects/${l}.json`]=s}t.engine&&(t.engine.runtime&&(i["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(i["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(i["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(i["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(i["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(i["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(i["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(i["engine/engine.json"]=t.engine));for(let[r,o]of Object.entries(t.scenes)){let s=r.startsWith("scene.")?r:`scene.${r}`;i[`scenes/${s}.json`]=o}let n=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:i,assets:{}})});if(!n.ok){let r=await n.json();throw new Error(r.error||"Direct apply failed")}se(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Ot=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 fi;this.sceneToolsPanel=new mi;this.nudgePanel=new bi;this.inspectorPanel=new _i;this.libraryPanel=new Ct;this.libraryPanelDocked=new Ct;this.brandVisionPanel=new Oi;this.customizeSettingsPanel=new Ii;this.configPersistencePanel=new Fi;this.loadingScreenPanel=new ji}applyAssetChange(e,t){return Gr(this,e,t)}resetAsset(e){return qr(this,e)}applySlotAsset(e,t,i){return Vr(this,e,t,i)}resetSlotAsset(e,t,i){return Wr(this,e,t,i)}startObjectVisuals(){return Jr(this)}stopObjectVisuals(){return Zr(this)}shouldRunObjectVisuals(){return Ri(this)}updateObjectVisuals(){return zi(this)}getSelectedInstanceId(){return Fn(this)}getDisplayObjectById(e){return Bn(this,e)}getSelectedObjectConfig(){return Mt(this)}getConfigAnchorWorldPoint(e){return Un(this,e)}getScreenSize(){return Gn(this)}ensureBoundsGfx(){return qn(this)}ensureAnchorGfx(){return Vn(this)}drawBounds(e){return Wn(this,e)}drawAnchor(e){return Yn(this,e)}clearBounds(){return Kn(this)}clearAnchor(){return Xn(this)}clearObjectVisuals(){return kt(this)}updateObjectInfo(e){return Lt(this,e)}resetDebugConfig(){return $i(this)}applyDebugConfig(){return to(this)}exportDebugConfig(){return Hi(this)}loadObjectConfig(e){return io(this,e)}fillConfigViewer(e){return Di(this,e)}copyConfigValues(){return no(this)}applyObjectConfig(e){return Zn(this,e)}applyCustomizeSettings(e,t){return ao(this,e,t)}scheduleObjectAutoApply(){return ro(this)}setupDebugEventListeners(){return so(this)}setupDebugInputListeners(e){return ia(this,e)}setupPanelLayout(){return lo(this)}setupCollapsiblePanels(e){return na(this,e)}setupRangeInput(e,t,i,n){return te(this,e,t,i,n)}updateWorkbenchTabs(){return ta(this)}saveWorkbenchState(){return tt(this)}loadWorkbenchState(){return Ni(this)}initialize(e){var n;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,s)=>this.applySlotAsset(r,o,s),onReset:(r,o,s)=>this.resetSlotAsset(r,o,s)});let t=e.querySelector("#dock-library-content");t&&(t.innerHTML=this.libraryPanelDocked.render(),this.libraryPanelDocked.initialize(t,{onApply:(r,o,s)=>this.applySlotAsset(r,o,s),onReset:(r,o,s)=>this.resetSlotAsset(r,o,s)})),this.inspectorPanel.initialize(e,{onPropertyChange:(r,o,s)=>{console.log("[Inspector] Property changed:",r,o,s)}}),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)}),this.sceneToolsPanel.initialize(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(e,{onNudge:async(r,o)=>{var g,m,h,f,b,y;if(!this.selectedObjectId)return;let s=this.getSelectedObjectConfig();if(!s)return;let l=(g=s.transform)==null?void 0:g.position,c=((m=l==null?void 0:l.x)!=null?m:0)+r,p=((h=l==null?void 0:l.y)!=null?h:0)+o,{applyConfigOverride:d}=await Promise.resolve().then(()=>(K(),Xe));d({objectId:this.selectedObjectId,path:"transform.position",value:{x:c,y:p}},{silent:!0,emitEvent:!0});let u=window.applyEditableObjectConfig;if(typeof u=="function"){let v=window.__editableConfig,x=(y=(b=(f=v==null?void 0:v.objects)==null?void 0:f.get)==null?void 0:b.call(f,this.selectedObjectId))!=null?y:s;await u(this.selectedObjectId,x)}window.dispatchEvent(new CustomEvent("inspector:refresh"))},onScale:async r=>{var d,u,g,m,h;if(!this.selectedObjectId)return;let o=this.getSelectedObjectConfig();if(!o)return;let s=(u=(d=o.transform)==null?void 0:d.scale)!=null?u:1,l=Math.max(.1,s+r),{applyConfigOverride:c}=await Promise.resolve().then(()=>(K(),Xe));c({objectId:this.selectedObjectId,path:"transform.scale",value:l},{silent:!0,emitEvent:!0});let p=window.applyEditableObjectConfig;if(typeof p=="function"){let f=window.__editableConfig,b=(h=(m=(g=f==null?void 0:f.objects)==null?void 0:g.get)==null?void 0:m.call(g,this.selectedObjectId))!=null?h:o;await p(this.selectedObjectId,b)}window.dispatchEvent(new CustomEvent("inspector:refresh"))}});let i=e.querySelector("#debug-nudge-enabled");i==null||i.addEventListener("change",()=>{i.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,s,l)=>{this.customizeSettingsPanel.openAiEditor(r,o,s,l)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(n=this.debugOverlay)==null||n.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=r=>this.selectObject(r),window.addEventListener("config:changed",r=>{var o,s;((o=r.detail)==null?void 0:o.action)!=="remove"&&((s=r.detail)==null?void 0:s.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(r,o,s)=>this.applySlotAsset(r,o,s),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var o;let r=window.getActiveConfig;if(typeof r=="function"){let s=r();return((o=s==null?void 0:s.engine)==null?void 0:o.splash)||null}return null},window.addAssetToRegistry=(r,o)=>{let s=window.getEditableAssets;if(typeof s=="function"){let l=s();if(l!=null&&l.libraryAssets&&(l.libraryAssets[r]||(l.libraryAssets[r]=[]),!l.libraryAssets[r].some(p=>p.filename===o))){let p=o.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");l.libraryAssets[r].unshift({filename:o,displayName:p}),console.log(`[DEBUG] Added ${o} to registry category ${r}`)}}},window.__highlightLibrarySlot=(r,o)=>{this.libraryPanel.highlightSlot(r,o)}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&this.activeTab!=="ai"&&this.setActiveTab("inspector")}setActiveTab(e){this.activeTab=e,this.updateWorkbenchTabs(),this.saveWorkbenchState()}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1124
1390
  <div class="debug-overlay hidden" id="debug-overlay">
1125
1391
  <div class="debug-workbench" id="debug-workbench">
1126
1392
  <div class="workbench-header" id="workbench-handle">
@@ -1167,7 +1433,7 @@ Are you absolutely sure?`))try{let t=De(),i={};for(let[r,o]of Object.entries(t.o
1167
1433
  ${this.sceneToolsPanel.render()}
1168
1434
  ${this.nudgePanel.render()}
1169
1435
  </div>
1170
- `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals()}nudgeSelectedObject(e,t){var p,d,u;if(!this.selectedObjectId||!this.container)return;let i=this.nudgePanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),r=this.container.querySelector("#config-pos-y");if(!a||!r)return;let o=Number((p=a.value)!=null?p:0),s=Number((d=r.value)!=null?d:0),l=o+e*i,c=s+t*i;a&&(a.value=String(l)),r&&(r.value=String(c)),(u=this.configViewer)==null||u.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function qs(n){return new Promise((e,t)=>{let i=new FileReader;i.onerror=()=>t(new Error("FileReader failed")),i.onload=()=>e(String(i.result||"")),i.readAsDataURL(n)})}function Vs(n){var a;let[e,t]=n.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=i==null?void 0:i[1])!=null?a:"image/png"}}function Ws(n){return`
1436
+ `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.libraryPanelDocked.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals()}nudgeSelectedObject(e,t){var p,d,u;if(!this.selectedObjectId||!this.container)return;let i=this.nudgePanel.getNudgeStep(),n=this.container.querySelector("#config-pos-x"),r=this.container.querySelector("#config-pos-y");if(!n||!r)return;let o=Number((p=n.value)!=null?p:0),s=Number((d=r.value)!=null?d:0),l=o+e*i,c=s+t*i;n&&(n.value=String(l)),r&&(r.value=String(c)),(u=this.configViewer)==null||u.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function Js(a){return new Promise((e,t)=>{let i=new FileReader;i.onerror=()=>t(new Error("FileReader failed")),i.onload=()=>e(String(i.result||"")),i.readAsDataURL(a)})}function Zs(a){var n;let[e,t]=a.split(","),i=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(n=i==null?void 0:i[1])!=null?n:"image/png"}}function Qs(a){return`
1171
1437
  Analyze these screenshots of a brand or game and extract its "Brand DNA".
1172
1438
 
1173
1439
  Provide a concise summary (2-3 sentences) covering:
@@ -1181,12 +1447,12 @@ FORMAT:
1181
1447
  Summary: [Your summary here]
1182
1448
  Palette: [#RRGGBB, #RRGGBB, ...]
1183
1449
 
1184
- ${n?`
1450
+ ${a?`
1185
1451
  ADDITIONAL RULES/NOTES:
1186
- ${n}`:""}
1187
- `.trim()}function oo(){let n=[],e="",t=null;return{async addSources(i){let a=[];for(let r of i){let o=await qs(r),s=Vs(o),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:r.name,base64:s.base64,mimeType:s.mimeType,dataUrl:o};n.push(l),a.push(l)}return a},getSources(){return n.slice()},async analyze(i,a,r){if(n.length===0)throw new Error("No screenshots to analyze.");let o=Ws(a),s=n.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await _i(i,o,s,{model:r}),c=e,p=[],d=l.split(`
1452
+ ${a}`:""}
1453
+ `.trim()}function co(){let a=[],e="",t=null;return{async addSources(i){let n=[];for(let r of i){let o=await Js(r),s=Zs(o),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:r.name,base64:s.base64,mimeType:s.mimeType,dataUrl:o};a.push(l),n.push(l)}return n},getSources(){return a.slice()},async analyze(i,n,r){if(a.length===0)throw new Error("No screenshots to analyze.");let o=Qs(n),s=a.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await Pi(i,o,s,{model:r}),c=e,p=[],d=l.split(`
1188
1454
  `);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(m=>{p.includes(m.toUpperCase())||p.push(m.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(i){e=i,t&&(t={...t,summary:i})},getResult(){return t}}}var He="handler_api_key_";var it=class{static setKey(e,t,i){try{let a={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:i||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}`,i=localStorage.getItem(t);if(!i)return null;let a=JSON.parse(i);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 i=localStorage.key(t);if(i&&i.startsWith(He)){let a=i.substring(He.length),r=localStorage.getItem(i);if(r){let o=JSON.parse(r);e.push({service:a,label:o.label,created:o.created,lastUsed:o.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,i)=>i.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let i=localStorage.key(t);i&&i.startsWith(He)&&e.push(i)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let i="handler_preview_salt_2024"+e;return btoa(i)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),i="handler_preview_salt_2024";return t.startsWith(i)?t.substring(i.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},ia=()=>it.getKey("gemini"),na=(n,e)=>it.setKey("gemini",n,e),Ys=()=>it.hasKey("gemini");window.ApiKeyStorage=it;window.getGeminiApiKey=ia;window.setGeminiApiKey=na;window.hasGeminiApiKey=Ys;var ra=class{constructor(){this.modal=null;this.options=null;this.analyzer=oo();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,i;(t=this.promptInput)==null||t.focus(),(i=this.promptInput)==null||i.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
1455
+ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(i){e=i,t&&(t={...t,summary:i})},getResult(){return t}}}var Ne="handler_api_key_";var it=class{static setKey(e,t,i){try{let n={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:i||e},r=`${Ne}${e}`;localStorage.setItem(r,JSON.stringify(n))}catch(n){console.error("[ApiKeyStorage] Failed to store API key:",n)}}static getKey(e){try{let t=`${Ne}${e}`,i=localStorage.getItem(t);if(!i)return null;let n=JSON.parse(i);return n.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(n)),this.decryptKey(n.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${Ne}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${Ne}${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 i=localStorage.key(t);if(i&&i.startsWith(Ne)){let n=i.substring(Ne.length),r=localStorage.getItem(i);if(r){let o=JSON.parse(r);e.push({service:n,label:o.label,created:o.created,lastUsed:o.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,i)=>i.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let i=localStorage.key(t);i&&i.startsWith(Ne)&&e.push(i)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let i="handler_preview_salt_2024"+e;return btoa(i)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),i="handler_preview_salt_2024";return t.startsWith(i)?t.substring(i.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},aa=()=>it.getKey("gemini"),ra=(a,e)=>it.setKey("gemini",a,e),el=()=>it.hasKey("gemini");window.ApiKeyStorage=it;window.getGeminiApiKey=aa;window.setGeminiApiKey=ra;window.hasGeminiApiKey=el;var sa=class{constructor(){this.modal=null;this.options=null;this.analyzer=co();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,i;(t=this.promptInput)==null||t.focus(),(i=this.promptInput)==null||i.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
1190
1456
  <div class="ai-modal-card">
1191
1457
  <div class="ai-modal-header">
1192
1458
  <div class="ai-modal-actions">
@@ -1265,17 +1531,17 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0
1265
1531
  <button class="ai-btn primary" data-action="apply" disabled>Apply</button>
1266
1532
  </div>
1267
1533
  </div>
1268
- `,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var i;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]"),(i=this.promptInput)==null||i.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 s;let r=a.target;switch(r.dataset.action||((s=r.closest("[data-action]"))==null?void 0:s.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 o=r.closest(".ai-gallery-item"),s=parseInt(o.dataset.index||"-1");s>=0&&this.selectImage(s)}}),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 i=this.analyzer.getResult();if(i!=null&&i.summary&&this.promptInput){let a=`${this.currentPrompt}
1534
+ `,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var i;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]"),(i=this.promptInput)==null||i.addEventListener("input",()=>{var n;this.currentPrompt=((n=this.promptInput)==null?void 0:n.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",n=>{var s;let r=n.target;switch(r.dataset.action||((s=r.closest("[data-action]"))==null?void 0:s.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",n=>{let r=n.target;if(r.classList.contains("ai-gallery-item")||r.closest(".ai-gallery-item")){let o=r.closest(".ai-gallery-item"),s=parseInt(o.dataset.index||"-1");s>=0&&this.selectImage(s)}}),this.modal.addEventListener("click",n=>{n.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 i=this.analyzer.getResult();if(i!=null&&i.summary&&this.promptInput){let n=`${this.currentPrompt}
1269
1535
 
1270
- Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}catch(i){console.warn("[AiEditorModal] Failed to apply brand DNA:",i)}}async generateImage(){var e,t,i,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 o=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await ki(this.options.currentValue);c&&(o=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let s=await et(r,this.currentPrompt,o,{aspectRatio:"1:1"}),l=await Qe(s);this.generatedImages.push(l||s),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,(i=this.loadingEl)==null||i.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,i)=>`
1536
+ Style guidelines: ${i.summary}`;this.promptInput.value=n,this.currentPrompt=n}}catch(i){console.warn("[AiEditorModal] Failed to apply brand DNA:",i)}}async generateImage(){var e,t,i,n;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 o=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await Mi(this.options.currentValue);c&&(o=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let s=await et(r,this.currentPrompt,o,{aspectRatio:"1:1"}),l=await Qe(s);this.generatedImages.push(l||s),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,(i=this.loadingEl)==null||i.classList.add("hidden"),(n=this.previewEl)==null||n.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,i)=>`
1271
1537
  <div class="ai-gallery-item ${i===this.selectedImageIndex?"active":""}" data-index="${i}">
1272
1538
  <img class="ai-gallery-thumb" src="${t}" alt="Generated ${i+1}" />
1273
1539
  <div class="ai-gallery-label">#${i+1}</div>
1274
1540
  </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=ia();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return na(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}},aa=null;window.__openAiEditor=function(n,e,t,i){aa||(aa=new ra),aa.open({objectId:n,initialPrompt:e,currentValue:t,path:i==null?void 0:i.path,onApply:a=>{if(i!=null&&i.path){let r=window.updateManager;if(r)r.updateProperty(n,i.path,a);else{let o=window.getEditableObjectConfig,s=o==null?void 0:o(n);if(s){let l=i.path.split("."),c=s;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"))}})};sa();var la=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:i}=this.options,a=i||"Asset Preview",r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
1541
+ `).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=aa();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return ra(t.apiKey,"From Brand DNA"),t.apiKey}catch(t){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",t)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},oa=null;window.__openAiEditor=function(a,e,t,i){oa||(oa=new sa),oa.open({objectId:a,initialPrompt:e,currentValue:t,path:i==null?void 0:i.path,onApply:n=>{if(i!=null&&i.path){let r=window.updateManager;if(r)r.updateProperty(a,i.path,n);else{let o=window.getEditableObjectConfig,s=o==null?void 0:o(a);if(s){let l=i.path.split("."),c=s;for(let p=0;p<l.length-1;p++)c[l[p]]||(c[l[p]]={}),c=c[l[p]];c[l[l.length-1]]=n}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};ca();var da=class{constructor(){this.modal=null;this.options=null}open(e){this.options=e,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:e,assetType:t,objectId:i}=this.options,n=i||"Asset Preview",r=document.createElement("div");r.className="asset-preview-modal",r.innerHTML=`
1276
1542
  <div class="asset-preview-card">
1277
1543
  <div class="asset-preview-header">
1278
- <div class="asset-preview-title">${a}</div>
1544
+ <div class="asset-preview-title">${n}</div>
1279
1545
  <button class="asset-preview-close" data-action="close">\xD7</button>
1280
1546
  </div>
1281
1547
 
@@ -1293,13 +1559,13 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1293
1559
  ${t==="image"?'<button class="asset-preview-ai" data-action="edit">\u2728 AI Edit</button>':""}
1294
1560
  </div>
1295
1561
  </div>
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`
1562
+ `,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 n=this.resolveAssetUrl(e);return`
1297
1563
  <audio controls style="width: 100%;">
1298
- <source src="${a}" type="audio/mpeg">
1299
- <source src="${a}" type="audio/wav">
1564
+ <source src="${n}" type="audio/mpeg">
1565
+ <source src="${n}" type="audio/wav">
1300
1566
  Your browser does not support the audio element.
1301
1567
  </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",i=>{let a=i.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(()=>(sa(),so)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,i=>{var a;(a=this.options)!=null&&a.onChange&&this.options.onChange(i),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(n){new la().open(n)};var ca=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=`
1568
+ `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",i=>{let n=i.target;(n.dataset.action==="close"||n===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(ca(),po)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var i;(i=this.options)!=null&&i.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(a){new da().open(a)};var pa=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
1569
  <div class="asset-crop-card">
1304
1570
  <div class="asset-crop-header">
1305
1571
  <div>
@@ -1350,7 +1616,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1350
1616
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
1351
1617
  </div>
1352
1618
  </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 i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,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,i-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,i=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,i,a),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,a),this.ctx.fillStyle="#ffffff";let r=8;[[e,t],[e+i-r,t],[e,t+a-r],[e+i-r,t+a-r]].forEach(([s,l])=>{var c;(c=this.ctx)==null||c.fillRect(s,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 i=150;e.width=i,e.height=i;let a=i/this.cropWidth,r=i/this.cropHeight,o=Math.min(a,r),s=this.cropWidth*o,l=this.cropHeight*o,c=(i-s)/2,p=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,s,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",i=>{let a=parseFloat(i.target.value);this.setZoom(a)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let a=i.target.value;this.setAspectRatio(a)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var 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 i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(n){new ca().open(n)};var Hi=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[Ne("playable-portrait"),Ne("iphone-14"),Ne("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.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,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,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=Ne(e.defaultDevice||ui.id),this.debugPanel=new Ot,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.updateDockState(),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(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var a,r;let i=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Ne(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:i}),t.suppressCallback||(r=(a=this.options).onDeviceChange)==null||r.call(a,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(a=>a.classList.toggle("active",a.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(a=>{a.style.left="",a.style.top="",a.style.width="",a.style.height="",a.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,a,r=s=>{let l=s.clientY-i,c=Math.max(100,Math.min(800,a-l));e.style.height=`${c}px`;let p=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:p})},o=()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",s=>{s.preventDefault(),i=s.clientY,a=e.offsetHeight,document.addEventListener("pointermove",r),document.addEventListener("pointerup",o),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let a,r,o=l=>{let c=i==="left"?l.clientX-a:a-l.clientX,p=Math.max(200,Math.min(600,r+c));e.style.width=`${p}px`;let d=this.container.querySelector(".preview-main");if(d){let g=i==="left"?`${p}px`:d.style.gridTemplateColumns.split(" ")[0]||"300px",m=i==="right"?`${p}px`:d.style.gridTemplateColumns.split(" ")[2]||"350px";d.style.gridTemplateColumns=`${g} 1fr ${m}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},s=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),a=l.clientX,r=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",s),e.classList.add("resizing")})}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
1619
+ `,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 i;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(i=this.options)!=null&&i.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,i=this.cropX+this.cropWidth/2,n=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,i-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,n-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!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,i=this.cropWidth*this.scale,n=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,i,n),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,i,n),this.ctx.fillStyle="#ffffff";let r=8;[[e,t],[e+i-r,t],[e,t+n-r],[e+i-r,t+n-r]].forEach(([s,l])=>{var c;(c=this.ctx)==null||c.fillRect(s,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 i=150;e.width=i,e.height=i;let n=i/this.cropWidth,r=i/this.cropHeight,o=Math.min(n,r),s=this.cropWidth*o,l=this.cropHeight*o,c=(i-s)/2,p=(i-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,s,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",i=>{let n=parseFloat(i.target.value);this.setZoom(n)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",i=>{let n=i.target.value;this.setAspectRatio(n)}),this.modal.addEventListener("click",i=>{switch(i.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",i=>{i.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,i=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,i=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+i,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var n;if(!this.image||!((n=this.options)!=null&&n.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let i=e.toDataURL("image/png");this.options.onCrop(i),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(a){new pa().open(a)};var Bi=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.layoutMode="fixed";this.comparePresets=[He("playable-portrait"),He("iphone-14"),He("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.originalConsole={log:console.log.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),info:console.info.bind(console)};this.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,i=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+i,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=He(e.defaultDevice||ui.id),this.debugPanel=new Ot,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.updateDockState(),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(),requestAnimationFrame(()=>this.updatePanelPositions())}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var n,r;let i=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=He(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:i}),t.suppressCallback||(r=(n=this.options).onDeviceChange)==null||r.call(n,this.getEffectivePreset()),this.emitScreenChange()}setTheme(e){e==="dark"?this.container.classList.add("theme-dark"):this.container.classList.remove("theme-dark"),requestAnimationFrame(()=>this.updatePanelPositions())}setLayoutMode(e){if(this.layoutMode===e)return;this.layoutMode=e,this.container.classList.toggle("layout-fixed",e==="fixed"),this.container.classList.toggle("layout-draggable",e==="draggable"),Array.from(this.container.querySelectorAll("[data-layout-toggle]")).forEach(n=>n.classList.toggle("active",n.dataset.layoutToggle===e)),Array.from(this.container.querySelectorAll(".debug-workbench, .scene-panel")).forEach(n=>{n.style.left="",n.style.top="",n.style.width="",n.style.height="",n.style.zIndex=""}),this.scheduleFit(),this.updateDockState(),this.updatePanelPositions(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}updateDockState(){let e=this.container.querySelector("#bottom-dock");e==null||e.classList.remove("hidden");let t=this.container.querySelector("#console-messages"),i=this.container.querySelector("#dock-console-content");t&&i&&t.parentElement!==i&&i.appendChild(t)}makeBottomDockResizable(e,t){let i,n,r=s=>{let l=s.clientY-i,c=Math.max(100,Math.min(800,n-l));e.style.height=`${c}px`;let p=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:p})},o=()=>{document.removeEventListener("pointermove",r),document.removeEventListener("pointerup",o),e.classList.remove("resizing")};t.addEventListener("pointerdown",s=>{s.preventDefault(),i=s.clientY,n=e.offsetHeight,document.addEventListener("pointermove",r),document.addEventListener("pointerup",o),e.classList.add("resizing")})}makeSidebarResizable(e,t,i){let n,r,o=l=>{let c=i==="left"?l.clientX-n:n-l.clientX,p=Math.max(200,Math.min(600,r+c));e.style.width=`${p}px`;let d=this.container.querySelector(".preview-main");if(d){let g=i==="left"?`${p}px`:d.style.gridTemplateColumns.split(" ")[0]||"300px",m=i==="right"?`${p}px`:d.style.gridTemplateColumns.split(" ")[2]||"350px";d.style.gridTemplateColumns=`${g} 1fr ${m}`}let u=this.autoScale*this.userScaleMultiplier;this.fitToScreen({keepVisibleScale:u})},s=()=>{document.removeEventListener("pointermove",o),document.removeEventListener("pointerup",s),e.classList.remove("resizing")};t.addEventListener("pointerdown",l=>{l.preventDefault(),n=l.clientX,r=e.offsetWidth,document.addEventListener("pointermove",o),document.addEventListener("pointerup",s),e.classList.add("resizing")})}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell layout-fixed",e.innerHTML=`
1354
1620
  <div class="preview-toolbar">
1355
1621
  <div class="preview-toolbar-left">
1356
1622
  <span class="preview-logo">PREVIEWER</span>
@@ -1359,11 +1625,11 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1359
1625
  <div class="preview-toolbar-center">
1360
1626
  <div class="device-selector-wrapper">
1361
1627
  <select class="device-dropdown" id="device-select">
1362
- ${Mn.map(i=>`
1628
+ ${In.map(i=>`
1363
1629
  <optgroup label="${i.label}">
1364
- ${i.devices.map(a=>`
1365
- <option value="${a.id}" ${a.id===this.currentPreset.id?"selected":""}>
1366
- ${a.label} (${a.width}\xD7${a.height})
1630
+ ${i.devices.map(n=>`
1631
+ <option value="${n.id}" ${n.id===this.currentPreset.id?"selected":""}>
1632
+ ${n.label} (${n.width}\xD7${n.height})
1367
1633
  </option>
1368
1634
  `).join("")}
1369
1635
  </optgroup>
@@ -1511,7 +1777,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1511
1777
  </div>
1512
1778
 
1513
1779
  </div>
1514
- `,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,h,f,b,y,v,x;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",w=>{if(this.viewMode==="compare")return;let E=w.target.value;this.setDevice(E)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",w=>{let E=w.target.value;this.setTheme(E)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.viewToggle;E&&this.setViewMode(E)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.layoutToggle;E&&this.setLayoutMode(E)})}),(g=e.querySelector("#rotate-btn"))==null||g.addEventListener("click",()=>this.toggleRotation()),(m=e.querySelector("#zoom-in-btn"))==null||m.addEventListener("click",()=>this.adjustUserZoom(.1)),(h=e.querySelector("#zoom-out-btn"))==null||h.addEventListener("click",()=>this.adjustUserZoom(-.1)),(f=e.querySelector("#refresh-btn"))==null||f.addEventListener("click",()=>this.refresh());let o=e.querySelector("#bottom-dock"),s=e.querySelector("#bottom-dock-resize");o&&s&&this.makeBottomDockResizable(o,s);let l=Array.from(e.querySelectorAll(".bottom-dock-tab"));l.forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.dockTab;if(!E)return;l.forEach(A=>A.classList.remove("active")),w.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(A=>{let M=A.dataset.dockPanel;A.classList.toggle("active",M===E)})})}),(b=e.querySelector("#console-clear"))==null||b.addEventListener("click",()=>this.clearConsole()),(y=e.querySelector("#corner-zoom-in-btn"))==null||y.addEventListener("click",()=>this.adjustUserZoom(.1)),(v=e.querySelector("#corner-zoom-out-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(-.1)),(x=e.querySelector("#corner-grab-btn"))==null||x.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let c=e.querySelector(".scene-panel.scene-objects"),p=c==null?void 0:c.querySelector("[data-panel-resize-v]");c&&p&&this.makeSidebarResizable(c,p,"left");let d=e.querySelector(".debug-workbench"),u=d==null?void 0:d.querySelector("#workbench-resize-v");d&&u&&this.makeSidebarResizable(d,u,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),i=this.getFitBounds(),a=Math.max(0,i.width),r=Math.max(0,i.height);if(a<=0||r<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let o=a/t.width,s=r/t.height;if(this.autoScale=Math.max(.01,Math.min(o,s)),!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(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let i=this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,i;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(i=(t=this.options).onDeviceChange)==null||i.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(a,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let a=i.map(o=>typeof o=="object"?this.safeStringify(o):String(o)).join(" ");this.consoleMessages.push({type:t,message:a,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let r=this.container.querySelector("#console-badge");if(r){let o=this.consoleMessages.filter(s=>s.type==="error").length;r.textContent=o>0?`${o}!`:"0",r.classList.toggle("has-errors",o>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let i=document.createElement("div");i.className=`console-msg type-${e.type}`;let a=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(a)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let i=this.container.querySelector('[data-dock-tab="console"]');if(i){i.click();let a=this.container.querySelector("#bottom-dock");a==null||a.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let i=t.dataset.viewport;if(!i)return;let a=this.comparePresets.find(d=>d.id===i);if(!a)return;let r=t.querySelector("[data-compare-slot]"),o=t.querySelector("[data-compare-ghost]"),s=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),p=t.querySelector("[data-compare-focus]");!r||!o||!s||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:a,root:t,slot:r,ghost:o,wrapper:s,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 i=this.container.querySelector("#rotate-btn");if(i&&(i.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,o;let t=this.compareViewports.get(e);if(!t)return;let i=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((s,l)=>{s.root.classList.toggle("is-active",l===e),s.ghost.classList.toggle("hidden",l===e),s.focus&&(s.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:i}),(o=(r=this.options).onDeviceChange)==null||o.call(r,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,a=`${t.height}px`;e.frame.style.width=i,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 i=Math.max(0,t.clientWidth-24),a=Math.max(0,t.clientHeight-24);if(i<=0||a<=0)return;let r=i/e.preset.width,o=a/e.preset.height,s=Math.max(.01,Math.min(r,o));e.wrapper.style.transform=`scale(${s})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let a=t.canvas.getContext("2d");if(!a)return;let r=t.canvas.width,o=t.canvas.height,s=Math.min(r/i.width,o/i.height),l=i.width*s,c=i.height*s,p=(r-l)/2,d=(o-c)/2;a.clearRect(0,0,r,o),a.drawImage(i,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 da(n={}){let e=new Hi(n);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}K();function pa(n){try{if(n&&typeof n.keys=="function")return Array.from(n.keys())}catch{}return[]}function lo(n){var e;return n?((e=n.getDisplayObject)==null?void 0:e.call(n))||n.pixiObject||n:null}function Ks(n,e){if(!n||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);n.eventMode=i?"static":"none",n.interactive=i,i&&(n.cursor=t.draggable?"move":"pointer")}function co(n,e){var l,c,p;if(!n||!e)return;let t=e.transform||{};Ks(n,e);let i=t.position||{},a=t.offset||{},r=(typeof i.x=="number"?i.x:0)+(typeof a.x=="number"?a.x:0),o=(typeof i.y=="number"?i.y:0)+(typeof a.y=="number"?a.y:0);(l=n.position)!=null&&l.set?n.position.set(r,o):(typeof n.x=="number"&&(n.x=r),typeof n.y=="number"&&(n.y=o)),typeof t.scale=="number"&&((c=n.scale)!=null&&c.set?n.scale.set(t.scale):n.scale&&(n.scale.x=t.scale,n.scale.y=t.scale));let s=t.anchor;if(s&&((p=n.anchor)!=null&&p.set)){let d=null;typeof window!="undefined"&&window.resolveAnchorVec2?d=window.resolveAnchorVec2(s):typeof s=="object"&&s.x!==void 0&&s.y!==void 0?d=s:Array.isArray(s)&&s.length===2&&(d={x:s[0],y:s[1]}),d&&typeof d.x=="number"&&typeof d.y=="number"&&n.anchor.set(d.x,d.y)}}function po(n){if(typeof window=="undefined")return;let e=n==null?void 0:n.objects,t=pa(e),i=r=>{try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let s=window.__HANDLER_SCREEN_INDEX,l=s==null?void 0:s.instanceToScreen;return l?r.filter(c=>l[c]===o):r}catch{return r}};window.__editableObjectConfigs=e;let a=new Map;t.forEach(r=>a.set(r,[r])),window.__editableObjectInstances=a,window.refreshEditableConfigIndex=()=>po(window.__editableConfig),window.getEditableObjectList=()=>{var r;return i(pa((r=window.__editableConfig)==null?void 0:r.objects))},window.getEditableObjectListAll=()=>{var r;return pa((r=window.__editableConfig)==null?void 0:r.objects)},window.getEditableObjectConfig=r=>{var p,d,u,g,m;let o=(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,s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return o;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[r];return c&&c===s?o: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 o={...r.engine,objects:r.objects,scene:r.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(o.assets||{})),o}return r}}function Xs(){if(typeof window=="undefined")return;let n=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var r,o,s;let a=n(i);if(a)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Ke(),sr))]),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 m=window.gameObjectManager,h=(o=m==null?void 0:m.get)==null?void 0:o.call(m,t);if(h){let f=((s=h.getDisplayObject)==null?void 0:s.call(h))||h.pixiObject||h.pixi||h;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let a=[];if(t.runtime)for(let[r,o]of Object.entries(t.runtime))a.push({path:`runtime.${r}`,value:o});if(t.assets)for(let[r,o]of Object.entries(t.assets))a.push({path:`assets.${r}`,value:o}),typeof o=="string"&&e(r,o);if(t.splash)for(let[r,o]of Object.entries(t.splash))a.push({path:`splash.${r}`,value:o});if(t.loading)for(let[r,o]of Object.entries(t.loading))a.push({path:`loading.${r}`,value:o});if(t.start)for(let[r,o]of Object.entries(t.start))a.push({path:`start.${r}`,value:o});a.length&&Ce(a,{silent:!0,persist:!0,emitEvent:!0})}}function Bi(n){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=n;t&&(t.onObjectRebuildRequired=async(r,o)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${r} due to type change...`);let s=t.get(r),l=s==null?void 0:s.pixiObject,c=l==null?void 0:l.parent,p=c==null?void 0:c.children.indexOf(l);s?t.remove(r):l&&l.destroy();let d=window.gameApp,u=await Ae.create(r,o,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"&&(Xs(),window.applyEditableObjectConfig=(r,o)=>{var s,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",r);try{let p=window.__editableConfig;(s=p==null?void 0:p.objects)!=null&&s.set&&(p.objects.set(r,o),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(o);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=lo(d);co(u,o)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let a={async applyObjectConfig(r,o){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",r);let s=e();(p=s==null?void 0:s.objects)!=null&&p.set&&(s.objects.set(r,o),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(o);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=lo(l);co(u,o)}let c=[r];i==null||i(r,o,c)},rebuildIndexes(){let r=e();typeof window!="undefined"&&(window.__editableConfig=r,po(r))}};return a.rebuildIndexes(),a}K();var ho=qe(require("lottie-web"),1);sn(rn);typeof window!="undefined"&&!window.lottie&&(window.lottie=ho.default);var nt=null,Js=async()=>{if(!nt){let n=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(n==null?void 0:n["handler.config"])||(n==null?void 0:n["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);nt=JSON.parse(i)}else nt=JSON.parse(e);return nt}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}nt=await(await fetch("./handler.config.json")).json()}return nt},fa,jt,fo,at,ga,ha;function Zs(n){fa=n.initGame,jt=n.CustomAssets,fo=n.updateScreenState,at=n.globalResponsiveMultipliers,ga=n.layout,ha=n.clearResponsiveElements}var Fi="web_embed",It="https://example.com",uo={profile_id:Fi},_e=null,le=null,ua={width:0,height:0},Qs=!0,el=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let n=await Js();uo={...n.ids||{},profile_id:Fi},It=n.destination_url||((p=(c=n.export_profiles)==null?void 0:c[Fi])==null?void 0:p.destination_url)||It,Oe.init({ids:uo,profile:Fi,destinationUrl:It});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),le=da({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),go()},onRefresh:go});let g=le.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",m=>{var v,x,w,E,C,A,M,B,P,L,I;let h=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=m.detail;if(ua.width=b,ua.height=y,fo(b,y),!(!h||!h.renderer)){f&&s(h,f);try{h.renderer.resize(b,y);let O=h.view;O&&(O.style.width="100%",O.style.height="100%",O.style.display="block")}catch(O){console.warn("[SCREEN] Error resizing renderer:",O);return}if(t&&f&&ga)try{let O=(v=window.__mainContainer)!=null?v:h.stage,D=(M=(A=(E=window.__tutorialLabel)!=null?E:(w=(x=f.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:w.call(x))!=null?A:(C=f.get("label_1"))==null?void 0:C.pixiObject)!=null?M:f.get("label_1"),j=f.get("background_1"),$=(I=(L=(P=window.__background)!=null?P:(B=j==null?void 0:j.getDisplayObject)==null?void 0:B.call(j))!=null?L:j==null?void 0:j.pixiObject)!=null?I:j;if(O){let S=O===h.stage;ga({mainContainer:O,label:D,background:$,backgroundTexture:($==null?void 0:$.texture)||null,app:h},t,0,ua,f,{skipMainContainerTransform:S})}}catch(O){console.warn("[SCREEN] Error in layout:",O)}}})}let t=await be("scene.main");window.__editableConfig=t,o(),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 be("scene.main"));let i=await fa(e,t,It,le);_e=i.app;let a=i.gameObjectManager;window.gameApp=_e,window.gameObjectManager=a;try{window.__liveEditBridge=Bi({getConfig:()=>window.__editableConfig,gameObjectManager:a,assets:jt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}le&&le.notifyGameLoaded();let r=window.__debugScale;r&&typeof r=="number"&&(at.scale=r,console.log(`[DEBUG] Applied persisted debug scale: ${r}`)),s(_e,a);async function o(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let w=await x.text();try{return JSON.parse(w)}catch{return null}},m=await g("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let h=m.screens;if(!h||typeof h!="object")return;let f={},b={};for(let[y,v]of Object.entries(h)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let w=await g(x),E=w==null?void 0:w.elements;if(!Array.isArray(E))continue;let C=E.map(A=>A==null?void 0:A.instance_id).filter(A=>typeof A=="string");f[y]=C;for(let A of C)b[A]||(b[A]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function s(g,m){if(Qs){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${at.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,w)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let E=x.scale.x||1,C=x.scale.y||1;x.__originalScale||(x.__originalScale={x:E,y:C},console.log(`${v}[RESPONSIVE] Stored original scale for child[${w}]: ${E.toFixed(3)}, ${C.toFixed(3)}`));let A=x.__originalScale.x*at.scale,M=x.__originalScale.y*at.scale;typeof x.scale.set=="function"?x.scale.set(A,M):(x.scale.x=A,x.scale.y=M),console.log(`${v}[RESPONSIVE] Child[${w}] scale: ${E.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),f(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${w}] has no scale (type: ${x.constructor.name})`)})};var h=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){at.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let m=window.gameApp,h=window.gameObjectManager;m&&h?(s(m,h),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},go=async()=>{var e,t,i,a;console.log("[PREVIEW] Restarting game in 1 seconds...");let n=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(n){let r=((t=n.getDisplayObject)==null?void 0:t.call(n))||n;r&&r.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=r.scale.x)!=null?i:1).toFixed(3)}, y: ${((a=r.scale.y)!=null?a:1).toFixed(3)}`)}if(le){le.notifyGameDestroyed();try{ha&&ha()}catch(r){console.warn("Failed to clear responsive elements",r)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let r=le.getGameContainer(),o=window.gameObjectManager;if(o&&typeof o.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),o.clear()),_e){try{_e.destroy(!0,{children:!0,texture:!1})}catch(s){console.warn("[PREVIEW] Destroy warning:",s)}_e=null}window.gameApp=null,window.gameObjectManager=null,r&&(r.innerHTML="");try{typeof jt.resetScene=="function"&&jt.resetScene()}catch(s){console.warn("Asset reset failed",s)}setTimeout(()=>{be("scene.main").then(s=>{window.__editableConfig=s,window.__editableConfigBaseline||(window.__editableConfigBaseline=G(s)),fa(r,s,It).then(l=>{_e=l.app,window.gameApp=_e,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Bi({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:jt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}le&&le.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};pi();K();var ce={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},mo=1.25,bo={fontFamily:"Inter, system-ui, sans-serif"};var Ui=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=`
1780
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var g,m,h,f,b,y,v,x;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",w=>{if(this.viewMode==="compare")return;let E=w.target.value;this.setDevice(E)});let i=e.querySelector("#theme-select");i==null||i.addEventListener("change",w=>{let E=w.target.value;this.setTheme(E)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.viewToggle;E&&this.setViewMode(E)})}),Array.from(e.querySelectorAll("[data-layout-toggle]")).forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.layoutToggle;E&&this.setLayoutMode(E)})}),(g=e.querySelector("#rotate-btn"))==null||g.addEventListener("click",()=>this.toggleRotation()),(m=e.querySelector("#zoom-in-btn"))==null||m.addEventListener("click",()=>this.adjustUserZoom(.1)),(h=e.querySelector("#zoom-out-btn"))==null||h.addEventListener("click",()=>this.adjustUserZoom(-.1)),(f=e.querySelector("#refresh-btn"))==null||f.addEventListener("click",()=>this.refresh());let o=e.querySelector("#bottom-dock"),s=e.querySelector("#bottom-dock-resize");o&&s&&this.makeBottomDockResizable(o,s);let l=Array.from(e.querySelectorAll(".bottom-dock-tab"));l.forEach(w=>{w.addEventListener("click",()=>{let E=w.dataset.dockTab;if(!E)return;l.forEach(S=>S.classList.remove("active")),w.classList.add("active"),Array.from(e.querySelectorAll(".bottom-dock-panel")).forEach(S=>{let P=S.dataset.dockPanel;S.classList.toggle("active",P===E)})})}),(b=e.querySelector("#console-clear"))==null||b.addEventListener("click",()=>this.clearConsole()),(y=e.querySelector("#corner-zoom-in-btn"))==null||y.addEventListener("click",()=>this.adjustUserZoom(.1)),(v=e.querySelector("#corner-zoom-out-btn"))==null||v.addEventListener("click",()=>this.adjustUserZoom(-.1)),(x=e.querySelector("#corner-grab-btn"))==null||x.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)});let c=e.querySelector(".scene-panel.scene-objects"),p=c==null?void 0:c.querySelector("[data-panel-resize-v]");c&&p&&this.makeSidebarResizable(c,p,"left");let d=e.querySelector(".debug-workbench"),u=d==null?void 0:d.querySelector("#workbench-resize-v");d&&u&&this.makeSidebarResizable(d,u,"right")}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"var(--ui-shadow-strong)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,i=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=i,this.gameContainer.style.width=t,this.gameContainer.style.height=i,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=i,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=i,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),i=this.getFitBounds(),n=Math.max(0,i.width),r=Math.max(0,i.height);if(n<=0||r<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let o=n/t.width,s=r/t.height;if(this.autoScale=Math.max(.01,Math.min(o,s)),!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(),requestAnimationFrame(()=>this.updatePanelPositions()),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`),requestAnimationFrame(()=>this.updatePanelPositions())}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`,requestAnimationFrame(()=>this.updatePanelPositions())}updatePanelPositions(){if(!this.gameReady||this.viewMode==="compare")return;let e=this.container.querySelector('[data-panel="scene-tools-corner"]'),t=this.container.querySelector('[data-panel="nudge-panel"]');if(this.layoutMode==="fixed"){let i=this.container.querySelector(".preview-container");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}else{let i=this.container.querySelector(".preview-main");i&&(e&&e.parentElement!==i&&i.appendChild(e),t&&t.parentElement!==i&&i.appendChild(t))}e&&(e.style.zIndex="100"),t&&(t.style.position="absolute",t.style.left="50%",t.style.top="16px",t.style.transform="translateX(calc(-50% + 200px))",t.style.zIndex="100")}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,i;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(i=(t=this.options).onDeviceChange)==null||i.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let i=window.gameApp;if(!(i!=null&&i.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var i;let t=new WeakSet;try{return JSON.stringify(e,(n,r)=>{if(typeof r=="object"&&r!==null){if(t.has(r))return"[Circular]";t.add(r)}return r},2)}catch{try{if(e&&((i=e.constructor)!=null&&i.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=(t,...i)=>{let n=i.map(o=>typeof o=="object"?this.safeStringify(o):String(o)).join(" ");this.consoleMessages.push({type:t,message:n,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let r=this.container.querySelector("#console-badge");if(r){let o=this.consoleMessages.filter(s=>s.type==="error").length;r.textContent=o>0?`${o}!`:"0",r.classList.toggle("has-errors",o>0)}};console.log=(...t)=>{this.originalConsole.log(...t),e("log",...t)},console.warn=(...t)=>{this.originalConsole.warn(...t),e("warn",...t)},console.error=(...t)=>{this.originalConsole.error(...t),e("error",...t)},console.info=(...t)=>{this.originalConsole.info(...t),e("info",...t)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let i=document.createElement("div");i.className=`console-msg type-${e.type}`;let n=e.timestamp.toLocaleTimeString();i.innerHTML=`<span class="time">${this.escapeHtml(n)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(i),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;if(this.layoutMode==="fixed"){let i=this.container.querySelector('[data-dock-tab="console"]');if(i){i.click();let n=this.container.querySelector("#bottom-dock");n==null||n.classList.remove("hidden")}return}this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let i=t.dataset.viewport;if(!i)return;let n=this.comparePresets.find(d=>d.id===i);if(!n)return;let r=t.querySelector("[data-compare-slot]"),o=t.querySelector("[data-compare-ghost]"),s=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),p=t.querySelector("[data-compare-focus]");!r||!o||!s||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(i);return}t.classList.contains("is-active")||this.activateCompareViewport(i)}),this.compareViewports.set(i,{preset:n,root:t,slot:r,ghost:o,wrapper:s,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 i=this.container.querySelector("#rotate-btn");if(i&&(i.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,o;let t=this.compareViewports.get(e);if(!t)return;let i=this.autoScale*this.userScaleMultiplier,n=this.activeCompareId;n&&n!==e&&this.captureCompareSnapshot(n),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((s,l)=>{s.root.classList.toggle("is-active",l===e),s.ghost.classList.toggle("hidden",l===e),s.focus&&(s.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:i}),(o=(r=this.options).onDeviceChange)==null||o.call(r,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,i=`${t.width}px`,n=`${t.height}px`;e.frame.style.width=i,e.frame.style.height=n,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let i=Math.max(0,t.clientWidth-24),n=Math.max(0,t.clientHeight-24);if(i<=0||n<=0)return;let r=i/e.preset.width,o=n/e.preset.height,s=Math.max(.01,Math.min(r,o));e.wrapper.style.transform=`scale(${s})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let i=this.gameContainer.querySelector("canvas");if(!i)return;let n=t.canvas.getContext("2d");if(!n)return;let r=t.canvas.width,o=t.canvas.height,s=Math.min(r/i.width,o/i.height),l=i.width*s,c=i.height*s,p=(r-l)/2,d=(o-c)/2;n.clearRect(0,0,r,o),n.drawImage(i,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 ua(a={}){let e=new Bi(a);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}K();function ga(a){try{if(a&&typeof a.keys=="function")return Array.from(a.keys())}catch{}return[]}function uo(a){var e;return a?((e=a.getDisplayObject)==null?void 0:e.call(a))||a.pixiObject||a:null}function tl(a,e){if(!a||!(e!=null&&e.interaction))return;let t=e.interaction,i=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);a.eventMode=i?"static":"none",a.interactive=i,i&&(a.cursor=t.draggable?"move":"pointer")}function go(a,e){var l,c,p;if(!a||!e)return;let t=e.transform||{};tl(a,e);let i=t.position||{},n=t.offset||{},r=(typeof i.x=="number"?i.x:0)+(typeof n.x=="number"?n.x:0),o=(typeof i.y=="number"?i.y:0)+(typeof n.y=="number"?n.y:0);(l=a.position)!=null&&l.set?a.position.set(r,o):(typeof a.x=="number"&&(a.x=r),typeof a.y=="number"&&(a.y=o)),typeof t.scale=="number"&&((c=a.scale)!=null&&c.set?a.scale.set(t.scale):a.scale&&(a.scale.x=t.scale,a.scale.y=t.scale));let s=t.anchor;if(s&&((p=a.anchor)!=null&&p.set)){let d=null;typeof window!="undefined"&&window.resolveAnchorVec2?d=window.resolveAnchorVec2(s):typeof s=="object"&&s.x!==void 0&&s.y!==void 0?d=s:Array.isArray(s)&&s.length===2&&(d={x:s[0],y:s[1]}),d&&typeof d.x=="number"&&typeof d.y=="number"&&a.anchor.set(d.x,d.y)}}function ho(a){if(typeof window=="undefined")return;let e=a==null?void 0:a.objects,t=ga(e),i=r=>{try{let o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let s=window.__HANDLER_SCREEN_INDEX,l=s==null?void 0:s.instanceToScreen;return l?r.filter(c=>l[c]===o):r}catch{return r}};window.__editableObjectConfigs=e;let n=new Map;t.forEach(r=>n.set(r,[r])),window.__editableObjectInstances=n,window.refreshEditableConfigIndex=()=>ho(window.__editableConfig),window.getEditableObjectList=()=>{var r;return i(ga((r=window.__editableConfig)==null?void 0:r.objects))},window.getEditableObjectListAll=()=>{var r;return ga((r=window.__editableConfig)==null?void 0:r.objects)},window.getEditableObjectConfig=r=>{var p,d,u,g,m;let o=(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,s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return o;let l=window.__HANDLER_SCREEN_INDEX,c=(m=l==null?void 0:l.instanceToScreen)==null?void 0:m[r];return c&&c===s?o: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 o={...r.engine,objects:r.objects,scene:r.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(o.assets||{})),o}return r}}function il(){if(typeof window=="undefined")return;let a=t=>{let i=String(t||"").trim();return i?/^(data:|blob:|https?:)/.test(i)||i.startsWith("/")?i:`/${i.replace(/^\.\//,"")}`:""},e=async(t,i)=>{var r,o,s;let n=a(i);if(n)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Ke(),cr))]),p=Date.now(),d=/^(data:|blob:)/.test(n)?n:n+(n.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 m=window.gameObjectManager,h=(o=m==null?void 0:m.get)==null?void 0:o.call(m,t);if(h){let f=((s=h.getDisplayObject)==null?void 0:s.call(h))||h.pixiObject||h.pixi||h;if(f!=null&&f.texture)f.texture=u;else if(f!=null&&f.children){let b=f.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let i=Y();Array.isArray(i)&&i.length&&(window.__editableConfig=t,Ce(i,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let i=window.__editableConfig;if(!(i!=null&&i.engine))return;let n=[];if(t.runtime)for(let[r,o]of Object.entries(t.runtime))n.push({path:`runtime.${r}`,value:o});if(t.assets)for(let[r,o]of Object.entries(t.assets))n.push({path:`assets.${r}`,value:o}),typeof o=="string"&&e(r,o);if(t.splash)for(let[r,o]of Object.entries(t.splash))n.push({path:`splash.${r}`,value:o});if(t.loading)for(let[r,o]of Object.entries(t.loading))n.push({path:`loading.${r}`,value:o});if(t.start)for(let[r,o]of Object.entries(t.start))n.push({path:`start.${r}`,value:o});n.length&&Ce(n,{silent:!0,persist:!0,emitEvent:!0})}}function Ui(a){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:i}=a;t&&(t.onObjectRebuildRequired=async(r,o)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${r} due to type change...`);let s=t.get(r),l=s==null?void 0:s.pixiObject,c=l==null?void 0:l.parent,p=c==null?void 0:c.children.indexOf(l);s?t.remove(r):l&&l.destroy();let d=window.gameApp,u=await Se.create(r,o,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"&&(il(),window.applyEditableObjectConfig=(r,o)=>{var s,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",r);try{let p=window.__editableConfig;(s=p==null?void 0:p.objects)!=null&&s.set&&(p.objects.set(r,o),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(o);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=uo(d);go(u,o)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let n={async applyObjectConfig(r,o){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",r);let s=e();(p=s==null?void 0:s.objects)!=null&&p.set&&(s.objects.set(r,o),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(o);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=uo(l);go(u,o)}let c=[r];i==null||i(r,o,c)},rebuildIndexes(){let r=e();typeof window!="undefined"&&(window.__editableConfig=r,ho(r))}};return n.rebuildIndexes(),n}K();var bo=qe(require("lottie-web"),1);cn(sn);typeof window!="undefined"&&!window.lottie&&(window.lottie=bo.default);var nt=null,nl=async()=>{if(!nt){let a=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(a==null?void 0:a["handler.config"])||(a==null?void 0:a["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let i=atob(e.split(",")[1]);nt=JSON.parse(i)}else nt=JSON.parse(e);return nt}catch(i){console.warn("[CONFIG] Failed to parse inline handler.config.json:",i)}nt=await(await fetch("./handler.config.json")).json()}return nt},ba,jt,yo,at,fa,ma;function al(a){ba=a.initGame,jt=a.CustomAssets,yo=a.updateScreenState,at=a.globalResponsiveMultipliers,fa=a.layout,ma=a.clearResponsiveElements}var Gi="web_embed",It="https://example.com",fo={profile_id:Gi},_e=null,le=null,ha={width:0,height:0},rl=!0,ol=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let a=await nl();fo={...a.ids||{},profile_id:Gi},It=a.destination_url||((p=(c=a.export_profiles)==null?void 0:c[Gi])==null?void 0:p.destination_url)||It,Oe.init({ids:fo,profile:Gi,destinationUrl:It});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),le=ua({onDeviceChange:m=>{console.log(`[PREVIEW] Device switched to ${m.width}x${m.height}, restarting game...`),mo()},onRefresh:mo});let g=le.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",m=>{var v,x,w,E,C,S,P,F,M,T,I;let h=window.gameApp,f=window.gameObjectManager,{width:b,height:y}=m.detail;if(ha.width=b,ha.height=y,yo(b,y),!(!h||!h.renderer)){f&&s(h,f);try{h.renderer.resize(b,y);let O=h.view;O&&(O.style.width="100%",O.style.height="100%",O.style.display="block")}catch(O){console.warn("[SCREEN] Error resizing renderer:",O);return}if(t&&f&&fa)try{let O=(v=window.__mainContainer)!=null?v:h.stage,z=(P=(S=(E=window.__tutorialLabel)!=null?E:(w=(x=f.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:w.call(x))!=null?S:(C=f.get("label_1"))==null?void 0:C.pixiObject)!=null?P:f.get("label_1"),j=f.get("background_1"),D=(I=(T=(M=window.__background)!=null?M:(F=j==null?void 0:j.getDisplayObject)==null?void 0:F.call(j))!=null?T:j==null?void 0:j.pixiObject)!=null?I:j;if(O){let A=O===h.stage;fa({mainContainer:O,label:z,background:D,backgroundTexture:(D==null?void 0:D.texture)||null,app:h},t,0,ha,f,{skipMainContainerTransform:A})}}catch(O){console.warn("[SCREEN] Error in layout:",O)}}})}let t=await be("scene.main");window.__editableConfig=t,o(),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 be("scene.main"));let i=await ba(e,t,It,le);_e=i.app;let n=i.gameObjectManager;window.gameApp=_e,window.gameObjectManager=n;try{window.__liveEditBridge=Ui({getConfig:()=>window.__editableConfig,gameObjectManager:n,assets:jt})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}le&&le.notifyGameLoaded();let r=window.__debugScale;r&&typeof r=="number"&&(at.scale=r,console.log(`[DEBUG] Applied persisted debug scale: ${r}`)),s(_e,n);async function o(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let w=await x.text();try{return JSON.parse(w)}catch{return null}},m=await g("configs/flow/app.flow.json");if(!m||typeof m!="object")return;let h=m.screens;if(!h||typeof h!="object")return;let f={},b={};for(let[y,v]of Object.entries(h)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let w=await g(x),E=w==null?void 0:w.elements;if(!Array.isArray(E))continue;let C=E.map(S=>S==null?void 0:S.instance_id).filter(S=>typeof S=="string");f[y]=C;for(let S of C)b[S]||(b[S]=y)}window.__HANDLER_APP_FLOW=m,window.__HANDLER_SCREEN_INDEX={screenToInstances:f,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function s(g,m){if(rl){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${at.scale.toFixed(3)}`),g.stage){let f=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,w)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let E=x.scale.x||1,C=x.scale.y||1;x.__originalScale||(x.__originalScale={x:E,y:C},console.log(`${v}[RESPONSIVE] Stored original scale for child[${w}]: ${E.toFixed(3)}, ${C.toFixed(3)}`));let S=x.__originalScale.x*at.scale,P=x.__originalScale.y*at.scale;typeof x.scale.set=="function"?x.scale.set(S,P):(x.scale.x=S,x.scale.y=P),console.log(`${v}[RESPONSIVE] Child[${w}] scale: ${E.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),f(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${w}] has no scale (type: ${x.constructor.name})`)})};var h=f;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),f(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){at.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let m=window.gameApp,h=window.gameObjectManager;m&&h?(s(m,h),m.renderer&&(m.renderer.render(m.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!m}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},mo=async()=>{var e,t,i,n;console.log("[PREVIEW] Restarting game in 1 seconds...");let a=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(a){let r=((t=a.getDisplayObject)==null?void 0:t.call(a))||a;r&&r.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((i=r.scale.x)!=null?i:1).toFixed(3)}, y: ${((n=r.scale.y)!=null?n:1).toFixed(3)}`)}if(le){le.notifyGameDestroyed();try{ma&&ma()}catch(r){console.warn("Failed to clear responsive elements",r)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let r=le.getGameContainer(),o=window.gameObjectManager;if(o&&typeof o.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),o.clear()),_e){try{_e.destroy(!0,{children:!0,texture:!1})}catch(s){console.warn("[PREVIEW] Destroy warning:",s)}_e=null}window.gameApp=null,window.gameObjectManager=null,r&&(r.innerHTML="");try{typeof jt.resetScene=="function"&&jt.resetScene()}catch(s){console.warn("Asset reset failed",s)}setTimeout(()=>{be("scene.main").then(s=>{window.__editableConfig=s,window.__editableConfigBaseline||(window.__editableConfigBaseline=G(s)),ba(r,s,It).then(l=>{_e=l.app,window.gameApp=_e,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Ui({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:jt})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}le&&le.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};pi();K();var ce={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},vo=1.25,xo={fontFamily:"Inter, system-ui, sans-serif"};var qi=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=`
1515
1781
  position: fixed;
1516
1782
  inset: 0;
1517
1783
  display: flex;
@@ -1534,7 +1800,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1534
1800
  height: 96px;
1535
1801
  opacity: 0.9;
1536
1802
  transform: scale(0.9);
1537
- `,i.innerHTML='<div class="boxLoading"></div>',t.appendChild(i);let a=document.createElement("div");a.style.cssText=`
1803
+ `,i.innerHTML='<div class="boxLoading"></div>',t.appendChild(i);let n=document.createElement("div");n.style.cssText=`
1538
1804
  width: 100%;
1539
1805
  position: relative;
1540
1806
  display: flex;
@@ -1590,7 +1856,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1590
1856
  width: 1.5px;
1591
1857
  background-color: black;
1592
1858
  height: ${u%4===0?"6px":"2px"};
1593
- `,c.appendChild(g)}a.appendChild(r),a.appendChild(s),a.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
1859
+ `,c.appendChild(g)}n.appendChild(r),n.appendChild(s),n.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
1594
1860
  position: absolute;
1595
1861
  top: 48px;
1596
1862
  width: 600px;
@@ -1614,7 +1880,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1614
1880
  align-items: center;
1615
1881
  justify-content: center;
1616
1882
  animation-delay: ${[1.05,.875,.7,.525,.35,.175,0][g]}s;
1617
- `,p.appendChild(m)}),t.appendChild(a),t.appendChild(p),this.authSeq=document.createElement("div"),this.authSeq.style.cssText=`
1883
+ `,p.appendChild(m)}),t.appendChild(n),t.appendChild(p),this.authSeq=document.createElement("div"),this.authSeq.style.cssText=`
1618
1884
  position: absolute;
1619
1885
  bottom: 48px;
1620
1886
  font-size: 8px;
@@ -1710,7 +1976,7 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1710
1976
  0%, 100% { opacity: 1; }
1711
1977
  50% { opacity: 0.3; }
1712
1978
  }
1713
- `,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 ma=$a.version,tl=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"]);Da();var So={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"},Co=Math.random().toString(36).slice(2),st=null,rt={...So},Lo="web_embed",xa={},Dt,ba=!1,Rt=!1,zt=!1,To=!1,Sa=1,qi=0,Yi=!1,ve=!1,ot="",lt=Math.floor(window.innerWidth),ct=Math.floor(window.innerHeight),wa=lt>ct,xe=!1,$t=!1,yo=!1,vo=!1,ya=!1,Vi=null,Be=null,Ea=!1,Aa=!1,Gi=new Map;function ko(){if(!Be)return null;let n=Date.now()-Be;return!Number.isFinite(n)||n<0?null:n}function va(n){if(Ea)return;let e=ko();e!==null&&(Ea=!0,T("session_time",{duration_ms:e,reason:n}))}function xo(){if(st)return st;let n=document.createElement("div");return n.id="handler-root",n.setAttribute("data-handler-root","true"),document.body.appendChild(n),st=n,n}function Wi(n){switch(n){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return n}}function _o(n,e){return{event_name:n,ts:Date.now(),session_id:Co,deployment_id:rt.deployment_id,variant_id:rt.variant_id,export_profile_id:rt.profile_id,instance_id:rt.instance_id||"default",env:Lo==="mraid"?"mraid":"web",attribution:Dt,payload:e}}function T(n,e){let t=Wi(n),i=_o(t,e);tn(i,!!xa.analytics),Gt(t,i),t!==n&&Gt(n,i)}function Nt(){Vi&&(Vi(lt,ct),Vi=null)}function dt(n){Sa=n,T("volume",n)}function pt(n){n&&(To=!0),!zt&&(zt=!0,T("pause"),dt(0))}function Ht(n){!n&&To||zt&&(zt=!1,T("resume"),dt(Sa))}function Pe(n,e){lt=Math.floor(n||window.innerWidth),ct=Math.floor(e||window.innerHeight),wa=lt>ct,T("resize",{width:lt,height:ct})}function il(){if(Ka())try{let n=mraid.getMaxSize();Pe(n.width,n.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Ht():pt()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Pe(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();dt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&dt(t>0?1:0)}),mraid.addEventListener("error",(t,i)=>{console.warn("mraid error:",t,"action:",i)}),Yi=!0,mraid.isViewable()&&mraid.getState()!=="hidden")xe=!0,T("boot"),T("view"),T("ready"),ve=!0,Nt();else{let t=()=>{xe=!0,T("boot"),T("view"),T("ready"),ve=!0,Nt()};mraid.addEventListener("ready",t)}}catch(n){console.warn("MRAID hook skipped",n)}}function nl(){if(Xa())try{let n=dapi.getScreenSize();Pe(n.width,n.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?Ht():pt()}),dapi.addEventListener("adResized",t=>{let i=dapi.getScreenSize();Pe(t.width||i.width,t.height||i.height)});let e=dapi.getAudioVolume();if(dt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>dt(t?1:0)),Yi=!0,dapi.isViewable())xe=!0,T("boot"),T("view"),T("ready"),ve=!0,Nt();else{let t=()=>{xe=!0,T("boot"),T("view"),T("ready"),ve=!0,Nt()};dapi.addEventListener("ready",t)}}catch(n){console.warn("DAPI hook skipped",n)}}function wo(){let n=()=>{xe||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(xe=!0,T("boot"),T("view"),T("ready"),ve=!0,Nt(),$t&&($t=!1,ie.start()))};window.addEventListener("resize",()=>Pe()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Ht(),n()):pt()}),document.readyState==="complete"||document.readyState==="interactive"?n():window.addEventListener("load",n),Yi=!0}function al(){let n=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(yo=!0),!(yo&&e instanceof MouseEvent)&&(qi+=1,Aa||(Aa=!0,T("first_interaction",{count:qi})),T("interaction",qi))};document.addEventListener("mousedown",n),document.addEventListener("touchstart",n)}function Eo(n){var i,a,r,o,s,l,c,p,d,u,g,m;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(i=window.ExitApi)==null||i.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(n||"");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(Ja())(s=(o=window.FbPlayableAd)==null?void 0:o.onCTAClick)==null||s.call(o);else if(tr())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(er())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(h){console.warn("Smadex redirect failed",h)}else if(Za()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(n||ot||""):n&&window.open(n)}else We()?(u=window.install)==null||u.call(window):Qa()?(g=window.openAppStore)==null||g.call(window):nn()?(m=parent==null?void 0:parent.postMessage)==null||m.call(parent,"download","*"):n&&window.open(n)}function rl(){let n=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let i=new Image;i.src=t};if(n==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;X("view",()=>e(t.mraid_viewable)),X("start",()=>e(t.game_viewable)),X("engagement",()=>e(t.engagement));let i=()=>e(t.complete);X("complete",i),Ut("engagement",a=>{var r;((r=a==null?void 0:a.payload)==null?void 0:r.count)>3&&i()}),X("cta_click",()=>e(t.click))}else if(n==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;X("view",()=>e(t.Ad_Load_Start)),X("start",()=>e(t.Ad_Viewable)),X("engagement",()=>e(t.First_Engagement)),X("complete",()=>e(t.Gameplay_Complete)),X("cta_click",()=>e(t.DSP_Click)),X("start",()=>{[5,10,15,20,25,30].forEach(i=>setTimeout(()=>e(t[`Spent_${i}_Seconds`]),i*1e3))})}}function ol(){if(!Ye())return;let n=window.TJ_API;n&&n.setPlayableAPI&&n.setPlayableAPI({skipAd:()=>{try{ie.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Ao(){var e,t,i;let n=window.TJ_API;(e=n==null?void 0:n.objectiveComplete)==null||e.call(n),(t=n==null?void 0:n.playableFinished)==null||t.call(n),(i=n==null?void 0:n.gameplayFinished)==null||i.call(n)}function sl(){We()&&(window.mintGameStart=()=>{Ht(!0),Pe()},window.mintGameClose=()=>{pt(!0)})}function ll(){if(!an())return;let n=window.NUC;!n||!n.trigger||(ie.on("cta_click",()=>{var e,t;return(t=(e=n.trigger).convert)==null?void 0:t.call(e,ot)}),ie.on("complete",()=>{var e,t;return(t=(e=n.trigger).tryAgain)==null?void 0:t.call(e)}))}var ie={init(n={},e){var t;if(Lo=n.profile||"web_embed",xa=n.consent||{},rt={...So,...n.ids||{}},st=n.rootEl||st,Dt=void 0,_a((t=n.telemetry)!=null&&t.endpoint?n.telemetry:null),Be=null,Ea=!1,Aa=!1,Gi.clear(),ot=n.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(Vi=e),T("init"),document.body.oncontextmenu=()=>!1,xo(),dl(st),ir(),il(),nl(),!Yi){if(document.readyState==="complete")wo();else if(!vo){vo=!0;let i=()=>{wo(),window.removeEventListener("load",i),document.removeEventListener("DOMContentLoaded",i)};window.addEventListener("load",i),document.addEventListener("DOMContentLoaded",i)}}al(),rl(),ol(),sl(),ll(),console.log(`%c @handler/playable-sdk %c v${ma} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),xe&&!ve&&(T("boot"),T("view"),T("ready"),$t&&($t=!1,ie.start()),ve=!0),ve=xe},getRoot(){return xo()},get version(){return ma},get maxWidth(){return lt},get maxHeight(){return ct},get isLandscape(){return wa},get isReady(){return ve},get isStarted(){return ba},get isPaused(){return zt},get isFinished(){return Rt},get volume(){return Sa},get interactions(){return qi},on(n,e){Ut(Wi(n),e)},off(n,e){en(Wi(n),e)},start(){var n,e;if(!ba){if(!xe){$t=!0;return}if(ba=!0,Be||(Be=Date.now()),T("start"),Pe(),We())pt(),(n=window.gameReady)==null||n.call(window);else if(Ye()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:wa?"landscape":"portrait",buildID:ma})}}},finish(){var n,e;Rt||(Rt=!0,T("complete"),va("complete"),We()?(n=window.gameEnd)==null||n.call(window):nn()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Ye()&&Ao())},install(n){if(!Rt){Rt=!0,Ye()?(Ao(),setTimeout(()=>ie.install(n),300)):(T("complete"),setTimeout(()=>ie.install(n),0));return}ya||(ya=!0,setTimeout(()=>ya=!1,500),T("cta_click"),T("conversion"),va("cta"),Eo(n||ot))},emit(n,e){let t=Wi(n);if(!tl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${n} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let i=_o(t,e);tn(i,!!xa.analytics),Gt(t,i)},gameStart(){ie.start()},gameEnd(){ie.finish()},ctaClick(n,e){T("cta_click",{url:n||ot,manual:!0}),(e==null?void 0:e.open)!==!1&&Eo(n||ot)},ctaShow(n){T("cta_show",n)},ctaDismiss(n){T("cta_dismiss",n)},getGameTimeMs(){return ko()},endSession(n="manual"){va(n)},setAttribution(n){Dt=n},abTest(n,e){if(!n)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(cl(`${Co}:${n}`))%e.length,i=e[t];return Dt={...Dt||{},experiment_id:n},rt.variant_id=i,T("ab_assign",{experiment_id:n,variant_id:i}),i},levelStart(n,e){Be||(Be=Date.now()),T("level_start",{level_id:n,...e})},levelComplete(n,e){T("level_complete",{level_id:n,...e})},levelFail(n,e){T("level_fail",{level_id:n,...e})},checkpoint(n,e){T("checkpoint",{checkpoint_id:n,...e})},reward(n,e){T("reward",{reward_id:n,...e})},tutorialStart(n,e){T("tutorial_start",{step_id:n,...e})},tutorialComplete(n,e){T("tutorial_complete",{step_id:n,...e})},tutorialSkip(n,e){T("tutorial_skip",{step_id:n,...e})},timerStart(n){n&&Gi.set(n,Date.now())},timerEnd(n,e="custom",t){if(!n)return;let i=Gi.get(n);if(!i)return;Gi.delete(n);let a=Date.now()-i;if(!(!Number.isFinite(a)||a<0)){if(e==="custom"){T("engagement",{action:"timer",key:n,duration_ms:a,...t});return}T(e,{key:n,duration_ms:a,...t})}},fps(n,e){T("fps",{value:n,...e})},memory(n,e){T("memory",{bytes:n,...e})},assetLoadStart(n,e){T("asset_load_start",{asset_id:n,...e})},assetLoadComplete(n,e){T("asset_load_complete",{asset_id:n,...e})},reportError(n,e,t){T("error",{code:n,message:e,...t})},retry(){var n,e,t;if(We())(n=window.gameRetry)==null||n.call(window);else if(an()){let i=window.NUC;(t=(e=i==null?void 0:i.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}T("engagement",{action:"retry"})},pause(){pt(!0)},resume(){Ht(!0)},resize(n,e){Pe(n,e)}},Oe=ie;function cl(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function dl(n){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
1979
+ `,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 ya=Ha.version,sl=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"]);$a();var Lo={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"},ko=Math.random().toString(36).slice(2),st=null,rt={...Lo},_o="web_embed",Ea={},zt,va=!1,Rt=!1,$t=!1,Mo=!1,Ta=1,Wi=0,Xi=!1,ve=!1,ot="",lt=Math.floor(window.innerWidth),ct=Math.floor(window.innerHeight),Sa=lt>ct,xe=!1,Dt=!1,wo=!1,Eo=!1,xa=!1,Yi=null,Fe=null,Aa=!1,Ca=!1,Vi=new Map;function Po(){if(!Fe)return null;let a=Date.now()-Fe;return!Number.isFinite(a)||a<0?null:a}function wa(a){if(Aa)return;let e=Po();e!==null&&(Aa=!0,L("session_time",{duration_ms:e,reason:a}))}function So(){if(st)return st;let a=document.createElement("div");return a.id="handler-root",a.setAttribute("data-handler-root","true"),document.body.appendChild(a),st=a,a}function Ki(a){switch(a){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return a}}function Oo(a,e){return{event_name:a,ts:Date.now(),session_id:ko,deployment_id:rt.deployment_id,variant_id:rt.variant_id,export_profile_id:rt.profile_id,instance_id:rt.instance_id||"default",env:_o==="mraid"?"mraid":"web",attribution:zt,payload:e}}function L(a,e){let t=Ki(a),i=Oo(t,e);an(i,!!Ea.analytics),Gt(t,i),t!==a&&Gt(a,i)}function Ht(){Yi&&(Yi(lt,ct),Yi=null)}function dt(a){Ta=a,L("volume",a)}function pt(a){a&&(Mo=!0),!$t&&($t=!0,L("pause"),dt(0))}function Nt(a){!a&&Mo||$t&&($t=!1,L("resume"),dt(Ta))}function Me(a,e){lt=Math.floor(a||window.innerWidth),ct=Math.floor(e||window.innerHeight),Sa=lt>ct,L("resize",{width:lt,height:ct})}function ll(){if(Ja())try{let a=mraid.getMaxSize();Me(a.width,a.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?Nt():pt()};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();dt(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&dt(t>0?1:0)}),mraid.addEventListener("error",(t,i)=>{console.warn("mraid error:",t,"action:",i)}),Xi=!0,mraid.isViewable()&&mraid.getState()!=="hidden")xe=!0,L("boot"),L("view"),L("ready"),ve=!0,Ht();else{let t=()=>{xe=!0,L("boot"),L("view"),L("ready"),ve=!0,Ht()};mraid.addEventListener("ready",t)}}catch(a){console.warn("MRAID hook skipped",a)}}function cl(){if(Za())try{let a=dapi.getScreenSize();Me(a.width,a.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?Nt():pt()}),dapi.addEventListener("adResized",t=>{let i=dapi.getScreenSize();Me(t.width||i.width,t.height||i.height)});let e=dapi.getAudioVolume();if(dt(e?1:0),dapi.addEventListener("audioVolumeChange",t=>dt(t?1:0)),Xi=!0,dapi.isViewable())xe=!0,L("boot"),L("view"),L("ready"),ve=!0,Ht();else{let t=()=>{xe=!0,L("boot"),L("view"),L("ready"),ve=!0,Ht()};dapi.addEventListener("ready",t)}}catch(a){console.warn("DAPI hook skipped",a)}}function Ao(){let a=()=>{xe||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(xe=!0,L("boot"),L("view"),L("ready"),ve=!0,Ht(),Dt&&(Dt=!1,ie.start()))};window.addEventListener("resize",()=>Me()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(Nt(),a()):pt()}),document.readyState==="complete"||document.readyState==="interactive"?a():window.addEventListener("load",a),Xi=!0}function dl(){let a=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(wo=!0),!(wo&&e instanceof MouseEvent)&&(Wi+=1,Ca||(Ca=!0,L("first_interaction",{count:Wi})),L("interaction",Wi))};document.addEventListener("mousedown",a),document.addEventListener("touchstart",a)}function Co(a){var i,n,r,o,s,l,c,p,d,u,g,m;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(i=window.ExitApi)==null||i.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(a||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Ye())(r=(n=window.TJ_API)==null?void 0:n.click)==null||r.call(n);else if(Qa())(s=(o=window.FbPlayableAd)==null?void 0:o.onCTAClick)==null||s.call(o);else if(nr())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(ir())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(h){console.warn("Smadex redirect failed",h)}else if(er()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(a||ot||""):a&&window.open(a)}else We()?(u=window.install)==null||u.call(window):tr()?(g=window.openAppStore)==null||g.call(window):rn()?(m=parent==null?void 0:parent.postMessage)==null||m.call(parent,"download","*"):a&&window.open(a)}function pl(){let a=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let i=new Image;i.src=t};if(a==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;X("view",()=>e(t.mraid_viewable)),X("start",()=>e(t.game_viewable)),X("engagement",()=>e(t.engagement));let i=()=>e(t.complete);X("complete",i),Ut("engagement",n=>{var r;((r=n==null?void 0:n.payload)==null?void 0:r.count)>3&&i()}),X("cta_click",()=>e(t.click))}else if(a==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;X("view",()=>e(t.Ad_Load_Start)),X("start",()=>e(t.Ad_Viewable)),X("engagement",()=>e(t.First_Engagement)),X("complete",()=>e(t.Gameplay_Complete)),X("cta_click",()=>e(t.DSP_Click)),X("start",()=>{[5,10,15,20,25,30].forEach(i=>setTimeout(()=>e(t[`Spent_${i}_Seconds`]),i*1e3))})}}function ul(){if(!Ye())return;let a=window.TJ_API;a&&a.setPlayableAPI&&a.setPlayableAPI({skipAd:()=>{try{ie.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function To(){var e,t,i;let a=window.TJ_API;(e=a==null?void 0:a.objectiveComplete)==null||e.call(a),(t=a==null?void 0:a.playableFinished)==null||t.call(a),(i=a==null?void 0:a.gameplayFinished)==null||i.call(a)}function gl(){We()&&(window.mintGameStart=()=>{Nt(!0),Me()},window.mintGameClose=()=>{pt(!0)})}function hl(){if(!on())return;let a=window.NUC;!a||!a.trigger||(ie.on("cta_click",()=>{var e,t;return(t=(e=a.trigger).convert)==null?void 0:t.call(e,ot)}),ie.on("complete",()=>{var e,t;return(t=(e=a.trigger).tryAgain)==null?void 0:t.call(e)}))}var ie={init(a={},e){var t;if(_o=a.profile||"web_embed",Ea=a.consent||{},rt={...Lo,...a.ids||{}},st=a.rootEl||st,zt=void 0,Pa((t=a.telemetry)!=null&&t.endpoint?a.telemetry:null),Fe=null,Aa=!1,Ca=!1,Vi.clear(),ot=a.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(Yi=e),L("init"),document.body.oncontextmenu=()=>!1,So(),ml(st),ar(),ll(),cl(),!Xi){if(document.readyState==="complete")Ao();else if(!Eo){Eo=!0;let i=()=>{Ao(),window.removeEventListener("load",i),document.removeEventListener("DOMContentLoaded",i)};window.addEventListener("load",i),document.addEventListener("DOMContentLoaded",i)}}dl(),pl(),ul(),gl(),hl(),console.log(`%c @handler/playable-sdk %c v${ya} `,"background: var(--ui-console-info); color: var(--ui-white); font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: var(--ui-console-bg); color: var(--ui-console-text); font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),xe&&!ve&&(L("boot"),L("view"),L("ready"),Dt&&(Dt=!1,ie.start()),ve=!0),ve=xe},getRoot(){return So()},get version(){return ya},get maxWidth(){return lt},get maxHeight(){return ct},get isLandscape(){return Sa},get isReady(){return ve},get isStarted(){return va},get isPaused(){return $t},get isFinished(){return Rt},get volume(){return Ta},get interactions(){return Wi},on(a,e){Ut(Ki(a),e)},off(a,e){nn(Ki(a),e)},start(){var a,e;if(!va){if(!xe){Dt=!0;return}if(va=!0,Fe||(Fe=Date.now()),L("start"),Me(),We())pt(),(a=window.gameReady)==null||a.call(window);else if(Ye()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:Sa?"landscape":"portrait",buildID:ya})}}},finish(){var a,e;Rt||(Rt=!0,L("complete"),wa("complete"),We()?(a=window.gameEnd)==null||a.call(window):rn()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Ye()&&To())},install(a){if(!Rt){Rt=!0,Ye()?(To(),setTimeout(()=>ie.install(a),300)):(L("complete"),setTimeout(()=>ie.install(a),0));return}xa||(xa=!0,setTimeout(()=>xa=!1,500),L("cta_click"),L("conversion"),wa("cta"),Co(a||ot))},emit(a,e){let t=Ki(a);if(!sl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${a} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let i=Oo(t,e);an(i,!!Ea.analytics),Gt(t,i)},gameStart(){ie.start()},gameEnd(){ie.finish()},ctaClick(a,e){L("cta_click",{url:a||ot,manual:!0}),(e==null?void 0:e.open)!==!1&&Co(a||ot)},ctaShow(a){L("cta_show",a)},ctaDismiss(a){L("cta_dismiss",a)},getGameTimeMs(){return Po()},endSession(a="manual"){wa(a)},setAttribution(a){zt=a},abTest(a,e){if(!a)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(fl(`${ko}:${a}`))%e.length,i=e[t];return zt={...zt||{},experiment_id:a},rt.variant_id=i,L("ab_assign",{experiment_id:a,variant_id:i}),i},levelStart(a,e){Fe||(Fe=Date.now()),L("level_start",{level_id:a,...e})},levelComplete(a,e){L("level_complete",{level_id:a,...e})},levelFail(a,e){L("level_fail",{level_id:a,...e})},checkpoint(a,e){L("checkpoint",{checkpoint_id:a,...e})},reward(a,e){L("reward",{reward_id:a,...e})},tutorialStart(a,e){L("tutorial_start",{step_id:a,...e})},tutorialComplete(a,e){L("tutorial_complete",{step_id:a,...e})},tutorialSkip(a,e){L("tutorial_skip",{step_id:a,...e})},timerStart(a){a&&Vi.set(a,Date.now())},timerEnd(a,e="custom",t){if(!a)return;let i=Vi.get(a);if(!i)return;Vi.delete(a);let n=Date.now()-i;if(!(!Number.isFinite(n)||n<0)){if(e==="custom"){L("engagement",{action:"timer",key:a,duration_ms:n,...t});return}L(e,{key:a,duration_ms:n,...t})}},fps(a,e){L("fps",{value:a,...e})},memory(a,e){L("memory",{bytes:a,...e})},assetLoadStart(a,e){L("asset_load_start",{asset_id:a,...e})},assetLoadComplete(a,e){L("asset_load_complete",{asset_id:a,...e})},reportError(a,e,t){L("error",{code:a,message:e,...t})},retry(){var a,e,t;if(We())(a=window.gameRetry)==null||a.call(window);else if(on()){let i=window.NUC;(t=(e=i==null?void 0:i.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}L("engagement",{action:"retry"})},pause(){pt(!0)},resume(){Nt(!0)},resize(a,e){Me(a,e)}},Oe=ie;function fl(a){let e=2166136261;for(let t=0;t<a.length;t++)e^=a.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function ml(a){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
1714
1980
  (function(){
1715
1981
  var events = ['touchstart','touchend','mousedown','keydown'];
1716
1982
  function unlock(){
@@ -1726,4 +1992,4 @@ Style guidelines: ${i.summary}`;this.promptInput.value=a,this.currentPrompt=a}}c
1726
1992
  }
1727
1993
  events.forEach(function(e){ document.addEventListener(e, unlock, false); });
1728
1994
  })();
1729
- `,n.appendChild(e)}0&&(module.exports={COLORS,ConfigWatcher,DebugPanel,DefaultReloadStrategy,Handler,PlayableLoadingScreen,PreviewShell,STROKE_WIDTH,THEME,applyConfigOverride,applyConfigOverrides,applyConfigsToDisk,applyDefaults,baseLottie,bootstrap,clearConfigOverrides,clearConfigOverridesForObject,configOverrideManager,createPreviewShell,deepClone,defaultPreset,deviceGroups,devicePresets,diffConfigs,exportConfigsAsJSON,getConfigOverrides,getConfigStateSummary,getOverrideMode,getPresetById,getPresetsByCategory,loadAllObjectConfigs,loadComponentSchemas,loadEngineConfig,loadGamePromptConfig,loadObjectCentricConfig,loadObjectConfig,loadSceneConfig,rehydrateObject,removeConfigOverride,resetToApplied,resetToOriginal,setBootstrapDependencies,setOverrideMode,setupHotReload,setupLiveEditBridge,toLegacyFormat,validateObjectConfig});
1995
+ `,a.appendChild(e)}0&&(module.exports={COLORS,ConfigWatcher,DebugPanel,DefaultReloadStrategy,Handler,PlayableLoadingScreen,PreviewShell,STROKE_WIDTH,THEME,applyConfigOverride,applyConfigOverrides,applyConfigsToDisk,applyDefaults,baseLottie,bootstrap,clearConfigOverrides,clearConfigOverridesForObject,configOverrideManager,createPreviewShell,deepClone,defaultPreset,deviceGroups,devicePresets,diffConfigs,exportConfigsAsJSON,getConfigOverrides,getConfigStateSummary,getOverrideMode,getPresetById,getPresetsByCategory,loadAllObjectConfigs,loadComponentSchemas,loadEngineConfig,loadGamePromptConfig,loadObjectCentricConfig,loadObjectConfig,loadSceneConfig,rehydrateObject,removeConfigOverride,resetToApplied,resetToOriginal,setBootstrapDependencies,setOverrideMode,setupHotReload,setupLiveEditBridge,toLegacyFormat,validateObjectConfig});