@joshtol/emotive-engine 3.4.0 โ 3.4.2
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/README.md +81 -530
- package/dist/emotive-mascot-3d-elementals.js +1 -1
- package/dist/emotive-mascot-3d-elementals.umd.js +1 -1
- package/dist/emotive-mascot-3d.js +1 -1
- package/dist/emotive-mascot-3d.umd.js +1 -1
- package/dist/emotive-mascot.lean.js +1 -1
- package/dist/emotive-mascot.lean.umd.js +1 -1
- package/dist/emotive-mascot.minimal.js +1 -1
- package/dist/emotive-mascot.minimal.umd.js +1 -1
- package/dist/emotive-mascot.umd.js +1 -1
- package/dist/mascot.js +1 -1
- package/docs/README.md +263 -0
- package/package.json +4 -5
- /package/{THIRD-PARTY-LICENSES.md โ docs/THIRD-PARTY-LICENSES.md} +0 -0
package/dist/mascot.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
class e{constructor(){this.errors=[],this.maxErrors=10,this.errorCounts=new Map,this.defaults={emotion:"neutral",gesture:null,audioLevel:0,particleCount:0,glowIntensity:.7,coreSize:1,breathRate:1,color:"#B0B0B0"}}wrap(e,t,i=null){return(...s)=>{try{const n=e(...s);return n&&"function"==typeof n.then?n.catch(e=>(this.logError(e,t),null!==i?i:this.getDefault(t))):n}catch(e){return this.logError(e,t),null!==i?i:this.getDefault(t)}}}logError(e,t){const i={timestamp:(new Date).toISOString(),context:t,message:e.message,stack:e.stack};this.errors.push(i);const s=this.errorCounts.get(t)||0;this.errorCounts.set(t,s+1),this.errors.length>this.maxErrors&&this.errors.shift(),s<3?console.warn(`[EmotiveEngine] ${t}:`,e.message):3===s&&console.warn(`[EmotiveEngine] ${t}: Error occurred 3+ times, suppressing further logs`)}getDefault(e){const t={"emotion-transition":this.defaults.emotion,"gesture-execution":this.defaults.gesture,"audio-processing":this.defaults.audioLevel,"particle-system":this.defaults.particleCount,rendering:{glowIntensity:this.defaults.glowIntensity,coreSize:this.defaults.coreSize,color:this.defaults.color},"canvas-operations":null,"state-management":this.defaults.emotion};return{}.hasOwnProperty.call(t,e)?t[e]:null}validateInput(e,t,i){try{switch(t){case"emotion":return["neutral","joy","sadness","anger","fear","surprise","disgust","love","euphoria"].includes(e)?e:i;case"undertone":return null===e||["nervous","confident","tired","intense","subdued"].includes(e)?e:null;case"gesture":return["bounce","pulse","shake","spin","nod","tilt","expand","contract","flash","drift"].includes(e)?e:i;case"number":return"number"!=typeof e||isNaN(e)?i:e;case"string":return"string"==typeof e?e:i;case"boolean":return"boolean"==typeof e?e:i;default:return null!=e?e:i}}catch(e){return this.logError(e,"input-validation"),i}}hasExceededThreshold(e,t=5){return(this.errorCounts.get(e)||0)>=t}getErrorStats(){return{totalErrors:this.errors.length,errorsByContext:Object.fromEntries(this.errorCounts),recentErrors:this.errors.slice(-5)}}clearErrors(){this.errors=[],this.errorCounts.clear()}async attemptRecovery(e,t,i=3){let s=0;for(;s<i;)try{return await t()}catch(t){if(s++,this.logError(t,`recovery-${e}-attempt-${s}`),s>=i)throw new Error(`Recovery failed for ${e} after ${i} attempts`);await new Promise(e=>setTimeout(e,100*Math.pow(2,s)))}}}const t=new Map;var i={registerPluginEmotion:function(e,i){return!!i.color&&(i.name||(i.name=e),i.visual||(i.visual={primaryColor:i.color,particleCount:i.particleCount||15,particleSize:i.particleSize||{min:2,max:6}}),i.modifiers||(i.modifiers={speed:1,amplitude:1,intensity:1}),t.set(e,i),!0)},unregisterPluginEmotion:function(e){return!!t.has(e)&&(t.delete(e),!0)},getPluginEmotion:function(e){return t.get(e)||null},getAllPluginEmotions:function(){return Array.from(t.keys())},clearPluginEmotions:function(){t.clear()},createLegacyAdapter:function(e){return{name:e.name||"unknown",emoji:e.emoji||"๐",color:e.primaryColor||e.color||"#7B68EE",energy:e.energy||"medium",visual:{primaryColor:e.primaryColor||e.color||"#7B68EE",secondaryColor:e.secondaryColor,particleCount:e.particleCount||e.particleRate||15,particleSize:e.particleSize||{min:2,max:6},glowIntensity:e.glowIntensity||.5,trailLength:e.trailLength||5,pulseRate:e.pulseRate||e.breathRate||1},particles:{behavior:e.particleBehavior||"ambient",density:e.particleDensity||"medium",speed:e.particleSpeed||"normal"},modifiers:{speed:e.speedMultiplier||1,amplitude:e.amplitudeMultiplier||1,intensity:e.intensityMultiplier||1,smoothness:e.smoothnessMultiplier||1},gestures:e.gestures||[],transitions:e.transitions||{}}}},s={name:"suspicion",emoji:"๐คจ",description:"Paranoid watchfulness with surveillance scanning",visual:{glowColor:"#6B46C1",particleRate:4,minParticles:6,maxParticles:12,particleBehavior:"surveillance",particleSpeed:.2,breathRate:.6,breathDepth:.04,coreJitter:.02,blinkRate:1.1,blinkSpeed:1,particleColors:[{color:"#6B46C1",weight:30},{color:"#4A5568",weight:25},{color:"#8B4789",weight:20},{color:"#9F7AEA",weight:15},{color:"#2D3748",weight:10}],threatLevel:0,getGlowIntensity(){return.3+.7*this.threatLevel},getParticleSpeed(){return.2+.8*this.threatLevel},getGlowColor(){const e=this.threatLevel||0,t=Math.round(107+113*e),i=Math.round(70+-32*e),s=Math.round(193+-66*e),n=e=>e.toString(16).padStart(2,"0");return`#${n(t)}${n(i)}${n(s)}`}},modifiers:{speed:.4,amplitude:.6,intensity:1.2,smoothness:.3,regularity:.2,focus:1.5,addWobble:!0},typicalGestures:["scan","twitch","peek","tilt","hold"],transitions:{duration:500,easing:"linear",priority:4},special:{coreSquint:.6,scanInterval:2e3,scanDuration:1200,scanAngle:60,twitchChance:.02,peekInterval:4e3,maxThreatDistance:300,alertThreshold:.7},"3d":{rotation:{type:"suspicious",speed:1,axes:[0,0,0],musicSync:!1},glow:{color:"#6B46C1",intensity:.85,pulse:{speed:.6,range:[.7,1]}},scale:{base:1,breathe:{enabled:!0,depth:.04,rate:.6}}},soulAnimation:{driftSpeed:.9,shimmerSpeed:1.8,turbulence:.4},rhythmModifiers:{windowMultiplier:.9,visualNoise:.3,inputDelay:0,tempoShift:0}},n={name:"calm",emoji:"๐",description:"Serene, peaceful state with gentle movements",visual:{glowColor:"#66D9CC",particleRate:6,minParticles:10,maxParticles:50,particleBehavior:"ascending",breathRate:.4,breathDepth:.12,coreJitter:!1,blinkRate:.8,blinkSpeed:1,particleColors:[{color:"#66D9CC",weight:35},{color:"#99E6D9",weight:25},{color:"#40BFB3",weight:20},{color:"#B3F2E6",weight:15},{color:"#339980",weight:5}]},modifiers:{speed:.5,amplitude:.3,intensity:.4,smoothness:2,regularity:1.5,addWeight:!1,floatHeight:.2,swayAmount:.15,duration:1.5},typicalGestures:["breathe","float","drift","idle"],transitions:{duration:800,easing:"easeInOutSine",priority:1},movement:{floatPattern:"sine_slow",floatPeriod:6e3,floatAmplitude:8,swayPattern:"gentle",swayPeriod:8e3,swayAmplitude:5,microMovements:!1},getCoreParams(e){const t=e.time||Date.now(),i=.5*Math.sin(6e-4*t)+.5;return{scaleX:1-.02*i,scaleY:1-.02*i,eyeOpenness:.85,eyeExpression:"serene",pupilOffset:{x:2*Math.sin(3e-4*t),y:1*Math.cos(4e-4*t)},glowPulse:.95+.05*i}},updateParticle(e,t){e.x+=.1*Math.sin(.001*e.life),e.y-=.02*t,e.opacity=.3*Math.sin(.002*e.life)+.2,e.size=e.baseSize*(1+.2*Math.sin(.001*e.life))},renderCore:(e,t,i,s)=>!1,"3d":{rotation:{type:"gentle",speed:.5,axes:[0,.3,0],musicSync:!0},glow:{color:"#66D9CC",intensity:.6,pulse:{speed:.4,range:[.5,.7]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.4}}},soulAnimation:{driftSpeed:.3,shimmerSpeed:.4,turbulence:.1},rhythmModifiers:{windowMultiplier:1.2,visualNoise:0,inputDelay:0,tempoShift:0}};const a=new Map,r={happy:"joy",peaceful:"calm",curious:"surprise",frustrated:"anger",sad:"sadness",excitement:"excited"};function o(e){e.name&&a.set(e.name,e)}function l(e){const t=r[e]||e,s=a.get(t);if(s)return s;return i.getPluginEmotion(t)||null}function h(e){const t=l(e);if(!t)return l("neutral").visual;if(!t.visual)return{};const{visual:i}=t,s={};for(const e in i)"function"!=typeof i[e]&&(s[e]=i[e]);return"function"==typeof i.getGlowIntensity&&(s.glowIntensity=i.getGlowIntensity()),"function"==typeof i.getParticleSpeed&&(s.particleSpeed=i.getParticleSpeed()),"function"==typeof i.getParticleRate&&(s.particleRate=i.getParticleRate()),"function"==typeof i.getGlowColor&&(s.glowColor=i.getGlowColor()),s}function c(e){const t=l(e);return t?t.modifiers:l("neutral").modifiers}function u(){return[...Array.from(a.keys()),...i.getAllPluginEmotions()]}function d(){const e={};return a.forEach((t,i)=>{e[i]=t}),e}function g(e){const t=r[e]||e;return a.has(t)||null!==i.getPluginEmotion(t)}function m(e,t){r[e]=t}function p(e,t){const i=l(e),s=l(t);return i&&s?s.transitions&&s.transitions[e]?s.transitions[e]:{duration:1e3,easing:"ease-in-out",gesture:s.transitions?.defaultGesture||null}:{duration:1e3,easing:"ease-in-out"}}function f(e){const t=l(e);return t?.gestures||[]}function y(e){const t=l(e);return t?.rhythmModifiers??{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}}function b(e){if(!e||0===e.length)return{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0};if(1===e.length){const t=y(e[0].emotion),i=e[0].intensity;return{windowMultiplier:1+(t.windowMultiplier-1)*i,visualNoise:t.visualNoise*i,inputDelay:t.inputDelay*i,tempoShift:t.tempoShift*i}}let t=0;for(let i=1;i<e.length;i++)e[i].intensity>e[t].intensity&&(t=i);const i={windowMultiplier:0,visualNoise:0,inputDelay:0,tempoShift:0},s=e.filter((e,i)=>i!==t),n=s.length>0?.25/s.length:0,a=y(e[t].emotion),r=e[t].intensity;i.windowMultiplier+=.75*(1+(a.windowMultiplier-1)*r),i.visualNoise+=a.visualNoise*r*.75,i.inputDelay+=a.inputDelay*r*.75,i.tempoShift+=a.tempoShift*r*.75;for(const e of s){const t=y(e.emotion),s=e.intensity;i.windowMultiplier+=(1+(t.windowMultiplier-1)*s)*n,i.visualNoise+=t.visualNoise*s*n,i.inputDelay+=t.inputDelay*s*n,i.tempoShift+=t.tempoShift*s*n}return i}[{name:"neutral",emoji:"๐",description:"Calm, balanced emotional state",visual:{glowColor:"#00BCD4",particleRate:2,minParticles:8,maxParticles:10,particleBehavior:"ambient",breathRate:1,breathDepth:.08,coreJitter:!1,blinkRate:1,blinkSpeed:1,particleColors:[{color:"#00BCD4",weight:25},{color:"#00ACC1",weight:20},{color:"#26C6DA",weight:15},{color:"#B2EBF2",weight:15},{color:"#0097A7",weight:10},{color:"#80DEEA",weight:10},{color:"#E0F7FA",weight:5}]},modifiers:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1},typicalGestures:["breathe","float","idle","blink"],transitions:{duration:500,easing:"easeInOut",priority:0},getCoreParams:e=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"neutral",pupilOffset:{x:0,y:0}}),renderCore:(e,t,i,s)=>!1,"3d":{rotation:{type:"gentle",speed:1,axes:[0,.3,0],musicSync:!1},glow:{color:"#00BCD4",intensity:.9,pulse:{speed:1,range:[.8,1]}},scale:{base:1,breathe:{enabled:!0,depth:.08,rate:1}}},soulAnimation:{driftSpeed:.5,shimmerSpeed:.5,turbulence:.2},rhythmModifiers:{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"joy",emoji:"๐",description:"Playful happiness and celebration",visual:{glowColor:"#FFEB3B",particleRate:8,minParticles:0,maxParticles:50,particleBehavior:"popcorn",breathRate:1.5,breathDepth:.1,coreJitter:!1,blinkRate:1.3,blinkSpeed:1.1,particleColors:[{color:"#FFEB3B",weight:25},{color:"#FFC107",weight:20},{color:"#FFFF00",weight:15},{color:"#FFD700",weight:15},{color:"#FFF59D",weight:10},{color:"#FF9800",weight:10},{color:"#FFFDE7",weight:5}]},modifiers:{speed:1.8,amplitude:1.9,intensity:1.1,smoothness:1,regularity:.9,addBounce:!0},typicalGestures:["bounce","spin","wave","expand","shake","float"],transitions:{duration:400,easing:"easeOutBack",priority:5,burstOnEntry:!0},getCoreParams:e=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"happy",pupilOffset:{x:0,y:-.1},sparkle:!0}),"3d":{rotation:{type:"rhythmic",speed:1.8,axes:[0,.3,0],musicSync:!0},glow:{color:"#FFEB3B",intensity:1.6,pulse:{speed:1.5,range:[1.2,1.8]}},scale:{base:1,breathe:{enabled:!0,depth:.1,rate:1.5}}},soulAnimation:{driftSpeed:1.2,shimmerSpeed:1.5,turbulence:.3},rhythmModifiers:{windowMultiplier:1.3,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"sadness",emoji:"๐ข",description:"Deep melancholic sorrow",visual:{glowColor:"#4169E1",particleRate:6,minParticles:0,maxParticles:50,particleBehavior:"falling",breathRate:.6,breathDepth:.12,coreJitter:!1,blinkRate:.6,blinkSpeed:.8,particleColors:[{color:"#4169E1",weight:25},{color:"#1E90FF",weight:20},{color:"#6495ED",weight:15},{color:"#B0C4DE",weight:15},{color:"#191970",weight:10},{color:"#87CEEB",weight:10},{color:"#2F4F4F",weight:5}]},modifiers:{speed:.7,amplitude:.6,intensity:.8,smoothness:1.3,regularity:1.1,addGravity:!0},typicalGestures:["droop","sway","contract","drift","sink"],transitions:{duration:800,easing:"easeInOut",priority:3},"3d":{rotation:{type:"gentle",speed:.7,axes:[0,.2,0],musicSync:!1},glow:{color:"#4169E1",intensity:.65,pulse:{speed:.6,range:[.5,.8]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.6}}},soulAnimation:{driftSpeed:.2,shimmerSpeed:.3,turbulence:.1},rhythmModifiers:{windowMultiplier:1,visualNoise:0,inputDelay:45,tempoShift:0}},{name:"anger",emoji:"๐ ",description:"Intense rage and aggression",visual:{glowColor:"#DC143C",particleRate:8,minParticles:8,maxParticles:50,particleBehavior:"aggressive",breathRate:2.2,breathDepth:.15,coreJitter:!0,blinkRate:1.6,blinkSpeed:1.3,particleColors:[{color:"#DC143C",weight:25},{color:"#FF0000",weight:20},{color:"#B22222",weight:15},{color:"#FF4500",weight:15},{color:"#8B0000",weight:10},{color:"#FF6347",weight:10},{color:"#660000",weight:5}]},modifiers:{speed:1.5,amplitude:1.4,intensity:1.3,smoothness:.3,regularity:.7,addShake:!0},typicalGestures:["shake","vibrate","expand","pulse","flicker","strike"],transitions:{duration:300,easing:"easeOutExpo",priority:8,shakeOnEntry:!0},special:{screenShake:!0,particleTrails:"fire",glowPulse:!0,temperatureEffect:"hot"},"3d":{rotation:{type:"unstable",speed:1.5,axes:[0,.3,0],shake:{amplitude:.02,frequency:7},eruption:{enabled:!0,interval:3e3,speedMultiplier:3.5,duration:400},musicSync:!1},glow:{color:"#DC143C",intensity:1.8,pulse:{speed:2.2,range:[.8,2]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:2.2}}},soulAnimation:{driftSpeed:2,shimmerSpeed:.8,turbulence:.8},rhythmModifiers:{windowMultiplier:.75,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"fear",emoji:"๐จ",description:"Anxious state with fleeing particles",visual:{glowColor:"#8A2BE2",particleRate:8,minParticles:8,maxParticles:50,particleBehavior:"scattering",breathRate:2.5,breathDepth:.06,coreJitter:!0,blinkRate:1.7,blinkSpeed:1.4,particleColors:[{color:"#8A2BE2",weight:25},{color:"#4B0082",weight:20},{color:"#9400D3",weight:15},{color:"#6B46C1",weight:15},{color:"#9932CC",weight:10},{color:"#E6E6FA",weight:8},{color:"#301934",weight:7}]},modifiers:{speed:1.4,amplitude:.8,intensity:1.2,smoothness:.5,regularity:.5,addJitter:!0},typicalGestures:["shake","vibrate","contract","flicker","retreat"],transitions:{duration:400,easing:"easeOut",priority:7},"3d":{rotation:{type:"unstable",speed:1.4,axes:[0,.3,0],shake:{amplitude:.015,frequency:3.5},musicSync:!1},glow:{color:"#8A2BE2",intensity:.9,pulse:{speed:2.5,range:[.6,1.2]}},scale:{base:1,breathe:{enabled:!0,depth:.06,rate:2.5}}},soulAnimation:{driftSpeed:1.8,shimmerSpeed:2.5,turbulence:.6},rhythmModifiers:{windowMultiplier:1,visualNoise:.6,inputDelay:0,tempoShift:0}},{name:"surprise",emoji:"๐ฒ",description:"Sudden shock with explosive particles",visual:{glowColor:"#FFD700",particleRate:5,minParticles:0,maxParticles:15,particleBehavior:"burst",breathRate:.3,breathDepth:.18,coreJitter:!1,blinkRate:1.4,blinkSpeed:1.2,particleColors:[{color:"#FFD700",weight:25},{color:"#FFA500",weight:20},{color:"#FFFF00",weight:15},{color:"#FF6347",weight:15},{color:"#FFE4B5",weight:10},{color:"#FF4500",weight:10},{color:"#FFFACD",weight:5}]},modifiers:{speed:1.6,amplitude:1.5,intensity:1.4,smoothness:.7,regularity:.8,addPop:!0},typicalGestures:["expand","bounce","flash","pulse","pop"],transitions:{duration:200,easing:"easeOutBack",priority:6},"3d":{rotation:{type:"unstable",speed:1.6,axes:[0,.45,0],shake:{amplitude:.01,frequency:3},musicSync:!1},glow:{color:"#FFD700",intensity:1.8,pulse:{speed:.3,range:[1,2.2]}},scale:{base:1,breathe:{enabled:!0,depth:.18,rate:.3}}},soulAnimation:{driftSpeed:1.5,shimmerSpeed:2,turbulence:.5},rhythmModifiers:{windowMultiplier:2,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"disgust",emoji:"๐คข",description:"Revulsion with repelling particles",visual:{glowColor:"#9ACD32",particleRate:4,minParticles:5,maxParticles:12,particleBehavior:"repelling",breathRate:.7,breathDepth:.04,coreJitter:!1,blinkRate:.9,blinkSpeed:.9,particleColors:[{color:"#9ACD32",weight:25},{color:"#ADFF2F",weight:20},{color:"#7FFF00",weight:15},{color:"#BDB76B",weight:15},{color:"#6B8E23",weight:10},{color:"#CCFF00",weight:8},{color:"#556B2F",weight:7}]},modifiers:{speed:.9,amplitude:.7,intensity:.9,smoothness:.8,regularity:1,addRecoil:!0},typicalGestures:["contract","shake","recoil","wobble"],transitions:{duration:600,easing:"easeIn",priority:4},"3d":{rotation:{type:"gentle",speed:.9,axes:[0,.25,0],musicSync:!1},glow:{color:"#9ACD32",intensity:1,pulse:{speed:.7,range:[.7,1.2]}},scale:{base:1,breathe:{enabled:!0,depth:.04,rate:.7}}},soulAnimation:{driftSpeed:.4,shimmerSpeed:.6,turbulence:.35},rhythmModifiers:{windowMultiplier:.85,visualNoise:.2,inputDelay:0,tempoShift:0}},{name:"love",emoji:"๐",description:"Warm affection with orbiting particles",visual:{glowColor:"#FF1493",particleRate:6,minParticles:15,maxParticles:50,particleBehavior:"orbiting",breathRate:.75,breathDepth:.15,coreJitter:!1,blinkRate:1.2,blinkSpeed:1,particleColors:[{color:"#FF1493",weight:30},{color:"#FF69B4",weight:25},{color:"#FF007F",weight:15},{color:"#FFB6C1",weight:10},{color:"#FF45A0",weight:10},{color:"#E91E63",weight:5},{color:"#FFC0CB",weight:5}]},modifiers:{speed:.9,amplitude:1.1,intensity:1.2,smoothness:1.4,regularity:1.2,addWarmth:!0},typicalGestures:["pulse","sway","orbit","glow","breathe","float"],transitions:{duration:700,easing:"easeInOut",priority:5},"3d":{rotation:{type:"gentle",speed:.9,axes:[0,.28,0],musicSync:!0},glow:{color:"#FF1493",intensity:1.8,pulse:{speed:.75,range:[1.3,2]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:.75}}},soulAnimation:{driftSpeed:.8,shimmerSpeed:1.2,turbulence:.2},rhythmModifiers:{windowMultiplier:1.15,visualNoise:0,inputDelay:0,tempoShift:0}},s,{name:"excited",emoji:"๐คฉ",description:"High energy with rapid particles",visual:{glowColor:"#FF6B35",particleRate:8,minParticles:10,maxParticles:50,particleBehavior:"burst",breathRate:2,breathDepth:.14,coreJitter:!0,blinkRate:1.5,blinkSpeed:1.2,particleColors:[{color:"#FF6B35",weight:25},{color:"#FF1744",weight:20},{color:"#FFC107",weight:15},{color:"#FF9100",weight:15},{color:"#FFEB3B",weight:10},{color:"#FF5722",weight:10},{color:"#FFF59D",weight:5}]},modifiers:{speed:1.4,amplitude:1.3,intensity:1.3,smoothness:.8,regularity:.7,addVibration:!0},typicalGestures:["bounce","spin","vibrate","expand","shake","pulse"],transitions:{duration:300,easing:"easeOutElastic",priority:6},"3d":{rotation:{type:"unstable",speed:1.4,axes:[0,.4,0],shake:{amplitude:.01,frequency:4},musicSync:!1},glow:{color:"#FF6B35",intensity:1.5,pulse:{speed:2,range:[1,1.8]}},scale:{base:1,breathe:{enabled:!0,depth:.14,rate:2}}},soulAnimation:{driftSpeed:1.5,shimmerSpeed:2,turbulence:.5},rhythmModifiers:{windowMultiplier:1.2,visualNoise:.1,inputDelay:0,tempoShift:0}},{name:"resting",emoji:"๐ด",description:"Deep relaxation with slow drift",visual:{glowColor:"#9370DB",particleRate:1,minParticles:3,maxParticles:5,particleBehavior:"resting",breathRate:.8,breathDepth:.12,coreJitter:!1,blinkRate:.4,blinkSpeed:.7,particleColors:[{color:"#9370DB",weight:30},{color:"#A591C4",weight:20},{color:"#B366FF",weight:20},{color:"#B8A1E6",weight:15},{color:"#674D9B",weight:15}]},modifiers:{speed:.5,amplitude:.4,intensity:.5,smoothness:1.4,regularity:.9,addWeight:!0},typicalGestures:["breathe","drift","sway","float"],transitions:{duration:1e3,easing:"easeInOut",priority:2},"3d":{rotation:{type:"gentle",speed:.5,axes:[0,.15,0],musicSync:!1},glow:{color:"#9370DB",intensity:.8,pulse:{speed:.8,range:[.6,1]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.8}}},soulAnimation:{driftSpeed:.15,shimmerSpeed:.1,turbulence:.05},rhythmModifiers:{windowMultiplier:1.1,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"euphoria",emoji:"๐",description:"Radiant hope and new beginnings",visual:{glowColor:"#FFB6C1",particleRate:6,minParticles:15,maxParticles:30,particleBehavior:"radiant",breathRate:1.3,breathDepth:.25,coreJitter:!1,blinkRate:1.4,blinkSpeed:1.1,particleColors:[{color:"#FFB6C1",weight:20},{color:"#FFD700",weight:18},{color:"#87CEEB",weight:15},{color:"#DDA0DD",weight:15},{color:"#98FB98",weight:12},{color:"#FFA07A",weight:10},{color:"#E6E6FA",weight:8},{color:"#FFFFFF",weight:2}]},modifiers:{speed:1.4,amplitude:1.5,intensity:1.6,smoothness:1.3,regularity:.8,addWarmth:!0,addLift:!0},typicalGestures:["expand","radiate","pulse","glow","float","bloom"],transitions:{duration:600,easing:"easeOutExpo",priority:8},"3d":{rotation:{type:"rhythmic",speed:1.4,axes:[0,.35,0],musicSync:!0},glow:{color:"#FFB6C1",intensity:1.2,pulse:{speed:1.3,range:[.9,1.5]}},scale:{base:1,breathe:{enabled:!0,depth:.25,rate:1.3}}},soulAnimation:{driftSpeed:1.8,shimmerSpeed:2.5,turbulence:.7},rhythmModifiers:{windowMultiplier:1.5,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"focused",emoji:"๐ฏ",description:"Intense concentration with directed flow",visual:{glowColor:"#00CED1",particleRate:4,minParticles:5,maxParticles:12,particleBehavior:"directed",breathRate:1.2,breathDepth:.08,coreJitter:!0,blinkRate:.7,blinkSpeed:1,particleColors:[{color:"#00CED1",weight:30},{color:"#4A9FA0",weight:20},{color:"#00FFFF",weight:20},{color:"#5FE5E7",weight:15},{color:"#006B6D",weight:15}],eyeOpenness:.7,microAdjustments:!0},modifiers:{speed:1,amplitude:.9,intensity:1.1,smoothness:1.1,regularity:1.2,addPrecision:!0},typicalGestures:["track","lock","scan","pulse","vibrate"],transitions:{duration:400,easing:"easeIn",priority:5},getCoreParams:e=>({scaleX:1.1,scaleY:.7,eyeOpenness:.7,eyeExpression:"focused",pupilOffset:{x:0,y:0},microAdjustments:!0}),"3d":{rotation:{type:"still",speed:.5,axes:[0,.1,0],musicSync:!1},glow:{color:"#00CED1",intensity:1.2,pulse:{speed:1.2,range:[1,1.3]}},scale:{base:1,breathe:{enabled:!0,depth:.08,rate:1.2}}},soulAnimation:{driftSpeed:.6,shimmerSpeed:.2,turbulence:.1},rhythmModifiers:{windowMultiplier:.85,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"glitch",emoji:"๐",description:"Surprised sadness with rainbow colors and glitch wiggle",visual:{primaryColor:"#FF6B9D",glowColor:"#4169E1",glowIntensity:1.2,particleRate:5,minParticles:5,maxParticles:15,particleBehavior:"burst",particleSpeed:1,breathRate:.4,breathDepth:.15,coreJitter:!1,coreSize:1,eyeOpenness:.8,blinkRate:1.3,blinkSpeed:1.2,particleColors:[{color:"#FF0080",weight:18},{color:"#00FF80",weight:18},{color:"#8000FF",weight:18},{color:"#FF8000",weight:15},{color:"#0080FF",weight:15},{color:"#FFFF00",weight:10},{color:"#FF6B9D",weight:6}],particleGlitchWiggle:!0,glitchWiggleIntensity:.3,glitchWiggleFrequency:.1},modifiers:{speed:1.1,amplitude:1,intensity:1.1,smoothness:.8,regularity:.7,focus:.6},typicalGestures:["bounce","sway","pulse","drift","flash"],transitions:{duration:300,easing:"easeInOut",priority:5},"3d":{rotation:{type:"unstable",speed:1.1,axes:[0,.35,0],shake:{amplitude:.02,frequency:5},musicSync:!1},glow:{color:"#FF6B9D",intensity:1.2,pulse:{speed:.4,range:[.8,1.6]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:.4}}},rhythmModifiers:{windowMultiplier:1,visualNoise:.8,inputDelay:20,tempoShift:0}},n].forEach(e=>{e&&e.name&&a.set(e.name,e)});var v={registerEmotion:o,getEmotion:l,getEmotionVisualParams:h,getEmotionParams:h,getEmotionModifiers:c,getEmotionRhythmModifiers:y,getBlendedRhythmModifiers:b,listEmotions:u,getAllEmotions:d,hasEmotion:g,addEmotionAlias:m,getTransitionParams:p,getEmotionGestures:f,pluginAdapter:i},M=Object.freeze({__proto__:null,addEmotionAlias:m,default:v,getAllEmotions:d,getBlendedRhythmModifiers:b,getEmotion:l,getEmotionGestures:f,getEmotionModifiers:c,getEmotionRhythmModifiers:y,getEmotionVisualParams:h,getTransitionParams:p,hasEmotion:g,listEmotions:u,pluginAdapter:i,registerEmotion:o});const w=new Map;var S={registerPluginGesture:function(e,t){return!(!t.apply&&!t.type||(t.name||(t.name=e),t.type||(t.type="blending"),w.set(e,t),0))},unregisterPluginGesture:function(e){return!!w.has(e)&&(w.delete(e),!0)},getPluginGesture:function(e){return w.get(e)||null},getAllPluginGestures:function(){return Array.from(w.keys())},clearPluginGestures:function(){w.clear()},createLegacyAdapter:function(e){return{name:e.name||"unknown",type:e.type||"blending",emoji:e.emoji||"๐",description:e.description||"Plugin gesture",config:e.config||{},apply(t,i,s,n,a,r){e.animate?e.animate(t,i,s,n,a,r):e.apply&&e.apply(t,i,s,n,a,r)},cleanup:e.cleanup||function(e){e.gestureData&&e.gestureData[this.name]&&delete e.gestureData[this.name]}}}},x={name:"breathe",emoji:"๐ซ",type:"blending",description:"Breathing rhythm with inhale and exhale",config:{musicalDuration:{musical:!0,bars:1,minBeats:2,maxBeats:16},phases:[{name:"inhale",beats:1.5},{name:"hold_in",beats:.5},{name:"exhale",beats:1.5},{name:"hold_out",beats:.5}],inhaleRadius:1.5,exhaleRadius:.3,breathRate:.3,spiralStrength:.002,scaleAmount:.25,glowAmount:.4,frequency:1,easing:"sine",strength:.8,particleMotion:{type:"breathe",strength:.8,inhaleRadius:1.5,exhaleRadius:.3}},rhythm:{enabled:!0,syncMode:"phrase",breathRateSync:{mode:"tempo",bpm:"auto",subdivision:"whole",curve:"sine"},radiusSync:{inhale:{onUpbeat:1.8,onDownbeat:1.4,curve:"ease-in"},exhale:{onUpbeat:.2,onDownbeat:.4,curve:"ease-out"}},durationSync:{mode:"phrases",phrases:2,hold:"fermata"},accentResponse:{enabled:!0,multiplier:1.5,type:"expansion"},patternOverrides:{ballad:{breathRateSync:{subdivision:"double-whole"},radiusSync:{inhale:{onUpbeat:2.2,onDownbeat:1.8},exhale:{onUpbeat:.1,onDownbeat:.2}}},uptempo:{breathRateSync:{subdivision:"half"},radiusSync:{inhale:{onUpbeat:1.4,onDownbeat:1.2},exhale:{onUpbeat:.3,onDownbeat:.4}}},ambient:{breathRateSync:{subdivision:"whole",curve:"ease"},radiusSync:{inhale:{onUpbeat:1.6,onDownbeat:1.6},exhale:{onUpbeat:.2,onDownbeat:.2}}}},dynamics:{forte:{radiusSync:{inhale:{multiplier:1.8},exhale:{multiplier:.5}},spiralStrength:.004,scaleAmount:.4},piano:{radiusSync:{inhale:{multiplier:1.2},exhale:{multiplier:.8}},spiralStrength:.001,scaleAmount:.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.breathe={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),phaseOffset:.2*Math.random()-.1}},apply(e,t,i,s,n,a){e.gestureData?.breathe||this.initialize(e,i,n,a);const r={...this.config,...i},o=(Math.sin(t*Math.PI*2*r.breathRate)+1)/2,l=100*(e.scaleFactor||1),h=r.inhaleRadius*l,c=r.exhaleRadius*l,u=c+(h-c)*o,d=e.x-n,g=e.y-a,m=Math.sqrt(d*d+g*g),p=u-m,f=.05*(i.strength||.8)*s;if(m>0){const t=d/m*p*f,n=g/m*p*f;e.vx+=t,e.vy+=n;const a=r.spiralStrength*s*(i.strength||1),l=-g/m,h=d/m;e.vx+=l*a*o,e.vy+=h*a*o}e.vx*=.98,e.vy*=.98},cleanup(e){e.gestureData?.breathe&&delete e.gestureData.breathe},"3d":{evaluate(e,t){const i=(t.config||{}).breathRate||.3,s=Math.sin(e*Math.PI*2*i);let n=1;if(e>.8){const t=(e-.8)/(1-.8);n=1-t*t*t}const a=.2*s*n;return{position:[0,.05*s*n,0],rotation:[0,0,0],scale:1+.35*s*n,glowIntensity:1+a,glowBoost:Math.max(0,2*a)}}}},C={name:"expand",emoji:"๐ซ",type:"blending",description:"Radial expansion from center",config:{duration:600,scaleAmount:3,scaleTarget:3,glowAmount:.5,easing:"back",strength:3,particleMotion:{type:"pulse",strength:3,direction:"outward",persist:!0}},rhythm:{enabled:!0,syncMode:"crescendo",strengthSync:{pianissimo:1.5,fortissimo:5,crescendo:"build",sforzando:"burst"},scaleTargetSync:{verse:2,chorus:4.5,climax:6,curve:"exponential"},durationSync:{mode:"phrases",build:1.2,release:.8,sustain:"hold"},accentResponse:{enabled:!0,multiplier:2.8,type:"strength"},patternOverrides:{orchestral:{strengthSync:{pianissimo:2,fortissimo:6.5,crescendo:"dramatic"},scaleTargetSync:{climax:8}},rock:{strengthSync:{pianissimo:1.8,fortissimo:5.5,curve:"power"},accentResponse:{multiplier:3.2}},ambient:{strengthSync:{pianissimo:1.2,fortissimo:3.5,crescendo:"organic"},durationSync:{build:1.8,release:1.2}},electronic:{strengthSync:{pianissimo:1.6,fortissimo:4.8,curve:"digital"},scaleTargetSync:{curve:"linear"}}},dynamics:{forte:{strengthSync:{pianissimo:{multiplier:1.4},fortissimo:{multiplier:1.8}},scaleTargetSync:{multiplier:1.6},accentResponse:{multiplier:3.5}},piano:{strengthSync:{pianissimo:{multiplier:.8},fortissimo:{multiplier:1.2}},scaleTargetSync:{multiplier:.7},accentResponse:{multiplier:2}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.expand={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.expand?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.expand,o={...this.config,...i},l=o.strength||1,h=1+(o.scaleTarget-1)*t*l,c=r.baseRadius*h,u=n+Math.cos(r.angle)*c,d=a+Math.sin(r.angle)*c,g=u-e.x,m=d-e.y;e.vx+=.8*g*s,e.vy+=.8*m*s,e.vx*=.95,e.vy*=.95},cleanup(e){e.gestureData?.expand&&delete e.gestureData.expand},"3d":{evaluate(e,t){const i={...this.config,...t},s=i.strength||3;return{position:[0,0,0],rotation:[0,0,0],scale:1+e*(i.scaleAmount||3)*(s/3),glowIntensity:1+.25*e,glowBoost:.8*e}}}},k={name:"contract",emoji:"๐",type:"blending",description:"Radial contraction toward center",config:{duration:600,scaleAmount:.2,scaleTarget:.2,glowAmount:-.2,easing:"cubic",strength:2.5,particleMotion:{type:"pulse",strength:2.5,direction:"inward",persist:!0}},rhythm:{enabled:!0,syncMode:"tension",strengthSync:{onTension:4,onRelease:1.5,curve:"magnetic"},scaleTargetSync:{forte:.1,piano:.4,crescendo:"gradual",diminuendo:"ease"},durationSync:{mode:"phrases",shortPhrase:.8,longPhrase:1.5,hold:"sustain"},accentResponse:{enabled:!0,multiplier:2.2,type:"strength"},patternOverrides:{classical:{strengthSync:{onTension:3.5,onRelease:1.8},scaleTargetSync:{forte:.15,piano:.35}},metal:{strengthSync:{onTension:5,onRelease:2,curve:"sharp"},scaleTargetSync:{forte:.05,piano:.25}},ambient:{strengthSync:{onTension:2.8,onRelease:1.2,curve:"ease"},durationSync:{shortPhrase:1.2,longPhrase:2}},trap:{strengthSync:{onTension:4.5,onRelease:1,dropBeat:6},scaleTargetSync:{forte:.08,piano:.3}}},dynamics:{forte:{strengthSync:{onTension:{multiplier:1.8},onRelease:{multiplier:1.4}},scaleTargetSync:{multiplier:.6},accentResponse:{multiplier:2.8}},piano:{strengthSync:{onTension:{multiplier:.7},onRelease:{multiplier:.8}},scaleTargetSync:{multiplier:1.4},accentResponse:{multiplier:1.6}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.contract={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.contract?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.contract,o={...this.config,...i},l=o.strength||1,h=1-(1-o.scaleTarget)*t*l,c=r.baseRadius*h,u=n+Math.cos(r.angle)*c,d=a+Math.sin(r.angle)*c,g=u-e.x,m=d-e.y;e.vx+=.5*g*s,e.vy+=.5*m*s,e.vx*=.95,e.vy*=.95},cleanup(e){e.gestureData?.contract&&delete e.gestureData.contract},"3d":{evaluate(e,t){const i={...this.config,...t},s=i.strength||2.5,n=i.scaleTarget||.2,a=1-e*(1-n)*(s/2.5),r=1-.15*e;return{position:[0,0,0],rotation:[0,0,0],scale:Math.max(n,a),glowIntensity:r}}}},P={name:"pulse",emoji:"๐",type:"blending",description:"Radial expansion and contraction from center",config:{duration:600,amplitude:30,frequency:1,holdPeak:.1,easing:"sine",scaleAmount:.2,glowAmount:.3,strength:.15,direction:"outward",particleMotion:{type:"pulse",strength:.15,direction:"outward",frequency:1}},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.6,offBeat:.8,curve:"pulse"},frequencySync:{mode:"locked",subdivision:"quarter"},durationSync:{mode:"beats",beats:1},accentResponse:{enabled:!0,multiplier:2},patternOverrides:{waltz:{amplitudeSync:{onBeat:2,offBeat:.5},durationSync:{beats:3}},swing:{amplitudeSync:{onBeat:1.8,offBeat:.6,curve:"ease"},frequencySync:{subdivision:"swing"}},dubstep:{amplitudeSync:{onBeat:1.2,dropBeat:4,curve:"pulse"}},breakbeat:{frequencySync:{mode:"random",range:[.5,2]},amplitudeSync:{onBeat:2.5,offBeat:.3}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.atan2(a,n);e.gestureData.pulse={baseDistance:r,angle:o,startX:e.x,startY:e.y,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.pulse?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.pulse,o={...this.config,...i},l=i.strength||1,h=this.easeInOutSine(t);let c,{frequency:u}=o,{amplitude:d}=o;i.rhythmModulation&&(d*=i.rhythmModulation.amplitudeMultiplier||1,d*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(u*=i.rhythmModulation.frequencyMultiplier));const g=h*u*2%2;c=o.holdPeak>0&&g>1-o.holdPeak&&g<1+o.holdPeak?1:Math.sin(h*Math.PI*2*u);const m=c*d*l*e.scaleFactor,p=r.baseDistance+m,f=n+Math.cos(r.angle)*p,y=a+Math.sin(r.angle)*p,b=.15*s;if(e.vx+=(f-e.x)*b*.1,e.vy+=(y-e.y)*b*.1,t>.9){const i=1-10*(t-.9);e.vx*=.9+.1*i,e.vy*=.9+.1*i}},cleanup(e){e.gestureData?.pulse&&delete e.gestureData.pulse},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i=t||{},s=i.frequency||1,n=i.strength||.15,a=i.scaleAmount||.2,r=i.glowAmount||.3,o=-(Math.cos(Math.PI*e)-1)/2,l=Math.sin(o*Math.PI*2*s);return{position:[0,0,0],rotation:[0,0,0],scale:1+l*a*n,glowIntensity:1+Math.max(-.3,Math.min(.3,l*r*n*2)),glowBoost:Math.max(0,.8*l)}}}},T={name:"sway",type:"blending",emoji:"๐",description:"Gentle side-to-side swaying motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},amplitude:20,frequency:1,strength:.5},rhythm:{enabled:!0,syncMode:"bar",amplitudeSync:{onBeat:1.2,offBeat:.9,curve:"ease"},durationSync:{mode:"bars",bars:1},patternOverrides:{waltz:{durationSync:{bars:1},amplitudeSync:{onBeat:1.5,curve:"ease"}},swing:{amplitudeSync:{onBeat:1.3,offBeat:.7,curve:"bounce"}}}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.amplitude||this.config.amplitude,l=r.frequency||this.config.frequency,h=r.strength||this.config.strength,c=Math.sin(t*Math.PI*2*l)*o;e.vx+=.01*c*s*h,e.vy+=.5*Math.cos(t*Math.PI*4)*s*h},cleanup(e){},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.amplitude||this.config.amplitude;const n=i.frequency||this.config.frequency,a=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const r=Math.sin(e*Math.PI*2*n),o=s*a*.3*.01,l=.15*r*a,h=.08*r*a;return{position:[r*o,.3*Math.cos(e*Math.PI*4)*o,Math.sin(e*Math.PI*n)*o*.5],rotation:[0,h,l],scale:1}}}},E={name:"float",type:"blending",emoji:"๐",description:"Gentle floating upward motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:2},amplitude:80,wobbleAmount:20,strength:1},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},wobbleSync:{subdivision:"eighth",intensity:.7},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:1.3},patternOverrides:{waltz:{wobbleSync:{subdivision:"quarter",intensity:.9}},dubstep:{amplitudeSync:{onBeat:2,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.float||(e.gestureData.float={originalSize:e.size,originalOpacity:e.opacity||1});const r={...this.config,...i};let o=r.amplitude||this.config.amplitude,l=r.wobbleAmount||this.config.wobbleAmount;const h=r.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1,l*=i.rhythmModulation.wobbleMultiplier||1);const c=Math.sin(t*Math.PI*4)*l;e.vy-=.01*o*s*h*(1-.5*t),e.vx+=.01*c*s*h,e.size=e.baseSize*(1+.1*t),e.opacity=1-.3*t},cleanup(e){e.gestureData?.float?(e.opacity=e.gestureData.float.originalOpacity,e.size=e.gestureData.float.originalSize,delete e.gestureData.float):(e.opacity=1,e.size=e.baseSize),e.vx*=.5,e.vy*=.5},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.amplitude||this.config.amplitude,n=i.wobbleAmount||this.config.wobbleAmount;const a=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1,n*=t.rhythmModulation.wobbleMultiplier||1);const r=Math.sin(e*Math.PI),o=s*r*a*.005,l=Math.sin(e*Math.PI*4)*n*.3*.005,h=Math.sin(e*Math.PI)*Math.PI*.5*a,c=Math.sin(e*Math.PI);return{position:[l,o,0],rotation:[c*Math.sin(e*Math.PI*2)*.1,h,c*Math.cos(e*Math.PI*3)*.08],scale:1+.1*r}}}};const A={left:{x:-1,y:0},right:{x:1,y:0},up:{x:0,y:1},down:{x:0,y:-1}};function D(e){return e.charAt(0).toUpperCase()+e.slice(1)}function _(e){const t=A[e];if(!t)throw new Error(`Invalid float direction: ${e}`);const i="up"===e||"down"===e;return{name:`float${D(e)}`,emoji:"up"===e?"๐":"down"===e?"๐":"left"===e?"๐ฌ๏ธ":"๐จ",type:"blending",description:`Gentle floating ${e}`,config:{duration:2e3,amplitude:80,wobbleAmount:20,strength:1,direction:e},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},wobbleSync:{subdivision:"eighth",intensity:.7},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:1.3}},apply(e,s,n,a,r,o){e.gestureData||(e.gestureData={}),e.gestureData.float||(e.gestureData.float={originalSize:e.size,originalOpacity:e.opacity||1});const l={...this.config,...n};let h=l.amplitude||80,c=l.wobbleAmount||20;const u=l.strength||1;n.rhythmModulation&&(h*=n.rhythmModulation.amplitudeMultiplier||1,h*=n.rhythmModulation.accentMultiplier||1,c*=n.rhythmModulation.wobbleMultiplier||1);const d=Math.sin(s*Math.PI*4)*c,g=.01*h*a*u*(1-.5*s);i?(e.vy+=t.y*g,e.vx+=.01*d*a*u):(e.vx+=t.x*g,e.vy+=.01*d*a*u),e.size=e.baseSize*(1+.1*s),e.opacity=1-.3*s},cleanup(e){e.gestureData?.float?(e.opacity=e.gestureData.float.originalOpacity,e.size=e.gestureData.float.originalSize,delete e.gestureData.float):(e.opacity=1,e.size=e.baseSize),e.vx*=.5,e.vy*=.5},"3d":{evaluate(e,s){const n=s||{};let a=n.amplitude||80,r=n.wobbleAmount||20;const o=n.strength||1;s.rhythmModulation&&(a*=s.rhythmModulation.amplitudeMultiplier||1,a*=s.rhythmModulation.accentMultiplier||1,r*=s.rhythmModulation.wobbleMultiplier||1);const l=Math.sin(e*Math.PI),h=a*l*o*.005,c=Math.sin(e*Math.PI*4)*r*.3*.005,u=Math.sin(e*Math.PI)*Math.PI*.5*o,d=Math.sin(e*Math.PI),g=d*Math.sin(e*Math.PI*2)*.1,m=d*Math.cos(e*Math.PI*3)*.08,p=1+.1*l;let f=0,y=0;return i?(y=t.y*h,f=c):(f=t.x*h,y=c),{cameraRelativePosition:[f,y,0],rotation:[g,u,m],scale:p}}}}}var I=_("up"),R=_("down"),B=_("left"),z=_("right"),F={name:"lean",emoji:"โ๏ธ",type:"blending",description:"Diagonal tilting motion with smooth return",config:{duration:1200,musicalDuration:{musical:!0,beats:2},amplitude:10,frequency:1,direction:"right",strength:.7,particleMotion:{type:"lean",direction:"right",strength:.7,frequency:1}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.3,offBeat:.8,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.4},patternOverrides:{waltz:{durationSync:{beats:3},amplitudeSync:{onBeat:1.5,offBeat:.6}},swing:{amplitudeSync:{onBeat:1.6,offBeat:.5,curve:"bounce"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.lean={startX:e.x,startY:e.y,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.lean?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t),h=r.frequency||this.config.frequency;let c=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI*h),d="left"===r.direction?-1:1;if(e.vx+=u*c*.015*s*d,e.vy+=u*c*.01*s*d*.5,t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.lean&&delete e.gestureData.lean},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||10,n=i.frequency||1,a=i.strength||.7,r=i.direction||"right",o=.003*s*a,l=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,h=Math.sin(l*Math.PI*n),c="left"===r?-1:1;return{position:[h*o*c,0,0],rotation:[0,0,.35*h*c],scale:1}}}};function O(e){if("left"!==e&&"right"!==e)throw new Error(`Invalid lean direction: ${e}. Only 'left' and 'right' are supported.`);const t=A[e];return{name:`lean${D(e)}`,emoji:"left"===e?"โ๏ธ":"โ๏ธ",type:"blending",description:`Lean ${e} with smooth return`,config:{duration:800,amplitude:10,frequency:1,strength:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:1.3,offBeat:.8,curve:"ease"},accentResponse:{enabled:!0,multiplier:1.4}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.lean={startX:e.x,startY:e.y,initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.lean?.initialized||this.initialize(e,s);const o={...this.config,...s},l=o.strength||.7,h=this.easeInOutCubic(i);let c=o.amplitude*l*e.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI*o.frequency);if(e.vx+=u*c*.015*n*t.x,e.vy+=u*c*.01*n*t.x*.5,i>.9){const t=1-10*(i-.9);e.vx*=.95+.05*t,e.vy*=.95+.05*t}},cleanup(e){e.gestureData?.lean&&delete e.gestureData.lean},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||10,a=s.frequency||1,r=.003*n*(s.strength||.7),o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI*a),h=.35*l*t.x;return{cameraRelativePosition:[l*r*t.x,0,0],cameraRelativeRotation:[0,0,h],scale:1}}}}}var L=O("left"),q=O("right"),G={name:"jitter",type:"blending",emoji:"๐ซจ",description:"Nervous jittery movement",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},intensity:15,frequency:30,strength:1},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:2,offBeat:.5,curve:"pulse"},patternOverrides:{breakbeat:{amplitudeSync:{onBeat:3,offBeat:.3}},dubstep:{amplitudeSync:{onBeat:5,offBeat:.1,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.jitter||(e.gestureData.jitter={originalSize:e.size});const r={...this.config,...i};let o=r.intensity||this.config.intensity;const l=r.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1);const h=(Math.random()-.5)*o*l,c=(Math.random()-.5)*o*l,u=1-.5*t;e.vx+=.1*h*s*u,e.vy+=.1*c*s*u,e.size=e.baseSize*(1+.1*(Math.random()-.5))},cleanup(e){e.gestureData?.jitter?(e.size=e.gestureData.jitter.originalSize,delete e.gestureData.jitter):e.size=e.baseSize,e.vx*=.7,e.vy*=.7},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.intensity||this.config.intensity;const n=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const a=Math.sin(e*Math.PI),r=s*n*.002*a;return{position:[(Math.random()-.5)*r,(Math.random()-.5)*r,(Math.random()-.5)*r],rotation:[.005*(Math.random()-.5)*a,.005*(Math.random()-.5)*a,.005*(Math.random()-.5)*a],scale:1+.02*(Math.random()-.5)*a}}}},H={name:"twitch",emoji:"โก",type:"blending",description:"Nervous, paranoid twitching",config:{intensity:8,frequency:.08,duration:100,musicalDuration:{musical:!0,beats:.5},recovery:200,maxOffset:15,sharpness:.9},rhythm:{enabled:!0,syncMode:"subdivision",durationSync:{mode:"beats",beats:.5},probabilitySync:{subdivision:"sixteenth",onBeat:.3,offBeat:.05,accentBoost:2},intensitySync:{onBeat:2,offBeat:.8,curve:"pulse"},patternOverrides:{breakbeat:{probabilitySync:{onBeat:.5,offBeat:.1},intensitySync:{onBeat:3,offBeat:.5}},dubstep:{intensitySync:{onBeat:1.5,dropBeat:5,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.twitch||(e.gestureData.twitch={twitchOffset:{x:0,y:0},targetOffset:{x:0,y:0},isTwitching:!1,twitchTimer:0,cooldownTimer:0,lastTwitch:0});const r=e.gestureData.twitch,{config:o}=this;let l=i.intensity||o.intensity;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.probabilityMultiplier);const h=Date.now();if(!r.isTwitching&&r.cooldownTimer<=0&&Math.random()<(i.frequency||o.frequency)){r.isTwitching=!0,r.twitchTimer=o.duration,r.cooldownTimer=o.recovery;const e=Math.random()*Math.PI*2,t=.5*o.maxOffset+Math.random()*(.5*o.maxOffset);r.targetOffset={x:Math.cos(e)*t*l/8,y:Math.sin(e)*t*l/8},r.lastTwitch=h}if(r.cooldownTimer>0&&(r.cooldownTimer-=16*s),r.isTwitching)if(r.twitchTimer-=16*s,r.twitchTimer>0){const{sharpness:e}=o;r.twitchOffset.x+=(r.targetOffset.x-r.twitchOffset.x)*e,r.twitchOffset.y+=(r.targetOffset.y-r.twitchOffset.y)*e}else r.isTwitching=!1;else r.twitchOffset.x*=.85,r.twitchOffset.y*=.85;e.vx+=r.twitchOffset.x*s*.5,e.vy+=r.twitchOffset.y*s*.5,Math.random()<.1&&(e.vx+=(Math.random()-.5)*l*.3,e.vy+=(Math.random()-.5)*l*.3)},cleanup(e){e.gestureData?.twitch&&delete e.gestureData.twitch},"3d":{evaluate(e,t){const i=t.config||{};let s=.6*(i.intensity||8);const n=i.maxOffset||15,a=i.frequency||.08;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const r=9999*Math.floor(10*e),o=e=>{const t=1e4*Math.sin(r+e);return t-Math.floor(t)};if(o(0)<3*a){const e=o(1)*Math.PI*2,t=n*s/8*.003;return{position:[Math.cos(e)*t*o(2),Math.sin(e)*t*o(3),(o(4)-.5)*t],rotation:[.12*(o(5)-.5),.12*(o(6)-.5),.12*(o(7)-.5)],scale:1+.06*(o(8)-.5)}}{const e=.3;return{position:[(o(10)-.5)*e,(o(11)-.5)*e,(o(12)-.5)*e],rotation:[.006*(o(13)-.5),.006*(o(14)-.5),.006*(o(15)-.5)],scale:1}}}}},j={name:"vibrate",emoji:"๐ณ",type:"blending",description:"High frequency vibration",config:{duration:500,frequency:20,amplitude:8,easing:"linear",strength:2,particleMotion:{type:"shake",strength:2,frequency:20,amplitude:8}},rhythm:{enabled:!0,syncMode:"subdivision",frequencySync:{subdivision:"thirty-second",baseFrequency:20,tempoScaling:!0},amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"pulse"},durationSync:{mode:"beats",beats:1},patternOverrides:{dubstep:{frequencySync:{subdivision:"sixteenth"},amplitudeSync:{onBeat:2,dropBeat:3}},breakbeat:{frequencySync:{mode:"random",range:[15,30]}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.vibrate={timer:0,seed:1e3*Math.random(),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.vibrate?.initialized||this.initialize(e,i);const r=e.gestureData.vibrate,o={...this.config,...i},l=o.strength||this.config.strength||1;let{amplitude:h}=o,{frequency:c}=o;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier)),r.timer+=s*c;const u=(Math.random()-.5)*h*l,d=(Math.random()-.5)*h*l;if(e.vx+=.5*u*s,e.vy+=.5*d*s,e.vx*=.9,e.vy*=.9,t>.8){const i=1-5*(t-.8);e.vx*=i,e.vy*=i}},cleanup(e){e.gestureData?.vibrate&&delete e.gestureData.vibrate},"3d":{evaluate(e,t){const i={...this.config,...t};let{amplitude:s}=i;const n=i.strength||this.config.strength||1;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const a=Math.sin(e*Math.PI),r=s*n*.003*a;return{position:[(Math.random()-.5)*r,(Math.random()-.5)*r,(Math.random()-.5)*r],rotation:[.01*(Math.random()-.5)*a,.01*(Math.random()-.5)*a,.01*(Math.random()-.5)*a],scale:1+.01*(Math.random()-.5)*a}}}},$={name:"shake",emoji:"๐ซจ",type:"blending",description:"Random jitter movement for vibration effects",config:{duration:400,amplitude:15,frequency:15,decay:.9,smoothing:.1,axes:"both",easing:"linear",strength:3,particleMotion:{type:"shake",strength:3,frequency:15,decay:!1}},rhythm:{enabled:!0,syncMode:"subdivision",amplitudeSync:{subdivision:"sixteenth",onBeat:2.5,offBeat:.7,curve:"pulse"},frequencySync:{mode:"tempo",baseFrequency:15,scaling:"linear"},durationSync:{mode:"beats",beats:2},patternOverrides:{breakbeat:{amplitudeSync:{onBeat:3,offBeat:.2},frequencySync:{mode:"random",range:[8,20]}},dubstep:{amplitudeSync:{subdivision:"eighth",onBeat:4,dropBeat:6,curve:"pulse"}},swing:{amplitudeSync:{onBeat:1.8,offBeat:1,curve:"ease"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.shake={originalX:e.x,originalY:e.y,randomAngle:Math.random()*Math.PI*2,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.shake?.initialized||this.initialize(e,i);const r=e.gestureData.shake,o={...this.config,...i},l=o.strength||this.config.strength||1;let{amplitude:h}=o,{frequency:c}=o;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier));const u=o.decay?1-t:1,d=Math.sin(t*Math.PI*c)*h*u*l*e.scaleFactor,g=d*Math.cos(r.randomAngle),m=d*Math.sin(r.randomAngle);e.x=r.originalX+g,e.y=r.originalY+m},pseudoRandom(e){const t=1e4*Math.sin(e);return t-Math.floor(t)},cleanup(e){e.gestureData?.shake&&(e.x=e.gestureData.shake.originalX,e.y=e.gestureData.shake.originalY,delete e.gestureData.shake)},"3d":{evaluate(e,t){const i=t||{},s=.003*(i.amplitude||15),n=i.frequency||15,a=.5*(i.strength||1),r=i.decay?1-e:1,o=Math.sin(e*Math.PI*n)*s*r*a,l=Math.floor(e*n);return{position:[o*(1e4*Math.sin(l)%1-.5)*2,0,o*(1e4*Math.sin(1.3*l)%1-.5)*2],rotation:[0,0,o*(1e4*Math.sin(1.7*l)%1-.5)*.2],scale:1}}}},W={name:"wiggle",emoji:"ใฐ๏ธ",type:"additive",description:"Rapid side-to-side oscillation",config:{duration:600,musicalDuration:{musical:!0,beats:1},amplitude:15,frequency:6,strength:1,damping:.3,easing:"linear",particleMotion:{type:"wiggle",strength:1,amplitude:15,frequency:6}},rhythm:{enabled:!0,syncMode:"beat",frequencySync:{subdivision:"sixteenth",wigglePerBeat:4},amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},durationSync:{mode:"beats",beats:1}},apply(e,t,i,s,n,a,r){const o=(i.amplitude||this.config.amplitude)*n,l=i.frequency||this.config.frequency,h=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*l)*o*h;e.vx+=.5*c;const u=Math.cos(s*Math.PI*l*2)*o*.1*h;e.vy+=.3*u},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.amplitude||15,a=Math.pow(1-e,.5),r=Math.sin(e*Math.PI*14)*a,o=Math.cos(e*Math.PI*14*.7)*a*.4,l=n/15*s,h=.15*r*s;return{cameraRelativePosition:[.08*r*l,.02*Math.abs(o)*l,0],cameraRelativeRotation:[0,0,h],scale:1+.05*Math.abs(r),glowIntensity:1+.2*Math.abs(r)}}}};function U(e){const t=A[e];if(!t)throw new Error(`Invalid step direction: ${e}`);return{name:`step${D(e)}`,emoji:"left"===e?"๐":"right"===e?"๐":"up"===e?"๐":"๐",type:"blending",description:`Quick step ${e} and return`,config:{duration:400,amplitude:25,strength:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:5,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"snap"}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l,h=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1),l=i<.3?this.easeOutQuad(i/.3):1-this.easeInOutCubic((i-.3)/.7);const c=t.x*h*l*.01*n,u=t.y*h*l*.01*n;e.vx+=c,e.vy+=u},cleanup(e){},easeOutQuad:e=>1-(1-e)*(1-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||25,a=s.strength||.7;let r,o=.008*n*a;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),e<.3)r=1-(1-e/.3)*(1-e/.3);else{const t=(e-.3)/.7;r=1-(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)}const l=t.x*o*r,h=t.y*o*r,c=.12*r*a,u=-t.x*c;return{cameraRelativePosition:[l,h,0],rotation:[t.y*c*.5,0,u],scale:1}}}}}function V(e){const t=A[e];if(!t)throw new Error(`Invalid slide direction: ${e}`);return{name:`slide${D(e)}`,emoji:"left"===e?"โฌ
๏ธ":"โก๏ธ",type:"blending",description:`Smooth slide ${e} and return`,config:{duration:800,amplitude:35,strength:.6,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:1.2,offBeat:.9,curve:"ease"}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1);const h=Math.sin(i*Math.PI),c=t.x*l*h*.008*n,u=t.y*l*h*.008*n;e.vx+=c,e.vy+=u},cleanup(e){},"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||35,a=s.strength||.6;let r=.008*n*a;i.rhythmModulation&&(r*=i.rhythmModulation.amplitudeMultiplier||1);const o=Math.sin(e*Math.PI),l=t.x*r*o,h=t.y*r*o,c=.08*o*a,u=-t.x*c,d=t.x*c*.5;return{cameraRelativePosition:[l,h,.02*Math.sin(e*Math.PI*2)*a],rotation:[0,d,u],scale:1+.03*o}}}}}var Y=U("left"),X=U("right"),N=U("up"),Q=U("down"),J=V("left"),K=V("right"),Z={name:"runningman",emoji:"๐",type:"effect",description:"Hip-hop running man shuffle",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},slideDistance:30,stepHeight:15,speed:1.2,strength:.8,particleMotion:{type:"runningman",strength:.7}},rhythm:{enabled:!0,syncToBeat:!0,durationSync:{mode:"bars",bars:1},beatMultiplier:1,accentBeats:[1,3]},apply:(e,t,i,s,n,a)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i={...this.config,...t}.strength||.8;return{position:[.1*Math.sin(e*Math.PI*4)*i,.05*Math.abs(Math.sin(e*Math.PI*8))*i,0],rotation:[0,0,.035*Math.sin(e*Math.PI*4)*i],scale:1-.035*Math.abs(Math.sin(e*Math.PI*8))*i,glowIntensity:1+.25*Math.abs(Math.sin(e*Math.PI*8)),glowBoost:.35*Math.max(0,Math.abs(Math.sin(e*Math.PI*8)))}}}},ee={name:"charleston",emoji:"๐บ",type:"effect",description:"Hip-hop Charleston shuffle with crisscross",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},kickDistance:35,swivelRange:40,bounceHeight:12,strength:.9,particleMotion:{type:"charleston",strength:.8}},rhythm:{enabled:!0,syncToBeat:!0,durationSync:{mode:"bars",bars:1.5},beatMultiplier:2,accentBeats:[1,2.5,3,4.5]},apply:(e,t,i,s,n,a)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i={...this.config,...t}.strength||.9;return{position:[.12*Math.sin(e*Math.PI*8)*i,.05*Math.abs(Math.sin(e*Math.PI*8))*i,0],rotation:[0,0,.05*Math.sin(e*Math.PI*8)*i],scale:1-.04*Math.abs(Math.sin(e*Math.PI*8))*i,glowIntensity:1+.3*Math.abs(Math.sin(e*Math.PI*8)),glowBoost:.4*Math.max(0,Math.abs(Math.sin(e*Math.PI*8)))}}}},te={name:"hula",emoji:"๐",type:"override",description:"Hula-hoop motion with vertical waves",config:{speed:.015,maintainRadius:!1,elliptical:!0,use3D:!0,zPhaseOffset:Math.PI/4,verticalOscillation:.3,wobbleAmount:.15,duration:2500,musicalDuration:{musical:!0,bars:1.5},particleMotion:{type:"hula",strength:1,verticalOscillation:.3}},rhythm:{enabled:!0,syncMode:"bar",durationSync:{mode:"bars",bars:1.5},speedSync:{mode:"tempo",baseSpeed:.015,scaling:"proportional"},wobbleSync:{onBeat:.25,offBeat:.1,curve:"sine"},verticalSync:{subdivision:"quarter",amplitude:.4,phase:"sequential"},dynamics:{forte:{wobbleAmount:.3,speed:1.2},piano:{wobbleAmount:.05,speed:.8}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.random()<.5?1:-1,l=Math.max(r,100+180*Math.random()),h=r<5?Math.random()*Math.PI*2:Math.atan2(a,n);e.gestureData.hula={radius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,wobblePhase:Math.random()*Math.PI*2,direction:o}},apply(e,t,i,s,n,a){e.gestureData?.hula||this.initialize(e,i,n,a);const r=e.gestureData.hula,o=(i.speed||this.config.speed)*(i.strength||1);let l=1;t<.1?(l=t/.1,l=Math.sin(l*Math.PI*.5)):t>.9&&(l=(1-t)/.1,l=Math.sin(l*Math.PI*.5)),r.angle+=o*s*r.direction*l;const h=Math.sin(2*r.angle+r.wobblePhase)*(i.wobbleAmount||this.config.wobbleAmount)*l,c=r.radius*(1+h)*l,u=r.radius*(.7+h)*l,d=n+Math.cos(r.angle)*c,g=a+Math.sin(r.angle)*u;if(t<.1){const t=e.x-n,i=e.y-a;Math.sqrt(t*t+i*i)<50?(e.x=n+Math.cos(r.angle)*c,e.y=a+Math.sin(r.angle)*u):(e.x=e.x+(d-e.x)*l*.5,e.y=e.y+(g-e.y)*l*.5)}else e.x=d,e.y=g;const m=r.angle+r.zPhase+(i.zPhaseOffset||this.config.zPhaseOffset);e.z=.9*Math.sin(m)*l;const p=i.verticalOscillation||this.config.verticalOscillation,f=Math.cos(2*m)*p*r.radius*.2*l;e.y+=f;const y=e.z*r.radius*.1;e.y-=y;const b=-Math.sin(r.angle)*c*o,v=Math.cos(r.angle)*u*o;t<.1?(e.vx=r.originalVx+(b-r.originalVx)*l,e.vy=r.originalVy+(v-r.originalVy)*l):t>.9?(e.vx=b*l+r.originalVx*(1-l),e.vy=v*l+r.originalVy*(1-l),e.z=e.z*l+r.originalZ*(1-l)):(e.vx=b,e.vy=v)},cleanup(e){if(e.gestureData?.hula){const t=e.gestureData.hula;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.hula}},"3d":{evaluate(e,t){const{particle:i}=t;if(!i||!i.gestureData?.hula)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.hula,n=t.config||{};let a=1;e<.15?(a=e/.15,a=Math.sin(a*Math.PI*.5)):e>.85&&(a=(1-e)/.15,a=Math.sin(a*Math.PI*.5));const r=s.initialAngle+e*Math.PI*2*s.direction,o=.25*Math.cos(r)*a,l=.25*Math.sin(r)*a,h=n.verticalOscillation||.3;return{position:[o,Math.sin(2*r+s.wobblePhase)*h*a,l],rotation:[0,(r-s.initialAngle)*a,0],scale:1+.15*Math.abs(Math.sin(r))*a}}}},ie={name:"twist",emoji:"๐",type:"override",description:"Twisting dance motion with alternating rotation",config:{duration:1200,musicalDuration:{musical:!0,beats:3},rotationAngle:45,contractionFactor:.8,twistFrequency:2,easing:"smooth",strength:.8,particleMotion:{type:"twist",rotationAngle:45,contractionFactor:.8,twistFrequency:2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!1,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"elastic"},patternOverrides:{funk:{rotationAngle:60,contractionFactor:.7},disco:{twistFrequency:3,rotationAngle:50},latin:{rotationAngle:35,contractionFactor:.85,twistFrequency:2.5}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.twist={startX:e.x,startY:e.y,startAngle:Math.atan2(e.y-t.centerY,e.x-t.centerX),startDistance:Math.sqrt(Math.pow(e.x-t.centerX,2)+Math.pow(e.y-t.centerY,2)),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.twist?.initialized||this.initialize(e,{...i,centerX:n,centerY:a});const r={...this.config,...i},o=e.gestureData.twist,l=r.strength||this.config.strength||1,h=t*r.twistFrequency*Math.PI*2,c=Math.sin(h)*l;let{rotationAngle:u}=r,{contractionFactor:d}=r;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,d=1-(1-d)*(i.rhythmModulation.amplitudeMultiplier||1));const g=u*Math.PI/180*c,m=1-(1-d)*Math.abs(c),p=o.startAngle+g,f=o.startDistance*m,y=n+Math.cos(p)*f,b=a+Math.sin(p)*f,v=.15*l;e.x+=(y-e.x)*v,e.y+=(b-e.y)*v,e.vx=.05*(y-e.x),e.vy=.05*(b-e.y);const M=5*Math.sin(t*Math.PI*4)*l;if(e.y+=.1*M,t>.9){const i=1-10*(t-.9);e.vx*=i,e.vy*=i}},cleanup(e){e.gestureData?.twist&&delete e.gestureData.twist},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||.8,n=e>.85?(1-e)/.15:1,a=e*(i.twistFrequency||2)*Math.PI*2,r=Math.sin(a)*s*n,o=r*((i.rotationAngle||45)*Math.PI/180);return{position:[.05*Math.sin(a)*s*n,.02*Math.abs(Math.sin(2*a))*s*n,0],rotation:[.08*Math.cos(a)*s*n,o,.12*Math.sin(.5*a)*s*n],scale:1-(1-(i.contractionFactor||.8))*Math.abs(r),glowIntensity:1+.3*Math.abs(r)}}}},se={name:"pop",emoji:"๐ฅ",type:"blending",description:"Quick scale pulse - the classic beat hit",config:{duration:200,musicalDuration:{musical:!0,beats:.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:.5},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;return e<.15?(s=e/.15,s=1-Math.pow(1-s,3)):(s=1-(e-.15)/.85,s=Math.pow(s,2)),{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+.08*s*i,glowBoost:.3*s*i,positionBoost:[0,.02*s*i,0]}}}},ne={name:"flare",emoji:"๐ฅ",type:"blending",description:"Dramatic scale burst with intense glow - for big moments",config:{duration:400,musicalDuration:{musical:!0,beats:1},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1},interruptible:!0,priority:6,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.1){const t=e/.1;s=1-Math.pow(1-t,4)}else if(e<.3){const t=(e-.1)/.2;s=1-.1*Math.sin(t*Math.PI)}else s=1-(e-.3)/.7,s=Math.pow(s,.6);return{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+(.15*s+.15*Math.sin(e*Math.PI*4)*(1-e)*.02)*i,glowBoost:.8*s*i,positionBoost:[0,.04*s*i,0]}}}},ae={name:"swell",emoji:"๐",type:"blending",description:"Glow build with scale - for transitions and builds",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1.5},interruptible:!0,priority:4,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.6){const t=e/.6;s=t*t}else{const t=(e-.6)/.4;s=1-t*t}return{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+.1*s*i,glowBoost:.4*s*i,positionBoost:[0,.03*Math.sin(e*Math.PI)*i,0]}}}},re={name:"swagger",emoji:"๐",type:"blending",description:"Side lean with drift - confident swagger",config:{duration:400,musicalDuration:{musical:!0,beats:1},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1},interruptible:!0,priority:4,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.3){const t=e/.3;s=1-Math.pow(1-t,2)}else if(e<.7)s=1;else{const t=(e-.7)/.3;s=1-t*t}return{position:[0,0,0],rotation:[0,0,0],scale:1,rotationBoost:[0,0,.12*s*i*1],positionBoost:[.04*s*i*1,.01*s*i,0],scaleBoost:1+.03*s*i}}}},oe={name:"dip",emoji:"โฌ๏ธ",type:"blending",description:"Downward bob - groove dip feel",config:{duration:250,musicalDuration:{musical:!0,beats:.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:.5},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1,s=Math.sin(e*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1,positionBoost:[0,.015*-s*i,0],scaleBoost:1-.015*s*i}}}},le={name:"bounce",emoji:"โฌ๏ธ",type:"blending",description:"Vertical oscillation with smooth easing",config:{duration:800,musicalDuration:{musical:!0,beats:2},amplitude:30,frequency:2,axis:"vertical",damping:!0,easing:"sine",strength:.6,particleMotion:{type:"bounce",axis:"vertical",strength:.6,frequency:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.8,offBeat:.6,curve:"bounce"},frequencySync:{mode:"tempo",multiplier:1},durationSync:{mode:"beats",beats:4},accentResponse:{enabled:!0,multiplier:1.5},patternOverrides:{waltz:{frequencySync:{multiplier:.75},durationSync:{beats:3}},swing:{amplitudeSync:{onBeat:2,offBeat:.4,curve:"ease"}},dubstep:{amplitudeSync:{onBeat:1.5,dropBeat:3,curve:"pulse"}},breakbeat:{frequencySync:{multiplier:1.5},amplitudeSync:{onBeat:2.2,offBeat:.3}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.bounce={startY:e.y,startX:e.x,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.bounce?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t);let{frequency:h}=r;const c=i.phase||0;let u=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,u*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const d=Math.sin((l+c)*Math.PI*2*h);if(r.damping&&t>.7&&(u*=1-(t-.7)/.3*.8),"vertical"===r.axis?(e.vy+=d*u*.01*s,t>.9&&(e.vx*=.98)):"horizontal"===r.axis&&(e.vx+=d*u*.01*s,t>.9&&(e.vy*=.98)),t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.bounce&&delete e.gestureData.bounce},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||30,n=i.frequency||2,a=.003*s*(i.strength||.6),r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*Math.PI*n,o=Math.abs(Math.sin(r));let l=a;return e>.7&&(l*=1-(e-.7)/.3*.8),{position:[0,o*l,0],rotation:[0,0,0],scale:1+.08*o}}}},he={name:"orbit",emoji:"๐ช",type:"override",description:"Orbital motion around center",config:{speed:.02,maintainRadius:!0,elliptical:!1,use3D:!0,zPhaseOffset:0,verticalOscillation:0,duration:3e3,musicalDuration:{musical:!0,bars:2},particleMotion:{type:"orbit",strength:1}},rhythm:{enabled:!0,syncMode:"harmonic",durationSync:{mode:"bars",bars:2},speedSync:{tonic:.02,fifth:.03,octave:.04,third:.025,curve:"smooth"},radiusSync:{bass:150,mid:100,treble:50,scaling:"logarithmic"},depthSync:{major:{z:1,phase:0},minor:{z:-1,phase:Math.PI},diminished:{z:.5,phase:Math.PI/2},augmented:{z:.8,phase:-Math.PI/2}},phaseSync:{mode:"harmonic",intervals:[1,1.5,2],drift:.05},dynamics:{forte:{speed:.04,maintainRadius:!1},piano:{speed:.01,maintainRadius:!0}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.random()<.5?1:-1,l=Math.max(r,100+180*Math.random()),h=r<5?Math.random()*Math.PI*2:Math.atan2(a,n);e.gestureData.orbit={radius:l,targetRadius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,direction:o}},apply(e,t,i,s,n,a){e.gestureData?.orbit||this.initialize(e,i,n,a);const r=e.gestureData.orbit,o=(i.speed||this.config.speed)*(i.strength||1);r.angle+=o*s*r.direction;let{radius:l}=r;if(i.maintainRadius||(l=r.radius*(1+.1*Math.sin(t*Math.PI*2))),e.x=n+Math.cos(r.angle)*l,e.y=a+Math.sin(r.angle)*l,!1!==i.use3D){const t=r.angle+r.zPhase+(i.zPhaseOffset||0);if(e.z=.8*Math.sin(t),i.verticalOscillation){const s=Math.cos(t)*i.verticalOscillation*l*.1;e.y+=s}}if(e.vx=-Math.sin(r.angle)*l*o,e.vy=Math.cos(r.angle)*l*o,t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.orbit){const t=e.gestureData.orbit;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.orbit}},"3d":{evaluate(e,t){const i=t?.particle;if(!i||!i.gestureData?.orbit)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.orbit;let n=1;e<.15?n=Math.sin(e/.15*Math.PI*.5):e>.85&&(n=Math.sin((1-e)/.15*Math.PI*.5));const a=s.initialAngle+e*Math.PI*2*s.direction,r=.3*Math.cos(a)*n,o=.3*Math.sin(a)*n,l=(a+Math.PI/2-(s.initialAngle+Math.PI/2))*n,h=i.z||0;return{position:[r,0,o+.1*h*n],rotation:[0,l,0],scale:1+.15*h*n}}}};function ce(e){const t=A[e];if(!t)throw new Error(`Invalid orbit direction: ${e}`);const i="up"===e||"down"===e,s="left"===e||"up"===e?1:-1;return{name:`orbit${D(e)}`,emoji:"left"===e?"๐":"right"===e?"๐":"up"===e?"๐":"๐ซ",type:"override",description:`Orbit ${"left"===e?"counter-clockwise":"right"===e?"clockwise":e}`,config:{duration:1500,musicalDuration:{musical:!0,beats:4},speed:.02,maintainRadius:!0,use3D:!0,rotations:1,strength:1,direction:e,verticalOscillation:i?.3:0,particleMotion:{type:"orbit",strength:1,rotations:1}},rhythm:{enabled:!0,syncMode:"harmonic",durationSync:{mode:"bars",bars:1},speedSync:{tonic:.02,fifth:.03,octave:.04,curve:"smooth"},radiusSync:{bass:150,mid:100,treble:50,scaling:"logarithmic"},dynamics:{forte:{speed:.04,maintainRadius:!1},piano:{speed:.01,maintainRadius:!0}}},initialize(e,t,i,n){e.gestureData||(e.gestureData={});const a=e.x-i,r=e.y-n,o=Math.sqrt(a*a+r*r),l=Math.max(o,80+100*Math.random()),h=o<5?Math.random()*Math.PI*2:Math.atan2(r,a);e.gestureData.orbit={radius:l,targetRadius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,direction:s,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.orbit?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.orbit,h={...this.config,...n},c=n.strength||1,u=(h.speed||.02)*c;let d=1;s<.15?(d=s/.15,d=Math.sin(d*Math.PI*.5)):s>.85&&(d=(1-s)/.15,d=Math.sin(d*Math.PI*.5)),l.angle+=u*a*l.direction*d;let{radius:g}=l;h.maintainRadius||(g=l.radius*(1+.1*Math.sin(s*Math.PI*2)));const m=g*d+(1-d)*l.radius*.5;if(e.x=r+Math.cos(l.angle)*m,e.y=o+Math.sin(l.angle)*m,!1!==h.use3D){const n=l.angle+l.zPhase;if(e.z=.8*Math.sin(n)*d,i&&h.verticalOscillation){const i=t.y*s*h.verticalOscillation*g*.5;e.y+=i}}if(e.vx=-Math.sin(l.angle)*m*u*d,e.vy=Math.cos(l.angle)*m*u*d,s>.9){const t=10*(1-s);e.vx=e.vx*t+l.originalVx*(1-t),e.vy=e.vy*t+l.originalVy*(1-t)}},cleanup(e){if(e.gestureData?.orbit){const t=e.gestureData.orbit;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.orbit}},"3d":{evaluate(e,n){const a=n.config||n||{},r=n.strength||1,o=a.rotations||1;let l=1;e<.15?l=Math.sin(e/.15*Math.PI*.5):e>.85&&(l=Math.sin((1-e)/.15*Math.PI*.5));const h=.25*r,c=e*Math.PI*2*o*s,u=Math.cos(c)*h*l,d=Math.sin(c)*h*l;let g=0;return i&&(g=t.y*e*.2*r*l),{cameraRelativePosition:[u,g,d],rotation:[0,c*l*.5,0],scale:1+.2*d}}}}}var ue=ce("left"),de=ce("right"),ge=ce("up"),me=ce("down"),pe={name:"jump",emoji:"๐ฆ",type:"override",description:"Squash, leap, and land with classic animation principles",config:{duration:800,musicalDuration:{musical:!0,beats:2},jumpHeight:60,squashAmount:.8,stretchAmount:1.2,anticipation:.2,hangTime:.1,landingImpact:!0,driftOutward:!0,easing:"quad",particleMotion:{type:"jump",strength:.9,jumpHeight:60,squash:.8,stretch:1.2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},phaseSync:{anticipation:"eighth",jump:"beat",landing:"sixteenth"},heightSync:{onBeat:1.5,offBeat:.8,accent:2,curve:"exponential"},deformationSync:{squashOnBeat:.6,stretchOnBeat:1.4,timing:"anticipatory"},hangTimeSync:{mode:"tempo",baseDuration:.1,scaling:"inverse"},dynamics:{forte:{jumpHeight:80,stretch:1.3},piano:{jumpHeight:30,stretch:1.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.jump={startX:e.x,startY:e.y,startSize:e.size,originalVx:e.vx,originalVy:e.vy,driftDirection:.1*(e.x-i),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.jump?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.jump,o={...this.config,...i},l=i.strength||1,h=o.jumpHeight*l*e.scaleFactor,c=o.squashAmount,u=o.stretchAmount,d=o.anticipation,g=1-.5*o.anticipation;if(t<d){const i=t/d,s=this.easeOutQuad(i);e.size=r.startSize*(1-(1-c)*s),e.y=r.startY+5*s*e.scaleFactor,e.vx=0,e.vy=0}else if(t<g){const i=(t-d)/(g-d);let s=Math.sin(i*Math.PI);if(o.hangTime>0&&i>.4&&i<.6){const e=(i-.4)/.2;s=.95+.05*this.easeInOutCubic(e)}if(e.y=r.startY-s*h,o.driftOutward&&(e.x=r.startX+s*r.driftDirection),i<.5){const t=2*i;e.size=r.startSize*(c+(u-c)*t)}else{const t=2*(i-.5);e.size=r.startSize*(u-(u-1)*t*.8)}e.vx=.5*r.driftDirection,e.vy=-Math.cos(i*Math.PI)*h*.1}else{const i=(t-g)/(1-g),s=this.easeOutBounce(i);if(e.y=r.startY,o.landingImpact)if(i<.3){const t=i/.3;e.size=r.startSize*(1-(1-.8*c)*(1-t))}else{const t=(i-.3)/.7;e.size=r.startSize*(.8*c+(1-.8*c)*t)}else e.size=r.startSize*(c+(1-c)*s);e.vx=r.originalVx*s,e.vy=r.originalVy*s}},cleanup(e){if(e.gestureData?.jump){const t=e.gestureData.jump;e.size=t.startSize,e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.jump}},easeOutQuad:e=>e*(2-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutBounce(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375},"3d":{evaluate(e,t){const i=t.config||t||{},s=t.strength||1,n=.004*(i.jumpHeight||60)*s,a=i.squashAmount||.8,r=i.stretchAmount||1.2,o=i.anticipation||.2,l=1-.5*o;let h=0,c=1,u=0;if(e<o){const t=e/o,i=t*(2-t);c=1-(1-a)*i,h=.02*-i}else if(e<l){const t=(e-o)/(l-o);h=Math.sin(t*Math.PI)*n,c=t<.5?a+2*t*(r-a):r-2*(t-.5)*(r-1)*.8,u=.05*Math.sin(t*Math.PI)}else{const t=(e-l)/(1-l);if(t<.5){const e=2*t;h=-Math.sin(e*Math.PI)*n*.15}else h=0;c=!1!==i.landingImpact?t<.3?1-(1-.8*a)*(1-t/.3):.8*a+(t-.3)/.7*(1-.8*a):a+(1-a)*t}return{position:[0,h,0],rotation:[u,0,0],scale:c}}}};function fe(e){const t=A[e];if(!t)throw new Error(`Invalid jump direction: ${e}`);const i="up"===e||"down"===e;return{name:`jump${D(e)}`,emoji:"up"===e?"๐ฆ":"down"===e?"๐ฅ":"left"===e?"โฌ
๏ธ":"โก๏ธ",type:"override",description:`Jump ${e} with squash & stretch`,config:{duration:800,musicalDuration:{musical:!0,beats:2},jumpDistance:60,squashAmount:.8,stretchAmount:1.2,anticipation:.2,hangTime:.1,landingImpact:!0,easing:"quad",strength:1,direction:e,particleMotion:{type:"jump",strength:.9,jumpDistance:60,squash:.8,stretch:1.2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},phaseSync:{anticipation:"eighth",jump:"beat",landing:"sixteenth"},distanceSync:{onBeat:1.5,offBeat:.8,accent:2,curve:"exponential"},deformationSync:{squashOnBeat:.6,stretchOnBeat:1.4,timing:"anticipatory"},dynamics:{forte:{jumpDistance:80,stretch:1.3},piano:{jumpDistance:30,stretch:1.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.jump={startX:e.x,startY:e.y,startSize:e.size,originalVx:e.vx,originalVy:e.vy,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.jump?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.jump,h={...this.config,...n},c=n.strength||1,u=h.jumpDistance*c*e.scaleFactor,d=h.squashAmount,g=h.stretchAmount,m=h.anticipation,p=1-.5*h.anticipation;if(s<m){const n=s/m,a=this.easeOutQuad(n);e.size=l.startSize*(1-(1-d)*a),i?e.y=l.startY-t.y*a*5*e.scaleFactor:e.x=l.startX-t.x*a*5*e.scaleFactor,e.vx=0,e.vy=0}else if(s<p){const n=(s-m)/(p-m);let a=Math.sin(n*Math.PI);if(h.hangTime>0&&n>.4&&n<.6){const e=(n-.4)/.2;a=.95+.05*this.easeInOutCubic(e)}if(i?(e.y=l.startY+t.y*a*u,e.x=l.startX+3*Math.sin(n*Math.PI*2)):(e.x=l.startX+t.x*a*u,e.y=l.startY-Math.sin(n*Math.PI)*u*.3),n<.5){const t=2*n;e.size=l.startSize*(d+(g-d)*t)}else{const t=2*(n-.5);e.size=l.startSize*(g-(g-1)*t*.8)}i?(e.vy=t.y*Math.cos(n*Math.PI)*u*.1,e.vx=0):(e.vx=t.x*Math.cos(n*Math.PI)*u*.1,e.vy=-Math.cos(n*Math.PI)*u*.05)}else{const t=(s-p)/(1-p),i=this.easeOutBounce(t);if(e.x=l.startX,e.y=l.startY,h.landingImpact)if(t<.3){const i=t/.3;e.size=l.startSize*(1-(1-.8*d)*(1-i))}else{const i=(t-.3)/.7;e.size=l.startSize*(.8*d+(1-.8*d)*i)}else e.size=l.startSize*(d+(1-d)*i);e.vx=l.originalVx*i,e.vy=l.originalVy*i}},cleanup(e){if(e.gestureData?.jump){const t=e.gestureData.jump;e.size=t.startSize,e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.jump}},easeOutQuad:e=>e*(2-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutBounce(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375},"3d":{evaluate(e,s){const n=s.config||s||{},a=s.strength||1,r=.004*(n.jumpDistance||60)*a,o=n.squashAmount||.8,l=n.stretchAmount||1.2,h=n.anticipation||.2,c=1-.5*h;let u=0,d=0,g=1,m=0,p=0,f=0;if(e<h){const s=e/h,n=s*(2-s);g=1-(1-o)*n,i?d=-t.y*n*.02:u=-t.x*n*.02}else if(e<c){const s=(e-h)/(c-h),n=Math.sin(s*Math.PI);i?d=t.y*n*r:(u=t.x*n*r,d=Math.sin(s*Math.PI)*r*.3),g=s<.5?o+2*s*(l-o):l-2*(s-.5)*(l-1)*.8,i?m=t.y*Math.sin(s*Math.PI)*.1:(p=t.x*Math.sin(s*Math.PI)*.15,f=-t.x*Math.sin(s*Math.PI)*.05)}else{const s=(e-c)/(1-c);if(s<.5){const e=2*s;i?d=-t.y*Math.sin(e*Math.PI)*r*.15:u=-t.x*Math.sin(e*Math.PI)*r*.1}g=!1!==n.landingImpact?s<.3?1-(1-.8*o)*(1-s/.3):.8*o+(s-.3)/.7*(1-.8*o):o+(1-o)*s}return{cameraRelativePosition:[u,d,0],rotation:[m,p,f],scale:g}}}}}var ye=fe("down"),be=fe("left"),ve=fe("right");function Me(e){if(!["forward","back","left","right","up","down"].includes(e))throw new Error(`Invalid rush direction: ${e}`);return{name:`rush${D(e)}`,emoji:{forward:"๐จ",back:"๐",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ"}[e],type:"override",description:{forward:"Quick rush toward camera",back:"Quick retreat away",left:"Quick strafe left",right:"Quick strafe right",up:"Quick leap upward",down:"Quick dive downward"}[e],config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1,direction:e,particleMotion:{type:"rush",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"forward";let a=0,r=0,o=0,l=0,h=0,c=1,u=1,d=0;const g={forward:{x:0,y:0,z:1,lean:{x:.2,z:0}},back:{x:0,y:0,z:-1,lean:{x:-.2,z:0}},left:{x:-1,y:0,z:0,lean:{x:0,z:.2}},right:{x:1,y:0,z:0,lean:{x:0,z:-.2}},up:{x:0,y:1,z:0,lean:{x:-.15,z:0}},down:{x:0,y:-1,z:0,lean:{x:.2,z:0}}}[n],m=.2;if(e<.2){const t=e/.2,i=1-Math.pow(1-t,2);l=i*g.lean.x*s,h=i*g.lean.z*s,r="up"===n?.03*-i*s:.02*-i*s,u=1+.3*i}else if(e<.6){const t=(e-.2)/.4,i=1-Math.pow(1-t,3);a=g.x*i*m*s,r=g.y*i*m*s,o=g.z*i*m*s,"up"===n?r+=.05*i*s:"down"!==n&&(r+=(.04*i-.02)*s),l=g.lean.x*s,h=g.lean.z*s,c=1+.08*i,u=1.3+.5*i,d=.35*i,h+=Math.sin(t*Math.PI*12)*(1-t)*.015*s}else{const t=(e-.6)/.4,i=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;if(a=g.x*m*(1-i)*s,r=g.y*m*(1-i)*s,o=g.z*m*(1-i)*s,l=g.lean.x*(1-i)*s,h=g.lean.z*(1-i)*s,c=1.08-.08*i,t>.7){const e=(t-.7)/.3;r-=.02*Math.sin(e*Math.PI)*s}u=1.8-.8*i,d=.35*(1-i)}return{cameraRelativePosition:[a,r,o],cameraRelativeRotation:[l,0,h],scale:c,glowIntensity:u,glowBoost:d}}}}}var we={name:"lunge",emoji:"๐คบ",type:"override",description:"Forward thrust lunge with emphasis",config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,direction:"forward",recover:!0,strength:1,particleMotion:{type:"lunge",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.25,a=!1!==i.recover;let r;e<.3?(r=e/.3,r=1-Math.pow(1-r,3)):e<.6?r=1:a?(r=1-(e-.6)/.4,r=Math.pow(r,2)):r=1;const o=r*n*s;return{position:[0,.05*-Math.sin(r*Math.PI)*s,o],rotation:[.2*r*s,0,0],scale:1+.1*r*s,glowIntensity:1+.3*r,glowBoost:e<.4?.4*r:0}}}};function Se(e){if(!{...A,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[e])throw new Error(`Invalid lunge direction: ${e}`);return{name:`lunge${D(e)}`,emoji:{forward:"๐คบ",back:"๐",left:"๐",right:"๐",up:"โ๏ธ",down:"๐"}[e]||"๐คบ",type:"override",description:`Lunge thrust ${e}`,config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,recover:!0,strength:1,direction:e,particleMotion:{type:"lunge",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.25,a=!1!==i.recover,r=i.direction||"forward";let o;e<.3?(o=e/.3,o=1-Math.pow(1-o,3)):e<.6?o=1:a?(o=1-(e-.6)/.4,o=Math.pow(o,2)):o=1;let l=0,h=0,c=0,u=0,d=0;switch(r){case"forward":c=o*n*s,u=.2*o*s,h=.05*-Math.sin(o*Math.PI)*s;break;case"back":c=-o*n*s,u=.2*-o*s,h=.05*-Math.sin(o*Math.PI)*s;break;case"left":l=-o*n*s,d=.2*-o*s,h=.03*-Math.sin(o*Math.PI)*s;break;case"right":l=o*n*s,d=.2*o*s,h=.03*-Math.sin(o*Math.PI)*s;break;case"up":h=o*n*s,u=.15*-o*s;break;case"down":h=-o*n*s,u=.25*o*s}return{cameraRelativePosition:[l,h,c],cameraRelativeRotation:[u,0,d],scale:1+.1*o*s,glowIntensity:1+.3*o,glowBoost:e<.4?.4*o:0}}}}}var xe={name:"spin",emoji:"๐",type:"override",description:"Orbital rotation around center point",config:{duration:600,musicalDuration:{musical:!0,beats:1},rotations:1,direction:"random",radiusMultiplier:1,spiralOut:!1,accelerate:!0,maintainDistance:!0,scaleAmount:.1,easing:"linear",strength:.7,particleMotion:{type:"spin",strength:.7,rotations:1,radius:1}},rhythm:{enabled:!0,syncMode:"bar",rotationSync:{mode:"bars",rotationsPerBar:1,accelerateOnBeat:!0},radiusSync:{subdivision:"quarter",expandOnBeat:1.2,contractOffBeat:.9,curve:"bounce"},durationSync:{mode:"beats",beats:4},patternOverrides:{waltz:{rotationSync:{rotationsPerBar:.75},radiusSync:{curve:"ease"}},swing:{rotationSync:{accelerateOnBeat:!1},direction:"alternating"},dubstep:{radiusSync:{subdivision:"eighth",expandOnBeat:1.5,dropMultiplier:2},spiralOut:!0},breakbeat:{rotationSync:{mode:"random",range:[.5,2]},direction:"random"}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;let r=t.direction||this.config.direction;"random"===r&&(r=Math.random()<.5?"clockwise":"counter-clockwise"),e.gestureData.spin={startAngle:Math.atan2(a,n),startRadius:Math.sqrt(n*n+a*a)||30,originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,direction:r,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.spin?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.spin,o={...this.config,...i},l=i.strength||1;let{rotations:h}=o,{radiusMultiplier:c}=o;i.rhythmModulation&&(i.rhythmModulation.rotationMultiplier&&(h*=i.rhythmModulation.rotationMultiplier),i.rhythmModulation.radiusMultiplier&&(c*=i.rhythmModulation.radiusMultiplier));let u=t;o.accelerate&&(u=t<.5?.5*this.easeInQuad(2*t):.5+.5*this.easeOutQuad(2*(t-.5)));const d=h*Math.PI*2*l,g="counter-clockwise"===r.direction?-1:1,m=r.startAngle+d*u*g;let p=r.startRadius;o.spiralOut&&(p*=1+.5*t),1!==c&&(p*=1+(c-1)*Math.sin(t*Math.PI));const f=n+Math.cos(m)*p,y=a+Math.sin(m)*p;if(e.x+=.25*(f-e.x),e.y+=.25*(y-e.y),e.vx=.5*(f-e.x),e.vy=.5*(y-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.spin){const t=e.gestureData.spin;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.spin}},easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const i=t?.config||t||{},s=t?.strength||1,n=t?.particle;let a=1;n?.gestureData?.spin?a="counter-clockwise"===n.gestureData.spin.direction?-1:1:"counter-clockwise"!==i.direction&&"left"!==i.direction||(a=-1);let r=e;return!1!==i.accelerate&&(r=e<.5?e*e*4*.5:.5+(e-.5)*(2-(e-.5))*.5),{position:[0,0,0],rotation:[0,(i.rotations||1)*Math.PI*2*s*r*a,0],scale:1+(i.scaleAmount||.1)*Math.sin(e*Math.PI)*s}}}};const Ce={left:"counter-clockwise",right:"clockwise"};function ke(e){const t=Ce[e];if(!t)throw new Error(`Invalid spin direction: ${e}`);const i="left"===e?-1:1;return{name:`spin${D(e)}`,emoji:"left"===e?"โบ":"โป",type:"override",description:`Spin ${t}`,config:{duration:600,rotations:1,direction:t,radiusMultiplier:1,spiralOut:!1,accelerate:!0,maintainDistance:!0,scaleAmount:.1,strength:.7},rhythm:{enabled:!0,syncMode:"bar",timingSync:"nextBeat",interruptible:!1,priority:7,blendable:!1,durationSync:{mode:"beats",beats:4},rotationSync:{mode:"bars",rotationsPerBar:1,accelerateOnBeat:!0}},initialize(e,i,s,n){e.gestureData||(e.gestureData={});const a=e.x-s,r=e.y-n;e.gestureData.spin={startAngle:Math.atan2(r,a),startRadius:Math.sqrt(a*a+r*r)||30,originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,direction:t,initialized:!0}},apply(e,t,s,n,a,r){e.gestureData?.spin?.initialized||this.initialize(e,s,a,r);const o=e.gestureData.spin,l={...this.config,...s},h=s.strength||1;let{rotations:c,radiusMultiplier:u}=l;s.rhythmModulation&&(s.rhythmModulation.rotationMultiplier&&(c*=s.rhythmModulation.rotationMultiplier),s.rhythmModulation.radiusMultiplier&&(u*=s.rhythmModulation.radiusMultiplier));let d=t;l.accelerate&&(d=t<.5?.5*this.easeInQuad(2*t):.5+.5*this.easeOutQuad(2*(t-.5)));const g=c*Math.PI*2*h,m=o.startAngle+g*d*i;let p=o.startRadius;l.spiralOut&&(p*=1+.5*t),1!==u&&(p*=1+(u-1)*Math.sin(t*Math.PI));const f=a+Math.cos(m)*p,y=r+Math.sin(m)*p;if(e.x+=.25*(f-e.x),e.y+=.25*(y-e.y),e.vx=.5*(f-e.x),e.vy=.5*(y-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+o.originalVx*(1-i),e.vy=e.vy*i+o.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.spin){const t=e.gestureData.spin;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.spin}},easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const s=t?.config||t||{},n=t?.strength||1;let a=e;return!1!==s.accelerate&&(a=e<.5?e*e*4*.5:.5+(e-.5)*(2-(e-.5))*.5),{position:[0,0,0],rotation:[0,(s.rotations||1)*Math.PI*2*n*a*i,0],scale:1+(s.scaleAmount||.1)*Math.sin(e*Math.PI)*n}}}}}var Pe=ke("left"),Te=ke("right"),Ee={name:"flip",emoji:"๐คธ",type:"override",description:"Front flip rotation with arc trajectory",config:{duration:800,musicalDuration:{musical:!0,beats:2},rotations:1,height:.3,direction:"forward",strength:1,particleMotion:{type:"flip",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotations||1,a=i.height||.3,r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*(2*-Math.PI*n),o=Math.sin(e*Math.PI)*a*s;let l=1;if(e<.1)l=1-e/.1*.15;else if(e<.2)l=.85+(e-.1)/.1*.2;else if(e>.9){const t=(e-.9)/.1;l=1.05-.1*Math.sin(t*Math.PI)}else l=1.05;return e>=.99&&(l=1),{position:[0,o,0],rotation:[r,0,0],scale:l,glowIntensity:1+.4*Math.sin(e*Math.PI),glowBoost:e>.2&&e<.8?.3:0}}}},Ae={name:"backflip",emoji:"โฌ๏ธ",type:"override",description:"Backwards flip with dramatic arc trajectory",config:{duration:900,musicalDuration:{musical:!0,beats:2},rotations:1,height:.35,strength:1,particleMotion:{type:"backflip",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotations||1,a=i.height||.35,r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*(2*Math.PI*n),o=Math.sin(e*Math.PI)*a*s,l=.1*Math.sin(e*Math.PI)*s;let h=1;if(e<.1)h=1-e/.1*.15;else if(e<.2)h=.85+(e-.1)/.1*.25;else if(e>.9){const t=(e-.9)/.1;h=1.1-.15*Math.sin(t*Math.PI)}else h=1.1;return e>=.99&&(h=1),{position:[0,o,l],rotation:[r,0,0],scale:h,glowIntensity:1+.5*Math.sin(e*Math.PI),glowBoost:.4*Math.sin(e*Math.PI)}}}},De={name:"point",emoji:"๐",type:"blending",description:"Directional pointing motion with forward momentum",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},amplitude:15,direction:"right",strength:.8,particleMotion:{type:"point",direction:"right",strength:.8}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.6},patternOverrides:{march:{amplitudeSync:{onBeat:2,offBeat:.5,curve:"pulse"}},swing:{amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"bounce"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.point={startX:e.x,startY:e.y,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.point?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t);let h=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1);const c=Math.sin(l*Math.PI);let u=0,d=0;switch(r.direction||"right"){case"right":u=1;break;case"left":u=-1;break;case"up":d=-1;break;case"down":d=1}if(e.vx+=c*h*.02*s*u,e.vy+=c*h*.02*s*d,t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.point&&delete e.gestureData.point},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||15,n=i.strength||.8,a=i.direction||"right",r=.005*s*n,o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI);let h=0,c=0;switch(a){case"right":h=l*r,c=.25*l;break;case"left":h=-l*r,c=.25*-l;break;case"up":case"down":c=0}return{position:[h,0,0],rotation:[0,c,0],scale:1}}}};function _e(e){const t=A[e];if(!t)throw new Error(`Invalid point direction: ${e}`);const i="up"===e||"down"===e;return{name:`point${D(e)}`,emoji:"up"===e?"โ๏ธ":"down"===e?"๐":"left"===e?"๐":"๐",type:"blending",description:`Point ${e} with extension and return`,config:{duration:500,amplitude:15,strength:.8,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"ease"},accentResponse:{enabled:!0,multiplier:1.6}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.point={startX:e.x,startY:e.y,initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.point?.initialized||this.initialize(e,s);const o={...this.config,...s},l=o.strength||.8,h=this.easeInOutCubic(i);let c=o.amplitude*l*e.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI);if(e.vx+=u*c*.02*n*t.x,e.vy+=u*c*.02*n*-t.y,i>.9){const t=1-10*(i-.9);e.vx*=.95+.05*t,e.vy*=.95+.05*t}},cleanup(e){e.gestureData?.point&&delete e.gestureData.point},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,s){const n=s||{},a=.005*(n.amplitude||15)*(n.strength||.8),r=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,o=Math.sin(r*Math.PI),l=t.x*o*a,h=t.y*o*a;let c=0,u=0,d=0;return i?c=t.y*o*.2:(u=t.x*o*.25,d=-t.x*o*.1),{cameraRelativePosition:[l,h,0],rotation:[c,u,d],scale:1}}}}}var Ie=_e("up"),Re=_e("down"),Be=_e("left"),ze=_e("right");function Fe(e){if("left"!==e&&"right"!==e)throw new Error(`Invalid kick direction: ${e}. Only 'left' and 'right' are supported.`);const t=A[e];return{name:`kick${D(e)}`,emoji:"left"===e?"๐ฆต":"๐ฆถ",type:"blending",description:`Quick kick ${e} with snap return`,config:{duration:400,amplitude:30,strength:.8,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:5,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"snap"},accentResponse:{enabled:!0,multiplier:1.5}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l,h=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1),l=i<.25?this.easeOutQuad(i/.25):i<.5?1:1-this.easeInQuad((i-.5)/.5);const c=t.x*h*l*.012*n,u=t.y*h*l*.012*n;e.vx+=c,e.vy+=u},cleanup(e){},easeOutQuad:e=>1-(1-e)*(1-e),easeInQuad:e=>e*e,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||30,a=s.strength||.8;let r,o=.008*n*a;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),e<.25)r=1-(1-e/.25)*(1-e/.25);else if(e<.5)r=1;else{const t=(e-.5)/.5;r=1-t*t}const l=.15*r*a;return{cameraRelativePosition:[t.x*o*r,t.y*o*r*.3,0],rotation:[.08*r*a,0,t.x*l],scale:1+.05*r}}}}}var Oe=Fe("left"),Le=Fe("right"),qe={name:"bow",emoji:"๐",type:"override",description:"Graceful forward bow of respect",config:{duration:1200,musicalDuration:{musical:!0,beats:3},depth:.4,holdTime:.4,graceful:!0,strength:1,particleMotion:{type:"bow",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.depth||.4,a=i.holdTime||.4;let r;const o=.4*(1-a),l=1-.6*(1-a);return e<o?(r=e/o,r=Math.sin(r*Math.PI/2)):e<l?r=1:(r=1-(e-l)/(1-l),r=Math.sin(r*Math.PI/2)),{cameraRelativePosition:[0,.1*-r*s,.05*-r*s],cameraRelativeRotation:[r*n*Math.PI*s,0,0],scale:1,glowIntensity:1-.2*r,glowBoost:0}}}},Ge={name:"nod",emoji:"๐",type:"blending",description:"Vertical nodding motion",config:{duration:500,amplitude:15,frequency:2,easing:"sine",strength:.4,particleMotion:{type:"bounce",axis:"vertical",strength:.4,frequency:2,phase:0}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!1,priority:5,blendable:!1,minDuration:"halfBar",frequencySync:{mode:"subdivision",subdivision:"half",multiplier:1},amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"ease"},durationSync:{mode:"beats",beats:2},patternOverrides:{waltz:{frequencySync:{subdivision:"quarter"},amplitudeSync:{onBeat:1.6,curve:"ease"}},swing:{amplitudeSync:{onBeat:1.5,offBeat:.9}},dubstep:{amplitudeSync:{onBeat:1.2,dropBeat:3,curve:"pulse"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.nod={startY:e.y,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.nod?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1;let{frequency:l}=r,{amplitude:h}=r;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const c=Math.sin(t*Math.PI*2*l);h=h*o*e.scaleFactor,e.vy+=c*h*.01*s,t>.9&&(e.vy*=.95)},cleanup(e){e.gestureData?.nod&&delete e.gestureData.nod},"3d":{evaluate(e,t){const i={...this.config,...t};let{amplitude:s}=i;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);let n=0;if(e<.4){const t=e/.4;n=.12*Math.sin(t*Math.PI)}else if(e<.8){const t=(e-.4)/.4;n=.07*Math.sin(t*Math.PI)}return n*=s/15,{cameraRelativePosition:[0,0,n],scale:1-.3*Math.abs(n),glowIntensity:1+.5*Math.abs(n)}}}},He={name:"reach",emoji:"๐",type:"blending",description:"Upward reaching motion with scale increase",config:{duration:1400,musicalDuration:{musical:!0,beats:2},amplitude:25,strength:.9,scaleMax:1.05,particleMotion:{type:"reach",strength:.9,scaleMax:1.05}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.4,offBeat:.9,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.5},patternOverrides:{uplifting:{amplitudeSync:{onBeat:1.8,offBeat:.7,curve:"ease"},durationSync:{beats:3}},ambient:{amplitudeSync:{onBeat:1.2,offBeat:1,curve:"linear"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.reach={startY:e.y,startVy:e.vy,originalSize:e.size,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.reach?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=r.scaleMax||this.config.scaleMax||1.05,h=this.easeInOutCubic(t);let c=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI);e.vy-=u*c*.015*s;const d=1+u*(l-1);if(e.size=e.baseSize*d,t>.9){const i=1-10*(t-.9);e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.reach&&(e.gestureData.reach.originalSize?e.size=e.gestureData.reach.originalSize:e.size=e.baseSize,delete e.gestureData.reach)},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||25,n=i.strength||.9,a=i.scaleMax||1.05,r=.004*s*n,o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI);return{position:[0,l*r,0],rotation:[.1*l,0,0],scale:1+l*(a-1)}}}},je={name:"headBob",emoji:"๐ง",type:"additive",description:"Rhythmic vertical bobbing to music",config:{duration:600,musicalDuration:{musical:!0,beats:1},amplitude:12,frequency:2,strength:1,damping:.1,easing:"linear",particleMotion:{type:"headBob",strength:1,amplitude:12,frequency:2}},rhythm:{enabled:!0,syncMode:"beat",frequencySync:{subdivision:"eighth",bobsPerBeat:2},amplitudeSync:{onBeat:1.3,offBeat:1,curve:"pulse"},durationSync:{mode:"beats",beats:1}},apply(e,t,i,s,n,a,r){const o=(i.amplitude||this.config.amplitude)*n,l=i.frequency||this.config.frequency,h=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*2*l)*o*h;e.vy+=.5*c;const u=Math.cos(s*Math.PI*2*l*1.5)*o*.05*h;e.vx+=.2*u},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.amplitude||12,a=e<.15?e/.15:Math.pow(1-(e-.15)/.85,2),r=n/12*s;return{cameraRelativePosition:[0,0,.08*a*r],position:[0,.015*-a*r,0],scale:1-.05*a,glowIntensity:1+.15*a}}}},$e={name:"crouch",emoji:"๐ฆ",type:"override",description:"Compress down into a low crouch position",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},depth:.3,widen:.2,holdTime:.5,strength:1,particleMotion:{type:"crouch",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.depth||.3,a=i.widen||.2;let r;const o=(1-(i.holdTime||.5))/2,l=1-o;return r=e<o?e/o:e<l?1:1-(e-l)/o,r=Math.sin(r*Math.PI/2),{position:[0,-r*n*s,0],rotation:[.15*r*s,0,0],scale:(1+r*a*s+(1-.25*r*s))/2,glowIntensity:1-.3*r,glowBoost:0}}}},We={name:"tilt",emoji:"๐ค",type:"override",description:"Gather particles then tilt as unified group",config:{duration:500,musicalDuration:{musical:!0,beats:1},gatherPhase:.2,tiltAngle:45,swayAmount:80,liftAmount:60,frequency:3,homeRadius:20,easing:"sine",strength:2.5,particleMotion:{type:"tilt",strength:2.5,frequency:3,swayAmount:80,liftAmount:60},smoothness:.25},rhythm:{enabled:!0,syncMode:"swing",durationSync:{mode:"beats",beats:1},angleSync:{onBeat:45,offBeat:-30,swing:15,subdivision:"triplet",curve:"ease-in-out"},gatherSync:{beatsBefore:.5,releaseAfter:.25,intensity:"dynamic"},swaySync:{verse:60,chorus:100,bridge:80,syncopated:!0},liftSync:{upOnTilt:!0,heightOnAccent:80,normalHeight:40,curve:"bounce"},dynamics:{forte:{tiltAngle:60,swayAmount:120,frequency:4},piano:{tiltAngle:20,swayAmount:40,frequency:2}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=Math.random(),h=({...this.config,...t}.homeRadius+20*Math.random())*e.scaleFactor;e.gestureData.tilt={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,angle:r,distance:o,homeRadius:h,homeX:i+Math.cos(r)*h,homeY:s+Math.sin(r)*h,role:l,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.tilt?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.tilt,o={...this.config,...i},l=i.strength||1;let h,c;if(t<o.gatherPhase){const i=t/o.gatherPhase,s=this.easeInOutCubic(i);h=r.startX+(r.homeX-r.startX)*s,c=r.startY+(r.homeY-r.startY)*s;const n=.6;e.x+=(h-e.x)*n,e.y+=(c-e.y)*n}else{const i=(t-o.gatherPhase)/(1-o.gatherPhase)*Math.PI*o.frequency,s=Math.sin(i),u=o.tiltAngle*Math.PI/180*l,d=r.angle+s*u,g=Math.abs(s)*o.liftAmount*e.scaleFactor,m=r.homeRadius+g;h=n+Math.cos(d)*m,c=a+Math.sin(d)*m-.3*g;const p=o.smoothness+.1*r.role;e.x+=(h-e.x)*p,e.y+=(c-e.y)*p;const f=-Math.sin(d),y=Math.cos(d);e.vx=f*s*2,e.vy=y*s*2}if(t<o.gatherPhase&&(e.vx=.25*(h-e.x),e.vy=.25*(c-e.y)),t>.9){const i=10*(1-t),s=r.startX+(e.x-r.startX)*i,n=r.startY+(e.y-r.startY)*i;e.x=s,e.y=n,e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.tilt){const t=e.gestureData.tilt;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.tilt}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.gatherPhase||.2,a=i.frequency||3,r=i.tiltAngle||45;let o=0;if(e>=n){const t=(e-n)/(1-n)*Math.PI*a;o=Math.sin(t)*(r*Math.PI/180*s*.4)}return{position:[0,0,0],rotation:[0,0,o],scale:1}}}};function Ue(e){const t=A[e];if(!t)throw new Error(`Invalid tilt direction: ${e}`);const i="up"===e||"down"===e;return{name:`tilt${D(e)}`,emoji:"up"===e?"๐ญ":"down"===e?"๐":"left"===e?"๐ค":"๐ง",type:"override",description:`Tilt ${e} with curious expression`,config:{duration:500,musicalDuration:{musical:!0,beats:1},gatherPhase:.2,tiltAngle:45,tiltAmount:40,holdPhase:.4,homeRadius:20,easing:"sine",strength:1,direction:e,smoothness:.25,particleMotion:{type:"tilt",strength:1,tiltAmount:40}},rhythm:{enabled:!0,syncMode:"swing",durationSync:{mode:"beats",beats:1},angleSync:{onBeat:45,offBeat:30,subdivision:"triplet",curve:"ease-in-out"},gatherSync:{beatsBefore:.5,releaseAfter:.25,intensity:"dynamic"},dynamics:{forte:{tiltAngle:60,tiltAmount:60},piano:{tiltAngle:25,tiltAmount:25}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=({...this.config,...t}.homeRadius+20*Math.random())*e.scaleFactor;e.gestureData.tilt={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,angle:r,distance:o,homeRadius:l,homeX:i+Math.cos(r)*l,homeY:s+Math.sin(r)*l,role:Math.random(),initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.tilt?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.tilt,h={...this.config,...n},c=n.strength||1;let u,d;if(s<h.gatherPhase){const t=s/h.gatherPhase,i=this.easeInOutCubic(t);u=l.startX+(l.homeX-l.startX)*i,d=l.startY+(l.homeY-l.startY)*i;const n=.6;e.x+=(u-e.x)*n,e.y+=(d-e.y)*n}else if(s<h.gatherPhase+h.holdPhase){const n=(s-h.gatherPhase)/h.holdPhase,a=this.easeOutCubic(Math.min(2*n,1)),r=h.tiltAmount*c*e.scaleFactor*a;i?(u=l.homeX,d=l.homeY+t.y*r):(u=l.homeX+t.x*r,d=l.homeY-Math.abs(t.x)*r*.2);const o=h.smoothness+.1*l.role;e.x+=(u-e.x)*o,e.y+=(d-e.y)*o,e.vx=.5*(u-e.x),e.vy=.5*(d-e.y)}else{const t=(s-h.gatherPhase-h.holdPhase)/(1-h.gatherPhase-h.holdPhase),i=this.easeInOutCubic(t);u=e.x+(l.startX-e.x)*i,d=e.y+(l.startY-e.y)*i,e.x=u,e.y=d,e.vx=l.originalVx*i,e.vy=l.originalVy*i}s<h.gatherPhase&&(e.vx=.25*(u-e.x),e.vy=.25*(d-e.y))},cleanup(e){if(e.gestureData?.tilt){const t=e.gestureData.tilt;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.tilt}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutCubic:e=>1-Math.pow(1-e,3),"3d":{evaluate(e,s){const n=s.config||s||{},a=s.strength||1,r=n.gatherPhase||.2,o=n.holdPhase||.4,l=n.tiltAngle||45,h=n.tiltAmount||40;let c=0,u=0,d=0,g=0,m=0;if(e<r);else if(e<r+o){const s=(e-r)/o,n=1-Math.pow(1-Math.min(2*s,1),3),p=l*Math.PI/180*a*.4*n,f=.004*h*a*n;i?(d=t.y*p,u=t.y*f):(m=-t.x*p,c=t.x*f*.5,g=t.x*p*.3)}else{const s=(e-r-o)/(1-r-o),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,p=l*Math.PI/180*a*.4*(1-n),f=.004*h*a*(1-n);i?(d=t.y*p,u=t.y*f):(m=-t.x*p,c=t.x*f*.5,g=t.x*p*.3)}return{cameraRelativePosition:[c,u,0],rotation:[d,g,m],scale:1}}}}}var Ve=Ue("up"),Ye=Ue("down"),Xe=Ue("left"),Ne=Ue("right");function Qe(e){if(!["left","right","front","back","up","down"].includes(e))throw new Error(`Invalid oof direction: ${e}`);return{name:`oof${D(e)}`,emoji:{left:"๐ค",right:"๐ค",front:"๐",back:"๐ซ",up:"๐ฅ",down:"๐ฅ"}[e],type:"override",description:{left:"Punched from left",right:"Punched from right",front:"Gut punch",back:"Kidney shot",up:"Uppercut",down:"Hammer fist"}[e],config:{duration:500,musicalDuration:{musical:!0,beats:1},intensity:1,strength:1,direction:e,particleMotion:{type:"oof",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1;let n,a;if(e<.25){const t=e/.25;n=t*(2-t)}else{const t=(e-.25)/.75;n=1-t*t}a=e<.1?e/.1:e<.4?1:1-(e-.4)/.6;const r=.2*s,o=.35*s;let l=0,h=0,c=0,u=0,d=0;let g=[0,0,.4];switch(i.direction||"front"){case"left":l=-n*r,d=n*o,g=[.4,0,0];break;case"right":l=n*r,d=-n*o,g=[-.4,0,0];break;case"front":c=-n*r,h=.03*-n,u=n*o*.7,g=[0,0,.4];break;case"back":c=n*r,u=-n*o*.6,g=[0,0,-.4];break;case"up":h=n*r,u=-n*o*.4,g=[0,.8,0];break;case"down":h=-n*r,u=n*o*.3,g=[0,-.8,0]}let m=1,p=0;if(e<.15){const t=e/.15;m=1+.6*(1-t),p=.4*(1-t)}return{cameraRelativePosition:[l,h,c],cameraRelativeRotation:[u,0,d],scale:1,glowIntensity:m,glowBoost:p,deformation:{enabled:!0,strength:a*s*2,impactPoint:g,falloffRadius:.5}}}}}}var Je={name:"recoil",emoji:"๐ฑ",type:"override",description:"Snap backwards in shock or surprise",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,particleMotion:{type:"recoil",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.2,a=i.intensity||1,r=!1!==i.recover;let o;return e<.15?(o=e/.15,o=1-Math.pow(1-o,4)):e<.4?o=1:r?(o=1-(e-.4)/.6,o=Math.pow(o,.5)):o=1,{position:[0,.05*o*s,-o*n*s*a],rotation:[.25*-o*s*a,0,0],scale:1-.1*o*a,glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.5:0}}}};function Ke(e){if(!{...A,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[e])throw new Error(`Invalid recoil direction: ${e}`);return{name:`recoil${D(e)}`,emoji:{back:"๐ฑ",forward:"๐ต",left:"๐ฐ",right:"๐ฐ",up:"๐ฒ",down:"๐จ"}[e]||"๐ฑ",type:"override",description:`Recoil ${e} in shock`,config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,direction:e,particleMotion:{type:"recoil",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.2,a=i.intensity||1,r=!1!==i.recover,o=i.direction||"back";let l;e<.15?(l=e/.15,l=1-Math.pow(1-l,4)):e<.4?l=1:r?(l=1-(e-.4)/.6,l=Math.pow(l,.5)):l=1;let h=0,c=0,u=0,d=0,g=0;switch(o){case"back":u=-l*n*s*a,d=.25*-l*s*a,c=.05*l*s;break;case"forward":u=l*n*s*a,d=.25*l*s*a,c=.05*-l*s;break;case"left":h=-l*n*s*a,g=.2*l*s*a;break;case"right":h=l*n*s*a,g=.2*-l*s*a;break;case"up":c=l*n*s*a,d=.1*-l*s*a;break;case"down":c=-l*n*s*a,d=.3*l*s*a}return{cameraRelativePosition:[h,c,u],cameraRelativeRotation:[d,0,g],scale:1-.1*l*a,glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.5:0}}}}}var Ze={name:"knockdown",emoji:"๐ฅ",type:"override",description:"Quick knockdown with fast recovery",config:{duration:1500,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"knockdown",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.15){const t=e/.15,s=1-Math.pow(1-t,2);n=.1*s*i,a=.2*-s*i,l=1+.6*s,h=.5*s}else if(e<.4){const t=(e-.15)/.25,n=t*t;s=.2*-n*i,a=(.6*n-.2)*i,r=.3*n*i,t>.7&&(o=1-(t-.7)/.3*.1),l=1.6-.5*t,h=.5-.4*t}else if(e<.6){const t=(e-.4)/.2;s=-.2*i,a=.4*i,r=.3*i,r+=.02*Math.sin(t*Math.PI*2),o=.9,l=.8}else{const t=(e-.6)/.4,n=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;if(s=(.2*n-.2)*i,a=(.4-.4*n)*i,r=(.3-.3*n)*i,o=.9+.1*n,t>.7){const e=(t-.7)/.3;r+=.03*Math.sin(e*Math.PI*4)*(1-e)}l=.8+.2*n,t>.9&&(h=(t-.9)/.1*.2)}return{position:[0,s,n],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},et={name:"knockout",emoji:"๐ซ",type:"override",description:"Theatrical knockout with failed rise attempt, then recovery",config:{duration:4e3,musicalDuration:{musical:!0,bars:2},strength:1,particleMotion:{type:"knockout",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=0,l=1,h=1,c=0;if(e<.1){const t=e/.1,s=1-Math.pow(1-t,3);n=.15*s*i,a=.3*-s*i,h=1+.8*s,c=.6*s,o=.1*Math.sin(t*Math.PI*4)*s}else if(e<.25){const t=(e-.1)/.15,n=t*t;s=.25*-n*i,a=(.8*n-.3)*i,o=.4*n*i,t>.8&&(l=1-(t-.8)/.2*.15),h=1.8-.6*t,c=.6-.4*t}else if(e<.35){const t=(e-.25)/.1;s=-.25*i,a=.5*i,o=.4*i,o+=.03*Math.sin(t*Math.PI*6)*(1-t),l=.85,h=1-.3*t}else if(e<.45){const t=(e-.35)/.1,n=1-Math.pow(1-t,2);s=(.15*n-.25)*i,a=(.5-.3*n)*i,o=(.4-.2*n)*i,l=.85+.1*n,h=.7+.4*n}else if(e<.55){const t=(e-.45)/.1,n=t*t;s=(-.1-.15*n)*i,a=(.2+.35*n)*i,o=(.2+.25*n)*i,l=.95-.12*n,t>.7&&(c=(t-.7)/.3*.3),h=1.1-.4*t}else if(e<.75){const t=(e-.55)/.2;s=-.25*i,a=.55*i,o=.45*i,l=.83;const n=.02*Math.sin(t*Math.PI*4)*Math.sin(t*Math.PI);o+=n,h=.6+2*n}else if(e<.9){const t=(e-.75)/.15,n=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;s=(.25*n-.25)*i,a=(.55-.55*n)*i,o=(.45-.45*n)*i,l=.83+.17*n,h=.6+.5*n}else{const t=(e-.9)/.1;s=0,a=0,o=Math.sin(t*Math.PI*6)*(1-t)*.08*i,r=Math.sin(t*Math.PI*8)*(1-t)*.1*i,l=1,h=1+.2*Math.sin(t*Math.PI*3)*(1-t),c=.2*Math.sin(t*Math.PI)}return{position:[0,s,n],rotation:[a,r,o],scale:l,glowIntensity:h,glowBoost:c}}}},tt={name:"inflate",emoji:"๐",type:"override",description:"Puff up dramatically like a balloon",config:{duration:800,musicalDuration:{musical:!0,beats:2},maxScale:1.4,holdTime:.3,deflate:!0,strength:1,particleMotion:{type:"inflate",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",strengthSync:{onBeat:1.3,offBeat:.8}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.maxScale||1.4,a=i.holdTime||.3,r=!1!==i.deflate;let o;const l=.5*(1-a),h=1-l;e<l?(o=e/l,o=1-Math.pow(1-o,2)):e<h||!r?o=1:(o=1-(e-h)/l,o=Math.pow(o,2));const c=1+(n-1)*o*s,u=.08*o*s,d=1+.4*o*s,g=.3*o,m=o>.8?.02*Math.sin(e*Math.PI*8):0;return{position:[m,u,0],rotation:[0,0,2*m],scale:c,glowIntensity:d,glowBoost:g}}}},it={name:"deflate",emoji:"๐จ",type:"override",description:"Shrink down sadly like a deflating balloon",config:{duration:1e3,musicalDuration:{musical:!0,beats:2.5},minScale:.6,droop:.15,reinflate:!0,strength:1,particleMotion:{type:"deflate",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2.5},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.minScale||.6,a=i.droop||.15,r=!1!==i.reinflate;let o;return e<.5?(o=e/.5,o=Math.pow(o,.7)):e<.7||!r?o=1:(o=1-(e-.7)/.3,o=Math.pow(o,1.5)),{position:[0,-o*a*s,0],rotation:[.15*o*s,0,.1*o*s],scale:1-(1-n)*o*s,glowIntensity:1-.4*o,glowBoost:0}}}},st={name:"squash",emoji:"๐ซ",type:"override",description:"Flatten horizontally like a cartoon impact",config:{duration:500,musicalDuration:{musical:!0,beats:1},squashAmount:.5,stretchAmount:1.5,bounce:!0,strength:1,particleMotion:{type:"squash",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.squashAmount||.5,a=i.stretchAmount||1.5,r=!1!==i.bounce;let o;if(e<.15)o=e/.15,o=1-Math.pow(1-o,3);else if(r){const t=(e-.15)/.85,i=Math.exp(4*-t);o=Math.cos(t*Math.PI*3)*i,o=Math.max(0,o)}else o=0;const l=1+o*(a-1)*s;return{position:[0,.15*-o*s,0],rotation:[0,0,0],scale:[l,1-o*(1-n)*s,l],glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.6:0}}}},nt={name:"stretch",emoji:"โ๏ธ",type:"override",description:"Scale particles along X and Y axes",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},scaleX:1.3,scaleY:.9,alternate:!1,elastic:!0,overshoot:.1,frequency:1,easing:"sine",strength:1,particleMotion:{type:"stretch",scaleX:1.8,scaleY:.6,strength:1},centerBased:!0,preserveArea:!1},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},scaleSync:{onBeat:{x:1.5,y:.7},offBeat:{x:.8,y:1.3},subdivision:"eighth",curve:"elastic"},alternateSync:{pattern:"XYXY",beatsPerChange:1,overlap:.1},overshootSync:{normal:.1,accent:.3,downbeat:.2,curve:"spring"},preservationSync:{verse:!0,chorus:!1,bridge:!0},dynamics:{forte:{scaleX:2,scaleY:.5,overshoot:.4},piano:{scaleX:1.1,scaleY:.95,overshoot:.05}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.stretch={offsetX:n,offsetY:a,startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.stretch?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.stretch,o={...this.config,...i},l=i.strength||1;let h,c,{scaleX:u}=o,{scaleY:d}=o;if(o.preserveArea&&1!==u&&1!==d){const e=u*d,t=Math.sqrt(1/e);u*=t,d*=t}if(o.alternate)if(t<.5){const e=2*t;u=1+(u-1)*this.getElasticProgress(e,o),d=1+(1/u-1)*(o.preserveArea?1:0)}else{const e=2*(t-.5);u+=(1-u)*this.getElasticProgress(e,o),d=1+(d-1)*this.getElasticProgress(e,o)}else{const e=this.getElasticProgress(t,o);u=1+(u-1)*e*l,d=1+(d-1)*e*l}if(o.centerBased?(h=n+r.offsetX*u,c=a+r.offsetY*d):(h=r.startX*u,c=r.startY*d),e.x=h,e.y=c,e.vx=r.offsetX*(u-1)*l*.1,e.vy=r.offsetY*(d-1)*l*.1,t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},getElasticProgress(e,t){if(!t.elastic)return this.easeInOutCubic(e);if(0===e)return 0;if(1===e)return 1;const i=t.overshoot||.1;if(e<.5){const t=2*e;return.5*this.easeInElastic(t,i)}{const t=2*(e-.5);return.5+.5*this.easeOutElastic(t,i)}},cleanup(e){if(e.gestureData?.stretch){const t=e.gestureData.stretch;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.stretch}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeInElastic:(e,t)=>0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin((e-1-.075)*(2*Math.PI)/.3)*(1+t),easeOutElastic:(e,t)=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((e-.075)*(2*Math.PI)/.3)*(1+t)+1,"3d":{evaluate(e,t){const{particle:i}=t;if(!i||!i.gestureData?.stretch)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=t.config||{},n=t.strength||1;let a,r=s.scaleX||1.3,o=s.scaleY||.9;if(s.preserveArea&&1!==r&&1!==o){const e=r*o,t=Math.sqrt(1/e);r*=t,o*=t}if(s.elastic){const t=s.overshoot||.1;if(e<.5){const i=2*e,s=.3,n=s/4;a=-Math.pow(2,10*(i-1))*Math.sin((i-1-n)*(2*Math.PI)/s)*(1+t)*.5}else{const i=2*(e-.5),s=.3,n=s/4;a=.5+.5*(Math.pow(2,-10*i)*Math.sin((i-n)*(2*Math.PI)/s)*(1+t)+1)}}else a=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;let l,h=1;if(e>.8){const t=(e-.8)/(1-.8);h=1-t*t*t}l=s.alternate?e<.5?2*e*.8:.8-2*(e-.5)*1.4:1*a*n;const c=1+l*h;return{position:[0,0,0],rotation:[0,0,.1*Math.sin(e*Math.PI*4)*a*h],scale:c}}}},at={name:"pancake",emoji:"๐ฅ",type:"override",description:"Extreme flatten and hold - cartoon pancake effect",config:{duration:1600,musicalDuration:{musical:!0,bars:1},squashAmount:.2,stretchAmount:2,holdRatio:.5,strength:1,particleMotion:{type:"pancake",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.squashAmount||.2,a=i.stretchAmount||2,r=.1+.6*(i.holdRatio||.5);let o=0,l=0;if(e<.1){const t=e/.1;o=1-Math.pow(1-t,2)}else if(e<r){o=1;const t=(e-.1)/(r-.1);l=Math.sin(t*Math.PI*4)*(1-t)*.02}else{const t=(e-r)/(1-r);if(o=1-(t<.3?t/.3*.3:.3+(t-.3)/.7*.7),t>.8){const e=(t-.8)/.2,i=.15*Math.sin(e*Math.PI);o=Math.max(0,o-i)}}const h=1+o*(a-1)*s;let c=1,u=0;return e<.15?(c=1+.8*(1-e/.15),u=.6*(1-e/.15)):e<r?(c=1.3,u=.2):c=1.3-(e-r)/(1-r)*.3,{position:[l*s,.2*-o*s,0],rotation:[0,0,2*l*s],scale:[h,1-o*(1-n)*s,h],glowIntensity:c,glowBoost:u}}}},rt={name:"rage",emoji:"๐ข",type:"override",description:"Barbarian rage - intense buildup and release",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"rage",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.2){const t=e/.2,o=t*t;n=.05*-o*i,a=.15*o*i;const h=Math.sin(80*e)*o*.02;r=h*i,s=.02*h*i,l=1+.3*o}else if(e<.6){const t=(e-.2)/.4,c=t*t;n=(-.05-.03*c)*i,a=(.15+.1*c)*i;const u=.02+.04*c,d=100+50*t,g=Math.sin(e*d)*u;r=g*i,s=.03*g*i,o=1+.1*c,l=1.3+.7*c,h=.5*c}else if(e<.8){const t=(e-.6)/.2;n=(.15*t-.08)*i,a=(.25-.4*t)*i,r=Math.sin(150*e)*(1-.5*t)*.05*i,o=1.1+.08*Math.sin(t*Math.PI),l=2-.3*t,h=.5+.3*Math.sin(t*Math.PI)}else{const t=(e-.8)/.2,s=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;n=(.07-.07*s)*i,a=(.15*s-.15)*i,r=Math.sin(50*e)*(1-s)*.02*i,o=1.1-.1*s,l=1.7-.7*s,h=.5*(1-s)}return{position:[s,n,0],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},ot={name:"fury",emoji:"๐ค",type:"override",description:"Quick fury burst - intense flash of anger",config:{duration:800,musicalDuration:{musical:!0,beats:2},strength:1,particleMotion:{type:"fury",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=1,o=1,l=0;if(e<.2){const t=e/.2,n=1-Math.pow(1-t,3);r=1+.15*n*i;const h=Math.sin(120*e)*n*.04;a=h*i,s=.02*h*i,o=1+1.2*n,l=.7*n}else if(e<.5){const t=(e-.2)/.3;r=1.15+.03*Math.sin(t*Math.PI*3);const h=.05*Math.sin(150*e)*(1-.3*t);a=h*i,s=.025*h*i,n=.1*Math.sin(t*Math.PI)*i,o=2.2-.3*t,l=.7-.2*t}else{const t=(e-.5)/.5,s=t*t;r=1.15-.15*s,a=Math.sin(80*e)*(1-s)*.03*i,n=.1*(1-s)*i,o=1.9-.9*s,l=.5*(1-s)}return{position:[s,0,0],rotation:[n,0,a],scale:r,glowIntensity:o,glowBoost:l}}}},lt={name:"battlecry",emoji:"๐ฃ",type:"override",description:"Warrior battlecry - inhale, expand, roar",config:{duration:1500,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"battlecry",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.25){const t=e/.25,r=t*t;n=.08*r*i,a=.15*-r*i,s=.03*-r*i,o=1+.05*r,l=1+.4*r}else if(e<.4){const t=(e-.25)/.15;n=(.08+.02*t)*i,a=(-.15-.1*t)*i,s=(.05*t-.03)*i,o=1.05+.08*t,l=1.4+.5*t,h=.4*t}else if(e<.6){const t=(e-.4)/.2,c=1-Math.pow(1-t,3);n=(.1-.2*c)*i,a=(.4*c-.25)*i,s=(.02+.08*c)*i,o=1.13+.12*c,l=1.9+.6*c,h=.4+.4*c,r=Math.sin(t*Math.PI*20)*(1-t)*.02*i}else{const t=(e-.6)/.4,c=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;n=-.1*(1-c)*i,a=.15*(1-c)*i,s=.1*(1-c)*i,o=1.25-.25*c,r=Math.sin(t*Math.PI*8)*(1-c)*.015*i,l=2.5-1.5*c,h=.8-.8*c}return{position:[0,s,n],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},ht={name:"charge",emoji:"๐",type:"override",description:"Bull charge - wind up and rush forward",config:{duration:1200,musicalDuration:{musical:!0,beats:3},strength:1,particleMotion:{type:"charge",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=0,l=1,h=1,c=0;if(e<.2){const t=e/.2,s=t*t;n=.08*-s*i,a=.1*s*i,r=.25*s*i,l=1-.05*s,h=1+.4*s}else if(e<.6){const t=(e-.2)/.4,s=1-Math.pow(1-t,2);a=(.1-.35*s)*i,r=(.25+.1*s)*i,n=(.06*s-.08)*i,l=.95+.15*s,h=1.4+.6*s,c=.4*s,o=Math.sin(t*Math.PI*10)*s*.02*i}else if(e<.85){const t=(e-.6)/.25;a=-.25*i,r=(.35-.1*t)*i;const n=Math.sin(t*Math.PI*15)*(1-t)*.04;o=n*i,s=.02*n*i,l=1.1+.05*Math.sin(t*Math.PI),h=2-.3*t,c=.4*(1-.5*t)}else{const t=(e-.85)/.15,s=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;a=-.25*(1-s)*i,r=.25*(1-s)*i,n=-.02*(1-s)*i,l=1.1-.1*s,h=1.7-.7*s,c=.2*(1-s)}return{cameraRelativePosition:[s,n,a],rotation:[r,0,o],scale:l,glowIntensity:h,glowBoost:c}}}},ct={name:"wobble",emoji:"๐ฅด",type:"override",description:"Unsteady circular wobbling motion",config:{duration:1500,musicalDuration:{musical:!0,beats:4},wobbleRadius:.08,wobbleAngle:.2,rotations:2,decay:.5,strength:1,particleMotion:{type:"wobble",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:4},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.wobbleRadius||.08,a=i.wobbleAngle||.2,r=i.rotations||2,o=i.decay||.5,l=e*r*Math.PI*2,h=1-o*e,c=Math.sin(l)*n*h*s,u=Math.cos(l)*n*h*s,d=Math.cos(l)*a*h*s,g=Math.sin(l)*a*h*s;return{position:[c,.02*Math.sin(2*l)*h*s,u],rotation:[d,0,g],scale:1+.05*Math.sin(2*l)*h,glowIntensity:1+.2*Math.sin(l)*h,glowBoost:0}}}},ut={name:"teeter",emoji:"โ๏ธ",type:"override",description:"Rock back and forth unstably like losing balance",config:{duration:1200,musicalDuration:{musical:!0,beats:3},tiltAngle:.25,frequency:3,irregularity:.3,strength:1,particleMotion:{type:"teeter",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.tiltAngle||.25,a=i.frequency||3,r=i.irregularity||.3,o=(Math.sin(e*a*Math.PI*2)+Math.sin(e*(a+1.7)*Math.PI*2)*r+Math.sin(e*(.5*a)*Math.PI*2)*r*.5)/(1+1.5*r),l=o*n*s*.7,h=Math.sin(e*a*Math.PI*2+.5)*n*s*.5;return{position:[.15*h,0,.1*l],rotation:[l,0,h],scale:1+.05*Math.abs(o),glowIntensity:1+.2*Math.abs(o),glowBoost:0}}}},dt={name:"rock",emoji:"๐ชจ",type:"override",description:"Gentle front-back rocking motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},rockAngle:.15,rockCycles:2,smooth:!0,strength:1,particleMotion:{type:"rock",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rockAngle||.15,a=e*(i.rockCycles||2)*Math.PI*2,r=Math.sin(a),o=r*n*s,l=.05*r*s;return{position:[0,.02*Math.abs(r)*s,l],rotation:[o,0,0],scale:1+.02*Math.sin(.5*a),glowIntensity:1+.1*r,glowBoost:0}}}},gt={name:"pendulum",emoji:"๐ฐ๏ธ",type:"override",description:"Swing side to side like a pendulum clock",config:{duration:1500,musicalDuration:{musical:!0,beats:4},swingAngle:.4,swings:2,damping:.3,strength:1,particleMotion:{type:"pendulum",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:4},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.swingAngle||.4,a=i.swings||2,r=i.damping||.3,o=e*a*Math.PI*2,l=1-r*e,h=Math.sin(o)*l,c=h*n*s;return{position:[.1*h*s,.03*-Math.abs(h)*s,0],rotation:[0,0,c],scale:1,glowIntensity:1+.15*Math.abs(h),glowBoost:0}}}};function mt(e){const t={front:{screenOffset:[0,0],screenDirection:[0,0],recoilDir:[0,0,-1]},back:{screenOffset:[0,0],screenDirection:[0,0],recoilDir:[0,0,1]},left:{screenOffset:[-.1,0],screenDirection:[1,0],recoilDir:[1,0,0]},right:{screenOffset:[.1,0],screenDirection:[-1,0],recoilDir:[-1,0,0]},up:{screenOffset:[0,.1],screenDirection:[0,-1],recoilDir:[0,-1,0]},down:{screenOffset:[0,-.1],screenDirection:[0,1],recoilDir:[0,1,0]}},i=t[e]||t.front;return{name:`crack${e.charAt(0).toUpperCase()+e.slice(1)}`,emoji:"๐",type:"override",category:"reactions",description:`Surface cracks spreading from ${e} impact`,config:{duration:2e3,strength:1,glowStrength:.3,holdTime:500},rhythm:{enabled:!0,syncMode:"accent",strengthSync:{onBeat:1.2,offBeat:.8}},"3d":{evaluate(e,t){const s={strength:1,glowStrength:.3,...t},{strength:n,glowStrength:a}=s,r=.03*Math.max(0,1-4*e)*n,{recoilDir:o}=i,l=e<.05;return{cameraRelativePosition:[o[0]*r,o[1]*r,o[2]*r],crack:{enabled:!0,trigger:l,amount:n,propagation:.8,screenOffset:i.screenOffset,screenDirection:i.screenDirection,glowStrength:a}}}}}}const pt=mt("front"),ft=mt("back"),yt=mt("left"),bt=mt("right"),vt=mt("up"),Mt=mt("down"),wt={name:"crackHeal",emoji:"โจ",type:"override",category:"reactions",description:"Heal and fade existing cracks",config:{duration:1500,glowStrength:.5},"3d":{evaluate(e,t){const i={duration:1500,...t},s=e<.05;return{cameraRelativePosition:[0,.02*Math.sin(e*Math.PI),0],crack:{enabled:!1,heal:!0,healTrigger:s,healDuration:i.duration},glowBoost:.1*Math.sin(e*Math.PI)}}}};var St={name:"shatter",emoji:"๐ฅ",type:"override",description:"Particles explode outward then freeze like shattered glass",config:{duration:1500,musicalDuration:{musical:!0,bars:1},explosionPhase:.3,freezePhase:.7,distance:100,tumble:1,strength:1,particleMotion:{type:"shatter",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=Math.random()*Math.PI*2,a=.5+.5*Math.random();e.gestureData.shatter={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,velocityX:Math.cos(n)*a,velocityY:Math.sin(n)*a,tumbleAngle:0,tumbleSpeed:4*(Math.random()-.5),frozenX:null,frozenY:null,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.shatter?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=r.distance||100,h=e.gestureData.shatter,c=r.explosionPhase||.3,u=r.freezePhase||.7;if(t<c){const i=t/c,s=1-Math.pow(1-i,3),n=h.velocityX*l*s*o,a=h.velocityY*l*s*o;e.x=h.originalX+n,e.y=h.originalY+a,h.tumbleAngle+=h.tumbleSpeed*(1-i)}else if(t<u){const i=(t-c)/(u-c),s=h.originalX+h.velocityX*l*o,n=h.originalY+h.velocityY*l*o,a=h.velocityX*l*.2*i*o,r=h.velocityY*l*.2*i*o;e.x=s+a,e.y=n+r,h.tumbleAngle+=.3*h.tumbleSpeed*(1-i),i>.95&&null===h.frozenX&&(h.frozenX=e.x,h.frozenY=e.y)}else if(null!==h.frozenX&&(e.x=h.frozenX,e.y=h.frozenY),t>.9){const i=(t-.9)/.1;e.opacity=h.originalOpacity*(1-.5*i)}},cleanup(e){if(e.gestureData?.shatter){const t=e.gestureData.shatter;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.shatter}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=1,n=1,a=1,r=0,o=0,l=0,h=0,c=0,u=0,d=1,g=0;if(e<.1){const t=e/.1,r=1-Math.pow(1-t,2);n=1-.4*r*i,s=1+.2*r*i,a=1+.2*r*i,c=.1*-r*i,d=1+1*r,g=.8*r}else if(e<.4){const t=(e-.1)/.3,m=1-.6*t,p=40,f=Math.sin(e*p*Math.PI)*m,y=Math.cos(e*p*1.3*Math.PI)*m,b=Math.sin(e*p*.7*Math.PI)*m,v=1+.3*(1-Math.pow(1-t,2))*i;s=v+.15*f*i,n=v+.15*y*i,a=v+.15*b*i,r=.4*f*i,o=.5*y*i,l=.3*b*i,h=.15*f*i,c=.12*y*i+.1*t,u=.1*b*i,d=1.5+.5*Math.abs(f),g=.5*m}else if(e<.7){const t=(e-.4)/.3,r=t*t,o=1-r,h=20*o,u=Math.sin(e*h*Math.PI)*o,m=1.3-.4*r;s=m+.05*u*i,n=m+.05*u*i,a=m+.05*u*i,l=.15*u*i,c=.1*o,d=1.5-.3*r,g=.3*o}else{const t=(e-.7)/.3,i=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,r=Math.sin(t*Math.PI*2)*(1-t)*.05;if(s=.9+.1*i+r,n=.9+.1*i+r,a=.9+.1*i+r,d=1.2-.2*i,e>.95){const t=(e-.95)/.05;g=.3*Math.sin(t*Math.PI)}}return{position:[h,c,u],rotation:[r,o,l],scale:[s,n,a],glowIntensity:d,glowBoost:g}}}};const xt={default:{name:"shatter",emoji:"๐ฅ",description:"Dramatic shattering effect",duration:2500,beats:4,intensity:1,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!1,revealSoul:!1},explosive:{name:"shatterExplosive",emoji:"๐ฅ",description:"Explosive outward shatter",duration:2e3,beats:3,intensity:1.5,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0},crumble:{name:"shatterCrumble",emoji:"๐ชจ",description:"Slow crumbling collapse",duration:8e3,beats:16,intensity:.15,impactPoint:[0,-.4,0],impactDirection:[0,-1,0],reassemble:!1,revealSoul:!0,gravity:-.8,explosionForce:.1,rotationForce:.5,shatterTriggerAt:0},reform:{name:"shatterReform",emoji:"โจ",description:"Shatter then magically reassemble",duration:4e3,beats:8,intensity:1,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!0,reassembleAt:.5,reassembleDuration:1500,revealSoul:!0},punchLeft:{name:"shatterPunchLeft",emoji:"๐",description:"Shatter from left impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[-.4,0,0],impactDirection:[1,0,0],reassemble:!1,useDeformation:!0,direction:"left",revealSoul:!1},punchRight:{name:"shatterPunchRight",emoji:"๐",description:"Shatter from right impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[.4,0,0],impactDirection:[-1,0,0],reassemble:!1,useDeformation:!0,direction:"right",revealSoul:!1},punchFront:{name:"shatterPunchFront",emoji:"๐",description:"Shatter from front impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!1,useDeformation:!0,direction:"front",revealSoul:!1},suspend:{name:"shatterSuspend",emoji:"๐",description:"Shatter, freeze mid-air, then reassemble",duration:4e3,beats:8,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!0,reassembleAt:.7,reassembleDuration:1200,revealSoul:!0,isSuspendMode:!0,suspendAt:.12,suspendDuration:.2,gravity:-2,explosionForce:1.2},freeze:{name:"shatterFreeze",emoji:"โ๏ธ",description:"Shatter and freeze mid-air (call triggerReassembly to reform)",duration:2e3,beats:4,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0,isFreezeMode:!0,isSuspendMode:!0,suspendAt:.12,suspendDuration:.2,gravity:-2,explosionForce:1.2},implode:{name:"shatterImplode",emoji:"๐",description:"Shards implode inward to center (or implode existing frozen shards)",duration:2500,beats:4,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0,isDualMode:!0,dualModeType:"implode",dualModeDuration:1800,gravity:-3,explosionForce:1.2},gravity:{name:"shatterGravity",emoji:"โฌ๏ธ",description:"Shards fall with gravity and bounce on floor (or drop frozen shards)",duration:4e3,beats:8,intensity:.6,impactPoint:[0,0,0],impactDirection:[0,-1,0],reassemble:!1,revealSoul:!0,isDualMode:!0,dualModeType:"gravity",dualModeDuration:3e3,floorY:-.35,gravity:-2,explosionForce:.4},orbit:{name:"shatterOrbit",emoji:"๐ช",description:"Shards orbit around the soul then reassemble",duration:5e3,beats:10,intensity:.6,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!0,reassembleAt:.75,reassembleDuration:1200,revealSoul:!0,isDualMode:!0,dualModeType:"orbit",dualModeDuration:3500,orbitSpeed:1.5,radiusMultiplier:1.2,gravity:-3,explosionForce:1}};function Ct(e="default"){const t=xt[e]||xt.default;return{name:t.name,emoji:t.emoji,type:"override",description:t.description,config:{duration:t.duration,musicalDuration:{musical:!0,beats:t.beats},intensity:t.intensity,variant:e},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:t.beats},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.intensity||1,n=i.variant||"default",a=xt[n]||xt.default,r=a.useDeformation||!1,o=a.direction||"front";let l=!1,h=!1,c=1,u=0,d=1,g=null,m=null,p=null;const f=a.reassemble,y=a.reassembleAt||.5;if(r){let t;if(e<.3){const i=e/.3;t=i*(2-i)}else t=0;let i=0;e<.25?i=e/.25:e<.3&&(i=1);const n=.15*s,r=.25*s;let h=0,d=0;const f=0;let y=0,b=0;switch(o){case"left":h=t*n,b=-t*r;break;case"right":h=-t*n,b=t*r;break;case"front":d=-t*n,y=t*r*.7}if(t>0&&(m=[h,f,d],p=[y,0,b]),i>0&&(g={enabled:!0,strength:i*s*2.5,impactPoint:a.impactPoint,falloffRadius:.5}),e>=.28&&e<.32&&(l=!0),e<.35){const t=e/.35;c=1+.8*(1-t),u=.5*(1-t)}}else{const t=void 0!==a.shatterTriggerAt?a.shatterTriggerAt:.1,i=t+.02;if(e<t){if(t>0){const i=e/t,s=i*i;c=1+.6*s,u=.3*s,d=1+.05*s,"explosive"===n&&(d+=.01*Math.sin(200*e)*i)}}else if(e<i)l=e>=t&&e<t+.005,c=1.6,u=.4,d=1.05;else{if(f&&e>=y&&e<y+.02&&(h=!0),f&&e>=y){const t=(e-y)/(1-y),i=t*t;c=1+.8*i,u=.5*i,e>.95&&(c=2,u=.8)}else{const t=(e-i)/(f?y-i:1-i),s=Math.min(1,t),n=1-(1-s)*(1-s);c=1.6-.6*n,u=.4-.4*n}d=1}}const b={scale:d,glowIntensity:c,glowBoost:u,shatter:{enabled:l,impactPoint:a.impactPoint,impactDirection:a.impactDirection||[0,0,-1],intensity:s*a.intensity,variant:n,reassemble:h,reassembleDuration:a.reassembleDuration||1e3,revealSoul:!1!==a.revealSoul,isSuspendMode:a.isSuspendMode||!1,suspendAt:a.suspendAt||.25,suspendDuration:a.suspendDuration||.35,isFreezeMode:a.isFreezeMode||!1,gravity:a.gravity,explosionForce:a.explosionForce,rotationForce:a.rotationForce,gestureDuration:a.duration,isDualMode:a.isDualMode||!1,dualModeType:a.dualModeType,dualModeConfig:{duration:a.dualModeDuration||2e3,impactPoint:a.impactPoint,windDirection:a.windDirection,windForce:a.windForce,turbulence:a.turbulence,waveSpeed:a.waveSpeed,floorY:a.floorY,orbitSpeed:a.orbitSpeed,radiusMultiplier:a.radiusMultiplier,reassemble:a.reassemble,reassembleDuration:a.reassembleDuration}}};return g&&(b.deformation=g),m&&(b.cameraRelativePosition=m),p&&(b.cameraRelativeRotation=p),b}}}}const kt={up:{name:"dissolveUp",emoji:"๐ฌ๏ธ",description:"Shards blow upward like rising dust",windDirection:[0,1,.1],windForce:2.5,turbulence:.6},down:{name:"dissolveDown",emoji:"๐จ",description:"Shards blow downward like falling ash",windDirection:[0,-1,.1],windForce:1.8,turbulence:.4},left:{name:"dissolveLeft",emoji:"โฌ
๏ธ",description:"Shards blow left in the wind",windDirection:[-1,.15,0],impactDir:[1,.15,0],windForce:2.2,turbulence:.5},right:{name:"dissolveRight",emoji:"โก๏ธ",description:"Shards blow right in the wind",windDirection:[1,.15,0],impactDir:[-1,.15,0],windForce:2.2,turbulence:.5},away:{name:"dissolveAway",emoji:"๐ซ๏ธ",description:"Shards blow away from camera into distance",windDirection:[0,.1,-1],windForce:2,turbulence:.4},toward:{name:"dissolveToward",emoji:"๐ช๏ธ",description:"Shards blow toward camera",windDirection:[0,.1,1],windForce:2.5,turbulence:.6}};function Pt(e="away"){const t=kt[e]||kt.away;return{name:t.name,emoji:t.emoji,type:"override",description:t.description,config:{duration:3500,musicalDuration:{musical:!0,beats:6},intensity:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:6},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.2}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.intensity||.7,n=i.direction||"away",a=kt[n]||kt.away;let r=!1,o=1,l=0,h=1;const c=.06;if(e<c){const t=e/c;o=1+.4*t,l=.2*t,h=1+.03*t}else if(e<.08)r=e>=c&&e<.065,o=1.4,l=.3;else{const t=(e-c)/.94;o=1.4-.6*t,l=Math.max(0,.3-.3*t)}return{scale:h,glowIntensity:o,glowBoost:l,shatter:{enabled:r,impactPoint:[0,0,0],impactDirection:a.impactDir||a.windDirection,intensity:.5*s,variant:`dissolve_${n}`,revealSoul:!0,isSuspendMode:!1,isFreezeMode:!1,gravity:-.5,explosionForce:.3,gestureDuration:3500,isDualMode:!0,dualModeType:"dissolve",dualModeConfig:{duration:3e3,windDirection:a.windDirection,windForce:a.windForce*s,turbulence:a.turbulence}}}}}}}var Tt={name:"morph",emoji:"โจ",type:"override",description:"Form geometric patterns and shapes",config:{musicalDuration:{musical:!0,beats:2,minBeats:1,maxBeats:8},phases:[{name:"gather",beats:.25},{name:"form",beats:.75},{name:"hold",beats:.5},{name:"dissolve",beats:.5}],morphType:"fluid",pattern:"star",points:5,innerRadius:.4,size:80,amplitude:20,rotation:0,smooth:!0,randomizeOrder:!1,easing:"sine",strength:1.2,particleMotion:{type:"morph",pattern:"star",strength:1.2,smooth:!0,points:5}},rhythm:{enabled:!0,syncMode:"phrase",patternSync:{verse:"circle",chorus:"star",bridge:"heart",drop:"explosion"},timingSync:{formationBeat:1,holdBeats:2,dissolveBeat:4,curve:"anticipatory"},sizeSync:{onBeat:1.2,offBeat:.95,subdivision:"quarter",curve:"elastic"},rotationSync:{mode:"continuous",degreesPerBar:90,direction:"clockwise"},dynamics:{forte:{points:8,size:100},piano:{points:3,size:60}}},initialize(e,t,i,s,n){e.gestureData||(e.gestureData={});const a={...this.config,...t},r=e.x,o=e.y,l=Math.atan2(e.y-s,e.x-i),h=Math.random()<.5?1:-1;let c,u;const d=a.size*e.scaleFactor,g=(a.rotation||0)*Math.PI/180*h;switch(a.pattern){case"star":c=i,u=s,this.calculateStarPosition(e,l,d,a.points,a.innerRadius,g,i,s);break;case"heart":this.calculateHeartPosition(e,l,d,g,i,s);break;case"square":this.calculateSquarePosition(e,l,d,g,i,s);break;case"triangle":this.calculateTrianglePosition(e,l,d,g,i,s);break;default:{const e=d;c=i+Math.cos(l+g)*e,u=s+Math.sin(l+g)*e;break}}e.gestureData.morph={startX:r,startY:o,targetX:e.gestureData.morphTargetX||c,targetY:e.gestureData.morphTargetY||u,originalVx:e.vx,originalVy:e.vy,rotationDirection:h,initialized:!0}},calculateStarPosition(e,t,i,s,n,a,r,o){const l=((t+Math.PI)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),h=Math.floor(l/(2*Math.PI)*10),c=h%2==0,u=Math.floor(h/2);let d;d=c?72*u*Math.PI/180:(72*u+36)*Math.PI/180,d+=a;const g=c?i:i*n;e.gestureData.morphTargetX=r+Math.cos(d)*g,e.gestureData.morphTargetY=o+Math.sin(d)*g},calculateHeartPosition(e,t,i,s,n,a){const r=(t+Math.PI)/(2*Math.PI),o=.05*i,l=16*Math.pow(Math.sin(r*Math.PI*2),3),h=-(13*Math.cos(r*Math.PI*2)-5*Math.cos(2*r*Math.PI*2)-2*Math.cos(3*r*Math.PI*2)-Math.cos(4*r*Math.PI*2)),c=Math.cos(s),u=Math.sin(s),d=l*c-h*u,g=l*u+h*c;e.gestureData.morphTargetX=n+d*o,e.gestureData.morphTargetY=a+g*o},calculateSquarePosition(e,t,i,s,n,a){const r=((t+s)%(2*Math.PI)+2*Math.PI)%(2*Math.PI);let o,l;const h=i;r<Math.PI/4||r>=7*Math.PI/4?(o=h,l=h*Math.tan(r)):r<3*Math.PI/4?(o=h/Math.tan(r),l=h):r<5*Math.PI/4?(o=-h,l=-h*Math.tan(r)):(o=-h/Math.tan(r),l=-h);const c=Math.cos(s),u=Math.sin(s),d=o*c-l*u,g=o*u+l*c;e.gestureData.morphTargetX=n+d,e.gestureData.morphTargetY=a+g},calculateTrianglePosition(e,t,i,s,n,a){const r=[{x:0,y:-i},{x:.866*-i,y:.5*i},{x:.866*i,y:.5*i}],o=Math.floor((t+Math.PI)/(2*Math.PI)*3)%3,l=(o+1)%3,h=Math.random(),c=r[o].x+(r[l].x-r[o].x)*h,u=r[o].y+(r[l].y-r[o].y)*h,d=Math.cos(s),g=Math.sin(s),m=c*d-u*g,p=c*g+u*d;e.gestureData.morphTargetX=n+m,e.gestureData.morphTargetY=a+p},apply(e,t,i,s,n,a){e.gestureData?.morph?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.morph,o={...this.config,...i};let l,h,c=t;if(o.holdTime>0){const e=.5-o.holdTime/2,i=.5+o.holdTime/2;c=t<e?t/e*.5:t<i?.5:.5+(t-i)/(1-i)*.5}if(c<=.5){const e=2*c;l=r.startX+(r.targetX-r.startX)*this.easeOutQuad(e),h=r.startY+(r.targetY-r.startY)*this.easeOutQuad(e)}else{const e=2*(c-.5);l=r.targetX+(r.startX-r.targetX)*this.easeInQuad(e),h=r.targetY+(r.startY-r.targetY)*this.easeInQuad(e)}if(o.smooth){const t=.2;e.x+=(l-e.x)*t,e.y+=(h-e.y)*t}else e.x=l,e.y=h;if(e.vx=.5*(l-e.x),e.vy=.5*(h-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.morph){const t=e.gestureData.morph;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.morph,delete e.gestureData.morphTargetX,delete e.gestureData.morphTargetY}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutQuad:e=>e*(2-e),easeInQuad:e=>e*e,"3d":{evaluate(e,t){const i=t?.strength||1,s=Math.sin(e*Math.PI);let n;if(e<=.5){const t=2*e;n=1+t*(2-t)*.25*i}else{const t=2*(e-.5);n=1.25*i+t*t*(1-1.25*i),n=Math.max(1,n)}return{position:[0,0,0],rotation:[0,s*Math.PI*.3*i,.1*Math.sin(e*Math.PI*2)*i],scale:n,glowIntensity:1+.4*s*i,glowBoost:1.5*s*i}}}},Et={name:"rain",emoji:"๐ง๏ธ",type:"override",description:"Particles fall down from their current positions",config:{duration:3e3,musicalDuration:{musical:!0,bars:2},fallSpeed:8,fallDistance:400,wobbleAmount:1.5,strength:1,particleMotion:{type:"rain",strength:1,fallSpeed:8}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:2},intensitySync:{quiet:.5,loud:1.5,crescendo:"increase",diminuendo:"decrease"}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.rain={originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,originalOpacity:e.opacity??e.life??1,currentX:e.x,currentY:e.y,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(e,t,i,s){const n="number"==typeof s?s:1;e.gestureData?.rain?.initialized||this.initialize(e,i);const a=e.gestureData.rain,r={...this.config,...i},o=i?.strength||1,l=(r.fallSpeed||8)*o,h=(r.fallDistance||400)*t*o;a.wobblePhase+=a.wobbleSpeed*n*.1;const c=Math.sin(a.wobblePhase)*(r.wobbleAmount||1.5);if(e.x=a.originalX+c,e.y=a.originalY+h,e.vx=.3*c,e.vy=10*l,t>.6){const i=(t-.6)/.4;e.opacity=a.originalOpacity*(1-i),void 0!==e.life&&(e.life=a.originalOpacity*(1-i))}else e.opacity=a.originalOpacity,void 0!==e.life&&(e.life=a.originalOpacity)},cleanup(e){if(e.gestureData?.rain){const t=e.gestureData.rain;e.x=t.originalX,e.y=t.originalY,e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.originalOpacity,void 0!==e.life&&(e.life=t.originalOpacity),delete e.gestureData.rain}},"3d":{evaluate:(e,t)=>({position:[0,0,0],rotation:[0,0,0],scale:1})}},At={name:"drift",emoji:"โ๏ธ",type:"override",description:"Controlled floating with fade effects",config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,angle:45,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,angleSpread:45,smoothness:.08,easing:"ease",strength:1,particleMotion:{type:"drift",strength:1,distance:60}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"beats",beats:2},distanceSync:{quiet:30,loud:80,crescendo:"expand",diminuendo:"contract"},angleSync:{major:45,minor:225,modulation:"smooth",cadence:"return"},holdSync:{shortPhrase:.1,longPhrase:.4,fermata:"sustain"},accentResponse:{enabled:!0,multiplier:1.3,type:"distance"},patternOverrides:{ambient:{distanceSync:{quiet:40,loud:100},holdSync:{shortPhrase:.3,longPhrase:.6}},classical:{angleSync:{major:30,minor:210},distanceSync:{quiet:25,loud:60}},jazz:{angleSync:{major:60,minor:240,swing:!0,syncopated:!0}},new_age:{distanceSync:{quiet:35,loud:70},holdSync:{shortPhrase:.4,longPhrase:.8},angleSync:{modulation:"gradual"}}},dynamics:{forte:{distanceSync:{quiet:{multiplier:1.5},loud:{multiplier:1.8}},holdSync:{multiplier:1.2},accentResponse:{multiplier:1.6}},piano:{distanceSync:{quiet:{multiplier:.6},loud:{multiplier:.8}},holdSync:{multiplier:.8},accentResponse:{multiplier:1.1}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;let r=Math.atan2(a,n);const o={...this.config,...t}.angleSpread*Math.PI/180,l=(Math.random()-.5)*o;r+=l;const h=30+30*Math.random();e.gestureData.drift={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,driftAngle:r,angleOffset:l,homeRadius:h*e.scaleFactor,homeX:i+Math.cos(r)*h,homeY:s+Math.sin(r)*h,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.drift?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.drift,o={...this.config,...i},l=i.strength||1,h=this.easeInOutCubic(t),c=Math.max(0,h-.1*r.role);let u,d,g;if(o.returnToOrigin)if(c<.4){const e=c/.4,t=this.easeOutQuad(e);u=r.startX+(r.homeX-r.startX)*t,d=r.startY+(r.homeY-r.startY)*t}else if(c<.6+o.holdTime){const t=(c-.4)/(.2+o.holdTime);g=r.homeRadius+Math.sin(t*Math.PI*.5)*o.distance*l*e.scaleFactor}else{const t=(c-.6-o.holdTime)/(.4-o.holdTime);g=r.homeRadius+Math.cos(t*Math.PI*.5)*o.distance*l*e.scaleFactor}else{const t=c;g=r.homeRadius+t*o.distance*l*e.scaleFactor}if(void 0!==g){r.turbulencePhase+=o.turbulence*s;const e=Math.sin(r.turbulencePhase)*o.turbulence*10,t=Math.cos(1.3*r.turbulencePhase)*o.turbulence*10,i=r.driftAngle+r.angleOffset;u=n+Math.cos(i)*g+e,d=a+Math.sin(i)*g+t}const m=o.smoothness+.08*r.role;if(e.x+=(u-e.x)*m,e.y+=(d-e.y)*m,e.vx=.25*(u-e.x),e.vy=.25*(d-e.y),o.fadeOut){let i;i=t<.25?.3+t/.25*.7:t<.75?.7+.3*Math.sin((t-.25)*Math.PI/.5):4*(1-t),e.opacity=r.baseOpacity*i,void 0!==e.life&&(e.life=e.opacity)}t>=.99&&(e.vx=.1*r.originalVx,e.vy=.1*r.originalVy,o.fadeOut&&(e.opacity=r.baseOpacity,void 0!==e.life&&(e.life=r.baseOpacity)))},cleanup(e){if(e.gestureData?.drift){const t=e.gestureData.drift;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.drift}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const i={...this.config,...t},s=t.strength||1,n=(i.angle||45)*Math.PI/180,a=i.returnToOrigin?e<.5?2*e:2*(1-e):e;return{position:[Math.cos(n)*a*.3*s,Math.sin(n)*a*.3*s,.15*Math.sin(e*Math.PI)*s],rotation:[0,10*a*s,0],scale:1+.03*Math.sin(e*Math.PI),glowIntensity:1-.1*a}}}};function Dt(e){const t=A[e];if(!t)throw new Error(`Invalid drift direction: ${e}`);const i="up"===e||"down"===e;return{name:`drift${D(e)}`,emoji:"up"===e?"โ๏ธ":"down"===e?"๐":"left"===e?"๐ซ๏ธ":"๐ญ",type:"override",description:`Gentle drifting ${e}`,config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,smoothness:.08,strength:1,direction:e,particleMotion:{type:"drift",strength:1,distance:60}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"beats",beats:2},distanceSync:{quiet:30,loud:80,crescendo:"expand",diminuendo:"contract"},holdSync:{shortPhrase:.1,longPhrase:.4,fermata:"sustain"},accentResponse:{enabled:!0,multiplier:1.3,type:"distance"}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=(30+30*Math.random())*e.scaleFactor;e.gestureData.drift={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,homeRadius:n,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.drift?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.drift,h={...this.config,...n},c=n.strength||1,u=this.easeInOutCubic(s),d=Math.max(0,u-.1*l.role);let g,m=l.startX,p=l.startY;g=h.returnToOrigin?d<.5?2*d:2*(1-d):d;const f=h.distance*c*e.scaleFactor*g;l.turbulencePhase+=h.turbulence*a;const y=Math.sin(l.turbulencePhase)*h.turbulence*10,b=Math.cos(1.3*l.turbulencePhase)*h.turbulence*10;i?(p=l.startY+t.y*f+y,m=l.startX+.5*b):(m=l.startX+t.x*f+b,p=l.startY+.5*y);const v=h.smoothness+.08*l.role;if(e.x+=(m-e.x)*v,e.y+=(p-e.y)*v,e.vx=.25*(m-e.x),e.vy=.25*(p-e.y),h.fadeOut){let t=1;t=s<.25?.3+s/.25*.7:s<.75?.7+.3*Math.sin((s-.25)*Math.PI/.5):4*(1-s),e.opacity=l.baseOpacity*t}s>=.99&&(e.vx=.1*l.originalVx,e.vy=.1*l.originalVy,h.fadeOut&&(e.opacity=l.baseOpacity))},cleanup(e){if(e.gestureData?.drift){const t=e.gestureData.drift;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,delete e.gestureData.drift}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,s){const n=s||{},a=n.strength||1,r=n.distance||50,o=!1!==n.returnToOrigin?Math.sin(e*Math.PI):e,l=.004*r*a*o,h=t.x*l,c=t.y*l;let u=0,d=0;return i?u=t.y*o*.1:d=t.x*o*.15,{cameraRelativePosition:[h,c,0],rotation:[u,d,0],scale:1+.03*o,glowIntensity:1-.1*o}}}}}var _t=Dt("up"),It=Dt("down"),Rt=Dt("left"),Bt=Dt("right"),zt={name:"vortex",emoji:"๐",type:"override",description:"Spiral tornado pattern inward or outward",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},direction:"inward",rotationSpeed:2,pullStrength:1,liftAmount:.5,strength:1,particleMotion:{type:"vortex",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",rotationSync:{onBeat:1.5,offBeat:.8}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-(i||0),a=e.y-(s||0);e.gestureData.vortex={originalX:e.x,originalY:e.y,startAngle:Math.atan2(a,n),startDistance:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.vortex?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=e.gestureData.vortex,l="outward"!==r.direction,h=r.rotationSpeed||2,c=r.pullStrength||1,u=t*h*Math.PI*2,d=o.startAngle+u;let g;g=l?1-t*c*.8:1+t*c*.5;const m=o.startDistance*g;e.x=n+Math.cos(d)*m,e.y=a+Math.sin(d)*m,l&&t>.7&&(e.opacity=1-(t-.7)/.3)},cleanup(e){if(e.gestureData?.vortex){const t=e.gestureData.vortex;e.x=t.originalX,e.y=t.originalY,e.opacity=1,delete e.gestureData.vortex}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n="outward"!==i.direction,a=i.rotationSpeed||2,r=i.liftAmount||.5,o=e*a*Math.PI*2*s;let l;l=n?1-.3*e*s:1+.2*e*s;const h=e>.85?(1-e)/.15:1;return{position:[0,Math.sin(e*Math.PI)*r*.1*s*h,0],rotation:[.1*Math.sin(o)*s*h,o,.1*Math.cos(o)*s*h],scale:l,glowIntensity:1+.4*e,glowBoost:.3*e}}}};function Ft(e){if(!A[e])throw new Error(`Invalid cascade direction: ${e}`);const t="up"===e||"down"===e,i="down"===e||"right"===e;return{name:`cascade${D(e)}`,emoji:"down"===e?"๐":"up"===e?"โจ":"left"===e?"๐":"๐ฌ๏ธ",type:"override",description:`Sequential cascade ${e}`,config:{duration:2e3,musicalDuration:{musical:!0,bars:1},distance:200,waveCount:4,staggerDelay:.15,wobble:1,strength:1,direction:e,particleMotion:{type:"cascade",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",distanceSync:{quiet:100,loud:300,crescendo:"expand",diminuendo:"contract"}},initialize(e,t){e.gestureData||(e.gestureData={});const i=t?.waveCount||4;let s;s=Math.floor(Math.random()*i),e.gestureData.cascade={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,waveGroup:s,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.cascade?.initialized||this.initialize(e,n);const l={...this.config,...n},h=l.strength||1,c=e.gestureData.cascade,u="number"==typeof a?a:1,d=l.waveCount||4,g=l.staggerDelay||.15,m=c.waveGroup*g,p=Math.max(0,(s-m)/(1-m*(d-1)/d));if(p<=0)return;const f=(1-Math.pow(1-p,2))*((l.distance||200)*h)*(i?1:-1);c.wobblePhase+=c.wobbleSpeed*u*.1;const y=Math.sin(c.wobblePhase)*(l.wobble||1)*10;if(t?(e.y=c.originalY+f,e.x=c.originalX+y):(e.x=c.originalX+f,e.y=c.originalY+y),p>.6){const t=(p-.6)/.4;e.opacity=c.originalOpacity*(1-t)}},cleanup(e){if(e.gestureData?.cascade){const t=e.gestureData.cascade;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.cascade}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"down",a=1-Math.pow(1-e,2);let r=0,o=0;const l=.3*a*s;switch(n){case"down":o=-l;break;case"up":o=l;break;case"left":r=-l;break;case"right":r=l}const h=.03*Math.sin(e*Math.PI*4)*s;"down"===n||"up"===n?r+=h:o+=h;const c=e>.85?(1-e)/.15:1;return{cameraRelativePosition:[r*c,o*c,0],rotation:[("down"===n?.05:"up"===n?-.05:0)*s*c,0,("left"===n?.1:"right"===n?-.1:0)*s*c],scale:1-.1*a,glowIntensity:1+.2*(1-a)}}}}}var Ot=Ft("up"),Lt=Ft("down"),qt=Ft("left"),Gt=Ft("right"),Ht={name:"confetti",emoji:"๐",type:"effect",description:"Celebratory confetti flutter with chaotic rotation",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},burstHeight:.3,fallSpeed:1,tumbleSpeed:2,spread:1,strength:1,particleMotion:{type:"confetti",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1.5},timingSync:"onBeat"},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.confetti={originalX:e.x,originalY:e.y,driftX:2*(Math.random()-.5),tumblePhase:Math.random()*Math.PI*2,tumbleSpeed:.5+1.5*Math.random(),flutterAmp:.3+.7*Math.random(),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.confetti?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||1,l=e.gestureData.confetti,h=Math.min(t/.2,1),c=Math.max(0,(t-.2)/.8),u=-50*Math.sin(h*Math.PI)*(r.burstHeight||.3),d=c*c*200*(r.fallSpeed||1),g=20*Math.sin(t*Math.PI*8*l.tumbleSpeed)*l.flutterAmp,m=l.driftX*t*100*(r.spread||1);e.x=l.originalX+m+g*o,e.y=l.originalY+u+d*o,t>.7&&(e.opacity=1-(t-.7)/.3)},cleanup(e){e.gestureData?.confetti&&delete e.gestureData.confetti},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1,s=Math.min(e/.2,1),n=Math.max(0,(e-.2)/.8),a=.15*Math.sin(s*Math.PI)-n*n*.3,r=e*Math.PI*4,o=.3*Math.sin(1.3*r)*i,l=.4*Math.sin(.7*r)*i,h=.5*Math.sin(1.1*r)*i,c=e>.85?(1-e)/.15:1;return{position:[.08*Math.sin(e*Math.PI*6)*i*c,a*i*c,0],rotation:[o*c,l*c,h*c],scale:1+.1*Math.sin(2*r)*i,glowIntensity:1+.3*(1-n)}}}},jt={name:"fizz",emoji:"๐ซง",type:"override",description:"Bubbles rising upward with wobble",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},riseSpeed:6,riseDistance:300,wobbleAmount:2,strength:1,particleMotion:{type:"fizz",strength:1}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:1.5},intensitySync:{quiet:.5,loud:1.5}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.fizz={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.4+.6*Math.random(),riseMultiplier:.7+.6*Math.random(),initialized:!0}},apply(e,t,i,s){e.gestureData?.fizz?.initialized||this.initialize(e,i);const n={...this.config,...i},a=n.strength||1,r=e.gestureData.fizz,o="number"==typeof s?s:1,l=(n.riseDistance||300)*t*a*r.riseMultiplier;r.wobblePhase+=r.wobbleSpeed*o*.1;const h=Math.sin(r.wobblePhase)*(n.wobbleAmount||2)*(1+t);if(e.x=r.originalX+h,e.y=r.originalY-l,e.vx=.3*h,e.vy=10*-(n.riseSpeed||6),t>.6){const i=(t-.6)/.4;e.opacity=r.originalOpacity*(1-i),void 0!==e.life&&(e.life=r.originalOpacity*(1-i))}},cleanup(e){if(e.gestureData?.fizz){const t=e.gestureData.fizz;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,void 0!==e.life&&(e.life=t.originalOpacity),delete e.gestureData.fizz}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=1,a=1;if(e<.15){const t=e/.15;s=.15*t,n=1+.02*t,a=1+.15*t}else if(e<.7){const t=(e-.15)/.55;s=.5-.15*t,n=1.02+.03*Math.sin(t*Math.PI*6),a=1.2+.15*Math.sin(t*Math.PI*8)}else{const t=(e-.7)/.3;s=.35*(1-t),n=1.02-.02*t,a=1.2-.2*t}const r=35*e;return{position:[.008*Math.sin(1.7*r)*s*i,.006*Math.sin(2.3*r)*s*i,.004*Math.sin(1.9*r)*s*i],rotation:[.03*Math.sin(1.3*r)*s*i,.02*Math.sin(1.1*r)*s*i,.04*Math.sin(1.5*r)*s*i],scale:[n+.015*Math.sin(2.1*r)*s,n+.02*Math.sin(1.8*r)*s,n+.015*Math.sin(2.4*r)*s],glowIntensity:a,glowBoost:.2*s}}}};function $t(e){const t=A[e];if(!t)throw new Error(`Invalid swarm direction: ${e}`);return{name:`swarm${D(e)}`,emoji:"up"===e?"๐ฆ
":"down"===e?"๐ฆ":"๐",type:"override",description:`Flock movement ${e}`,config:{duration:1800,musicalDuration:{musical:!0,bars:1},clusterPhase:.3,moveDistance:120,clusterTightness:.5,wobble:1,strength:1,direction:e,particleMotion:{type:"swarm",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.swarm={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),timeOffset:.1*Math.random(),initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.swarm?.initialized||this.initialize(e,s,a,r);const o={...this.config,...s},l=o.strength||1,h=e.gestureData.swarm,c=o.clusterPhase||.3,u=o.moveDistance||120,d=o.clusterTightness||.5,g=Math.max(0,Math.min(1,i-h.timeOffset));let m,p;if(g<c){const e=g/c,t=1-Math.pow(1-e,2);m=h.originalX+(a-h.originalX)*d*t,p=h.originalY+(r-h.originalY)*d*t}else{const e=(g-c)/(1-c),i=1-Math.pow(1-e,2),s=h.originalX+(a-h.originalX)*d,n=h.originalY+(r-h.originalY)*d;m=s+t.x*u*i*l,p=n+t.y*u*i*l}const f="number"==typeof n?n:1;h.wobblePhase+=h.wobbleSpeed*f*.1;const y=Math.sin(3*h.wobblePhase)*o.wobble*5,b=Math.cos(2.5*h.wobblePhase)*o.wobble*5;e.x=m+y,e.y=p+b,g>.8&&(e.opacity=h.originalOpacity*(1-5*(g-.8)))},cleanup(e){if(e.gestureData?.swarm){const t=e.gestureData.swarm;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.swarm}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"up",a=i.clusterPhase||.3,[r,o]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];let l=0,h=0,c=1;if(e<a)c=1-e/a*.1*s;else{const t=(e-a)/(1-a),i=1-Math.pow(1-t,2);l=r*i*.25*s,h=o*i*.25*s,c=.9+.1*t}const u=e>a?.1:0,d=e>.85?(1-e)/.15:1;return{cameraRelativePosition:[(l+.02*Math.sin(e*Math.PI*6)*s)*d,h*d,0],rotation:[o*u*s,0,-r*u*s],scale:c,glowIntensity:1+(e>a?.2:0)}}}}}var Wt=$t("up"),Ut=$t("down"),Vt=$t("left"),Yt=$t("right"),Xt={name:"burst",emoji:"๐ฅ",type:"blending",description:"Explosive outward burst from center",config:{decay:.5,strength:2},rhythm:{enabled:!0,syncMode:"beat",strengthSync:{onBeat:3.5,offBeat:1,curve:"explosion"},decaySync:{mode:"tempo",fast:.8,slow:.3,curve:"exponential"},durationSync:{mode:"beats",beats:.5,sustain:!1},accentResponse:{enabled:!0,multiplier:2.5,type:"strength"},patternOverrides:{rock:{strengthSync:{onBeat:4,offBeat:1.5},decaySync:{fast:.6,slow:.4}},electronic:{strengthSync:{onBeat:3.8,offBeat:.8,curve:"sharp"},decaySync:{fast:.9,slow:.7}},jazz:{strengthSync:{onBeat:2.8,offBeat:1.8,swing:!0},decaySync:{fast:.5,slow:.2}},orchestral:{strengthSync:{onBeat:3.2,offBeat:.5},accentResponse:{multiplier:3}}},dynamics:{forte:{strengthSync:{onBeat:{multiplier:2},offBeat:{multiplier:1.5}},decaySync:{multiplier:.7},accentResponse:{multiplier:3.5}},piano:{strengthSync:{onBeat:{multiplier:.6},offBeat:{multiplier:.3}},decaySync:{multiplier:1.3},accentResponse:{multiplier:1.8}}}},apply(e,t,i,s,n,a){const r=i.decay||this.config.decay,o=(i.strength||this.config.strength)*(1-t*r),l=e.x-n,h=e.y-a,c=Math.sqrt(l*l+h*h);c>1&&(e.vx+=l/c*o*2*s,e.vy+=h/c*o*2*s)},"3d":{evaluate(e,t){const i=t.strength||2;let s=0,n=1,a=1,r=0;if(e<.15){const t=e/.15,o=1-Math.pow(1-t,3);s=.15*o*i,n=1+.2*o*i,a=1+.5*o,r=.4*o}else if(e<.35){const t=(e-.15)/.2;s=.15*(1-1.5*t)*i,n=1+.2*(1-t)*i-.1*Math.sin(t*Math.PI),a=1+.4*(1-t),r=.2*(1-t)}else{const t=(e-.35)/.65,r=Math.pow(1-t,2),o=Math.sin(t*Math.PI*2)*r;s=.03*o*i,n=1+.05*o,a=1+.15*Math.abs(o)}return{cameraRelativePosition:[0,0,s],position:[0,0,0],rotation:[0,0,0],scale:n,glowIntensity:a,glowBoost:r}}}};function Nt(e){const t=A[e];if(!t)throw new Error(`Invalid burst direction: ${e}`);const i="up"===e||"down"===e;return{name:`burst${D(e)}`,emoji:"up"===e?"โฒ":"down"===e?"๐ฟ":"๐จ",type:"blending",description:`Explosive burst ${e}`,config:{duration:600,musicalDuration:{musical:!0,beats:1},decay:.5,strength:2,spread:.3,direction:e,particleMotion:{type:"burst",strength:2,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",strengthSync:{onBeat:3.5,offBeat:1,curve:"explosion"},accentResponse:{enabled:!0,multiplier:2.5,type:"strength"}},apply(e,s,n,a,r,o){const l={...this.config,...n},h=l.decay||.5,c=(l.strength||2)*(1-s*h),u=l.spread||.3;let d=t.x*c*2,g=t.y*c*2;const m=(Math.random()-.5)*u*c;i?d+=m:g+=m,e.vx+=d*a,e.vy+=g*a},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||2,n=i.direction||"up";let a=0,r=0,o=0,l=1,h=1,c=0;const[u,d]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];if(e<.15){const t=e/.15,i=1-Math.pow(1-t,3);a=u*i*.2*s,r=d*i*.2*s,o=.1*i*s,l=1+.15*i*s,h=1+.5*i,c=.4*i}else if(e<.35){const t=(e-.15)/.2,i=1-1.5*t;a=.2*u*i*s,r=.2*d*i*s,o=.1*i*s,l=1+.15*(1-t)*s,h=1+.4*(1-t),c=.2*(1-t)}else{const t=(e-.35)/.65,i=Math.pow(1-t,2),n=Math.sin(t*Math.PI*2)*i;a=u*n*.05*s,r=d*n*.05*s,l=1+.05*n,h=1+.15*Math.abs(n)}return{cameraRelativePosition:[a,r,o],position:[0,0,0],rotation:[0,0,0],scale:l,glowIntensity:h,glowBoost:c}}}}}var Qt=Nt("up"),Jt=Nt("down"),Kt=Nt("left"),Zt=Nt("right"),ei={name:"ripple",emoji:"๐",type:"effect",description:"Concentric waves emanating from center",config:{duration:1500,musicalDuration:{musical:!0,bars:1},waveCount:3,waveSpeed:1,amplitude:15,damping:.7,strength:1,particleMotion:{type:"ripple",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",amplitudeSync:{onBeat:1.5,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=r.waveCount||3,h=r.amplitude||15,c=r.damping||.7,u=e.x-n,d=e.y-a,g=Math.sqrt(u*u+d*d),m=(g/50-t*l*2)*Math.PI,p=Math.pow(1-t,c),f=Math.sin(m)*h*o*p;if(g>1){const t=.5*Math.cos(m)*o*p;e.x+=u/g*t,e.y+=d/g*t}e.opacity=Math.max(.3,1-.3*Math.abs(f/h))},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.waveCount||3,a=i.damping||.7,r=Math.pow(1-e,a),o=e*Math.PI*n*2,l=Math.sin(o),h=e*Math.PI*4,c=Math.sin(h)*s*r,u=.5*Math.sin(h+Math.PI/2)*s*r,d=.12,g=1-c*d+u*d*.3,m=1+c*d,p=1-c*d-u*d*.3,f=.08*(m-1);return{position:[.01*Math.sin(1.5*h)*r,f,0],rotation:[.04*l*s*r,0,.03*u*s*r],scale:[g,m,p],glowIntensity:1+.3*Math.abs(c),glowBoost:.25*Math.max(0,c)*r}}}},ti={name:"wave",emoji:"๐",type:"override",description:"Infinity pattern flow with phasing",config:{musicalDuration:{musical:!0,bars:1,minBeats:4,maxBeats:16},phases:[{name:"gather",beats:.5},{name:"rise",beats:.5},{name:"waveLeft",beats:1},{name:"waveRight",beats:1},{name:"settle",beats:1}],amplitude:40,frequency:1,phaseShift:.3,liftHeight:20,fadeInOut:!0,smoothness:.1,easing:"sine",strength:1,particleMotion:{type:"wave",strength:1,amplitude:50}},rhythm:{enabled:!0,syncMode:"wave",amplitudeSync:{onWave:65,onStatic:25,curve:"flowing"},frequencySync:{mode:"phrase",slow:.7,fast:1.8,curve:"melodic"},durationSync:{mode:"bars",adaptToPhrase:!0,sustain:!0},phaseSync:{enabled:!0,multiplier:.5,type:"ensemble"},melodicResponse:{enabled:!0,multiplier:1.4,type:"amplitude"},patternOverrides:{ambient:{amplitudeSync:{onWave:80,onStatic:40,curve:"hypnotic"},frequencySync:{slow:.5,fast:1.2},durationSync:{minBeats:16,maxBeats:64}},ocean:{amplitudeSync:{onWave:90,onStatic:20,curve:"natural"},phaseSync:{multiplier:.8},melodicResponse:{multiplier:1.8}},electronic:{amplitudeSync:{onWave:70,onStatic:30,curve:"digital"},frequencySync:{slow:.8,fast:2.5,curve:"precise"}},orchestral:{amplitudeSync:{onWave:75,onStatic:35},phaseSync:{multiplier:.7},melodicResponse:{multiplier:2}}},dynamics:{forte:{amplitudeSync:{onWave:{multiplier:1.8},onStatic:{multiplier:1.4}},frequencySync:{multiplier:1.3},melodicResponse:{multiplier:2.2}},piano:{amplitudeSync:{onWave:{multiplier:.6},onStatic:{multiplier:.4}},frequencySync:{multiplier:.7},melodicResponse:{multiplier:1.1}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=Math.random()<.5?1:-1;e.gestureData.wave={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,angle:r,radius:o,offset:Math.random()*Math.PI*2,role:Math.random(),direction:l,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.wave?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.wave,o={...this.config,...i},l=i.strength||1,h=this.easeInOutSine(t),c=r.role*o.phaseShift,u=Math.max(0,h-c),d=u*Math.PI*2*o.frequency*r.direction+r.offset,g=.5+r.radius/100*.5,m=o.amplitude*g*l*e.scaleFactor,p=n+Math.sin(d)*m,f=a+Math.sin(2*d)*m*.3+-Math.abs(Math.sin(h*Math.PI))*o.liftHeight*e.scaleFactor,y=o.smoothness+.12*r.role;if(e.x+=(p-e.x)*y,e.y+=(f-e.y)*y,e.vx=.3*(p-e.x),e.vy=.3*(f-e.y),o.fadeInOut){let t;t=u<.1?u/.1:u>.9?(1-u)/.1:.5+.5*Math.sin(u*Math.PI),e.opacity=r.baseOpacity*(.3+.7*t),void 0!==e.life&&(e.life=e.opacity)}if(t>=.95){const i=20*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i),o.fadeInOut&&(e.opacity=r.baseOpacity*i,void 0!==e.life&&(e.life=e.opacity))}},cleanup(e){if(e.gestureData?.wave){const t=e.gestureData.wave;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.wave}},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i=t?.strength||1,s=t?.frequency||1,n=-(Math.cos(Math.PI*e)-1)/2,a=n*Math.PI*2*s,r=.12*Math.sin(a)*i,o=.06*Math.sin(2*a)*i,l=.03*Math.sin(a)*i,h=.08*Math.sin(2*a)*i,c=.05*Math.sin(a)*i,u=1+.08*Math.abs(Math.sin(n*Math.PI))*i,d=Math.abs(Math.sin(a));return{position:[r,o,l],rotation:[h,0,c],scale:u,glowIntensity:1+.3*d*i,glowBoost:.6*d*i}}}},ii={name:"flash",emoji:"โก",type:"blending",description:"Bright flash burst effect",config:{duration:400,glowAmount:2.5,glowPeak:3,scalePeak:1.1,easing:"cubic",strength:1,particleMotion:{type:"burst",strength:1,decay:.3}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"immediate",interruptible:!0,priority:8,blendable:!0,intensitySync:{onBeat:3.5,offBeat:1,accent:5,subdivision:"quarter",curve:"exponential"},durationSync:{mode:"tempo",baseDuration:400,scaling:"inverse"},scaleSync:{onBeat:1.2,offBeat:1,accent:1.4,curve:"elastic"},strobeSync:{enabled:!1,pattern:"XXOX",subdivision:"sixteenth"},dynamics:{forte:{glowPeak:4,scalePeak:1.3,duration:300},piano:{glowPeak:2,scalePeak:1.05,duration:500}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.flash={originalOpacity:e.opacity,originalSize:e.size,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.flash?.initialized||this.initialize(e,i);const r=e.gestureData.flash,o={...this.config,...i},l=o.strength||1;let h;if(h=t<.3?t/.3*o.glowPeak:o.glowPeak*(1-(t-.3)/.7),e.opacity=Math.min(1,r.originalOpacity*(1+h*l)),e.size=r.originalSize*(1+(o.scalePeak-1)*h*l*.1),t<.2){const i=(1-t/.2)*l,r=Math.atan2(e.y-a,e.x-n);e.vx+=Math.cos(r)*i*2*s,e.vy+=Math.sin(r)*i*2*s}e.vx*=1-.1*o.particleMotion.decay,e.vy*=1-.1*o.particleMotion.decay},cleanup(e){e.gestureData?.flash&&(e.opacity=e.gestureData.flash.originalOpacity,e.size=e.gestureData.flash.originalSize,delete e.gestureData.flash)},"3d":{evaluate(e,t){const i={...this.config,...t};let s;t.strength,s=e<.3?e/.3:1-(e-.3)/.7;const n=1+.4*s;return{position:[0,0,0],rotation:[0,0,0],scale:1+s*((i.scalePeak||1.1)-1),glowIntensity:n,glowBoost:2*s}}}},si={name:"glow",emoji:"โจ",type:"blending",description:"Pure luminous glow without movement",config:{duration:1500,amplitude:0,frequency:1,holdPeak:.3,easing:"sine",scaleAmount:.1,glowAmount:.8,strength:0,direction:"none",particleMotion:{type:"glow",strength:0,direction:"none",frequency:1}},rhythm:{enabled:!0,syncMode:"phrase",amplitudeSync:{onBeat:2,offBeat:1.2,curve:"smooth"},frequencySync:{mode:"phrase",subdivision:"bar"},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:2.5},patternOverrides:{ambient:{amplitudeSync:{onBeat:2.5,offBeat:1.8},durationSync:{bars:4}},electronic:{amplitudeSync:{onBeat:3,offBeat:.5,curve:"sharp"},frequencySync:{subdivision:"quarter"}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.glow={startOpacity:e.opacity,startGlow:e.glowSizeMultiplier||0,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.glow?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=this.easeInOutSine(t);let l,{frequency:h}=r,{glowAmount:c}=r;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const u=o*h*2%2;l=r.holdPeak>0&&u>1-r.holdPeak&&u<1+r.holdPeak?1:Math.sin(o*Math.PI*2*h);let d=1;t>.9&&(d=.5+.5*(1-10*(t-.9))),e.glowIntensity=1+l*c*d},cleanup(e){e.gestureData?.glow&&(e.glowIntensity=1,delete e.gestureData.glow)},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i={...this.config,...t},s=-(Math.cos(Math.PI*e)-1)/2,n=Math.sin(s*Math.PI);let a=i.glowAmount||.8;t.rhythmModulation&&(a*=t.rhythmModulation.amplitudeMultiplier||1,a*=t.rhythmModulation.accentMultiplier||1);const r=1+n*a;return{position:[0,0,0],rotation:[0,0,0],scale:1+n*(i.scaleAmount||.1)*.5,glowIntensity:r,glowBoost:1.5*n}}}},ni={name:"bloom",emoji:"๐ธ",type:"effect",description:"Particles unfold outward like flower petals opening",config:{duration:1500,musicalDuration:{musical:!0,bars:1},petalCount:6,openingSpeed:1,rotationAmount:.3,strength:1,particleMotion:{type:"bloom",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",amplitudeSync:{onBeat:1.3,offBeat:.8}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-(i||0),a=e.y-(s||0);e.gestureData.bloom={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,startAngle:Math.atan2(a,n),startDistance:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.bloom?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=e.gestureData.bloom,h=Math.pow(t,.7),c=(r.rotationAmount||.3)*Math.PI,u=Math.sin(h*Math.PI)*c,d=1+.5*h*o,g=l.startDistance*d,m=l.startAngle+u;e.x=n+Math.cos(m)*g,e.y=a+Math.sin(m)*g,e.opacity=Math.min(1,l.originalOpacity*(.7+.3*h))},cleanup(e){if(e.gestureData?.bloom){const t=e.gestureData.bloom;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.bloom}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotationAmount||.3,a=Math.pow(e,.7),r=1+.2*a*s,o=Math.sin(a*Math.PI)*n*s,l=.1*Math.sin(a*Math.PI*.5)*s,h=e>.85?1-(e-.85)/.15*.3:1;return{position:[0,.05*Math.sin(a*Math.PI)*s*h,0],rotation:[0,o*h,l*h],scale:r*(.7+.3*h),glowIntensity:1+.4*a,glowBoost:.3*a}}}},ai={name:"flicker",emoji:"โก",type:"blending",description:"Rapid opacity changes with motion jitter",config:{duration:800,musicalDuration:{musical:!0,beats:2},flickerRate:15,frequency:6,minOpacity:.3,maxOpacity:1,jitterAmount:2,colorShift:!1,strobe:!1,pulseMode:!1,groupFlicker:.3,easing:"linear",strength:.7,particleMotion:{type:"flicker",strength:.7,frequency:6}},rhythm:{enabled:!0,syncMode:"subdivision",durationSync:{mode:"beats",beats:2},rateSync:{subdivision:"sixteenth",onBeat:30,offBeat:10,triplet:20,curve:"step"},opacitySync:{pattern:"HLMH",subdivision:"eighth",onAccent:.1,regular:.5},jitterSync:{onBeat:5,offBeat:1,accent:10,curve:"random"},strobeSync:{verse:!1,chorus:!0,drop:"intense",pattern:"XOXO"},dynamics:{forte:{flickerRate:25,jitterAmount:5,minOpacity:.1},piano:{flickerRate:8,jitterAmount:1,minOpacity:.5}}},initialize(e,t){e.gestureData||(e.gestureData={});const i={...this.config,...t},s=Math.random()<i.groupFlicker;e.gestureData.flicker={baseOpacity:e.opacity||e.life||1,baseColor:e.color,baseX:e.x,baseY:e.y,flickerTimer:0,lastFlicker:0,flickerState:!0,isGrouped:s,groupId:s?Math.floor(3*Math.random()):-1,phase:Math.random()*Math.PI*2,colorHue:0,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.flicker?.initialized||this.initialize(e,i);const r=e.gestureData.flicker,o={...this.config,...i},l=i.strength||1;let h;if(r.flickerTimer+=s*o.flickerRate,o.strobe)h=(r.flickerTimer+r.phase)%1<.5?1:o.minOpacity;else if(o.pulseMode){const e=r.flickerTimer+r.phase;h=o.minOpacity+(o.maxOpacity-o.minOpacity)*(.5*Math.sin(e)+.5)}else{if(r.flickerTimer-r.lastFlicker>1)if(r.lastFlicker=r.flickerTimer,r.isGrouped){const e=Math.floor(r.flickerTimer)%3;r.flickerState=e===r.groupId}else r.flickerState=Math.random()>.3;const t=r.flickerState?o.maxOpacity:o.minOpacity+.3*Math.random(),i=e.opacity/r.baseOpacity;h=i+.3*(t-i)}const c=r.baseOpacity*(1+(h-1)*l);if(e.opacity=Math.max(0,Math.min(1,c)),void 0!==e.life&&(e.life=e.opacity),o.jitterAmount>0&&h>o.minOpacity){const t=o.jitterAmount*l*e.scaleFactor,i=(Math.random()-.5)*t*h,n=(Math.random()-.5)*t*h;e.vx+=.1*i*s,e.vy+=.1*n*s}if(o.colorShift&&e.color){r.colorHue+=.01*s;const t=30*Math.sin(r.colorHue);e.color=this.shiftHue(r.baseColor,t*l)}let u=1;t<.1?u=t/.1:t>.9&&(u=(1-t)/.1),e.opacity*=u,void 0!==e.life&&(e.life=e.opacity),t>.8&&(e.vx*=.95,e.vy*=.95)},shiftHue(e,t){if(!e||!e.startsWith("#"))return e;const i=e.slice(1),s=parseInt(i.substr(0,2),16)/255,n=parseInt(i.substr(2,2),16)/255,a=parseInt(i.substr(4,2),16)/255,r=t*Math.PI/180,o=Math.cos(r),l=Math.sin(r),h=s*l+n*o,c=a,u=e=>Math.max(0,Math.min(255,Math.round(255*e))).toString(16).padStart(2,"0");return`#${u(s*o-n*l)}${u(h)}${u(c)}`},cleanup(e){if(e.gestureData?.flicker){const t=e.gestureData.flicker;e.opacity=t.baseOpacity,e.color=t.baseColor,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.flicker}},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||.7,n=i.flickerRate||15;i.minOpacity;const a=e*n,r=Math.sin(a*Math.PI*2),o=Math.floor(10*a),l=.3*r+.5*(Math.sin(123.456*o)+1)*.7,h=.6+.8*l,c=i.jitterAmount||2,u=.003*s*h,d=(Math.random()-.5)*c*u,g=(Math.random()-.5)*c*u,m=.03*(Math.random()-.5)*s*h;return{position:[d,g,0],rotation:[.5*m,0,m],scale:1+.08*(h-1),glowIntensity:h,glowBoost:1.2*l}}}},ri={name:"shiver",emoji:"๐ฅถ",type:"effect",description:"High-frequency micro-vibrations for nervousness or cold",config:{duration:1500,musicalDuration:{musical:!0,bars:1},frequency:30,amplitude:.02,decay:.3,strength:1,particleMotion:{type:"shiver",strength:.8}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:1},intensitySync:{quiet:.5,loud:1.5,crescendo:"increase",diminuendo:"decrease"}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=r.frequency||30,h=100*(r.amplitude||.02),c=t*l*Math.PI*2,u=(.6*Math.sin(c)+.3*Math.sin(1.7*c+1.3)+.1*Math.sin(2.3*c+2.7))*h*o,d=Math.sin(t*Math.PI);e.x+=u*d*(Math.random()-.5)*2,e.y+=u*d*(Math.random()-.5)*2},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.frequency||30,a=i.amplitude||.02,r=Math.sin(e*Math.PI),o=e*n*Math.PI*2,l=.6*Math.sin(o)+.3*Math.sin(1.7*o)+.1*Math.sin(2.3*o),h=.5*Math.cos(1.1*o)+.3*Math.cos(1.9*o)+.2*Math.cos(2.7*o);return{position:[l*a*s*r,h*a*s*r,(.4*Math.sin(.9*o+1)+.4*Math.sin(1.5*o+2))*a*.5*s*r],rotation:[.02*h*s*r,0,.02*l*s*r],scale:1+.01*Math.abs(l)*s*r,glowIntensity:1+.1*Math.abs(l)*r}}}},oi={name:"heartbeat",emoji:"๐",type:"effect",description:"Rhythmic double-pump heartbeat (lub-dub)",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},lubStrength:.8,dubStrength:1,lubDubGap:.15,strength:1,particleMotion:{type:"heartbeat",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",amplitudeSync:{onBeat:1.2,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=this._calculatePulse(t,r),h=e.x-n,c=e.y-a,u=Math.sqrt(h*h+c*c)||1,d=10*l*o;e.x+=h/u*d,e.y+=c/u*d},_calculatePulse(e,t){const i=t.lubDubGap||.15,s=t.lubStrength||.8,n=t.dubStrength||1;let a=0;const r=Math.abs(e-.1);r<.08&&(a=Math.cos(r/.08*Math.PI*.5)*s);const o=.1+i+.05,l=Math.abs(e-o);if(l<.1){const e=Math.cos(l/.1*Math.PI*.5)*n;a=Math.max(a,e)}return a},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.lubDubGap||.15,a=i.lubStrength||.8,r=i.dubStrength||1;let o=0;const l=Math.abs(e-.1);l<.08&&(o=Math.cos(l/.08*Math.PI*.5)*a);const h=.1+n+.05,c=Math.abs(e-h);if(c<.1){const e=Math.cos(c/.1*Math.PI*.5)*r;o=Math.max(o,e)}return{position:[0,0,.03*o*s],rotation:[0,0,0],scale:1+.15*o*s,glowIntensity:1+.5*o*s,glowBoost:.8*o*s}}}},li={name:"snap",emoji:"โก",type:"effect",description:"Quick elastic snap with overshoot and settle",config:{duration:500,musicalDuration:{musical:!0,beats:1},snapDistance:.1,overshoot:1.3,bounces:2,strength:1,particleMotion:{type:"snap",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=100*(r.snapDistance||.1),h=r.overshoot||1.3,c=this._calculateSnap(t,h,r.bounces||2),u=n-e.x,d=a-e.y,g=Math.sqrt(u*u+d*d)||1;e.x+=u/g*c*l*o*.1,e.y+=d/g*c*l*o*.1},_calculateSnap(e,t,i){if(e<.2){const i=e/.2;return(1-Math.pow(1-i,3))*t}{const s=(e-.2)/.8,n=Math.exp(4*-s);return 1+(t-1)*Math.cos(s*Math.PI*i*2)*n}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.snapDistance||.1,a=i.overshoot||1.3,r=i.bounces||2;let o;if(e<.2){const t=e/.2;o=(1-Math.pow(1-t,3))*a}else{const t=(e-.2)/.8,i=Math.exp(4*-t);o=1+(a-1)*Math.cos(t*Math.PI*r*2)*i}return{position:[0,0,(o-1)*n*s],rotation:[0,0,.1*(o-1)*s],scale:1+.15*(o-1),glowIntensity:1+.5*Math.abs(o-1),glowBoost:e<.3?(.3-e)/.3*.4:0}}}},hi={name:"elasticBounce",emoji:"๐",type:"effect",description:"Drop and bounce with elastic oscillation",config:{duration:1200,musicalDuration:{musical:!0,beats:3},dropHeight:.15,bounceCount:3,elasticity:.6,strength:1,particleMotion:{type:"elasticBounce",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",amplitudeSync:{onBeat:1.3,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=200*(r.dropHeight||.15),h=r.bounceCount||3,c=r.elasticity||.6,u=this._calculateBounce(t,l,h,c);e.y+=u*o;const d=.3*Math.max(0,-u/l);e.scaleY=1-d*o,e.scaleX=1+.5*d*o},_calculateBounce(e,t,i,s){let n=t,a=0,r=0,o=.3;for(;r<i&&a<1;){const t=o*Math.pow(s,.5*r);if(e<a+t){const i=(e-a)/t;return 4*i*(1-i)*-n}a+=t,n*=s,r++,o*=s}return 0},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.dropHeight||.15,a=i.bounceCount||3,r=i.elasticity||.6;let o=n,l=0,h=0,c=.3,u=0,d=!1;for(;h<a&&l<1;){const t=c*Math.pow(r,.5*h);if(e<l+t){const i=(e-l)/t;u=o*(4*i*(1-i))*s,d=i>.45&&i<.55;break}l+=t,o*=r,h++,c*=r}let g=1,m=1;if(d){const e=.15*s*Math.pow(r,h);g=1+e,m=1-e}return{position:[0,u,0],rotation:[0,0,0],scale:(g+m)/2,glowIntensity:1+(d?.3:0)}}}},ci={name:"hold",emoji:"โธ๏ธ",type:"override",description:"Hold particles in current position",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},holdStrength:.95,allowDrift:!1,strength:1},rhythm:{enabled:!0,syncMode:"rest",holdSync:{onRest:.98,onSound:.8,curve:"immediate"},durationSync:{mode:"rests",minBeats:.5,maxBeats:8,sustain:!0},pauseResponse:{enabled:!0,multiplier:1.5,type:"strength"},patternOverrides:{classical:{holdSync:{onRest:.99,onSound:.75,curve:"dramatic"},pauseResponse:{multiplier:2}},minimal:{holdSync:{onRest:.95,onSound:.85},durationSync:{minBeats:2,maxBeats:16}},jazz:{holdSync:{onRest:.9,onSound:.7},allowDrift:!0},electronic:{holdSync:{onRest:.99,onSound:.6,curve:"digital"},pauseResponse:{multiplier:1.2}}},dynamics:{forte:{holdSync:{onRest:{multiplier:1.02},onSound:{multiplier:.9}},pauseResponse:{multiplier:2.2}},piano:{holdSync:{onRest:{multiplier:.97},onSound:{multiplier:.85}},pauseResponse:{multiplier:1.3}}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.hold={holdX:e.x,holdY:e.y,originalVx:e.vx,originalVy:e.vy}},apply(e,t,i,s,n,a){e.gestureData?.hold||this.initialize(e);const r=e.gestureData.hold,o=i.holdStrength||this.config.holdStrength;if(i.allowDrift?(e.vx*=o,e.vy*=o):(e.x+=(r.holdX-e.x)*(1-o),e.y+=(r.holdY-e.y)*(1-o),e.vx=0,e.vy=0),t>.9){const i=10*(t-.9);e.vx=e.vx*(1-i)+r.originalVx*i,e.vy=e.vy*(1-i)+r.originalVy*i}},cleanup(e){if(e.gestureData?.hold){const t=e.gestureData.hold;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.hold}},"3d":{evaluate(e,t){let i=0,s=1;if(e<.15){const t=e/.15;i=t*t*(3-2*t),s=1-.2*i}else if(e<.85)i=1,s=.8;else{const t=(e-.85)/.15;i=1-t*t*(3-2*t),s=.8+.2*t}return i*=(t.config||this.config||{}).strength||1,{position:[0,0,0],rotation:[0,0,0],scale:1,glowIntensity:s,freezeRotation:i,freezeWobble:i,freezeGroove:i,freezeParticles:i}}}},ui={name:"fade",emoji:"๐ป",type:"blending",description:"Fade particle opacity",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},fadeIn:!0,fadeOut:!0,minOpacity:0,maxOpacity:1},rhythm:{enabled:!0,syncMode:"dynamic",durationSync:{mode:"bars",bars:1},opacitySync:{onBeat:.9,offBeat:.3,subdivision:"eighth",curve:"exponential"},fadePhaseSync:{verse:{fadeIn:!0,fadeOut:!1},chorus:{fadeIn:!1,fadeOut:!1},bridge:{fadeIn:!0,fadeOut:!0},outro:{fadeIn:!1,fadeOut:!0}},pulseSync:{enabled:!0,frequency:"quarter",intensity:.2,onAccent:.4},dynamics:{forte:{minOpacity:.5,maxOpacity:1},piano:{minOpacity:0,maxOpacity:.4}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.fade={baseOpacity:e.opacity||e.life||1}},apply(e,t,i,s,n,a){e.gestureData?.fade||this.initialize(e);const r=e.gestureData.fade,o={...this.config,...i};let l;l=o.fadeIn&&!o.fadeOut?o.minOpacity+(o.maxOpacity-o.minOpacity)*t:o.fadeOut&&!o.fadeIn?o.maxOpacity-(o.maxOpacity-o.minOpacity)*t:t<.5?o.minOpacity+(o.maxOpacity-o.minOpacity)*(2*t):o.maxOpacity-(o.maxOpacity-o.minOpacity)*(2*(t-.5)),e.opacity=r.baseOpacity*l,void 0!==e.life&&(e.life=e.opacity)},cleanup(e){e.gestureData?.fade&&(e.opacity=e.gestureData.fade.baseOpacity,void 0!==e.life&&(e.life=e.opacity),delete e.gestureData.fade)},"3d":{evaluate(e,t){const i={...this?.config||{},...t},s=i.fadeIn??!0,n=i.fadeOut??!0;let a;a=s&&!n?e:n&&!s?1-e:e<.5?1-e/.5:(e-.5)/.5;const r=a*a*(3-2*a);return{position:[0,0,0],rotation:[0,0,0],scale:.01+.99*r,glowIntensity:r,glowBoost:0}}}},di={name:"settle",emoji:"๐",type:"blending",description:"Gradually settle particles to rest",config:{damping:.02,threshold:.01},rhythm:{enabled:!0,syncMode:"resolution",dampingSync:{onResolution:.035,onTension:.015,curve:"gradual"},thresholdSync:{mode:"dynamics",forte:.02,piano:.005,curve:"exponential"},durationSync:{mode:"phrase",minBeats:2,maxBeats:12,sustain:!0},cadenceResponse:{enabled:!0,multiplier:1.6,type:"damping"},patternOverrides:{ambient:{dampingSync:{onResolution:.025,onTension:.008,curve:"atmospheric"},durationSync:{minBeats:8,maxBeats:32}},jazz:{dampingSync:{onResolution:.04,onTension:.02},cadenceResponse:{multiplier:1.8}},classical:{dampingSync:{onResolution:.045,onTension:.012,curve:"expressive"},cadenceResponse:{multiplier:2}},minimalist:{dampingSync:{onResolution:.02,onTension:.005},durationSync:{minBeats:16,maxBeats:64}}},dynamics:{forte:{dampingSync:{onResolution:{multiplier:1.4},onTension:{multiplier:.8}},thresholdSync:{multiplier:2},cadenceResponse:{multiplier:2.2}},piano:{dampingSync:{onResolution:{multiplier:.7},onTension:{multiplier:1.2}},thresholdSync:{multiplier:.5},cadenceResponse:{multiplier:1.3}}}},apply(e,t,i,s,n,a){const r=i.damping||this.config.damping,o=i.threshold||this.config.threshold;e.vx*=Math.max(0,1-r*s*60),e.vy*=Math.max(0,1-r*s*60),Math.abs(e.vx)<o&&(e.vx=0),Math.abs(e.vy)<o&&(e.vy=0)},"3d":{evaluate(e,t){const i=1-Math.pow(1-e,2),s=.01*(1-i);return{position:[Math.sin(e*Math.PI*2)*s,Math.cos(e*Math.PI*3)*s*.5,0],rotation:[0,0,0],scale:1-.03*i,glowIntensity:1-.15*i}}}},gi={name:"peek",emoji:"๐",type:"effect",description:"Quick peek and hide motion",config:{peekDistance:40,peekSpeed:.15,holdDuration:200,hideSpeed:.25,stagger:!0,duration:1500},rhythm:{enabled:!0,syncMode:"accent",distanceSync:{onAccent:60,offAccent:25,curve:"quick"},speedSync:{mode:"tempo",fast:.25,slow:.1,hideMultiplier:1.8},durationSync:{mode:"subdivision",beats:.25,staggerBeats:.125,sustain:!1},syncopationResponse:{enabled:!0,multiplier:1.8,type:"distance"},patternOverrides:{funk:{distanceSync:{onAccent:70,offAccent:35,curve:"funky"},syncopationResponse:{multiplier:2.2}},latin:{speedSync:{fast:.3,slow:.12},durationSync:{beats:.5,staggerBeats:.25}},breakbeat:{distanceSync:{onAccent:55,offAccent:40},syncopationResponse:{multiplier:2.5}},classical:{distanceSync:{onAccent:45,offAccent:20,curve:"elegant"},speedSync:{fast:.18,slow:.08}}},dynamics:{forte:{distanceSync:{onAccent:{multiplier:1.6},offAccent:{multiplier:1.3}},speedSync:{multiplier:1.4},syncopationResponse:{multiplier:2.8}},piano:{distanceSync:{onAccent:{multiplier:.6},offAccent:{multiplier:.4}},speedSync:{multiplier:.7},syncopationResponse:{multiplier:1.2}}}},apply(e,t,i,s,n,a){if(e.gestureData||(e.gestureData={}),!e.gestureData.peek){const t=e.x-n,i=e.y-a,s=Math.atan2(i,t),r=Math.sqrt(t*t+i*i);e.gestureData.peek={originalX:e.x,originalY:e.y,peekAngle:s,originalDistance:r,staggerDelay:this.config.stagger?.3*Math.random():0,phase:"waiting",phaseTimer:0,peekOffset:{x:0,y:0}}}const r=e.gestureData.peek,{config:o}=this,l=Math.max(0,Math.min(1,(t-r.staggerDelay)/(1-r.staggerDelay)));0===l?r.phase="waiting":l<.3?r.phase="peeking":l<.6?r.phase="holding":l<1&&(r.phase="hiding");let h=0;switch(r.phase){case"peeking":{const e=l/.3;h=this.easeOutCubic(e)*o.peekDistance;break}case"holding":h=o.peekDistance,Math.random()<.1&&(r.peekOffset.x+=2*(Math.random()-.5),r.peekOffset.y+=2*(Math.random()-.5));break;case"hiding":{const e=(l-.6)/.4;h=(1-this.easeInCubic(e))*o.peekDistance;break}}if("waiting"!==r.phase){const t=Math.cos(r.peekAngle)*h,i=Math.sin(r.peekAngle)*h;r.peekOffset.x+=(t-r.peekOffset.x)*o.peekSpeed,r.peekOffset.y+=(i-r.peekOffset.y)*o.peekSpeed,e.x=r.originalX+r.peekOffset.x,e.y=r.originalY+r.peekOffset.y}void 0!==e.alpha&&("peeking"===r.phase||"holding"===r.phase?e.alpha=.7+.3*Math.random():e.alpha=1)},easeOutCubic:e=>1-Math.pow(1-e,3),easeInCubic:e=>e*e*e,cleanup(e){e.gestureData?.peek&&(e.x=e.gestureData.peek.originalX,e.y=e.gestureData.peek.originalY,void 0!==e.alpha&&(e.alpha=1),delete e.gestureData.peek)},"3d":{evaluate(e,t){const i=.01*({...this.config,...t}.peekDistance||40);let s=0,n=1;if(e<.3){const t=e/.3;s=(1-Math.pow(1-t,3))*i}else if(e<.6)s=i,n=.7+.3*Math.random();else{const t=(e-.6)/.4;s=(1-Math.pow(t,3))*i}return{position:[s,0,0],rotation:[0,0,0],scale:1,glowIntensity:n}}}},mi={name:"directional",emoji:"โก๏ธ",type:"blending",description:"Move particles in a specific direction",config:{angle:0,returnToOrigin:!1,strength:1},rhythm:{enabled:!0,syncMode:"flow",angleSync:{verse:0,chorus:90,bridge:180,outro:270,transition:"smooth"},strengthSync:{onBeat:1.8,offBeat:.6,curve:"wave"},returnSync:{enabled:!0,onSectionChange:!0,duration:"transition",strength:1.2},accentResponse:{enabled:!0,multiplier:2,type:"strength"},patternOverrides:{march:{angleSync:{verse:0,chorus:0},strengthSync:{onBeat:2.5,offBeat:1}},waltz:{angleSync:{verse:45,chorus:135,bridge:225,outro:315,transition:"circular"}},swing:{strengthSync:{onBeat:1.6,offBeat:1.4,swing:!0}},electronic:{angleSync:{transition:"instant"},strengthSync:{onBeat:2.2,offBeat:.4,curve:"sharp"}}},dynamics:{forte:{strengthSync:{onBeat:{multiplier:1.6},offBeat:{multiplier:1.2}},angleSync:{transition:"sharp"},accentResponse:{multiplier:2.5}},piano:{strengthSync:{onBeat:{multiplier:.7},offBeat:{multiplier:.8}},angleSync:{transition:"gradual"},accentResponse:{multiplier:1.4}}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.directional={initialX:e.x,initialY:e.y}},apply(e,t,i,s,n,a){e.gestureData?.directional||this.initialize(e);const r=(i.angle||this.config.angle)*Math.PI/180,o=i.strength||this.config.strength;if(e.vx+=Math.cos(r)*o*.3*s,e.vy+=Math.sin(r)*o*.3*s,i.returnToOrigin&&t>.5){const i=2*(t-.5),n=e.gestureData.directional,a=n.initialX-e.x,r=n.initialY-e.y;e.vx+=a*i*.02*s,e.vy+=r*i*.02*s}},"3d":{evaluate(e,t){const i={...this.config,...t},s=(i.angle||0)*Math.PI/180,n=t.strength||1,a=i.returnToOrigin?e<.5?2*e:2*(1-e):e;return{position:[Math.cos(s)*a*.4*n,Math.sin(s)*a*.4*n,0],rotation:[0,0,0],scale:1,glowIntensity:1}}}};function pi(e){if(!["forward","back","left","right","up","down","attract","repel"].includes(e))throw new Error(`Invalid magnetic direction: ${e}`);return{name:`magnetic${D(e)}`,emoji:{forward:"๐งฒ",back:"๐งฒ",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ",attract:"๐งฒ",repel:"๐ฅ"}[e],type:"effect",description:{forward:"Magnetic pull toward camera",back:"Magnetic push away from camera",left:"Magnetic pull leftward",right:"Magnetic pull rightward",up:"Magnetic pull upward",down:"Magnetic pull downward",attract:"Magnetic attraction to center",repel:"Magnetic repulsion from center"}[e],config:{duration:1200,musicalDuration:{musical:!0,beats:3},direction:e,pullStrength:1,returnToOrigin:!0,strength:1,particleMotion:{type:"magnetic",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",strengthSync:{onBeat:1.5,offBeat:.7}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.magnetic={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.magnetic?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=r.pullStrength||1,h=!1!==r.returnToOrigin,c=e.gestureData.magnetic,u=r.direction||"attract";let d,g,m;switch(d=h?Math.sin(t*Math.PI):Math.min(1,2*t),u){case"left":g=c.originalX-100,m=c.originalY;break;case"right":g=c.originalX+100,m=c.originalY;break;case"up":g=c.originalX,m=c.originalY-100;break;case"down":g=c.originalX,m=c.originalY+100;break;case"repel":{const e=c.originalX-n,t=c.originalY-a,i=Math.sqrt(e*e+t*t)||1;g=c.originalX+e/i*100,m=c.originalY+t/i*100;break}default:g=n,m=a}const p=(g-c.originalX)*d*l*o*.5,f=(m-c.originalY)*d*l*o*.5;e.x=c.originalX+p,e.y=c.originalY+f},cleanup(e){if(e.gestureData?.magnetic){const t=e.gestureData.magnetic;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.magnetic}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"attract";let a;a=!1!==i.returnToOrigin?Math.sin(e*Math.PI):Math.min(1,2*e);let r=0,o=0,l=0,h=1;const c=.15*a*s;switch(n){case"forward":l=c,h=1+.1*a*s;break;case"back":l=-c,h=1-.08*a*s;break;case"left":r=-c;break;case"right":r=c;break;case"up":o=c;break;case"down":o=-c;break;case"attract":l=c,h=1-.1*a*s;break;case"repel":l=-c,h=1+.1*a*s}const u=1+.4*a,d=.3*a;return{cameraRelativePosition:[r+(a>.5?.01*Math.sin(e*Math.PI*20)*(a-.5)*2:0),o,l],rotation:[0,0,0],scale:h,glowIntensity:u,glowBoost:d}}}}}const fi={name:"sparkle",emoji:"โจ",type:"blending",description:"Bright twinkling sparkle bursts",config:{duration:800,musicalDuration:{musical:!0,beats:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:2},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i=t?.strength||1,s=Math.pow(Math.max(0,Math.sin(e*Math.PI*6)),3),n=Math.pow(Math.max(0,Math.sin(e*Math.PI*8+1)),3),a=Math.pow(Math.max(0,Math.sin(e*Math.PI*10+2)),3),r=Math.max(s,n,a)*Math.sin(e*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1+.08*r*i,glowIntensity:1+.5*r*i,glowBoost:2*r*i}}}},yi={name:"shimmer",emoji:"๐",type:"particle",description:"Shimmer effect with sparkling particles",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},particleMotion:"radiant"},rhythm:{enabled:!0,syncType:"beat",durationSync:{mode:"bars",bars:1},intensity:.8},override:(e,t,i)=>(e.shimmerEffect=!0,e.shimmerProgress=t,!0),blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i=t?.strength||1,s=(.4*Math.sin(e*Math.PI*4)+.35*Math.sin(e*Math.PI*6+.5)+.25*Math.sin(e*Math.PI*10+1)+1)/2;return{position:[0,0,0],rotation:[0,0,0],scale:1+.05*s*i,glowIntensity:1+.3*s*i,glowBoost:1*s*i}}}},bi=((e,t="โจ")=>({name:e,emoji:t,type:"blending",description:`${e} animation`,config:{duration:1e3,musicalDuration:{musical:!0,beats:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:2},interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",maxQueue:3},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1}))("groove","๐ต"),vi={},Mi=[],wi=[],Si=[];function xi(e,t){vi[e.name]=e,t.push(e.name)}function Ci(e,t,i){Object.defineProperty(vi,e,{configurable:!0,enumerable:!0,get(){const i=t();return Object.defineProperty(vi,e,{configurable:!0,enumerable:!0,writable:!0,value:i}),i}}),i.push(e)}[le,P,$,Ge,j,H,T,E,G,fi,yi,W,bi,De,F,He,je,se,ae,re,oe,ne,Y,X,N,Q,J,K,L,q,Oe,Le,I,R,B,z,Ie,Re,Be,ze,x,C,k,dt,gt,ct,ut,te,he,ue,de,ge,me,ie,Z,ee].forEach(e=>xi(e,Mi)),[xe,Pe,Te,pe,ye,be,ve,Tt,nt,We,Ve,Ye,Xe,Ne,St,Ee,Ae,$e,we,Je,qe,tt,it,st,et,Ze,pt,ft,yt,bt,vt,Mt,wt,rt,ot,lt,ht,at].forEach(e=>xi(e,wi)),Ci("lungeForward",()=>Se("forward"),wi),Ci("lungeBack",()=>Se("back"),wi),Ci("lungeLeft",()=>Se("left"),wi),Ci("lungeRight",()=>Se("right"),wi),Ci("lungeUp",()=>Se("up"),wi),Ci("lungeDown",()=>Se("down"),wi),Ci("recoilBack",()=>Ke("back"),wi),Ci("recoilForward",()=>Ke("forward"),wi),Ci("recoilLeft",()=>Ke("left"),wi),Ci("recoilRight",()=>Ke("right"),wi),Ci("recoilUp",()=>Ke("up"),wi),Ci("recoilDown",()=>Ke("down"),wi),Ci("oofLeft",()=>Qe("left"),wi),Ci("oofRight",()=>Qe("right"),wi),Ci("oofFront",()=>Qe("front"),wi),Ci("oofBack",()=>Qe("back"),wi),Ci("oofUp",()=>Qe("up"),wi),Ci("oofDown",()=>Qe("down"),wi),Ci("shatter",()=>Ct("default"),wi),Ci("shatterExplosive",()=>Ct("explosive"),wi),Ci("shatterCrumble",()=>Ct("crumble"),wi),Ci("shatterReform",()=>Ct("reform"),wi),Ci("shatterPunchLeft",()=>Ct("punchLeft"),wi),Ci("shatterPunchRight",()=>Ct("punchRight"),wi),Ci("shatterPunchFront",()=>Ct("punchFront"),wi),Ci("shatterSuspend",()=>Ct("suspend"),wi),Ci("shatterImplode",()=>Ct("implode"),wi),Ci("shatterGravity",()=>Ct("gravity"),wi),Ci("shatterOrbit",()=>Ct("orbit"),wi),Ci("dissolveUp",()=>Pt("up"),wi),Ci("dissolveDown",()=>Pt("down"),wi),Ci("dissolveLeft",()=>Pt("left"),wi),Ci("dissolveRight",()=>Pt("right"),wi),Ci("dissolveAway",()=>Pt("away"),wi),Ci("dissolveToward",()=>Pt("toward"),wi),Ci("rushForward",()=>Me("forward"),wi),Ci("rushBack",()=>Me("back"),wi),Ci("rushLeft",()=>Me("left"),wi),Ci("rushRight",()=>Me("right"),wi),Ci("rushUp",()=>Me("up"),wi),Ci("rushDown",()=>Me("down"),wi),[ti,At,_t,It,Rt,Bt,ai,Xt,mi,di,ui,ci,ii,si,gi,Et,ri,oi,Ht,jt,Ot,Lt,qt,Gt,Qt,Jt,Kt,Zt,ei,hi,Wt,Ut,Vt,Yt,ni,li,zt].forEach(e=>xi(e,Si)),Ci("magneticForward",()=>pi("forward"),Si),Ci("magneticBack",()=>pi("back"),Si),Ci("magneticLeft",()=>pi("left"),Si),Ci("magneticRight",()=>pi("right"),Si),Ci("magneticUp",()=>pi("up"),Si),Ci("magneticDown",()=>pi("down"),Si),Ci("magneticAttract",()=>pi("attract"),Si),Ci("magneticRepel",()=>pi("repel"),Si);const ki={blending:Mi,override:wi,effect:Si},Pi={idle:["breathe","expand","contract","pulse","sway","float","floatUp","floatDown","floatLeft","floatRight","bob","lean","leanLeft","leanRight","jitter","twitch","vibrate","shake","wiggle"],dance:["stepLeft","stepRight","stepUp","stepDown","slideLeft","slideRight","runningman","charleston","hula","twist","pop","flare","swell","swagger","dip","bounce","orbit","orbitLeft","orbitRight","orbitUp","orbitDown","sparkle","shimmer","groove"],actions:["jump","jumpDown","jumpLeft","jumpRight","rushForward","rushBack","rushLeft","rushRight","rushUp","rushDown","lunge","lungeForward","lungeBack","lungeLeft","lungeRight","lungeUp","lungeDown","spin","spinLeft","spinRight","flip","backflip","point","pointUp","pointDown","pointLeft","pointRight","kickLeft","kickRight","bow","nod","reach","headBob","crouch","tilt","tiltUp","tiltDown","tiltLeft","tiltRight"],reactions:["oofLeft","oofRight","oofFront","oofBack","oofUp","oofDown","recoil","recoilBack","recoilForward","recoilLeft","recoilRight","recoilUp","recoilDown","knockdown","knockout","inflate","deflate","squash","stretch","pancake","crackFront","crackBack","crackLeft","crackRight","crackUp","crackDown","crackHeal","rage","fury","battlecry","charge","wobble","teeter","rock","pendulum"],destruction:["shatter","shatterMesh","shatterExplosive","shatterCrumble","shatterReform","shatterPunchLeft","shatterPunchRight","shatterPunchFront","shatterSuspend","shatterImplode","shatterGravity","shatterOrbit","dissolveUp","dissolveDown","dissolveLeft","dissolveRight","dissolveAway","dissolveToward","splash","drench","soak","flow","tide","liquefy","poolWater","vortexWater","watercrown","waterdance","waterdrill","waterhelix","watermeditation","waterpillar","waterflourish","waterbarrage","waterimpact","watercrush","watertwirl","watershield","smokebomb","vanish","materialize","phoenix","burn","scorch","combust","flameVortex","firedance","fireflourish","firecrown","firemeditation","firedrill","firepillar","firehelix","firebarrage","fireimpact","fireblast","radiate","blaze","firetwirl","fireshield","puff","billow","fume","shroud","hazeSmoke","chokeSmoke","iceFreeze","shatterIce","shock","overload","glitch","crackle","chargeUp","electricAuraEffect","staticDischarge","electriccrown","electricdance","electrichelix","electricpillar","electricdrill","electricflourish","electricvortex","electricbarrage","electricimpact","electricblast","electricsurge","electriczap","electricmeditation","electrictwirl","electricshield","zap","drain","hollow","corrupt","consume","singularity","voidcrown","voiddance","voidhelix","voidpillar","voiddrill","voidflourish","voidvortex","voidbarrage","voidimpact","voidmeditation","voidtwirl","voidshield","iceCrown","iceDance","icePillar","iceHelix","iceMeditation","iceVortex","iceSplash","iceEncase","iceDrill","iceFlourish","iceBarrage","iceImpact","icemist","iceshiver","icetwirl","iceshield","lightBlind","lightPurify","lightCleanse","lightRadiate","lightGlow","lightBeacon","lightAscend","lightIlluminate","lightDissolve","lightMeditation","lightcrown","lightdance","lighthelix","lightpillar","lightdrill","lightflourish","lightvortex","lightbarrage","lightimpact","lightblast","lightsurge","lightmeditation","lighttwirl","lightshield","poisonInfect","poisonSicken","poisonOoze","poisonSeep","poisonToxic","poisonCorrode","poisonMelt","poisonDecay","poisonDissolve","earthPetrify","earthBurden","earthRumble","earthQuake","earthMeditation","earthEncase","earthCrumble","earthShatter","earthErode","earthcrown","earthdance","earthhelix","earthpillar","earthdrill","earthflourish","earthvortex","earthbarrage","earthimpact","earthblast","earthsurge","earthmeditation","earthtwirl","earthshield","morph"],atmosphere:["rain","drift","driftUp","driftDown","driftLeft","driftRight","vortex","cascadeUp","cascadeDown","cascadeLeft","cascadeRight","confetti","fizz","swarmUp","swarmDown","swarmLeft","swarmRight","burst","burstUp","burstDown","burstLeft","burstRight","ripple","wave","flash","glow","bloom","flicker","shiver","heartbeat","snap","elasticBounce","hold","fade","settle","peek","directional","magneticForward","magneticBack","magneticLeft","magneticRight","magneticUp","magneticDown","magneticAttract","magneticRepel"]},Ti={};function Ei(e){return Ti[e]||"atmosphere"}function Ai(e){if(vi[e])return vi[e];return S.getPluginGesture(e)||null}function Di(e){const t=Ai(e);return!!t&&"blending"===t.type}function _i(e){const t=Ai(e);return!!t&&"override"===t.type}function Ii(e,t,i,s,n,a,r){const o=Ai(t);return!!o&&(o.apply&&o.apply(e,i,s,n,a,r),i>=1&&o.cleanup&&o.cleanup(e),!0)}function Ri(){const e=[];return Object.values(vi).forEach(t=>{e.push({name:t.name,emoji:t.emoji||"๐ญ",type:t.type,category:Ti[t.name]||"atmosphere",description:t.description||"No description",source:"core",usesShatter:t.usesShatter||!1})}),S.getAllPluginGestures().forEach(t=>{const i=S.getPluginGesture(t);e.push({name:i.name,emoji:i.emoji||"๐",type:i.type,category:i.category||"effect",description:i.description||"Plugin gesture",source:"plugin"})}),e}function Bi(e){return vi[e]||null}function zi(){return Object.keys(vi).filter(e=>{const t=Object.getOwnPropertyDescriptor(vi,e);return t&&"function"==typeof t.get})}Object.entries(Pi).forEach(([e,t])=>{t.forEach(t=>{Ti[t]=e})});var Fi={GESTURE_REGISTRY:vi,GESTURE_TYPES:ki,GESTURE_CATEGORIES:Pi,GESTURE_TO_CATEGORY:Ti,getGesture:Ai,getGestureCategory:Ei,isBlendingGesture:Di,isOverrideGesture:_i,applyGesture:Ii,listGestures:Ri,pluginAdapter:S},Oi=Object.freeze({__proto__:null,GESTURE_CATEGORIES:Pi,GESTURE_REGISTRY:vi,GESTURE_TO_CATEGORY:Ti,GESTURE_TYPES:ki,applyGesture:Ii,default:Fi,getGesture:Ai,getGestureCategory:Ei,getLazyGestureNames:zi,isBlendingGesture:Di,isOverrideGesture:_i,listGestures:Ri,pluginAdapter:S,resolveGesture:Bi,warmUpGestures:function({onBatch:e,onComplete:t}={}){const i=Object.keys(vi);e&&e(i.map(e=>({name:e,category:Ti[e]||"atmosphere",source:"core"})));try{const t=[];S.getAllPluginGestures().forEach(e=>{const i=S.getPluginGesture(e);t.push({name:i.name,emoji:i.emoji||"๐",type:i.type,category:i.category||"effect",description:i.description||"Plugin gesture",source:"plugin"})}),t.length&&e&&e(t)}catch{}return t&&t(),zi().map(e=>()=>Bi(e))}});function Li(e){if(!e||0===e.length)return"#FFFFFF";let t=0,i=0;const s=[];for(const n of e)"string"==typeof n?(s.push({color:n,weight:null}),i++):n&&"object"==typeof n&&n.color&&(s.push({color:n.color,weight:n.weight||null}),n.weight?t+=n.weight:i++);const n=Math.max(0,100-t),a=i>0?n/i:0,r=[];let o=0;for(const e of s)o+=null!==e.weight?e.weight:a,r.push({color:e.color,threshold:o});const l=Math.random()*o;for(const e of r)if(l<=e.threshold)return e.color;return s[s.length-1].color}var qi={name:"ambient",emoji:"โ๏ธ",description:"Gentle upward drift like smoke",initialize:function(e){e.vx=0,e.vy=-.04-.02*Math.random(),e.lifeDecay=.002,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={upwardSpeed:5e-4,waviness:0,friction:.998}},update:function(e,t,i,s){const n=e.behaviorData;e.vy*=Math.pow(n.friction,t),e.vy-=n.upwardSpeed*t,e.vx=0}};const Gi=2*Math.PI;var Hi={name:"orbiting",emoji:"๐",description:"Romantic firefly dance around the orb",initialize:function(e){e.lifeDecay=.001+.002*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.isSparkle="#FFE4E1"===e.color||"#FFCCCB"===e.color||"#FFC0CB"===e.color;const t=40*(e.scaleFactor||1)*(1.3+.9*Math.random());e.blinkPhase=Math.random()*Gi,e.blinkSpeed=.3+1.2*Math.random(),e.blinkIntensity=.6+.4*Math.random(),e.fadePhase=Math.random()*Gi,e.fadeSpeed=.1+.3*Math.random(),e.minOpacity=.2+.2*Math.random(),e.maxOpacity=.8+.2*Math.random(),e.isSparkle&&(e.blinkSpeed*=2,e.blinkIntensity=1,e.minOpacity=0,e.maxOpacity=1),e.behaviorData={angle:Math.random()*Gi,radius:t,baseRadius:t,angularVelocity:8e-4+.0017*Math.random(),swayAmount:3+7*Math.random(),swaySpeed:.2+.5*Math.random(),floatOffset:Math.random()*Gi,floatSpeed:.3+.7*Math.random(),floatAmount:2+6*Math.random(),twinklePhase:Math.random()*Gi,twinkleSpeed:2+3*Math.random()}},update:function(e,t,i,s){const n=e.behaviorData;n.angle+=n.angularVelocity*t;const a=Math.sin(n.angle*n.swaySpeed)*n.swayAmount,r=6*Math.sin(1.5*n.angle),o=(n.radius||n.baseRadius)+r+.2*a,l=i+Math.cos(n.angle)*o,h=s+Math.sin(n.angle)*o;n.floatOffset+=n.floatSpeed*t*.001;const c=Math.sin(n.floatOffset)*n.floatAmount;e.vx=.1*(l-e.x),e.vy=.1*(h+c-e.y),e.fadePhase+=e.fadeSpeed*t*.001;const u=.5*Math.sin(e.fadePhase)+.5,d=e.minOpacity+(e.maxOpacity-e.minOpacity)*u;let g;e.blinkPhase+=e.blinkSpeed*t*.002,e.isSparkle?(n.twinklePhase+=n.twinkleSpeed*t*.001,g=.7*Math.pow(Math.sin(n.twinklePhase),16)+.2*Math.sin(5*e.blinkPhase)+.1):g=.4*Math.sin(e.blinkPhase)+.3*Math.sin(3*e.blinkPhase)+.2*Math.sin(7*e.blinkPhase)+.1*Math.sin(11*e.blinkPhase);const m=.5*(g+1),p=.2+m*e.blinkIntensity*.8;e.opacity=e.baseOpacity*d*p,e.isSparkle?e.size=e.baseSize*(.5+1*m):e.size=e.baseSize*(.8+.3*m),e.isSparkle&&(e.tempColor=m>.85?"#FFFFFF":e.color)}},ji={name:"rising",emoji:"๐",description:"Buoyant upward movement like balloons",initialize:function(e){e.vx=.02*(Math.random()-.5),e.vy=-.05-.03*Math.random(),e.lifeDecay=.002,e.baseOpacity=.7+.3*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={buoyancy:.001,driftAmount:.005}},update:function(e,t,i,s){const n=e.behaviorData;e.vy-=n.buoyancy*t,e.vx+=(Math.random()-.5)*n.driftAmount*t,e.vx*=Math.pow(.995,t),e.vy*=Math.pow(.998,t)}};function $i(e){e.fallingData||(e.fallingData={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),fallProgress:0}),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors));const t=Math.random(),i=Math.random(),s=t*Math.PI*2,n=2*i-1,a=Math.sqrt(1-n*n);e.behaviorData={fallSpeed:8,fallDistance:400,wobbleAmount:1.5,fallingDir:{x:a*Math.cos(s),y:n,z:a*Math.sin(s)},orbitDistanceRatio:.7+.4*Math.random()}}var Wi={name:"falling",emoji:"๐ง",description:"Heavy downward drift like tears",initialize:$i,update:function(e,t,i,s){const n=e.behaviorData;let a=e.fallingData;a||($i(e),a=e.fallingData),a.fallProgress+=.02*t;const r=Math.min(a.fallProgress,1),o=n.fallDistance*r;a.wobblePhase+=a.wobbleSpeed*t*.1;const l=Math.sin(a.wobblePhase)*n.wobbleAmount;if(e.x=a.originalX+l,e.y=a.originalY+o,e.vx=.3*l,e.vy=10*n.fallSpeed,r>.6){const t=(r-.6)/.4;e.opacity=a.originalOpacity*(1-t),void 0!==e.life&&(e.life=a.originalOpacity*(1-t))}}};const Ui=2e3,Vi=3,Yi=8,Xi=.7;var Ni={name:"popcorn",emoji:"๐ฟ",description:"Spontaneous popping with gravity and bounces",initialize:function(e){if(e.vx=.1*(Math.random()-.5),e.vy=.1*(Math.random()-.5),e.lifeDecay=.008+.012*Math.random(),e.emotionColors&&e.emotionColors.length>0)e.color=Li(e.emotionColors);else{const t=["#FFFFFF","#FFFACD","#FFF8DC","#FFFFE0","#FAFAD2"];e.color=Li(t)}e.size=Math.random()<.3?(8+4*Math.random())*e.scaleFactor*e.particleSizeMultiplier:(2+4*Math.random())*e.scaleFactor*e.particleSizeMultiplier,e.baseSize=e.size,e.hasGlow=Math.random()<.2,e.glowSizeMultiplier=e.hasGlow?1.2:0,e.behaviorData={popDelay:Math.random()*Ui,hasPopped:!1,popStrength:Vi+Math.random()*(Yi-Vi),gravity:.098,bounceDamping:Xi,bounceCount:0,maxBounces:2+Math.floor(2*Math.random()),spinRate:10*(Math.random()-.5),lifetime:0}},update:function(e,t,i,s){const n=e.behaviorData;if(n.lifetime+=16.67*t,!n.hasPopped&&n.lifetime>n.popDelay){n.hasPopped=!0;const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*n.popStrength*1.5,e.vy=Math.sin(t)*n.popStrength-.3,e.size=1.25*e.baseSize}if(n.hasPopped){e.vy+=n.gravity*t;const i=s+100*e.scaleFactor;e.y>i&&n.bounceCount<n.maxBounces&&(e.y=i,e.vy=-Math.abs(e.vy)*n.bounceDamping,e.vx*=.9,n.bounceCount++,e.size=e.baseSize*(1.5-.1*n.bounceCount)),n.bounceCount>=n.maxBounces&&(e.lifeDecay=.03+.02*Math.random(),e.size*=.95),Math.sqrt(e.vx*e.vx+e.vy*e.vy)<.5&&(e.lifeDecay*=1.5)}}},Qi={name:"burst",emoji:"๐ฅ",description:"Explosive expansion from center",initialize:function(e){const t="suspicion"===e.emotion,i="surprise"===e.emotion,s="glitch"===e.emotion,n=Math.random()*Gi,a=t?1+.8*Math.random():i?7+5*Math.random():s?2+1.5*Math.random():3.5+2.5*Math.random();e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a,e.lifeDecay=t?.01:i?.006+.008*Math.random():s?.012:.015,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),t&&(e.size=(6+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.opacity=1,e.baseOpacity=e.opacity),e.behaviorData={isSuspicion:t,isSurprise:i,isGlitch:s,age:0,fadeStart:t?.3:.2,glitchPhase:Math.random()*Math.PI*2,glitchIntensity:s?.3:0,glitchFrequency:s?.1:0}},update:function(e,t,i,s){const n=e.behaviorData;if(n.isSurprise)if(n.age+=.016*t,n.age<.15){const i=.98;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}else if(n.age<.25){const i=.85;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}else{const i=.99;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t),e.vx+=.01*(Math.random()-.5)*t,e.vy+=.01*(Math.random()-.5)*t}else{const i=n.isSuspicion?.99:n.isGlitch?.97:.95;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}if(n.isSuspicion){const i=.001*Date.now();e.vx+=.01*Math.sin(2*i+e.id)*t}if(n.isGlitch){n.age+=.016*t,n.glitchPhase+=n.glitchFrequency*t;const i=Math.sin(n.glitchPhase)*n.glitchIntensity*t,s=Math.cos(1.3*n.glitchPhase)*n.glitchIntensity*t;if(e.vx+=i,e.vy+=s,Math.random()<.02){const t=Math.random()*Math.PI*2,i=.5+.5*Math.random();e.vx+=Math.cos(t)*i,e.vy+=Math.sin(t)*i}}}},Ji={name:"aggressive",emoji:"โก",description:"Sharp, chaotic movement with violent bursts",initialize:function(e){const t=Math.random()*Gi,i=1.5+2*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.015,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={acceleration:.05,jitter:.3,speedDecay:.95}},update:function(e,t,i,s){const n=e.behaviorData;if(e.vx+=(Math.random()-.5)*n.jitter*t,e.vy+=(Math.random()-.5)*n.jitter*t,e.vx*=Math.pow(n.speedDecay,t),e.vy*=Math.pow(n.speedDecay,t),Math.random()<Math.min(.05*t,.5)){const t=Math.random()*Gi;e.vx+=Math.cos(t)*n.acceleration,e.vy+=Math.sin(t)*n.acceleration}}},Ki={name:"scattering",emoji:"๐จ",description:"Particles flee from center in panic",initialize:function(e){e.vx=0,e.vy=0,e.lifeDecay=.008,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={fleeSpeed:2,panicFactor:1.2,initialized:!1}},update:function(e,t,i,s){const n=e.behaviorData;if(!n.initialized){const t=e.x-i,a=e.y-s,r=Math.sqrt(t*t+a*a);if(r>0)e.vx=t/r*n.fleeSpeed,e.vy=a/r*n.fleeSpeed;else{const t=Math.random()*Gi;e.vx=Math.cos(t)*n.fleeSpeed,e.vy=Math.sin(t)*n.fleeSpeed}n.initialized=!0}const a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);o>0&&(e.vx+=a/o*n.panicFactor*.01*t,e.vy+=r/o*n.panicFactor*.01*t),e.vx+=.1*(Math.random()-.5)*t,e.vy+=.1*(Math.random()-.5)*t,e.vx*=Math.pow(.98,t),e.vy*=Math.pow(.98,t)}},Zi={name:"repelling",emoji:"๐ซ",description:"Particles pushed away from center, maintaining distance",initialize:function(e){e.vx=0,e.vy=0,e.lifeDecay=.01,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={repelStrength:.8,minDistance:50,initialized:!1}},update:function(e,t,i,s){const n=e.behaviorData,a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(!n.initialized||o<n.minDistance){if(o>0){const i=n.repelStrength/Math.max(o,5);e.vx+=a/o*i*t,e.vy+=r/o*i*t}n.initialized=!0}e.vx*=Math.pow(.99,t),e.vy*=Math.pow(.99,t)}},es={name:"connecting",emoji:"๐",description:"Chaotic movement with center attraction for social states",initialize:function(e){const t=Math.random()*Gi,i=2+5*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.012,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={attractionForce:.008,chaosFactor:1,friction:.95}},update:function(e,t,i,s){const n=e.behaviorData;e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t);const a=(i-e.x)*n.attractionForce,r=(s-e.y)*n.attractionForce,o=(Math.random()-.5)*n.chaosFactor,l=(Math.random()-.5)*n.chaosFactor;e.vx+=a+o,e.vy+=r+l}},ts={name:"resting",emoji:"๐ด",description:"Ultra-slow vertical drift for deep rest states",initialize:function(e){e.vx=0,e.vy=-.01,e.lifeDecay=.001,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={upwardSpeed:2e-5,friction:.999}},update:function(e,t,i,s){const n=e.behaviorData;e.vy*=Math.pow(n.friction,t),e.vy-=n.upwardSpeed*t,e.vx=0}},is={name:"radiant",emoji:"โ๏ธ",description:"Particles radiate outward like sunbeams",initialize:function(e){const t=Math.random()*Gi,i=.8+.4*Math.random();if(e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.006,e.emotionColors&&e.emotionColors.length>0)e.color=Li(e.emotionColors);else{const t=["#FFD700","#FFB347","#FFA500","#FF69B4"];e.color=Li(t)}e.hasGlow=Math.random()<.7,e.glowSizeMultiplier=e.hasGlow?1.5+.5*Math.random():0,e.behaviorData={radialSpeed:.02,shimmer:Math.random()*Gi,shimmerSpeed:.1,friction:.99}},update:function(e,t,i,s){const n=e.behaviorData,a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(o>0){const i=a/o,s=r/o;e.vx+=i*n.radialSpeed*t,e.vy+=s*n.radialSpeed*t}n.shimmer+=n.shimmerSpeed*t;const l=Math.sin(n.shimmer);e.size=e.baseSize*(1+.2*l),e.opacity=e.baseOpacity*(1+.3*l),e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t)}};function ss(e){e.vx=.02*(Math.random()-.5),e.vy=-.03-.02*Math.random(),e.lifeDecay=8e-4,e.size=(6+6*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1)*1.33,e.baseSize=e.size,e.baseOpacity=.2+.2*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={ascensionSpeed:3e-4,waveFactor:.5,waveFrequency:.001,friction:.998,fadeStartDistance:100}}var ns={name:"ascending",emoji:"๐ง",description:"Slow steady upward float like incense smoke",initialize:ss,update:function(e,t,i,s){const n=e.behaviorData;if(!n)return void ss(e);e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t),e.vy-=n.ascensionSpeed*t;const a=Math.sin(e.age*n.waveFrequency*1e3)*n.waveFactor;e.vx+=.001*a*t,void 0===e.initialY&&(e.initialY=e.y);const r=e.initialY-e.y;if(r>n.fadeStartDistance){const t=(r-n.fadeStartDistance)/100,i=Math.max(0,1-t);e.baseOpacity*=.995,i<.5&&(e.lifeDecay*=1.02)}Math.abs(e.vx)>.05&&(e.vx*=Math.pow(.95,t)),e.vy<-.1&&(e.vy=-.1)}},as={name:"erratic",emoji:"๐ฐ",description:"Nervous jittery movement for anxious states",initialize:function(e){const t=Math.random()*Gi,i=.1+.15*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.004,e.size=(2+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.baseOpacity=.4+.3*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={jitterStrength:.02,directionChangeRate:.1,speedVariation:.3,spinRate:.05+.1*Math.random()}},update:function(e,t){const i=e.behaviorData;if(e.vx+=(Math.random()-.5)*i.jitterStrength*t,e.vy+=(Math.random()-.5)*i.jitterStrength*t,Math.random()<Math.min(i.directionChangeRate*t,.5)){const t=Math.random()*Gi,i=Math.sqrt(e.vx*e.vx+e.vy*e.vy);e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i}const s=1+(Math.random()-.5)*i.speedVariation*t;e.vx*=s,e.vy*=s;const n=e.age*i.spinRate*1e3;e.size=e.baseSize*(1+.2*Math.sin(n)),e.opacity=e.baseOpacity*(.8+.4*Math.random()),e.vx*=Math.pow(.98,t),e.vy*=Math.pow(.98,t);const a=Math.sqrt(e.vx*e.vx+e.vy*e.vy);a>.5&&(e.vx=e.vx/a*.5,e.vy=e.vy/a*.5)}},rs={name:"cautious",emoji:"๐คจ",description:"Slow careful movement with watchful pauses",initialize:function(e){const t=Math.random()*Gi,i=.02+.03*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.001,e.life=1,e.size=(4+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.baseOpacity=.8+.2*Math.random(),e.opacity=e.baseOpacity,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={pauseTimer:2*Math.random(),pauseDuration:.5+.5*Math.random(),moveDuration:1+.5*Math.random(),isMoving:Math.random()>.5,moveTimer:0,originalVx:e.vx,originalVy:e.vy,watchRadius:50+30*Math.random()}},update:function(e,t,i,s){const n=e.behaviorData;if(n.moveTimer+=t,n.isMoving)n.moveTimer>n.moveDuration?(n.isMoving=!1,n.moveTimer=0,e.vx=0,e.vy=0):(e.vx=n.originalVx,e.vy=n.originalVy);else if(n.moveTimer>n.pauseDuration){n.isMoving=!0,n.moveTimer=0;const t=Math.random()*Gi,i=.02+.03*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,n.originalVx=e.vx,n.originalVy=e.vy}const a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(o>n.watchRadius){const i=.02;e.vx-=a/o*i*t,e.vy-=r/o*i*t}e.vx*=Math.pow(.995,t),e.vy*=Math.pow(.995,t),n.isMoving?e.opacity=e.baseOpacity:e.opacity=e.baseOpacity*(.9+.1*Math.sin(5*e.age))}},os={name:"surveillance",emoji:"๐๏ธ",description:"Searchlight scanning with paranoid watchfulness",initialize(e,t){e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorState={scanAngle:Math.random()*Math.PI-Math.PI/2,scanDirection:Math.random()<.5?1:-1,scanSpeed:.3+.2*Math.random(),scanRange:Math.PI/3+Math.random()*Math.PI/4,scanCenter:Math.random()*Math.PI*2,pauseTimer:0,pauseDuration:500+500*Math.random(),mode:"scanning",modeTimer:0,nextModeChange:2e3+3e3*Math.random(),dartTarget:{x:0,y:0},dartSpeed:0,patrolRadius:150+100*Math.random(),patrolAngle:Math.random()*Math.PI*2,alertLevel:0,lastPosition:{x:e.x,y:e.y}};const i=Math.random();i<.7?e.behaviorState.primaryRole="scanner":i<.9?(e.behaviorState.primaryRole="patroller",e.behaviorState.mode="patrolling"):(e.behaviorState.primaryRole="watcher",e.behaviorState.mode="frozen")},update(e,t,i){const s=e.behaviorState;if(s){switch(s.modeTimer+=16*t,s.modeTimer>s.nextModeChange&&(this.changeMode(e,s,i),s.modeTimer=0,s.nextModeChange=2e3+4e3*Math.random()),s.mode){case"scanning":this.updateScanning(e,t,s,i);break;case"darting":this.updateDarting(e,t,s,i);break;case"frozen":this.updateFrozen(e,t,s,i);break;case"patrolling":this.updatePatrolling(e,t,s,i)}e.vy+=.05*t,e.x+=e.vx*t,e.y+=e.vy*t,s.lastPosition.x=e.x,s.lastPosition.y=e.y}},updateScanning(e,t,i,s){i.pauseTimer>0?(i.pauseTimer-=16*t,e.vx*=.9,e.vy*=.9):(i.scanAngle+=i.scanDirection*i.scanSpeed*t*.02,Math.abs(i.scanAngle)>i.scanRange/2&&(i.scanDirection*=-1,i.pauseTimer=i.pauseDuration,i.scanAngle=Math.sign(i.scanAngle)*i.scanRange/2));const n=i.scanCenter+i.scanAngle,a=.8+.5*i.alertLevel;e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a*.3},updateDarting(e,t,i,s){const n=i.dartTarget.x-e.x,a=i.dartTarget.y-e.y,r=Math.sqrt(n*n+a*a);r>5?(e.vx=n/r*i.dartSpeed,e.vy=a/r*i.dartSpeed):(i.mode="scanning",i.modeTimer=0)},updateFrozen(e,t,i,s){e.vx*=.95,e.vy*=.95,Math.random()<.01&&(e.vx+=.5*(Math.random()-.5),e.vy+=.5*(Math.random()-.5))},updatePatrolling(e,t,i,s){i.patrolAngle+=.01*t;const n=s.corePosition?.x??s.canvasWidth/2,a=s.corePosition?.y??s.canvasHeight/2,r=n+Math.cos(i.patrolAngle)*i.patrolRadius,o=a+Math.sin(i.patrolAngle)*i.patrolRadius,l=r-e.x,h=o-e.y;e.vx=.02*l,e.vy=.02*h},changeMode(e,t,i){const s=Math.random(),n=i?.corePosition?.x??(i?.canvasWidth/2||e.x),a=i?.corePosition?.y??(i?.canvasHeight/2||e.y);"scanner"===t.primaryRole?s<.1?(t.mode="darting",t.dartTarget={x:n+200*(Math.random()-.5),y:a+200*(Math.random()-.5)},t.dartSpeed=3+2*Math.random()):t.mode=s<.2?"frozen":"scanning":"patroller"===t.primaryRole?t.mode=s<.1?"frozen":"patrolling":t.mode=s<.3?"scanning":"frozen"}},ls={name:"glitchy",emoji:"โก",description:"Digital glitch with stuttering orbits and corruption",rhythm:{enabled:!0,glitchTiming:{mode:"subdivision",subdivision:"sixteenth",probability:.3,intensityOnBeat:2,intensityOffBeat:.5},stutterSync:{mode:"pattern",patterns:{dubstep:{freezeOnDrop:!0,dropDuration:100},breakbeat:{randomFreeze:.1,duration:50}}},orbitRhythm:{baseSpeed:"tempo",wobbleSync:"eighth",beatAcceleration:1.5,barReset:!0},rgbSync:{enabled:!0,amount:"intensity",direction:"beat",maxSplit:10},noiseRhythm:{trigger:"accent",duration:50,intensity:"drop"}},initialize(e,t,i,s){e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorState={orbitAngle:Math.random()*Math.PI*2,orbitRadius:300+400*Math.random(),orbitSpeed:.01+.02*Math.random(),glitchTimer:0,nextGlitch:500*Math.random()+100,isGlitching:!1,glitchDuration:0,glitchOffset:{x:0,y:0},stutterTimer:0,nextStutter:200*Math.random()+50,isFrozen:!1,frozenPosition:{x:0,y:0},frozenVelocity:{x:0,y:0},hasGhost:Math.random()<.3,ghostOffset:20*Math.random()+10,ghostAngle:Math.random()*Math.PI*2,rgbSplit:Math.random()<.4,rgbPhase:Math.random()*Math.PI*2,noiseLevel:0,noiseBurst:!1,beatPhase:Math.random()*Math.PI*2,beatFrequency:.05+.03*Math.random(),dropIntensity:0},e.lifeDecay=.0015,e.hasGlow=!0,e.glowSizeMultiplier=3+2*Math.random()},update(e,t,i,s){const n=e.behaviorState;if(!n)return;n.glitchTimer+=16*t,n.stutterTimer+=16*t,n.stutterTimer>n.nextStutter&&(n.isFrozen?(n.isFrozen=!1,n.stutterTimer=0,n.nextStutter=100+300*Math.random(),Math.random()<.3&&(e.x+=60*(Math.random()-.5),e.y+=60*(Math.random()-.5))):(n.isFrozen=!0,n.frozenPosition={x:e.x,y:e.y},n.frozenVelocity={x:e.vx,y:e.vy},n.stutterTimer=0,n.nextStutter=20+40*Math.random())),n.glitchTimer>n.nextGlitch&&!n.isGlitching&&(n.isGlitching=!0,n.glitchDuration=50+100*Math.random(),n.glitchOffset={x:80*(Math.random()-.5),y:80*(Math.random()-.5)},n.glitchTimer=0,Math.random()<.5&&e.emotionColors&&(e.color=Li(e.emotionColors))),n.isGlitching&&n.glitchTimer>n.glitchDuration&&(n.isGlitching=!1,n.glitchTimer=0,n.nextGlitch=200+800*Math.random(),n.glitchOffset={x:0,y:0}),n.beatPhase+=n.beatFrequency*t;const a=.5*Math.sin(n.beatPhase)+.5;if(n.beatPhase%(4*Math.PI)<.5*Math.PI?n.dropIntensity=Math.min(1,n.dropIntensity+.1*t):n.dropIntensity=Math.max(0,n.dropIntensity-.05*t),n.isFrozen)e.vx=.5*(Math.random()-.5),e.vy=.5*(Math.random()-.5);else{n.orbitAngle+=n.orbitSpeed*t*(1+.5*a);const r=n.orbitRadius*(1+.3*n.dropIntensity*Math.sin(4*n.beatPhase));let o=i+Math.cos(n.orbitAngle)*r,l=s+Math.sin(n.orbitAngle)*r*.6;if(n.isGlitching&&(o+=n.glitchOffset.x*Math.random()*.8,l+=n.glitchOffset.y*Math.random()*.8),n.rgbSplit){const e=3*(1+n.dropIntensity);o+=Math.sin(n.rgbPhase)*e,l+=Math.cos(n.rgbPhase)*e,n.rgbPhase+=.1*t}n.dropIntensity>.8&&Math.random()<.1&&(o+=30*(Math.random()-.5),l+=30*(Math.random()-.5));const h=n.isGlitching?.02:.03;e.vx=(o-e.x)*h,e.vy=(l-e.y)*h,e.vx+=(Math.random()-.5)*a*2,e.vy+=(Math.random()-.5)*a*2}e.x+=e.vx*t,e.y+=e.vy*t,Math.random()<.02&&(e.opacity=.1+.9*Math.random()),e.size=e.baseSize*(1+.3*a+.5*n.dropIntensity)}},hs={name:"spaz",description:"Ultra-aggressive particles with explosive spread and chaotic motion",initialize(e,t,i,s){e.x=i,e.y=s,e.life=1,e.size=3+4*Math.random();const n=Math.random()*Math.PI*2,a=200+300*Math.random();e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a,e.behaviorState={explosionPhase:0,explosionTimer:0,explosionDuration:1e3+2e3*Math.random(),chaosTimer:0,nextChaosChange:100+200*Math.random(),chaosAngle:n,chaosSpeed:50+100*Math.random(),spazIntensity:.8+.4*Math.random(),zigzagPattern:Math.random()<.5,spiralPattern:Math.random()<.3,teleportChance:.02,sizePulse:!0,sizePulseSpeed:.1+.05*Math.random(),sizePulsePhase:Math.random()*Math.PI*2,colorShift:Math.random()<.3,colorShiftSpeed:.05+.03*Math.random()},e.lifeDecay=8e-4,e.hasGlow=!0,e.glowSizeMultiplier=4+3*Math.random(),e.glowIntensity=1.5+.5*Math.random()},update(e,t,i,s){const n=e.behaviorState;if(n.explosionTimer+=t,n.chaosTimer+=t,0===n.explosionPhase&&n.explosionTimer<500)e.vx*=.98,e.vy*=.98,Math.random()<.1&&(e.vx+=100*(Math.random()-.5),e.vy+=100*(Math.random()-.5));else if(0===n.explosionPhase&&n.explosionTimer>=500)n.explosionPhase=1,n.chaosAngle=Math.random()*Math.PI*2,n.chaosSpeed=30+70*Math.random();else if(1===n.explosionPhase){n.chaosTimer>=n.nextChaosChange&&(n.chaosAngle=Math.random()*Math.PI*2,n.chaosSpeed=20+80*Math.random(),n.nextChaosChange=50+150*Math.random(),n.chaosTimer=0);const t=Math.cos(n.chaosAngle)*n.chaosSpeed,i=Math.sin(n.chaosAngle)*n.chaosSpeed;if(e.vx=.7*e.vx+.3*t,e.vy=.7*e.vy+.3*i,n.zigzagPattern){const t=.01*n.chaosTimer;e.vx+=20*Math.sin(t),e.vy+=20*Math.cos(t)}if(n.spiralPattern){const t=.005*n.chaosTimer,i=50+30*Math.sin(.003*n.chaosTimer);e.vx+=Math.cos(t)*i*.1,e.vy+=Math.sin(t)*i*.1}}if(Math.random()<n.teleportChance){const t=Math.random()*Math.PI*2,n=200+400*Math.random();e.x=i+Math.cos(t)*n,e.y=s+Math.sin(t)*n,e.vx=200*(Math.random()-.5),e.vy=200*(Math.random()-.5)}if(e.x+=e.vx*(t/1e3),e.y+=e.vy*(t/1e3),n.sizePulse){n.sizePulsePhase+=n.sizePulseSpeed*t;const i=1+.5*Math.sin(n.sizePulsePhase);e.size=(3+4*Math.random())*i}n.colorShift&&(n.colorShiftPhase=(n.colorShiftPhase||0)+n.colorShiftSpeed*t),e.vx*=.995,e.vy*=.995,e.life-=e.lifeDecay*t,(e.life<=0||Math.abs(e.x-i)>2e3||Math.abs(e.y-s)>2e3)&&(e.life=0)},getSpawnPosition(e,t){const i=Math.random()*Math.PI*2,s=100+200*Math.random();return{x:e+Math.cos(i)*s,y:t+Math.sin(i)*s}},getVisualProperties:()=>({glowColor:"#FF00AA",glowIntensity:2,particleColors:[{color:"#FF00AA",weight:30},{color:"#00FFAA",weight:25},{color:"#FFAA00",weight:20},{color:"#AA00FF",weight:15},{color:"#00AAFF",weight:10}]})},cs={name:"directed",emoji:"๐ฏ",description:"Focused, straight-line movement toward target",config:{speed:3,acceleration:.15,focusStrength:.8,randomness:.1,edgeBuffer:50},initialize(e,t,i,s,n){const a=t-e.x,r=i-e.y,o=Math.sqrt(a*a+r*r);if(o>0)e.vx=a/o*this.config.speed,e.vy=r/o*this.config.speed;else{const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*this.config.speed,e.vy=Math.sin(t)*this.config.speed}e.targetX=t,e.targetY=i,e.directedPhase=0},update(e,t,i,s,n,a){e.directedPhase+=.05*t;const r=e.targetX-e.x,o=e.targetY-e.y,l=Math.sqrt(r*r+o*o);if(l>10){const i=r/l*this.config.speed,s=o/l*this.config.speed;e.vx+=(i-e.vx)*this.config.acceleration*t,e.vy+=(s-e.vy)*this.config.acceleration*t,e.vx+=(Math.random()-.5)*this.config.randomness,e.vy+=(Math.random()-.5)*this.config.randomness}else{const t=Math.random()*Math.PI*2,r=100+200*Math.random();e.targetX=i+Math.cos(t)*r,e.targetY=s+Math.sin(t)*r,e.targetX=Math.max(this.config.edgeBuffer,Math.min(n-this.config.edgeBuffer,e.targetX)),e.targetY=Math.max(this.config.edgeBuffer,Math.min(a-this.config.edgeBuffer,e.targetY))}e.x+=e.vx*t,e.y+=e.vy*t,(e.x<=0||e.x>=n)&&(e.vx*=-.8,e.x=Math.max(0,Math.min(n,e.x)),e.targetX=i+300*(Math.random()-.5)),(e.y<=0||e.y>=a)&&(e.vy*=-.8,e.y=Math.max(0,Math.min(a,e.y)),e.targetY=s+300*(Math.random()-.5))},visuals:{trailLength:"medium",opacity:.9,sizeMultiplier:1,blurAmount:.2}},us={name:"fizzy",emoji:"๐ซง",description:"Bubbly, effervescent movement like carbonation",config:{baseRiseSpeed:2.5,wobbleAmplitude:30,wobbleFrequency:.15,popChance:.002,popForce:8,fizziness:.3,gravity:-.05},initialize(e,t,i,s,n){e.vx=2*(Math.random()-.5),e.vy=-this.config.baseRiseSpeed-2*Math.random(),e.wobblePhase=Math.random()*Math.PI*2,e.wobbleSpeed=this.config.wobbleFrequency*(.8+.4*Math.random()),e.bubbleSize=.5+.5*Math.random(),e.popTimer=0,e.isFizzing=!0},update(e,t,i,s,n,a){e.wobblePhase+=e.wobbleSpeed*t;const r=Math.sin(e.wobblePhase)*this.config.wobbleAmplitude;if(e.vx=.05*r+(Math.random()-.5)*this.config.fizziness,e.vy+=this.config.gravity*t,e.vy+=(Math.random()-.5)*this.config.fizziness,Math.random()<this.config.popChance){const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*this.config.popForce,e.vy=Math.sin(t)*this.config.popForce*.7,e.popTimer=1,e.bubbleSize=.3+.7*Math.random()}e.popTimer>0&&(e.popTimer-=.05*t,e.vx*=.95,e.vy*=.95),e.x+=e.vx*t,e.y+=e.vy*t,e.y<-50&&(e.y=a+50,e.x=i+300*(Math.random()-.5),e.vy=-this.config.baseRiseSpeed-2*Math.random(),e.bubbleSize=.5+.5*Math.random()),(e.x<=0||e.x>=n)&&(e.vx*=-.5,e.x=Math.max(0,Math.min(n,e.x))),e.y>a+50&&(e.y=a,e.vy=1.5*-this.config.baseRiseSpeed),e.size=e.baseSize*e.bubbleSize*(1+.1*Math.sin(2*e.wobblePhase))},visuals:{trailLength:"short",opacity:.6,sizeMultiplier:1.2,blurAmount:.5,sparkle:!0}};const ds=new Map;var gs={registerPluginBehavior:function(e,t){return ds.has(e),!(!t.initialize||"function"!=typeof t.initialize||!t.update||"function"!=typeof t.update||(ds.set(e,{name:e,emoji:t.emoji||"๐",description:t.description||`Plugin behavior: ${e}`,initialize:t.initialize,update:t.update,isPlugin:!0}),0))},unregisterPluginBehavior:function(e){return!!ds.has(e)&&(ds.delete(e),!0)},getPluginBehavior:function(e){return ds.get(e)||null},getAllPluginBehaviors:function(){return Array.from(ds.keys())},createLegacyAdapter:function(e){return{name:e.name||"legacy",emoji:"๐",description:e.description||"Legacy plugin behavior",initialize(t){if(e.size&&(t.size="object"==typeof e.size?e.size.min+Math.random()*(e.size.max-e.size.min):e.size,t.baseSize=t.size),e.speed){const i="object"==typeof e.speed?e.speed.min+Math.random()*(e.speed.max-e.speed.min):e.speed,s=Math.random()*Math.PI*2;t.vx=Math.cos(s)*i,t.vy=Math.sin(s)*i}if(e.lifespan){const i="object"==typeof e.lifespan?e.lifespan.min+Math.random()*(e.lifespan.max-e.lifespan.min):e.lifespan;t.lifeDecay=1e3/i}e.color&&(t.color=Array.isArray(e.color)?Li(e.color):e.color),e.opacity&&(t.life="object"==typeof e.opacity?e.opacity.min+Math.random()*(e.opacity.max-e.opacity.min):e.opacity),t.behaviorData={movementType:e.movementType||"linear",turbulence:e.turbulence||0,drift:e.drift||0,acceleration:e.acceleration||0,...e.customData}},update(t,i,s,n){const a=t.behaviorData;switch(a.movementType){case"wander":t.vx+=(Math.random()-.5)*a.turbulence*i,t.vy+=(Math.random()-.5)*a.turbulence*i;break;case"fall":t.vy+=.1*i,t.vx+=(Math.random()-.5)*a.drift*i;break;case"rain":t.vy+=a.acceleration*i;break;case"orbit":{const e=t.x-s,a=t.y-n,r=Math.sqrt(e*e+a*a);if(r>0){const o=Math.atan2(a,e)+.02*i;t.x=s+Math.cos(o)*r,t.y=n+Math.sin(o)*r}break}}e.customUpdate&&e.customUpdate(t,i,s,n)}}}};const ms={};function ps(e){if(ms[e])return ms[e];return gs.getPluginBehavior(e)||null}function fs(e,t){const i=ps(t);return i&&i.initialize?(i.initialize(e),!0):"ambient"!==t&&(console.warn(`โ ๏ธ Behavior '${t}' not found, falling back to ambient`),fs(e,"ambient"))}function ys(e,t,i,s,n){const a=ps(t);return!(!a||!a.update||(a.update(e,i,s,n),0))}function bs(){return[...Object.values(ms).map(e=>({name:e.name,emoji:e.emoji||"๐ฏ",description:e.description||"No description",type:"core"})),...gs.getAllPluginBehaviors().map(e=>{const t=gs.getPluginBehavior(e);return{name:t.name,emoji:t.emoji||"๐",description:t.description||"Plugin behavior",type:"plugin"}})]}[qi,cs,us,Hi,ji,Wi,Ni,Qi,Ji,Ki,Zi,es,ts,is,ns,as,rs,os,ls,hs].forEach(e=>{ms[e.name]=e}),"undefined"!=typeof window&&window.DEBUG_PARTICLES&&(window.ParticleBehaviors={registry:ms,list:bs,get:ps});var vs={BEHAVIOR_REGISTRY:ms,getBehavior:ps,initializeBehavior:fs,updateBehavior:ys,listBehaviors:bs,pluginAdapter:gs},Ms=Object.freeze({__proto__:null,BEHAVIOR_REGISTRY:ms,default:vs,getBehavior:ps,initializeBehavior:fs,listBehaviors:bs,pluginAdapter:gs,updateBehavior:ys});class ws{constructor(){this.listeners=new Map,this.groups=new Map,this.stats={registered:0,removed:0,active:0},this._listeners={},this._emitters=new Map}addEventListener(e,t,i,s={},n="default"){const a=this.generateId(),r={id:a,target:e,eventType:t,handler:i,options:s,group:n,active:!0};return this.listeners.set(a,r),this.groups.has(n)||this.groups.set(n,new Set),this.groups.get(n).add(a),e.addEventListener(t,i,s),this.stats.registered++,this.stats.active++,a}removeEventListener(e){const t=this.listeners.get(e);if(!t||!t.active)return!1;t.target.removeEventListener(t.eventType,t.handler,t.options),t.active=!1;const i=this.groups.get(t.group);return i&&(i.delete(e),0===i.size&&this.groups.delete(t.group)),this.listeners.delete(e),this.stats.removed++,this.stats.active--,!0}removeGroup(e){const t=this.groups.get(e);if(!t)return 0;let i=0;for(const e of t)this.removeEventListener(e)&&i++;return i}removeAllForTarget(e){let t=0;for(const[i,s]of this.listeners.entries())s.target===e&&s.active&&this.removeEventListener(i)&&t++;return t}removeAllOfType(e){let t=0;for(const[i,s]of this.listeners.entries())s.eventType===e&&s.active&&this.removeEventListener(i)&&t++;return t}removeAll(){let e=0;for(const[t,i]of this.listeners.entries())i.active&&this.removeEventListener(t)&&e++;return e}createAutoRemove(e,t,i,s={}){const n=this.addEventListener(e,t,i,s);return{id:n,remove:()=>this.removeEventListener(n)}}once(e,t,i,s={}){const n=this.addEventListener(e,t,e=>{i(e),this.removeEventListener(n)},s);return n}debounced(e,t,i,s=250,n={}){let a;return this.addEventListener(e,t,e=>{clearTimeout(a),a=setTimeout(()=>i(e),s)},n)}throttled(e,t,i,s=100,n={}){let a=!1;return this.addEventListener(e,t,e=>{a||(i(e),a=!0,setTimeout(()=>{a=!1},s))},n)}on(e,t){this._emitters.has(e)||this._emitters.set(e,[]),this._emitters.get(e).push(t)}off(e,t){const i=this._emitters.get(e);if(!i)return;const s=i.indexOf(t);-1!==s&&i.splice(s,1),0===i.length&&this._emitters.delete(e)}emit(e,t=null){const i=this._emitters.get(e);if(i)for(let s=0;s<i.length;s++)try{i[s](t)}catch(t){console.warn(`[EventManager] Error in "${e}" listener:`,t)}}removeAllListeners(e=null){if(e){const t=this._emitters.get(e),i=t?t.length:0;return this._emitters.delete(e),i}let t=0;for(const e of this._emitters.values())t+=e.length;return this._emitters.clear(),t}listenerCount(e){const t=this._emitters.get(e);return t?t.length:0}getEventNames(){return Array.from(this._emitters.keys())}getEventStats(){let e=0;for(const t of this._emitters.values())e+=t.length;return{domListeners:this.stats.active,emitterEvents:this._emitters.size,emitterListeners:e}}getDebugInfo(){const e={};for(const[t,i]of this._emitters)e[t]=i.length;return{domStats:this.getStats(),emitterEvents:e,activeListeners:this.getActiveListeners()}}generateId(){return`listener_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getStats(){return{...this.stats,groups:this.groups.size,listeners:this.listeners.size}}getActiveListeners(){const e=[];for(const[t,i]of this.listeners.entries())i.active&&e.push({id:t,eventType:i.eventType,group:i.group,target:i.target.constructor.name});return e}analyzeLeaks(){const e={totalListeners:this.listeners.size,activeListeners:this.stats.active,inactiveButNotRemoved:0,byTarget:new Map,byType:new Map,potentialLeaks:[]};for(const[t,i]of this.listeners.entries()){const s=i.target.constructor.name;e.byTarget.set(s,(e.byTarget.get(s)||0)+1),e.byType.set(i.eventType,(e.byType.get(i.eventType)||0)+1),i.active||(e.inactiveButNotRemoved++,e.potentialLeaks.push({id:t,eventType:i.eventType,target:s}))}return e.byTarget=Object.fromEntries(e.byTarget),e.byType=Object.fromEntries(e.byType),e}cleanup(){let e=0;for(const[t,i]of this.listeners.entries())i.active||(this.listeners.delete(t),e++);return e}destroy(){const e=this.removeAll();return this.listeners.clear(),this.groups.clear(),this._emitters.clear(),this._listeners=null,this.stats={registered:0,removed:0,active:0},e}}const Ss=new ws,xs={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,TRACE:5},Cs=new class{constructor(e={}){this.config={enabled:!1!==e.enabled,level:e.level||xs.INFO,enableProfiling:!1!==e.enableProfiling,enableErrorTracking:!1!==e.enableErrorTracking,enableMemoryTracking:!1!==e.enableMemoryTracking,maxLogEntries:e.maxLogEntries||1e3,maxProfileEntries:e.maxProfileEntries||500,...e},this._logBuffer=new Array(e.maxLogEntries||1e3),this._logIndex=0,this._logCount=0,this.errors=[],this.profiles=new Map,this.memorySnapshots=[],this.maxFrameTimings=120,this._frameBuffer=new Array(this.maxFrameTimings),this._frameIndex=0,this._frameCount=0,this.errorCounts=new Map,this.lastErrors=new Map,this.capabilities={performance:"undefined"!=typeof performance&&performance.now,memory:"undefined"!=typeof performance&&performance.memory,console:"undefined"!=typeof console,stackTrace:"undefined"!=typeof Error};const t=(()=>{}).bind(console);this._consoleMethods={ERROR:t,WARN:t,DEBUG:t,TRACE:t,DEFAULT:t},this.startTime=this.now(),this.setupErrorHandling(),this.config.enabled&&this.log("DEBUG","EmotiveDebugger initialized",{config:this.config,capabilities:this.capabilities})}now(){return this.capabilities.performance?performance.now():Date.now()-this.startTime}setupErrorHandling(){this.config.enableErrorTracking&&"undefined"!=typeof window&&(window.addEventListener("error",e=>{this.trackError("UNHANDLED_ERROR",e.error||new Error(e.message),{filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError("UNHANDLED_REJECTION",e.reason,{promise:e.promise})}))}log(e,t,i=null){if(!this.config.enabled)return;if((xs[e]||xs.INFO)>this.config.level)return;const s=this.now(),n={timestamp:s,level:e,message:t,data:i,stackTrace:this.getStackTrace()};if(this._logBuffer[this._logIndex]=n,this._logIndex=(this._logIndex+1)%this.config.maxLogEntries,this._logCount<this.config.maxLogEntries&&this._logCount++,this.capabilities.console){const n=this.getConsoleMethod(e),a=`[${(s/1e3).toFixed(3)}s]`;i?n(`${a} [${e}] ${t}`,i):n(`${a} [${e}] ${t}`)}}getConsoleMethod(e){return this._consoleMethods[e]||this._consoleMethods.DEFAULT}getStackTrace(){if(!this.capabilities.stackTrace)return null;try{throw new Error}catch(e){return e.stack}}trackError(e,t,i={}){if(!this.config.enableErrorTracking)return;const s={timestamp:this.now(),type:e,message:t.message||String(t),stack:t.stack,context:i,count:1},n=`${e}:${t.message}`;this.errorCounts.has(n)?(this.errorCounts.set(n,this.errorCounts.get(n)+1),s.count=this.errorCounts.get(n)):this.errorCounts.set(n,1),this.errors.push(s),this.lastErrors.set(e,s),this.log("ERROR",`${e}: ${t.message}`,{error:s,context:i})}startProfile(e,t={}){if(!this.config.enableProfiling)return;const i={name:e,startTime:this.now(),metadata:t,samples:[],isActive:!0};this.profiles.set(e,i),this.log("TRACE",`Started profiling: ${e}`,t)}profileSample(e,t,i=null){if(!this.config.enableProfiling)return;const s=this.profiles.get(e);if(!s||!s.isActive)return;const n={timestamp:this.now(),label:t,data:i,relativeTime:this.now()-s.startTime};s.samples.push(n)}endProfile(e){if(!this.config.enableProfiling)return null;const t=this.profiles.get(e);if(!t||!t.isActive)return null;if(t.endTime=this.now(),t.duration=t.endTime-t.startTime,t.isActive=!1,t.stats=this.calculateProfileStats(t),this.log("TRACE",`Ended profiling: ${e}`,{duration:t.duration,samples:t.samples.length,stats:t.stats}),this.profiles.size>this.config.maxProfileEntries){const e=this.profiles.keys().next().value;this.profiles.delete(e)}return{...t}}calculateProfileStats(e){if(0===e.samples.length)return{sampleCount:0};const t=[];for(let i=1;i<e.samples.length;i++)t.push(e.samples[i].relativeTime-e.samples[i-1].relativeTime);if(0===t.length)return{sampleCount:e.samples.length};const i=t.reduce((e,t)=>e+t,0)/t.length,s=Math.min(...t),n=Math.max(...t);return{sampleCount:e.samples.length,avgSampleDuration:i,minSampleDuration:s,maxSampleDuration:n,totalDuration:e.duration}}trackFrameTiming(e){this.config.enableProfiling&&(this._frameBuffer[this._frameIndex]={timestamp:this.now(),frameTime:e,fps:1e3/e},this._frameIndex=(this._frameIndex+1)%this.maxFrameTimings,this._frameCount<this.maxFrameTimings&&this._frameCount++)}_readCircular(e,t,i,s,n=0){const a=n>0?Math.min(n,i):i,r=new Array(a),o=(t-a+s)%s;for(let t=0;t<a;t++)r[t]=e[(o+t)%s];return r}takeMemorySnapshot(e="snapshot"){if(!this.config.enableMemoryTracking||!this.capabilities.memory)return;const t={timestamp:this.now(),label:e,memory:{usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}};this.memorySnapshots.push(t),this.memorySnapshots.length>100&&this.memorySnapshots.shift(),this.log("DEBUG",`Memory snapshot: ${e}`,t.memory)}getDebugReport(){return{timestamp:this.now(),uptime:this.now()-0,config:this.config,capabilities:this.capabilities,logCount:this._logCount,recentLogs:this._readCircular(this._logBuffer,this._logIndex,this._logCount,this.config.maxLogEntries,10),errorCount:this.errors.length,uniqueErrors:this.errorCounts.size,recentErrors:this.errors.slice(-5),errorCounts:Object.fromEntries(this.errorCounts),activeProfiles:Array.from(this.profiles.values()).filter(e=>e.isActive).length,completedProfiles:Array.from(this.profiles.values()).filter(e=>!e.isActive).length,frameTimings:this.getFrameTimingStats(),memorySnapshots:this.memorySnapshots.slice(-5)}}getFrameTimingStats(){if(0===this._frameCount)return{sampleCount:0};const e=this._readCircular(this._frameBuffer,this._frameIndex,this._frameCount,this.maxFrameTimings),t=e.map(e=>e.frameTime),i=e.map(e=>e.fps);return{sampleCount:this._frameCount,avgFrameTime:t.reduce((e,t)=>e+t,0)/t.length,minFrameTime:Math.min(...t),maxFrameTime:Math.max(...t),avgFPS:i.reduce((e,t)=>e+t,0)/i.length,minFPS:Math.min(...i),maxFPS:Math.max(...i)}}exportDebugData(){return{metadata:{exportTime:Date.now(),debuggerUptime:this.now(),config:this.config,capabilities:this.capabilities},logs:this._readCircular(this._logBuffer,this._logIndex,this._logCount,this.config.maxLogEntries),errors:[...this.errors],profiles:Object.fromEntries(this.profiles),frameTimings:this._readCircular(this._frameBuffer,this._frameIndex,this._frameCount,this.maxFrameTimings),memorySnapshots:[...this.memorySnapshots],errorCounts:Object.fromEntries(this.errorCounts)}}clear(){this._logBuffer.fill(void 0),this._logIndex=0,this._logCount=0,this.errors=[],this.profiles.clear(),this._frameBuffer.fill(void 0),this._frameIndex=0,this._frameCount=0,this.memorySnapshots=[],this.errorCounts.clear(),this.lastErrors.clear(),this.log("INFO","Debug data cleared")}destroy(){this.clear(),this.config.enabled=!1}}({enabled:"undefined"!=typeof window&&window.location&&window.location.search.includes("debug=true"),level:xs.INFO}),ks=new class{constructor(){this.capabilities=this.detectCapabilities(),this.performance=this.measurePerformance()}detectCapabilities(){return{es6:this.detectES6(),es2017:this.detectES2017(),modules:this.detectModules(),webGL:this.detectWebGL(),webGL2:this.detectWebGL2(),webWorkers:this.detectWebWorkers(),serviceWorkers:this.detectServiceWorkers(),performanceObserver:this.detectPerformanceObserver(),intersectionObserver:this.detectIntersectionObserver(),resizeObserver:this.detectResizeObserver(),localStorage:this.detectLocalStorage(),sessionStorage:this.detectSessionStorage(),indexedDB:this.detectIndexedDB(),fetch:this.detectFetch(),webSockets:this.detectWebSockets(),touchEvents:this.detectTouchEvents(),pointerEvents:this.detectPointerEvents(),deviceOrientation:this.detectDeviceOrientation(),canvas2d:this.detectCanvas2D(),canvasFilters:this.detectCanvasFilters(),offscreenCanvas:this.detectOffscreenCanvas()}}detectES6(){try{return"undefined"!=typeof Symbol&&"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set}catch{return!1}}detectES2017(){try{return"undefined"!=typeof async||function(){try{return"function"==typeof async function(){}.constructor}catch{return!1}}()}catch{return!1}}detectModules(){try{return"undefined"!=typeof document&&"noModule"in document.createElement("script")}catch{return!1}}detectWebGL(){try{const e=document.createElement("canvas");return!(!e.getContext("webgl")&&!e.getContext("experimental-webgl"))}catch{return!1}}detectWebGL2(){try{return!!document.createElement("canvas").getContext("webgl2")}catch{return!1}}detectWebWorkers(){return"undefined"!=typeof Worker}detectServiceWorkers(){return"serviceWorker"in navigator}detectPerformanceObserver(){return"undefined"!=typeof PerformanceObserver}detectIntersectionObserver(){return"undefined"!=typeof IntersectionObserver}detectResizeObserver(){return"undefined"!=typeof ResizeObserver}detectLocalStorage(){try{return"undefined"!=typeof localStorage&&null!==localStorage}catch{return!1}}detectSessionStorage(){try{return"undefined"!=typeof sessionStorage&&null!==sessionStorage}catch{return!1}}detectIndexedDB(){return"undefined"!=typeof indexedDB}detectFetch(){return"undefined"!=typeof fetch}detectWebSockets(){return"undefined"!=typeof WebSocket}detectTouchEvents(){return"ontouchstart"in window||navigator.maxTouchPoints>0}detectPointerEvents(){return"undefined"!=typeof PointerEvent}detectDeviceOrientation(){return"ondeviceorientation"in window}detectCanvas2D(){try{return!!document.createElement("canvas").getContext("2d")}catch{return!1}}detectCanvasFilters(){try{return"filter"in document.createElement("canvas").getContext("2d")}catch{return!1}}detectOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}measurePerformance(){const e={},t=performance.now();e.jsExecutionSpeed=performance.now()-t;try{const t=document.createElement("canvas");t.width=100,t.height=100;const i=t.getContext("2d"),s=performance.now();for(let e=0;e<1e3;e++)i.fillRect(100*Math.random(),100*Math.random(),10,10);e.canvasPerformance=performance.now()-s}catch{e.canvasPerformance=null}return e}getCapabilities(){return{...this.capabilities}}getPerformance(){return{...this.performance}}generateReport(){const e=Object.entries(this.capabilities).filter(([,e])=>e).map(([e])=>e),t=Object.entries(this.capabilities).filter(([,e])=>!e).map(([e])=>e),i=e.length/Object.keys(this.capabilities).length*100;return{timestamp:Date.now(),userAgent:navigator.userAgent,supportedFeatures:e,unsupportedFeatures:t,supportPercentage:Math.round(i),performance:this.performance,recommendations:this.generateRecommendations(i)}}generateRecommendations(e){const t=[];return e<50&&t.push("Consider using the minimal build for better compatibility"),this.capabilities.webGL||t.push("WebGL not supported - advanced graphics features unavailable"),this.capabilities.webWorkers||t.push("Web Workers not supported - background processing unavailable"),this.capabilities.fetch||t.push("Fetch API not supported - consider using XMLHttpRequest polyfill"),this.performance.jsExecutionSpeed>50&&t.push("Slow JavaScript execution detected - consider performance optimizations"),this.performance.canvasPerformance>100&&t.push("Slow canvas performance detected - consider reducing visual complexity"),t}};class Ps{constructor(e){this.canvas=e,this.ctx=e.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),this.ctx||(console.warn('CanvasManager: getContext("2d") returned null โ canvas may be unavailable or context already acquired.'),this._contextLost=!0),this.dpr=window.devicePixelRatio||1,this.width=0,this.height=0,this.centerX=0,this.centerY=0,this.renderSize=null,this.resizeCallbacks=[],this.handleResize=this.handleResize.bind(this),window.addEventListener("resize",this.handleResize),this.resize()}resize(){if(!this._contextLost){if(this.renderSize&&this.renderSize.width&&this.renderSize.height)this.width=this.renderSize.width,this.height=this.renderSize.height,this.canvas.width=this.width,this.canvas.height=this.height;else if(this.canvas.hasAttribute("width")&&this.canvas.hasAttribute("height")){const e=parseInt(this.canvas.getAttribute("width"),10),t=parseInt(this.canvas.getAttribute("height"),10),i=this.canvas.getBoundingClientRect(),s=i.width,n=i.height;e>1.5*s||t>1.5*n?(this.width=s,this.height=n,this.canvas.width=e,this.canvas.height=t,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)):(this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t)}else{const e=this.canvas.getBoundingClientRect();this.width=e.width,this.height=e.height,this.canvas.width=this.width*this.dpr,this.canvas.height=this.height*this.dpr,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)}this.centerX=this.width/2,this.centerY=this.height/2,this.resizeCallbacks.forEach(e=>{try{e(this.width,this.height,this.dpr)}catch{}})}}onResize(e){"function"==typeof e&&this.resizeCallbacks.push(e)}handleResize(){clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{this.renderSize&&this.renderSize.width&&this.renderSize.height||this.resize()},100)}setRenderSize(e,t){this.renderSize={width:e,height:t},this.resize()}clear(){this._contextLost||this.ctx.clearRect(0,0,this.width,this.height)}getCenter(){return{x:this.centerX,y:this.centerY}}setTransform(e=0,t=0,i=1,s=0){this._contextLost||(this.ctx.save(),this.ctx.translate(e,t),this.ctx.rotate(s),this.ctx.scale(i,i))}restoreTransform(){this._contextLost||this.ctx.restore()}getContext(){return this.ctx}getDimensions(){return{width:this.width,height:this.height}}destroy(){window.removeEventListener("resize",this.handleResize),clearTimeout(this.resizeTimeout),this.ctx&&(this.ctx.clearRect(0,0,this.width,this.height),this.ctx=null),this.canvas&&(this.canvas.width=0,this.canvas.height=0,this.canvas=null),this.resizeCallbacks=[],this.resizeTimeout=null}}function Ts(e){return 3===(e=e.replace("#","")).length&&(e=e.split("").map(e=>e+e).join("")),{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16)}}function Es(e,t,i){const s=e=>{const t=Math.round(Math.max(0,Math.min(255,e))).toString(16);return 1===t.length?`0${t}`:t};return`#${s(e)}${s(t)}${s(i)}`}function As(e,t,i){e/=255,t/=255,i/=255;const s=Math.max(e,t,i),n=Math.min(e,t,i),a=(s+n)/2;let r,o;if(s===n)r=o=0;else{const l=s-n;switch(o=a>.5?l/(2-s-n):l/(s+n),s){case e:r=(t-i)/l+(t<i?6:0);break;case t:r=(i-e)/l+2;break;case i:r=(e-t)/l+4}r/=6}return{h:360*r,s:100*o,l:100*a}}function Ds(e,t,i){e/=360,i/=100;const s=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e);let n,a,r;if(0==(t/=100))n=a=r=i;else{const o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;n=s(l,o,e+1/3),a=s(l,o,e),r=s(l,o,e-1/3)}return{r:Math.round(255*n),g:Math.round(255*a),b:Math.round(255*r)}}function _s(e,t,i){const s=Ts(e),n=Ts(t),a=As(s.r,s.g,s.b),r=As(n.r,n.g,n.b),o=a.h;let l=r.h;const h=l-o;h>180?l-=360:h<-180&&(l+=360);const c=Ds(((o+(l-o)*i)%360+360)%360,a.s+(r.s-a.s)*i,a.l+(r.l-a.l)*i);return Es(c.r,c.g,c.b)}function Is(e,t){const i=Ts(e),s=As(i.r,i.g,i.b);s.s=Math.max(0,Math.min(100,s.s*t));const n=Ds(s.h,s.s,s.l);return Es(n.r,n.g,n.b)}function Rs(e){const t=Ts(e),i=e=>{const t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b)}const Bs={intense:1.6,confident:1.3,nervous:1.15,clear:1,tired:.8,subdued:.5};function zs(e,t){if(!t||"clear"===t)return e;const i=Bs[t.toLowerCase()];return i&&1!==i?Is(e,i):e}function Fs(e,t){return e&&Array.isArray(e)&&t&&"clear"!==t?e.map(e=>"string"==typeof e?zs(e,t):e&&"object"==typeof e&&e.color?{...e,color:zs(e.color,t)}:e):e}const Os={neutral:"#B0B0B0",joy:"#FFD700",sadness:"#4169E1",anger:"#DC143C",fear:"#8B008B",surprise:"#FF8C00",disgust:"#9ACD32",love:"#FF69B4"},Ls=Object.fromEntries(Object.entries(Os).map(([e,t])=>{const i=Ts(t);return[e,`${i.r}, ${i.g}, ${i.b}`]}));function qs(e){return e}function Gs(e){return e*(2-e)}function Hs(e){return e*e}function js(e){return e<.5?2*e*e:(4-2*e)*e-1}function $s(e){return 1-Math.pow(1-e,3)}function Ws(e){return e*e*e}function Us(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function Vs(e){const t=2*Math.PI/3;return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((10*e-.75)*t)+1}function Ys(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375}function Xs(e){const t=2.5949095;return e<.5?Math.pow(2*e,2)*(7.189819*e-t)/2:(Math.pow(2*e-2,2)*((t+1)*(2*e-2)+t)+2)/2}function Ns(e){return Math.sin(e*Math.PI/2)}function Qs(e){return-(Math.cos(Math.PI*e)-1)/2}function Js(e,t,i,s="linear"){return t+(i-t)*("string"==typeof s?{linear:qs,easeOutQuad:Gs,easeInQuad:Hs,easeInOutQuad:js,easeOutCubic:$s,easeInCubic:Ws,easeInOutCubic:Us,easeOutElastic:Vs,easeOutBounce:Ys,easeInOutBack:Xs,easeOutSine:Ns,easeInOutSine:Qs}[s]||qs:s)(Math.max(0,Math.min(1,e)))}const Ks=new class{constructor(){this.emotionCache=new Map,this.visualParamsCache=new Map,this.modifiersCache=new Map,this.transitionCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1,this.loadStartTime=0,this.initialize()}initialize(){this.loadStartTime=performance.now();try{const e=u();e.forEach(e=>{this.cacheEmotion(e)}),this.cacheCommonTransitions(e),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.emotionCache.size}catch(e){console.error("[EmotionCache] Initialization failed:",e),this.isInitialized=!1,console.warn("[EmotionCache] Running uninitialized โ lookups will return defaults")}}cacheEmotion(e){try{const t=l(e);t&&this.emotionCache.set(e,t);const i=h(e);this.visualParamsCache.set(e,i);const s=c(e);this.modifiersCache.set(e,s)}catch(t){console.warn(`[EmotionCache] Failed to cache emotion '${e}':`,t)}}cacheCommonTransitions(e){[["neutral","joy"],["neutral","sadness"],["neutral","anger"],["joy","sadness"],["sadness","joy"],["anger","calm"],["calm","anger"]].forEach(([t,i])=>{if(e.includes(t)&&e.includes(i))try{const e=p(t,i),s=`${t}->${i}`;this.transitionCache.set(s,e)}catch(e){console.warn(`[EmotionCache] Failed to cache transition '${t}->${i}':`,e)}})}getEmotion(e){if(!this.isInitialized)return console.warn("[EmotionCache] Cache not initialized, falling back to direct access"),l(e);const t=this.emotionCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,l(e))}getVisualParams(e){if(!this.isInitialized)return h(e);const t=this.visualParamsCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,h(e))}getModifiers(e){if(!this.isInitialized)return c(e);const t=this.modifiersCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,c(e))}getTransitionParams(e,t){if(!this.isInitialized)return p(e,t);const i=`${e}->${t}`,s=this.transitionCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,p(e,t))}hasEmotion(e){return this.emotionCache.has(e)}getStats(){const e=this.stats.hits+this.stats.misses,t=e>0?(this.stats.hits/e*100).toFixed(2):0;return{isInitialized:this.isInitialized,loadTime:this.stats.loadTime,cacheSize:this.stats.cacheSize,hits:this.stats.hits,misses:this.stats.misses,hitRate:`${t}%`,emotions:this.emotionCache.size,visualParams:this.visualParamsCache.size,modifiers:this.modifiersCache.size,transitions:this.transitionCache.size}}clear(){this.emotionCache.clear(),this.visualParamsCache.clear(),this.modifiersCache.clear(),this.transitionCache.clear(),this.isInitialized=!1,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0}}reinitialize(){this.clear(),this.initialize()}};class Zs{constructor(e){this.errorBoundary=e,this.state={emotion:"neutral",undertone:null,intensity:1,gesture:null,speaking:!1,audioLevel:0},this.slots=[],this.maxSlots=3,this._eventCallback=null,this._previousDominant=null,this._emotionDampening=0,this._negativeEmotions=new Set(["anger","fear","sadness","disgust","suspicion"]),this.transitions={emotional:{current:"neutral",target:null,progress:0,duration:500,startTime:0,isActive:!1},intensity:{from:1,to:1,progress:1,duration:500,startTime:0,isActive:!1},undertone:{current:null,target:null,progress:0,duration:300,startTime:0,isActive:!1,currentWeight:0,targetWeight:0}},this.interpolationCache={lastUpdate:0,cacheInterval:100,cachedProperties:null,cachedRenderState:null},this.initializeEmotionalStates(),this.initializeUndertoneModifiers()}initializeEmotionalStates(){this.emotionalStates=this.loadEmotionalStatesFromCache()}loadEmotionalStatesFromCache(){const e={};return["neutral","joy","sadness","anger","fear","surprise","disgust","love","suspicion","excited","resting","euphoria","focused","glitch","calm"].forEach(t=>{const i=Ks.getVisualParams(t);i&&(e[t]={primaryColor:i.primaryColor||"#B0B0B0",glowIntensity:i.glowIntensity||.7,particleRate:i.particleRate||1,minParticles:i.minParticles||3,maxParticles:i.maxParticles||4,particleBehavior:i.particleBehavior||"ambient",coreSize:i.coreSize||1,breathRate:i.breathRate||1,breathDepth:i.breathDepth||.1})}),e}initializeUndertoneModifiers(){this.undertoneModifiers={nervous:{jitterAmount:.3,breathRateMultiplier:1.2,glowIntensityMultiplier:.9,particleRateMultiplier:1.1},confident:{coreSizeMultiplier:1.1,glowIntensityMultiplier:1.2,breathRateMultiplier:.9,particleRateMultiplier:1},tired:{breathRateMultiplier:.7,particleRateMultiplier:.5,glowIntensityMultiplier:.8,coreSizeMultiplier:.95},intense:{amplificationFactor:1.3},subdued:{dampeningFactor:.7}}}setEmotion(e,t=null,i=500){return this.errorBoundary.wrap(()=>{let s=null,n=1;if("string"==typeof t?s=t:t&&"object"==typeof t&&(s=t.undertone??null,i=t.duration??i,n=t.intensity??1),this.interpolationCache.cachedProperties=null,this.interpolationCache.cachedRenderState=null,!g(e)&&!{}.hasOwnProperty.call(this.emotionalStates,e)){const t=[...Object.keys(this.emotionalStates),...u()],i=[...new Set(t)];throw new Error(`Invalid emotion: ${e}. Valid emotions: ${i.join(", ")}`)}if(null!==s&&!{}.hasOwnProperty.call(this.undertoneModifiers,s))throw new Error(`Invalid undertone: ${s}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return n=Math.max(0,Math.min(1,n)),this.slots=[{emotion:e,intensity:n}],this._previousDominant=e,this.state.emotion===e&&this.state.undertone===s&&this.state.intensity===n||(this.state.emotion!==e&&(i>0?(this.transitions.emotional={current:this.state.emotion,target:e,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},void 0!==this._simulatedTime&&(this._simulatedTime=0)):this.transitions.emotional={current:e,target:null,progress:1,duration:0,startTime:performance.now(),isActive:!1},this.state.emotion=e),this.state.intensity!==n&&(this.transitions.intensity={from:this.state.intensity,to:n,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},this.state.intensity=n),this.state.undertone!==s&&(this.transitions.undertone={current:this.state.undertone,target:s,progress:0,duration:300,startTime:performance.now(),isActive:!0,currentWeight:this.state.undertone?1:0,targetWeight:s?1:0},this.state.undertone=s)),!0},"emotion-setting",!1)()}setEventCallback(e){this._eventCallback=e}_emitEvent(e,t){this._eventCallback&&this._eventCallback(e,t)}_checkDominantChange(){const e=this.getDominant(),t=e?e.emotion:null,i=this._previousDominant;t!==i&&(this._previousDominant=t,this._emitEvent("dominantChanged",{previous:i,current:t,intensity:e?e.intensity:0}))}setEmotionDampening(e){this._emotionDampening=Math.max(0,Math.min(1,e))}getEmotionDampening(){return this._emotionDampening}setNegativeEmotions(e){this._negativeEmotions=new Set(e)}pushEmotion(e,t=.5){return this.errorBoundary.wrap(()=>{if(!g(e)&&!{}.hasOwnProperty.call(this.emotionalStates,e))return!1;t=Math.max(0,Math.min(1,t)),this.interpolationCache.cachedProperties=null;const i=this.slots.find(t=>t.emotion===e);if(i){const s=i.intensity;i.intensity=Math.min(1,i.intensity+t),this._emitEvent("slotChanged",{emotion:e,intensity:i.intensity,action:"push"}),i.intensity>=1&&s<1&&this._emitEvent("emotionPeaked",{emotion:e,intensity:i.intensity})}else if(this.slots.length<this.maxSlots)this.slots.push({emotion:e,intensity:t}),this._emitEvent("slotChanged",{emotion:e,intensity:t,action:"push"}),t>=1&&this._emitEvent("emotionPeaked",{emotion:e,intensity:t});else{let i=0;for(let e=1;e<this.slots.length;e++)this.slots[e].intensity<this.slots[i].intensity&&(i=e);const s=this.slots[i];this._emitEvent("slotChanged",{emotion:s.emotion,intensity:0,action:"replaced"}),this.slots[i]={emotion:e,intensity:t},this._emitEvent("slotChanged",{emotion:e,intensity:t,action:"push"})}return this._syncDominantToState(),this._checkDominantChange(),!0},"push-emotion",!1)()}nudgeEmotion(e,t,i=1){t>0&&this._emotionDampening>0&&this._negativeEmotions.has(e)&&(t*=1-this._emotionDampening),this.interpolationCache.cachedProperties=null;const s=this.slots.find(t=>t.emotion===e);if(s){const n=s.intensity;s.intensity=Math.max(0,Math.min(i,s.intensity+t)),s.intensity<=0?(this.slots=this.slots.filter(e=>e!==s),this._emitEvent("slotChanged",{emotion:e,intensity:0,action:"removed"})):(this._emitEvent("slotChanged",{emotion:e,intensity:s.intensity,action:"nudge"}),s.intensity>=i&&n<i&&this._emitEvent("emotionPeaked",{emotion:e,intensity:s.intensity}))}else if(t>0)return void this.pushEmotion(e,Math.min(i,t));this._syncDominantToState(),this._checkDominantChange()}clearEmotions(){const e=this.slots.length>0;this.slots=[],this.interpolationCache.cachedProperties=null,this.state.emotion="neutral",this.state.intensity=1,e&&(this._emitEvent("slotChanged",{emotion:null,intensity:0,action:"cleared"}),this._previousDominant=null,this._emitEvent("dominantChanged",{previous:this._previousDominant,current:null,intensity:0}))}getSlots(){return this.slots}pruneEmptySlots(){const e=this.slots.length,t=this.slots.filter(e=>e.intensity<=0);if(this.slots=this.slots.filter(e=>e.intensity>0),this.slots.length!==e){this.interpolationCache.cachedProperties=null;for(const e of t)this._emitEvent("emotionDecayed",{emotion:e.emotion,intensity:0,removed:!0});this._syncDominantToState(),this._checkDominantChange()}}getDominant(){return this.slots.length?this.slots.reduce((e,t)=>t.intensity>e.intensity?t:e):null}getUndercurrents(){const e=this.getDominant();return e?this.slots.filter(t=>t!==e):[]}getEmotionalState(){const e=this.getDominant();return{dominant:e?{...e}:null,undercurrents:this.getUndercurrents().map(e=>({...e})),slots:this.slots.map(e=>({...e}))}}getCurrentRhythmModifiers(){return this.slots.length>0?b(this.slots):b([{emotion:this.state.emotion,intensity:this.state.intensity}])}_syncDominantToState(){const e=this.getDominant();e?(this.state.emotion!==e.emotion&&(this.transitions.emotional={current:this.state.emotion,target:e.emotion,progress:0,duration:300,startTime:performance.now(),isActive:!0},this.state.emotion=e.emotion),this.state.intensity=e.intensity):(this.state.emotion="neutral",this.state.intensity=1)}applyUndertone(e,t){if(!t||!{}.hasOwnProperty.call(this.undertoneModifiers,t))return{...e};const i=this.undertoneModifiers[t],s={...e};if(void 0!==i.glowIntensityMultiplier&&(s.glowIntensity*=i.glowIntensityMultiplier),void 0!==i.breathRateMultiplier&&(s.breathRate*=i.breathRateMultiplier),void 0!==i.particleRateMultiplier&&(s.particleRate=Math.round(s.particleRate*i.particleRateMultiplier)),void 0!==i.coreSizeMultiplier&&(s.coreSize*=i.coreSizeMultiplier),void 0!==i.amplificationFactor){const e=i.amplificationFactor;s.glowIntensity*=e,s.breathRate*=e,s.particleRate=Math.round(s.particleRate*e),s.coreSize*=e}if(void 0!==i.dampeningFactor){const e=i.dampeningFactor;s.glowIntensity*=e,s.breathRate*=e,s.particleRate=Math.round(s.particleRate*e),s.coreSize*=e}return void 0!==i.jitterAmount&&(s.jitterAmount=i.jitterAmount),s}update(e){this.errorBoundary.wrap(()=>{this.transitions.emotional.isActive&&this.updateEmotionalTransition(e),this.transitions.intensity.isActive&&this.updateIntensityTransition(e),this.transitions.undertone.isActive&&this.updateUndertoneTransition(e)},"state-machine-update")()}updateUndertoneTransition(e){const t=this.transitions.undertone,i=performance.now()-t.startTime,s=Math.min(i/t.duration,1),n=Us(s);t.current&&t.target?(t.currentWeight=1-n,t.targetWeight=n):t.current&&!t.target?(t.currentWeight=1-n,t.targetWeight=0):!t.current&&t.target&&(t.currentWeight=0,t.targetWeight=n),t.progress=s,s>=1&&(t.isActive=!1,t.current=t.target,t.currentWeight=t.target?1:0,t.targetWeight=0)}updateIntensityTransition(e){const t=this.transitions.intensity,i=performance.now()-t.startTime;t.progress=Math.min(1,i/t.duration),t.progress>=1&&(t.isActive=!1,t.from=t.to,t.progress=1)}getEffectiveIntensity(){const e=this.transitions.intensity;if(!e.isActive)return this.state.intensity;const t=Us(e.progress);return e.from+(e.to-e.from)*t}updateEmotionalTransition(e){const t=this.transitions.emotional;let i;void 0!==this._simulatedTime?(this._simulatedTime+=e,i=this._simulatedTime):i=performance.now()-t.startTime,t.progress=Math.min(1,i/t.duration),t.progress>=1&&(t.isActive=!1,t.current=t.target,t.target=null,t.progress=1)}getCurrentEmotionalProperties(){return this.errorBoundary.wrap(()=>{const e=performance.now();if(this.interpolationCache.cachedProperties&&e-this.interpolationCache.lastUpdate<this.interpolationCache.cacheInterval)return this.interpolationCache.cachedProperties;let t;if(this.slots.length>1)t=this._blendSlotProperties();else{const e=this.transitions.emotional;t=e.isActive&&e.target?this.interpolateEmotionalProperties(e.current,e.target,e.progress):{...this.emotionalStates[this.state.emotion]||this.emotionalStates.neutral};const i=this.getEffectiveIntensity();i<1&&(t.glowIntensity=this._lerp(.7,t.glowIntensity,i),t.particleRate=Math.round(this._lerp(1,t.particleRate,i)),t.breathRate=this._lerp(1,t.breathRate,i),t.breathDepth=t.breathDepth*i,t.coreSize=this._lerp(1,t.coreSize,i))}return t=this.applyUndertone(t,this.state.undertone),this.interpolationCache.cachedProperties=t,this.interpolationCache.lastUpdate=e,t},"emotional-properties",()=>this.emotionalStates.neutral)()}_blendSlotProperties(){const e=this.getDominant(),t=this.getUndercurrents(),i=this.emotionalStates[e.emotion]||this.emotionalStates.neutral,s={...i},n=e.intensity;s.glowIntensity=.75*this._lerp(.7,i.glowIntensity,n),s.particleRate=i.particleRate*n*.75,s.breathRate=.75*this._lerp(1,i.breathRate,n),s.breathDepth=i.breathDepth*n*.75,s.coreSize=.75*this._lerp(1,i.coreSize,n);const a=t.length>0?.25/t.length:0;for(const e of t){const t=this.emotionalStates[e.emotion]||this.emotionalStates.neutral,i=e.intensity;s.glowIntensity+=this._lerp(.7,t.glowIntensity,i)*a,s.particleRate+=t.particleRate*i*a,s.breathRate+=this._lerp(1,t.breathRate,i)*a,s.breathDepth+=t.breathDepth*i*a,s.coreSize+=this._lerp(1,t.coreSize,i)*a}if(s.particleRate=Math.round(s.particleRate),t.length>0){const e=this.slots.reduce((e,t)=>e+t.intensity,0);let n=i.primaryColor;for(const i of t){const t=this.emotionalStates[i.emotion]||this.emotionalStates.neutral,s=i.intensity/e;n=_s(n,t.primaryColor,s)}s.primaryColor=n}return s.particleBehavior=i.particleBehavior,s}_lerp(e,t,i){return e+(t-e)*i}interpolateEmotionalProperties(e,t,i){const s=this.emotionalStates[e]||this.emotionalStates.neutral,n=this.emotionalStates[t]||this.emotionalStates.neutral,a=Js(i,0,1,"easeOutCubic");return{primaryColor:_s(s.primaryColor,n.primaryColor,a),glowIntensity:s.glowIntensity+(n.glowIntensity-s.glowIntensity)*a,particleRate:Math.round(s.particleRate+(n.particleRate-s.particleRate)*a),coreSize:s.coreSize+(n.coreSize-s.coreSize)*a,breathRate:s.breathRate+(n.breathRate-s.breathRate)*a,breathDepth:s.breathDepth+(n.breathDepth-s.breathDepth)*a,particleBehavior:a>.5?n.particleBehavior:s.particleBehavior}}getCurrentState(){return{emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,isTransitioning:this.transitions.emotional.isActive,transitionProgress:this.transitions.emotional.progress,properties:this.getCurrentEmotionalProperties()}}applyUndertoneModifier(e){return this.errorBoundary.wrap(()=>{if(null!==e&&!{}.hasOwnProperty.call(this.undertoneModifiers,e))throw new Error(`Invalid undertone: ${e}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return this.state.undertone=e,!0},"undertone-application",!1)()}clearUndertone(){this.state.undertone=null}getUndertoneModifier(e){return this.errorBoundary.wrap(()=>{if(this.renderer&&this.renderer.undertoneModifiers&&this.renderer.undertoneModifiers[e])return{...this.renderer.undertoneModifiers[e]};if(!e||!{}.hasOwnProperty.call(this.undertoneModifiers,e))return null;const t={...this.undertoneModifiers[e]};return t.glowRadiusMult||(t.glowRadiusMult=1),t},"undertone-retrieval",null)()}getWeightedUndertoneModifiers(){const e=this.transitions.undertone;if(!e.isActive){if(this.state.undertone){const e=this.getUndertoneModifier(this.state.undertone);if(e)return{...e,weight:1,type:this.state.undertone}}return null}if(e.target){const t=this.getUndertoneModifier(e.target);if(t)return{...t,weight:e.targetWeight,type:e.target}}if(e.current&&e.currentWeight>0){const t=this.getUndertoneModifier(e.current);if(t)return{...t,weight:e.currentWeight,type:e.current}}return null}reset(e=500){this.slots=[],this.setEmotion("neutral",null,e)}isValidEmotion(e){return{}.hasOwnProperty.call(this.emotionalStates,e)}isValidUndertone(e){return null===e||{}.hasOwnProperty.call(this.undertoneModifiers,e)}getAvailableEmotions(){return Object.keys(this.emotionalStates)}getAvailableUndertones(){return Object.keys(this.undertoneModifiers)}isTransitioning(){return this.transitions.emotional.isActive}getTransitionProgress(){return this.transitions.emotional.isActive?this.transitions.emotional.progress:1}completeTransition(){this.transitions.emotional.isActive&&(this.transitions.emotional.progress=1,this.transitions.emotional.isActive=!1,this.transitions.emotional.current=this.transitions.emotional.target,this.transitions.emotional.target=null)}interpolateProperty(e,t,i,s="easeOutCubic"){return e+(t-e)*Js(i,0,1,s)}serialize(){return{version:1,emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,slots:this.slots.map(e=>({...e})),dampening:this._emotionDampening,negativeEmotions:[...this._negativeEmotions]}}deserialize(e){e&&1===e.version&&(this.slots=(e.slots||[]).map(e=>({emotion:e.emotion,intensity:e.intensity})),this._emotionDampening=e.dampening??0,e.negativeEmotions&&(this._negativeEmotions=new Set(e.negativeEmotions)),this.state.emotion=e.emotion||"neutral",this.state.undertone=e.undertone||null,this.state.intensity=e.intensity??1,this._previousDominant=e.emotion||null,this.transitions.emotional.isActive=!1,this.transitions.intensity.isActive=!1,this.transitions.undertone.isActive=!1,this.interpolationCache.cachedProperties=null)}enableSimulatedTime(e=!0){e?this._simulatedTime=0:delete this._simulatedTime}}const en=16.67,tn=3e4;let sn;"undefined"!=typeof window&&window.__emotiveRhythmEngine?sn=window.__emotiveRhythmEngine:(sn=new class{constructor(){this.bpm=120,this.timeSignature=[4,4],this.isPlaying=!1,this.startTime=0,this.currentBeat=0,this.currentBar=0,this.beatProgress=0,this.barProgress=0,this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.lastBeatTime=0,this.nextBeatTime=0,this.listeners=new Map,this.beatCallbacks=new Set,this.barCallbacks=new Set,this.subdivisions={sixteenth:0,eighth:0,triplet:0,swing:0},this.audioSync=null,this.syncOffset=0,this.autoSync=!1,this.intensity=1,this.groove=0,this.humanize=.05,this.patterns=new Map,this.currentPattern=null,this.initializePatterns()}initializePatterns(){this.patterns.set("4/4",{name:"4/4",description:"Common time - 4 beats per bar",timeSignature:[4,4],groove:0,accents:[1,.5,.7,.5]}),this.patterns.set("straight",{name:"straight",description:"Straight, even timing",groove:0,accents:[1,.5,.7,.5]}),this.patterns.set("swing",{name:"swing",description:"Swing/shuffle timing",groove:.67,accents:[1,.3,.8,.3]}),this.patterns.set("3/4",{name:"3/4",description:"Waltz time - 3 beats per bar",timeSignature:[3,4],accents:[1,.5,.5]}),this.patterns.set("waltz",{name:"waltz",description:"3/4 waltz timing",timeSignature:[3,4],accents:[1,.5,.5]}),this.patterns.set("6/8",{name:"6/8",description:"Compound duple time",timeSignature:[6,8],accents:[1,.3,.3,.7,.3,.3]}),this.patterns.set("5/4",{name:"5/4",description:"Complex meter - 5 beats per bar",timeSignature:[5,4],accents:[1,.5,.6,.5,.7]}),this.patterns.set("7/8",{name:"7/8",description:"Irregular meter",timeSignature:[7,8],accents:[1,.5,.5,.7,.5,.5,.6]}),this.patterns.set("dubstep",{name:"dubstep",description:"Dubstep half-time feel",accents:[.2,.2,1,.2],subdivisions:{wobble:!0}}),this.patterns.set("breakbeat",{name:"breakbeat",description:"Broken beat pattern",accents:[1,.2,.7,.9,.2,.8,.4,.2]})}start(){this.isPlaying||(this.isPlaying=!0,this.isRunning=!0,this.startTime=performance.now(),this.lastBeatTime=this.startTime,this.nextBeatTime=this.startTime+this.beatDuration,this.currentBeat=0,this.currentBar=0,this.emit("start",{bpm:this.bpm,timeSignature:this.timeSignature,pattern:this.currentPattern}),this.update())}stop(){this.isPlaying&&(this.isPlaying=!1,this.emit("stop",{totalBeats:this.currentBeat,totalBars:this.currentBar}))}update(){if(!this.isPlaying)return;const e=(performance.now()-this.startTime)/this.beatDuration,t=Math.floor(e);this.beatProgress=e%1,t>this.currentBeat&&this.onBeat(t);const i=Math.floor(t/this.timeSignature[0]);i>this.currentBar&&this.onBar(i),this.currentBeat=t,this.currentBar=i,this.barProgress=t%this.timeSignature[0]/this.timeSignature[0],this.updateSubdivisions(),this.emit("update",this.getTimeInfo()),this.isPlaying&&requestAnimationFrame(()=>this.update())}onBeat(e){const t=e%this.timeSignature[0],i=this.getAccent(t),s=this.humanize*(Math.random()-.5)*this.beatDuration,n={beat:e,beatInBar:t,bar:this.currentBar,accent:i,intensity:this.intensity*i,humanTiming:s,timestamp:performance.now()};this.emit("beat",n),this.beatCallbacks.forEach(e=>e(n)),this.lastBeatTime=performance.now(),this.nextBeatTime=this.lastBeatTime+this.beatDuration}onBar(e){const t={bar:e,timeSignature:this.timeSignature,pattern:this.currentPattern,timestamp:performance.now()};this.emit("bar",t),this.barCallbacks.forEach(e=>e(t))}updateSubdivisions(){if(this.subdivisions.sixteenth=4*this.beatProgress%1,this.subdivisions.eighth=2*this.beatProgress%1,this.subdivisions.triplet=3*this.beatProgress%1,this.groove>0){const e=.5+.17*this.groove;this.subdivisions.eighth<.5?this.subdivisions.swing=this.subdivisions.eighth/e:this.subdivisions.swing=.5+(this.subdivisions.eighth-.5)/(1-e)}else this.subdivisions.swing=this.subdivisions.eighth}getAccent(e){if(this.currentPattern&&this.patterns.has(this.currentPattern)){const t=this.patterns.get(this.currentPattern);if(t.accents&&void 0!==t.accents[e])return t.accents[e]}return 0===e?1:2===e&&4===this.timeSignature[0]?.7:.5}getTimeInfo(){return{elapsed:performance.now()-this.startTime,beat:this.currentBeat,bar:this.currentBar,beatInBar:this.currentBeat%this.timeSignature[0],beatProgress:this.beatProgress,barProgress:this.barProgress,subdivisions:{...this.subdivisions},bpm:this.bpm,beatDuration:this.beatDuration,timeSignature:[...this.timeSignature],intensity:this.intensity,groove:this.groove,pattern:this.currentPattern,nextBeatIn:this.nextBeatTime-performance.now(),accent:this.getAccent(this.currentBeat%this.timeSignature[0])}}setBPM(e){this.bpm=Math.max(20,Math.min(360,e)),this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.emit("tempoChange",{bpm:this.bpm})}setTimeSignature(e,t){this.timeSignature=[e,t],this.barDuration=this.beatDuration*e,this.emit("timeSignatureChange",{timeSignature:this.timeSignature})}setPattern(e){if(!this.patterns.has(e))return;const t=this.patterns.get(e);this.currentPattern=e,t.timeSignature&&this.setTimeSignature(...t.timeSignature),void 0!==t.groove&&(this.groove=t.groove),this.emit("patternChange",{pattern:e})}onBeatCallback(e){return this.beatCallbacks.add(e),()=>this.beatCallbacks.delete(e)}onBarCallback(e){return this.barCallbacks.add(e),()=>this.barCallbacks.delete(e)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(e=>e(t))}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.has(e)&&this.listeners.get(e).delete(t)}}syncToAudio(e,t){this._syncToAudioWarned||(console.warn("[Rhythm] syncToAudio() is not yet implemented"),this._syncToAudioWarned=!0),this.audioSync={context:e,source:t}}getAdapter(){return{getTimeInfo:()=>this.getTimeInfo(),isOnBeat:(e=.1)=>this.beatProgress<e||this.beatProgress>1-e,isOnSubdivision:(e,t=.1)=>{const i=this.subdivisions[e]||0;return i<t||i>1-t},getBeatSync:(e=0,t=1,i="linear")=>{let s=this.beatProgress;switch(i){case"ease":s=.5-Math.cos(s*Math.PI)/2;break;case"bounce":s=Math.abs(Math.sin(s*Math.PI));break;case"pulse":s=Math.pow(Math.sin(s*Math.PI),2)}return e+(t-e)*s},getAccentedValue:(e,t=2)=>e*(1+(this.getAccent(this.currentBeat%this.timeSignature[0])-.5)*t),onBeat:e=>this.onBeatCallback(e),onBar:e=>this.onBarCallback(e),beatsToMs:e=>e*this.beatDuration,msToBeats:e=>e/this.beatDuration,isPlaying:()=>this.isPlaying,getBPM:()=>this.bpm,getPattern:()=>this.currentPattern}}},"undefined"!=typeof window&&(window.__emotiveRhythmEngine=sn));class nn{constructor(e,t={}){this._adapter=e,this._windows={perfect:t.windows?.perfect??30,great:t.windows?.great??60,good:t.windows?.good??100},this._grades={perfect:{multiplier:2,label:"Perfect"},great:{multiplier:1.5,label:"Great"},good:{multiplier:1,label:"Good"},miss:{multiplier:0,label:"Miss"}},this._windowModifiers={multiplier:1},this._emotionSource=t.emotionSource??null,this._history=[],this._maxHistory=100,this._onEvaluate=[],this._emotionFeedback=null,this._emotionTarget=null,this._difficultyManager=null}evaluate(e=performance.now()){const t=this._adapter.getTimeInfo(),{beatDuration:i}=t,s=performance.now()-t.elapsed,n=e-s,a=n-n%i,r=a+i,o=n-a<r-n?a:r,l=n-o;return this._gradeOffset(l,e,o+s)}evaluateAgainst(e,t){return this._gradeOffset(e-t,e,t)}evaluateSequence(e,t){const i=[],s=new Set;for(const n of e){let e=-1,a=1/0;for(let i=0;i<t.length;i++){if(s.has(i))continue;const r=Math.abs(n-t[i]);r<a&&(a=r,e=i)}e>=0?(s.add(e),i.push(this.evaluateAgainst(n,t[e]))):i.push({grade:"miss",offset:0,absOffset:0,multiplier:0,label:"Miss",timestamp:n,targetTime:null})}return i}_gradeOffset(e,t,i){if(this._difficultyManager&&this._difficultyManager.autoRhythm)return this._recordResult("good",e,t,i);const s=Math.abs(e),n=this._emotionSource?.()??{windowMultiplier:1},a=this._difficultyManager?this._difficultyManager.getWindowMultiplier():1,r=this._windowModifiers.multiplier*(n.windowMultiplier||1)*a;let o;return o=s<=this._windows.perfect*r?"perfect":s<=this._windows.great*r?"great":s<=this._windows.good*r?"good":"miss",this._recordResult(o,e,t,i)}_recordResult(e,t,i,s){const n={grade:e,offset:t,absOffset:Math.abs(t),multiplier:this._grades[e].multiplier,label:this._grades[e].label,timestamp:i,targetTime:s};this._history.push(n),this._history.length>this._maxHistory&&this._history.shift();for(const e of this._onEvaluate)e(n);if(this._emotionFeedback&&this._emotionTarget){const t=this._emotionFeedback[e];t&&this._emotionTarget(t.emotion,t.delta)}return n}setWindowModifier(e){this._windowModifiers.multiplier=Math.max(.3,Math.min(3,e))}setEmotionSource(e){this._emotionSource=e}getAccuracy(){if(!this._history.length)return{perfect:0,great:0,good:0,miss:0,averageOffset:0,total:0};const e={perfect:0,great:0,good:0,miss:0};let t=0;for(const i of this._history)e[i.grade]++,t+=i.offset;return{...e,averageOffset:t/this._history.length,total:this._history.length}}getHistory(){return[...this._history]}clearHistory(){this._history.length=0}onEvaluate(e){return this._onEvaluate.push(e),()=>{this._onEvaluate=this._onEvaluate.filter(t=>t!==e)}}setEmotionFeedback(e){this._emotionFeedback=e||null}setEmotionTarget(e){this._emotionTarget=e||null}setDifficultyManager(e){this._difficultyManager=e||null}setWindows(e){Object.assign(this._windows,e)}setGrades(e){Object.assign(this._grades,e)}destroy(){this._history.length=0,this._onEvaluate.length=0}}const an=new class{constructor(){this.enabled=!1,this.adapter=null,this.subsystemConfigs=new Map,this.activeModulations=new Map,this._inputEvaluator=null,this._unsubBeat=null,this._unsubBar=null}initialize(){this.adapter=sn.getAdapter(),this.enabled=!0,this._unsubBeat=this.adapter.onBeat(this.handleBeat.bind(this)),this._unsubBar=this.adapter.onBar(this.handleBar.bind(this))}updateBPM(e){if(e>=60&&e<=220){if(window.rhythmManuallyStoppedForCurrentAudio)return;if(!sn.isRunning)return this.start(e,"straight"),void(window.rhythmSyncVisualizer&&!window.rhythmSyncVisualizer.state.active&&window.rhythmSyncVisualizer.start());sn.setBPM(e)}}registerConfig(e,t,i){if(!i.rhythm||!i.rhythm.enabled)return;const s=`${e}:${t}`;this.subsystemConfigs.set(s,{type:e,name:t,rhythmConfig:i.rhythm,originalConfig:i})}applyGestureRhythm(e,t,i,s){if(!this.enabled||!e.rhythm?.enabled)return{};const n=e.rhythm,a={};if(n.amplitudeSync){const e=n.amplitudeSync,t=this.adapter.getBeatSync(e.offBeat||.8,e.onBeat||1.5,e.curve||"linear");a.amplitudeMultiplier=t}if(n.wobbleSync){const e=n.wobbleSync;this.adapter.isOnSubdivision(e.subdivision,.1)?a.wobbleMultiplier=1+e.intensity:a.wobbleMultiplier=1}if(n.accentResponse?.enabled){const e=this.adapter.getAccentedValue(1,n.accentResponse.multiplier||1.5);a.accentMultiplier=e}const r=this.adapter.getPattern();return r&&n.patternOverrides?.[r]&&Object.assign(a,n.patternOverrides[r]),a}applyParticleRhythm(e,t){if(!this.enabled||!e.rhythm?.enabled)return{};const i=this.adapter.getTimeInfo(),s=e.rhythm,n={};if(s.particleEmission){const e=s.particleEmission;"beat"===e.syncMode&&this.adapter.isOnBeat(.1)?n.emitBurst=e.burstSize||3:void 0!==e.offBeatRate&&(n.emissionRate=e.offBeatRate)}if(s.glowSync){const e=s.glowSync,t=this.adapter.getBeatSync(e.intensityRange[0]||1,e.intensityRange[1]||2,"pulse");n.glowIntensity=t}if("bars"===s.breathSync?.mode){const e=s.breathSync,t=i.bar%e.barsPerBreath/e.barsPerBreath;n.breathPhase=t*Math.PI*2}return n}applyBehaviorRhythm(e,t,i){if(!this.enabled||!e.rhythm?.enabled)return{};const s=this.adapter.getTimeInfo(),n=e.rhythm,a={};if(n.glitchTiming){const e=n.glitchTiming;if(this.adapter.isOnSubdivision(e.subdivision,.05)&&Math.random()<e.probability){const t=this.adapter.isOnBeat()?e.intensityOnBeat:e.intensityOffBeat;a.triggerGlitch=!0,a.glitchIntensity=t}}if(n.orbitRhythm){const e=n.orbitRhythm;"tempo"===e.baseSpeed&&(a.speedMultiplier=this.adapter.getBPM()/120),e.beatAcceleration&&this.adapter.isOnBeat(.1)&&(a.speedBoost=e.beatAcceleration),e.barReset&&0===s.beatInBar&&(a.resetOrbit=!0)}if(n.stutterSync){const e=n.stutterSync,t=this.adapter.getPattern();if(t&&e.patterns?.[t]){const i=e.patterns[t];i.freezeOnDrop&&2===s.beatInBar?(a.freeze=!0,a.freezeDuration=i.dropDuration):i.randomFreeze&&Math.random()<i.randomFreeze&&(a.freeze=!0,a.freezeDuration=i.duration)}}return a}handleBeat(e){this.lastBeatInfo=e}handleBar(e){this.lastBarInfo=e}getMusicalDuration(e,t){if(!this.enabled||!e?.durationSync)return t;const i=e.durationSync;return"bars"===i.mode?this.adapter.beatsToMs(4*i.bars):"beats"===i.mode?this.adapter.beatsToMs(i.beats):t}isEnabled(){return this.enabled&&this.adapter.isPlaying()}start(e=120,t="straight"){e&&sn.setBPM(e),t&&sn.setPattern(t),sn.start(),this.enabled=!0}stop(){sn.stop(),this.enabled=!1,this.bpmLocked=!1,this.lockedBPM=null}destroy(){this.stop(),this._unsubBeat&&(this._unsubBeat(),this._unsubBeat=null),this._unsubBar&&(this._unsubBar(),this._unsubBar=null),this.enabled=!1,this.adapter=null,this.subsystemConfigs.clear(),this.activeModulations.clear(),this.lastBeatInfo=null,this.lastBarInfo=null,this._inputEvaluator=null}setPattern(e){sn.setPattern(e)}setBPM(e){sn.setBPM(e),this.bpmLocked&&(this.lockedBPM=e)}resampleBPM(){this.bpmLocked=!1,this.lockedBPM=null}setTimeSignature(e){this.timeSignature=e;const t=document.getElementById("time-sig-display");t&&(t.textContent=e),"3/4"===e&&sn.getPattern()}getInputEvaluator(e){return this._inputEvaluator||(this.adapter||this.initialize(),this._inputEvaluator=new nn(this.adapter,e)),this._inputEvaluator}getEffectiveBPM(e){if(!this.adapter)return 120;let t=this.adapter.getBPM();if(e&&"function"==typeof e.getCurrentRhythmModifiers){const i=e.getCurrentRhythmModifiers();i.tempoShift&&(t*=1+i.tempoShift)}return Math.round(100*t)/100}syncToAudio(e,t){sn.syncToAudio(e,t)}};class rn{constructor(e,t,i="ambient",s=1,n=1,a=null){const r=Math.random();this.z=r<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,l=Math.random()*Math.PI*2;this.x=e+Math.cos(l)*o,this.y=t+Math.sin(l)*o,this.vx=0,this.vy=0,this.vz=0,this.life=0,this.maxLife=1,this.lifeDecay=.01,this.fadeInTime=.15,this.fadeOutTime=.3,this.isFadingOut=!1,this.age=0,this.scaleFactor=s,this.particleSizeMultiplier=n,this.size=(4+6*Math.random())*s*n,this.baseSize=this.size,this.emotionColors=a,this.color="#ffffff",this.opacity=1,this.hasGlow=Math.random()<.333,this.glowSizeMultiplier=this.hasGlow?1.33+.33*Math.random():0,this.isCellShaded=Math.random()<.333,this.baseOpacity=.3+.4*Math.random(),this.cachedColors=new Map,this.maxCachedColors=20,this.colorAccessOrder=[],this.lastColor=null,this.lastOpacity=-1,this.behavior=i,this.behaviorData={},this.gestureData={initialX:e,initialY:t},fs(this,i)}update(e,t,i,s=null,n=null,a=0,r=null){const o=Math.min(e,50)/en,l=n&&n.type&&a>0&&_i(n.type),h=this.rainData||"falling"===this.gestureBehavior||this.fallingData||this.gestureData?.rain,c=l||h;if(c||(this.x+=this.vx*o,this.y+=this.vy*o),!c){let e,s;if(r)e=r.width,s=r.height;else{const n=document.getElementById("card-mascot")||document.getElementById("cherokee-guide-mascot")||document.querySelector("canvas");e=n?n.width:2*t,s=n?n.height:2*i}const n=20,a=t-e/2+n,o=t+e/2+n,l=i-s/2+n,h=i+s/2-n;this.x-this.size<a?(this.x=a+this.size,this.vx=.5*Math.abs(this.vx)):this.x+this.size>o&&(this.x=o-this.size,this.vx=.5*-Math.abs(this.vx)),this.y-this.size<l?(this.y=l+this.size,this.vy=.5*Math.abs(this.vy)):this.y+this.size>h&&(this.y=h-this.size,this.vy=.5*-Math.abs(this.vy))}this.age+=this.lifeDecay*o,this.age<this.fadeInTime?this.life=this.age/this.fadeInTime:this.age<1-this.fadeOutTime?this.life=1:(this.life=(1-this.age)/this.fadeOutTime,this.isFadingOut=!0,"popcorn"===this.behavior&&(this.size=this.baseSize*(.5+.5*this.life))),this.life=Math.max(0,Math.min(1,this.life)),"falling"===this.behavior?this.opacity=this.life:this.opacity=this.easeInOutCubic(this.life),"burst"===this.behavior&&this.behaviorData&&this.life<this.behaviorData.fadeStart&&(this.size=this.baseSize*(this.life/this.behaviorData.fadeStart))}applyUndertoneModifier(e,t){}applyGestureMotion(e,t,i,s,n){!function(e,t,i,s,n,a){if(!i||!i.type||s>=1)return;e.gestureData||(e.gestureData={originalVx:e.vx,originalVy:e.vy,initialX:e.x,initialY:e.y,startAngle:Math.atan2(e.y-a,e.x-n),startRadius:Math.sqrt(Math.pow(e.x-n,2)+Math.pow(e.y-a,2))});const r=Ai(i.type);if(!r)return;let o=i;if(an.isEnabled()&&r.rhythm?.enabled){const n=an.applyGestureRhythm(r,e,s,t);o={...i,amplitude:(i.amplitude||1)*(n.amplitudeMultiplier||1)*(n.accentMultiplier||1),wobbleAmount:(i.wobbleAmount||0)*(n.wobbleMultiplier||1),rhythmModulation:n}}r.apply&&r.apply(e,s,o,t,n,a),s>=.99&&r.cleanup&&(r.cleanup(e),e.gestureData=null)}(this,i,e,t,s,n)}isOutOfBounds(e,t){return this.x<-50||this.x>e+50||this.y<-50||this.y>t+50}isAlive(){return this.life>0}setOutwardVelocity(e){if(this.behaviorData&&void 0!==this.behaviorData.outwardSpeed){const t=this.behaviorData.outwardSpeed;this.vx=Math.cos(e)*t,this.vy=Math.sin(e)*t+(this.behaviorData.upwardBias||0)}}getDepthAdjustedSize(){const e=1+.2*this.z;return this.size*e}getState(){return{position:{x:this.x,y:this.y,z:this.z},velocity:{x:this.vx,y:this.vy,z:this.vz},life:this.life,behavior:this.behavior,size:this.size,opacity:this.opacity}}reset(e,t,i="ambient",s=1,n=1,a=null){const r=Math.random();this.z=r<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,l=Math.random()*Math.PI*2;if(this.x=e+Math.cos(l)*o,this.y=t+Math.sin(l)*o,this.vx=0,this.vy=0,this.vz=0,this.life=0,this.age=0,this.scaleFactor=s,this.particleSizeMultiplier=n,this.size=(4+6*Math.random())*s*n,this.baseSize=this.size,this.emotionColors=a,this.cachedColors.clear(),this.colorAccessOrder=[],this.opacity=0,this.isFadingOut=!1,this.baseOpacity=.3+.4*Math.random(),this.color="#ffffff",this.behavior=i,this.gestureData=null,this.behaviorData)for(const e in this.behaviorData)delete this.behaviorData[e];else this.behaviorData={};fs(this,i)}getCachedColor(e,t){const i=Math.round(100*t)/100,s=`${e}_${i}`;if(this.cachedColors.has(s)){const e=this.colorAccessOrder.indexOf(s);-1!==e&&this.colorAccessOrder.splice(e,1),this.colorAccessOrder.push(s)}else{if(this.cachedColors.size>=this.maxCachedColors){const e=this.colorAccessOrder.shift();this.cachedColors.delete(e)}this.cachedColors.set(s,this.hexToRgba(e,i)),this.colorAccessOrder.push(s)}return this.cachedColors.get(s)}hexToRgba(e,t){const i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return i?`rgba(${parseInt(i[1],16)}, ${parseInt(i[2],16)}, ${parseInt(i[3],16)}, ${t})`:`rgba(255, 255, 255, ${t})`}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}render(e,t="#ffffff"){if(this.life<=0)return;if(!isFinite(this.x)||!isFinite(this.y))return;const i=this.x,s=this.y,n=Math.max(.1,this.size),a=this.tempColor||this.color||t;if(e.save(),this.isCellShaded){e.strokeStyle=this.getCachedColor(a,.9*this.opacity),e.lineWidth=2,e.beginPath(),e.arc(i,s,n,0,2*Math.PI),e.stroke();const t=Math.floor(3*this.opacity)/3;e.fillStyle=this.getCachedColor(a,t*(this.baseOpacity||.5)*.5),e.beginPath(),e.arc(i,s,Math.max(.1,n-1),0,2*Math.PI),e.fill(),t>.5&&(e.fillStyle=this.getCachedColor("#FFFFFF",.3),e.beginPath(),e.arc(i-.3*n,s-.3*n,.3*n,0,2*Math.PI),e.fill())}else{const t=e.createRadialGradient(i,s,0,i,s,n);if(t.addColorStop(0,this.getCachedColor(a,this.opacity*(this.baseOpacity||.5))),t.addColorStop(.5,this.getCachedColor(a,this.opacity*(this.baseOpacity||.5)*.5)),t.addColorStop(1,this.getCachedColor(a,0)),e.fillStyle=t,e.beginPath(),e.arc(i,s,n,0,2*Math.PI),e.fill(),this.hasGlow&&this.glowSizeMultiplier>0){const t=n*this.glowSizeMultiplier,r=e.createRadialGradient(i,s,.5*n,i,s,t),o=.3,l=Math.max(o,this.opacity),h=Math.min(1,this.glowSizeMultiplier/3);r.addColorStop(0,this.getCachedColor(a,Math.max(.5,.8*l)*h)),r.addColorStop(.25,this.getCachedColor(a,Math.max(.3,.6*l)*h)),r.addColorStop(.5,this.getCachedColor(a,Math.max(.2,.4*l)*h)),r.addColorStop(.75,this.getCachedColor(a,Math.max(.1,.2*l)*h)),r.addColorStop(1,this.getCachedColor(a,0)),e.save(),e.globalCompositeOperation="screen",e.fillStyle=r,e.beginPath(),e.arc(i,s,t,0,2*Math.PI),e.fill(),e.restore()}}e.restore()}}class on{constructor(e=50){this.poolSize=Math.min(e,50),this.pool=[],this.totalParticlesCreated=0,this.totalParticlesDestroyed=0,this.poolHits=0,this.poolMisses=0}getParticle(e,t,i,s,n,a,r,o=null){let l;return this.pool.length>0?(l=this.pool.pop(),l.reset(e,t,i,s,n,a),this.poolHits++):(l=new rn(e,t,i,s,n,a),this.poolMisses++,this.totalParticlesCreated++),l.emotion=r,o&&(l.gestureBehavior=o),l}returnParticle(e){if(this.pool.length<this.poolSize){if(e.cachedGradient=null,e.cachedGradientKey=null,e.behaviorData)for(const t in e.behaviorData)delete e.behaviorData[t];this.pool.push(e)}else this.totalParticlesDestroyed++}refreshPool(){const e=this.pool.length-this.poolSize;e>0&&(this.pool.splice(this.poolSize),this.totalParticlesDestroyed+=e)}getStats(){return{poolSize:this.pool.length,poolHits:this.poolHits,poolMisses:this.poolMisses,totalCreated:this.totalParticlesCreated,totalDestroyed:this.totalParticlesDestroyed}}clear(){this.pool=[],this.poolHits=0,this.poolMisses=0,this.totalParticlesCreated=0,this.totalParticlesDestroyed=0}}class ln{constructor(){this.spawnAccumulator=0}getSpawnPosition(e,t,i,s,n,a=null){const r=Math.min(s,n)/12,o=2.5*r,l=1.1*o,h=Math.min(t-30,s-t-30),c=Math.min(i-30,n-i-30),u=Math.min(1.5*o,h,c);switch(e){case"ambient":case"resting":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"ascending":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"rising":{const e=Math.random()*Math.PI*2,s=l+Math.random()*(u-l);return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"falling":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"aggressive":{const e=Math.random()*Math.PI*2,s=o+Math.random()*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"scattering":default:return{x:t,y:i};case"burst":{const e=Math.random()*Math.PI*2;if("suspicion"===a){const s=1.5*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}if("surprise"===a){const s=1.2*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}return{x:t,y:i}}case"repelling":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"orbiting":{const e=Math.random()*Math.PI*2,s=1.2*o+Math.random()*o*.5;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"glitchy":{const e=Math.random()*Math.PI*2,s=3*o+Math.random()*o*4;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"spaz":{const e=Math.random()*Math.PI*2,s=2*o+Math.random()*o*3;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}}}clampToCanvas(e,t,i,s,n=30){return{x:Math.max(n,Math.min(i-n,e)),y:Math.max(n,Math.min(s-n,t))}}calculateSpawnRate(e,t){if(e<=0)return 0;const i=Math.min(t,50),s=e/1e3;this.spawnAccumulator+=s*i,this.spawnAccumulator=Math.min(this.spawnAccumulator,3);let n=0;for(;this.spawnAccumulator>=1;)n++,this.spawnAccumulator-=1;return n}resetAccumulator(){this.spawnAccumulator=0}}class hn{render(e,t,i="#ffffff",s=null){const n=[];for(const e of t)e.life<=0||n.push(e);this._renderParticles(e,n,i,s)}renderLayer(e,t,i="#ffffff",s=!1,n=null){const a=[],r=e.canvas.width,o=e.canvas.height;for(const e of t)e.z>=0===s&&(e.x<-50||e.x>r+50||e.y<-50||e.y>o+50||e.life<=0||a.push(e));return a.sort((e,t)=>e.isCellShaded!==t.isCellShaded?e.isCellShaded?-1:1:e.hasGlow!==t.hasGlow?e.hasGlow?-1:1:0),this._renderParticles(e,a,i,n),a}_renderParticles(e,t,i,s=null){e.save();let n=null;for(const a of t)if(a.isCellShaded)a.render(e,i),n=null;else{const t=a.color||i;if(t!==n&&(e.fillStyle=t,n=t),!isFinite(a.x)||!isFinite(a.y))continue;const r=a.getDepthAdjustedSize?a.getDepthAdjustedSize():a.size;let o=Math.max(.1,r),l=1;if(s&&s.fireflyEffect){const e=(.01*a.x+.01*a.y+.1*a.size)%(2*Math.PI),t=s.fireflyTime||.001*Date.now(),i=s.particleGlow||2;l=.3+Math.max(0,Math.sin(3*t+e))*i}if(s&&s.flickerEffect){const e=(.02*a.x+.02*a.y)%(2*Math.PI),t=s.flickerTime||.001*Date.now(),i=s.particleGlow||2;l=.5+Math.sin(12*t+e)*i*.5}if(s&&s.shimmerEffect){const t=a.x-e.canvas.width/2,i=a.y-e.canvas.height/2,n=Math.sqrt(t*t+i*i)/200,r=s.shimmerTime||.001*Date.now(),o=s.shimmerWave||0,h=s.particleGlow||1.2;l=1+.15*Math.sin(3*r-n+o)*h}if(s&&s.glowEffect){const t=s.glowProgress||0,i=s.particleGlow||2,n=a.x-e.canvas.width/2,r=a.y-e.canvas.height/2,l=Math.sqrt(n*n+r*r)/300,h=Math.min(.3*l,.5),c=Math.max(0,(t-h)/(1-h)),u=Math.sin(c*Math.PI);a._originalGlow||(a._originalGlow={hasGlow:a.hasGlow,glowSizeMultiplier:a.glowSizeMultiplier||0}),a.hasGlow=!0,a.glowSizeMultiplier=Math.max(3,a._originalGlow.glowSizeMultiplier)+u*i*3,o*=1+.3*u,t>=.99&&a._originalGlow&&(a.hasGlow=a._originalGlow.hasGlow,a.glowSizeMultiplier=a._originalGlow.glowSizeMultiplier,delete a._originalGlow)}if(a.hasGlow||l>1){const t=Math.max(.1,o*(a.glowSizeMultiplier||1.5)*l),i=e.globalCompositeOperation;e.globalCompositeOperation="screen",e.globalAlpha=.15*a.opacity*l,e.beginPath(),e.arc(a.x,a.y,t,0,2*Math.PI),e.fill(),e.globalAlpha=.25*a.opacity*l,e.beginPath(),e.arc(a.x,a.y,.6*t,0,2*Math.PI),e.fill(),e.globalCompositeOperation=i}e.globalAlpha=a.opacity*(a.baseOpacity||.5)*.6*Math.min(2,l),e.beginPath(),e.arc(a.x,a.y,o,0,2*Math.PI),e.fill()}e.restore()}}class cn{constructor(e=50,t=null){this.errorBoundary=t,this.maxParticles=e,this.absoluteMaxParticles=2*e,this.particles=[],this.particlePool=new on(e),this.particleSpawner=new ln,this.particleRenderer=new hn,this.containmentBounds=null,this.stateChangeCount=0,this.lastMemoryCheck=Date.now(),this.lastLeakedCount=0,this.particleCount=0,this.cleanupTimer=0,this.cleanupInterval=5e3}get pool(){return this.particlePool.pool}get poolSize(){return this.particlePool.poolSize}get poolHits(){return this.particlePool.poolHits}get poolMisses(){return this.particlePool.poolMisses}get totalParticlesCreated(){return this.particlePool.totalParticlesCreated}get totalParticlesDestroyed(){return this.particlePool.totalParticlesDestroyed}get spawnAccumulator(){return this.particleSpawner.spawnAccumulator}set spawnAccumulator(e){this.particleSpawner.spawnAccumulator=e}getParticleFromPool(e,t,i){return this.particlePool.getParticle(e,t,i,this.scaleFactor||1,this.particleSizeMultiplier||1,this.currentEmotionColors,this.currentEmotion,this.gestureBehavior)}returnParticleToPool(e){this.particlePool.returnParticle(e)}spawn(e,t,i,s,n,a,r=null,o=0,l=10,h=1,c=1,u=null,d=null){if(this.scaleFactor=h,this.particleSizeMultiplier=c,this.errorBoundary)return this.errorBoundary.wrap(()=>{this._spawn(e,t,i,s,n,a,r,o,l,u,d)},"particle-spawn")();this._spawn(e,t,i,s,n,a,r,o,l,u,d)}resetAccumulator(){this.particleSpawner.resetAccumulator()}_spawn(e,t,i,s,n,a,r,o=0,h=10,c=null,u=null){this.currentEmotion=t,this.baseEmotionColors=c,this.currentUndertone=u,this.currentEmotionColors=c&&u?Fs(c,u):c;let d=i;if(an.isEnabled()){const i=Ks&&Ks.isInitialized?Ks.getEmotion(t):l(t);if(i){const t=an.applyParticleRhythm(i,this);if(t.emitBurst)for(let i=0;i<t.emitBurst&&this.particles.length<h;i++)this.spawnSingleParticle(e,s,n);void 0!==t.emissionRate&&(d*=t.emissionRate)}}if(null!==r){for(let t=0;t<r&&this.particles.length<this.maxParticles;t++)this.spawnSingleParticle(e,s,n);return}if(this.skipSpawnThisFrame)return;for(;this.particles.length<o&&this.particles.length<this.maxParticles;)this.spawnSingleParticle(e,s,n);if(this.particles.length>=h)return;if(d<=0)return;const g=this.particleSpawner.calculateSpawnRate(d,a);for(let t=0;t<g&&this.particles.length<h;t++)this.spawnSingleParticle(e,s,n)}getSpawnPosition(e,t,i,s,n){return this._deprecationWarned_getSpawnPosition||(this._deprecationWarned_getSpawnPosition=!0,console.warn("[ParticleSystem] getSpawnPosition() is deprecated. Use particleSpawner.getSpawnPosition() instead.")),this.particleSpawner.getSpawnPosition(e,t,i,s,n,this.currentEmotion)}clampToCanvas(e,t,i,s,n=30){return this._deprecationWarned_clampToCanvas||(this._deprecationWarned_clampToCanvas=!0,console.warn("[ParticleSystem] clampToCanvas() is deprecated. Use particleSpawner.clampToCanvas() instead.")),this.particleSpawner.clampToCanvas(e,t,i,s,n)}spawnSingleParticle(e,t,i){if(this.particles.length>=this.absoluteMaxParticles)return;const s=this.canvasWidth||2*t,n=this.canvasHeight||2*i,a=this.particleSpawner.getSpawnPosition(e,t,i,s,n,this.currentEmotion),r=this.particleSpawner.clampToCanvas(a.x,a.y,s,n);a.x=r.x,a.y=r.y;const o=this.getParticleFromPool(a.x,a.y,e);"meditation_swirl"===e&&a.palmCenter&&(o.palmCenter=a.palmCenter,o.swirlAngle=a.swirlAngle),this.particles.push(o),this.particleCount++}update(e,t,i,s=null,n=0,a=null){if(this.errorBoundary)return this.errorBoundary.wrap((e,t,i,s,n,a)=>this._update(e,t,i,s,n,a),"particle-update")(e,t,i,s,n,a);this._update(e,t,i,s,n,a)}_update(e,t,i,s=null,n=0,a=null){for(let r=this.particles.length-1;r>=0;r--)this.particles[r].update(e,t,i,a,s,n,this.containmentBounds),this.particles[r].isAlive()||this.removeParticle(r);for(;this.particles.length>this.maxParticles;)this.removeParticle(0)}setGestureBehavior(e,t){this.gestureBehavior=t?e:null,t?this.particles.forEach(t=>{t.gestureBehavior=e}):this.particles.forEach(e=>{e.gestureBehavior=null})}removeParticle(e){if(e>=0&&e<this.particles.length){const t=this.particles.splice(e,1)[0];t.cachedGradient=null,t.cachedGradientKey=null,this.returnParticleToPool(t),this.particleCount=Math.max(0,this.particleCount-1)}}render(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._render(e,t,i)},"particle-render")();this._render(e,t,i)}renderBackground(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._renderLayer(e,t,!1,i)},"particle-render-bg")();this._renderLayer(e,t,!1,i)}renderForeground(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._renderLayer(e,t,!0,i)},"particle-render-fg")();this._renderLayer(e,t,!0,i)}_renderLayer(e,t,i,s=null){this.particleRenderer.renderLayer(e,this.particles,t,i,s)}_render(e,t,i=null){this.particleRenderer.render(e,this.particles,t,i)}onVisibilityResume(e,t=null){if(this.resetAccumulator(),e>tn)this.clear();else if(e>1e4){const e=this.particles.length,i=t??e,s=Math.max(10,Math.floor(.5*i));for(;this.particles.length>s;)this.removeParticle(0)}}clear(){for(this.stateChangeCount++;this.particles.length>0;){const e=this.particles.pop();if(e.cachedColors&&e.cachedColors.clear(),e.behaviorData)for(const t in e.behaviorData)delete e.behaviorData[t];this.pool.length<this.poolSize&&!this.pool.includes(e)&&this.pool.push(e)}if(this.particles.length=0,this.particleCount=0,this.spawnAccumulator=0,this.pool.length>this.poolSize){const e=this.pool.length-this.poolSize;this.pool.splice(this.poolSize,e)}}burst(e,t,i,s){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._burst(e,t,i,s)},"particle-burst")();this._burst(e,t,i,s)}_burst(e,t,i,s){const n=Math.min(e,this.maxParticles-this.particles.length);for(let e=0;e<n;e++)this.spawnSingleParticle(t,i,s)}performCleanup(){if(this.pool.length>this.poolSize){const e=this.pool.length-this.poolSize;for(let t=0;t<e;t++){const e=this.pool.pop();e&&(e.cachedGradient=null,e.cachedGradientKey=null,e.behaviorData=null)}}for(const e of this.particles)e.cachedGradient&&e.life<.5&&(e.cachedGradient=null,e.cachedGradientKey=null)}getStats(){return{activeParticles:this.particles.length,maxParticles:this.maxParticles,poolSize:this.pool.length,poolHits:this.poolHits,poolMisses:this.poolMisses,poolEfficiency:this.poolHits/Math.max(1,this.poolHits+this.poolMisses),spawnAccumulator:this.spawnAccumulator}}setMaxParticles(e){for(this.originalMaxParticles=this.originalMaxParticles||this.maxParticles,this.maxParticles=Math.max(1,e);this.particles.length>this.maxParticles;)this.removeParticle(0)}cleanupDeadParticles(){const e=this.particles.length;this.particles=this.particles.filter(e=>e.isAlive());const t=e-this.particles.length;return this.pool.length>20&&(this.pool.length=20),t}getParticlesByBehavior(e){return this.particles.filter(t=>t.behavior===e)}validateParticles(){for(const e of this.particles)if(!e.isAlive()||e.life<0||e.life>1)return!1;return!0}cleanup(){for(let e=this.particles.length-1;e>=0;e--)this.particles[e].isAlive()||this.removeParticle(e)}refreshPool(){this.particlePool.clear();for(const e of this.particles)e.life=0}setContainmentBounds(e){this.containmentBounds=e}destroy(){this.clear(),this.particlePool.clear()}}var un=Object.freeze({__proto__:null,default:cn});const dn=new class{constructor(){this.gestureCache=new Map,this.propertyCache=new Map,this.compositionCache=new Map,this.pluginCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0,gestureHits:0,propertyHits:0,compositionHits:0},this.isInitialized=!1,this.loadStartTime=0}_ensureInitialized(){this.isInitialized||this.initialize()}initialize(){this.loadStartTime=performance.now();try{this.cacheCoreGestures(),this.cacheGestureProperties(),this.cacheCommonCombinations(),this.cachePluginGestures(),this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.gestureCache.size+this.propertyCache.size+this.compositionCache.size,this.isInitialized=!0}catch(e){console.error("GestureCache initialization failed:",e),this.isInitialized=!1,console.warn("[GestureCache] Running uninitialized โ lookups will return defaults")}}cacheCoreGestures(){Object.values(vi).forEach(e=>{e&&e.name&&this.gestureCache.set(e.name,{...e,cached:!0,cacheTime:performance.now()})})}cacheGestureProperties(){this.gestureCache.forEach((e,t)=>{const i={type:e.type,emoji:e.emoji,description:e.description,config:e.config,rhythm:e.rhythm,duration:this.calculateGestureDuration(e),easing:this.extractEasingFunction(e),physics:this.extractPhysicsProperties(e),timing:this.extractTimingProperties(e)};this.propertyCache.set(t,i)})}cacheCommonCombinations(){[["bounce","pulse"],["shake","vibrate"],["orbit","spin"],["morph","glow"],["breathe","fade"],["wave","drift"],["nod","sway"],["jump","stretch"]].forEach(([e,t])=>{const i=`${e}+${t}`,s=this.calculateGestureCombination(e,t);s&&this.compositionCache.set(i,s)})}cachePluginGestures(){try{const e=S.getAllPluginGestures();e&&Object.entries(e).forEach(([e,t])=>{this.pluginCache.set(e,{...t,cached:!0,cacheTime:performance.now(),isPlugin:!0})})}catch(e){console.warn("Could not cache plugin gestures:",e)}}getGesture(e){return this._ensureInitialized(),this.gestureCache.has(e)?(this.stats.hits++,this.stats.gestureHits++,this.gestureCache.get(e)):this.pluginCache.has(e)?(this.stats.hits++,this.stats.gestureHits++,this.pluginCache.get(e)):(this.stats.misses++,null)}getGestureProperties(e){return this._ensureInitialized(),this.propertyCache.has(e)?(this.stats.hits++,this.stats.propertyHits++,this.propertyCache.get(e)):(this.stats.misses++,null)}getGestureCombination(e,t){this._ensureInitialized();const i=`${e}+${t}`;return this.compositionCache.has(i)?(this.stats.hits++,this.stats.compositionHits++,this.compositionCache.get(i)):(this.stats.misses++,null)}calculateGestureDuration(e){if(!e.config)return 1e3;const{musicalDuration:t,duration:i}=e.config;return t&&t.musical?500*(t.beats||2):i||1e3}extractEasingFunction(e){if(!e.config)return"sine";const{easing:t,particleMotion:i}=e.config;return t||i?.easing||"sine"}extractPhysicsProperties(e){if(!e.config)return{};const{amplitude:t,strength:i,size:s,rotation:n}=e.config;return{amplitude:t||20,strength:i||1,size:s||80,rotation:n||0}}extractTimingProperties(e){if(!e.config)return{};const{phases:t,timingSync:i}=e.config;return{phases:t||[],timingSync:i||{},hasPhases:!!(t&&t.length>0),hasTimingSync:!!(i&&Object.keys(i).length>0)}}calculateGestureCombination(e,t){const i=this.getGesture(e),s=this.getGesture(t);return i&&s?{gestures:[e,t],combinedDuration:Math.max(this.calculateGestureDuration(i),this.calculateGestureDuration(s)),combinedType:i.type===s.type?i.type:"mixed",combinedEasing:this.extractEasingFunction(i),combinedPhysics:this.combinePhysicsProperties(i,s),compatibility:this.calculateCompatibility(i,s)}:null}combinePhysicsProperties(e,t){const i=this.extractPhysicsProperties(e),s=this.extractPhysicsProperties(t);return{amplitude:Math.max(i.amplitude,s.amplitude),strength:(i.strength+s.strength)/2,size:Math.max(i.size,s.size),rotation:(i.rotation+s.rotation)/2}}calculateCompatibility(e,t){return e.type===t.type?"high":"blending"===e.type&&"blending"===t.type?"medium":"override"===e.type||"override"===t.type?"low":"medium"}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(1):0;return{...this.stats,hitRate:`${e}%`,isInitialized:this.isInitialized,cacheSize:this.stats.cacheSize,coreGestures:this.gestureCache.size,pluginGestures:this.pluginCache.size,properties:this.propertyCache.size,combinations:this.compositionCache.size}}clear(){this.gestureCache.clear(),this.propertyCache.clear(),this.compositionCache.clear(),this.pluginCache.clear(),this.stats={hits:0,misses:0,loadTime:0,cacheSize:0,gestureHits:0,propertyHits:0,compositionHits:0},this.isInitialized=!1}warmUp(e){e.forEach(e=>{this.getGesture(e),this.getGestureProperties(e)})}};function gn(e){if(dn&&dn.isInitialized){const t=dn.getGesture(e);if(t)return t}return Ai(e)}const mn={none:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1,"3d":{rotation:{speedMultiplier:1,shakeMultiplier:1},glow:{intensityMultiplier:1,pulseSpeedMultiplier:1},scale:{breathDepthMultiplier:1,breathRateMultiplier:1},righting:{strengthMultiplier:1}}},clear:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1,"3d":{rotation:{speedMultiplier:1,shakeMultiplier:1},glow:{intensityMultiplier:1,pulseSpeedMultiplier:1},scale:{breathDepthMultiplier:1,breathRateMultiplier:1},righting:{strengthMultiplier:1}}},nervous:{speed:1.2,amplitude:.9,intensity:1.1,smoothness:.7,regularity:.6,addFlutter:!0,addMicroShake:!0,"3d":{rotation:{speedMultiplier:1.5,shakeMultiplier:3.5,enableEpisodicWobble:!0},glow:{intensityMultiplier:1.25,pulseSpeedMultiplier:2},scale:{breathDepthMultiplier:.5,breathRateMultiplier:1.8},righting:{strengthMultiplier:.7}}},confident:{speed:.9,amplitude:1.3,intensity:1.2,smoothness:1.1,regularity:1.2,addPower:!0,addHold:!0,"3d":{rotation:{speedMultiplier:.7,shakeMultiplier:.2},glow:{intensityMultiplier:1.4,pulseSpeedMultiplier:.7},scale:{breathDepthMultiplier:1.5,breathRateMultiplier:.7},righting:{strengthMultiplier:1.6}}},tired:{speed:.7,amplitude:.7,intensity:.8,smoothness:1.3,regularity:.8,addDroop:!0,addPause:!0,"3d":{rotation:{speedMultiplier:.4,shakeMultiplier:.15},glow:{intensityMultiplier:.5,pulseSpeedMultiplier:.5},scale:{breathDepthMultiplier:1.3,breathRateMultiplier:.5},righting:{strengthMultiplier:.6}}},intense:{speed:1.3,amplitude:1.2,intensity:1.4,smoothness:.6,regularity:.9,addPulse:!0,addFocus:!0,"3d":{rotation:{speedMultiplier:1.6,shakeMultiplier:2.5},glow:{intensityMultiplier:1.8,pulseSpeedMultiplier:2.2},scale:{breathDepthMultiplier:1.6,breathRateMultiplier:1.8},righting:{strengthMultiplier:1.3}}},subdued:{speed:.8,amplitude:.8,intensity:.7,smoothness:1.2,regularity:1.1,addSoftness:!0,addFade:!0,"3d":{rotation:{speedMultiplier:.5,shakeMultiplier:.1},glow:{intensityMultiplier:.55,pulseSpeedMultiplier:.6},scale:{breathDepthMultiplier:.7,breathRateMultiplier:.6},righting:{strengthMultiplier:1.4}}}};class pn{constructor(){this.cache=new Map,this.easingCache=new Map,this.preCalculateEasingCurves()}preCalculateEasingCurves(){const e=["linear","ease-in","ease-out","ease-in-out","bounce"];for(const t of e){const e=new Float32Array(101);for(let i=0;i<=100;i++){const s=i/100;e[i]=this.calculateEasing(s,t)}this.easingCache.set(t,e)}}calculateEasing(e,t){switch(t){case"ease-in":return e*e;case"ease-out":return e*(2-e);case"ease-in-out":return e<.5?2*e*e:(4-2*e)*e-1;case"bounce":return e<.363636?7.5625*e*e:e<.727272?7.5625*(e-=.545454)*e+.75:e<.90909?7.5625*(e-=.818181)*e+.9375:7.5625*(e-=.954545)*e+.984375;default:return e}}getEasingValue(e,t){const i=this.easingCache.get(t);return i?i[Math.min(Math.floor(100*e),100)]:e}compose(e,t,i=null){const s=`${e}-${t}-${i||"none"}`;if(this.cache.has(s))return this.cache.get(s);const n=gn(e),a=n?n.config:{duration:500,amplitude:20,easing:"sine"},r=Ks&&Ks.isInitialized?Ks.getModifiers(t):c(t),o=function(e){return e&&""!==e&&"clear"!==e&&mn[e]||mn.clear}(i),l=this.applyModifiers(a,r,o,e);return this.cache.size>100&&this.cache.clear(),this.cache.set(s,l),l}applyModifiers(e,t,i,s){const n={...e},a=t.speed*i.speed;if(n.duration=Math.round(e.duration/a),void 0!==n.amplitude&&(n.amplitude=e.amplitude*t.amplitude*i.amplitude),void 0!==n.scaleAmount&&(n.scaleAmount=e.scaleAmount*t.intensity*i.intensity),void 0!==n.scaleTarget){const s=t.amplitude*i.amplitude;n.scaleTarget=1+(e.scaleTarget-1)*s}void 0!==n.glowAmount&&(n.glowAmount=e.glowAmount*t.intensity*i.intensity),void 0!==n.glowPeak&&(n.glowPeak=1+(e.glowPeak-1)*t.intensity*i.intensity),void 0!==n.rotations&&(n.rotations=e.rotations*t.amplitude*i.amplitude),void 0!==n.angle&&(n.angle=e.angle*t.amplitude*i.amplitude),void 0!==n.distance&&(n.distance=e.distance*t.amplitude*i.amplitude);const r=t.smoothness*i.smoothness;return n.smoothness=r,n.easing=this.selectEasing(e.easing,r),n.regularity=t.regularity*i.regularity,n.effects=[],t.addBounce&&n.effects.push("bounce"),t.addGravity&&n.effects.push("gravity"),t.addShake&&n.effects.push("shake"),t.addJitter&&n.effects.push("shake"),t.addPop&&n.effects.push("pop"),t.addRecoil&&n.effects.push("recoil"),t.addWarmth&&n.effects.push("warmth"),t.addFlow&&n.effects.push("flow"),t.addWobble&&n.effects.push("wobble"),t.addVibration&&n.effects.push("vibration"),t.addDrag&&n.effects.push("drag"),t.addWeight&&n.effects.push("weight"),t.addTension&&n.effects.push("tension"),t.addPrecision&&n.effects.push("precision"),i.addFlutter&&n.effects.push("flutter"),i.addMicroShake&&n.effects.push("microShake"),i.addPower&&n.effects.push("power"),i.addHold&&n.effects.push("hold"),i.addDroop&&n.effects.push("droop"),i.addPause&&n.effects.push("pause"),i.addPulse&&n.effects.push("pulse"),i.addFocus&&n.effects.push("focus"),i.addSoftness&&n.effects.push("softness"),i.addFade&&n.effects.push("fade"),this.applyGestureSpecificMods(n,s,t,i),e.particleMotion&&(n.particleMotion={...e.particleMotion},void 0!==n.particleMotion.strength&&(n.particleMotion.strength*=t.intensity*i.intensity),void 0!==n.particleMotion.frequency&&(n.particleMotion.frequency*=a),void 0!==n.particleMotion.amplitude&&(n.particleMotion.amplitude*=t.amplitude*i.amplitude)),n}selectEasing(e,t){return t<.5?"linear":t<.8?"quad":t<1.2?e:t<1.5?"cubic":"sine"}applyGestureSpecificMods(e,t,i,s){switch(t){case"bounce":i.addShake&&(e.frequency=Math.floor(1.5*e.frequency)),i.addGravity&&(e.amplitude*=.6,e.frequency=1);break;case"pulse":i.addWarmth&&(e.frequency=2,e.glowAmount*=1.5),s.addFlutter&&(e.irregular=!0);break;case"shake":i.addJitter&&(e.frequency*=1.5,e.amplitude*=1.2),i.addShake&&(e.amplitude*=1.5,e.decay=!1);break;case"spin":i.addBounce&&(e.rotations*=1.5),i.addWobble&&(e.wobble=!0)}}clearCache(){this.cache.clear()}}const fn=new class{constructor(){this.noteDurations={whole:4,half:2,quarter:1,eighth:.5,sixteenth:.25,triplet:.333,"dotted-quarter":1.5,"dotted-half":3},this.cache=new Map,this.maxCacheSize=100,this.cacheAccessOrder=[],this.lastBPM=0,this.prewarmCache()}prewarmCache(){const e=[{musical:!0,beats:1},{musical:!0,bars:1},{musical:!0,beats:.5},{musical:!0,beats:2}];[60,90,120,140,160,180].forEach(t=>{e.forEach(e=>{const i=`${t}_${JSON.stringify(e)}`,s=this.toMilliseconds(e,t);if(this.cache.size>=this.maxCacheSize){const e=this.cacheAccessOrder.shift();this.cache.delete(e)}this.cache.set(i,s),this.cacheAccessOrder.push(i)})})}toMilliseconds(e,t=null){const i=t||sn.bpm||120;if("number"==typeof e)return e;if("object"==typeof e&&e.musical){const t=6e4/i;if(void 0!==e.beats)return e.beats*t;if(void 0!==e.bars){const i=sn.timeSignature||[4,4];return e.bars*i[0]*t}if(void 0!==e.subdivision)return(this.noteDurations[e.subdivision]||1)*t}return 1e3}toMusical(e,t=null){const i=e/(6e4/(t||sn.bpm||120));let s="quarter",n=Math.abs(i-1);for(const[e,t]of Object.entries(this.noteDurations)){const a=Math.abs(i-t);a<n&&(n=a,s=e)}return{musical:!0,beats:i,bars:i/4,closestSubdivision:s,exact:n<.01}}calculatePhases(e,t){if(!e||0===e.length)return[{name:"main",beats:t,start:0,end:1}];const i=e.reduce((e,t)=>e+(t.beats||1),0),s=t/i;let n=0;return e.map(e=>{const i=(e.beats||1)*s,a=n/t;n+=i;const r=n/t;return{name:e.name,beats:i,start:a,end:r,duration:this.toMilliseconds({musical:!0,beats:i})}})}getBeatProgress(){const e=sn.getTimeInfo();return e?e.beatProgress:0}getBarProgress(){const e=sn.getTimeInfo();return e?e.barProgress:0}timeToNextBoundary(e="beat"){const t=sn.getTimeInfo();if(!t)return 100;switch(e){case"beat":default:return t.nextBeatIn;case"bar":return(t.timeSignature[0]-t.beatInBar)*t.beatDuration;case"phrase":{const e=4,i=t.timeSignature[0];return(e-(t.bar||0)%e)*i*t.beatDuration}}}quantize(e,t="eighth"){const i=6e4/(sn.bpm||120),s=(this.noteDurations[t]||1)*i;return Math.round(e/s)*s}isOnBoundary(e="beat",t=50){const i=this.timeToNextBoundary(e),s=sn.getTimeInfo();return!!s&&(i<t||s.beatDuration-i<t)}getTempoAdaptation(e=120){const t=(sn.bpm||120)/e;return{speed:t,energy:Math.min(2,Math.max(.5,t)),smoothness:t<.8?1.2:t>1.5?.8:1,intensity:t>1.3?1.2:t<.7?.8:1}}};class yn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyBounce(e,t){return{offsetY:-Math.abs(Math.sin(t*Math.PI*e.params.frequency))*e.params.amplitude*this.scaleFactor*(e.params.effects&&e.params.effects.includes("gravity")?.6:1)}}applyShake(e,t){e.randomAngle||(e.randomAngle=Math.random()*Math.PI*2);const i=e.params.decay?1-t:1,s=Math.sin(t*Math.PI*e.params.frequency)*e.params.amplitude*i*this.scaleFactor;return{offsetX:s*Math.cos(e.randomAngle),offsetY:s*Math.sin(e.randomAngle)}}applyJump(e,t){let i,s,n=0,a=1;if(t<.2){const i=t/.2;a=1-(1-e.params.squashAmount)*i}else if(t<.7){const i=(t-.2)/.5,s=Math.sin(i*Math.PI);n=-e.params.jumpHeight*s*this.scaleFactor,a=e.params.squashAmount+(e.params.stretchAmount-e.params.squashAmount)*s}else{const i=(t-.7)/.3;a=e.params.stretchAmount-(e.params.stretchAmount-1)*i}if(e.params.effects&&e.params.effects.includes("gravity")){const e=t<.7?(t-.2)/.5:0,n=Math.sin(e*Math.PI);i=1+.2*n,s=1-.15*n}const r={offsetY:n,scale:a};return void 0!==i&&(r.scaleX=i),void 0!==s&&(r.scaleY=s),r}applyVibrate(e,t){if(!e.vibrateAngles){e.vibrateAngles={x:2*Math.random()-1,y:2*Math.random()-1};const t=Math.sqrt(e.vibrateAngles.x**2+e.vibrateAngles.y**2);e.vibrateAngles.x/=t,e.vibrateAngles.y/=t}const i=e.params.amplitude||5,s=e.params.frequency||20,n=Math.sin(t*Math.PI*2*s)*i*this.scaleFactor;return{offsetX:n*e.vibrateAngles.x,offsetY:n*e.vibrateAngles.y}}applyWiggle(e,t){const i=(e.params?.amplitude||15)*this.scaleFactor;void 0===e.wiggleDirection&&(e.wiggleDirection=Math.random()<.5?1:-1);const s=e.wiggleDirection;let n=0,a=0;if(t<.25){const e=t/.25;n=i*s*e,a=3*s*e}else if(t<.5){const e=(t-.25)/.25;n=i*s*(1-2*e),a=3*s*(1-2*e)}else if(t<.75){const e=(t-.5)/.25;n=i*-s*(1-2*e),a=3*-s*(1-2*e)}else{const e=(t-.75)/.25;n=i*s*(1-e),a=3*s*(1-e)}return{offsetX:n,offsetY:-Math.abs(Math.sin(t*Math.PI*4))*i*.15,rotation:a}}}class bn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyFlash(e,t){const i=Math.sin(t*Math.PI);return{glow:1+((e.params.glowPeak||2)-1)*i,scale:1+((e.params.scalePeak||1.1)-1)*i}}applyGlow(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+i*(e.params.scaleAmount||.1),glow:1+i*(e.params.glowAmount||.8)}}applyFlicker(e,t){const i=e.params?.intensity||2,s=e.params?.speed||3,n=1+Math.sin(t*Math.PI*2*s)*i*.3,a=5*Math.sin(t*Math.PI*4)*this.scaleFactor,r=.001*Date.now();return{offsetX:a,glow:n,particleGlow:(.5*Math.sin(t*Math.PI*s*2)+.5)*i,flickerTime:r,flickerEffect:!0}}applySparkle(e,t){const i=e.params?.intensity||2,s=.001*Date.now();return{particleGlow:i,glow:.3*Math.sin(t*Math.PI*4)+.7,fireflyTime:s,fireflyEffect:!0}}applyShimmer(e,t){const i=.001*Date.now(),s=e.params?.intensity||.3,n=Math.sin(2*i+t*Math.PI*2);return{offsetX:0,offsetY:0,glow:1+n*s,scale:1+.01*n,particleGlow:1+.2*n,shimmerTime:i,shimmerWave:n,shimmerEffect:!0}}}class vn{constructor(e){this.renderer=e}applyBreathe(e,t){const{params:i}=e,s=i.particleMotion?.holdPercent||.1;let n;if(t<.4)n=Math.sin(t/.4*Math.PI/2);else if(t<.4+s)n=1;else if(t<.9){const e=(t-.4-s)/(.5-s);n=Math.cos(e*Math.PI/2)}else n=0;const a=1+n*(i.scaleAmount||.25),r=1+n*(i.glowAmount||.4);return e.breathPhase=n,{scale:a,glow:r,breathPhase:n}}applyBreathIn(e,t){return{scale:1+(e.params.scaleAmount-1)*Math.sin(t*Math.PI/2)}}applyBreathOut(e,t){return{scale:1-(1-e.params.scaleAmount)*Math.sin(t*Math.PI/2)}}applyBreathHold(e,t){return{scale:e.params.scaleAmount}}applyBreathHoldEmpty(e,t){return{scale:e.params.scaleAmount}}}class Mn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applySpin(e,t){return{rotation:Math.min(1.05*t,1)*e.params.rotations*360,scale:1+Math.sin(t*Math.PI)*e.params.scaleAmount}}applyDrift(e,t){t<=.01&&!e.currentDriftAngle&&(e.currentDriftAngle=Math.random()*Math.PI*2);const i=e.params.distance*Math.sin(t*Math.PI)*this.scaleFactor,s=e.currentDriftAngle||0;return t>=.99&&(e.currentDriftAngle=null),{offsetX:Math.cos(s)*i,offsetY:Math.sin(s)*i}}applyWave(e,t){const i=(e.params.amplitude||40)*this.scaleFactor,s=t*Math.PI*2,n=Math.sin(s)*i,a=-Math.sin(t*Math.PI)*i*.3;return{offsetX:n,offsetY:Math.sin(2*s)*i*.2+a,rotation:5*Math.sin(s),scale:1+.05*Math.sin(t*Math.PI*2),glow:1+.2*Math.sin(t*Math.PI)}}applySway(e,t){const i=(e.params?.amplitude||30)*this.scaleFactor,s=e.params?.frequency||1;return{offsetX:Math.sin(t*Math.PI*2*s)*i,offsetY:Math.sin(t*Math.PI*4*s)*i*.1,rotation:5*Math.sin(t*Math.PI*2*s)}}applyFloat(e,t){const i=(e.params?.amplitude||20)*this.scaleFactor,s=e.params?.speed||1,n=Math.sin(t*Math.PI*2*s)*i;return{offsetX:Math.sin(t*Math.PI*3*s)*i*.3,offsetY:n,scale:1+.02*Math.sin(t*Math.PI*4*s)}}applyOrbital(e,t){return{offsetX:0,offsetY:0}}applyHula(e,t){const i=(e.params?.amplitude||40)*this.scaleFactor,s=t*Math.PI*2;return{offsetX:Math.sin(s)*i,offsetY:Math.sin(2*s)*i*.5}}applyOrbit(e,t){const i=(e.params?.radius||30)*this.scaleFactor,s=e.params?.speed||1,n=t*Math.PI*2*s;return{offsetX:Math.cos(n)*i,offsetY:Math.sin(n)*i}}}class wn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyPulse(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+i*e.params.scaleAmount,glow:1+i*e.params.glowAmount}}applyExpand(e,t){const i=Math.max(e.params.scaleAmount||e.params.scaleTarget||1.5,1),s=Math.sin(t*Math.PI/2);return{scale:1+(i-1)*s,glow:1+Math.abs(e.params.glowAmount||.2)*s}}applyContract(e,t){const i=e.params.scaleAmount||e.params.scaleTarget||.7,s=Math.sin(t*Math.PI/2);return{scale:1+(i-1)*s,glow:1+(e.params.glowAmount||-.2)*s}}applyStretch(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+((e.params.scaleX+e.params.scaleY)/2-1)*i}}applyMorph(e,t){const i=Math.sin(t*Math.PI*2);return{scale:1+.1*i,rotation:10*i}}}class Sn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyNod(e,t){return{offsetY:Math.sin(t*Math.PI*e.params.frequency)*e.params.amplitude*this.scaleFactor}}applyTilt(e,t){e.tiltDirection||(e.tiltDirection=Math.random()<.5?-1:1);const i=e.params.frequency||2,s=(e.params.angle||15)*Math.PI/180,n=Math.sin(t*Math.PI*i)*e.tiltDirection;return{rotation:n*s,scaleX:1+.1*Math.abs(n),scaleY:1-.05*Math.abs(n),offsetX:10*n,offsetY:-5*Math.abs(n)}}applySlowBlink(e,t){let i=1;return i=t<.3?1-t/.3:t<.5?0:t<.8?(t-.5)/.3:1,{glow:i}}applyLook(e,t){if(!e.targetX){const t=e.params.lookDirection,i=50*e.params.lookDistance*this.scaleFactor;switch(t){case"left":e.targetX=-i,e.targetY=0;break;case"right":e.targetX=i,e.targetY=0;break;case"up":e.targetX=0,e.targetY=-i;break;case"down":e.targetX=0,e.targetY=i;break;default:{const t=Math.random()*Math.PI*2;e.targetX=Math.cos(t)*i,e.targetY=Math.sin(t)*i;break}}}let i=t;return i=t<.3?t/.3:t<.7?1:1-(t-.7)/.3,{offsetX:e.targetX*i,offsetY:e.targetY*i}}applySettle(e,t){const i=Math.sin(t*Math.PI*e.params.wobbleFreq)*Math.exp(3*-t)*20*this.scaleFactor;return{offsetY:i,scale:1+.01*i}}}class xn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyPoint(e,t){void 0===e.pointDirection&&(e.pointDirection=Math.random()<.5?-1:1);const i=void 0!==e.params?.direction?e.params.direction:e.pointDirection,s=(e.params?.distance||40)*this.scaleFactor;let n,a;return t<.4?(n=1-Math.pow(1-t/.4,3),a=n):t<.6?(n=1,a=1):(n=Math.pow(1-(t-.6)/.4,3),a=n),{offsetX:i*s*n,offsetY:-Math.abs(.15*s*n),scale:1+.15*a,rotation:5*i*a}}applyLean(e,t){const i=e.params?.angle||15,s=e.params?.side||1,n=Math.sin(t*Math.PI),a=i*s*n;return{offsetX:10*s*this.scaleFactor*n,rotation:a}}applyReach(e,t){const i=void 0!==e.params?.direction?e.params.direction:-Math.PI/2,s=(e.params?.distance||40)*this.scaleFactor;let n;return n=t<.4?t/.4:t<.6?1:1-(t-.6)/.4,n=n*n*(3-2*n),{offsetX:Math.cos(i)*s*n,offsetY:Math.sin(i)*s*n,scale:1+.15*n}}}class Cn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyFlashWave(e,t){e.flashWave||(e.flashWave={innerRadius:0,outerRadius:0,maxRadius:3}),e.flashWave.outerRadius=t*e.flashWave.maxRadius,e.flashWave.innerRadius=Math.max(0,(t-.1)*e.flashWave.maxRadius);const i=Math.max(0,1-.7*t);return e.flashWaveData={innerRadius:e.flashWave.innerRadius,outerRadius:e.flashWave.outerRadius,intensity:i},{glow:1+.3*i,flashWave:e.flashWaveData}}applyRain(e,t){return{offsetX:0,offsetY:0,particleEffect:"rain"}}applyGroove(e,t){const i=(e.params?.amplitude||25)*this.scaleFactor;return{offsetX:Math.sin(t*Math.PI*2)*i+Math.sin(t*Math.PI*3+.5)*i*.4,offsetY:Math.sin(t*Math.PI*4+.3)*i*.25,scale:1+.03*Math.sin(t*Math.PI*3+.7),rotation:8*Math.sin(t*Math.PI*2+.2)}}applyHeadBob(e,t){const i=(e.params?.amplitude||20)*this.scaleFactor,s=t*(e.params?.frequency||2)%1;let n;return n=s<.3?s/.3*-i:-i*(1-(s-.3)/.7),{offsetY:n,rotation:s<.3?-3:0}}applyRunningMan(e,t){const i=20*Math.sin(t*Math.PI*4)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(t*Math.PI*8))*this.scaleFactor,rotation:.3*i,scaleY:1-.05*Math.abs(Math.sin(t*Math.PI*8))}}applyCharleston(e,t){const i=25*Math.sin(t*Math.PI*8)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(t*Math.PI*8))*this.scaleFactor,rotation:.6*i,scaleY:1-.06*Math.abs(Math.sin(t*Math.PI*8))}}}class kn{constructor(e){this.renderer=e,this.activeGestures=new Map,this.scaleFactor=e.scaleFactor||1,this.physicalGestureAnimator=new yn(e),this.visualEffectAnimator=new bn(e),this.breathGestureAnimator=new vn(e),this.movementGestureAnimator=new Mn(e),this.shapeTransformAnimator=new wn(e),this.expressionGestureAnimator=new Sn(e),this.directionalGestureAnimator=new xn(e),this.complexAnimationAnimator=new Cn(e),this.gestureAnimations={bounce:{active:!1,progress:0,params:{}},pulse:{active:!1,progress:0,params:{}},shake:{active:!1,progress:0,params:{}},spin:{active:!1,progress:0,params:{}},nod:{active:!1,progress:0,params:{}},tilt:{active:!1,progress:0,params:{}},expand:{active:!1,progress:0,params:{}},contract:{active:!1,progress:0,params:{}},flash:{active:!1,progress:0,params:{}},drift:{active:!1,progress:0,params:{}},stretch:{active:!1,progress:0,params:{}},glow:{active:!1,progress:0,params:{}},flicker:{active:!1,progress:0,params:{}},vibrate:{active:!1,progress:0,params:{}},orbital:{active:!1,progress:0,params:{}},hula:{active:!1,progress:0,params:{}},wave:{active:!1,progress:0,params:{}},breathe:{active:!1,progress:0,params:{}},morph:{active:!1,progress:0,params:{}},slowBlink:{active:!1,progress:0,params:{}},look:{active:!1,progress:0,params:{}},settle:{active:!1,progress:0,params:{}},breathIn:{active:!1,progress:0,params:{}},breathOut:{active:!1,progress:0,params:{}},breathHold:{active:!1,progress:0,params:{}},breathHoldEmpty:{active:!1,progress:0,params:{}},jump:{active:!1,progress:0,params:{}},sway:{active:!1,progress:0,params:{}},float:{active:!1,progress:0,params:{}},sparkle:{active:!1,progress:0,params:{}},shimmer:{active:!1,progress:0,params:{}},wiggle:{active:!1,progress:0,params:{}},groove:{active:!1,progress:0,params:{}},point:{active:!1,progress:0,params:{}},lean:{active:!1,progress:0,params:{}},reach:{active:!1,progress:0,params:{}},headBob:{active:!1,progress:0,params:{}},orbit:{active:!1,progress:0,params:{}},rain:{active:!1,progress:0,params:{}},runningman:{active:!1,progress:0,params:{}},charleston:{active:!1,progress:0,params:{}}}}startGesture(e){const t=gn(e);if(["bounce","shake","pulse","flash","jump","slam","spin","flicker"].includes(e)&&this.renderer.specialEffects){const t={flash:1,jump:1,shake:.9,bounce:.8,pulse:.7,slam:1,spin:.8,flicker:1}[e]||.8;this.renderer.specialEffects.triggerChromaticAberration(t)}let i;i=this.renderer.gestureCompositor?this.renderer.gestureCompositor.compose(e,this.renderer.state.emotion,this.renderer.currentUndertone):t?.config||{amplitude:20,frequency:2,duration:1e3,scaleAmount:.2,glowAmount:.3,rotations:1,distance:50,angle:15,scaleTarget:1.5,glowPeak:2,scalePeak:1.1,scaleX:1.2,scaleY:.8,maxOpacity:1,minOpacity:.5,lookDirection:"random",lookDistance:1,wobbleFreq:4,squashAmount:.8,stretchAmount:1.2,jumpHeight:100,decay:!0,easing:"sine",effects:[]};let s=1e3;if(t&&t.config)if(t.config.musicalDuration)s=fn.toMilliseconds(t.config.musicalDuration);else if(t.config.duration){const{duration:e}=t.config;s=e}const n=this.gestureAnimations[e];n&&(n.active=!0,n.startTime=performance.now(),n.progress=0,n.params=i,n.duration=s,"shake"===e?n.randomAngle=void 0:"drift"===e?(n.startX=void 0,n.startY=void 0,n.currentDriftAngle=void 0):"tilt"===e?n.tiltDirection=void 0:"vibrate"===e&&(n.vibrateAngles=void 0))}applyGestureAnimations(){const e=performance.now(),t={offsetX:0,offsetY:0,scale:1,rotation:0,glow:1};for(const[i,s]of Object.entries(this.gestureAnimations)){if(!s.active)continue;const n=e-s.startTime,a=s.duration||(s.params?s.params.duration:1e3);s.progress=Math.min(n/a,1);const r=this.applyEasing(s.progress,s.params.easing);let o={};switch(i){case"bounce":o=this.applyBounce(s,r);break;case"pulse":o=this.applyPulse(s,r);break;case"shake":o=this.applyShake(s,r);break;case"spin":o=this.applySpin(s,r);break;case"nod":o=this.applyNod(s,r);break;case"tilt":o=this.applyTilt(s,r);break;case"expand":o=this.applyExpand(s,r);break;case"contract":o=this.applyContract(s,r);break;case"flash":o=this.applyFlash(s,r);break;case"drift":o=this.applyDrift(s,r);break;case"stretch":o=this.applyStretch(s,r);break;case"glow":o=this.applyGlow(s,r);break;case"flicker":o=this.applyFlicker(s,r);break;case"vibrate":o=this.applyVibrate(s,r);break;case"orbital":o=this.applyOrbital(s,r);break;case"hula":o=this.applyHula(s,r);break;case"wave":o=this.applyWave(s,r);break;case"breathe":o=this.applyBreathe(s,r);break;case"morph":o=this.applyMorph(s,r);break;case"slowBlink":o=this.applySlowBlink(s,r);break;case"look":o=this.applyLook(s,r);break;case"settle":o=this.applySettle(s,r);break;case"breathIn":o=this.applyBreathIn(s,r);break;case"breathOut":o=this.applyBreathOut(s,r);break;case"breathHold":o=this.applyBreathHold(s,r);break;case"breathHoldEmpty":o=this.applyBreathHoldEmpty(s,r);break;case"jump":o=this.applyJump(s,r);break;case"sway":o=this.applySway(s,r);break;case"float":o=this.applyFloat(s,r);break;case"rain":o=this.applyRain(s,r);break;case"runningman":o=this.applyRunningMan(s,r);break;case"charleston":o=this.applyCharleston(s,r);break;case"sparkle":o=this.applySparkle(s,r);break;case"shimmer":o=this.applyShimmer(s,r);break;case"wiggle":o=this.applyWiggle(s,r);break;case"groove":o=this.applyGroove(s,r);break;case"point":o=this.applyPoint(s,r);break;case"lean":o=this.applyLean(s,r);break;case"reach":o=this.applyReach(s,r);break;case"headBob":o=this.applyHeadBob(s,r);break;case"orbit":o=this.applyOrbit(s,r)}t.offsetX+=o.offsetX||0,t.offsetY+=o.offsetY||0,t.scale*=o.scale||1,t.rotation+=o.rotation||0,t.glow=Math.max(t.glow,o.glow||1),o.flashWave&&(t.flashWave=o.flashWave),o.fireflyEffect&&(t.fireflyEffect=o.fireflyEffect,t.particleGlow=o.particleGlow,t.fireflyTime=o.fireflyTime),o.flickerEffect&&(t.flickerEffect=o.flickerEffect,t.particleGlow=o.particleGlow,t.flickerTime=o.flickerTime),o.shimmerEffect&&(t.shimmerEffect=o.shimmerEffect,t.particleGlow=o.particleGlow,t.shimmerTime=o.shimmerTime,t.shimmerWave=o.shimmerWave),o.glowEffect&&(t.glowEffect=o.glowEffect,t.particleGlow=o.particleGlow,t.glowTime=o.glowTime,t.glowProgress=o.glowProgress,t.glowEnvelope=o.glowEnvelope),s.progress>=1&&(s.active=!1,s.progress=0,s.startTime=0,"flash"===i&&(s.flashWave=null,s.flashWaveData=null),o.glowEffect&&(o.glowEffect=null,o.particleGlow=null,o.glowTime=null,o.glowProgress=null,o.glowEnvelope=null),o.fireflyEffect&&(o.fireflyEffect=null,o.particleGlow=null,o.fireflyTime=null),o.flickerEffect&&(o.flickerEffect=null,o.particleGlow=null,o.flickerTime=null),o.shimmerEffect&&(o.shimmerEffect=null,o.particleGlow=null,o.shimmerTime=null,o.shimmerWave=null))}return t}update(e){return this.applyGestureAnimations()}stopAllGestures(){Object.keys(this.gestureAnimations).forEach(e=>{const t=this.gestureAnimations[e];t.active=!1,t.startTime=0,t.progress=0,t.params=null,t.glowEffect&&(t.glowEffect=null,t.particleGlow=null,t.glowTime=null,t.glowProgress=null,t.glowEnvelope=null),t.fireflyEffect&&(t.fireflyEffect=null,t.particleGlow=null,t.fireflyTime=null),t.flickerEffect&&(t.flickerEffect=null,t.particleGlow=null,t.flickerTime=null),t.shimmerEffect&&(t.shimmerEffect=null,t.particleGlow=null,t.shimmerTime=null,t.shimmerWave=null),t.flashWave&&(t.flashWave=null,t.flashWaveData=null)}),this.activeGestures.clear()}getCurrentGesture(){const e=performance.now(),t=["orbital","hula","wave","spin"];for(const i of t){const t=this.gestureAnimations[i];if(t&&t.active){const s=gn(i),n=e-t.startTime,a=t.duration||(t.params?t.params.duration:1e3),r=Math.min(n/a,1);return{name:i,particleMotion:s?.config?.particleMotion||{type:i,strength:t.params?.strength||1},progress:r,params:t.params}}}for(const[t,i]of Object.entries(this.gestureAnimations))if(i.active){const s=gn(t),n=e-i.startTime,a=i.duration||(i.params?i.params.duration:1e3),r=Math.min(n/a,1),o={name:t,particleMotion:s?.config?.particleMotion||i.params?.particleMotion||{type:t,strength:i.params?.strength||1},progress:r,params:i.params};return"breathe"===t&&void 0!==i.breathPhase&&(o.breathPhase=i.breathPhase),o}return null}applyEasing(e,t){switch(t){case"linear":default:return e;case"quad":return e*e;case"cubic":return e*e*e;case"sine":return Math.sin(e*Math.PI/2);case"back":return e*e*(2.7*e-1.7)}}applyBounce(e,t){return this.physicalGestureAnimator.applyBounce(e,t)}applyPulse(e,t){return this.shapeTransformAnimator.applyPulse(e,t)}applyShake(e,t){return this.physicalGestureAnimator.applyShake(e,t)}applySpin(e,t){return this.movementGestureAnimator.applySpin(e,t)}applyNod(e,t){return this.expressionGestureAnimator.applyNod(e,t)}applyTilt(e,t){return this.expressionGestureAnimator.applyTilt(e,t)}applyExpand(e,t){return this.shapeTransformAnimator.applyExpand(e,t)}applyContract(e,t){return this.shapeTransformAnimator.applyContract(e,t)}applyFlash(e,t){return this.visualEffectAnimator.applyFlash(e,t)}applyDrift(e,t){return this.movementGestureAnimator.applyDrift(e,t)}applyStretch(e,t){return this.shapeTransformAnimator.applyStretch(e,t)}applyGlow(e,t){return this.visualEffectAnimator.applyGlow(e,t)}applyFlashWave(e,t){return this.complexAnimationAnimator.applyFlashWave(e,t)}applyFlicker(e,t){return this.visualEffectAnimator.applyFlicker(e,t)}applyVibrate(e,t){return this.physicalGestureAnimator.applyVibrate(e,t)}applyWave(e,t){return this.movementGestureAnimator.applyWave(e,t)}applyBreathe(e,t){return this.breathGestureAnimator.applyBreathe(e,t)}applyMorph(e,t){return this.shapeTransformAnimator.applyMorph(e,t)}applySlowBlink(e,t){return this.expressionGestureAnimator.applySlowBlink(e,t)}applyLook(e,t){return this.expressionGestureAnimator.applyLook(e,t)}applySettle(e,t){return this.expressionGestureAnimator.applySettle(e,t)}applyBreathIn(e,t){return this.breathGestureAnimator.applyBreathIn(e,t)}applyBreathOut(e,t){return this.breathGestureAnimator.applyBreathOut(e,t)}applyBreathHold(e,t){return this.breathGestureAnimator.applyBreathHold(e,t)}applyBreathHoldEmpty(e,t){return this.breathGestureAnimator.applyBreathHoldEmpty(e,t)}applyJump(e,t){return this.physicalGestureAnimator.applyJump(e,t)}applySway(e,t){return this.movementGestureAnimator.applySway(e,t)}applyRain(e,t){return this.complexAnimationAnimator.applyRain(e,t)}applyFloat(e,t){return this.movementGestureAnimator.applyFloat(e,t)}applyOrbital(e,t){return this.movementGestureAnimator.applyOrbital(e,t)}applyHula(e,t){return this.movementGestureAnimator.applyHula(e,t)}applySparkle(e,t){return this.visualEffectAnimator.applySparkle(e,t)}applyShimmer(e,t){return this.visualEffectAnimator.applyShimmer(e,t)}applyWiggle(e,t){return this.physicalGestureAnimator.applyWiggle(e,t)}applyGroove(e,t){return this.complexAnimationAnimator.applyGroove(e,t)}applyPoint(e,t){return this.directionalGestureAnimator.applyPoint(e,t)}applyLean(e,t){return this.directionalGestureAnimator.applyLean(e,t)}applyReach(e,t){return this.directionalGestureAnimator.applyReach(e,t)}applyHeadBob(e,t){return this.complexAnimationAnimator.applyHeadBob(e,t)}applyOrbit(e,t){return this.movementGestureAnimator.applyOrbit(e,t)}startBounce(){this.startGesture("bounce")}startPulse(){this.startGesture("pulse")}startShake(){this.startGesture("shake")}startSpin(){this.startGesture("spin")}startNod(){this.startGesture("nod")}startTilt(){this.startGesture("tilt")}startExpand(){this.startGesture("expand")}startContract(){this.startGesture("contract")}startFlash(){this.startGesture("flash")}startDrift(){this.startGesture("drift")}startStretch(){this.startGesture("stretch")}startGlow(){this.startGesture("glow")}startFlicker(){this.startGesture("flicker")}startVibrate(){this.startGesture("vibrate")}startOrbital(){this.startGesture("orbital")}startHula(){this.startGesture("hula")}startWave(){this.startGesture("wave")}startBreathe(){this.startGesture("breathe")}startMorph(){this.startGesture("morph")}startSlowBlink(){this.startGesture("slowBlink")}startLook(){this.startGesture("look")}startSettle(){this.startGesture("settle")}startBreathIn(){this.startGesture("breathIn")}startBreathOut(){this.startGesture("breathOut")}startBreathHold(){this.startGesture("breathHold")}startBreathHoldEmpty(){this.startGesture("breathHoldEmpty")}startJump(){this.startGesture("jump")}startSway(){this.startGesture("sway")}startFloat(){this.startGesture("float")}startRain(){this.startGesture("rain")}startRunningMan(){this.startGesture("runningman")}startCharleston(){this.startGesture("charleston")}startSparkle(){this.startGesture("sparkle")}startShimmer(){this.startGesture("shimmer")}startWiggle(){this.startGesture("wiggle")}startGroove(){this.startGesture("groove")}startPoint(){this.startGesture("point")}startLean(){this.startGesture("lean")}startReach(){this.startGesture("reach")}startHeadBob(){this.startGesture("headBob")}startOrbit(){this.startGesture("orbit")}applyRunningMan(e,t){return this.complexAnimationAnimator.applyRunningMan(e,t)}applyCharleston(e,t){return this.complexAnimationAnimator.applyCharleston(e,t)}startRunningManGesture(){this.startGesture("runningman")}startCharlestonGesture(){this.startGesture("charleston")}pauseCurrentAnimation(){const e=performance.now();for(const[,t]of Object.entries(this.gestureAnimations))t.active&&(t.pausedAt=e,t.pausedProgress=t.progress);this.isPaused=!0}resumeAnimation(){if(!this.isPaused)return;const e=performance.now();for(const[,t]of Object.entries(this.gestureAnimations))if(t.active&&t.pausedAt){const i=e-t.pausedAt;t.startTime&&(t.startTime+=i),delete t.pausedAt,delete t.pausedProgress}this.isPaused=!1}reset(){for(const[,e]of Object.entries(this.gestureAnimations))e.active=!1,e.progress=0,e.params={},delete e.startTime,delete e.pausedAt,delete e.pausedProgress;this.activeGestures.clear(),this.isPaused=!1}destroy(){this.stopAllGestures(),this.physicalGestureAnimator&&"function"==typeof this.physicalGestureAnimator.destroy&&this.physicalGestureAnimator.destroy(),this.visualEffectAnimator&&"function"==typeof this.visualEffectAnimator.destroy&&this.visualEffectAnimator.destroy(),this.breathGestureAnimator&&"function"==typeof this.breathGestureAnimator.destroy&&this.breathGestureAnimator.destroy(),this.movementGestureAnimator&&"function"==typeof this.movementGestureAnimator.destroy&&this.movementGestureAnimator.destroy(),this.shapeTransformAnimator&&"function"==typeof this.shapeTransformAnimator.destroy&&this.shapeTransformAnimator.destroy(),this.expressionGestureAnimator&&"function"==typeof this.expressionGestureAnimator.destroy&&this.expressionGestureAnimator.destroy(),this.directionalGestureAnimator&&"function"==typeof this.directionalGestureAnimator.destroy&&this.directionalGestureAnimator.destroy(),this.complexAnimationAnimator&&"function"==typeof this.complexAnimationAnimator.destroy&&this.complexAnimationAnimator.destroy(),this.physicalGestureAnimator=null,this.visualEffectAnimator=null,this.breathGestureAnimator=null,this.movementGestureAnimator=null,this.shapeTransformAnimator=null,this.expressionGestureAnimator=null,this.directionalGestureAnimator=null,this.complexAnimationAnimator=null,this.gestureAnimations=null,this.activeGestures.clear(),this.activeGestures=null,this.renderer=null,this.scaleFactor=null,this.isPaused=!1}}class Pn{constructor(){this.colorTransition=null}applyUndertoneModifiers(e,t){return t}applyUndertoneToColor(e,t){if(t&&"object"==typeof t&&void 0!==t.weight){const{weight:i}=t,s=t.type||"clear";if("clear"===s||0===i)return e;const n=this.applyUndertoneSaturation(e,s),a=this.hexToRgb(e),r=this.hexToRgb(n),o=Math.round(a.r+(r.r-a.r)*i),l=Math.round(a.g+(r.g-a.g)*i),h=Math.round(a.b+(r.b-a.b)*i);return this.rgbToHex(o,l,h)}return t&&"clear"!==t?this.applyUndertoneSaturation(e,t):e}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}rgbToHsl(e,t,i){e/=255,t/=255,i/=255;const s=Math.max(e,t,i),n=Math.min(e,t,i),a=(s+n)/2;let r,o;if(s===n)r=o=0;else{const l=s-n;switch(o=a>.5?l/(2-s-n):l/(s+n),s){case e:r=((t-i)/l+(t<i?6:0))/6;break;case t:r=((i-e)/l+2)/6;break;case i:r=((e-t)/l+4)/6}}return{h:360*r,s:100*o,l:100*a}}hslToHex(e,t,i){let s,n,a;if(e/=360,i/=100,0==(t/=100))s=n=a=i;else{const r=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e),o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;s=r(l,o,e+1/3),n=r(l,o,e),a=r(l,o,e-1/3)}const r=e=>{const t=Math.round(255*e).toString(16);return 1===t.length?`0${t}`:t};return`#${r(s)}${r(n)}${r(a)}`}applyUndertoneSaturation(e,t){const i=this.hexToRgb(e),s=this.rgbToHsl(i.r,i.g,i.b),n={intense:1.5,confident:1.3,energetic:1.2,upbeat:1.2,nervous:1.15,mellow:.8,tired:.8,subdued:.5}[t]||1;return s.s=Math.min(100,s.s*n),this.hslToHex(s.h,s.s,s.l)}rgbToHex(e,t,i){const s=e=>{const t=Math.round(e).toString(16);return 1===t.length?`0${t}`:t};return`#${s(e)}${s(t)}${s(i)}`}startColorTransition(e,t,i=1500){this.currentColor===e&&this.currentIntensity===t||(this.colorTransition={active:!0,fromColor:this.currentColor||"#ffffff",toColor:e,fromIntensity:this.currentIntensity||1,toIntensity:t,progress:0,startTime:performance.now(),duration:i})}updateColorTransition(e){if(!this.colorTransition||!this.colorTransition.active)return null;const t=performance.now()-this.colorTransition.startTime,i=Math.min(t/this.colorTransition.duration,1),s=1-Math.pow(1-i,2),n=this.hexToRgb(this.colorTransition.fromColor),a=this.hexToRgb(this.colorTransition.toColor),r=Math.round(n.r+(a.r-n.r)*s),o=Math.round(n.g+(a.g-n.g)*s),l=Math.round(n.b+(a.b-n.b)*s),h=this.rgbToHex(r,o,l),c=this.colorTransition.fromIntensity+(this.colorTransition.toIntensity-this.colorTransition.fromIntensity)*s;return this.currentColor=h,this.currentIntensity=c,i>=1&&(this.colorTransition.active=!1),{color:h,intensity:c}}}class Tn{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvasManager?.canvas||e.canvas,this.recordingActive=!1,this.sleepMode=!1,this.speakingActive=!1,this.speakingRings=[],this.ringSpawnTimer=0,this.ringSpawnInterval=300,this.maxRings=3,this.sleepZ=[],this.sparkles=[],this.chromaticAberration={active:!1,intensity:0,targetIntensity:0,fadeSpeed:.01,maxOffset:30},this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}renderRecordingGlow(e,t,i,s){const{ctx:n}=this,a=2.5*i,r=n.createRadialGradient(e,t,0,e,t,a);r.addColorStop(0,`rgba(255, 0, 0, ${.3*s})`),r.addColorStop(.5,`rgba(255, 0, 0, ${.15*s})`),r.addColorStop(1,"rgba(255, 0, 0, 0)"),n.save(),n.globalCompositeOperation="screen",n.fillStyle=r,n.fillRect(e-a,t-a,2*a,2*a),n.restore()}renderRecordingIndicator(e,t){const i=Date.now()/1e3,s=.8+.2*Math.sin(2*i);this.ctx.save(),this.ctx.translate(e,t),this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=`rgba(255, 0, 0, ${.8*s})`;const n=this.scaleValue(80);this.ctx.font=`italic 900 ${n}px "Poppins", sans-serif`,this.ctx.fillStyle=`rgba(255, 0, 0, ${s})`,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText("REC",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic 900 ${n-1}px "Poppins", sans-serif`,this.ctx.fillStyle=`rgba(255, 255, 255, ${.3*s})`,this.ctx.fillText("REC",-.5,-.5),this.ctx.restore()}renderSleepIndicator(e,t,i){if(this.ringSpawnTimer+=i,this.ringSpawnTimer>=2e3&&this.sleepZ.length<3){const i=["300","500","700","900"],s=i[Math.floor(Math.random()*i.length)],n=Math.random()>.5?"Z":"z";this.sleepZ.push({x:e+Math.random()*this.scaleValue(30)-this.scaleValue(15),y:t+this.scaleValue(80),size:this.scaleValue(3*(24+8*Math.random())),opacity:1,speed:-.025,drift:Math.random()*this.scaleValue(20)-this.scaleValue(10),lifetime:0,rotation:30*Math.random()-15,text:n,weight:s}),this.ringSpawnTimer=0}this.sleepZ=this.sleepZ.filter(e=>{e.lifetime+=i,e.y+=e.speed*i,e.x+=Math.sin(8e-4*e.lifetime)*e.drift*.008,e.rotation+=.01*i;if(e.lifetime<2e3?e.opacity=1:e.lifetime<4e3?e.opacity=1-(e.lifetime-2e3)/2e3:e.opacity=0,e.opacity>.01){this.ctx.save(),this.ctx.translate(e.x,e.y),this.ctx.rotate(e.rotation*Math.PI/180);const t=this.renderer.state.glowColor||"#4a90e2";this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=this.hexToRgba(t,.5*e.opacity);const i=this.ctx.createLinearGradient(-e.size/2,-e.size/2,e.size/2,e.size/2);return i.addColorStop(0,this.hexToRgba(t,e.opacity)),i.addColorStop(.5,this.hexToRgba("#ffffff",.9*e.opacity)),i.addColorStop(1,this.hexToRgba(t,.7*e.opacity)),this.ctx.font=`italic ${e.weight||"900"} ${e.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=i,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(e.text||"Z",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic ${e.weight||"900"} ${.9*e.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=this.hexToRgba("#ffffff",.3*e.opacity),this.ctx.fillText(e.text||"Z",-1,-1),this.ctx.restore(),!0}return!1})}renderSpeakingRings(e,t,i,s){this.ringSpawnTimer+=s,this.ringSpawnTimer>=this.ringSpawnInterval&&this.speakingRings.length<this.maxRings&&(this.speakingRings.push({radius:i,opacity:.8,speed:.15}),this.ringSpawnTimer=0),this.speakingRings=this.speakingRings.filter(n=>(n.radius+=n.speed*s,n.opacity=Math.max(0,.8*(1-(n.radius-i)/(2*i))),n.opacity>.01&&(this.ctx.strokeStyle=this.hexToRgba(this.renderer.state.glowColor,n.opacity),this.ctx.lineWidth=this.scaleValue(2),this.ctx.beginPath(),this.ctx.arc(e,t,n.radius,0,2*Math.PI),this.ctx.stroke(),!0)))}startRecording(){this.recordingActive=!0}stopRecording(){this.recordingActive=!1}enterSleepMode(){this.sleepMode=!0}wakeUp(){this.sleepMode=!1}startSpeaking(){this.speakingActive=!0}stopSpeaking(){this.speakingActive=!1}createSparkle(e,t,i={}){this.sparkles.push({x:e,y:t,vx:i.velocity?.x||0,vy:i.velocity?.y||0,size:i.size||3,color:i.color||"hsl(50, 100%, 70%)",lifetime:i.lifetime||1e3,maxLifetime:i.lifetime||1e3,rotation:Math.random()*Math.PI*2,rotationSpeed:.2*(Math.random()-.5)})}renderSparkles(){const{ctx:e}=this;this.sparkles.forEach(t=>{const i=1-t.lifetime/t.maxLifetime,s=1-i;e.save(),e.translate(t.x,t.y),e.rotate(t.rotation);const n=this.scaleValue(t.size*(1-.5*i));e.beginPath();const a=n,r=.38*n;for(let t=0;t<10;t++){const i=t*Math.PI/5-Math.PI/2,s=t%2==0?a:r;0===t?e.moveTo(Math.cos(i)*s,Math.sin(i)*s):e.lineTo(Math.cos(i)*s,Math.sin(i)*s)}e.closePath(),e.shadowBlur=this.scaleValue(10),e.shadowColor=t.color,e.fillStyle=t.color.replace("70%",70+30*i+"%").replace(")",`, ${s})`).replace("hsl","hsla"),e.fill(),e.restore()})}triggerChromaticAberration(e=.8){this.chromaticAberration.active=!0,this.chromaticAberration.targetIntensity=Math.min(1,e),this.chromaticAberration.intensity=this.chromaticAberration.targetIntensity;const t=document.getElementById("emotive-canvas")||document.querySelector("canvas")||this.canvas;if(t){if(t.style.animation="none",t.offsetHeight,!document.getElementById("chromatic-styles")){const e=document.createElement("style");e.id="chromatic-styles",e.textContent="\n @keyframes chromaticGlitch {\n 0% {\n filter: none;\n transform: translateX(0);\n }\n 15% {\n filter: drop-shadow(-2px 0 0 rgba(255,0,0,0.7)) drop-shadow(2px 0 0 rgba(0,255,255,0.7));\n transform: translateX(-0.5px);\n }\n 30% {\n filter: drop-shadow(-3px 0 0 rgba(255,0,0,0.8)) drop-shadow(3px 0 0 rgba(0,255,255,0.8));\n transform: translateX(0.5px);\n }\n 45% {\n filter: drop-shadow(-2px 0 0 rgba(255,0,0,0.6)) drop-shadow(2px 0 0 rgba(0,255,255,0.6));\n transform: translateX(-0.3px);\n }\n 60% {\n filter: drop-shadow(-1px 0 0 rgba(255,0,0,0.4)) drop-shadow(1px 0 0 rgba(0,255,255,0.4));\n transform: translateX(0.2px);\n }\n 100% {\n filter: none;\n transform: translateX(0);\n }\n }\n ",document.head.appendChild(e)}t.style.animation=`chromaticGlitch ${300+200*e}ms ease-out`}}applyChromaticAberration(e,t){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return;const{intensity:i}=this.chromaticAberration,s=this.scaleValue(this.chromaticAberration.maxOffset*i),n=e.globalCompositeOperation;e.save(),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.globalCompositeOperation="source-over",e.filter="url(#red-channel)",e.drawImage(t,-s,0),e.globalCompositeOperation="screen",e.filter="url(#green-channel)",e.drawImage(t,0,0),e.globalCompositeOperation="screen",e.filter="url(#blue-channel)",e.drawImage(t,s,0),e.filter="none",e.globalCompositeOperation=n,e.restore()}applyChromaticAberrationSimple(e,t,i,s,n){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return void n();const{intensity:a}=this.chromaticAberration,r=this.scaleValue(this.chromaticAberration.maxOffset*a);e.save(),e.globalCompositeOperation="source-over",e.translate(-r,0),e.globalAlpha=.33,e.fillStyle="#ff0000",e.filter="brightness(3)",n(),e.translate(r,0),e.globalCompositeOperation="screen",e.globalAlpha=.33,e.fillStyle="#00ff00",n(),e.translate(r,0),e.globalAlpha=.33,e.fillStyle="#0000ff",n(),e.restore()}update(e){this.sparkles=this.sparkles.filter(t=>(t.x+=t.vx,t.y+=t.vy,t.rotation+=t.rotationSpeed,t.lifetime-=e,t.vy+=.1,t.lifetime>0)),this.chromaticAberration.active&&(this.chromaticAberration.intensity-=this.chromaticAberration.fadeSpeed,this.chromaticAberration.intensity<=0&&(this.chromaticAberration.intensity=0,this.chromaticAberration.active=!1,this.chromaticAberration.targetIntensity=0))}destroy(){this.speakingRings=[],this.sleepZ=[],this.sparkles=[],this.recordingActive=!1,this.sleepMode=!1,this.speakingActive=!1,this.chromaticAberration.active=!1,this.chromaticAberration.intensity=0,this.chromaticAberration.targetIntensity=0,this.ringSpawnTimer=0,this.renderer=null,this.ctx=null,this.canvas=null}}class En{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.blinking=!1,this.blinkingEnabled=!0,this.blinkTimer=0,this.nextBlinkTime=this.getRandomBlinkTime(),this.squintAmount=0,this.eyeClose=null,this.eyeOpen=null,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}update(e){this.blinking&&(this.blinkTimer+=e,this.blinkTimer>=150&&(this.blinking=!1,this.blinkTimer=0,this.nextBlinkTime=Date.now()+this.getRandomBlinkTime())),this.blinkingEnabled&&!this.blinking&&Date.now()>=this.nextBlinkTime&&this.startBlink()}startBlink(){this.blinkingEnabled&&(this.blinking=!0,this.blinkTimer=0)}getRandomBlinkTime(){return 3e3+4e3*Math.random()}getBlinkScale(){if(!this.blinking)return 1;const e=Math.min(this.blinkTimer/150,1);return 1-.7*Math.sin(e*Math.PI)}drawEyes(e,t,i,s,n={}){const{ctx:a}=this,r=n.eyeOpenness||1,o=n.eyeExpression||"neutral";if("neutral"===s||r<=0)return;a.save(),a.strokeStyle="rgba(0, 0, 0, 0.3)",a.lineWidth=this.scaleValue(2),a.lineCap="round";const l=.4*i,h=t-.1*i,c=.25*i;switch(o){case"happy":this.drawHappyEyes(a,e,h,l,c,r);break;case"sad":this.drawSadEyes(a,e,h,l,c,r);break;case"angry":this.drawAngryEyes(a,e,h,l,c,r);break;case"surprised":this.drawSurprisedEyes(a,e,h,l,c,r);break;case"focused":this.drawFocusedEyes(a,e,h,l,c,r);break;case"sleepy":this.drawSleepyEyes(a,e,h,l,c,r);break;case"suspicious":this.drawSuspiciousEyes(a,e,h,l,c,r)}a.restore()}drawHappyEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i,n,.2*Math.PI,.8*Math.PI,!1),e.stroke(),e.beginPath(),e.arc(t+s,i,n,.2*Math.PI,.8*Math.PI,!1),e.stroke()}drawSadEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),e.stroke(),e.beginPath(),e.arc(t+s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),e.stroke()}drawAngryEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i-.3*n),e.lineTo(t-s+.5*n,i+.3*n),e.stroke(),e.beginPath(),e.moveTo(t+s+n,i-.3*n),e.lineTo(t+s-.5*n,i+.3*n),e.stroke()}drawSurprisedEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i,1.2*n,0,2*Math.PI),e.stroke(),e.beginPath(),e.arc(t+s,i,1.2*n,0,2*Math.PI),e.stroke()}drawFocusedEyes(e,t,i,s,n,a){e.fillStyle="rgba(0, 0, 0, 0.4)",e.beginPath(),e.arc(t-s,i,.3*n,0,2*Math.PI),e.fill(),e.beginPath(),e.arc(t+s,i,.3*n,0,2*Math.PI),e.fill()}drawSleepyEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i),e.lineTo(t-s+n,i),e.stroke(),e.beginPath(),e.moveTo(t+s-n,i),e.lineTo(t+s+n,i),e.stroke()}drawSuspiciousEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i),e.lineTo(t-s+.7*n,i),e.stroke(),e.beginPath(),e.arc(t+s,i,.8*n,.1*Math.PI,.9*Math.PI,!1),e.stroke()}setBlinkingEnabled(e){this.blinkingEnabled=e,e||(this.blinking=!1,this.blinkTimer=0)}setSquintAmount(e){this.squintAmount=Math.max(0,Math.min(1,e))}forceBlink(){this.startBlink()}}class An{constructor(e){this.renderer=e,this.breathingSpeed=.42,this.breathingDepth=.08,this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null,this.emotionBreathPatterns={happy:{rate:1.1,depth:1.2},sad:{rate:.8,depth:.7},angry:{rate:1.4,depth:1.3},calm:{rate:.7,depth:.9},excited:{rate:1.5,depth:1.4},focused:{rate:.9,depth:.6},neutral:{rate:1,depth:1},love:{rate:1.2,depth:1.3},surprised:{rate:1.3,depth:1.1},confused:{rate:1.1,depth:.9},amused:{rate:1.2,depth:1.1},bored:{rate:.6,depth:.8},tired:{rate:.5,depth:1.2},anxious:{rate:1.6,depth:.9},determined:{rate:1.1,depth:1},proud:{rate:.9,depth:1.3},content:{rate:.8,depth:1},hopeful:{rate:1,depth:1.1},intrigued:{rate:1.1,depth:.8},embarrassed:{rate:1.3,depth:.7},grateful:{rate:.9,depth:1.1},inspired:{rate:1,depth:1.3},silly:{rate:1.4,depth:1.2},sleepy:{rate:.3,depth:1.4}}}update(e,t,i={}){i=i||{};const s=this.emotionBreathPatterns[t]||{rate:1,depth:1},n=i?.breathRateMult||1,a=i?.breathDepthMult||1;this.breathRate=s.rate*this.breathRateMult*n,this.breathDepth=this.breathingDepth*s.depth*this.breathDepthMult*a;let r=this.breathingSpeed*this.breathRate*(e/1e3);this.breathIrregular&&i?.breathIrregular&&(r*=.8+.4*Math.sin(3e-4*Date.now())),this.breathingPhase+=r,this.breathingPhase>2*Math.PI&&(this.breathingPhase-=2*Math.PI)}getBreathingScale(){return null!==this.customScale?this.customScale:1+Math.sin(this.breathingPhase)*this.breathDepth}setCustomScale(e){this.customScale=e}setBreathingSpeed(e){this.breathingSpeed=e}setBreathingDepth(e){this.breathingDepth=Math.max(0,Math.min(1,e))}setBreathRateMultiplier(e){this.breathRateMult=e}setBreathDepthMultiplier(e){this.breathDepthMult=e}setIrregularBreathing(e){this.breathIrregular=e}reset(){this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null}holdBreath(e=!1){this.customScale=e?.92:1.08}releaseBreath(){this.customScale=null}getBreathingInfo(){return{phase:this.breathingPhase,rate:this.breathRate,depth:this.breathDepth,scale:this.getBreathingScale(),isCustom:null!==this.customScale,isIrregular:this.breathIrregular}}}class Dn{constructor(){this.cache=new Map,this.stats={hits:0,misses:0,evictions:0},this.maxSize=100,this.ttl=6e4,this.accessOrder=[],this.cleanupInterval=setInterval(()=>{this.clearExpired()},6e4)}generateKey(e,t){if("radial"===e){const{x0:e,y0:i,r0:s,x1:n,y1:a,r1:r,stops:o}=t;return`radial:${e},${i},${s},${n},${a},${r}:${o.map(e=>`${e.offset}:${e.color}`).join("|")}`}if("linear"===e){const{x0:e,y0:i,x1:s,y1:n,stops:a}=t;return`linear:${e},${i},${s},${n}:${a.map(e=>`${e.offset}:${e.color}`).join("|")}`}return null}getRadialGradient(e,t,i,s,n,a,r,o){const l=this.generateKey("radial",{x0:t,y0:i,r0:s,x1:n,y1:a,r1:r,stops:o}),h=this.cache.get(l);if(h&&Date.now()-h.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(l),h.gradient;this.stats.misses++;const c=e.createRadialGradient(t,i,s,n,a,r);return o.forEach(e=>{c.addColorStop(e.offset,e.color)}),this.set(l,c),c}getLinearGradient(e,t,i,s,n,a){const r=this.generateKey("linear",{x0:t,y0:i,x1:s,y1:n,stops:a}),o=this.cache.get(r);if(o&&Date.now()-o.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(r),o.gradient;this.stats.misses++;const l=e.createLinearGradient(t,i,s,n);return a.forEach(e=>{l.addColorStop(e.offset,e.color)}),this.set(r,l),l}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{gradient:t,timestamp:Date.now()}),this.updateAccessOrder(e)}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){const e=this.accessOrder.shift();this.cache.delete(e),this.stats.evictions++}}clear(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.cache.clear(),this.accessOrder=[]}clearExpired(){const e=Date.now(),t=[];for(const[i,s]of this.cache.entries())e-s.timestamp>=this.ttl&&t.push(i);t.forEach(e=>{this.cache.delete(e);const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)})}destroy(){this.clear()}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate:`${e}%`}}createHelper(e){return{radial:(t,i,s,n,a,r,o)=>this.getRadialGradient(e,t,i,s,n,a,r,o),linear:(t,i,s,n,a)=>this.getLinearGradient(e,t,i,s,n,a)}}}const _n=new Dn;class In{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.glowIntensity=1,this.glowColor="#4a90e2",this.targetGlowColor="#4a90e2",this.glowColorTransition=0,this.glowColorTransitionSpeed=.05,this.offscreenCanvas=null,this.offscreenCtx=null,this.cachedGlowColor=null,this.cachedGlowRadius=0,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i),this.initOffscreenCanvas()}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d")}updateOffscreenSize(e){this.offscreenCanvas.width===e&&this.offscreenCanvas.height===e||(this.offscreenCanvas.width=e,this.offscreenCanvas.height=e,this.cachedGlowColor=null)}renderGlow(e,t,i,s={}){const{ctx:n}=this,a=s.color||this.glowColor,r=void 0!==s.intensity?s.intensity:this.glowIntensity;r<.01||this.renderGlowDirect(n,e,t,i,a,r)}cacheGlowGradient(e,t){const i=this.offscreenCtx,s=t;this.updateOffscreenSize(2*t),i.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height);const n=_n.getRadialGradient(i,s,s,0,s,s,t,[{offset:0,color:this.hexToRgba(e,.4)},{offset:.3,color:this.hexToRgba(e,.2)},{offset:.6,color:this.hexToRgba(e,.1)},{offset:1,color:this.hexToRgba(e,0)}]);i.fillStyle=n,i.fillRect(0,0,2*t,2*t),this.cachedGlowColor=e,this.cachedGlowRadius=t}renderGlowDirect(e,t,i,s,n,a){e.save(),e.globalCompositeOperation="screen";const r=[];for(let e=0;e<=20;e++){const t=e/20,i=.6*Math.pow(1-t,2.2),s=Math.max(0,Math.min(1,i*a));r.push({offset:t,color:this.hexToRgba(n,s)})}const o=_n.getRadialGradient(e,t,i,0,t,i,s,r);e.fillStyle=o,e.beginPath(),e.arc(t,i,s,0,2*Math.PI),e.fill(),e.restore()}renderRecordingGlow(e,t,i,s){const{ctx:n}=this,a=2.5*i,r=_n.getRadialGradient(n,e,t,0,e,t,a,[{offset:0,color:`rgba(255, 0, 0, ${.3*s})`},{offset:.5,color:`rgba(255, 0, 0, ${.15*s})`},{offset:1,color:"rgba(255, 0, 0, 0)"}]);n.save(),n.globalCompositeOperation="screen",n.fillStyle=r,n.fillRect(e-a,t-a,2*a,2*a),n.restore()}updateGlowColor(e,t){this.targetGlowColor!==e&&(this.targetGlowColor=e,this.glowColorTransition=0),this.glowColorTransition<1&&(this.glowColorTransition=Math.min(1,this.glowColorTransition+this.glowColorTransitionSpeed),this.glowColor=this.lerpColor(this.glowColor,this.targetGlowColor,this.glowColorTransition))}lerpColor(e,t,i){const s=this.hexToRgb(e),n=this.hexToRgb(t);return`#${((1<<24)+(Math.round(s.r+(n.r-s.r)*i)<<16)+(Math.round(s.g+(n.g-s.g)*i)<<8)+Math.round(s.b+(n.b-s.b)*i)).toString(16).slice(1)}`}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:{r:0,g:0,b:0}}setGlowIntensity(e){this.glowIntensity=Math.max(0,Math.min(1,e))}setGlowColor(e){this.glowColor=e,this.targetGlowColor=e,this.glowColorTransition=1}destroy(){this.offscreenCanvas&&(this.offscreenCtx&&(this.offscreenCtx.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),this.offscreenCtx=null),this.offscreenCanvas.width=0,this.offscreenCanvas.height=0,this.offscreenCanvas=null),this.cachedGlowColor=null,this.cachedGlowRadius=0}}class Rn{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.coreColor="#FFFFFF",this.coreOpacity=1,this.coreBorderWidth=0,this.coreBorderColor=null,this.shapePoints=null,this.isMorphing=!1,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}renderCore(e,t,i,s={}){const{ctx:n}=this,a=s.scaleX||1,r=s.scaleY||1,o=s.rotation||0,l=void 0!==s.opacity?s.opacity:this.coreOpacity,h=s.color||this.coreColor,c=s.shapePoints||this.shapePoints;n.save(),n.translate(e,t),0!==o&&n.rotate(o),n.scale(a,r),n.fillStyle=this.hexToRgba(h,l),c&&c.length>0?this.drawMorphedShape(n,c,i):this.drawCircle(n,i),this.coreBorderWidth>0&&this.coreBorderColor&&(n.strokeStyle=this.coreBorderColor,n.lineWidth=this.scaleValue(this.coreBorderWidth),n.stroke()),n.restore()}drawDropShadow(e,t,i){e.save();const s=this.scaleValue(2);if(e.translate(0,s),i&&i.length>32)e.fillStyle="rgba(0, 0, 0, 0.15)",e.beginPath(),e.arc(0,0,1.05*t,0,2*Math.PI),e.fill();else{const s=_n.getRadialGradient(e,0,0,.7*t,0,0,1.2*t,[{offset:0,color:"rgba(0, 0, 0, 0.2)"},{offset:.8,color:"rgba(0, 0, 0, 0.1)"},{offset:1,color:"rgba(0, 0, 0, 0)"}]);if(e.fillStyle=s,e.beginPath(),i){const t=1.1,s=i.length>20?2:1;e.moveTo(i[0].x*t,i[0].y*t);for(let n=s;n<i.length;n+=s)e.lineTo(i[n].x*t,i[n].y*t);e.closePath()}else e.arc(0,0,1.1*t,0,2*Math.PI);e.fill()}e.restore()}drawCircle(e,t){e.beginPath(),e.arc(0,0,t,0,2*Math.PI),e.fill()}drawMorphedShape(e,t,i){!t||t.length<3?this.drawCircle(e,i):(e.beginPath(),t.forEach((t,i)=>{0===i?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath(),e.fill())}renderSleepyCore(e,t,i){const{ctx:s}=this;s.save(),s.translate(e,t),s.scale(1,.85),s.fillStyle="#FFFFFF",s.beginPath(),s.arc(0,0,i,0,2*Math.PI),s.fill(),s.restore()}renderGlitchedCore(e,t,i,s){const{ctx:n}=this;n.save(),[{x:-2,y:0,alpha:.3},{x:2,y:0,alpha:.3},{x:0,y:-1,alpha:.2}].forEach(a=>{n.fillStyle=this.hexToRgba("#FFFFFF",a.alpha*s),n.beginPath(),n.arc(e+a.x*s*this.scaleValue(5),t+a.y*s*this.scaleValue(5),i,0,2*Math.PI),n.fill()}),n.fillStyle="#FFFFFF",n.beginPath(),n.arc(e,t,i,0,2*Math.PI),n.fill(),n.restore()}setShapePoints(e){this.shapePoints=e,this.isMorphing=e&&e.length>0}clearShapePoints(){this.shapePoints=null,this.isMorphing=!1}setCoreColor(e){this.coreColor=e}setCoreOpacity(e){this.coreOpacity=Math.max(0,Math.min(1,e))}setCoreBorder(e,t){this.coreBorderWidth=e,this.coreBorderColor=t}getCoreInfo(){return{color:this.coreColor,opacity:this.coreOpacity,hasBorder:this.coreBorderWidth>0,isMorphing:this.isMorphing,shapePointCount:this.shapePoints?this.shapePoints.length:0}}}class Bn{renderSunEffects(e,t,i,s,n){const a=Date.now()/100;if(e.save(),e.translate(t,i),n.texture&&(void 0===n.textureOpacity||n.textureOpacity>0)){e.save(),e.globalCompositeOperation="screen",e.globalAlpha=void 0!==n.textureOpacity?n.textureOpacity:1;const t=.05*a*(n.turbulence||.3)/.3,i=e.createRadialGradient(Math.sin(t)*s*.15,Math.cos(.7*t)*s*.15,.2*s,0,0,s);i.addColorStop(0,"rgba(255, 255, 200, 0)"),i.addColorStop(.4,"rgba(255, 200, 100, 0.1)"),i.addColorStop(.7,"rgba(255, 150, 50, 0.08)"),i.addColorStop(1,"rgba(255, 100, 30, 0.05)"),e.fillStyle=i,e.beginPath(),e.arc(0,0,s,0,2*Math.PI),e.fill(),e.restore()}const r=void 0!==n.coronaOpacity?n.coronaOpacity:1;if(r>0){e.save(),e.globalCompositeOperation="screen";const t=e.createRadialGradient(0,0,.5*s,0,0,1.1*s);t.addColorStop(0,`rgba(255, 255, 255, ${.8*r})`),t.addColorStop(.3,`rgba(255, 250, 200, ${.6*r})`),t.addColorStop(.5,`rgba(255, 200, 100, ${.4*r})`),t.addColorStop(.7,`rgba(255, 150, 50, ${.2*r})`),t.addColorStop(1,"rgba(255, 100, 20, 0)"),e.fillStyle=t,e.beginPath(),e.arc(0,0,1.1*s,0,2*Math.PI),e.fill();for(let t=0;t<2;t++){const i=1.3+.4*t,n=(.35-.15*t)*r,o=.05*Math.sin(.1*a+t),l=e.createRadialGradient(0,0,s*(.9+o),0,0,s*(i+o));l.addColorStop(0,"rgba(255, 255, 200, 0)"),l.addColorStop(.4,`rgba(255, 200, 100, ${.5*n})`),l.addColorStop(.7,`rgba(255, 150, 50, ${n})`),l.addColorStop(.9,`rgba(255, 100, 30, ${.5*n})`),l.addColorStop(1,"rgba(255, 50, 10, 0)"),e.fillStyle=l,e.beginPath(),e.arc(0,0,s*(i+o),0,2*Math.PI),e.fill()}e.restore()}if(n.flares){e.save();const t=Math.sin(.08*a),i=Math.sin(.12*a),n=Math.sin(.16*a),r=e.createLinearGradient(0,-s,0,3*-s);r.addColorStop(0,"rgba(255, 255, 230, 0.4)"),r.addColorStop(.2,"rgba(255, 220, 150, 0.25)"),r.addColorStop(.5,"rgba(255, 180, 80, 0.15)"),r.addColorStop(.8,"rgba(255, 120, 40, 0.08)"),r.addColorStop(1,"rgba(255, 60, 20, 0)"),e.fillStyle=r,e.globalCompositeOperation="screen",e.beginPath();const o=(t,i,n,a)=>{const r=Math.cos(t),o=Math.sin(t),l=r*s,h=o*s,c=r*(s+i),u=o*(s+i),d=-o*n*.5,g=r*n*.5,m=a*n*.3;e.moveTo(l-d,h-g),e.quadraticCurveTo(.5*(l+c)+d*m,.5*(h+u)+g*m,c,u),e.quadraticCurveTo(.5*(l+c)-d*m,.5*(h+u)-g*m,l+d,h+g)};for(let e=0;e<8;e++)o(e/8*Math.PI*2+.1*t,s*(1.8+.4*Math.sin(.1*a+.5*e)),.18*s,Math.sin(.15*a+e));for(let e=0;e<12;e++)o((e+.5)/12*Math.PI*2+.08*i,s*(1.2+.3*Math.sin(.13*a+.7*e)),.12*s,Math.sin(.18*a+1.2*e));for(let e=0;e<15;e++)o(e/15*Math.PI*2+.05*n,s*(.7+.25*Math.sin(.17*a+.9*e)),.08*s,Math.sin(.2*a+1.5*e));for(let t=0;t<15;t++){const i=(t+.25)/15*Math.PI*2,n=s*(.4+.2*Math.sin(.22*a+t)),r=.06*s,o=Math.cos(i),l=Math.sin(i),h=o*s,c=l*s,u=o*(s+n),d=l*(s+n),g=-l*r*.5,m=o*r*.5;e.moveTo(h-g,c-m),e.lineTo(u,d),e.lineTo(h+g,c+m)}e.fill(),e.restore()}const o=e.createRadialGradient(0,0,.95*s,0,0,1.05*s);o.addColorStop(0,"rgba(255, 255, 255, 0)"),o.addColorStop(.7,"rgba(255, 255, 200, 0.2)"),o.addColorStop(.9,"rgba(255, 200, 100, 0.5)"),o.addColorStop(1,"rgba(255, 150, 50, 0.3)"),e.fillStyle=o,e.beginPath(),e.arc(0,0,1.05*s,0,2*Math.PI),e.fill(),e.restore()}renderBaileysBeads(e,t,i,s,n,a,r,o,l,h=e=>e){if(!l)return void(this._beadStartTime=null);const c=Math.abs(n)<1&&Math.abs(a)<1,u=o?30:15;if(!(Math.abs(n)<u&&Math.abs(a)<u||c))return void(this._beadStartTime=null);if(!this._beadStartTime){const e=Math.floor(4*Math.random())+1;this._currentBeads=[];const t=[];for(let i=0;i<e;i++)t.push(Math.random()*Math.PI*2);const i=Array.from({length:e},(e,t)=>t);for(let e=i.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[i[e],i[t]]=[i[t],i[e]]}for(let s=0;s<e;s++)this._currentBeads.push({angle:t[s],size:3+5*Math.random(),order:i[s],delay:200*i[s]});this._beadStartTime=Date.now()}const d=Date.now()-this._beadStartTime;(this._currentBeads||[]).forEach(n=>{if(d<n.delay)return;const a=d-n.delay,r=Math.min(1,a/300),o=t+Math.cos(n.angle)*s,l=i+Math.sin(n.angle)*s;e.save(),e.translate(o,l),e.globalAlpha=r;const c=h(n.size),u=[{color:`rgba(255, 100, 100, ${.6*r})`,offset:-2},{color:`rgba(100, 255, 100, ${.6*r})`,offset:0},{color:`rgba(100, 100, 255, ${.6*r})`,offset:2}];e.globalCompositeOperation="screen",u.forEach(({color:t,offset:i})=>{const s=e.createRadialGradient(i,i,0,i,i,2*c);s.addColorStop(0,t),s.addColorStop(.2,t.replace(""+.6*r,""+.4*r)),s.addColorStop(.5,t.replace(""+.6*r,""+.2*r)),s.addColorStop(1,"rgba(255, 255, 255, 0)"),e.fillStyle=s,e.beginPath(),e.arc(i,i,2*c,0,2*Math.PI),e.fill()}),e.globalCompositeOperation="lighter";const g=e.createRadialGradient(0,0,0,0,0,c);g.addColorStop(0,`rgba(255, 255, 255, ${r})`),g.addColorStop(.3,`rgba(255, 255, 255, ${.5*r})`),g.addColorStop(1,"rgba(255, 255, 255, 0)"),e.fillStyle=g,e.beginPath(),e.arc(0,0,c,0,2*Math.PI),e.fill(),e.restore()})}renderMoonShadow(e,t,i,s,n,a,r=!1,o=0,l=null){if(e.save(),e.globalAlpha=1,e.translate(t,i),"crescent"===n.type){let t=1,i=n.offset||.7;if(l){const e=l.getProgress(),{targetShape:s}=l;"moon"===s&&void 0!==e&&e<1&&!n.shadowX&&(t=e,i=2.7*t-2)}const r=(n.angle||-30)*Math.PI/180,o=Math.cos(r)*s*i,h=Math.sin(r)*s*i;if(e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.beginPath(),a&&a.length>0){e.moveTo(a[0].x,a[0].y);for(let t=1;t<a.length;t++)e.lineTo(a[t].x,a[t].y);e.closePath()}else e.arc(0,0,s,0,2*Math.PI);e.clip();const c=e.createRadialGradient(o,h,.9*s,o,h,1.1*s),u=void 0!==n.coverage?n.coverage:.85,d=Math.min(1,1.2*t)*(u/.85);c.addColorStop(0,`rgba(0, 0, 0, ${1*d})`),c.addColorStop(.8,`rgba(0, 0, 0, ${1*d})`),c.addColorStop(.88,`rgba(0, 0, 0, ${.98*d})`),c.addColorStop(.91,`rgba(0, 0, 0, ${.95*d})`),c.addColorStop(.93,`rgba(0, 0, 0, ${.9*d})`),c.addColorStop(.95,`rgba(0, 0, 0, ${.8*d})`),c.addColorStop(.96,`rgba(0, 0, 0, ${.65*d})`),c.addColorStop(.97,`rgba(0, 0, 0, ${.45*d})`),c.addColorStop(.98,`rgba(0, 0, 0, ${.25*d})`),c.addColorStop(.99,`rgba(0, 0, 0, ${.1*d})`),c.addColorStop(1,"rgba(0, 0, 0, 0)"),e.fillStyle=c,e.beginPath(),e.arc(o,h,1.1*s,0,2*Math.PI),e.fill()}else if("lunar"===n.type){const t=1-(void 0!==n.diffusion?n.diffusion:1);let i=0,a=0;if(l){const e=l.getProgress(),{currentShape:t,targetShape:n}=l;if(r&&"solar"===n&&void 0!==e&&e<1){const t=2.5*s;i=-t*(1-e),a=t*(1-e)}else if(r&&"solar"===t&&"solar"!==n&&null!==n&&void 0!==e&&e<1){const t=2.5*s;i=t*e,a=-t*e}}e.translate(i,a),r?(e.save(),e.beginPath(),e.arc(-i,-a,s,0,2*Math.PI),e.clip()):(e.beginPath(),e.arc(0,0,s,0,2*Math.PI),e.clip());const o=s*(1.8-.5*t),h=e.createRadialGradient(0,0,.2*s,0,0,o),c=n.coverage||.9;if(n.color&&n.color.includes("0, 0, 0")?(h.addColorStop(0,`rgba(0, 0, 0, ${c})`),h.addColorStop(.3+.2*t,`rgba(0, 0, 0, ${.95*c})`),h.addColorStop(.6+.2*t,`rgba(0, 0, 0, ${.8*c})`),h.addColorStop(.85,`rgba(0, 0, 0, ${.4*c})`),h.addColorStop(1,"rgba(0, 0, 0, 0)")):(h.addColorStop(0,`rgba(10, 2, 0, ${c})`),h.addColorStop(.3+.2*t,`rgba(20, 5, 0, ${.95*c})`),h.addColorStop(.6+.2*t,`rgba(40, 10, 5, ${.8*c})`),h.addColorStop(.85,`rgba(60, 15, 10, ${.4*c})`),h.addColorStop(1,"rgba(80, 20, 15, 0)")),e.fillStyle=h,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),t>.3){const i=s*(.8+.3*t),a=e.createRadialGradient(0,0,0,0,0,i);n.color&&n.color.includes("0, 0, 0")?(a.addColorStop(0,`rgba(0, 0, 0, ${c})`),a.addColorStop(.5,`rgba(0, 0, 0, ${.9*c})`),a.addColorStop(.8,`rgba(0, 0, 0, ${.5*c})`),a.addColorStop(1,"rgba(0, 0, 0, 0)")):(a.addColorStop(0,`rgba(0, 0, 0, ${c})`),a.addColorStop(.5,`rgba(10, 2, 0, ${.9*c})`),a.addColorStop(.8,`rgba(20, 5, 0, ${.5*c})`),a.addColorStop(1,"rgba(30, 8, 5, 0)")),e.fillStyle=a,e.beginPath(),e.arc(0,0,i,0,2*Math.PI),e.fill()}}r&&e.restore(),e.restore()}}class zn{constructor(e){this.renderer=e,this.episodicEffects={nervous:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:3e3+2e3*Math.random()},confident:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:4e3+2e3*Math.random()},tired:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:5e3+2e3*Math.random()},intense:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:3e3+3e3*Math.random()},subdued:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:4e3+3e3*Math.random()}}}getEpisodicEffects(){return this.episodicEffects}updateEpisodicEffects(e,t,i,s,n){if(!e||!this.episodicEffects[e])return{jitterX:t,jitterY:i,coreRadius:s,glowRadius:n};const a=this.episodicEffects[e],r=performance.now();if(!a.active&&r>=a.nextTrigger)switch(a.active=!0,a.startTime=r,e){case"nervous":a.duration=500+500*Math.random(),a.intensity=2+Math.random(),a.nextTrigger=r+3e3+2e3*Math.random();break;case"confident":a.duration=1e3+1e3*Math.random(),a.intensity=.15,a.nextTrigger=r+4e3+2e3*Math.random();break;case"tired":a.duration=1e3+2e3*Math.random(),a.intensity=.2,a.nextTrigger=r+5e3+2e3*Math.random();break;case"intense":a.duration=500+500*Math.random(),a.intensity=.5,a.nextTrigger=r+3e3+3e3*Math.random();break;case"subdued":a.duration=2e3+1e3*Math.random(),a.intensity=.3,a.nextTrigger=r+4e3+3e3*Math.random()}if(a.active){const o=r-a.startTime;if(o<a.duration){const r=o/a.duration;switch(e){case"nervous":{const e=1-r,s=15,n=Math.sin(r*Math.PI*s)*e;t=n*a.intensity,i=n*a.intensity*.7;break}case"confident":{const e=Math.sin(r*Math.PI);s*=1+a.intensity*e,n*=1+.5*a.intensity*e;break}case"tired":{const e=Math.sin(r*Math.PI*.5);s*=1-a.intensity*e,i+=5*e;break}case"intense":{const e=1-Math.cos(r*Math.PI);s*=1-.05*e,n*=1+a.intensity*e;break}case"subdued":{const e=Math.sin(r*Math.PI*.5);s*=1-.1*e,n*=1-a.intensity*e;break}}}else a.active=!1}return{jitterX:t,jitterY:i,coreRadius:s,glowRadius:n}}reset(){Object.keys(this.episodicEffects).forEach(e=>{this.episodicEffects[e].active=!1,this.episodicEffects[e].startTime=0,this.episodicEffects[e].duration=0,this.episodicEffects[e].intensity=0})}getEpisodeState(e){return this.episodicEffects[e]||null}isEpisodeActive(e){const t=this.episodicEffects[e];return!!t&&t.active}}class Fn{constructor(e){this.renderer=e,this.brakeStartTime=null,this.brakeDuration=2500,this.brakeStartRotation=0,this.brakeTargetRotation=0,this.brakeStartVelocity=0,this.onComplete=null,this.onProgress=null,this.DURATION_FACTOR=14}brakeToUpright(e={}){return this.brakeToTarget(0,e)}brakeToNearest(e,t={}){const i=this.renderer.state.manualRotation||0,s=Math.round(i/e)*e;return this.brakeToTarget(s,t)}brakeToTarget(e,t={}){return new Promise(i=>{const{onProgress:s=null,onComplete:n=null}=t;this.onProgress=s,this.onComplete=n;const a=this.renderer.state.rotationSpeed||0,r=this.renderer.state.manualRotation||0;if(0===a||this.brakeStartTime)return void i();if(this.brakeStartTime=performance.now(),this.brakeStartRotation=r,this.brakeStartVelocity=a,0===e)this.brakeTargetRotation=a>0?360*(Math.floor(r/360)+1):360*Math.floor(r/360);else{const t=e%360,i=Math.floor(r/360);this.brakeTargetRotation=a>0?t>r%360?360*i+t:360*(i+1)+t:t<r%360?360*i+t:360*(i-1)+t}const o=Math.abs(this.brakeTargetRotation-this.brakeStartRotation);this.brakeDuration=Math.max(500,o/Math.abs(a)*this.DURATION_FACTOR*5),this.renderer.setRotationSpeed(0),this.resolvePromise=i})}updateBrake(e){if(!this.brakeStartTime)return null;const t=e-this.brakeStartTime,i=Math.min(t/this.brakeDuration,1),s=1-Math.pow(1-i,4),n=this.brakeStartRotation+(this.brakeTargetRotation-this.brakeStartRotation)*s,a=this.brakeStartVelocity*Math.pow(1-s,2);return this.onProgress&&this.onProgress(s,a,n),i>=1?(this.brakeStartTime=null,this.complete(),{rotation:this.brakeTargetRotation,speed:0,complete:!0}):{rotation:n,speed:a,complete:!1}}stop(){this.brakeStartTime=null}complete(){this.onComplete&&this.onComplete(),this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=null)}isBraking(){return null!==this.brakeStartTime}emergencyStop(){this.stop(),this.renderer.setRotationSpeed(0),this.complete()}getProgress(){if(!this.brakeStartTime)return 0;const e=performance.now()-this.brakeStartTime;return Math.min(e/this.brakeDuration,1)}destroy(){this.stop(),this.onComplete=null,this.onProgress=null,this.resolvePromise=null,this.renderer=null,this.brakeStartTime=null,this.brakeStartRotation=0,this.brakeTargetRotation=0,this.brakeStartVelocity=0}}class On{constructor(e){this.renderer=e,this.rotationBrake=new Fn(e)}setRotationSpeed(e){this.renderer.state.rotationSpeed=e}setRotationAngle(e){this.renderer.state.manualRotation=e}getRotationAngle(){return this.renderer.state.manualRotation}getRotationSpeed(){return this.renderer.state.rotationSpeed}isBraking(){return this.rotationBrake&&this.rotationBrake.isBraking()}updateRotation(e){if(this.rotationBrake&&this.rotationBrake.isBraking()){const t=this.rotationBrake.updateBrake(e);t&&(this.renderer.state.manualRotation=t.rotation,this.renderer.state.rotationSpeed=t.complete?0:t.speed)}else 0!==this.renderer.state.rotationSpeed&&(this.renderer.state.manualRotation+=this.renderer.state.rotationSpeed);this.renderer.state.lastRotationUpdate=e}calculateTotalRotation(e=0,t=0){return(e+t+this.renderer.state.manualRotation)*Math.PI/180}applyRotation(e,t){0!==t&&e.rotate(t)}applyRotationTransform(e,t,i,s){this.updateRotation(performance.now());const n=this.calculateTotalRotation(s);return 0!==n&&(e.save(),e.translate(t,i),this.applyRotation(e,n),e.translate(-t,-i)),n}reset(){this.renderer.state.manualRotation=0,this.renderer.state.rotationSpeed=0,this.renderer.state.lastRotationUpdate=performance.now()}destroy(){this.rotationBrake&&(this.rotationBrake=null)}}let Ln=class{constructor(e){this.renderer=e,this.canvas=e.canvas,this.initialized=!1,this.handleMouseMove=null,this.handleTouchMove=null}setEnabled(e){this.renderer.state.gazeTrackingEnabled=e,e?this.initialized||this.initialize():this.renderer.state.gazeTarget={x:0,y:0}}initialize(){this.initialized||(this.handleMouseMove=e=>{if(!this.renderer.state.gazeTrackingEnabled)return;const t=this.canvas.getBoundingClientRect(),i=t.width/2,s=t.height/2,n=e.clientX-t.left-i,a=e.clientY-t.top-s;this.renderer.state.gazeTarget={x:n/i,y:a/s}},this.handleTouchMove=e=>{if(this.renderer.state.gazeTrackingEnabled&&e.touches.length>0){const t=e.touches[0],i=this.canvas.getBoundingClientRect(),s=i.width/2,n=i.height/2,a=t.clientX-i.left-s,r=t.clientY-i.top-n;this.renderer.state.gazeTarget={x:a/s,y:r/n}}},document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),this.initialized=!0)}cleanup(){this.initialized&&(this.handleMouseMove&&(document.removeEventListener("mousemove",this.handleMouseMove),this.handleMouseMove=null),this.handleTouchMove&&(document.removeEventListener("touchmove",this.handleTouchMove),this.handleTouchMove=null),this.initialized=!1)}isInitialized(){return this.initialized}getGazeTarget(){return this.renderer.state.gazeTarget}isEnabled(){return this.renderer.state.gazeTrackingEnabled}};class qn{constructor(e){this.renderer=e}setupCanvas(){this.renderer.updateOffscreenSize();const e=this.renderer.canvasManager.width||this.renderer.canvas.width||400,t=this.renderer.canvasManager.height||this.renderer.canvas.height||400,i=this.renderer.ctx;return this.renderer.ctx=this.renderer.offscreenCtx,{logicalWidth:e,logicalHeight:t,originalCtx:i}}renderBackdrop(e,t,i,s){const n=Math.min(e,t),a=this.renderer.getEffectiveCenter(),r=a.x,o=a.y-this.renderer.config.topOffset,l=n/this.renderer.config.referenceSize*this.renderer.config.baseScale*(a.coreScale||a.scale),h=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*l;this.renderer.backdropRenderer.update(s),this.renderer.audioAnalyzer&&this.renderer.audioAnalyzer.currentAmplitude&&this.renderer.backdropRenderer.setAudioIntensity(this.renderer.audioAnalyzer.currentAmplitude),this.renderer.backdropRenderer.render(r,o,h,i)}applyCanvasDecay(e,t,i){const s=this.renderer.particleSystem?this.renderer.particleSystem.particles.length:0,n=.12+Math.min(.08,.003*s);e.save(),e.globalCompositeOperation="destination-out",e.fillStyle=`rgba(0, 0, 0, ${n})`,e.fillRect(0,0,t,i),e.restore()}clearOffscreenCanvas(e,t){this.renderer.ctx.clearRect(0,0,e,t)}performCanvasSetup(e,t,i,s){this.renderBackdrop(e,t,i,s),this.applyCanvasDecay(i,e,t),this.clearOffscreenCanvas(e,t)}}class Gn{constructor(e){this.renderer=e}markFrameStart(){return this.renderer.performanceMonitor&&this.renderer.performanceMonitor.markFrameStart(),performance.now()}handleCleanRender(){this.renderer.forceCleanRender&&(this.renderer.forceCleanRender=!1,this.renderer.canvas&&this.renderer.ctx&&this.renderer.ctx.clearRect(0,0,this.renderer.canvas.width,this.renderer.canvas.height))}initializeFrame(){const e=this.markFrameStart();return this.handleCleanRender(),e}}class Hn{constructor(e){this.renderer=e}mergeTransforms(e,t){const i=this.renderer.ambientDanceAnimator.getTransform(t);return e?(e.x=(e.x||0)+(i.x||0),e.y=(e.y||0)+(i.y||0),e.rotation=(e.rotation||0)+(i.rotation||0),e.scale=(e.scale||1)*(i.scale||1),e):i}mergeAndStoreTransforms(e,t){const i=this.mergeTransforms(e,t);return this.renderer.gestureTransform=i,i}}class jn{constructor(e){this.renderer=e}updateUndertoneModifiers(){if(this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers){const e=this.renderer.stateMachine.getWeightedUndertoneModifiers();e?this.renderer.applyUndertoneModifiers(e):this.renderer.applyUndertoneModifiers(null)}}updateColorTransition(e){this.renderer.colorTransition&&this.renderer.colorTransition.active&&this.renderer.updateColorTransition(e)}updateAnimationTimers(e){this.renderer.updateTimers(e)}updateGazeOffset(){if(this.renderer.state.gazeTrackingEnabled){const e=.15,t=50;this.renderer.state.gazeOffset.x+=(this.renderer.state.gazeTarget.x*t-this.renderer.state.gazeOffset.x)*e,this.renderer.state.gazeOffset.y+=(this.renderer.state.gazeTarget.y*t-this.renderer.state.gazeOffset.y)*e}else{const e=.1;this.renderer.state.gazeOffset.x+=(0-this.renderer.state.gazeOffset.x)*e,this.renderer.state.gazeOffset.y+=(0-this.renderer.state.gazeOffset.y)*e}}performFrameStateUpdates(e){this.updateUndertoneModifiers(),this.updateColorTransition(e),this.updateAnimationTimers(e),this.updateGazeOffset()}}class $n{constructor(e){this.renderer=e}calculateBaseDimensions(e,t){const i=Math.min(e,t),s=this.renderer.getEffectiveCenter();return this.renderer.scaleFactor=i/this.renderer.config.referenceSize*this.renderer.config.baseScale*(s.coreScale||s.scale),this.renderer.particleScaleFactor=i/this.renderer.config.referenceSize*this.renderer.config.baseScale*(s.particleScale||s.scale),{canvasSize:i,effectiveCenter:s}}calculateCenterPosition(e,t,i){const s=e.x;let n=e.y-this.renderer.config.topOffset;return t.properties&&t.properties.verticalOffset&&(n=e.y-this.renderer.config.topOffset+i*t.properties.verticalOffset),{centerX:s,centerY:n}}applyGestureTransform(e,t,i){let s=1,n=0,a=1;return i&&(e+=i.x||0,t+=i.y||0,s=i.scale||1,n=(i.rotation||0)*Math.PI/180,a=i.glowIntensity||1),{centerX:e,centerY:t,scaleMultiplier:s,rotationAngle:n,glowMultiplier:a}}applyGestureAnimations(e,t,i,s,n){const a=this.renderer.gestureAnimator.applyGestureAnimations();return a&&(e+=a.offsetX||0,t+=a.offsetY||0,i*=a.scale||1,s+=(a.rotation||0)*Math.PI/180,n=a.glow||1),{centerX:e,centerY:t,scaleMultiplier:i,rotationAngle:s,glowMultiplier:n,gestureTransforms:a}}calculateRenderDimensions(e,t,i,s){const{canvasSize:n,effectiveCenter:a}=this.calculateBaseDimensions(e,t);let r,o,l,{centerX:h,centerY:c}=this.calculateCenterPosition(a,i,t);({centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l}=this.applyGestureTransform(h,c,s));const u=this.applyGestureAnimations(h,c,r,o,l);({centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l}=u);const{gestureTransforms:d}=u;return{canvasSize:n,effectiveCenter:a,centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l,gestureTransforms:d}}}var Wn={name:"recording-glow",emoji:"๐ด",description:"Pulsating red recording indicator",config:{color:"#FF0000",pulseSpeed:.08,minIntensity:.6,maxIntensity:1,radiusMultiplier:2,gradientStops:[{position:0,opacity:1},{position:.3,opacity:.7},{position:.6,opacity:.4},{position:.85,opacity:.2},{position:1,opacity:0}]},state:{pulsePhase:0,intensity:.8},shouldActivate:e=>!0===e.recording,apply(e,t){const{deltaTime:i=16.67}=t;this.state.pulsePhase+=this.config.pulseSpeed*(i/16.67);const s=(Math.sin(this.state.pulsePhase)+1)/2;return this.state.intensity=this.config.minIntensity+(this.config.maxIntensity-this.config.minIntensity)*s,!0},drawRecordingIndicator(e,t,i){e.save();const s=Math.min(t,i),n=Math.floor(.08*s),a=1.5*n,r=1.5*n,o=.3*n;e.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),e.beginPath(),e.arc(a-n,r,o,0,2*Math.PI),e.fill(),e.strokeStyle=this.hexToRgba("#FFFFFF",.8*this.state.intensity),e.lineWidth=3,e.font=`bold ${n}px 'Arial', sans-serif`,e.textAlign="left",e.textBaseline="middle",e.strokeText("REC",a,r),e.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),e.fillText("REC",a,r),e.restore()},hexToRgba:(e,t)=>`rgba(${parseInt(e.slice(1,3),16)}, ${parseInt(e.slice(3,5),16)}, ${parseInt(e.slice(5,7),16)}, ${t})`,reset(){this.state.pulsePhase=0,this.state.intensity=0}},Un={name:"speaking-pulse",emoji:"๐ฃ๏ธ",description:"Audio-reactive pulse when speaking",config:{scaleMultiplier:.15,smoothing:.1,minPulse:.02,colorShift:!0,ringEffect:!0},state:{audioLevel:0,smoothedLevel:0,rings:[]},shouldActivate:e=>!0===e.speaking,apply(e,t){const{x:i,y:s,radius:n,audioLevel:a=0,deltaTime:r=16.67}=t;this.state.smoothedLevel+=(a-this.state.smoothedLevel)*this.config.smoothing,a>.5&&this.state.audioLevel<=.5&&this.state.rings.push({radius:n,opacity:.5,speed:2}),this.config.ringEffect&&this.drawRings(e,i,s,r),this.state.audioLevel=a},drawRings(e,t,i,s){e.save(),e.strokeStyle="rgba(100, 200, 255, 0.5)",e.lineWidth=2;for(let n=this.state.rings.length-1;n>=0;n--){const a=this.state.rings[n];a.radius+=a.speed*(s/16.67),a.opacity-=s/16.67*.02,a.opacity<=0?this.state.rings.splice(n,1):(e.globalAlpha=a.opacity,e.beginPath(),e.arc(t,i,a.radius,0,2*Math.PI),e.stroke())}e.restore()},getScaleModifier(){return 1+this.state.smoothedLevel*this.config.scaleMultiplier}},Vn={name:"sleeping",emoji:"๐ด",description:"Sleeping with closed eyes and Z particles",config:{eyeClosedScale:.1,breathingDepth:.15,breathingRate:.8,zParticleInterval:2e3,zDriftSpeed:1,zFadeSpeed:.01,orbDimming:.3,glowDimming:.2},state:{lastZSpawn:0,zParticles:[]},shouldActivate:e=>!0===e.sleeping||"resting"===e.emotion,apply(e,t){const{x:i,y:s,radius:n,deltaTime:a=16.67}=t,r=Date.now();if(r-this.state.lastZSpawn>this.config.zParticleInterval){const e=[100,200,300,400,500,600,700,800,900],t=e[Math.floor(Math.random()*e.length)];this.state.zParticles.push({x:i+n,y:s-n,opacity:1,size:12+8*Math.random(),drift:.5*Math.random()-.25,weight:t,rotation:30*Math.random()-15}),this.state.lastZSpawn=r}this.drawZParticles(e,a)},drawZParticles(e,t){e.save(),e.textAlign="center",e.textBaseline="middle";for(let i=this.state.zParticles.length-1;i>=0;i--){const s=this.state.zParticles[i];s.y-=this.config.zDriftSpeed*(t/16.67),s.x+=s.drift*(t/16.67),s.opacity-=this.config.zFadeSpeed*(t/16.67),s.rotation+=t/16.67*.5,s.opacity<=0?this.state.zParticles.splice(i,1):(e.save(),e.translate(s.x,s.y),e.rotate(s.rotation*Math.PI/180),e.globalAlpha=.7*s.opacity,e.fillStyle="rgba(255, 255, 255, 0.9)",e.font=`${s.weight} ${s.size}px 'Poppins', sans-serif`,e.fillText("Z",0,0),e.shadowBlur=3,e.shadowColor="rgba(147, 112, 219, 0.5)",e.fillText("Z",0,0),e.restore())}e.restore()},getEyeOpenness(){return this.config.eyeClosedScale},getBreathingModifiers(){return{rate:this.config.breathingRate,depth:this.config.breathingDepth}},getDimmingValues(){return{orbDimming:this.config.orbDimming,glowDimming:this.config.glowDimming}}},Yn={name:"suspicion-scan",emoji:"๐",description:"Suspicious scanning and squinting",config:{squintAmount:.4,scanInterval:5e3,scanDuration:800,scanAngle:45,squintSpeed:.02,pupilShift:.3},state:{currentSquint:0,targetSquint:0,lastScanTime:0,scanPhase:0,scanning:!1},shouldActivate:e=>"suspicion"===e.emotion||!0===e.suspicious,apply(e,t){const{deltaTime:i=16.67}=t,s=Date.now();this.updateSquint(i),s-this.state.lastScanTime>this.config.scanInterval&&(this.startScan(),this.state.lastScanTime=s),this.state.scanning&&this.updateScan(s,i)},updateSquint(e){this.state.targetSquint=this.config.squintAmount;const t=this.state.targetSquint-this.state.currentSquint;Math.abs(t)>.01?this.state.currentSquint+=t*this.config.squintSpeed*(e/16.67):this.state.currentSquint=this.state.targetSquint},startScan(){this.state.scanning=!0,this.state.scanStartTime=Date.now(),this.state.scanPhase=-1},updateScan(e,t){const i=(e-this.state.scanStartTime)/this.config.scanDuration;i<.33?this.state.scanPhase=-1:i<.66?this.state.scanPhase=1:(i<1||(this.state.scanning=!1),this.state.scanPhase=0)},getEyeModifiers(){return{scaleY:1-this.state.currentSquint,scaleX:1+.3*this.state.currentSquint,offsetX:this.state.scanPhase*this.config.pupilShift}},drawScanLines(e,t,i,s){if(!this.state.scanning)return;e.save(),e.strokeStyle="rgba(255, 165, 0, 0.3)",e.lineWidth=1,e.setLineDash([5,5]);const n=this.state.scanPhase*(this.config.scanAngle*Math.PI/180),a=t+Math.cos(n)*s*2,r=i+Math.sin(n)*s*.5;e.beginPath(),e.moveTo(t,i),e.lineTo(a,r),e.stroke(),e.restore()}},Xn={name:"gaze-narrowing",emoji:"๐๏ธ",description:"Eye narrowing based on gaze proximity",config:{maxHorizontalScale:1.3,maxVerticalScale:.5,smoothing:.1,focusThreshold:.3},state:{currentScaleX:1,currentScaleY:1,targetScaleX:1,targetScaleY:1},shouldActivate:e=>e.gazeIntensity>0||e.gazeLocked,apply(e,t){const{gazeIntensity:i=0,deltaTime:s=16.67}=t;if(i>this.config.focusThreshold){const e=(i-this.config.focusThreshold)/(1-this.config.focusThreshold);this.state.targetScaleX=1+(this.config.maxHorizontalScale-1)*e,this.state.targetScaleY=1-(1-this.config.maxVerticalScale)*e}else this.state.targetScaleX=1,this.state.targetScaleY=1;this.animateScales(s)},animateScales(e){const t=this.config.smoothing*(e/16.67),i=this.state.targetScaleX-this.state.currentScaleX;Math.abs(i)>.001&&(this.state.currentScaleX+=i*t);const s=this.state.targetScaleY-this.state.currentScaleY;Math.abs(s)>.001&&(this.state.currentScaleY+=s*t)},getEyeScales(){return{scaleX:this.state.currentScaleX,scaleY:this.state.currentScaleY}},drawFocusIndicator(e,t,i,s,n){if(n<this.config.focusThreshold)return;e.save();const a=.5*(n-this.config.focusThreshold);e.strokeStyle=`rgba(100, 200, 255, ${a})`,e.lineWidth=1,e.setLineDash([2,4]);const r=[0,60,120,180,240,300];for(const n of r){const a=n*Math.PI/180,r=2*s,o=1.2*s;e.beginPath(),e.moveTo(t+Math.cos(a)*r,i+Math.sin(a)*r),e.lineTo(t+Math.cos(a)*o,i+Math.sin(a)*o),e.stroke()}e.restore()}},Nn={name:"fingerprint",emoji:"๐",description:"Biometric fingerprint pattern for authentication UI",config:{rings:8,ringSpacing:15,lineWidth:1.5,rotationSpeed:.001,pulseSpeed:.02,waveAmplitude:3,waveFrequency:8,breakPoints:5,opacity:.4,scanLineSpeed:.01,scanLineWidth:3,color:"#00CED1",glowColor:"#00FFFF",successColor:"#00FF00",failColor:"#FF0000"},state:{rotation:0,pulsePhase:0,scanPosition:0,scanDirection:1,isScanning:!1,scanResult:null,breaks:[],whorls:[]},shouldActivate:e=>!0===e.biometric||!0===e.fingerprint||!0===e.authenticating,initialize(){this.state.breaks=[];for(let e=0;e<this.config.rings;e++){const e=[];for(let t=0;t<this.config.breakPoints;t++)e.push(Math.random()*Math.PI*2);this.state.breaks.push(e)}this.state.whorls=[{x:.2,y:-.1,strength:.3},{x:-.15,y:.2,strength:.25},{x:0,y:0,strength:.5}]},apply(e,t){const{x:i,y:s,radius:n,deltaTime:a=16.67,scanning:r=!1,authResult:o=null}=t;0===this.state.breaks.length&&this.initialize(),this.state.rotation+=this.config.rotationSpeed*(a/16.67),this.state.pulsePhase+=this.config.pulseSpeed*(a/16.67),(r||this.state.isScanning)&&(this.state.isScanning=!0,this.state.scanPosition+=this.config.scanLineSpeed*this.state.scanDirection*(a/16.67),this.state.scanPosition>1?(this.state.scanPosition=1,this.state.scanDirection=-1):this.state.scanPosition<-1&&(this.state.scanPosition=-1,this.state.scanDirection=1)),e.save(),this.drawFingerprintPattern(e,i,s,n),this.state.isScanning&&this.drawScanLine(e,i,s,n),o&&this.showAuthResult(e,i,s,n,o),e.restore()},drawFingerprintPattern(e,t,i,s){const n=.1*Math.sin(this.state.pulsePhase)+1;for(let a=0;a<this.config.rings;a++){const r=(a+1)*this.config.ringSpacing*n;if(!(r>2*s)){e.beginPath(),e.strokeStyle=this.config.color,e.lineWidth=this.config.lineWidth,e.globalAlpha=this.config.opacity*(1-a/this.config.rings*.5);for(let n=0;n<2*Math.PI;n+=.05){let o=!1;for(const e of this.state.breaks[a]||[])if(Math.abs(n-e)<.1){o=!0;break}if(o){e.stroke(),e.beginPath();continue}let l=r,h=n+this.state.rotation;for(const e of this.state.whorls){const n=t+e.x*s,a=i+e.y*s,r=t+Math.cos(h)*l,o=i+Math.sin(h)*l,c=Math.sqrt(Math.pow(r-n,2)+Math.pow(o-a,2));h+=Math.exp(-c/(.5*s))*e.strength*.5}l+=Math.sin(n*this.config.waveFrequency)*this.config.waveAmplitude;const c=t+Math.cos(h)*l,u=i+Math.sin(h)*l;0===n?e.moveTo(c,u):e.lineTo(c,u)}e.stroke()}}},drawScanLine(e,t,i,s){const n=i+this.state.scanPosition*s,a=e.createLinearGradient(t-s,n,t+s,n);a.addColorStop(0,"rgba(0, 255, 255, 0)"),a.addColorStop(.5,this.config.glowColor),a.addColorStop(1,"rgba(0, 255, 255, 0)"),e.strokeStyle=a,e.lineWidth=this.config.scanLineWidth,e.globalAlpha=.8,e.shadowBlur=10,e.shadowColor=this.config.glowColor,e.beginPath(),e.moveTo(t-s,n),e.lineTo(t+s,n),e.stroke(),e.shadowBlur=0},showAuthResult(e,t,i,s,n){const a="success"===n?this.config.successColor:this.config.failColor,r="success"===n?"โ AUTHENTICATED":"โ ACCESS DENIED";e.fillStyle=a,e.font=`bold ${.15*s}px monospace`,e.textAlign="center",e.textBaseline="middle",e.globalAlpha=.9,e.fillText(r,t,i+1.3*s),e.strokeStyle=a,e.lineWidth=3,e.globalAlpha=.5,e.beginPath(),e.arc(t,i,1.1*s,0,2*Math.PI),e.stroke()},startScan(){this.state.isScanning=!0,this.state.scanPosition=-1,this.state.scanDirection=1,this.state.scanResult=null},completeScan(e=!0){this.state.isScanning=!1,this.state.scanResult=e?"success":"fail",setTimeout(()=>{this.state.scanResult=null},2e3)},reset(){this.state.rotation=0,this.state.pulsePhase=0,this.state.scanPosition=0,this.state.scanDirection=1,this.state.isScanning=!1,this.state.scanResult=null}};const Qn=new Map;function Jn(e){e.name&&Qn.set(e.name,e)}function Kn(e){return Qn.get(e)||null}function Zn(e,t,i){const s=Kn(e);return!!s&&!!s.apply&&(s.apply(t,i),!0)}function ea(e,t){const i=Kn(e);return!(!i||!i.shouldActivate)&&i.shouldActivate(t)}Jn(Wn),Jn(Un),Jn(Vn),Jn(Yn),Jn(Xn),Jn(Nn);class ta{constructor(e){this.renderer=e}calculateSleepModifiers(){let e=1,t=1,i=1;if(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||ea("sleeping",this.renderer.state)){const s=Kn("sleeping");if(s){const n=s.getDimmingValues();e=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:n.orbDimming,i=n.glowDimming,t=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9}else e=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:.3,i=.2,t=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9;this.renderer.state.breathRate=.5,this.renderer.state.breathDepth=.15}return{sleepOpacityMod:e,sleepScaleMod:t,glowOpacityMod:i}}calculateBreathingFactors(){let e,t;if(null!==this.renderer.state.customScale)e=this.renderer.state.customScale,t=1+.5*(this.renderer.state.customScale-1);else{const i=this.renderer.breathingAnimator.getBreathingScale();e=i,t=1-.5*(i-1)}return"nervous"===this.renderer.state.undertone&&this.renderer.undertoneModifiers.nervous.glowPulse&&(t*=1+Math.sin(Date.now()/200)*this.renderer.undertoneModifiers.nervous.glowPulse),{coreBreathFactor:e,glowBreathFactor:t}}calculateRadii(e,t,i){const{sleepOpacityMod:s,sleepScaleMod:n,glowOpacityMod:a}=this.calculateSleepModifiers(),{coreBreathFactor:r,glowBreathFactor:o}=this.calculateBreathingFactors(),l=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*this.renderer.scaleFactor,h=e.properties&&e.properties.coreSize?e.properties.coreSize:1,c=this.renderer.state.sizeMultiplier||1;return{coreRadius:l*h*r*t*n*c,glowRadius:l*this.renderer.config.glowMultiplier*o*this.renderer.state.glowIntensity*t*n*c*i,effectiveGlowIntensity:this.renderer.state.glowIntensity*i,sleepOpacityMod:s,glowOpacityMod:a}}}class ia{constructor(e){this.renderer=e}applyBlinkSquish(e){return this.renderer.state.sleeping||(e*=this.renderer.eyeRenderer.getBlinkScale()),e}calculateJitter(e,t){let i=0,s=0;const n=this.renderer.state.jitterAmount||0;if(this.renderer.currentUndertone)({jitterX:i,jitterY:s,coreRadius:e,glowRadius:t}=this.renderer.episodicEffectController.updateEpisodicEffects(this.renderer.currentUndertone,i,s,e,t));else if(this.renderer.state.coreJitter||n>0){const e=Math.max(n,this.renderer.state.coreJitter?this.renderer.scaleValue(2):0);i=(Math.random()-.5)*e,s=(Math.random()-.5)*e}return{jitterX:i,jitterY:s,coreRadius:e,glowRadius:t}}calculateFinalPosition(e,t,i,s){return{coreX:e+this.renderer.state.gazeOffset.x+i,coreY:t+this.renderer.state.gazeOffset.y+s}}applyAllModifications(e,t,i,s,n){let a,r;s=this.applyBlinkSquish(s),({jitterX:a,jitterY:r,coreRadius:s,glowRadius:n}=this.calculateJitter(s,n));const{coreX:o,coreY:l}=this.calculateFinalPosition(e,t,a,r);return{coreX:o,coreY:l,rotationAngle:i,coreRadius:s,glowRadius:n}}}class sa{constructor(e){this.renderer=e}renderGlow(e,t,i,s,n,a){ea("recording-glow",this.renderer.state)?Zn("recording-glow",this.renderer.ctx,{x:e,y:t,radius:i,deltaTime:a}):this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||ea("sleeping",this.renderer.state)?(this.renderer.ctx.save(),this.renderer.ctx.globalAlpha=n,this.renderer.glowRenderer.renderGlow(e,t,i,{intensity:s}),this.renderer.ctx.restore()):this.renderer.glowRenderer.renderGlow(e,t,i,{intensity:s})}renderFlashWave(e,t,i,s){if(e&&e.flashWave){const n=e.flashWave,{ctx:a}=this.renderer;a.save(),a.globalCompositeOperation="lighter";const r=s*n.innerRadius,o=s*n.outerRadius;if(o>r){const e=_n.getRadialGradient(a,t,i,r,t,i,o,[{offset:0,color:"rgba(255, 255, 255, 0)"},{offset:.2,color:`rgba(255, 255, 255, ${.15*n.intensity})`},{offset:.5,color:`rgba(255, 255, 255, ${.25*n.intensity})`},{offset:.8,color:`rgba(255, 255, 255, ${.15*n.intensity})`},{offset:1,color:"rgba(255, 255, 255, 0)"}]);a.fillStyle=e,a.beginPath(),a.arc(t,i,o,0,2*Math.PI),a.arc(t,i,Math.max(0,r),0,2*Math.PI,!0),a.fill()}a.restore()}}renderSpeakingPulse(e,t,i,s){ea("speaking-pulse",this.renderer.state)&&Zn("speaking-pulse",this.renderer.ctx,{x:e,y:t,radius:i,audioLevel:this.renderer.state.audioLevel||0,deltaTime:s})}renderAllEffects(e){const{coreX:t,coreY:i,glowRadius:s,effectiveGlowIntensity:n,glowOpacityMod:a,gestureTransforms:r,coreRadius:o,deltaTime:l}=e;this.renderGlow(t,i,s,n,a,l),this.renderFlashWave(r,t,i,o),this.renderSpeakingPulse(t,i,o,l)}}class na{constructor(e){this.renderer=e}applySleepOpacity(e){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=e)}updateShapeMorpher(e){let t=null,i=null;return this.renderer.shapeMorpher&&(this.renderer.shapeMorpher.update(),t=this.renderer.shapeMorpher.getCanvasPoints(0,0,e),i=this.renderer.shapeMorpher.getCurrentShadow()),{shapePoints:t,currentShadow:i}}renderSunEffects(e,t,i,s){let n=!1;return!s||"sun"!==s.type&&"solar-hybrid"!==s.type||(this.renderer.renderSunEffects(e,t,i,s),n=!0),n}renderCore(e,t,i,s,n){this.renderer.coreRenderer.renderCore(e,t,i,{scaleX:1,scaleY:1,rotation:s,shapePoints:n})}renderSparkles(e){this.renderer.specialEffects&&(this.renderer.specialEffects.update(e),this.renderer.specialEffects.renderSparkles())}renderShadowEffects(e,t,i,s,n,a){const r=this.renderer.shapeMorpher?this.renderer.shapeMorpher.currentShape:null,o=this.renderer.shapeMorpher?this.renderer.shapeMorpher.targetShape:null,l=this.renderer.shapeMorpher&&"solar"===o&&this.renderer.shapeMorpher.isTransitioning,h=this.renderer.shapeMorpher&&"solar"===r&&this.renderer.shapeMorpher.isTransitioning,c=s&&"solar-hybrid"===s.type,u=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"solar"===r&&"moon"===o,d=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"moon"===r&&"solar"===o;if(!s||"crescent"!==s.type&&"lunar"!==s.type||d||this.renderer.renderMoonShadow(e,t,i,s,n,!1,0),(c&&s.lunarOverlay||l||h)&&!u){const r=c&&s.lunarOverlay?s.lunarOverlay:{type:"lunar",coverage:1,color:"rgba(0, 0, 0, 1.0)",progression:"center"};let o=0,u=0,d=0;if(this.renderer.shapeMorpher){d=this.renderer.shapeMorpher.getProgress();const e=2.5*i;l&&d<1?(o=-e*(1-d),u=e*(1-d)):h&&d<1&&(o=e*d,u=-e*d)}if(this.renderer.renderMoonShadow(e,t,i,r,n,!0),(l||h)&&(l||a)&&(this.renderer.renderBaileysBeads(e,t,i,o,u,d,l,!0),Math.abs(o)<30&&Math.abs(u)<30&&this.renderer.specialEffects)){const e=Math.sqrt(o*o+u*u),t=Math.max(.1,.5*(1-e/30));this.renderer.specialEffects.triggerChromaticAberration(t)}}}cleanup(e){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=1),0!==e&&this.renderer.ctx.restore()}renderCoreAndShapes(e){const{coreX:t,coreY:i,coreRadius:s,totalRotation:n,sleepOpacityMod:a,deltaTime:r}=e;this.applySleepOpacity(a);const{shapePoints:o,currentShadow:l}=this.updateShapeMorpher(s),h=this.renderSunEffects(t,i,s,l);this.renderCore(t,i,s,n,o),this.renderSparkles(r),this.renderShadowEffects(t,i,s,l,o,h),this.cleanup(n)}}class aa{constructor(e){this.renderer=e}renderSleepIndicator(e,t,i,s){this.renderer.state.sleeping&&this.renderer.renderSleepIndicator(e,t-i-this.renderer.scaleValue(20),s)}finalizeCanvas(e,t,i){this.renderer.ctx=e,e.drawImage(this.renderer.offscreenCanvas,0,0,t,i)}drawRecordingIndicator(e){if(ea("recording-glow",this.renderer.state)){const t=Kn("recording-glow");t&&t.drawRecordingIndicator&&t.drawRecordingIndicator(e,this.renderer.canvas.width,this.renderer.canvas.height)}}finalizePerformanceMetrics(e){const t=performance.now()-e;this.renderer.performanceMonitor&&(this.renderer.performanceMonitor.markFrameEnd(),this.renderer.performanceMonitor.recordFrameTime(t))}finalizeRender(e){const{centerX:t,centerY:i,glowRadius:s,deltaTime:n,originalCtx:a,logicalWidth:r,logicalHeight:o,frameStartTime:l}=e;this.renderSleepIndicator(t,i,s,n),this.finalizeCanvas(a,r,o),this.drawRecordingIndicator(a),this.finalizePerformanceMetrics(l)}}class ra{constructor(e){this.renderer=e,this.animations={grooveSway:null,grooveBob:null,grooveFlow:null,groovePulse:null,grooveStep:null},this.activeAnimation=null,this.blendState={x:0,y:0,rotation:0,scale:1,opacity:1}}startAmbientAnimation(e,t={}){this.activeAnimation&&this.activeAnimation!==e&&this.stopAmbientAnimation(this.activeAnimation),this.activeAnimation=e,this.animations[e]={startTime:Date.now(),intensity:t.intensity||1,frequency:t.frequency||1,options:t}}stopAmbientAnimation(e){this.animations[e]&&(this.animations[e]=null),this.activeAnimation===e&&(this.activeAnimation=null)}updateBlendState(e){if(!e)return;const t=.2;this.blendState.x=this.lerp(this.blendState.x,e.x||0,t),this.blendState.y=this.lerp(this.blendState.y,e.y||0,t),this.blendState.rotation=this.lerp(this.blendState.rotation,e.rotation||0,t),this.blendState.scale=this.lerp(this.blendState.scale,e.scale||1,t),this.blendState.opacity=this.lerp(this.blendState.opacity,e.opacity||1,t)}getTransform(e){const t={x:this.blendState.x,y:this.blendState.y,rotation:this.blendState.rotation,scale:this.blendState.scale,opacity:this.blendState.opacity};if(this.activeAnimation){const e=this.animations[this.activeAnimation];if(e){const i=Date.now()-e.startTime;switch(this.activeAnimation){case"grooveSway":t.x+=15*Math.sin(i/500*e.frequency)*e.intensity,t.rotation+=5*Math.sin(i/500*e.frequency+Math.PI/4)*e.intensity;break;case"grooveBob":t.y+=10*Math.sin(i/400*e.frequency)*e.intensity,t.scale*=1+.03*Math.sin(i/400*e.frequency)*e.intensity;break;case"grooveFlow":{const s=i/1e3*e.frequency;t.x+=Math.sin(s)*Math.cos(2*s)*20*e.intensity,t.y+=Math.cos(s)*Math.sin(2*s)*10*e.intensity,t.rotation+=8*Math.sin(2*s)*e.intensity;break}case"groovePulse":t.scale*=1+.05*Math.sin(i/250*e.frequency)*e.intensity,t.opacity*=.9+.1*Math.sin(i/250*e.frequency)*e.intensity;break;case"grooveStep":{const s=Math.floor(i/500*e.frequency)%4,n=i/500*e.frequency%1,a=this.smoothStep(n);0===s?t.x+=25*a*e.intensity:2===s&&(t.x-=25*a*e.intensity),t.y+=5*Math.abs(Math.sin(i/250*e.frequency))*e.intensity;break}}}}return t}lerp(e,t,i){return e+(t-e)*i}smoothStep(e){return e*e*(3-2*e)}}class oa{constructor(e){this.renderer=e,this.ctx=e.ctx,this.config={enabled:!1,radius:1.5,shape:"circle",color:"rgba(0, 0, 0, 0.6)",intensity:.7,blendMode:"normal",falloff:"smooth",falloffCurve:null,edgeSoftness:.6,coreTransparency:.2,blur:0,responsive:!0,pulse:!1,offset:{x:0,y:0},type:"radial-gradient"},this.currentIntensity=0,this.targetIntensity=0,this.pulsePhase=0}setConfig(e={}){this.config={...this.config,...e},void 0!==e.enabled&&(this.targetIntensity=e.enabled?this.config.intensity:0)}update(e){this.config.enabled?(this.currentIntensity+=.1*(this.targetIntensity-this.currentIntensity),this.config.responsive&&(this.pulsePhase+=.001*e)):this.currentIntensity*=.95}setAudioIntensity(e){if(!this.config.responsive)return;const t=.2*e;this.targetIntensity=Math.min(1,this.config.intensity+t)}render(e,t,i,s=null){if(this.currentIntensity<.01)return;const n=s||this.ctx;switch(n.save(),this.config.type){case"radial-gradient":this.renderRadialGradient(e,t,i,n);break;case"vignette":this.renderVignette(e,t,i,n);break;case"glow":this.renderGlow(e,t,i,n)}n.restore()}renderRadialGradient(e,t,i,s){s=s||this.ctx;const n=i*this.config.radius,a=e+(this.config.offset.x||0),r=t+(this.config.offset.y||0);let o=n;(this.config.pulse||this.config.responsive)&&(o*=1+.05*Math.sin(this.pulsePhase));const l=s.globalCompositeOperation;this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=this.config.blendMode),this.config.blur>0&&(s.filter=`blur(${this.config.blur}px)`);const h=s.createRadialGradient(a,r,0,a,r,o),c=this.config.color,u=this.currentIntensity;this.addGradientStopsSimple(h,c,u),s.fillStyle=h,s.beginPath(),s.arc(a,r,o,0,2*Math.PI),s.fill(),this.config.blur>0&&(s.filter="none"),this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=l)}renderVignette(e,t,i,s){s=s||this.ctx;const{canvas:n}=s,a=Math.max(n.width,n.height),r=s.createRadialGradient(e,t,.5*i,e,t,a);r.addColorStop(0,"rgba(0, 0, 0, 0)"),r.addColorStop(1,this.adjustColorAlpha(this.config.color,this.currentIntensity)),s.fillStyle=r,s.fillRect(0,0,n.width,n.height)}renderGlow(e,t,i,s){s=s||this.ctx;const n=i*this.config.radius;for(let i=0;i<3;i++){const a=n*(1-.2*i),r=this.currentIntensity*(.3-.1*i),o=s.createRadialGradient(e,t,0,e,t,a);o.addColorStop(0,this.adjustColorAlpha(this.config.color,r)),o.addColorStop(1,"rgba(0, 0, 0, 0)"),s.fillStyle=o,s.beginPath(),s.arc(e,t,a,0,2*Math.PI),s.fill()}}addGradientStopsSimple(e,t,i){const{coreTransparency:s}=this.config;e.addColorStop(0,this.adjustColorAlpha(t,i)),e.addColorStop(s,this.adjustColorAlpha(t,i));for(let n=1;n<=25;n++){const a=s+n/25*(1-s),r=(a-s)/(1-s),o=1-this.easeInOutCubic(r);e.addColorStop(a,this.adjustColorAlpha(t,i*o))}e.addColorStop(1,"rgba(0, 0, 0, 0)")}addGradientStops(e,t,i,s=1){const{coreTransparency:n}=this.config;if(this.config.falloffCurve&&Array.isArray(this.config.falloffCurve))this.config.falloffCurve.forEach(({stop:s,alpha:n})=>{e.addColorStop(s,this.adjustColorAlpha(t,i*n))});else switch(this.config.falloff){case"linear":e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n,"rgba(0, 0, 0, 0)"),e.addColorStop(1,this.adjustColorAlpha(t,i));break;case"exponential":e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n,"rgba(0, 0, 0, 0)"),e.addColorStop(n+.3*(1-n),this.adjustColorAlpha(t,.05*i)),e.addColorStop(n+.5*(1-n),this.adjustColorAlpha(t,.15*i)),e.addColorStop(n+.7*(1-n),this.adjustColorAlpha(t,.4*i)),e.addColorStop(n+.85*(1-n),this.adjustColorAlpha(t,.7*i)),e.addColorStop(1,this.adjustColorAlpha(t,i));break;default:{e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n*s,"rgba(0, 0, 0, 0)");const{edgeSoftness:a}=this.config,r=s,o=n*s+(r-n*s)*a,l=25;for(let a=1;a<=l;a++){const h=a/l;let c=0;if(h<=n*s)c=0;else if(h<=r)if(h<=o){const e=(h-n*s)/(o-n*s);c=this.easeInOutCubic(e)}else{const e=(h-o)/(r-o);c=1-.05*(1-this.easeInOutCubic(e))}else{const e=(h-r)/(1-r);c=1-this.easeInOutCubic(e)}e.addColorStop(h,this.adjustColorAlpha(t,i*c))}e.addColorStop(1,"rgba(0, 0, 0, 0)");break}}}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}adjustColorAlpha(e,t){const i=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(i){const[,e,s,n,a=1]=i;return`rgba(${e}, ${s}, ${n}, ${parseFloat(a)*t})`}return`rgba(0, 0, 0, ${.6*t})`}getConfig(){return{...this.config}}enable(){this.config.enabled=!0,this.targetIntensity=this.config.intensity}disable(){this.config.enabled=!1,this.targetIntensity=0}toggle(){this.config.enabled?this.disable():this.enable()}}const la={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3,IDLE:4};class ha{constructor(){this.callbacks=new Map,this.callbackIdCounter=0,this._groupedCallbacks=new Map,this._groupsDirty=!0,this.frameId=null,this.isRunning=!1,this.lastFrameTime=0,this.deltaTime=0,this.fps=60,this.frameCount=0,this.targetFPS=60,this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=16.67,this.prioritySkipCounters={[la.MEDIUM]:0,[la.LOW]:0,[la.IDLE]:0},this.performanceMonitor=null,this.frameTimeHistory=new Array(60).fill(0),this._historyIndex=0,this._historyCount=0,this.maxHistorySize=60,this.loop=this.loop.bind(this)}register(e,t=la.MEDIUM,i=null){if("function"!=typeof e)throw new Error("Callback must be a function");const s=++this.callbackIdCounter;return this.callbacks.set(s,{callback:e,priority:t,context:i,lastRun:0,runCount:0,totalTime:0,enabled:!0}),this._groupsDirty=!0,1!==this.callbacks.size||this.isRunning||this.start(),s}unregister(e){this.callbacks.delete(e),this._groupsDirty=!0,0===this.callbacks.size&&this.isRunning&&this.stop()}setEnabled(e,t){const i=this.callbacks.get(e);i&&(i.enabled=t)}start(){this.isRunning||(this.isRunning=!0,this.lastFrameTime=performance.now(),this.frameId=requestAnimationFrame(this.loop))}stop(){this.isRunning&&(this.isRunning=!1,this.frameId&&(cancelAnimationFrame(this.frameId),this.frameId=null))}loop(e){if(!this.isRunning)return;this.deltaTime=e-this.lastFrameTime,this.lastFrameTime=e,this.frameCount++,this.frameCount%60==0&&(this.fps=Math.round(1e3/(this.deltaTime||16.67))),this.frameTimeHistory[this._historyIndex]=this.deltaTime,this._historyIndex=(this._historyIndex+1)%this.maxHistorySize,this._historyCount<this.maxHistorySize&&this._historyCount++,this._groupsDirty&&this._rebuildGroups();const t=this._groupedCallbacks;let i=0;for(const s of[la.CRITICAL,la.HIGH,la.MEDIUM,la.LOW,la.IDLE]){if(s>la.CRITICAL&&i>.8*this.frameBudget)break;if(this.shouldSkipPriority(s))continue;const n=t.get(s)||[];for(const t of n){if(!t.enabled)continue;const s=performance.now();try{t.context?t.callback.call(t.context,this.deltaTime,e):t.callback(this.deltaTime,e);const n=performance.now()-s;t.totalTime+=n,t.runCount++,t.lastRun=e,i+=n}catch(e){console.error("Animation callback error:",e),t.runCount>0&&t.totalTime/t.runCount>10&&(console.warn("Disabling slow callback"),t.enabled=!1)}if(i>this.frameBudget)break}}this.frameId=requestAnimationFrame(this.loop)}_rebuildGroups(){this._groupedCallbacks.clear();for(const[,e]of this.callbacks){const{priority:t}=e;this._groupedCallbacks.has(t)||this._groupedCallbacks.set(t,[]),this._groupedCallbacks.get(t).push(e)}this._groupsDirty=!1}shouldSkipPriority(e){if(e===la.CRITICAL)return!1;if(this.fps<30&&e>=la.LOW)return!0;if(this.fps<45&&e===la.IDLE)return!0;if(e===la.MEDIUM){if(this.fps<50&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%2!=0))return!0}else if(e===la.LOW){if(this.fps<50&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%3!=0))return!0}else if(e===la.IDLE&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%5!=0))return!0;return!1}getStats(){const e={fps:this.fps,frameCount:this.frameCount,callbackCount:this.callbacks.size,averageFrameTime:0,maxFrameTime:0,minFrameTime:1/0};if(this._historyCount>0){let t=0;for(let i=0;i<this._historyCount;i++){const s=this.frameTimeHistory[i];t+=s,e.maxFrameTime=Math.max(e.maxFrameTime,s),e.minFrameTime=Math.min(e.minFrameTime,s)}e.averageFrameTime=t/this._historyCount}e.callbacksByPriority={};for(const[,t]of this.callbacks){const{priority:i}=t;e.callbacksByPriority[i]||(e.callbacksByPriority[i]={count:0,totalTime:0,enabled:0}),e.callbacksByPriority[i].count++,e.callbacksByPriority[i].totalTime+=t.totalTime,t.enabled&&e.callbacksByPriority[i].enabled++}return e}setTargetFPS(e){this.targetFPS=Math.max(15,Math.min(120,e)),this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=this.targetFrameTime}setPerformanceMonitor(e){this.performanceMonitor=e}destroy(){this.stop(),this.callbacks.clear(),this._groupedCallbacks.clear(),this._groupsDirty=!0,this.frameTimeHistory.fill(0),this._historyIndex=0,this._historyCount=0}}const ca=new ha;class ua{constructor(e){this.renderer=e,this.loopCallbackIds={eyeClose:null,eyeOpen:null},this.wakeJitterTimeout=null}enterSleepMode(){this.renderer.state.sleeping=!0,this.renderer.sleepZ=[],this.renderer.state.eyeOpenness=1,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.renderer.state.blinking=!1,this.animateEyeClose()}animateEyeClose(){this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null);const e=performance.now(),t=2e3;this.loopCallbackIds.eyeClose=ca.register(()=>{if(!this.renderer.state.sleeping)return void(this.loopCallbackIds.eyeClose=null);const i=performance.now()-e;if(i<t){const e=i/t,s=1-Math.pow(e,2);this.renderer.state.eyeOpenness=.1+.9*s,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1}else if(i<3e3){const e=(i-t)/1e3,s=1-Math.pow(1-e,3);this.renderer.state.eyeOpenness=.1,this.renderer.state.sleepDimness=1-.4*s,this.renderer.state.sleepScale=1-.1*s}else this.renderer.state.eyeOpenness=.1,this.renderer.state.sleepDimness=.6,this.renderer.state.sleepScale=.9,this.loopCallbackIds.eyeClose=null},la.HIGH,this.renderer)}wakeUp(){this.renderer.state.sleeping&&(this.renderer.state.sleeping=!1,this.renderer.state.breathRate=1,this.renderer.state.breathDepth=this.renderer.config.breathingDepth,this.renderer.sleepZ=[],this.renderer.state.blinking=!1,this.renderer.eyeRenderer.blinking=!1,this.renderer.eyeRenderer.blinkTimer=0,this.animateEyeOpen(),this.wakeJitterTimeout&&clearTimeout(this.wakeJitterTimeout),this.renderer.state.coreJitter=!0,this.wakeJitterTimeout=setTimeout(()=>{this.renderer.state.coreJitter=!1,this.wakeJitterTimeout=null},200))}animateEyeOpen(){this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null);const e=performance.now();this.loopCallbackIds.eyeOpen=ca.register(()=>{const t=performance.now()-e;if(t<500){const e=t/500,i=Math.sin(e*Math.PI/2);this.renderer.state.sleepDimness=.6+.4*i,this.renderer.state.sleepScale=.9+.1*i,this.renderer.state.eyeOpenness=.1}else if(t<1500){const e=(t-500)/1e3,i=Math.sin(e*Math.PI/2);this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.renderer.state.eyeOpenness=.1+.9*i}else this.renderer.state.eyeOpenness=1,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.loopCallbackIds.eyeOpen=null},la.HIGH,this.renderer)}renderSleepIndicator(e,t,i){return this.renderer.specialEffects.renderSleepIndicator(e,t,i)}cleanup(){this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.wakeJitterTimeout&&(clearTimeout(this.wakeJitterTimeout),this.wakeJitterTimeout=null)}}class da{constructor(e){this.renderer=e}applyUndertoneModifiers(e){if(e&&"object"==typeof e&&void 0!==e.weight){const{weight:t}=e;return this.renderer.state.sizeMultiplier=1+((e.sizeMultiplier||1)-1)*t,this.renderer.state.jitterAmount=(e.jitterAmount||0)*t,this.renderer.state.episodicFlutter=t>.5&&e.episodicFlutter||!1,this.renderer.state.glowRadiusMult=1+((e.glowRadiusMult||1)-1)*t,this.renderer.state.breathRateMult=1+((e.breathRateMult||1)-1)*t,this.renderer.state.breathDepthMult=1+((e.breathDepthMult||1)-1)*t,this.renderer.state.breathIrregular=t>.5&&e.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=(e.glowPulse||0)*t,this.renderer.state.brightnessFlicker=(e.brightnessFlicker||0)*t,this.renderer.state.brightnessMult=1+((e.brightnessMult||1)-1)*t,this.renderer.state.saturationMult=1+((e.saturationMult||1)-1)*t,void(this.renderer.state.hueShift=(e.hueShift||0)*t)}if(!e||!this.renderer.undertoneModifiers[e])return this.renderer.state.sizeMultiplier=1,this.renderer.state.jitterAmount=0,this.renderer.state.episodicFlutter=!1,this.renderer.state.glowRadiusMult=1,this.renderer.state.breathRateMult=1,this.renderer.state.breathDepthMult=1,this.renderer.state.breathIrregular=!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=0,this.renderer.state.brightnessFlicker=0,this.renderer.state.brightnessMult=1,this.renderer.state.saturationMult=1,void(this.renderer.state.hueShift=0);const t=this.renderer.undertoneModifiers[e];this.renderer.state.sizeMultiplier=t.sizeMultiplier,this.renderer.state.jitterAmount=t.jitterAmount||0,this.renderer.state.episodicFlutter=t.episodicFlutter||!1,this.renderer.state.glowRadiusMult=t.glowRadiusMult,this.renderer.state.breathRateMult=t.breathRateMult,this.renderer.state.breathDepthMult=t.breathDepthMult,this.renderer.state.breathIrregular=t.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=t.glowPulse||0,this.renderer.state.brightnessFlicker=t.brightnessFlicker||0,this.renderer.state.brightnessMult=t.brightnessMult||1,this.renderer.state.saturationMult=t.saturationMult||1,this.renderer.state.hueShift=t.hueShift||0}updateUndertone(e){this.renderer.state.undertone!==e&&this.renderer.glowCache&&this.renderer.glowCache.clear(),this.renderer.state.undertone=e,this.renderer.currentUndertone=e;const t=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;if(this.applyUndertoneModifiers(t||e),this.renderer.state.emotion){const i=Ks&&Ks.isInitialized?Ks.getEmotion(this.renderer.state.emotion):l(this.renderer.state.emotion);if(i){const s=i.glowColor||this.renderer.config.defaultGlowColor,n=this.renderer.applyUndertoneToColor(s,t||e);this.renderer.startColorTransition(n,200)}}}setEmotionalState(e,t,i=null){this.renderer.state.emotion===e&&this.renderer.state.undertone===i||!this.renderer.glowCache||this.renderer.glowCache.clear(),this.renderer.state.undertone=i,this.renderer.currentUndertone=i;const s=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;this.applyUndertoneModifiers(s||i);const n=t.glowColor||this.renderer.config.defaultGlowColor;let a;a="suspicion"===e?t.glowColor||n:this.renderer.applyUndertoneToColor(n,s||i);const r=s||(i?this.renderer.undertoneModifiers[i]:null),o=t.glowIntensity||1;let l=1;if(r)if(s){const e=r.weight||0;l=void 0!==r.glowRadiusMult&&isFinite(r.glowRadiusMult)&&isFinite(e)?1+(r.glowRadiusMult-1)*e:1}else l=void 0!==r.glowRadiusMult?r.glowRadiusMult:1;const h=o*l;let c=1500;"anger"===e||"fear"===e?c=800:"sadness"!==e&&"resting"!==e||(c=2e3),this.renderer.state.emotion=e,"suspicion"===e?(this.renderer.state.isSuspicious=!0,this.renderer.state.targetSquintAmount=t&&t.coreSquint?t.coreSquint:.4,void 0===this.renderer.state.squintAmount&&(this.renderer.state.squintAmount=0),this.renderer.state.lastScanTime=Date.now(),this.renderer.state.scanPhase=0):(this.renderer.state.isSuspicious=!1,this.renderer.state.targetSquintAmount=0,void 0===this.renderer.state.squintAmount&&(this.renderer.state.squintAmount=0)),this.renderer.startColorTransition(a,h,c);const u=t.breathRate||1,d=t.breathDepth||this.renderer.config.breathingDepth;this.renderer.state.breathRate=r?u*r.breathRateMult:u,this.renderer.state.breathDepth=r?d*r.breathDepthMult:d,this.renderer.state.coreJitter=t.coreJitter||r&&r.jitterAmount>0,this.renderer.state.emotionEyeOpenness=t.eyeOpenness,this.renderer.state.emotionEyeArc=t.eyeArc}}class ga{constructor(e){this.renderer=e}resetCanvasContext(){if(!this.renderer.canvas||!this.renderer.ctx)return;const{width:e}=this.renderer.canvas,{height:t}=this.renderer.canvas;this.resetContext(this.renderer.ctx,e,t),this.renderer.offscreenCanvas&&this.renderer.offscreenCtx&&this.resetContext(this.renderer.offscreenCtx,this.renderer.offscreenCanvas.width,this.renderer.offscreenCanvas.height),this.renderer.contextStateManager&&this.renderer.contextStateManager.reset(),this.renderer.forceCleanRender=!0}resetContext(e,t,i){e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.globalCompositeOperation="source-over",e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.clearRect(0,0,t,i)}setQualityLevel(e){this.renderer.qualityLevel=Math.max(0,Math.min(1,e)),this.renderer.qualityLevel<.5?this.applyLowQuality():this.renderer.qualityLevel<.8?this.applyMediumQuality():this.applyHighQuality()}applyLowQuality(){this.renderer.ctx.imageSmoothingEnabled=!1,this.renderer.state.breathDepth*=.5}applyMediumQuality(){this.renderer.ctx.imageSmoothingEnabled=!0,this.renderer.ctx.imageSmoothingQuality="medium"}applyHighQuality(){this.renderer.ctx.imageSmoothingEnabled=!0,this.renderer.ctx.imageSmoothingQuality="high"}setQualityReduction(e){e?this.setQualityLevel(.5):this.setQualityLevel(1)}handleContextRecovery(e){this.renderer.ctx=e}}class ma{constructor(e){this.renderer=e}destroy(){this.cancelAnimationFrames(),this.unregisterLoopCallbacks(),this.cleanupManagers(),this.clearTimeouts(),this.clearAnimationStates(),this.clearOtherResources()}cancelAnimationFrames(){for(const e in this.renderer.animationFrameIds)this.renderer.animationFrameIds[e]&&(cancelAnimationFrame(this.renderer.animationFrameIds[e]),this.renderer.animationFrameIds[e]=null)}unregisterLoopCallbacks(){for(const e in this.renderer.loopCallbackIds)this.renderer.loopCallbackIds[e]&&(ca.unregister(this.renderer.loopCallbackIds[e]),this.renderer.loopCallbackIds[e]=null)}cleanupManagers(){this.renderer.sleepManager&&this.renderer.sleepManager.cleanup(),this.renderer.gazeTracker&&this.renderer.gazeTracker.cleanup()}clearTimeouts(){this.renderer.wakeJitterTimeout&&(clearTimeout(this.renderer.wakeJitterTimeout),this.renderer.wakeJitterTimeout=null)}clearAnimationStates(){this.renderer.colorTransition.active=!1}clearOtherResources(){this.renderer.cleanupGazeTracking(),this.renderer.speakingRings=[],this.renderer.gestureCompositor&&this.renderer.gestureCompositor.clearCache(),this.renderer.specialEffects&&this.renderer.specialEffects.destroy(),this.renderer.cleanupOffscreenCanvas&&this.renderer.cleanupOffscreenCanvas()}}class pa{constructor(e){this.renderer=e}updateTimers(e){this.updateBreathing(e),this.updateBlinking(e)}updateBreathing(e){this.renderer.breathingAnimator.update(e,this.renderer.state.emotion,this.renderer.currentUndertone),this.renderer.state.sleeping?this.applySleepBreathing():this.applyNormalBreathing(),this.renderer.breathingAnimator.setIrregularBreathing(this.renderer.state.breathIrregular)}applySleepBreathing(){this.renderer.breathingAnimator.setBreathRateMultiplier(.5),this.renderer.breathingAnimator.setBreathDepthMultiplier(1.2)}applyNormalBreathing(){this.renderer.breathingAnimator.setBreathRateMultiplier(1),this.renderer.breathingAnimator.setBreathDepthMultiplier(1)}updateBlinking(e){const t=this.renderer.state.blinkingEnabled&&!this.renderer.state.sleeping;this.renderer.eyeRenderer.setBlinkingEnabled(t),this.renderer.eyeRenderer.update(e),this.renderer.state.blinking=this.renderer.eyeRenderer.blinking}}class fa{constructor(e){this.renderer=e}setGazeOffset(e){this.processGazeData(e),this.handleGazeInteraction()}processGazeData(e){"object"==typeof e&&null!==e&&(this.isOldFormat(e)?this.renderer.state.gazeOffset=e:this.applyNewFormatData(e))}isOldFormat(e){return{}.hasOwnProperty.call(e,"x")&&{}.hasOwnProperty.call(e,"y")}applyNewFormatData(e){this.renderer.state.gazeOffset=e.offset||{x:0,y:0},this.renderer.state.gazeIntensity=e.proximity||0,this.renderer.state.gazeLocked=e.isLocked||!1}handleGazeInteraction(){this.renderer.idleTimer=0,this.renderer.isAsleep&&this.renderer.wakeUp()}getCurrentOrbPosition(){const e=this.renderer.canvasManager.width/2,t=this.renderer.canvasManager.height/2-this.renderer.config.topOffset;return{x:e+this.renderer.state.gazeOffset.x,y:t+this.renderer.state.gazeOffset.y}}}class ya{constructor(e,t={}){this.canvasManager=e,this.ctx=e.getContext(),this.ctx||(console.warn("EmotiveRenderer: canvas 2D context is null โ rendering will be disabled."),this._contextLost=!0),this.gestureCompositor=new pn,this.currentUndertone=null,this.gestureAnimator=new kn(this),this.colorUtilities=new Pn,this.specialEffects=new Tn(this),this.eyeRenderer=new En(this),this.breathingAnimator=new An(this),this.glowRenderer=new In(this),this.coreRenderer=new Rn(this),this.celestialRenderer=new Bn,this.episodicEffectController=new zn(this),this.rotationManager=new On(this),this.gazeTracker=new Ln(this),this.canvasSetupManager=new qn(this),this.renderPerformanceManager=new Gn(this),this.transformMerger=new Hn(this),this.stateUpdateManager=new jn(this),this.dimensionCalculator=new $n(this),this.radiusCalculator=new ta(this),this.positionJitterManager=new ia(this),this.effectsRenderManager=new sa(this),this.coreShapeRenderManager=new na(this),this.renderFinalizationManager=new aa(this),this.ambientDanceAnimator=new ra(this),this.backdropRenderer=new oa(this),this.sleepManager=new ua(this),this.emotionalStateManager=new da(this),this.canvasContextManager=new ga(this),this.resourceCleanupManager=new ma(this),this.timerCoordinator=new pa(this),this.gazeInputHandler=new fa(this),this.config={coreColor:t.coreColor||"#FFFFFF",coreSizeDivisor:t.coreSizeDivisor||12,glowMultiplier:t.glowMultiplier||2.5,defaultGlowColor:t.defaultGlowColor||"#14B8A6",breathingSpeed:t.breathingSpeed||.42,breathingDepth:t.breathingDepth||.08,renderingStyle:t.renderingStyle||"classic",baseScale:t.baseScale||1,referenceSize:400,topOffset:t.topOffset||0,positionController:t.positionController||null};const i=Math.min(this.canvasManager.width||400,this.canvasManager.height||400);this.scaleFactor=i/this.config.referenceSize*this.config.baseScale,this.state={emotion:"neutral",glowColor:this.config.defaultGlowColor,glowIntensity:1,breathRate:1,breathDepth:this.config.breathingDepth,coreJitter:!1,speaking:!1,recording:!1,sleeping:!1,blinking:!1,blinkingEnabled:!0,gazeOffset:{x:0,y:0},gazeIntensity:0,gazeLocked:!1,gazeTrackingEnabled:!1,gazeTarget:{x:0,y:0},effectiveCenter:{x:0,y:0,scale:1},squintAmount:0,targetSquintAmount:0,scanPhase:0,lastScanTime:0,isSuspicious:!1,customScale:null,sizeMultiplier:1,jitterAmount:0,episodicFlutter:!1,glowRadiusMult:1,breathRateMult:1,breathDepthMult:1,breathIrregular:!1,particleRateMult:1,glowPulse:0,brightnessFlicker:0,brightnessMult:1,saturationMult:1,hueShift:0,manualRotation:0,rotationSpeed:0,lastRotationUpdate:performance.now()},this.animationFrameIds={colorTransition:null,eyeClose:null,eyeOpen:null},this.loopCallbackIds={eyeClose:null,eyeOpen:null},this.wakeJitterTimeout=null,this.offscreenCanvas=null,this.offscreenCtx=null,this.initOffscreenCanvas(),this.canvas=e.canvas,this.gestureAnimations={bounce:{active:!1,startTime:0,progress:0,params:null},pulse:{active:!1,startTime:0,progress:0,params:null},shake:{active:!1,startTime:0,progress:0,params:null},spin:{active:!1,startTime:0,progress:0,params:null},nod:{active:!1,startTime:0,progress:0,params:null},tilt:{active:!1,startTime:0,progress:0,params:null},expand:{active:!1,startTime:0,progress:0,params:null},contract:{active:!1,startTime:0,progress:0,params:null},flash:{active:!1,startTime:0,progress:0,params:null},drift:{active:!1,startTime:0,progress:0,params:null,startX:0,startY:0},stretch:{active:!1,startTime:0,progress:0,params:null},glow:{active:!1,startTime:0,progress:0,params:null},flicker:{active:!1,startTime:0,progress:0,params:null},vibrate:{active:!1,startTime:0,progress:0,params:null},wave:{active:!1,startTime:0,progress:0,params:null},breathe:{active:!1,startTime:0,progress:0,params:null},morph:{active:!1,startTime:0,progress:0,params:null},slowBlink:{active:!1,startTime:0,progress:0,params:null},look:{active:!1,startTime:0,progress:0,params:null,targetX:0,targetY:0},settle:{active:!1,startTime:0,progress:0,params:null},breathIn:{active:!1,startTime:0,progress:0,params:null},breathOut:{active:!1,startTime:0,progress:0,params:null},breathHold:{active:!1,startTime:0,progress:0,params:null},breathHoldEmpty:{active:!1,startTime:0,progress:0,params:null},jump:{active:!1,startTime:0,progress:0,params:null},orbital:{active:!1,startTime:0,progress:0,params:null},hula:{active:!1,startTime:0,progress:0,params:null}},Object.defineProperty(this,"episodicEffects",{get:()=>this.episodicEffectController.getEpisodicEffects(),enumerable:!0}),this.speakingRings=[],this.maxRings=5,this.ringSpawnTimer=0,this.ringSpawnInterval=200,this.recordingRings=[],this.recordingPulse=0,this.sleepZ=[],this.colorTransition={active:!1,fromColor:this.state.glowColor,toColor:this.state.glowColor,fromIntensity:this.state.glowIntensity,toIntensity:this.state.glowIntensity,progress:0,startTime:0,duration:1500},this.undertoneModifiers={nervous:{hueShift:0,saturationMult:1.05,brightnessMult:1,brightnessFlicker:.05,sizeMultiplier:1,jitterAmount:0,episodicFlutter:!0,glowRadiusMult:1,glowPulse:.05,breathRateMult:1.1,breathDepthMult:.9,breathIrregular:!0},confident:{hueShift:15,saturationMult:1.2,brightnessMult:1.1,sizeMultiplier:1,jitterAmount:0,episodicPowerPose:!0,glowRadiusMult:1.15,breathRateMult:.95,breathDepthMult:1.1,breathIrregular:!1},tired:{hueShift:-5,saturationMult:.7,brightnessMult:.85,sizeMultiplier:.95,jitterAmount:0,episodicMicroSleep:!0,glowRadiusMult:.9,breathRateMult:.8,breathDepthMult:1.2,breathIrregular:!1},intense:{hueShift:5,saturationMult:1.3,brightnessMult:1.15,sizeMultiplier:1,jitterAmount:0,episodicLaserFocus:!0,glowRadiusMult:1.2,breathRateMult:1.2,breathDepthMult:.9,breathIrregular:!1},subdued:{hueShift:-10,saturationMult:.75,brightnessMult:.9,sizeMultiplier:.95,jitterAmount:0,episodicWithdrawal:!0,glowRadiusMult:.85,breathRateMult:.9,breathDepthMult:.9,breathIrregular:!1}},this.lastFrameTime=0,this._createGestureDelegates()}scaleValue(e){return e*this.scaleFactor}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),this.offscreenCtx,this.updateOffscreenSize()}cleanupOffscreenCanvas(){this.offscreenCanvas&&(this.offscreenCtx&&(this.offscreenCtx.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),this.offscreenCtx=null),this.offscreenCanvas.width=0,this.offscreenCanvas.height=0,this.offscreenCanvas=null)}updateOffscreenSize(){if(this.offscreenCanvas&&this.canvasManager){const{width:e}=this.canvasManager.canvas,{height:t}=this.canvasManager.canvas;if(this.offscreenCanvas.width!==e||this.offscreenCanvas.height!==t){this.offscreenCanvas.width=e,this.offscreenCanvas.height=t;const i=this.canvasManager.canvas.width>this.canvasManager.width;this.offscreenCtx&&(this.offscreenCtx.setTransform(1,0,0,1,0,0),i&&this.canvasManager.dpr&&this.offscreenCtx.scale(this.canvasManager.dpr,this.canvasManager.dpr))}}}updateEffectiveCenter(e){this.state.effectiveCenter=e}getEffectiveCenter(){const e=this.canvasManager.getCenter();let t;return t=this.config.positionController?this.config.positionController.getEffectiveCenter(e.x,e.y):{x:e.x,y:e.y,scale:1},t.x+=this.state.gazeOffset.x,t.y+=this.state.gazeOffset.y,t}render(e,t,i=null){if(this._contextLost)return;const s=this.renderPerformanceManager.initializeFrame();i=this.transformMerger.mergeAndStoreTransforms(i,t);const{logicalWidth:n,logicalHeight:a,originalCtx:r}=this.canvasSetupManager.setupCanvas();this.canvasSetupManager.performCanvasSetup(n,a,r,t),this.stateUpdateManager.performFrameStateUpdates(t);const o=this.dimensionCalculator.calculateRenderDimensions(n,a,e,i),{scaleMultiplier:l,glowMultiplier:h,gestureTransforms:c,centerX:u,centerY:d}=o;let{rotationAngle:g}=o;const m=this.radiusCalculator.calculateRadii(e,l,h);let{coreRadius:p,glowRadius:f}=m;const{effectiveGlowIntensity:y,sleepOpacityMod:b,glowOpacityMod:v}=m,M=this.positionJitterManager.applyAllModifications(u,d,g,p,f),{coreX:w,coreY:S}=M;({rotationAngle:g,coreRadius:p,glowRadius:f}=M);const x=this.rotationManager.applyRotationTransform(this.ctx,w,S,g);this.effectsRenderManager.renderAllEffects({coreX:w,coreY:S,glowRadius:f,effectiveGlowIntensity:y,glowOpacityMod:v,gestureTransforms:c,coreRadius:p,deltaTime:t}),this.coreShapeRenderManager.renderCoreAndShapes({coreX:w,coreY:S,coreRadius:p,totalRotation:x,sleepOpacityMod:b,deltaTime:t}),this.renderFinalizationManager.finalizeRender({centerX:u,centerY:d,glowRadius:f,deltaTime:t,originalCtx:r,logicalWidth:n,logicalHeight:a,frameStartTime:s})}renderRecordingGlow(e,t,i,s){const n=this.canvas?.width||600,a=this.canvas?.height||600,r=Math.min(i,e-10,t-10,n-e-10,a-t-10),o=Math.max(50,r),l=_n.getRadialGradient(this.ctx,e,t,0,e,t,o,[{offset:0,color:this.hexToRgba("#FF0000",.7*s)},{offset:.3,color:this.hexToRgba("#FF0000",.5*s)},{offset:.6,color:this.hexToRgba("#FF0000",.3*s)},{offset:.85,color:this.hexToRgba("#FF0000",.1*s)},{offset:1,color:this.hexToRgba("#FF0000",0)}]);this.ctx.fillStyle=l,this.ctx.beginPath(),this.ctx.arc(e,t,o,0,2*Math.PI),this.ctx.fill()}renderDropShadow(e,t,i,s){const{ctx:n}=this,a=this.shapeMorpher&&this.shapeMorpher.isTransitioning;if(!(this.shapeMorpher&&(this.shapeMorpher.audioDeformation>.1||this.shapeMorpher.vocalEnergy>.1)||a&&!(this.shapeMorpher.morphProgress>.8))){n.save(),n.translate(e,t);const a=this.scaleValue(2);if(n.translate(0,a),s&&s.length>32)n.fillStyle="rgba(0, 0, 0, 0.15)",n.beginPath(),n.arc(0,0,1.05*i,0,2*Math.PI),n.fill();else{const e=n.createRadialGradient(0,0,.7*i,0,0,1.2*i);if(e.addColorStop(0,"rgba(0, 0, 0, 0.2)"),e.addColorStop(.8,"rgba(0, 0, 0, 0.1)"),e.addColorStop(1,"rgba(0, 0, 0, 0)"),n.fillStyle=e,n.beginPath(),s){const e=1.1,t=s.length>20?2:1;n.moveTo(s[0].x*e,s[0].y*e);for(let i=t;i<s.length;i+=t)n.lineTo(s[i].x*e,s[i].y*e);n.closePath()}else n.arc(0,0,1.1*i,0,2*Math.PI);n.fill()}n.restore()}}renderSunEffects(e,t,i,s){return this.celestialRenderer.renderSunEffects(this.ctx,e,t,i,s)}renderBaileysBeads(e,t,i,s,n,a,r,o){return this.celestialRenderer.renderBaileysBeads(this.ctx,e,t,i,s,n,a,r,o,this.scaleValue.bind(this))}renderMoonShadow(e,t,i,s,n,a=!1,r=0){return this.celestialRenderer.renderMoonShadow(this.ctx,e,t,i,s,n,a,r,this.shapeMorpher)}renderSpeakingRings(e,t,i,s){return this.specialEffects.renderSpeakingRings(e,t,i,s)}renderRecordingIndicator(e,t){return this.specialEffects.renderRecordingIndicator(e,t)}renderSleepIndicator(e,t,i){return this.sleepManager.renderSleepIndicator(e,t,i)}updateTimers(e){this.timerCoordinator.updateTimers(e)}applyUndertoneModifiers(e){this.emotionalStateManager.applyUndertoneModifiers(e)}applyUndertoneToColor(e,t){return this.colorUtilities.applyUndertoneToColor(e,t)}hexToRgb(e){return this.colorUtilities.hexToRgb(e)}rgbToHsl(e,t,i){return this.colorUtilities.rgbToHsl(e,t,i)}hslToHex(e,t,i){return this.colorUtilities.hslToHex(e,t,i)}hexToRgba(e,t=1){const i=this.hexToRgb(e);return i?`rgba(${i.r}, ${i.g}, ${i.b}, ${t})`:`rgba(255, 255, 255, ${t})`}startColorTransition(e,t,i=1500){this.colorUtilities.currentColor=this.state.glowColor,this.colorUtilities.currentIntensity=this.state.glowIntensity,this.colorUtilities.startColorTransition(e,t,i),this.colorTransition=this.colorUtilities.colorTransition}updateColorTransition(e){const t=this.colorUtilities.updateColorTransition(e);t&&(this.state.glowColor=t.color,this.state.glowIntensity=t.intensity,this.colorTransition=this.colorUtilities.colorTransition)}updateUndertone(e){this.emotionalStateManager.updateUndertone(e)}setEmotionalState(e,t,i=null){this.emotionalStateManager.setEmotionalState(e,t,i)}setBPM(e){}setRotationSpeed(e){this.rotationManager.setRotationSpeed(e)}setRotationAngle(e){this.rotationManager.setRotationAngle(e)}setGazeOffset(e){this.gazeInputHandler.setGazeOffset(e)}getCurrentOrbPosition(){return this.gazeInputHandler.getCurrentOrbPosition()}setCustomScale(e){this.state.customScale=e}startSpeaking(){this.state.speaking=!0,this.speakingRings=[],this.ringSpawnTimer=0}stopSpeaking(){this.state.speaking=!1,this.speakingRings=[]}enterSleepMode(){this.sleepManager.enterSleepMode()}wakeUp(){this.sleepManager.wakeUp()}startRecording(){this.state.recording=!0}stopRecording(){this.state.recording=!1}setBlinkingEnabled(e){this.state.blinkingEnabled=e,e||(this.state.blinking=!1,this.eyeRenderer.blinking=!1,this.eyeRenderer.blinkTimer=0)}setGazeTracking(e){this.gazeTracker.setEnabled(e)}initGazeTracking(){this._deprecationWarned_initGazeTracking||(this._deprecationWarned_initGazeTracking=!0,console.warn("[EmotiveRenderer] initGazeTracking() is deprecated. Use gazeTracker.initialize() directly.")),this.gazeTracker.initialize()}cleanupGazeTracking(){this._deprecationWarned_cleanupGazeTracking||(this._deprecationWarned_cleanupGazeTracking=!0,console.warn("[EmotiveRenderer] cleanupGazeTracking() is deprecated. Use gazeTracker.cleanup() directly.")),this.gazeTracker.cleanup()}resetCanvasContext(){this.canvasContextManager.resetCanvasContext()}setQualityLevel(e){this.canvasContextManager.setQualityLevel(e)}setQualityReduction(e){this.canvasContextManager.setQualityReduction(e)}handleContextRecovery(e){this.canvasContextManager.handleContextRecovery(e)}getUndertoneModifier(){return this.stateMachine&&this.stateMachine.getWeightedUndertoneModifiers?this.stateMachine.getWeightedUndertoneModifiers():this.currentUndertone&&this.undertoneModifiers[this.currentUndertone]?this.undertoneModifiers[this.currentUndertone]:null}applyGestureAnimations(){return this.gestureAnimator.applyGestureAnimations()}startGesture(e){return this.gestureAnimator.startGesture(e)}getCurrentGesture(){return this.gestureAnimator.getCurrentGesture()}_createGestureDelegates(){["Bounce","Pulse","Shake","Spin","Nod","Tilt","Expand","Contract","Flash","Drift","Stretch","Glow","Flicker","Vibrate","Orbital","Hula","Wave","Breathe","Morph","SlowBlink","Look","Settle","BreathIn","BreathOut","BreathHold","BreathHoldEmpty","Jump","Sway","Float","Rain","RunningMan","Charleston","Sparkle","Shimmer","Wiggle","Groove","Point","Lean","Reach","HeadBob","Orbit"].forEach(e=>{const t=`start${e}`;this[t]=()=>this.gestureAnimator[t]()})}startGrooveSway(e){this.ambientDanceAnimator.startAmbientAnimation("grooveSway",e)}startGrooveBob(e){this.ambientDanceAnimator.startAmbientAnimation("grooveBob",e)}startGrooveFlow(e){this.ambientDanceAnimator.startAmbientAnimation("grooveFlow",e)}startGroovePulse(e){this.ambientDanceAnimator.startAmbientAnimation("groovePulse",e)}startGrooveStep(e){this.ambientDanceAnimator.startAmbientAnimation("grooveStep",e)}stopAllGestures(){this.gestureAnimator.stopAllGestures(),this.currentGesture=null}isGestureActive(){return Object.values(this.gestureAnimator.gestureAnimations).some(e=>e.active)}destroy(){this.resourceCleanupManager.destroy()}}class ba{constructor(e,t={}){this.canvas=e,this.config={smoothing:t.smoothing||.1,maxOffset:t.maxOffset||.3,lockDistance:t.lockDistance||30,enabled:!1!==t.enabled,boundaryPadding:t.boundaryPadding||.8},this.canvasCenter={x:0,y:0},this.mousePos={x:0,y:0},this.targetGaze={x:0,y:0},this.currentGaze={x:0,y:0},this.isLocked=!1,this.proximity=0,this.cachedRect=null,this.touches=new Map,this.primaryTouch=null,this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.onInteraction=null,this.updateCanvasCenter(),this.attachEventListeners(),"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this.updateCanvasCenter()}),this.resizeObserver.observe(this.canvas))}updateCanvasCenter(){this.cachedRect=this.canvas.getBoundingClientRect(),this.canvasCenter={x:this.cachedRect.width/2,y:this.cachedRect.height/2},0===this.mousePos.x&&0===this.mousePos.y&&(this.mousePos={x:this.canvasCenter.x,y:this.canvasCenter.y})}attachEventListeners(){this.config.enabled&&(this.canvas.addEventListener("mousemove",this.handleMouseMove),this.canvas.addEventListener("mouseleave",this.handleMouseLeave),this.canvas.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.canvas.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.canvas.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.canvas.addEventListener("touchcancel",this.handleTouchEnd,{passive:!0}))}handleMouseMove(e){const t=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:e.clientX-t.left,y:e.clientY-t.top},this.updateTargetGaze(),this.onInteraction&&this.onInteraction("mouse")}handleMouseLeave(){this.targetGaze={x:0,y:0},this.isLocked=!1,this.proximity=0,this.mousePos={x:this.canvasCenter.x,y:this.canvasCenter.y}}handleTouchStart(e){for(const t of e.changedTouches)this.touches.set(t.identifier,{x:t.clientX,y:t.clientY}),this.primaryTouch||1!==this.touches.size||(this.primaryTouch=t.identifier);null!==this.primaryTouch&&this.updateTouchPosition(e.touches)}handleTouchMove(e){for(const t of e.changedTouches)this.touches.has(t.identifier)&&this.touches.set(t.identifier,{x:t.clientX,y:t.clientY});null!==this.primaryTouch&&(this.updateTouchPosition(e.touches),this.onInteraction&&this.onInteraction("touch"))}handleTouchEnd(e){for(const t of e.changedTouches)this.touches.delete(t.identifier),t.identifier===this.primaryTouch&&(this.primaryTouch=null,this.touches.size>0?this.primaryTouch=this.touches.keys().next().value:this.handleMouseLeave())}updateTouchPosition(e){for(const t of e)if(t.identifier===this.primaryTouch){const e=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:t.clientX-e.left,y:t.clientY-e.top},this.updateTargetGaze();break}}updateTargetGaze(){const e=this.mousePos.x-this.canvasCenter.x,t=this.mousePos.y-this.canvasCenter.y,i=Math.sqrt(e*e+t*t),s=Math.min(this.canvasCenter.x,this.canvasCenter.y);if(this.proximity=Math.max(0,1-i/s),this.isLocked=i<this.config.lockDistance,this.isLocked)this.targetGaze={x:e*this.config.maxOffset*2,y:t*this.config.maxOffset*2};else{const n=Math.min(this.canvasCenter.x,this.canvasCenter.y)*this.config.maxOffset;if(i>0){const a=Math.min(1,i/s);this.targetGaze={x:e/i*n*a*this.config.boundaryPadding,y:t/i*n*a*this.config.boundaryPadding}}else this.targetGaze={x:0,y:0}}}update(e){if(!this.config.enabled)return;const t=1-Math.pow(1-this.config.smoothing,e/16.67);if(this.currentGaze.x+=(this.targetGaze.x-this.currentGaze.x)*t,this.currentGaze.y+=(this.targetGaze.y-this.currentGaze.y)*t,this.isLocked){const e=.5;this.currentGaze.x+=(Math.random()-.5)*e,this.currentGaze.y+=(Math.random()-.5)*e}}getGazeOffset(e){return{x:this.currentGaze.x,y:this.currentGaze.y}}getState(){return{gaze:{...this.currentGaze},target:{...this.targetGaze},proximity:this.proximity,isLocked:this.isLocked,isActive:this.config.enabled}}enable(){this.config.enabled||(this.config.enabled=!0,this.attachEventListeners())}disable(){this.config.enabled&&(this.config.enabled=!1,this.detachEventListeners(),this.targetGaze={x:0,y:0})}detachEventListeners(){this.canvas.removeEventListener("mousemove",this.handleMouseMove),this.canvas.removeEventListener("mouseleave",this.handleMouseLeave),this.canvas.removeEventListener("touchstart",this.handleTouchStart),this.canvas.removeEventListener("touchmove",this.handleTouchMove),this.canvas.removeEventListener("touchend",this.handleTouchEnd),this.canvas.removeEventListener("touchcancel",this.handleTouchEnd)}setInteractionCallback(e){this.onInteraction=e}destroy(){this.detachEventListeners(),this.resizeObserver&&this.resizeObserver.disconnect(),this.touches.clear()}}class va{constructor(e={}){this.config={blinkInterval:e.blinkInterval||{min:3e3,max:7e3},blinkDuration:e.blinkDuration||150,swayInterval:e.swayInterval||{min:2e4,max:4e4},swayDuration:e.swayDuration||4e3,swayIntensity:e.swayIntensity||1.5,sleepTimeout:void 0!==e.sleepTimeout?e.sleepTimeout:1/0,breathingSpeed:e.breathingSpeed||.25,breathingDepth:e.breathingDepth||.1,enabled:!1!==e.enabled},this.state={isBlinking:!1,isSwaying:!1,isAsleep:!1,breathingPhase:0,breathRate:1,breathDepth:this.config.breathingDepth},this.timers={idle:0,blink:0,sway:0,swayProgress:0,nextBlink:this.getRandomInterval("blink"),nextSway:this.getRandomInterval("sway")},this.swayOffset={x:0,y:0},this.swayTarget={x:0,y:0},this.swayStart={x:0,y:0},this.wakeUpTimeout=null,this.callbacks={onBlink:null,onSway:null,onSleep:null,onWake:null}}update(e){this.config.enabled&&(this.updateBreathing(e),this.timers.idle+=e,!this.state.isAsleep&&this.timers.idle>=this.config.sleepTimeout&&this.enterSleep(),this.state.isAsleep||this.updateBlinking(e),this.state.isAsleep||this.updateSwaying(e))}updateBreathing(e){const t=this.config.breathingSpeed*this.state.breathRate;this.state.breathingPhase+=t*e/1e3,this.state.breathingPhase>2*Math.PI&&(this.state.breathingPhase-=2*Math.PI)}updateBlinking(e){this.isBlinkingEnabled()&&(this.state.isBlinking?(this.timers.blink+=e,this.timers.blink>=this.config.blinkDuration&&this.endBlink()):(this.timers.blink+=e,this.timers.blink>=this.timers.nextBlink&&this.startBlink()))}updateSwaying(e){if(this.state.isSwaying){this.timers.sway+=e;const t=Math.min(this.timers.sway/this.config.swayDuration,1),i=(Math.sin((t-.5)*Math.PI)+1)/2;this.swayOffset.x=this.swayStart.x+(this.swayTarget.x-this.swayStart.x)*i,this.swayOffset.y=this.swayStart.y+(this.swayTarget.y-this.swayStart.y)*i,t>=1&&this.endSway()}else this.timers.sway+=e,this.timers.sway>=this.timers.nextSway&&this.startSway()}startBlink(){this.state.isBlinking=!0,this.timers.blink=0,this.callbacks.onBlink&&this.callbacks.onBlink({phase:"start"})}endBlink(){this.state.isBlinking=!1,this.timers.blink=0,this.timers.nextBlink=this.getRandomInterval("blink"),this.callbacks.onBlink&&this.callbacks.onBlink({phase:"end"})}startSway(){this.state.isSwaying=!0,this.timers.sway=0,this.swayStart={...this.swayOffset};const e=Math.random()*Math.PI*2,t=this.config.swayIntensity*(.5+.5*Math.random());this.swayTarget={x:Math.cos(e)*t*1.5,y:Math.sin(e)*t*.5},this.callbacks.onSway&&this.callbacks.onSway({phase:"start",offset:this.swayOffset})}endSway(){this.state.isSwaying=!1,this.timers.sway=0,this.timers.nextSway=this.getRandomInterval("sway"),this.swayStart={...this.swayOffset},this.callbacks.onSway&&this.callbacks.onSway({phase:"end",offset:this.swayOffset})}enterSleep(){this.state.isAsleep=!0,this.state.breathRate=.5,this.state.breathDepth=.15,this.state.isBlinking&&(this.state.isBlinking=!1,this.timers.blink=0,this.callbacks.onBlink&&this.callbacks.onBlink({phase:"end"})),this.callbacks.onSleep&&this.callbacks.onSleep()}wakeUp(){this.state.isAsleep&&(this.state.isAsleep=!1,this.state.breathRate=1,this.state.breathDepth=this.config.breathingDepth,this.timers.idle=0,this.callbacks.onWake&&this.callbacks.onWake(),this.performWakeAnimation())}performWakeAnimation(){const e={x:.5*this.config.swayIntensity,y:-this.config.swayIntensity};this.swayStart={...this.swayOffset},this.swayTarget=e,this.state.isSwaying=!0,this.timers.sway=0,this.callbacks.onSway&&this.callbacks.onSway({phase:"wake",offset:this.swayOffset}),this.wakeUpTimeout&&clearTimeout(this.wakeUpTimeout),this.wakeUpTimeout=setTimeout(()=>{this.swayStart={...this.swayOffset},this.swayTarget={x:0,y:0},this.timers.sway=0,this.wakeUpTimeout=null},1e3)}resetIdleTimer(){this.timers.idle=0,this.state.isAsleep&&this.wakeUp()}setBlinkingEnabled(e){this.config.blinkingEnabled=e,!e&&this.state.isBlinking&&this.endBlink()}isBlinkingEnabled(){return!1!==this.config.blinkingEnabled}getBreathingFactor(){return 1+Math.sin(this.state.breathingPhase)*this.state.breathDepth*this.state.breathRate}getBlinkProgress(){return this.state.isBlinking?Math.min(this.timers.blink/this.config.blinkDuration,1):0}getSwayOffset(){return this.swayOffset||{x:0,y:0}}getRandomInterval(e){const t=this.config[`${e}Interval`];return t.min+Math.random()*(t.max-t.min)}setCallback(e,t){({}).hasOwnProperty.call(this.callbacks,e)&&(this.callbacks[e]=t)}getState(){return{...this.state,breathingFactor:this.getBreathingFactor(),blinkProgress:this.getBlinkProgress(),swayOffset:this.getSwayOffset()}}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1,this.state.isBlinking=!1,this.state.isSwaying=!1,this.swayOffset={x:0,y:0}}destroy(){this.wakeUpTimeout&&(clearTimeout(this.wakeUpTimeout),this.wakeUpTimeout=null),this.callbacks={onBlink:null,onSway:null,onSleep:null,onWake:null}}}var Ma=Object.freeze({__proto__:null,default:va});class wa{constructor(e){this.positionController=e,this.watchedElements=new Map,this.updateCallbacks=new Map}moveToElement(e,t="right",i={x:20,y:0},s={}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=n.getBoundingClientRect(),r=a.left+a.width/2,o=a.top+a.height/2;let l,h;switch(t){case"right":default:l=a.right+i.x,h=o+i.y;break;case"left":l=a.left-i.x,h=o+i.y;break;case"above":l=r+i.x,h=a.top-i.y;break;case"below":l=r+i.x,h=a.bottom+i.y;break;case"center":l=r+i.x,h=o+i.y}const c=l-window.innerWidth/2,u=h-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(c,u,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(c,u,0)}moveToButton(e="button",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToForm(e="form",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToModal(e='[role="dialog"], .modal',t="center",i={x:0,y:0}){this.moveToElement(e,t,i)}moveToNavigation(e="nav, .navigation",t="below",i={x:0,y:20}){this.moveToElement(e,t,i)}moveToContent(e="main, .content",t="center",i={x:0,y:0}){this.moveToElement(e,t,i)}moveToSidebar(e=".sidebar, aside",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToHeader(e="header, .header",t="below",i={x:0,y:20}){this.moveToElement(e,t,i)}moveToFooter(e="footer, .footer",t="above",i={x:0,y:20}){this.moveToElement(e,t,i)}watchElement(e,t="right",i={x:20,y:0}){const s=()=>{this.moveToElement(e,t,i,{animate:!1})},n=`${e}-${t}-${JSON.stringify(i)}`;return this.updateCallbacks.set(n,s),window.addEventListener("scroll",s),window.addEventListener("resize",s),s(),()=>{window.removeEventListener("scroll",s),window.removeEventListener("resize",s),this.updateCallbacks.delete(n)}}stopWatchingAll(){this.updateCallbacks.forEach(e=>{window.removeEventListener("scroll",e),window.removeEventListener("resize",e)}),this.updateCallbacks.clear()}destroy(){this.stopWatchingAll(),this.positionController=null}}class Sa extends wa{constructor(e){super(e),this.activeCallbacks=new Map,this.callbackStates=new Map}moveToElementWithCallback(e,t,i="right",s={x:20,y:0},n={}){const a=`callback-${Date.now()}-${Math.random()}`,r=document.querySelector(e);if(!r)return void console.warn(`Element not found: ${e}`);this.callbackStates.set(a,{executed:!1,element:r,callback:t,options:n}),this.moveToElement(e,i,s,n);const o=()=>{if(this.isMascotNearElement(r,n.proximity||50)){const e=this.callbackStates.get(a);e&&!e.executed&&(e.executed=!0,t(),n.repeat||this.callbackStates.delete(a))}this.callbackStates.has(a)&&requestAnimationFrame(o)};return this.activeCallbacks.set(a,o),o(),()=>{this.activeCallbacks.delete(a),this.callbackStates.delete(a)}}moveToElementSequence(e=[],t={}){let i=0;const s=[],n=()=>{if(i>=e.length)return void(t.onComplete&&t.onComplete());const a=e[i],r=this.moveToElementWithCallback(a.selector,()=>{a.callback&&a.callback(),i++,setTimeout(n,a.delay||0)},a.position||"right",a.offset||{x:20,y:0},{...t,...a.options});r&&s.push(r)};return n(),()=>{s.forEach(e=>e())}}moveToElementWithDelay(e,t,i=1e3,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,()=>{setTimeout(t,i)},s,n)}moveToElementWithCondition(e,t,i,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,()=>{t()&&i()},s,n)}moveToElementWithRepeat(e,t,i=1e3,s="right",n={x:20,y:0}){let a=null;const r=this.moveToElementWithCallback(e,()=>{a=setInterval(t,i)},s,n,{repeat:!0});return()=>{null!==a&&(clearInterval(a),a=null),r&&r()}}moveToElementWithProximity(e,t,i=100,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,t,s,n,{proximity:i})}isMascotNearElement(e,t=50){if(!this.positionController||!e)return!1;const i=e.getBoundingClientRect(),s=i.left+i.width/2,n=i.top+i.height/2,a=this.positionController.getOffset(),r=a.x+window.innerWidth/2,o=a.y+window.innerHeight/2;return Math.sqrt(Math.pow(r-s,2)+Math.pow(o-n,2))<=t}stopAllCallbacks(){this.activeCallbacks.forEach((e,t)=>{this.activeCallbacks.delete(t)}),this.callbackStates.clear()}destroy(){this.stopAllCallbacks(),super.destroy()}}class xa extends wa{constructor(e){super(e),this.activePaths=new Map,this.obstacles=new Set,this.audioContext=null,this.audioAnalyser=null,this.gazeTracker=null,this.activeRAFIds=new Set,this.activeSmoothAnimations=new Set}moveToElementWithPath(e,t=[],i="right",s={x:20,y:0},n={}){const a=`path-${Date.now()}-${Math.random()}`,r=document.querySelector(e);if(!r)return void console.warn(`Element not found: ${e}`);const o=window.innerWidth||1,l=window.innerHeight||1,h=o/2,c=l/2,u=n.coordinateSystem||"auto",d=Array.isArray(t)?t.map((e={})=>{const t="number"==typeof e.x?e.x:0,i="number"==typeof e.y?e.y:0;return"relative"===u||"auto"===u&&t>=0&&t<=1&&i>=0&&i<=1?{x:t*o-h,y:i*l-c}:"offset"===u||"auto"===u&&Math.abs(t)<=h&&Math.abs(i)<=c?{x:t,y:i}:{x:t-h,y:i-c}}):[],g=r.getBoundingClientRect(),m={x:g.left+g.width/2+s.x-h,y:g.top+g.height/2+s.y-c},p=this.positionController.getOffset?this.positionController.getOffset():{x:0,y:0},f=[{x:"number"==typeof p.x?p.x:0,y:"number"==typeof p.y?p.y:0},...d,m];if(f.length<2)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const y=[],b=[0];let v=0;for(let e=0;e<f.length-1;e++){const t=f[e+1].x-f[e].x,i=f[e+1].y-f[e].y,s=Math.hypot(t,i);y.push(s),v+=s,b.push(v)}if(0===v)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const M="number"==typeof n.speed&&n.speed>0?n.speed:250,w=!0===n.loop,S=n.easing||"linear",x={covered:0,lastTimestamp:null},C=e=>{if(w)e%=v;else{if(e<=0)return f[0];if(e>=v)return f[f.length-1]}for(let t=0;t<y.length;t++){const i=b[t];if(e<=b[t+1]){const s=y[t]||1,n=0===s?0:(e-i)/s,a=this.positionController&&"function"==typeof this.positionController.applyEasing?this.positionController.applyEasing(n,S):n,r=f[t],o=f[t+1];return{x:r.x+(o.x-r.x)*a,y:r.y+(o.y-r.y)*a}}}return f[f.length-1]},k={stop:()=>{k.frameId&&cancelAnimationFrame(k.frameId),this.activePaths.delete(a)},frameId:null};this.activePaths.set(a,k),this.positionController.setOffset(f[0].x,f[0].y,0);const P=e=>{if(!this.activePaths.has(a))return;null===x.lastTimestamp&&(x.lastTimestamp=e);const t=e-x.lastTimestamp;if(x.lastTimestamp=e,x.covered+=M*(t/1e3),!w&&x.covered>=v)return this.positionController.setOffset(m.x,m.y,0),k.stop(),void("function"==typeof n.onComplete&&n.onComplete());const i=C(x.covered);this.positionController.setOffset(i.x,i.y,0),k.frameId=requestAnimationFrame(P)};return k.frameId=requestAnimationFrame(P),()=>{k.stop()}}moveToElementWithEasing(e,t,i=1e3,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=a.getBoundingClientRect(),o=r.left+r.width/2+n.x-window.innerWidth/2,l=r.top+r.height/2+n.y-window.innerHeight/2,h=this.positionController.getOffset(),c=performance.now();let u=null;const d=e=>{const s=e-c,n=Math.min(s/i,1),a=t(n),r=h.x+(o-h.x)*a,g=h.y+(l-h.y)*a;this.positionController.setOffset(r,g,0),n<1?(u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)):null!==u&&this.activeSmoothAnimations.delete(u)};u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)}moveToElementWithCollision(e,t=[],i=100,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=a.getBoundingClientRect(),o=r.left+r.width/2+n.x-window.innerWidth/2,l=r.top+r.height/2+n.y-window.innerHeight/2,h=this.positionController.getOffset();(()=>{let e=h.x,s=h.y;for(let n=0;n<=100;n++){const a=.01*n,r=h.x+(o-h.x)*a,c=h.y+(l-h.y)*a;let u=!1;t.forEach(t=>{let n,a;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();n=t.left+t.width/2-window.innerWidth/2,a=t.top+t.height/2-window.innerHeight/2}}else n=t.x-window.innerWidth/2,a=t.y-window.innerHeight/2;if(Math.sqrt(Math.pow(r-n,2)+Math.pow(c-a,2))<i){u=!0;const t=Math.atan2(c-a,r-n),o=n+Math.cos(t)*i,l=a+Math.sin(t)*i;e=o,s=l}}),u||(e=r,s=c)}this.positionController.setOffset(e,s,0)})()}moveToElementWithAudio(e,t,i=50,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256),this.audioContext.createMediaStreamSource(t).connect(this.audioAnalyser);const r=new Uint8Array(this.audioAnalyser.frequencyBinCount),o=a.getBoundingClientRect(),l=o.left+o.width/2+n.x-window.innerWidth/2,h=o.top+o.height/2+n.y-window.innerHeight/2;let c=null;const u=()=>{this.audioAnalyser.getByteFrequencyData(r);let e=0;for(let t=0;t<r.length;t++)e+=r[t];const t=e/r.length/255*i,s=l+t,n=h+.5*t;this.positionController.setOffset(s,n,0),null!==c&&this.activeRAFIds.delete(c),c=requestAnimationFrame(u),this.activeRAFIds.add(c)};u()}moveToElementWithGaze(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);this.gazeTracker||(this.gazeTracker={x:window.innerWidth/2,y:window.innerHeight/2});const a=n.getBoundingClientRect(),r=a.left+a.width/2+s.x-window.innerWidth/2,o=a.top+a.height/2+s.y-window.innerHeight/2;let l=null;const h=()=>{const e=this.gazeTracker.x-window.innerWidth/2,i=this.gazeTracker.y-window.innerHeight/2,s=t.gazeWeight||.3,n=r+(e-r)*s,a=o+(i-o)*s;this.positionController.setOffset(n,a,0),null!==l&&this.activeRAFIds.delete(l),l=requestAnimationFrame(h),this.activeRAFIds.add(l)};h()}addObstacle(e){this.obstacles.add(e)}removeObstacle(e){this.obstacles.delete(e)}clearObstacles(){this.obstacles.clear()}destroy(){Array.from(this.activePaths.values()).forEach(e=>{e&&"function"==typeof e.stop?e.stop():e&&e.frameId&&cancelAnimationFrame(e.frameId)}),this.activePaths.clear(),this.activeRAFIds.forEach(e=>{cancelAnimationFrame(e)}),this.activeRAFIds.clear(),this.activeSmoothAnimations.forEach(e=>{cancelAnimationFrame(e)}),this.activeSmoothAnimations.clear(),this.obstacles.clear(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.audioAnalyser=null,this.gazeTracker=null,super.destroy()}}class Ca extends wa{constructor(e){super(e),this.scrollCallbacks=new Map,this.physicsSimulations=new Map,this.responsiveBreakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.accessibilityEnabled=!1}moveToElementWithScroll(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`scroll-${Date.now()}-${Math.random()}`,{startScroll:r=50,endScroll:o=300,onProgress:l=null,onStart:h=null,onComplete:c=null}=t;let u=!1,d=!1;const g=()=>{const{scrollY:e}=window,t=Math.min(Math.max((e-r)/(o-r),0),1);t>0&&!u&&(u=!0,h&&h()),t>=1&&!d&&(d=!0,c&&c());const i=n.getBoundingClientRect(),a=i.left+i.width/2+s.x-window.innerWidth/2,g=i.top+i.height/2+s.y-window.innerHeight/2,m=window.innerWidth>1024,p=m?.25*window.innerWidth:.33*window.innerWidth-50,f=m?-.25*window.innerHeight-50+.15*window.innerHeight:-.35*window.innerHeight-50+.08*window.innerHeight,y=p+(a-p)*t,b=f+(g-f)*t;this.positionController.setOffset(y,b,0),l&&l(t,{scrollY:e,currentX:y,currentY:b})};return this.scrollCallbacks.set(a,g),window.addEventListener("scroll",g),g(),()=>{this.scrollCallbacks.delete(a),window.removeEventListener("scroll",g)}}moveToElementWithPhysics(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`physics-${Date.now()}-${Math.random()}`,{mass:r=1,damping:o=.98,springConstant:l=.1,maxVelocity:h=10,onUpdate:c=null}=t,u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x-window.innerWidth/2,g=u.top+u.height/2+s.y-window.innerHeight/2,m=this.positionController.getOffset();let p=m.x,f=m.y,y=0,b=0;const v=()=>{y+=(d-p)*l/r,b+=(g-f)*l/r,y*=o,b*=o;const e=Math.sqrt(y*y+b*b);e>h&&(y=y/e*h,b=b/e*h),p+=y,f+=b,this.positionController.setOffset(p,f,0),c&&c({positionX:p,positionY:f,velocityX:y,velocityY:b}),this.physicsSimulations.has(a)&&requestAnimationFrame(v)};return this.physicsSimulations.set(a,v),v(),()=>{this.physicsSimulations.delete(a)}}moveToElementWithGroup(e=[],t="center",i={x:0,y:0}){if(0===e.length)return void console.warn("No element selectors provided");let s=0,n=0,a=0,r=0,o=0;if(e.forEach(e=>{const t=document.querySelector(e);if(t){const e=t.getBoundingClientRect();s+=e.left,n+=e.top,a=Math.max(a,e.left+e.width),r=Math.max(r,e.top+e.height),o++}}),0===o)return;const l=s/o,h=n/o;let c,u;switch(t){case"center":default:c=l+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"left":c=s+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"right":c=a+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"top":c=l+i.x-window.innerWidth/2,u=n+i.y-window.innerHeight/2;break;case"bottom":c=l+i.x-window.innerWidth/2,u=r+i.y-window.innerHeight/2}this.positionController.setOffset(c,u,0)}moveToElementWithResponsive(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=()=>{const e=this.getCurrentBreakpoint(),i=t[e]||t.default||{},a=n.getBoundingClientRect(),r=a.left+a.width/2+(i.offsetX||s.x)-window.innerWidth/2,o=a.top+a.height/2+(i.offsetY||s.y)-window.innerHeight/2;this.positionController.setOffset(r,o,0)},r=()=>{const e=this.getCurrentBreakpoint();e!==this.currentBreakpoint&&(this.currentBreakpoint=e,a())};return window.addEventListener("resize",r),a(),()=>{window.removeEventListener("resize",r)}}moveToElementWithAccessibility(e,t={},i="right",s={x:20,y:0}){if(!document.querySelector(e))return void console.warn(`Element not found: ${e}`);const{announce:n=!0,announcements:a=[],screenReaderPosition:r="bottom-right"}=t;let o,l;switch(r){case"bottom-right":default:o=window.innerWidth-100-window.innerWidth/2,l=window.innerHeight-100-window.innerHeight/2;break;case"bottom-left":o=100-window.innerWidth/2,l=window.innerHeight-100-window.innerHeight/2;break;case"top-right":o=window.innerWidth-100-window.innerWidth/2,l=100-window.innerHeight/2;break;case"top-left":o=100-window.innerWidth/2,l=100-window.innerHeight/2}this.positionController.setOffset(o,l,0),n&&window.speechSynthesis&&a.forEach(e=>{if(e.condition&&e.condition()){const t=new SpeechSynthesisUtterance(e.text);t.volume=.5,t.rate=.8,window.speechSynthesis.speak(t)}})}getCurrentBreakpoint(){const e=window.innerWidth;return e<this.responsiveBreakpoints.mobile?"mobile":e<this.responsiveBreakpoints.tablet?"tablet":e<this.responsiveBreakpoints.desktop?"desktop":"large"}setBreakpoints(e){this.responsiveBreakpoints={...this.responsiveBreakpoints,...e},this.currentBreakpoint=this.getCurrentBreakpoint()}enableAccessibility(){this.accessibilityEnabled=!0}disableAccessibility(){this.accessibilityEnabled=!1}destroy(){this.scrollCallbacks.forEach((e,t)=>{window.removeEventListener("scroll",e)}),this.scrollCallbacks.clear(),this.physicsSimulations.clear(),super.destroy()}}class ka extends wa{constructor(e){super(e),this.activeInteractions=new Map,this.hoverStates=new Map,this.clickStates=new Map,this.touchStates=new Map}moveToElementWithHover(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`hover-${Date.now()}-${Math.random()}`,{onMouseEnter:r=null,onMouseLeave:o=null,onHover:l=null,followMouse:h=!1,hoverDistance:c=50}=t;let u=!1,d=0,g=0;const m=e=>{u=!0,r&&r(e)},p=e=>{u=!1,o&&o(e)},f=e=>{if(d=e.clientX,g=e.clientY,u&&l&&l(e),h&&u){const e=n.getBoundingClientRect(),t=e.left+e.width/2,i=e.top+e.height/2;if(Math.sqrt(Math.pow(d-t,2)+Math.pow(g-i,2))<=c){const e=d+s.x-window.innerWidth/2,t=g+s.y-window.innerHeight/2;this.positionController.setOffset(e,t,0)}}};return n.addEventListener("mouseenter",m),n.addEventListener("mouseleave",p),n.addEventListener("mousemove",f),this.activeInteractions.set(a,{element:n,events:[{event:"mouseenter",handler:m},{event:"mouseleave",handler:p},{event:"mousemove",handler:f}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithClick(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`click-${Date.now()}-${Math.random()}`,{onClick:r=null,onDoubleClick:o=null,maxClicks:l=3}=t;let h=0;const c=e=>{if(h++,r&&r(e,h),h>=l){const e=n.getBoundingClientRect(),t=e.left+e.width/2+s.x-window.innerWidth/2,i=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(t,i,0)}},u=e=>{o&&o(e)};return n.addEventListener("click",c),n.addEventListener("dblclick",u),this.activeInteractions.set(a,{element:n,events:[{event:"click",handler:c},{event:"dblclick",handler:u}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithTouch(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`touch-${Date.now()}-${Math.random()}`,{onTouchStart:r=null,onTouchMove:o=null,onTouchEnd:l=null,onSwipe:h=null,swipeThreshold:c=50}=t;let u=0,d=0,g=0,m=0;const p=e=>{e.touches.length>0&&(u=e.touches[0].clientX,d=e.touches[0].clientY,r&&r(e))},f=e=>{if(e.touches.length>0){const t=e.touches[0].clientX,i=e.touches[0].clientY;o&&o(e);const n=t+s.x-window.innerWidth/2,a=i+s.y-window.innerHeight/2;this.positionController.setOffset(n,a,0)}},y=e=>{if(e.changedTouches.length>0){g=e.changedTouches[0].clientX,m=e.changedTouches[0].clientY,l&&l(e);const t=g-u,i=m-d,s=Math.sqrt(t*t+i*i);if(s>c&&h){const e=Math.abs(t)>Math.abs(i)?t>0?"right":"left":i>0?"down":"up";h(e,s)}}};return n.addEventListener("touchstart",p),n.addEventListener("touchmove",f),n.addEventListener("touchend",y),this.activeInteractions.set(a,{element:n,events:[{event:"touchstart",handler:p},{event:"touchmove",handler:f},{event:"touchend",handler:y}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithFocus(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`focus-${Date.now()}-${Math.random()}`,{onFocus:r=null,onBlur:o=null,onFocusIn:l=null,onFocusOut:h=null}=t,c=e=>{r&&r(e);const t=n.getBoundingClientRect(),i=t.left+t.width/2+s.x-window.innerWidth/2,a=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(i,a,0)},u=e=>{o&&o(e)},d=e=>{l&&l(e)},g=e=>{h&&h(e)};return n.addEventListener("focus",c),n.addEventListener("blur",u),n.addEventListener("focusin",d),n.addEventListener("focusout",g),this.activeInteractions.set(a,{element:n,events:[{event:"focus",handler:c},{event:"blur",handler:u},{event:"focusin",handler:d},{event:"focusout",handler:g}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithKeyboard(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`keyboard-${Date.now()}-${Math.random()}`,{onKeyDown:r=null,onKeyUp:o=null,onKeyPress:l=null,targetKeys:h=["Enter","Space"]}=t,c=e=>{if(r&&r(e),h.includes(e.key)){const e=n.getBoundingClientRect(),t=e.left+e.width/2+s.x-window.innerWidth/2,i=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(t,i,0)}},u=e=>{o&&o(e)},d=e=>{l&&l(e)};return n.addEventListener("keydown",c),n.addEventListener("keyup",u),n.addEventListener("keypress",d),this.activeInteractions.set(a,{element:n,events:[{event:"keydown",handler:c},{event:"keyup",handler:u},{event:"keypress",handler:d}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}stopAllInteractions(){this.activeInteractions.forEach((e,t)=>{e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(t)}),this.hoverStates.clear(),this.clickStates.clear(),this.touchStates.clear()}destroy(){this.stopAllInteractions(),super.destroy()}}class Pa extends wa{constructor(e){super(e),this.activeAnimations=new Map,this.animationQueue=[],this.isAnimating=!1,this.queueTimeouts=new Set,this.activeRAFIds=new Set,this.animationRAFIds=new Map}moveToElementWithBounce(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`bounce-${Date.now()}-${Math.random()}`,{duration:r=1e3,intensity:o=50,bounces:l=3,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=this.positionController.getOffset(),m=performance.now(),p=e=>{const t=e-m,i=Math.min(t/r,1),s=1-Math.pow(1-i,3),n=Math.sin(s*Math.PI*l)*o*(1-i),c=g.x+(u-g.x)*i,f=g.y+(d-g.y)*i+n;if(this.positionController.setOffset(c,f,0),i<1){this.activeAnimations.set(a,p);const e=requestAnimationFrame(p);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,p);const f=requestAnimationFrame(p);return this.activeRAFIds.add(f),this.animationRAFIds.set(a,f),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithShake(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`shake-${Date.now()}-${Math.random()}`,{duration:r=500,intensity:o=10,frequency:l=20,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=(Math.random()-.5)*o*(1-i),n=(Math.random()-.5)*o*(1-i),c=u+s,p=d+n;if(this.positionController.setOffset(c,p,0),i<1)this.activeAnimations.set(a,m),setTimeout(()=>{const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)},1e3/l);else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithPulse(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`pulse-${Date.now()}-${Math.random()}`,{duration:r=2e3,intensity:o=20,frequency:l=2,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=Math.sin(t*l*.01)*o*(1-i),n=u+s,c=d+s;if(this.positionController.setOffset(n,c,0),i<1){this.activeAnimations.set(a,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithWiggle(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`wiggle-${Date.now()}-${Math.random()}`,{duration:r=1e3,intensity:o=15,frequency:l=8,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=Math.sin(t*l*.01)*o*(1-i),n=Math.cos(t*l*.01)*o*(1-i),c=u+s,p=d+n;if(this.positionController.setOffset(c,p,0),i<1){this.activeAnimations.set(a,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithCustom(e,t,i={},s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=`custom-${Date.now()}-${Math.random()}`,{duration:o=1e3,onComplete:l=null}=i,h=a.getBoundingClientRect(),c=h.left+h.width/2+n.x-window.innerWidth/2,u=h.top+h.height/2+n.y-window.innerHeight/2,d=this.positionController.getOffset(),g=performance.now(),m=e=>{const i=e-g,s=Math.min(i/o,1),n=t(s,{elapsed:i,startOffset:d,targetX:c,targetY:u,currentTime:e});if(n&&"object"==typeof n){const e=void 0!==n.x?n.x:c,t=void 0!==n.y?n.y:u;this.positionController.setOffset(e,t,0)}if(s<1){this.activeAnimations.set(r,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(r,e)}else{this.activeAnimations.delete(r);const e=this.animationRAFIds.get(r);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(r,p),()=>{this.activeAnimations.delete(r);const e=this.animationRAFIds.get(r);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(r))}}queueAnimations(e=[]){this.animationQueue=[...this.animationQueue,...e],this.processAnimationQueue()}processAnimationQueue(){if(this.isAnimating||0===this.animationQueue.length)return;this.isAnimating=!0;const e=this.animationQueue.shift();if(e){const t=this.executeAnimation(e);if(t){const i=setTimeout(()=>{this.queueTimeouts.delete(i),t(),this.isAnimating=!1,this.processAnimationQueue()},e.duration||1e3);this.queueTimeouts.add(i)}}}executeAnimation(e){const{type:t,targetSelector:i,options:s={},position:n="right",offset:a={x:20,y:0}}=e;switch(t){case"bounce":return this.moveToElementWithBounce(i,s,n,a);case"shake":return this.moveToElementWithShake(i,s,n,a);case"pulse":return this.moveToElementWithPulse(i,s,n,a);case"wiggle":return this.moveToElementWithWiggle(i,s,n,a);case"custom":return this.moveToElementWithCustom(i,s.animationFunction,s,n,a);default:return this.moveToElement(i,n,a)}}stopAllAnimations(){this.activeAnimations.forEach((e,t)=>{this.activeAnimations.delete(t)}),this.activeRAFIds.forEach(e=>cancelAnimationFrame(e)),this.activeRAFIds.clear(),this.animationRAFIds.clear(),this.queueTimeouts.forEach(e=>clearTimeout(e)),this.queueTimeouts.clear(),this.animationQueue=[],this.isAnimating=!1}destroy(){this.stopAllAnimations(),super.destroy()}}class Ta extends wa{constructor(e){super(e),this.activeEffects=new Map,this.trailPoints=[],this.particles=[],this.effectCanvas=null,this.effectContext=null,this.maxTrailPoints=50,this.maxParticles=100}moveToElementWithTrail(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`trail-${Date.now()}-${Math.random()}`,{color:r="#00ff88",width:o=3,opacity:l=.8,fadeSpeed:h=.95,onComplete:c=null}=t;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,g=u.top+u.height/2+s.y,m=this.positionController.getOffset(),p=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),b=e=>{const t=e-y,i=Math.min(t/1e3,1),s=p+(d-p)*i,n=f+(g-f)*i;this.trailPoints.push({x:s,y:n,opacity:l*(1-i),timestamp:e}),this.trailPoints.length>this.maxTrailPoints&&this.trailPoints.shift(),this.trailPoints.forEach(e=>{e.opacity*=h}),this.trailPoints=this.trailPoints.filter(e=>e.opacity>.01),this.drawTrail(r,o),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(a,b),requestAnimationFrame(b)):(this.activeEffects.delete(a),c&&c())};return this.activeEffects.set(a,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(a)}}moveToElementWithParticles(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`particles-${Date.now()}-${Math.random()}`,{count:r=20,color:o="#00ff88",size:l=2,speed:h=2,life:c=1e3,onComplete:u=null}=t;this.initializeEffectCanvas();const d=n.getBoundingClientRect(),g=d.left+d.width/2+s.x,m=d.top+d.height/2+s.y,p=this.positionController.getOffset(),f=p.x+window.innerWidth/2,y=p.y+window.innerHeight/2,b=performance.now();for(let e=0;e<r;e++)this.particles.push({x:f,y:y,vx:(Math.random()-.5)*h,vy:(Math.random()-.5)*h,life:c,maxLife:c,color:o,size:l});const v=e=>{const t=e-b,i=Math.min(t/1e3,1);this.particles.forEach(e=>{e.x+=e.vx,e.y+=e.vy,e.life-=16,e.opacity=e.life/e.maxLife}),this.particles=this.particles.filter(e=>e.life>0),this.drawParticles();const s=f+(g-f)*i,n=y+(m-y)*i;this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1||this.particles.length>0?(this.activeEffects.set(a,v),requestAnimationFrame(v)):(this.activeEffects.delete(a),u&&u())};return this.activeEffects.set(a,v),requestAnimationFrame(v),()=>{this.activeEffects.delete(a)}}moveToElementWithGlow(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`glow-${Date.now()}-${Math.random()}`,{color:r="#00ff88",intensity:o=50,radius:l=100,duration:h=1e3,onComplete:c=null}=t;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,g=u.top+u.height/2+s.y,m=this.positionController.getOffset(),p=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),b=e=>{const t=e-y,i=Math.min(t/h,1),s=p+(d-p)*i,n=f+(g-f)*i;this.drawGlow(s,n,r,o,l,i),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(a,b),requestAnimationFrame(b)):(this.activeEffects.delete(a),c&&c())};return this.activeEffects.set(a,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(a)}}initializeEffectCanvas(){this.effectCanvas||(this.effectCanvas=document.createElement("canvas"),this.effectCanvas.style.position="fixed",this.effectCanvas.style.top="0",this.effectCanvas.style.left="0",this.effectCanvas.style.width="100%",this.effectCanvas.style.height="100%",this.effectCanvas.style.pointerEvents="none",this.effectCanvas.style.zIndex="1000",document.body.appendChild(this.effectCanvas),this.effectContext=this.effectCanvas.getContext("2d"),this.resizeEffectCanvas())}resizeEffectCanvas(){this.effectCanvas&&(this.effectCanvas.width=window.innerWidth,this.effectCanvas.height=window.innerHeight)}drawTrail(e,t){if(this.effectContext&&!(this.trailPoints.length<2)){this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.effectContext.strokeStyle=e,this.effectContext.lineWidth=t,this.effectContext.lineCap="round",this.effectContext.lineJoin="round",this.effectContext.beginPath(),this.effectContext.moveTo(this.trailPoints[0].x,this.trailPoints[0].y);for(let e=1;e<this.trailPoints.length;e++){const t=this.trailPoints[e];this.effectContext.globalAlpha=t.opacity,this.effectContext.lineTo(t.x,t.y)}this.effectContext.stroke(),this.effectContext.globalAlpha=1}}drawParticles(){this.effectContext&&(this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.particles.forEach(e=>{this.effectContext.globalAlpha=e.opacity,this.effectContext.fillStyle=e.color,this.effectContext.beginPath(),this.effectContext.arc(e.x,e.y,e.size,0,2*Math.PI),this.effectContext.fill()}),this.effectContext.globalAlpha=1)}drawGlow(e,t,i,s,n,a){if(!this.effectContext)return;this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height);const r=this.effectContext.createRadialGradient(e,t,0,e,t,n),o=Math.floor(s*a).toString(16).padStart(2,"0"),l=i.startsWith("#")?i:`#${i}`;r.addColorStop(0,`${l}${o}`),r.addColorStop(1,`${l}00`),this.effectContext.fillStyle=r,this.effectContext.beginPath(),this.effectContext.arc(e,t,n,0,2*Math.PI),this.effectContext.fill()}stopAllEffects(){this.activeEffects.forEach((e,t)=>{this.activeEffects.delete(t)}),this.trailPoints=[],this.particles=[]}destroy(){this.stopAllEffects(),this.effectCanvas&&(document.body.removeChild(this.effectCanvas),this.effectCanvas=null,this.effectContext=null),super.destroy()}}class Ea extends wa{constructor(e){super(e),this.accessibilityOptions={screenReader:!0,keyboardNavigation:!0,highContrast:!1,reducedMotion:!1,announcements:!0},this.announcements=[],this.keyboardListeners=new Map,this.focusableElements=new Set,this.currentFocusIndex=0,this.focusOrder=[]}moveToElementWithScreenReader(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{announce:a=!0,announcement:r="Mascot moved to element",role:o="button",label:l=n.textContent||n.alt||"Interactive element"}=t;this.moveToElement(e,i,s),a&&this.accessibilityOptions.screenReader&&this.announceToScreenReader(r),n&&(n.setAttribute("role",o),n.setAttribute("aria-label",l),n.setAttribute("aria-live","polite"))}moveToElementWithKeyboard(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{onKeyDown:a=null,onKeyUp:r=null,onEnter:o=null,onEscape:l=null,onArrowKeys:h=null}=t,c=`keyboard-${Date.now()}-${Math.random()}`,u=e=>{switch(a&&a(e),e.key){case"Enter":case" ":o&&o(e);break;case"Escape":l&&l(e);break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":h&&h(e)}},d=e=>{r&&r(e)};return n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),n.addEventListener("keydown",u),n.addEventListener("keyup",d),this.keyboardListeners.set(c,{element:n,events:[{event:"keydown",handler:u},{event:"keyup",handler:d}]}),this.moveToElement(e,i,s),()=>{const e=this.keyboardListeners.get(c);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.keyboardListeners.delete(c))}}moveToElementWithHighContrast(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{backgroundColor:a="#000000",textColor:r="#ffffff",borderColor:o="#ffffff",borderWidth:l=2}=t;this.accessibilityOptions.highContrast&&(n.style.backgroundColor=a,n.style.color=r,n.style.border=`${l}px solid ${o}`,n.style.outline=`${l}px solid ${o}`),this.moveToElement(e,i,s)}moveToElementWithReducedMotion(e,t={},i="right",s={x:20,y:0}){if(!document.querySelector(e))return void console.warn(`Element not found: ${e}`);const{duration:n=0,easing:a="linear"}=t;window.matchMedia("(prefers-reduced-motion: reduce)").matches||this.accessibilityOptions.reducedMotion?this.moveToElement(e,i,s):this.moveToElement(e,i,s,{duration:n,easing:a})}moveToElementWithFocus(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{autoFocus:a=!1,focusRing:r=!0,focusOrder:o=[]}=t;o.length>0?this.focusOrder=o:this.focusOrder.includes(e)||this.focusOrder.push(e),n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),r&&(n.style.outline="2px solid #0066cc",n.style.outlineOffset="2px"),a&&n.focus(),this.moveToElement(e,i,s)}navigateFocus(e="next"){if(0===this.focusOrder.length)return;this.currentFocusIndex="next"===e?(this.currentFocusIndex+1)%this.focusOrder.length:(this.currentFocusIndex-1+this.focusOrder.length)%this.focusOrder.length;const t=this.focusOrder[this.currentFocusIndex],i=document.querySelector(t);i&&(i.focus(),this.moveToElement(t,"right",{x:20,y:0}))}announceToScreenReader(e){if(!this.accessibilityOptions.announcements)return;let t=document.getElementById("mascot-live-region");t||(t=document.createElement("div"),t.id="mascot-live-region",t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.style.position="absolute",t.style.left="-10000px",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",document.body.appendChild(t)),t.textContent=e,setTimeout(()=>{t.textContent=""},1e3)}enableAccessibility(e={}){this.accessibilityOptions={...this.accessibilityOptions,...e}}disableAccessibility(e={}){Object.keys(e).forEach(e=>{({}).hasOwnProperty.call(this.accessibilityOptions,e)&&(this.accessibilityOptions[e]=!1)})}isAccessibilityEnabled(e){return this.accessibilityOptions[e]||!1}getAccessibilityOptions(){return{...this.accessibilityOptions}}destroy(){this.keyboardListeners.forEach((e,t)=>{e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)})}),this.keyboardListeners.clear();const e=document.getElementById("mascot-live-region");e&&document.body.removeChild(e),this.focusOrder=[],this.currentFocusIndex=0,super.destroy()}}class Aa{constructor(e){this.positionController=e,this.callbacks=new Sa(e),this.advanced=new xa(e),this.context=new Ca(e),this.interactions=new ka(e),this.animations=new Pa(e),this.effects=new Ta(e),this.accessibility=new Ea(e)}moveToElementWithCallback(...e){return this.callbacks.moveToElementWithCallback(...e)}moveToElementSequence(...e){return this.callbacks.moveToElementSequence(...e)}moveToElementWithDelay(...e){return this.callbacks.moveToElementWithDelay(...e)}moveToElementWithCondition(...e){return this.callbacks.moveToElementWithCondition(...e)}moveToElementWithRepeat(...e){return this.callbacks.moveToElementWithRepeat(...e)}moveToElementWithProximity(...e){return this.callbacks.moveToElementWithProximity(...e)}moveToElementWithPath(...e){return this.advanced.moveToElementWithPath(...e)}moveToElementWithEasing(...e){return this.advanced.moveToElementWithEasing(...e)}moveToElementWithCollision(...e){return this.advanced.moveToElementWithCollision(...e)}moveToElementWithAudio(...e){return this.advanced.moveToElementWithAudio(...e)}moveToElementWithGaze(...e){return this.advanced.moveToElementWithGaze(...e)}moveToElementWithScroll(...e){return this.context.moveToElementWithScroll(...e)}moveToElementWithPhysics(...e){return this.context.moveToElementWithPhysics(...e)}moveToElementWithGroup(...e){return this.context.moveToElementWithGroup(...e)}moveToElementWithResponsive(...e){return this.context.moveToElementWithResponsive(...e)}moveToElementWithAccessibility(...e){return this.context.moveToElementWithAccessibility(...e)}moveToElementWithHover(...e){return this.interactions.moveToElementWithHover(...e)}moveToElementWithClick(...e){return this.interactions.moveToElementWithClick(...e)}moveToElementWithTouch(...e){return this.interactions.moveToElementWithTouch(...e)}moveToElementWithFocus(...e){return this.interactions.moveToElementWithFocus(...e)}moveToElementWithKeyboard(...e){return this.interactions.moveToElementWithKeyboard(...e)}moveToElementWithBounce(...e){return this.animations.moveToElementWithBounce(...e)}moveToElementWithShake(...e){return this.animations.moveToElementWithShake(...e)}moveToElementWithPulse(...e){return this.animations.moveToElementWithPulse(...e)}moveToElementWithWiggle(...e){return this.animations.moveToElementWithWiggle(...e)}moveToElementWithCustom(...e){return this.animations.moveToElementWithCustom(...e)}moveToElementWithTrail(...e){return this.effects.moveToElementWithTrail(...e)}moveToElementWithParticles(...e){return this.effects.moveToElementWithParticles(...e)}moveToElementWithGlow(...e){return this.effects.moveToElementWithGlow(...e)}moveToElementWithScreenReader(...e){return this.accessibility.moveToElementWithScreenReader(...e)}moveToElementWithKeyboardAccessible(...e){return this.accessibility.moveToElementWithKeyboard(...e)}moveToElementWithHighContrast(...e){return this.accessibility.moveToElementWithHighContrast(...e)}moveToElementWithReducedMotion(...e){return this.accessibility.moveToElementWithReducedMotion(...e)}moveToElementWithFocusAccessible(...e){return this.accessibility.moveToElementWithFocus(...e)}announceToScreenReader(...e){return this.accessibility.announceToScreenReader(...e)}navigateFocus(...e){return this.accessibility.navigateFocus(...e)}enableAccessibility(...e){return this.accessibility.enableAccessibility(...e)}disableAccessibility(...e){return this.accessibility.disableAccessibility(...e)}destroy(){this.callbacks.destroy(),this.advanced.destroy(),this.context.destroy(),this.interactions.destroy(),this.animations.destroy(),this.effects.destroy(),this.accessibility.destroy()}}class Da{constructor(e){this.positionController=e,this.isTracking=!1,this.trackingCallbacks=new Map,this.audioContext=null,this.audioAnalyser=null,this.audioData=null}moveToMouse(e={x:20,y:20},t={}){const i="mouse-tracking",s=i=>{const s=i.clientX+e.x,n=i.clientY+e.y,a=s-window.innerWidth/2,r=n-window.innerHeight/2;!1!==t.smooth?this.positionController.animateOffset(a,r,0,t.duration||200,"easeOutQuad"):this.positionController.setOffset(a,r,0)};return this.trackingCallbacks.set(i,s),window.addEventListener("mousemove",s),()=>{window.removeEventListener("mousemove",s),this.trackingCallbacks.delete(i)}}moveToTouch(e={x:20,y:20},t={}){const i="touch-tracking",s=i=>{if(i.touches.length>0){const s=i.touches[0],n=s.clientX+e.x,a=s.clientY+e.y,r=n-window.innerWidth/2,o=a-window.innerHeight/2;!1!==t.smooth?this.positionController.animateOffset(r,o,0,t.duration||200,"easeOutQuad"):this.positionController.setOffset(r,o,0)}};return this.trackingCallbacks.set(i,s),window.addEventListener("touchmove",s),()=>{window.removeEventListener("touchmove",s),this.trackingCallbacks.delete(i)}}moveToAudio(e=0,t=50,i={}){if(this.audioContext||this.initAudioContext(),!this.audioContext||!this.audioAnalyser)return void console.warn("Audio context not available");const s="audio-tracking",n=()=>{if(!this.isTracking)return;this.audioAnalyser.getByteFrequencyData(this.audioData);let e=0;for(let t=0;t<this.audioData.length;t++)e+=this.audioData[t];const s=e/this.audioData.length/255*t,a=(i.centerX||0)+s,r=(i.centerY||0)+.5*s,o=a-window.innerWidth/2,l=r-window.innerHeight/2;this.positionController.setOffset(o,l,0),this.isTracking&&requestAnimationFrame(n)};return this.trackingCallbacks.set(s,n),this.isTracking=!0,n(),()=>{this.isTracking=!1,this.trackingCallbacks.delete(s)}}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256,this.audioData=new Uint8Array(this.audioAnalyser.frequencyBinCount)}catch(e){console.warn("Failed to initialize audio context:",e)}}connectAudioSource(e){this.audioContext&&this.audioAnalyser||this.initAudioContext(),this.audioContext&&this.audioAnalyser&&this.audioContext.createMediaStreamSource(e).connect(this.audioAnalyser)}moveToViewport(e="right",t={x:20,y:20}){let i,s;switch(e){case"top":i=window.innerWidth/2,s=t.y;break;case"bottom":i=window.innerWidth/2,s=window.innerHeight-t.y;break;case"left":i=t.x,s=window.innerHeight/2;break;case"right":default:i=window.innerWidth-t.x,s=window.innerHeight/2;break;case"top-left":i=t.x,s=t.y;break;case"top-right":i=window.innerWidth-t.x,s=t.y;break;case"bottom-left":i=t.x,s=window.innerHeight-t.y;break;case"bottom-right":i=window.innerWidth-t.x,s=window.innerHeight-t.y}const n=i-window.innerWidth/2,a=s-window.innerHeight/2;this.positionController.setOffset(n,a,0)}stopAllTracking(){this.trackingCallbacks.forEach((e,t)=>{"mouse-tracking"===t?window.removeEventListener("mousemove",e):"touch-tracking"===t&&window.removeEventListener("touchmove",e)}),this.trackingCallbacks.clear(),this.isTracking=!1}destroy(){this.stopAllTracking(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.positionController=null}}class _a{constructor(e){this.positionController=e,this.isRunning=!1,this.physicsCallbacks=new Map,this.velocity={x:0,y:0},this.acceleration={x:0,y:0},this.lastTime=0}moveToGrid(e,t,i={x:0,y:0},s={}){const n=s.gridSize||100,a=e*n+i.x,r=t*n+i.y,o=a-window.innerWidth/2,l=r-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(o,l,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(o,l,0)}moveToGravity(e={x:0,y:0},t=.1,i={}){const s="gravity",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y,o=e.x-n,l=e.y-r,h=Math.sqrt(o*o+l*l);if(h>0){const e=t/(h*h);this.acceleration.x=o/h*e,this.acceleration.y=l/h*e,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const s=i.damping||.98;this.velocity.x*=s,this.velocity.y*=s;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToMagnetic(e=[],t=.05,i={}){const s="magnetic",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y;let o=0,l=0;e.forEach(e=>{let i,s;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();i=e.left+e.width/2-window.innerWidth/2,s=e.top+e.height/2-window.innerHeight/2}}else{if(void 0===e.x||void 0===e.y)return;i=e.x-window.innerWidth/2,s=e.y-window.innerHeight/2}const a=i-n,h=s-r,c=Math.sqrt(a*a+h*h);if(c>0){const e=t/(c*c);o+=a/c*e,l+=h/c*e}}),this.acceleration.x=o,this.acceleration.y=l,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const h=i.damping||.95;this.velocity.x*=h,this.velocity.y*=h;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToAvoid(e=[],t=100,i={}){const s="avoid",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y;let o=0,l=0;e.forEach(e=>{let i,s;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();i=e.left+e.width/2-window.innerWidth/2,s=e.top+e.height/2-window.innerHeight/2}}else{if(void 0===e.x||void 0===e.y)return;i=e.x-window.innerWidth/2,s=e.y-window.innerHeight/2}const a=n-i,h=r-s,c=Math.sqrt(a*a+h*h);if(c<t&&c>0){const e=(t-c)/t;o+=a/c*e,l+=h/c*e}}),this.acceleration.x=o,this.acceleration.y=l,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const h=i.damping||.9;this.velocity.x*=h,this.velocity.y*=h;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToRandom(e={x:0,y:0,width:400,height:400},t=3e3,i={}){const s="random",n=()=>{if(!this.isRunning)return;const s=e.x+Math.random()*e.width,a=e.y+Math.random()*e.height,r=s-window.innerWidth/2,o=a-window.innerHeight/2;!1!==i.animate?this.positionController.animateOffset(r,o,0,i.duration||1e3,i.easing||"easeOutCubic"):this.positionController.setOffset(r,o,0),this.isRunning&&setTimeout(n,t)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}stopAllPhysics(){this.isRunning=!1,this.physicsCallbacks.clear(),this.velocity={x:0,y:0},this.acceleration={x:0,y:0}}destroy(){this.stopAllPhysics(),this.positionController=null}}class Ia{constructor(e){this.positionController=e,this.isRunning=!1,this.animationCallbacks=new Map,this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}moveToPath(e=[],t=1,i={}){if(e.length<2)return void console.warn("Path requires at least 2 points");const s="path",n=!1!==i.loop,a=i.reverse||!1,r=o=>{if(!this.isRunning)return;const l=o-(this.lastTime||o);if(this.lastTime=o,l>0){this.pathProgress+=t*l/1e3,this.pathProgress=n?this.pathProgress%e.length:Math.min(this.pathProgress,e.length-1);const r=Math.floor(this.pathProgress),o=this.pathProgress-r;let h,c;a?(h=e[e.length-1-r],c=e[e.length-2-r]||e[0]):(h=e[r],c=e[r+1]||e[0]);const u=h.x+(c.x-h.x)*o,d=h.y+(c.y-h.y)*o,g=u-window.innerWidth/2,m=d-window.innerHeight/2;if(this.positionController.setOffset(g,m,0),!n&&this.pathProgress>=e.length-1)return this.isRunning=!1,this.animationCallbacks.delete(s),void(i.onComplete&&i.onComplete())}this.isRunning&&requestAnimationFrame(r)};return this.animationCallbacks.set(s,r),this.isRunning=!0,this.lastTime=performance.now(),r(this.lastTime),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToTime(e=2e3,t="easeInOutCubic",i={}){const s="time",n=performance.now(),a=this.positionController.getOffset(),r=i.target||{x:0,y:0},o=l=>{if(!this.isRunning)return;const h=l-n,c=Math.min(h/e,1),u=this.applyEasing(c,t),d=a.x+(r.x-a.x)*u,g=a.y+(r.y-a.y)*u;this.positionController.setOffset(d,g,0),c>=1?(this.isRunning=!1,this.animationCallbacks.delete(s),i.onComplete&&i.onComplete()):requestAnimationFrame(o)};return this.animationCallbacks.set(s,o),this.isRunning=!0,o(n),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToScroll(e=0,t={x:0,y:0},i={}){const s="scroll",n=()=>{if(!this.isRunning)return;const s=window.innerWidth,n=window.innerHeight;let a,r;if("horizontal"===i.direction)a=e*s+t.x,r=n/2+t.y;else if("vertical"===i.direction)a=s/2+t.x,r=e*n+t.y;else{const o=e*Math.PI*2,l=i.radius||Math.min(s,n)/4;a=s/2+Math.cos(o)*l+t.x,r=n/2+Math.sin(o)*l+t.y}const o=a-s/2,l=r-n/2;this.positionController.setOffset(o,l,0)};return this.animationCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}animateTo(e,t,i=1e3,s="easeOutCubic"){this.positionController.animateOffset(e,t,0,i,s)}applyEasing(e,t){switch(t){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return 1-(1-e)*(1-e);case"easeInOutQuad":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"easeInCubic":return e*e*e;case"easeOutCubic":return 1-Math.pow(1-e,3);case"easeInOutCubic":return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;case"easeInBack":{const t=1.70158;return(t+1)*e*e*e-t*e*e}case"easeOutBack":{const t=1.70158;return 1+(t+1)*Math.pow(e-1,3)+t*Math.pow(e-1,2)}case"easeInElastic":return 0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*(2*Math.PI/3));case"easeOutElastic":return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((10*e-.75)*(2*Math.PI/3))+1}}stopAllAnimations(){this.isRunning=!1,this.animationCallbacks.clear(),this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}destroy(){this.stopAllAnimations(),this.positionController=null}}class Ra{constructor(e){this.positionController=e,this.breakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.responsiveCallbacks=new Map}getCurrentBreakpoint(){const e=window.innerWidth;return e<this.breakpoints.mobile?"mobile":e<this.breakpoints.tablet?"tablet":e<this.breakpoints.desktop?"desktop":"large"}moveToResponsive(e={},t={}){const i="responsive",s=()=>{if(!this.isRunning)return;const i=this.getCurrentBreakpoint(),s=e[i]||e.default||{x:0,y:0},n=s.x-window.innerWidth/2,a=s.y-window.innerHeight/2;!1!==t.animate?this.positionController.animateOffset(n,a,0,t.duration||500,t.easing||"easeOutCubic"):this.positionController.setOffset(n,a,0)};this.responsiveCallbacks.set(i,s),this.isRunning=!0,s();const n=()=>{const e=this.getCurrentBreakpoint();e!==this.currentBreakpoint&&(this.currentBreakpoint=e,s())};return window.addEventListener("resize",n),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(i),window.removeEventListener("resize",n)}}moveToGroup(e=[],t="center",i={x:0,y:0}){if(0===e.length)return;let s=0,n=0,a=0,r=0,o=0;if(e.forEach(e=>{let t,i,l,h;if("string"==typeof e){const s=document.querySelector(e);if(!s)return;{const e=s.getBoundingClientRect();t=e.left,i=e.top,l=e.width,h=e.height}}else{if(void 0===e.x||void 0===e.y)return;t=e.x,i=e.y,l=e.width||0,h=e.height||0}s+=t,n+=i,a=Math.max(a,t+l),r=Math.max(r,i+h),o++}),0===o)return;const l=s/o,h=n/o;let c,u;switch(t){case"center":default:c=l+i.x,u=h+i.y;break;case"left":c=s+i.x,u=h+i.y;break;case"right":c=a+i.x,u=h+i.y;break;case"top":c=l+i.x,u=n+i.y;break;case"bottom":c=l+i.x,u=r+i.y}const d=c-window.innerWidth/2,g=u-window.innerHeight/2;this.positionController.setOffset(d,g,0)}moveToAccessibility(e=[],t="bottom-right",i={}){const s="accessibility",n=()=>{if(!this.isRunning)return;let s,n;switch((window.speechSynthesis||window.webkitSpeechSynthesis)&&i.announce&&e.forEach(e=>{e.condition&&e.condition()&&this.announceToScreenReader(e.text)}),t){case"bottom-right":default:s=window.innerWidth-100,n=window.innerHeight-100;break;case"bottom-left":s=100,n=window.innerHeight-100;break;case"top-right":s=window.innerWidth-100,n=100;break;case"top-left":s=100,n=100;break;case"center":s=window.innerWidth/2,n=window.innerHeight/2}const a=s-window.innerWidth/2,r=n-window.innerHeight/2;this.positionController.setOffset(a,r,0)};return this.responsiveCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(s)}}announceToScreenReader(e){if(window.speechSynthesis){const t=new SpeechSynthesisUtterance(e);t.volume=.5,t.rate=.8,window.speechSynthesis.speak(t)}}setBreakpoints(e){this.breakpoints={...this.breakpoints,...e},this.currentBreakpoint=this.getCurrentBreakpoint()}getCurrentBreakpointName(){return this.currentBreakpoint}isBreakpoint(e){return this.currentBreakpoint===e}stopAllResponsive(){this.isRunning=!1,this.responsiveCallbacks.clear()}destroy(){this.stopAllResponsive(),this.positionController=null}}class Ba{constructor(e){this.positionController=e,this.elementTargeting=new wa(e),this.inputTracking=new Da(e),this.physics=new _a(e),this.animation=new Ia(e),this.responsive=new Ra(e),this.methods=new Map,this.registerMethods()}registerMethods(){this.methods.set("moveToElement",this.elementTargeting.moveToElement.bind(this.elementTargeting)),this.methods.set("moveToButton",this.elementTargeting.moveToButton.bind(this.elementTargeting)),this.methods.set("moveToForm",this.elementTargeting.moveToForm.bind(this.elementTargeting)),this.methods.set("moveToModal",this.elementTargeting.moveToModal.bind(this.elementTargeting)),this.methods.set("moveToNavigation",this.elementTargeting.moveToNavigation.bind(this.elementTargeting)),this.methods.set("moveToContent",this.elementTargeting.moveToContent.bind(this.elementTargeting)),this.methods.set("moveToSidebar",this.elementTargeting.moveToSidebar.bind(this.elementTargeting)),this.methods.set("moveToHeader",this.elementTargeting.moveToHeader.bind(this.elementTargeting)),this.methods.set("moveToFooter",this.elementTargeting.moveToFooter.bind(this.elementTargeting)),this.methods.set("watchElement",this.elementTargeting.watchElement.bind(this.elementTargeting)),this.methods.set("moveToMouse",this.inputTracking.moveToMouse.bind(this.inputTracking)),this.methods.set("moveToTouch",this.inputTracking.moveToTouch.bind(this.inputTracking)),this.methods.set("moveToAudio",this.inputTracking.moveToAudio.bind(this.inputTracking)),this.methods.set("moveToViewport",this.inputTracking.moveToViewport.bind(this.inputTracking)),this.methods.set("moveToGrid",this.physics.moveToGrid.bind(this.physics)),this.methods.set("moveToGravity",this.physics.moveToGravity.bind(this.physics)),this.methods.set("moveToMagnetic",this.physics.moveToMagnetic.bind(this.physics)),this.methods.set("moveToAvoid",this.physics.moveToAvoid.bind(this.physics)),this.methods.set("moveToRandom",this.physics.moveToRandom.bind(this.physics)),this.methods.set("moveToPath",this.animation.moveToPath.bind(this.animation)),this.methods.set("moveToTime",this.animation.moveToTime.bind(this.animation)),this.methods.set("moveToScroll",this.animation.moveToScroll.bind(this.animation)),this.methods.set("animateTo",this.animation.animateTo.bind(this.animation)),this.methods.set("moveToResponsive",this.responsive.moveToResponsive.bind(this.responsive)),this.methods.set("moveToGroup",this.responsive.moveToGroup.bind(this.responsive)),this.methods.set("moveToAccessibility",this.responsive.moveToAccessibility.bind(this.responsive))}call(e,...t){const i=this.methods.get(e);return i?i(...t):(console.warn(`Positioning method not found: ${e}`),null)}getAvailableMethods(){return Array.from(this.methods.keys())}hasMethod(e){return this.methods.has(e)}stopAll(){this.elementTargeting.stopWatchingAll(),this.inputTracking.stopAllTracking(),this.physics.stopAllPhysics(),this.animation.stopAllAnimations(),this.responsive.stopAllResponsive()}destroy(){this.stopAll(),this.elementTargeting.destroy(),this.inputTracking.destroy(),this.physics.destroy(),this.animation.destroy(),this.responsive.destroy(),this.methods.clear(),this.positionController=null}}class za{constructor(e={}){this.offsetX=e.offsetX||0,this.offsetY=e.offsetY||0,this.offsetZ=e.offsetZ||0,this.isAnimating=!1,this.animationId=null,this.animationStartTime=0,this.animationDuration=0,this.animationEasing="easeOutCubic",this.startOffset={x:0,y:0,z:0},this.targetOffset={x:0,y:0,z:0},this.onUpdate=e.onUpdate||(()=>{}),this.onAnimationComplete=e.onAnimationComplete||(()=>{}),this.minScale=e.minScale||.5,this.maxScale=e.maxScale||2,this.zScaleRange=e.zScaleRange||1e3,this.globalScale=1,this.coreScaleOverride=1,this.particleScaleOverride=1,this.positioning=new Ba(this),this.elementTargeting=new Aa(this)}setOffset(e,t,i=0){this.stopAnimation(),this.offsetX=e,this.offsetY=t,this.offsetZ=i,this.onUpdate(this.getEffectiveCenter())}getOffset(){return{x:this.offsetX,y:this.offsetY,z:this.offsetZ}}getPosition(e=window.innerWidth/2,t=window.innerHeight/2){return{x:e+this.offsetX,y:t+this.offsetY,z:this.offsetZ,scale:this.getZScale()}}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){this.stopAnimation(),this.startOffset={x:this.offsetX,y:this.offsetY,z:this.offsetZ},this.targetOffset={x:e,y:t,z:i},this.animationDuration=s,this.animationEasing=n,this.animationStartTime=performance.now(),this.isAnimating=!0,this.startAnimation()}stopAnimation(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isAnimating=!1}startAnimation(){const e=t=>{if(!this.isAnimating)return;const i=t-this.animationStartTime,s=Math.min(i/this.animationDuration,1),n=this.applyEasing(s,this.animationEasing);this.offsetX=this.lerp(this.startOffset.x,this.targetOffset.x,n),this.offsetY=this.lerp(this.startOffset.y,this.targetOffset.y,n),this.offsetZ=this.lerp(this.startOffset.z,this.targetOffset.z,n),this.onUpdate(this.getEffectiveCenter()),s>=1?(this.isAnimating=!1,this.onAnimationComplete()):this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getEffectiveCenter(e=0,t=0){return{x:e+this.offsetX,y:t+this.offsetY,scale:this.getZScale(),coreScale:this.getCoreScale(),particleScale:this.getParticleScale()}}getZScale(){const e=-this.offsetZ/this.zScaleRange,t=Math.max(-1,Math.min(1,e));return this.lerp(this.minScale,this.maxScale,(t+1)/2)*this.globalScale}setGlobalScale(e){this.globalScale=Math.max(.1,e),this.onUpdate(this.getEffectiveCenter())}setScaleOverrides(e){"number"==typeof e?(this.globalScale=Math.max(.1,e),this.coreScaleOverride=1,this.particleScaleOverride=1):(void 0!==e.global&&(this.globalScale=Math.max(.1,e.global)),void 0!==e.core&&(this.coreScaleOverride=Math.max(.1,e.core)),void 0!==e.particles&&(this.particleScaleOverride=Math.max(.1,e.particles))),this.onUpdate(this.getEffectiveCenter())}getCoreScale(){return this.calculateBaseZScale()*this.globalScale*this.coreScaleOverride}getParticleScale(){return this.calculateBaseZScale()*this.globalScale*this.particleScaleOverride}calculateBaseZScale(){const e=-this.offsetZ/this.zScaleRange,t=Math.max(-1,Math.min(1,e));return this.lerp(this.minScale,this.maxScale,(t+1)/2)}lerp(e,t,i){return e+(t-e)*i}applyEasing(e,t){switch(t){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return 1-(1-e)*(1-e);case"easeInOutQuad":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"easeInCubic":return e*e*e;case"easeOutCubic":return 1-Math.pow(1-e,3);case"easeInOutCubic":return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;case"easeInBack":{const t=1.70158;return(t+1)*e*e*e-t*e*e}case"easeOutBack":{const t=1.70158;return 1+(t+1)*Math.pow(e-1,3)+t*Math.pow(e-1,2)}}}getPositioning(){return this.positioning}getElementTargeting(){return this.elementTargeting}callPositioning(e,...t){return this.positioning.call(e,...t)}destroy(){this.stopAnimation(),this.positioning&&(this.positioning.destroy(),this.positioning=null),this.elementTargeting&&(this.elementTargeting.destroy(),this.elementTargeting=null),this.onUpdate=null,this.onAnimationComplete=null}}class Fa{static _getGestureSoundsMap(){return Fa._GESTURE_SOUNDS_CACHE||(Fa._GESTURE_SOUNDS_CACHE=new Map([["bounce",{duration:100,waveform:"triangle",volume:.3,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:400},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:1},{time:.1,volume:.8},{time:1,volume:0}]}],["pulse",{duration:300,waveform:"sine",volume:.25,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:450},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:1},{time:.7,volume:1},{time:1,volume:0}]}],["shake",{duration:200,waveform:"sawtooth",volume:.2,frequencyEnvelope:[{time:0,frequency:150},{time:.25,frequency:200},{time:.5,frequency:150},{time:.75,frequency:200},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:.8},{time:.5,volume:1},{time:1,volume:0}]}],["spin",{duration:800,waveform:"sine",volume:.18,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:600},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:.5},{time:.5,volume:1},{time:1,volume:0}]}],["breathe",{duration:1500,waveform:"sine",volume:.12,frequencyEnvelope:[{time:0,frequency:150},{time:.5,frequency:180},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:.7},{time:.7,volume:.7},{time:1,volume:0}]}],["morph",{duration:600,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:.3,frequency:400},{time:.7,frequency:300},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:1},{time:.8,volume:.8},{time:1,volume:0}]}],["float",{duration:2e3,waveform:"sine",volume:.15,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.6},{time:.8,volume:.6},{time:1,volume:0}]}],["wobble",{duration:400,waveform:"square",volume:.2,frequencyEnvelope:[{time:0,frequency:180},{time:.25,frequency:220},{time:.5,frequency:180},{time:.75,frequency:220},{time:1,frequency:180}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["wave",{duration:1200,waveform:"sine",volume:.22,frequencyEnvelope:[{time:0,frequency:200},{time:.25,frequency:400},{time:.5,frequency:250},{time:.75,frequency:450},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:1},{time:.8,volume:.9},{time:1,volume:0}]}],["pop",{duration:80,waveform:"triangle",volume:.4,frequencyEnvelope:[{time:0,frequency:500},{time:.3,frequency:300},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:1},{time:.2,volume:.6},{time:1,volume:0}]}],["shimmer",{duration:1e3,waveform:"sine",volume:.16,frequencyEnvelope:[{time:0,frequency:600},{time:.2,frequency:700},{time:.4,frequency:650},{time:.6,frequency:750},{time:.8,frequency:700},{time:1,frequency:600}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.8},{time:.8,volume:.8},{time:1,volume:0}]}],["glitch",{duration:250,waveform:"square",volume:.25,frequencyEnvelope:[{time:0,frequency:100},{time:.2,frequency:800},{time:.4,frequency:200},{time:.6,frequency:600},{time:.8,frequency:300},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:.8},{time:.5,volume:1},{time:1,volume:0}]}],["reach",{duration:500,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:1,frequency:450}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["shrink",{duration:600,waveform:"sine",volume:.18,frequencyEnvelope:[{time:0,frequency:400},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:.9},{time:.5,volume:.6},{time:1,volume:0}]}],["grow",{duration:700,waveform:"sine",volume:.22,frequencyEnvelope:[{time:0,frequency:150},{time:1,frequency:500}],volumeEnvelope:[{time:0,volume:.5},{time:.5,volume:.9},{time:1,volume:0}]}],["drift",{duration:1500,waveform:"sine",volume:.14,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:280},{time:1,frequency:220}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:.7},{time:.7,volume:.6},{time:1,volume:0}]}],["zoom",{duration:400,waveform:"triangle",volume:.28,frequencyEnvelope:[{time:0,frequency:200},{time:1,frequency:800}],volumeEnvelope:[{time:0,volume:.6},{time:.5,volume:1},{time:1,volume:0}]}],["squish",{duration:300,waveform:"sawtooth",volume:.24,frequencyEnvelope:[{time:0,frequency:350},{time:.5,frequency:120},{time:1,frequency:180}],volumeEnvelope:[{time:0,volume:.9},{time:.3,volume:1},{time:1,volume:0}]}],["stretch",{duration:800,waveform:"sine",volume:.19,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:.6},{time:.4,volume:1},{time:1,volume:0}]}],["snap",{duration:100,waveform:"square",volume:.35,frequencyEnvelope:[{time:0,frequency:600},{time:.5,frequency:300},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:1},{time:.3,volume:.5},{time:1,volume:0}]}],["ripple",{duration:1e3,waveform:"sine",volume:.17,frequencyEnvelope:[{time:0,frequency:300},{time:.25,frequency:350},{time:.5,frequency:300},{time:.75,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:.8},{time:.2,volume:1},{time:.8,volume:.7},{time:1,volume:0}]}],["swirl",{duration:1200,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:.33,frequency:400},{time:.66,frequency:300},{time:1,frequency:500}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.9},{time:.8,volume:.8},{time:1,volume:0}]}],["explode",{duration:600,waveform:"sawtooth",volume:.3,frequencyEnvelope:[{time:0,frequency:100},{time:.2,frequency:800},{time:1,frequency:50}],volumeEnvelope:[{time:0,volume:1},{time:.3,volume:.8},{time:1,volume:0}]}],["implode",{duration:700,waveform:"sine",volume:.25,frequencyEnvelope:[{time:0,frequency:500},{time:.5,frequency:200},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:.9},{time:.5,volume:1},{time:1,volume:0}]}],["flutter",{duration:800,waveform:"triangle",volume:.18,frequencyEnvelope:[{time:0,frequency:400},{time:.2,frequency:450},{time:.4,frequency:400},{time:.6,frequency:450},{time:.8,frequency:400},{time:1,frequency:450}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.8},{time:.8,volume:.7},{time:1,volume:0}]}],["twist",{duration:500,waveform:"sawtooth",volume:.21,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:400},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["blink",{duration:150,waveform:"sine",volume:.15,frequencyEnvelope:[{time:0,frequency:400},{time:.5,frequency:500},{time:1,frequency:400}],volumeEnvelope:[{time:0,volume:0},{time:.5,volume:1},{time:1,volume:0}]}],["glow",{duration:1500,waveform:"sine",volume:.12,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:400},{time:1,frequency:350}],volumeEnvelope:[{time:0,volume:0},{time:.4,volume:.8},{time:.6,volume:.8},{time:1,volume:0}]}],["sparkle",{duration:600,waveform:"sine",volume:.2,frequencyEnvelope:[{time:0,frequency:800},{time:.3,frequency:1e3},{time:.6,frequency:900},{time:1,frequency:700}],volumeEnvelope:[{time:0,volume:.6},{time:.2,frequency:1},{time:.8,volume:.9},{time:1,volume:0}]}]])),Fa._GESTURE_SOUNDS_CACHE}static getSoundConfig(e){return Fa._getGestureSoundsMap().get(e)||null}}class Oa{constructor(e){this._ctx=e,this._layers=new Map,this._masterGain=e.createGain(),this._masterGain.connect(e.destination),this._currentMix={},this._crossfadeId=0,this._isPlaying=!1,this._playOffset=0,this._playStartTime=0,this._emotionMod=null,this._baseBPM=null}async addLayer(e,t){let i;try{if(t.src instanceof ArrayBuffer)i=await this._ctx.decodeAudioData(t.src);else if(t.src instanceof Blob){const e=await t.src.arrayBuffer();i=await this._ctx.decodeAudioData(e)}else if("string"==typeof t.src){const s=await fetch(t.src);if(!s.ok)return void console.warn(`AudioLayerManager: failed to fetch layer "${e}" from "${t.src}" โ HTTP ${s.status}`);const n=await s.arrayBuffer();i=await this._ctx.decodeAudioData(n)}}catch(t){return void console.warn(`AudioLayerManager: failed to load layer "${e}" โ`,t.message||t)}if(!i)return void console.warn(`AudioLayerManager: no audio buffer produced for layer "${e}" โ skipping.`);const s=this._ctx.createGain(),n=t.gain??0;s.gain.setValueAtTime(n,this._ctx.currentTime),s.connect(this._masterGain),this._layers.set(e,{buffer:i,gainNode:s,sourceNode:null,loop:t.loop??!0,baseGain:n}),this._currentMix[e]=n}removeLayer(e){const t=this._layers.get(e);if(t){if(t.sourceNode)try{t.sourceNode.stop()}catch{}t.gainNode.disconnect(),this._layers.delete(e),delete this._currentMix[e]}}play(e=0){this._isPlaying&&this.stop();const t=e/1e3;this._playOffset=t,this._playStartTime=this._ctx.currentTime,this._isPlaying=!0;for(const[,e]of this._layers){const i=this._ctx.createBufferSource();i.buffer=e.buffer,i.loop=e.loop,i.connect(e.gainNode),i.start(0,t),e.sourceNode=i}}pause(){this._isPlaying&&(this._playOffset+=this._ctx.currentTime-this._playStartTime,this._stopAllSources(),this._isPlaying=!1)}stop(){this._stopAllSources(),this._isPlaying=!1,this._playOffset=0}_stopAllSources(){for(const[,e]of this._layers)if(e.sourceNode){try{e.sourceNode.stop()}catch{}e.sourceNode=null}}setMix(e){const t=this._ctx.currentTime;for(const[i,s]of Object.entries(e)){const e=this._layers.get(i);e&&(e.gainNode.gain.setValueAtTime(Math.max(0,Math.min(1,s)),t),this._currentMix[i]=s)}}crossfadeTo(e,t=1e3){++this._crossfadeId;const i=this._ctx.currentTime,s=t/1e3;for(const[t,n]of Object.entries(e)){const e=this._layers.get(t);if(e){const a=Math.max(1e-4,Math.min(1,n));e.gainNode.gain.setValueAtTime(e.gainNode.gain.value||1e-4,i),e.gainNode.gain.linearRampToValueAtTime(a,i+s),this._currentMix[t]=n}}return new Promise(e=>{setTimeout(()=>{this._crossfadeId,e()},t)})}setEmotionModulation(e){this._emotionMod=e}applyEmotionState(e){if(!this._emotionMod||!e?.dominant)return;const t={},i=this._emotionMod[e.dominant.emotion];if(i)for(const[s,n]of Object.entries(i))t[s]=(t[s]||0)+n*e.dominant.intensity;for(const i of e.undercurrents||[]){const e=this._emotionMod[i.emotion];if(e)for(const[s,n]of Object.entries(e))t[s]=(t[s]||0)+n*i.intensity*.25}const s={...this._currentMix};for(const[e,i]of Object.entries(t))e in s&&(s[e]=Math.max(0,Math.min(1,s[e]+i)));this.setMix(s)}syncToBPM(e,t){if(t&&(this._baseBPM=t),!this._baseBPM)return;const i=e/this._baseBPM;for(const[,e]of this._layers)e.sourceNode&&(e.sourceNode.playbackRate.value=i)}setMasterVolume(e){this._masterGain.gain.setValueAtTime(Math.max(0,Math.min(1,e)),this._ctx.currentTime)}getLayerNames(){return[...this._layers.keys()]}getCurrentMix(){return{...this._currentMix}}isPlaying(){return this._isPlaying}destroy(){this.stop();for(const[,e]of this._layers)e.gainNode.disconnect();this._layers.clear(),this._masterGain.disconnect()}}class La{constructor(){this.context=null,this.isEnabled=!1,this.isInitialized=!1,this.nodes={master:null,ambient:null,effects:null},this.warningTimestamps={},this.warningThrottle=5e3,this.maxWarningKeys=50,this.warningAccessOrder=[],this.currentOscillator=null,this.currentGain=null,this.masterVolume=.5,this.ambientVolume=.1,this.emotionalTones=new Map([["neutral",{frequency:220,waveform:"sine",volume:.1}],["joy",{frequency:440,waveform:"triangle",volume:.15}],["sadness",{frequency:165,waveform:"sine",volume:.08}],["anger",{frequency:330,waveform:"sawtooth",volume:.12}],["fear",{frequency:880,waveform:"square",volume:.09}],["surprise",{frequency:660,waveform:"triangle",volume:.13}],["disgust",{frequency:110,waveform:"sawtooth",volume:.07}],["love",{frequency:528,waveform:"sine",volume:.11}]]),this.emotionalModifiers=new Map([["neutral",{intensity:1,speed:1}],["joy",{intensity:1.3,speed:1.2}],["sadness",{intensity:.6,speed:.8}],["anger",{intensity:1.5,speed:1.4}],["fear",{intensity:.8,speed:1.3}],["surprise",{intensity:1.4,speed:1.5}],["disgust",{intensity:.7,speed:.9}],["love",{intensity:1.1,speed:.9}]])}initialize(){try{const e=window.AudioContext||window.webkitAudioContext;return!!e&&(this.context=new e,this.context.state,this.nodes.master=this.context.createGain(),this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),this.nodes.master.connect(this.context.destination),this.nodes.effects=this.context.createGain(),this.nodes.effects.gain.setValueAtTime(1,this.context.currentTime),this.nodes.effects.connect(this.nodes.master),this.isEnabled=!0,this.isInitialized=!0,!0)}catch{return this.isEnabled=!1,!1}}async resumeContext(){if(this.context&&"suspended"===this.context.state)try{await this.context.resume()}catch{}}setMasterVolume(e,t=null){this.masterVolume=Math.max(0,Math.min(1,e)),this.isEnabled&&this.nodes.master&&(this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),t&&this.updateAmbientVolume(t))}getMasterVolume(){return this.masterVolume}isAvailable(){return this.isEnabled&&this.isInitialized}getAudioLayerManager(){return this.isAvailable()?(this._audioLayerManager||(this._audioLayerManager=new Oa(this.context)),this._audioLayerManager):null}cleanup(){try{this.currentOscillator&&(this.currentOscillator.stop(),this.currentOscillator=null),this.currentGain&&(this.currentGain=null),this.context&&"closed"!==this.context.state&&this.context.close()}catch{}finally{this._audioLayerManager&&(this._audioLayerManager.destroy(),this._audioLayerManager=null),this.context=null,this.nodes={master:null,ambient:null,effects:null},this.currentOscillator=null,this.currentGain=null,this.isEnabled=!1,this.isInitialized=!1}}getEmotionalTone(e){return this.emotionalTones.get(e)||null}setAmbientTone(e,t=500){if(!this.isAvailable())return;const i=this.getEmotionalTone(e);if(i)try{this.resumeContext();const{currentTime:e}=this.context,s=t/1e3;this.currentOscillator&&this.currentGain&&(this.currentGain.gain.exponentialRampToValueAtTime(.001,e+.5*s),this.currentOscillator.stop(e+.5*s));const n=this.context.createOscillator(),a=this.context.createGain();n.type=i.waveform,n.frequency.setValueAtTime(i.frequency,e);const r=i.volume*this.masterVolume;a.gain.setValueAtTime(.001,e),a.gain.exponentialRampToValueAtTime(r,e+s),n.connect(a),a.connect(this.nodes.master),n.start(e),this.currentOscillator=n,this.currentGain=a}catch{}}stopAmbientTone(e=500){if(this.isAvailable()&&this.currentOscillator)try{const{currentTime:t}=this.context,i=e/1e3;this.currentGain&&this.currentGain.gain.exponentialRampToValueAtTime(.001,t+i),this.currentOscillator.stop(t+i),this.currentOscillator=null,this.currentGain=null}catch{}}updateAmbientVolume(e){if(!this.isAvailable()||!this.currentGain||!e)return;const t=this.getEmotionalTone(e);if(t)try{const e=t.volume*this.masterVolume,{currentTime:i}=this.context;this.currentGain.gain.exponentialRampToValueAtTime(e,i+.1)}catch{}}playGestureSound(e,t="neutral"){if(!this.isAvailable())return;const i=this.getGestureSoundConfig(e);if(i)try{this.resumeContext();const{currentTime:e}=this.context,s=i.duration/1e3,n=this.getEmotionalModifiers(t),a=i.volume*this.masterVolume*n.intensity,r=this.context.createOscillator(),o=this.context.createGain();r.type=i.waveform,this.applyFrequencyEnvelope(r,i.frequencyEnvelope,e,s),this.applyVolumeEnvelope(o,i.volumeEnvelope,e,s,a),r.connect(o),o.connect(this.nodes.effects),r.start(e),r.stop(e+s)}catch{}else this.throttledWarn(`Unknown gesture "${e}", cannot play sound`,`gesture_${e}`)}getGestureSoundConfig(e){return Fa.getSoundConfig(e)}applyFrequencyEnvelope(e,t,i,s){t.forEach(t=>{const n=i+t.time*s;e.frequency.linearRampToValueAtTime(t.frequency,n)})}applyVolumeEnvelope(e,t,i,s,n){t.forEach((t,a)=>{const r=i+t.time*s,o=t.volume*n;0===a?e.gain.setValueAtTime(o,r):e.gain.linearRampToValueAtTime(o,r)})}getEmotionalModifiers(e){return this.emotionalModifiers.get(e)||this.emotionalModifiers.get("neutral")}setQualityReduction(e){this.qualityReduction=e,e&&this.audioContext?(this.audioContext.sampleRate,this.maxOscillators=2):this.maxOscillators=4}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}throttledWarn(e,t){const i=Date.now();if(i-(this.warningTimestamps[t]||0)>this.warningThrottle){if(Object.keys(this.warningTimestamps).length>=this.maxWarningKeys){const e=this.warningAccessOrder.shift();delete this.warningTimestamps[e]}this.warningTimestamps[t]=i;const e=this.warningAccessOrder.indexOf(t);-1!==e&&this.warningAccessOrder.splice(e,1),this.warningAccessOrder.push(t)}}}class qa{constructor(){this._maxTimestamps=120,this._timestamps=new Float64Array(this._maxTimestamps),this._tsWriteIndex=0,this._tsCount=0,this.fps=0,this.smoothedFPS=0,this.smoothingFactor=.9,this.lastFrameTime=0,this.frameTime=0,this.maxFrameTimeSamples=10,this._frameTimes=new Float64Array(this.maxFrameTimeSamples),this._ftWriteIndex=0,this._ftCount=0,this.averageFrameTime=0}update(e){this._timestamps[this._tsWriteIndex]=e,this._tsWriteIndex=(this._tsWriteIndex+1)%this._maxTimestamps,this._tsCount<this._maxTimestamps&&this._tsCount++;const t=e-1e3;let i=0;for(let e=0;e<this._tsCount;e++)this._timestamps[e]>t&&i++;if(this.fps=i,0===this.smoothedFPS?this.smoothedFPS=this.fps:this.smoothedFPS=this.smoothedFPS*this.smoothingFactor+this.fps*(1-this.smoothingFactor),this.lastFrameTime>0&&(this.frameTime=e-this.lastFrameTime,this._frameTimes[this._ftWriteIndex]=this.frameTime,this._ftWriteIndex=(this._ftWriteIndex+1)%this.maxFrameTimeSamples,this._ftCount<this.maxFrameTimeSamples&&this._ftCount++,this._ftCount>0)){let e=0;for(let t=0;t<this._ftCount;t++)e+=this._frameTimes[t];this.averageFrameTime=e/this._ftCount}this.lastFrameTime=e}getFPS(){return Math.round(this.fps)}getSmoothedFPS(){return Math.round(this.smoothedFPS)}getFrameTime(){return this.frameTime}getAverageFrameTime(){return this.averageFrameTime}reset(){this._timestamps.fill(0),this._tsWriteIndex=0,this._tsCount=0,this.fps=0,this.smoothedFPS=0,this.lastFrameTime=0,this.frameTime=0,this._frameTimes.fill(0),this._ftWriteIndex=0,this._ftCount=0,this.averageFrameTime=0}getMetrics(){return{fps:this.getFPS(),smoothedFPS:this.getSmoothedFPS(),frameTime:this.getFrameTime(),averageFrameTime:this.getAverageFrameTime(),status:this.fps>=55?"good":this.fps>=30?"okay":"poor"}}}class Ga{constructor(e,t={}){this.errorBoundary=e,this.config=t,this.config.targetFPS=t.targetFPS||60,this.loopManager=t.loopManager||ca,this.isRunning=!1,this.animationFrameId=null,this.loopCallbackId=null,this.lastFrameTime=0,this.deltaTime=0,this.isPaused=!1,this.speedMultiplier=1,this.handleVisibilityChange=this.handleVisibilityChange.bind(this),this.handleWindowBlur=this.handleWindowBlur.bind(this),this.handleWindowFocus=this.handleWindowFocus.bind(this),"undefined"!=typeof document&&(document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("blur",this.handleWindowBlur),window.addEventListener("focus",this.handleWindowFocus)),this.performanceMonitor=null,this.fpsCounter=new qa,this.subsystems={},this.eventCallback=null,this.parentMascot=null}setSubsystems(e){this.subsystems={stateMachine:e.stateMachine,particleSystem:e.particleSystem,renderer:e.renderer,soundSystem:e.soundSystem,canvasManager:e.canvasManager};const t=["stateMachine","particleSystem","renderer"];for(const e of t)if(!this.subsystems[e])throw new Error(`Required subsystem '${e}' not provided`);this.performanceMonitor&&this.performanceMonitor.setSubsystems(this.subsystems)}setEventCallback(e){if("function"!=typeof e)throw new Error("Event callback must be a function");this.eventCallback=e}setParentMascot(e){this.parentMascot=e}emit(e,t=null){this.eventCallback&&this.eventCallback(e,t)}start(){return this.errorBoundary.wrap(()=>{if(this.isRunning)return!1;if(!this.subsystems.stateMachine)throw new Error("Cannot start animation without subsystems configured");return this.isRunning=!0,this.lastFrameTime=performance.now(),this.subsystems.soundSystem&&this.subsystems.soundSystem.isAvailable()&&this.subsystems.soundSystem.resumeContext(),this.loopCallbackId=this.loopManager.register((e,t)=>this.animate(e,t),la.CRITICAL,this),this.emit("animationStarted",{targetFPS:this.targetFPS}),!0},"animation-start")()}stop(){return this.errorBoundary.wrap(()=>!!this.isRunning&&(this.isRunning=!1,this.loopCallbackId&&(this.loopManager.unregister(this.loopCallbackId),this.loopCallbackId=null),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.subsystems.renderer&&this.subsystems.renderer.stopAllGestures&&this.subsystems.renderer.stopAllGestures(),this.subsystems.soundSystem&&this.subsystems.soundSystem.isAvailable()&&this.subsystems.soundSystem.stopAmbientTone(),this.subsystems.particleSystem&&this.subsystems.particleSystem.clear(),this.emit("animationStopped"),!0),"animation-stop")()}handleWindowBlur(){document.hidden||this.handleVisibilityChange()}handleWindowFocus(){!document.hidden&&this.isPaused&&this.handleVisibilityChange()}handleVisibilityChange(){if(document.hidden)this.wasRunning=this.isRunning,this.isPaused=!0,this.pauseTime=performance.now(),this.subsystems?.particleSystem&&(this.subsystems.particleSystem.resetAccumulator(),this.pausedParticleCount=this.subsystems.particleSystem.particles?.length||0),this.subsystems?.renderer?.gestureAnimator&&this.subsystems.renderer.gestureAnimator.pauseCurrentAnimation?.(),this.parentMascot?.pause&&this.parentMascot.pause();else if(this.isPaused&&this.wasRunning){const e=performance.now(),t=e-this.pauseTime;this.lastFrameTime=e,this.frameTimeAccumulator=0,this.fpsCounter&&this.fpsCounter.reset(),this.subsystems?.particleSystem&&this.subsystems.particleSystem.onVisibilityResume(t,this.pausedParticleCount),this.renderer&&(t>tn&&this.renderer.resetCanvasContext(),this.renderer.gestureAnimator&&this.renderer.gestureAnimator.resumeAnimation?.(),t>tn&&(this.renderer.forceCleanRender=!0)),this.subsystems?.stateMachine&&(this.subsystems.stateMachine.lastUpdateTime=e),this.parentMascot?.resume&&this.parentMascot.resume(),this.isPaused=!1}}animate(e,t){if(!this.isRunning||this.isPaused)return;const i=t||performance.now();this.deltaTime=e||i-this.lastFrameTime,this.deltaTime>20&&(this.deltaTime=20),this.deltaTime>en&&this.deltaTime<20&&(this.deltaTime=en),this.lastFrameTime=i,this.deltaTime*=this.speedMultiplier,this.update(this.deltaTime),this.render()}update(e){if(this.subsystems.stateMachine&&this.subsystems.stateMachine.update(e),this.parentMascot?.stateCoordinator?._modifierManager&&this.parentMascot.stateCoordinator._modifierManager.update(e),this.parentMascot&&"function"==typeof this.parentMascot.update&&this.parentMascot.update(e),"classic"!==this.parentMascot?.config?.renderingStyle&&this.subsystems.particleSystem&&this.subsystems.stateMachine&&this.subsystems.canvasManager){const t=this.subsystems.stateMachine.getCurrentEmotionalProperties();let i;i=this.subsystems.renderer&&"function"==typeof this.subsystems.renderer.getEffectiveCenter?this.subsystems.renderer.getEffectiveCenter():this.subsystems.canvasManager.getCenter();let s=null,n=0;if(this.subsystems.renderer&&this.subsystems.renderer.getCurrentGesture){const e=this.subsystems.renderer.getCurrentGesture();e&&e.particleMotion&&(s=e.particleMotion,n=e.progress||0)}this.subsystems.particleSystem.spawn(t.particleBehavior,this.subsystems.stateMachine.getCurrentState().emotion,t.particleRate,i.x,i.y,e),this.subsystems.particleSystem.update(e,i.x,i.y,s,n)}this.performanceMonitor&&this.performanceMonitor.updateMetrics({particleCount:this.subsystems.particleSystem?.getActiveParticleCount?.()||0,audioLatency:this.subsystems.soundSystem?.getLatency?.()||0})}render(){this.parentMascot&&"function"==typeof this.parentMascot.render?this.parentMascot.render():this.subsystems.renderer&&this.subsystems.renderer.render()}getPerformanceMetrics(){const e=this.fpsCounter?this.fpsCounter.getMetrics():{};return{fps:e.fps||60,instantFps:e.smoothedFPS||60,frameTime:e.frameTime||16.67,averageFrameTime:e.averageFrameTime||16.67,isRunning:this.isRunning,deltaTime:this.deltaTime}}setTargetFPS(e){}get targetFPS(){return this.config.targetFPS||60}setSpeedMultiplier(e){this.speedMultiplier=Math.max(.1,Math.min(10,e))}getSpeedMultiplier(){return this.speedMultiplier}isAnimating(){return this.isRunning}destroy(){this.stop(),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("blur",this.handleWindowBlur),window.removeEventListener("focus",this.handleWindowFocus)),this.performanceMonitor&&(this.performanceMonitor.destroy(),this.performanceMonitor=null),this.subsystems={},this.eventCallback=null}}class Ha{constructor(e={}){this.config={spikeThreshold:e.spikeThreshold||1.5,minimumSpikeLevel:e.minimumSpikeLevel||.1,spikeMinInterval:e.spikeMinInterval||1e3,historySize:e.historySize||10,smoothingTimeConstant:e.smoothingTimeConstant||.8,fftSize:e.fftSize||256,levelUpdateThrottle:e.levelUpdateThrottle||100,...e},this.audioContext=null,this.analyser=null,this.dataArray=null,this.currentLevel=0,this.levelHistory=[],this.isActive=!1,this.lastVolumeSpike=0,this.lastLevelEmit=0,this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}initialize(e){try{if(!e)throw new Error("AudioContext is required for audio level processing");if("function"!=typeof e.createAnalyser)throw new Error("Invalid AudioContext provided");return this.audioContext=e,this.analyser=e.createAnalyser(),this.analyser.fftSize=this.config.fftSize,this.analyser.smoothingTimeConstant=this.config.smoothingTimeConstant,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.currentLevel=0,this.levelHistory=[],this.lastVolumeSpike=0,this.isActive=!0,"suspended"===e.state&&e.resume().catch(e=>{this.emitError("Failed to resume AudioContext",e)}),!0}catch(e){return this.emitError("Failed to initialize AudioLevelProcessor",e),!1}}cleanup(){try{this.isActive=!1,this.currentLevel=0,this.levelHistory=[],this.lastVolumeSpike=0,this.lastLevelEmit=0,this.audioContext=null,this.analyser=null,this.dataArray=null}catch(e){this.emitError("Error during AudioLevelProcessor cleanup",e)}}updateAudioLevel(e=16){if(this.isActive&&this.analyser&&this.dataArray)try{this.analyser.getByteFrequencyData(this.dataArray);const e=this.calculateRMS();this.currentLevel=Math.min(1,2*e),this.updateLevelHistory(),this.detectVolumeSpikes(),this.emitLevelUpdate()}catch(e){this.emitError("Error updating audio level",e),this.currentLevel=0}}calculateRMS(){if(!this.dataArray||0===this.dataArray.length)return 0;let e=0;for(let t=0;t<this.dataArray.length;t++){const i=this.dataArray[t]/255;e+=i*i}return Math.sqrt(e/this.dataArray.length)}updateLevelHistory(){this.levelHistory.push(this.currentLevel),this.levelHistory.length>this.config.historySize&&this.levelHistory.shift()}detectVolumeSpikes(){if(this.levelHistory.length<5)return;const e=performance.now();if(e-this.lastVolumeSpike<this.config.spikeMinInterval)return;const t=this.levelHistory.slice(0,-1),i=t.reduce((e,t)=>e+t,0)/t.length;this.currentLevel>=i*this.config.spikeThreshold&&i>=this.config.minimumSpikeLevel&&this.currentLevel>=2*this.config.minimumSpikeLevel&&(this.lastVolumeSpike=e,this.emitVolumeSpike({level:this.currentLevel,previousAverage:i,spikeRatio:this.currentLevel/i,timestamp:e,threshold:this.config.spikeThreshold,minimumLevel:this.config.minimumSpikeLevel}))}clearHistory(){this.levelHistory=[]}getCurrentLevel(){return this.currentLevel}getLevelHistory(){return[...this.levelHistory]}getAnalyser(){return this.analyser}getFrequencyData(){return this.dataArray?new Uint8Array(this.dataArray):null}isProcessingActive(){return this.isActive}onLevelUpdate(e){if("function"!=typeof e)throw new Error("Level update callback must be a function");this.callbacks.levelUpdate=e}onVolumeSpike(e){if("function"!=typeof e)throw new Error("Volume spike callback must be a function");this.callbacks.volumeSpike=e}onError(e){if("function"!=typeof e)throw new Error("Error callback must be a function");this.callbacks.error=e}removeAllCallbacks(){this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}updateConfig(e){this.config={...this.config,...e},this.analyser&&(e.fftSize&&(this.analyser.fftSize=this.config.fftSize,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount)),void 0!==e.smoothingTimeConstant&&(this.analyser.smoothingTimeConstant=this.config.smoothingTimeConstant))}getConfig(){return{...this.config}}getStats(){return{isActive:this.isActive,currentLevel:this.currentLevel,historySize:this.levelHistory.length,maxHistorySize:this.config.historySize,lastSpikeTime:this.lastVolumeSpike,timeSinceLastSpike:this.lastVolumeSpike>0?performance.now()-this.lastVolumeSpike:0,averageLevel:this.levelHistory.length>0?this.levelHistory.reduce((e,t)=>e+t,0)/this.levelHistory.length:0}}emitLevelUpdate(){const e=performance.now();if(!(e-this.lastLevelEmit<this.config.levelUpdateThrottle)&&(this.lastLevelEmit=e,this.callbacks.levelUpdate))try{this.callbacks.levelUpdate({level:this.currentLevel,rawData:this.getFrequencyData(),timestamp:e,history:this.getLevelHistory()})}catch{}}emitVolumeSpike(e){if(this.callbacks.volumeSpike)try{this.callbacks.volumeSpike(e)}catch{}}emitError(e,t){if(this.callbacks.error)try{this.callbacks.error({message:e,error:t,timestamp:performance.now()})}catch{}}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}}class ja{constructor(e={}){this.config={enableReducedMotion:!1!==e.enableReducedMotion,enableHighContrast:!1!==e.enableHighContrast,enableScreenReaderSupport:!1!==e.enableScreenReaderSupport,enableKeyboardNavigation:!1!==e.enableKeyboardNavigation,enableFocusIndicators:!1!==e.enableFocusIndicators,announceStateChanges:!1!==e.announceStateChanges,colorBlindMode:e.colorBlindMode||"none",...e},this.reducedMotionPreferred=!1,this.highContrastEnabled=!1,this.screenReaderActive=!1,this.keyboardNavigationActive=!1,this.currentColorBlindMode=this.config.colorBlindMode,this.focusableElements=new Map,this.currentFocusIndex=-1,this.focusHistory=[],this.liveRegion=null,this.announcementQueue=[],this.boundHandleKeyDown=null,this.boundHandleKeyUp=null,this.colorSchemes={normal:null,highContrast:{primary:"#FFFFFF",secondary:"#000000",accent:"#FFFF00",background:"#000000",particles:"#FFFFFF"},protanopia:{primary:"#0066CC",secondary:"#FFCC00",accent:"#00CCFF",background:"#1A1A1A",particles:"#66CCFF"},deuteranopia:{primary:"#0099FF",secondary:"#FF9900",accent:"#FF00FF",background:"#1A1A1A",particles:"#9966FF"},tritanopia:{primary:"#FF0066",secondary:"#00FF66",accent:"#FF6600",background:"#1A1A1A",particles:"#FFCC00"}},this.patterns={dots:"dots",stripes:"stripes",crosshatch:"crosshatch",solid:"solid"},this.statePatterns={idle:this.patterns.solid,happy:this.patterns.dots,excited:this.patterns.stripes,calm:this.patterns.solid,curious:this.patterns.crosshatch,frustrated:this.patterns.stripes,sad:this.patterns.dots,neutral:this.patterns.solid},this.initialize()}initialize(){this.detectUserPreferences(),this.setupLiveRegion(),this.config.enableKeyboardNavigation&&this.setupKeyboardNavigation(),this.setupPreferenceListeners()}detectUserPreferences(){if(this.config.enableReducedMotion&&window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion: reduce)");this.reducedMotionPreferred=e.matches}if(this.config.enableHighContrast&&window.matchMedia){const e=window.matchMedia("(prefers-contrast: high)");if(this.highContrastEnabled=e.matches,!this.highContrastEnabled){const e=window.matchMedia("(-ms-high-contrast: active)");this.highContrastEnabled=e.matches}}this.detectScreenReader()}detectScreenReader(){const e=document.querySelector("[aria-live]"),t=document.querySelector("[aria-atomic]"),i=document.querySelector('[role="application"]'),s=navigator.userAgent.toLowerCase(),n=s.includes("nvda")||s.includes("jaws")||s.includes("voiceover");this.screenReaderActive=!!(e||t||i||n)}setupLiveRegion(){this.config.enableScreenReaderSupport&&(this.liveRegion=document.getElementById("mascot-announcements"),this.liveRegion||(this.liveRegion=document.createElement("div"),this.liveRegion.id="mascot-announcements",this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.position="absolute",this.liveRegion.style.left="-10000px",this.liveRegion.style.width="1px",this.liveRegion.style.height="1px",this.liveRegion.style.overflow="hidden",document.body.appendChild(this.liveRegion)))}setupKeyboardNavigation(){this.boundHandleKeyDown=this.handleKeyDown.bind(this),this.boundHandleKeyUp=this.handleKeyUp.bind(this),document.addEventListener("keydown",this.boundHandleKeyDown),document.addEventListener("keyup",this.boundHandleKeyUp)}setupPreferenceListeners(){window.matchMedia&&(this._motionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this._motionHandler=e=>{this.reducedMotionPreferred=e.matches,this.onPreferenceChange("reducedMotion",e.matches)},this._motionQuery.addEventListener?this._motionQuery.addEventListener("change",this._motionHandler):this._motionQuery.addListener&&this._motionQuery.addListener(this._motionHandler),this._contrastQuery=window.matchMedia("(prefers-contrast: high)"),this._contrastHandler=e=>{this.highContrastEnabled=e.matches,this.onPreferenceChange("highContrast",e.matches)},this._contrastQuery.addEventListener?this._contrastQuery.addEventListener("change",this._contrastHandler):this._contrastQuery.addListener&&this._contrastQuery.addListener(this._contrastHandler))}handleKeyDown(e){if(this.config.enableKeyboardNavigation){switch(e.key){case"Tab":e.preventDefault(),this.navigateFocus(e.shiftKey?-1:1);break;case"Enter":case" ":this.activateCurrentFocus();break;case"Escape":this.clearFocus();break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":this.handleArrowNavigation(e.key)}this.keyboardNavigationActive=!0}}handleKeyUp(e){}navigateFocus(e){const t=Array.from(this.focusableElements.values());if(0===t.length)return;this.currentFocusIndex+=e,this.currentFocusIndex<0?this.currentFocusIndex=t.length-1:this.currentFocusIndex>=t.length&&(this.currentFocusIndex=0);const i=t[this.currentFocusIndex];this.setFocus(i),i.label&&this.announce(`Focused on ${i.label}`)}handleArrowNavigation(e){const t={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}}[e];t&&this.onArrowNavigation&&this.onArrowNavigation(t)}registerFocusableElement(e,t){this.focusableElements.set(e,{id:e,label:t.label||e,bounds:t.bounds||null,action:t.action||null,type:t.type||"button"})}unregisterFocusableElement(e){this.focusableElements.delete(e)}setFocus(e){this.onFocusChange&&this.onFocusChange(e),this.focusHistory.push(e.id),this.focusHistory.length>10&&this.focusHistory.shift()}clearFocus(){this.currentFocusIndex=-1,this.onFocusChange&&this.onFocusChange(null),this.announce("Focus cleared")}activateCurrentFocus(){const e=Array.from(this.focusableElements.values());if(this.currentFocusIndex>=0&&this.currentFocusIndex<e.length){const t=e[this.currentFocusIndex];t.action&&(t.action(),this.announce(`Activated ${t.label}`))}}announce(e,t="polite"){this.config.enableScreenReaderSupport&&this.liveRegion&&(this.announcementQueue.push({message:e,priority:t}),this.processAnnouncementQueue())}processAnnouncementQueue(){if(0===this.announcementQueue.length)return;const{message:e,priority:t}=this.announcementQueue.shift();this.liveRegion.setAttribute("aria-live",t),this.liveRegion.textContent=e,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent=""),this.announcementQueue.length>0&&this.processAnnouncementQueue()},100)}getAnimationSettings(e={}){return this.reducedMotionPreferred?{...e,duration:e.duration?.5*e.duration:0,iterations:1,easing:"linear",particlesEnabled:!1,complexAnimations:!1,autoPlay:!1}:e}getColorScheme(e={}){return this.colorSchemes.normal||(this.colorSchemes.normal={...e}),this.highContrastEnabled?this.colorSchemes.highContrast:"none"!==this.currentColorBlindMode&&this.colorSchemes[this.currentColorBlindMode]?this.colorSchemes[this.currentColorBlindMode]:e}getStatePattern(e){return"none"===this.currentColorBlindMode?this.patterns.solid:this.statePatterns[e]||this.patterns.solid}applyPatternOverlay(e,t,i){if(t===this.patterns.solid)return;e.save();const s=document.createElement("canvas"),n=s.getContext("2d");switch(t){case this.patterns.dots:this.createDotPattern(n,s);break;case this.patterns.stripes:this.createStripePattern(n,s);break;case this.patterns.crosshatch:this.createCrosshatchPattern(n,s)}const a=e.createPattern(s,"repeat");e.fillStyle=a,e.globalAlpha=.3,e.fillRect(i.x,i.y,i.width,i.height),e.restore()}createDotPattern(e,t){t.width=10,t.height=10,e.fillStyle="white",e.beginPath(),e.arc(5,5,2,0,2*Math.PI),e.fill()}createStripePattern(e,t){t.width=10,t.height=10,e.strokeStyle="white",e.lineWidth=2,e.beginPath(),e.moveTo(0,10),e.lineTo(10,0),e.stroke()}createCrosshatchPattern(e,t){t.width=10,t.height=10,e.strokeStyle="white",e.lineWidth=1,e.beginPath(),e.moveTo(0,10),e.lineTo(10,0),e.stroke(),e.beginPath(),e.moveTo(0,0),e.lineTo(10,10),e.stroke()}setColorBlindMode(e){["none","protanopia","deuteranopia","tritanopia"].includes(e)&&(this.currentColorBlindMode=e,this.announce(`Color blind mode set to ${e}`),this.onColorSchemeChange&&this.onColorSchemeChange(this.getColorScheme()))}getStatus(){return{reducedMotion:this.reducedMotionPreferred,highContrast:this.highContrastEnabled,screenReader:this.screenReaderActive,keyboardNavigation:this.keyboardNavigationActive,colorBlindMode:this.currentColorBlindMode,focusedElement:this.currentFocusIndex>=0?Array.from(this.focusableElements.values())[this.currentFocusIndex]:null,registeredElements:this.focusableElements.size}}onPreferenceChange(e,t){this.announce(`${e} is now ${t?"enabled":"disabled"}`),"reducedMotion"===e&&this.onReducedMotionChange&&this.onReducedMotionChange(t),"highContrast"===e&&this.onHighContrastChange&&this.onHighContrastChange(t)}createStateDescription(e){return{idle:"Mascot is idle and gently breathing",happy:"Mascot is happy and bouncing",excited:"Mascot is excited with particles flying",calm:"Mascot is calm and peaceful",curious:"Mascot is curious and looking around",frustrated:"Mascot is frustrated and shaking",sad:"Mascot is sad and drooping",neutral:"Mascot is in a neutral state"}[e.emotional]||"Mascot is active"}destroy(){this.boundHandleKeyDown&&(document.removeEventListener("keydown",this.boundHandleKeyDown),this.boundHandleKeyDown=null),this.boundHandleKeyUp&&(document.removeEventListener("keyup",this.boundHandleKeyUp),this.boundHandleKeyUp=null),this._motionQuery&&this._motionHandler&&(this._motionQuery.removeEventListener?this._motionQuery.removeEventListener("change",this._motionHandler):this._motionQuery.removeListener&&this._motionQuery.removeListener(this._motionHandler),this._motionQuery=null,this._motionHandler=null),this._contrastQuery&&this._contrastHandler&&(this._contrastQuery.removeEventListener?this._contrastQuery.removeEventListener("change",this._contrastHandler):this._contrastQuery.removeListener&&this._contrastQuery.removeListener(this._contrastHandler),this._contrastQuery=null,this._contrastHandler=null),this.liveRegion&&this.liveRegion.parentNode&&this.liveRegion.parentNode.removeChild(this.liveRegion),this.focusableElements.clear(),this.announcementQueue=[],this.focusHistory=[]}}class $a{constructor(e={}){this.config={enableTouchOptimization:!1!==e.enableTouchOptimization,enableViewportHandling:!1!==e.enableViewportHandling,enableBatteryOptimization:!1!==e.enableBatteryOptimization,enableOrientationSupport:!1!==e.enableOrientationSupport,enableResponsiveScaling:!1!==e.enableResponsiveScaling,touchSensitivity:e.touchSensitivity||1,doubleTapDelay:e.doubleTapDelay||300,swipeThreshold:e.swipeThreshold||50,pinchThreshold:e.pinchThreshold||.1,...e},this.isMobile=this.detectMobile(),this.isTablet=this.detectTablet(),this.isTouchDevice=this.detectTouch(),this.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent),this.isAndroid=/Android/.test(navigator.userAgent),this.touches=new Map,this.lastTouchTime=0,this.lastTapTime=0,this.tapCount=0,this.touchStartPosition=null,this.isPinching=!1,this.isRotating=!1,this.lastPinchDistance=0,this.lastRotation=0,this.currentGesture=null,this.gestureStartTime=0,this.gestureHistory=[],this.viewportSize={width:window.innerWidth,height:window.innerHeight},this.orientation=this.getOrientation(),this.pixelRatio=window.devicePixelRatio||1,this.lastViewportChange=0,this.batteryLevel=1,this.isCharging=!0,this.lowPowerMode=!1,this.batteryRef=null,this.mobilePerformanceSettings={reducedParticles:this.isMobile,simplifiedAnimations:this.isMobile,lowerFrameRate:this.isMobile,reducedEffects:this.isMobile||this.isTablet,targetFPS:this.isMobile?30:60,maxParticles:this.isMobile?20:50},this.canvasScale=1,this.useOffscreenCanvas=this.supportsOffscreenCanvas(),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.handleTouchCancel=this.handleTouchCancel.bind(this),this.handleOrientationChange=this.handleOrientationChange.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.handleVisibilityChange=this.handleVisibilityChange.bind(this),this.handleContextMenu=e=>e.preventDefault(),this.initialize()}initialize(){this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers(),this.config.enableViewportHandling&&this.setupViewportHandlers(),this.config.enableBatteryOptimization&&this.setupBatteryMonitoring(),this.config.enableOrientationSupport&&this.setupOrientationHandlers(),this.applyMobileOptimizations()}detectMobile(){const e=navigator.userAgent.toLowerCase(),t=["android","iphone","ipod","windows phone","blackberry"].some(t=>e.includes(t)),i=window.innerWidth<=768,s="ontouchstart"in window||navigator.maxTouchPoints>0;return t||i&&s}detectTablet(){const e=navigator.userAgent.toLowerCase(),t=/ipad/.test(e),i=/android/.test(e)&&!/mobile/.test(e),s=/windows/.test(e)&&/touch/.test(e),n=window.innerWidth>768&&window.innerWidth<=1024,a="ontouchstart"in window||navigator.maxTouchPoints>0;return t||i||s||n&&a}detectTouch(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0}supportsOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}setupTouchHandlers(){const e=this.getCanvas();e&&(e.style.touchAction="none",e.style.userSelect="none",e.style.webkitUserSelect="none",e.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),e.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),e.addEventListener("touchend",this.handleTouchEnd,{passive:!1}),e.addEventListener("touchcancel",this.handleTouchCancel,{passive:!1}),e.addEventListener("contextmenu",this.handleContextMenu))}setupViewportHandlers(){window.addEventListener("resize",this.handleViewportChange),window.addEventListener("orientationchange",this.handleOrientationChange),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.setupViewportMeta()}setupViewportMeta(){let e=document.querySelector('meta[name="viewport"]');e||(e=document.createElement("meta"),e.name="viewport",document.head.appendChild(e)),e.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"}async setupBatteryMonitoring(){if(navigator.getBattery)try{const e=await navigator.getBattery();this.batteryRef=e,this.batteryLevel=e.level,this.isCharging=e.charging,this.boundBatteryLevelChange=()=>{this.batteryLevel=e.level,this.onBatteryChange()},this.boundBatteryChargingChange=()=>{this.isCharging=e.charging,this.onBatteryChange()},e.addEventListener("levelchange",this.boundBatteryLevelChange),e.addEventListener("chargingchange",this.boundBatteryChargingChange),this.onBatteryChange()}catch{}}setupOrientationHandlers(){window.DeviceOrientationEvent&&(this._deviceOrientationHandler=e=>{this.handleDeviceOrientation(e)},window.addEventListener("deviceorientation",this._deviceOrientationHandler))}handleTouchStart(e){e.cancelable&&e.preventDefault();const t=Date.now();this.gestureStartTime=t;for(const i of e.touches)this.touches.set(i.identifier,{id:i.identifier,startX:i.clientX,startY:i.clientY,currentX:i.clientX,currentY:i.clientY,startTime:t});1===e.touches.length?this.handleSingleTouchStart(e.touches[0]):2===e.touches.length&&this.handleMultiTouchStart(e.touches),this.emitTouchEvent("touchStart",{touches:Array.from(this.touches.values()),timestamp:t})}handleSingleTouchStart(e){const t=Date.now();t-this.lastTapTime<this.config.doubleTapDelay?this.tapCount++:this.tapCount=1,this.lastTapTime=t,this.touchStartPosition={x:e.clientX,y:e.clientY}}handleMultiTouchStart(e){if(2===e.length){const t=e[0],i=e[1];this.lastPinchDistance=this.getDistance(t.clientX,t.clientY,i.clientX,i.clientY),this.lastRotation=this.getAngle(t.clientX,t.clientY,i.clientX,i.clientY),this.isPinching=!0}}handleTouchMove(e){e.cancelable&&e.preventDefault();for(const t of e.touches){const e=this.touches.get(t.identifier);e&&(e.currentX=t.clientX,e.currentY=t.clientY)}1===e.touches.length?this.handleSingleTouchMove(e.touches[0]):2===e.touches.length&&this.handleMultiTouchMove(e.touches),this.emitTouchEvent("touchMove",{touches:Array.from(this.touches.values()),gesture:this.currentGesture})}handleSingleTouchMove(e){const t=this.touches.get(e.identifier);if(!t)return;const i=e.clientX-t.startX,s=e.clientY-t.startY;Math.sqrt(i*i+s*s)>this.config.swipeThreshold?Math.abs(i)>Math.abs(s)?this.currentGesture=i>0?"swipeRight":"swipeLeft":this.currentGesture=s>0?"swipeDown":"swipeUp":this.currentGesture="pan"}handleMultiTouchMove(e){if(2!==e.length)return;const t=e[0],i=e[1],s=this.getDistance(t.clientX,t.clientY,i.clientX,i.clientY),n=s-this.lastPinchDistance,a=s/this.lastPinchDistance;Math.abs(n)>this.config.pinchThreshold&&(this.currentGesture=a>1?"pinchOut":"pinchIn",this.emitTouchEvent("pinch",{scale:a,delta:n}));const r=this.getAngle(t.clientX,t.clientY,i.clientX,i.clientY),o=r-this.lastRotation;Math.abs(o)>5&&(this.currentGesture="rotate",this.emitTouchEvent("rotate",{angle:r,delta:o})),this.lastPinchDistance=s,this.lastRotation=r}handleTouchEnd(e){e.cancelable&&e.preventDefault();const t=Date.now();for(const i of e.changedTouches){const e=this.touches.get(i.identifier);if(e){const s=t-e.startTime,n=e.currentX-e.startX,a=e.currentY-e.startY,r=Math.sqrt(n*n+a*a);s<300&&r<10&&(2===this.tapCount?(this.emitTouchEvent("doubleTap",{x:e.currentX,y:e.currentY}),this.tapCount=0):this.emitTouchEvent("tap",{x:e.currentX,y:e.currentY})),s>500&&r<10&&this.emitTouchEvent("longPress",{x:e.currentX,y:e.currentY}),this.touches.delete(i.identifier)}}0===e.touches.length&&(this.currentGesture=null,this.isPinching=!1,this.isRotating=!1),this.emitTouchEvent("touchEnd",{gesture:this.currentGesture,duration:t-this.gestureStartTime})}handleTouchCancel(e){this.touches.clear(),this.currentGesture=null,this.isPinching=!1,this.isRotating=!1,this.emitTouchEvent("touchCancel",{})}handleOrientationChange(e){this.orientation=this.getOrientation(),this.emitTouchEvent("orientationChange",{orientation:this.orientation,angle:window.orientation||0}),this.applyOrientationOptimizations()}handleDeviceOrientation(e){const{alpha:t,beta:i,gamma:s}=e;this.emitTouchEvent("deviceOrientation",{alpha:t,beta:i,gamma:s})}handleViewportChange(e){const t=Date.now();t-this.lastViewportChange<100||(this.lastViewportChange=t,this.viewportSize={width:window.innerWidth,height:window.innerHeight},this.pixelRatio=window.devicePixelRatio||1,this.emitTouchEvent("viewportChange",{size:this.viewportSize,pixelRatio:this.pixelRatio,orientation:this.getOrientation()}),this.config.enableResponsiveScaling&&this.applyResponsiveScaling())}handleVisibilityChange(e){const t=!document.hidden;this.emitTouchEvent("visibilityChange",{visible:t}),!t&&this.config.enableBatteryOptimization?this.applyBackgroundOptimizations():this.restorePerformance()}getOrientation(){return window.innerWidth>window.innerHeight?"landscape":"portrait"}getDistance(e,t,i,s){const n=i-e,a=s-t;return Math.sqrt(n*n+a*a)}getAngle(e,t,i,s){return 180*Math.atan2(s-t,i-e)/Math.PI}applyMobileOptimizations(){if(!this.isMobile&&!this.isTablet)return;const e={...this.mobilePerformanceSettings,canvasScale:this.calculateOptimalCanvasScale(),useWebGL:!1,useOffscreenCanvas:this.useOffscreenCanvas};return this.emitTouchEvent("mobileOptimizations",e),e}applyOrientationOptimizations(){const e="landscape"===this.orientation,t={layoutMode:e?"horizontal":"vertical",particleDirection:e?"horizontal":"vertical",uiScale:e?.8:1};return this.emitTouchEvent("orientationOptimizations",t),t}applyResponsiveScaling(){const e=Math.min(this.viewportSize.width/375,2);return this.canvasScale=e,this.emitTouchEvent("responsiveScale",{scale:this.canvasScale,viewport:this.viewportSize}),this.canvasScale}applyBackgroundOptimizations(){const e={targetFPS:5,particlesEnabled:!1,animationsEnabled:!1,audioEnabled:!1};return this.emitTouchEvent("backgroundOptimizations",e),e}restorePerformance(){const e=this.applyMobileOptimizations();return this.emitTouchEvent("performanceRestore",e),e}onBatteryChange(){if(this.lowPowerMode=this.batteryLevel<.2&&!this.isCharging,this.lowPowerMode){const e={targetFPS:15,maxParticles:5,reducedEffects:!0,audioEnabled:!1};this.emitTouchEvent("lowPowerMode",{batteryLevel:this.batteryLevel,isCharging:this.isCharging,optimizations:e})}}calculateOptimalCanvasScale(){return this.isMobile?Math.min(this.pixelRatio,2):this.isTablet?Math.min(this.pixelRatio,2.5):this.pixelRatio}getCanvas(){return this.canvas||document.querySelector("canvas")}setCanvas(e){this.canvas=e,this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers()}emitTouchEvent(e,t){this.onTouchEvent&&this.onTouchEvent(e,t)}getStatus(){return{device:{isMobile:this.isMobile,isTablet:this.isTablet,isTouchDevice:this.isTouchDevice,isIOS:this.isIOS,isAndroid:this.isAndroid},viewport:{size:this.viewportSize,orientation:this.orientation,pixelRatio:this.pixelRatio,canvasScale:this.canvasScale},battery:{level:this.batteryLevel,isCharging:this.isCharging,lowPowerMode:this.lowPowerMode},touch:{activeTouches:this.touches.size,currentGesture:this.currentGesture,isPinching:this.isPinching,isRotating:this.isRotating},performance:this.mobilePerformanceSettings}}destroy(){const e=this.getCanvas();e&&(e.removeEventListener("touchstart",this.handleTouchStart),e.removeEventListener("touchmove",this.handleTouchMove),e.removeEventListener("touchend",this.handleTouchEnd),e.removeEventListener("touchcancel",this.handleTouchCancel),e.removeEventListener("contextmenu",this.handleContextMenu)),window.removeEventListener("resize",this.handleViewportChange),window.removeEventListener("orientationchange",this.handleOrientationChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange),this._deviceOrientationHandler&&(window.removeEventListener("deviceorientation",this._deviceOrientationHandler),this._deviceOrientationHandler=null),this.batteryRef&&(this.boundBatteryLevelChange&&this.batteryRef.removeEventListener("levelchange",this.boundBatteryLevelChange),this.boundBatteryChargingChange&&this.batteryRef.removeEventListener("chargingchange",this.boundBatteryChargingChange),this.batteryRef=null),this.touches.clear(),this.gestureHistory=[]}}class Wa{constructor(e={}){this.config={enablePlugins:!1!==e.enablePlugins,validatePlugins:!1!==e.validatePlugins,sandboxPlugins:!1!==e.sandboxPlugins,maxPlugins:e.maxPlugins||50,pluginTimeout:e.pluginTimeout||5e3,allowOverrides:!1!==e.allowOverrides},this.mascot=e.mascot||null,this.plugins=new Map,this.pluginTypes=["emotion","gesture","particle","audio","renderer","animation"],this.pluginsByType=new Map(this.pluginTypes.map(e=>[e,new Set])),this.dependencies=new Map,this.dependencyGraph=new Map,this.pluginStates=new Map,this.loadingPlugins=new Set,this.activePlugins=new Set,this.hooks=new Map([["beforeInit",new Set],["afterInit",new Set],["beforeUpdate",new Set],["afterUpdate",new Set],["beforeRender",new Set],["afterRender",new Set],["beforeDestroy",new Set],["afterDestroy",new Set]]),this.pluginAPI=this.createPluginAPI(),this.conflicts=new Map,this.resolutionStrategies={override:this.overrideConflict.bind(this),merge:this.mergeConflict.bind(this),reject:this.rejectConflict.bind(this),queue:this.queueConflict.bind(this)},this.validationSchemas=this.createValidationSchemas(),this.sandbox=null,this.config.sandboxPlugins&&(this.sandbox=this.createSandbox())}createPluginAPI(){return{mascot:this.mascot,registerHook:this.registerHook.bind(this),emit:this.emitPluginEvent.bind(this),on:this.onPluginEvent.bind(this),getPlugin:this.getPlugin.bind(this),hasPlugin:this.hasPlugin.bind(this),log:this.logFromPlugin.bind(this),error:this.errorFromPlugin.bind(this),setState:this.setPluginState.bind(this),getState:this.getPluginState.bind(this),getConfig:()=>({...this.config}),version:"1.0.0"}}createValidationSchemas(){const e=new Map,t={name:{type:"string",required:!0},version:{type:"string",required:!0},type:{type:"string",required:!0,enum:this.pluginTypes},description:{type:"string",required:!1},author:{type:"string",required:!1},dependencies:{type:"array",required:!1},conflicts:{type:"array",required:!1},init:{type:"function",required:!0},destroy:{type:"function",required:!0}};return e.set("emotion",{...t,emotion:{type:"object",required:!0,properties:{name:{type:"string",required:!0},color:{type:"string",required:!0},particleColor:{type:"string",required:!1},animation:{type:"object",required:!0},transitions:{type:"object",required:!1}}},updateEmotion:{type:"function",required:!0},renderEmotion:{type:"function",required:!1}}),e.set("gesture",{...t,gesture:{type:"object",required:!0,properties:{name:{type:"string",required:!0},duration:{type:"number",required:!0},keyframes:{type:"array",required:!0},compatibility:{type:"object",required:!1}}},executeGesture:{type:"function",required:!0},canExecute:{type:"function",required:!1}}),e.set("particle",{...t,particle:{type:"object",required:!0,properties:{name:{type:"string",required:!0},maxParticles:{type:"number",required:!1},behavior:{type:"function",required:!0},render:{type:"function",required:!0}}},updateParticles:{type:"function",required:!0},spawnParticle:{type:"function",required:!1}}),e.set("audio",{...t,audio:{type:"object",required:!0,properties:{name:{type:"string",required:!0},sounds:{type:"object",required:!0},effects:{type:"array",required:!1}}},playSound:{type:"function",required:!0},processAudio:{type:"function",required:!1}}),e}createSandbox(){return console.warn("[PluginSystem] sandboxPlugins is enabled, but the sandbox provides .bind() context isolation only, not true execution sandboxing. Plugins may still access globals through closures or prototype chains."),{Math:Math,Date:Date,JSON:JSON,console:{log:(...e)=>null,warn:(...e)=>null,error:(...e)=>null},window:void 0,document:void 0,localStorage:void 0,sessionStorage:void 0,fetch:void 0,XMLHttpRequest:void 0,api:this.pluginAPI}}async registerPlugin(e){if(!this.config.enablePlugins)return!1;if(this.plugins.size>=this.config.maxPlugins)return!1;if(this.config.validatePlugins&&!this.validatePlugin(e).valid)return!1;if(this.checkConflicts(e).length>0&&!this.config.allowOverrides)return!1;if(!(await this.resolveDependencies(e)).resolved)return!1;try{this.loadingPlugins.add(e.name);const t=this.config.sandboxPlugins?this.sandbox:window;if(!await this.initializePlugin(e,t))throw new Error("Plugin initialization failed");return this.plugins.set(e.name,e),this.pluginsByType.get(e.type).add(e.name),this.pluginStates.set(e.name,"active"),this.activePlugins.add(e.name),e.dependencies&&(this.dependencies.set(e.name,e.dependencies),this.updateDependencyGraph(e.name,e.dependencies)),e.hooks&&Object.entries(e.hooks).forEach(([t,i])=>{this.registerHook(t,i,e.name)}),this.emitPluginEvent("pluginRegistered",{name:e.name,type:e.type,version:e.version}),!0}catch(e){return console.warn("[PluginSystem] Failed to register plugin:",e),!1}finally{this.loadingPlugins.delete(e.name)}}validatePlugin(e){const t=[];if(e.name&&"string"==typeof e.name||t.push("Plugin must have a valid name"),e.type&&this.pluginTypes.includes(e.type)||t.push(`Plugin type must be one of: ${this.pluginTypes.join(", ")}`),e.version&&"string"==typeof e.version||t.push("Plugin must have a version"),"function"!=typeof e.init&&t.push("Plugin must have an init function"),"function"!=typeof e.destroy&&t.push("Plugin must have a destroy function"),e.type&&this.validationSchemas.has(e.type)){const i=this.validationSchemas.get(e.type),s=this.validateAgainstSchema(e,i);t.push(...s)}return{valid:0===t.length,errors:t}}validateAgainstSchema(e,t){const i=[];return Object.entries(t).forEach(([t,s])=>{if(s.required&&!(t in e)&&i.push(`Missing required property: ${t}`),t in e){const n=e[t];if(s.type&&typeof n!==s.type&&i.push(`Property ${t} must be of type ${s.type}`),s.enum&&!s.enum.includes(n)&&i.push(`Property ${t} must be one of: ${s.enum.join(", ")}`),s.properties&&"object"==typeof n){const e=this.validateAgainstSchema(n,s.properties);i.push(...e.map(e=>`${t}.${e}`))}}}),i}checkConflicts(e){const t=[];return e.conflicts&&e.conflicts.forEach(e=>{this.plugins.has(e)&&t.push(e)}),"emotion"!==e.type&&"gesture"!==e.type||this.plugins.forEach(i=>{if(i.type===e.type){const s=i[e.type]?.name,n=e[e.type]?.name;s===n&&t.push(`${e.type} name collision: ${n}`)}}),t}async resolveDependencies(e){if(!e.dependencies||0===e.dependencies.length)return{resolved:!0,missing:[]};const t=[];for(const i of e.dependencies)this.plugins.has(i)||await this.tryLoadDependency(i)||t.push(i);return{resolved:0===t.length,missing:t}}tryLoadDependency(e){return this.plugins.has(e)}updateDependencyGraph(e,t){this.dependencyGraph.set(e,new Set(t)),t.forEach(e=>{this.dependencyGraph.has(e)||this.dependencyGraph.set(e,new Set)})}async initializePlugin(e,t){try{const i=new Promise((e,t)=>{setTimeout(()=>t(new Error("Plugin initialization timeout")),this.config.pluginTimeout)}),s=e.init.bind(t);return!1!==await Promise.race([s(this.pluginAPI),i])}catch(e){return console.warn("[PluginSystem] Plugin initialization error:",e),!1}}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(this.getDependentPlugins(e).length>0)return!1;try{return"function"==typeof t.destroy&&await t.destroy(),this.plugins.delete(e),this.pluginsByType.get(t.type).delete(e),this.pluginStates.delete(e),this.activePlugins.delete(e),this.dependencies.delete(e),this.dependencyGraph.delete(e),this.hooks.forEach(t=>{t.forEach(i=>{i.pluginName===e&&t.delete(i)})}),this.emitPluginEvent("pluginUnregistered",{name:e}),!0}catch(e){return console.warn("[PluginSystem] Failed to unregister plugin:",e),!1}}getDependentPlugins(e){const t=[];return this.dependencies.forEach((i,s)=>{i.includes(e)&&t.push(s)}),t}registerHook(e,t,i){this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add({handler:t,pluginName:i})}async executeHooks(e,t){const i=this.hooks.get(e);if(!i||0===i.size)return[];const s=[];for(const n of i)try{const e=await n.handler(t);s.push({pluginName:n.pluginName,result:e})}catch(t){console.warn(`[PluginSystem] Hook '${e}' error in plugin '${n.pluginName}':`,t)}return s}getPlugin(e){return this.plugins.get(e)||null}hasPlugin(e){return this.plugins.has(e)}getPluginsByType(e){const t=this.pluginsByType.get(e);return t?Array.from(t).map(e=>this.plugins.get(e)):[]}enablePlugin(e){if(!this.plugins.has(e))return;this.pluginStates.set(e,"active"),this.activePlugins.add(e);const t=this.plugins.get(e);t.onEnable&&t.onEnable(),this.emitPluginEvent("pluginEnabled",{name:e})}disablePlugin(e){if(!this.plugins.has(e))return;this.getDependentPlugins(e).length,this.pluginStates.set(e,"disabled"),this.activePlugins.delete(e);const t=this.plugins.get(e);t.onDisable&&t.onDisable(),this.emitPluginEvent("pluginDisabled",{name:e})}emitPluginEvent(e,t){this.onPluginEvent&&this.onPluginEvent(e,t)}onPluginEvent(e,t){}logFromPlugin(e,...t){}errorFromPlugin(e,...t){console.warn(`[PluginSystem] ${e}:`,...t)}setPluginState(e,t,i){this.pluginStates.has(e)||this.pluginStates.set(e,{});const s=this.pluginStates.get(e);"object"==typeof s&&(s[t]=i)}getPluginState(e,t){const i=this.pluginStates.get(e);if("object"==typeof i)return i[t]}overrideConflict(e,t){return t}mergeConflict(e,t){return{...e,...t}}rejectConflict(e,t){return e}queueConflict(e,t){return[e,t]}getStatus(){return{enabled:this.config.enablePlugins,totalPlugins:this.plugins.size,activePlugins:this.activePlugins.size,loadingPlugins:this.loadingPlugins.size,pluginsByType:Object.fromEntries(Array.from(this.pluginsByType.entries()).map(([e,t])=>[e,t.size])),hooks:Object.fromEntries(Array.from(this.hooks.entries()).map(([e,t])=>[e,t.size]))}}update(e,t){if(this.config.enablePlugins)for(const i of this.activePlugins){const s=this.plugins.get(i);if(s&&"function"==typeof s.update)try{s.update(e,t)}catch(e){this.errorFromPlugin(i,"Update error:",e)}}}render(e,t){if(this.config.enablePlugins)for(const i of this.activePlugins){const s=this.plugins.get(i);if(s&&"function"==typeof s.render)try{s.render(e,t)}catch(e){this.errorFromPlugin(i,"Render error:",e)}}}async destroy(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t);this.plugins.clear(),this.pluginsByType.clear(),this.dependencies.clear(),this.dependencyGraph.clear(),this.pluginStates.clear(),this.activePlugins.clear(),this.loadingPlugins.clear(),this.hooks.clear(),this.conflicts.clear()}}class Ua{constructor(){if(Ua._cachedFeatures)return this.features=Ua._cachedFeatures,void(this.capabilities=Ua._cachedCapabilities);this.features={webAudio:this.detectWebAudio(),canvas2d:this.detectCanvas2D(),requestAnimationFrame:this.detectRequestAnimationFrame(),devicePixelRatio:this.detectDevicePixelRatio(),audioContext:this.detectAudioContext(),mediaDevices:this.detectMediaDevices(),performance:this.detectPerformance(),intersectionObserver:this.detectIntersectionObserver()},this.capabilities=this.assessCapabilities(),Ua._cachedFeatures=this.features,Ua._cachedCapabilities=this.capabilities}detectWebAudio(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectCanvas2D(){try{const e=document.createElement("canvas");return!(!e.getContext||!e.getContext("2d"))}catch{return!1}}detectRequestAnimationFrame(){return!!(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame)}detectDevicePixelRatio(){return"number"==typeof window.devicePixelRatio}detectAudioContext(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)}detectPerformance(){return!(!window.performance||!window.performance.now)}detectIntersectionObserver(){return"function"==typeof window.IntersectionObserver}assessCapabilities(){const e=Object.values(this.features).filter(Boolean).length,t=Object.keys(this.features).length,i=e/t*100;let s="basic";return i>=90?s="full":i>=70?s="good":i>=50&&(s="limited"),{score:e,total:t,percentage:i,level:s,recommendations:this.getRecommendations(s)}}getRecommendations(e){const t=[];return this.features.webAudio||t.push("Audio features will be disabled"),this.features.requestAnimationFrame||t.push("Animation will use setTimeout fallback"),this.features.performance||t.push("Performance monitoring will be limited"),"basic"===e&&t.push("Consider using minimal build for better performance"),t}getFeatures(){return{...this.features}}getCapabilities(){return{...this.capabilities}}}class Va{constructor(){this.polyfills=new Map,this.applied=new Set}register(e,t){this.polyfills.set(e,t)}apply(e){if(this.applied.has(e))return!0;const t=this.polyfills.get(e);if(!t)return!1;try{return t(),this.applied.add(e),!0}catch{return!1}}applyAll(){const e=[];for(const t of this.polyfills.keys())this.apply(t)&&e.push(t);return e}isApplied(e){return this.applied.has(e)}}function Ya(){window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return window.setTimeout(()=>{e(Date.now())},1e3/60)},window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(e){window.clearTimeout(e)})}function Xa(){if(window.performance&&window.performance.now)return;window.performance||(window.performance={});const e=Date.now();window.performance.now=function(){return Date.now()-e}}function Na(){window.AudioContext||window.webkitAudioContext||(window.AudioContext=function(){this.state="suspended",this.sampleRate=44100,this.currentTime=0,this.destination={connect(){},disconnect(){}},this.createGain=function(){return{gain:{value:1},connect(){},disconnect(){}}},this.createOscillator=function(){return{frequency:{value:440},type:"sine",start(){},stop(){},connect(){},disconnect(){}}},this.createAnalyser=function(){return{fftSize:2048,frequencyBinCount:1024,getByteFrequencyData(e){for(let t=0;t<e.length;t++)e[t]=0},connect(){},disconnect(){}}},this.resume=function(){return this.state="running",Promise.resolve()},this.suspend=function(){return this.state="suspended",Promise.resolve()},this.close=function(){return this.state="closed",Promise.resolve()}})}class Qa{constructor(e){this.canvas=e,this.context=null,this.isContextLost=!1,this.recoveryCallbacks=[],this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this),this.setupContextLossHandling()}handleContextLost(e){e.preventDefault(),this.isContextLost=!0}handleContextRestored(){this.isContextLost=!1,this.context=this.canvas.getContext("2d"),this.recoveryCallbacks.forEach(e=>{try{e(this.context)}catch{}})}setupContextLossHandling(){this.canvas.addEventListener("webglcontextlost",this.handleContextLost),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored)}getContext(){if(this.isContextLost)return null;if(!this.context)try{this.context=this.canvas.getContext("2d")}catch{return null}return this.context}onRecovery(e){this.recoveryCallbacks.push(e)}isLost(){return this.isContextLost}recover(){if(!this.isContextLost)return!0;try{if(this.context=this.canvas.getContext("2d"),this.context)return this.isContextLost=!1,!0}catch{}return!1}destroy(){this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this.handleContextLost),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored),this.canvas=null),this.context=null,this.recoveryCallbacks=[]}}class Ja{constructor(){if(Ja._cachedBrowser)return this.browser=Ja._cachedBrowser,void(this.optimizations=Ja._cachedOptimizations);this.browser=this.detectBrowser(),this.optimizations=new Map,this.setupOptimizations(),Ja._cachedBrowser=this.browser,Ja._cachedOptimizations=this.optimizations}detectBrowser(){const{userAgent:e}=navigator;let t="unknown",i="unknown";if(e.includes("Chrome")){t="chrome";const s=e.match(/Chrome\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Firefox")){t="firefox";const s=e.match(/Firefox\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Safari")&&!e.includes("Chrome")){t="safari";const s=e.match(/Version\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Edge")){t="edge";const s=e.match(/Edge\/(\d+)/);i=s?s[1]:"unknown"}return{name:t,version:i,userAgent:e}}setupOptimizations(){this.optimizations.set("chrome",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"interactive"},canvasOptimizations:["willReadFrequently"],particleLimit:50}),this.optimizations.set("firefox",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"balanced"},canvasOptimizations:[],particleLimit:40}),this.optimizations.set("safari",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"playback"},canvasOptimizations:[],particleLimit:30}),this.optimizations.set("edge",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"interactive"},canvasOptimizations:["willReadFrequently"],particleLimit:45})}getOptimizations(){return this.optimizations.get(this.browser.name)||this.optimizations.get("chrome")}getBrowser(){return{...this.browser}}applyCanvasOptimizations(e,t){if(this.getOptimizations().canvasOptimizations.includes("willReadFrequently"))try{e.getContext("2d",{willReadFrequently:!0})}catch{}}getRecommendedParticleLimit(){return this.getOptimizations().particleLimit}getAudioContextOptions(){return this.getOptimizations().audioContextOptions}}let Ka=null;function Za(){if(Ka)return Ka;const e=new Ua,t=new Va,i=new Ja;t.register("requestAnimationFrame",Ya),t.register("performanceNow",Xa),t.register("webAudio",Na);const s=[];return e.features.requestAnimationFrame||t.apply("requestAnimationFrame")&&s.push("requestAnimationFrame"),e.features.performance||t.apply("performanceNow")&&s.push("performanceNow"),e.features.webAudio||t.apply("webAudio")&&s.push("webAudio"),Ka={featureDetection:e,polyfillManager:t,browserOptimizations:i,appliedPolyfills:s,capabilities:e.getCapabilities(),browser:i.getBrowser()},Ka}let er=null;function tr(){return er||(er=Za()),er}const ir=tr();function sr(e){const t=[];for(let i=0;i<e;i++){const s=i/e*Math.PI*2;t.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)})}return t}function nr(e,t=12){return sr(e)}const ar={circle:{points:sr(64),shadow:{type:"none"}},sphere:{points:sr(64),shadow:{type:"none"}},heart:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64*Math.PI*2,s=16*Math.pow(Math.sin(i),3),n=-(13*Math.cos(i)-5*Math.cos(2*i)-2*Math.cos(3*i)-Math.cos(4*i));e.push({x:.5+s/32,y:.5+n/32})}return e}(),shadow:{type:"none"}},star:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64,s=Math.floor(10*i),n=s%2==0,a=Math.floor(s/2);let r;r=n?(72*a-90)*Math.PI/180:(72*a+36-90)*Math.PI/180;const o=n?.5:.2;e.push({x:.5+Math.cos(r)*o,y:.5+Math.sin(r)*o})}return e}(0),shadow:{type:"none"}},sun:{points:nr(64,12),shadow:{type:"sun",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3}},moon:{points:sr(64),shadow:{type:"crescent",coverage:.85,angle:-30,softness:.05,offset:.7}},lunar:{points:sr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)",progression:"center"}},suspicion:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64*Math.PI*2;let s,n;if(i<Math.PI)s=.45*Math.cos(i),n=.45*Math.sin(i);else{const e=2*Math.PI-i;s=.25*Math.cos(e)-.1,n=.35*Math.sin(e)}e.push({x:.5+s,y:.5+n})}return e}(),shadow:{type:"none"}},eclipse:{points:sr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)"}},square:{points:function(){const e=[],t=Math.floor(16);for(let i=0;i<4;i++)for(let s=0;s<t;s++){const n=s/t;let a,r;switch(i){case 0:a=-.5+n,r=-.5;break;case 1:a=.5,r=-.5+n;break;case 2:a=.5-n,r=.5;break;case 3:a=-.5,r=.5-n}e.push({x:.5+.8*a,y:.5+.8*r})}return e}(),shadow:{type:"none"}},triangle:{points:function(){const e=[],t=[{x:0,y:-.5},{x:-.433,y:.25},{x:.433,y:.25}],i=[Math.sqrt(Math.pow(t[1].x-t[0].x,2)+Math.pow(t[1].y-t[0].y,2)),Math.sqrt(Math.pow(t[2].x-t[1].x,2)+Math.pow(t[2].y-t[1].y,2)),Math.sqrt(Math.pow(t[0].x-t[2].x,2)+Math.pow(t[0].y-t[2].y,2))],s=i[0]+i[1]+i[2],n=i.map(e=>Math.round(64*e/s)),a=n.reduce((e,t)=>e+t,0);a<64&&(n[0]+=64-a);for(let i=0;i<3;i++){const s=t[i],a=t[(i+1)%3],r=n[i];for(let t=0;t<r;t++){if(t===r-1&&i<2)continue;const n=t/r,o=s.x+(a.x-s.x)*n,l=s.y+(a.y-s.y)*n;e.push({x:.5+.9*o,y:.5+.9*l})}}for(;e.length<64;)e.push(e[e.length-1]);for(;e.length>64;)e.pop();return e}(),shadow:{type:"none"}},solar:{points:nr(64,12),shadow:{type:"solar-hybrid",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3,lunarOverlay:{type:"lunar",coverage:1,color:"rgba(0, 0, 0, 1.0)",progression:"center"}}}};const rr=new class{constructor(){this.shapeCache=new Map,this.morphCache=new Map,this.propertyCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1,this.loadStartTime=0,this.initialize()}initialize(){this.loadStartTime=performance.now();try{const e=Object.keys(ar);e.forEach(e=>{this.cacheShape(e)}),this.cacheCommonMorphs(e),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.shapeCache.size}catch(e){console.error("[ShapeCache] Initialization failed:",e),this.isInitialized=!1,console.warn("[ShapeCache] Running uninitialized โ lookups will return defaults")}}cacheShape(e){try{const t=ar[e];if(t){this.shapeCache.set(e,t);const i={pointCount:t.points?.length||64,hasShadow:"none"!==t.shadow?.type,shadowType:t.shadow?.type||"none",isRadial:this.isRadialShape(e),bounds:this.calculateBounds(t.points)};this.propertyCache.set(e,i)}}catch(t){console.warn(`[ShapeCache] Failed to cache shape '${e}':`,t)}}cacheCommonMorphs(e){[["circle","heart"],["circle","star"],["circle","square"],["heart","star"],["star","circle"],["square","circle"],["triangle","circle"],["moon","sun"],["lunar","eclipse"]].forEach(([t,i])=>{if(e.includes(t)&&e.includes(i))try{const e=this.calculateMorphSteps(t,i),s=`${t}->${i}`;this.morphCache.set(s,e)}catch(e){console.warn(`[ShapeCache] Failed to cache morph '${t}->${i}':`,e)}})}calculateMorphSteps(e,t){const i=this.shapeCache.get(e),s=this.shapeCache.get(t);if(!i||!s)return null;const n=[];for(let e=0;e<5;e++){const t=e/4,a=this.interpolateShapePoints(i.points,s.points,t);n.push({progress:t,points:a})}return{from:e,to:t,steps:n,isRadial:this.isRadialShape(e)||this.isRadialShape(t)}}interpolateShapePoints(e,t,i){if(!e||!t)return e||t||[];const s=Math.max(e.length,t.length),n=[];for(let a=0;a<s;a++){const s=e[a]||e[0]||{x:.5,y:.5},r=t[a]||t[0]||{x:.5,y:.5};n.push({x:s.x+(r.x-s.x)*i,y:s.y+(r.y-s.y)*i})}return n}isRadialShape(e){return["circle","star","square","triangle","sun","moon"].includes(e)}calculateBounds(e){if(!e||0===e.length)return{minX:0,minY:0,maxX:1,maxY:1,width:1,height:1};let t=1/0,i=1/0,s=-1/0,n=-1/0;return e.forEach(e=>{t=Math.min(t,e.x),i=Math.min(i,e.y),s=Math.max(s,e.x),n=Math.max(n,e.y)}),{minX:t,minY:i,maxX:s,maxY:n,width:s-t,height:n-i}}getShape(e){if(!this.isInitialized)return console.warn("[ShapeCache] Cache not initialized, falling back to direct access"),ar[e]||null;const t=this.shapeCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,ar[e]||null)}getProperties(e){if(!this.isInitialized){const t=ar[e];return t?{pointCount:t.points?.length||64,hasShadow:"none"!==t.shadow?.type,shadowType:t.shadow?.type||"none",isRadial:this.isRadialShape(e),bounds:this.calculateBounds(t.points)}:{}}const t=this.propertyCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,{})}getMorph(e,t){if(!this.isInitialized)return this.calculateMorphSteps(e,t);const i=`${e}->${t}`,s=this.morphCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,this.calculateMorphSteps(e,t))}hasShape(e){return this.shapeCache.has(e)}getStats(){const e=this.stats.hits+this.stats.misses;return{...this.stats,hitRate:e>0?`${(this.stats.hits/e*100).toFixed(1)}%`:"0%",shapes:this.shapeCache.size,morphs:this.morphCache.size,properties:this.propertyCache.size}}clear(){this.shapeCache.clear(),this.morphCache.clear(),this.propertyCache.clear(),this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1}},or=new class{constructor(){this.pools=new Map,this.inUse=new Set}acquire(e,t="array"){const i=`${t}_${e}`;this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);if(s.length>0){const e=s.pop();return this.inUse.add(e),e}let n;switch(t){case"float32":n=new Float32Array(e);break;case"uint8":n=new Uint8Array(e);break;default:n=new Array(e).fill(0)}return this.inUse.add(n),n}release(e){if(!this.inUse.has(e))return;this.inUse.delete(e);let t="array";e instanceof Float32Array?t="float32":e instanceof Uint8Array&&(t="uint8");const i=`${t}_${e.length}`;e.fill(0),this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);s.length<10&&s.push(e)}clear(){this.pools.clear(),this.inUse.clear()}};class lr{constructor(e){this.morpher=e,this.audioDeformation=0,this.vocalEnergy=0,this.vocalEffectActive=!1,this.beatGlitchIntensity=0,this.glitchPoints=[],this.bassEnergy=0,this.vocalPresence=0,this.highFreqEnergy=0,this.transientActive=!1,this.transientStrength=0,this.transientDecay=.92,this.transientHoldTime=8,this.transientHoldCounter=0}applyAudioDeformation(e){if(!e||0===e.length)return this.morpher.generateFallbackCircle();if(this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.currentFrequencies&&this.morpher.audioAnalyzer.currentFrequencies.length>0){this.morpher.frequencyData=[...this.morpher.audioAnalyzer.currentFrequencies];let e=0,t=0;for(let i=0;i<=2&&i<this.morpher.frequencyData.length;i++)e+=this.morpher.frequencyData[i],t++;t>0&&(e/=t),this.morpher.bassPeakHistory||(this.morpher.bassPeakHistory=[],this.morpher.bassThumpTimer=0),this.morpher.bassPeakHistory.push(e),this.morpher.bassPeakHistory.length>20&&this.morpher.bassPeakHistory.shift();const i=this.morpher.bassPeakHistory.reduce((e,t)=>e+t,0)/this.morpher.bassPeakHistory.length,s=this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.microphoneStream;if(e>1.08*i&&e>(s?.15:.25)){const t=s?8:6;this.bassEnergy=Math.min(1,(e-i)*t),this.morpher.bassThumpTimer=12}else this.morpher.bassThumpTimer>0?(this.morpher.bassThumpTimer--,this.bassEnergy*=.9):this.bassEnergy=0;this.morpher.spectralHistory||(this.morpher.spectralHistory=[],this.morpher.spectralFluxHistory=[],this.morpher.onsetThreshold=0,this.morpher.musicDetector.reset(),this.morpher.detectedBPM=0,this.morpher.onsetStrengths=[],this.morpher.detectedTimeSignature=null,this.morpher.timeSignatureConfidence=0,this.morpher.measureStartTime=0,this.morpher.timeSignatureHistory=[],this.morpher.timeSignatureLocked=!1);const n=[...this.morpher.frequencyData];let a=0,r=0;if(this.morpher.spectralHistory.length>0){const e=this.morpher.spectralHistory[this.morpher.spectralHistory.length-1];for(let t=0;t<=2&&t<n.length;t++){const i=n[t]-e[t];i>0&&(r+=i)}for(let t=4;t<=15&&t<n.length;t++){const i=n[t]-e[t];i>0&&(a+=i*(t>=9&&t<=13?2:1))}r>.15&&(a*=.3)}if(this.morpher.spectralHistory.push(n),this.morpher.spectralHistory.length>30&&this.morpher.spectralHistory.shift(),this.morpher.spectralFluxHistory.push(a),this.morpher.spectralFluxHistory.length>30&&this.morpher.spectralFluxHistory.shift(),this.morpher.bassFluxHistory||(this.morpher.bassFluxHistory=[],this.morpher.bassOnsetThreshold=.05),this.morpher.bassFluxHistory.push(r),this.morpher.bassFluxHistory.length>30&&this.morpher.bassFluxHistory.shift(),this.morpher.spectralFluxHistory.length>=10){const e=[...this.morpher.spectralFluxHistory].sort((e,t)=>e-t),t=e[Math.floor(e.length/2)],i=e.reduce((e,t)=>e+t,0)/e.length;this.morpher.onsetThreshold=t+.5*(i-t)}if(this.morpher.bassFluxHistory.length>=10){const e=[...this.morpher.bassFluxHistory].sort((e,t)=>e-t),t=e[Math.floor(e.length/2)],i=e.reduce((e,t)=>e+t,0)/e.length;this.morpher.bassOnsetThreshold=t+.5*(i-t)}const o=a>1.2*this.morpher.onsetThreshold&&a>.02,l=r>1.5*this.morpher.bassOnsetThreshold&&r>.08;if(o&&(this.transientHoldTime=8,this.morpher.vocalGlowBoost=.3),l){const e=performance.now(),t={time:e,strength:r/(this.morpher.bassOnsetThreshold||1),bassWeight:r};this.morpher.onsetStrengths.push(t),this.morpher.onsetStrengths.length>40&&this.morpher.onsetStrengths.shift(),this.morpher.musicDetector.addOnset(e,r)}const h=performance.now();this.morpher.musicDetector.processFrequencyFrame&&this.morpher.musicDetector.processFrequencyFrame(this.morpher.frequencyData,h),this.morpher.musicDetector.update(h),this.morpher.detectedBPM=this.morpher.musicDetector.detectedBPM,this.morpher.bpmConfidence=this.morpher.musicDetector.bpmConfidence,this.morpher.detectedBPM>0&&this.morpher.bpmConfidence>.8&&this.morpher.forceFastDetection&&(this.morpher.forceFastDetection=!1),this.transientHoldTime>0&&this.transientHoldTime--,this.morpher.vocalGlowBoost>0&&(this.morpher.vocalGlowBoost*=.92),this.vocalPresence=a,this.morpher.bassHistory[this.morpher.historyIndex]=this.bassEnergy,this.morpher.vocalHistory[this.morpher.historyIndex]=this.vocalPresence,this.morpher.historyIndex=(this.morpher.historyIndex+1)%this.morpher.bassHistory.length,this.morpher.bassEffectActive=this.morpher.bassThumpTimer>0,this.morpher.lastVocalPresence=this.morpher.lastVocalPresence||0,this.morpher.lastVocalPresence=this.vocalPresence,this.vocalEffectActive=this.transientHoldTime>0}const t=this.morpher.frequencyData&&this.morpher.frequencyData.some(e=>e>.01);if(this.morpher.audioAnalyzer&&t||(this.audioDeformation>.15?(this.morpher.bassEffectActive=!0,this.bassEnergy=Math.min(1,.8*this.audioDeformation),(!this.morpher.bassThumpTimer||this.morpher.bassThumpTimer<=0)&&(this.morpher.bassThumpTimer=12)):this.morpher.bassThumpTimer>0&&(this.morpher.bassThumpTimer--,this.bassEnergy*=.9),this.vocalEnergy>.2&&(this.vocalEffectActive=!0,this.vocalPresence=this.vocalEnergy)),!t&&this.audioDeformation>.15&&!this.morpher.bassEffectActive&&(this.morpher.bassEffectActive=!0,this.bassEnergy=Math.max(this.bassEnergy,.8*this.audioDeformation),(!this.morpher.bassThumpTimer||this.morpher.bassThumpTimer<=0)&&(this.morpher.bassThumpTimer=12)),!(0!==this.audioDeformation||this.bassEnergy>.01||this.vocalPresence>.01))return e;const i=[];if(this.morpher.bassEffectActive&&(Math.random()<.05&&(this.morpher.undulationDirection*=-1),this.morpher.undulationPhase+=.08*this.morpher.undulationDirection),this.morpher.audioAnalyzer&&this.beatGlitchIntensity>0&&(this.beatGlitchIntensity*=.9),this.vocalEffectActive&&Math.random()<.2){this.glitchPoints=[];const t=2+Math.floor(2*Math.random());for(let i=0;i<t;i++)this.glitchPoints.push({index:Math.floor(Math.random()*e.length),intensity:.02+.03*Math.random(),decay:.94+.02*Math.random()})}this.glitchPoints=this.glitchPoints.filter(e=>(e.intensity*=e.decay,e.intensity>.01));for(let t=0;t<e.length;t++){const s=e[t];if(!s||void 0===s.x||void 0===s.y){const s=t/e.length*Math.PI*2;i.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)});continue}const n=s.x-.5,a=s.y-.5,r=Math.sqrt(n*n+a*a),o=Math.atan2(a,n),l=.12*Math.abs(this.audioDeformation);let h=0,c=0;if(this.morpher.bassEffectActive){const e=2,t=.25*this.bassEnergy;h=Math.sin(o*e+this.morpher.undulationPhase)*t,c=Math.sin(.5*this.morpher.undulationPhase)*this.bassEnergy*.08}let u=0;const d=this.glitchPoints.find(e=>e.index===t);if(d){const e=.015*Date.now(),i=Math.sin(e+.5*t)*Math.cos(.7*e);u=d.intensity*i*.5}const g=1+l+h+c+u,m=r*Math.max(.8,g);i.push({x:.5+Math.cos(o)*m,y:.5+Math.sin(o)*m})}return i}setAudioDeformation(e){this.audioDeformation=Math.max(0,Math.min(1,e)),this.vocalEffectActive=e>.01}setVocalEnergy(e){this.vocalEnergy=Math.max(0,Math.min(1,e)),this.vocalEffectActive=e>.01}updateFrequencyBands(e){e&&(this.bassEnergy=e.bass||0,this.vocalPresence=e.vocal||0,this.highFreqEnergy=e.high||0)}processTransient(e,t){e>t?(this.transientActive=!0,this.transientStrength=e,this.transientHoldCounter=this.transientHoldTime):this.transientHoldCounter>0?this.transientHoldCounter--:(this.transientStrength*=this.transientDecay,this.transientStrength<.01&&(this.transientActive=!1))}getState(){return{audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy,vocalEffectActive:this.vocalEffectActive,beatGlitchIntensity:this.beatGlitchIntensity,transientActive:this.transientActive,transientStrength:this.transientStrength}}reset(){this.audioDeformation=0,this.vocalEnergy=0,this.vocalEffectActive=!1,this.beatGlitchIntensity=0,this.glitchPoints=[],this.transientActive=!1,this.transientStrength=0}}class hr{constructor(){this.minBPM=60,this.maxBPM=180,this.lastPeakTime=0,this.peakCount=0,this.intervals=[],this.maxIntervals=40,this.bpmVotes=new Map,this.currentBPM=0,this.lockedBPM=0,this.confidence=0,this.isActive=!1,this.lockStage=0,this.stage1LockTime=0,this.stage2CorrectionApplied=!1,this.correctionType="none",this._recentSubdivisionChecks=[],this._stage3StartTime=0,this._stage3StableTime=0,this._memoryCleanedUp=!1,this._microTuneBPM=0,this.grooveConfidence=.15,this._grooveConfidenceTarget=.15,this._lastLogTime=0,this._logIntervalMs=2e3,this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0,this._logBuffer=[],this._maxLogEntries=20}processPeak(e,t=performance.now()){if(this.isActive=!0,this.peakCount++,e<.1)this._skippedPeaks++;else{if(this.lastPeakTime>0){const e=t-this.lastPeakTime;e>=250&&e<=2e3?(this.intervals.push(e),this._recentIntervals.push(Math.round(e)),this.intervals.length>this.maxIntervals&&this.intervals.shift(),this.voteForInterval(e)):this._skippedIntervals++}this.lastPeakTime=t,this.updateBPM(),this._debugLog(t)}}voteForInterval(e){const t=6e4/e;this._recentRawBPMs.push(Math.round(t));let i=t;const s=.95*this.minBPM,n=1.05*this.maxBPM;if(i<s)for(;i<this.minBPM;)i*=2;else if(i>n)for(;i>this.maxBPM;)i/=2;i=Math.max(this.minBPM,Math.min(this.maxBPM,i)),this._recentNormalizedBPMs.push(Math.round(i));const a=Math.round(i);for(let e=-2;e<=2;e++){const t=a+e;if(t>=this.minBPM&&t<=this.maxBPM){const i=Math.exp(-e*e/2),s=this.bpmVotes.get(t)||0;this.bpmVotes.set(t,s+i)}}for(const[e,t]of this.bpmVotes){const i=.95*t;i<.3?this.bpmVotes.delete(e):this.bpmVotes.set(e,i)}}updateBPM(){if(0===this.bpmVotes.size||this.intervals.length<3)return;const e=performance.now();let t=0,i=0,s=0;for(const[e,n]of this.bpmVotes)s+=n,n>i&&(i=n,t=e);if(0===t)return;let n=0;for(let e=-2;e<=2;e++){const i=t+e;n+=this.bpmVotes.get(i)||0}const a=n,r=Math.round(t/2);let o=0;if(r>=this.minBPM)for(let e=-2;e<=2;e++)o+=this.bpmVotes.get(r+e)||0;const l=2*t;let h=0;if(l<=this.maxBPM)for(let e=-2;e<=2;e++)h+=this.bpmVotes.get(l+e)||0;let c=0,u=0;const d=a>0?o/a:0;if(this.intervals.length>=6){const e=this.intervals.slice(-8),t=e.reduce((e,t)=>e+t,0)/e.length;let i=0;for(let s=0;s<e.length-1;s++)e[s]>t!=e[s+1]>t&&i++;c=i/(e.length-1);const s=[];for(let t=0;t<e.length-1;t+=2)s.push(e[t]+e[t+1]);if(s.length>=2){const e=s.reduce((e,t)=>e+t,0)/s.length;u=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}this.confidence=s>0?a/s:0;let g=0;if(this.intervals.length>=4){const e=6e4/t,i=e/2,s=this.intervals.slice(-8);let n=0;for(const t of s){const s=Math.abs(t-e)/e<.15,a=Math.abs(t-i)/i<.15,r=Math.abs(t-2*e)/(2*e)<.15;(s||a||r)&&n++}g=n/s.length}if(0===this.currentBPM)this.currentBPM=t;else{const e=this.intervals.length<6?.5:.3;this.currentBPM=this.currentBPM*(1-e)+t*e}if(0===this.lockStage){this._lastLockCheck={intervalCount:this.intervals.length,bestVotes:i.toFixed(1),clusterVotes:a.toFixed(1),confidence:`${(100*this.confidence).toFixed(0)}%`,consistency:`${(100*g).toFixed(0)}%`,bestBPM:t,adjustedBPM:t,isSubdivision:!1,stage:0,failReasons:[]};const s=t>120?12:8,n=.2,r=.45;this.intervals.length<s&&this._lastLockCheck.failReasons.push(`intervals<${s}`),a<=5&&this._lastLockCheck.failReasons.push("votes<=5"),this.confidence<=n&&this._lastLockCheck.failReasons.push(`conf<=${(100*n).toFixed(0)}%`),g<=r&&this._lastLockCheck.failReasons.push(`consistency<=${(100*r).toFixed(0)}%`),this.intervals.length>=s&&a>5&&this.confidence>n&&g>r&&(this.lockedBPM=Math.round(this.currentBPM),this.lockStage=1,this.stage1LockTime=e)}if(1===this.lockStage||2===this.lockStage){this._recentSubdivisionChecks.push({alternatingScore:c,pairVariance:u,halfVoteRatio:d,time:e}),this._recentSubdivisionChecks.length>15&&this._recentSubdivisionChecks.shift();const i=this._recentSubdivisionChecks.filter(e=>e.alternatingScore>.7&&e.pairVariance<.1).length,s=this._recentSubdivisionChecks.reduce((e,t)=>e+t.alternatingScore,0)/this._recentSubdivisionChecks.length,n=this._recentSubdivisionChecks.reduce((e,t)=>e+t.pairVariance,0)/this._recentSubdivisionChecks.length,o=this._recentSubdivisionChecks.reduce((e,t)=>e+t.halfVoteRatio,0)/this._recentSubdivisionChecks.length,g=this.intervals.length>0?this.intervals.reduce((e,t)=>e+t,0)/this.intervals.length:0,m=a>0?h/a:0;let p=0,f=0;if(this.intervals.length>=8){const e=this.intervals.slice(-12),t=[...e].sort((e,t)=>e-t),i=t[Math.floor(t.length/2)],s=e.filter(e=>Math.abs(e-i)/i<.5);if(f=s.length,s.length>=6){const e=s.reduce((e,t)=>e+t,0)/s.length;p=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}if(this._lastLockCheck={intervalCount:this.intervals.length,bestBPM:t,adjustedBPM:this.lockedBPM,halfBPM:r,stage:this.lockStage,subdivisionChecks:this._recentSubdivisionChecks.length,positiveChecks:i,avgAltScore:`${(100*s).toFixed(0)}%`,avgPairVar:`${(100*n).toFixed(1)}%`,avgHalfRatio:`${(100*o).toFixed(0)}%`,intervalVariance:`${(100*p).toFixed(1)}%`,filteredCount:f,correctionApplied:this.stage2CorrectionApplied,failReasons:[]},!this.stage2CorrectionApplied&&this._recentSubdivisionChecks.length>=10&&r>=this.minBPM){const e=i>=7&&s>.7&&n<.1&&this.lockedBPM>100,t=o>.4&&this.lockedBPM>150&&r>=65&&r<=85;let a=0,l=0;if(this.intervals.length>=8){const e=this.intervals.slice(-12),t=[...e].sort((e,t)=>e-t),i=t[Math.floor(t.length/2)],s=e.filter(e=>Math.abs(e-i)/i<.5);if(l=s.length,s.length>=6){const e=s.reduce((e,t)=>e+t,0)/s.length;a=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}const h=this.lockedBPM>140&&r>=65&&r<=85&&l>=8&&a<.05;(e||t||h)&&(this.lockedBPM=Math.round(this.lockedBPM/2),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="halved")}!this.stage2CorrectionApplied&&this._recentSubdivisionChecks.length>=10&&l<=this.maxBPM&&g>900&&m>.5&&this.lockedBPM<75&&(this.lockedBPM=Math.round(2*this.lockedBPM),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="doubled");const y=e-this.stage1LockTime;1===this.lockStage&&this._recentSubdivisionChecks.length>=6&&(this.lockStage=2);const b=this._recentSubdivisionChecks.length>=12&&i<3,v=y>1e4;2===this.lockStage&&(this.stage2CorrectionApplied||b||v)&&(this.lockStage=3,this._stage3StartTime=e)}if(3===this.lockStage){const t=e-this._stage3StartTime,i=this.intervals.slice(-8);if(i.length>=4){const e=6e4/(i.reduce((e,t)=>e+t,0)/i.length);if(Math.abs(e-this.lockedBPM)/this.lockedBPM<.05){0===this._microTuneBPM&&(this._microTuneBPM=this.lockedBPM),this._microTuneBPM=.9*this._microTuneBPM+.1*e;const t=Math.round(this._microTuneBPM);t!==this.lockedBPM&&(this.lockedBPM=t),this._stage3StableTime+=100}else this._stage3StableTime=0}const s=(t>5e3||this._stage3StableTime>3e3)&&!this._memoryCleanedUp;s&&3===this.lockStage&&(this._performMemoryCleanup(),this._memoryCleanedUp=!0),this._lastLockCheck={stage:3,lockedBPM:this.lockedBPM,correctionType:this.correctionType,timeSinceStage3:`${(t/1e3).toFixed(1)}s`,stableTime:`${(this._stage3StableTime/1e3).toFixed(1)}s`,finalized:s,failReasons:[]}}this._updateGrooveConfidence()}_updateGrooveConfidence(){this._memoryCleanedUp?this._grooveConfidenceTarget=1:this._grooveConfidenceTarget=[.15,.4,.65,.85][this.lockStage]||.15;const e=this.grooveConfidence+.08*(this._grooveConfidenceTarget-this.grooveConfidence);e>this.grooveConfidence&&(this.grooveConfidence=e)}_performMemoryCleanup(){this.intervals.length>8&&(this.intervals=this.intervals.slice(-8)),this.bpmVotes.clear(),this._subdivisionHistory=[],this._recentSubdivisionChecks=[],this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[]}processFrame(e,t=performance.now()){}reset(){this.intervals=[],this.bpmVotes.clear(),this.lastPeakTime=0,this.peakCount=0,this.currentBPM=0,this.lockedBPM=0,this.confidence=0,this.isActive=!1,this.lockStage=0,this.stage1LockTime=0,this.stage2CorrectionApplied=!1,this.correctionType="none",this._recentSubdivisionChecks=[],this._stage3StartTime=0,this._stage3StableTime=0,this._memoryCleanedUp=!1,this._microTuneBPM=0,this.grooveConfidence=.15,this._grooveConfidenceTarget=.15,this._lastLogTime=0,this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0,this._logBuffer=[],this._lastLockCheck=null,this._subdivisionHistory=[]}getBPM(){return this.lockedBPM>0?this.lockedBPM:Math.round(this.currentBPM)||0}getSubdivision(){return 1}getStatus(){return{bpm:this.getBPM(),subdivision:1,confidence:this.confidence,locked:this.lockedBPM>0,lockStage:this.lockStage,correctionType:this.correctionType,finalized:this._memoryCleanedUp,grooveConfidence:this.grooveConfidence,agentCount:this.bpmVotes.size,peakCount:this.peakCount,histogramSize:this.bpmVotes.size,topAgents:this.getTopCandidates(5),intervalCount:this.intervals.length}}getTopCandidates(e=5){return[...this.bpmVotes.entries()].sort((e,t)=>t[1]-e[1]).slice(0,e).map(([e,t])=>({bpm:e,score:t.toFixed(1),interval:Math.round(6e4/e)}))}getTopIntervals(e=5){return this.getTopCandidates(e).map(e=>({interval:e.interval,bpm:e.bpm,weight:e.score}))}_debugLog(e){if(e-this._lastLogTime<this._logIntervalMs)return;if(this._lastLogTime=e,0===this._recentIntervals.length&&0===this._skippedPeaks)return;const t=[],i=["Detecting","Initial Lock","Refinement","Final Lock"][this.lockStage]||"Unknown";t.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"),t.push(`Status: Stage ${this.lockStage} (${i}) | Current: ${Math.round(this.currentBPM)} BPM | Locked: ${this.lockedBPM||"-"}`),t.push(`Peaks: ${this.peakCount} total | ${this._skippedPeaks} skipped (weak) | ${this._skippedIntervals} intervals out-of-range`),this._recentIntervals.length>0&&t.push(`Recent intervals (ms): [${this._recentIntervals.join(", ")}]`),this._recentRawBPMs.length>0&&t.push(`Raw BPMs (before normalize): [${this._recentRawBPMs.join(", ")}]`),this._recentNormalizedBPMs.length>0&&t.push(`Normalized BPMs (60-180): [${this._recentNormalizedBPMs.join(", ")}]`);const s=this.getTopCandidates(5);if(s.length>0){const e=s.map(e=>`${e.bpm}(${e.score})`).join(", ");t.push(`Top candidates: ${e}`)}if(this._lastLockCheck){const e=this._lastLockCheck;0===e.stage?e.failReasons&&e.failReasons.length>0?t.push(`Stage 0: NOT locking - ${e.failReasons.join(", ")}`):t.push(`Stage 0: Ready to lock at ${e.bestBPM} BPM`):1===e.stage||2===e.stage?(t.push(`Stage ${e.stage}: Locked=${e.adjustedBPM} BPM | checks=${e.subdivisionChecks} positive=${e.positiveChecks}`),t.push(` altScore=${e.avgAltScore} pairVar=${e.avgPairVar} halfRatio=${e.avgHalfRatio}`),e.correctionApplied&&t.push(` Correction applied: ${this.correctionType}`)):3===e.stage&&(t.push(`Stage 3: Final=${e.lockedBPM} BPM | correction=${e.correctionType} | time=${e.timeSinceStage3} stable=${e.stableTime}`),e.finalized&&t.push(" FINALIZED - memory cleaned"))}if(this.intervals.length>=6){const e=this.intervals.slice(-8),i=e.reduce((e,t)=>e+t,0)/e.length,s=(e.reduce((e,t)=>e+Math.abs(t-i),0)/e.length/i*100).toFixed(1);let n=0;for(let t=0;t<e.length-1;t++)e[t]>i!=e[t+1]>i&&n++;const a=(n/(e.length-1)*100).toFixed(0);t.push(`Interval pattern: variance=${s}% alternating=${a}% (>70% triggers subdivision)`)}const n=[...this.intervals].map(e=>Math.round(e));if(n.length>0){const e=Math.min(...n),i=Math.max(...n),s=Math.round(n.reduce((e,t)=>e+t,0)/n.length);t.push(`Interval buffer (${n.length}/${this.maxIntervals}): min=${e}ms max=${i}ms avg=${s}ms (=${Math.round(6e4/s)} BPM)`)}t.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ");const a=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});for(this._logBuffer.push({time:a,lines:t});this._logBuffer.length>this._maxLogEntries;)this._logBuffer.shift();this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0}getDebugLog(){if(0===this._logBuffer.length)return"No BPM debug logs yet. Play audio to generate logs.";let e="=== BPM Debug Log ===\n\n";for(const t of this._logBuffer){e+=`[${t.time}]\n`;for(const i of t.lines)e+=`${i}\n`;e+="\n"}return e}clearDebugLog(){this._logBuffer=[]}}class cr{constructor(){this.onsetIntervals=[],this.onsetStrengths=[],this.lastOnsetTime=0,this.onsetThreshold=.3,this.detectedBPM=0,this.bpmConfidence=0,this.lastBPMCalculation=0,this.bpmCalculationInterval=2e3,this.bpmHistory=[],this.tempoLocked=!1,this.fundamentalBPM=0,this.agentDetector=new hr,this.useAgentDetection=!0,this.timeSignature="4/4",this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.timeSignatureHistory=[],this.timeSignatureLocked=!1,this.downbeatPhase=0,this.measureLength=4,this.measureStartTime=0,this.isMusicalContent=!1,this.musicalityScore=0,this.forceFastDetection=!1}calculateBPM(){if(this.useAgentDetection){const e=this.agentDetector.getStatus();if(e.locked&&e.confidence>.6)return this.detectedBPM=e.bpm,this.bpmConfidence=e.confidence,this.tempoLocked=!0,this.fundamentalBPM=e.bpm,this.bpmHistory.push(this.detectedBPM),this.bpmHistory.length>10&&this.bpmHistory.shift(),this.detectedBPM;if(e.bpm>0&&e.confidence>.4)return this.detectedBPM=e.bpm,this.bpmConfidence=e.confidence,e.confidence>.6&&(this.tempoLocked=!0),this.detectedBPM}if(this.onsetIntervals.length<4)return this.detectedBPM;const e=this.onsetIntervals.slice(-15),t=this.findTempoCandidates(e);if(0===t.length)return this.detectedBPM;const i=t[0],s=Math.round(6e4/i.interval);if(!this.tempoLocked&&this.bpmHistory.length>3){const e=this.bpmHistory.slice(-3),t=e.reduce((e,t)=>e+t,0)/e.length;e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length<5&&(this.fundamentalBPM=Math.round(t),this.tempoLocked=!0,this.bpmConfidence=1)}let n=s;if(this.tempoLocked&&(this.checkHarmonicRelation(s,this.fundamentalBPM)?(n=this.fundamentalBPM,this.bpmConfidence=Math.min(1,this.bpmConfidence+.1)):(this.bpmConfidence*=.9,this.bpmConfidence<.3&&i.strength>.8?(this.fundamentalBPM=s,this.bpmConfidence=.5):n=this.fundamentalBPM)),this.bpmHistory.push(n),this.bpmHistory.length>10&&this.bpmHistory.shift(),0===this.detectedBPM)this.detectedBPM=n;else{const e=this.tempoLocked?1:2,t=n-this.detectedBPM;Math.abs(t)<=e?this.detectedBPM=n:this.detectedBPM+=Math.sign(t)*e}return window.rhythmIntegration&&window.rhythmIntegration.updateBPM&&(window.rhythmManuallyStoppedForCurrentAudio||window.rhythmIntegration.updateBPM(this.detectedBPM)),this.detectedBPM}findTempoCandidates(e){const t=[];for(const i of[1,2,4]){const s=e.map(e=>e*i),n=this.clusterIntervals(s);for(const s of n){const n=s.intervals.reduce((e,t)=>e+t,0)/s.intervals.length/i,a=s.intervals.length/e.length*s.consistency,r=6e4/n,o=r>=120&&r<=140?.2:0;r>=60&&r<=220&&t.push({interval:n,strength:a+o,multiplier:i})}}return t.sort((e,t)=>t.strength-e.strength)}clusterIntervals(e){const t=[...e].sort((e,t)=>e-t),i=[];let s=[t[0]];for(let e=1;e<t.length;e++){const n=.03*s[0];if(t[e]-s[0]<=n)s.push(t[e]);else{if(s.length>=2){const e=s.reduce((e,t)=>e+t,0)/s.length,t=1/(1+s.reduce((t,i)=>t+Math.pow(i-e,2),0)/s.length/(e*e));i.push({intervals:s,consistency:t})}s=[t[e]]}}if(s.length>=3){const e=s.reduce((e,t)=>e+t,0)/s.length,t=1/(1+s.reduce((t,i)=>t+Math.pow(i-e,2),0)/s.length/(e*e));i.push({intervals:s,consistency:t})}return i}checkHarmonicRelation(e,t){const i=Math.max(e,t)/Math.min(e,t);return[2,1.5,1.333,1.25].some(e=>Math.abs(i-e)<.03)}detectTimeSignature(){const e=this.forceFastDetection?6:12;if(0===this.detectedBPM||this.onsetStrengths.length<e)return this.timeSignature;if(this.timeSignatureLocked&&!this.forceFastDetection)return this.detectedTimeSignature||this.timeSignature;const t=6e4/this.detectedBPM,i=new Array(4).fill(0).map(()=>({strength:0,bassWeight:0,count:0})),s=this.onsetStrengths.slice(-Math.min(20,this.onsetStrengths.length));if(0===s.length)return this.timeSignature;const n=s[0].time;for(const e of s){const s=(e.time-n)/t%4,a=Math.round(s)%4;i[a].strength+=e.strength,i[a].bassWeight+=e.bassWeight||0,i[a].count++}let a=0;for(const e of i)e.count>0&&(e.strength/=e.count,e.bassWeight/=e.count,a=Math.max(a,e.strength+e.bassWeight));let r="4/4";i[0].strength>2*i[1].strength&&i[0].strength>2*i[2].strength&&i[3].count<.5*i[0].count&&this.testWaltzPattern(s,t)>.8&&(r="3/4"),this.timeSignatureHistory.push(r),this.timeSignatureHistory.length>3&&this.timeSignatureHistory.shift();const o=this.forceFastDetection?2:3;if(this.timeSignatureHistory.length>=o){const e={};for(const t of this.timeSignatureHistory)e[t]=(e[t]||0)+1;let t="4/4",i=0;for(const[s,n]of Object.entries(e))n>i&&(i=n,t=s);if(i>=2){this.detectedTimeSignature=t,this.timeSignatureLocked=!0,this.timeSignatureConfidence=i/3,window.rhythmIntegration&&window.rhythmIntegration.setTimeSignature&&window.rhythmIntegration.setTimeSignature(this.detectedTimeSignature);const e=document.getElementById("time-sig-display");e&&(e.textContent=this.detectedTimeSignature)}}return this.detectedTimeSignature||this.timeSignature}testWaltzPattern(e,t){let i=0,s=0;for(let t=0;t<e.length-2;t+=3)if(t+2<e.length){s++;const n=e[t].strength+(e[t].bassWeight||0),a=e[t+1].strength+(e[t+1].bassWeight||0),r=e[t+2].strength+(e[t+2].bassWeight||0);n>1.5*a&&n>1.5*r&&i++}return s>0?i/s:0}processFrequencyFrame(e,t=performance.now()){this.useAgentDetection&&this.agentDetector.processFrame&&this.agentDetector.processFrame(e,t)}addOnset(e,t,i=0){if(this.useAgentDetection&&this.agentDetector.processPeak(t,e),this.lastOnsetTime>0){const t=e-this.lastOnsetTime;t>273&&t<1e3&&(this.onsetIntervals.push(t),this.onsetIntervals.length>20&&this.onsetIntervals.shift())}this.onsetStrengths.push({time:e,strength:t,bassWeight:i}),this.onsetStrengths.length>40&&this.onsetStrengths.shift(),this.lastOnsetTime=e}update(e){e-this.lastBPMCalculation>this.bpmCalculationInterval&&(this.calculateBPM(),this.detectTimeSignature(),this.lastBPMCalculation=e)}getRecommendedSubdivision(){return this.useAgentDetection?this.agentDetector.getSubdivision():this.detectedBPM<60?2:this.detectedBPM<80?1:this.detectedBPM>180||this.detectedBPM>140?.5:1}reset(){this.onsetIntervals=[],this.onsetStrengths=[],this.lastOnsetTime=0,this.detectedBPM=0,this.bpmConfidence=0,this.bpmHistory=[],this.tempoLocked=!1,this.fundamentalBPM=0,this.timeSignature="4/4",this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.timeSignatureHistory=[],this.agentDetector&&this.agentDetector.reset(),this.timeSignatureLocked=!1,this.isMusicalContent=!1,this.forceFastDetection=!1}getMusicInfo(){return{bpm:this.detectedBPM,confidence:this.bpmConfidence,timeSignature:this.timeSignature,isMusical:this.isMusicalContent,musicalityScore:this.musicalityScore}}}class ur{constructor(e){this.morpher=e,this.isTransitioning=!1,this.transitionStartTime=0,this.transitionDuration=800,this.transitionProgress=0,this.easingFunction="easeInOutQuad",this.currentShape="circle",this.targetShape=null,this.previousShape=null,this.morphQueue=[],this.maxQueueSize=3,this.shadowConfig=null,this.shadowProgress=0}startTransition(e,t={}){this.isTransitioning&&this.morphQueue.length<this.maxQueueSize?this.morphQueue.push({shape:e,options:t}):(this.previousShape=this.currentShape,this.targetShape=e,this.isTransitioning=!0,this.transitionStartTime=performance.now(),this.transitionDuration=t.duration||800,this.easingFunction=t.easing||"easeInOutQuad",this.transitionProgress=0,this.shadowConfig=this.getTransitionConfig(this.currentShape,e))}update(e){if(!this.isTransitioning)return;const t=performance.now()-this.transitionStartTime,i=Math.min(1,t/this.transitionDuration);this.transitionProgress=this.applyEasing(i),this.shadowConfig&&(this.shadowProgress=this.calculateShadowProgress(i)),i>=1&&this.completeTransition()}completeTransition(){if(this.currentShape=this.targetShape,this.targetShape=null,this.isTransitioning=!1,this.transitionProgress=0,this.shadowConfig=null,this.morphQueue.length>0){const e=this.morphQueue.shift();this.startTransition(e.shape,e.options)}}getTransitionConfig(e,t){return{"circle-heart":{type:"bloom",shadowColor:"#ff69b4",shadowIntensity:.3},"heart-circle":{type:"contract",shadowColor:"#ff69b4",shadowIntensity:.2},"circle-star":{type:"burst",shadowColor:"#ffd700",shadowIntensity:.4},"star-circle":{type:"collapse",shadowColor:"#ffd700",shadowIntensity:.3}}[`${e}-${t}`]||null}calculateShadowProgress(e){if(!this.shadowConfig)return 0;switch(this.shadowConfig.type){case"bloom":return e<.5?2*e:2-2*e;case"burst":return Math.pow(1-e,2);case"contract":case"collapse":return Math.sin(e*Math.PI);default:return 0}}applyEasing(e){switch(this.easingFunction){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return e*(2-e);case"easeInOutQuad":return e<.5?2*e*e:(4-2*e)*e-1;case"easeInCubic":return e*e*e;case"easeOutCubic":return--e*e*e+1;case"easeInOutCubic":return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}}clearQueue(){this.morphQueue=[]}hasQueuedMorphs(){return this.morphQueue.length>0}getState(){return{isTransitioning:this.isTransitioning,currentShape:this.currentShape,targetShape:this.targetShape,progress:this.transitionProgress,queueLength:this.morphQueue.length}}reset(){this.isTransitioning=!1,this.currentShape="circle",this.targetShape=null,this.transitionProgress=0,this.morphQueue=[],this.shadowConfig=null}}class dr{constructor(e){this._getMorpherState=e}getCurrentShadow(){const e=this._getMorpherState(),t=e.currentShape||"circle",i=rr&&rr.isInitialized?rr.getShape(t):ar[t],s=e.targetShape?rr&&rr.isInitialized?rr.getShape(e.targetShape):ar[e.targetShape]:null,n=i?.shadow||{type:"none"},a=s?.shadow||null;if(!e.isTransitioning||!a)return n;const r=e.morphProgress;if(e.transitionConfig&&"from_moon"===e.transitionConfig.type&&e.transitionConfig.slideOutCrescent)return this._calculateMoonSlideOut(r,e.transitionConfig);if(e.transitionConfig&&"moon_to_lunar"===e.transitionConfig.type)return this._calculateMoonToLunar(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_enter_lunar"===e.transitionConfig.type)return this._calculateEclipseEnterLunar(r,e.transitionConfig);if(e.transitionConfig&&"lunar_to_moon"===e.transitionConfig.type)return this._calculateLunarToMoon(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_exit_lunar"===e.transitionConfig.type)return this._calculateEclipseExitLunar(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_enter"===e.transitionConfig.type)return this._calculateEclipseEnter(r,a);if("eclipse_exit"===e.transitionConfig.type)return this._calculateEclipseExit(r,n);if("sun_fade"===e.transitionConfig.type)return this._calculateSunFade(r,n);if("sun_bloom"===e.transitionConfig.type)return this._calculateSunBloom(r,a);if("none"!==n.type||"none"!==a.type){const e=(n.coverage||0)+((a.coverage||0)-(n.coverage||0))*r;return{type:"none"!==a.type?a.type:n.type,coverage:e,angle:a.angle||n.angle||0,softness:a.softness||n.softness||.2,progress:r}}return n}_calculateMoonSlideOut(e,t){const i=t.shadowSlideRatio||.4;if(e<i){const t=e/i,s=-30*Math.PI/180,n=.7,a=n+(2.5-n)*t;return{type:"crescent",coverage:t>.8?.85*(1-5*(t-.8)):.85,angle:-30,offset:a,shadowX:Math.cos(s)*a,shadowY:Math.sin(s)*a}}return{type:"none"}}_calculateMoonToLunar(e,t){const i=t.startAngle*Math.PI/180,s=1-e,n=.7*Math.cos(i)*s,a=.7*Math.sin(i)*s,r=Math.pow(e,2);if(e<.6)return{type:"crescent",coverage:.85*(1-.2*r),angle:t.startAngle,offset:.7*s,shadowX:n,shadowY:a};{const t=(e-.6)/.4,i=Math.sin(t*Math.PI/2);return{type:"lunar",coverage:.85+.1*i,color:`rgba(80, 20, 0, ${.7+.2*i})`,shadowX:n*(1-i),shadowY:a*(1-i),diffusion:i,shadowProgress:e}}}_calculateEclipseEnterLunar(e,t){if(e<.3)return{type:"none"};const i=(e-.3)/.7,s=Math.sin(i*Math.PI/2),n=t.startAngle*Math.PI/180,a=1-s,r=.7*Math.cos(n)*a,o=.7*Math.sin(n)*a;if(i<.7)return{type:"crescent",coverage:.85*Math.pow(i/.7,.5),angle:t.startAngle,offset:.7*a,shadowX:r,shadowY:o};{const e=(i-.7)/.3,t=Math.sin(e*Math.PI/2);return{type:"lunar",coverage:.85+.1*t,color:`rgba(80, 20, 0, ${.6+.3*t})`,shadowX:r*(1-t),shadowY:o*(1-t),diffusion:t,shadowProgress:i}}}_calculateLunarToMoon(e,t){const i=t.exitAngle*Math.PI/180,s=Math.sin(e*Math.PI/2),n=.7*Math.cos(i)*s,a=.7*Math.sin(i)*s;if(e<.6){const t=e/.6,i=Math.pow(t,.7);return{type:"lunar",coverage:.95-.1*i,color:`rgba(80, 20, 0, ${.9-.3*i})`,shadowX:.7*n,shadowY:.7*a,diffusion:1-i}}{const i=(e-.6)/.4;return{type:"crescent",coverage:.85*Math.sin(i*Math.PI/2)+.1,angle:t.exitAngle,offset:.7,shadowX:n,shadowY:a}}}_calculateEclipseExitLunar(e,t){if(e<.7){const i=e/.7,s=t.exitAngle*Math.PI/180;if(i<.4){const e=i/.4,t=1-e,n=.3*e;return{type:"lunar",coverage:.95-.1*e,color:`rgba(80, 20, 0, ${.9-.2*e})`,shadowX:.7*Math.cos(s)*n,shadowY:.7*Math.sin(s)*n,diffusion:t}}{const e=(i-.4)/.6,n=Math.pow(e,.8),a=.7*Math.cos(s)*n,r=.7*Math.sin(s)*n;return{type:"crescent",coverage:.85*(1-Math.pow(e,2)),angle:t.exitAngle,offset:.7*n,shadowX:a,shadowY:r}}}return{type:"none"}}_calculateEclipseEnter(e,t){return{...t,shadowX:1.5-1.5*e,shadowProgress:e}}_calculateEclipseExit(e,t){const i=1.5*-e;return{...t,coverage:t.coverage*(1-e),shadowX:i,shadowProgress:1-e}}_calculateSunFade(e,t){const i=1-e;return{...t,intensity:(t.intensity||1)*Math.pow(i,.7),corona:t.corona,coronaOpacity:i,flares:t.flares,flaresOpacity:Math.pow(i,1.5),texture:t.texture,textureOpacity:Math.pow(i,2),turbulence:(t.turbulence||.3)*i}}_calculateSunBloom(e,t){const i=e;return{...t,intensity:(t.intensity||1)*Math.pow(i,1.5),corona:t.corona,coronaOpacity:Math.pow(i,.8),flares:t.flares,flaresOpacity:i>.3?Math.pow((i-.3)/.7,.7):0,texture:t.texture,textureOpacity:i>.5?Math.pow((i-.5)/.5,2):0,turbulence:(t.turbulence||.3)*i}}}class gr{constructor(e={}){this.numPoints=e.numPoints||64,this.morphDuration=e.morphDuration||1e3,this.easing=e.easing||"easeInOutCubic",this.transitionManager=new ur(this),this.audioDeformer=new lr(this),this.musicDetector=new cr,this.shadowEffectManager=new dr(()=>({currentShape:this.currentShape,targetShape:this.targetShape,morphProgress:this.morphProgress,isTransitioning:this.isTransitioning,transitionConfig:this.transitionConfig})),this.currentShape="circle",this.targetShape=null,this.morphProgress=0,this.visualProgress=0,this.morphStartTime=null,this.isTransitioning=!1,this.queuedMorphTimeout=null,this.shapeCache=new Map,this.currentPoints=[],this.targetPoints=[],this.musicalDuration=null,this.onBeat=!1,this.audioDeformation=0,this.vocalEnergy=0,this.lastAudioUpdate=0,this.lastVocalUpdate=0,this.audioUpdateInterval=33,this.audioAnalyzer=null,this.frequencyData=or.acquire(32,"float32"),this.glitchPoints=[],this.undulationPhase=0,this.undulationDirection=1,this.beatGlitchIntensity=0,this.bassEnergy=0,this.vocalPresence=0,this.bassHistory=or.acquire(60,"float32"),this.vocalHistory=or.acquire(60,"float32"),this.historyIndex=0,this.bassEffectCooldown=0,this.vocalEffectCooldown=0,this.bassThresholdMultiplier=1.2,this.vocalThresholdMultiplier=1.1,this.bassEffectActive=!1,this.vocalEffectActive=!1,this.transientHoldTime=0,this.vocalGlowBoost=0,this.onComplete=null,this.onProgress=null,this.queuedMorph=null,this.currentPoints=this.getShapePoints("circle"),this.shapesLoaded=!0,this.prewarmCache()}prewarmCache(){["circle","heart","star","sun","moon","lunar","square","triangle"].forEach(e=>{(rr&&rr.isInitialized?rr.hasShape(e):ar[e])&&this.getShapePoints(e)}),[0,.25,.5,.75,1].forEach(e=>{this.applyEasing(e)})}getShapePoints(e){if(!this.shapeCache.has(e)){const t=rr&&rr.isInitialized?rr.getShape(e):ar[e];if(!t||!t.points){const t=ar.circle.points;return this.shapeCache.set(e,t),t}const{points:i}=t;return this.shapeCache.set(e,i),i}return this.shapeCache.get(e)}morphTo(e,t={}){if(!this.shapesLoaded)return;if(e===this.currentShape&&!this.isTransitioning)return;if(this.isTransitioning&&!t.force)return this.queuedMorph={targetShape:e,options:t},"queued";this.isTransitioning&&t.force&&this.completeMorph(!0);const i=this.getTransitionConfig(this.currentShape,e);if(this.targetShape=e,this.targetPoints=this.getShapePoints(e),this.morphStartTime=Date.now(),this.isTransitioning=!0,this.morphProgress=0,this.visualProgress=0,"bar"===t.duration||"beat"===t.duration){const e=6e4/(sn.bpm||120);"bar"===t.duration?this.morphDuration=4*e:this.morphDuration=e,this.musicalDuration=!0,this.onBeat=!1!==t.onBeat}else this.morphDuration=i?.duration||t.duration||1e3,this.musicalDuration=null,this.onBeat=!1;this.morphMode=t.mode||"smooth",this.transitionConfig=i,this.onComplete=t.onComplete,this.onProgress=t.onProgress}update(e){if(this.audioAnalyzer&&this.audioAnalyzer.isAnalyzing){const e=this.audioAnalyzer.getShapeMorpherData();if(e&&e.frequencies)for(let t=0;t<Math.min(e.frequencies.length,this.frequencyData.length);t++)this.frequencyData[t]=e.frequencies[t]}if(this.musicDetector&&this.musicDetector.update(performance.now()),!this.isTransitioning||!this.targetShape)return;const t=Date.now()-this.morphStartTime;if(this.musicalDuration){const e=6e4/(sn.bpm||120),t=this.morphDuration>2*e;this.morphDuration=t?4*e:e}let i=Math.min(t/this.morphDuration,1);if(this.musicalDuration&&this.onBeat){const e=sn.bpm||120;let t;t=e>140?2:e>100?4:8;const s=6e4/e,n=this.morphDuration/s,a=i*n,r=Math.round(a*t)/t,o=Math.min(1,r/n),l=(.3+.5*(e<90?Math.max(.3,(e-60)/30):Math.max(.4,Math.min(1,1-(e-90)/90))))*(.3+.7*Math.sin(i*Math.PI));i+=l*l*(3-2*l)*(o-i)}this.morphProgress=this.applyEasing(i),this.visualProgress=.8*this.visualProgress+.2*this.morphProgress,Math.abs(this.visualProgress-this.morphProgress)<.001&&(this.visualProgress=this.morphProgress),this.onProgress&&this.onProgress(this.morphProgress),this.morphProgress>=1&&(this.visualProgress=1,this.completeMorph())}completeMorph(e=!1){if(this.targetShape&&(this.currentShape=this.targetShape,this.currentPoints=[...this.targetPoints]),this.targetShape=null,this.isTransitioning=!1,this.morphProgress=0,this.visualProgress=0,this.onComplete&&this.onComplete(this.currentShape),!e&&this.queuedMorph){const e=this.queuedMorph;this.queuedMorph=null,this.queuedMorphTimeout=setTimeout(()=>{this.morphTo(e.targetShape,e.options),this.queuedMorphTimeout=null},50)}}hasQueuedMorph(){return null!==this.queuedMorph}clearQueue(){this.queuedMorph=null,this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null)}getCanvasPoints(e,t,i){let s;try{s=this.getInterpolatedPoints()}catch{s=this.generateFallbackCircle()}this.canvasPointsCache||(this.canvasPointsCache=[]);const n=this.canvasPointsCache;if(n.length=0,!s||0===s.length){for(let s=0;s<this.numPoints;s++){const a=s/this.numPoints*Math.PI*2;n.push({x:e+Math.cos(a)*i,y:t+Math.sin(a)*i})}return n}const a=Array.isArray(s)?s:[];for(let s=0;s<a.length;s++){const r=a[s];if(r&&"number"==typeof r.x&&"number"==typeof r.y){const s=e+(r.x-.5)*i*2,a=t+(r.y-.5)*i*2;n.push({x:s,y:a})}else{const r=s/a.length*Math.PI*2;n.push({x:e+Math.cos(r)*i,y:t+Math.sin(r)*i})}}for(;n.length<this.numPoints;){const s=n.length/this.numPoints*Math.PI*2;n.push({x:e+Math.cos(s)*i,y:t+Math.sin(s)*i})}return n}getInterpolatedPoints(){if(this.currentPoints&&0!==this.currentPoints.length||(this.currentPoints=this.generateFallbackCircle()),!this.isTransitioning)return this.applyAudioDeformation(this.currentPoints);const e=[];for(let t=0;t<this.numPoints;t++){const i=this.currentPoints[t],s=this.targetPoints[t];if(!i||!s){const i=t/this.numPoints*Math.PI*2;e.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)});continue}const n=this.visualProgress;let a,r;const o=["square","circle","star","triangle"],l=o.includes(this.currentShape),h=o.includes(this.targetShape);if(l||h){const e=.5,t=.5;if(h&&!l){const o=s.x-e,l=s.y-t;if(n<.3){const s=n/.3;a=i.x+(e-i.x)*s,r=i.y+(t-i.y)*s}else{const i=(n-.3)/.7;a=e+o*i,r=t+l*i}}else if(l&&!h){const o=i.x-e,l=i.y-t;if(n<.5){const e=n/.5;a=i.x-o*e,r=i.y-l*e}else{const i=(n-.5)/.5;a=e+(s.x-e)*i,r=t+(s.y-t)*i}}else{const o=i.x-e,l=i.y-t,h=s.x-e,c=s.y-t;if(n<.5){const e=n/.5;a=i.x-o*e,r=i.y-l*e}else{const i=(n-.5)/.5;a=e+h*i,r=t+c*i}}}else if("spiral"===this.morphMode){const e=n*Math.PI*2,o=.02*Math.sin(e+.2*t)*(1-2*Math.abs(n-.5));a=i.x+(s.x-i.x)*n+o,r=i.y+(s.y-i.y)*n+o}else if("wave"===this.morphMode){const e=.01*Math.sin(.3*t+n*Math.PI*4);a=i.x+(s.x-i.x)*n+e,r=i.y+(s.y-i.y)*n+e}else a=i.x+(s.x-i.x)*n,r=i.y+(s.y-i.y)*n;e.push({x:a,y:r})}return this.applyAudioDeformation(e)}applyAudioDeformation(e){return this.audioDeformer.applyAudioDeformation(e)}setAudioDeformation(e){const t=Date.now();t-this.lastAudioUpdate>this.audioUpdateInterval&&(this.audioDeformation=Math.max(-1,Math.min(1,e)),this.lastAudioUpdate=t,this.audioDeformer&&this.audioDeformer.setAudioDeformation(Math.abs(this.audioDeformation)))}setVocalEnergy(e){const t=Date.now();t-this.lastVocalUpdate>this.audioUpdateInterval&&(this.vocalEnergy=Math.max(0,Math.min(1,e)),this.lastVocalUpdate=t,this.audioDeformer&&this.audioDeformer.setVocalEnergy(this.vocalEnergy))}getTransitionConfig(e,t){const i=rr&&rr.isInitialized?rr.getShape(e):ar[e],s=rr&&rr.isInitialized?rr.getShape(t):ar[t];return"moon"===t?{type:"to_moon",easing:"easeInOutCubic",duration:1500,glowIntensity:1.5,fadeInCrescent:!0}:"moon"===e&&"lunar"===t?{type:"moon_to_lunar",easing:"easeInOutSine",duration:2e3,slideOutCrescent:!1,description:"Crescent shadow moves to center and becomes lunar eclipse"}:"moon"===e?{type:"from_moon",easing:"easeInOutCubic",duration:1e3,slideOutCrescent:!0,shadowSlideRatio:.4,description:"Moon shadow slides away THEN morphs to target"}:"lunar"===t?{type:"eclipse_enter_lunar",startAngle:-30}:"lunar"===e&&"moon"===t?{type:"lunar_to_moon",exitAngle:-30}:"lunar"===e?{type:"eclipse_exit_lunar",exitAngle:-30}:"none"===i?.shadow?.type&&"solar"===s?.shadow?.type?{type:"eclipse_enter",direction:"right"}:"solar"===i?.shadow?.type&&"none"===s?.shadow?.type?{type:"eclipse_exit",direction:"left"}:"sun"===e&&"sun"!==t?{type:"sun_fade",fadeEffects:!0}:"sun"!==e&&"sun"===t?{type:"sun_bloom",bloomEffects:!0}:{type:"standard"}}getCurrentShadow(){return this.shadowEffectManager.getCurrentShadow()}getCurrentRenderer(){return null}applyEasing(e){switch(this.transitionConfig?.easing||this.easing||"linear"){case"linear":return e;case"easeInQuad":return e*e;case"easeOutQuad":return e*(2-e);case"easeInOutQuad":return e<.5?2*e*e:(4-2*e)*e-1;case"easeInOutSine":return-(Math.cos(Math.PI*e)-1)/2;default:return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}calculateBPM(){return this.musicDetector.calculateBPM()}findTempoCandidates(e){return this.musicDetector.findTempoCandidates(e)}clusterIntervals(e){return this.musicDetector.clusterIntervals(e)}checkHarmonicRelation(e,t){return this.musicDetector.checkHarmonicRelation(e,t)}detectTimeSignature(){this.musicDetector.forceFastDetection=this.forceFastDetection;const e=this.musicDetector.detectTimeSignature();return this.detectedTimeSignature=this.musicDetector.detectedTimeSignature,this.timeSignatureConfidence=this.musicDetector.timeSignatureConfidence,this.timeSignatureLocked=this.musicDetector.timeSignatureLocked,e}testWaltzPattern(e,t){return this.musicDetector.testWaltzPattern(e,t)}resetMusicDetection(){this.forceFastDetection=!0,this.musicDetector.reset(),this.musicDetector.forceFastDetection=!0,this.onsetThreshold=0,this.detectedBPM=0,this.bpmConfidence=0,this.onsetStrengths=[],this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.musicDetector.lastBPMCalculation=0,this.measureStartTime=0,this.timeSignatureHistory=[],this.timeSignatureLocked=!1,this.spectralHistory=[],this.spectralFluxHistory=[];const e=document.getElementById("time-sig-display");e&&(e.textContent="โ")}getCurrentMusicInfo(){return{bpm:this.detectedBPM,timeSignature:this.detectedTimeSignature,bpmLocked:this.tempoLocked,timeSigLocked:this.timeSignatureLocked}}generateFallbackCircle(){const e=[];for(let t=0;t<this.numPoints;t++){const i=t/this.numPoints*Math.PI*2;e.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)})}return e}getState(){return{currentShape:this.currentShape,targetShape:this.targetShape,isTransitioning:this.isTransitioning,progress:this.morphProgress,audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy}}getProgress(e=!0){return e?this.visualProgress:this.morphProgress}isInTransition(){return this.isTransitioning}destroy(){this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null),this.queuedMorph=null,this.shapeCache.clear(),this.canvasPointsCache=null,this.frequencyData&&(or.release(this.frequencyData),this.frequencyData=null),this.bassHistory&&(or.release(this.bassHistory),this.bassHistory=null),this.vocalHistory&&(or.release(this.vocalHistory),this.vocalHistory=null),this.audioAnalyzer=null}}class mr{constructor(){this.audioContext=null,this.analyser=null,this.source=null,this.elementSource=null,this.dataArray=null,this.isAnalyzing=!1,this.connectedElement=null,this.gainNode=null,this.animationFrameId=null,this.frequencyBands=32,this.smoothingFactor=.3,this.vocalRange={min:80,max:1e3},this.currentAmplitude=0,this.currentFrequencies=new Array(this.frequencyBands).fill(0),this.beatThreshold=.3,this.lastBeatTime=0,this.beatCallbacks=[],this._timeDataArray=null,this._boundAnalyze=()=>this.analyze()}init(){try{return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),"suspended"===this.audioContext.state?this.audioContext.resume().then(()=>(this.createAnalyser(),!0)).catch(()=>!1):(this.createAnalyser(),!0)}catch(e){return console.warn("AudioAnalyzer init failed:",e),!1}}createAnalyser(){if(this.audioContext&&!this.analyser){this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,this.analyser.smoothingTimeConstant=.5;const e=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(e),this._timeDataArray=new Uint8Array(e)}}connectAudioElement(e){if(this.audioContext)try{this.elementSource&&this.connectedElement===e||(this.elementSource=this.audioContext.createMediaElementSource(e),this.elementSource.connect(this.analyser),this.elementSource.connect(this.audioContext.destination)),this.source=this.elementSource,this.connectedElement=e,this.isAnalyzing=!0,this.analyze()}catch(t){const i=t instanceof Error?t.message:String(t);i.includes("already been used")?(this.source=this.elementSource,this.connectedElement=e,this.isAnalyzing=!0,this.analyze()):console.warn("[AudioAnalyzer] Unexpected error during connect:",i)}}analyze(){if(!this.isAnalyzing)return;this.animationFrameId=requestAnimationFrame(this._boundAnalyze),this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this._timeDataArray);let e=0,t=0,i=0;const s=this.audioContext.sampleRate/2/this.dataArray.length,n=Math.floor(this.vocalRange.min/s),a=Math.ceil(this.vocalRange.max/s);for(let s=0;s<this.dataArray.length;s++){const r=this.dataArray[s]/255;e+=r,s>=n&&s<=a&&(t+=r,i++)}this.currentAmplitude=e/this.dataArray.length;const r=i>0?t/i:0;return this.extractFrequencyBands(),this.detectBeat(this.currentAmplitude),{amplitude:this.currentAmplitude,vocalAmplitude:r,frequencies:this.currentFrequencies,rawData:this.dataArray}}extractFrequencyBands(){const e=Math.floor(this.dataArray.length/this.frequencyBands);for(let t=0;t<this.frequencyBands;t++){let i=0;const s=t*e,n=Math.min(s+e,this.dataArray.length);for(let e=s;e<n;e++)i+=this.dataArray[e]/255;const a=i/e;this.currentFrequencies[t]=this.currentFrequencies[t]*this.smoothingFactor+a*(1-this.smoothingFactor)}}detectBeat(e){const t=performance.now();e>this.beatThreshold&&t-this.lastBeatTime>60&&(this.lastBeatTime=t,this.beatCallbacks.forEach(t=>t(e)))}getVocalInstability(){let e=0;const t=this.currentFrequencies.reduce((e,t)=>e+t,0)/this.frequencyBands;for(let i=0;i<this.frequencyBands;i++)e+=Math.pow(this.currentFrequencies[i]-t,2);return e=Math.sqrt(e/this.frequencyBands),Math.min(1,2*e+.5*this.currentAmplitude)}getShapeMorpherData(){return{instability:this.getVocalInstability(),frequencies:[...this.currentFrequencies],amplitude:this.currentAmplitude}}onBeat(e){this.beatCallbacks.push(e)}stop(){if(this.isAnalyzing=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.gainNode){try{this.gainNode.disconnect()}catch(e){}this.gainNode=null}if(this.elementSource&&this.connectedElement){try{this.elementSource.connect(this.analyser)}catch(e){}this.source=this.elementSource}}async resume(){this.audioContext&&"suspended"===this.audioContext.state&&await this.audioContext.resume()}destroy(){this.stop(),null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.analyser=null,this.dataArray=null,this._timeDataArray=null,this.beatCallbacks=[]}}var pr=Object.freeze({__proto__:null,AudioAnalyzer:mr});class fr{constructor(){this.timingClasses={downbeat:{gestures:["bounce","jump","headBob","spin","orbit"],timing:1,priority:1,description:"Strong emphasis on the downbeat"},upbeat:{gestures:["wave","nod","point","reach"],timing:.5,priority:2,description:"Medium emphasis on upbeat"},offbeat:{gestures:["wiggle","sway","lean","tilt","groove"],timing:.5,priority:3,description:"Syncopated, creates groove"},subdivision:{gestures:["pulse","sparkle","flash","shimmer","flicker"],timing:.25,priority:4,description:"Quick accents and fills"},continuous:{gestures:["breathe","float","rain"],timing:-1,priority:5,description:"Ambient, continuous motion"}},this.fillPatterns={subtle:["breathe","float"],rhythmic:["pulse","shimmer"],energetic:["wiggle","sparkle"],smooth:["sway","glow"]},this.densityProfiles={sparse:{fillProbability:.1,subdivisionLevel:2,description:"Minimal movement"},moderate:{fillProbability:.3,subdivisionLevel:4,description:"Balanced movement"},dense:{fillProbability:.5,subdivisionLevel:8,description:"Busy, energetic"},chaos:{fillProbability:.8,subdivisionLevel:16,description:"Maximum energy"}},this.groups={movement:{gestures:["bounce","spin","orbit","sway","hula","jump","twist","groove"],maxSimultaneous:1,priority:1,description:"Primary body movements - mutually exclusive"},expression:{gestures:["wave","nod","shake","point","lean","tilt","reach"],maxSimultaneous:2,priority:2,description:"Expressive gestures - can combine up to 2"},dance:{gestures:["headBob","wiggle","runningman","charleston"],maxSimultaneous:1,priority:2,description:"Dance moves - one at a time but can add effects"},effects:{gestures:["pulse","glow","sparkle","flash","shimmer","flicker"],maxSimultaneous:-1,priority:3,description:"Visual effects - all can layer together"},modifiers:{gestures:["breathe","float","rain"],maxSimultaneous:-1,priority:4,description:"Ambient effects - always allowed"}},this.enhancingCombinations=[["bounce","sparkle"],["spin","glow"],["wave","pulse"],["nod","pulse"],["jump","flash"],["sway","breathe"],["float","shimmer"],["orbit","sparkle"],["headBob","pulse"]],this.incompatiblePairs=[["bounce","jump"],["spin","orbit"],["wave","point"],["nod","shake"],["lean","tilt"]],this.chords={celebrate:["bounce","sparkle","pulse"],greeting:["wave","nod","glow"],excited:["jump","flash","wiggle"],mystical:["float","shimmer","breathe"],party:["headBob","pulse","sparkle"],smooth:["sway","glow","breathe"],dramatic:["spin","flash","sparkle"]},this.chains={rise:"breathe > sway+lean+tilt",flow:"sway > lean+tilt > spin > bounce",burst:"jump > nod > shake > flash",drift:"sway+breathe+float+drift",chaos:"shake+shake > spin+flash > bounce+pulse > twist+sparkle",morph:"expand > contract > morph+glow > expand+flash",rhythm:"pulse > pulse+sparkle > pulse+flicker",spiral:"spin > orbital > twist > orbital+sparkle",routine:"nod > bounce > spin+sparkle > sway+pulse > nod+flash",radiance:"sparkle > pulse+flicker > shimmer",twinkle:"sparkle > flash > pulse+sparkle > shimmer+flicker",stream:"wave > nod+pulse > sparkle > flash",buildup:"pulse > pulse > bounce+sparkle > spin+flash",cascade:"wave > lean > tilt > spin > bounce+glow",celebrate:"bounce+sparkle > spin > jump+flash > nod+pulse",smooth:"sway+breathe > float > orbit+shimmer > sway+glow",custom:"expand > contract > morph > expand+glow",greeting:"wave+glow > nod+pulse > wave",mystical:"float+shimmer > orbit+breathe > spin+sparkle > float+glow"}}canExecuteSimultaneously(e,t){if(e===t)return!1;if(this.incompatiblePairs.some(i=>i.includes(e)&&i.includes(t)))return!1;const i=this.getGestureGroup(e),s=this.getGestureGroup(t);if(i===s){const e=this.groups[i];return e&&1!==e.maxSimultaneous}return!("movement"===i&&"movement"===s||"dance"===i&&"dance"===s)}getGestureGroup(e){for(const[t,i]of Object.entries(this.groups))if(i.gestures.includes(e))return t;return null}getGesturePriority(e){const t=this.getGestureGroup(e);return t?this.groups[t].priority:99}getCompatibleGestures(e){if(!e||0===e.length)return[];if(1===e.length)return e;const t=[],i=new Set,s=e=>"string"==typeof e?e:e.gestureName,n=[...e].sort((e,t)=>this.getGesturePriority(s(e))-this.getGesturePriority(s(t)));for(const e of n){if(i.has(e))continue;const n=s(e);let a=!0;for(const e of t){const t=s(e);if(!this.canExecuteSimultaneously(n,t)){a=!1;break}}if(a){const a=this.groups[this.getGestureGroup(n)];if(a&&a.maxSimultaneous>0&&t.filter(e=>this.getGestureGroup(s(e))===this.getGestureGroup(n)).length>=a.maxSimultaneous)continue;t.push(e),i.add(e)}}return t}parseChain(e){return e?(this.chains[e]&&(e=this.chains[e]),e.split(">").map(e=>e.trim()).map(e=>e.split("+").map(e=>e.trim()).filter(e=>e))):[]}isEnhancingCombination(e){const t=e.map(e=>"string"==typeof e?e:e.gestureName);return this.enhancingCombinations.some(e=>e.every(e=>t.includes(e)))}getChord(e){return this.chords[e]||null}createChord(e){const t=this.getCompatibleGestures(e),i=this.isEnhancingCombination(t);return{type:"chord",gestures:t.map(e=>"string"==typeof e?e:e.gestureName),isEnhancing:i,timestamp:Date.now()}}isValidGesture(e){return null!==this.getGestureGroup(e)}getAllGestures(){const e=[];for(const t of Object.values(this.groups))e.push(...t.gestures);return[...new Set(e)]}getGestureTiming(e){for(const[t,i]of Object.entries(this.timingClasses))if(i.gestures.includes(e))return{name:t,...i};return null}getNextBeatForGesture(e,t,i=1){const s=this.getGestureTiming(e);if(!s)return t+1;if(-1===s.timing)return t;const n=s.timing/i,a=Math.ceil(t/n)*n;return"offbeat"===s.name?a+.5:a}getFillGestures(e,t="moderate"){const i=this.densityProfiles[t]||this.densityProfiles.moderate;let s;return s=e<80?"energetic":e<120?"rhythmic":e<160?"smooth":"subtle",Math.random()<i.fillProbability&&this.fillPatterns[s]||[]}getNextBeatTiming(e,t,i){return this.getNextBeatForGesture(e,t)}getIntensityFromBPM(e){return e<60?"dense":e<100||e<140?"moderate":"sparse"}applySwingTiming(e,t=.67){return.5==e%1?Math.floor(e)+t:e}}const yr=new fr;var br=Object.freeze({__proto__:null,GestureCompatibility:fr,default:yr});class vr{constructor(){this.templates={straight:{name:"Straight",timeSignature:"4/4",baseMovement:"grooveBob",transitionStyle:"transitionLean",pattern:{emphasis:[1,0,.5,0],velocities:[1,0,.6,0],subdivisions:[0,.5]},swing:0,humanization:.05,preferredGestures:{downbeat:["bounce","headBob","jump"],offbeat:["pulse","breathe"],fills:["sparkle","glow"]},compositeMove:null,intensity:"moderate",description:"Standard 4/4 rhythm, good for pop/rock"},swing:{name:"Swing",timeSignature:"4/4",baseMovement:"grooveFlow",transitionStyle:"transitionGlide",compositeMove:"swingOut",pattern:{emphasis:[1,0,.66,0],velocities:[1,0,.7,0],subdivisions:[0,.66]},swing:.67,humanization:.08,preferredGestures:{downbeat:["sway","lean","bounce"],offbeat:["wiggle","pulse"],fills:["shimmer","float"]},intensity:"moderate",description:"Jazz swing feel with triplet subdivision"},shuffle:{name:"Shuffle",timeSignature:"4/4",baseMovement:"grooveBob",transitionStyle:"transitionLean",compositeMove:null,pattern:{emphasis:[1,.25,.5,.75],velocities:[1,.3,.7,.3],subdivisions:[0,.25,.5,.75]},swing:.75,humanization:.06,preferredGestures:{downbeat:["bounce","headBob"],upbeat:["twist","wiggle"],offbeat:["pulse","breathe"],fills:["sparkle","flash"]},intensity:"dense",description:"Blues/rock shuffle with heavy swing"},latin:{name:"Latin",timeSignature:"4/4",baseMovement:"grooveSway",transitionStyle:"transitionRoll",compositeMove:"latinHips",pattern:{emphasis:[1,0,.375,.5,0,.75,0,0],velocities:[1,0,.8,.9,0,.8,0,0],subdivisions:[0,.375,.5,.75]},swing:0,humanization:.04,preferredGestures:{downbeat:["sway","wiggle"],syncopation:["twist","lean"],offbeat:["pulse","shimmer"],fills:["sparkle","shake"]},intensity:"dense",description:"Latin clave rhythm with syncopation"},breakbeat:{name:"Breakbeat",timeSignature:"4/4",baseMovement:"grooveStep",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[1,0,0,.75,.25,.5,0,.625],velocities:[1,0,0,.9,.6,.8,0,.7],subdivisions:[0,.25,.5,.625,.75]},swing:0,humanization:.03,preferredGestures:{downbeat:["bounce","twist"],syncopation:["flash","shake"],offbeat:["pulse","wiggle"],fills:["sparkle","glitch"]},intensity:"chaos",description:"Hip-hop/DnB breakbeat pattern"},waltz:{name:"Waltz",timeSignature:"3/4",baseMovement:"grooveFlow",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[1,.33,.67],velocities:[1,.5,.5],subdivisions:[0,.33,.67]},swing:0,humanization:.07,preferredGestures:{downbeat:["sway","float"],weak:["breathe","lean"],fills:["shimmer","glow"]},intensity:"sparse",description:"3/4 waltz time"},techno:{name:"Techno",timeSignature:"4/4",baseMovement:"groovePulse",transitionStyle:"transitionLean",compositeMove:"robotPop",pattern:{emphasis:[1,.25,.5,.75,1,.25,.5,.75],velocities:[1,.6,1,.6,1,.6,1,.6],subdivisions:[0,.25,.5,.75]},swing:0,humanization:.02,preferredGestures:{downbeat:["pulse","bounce"],subdivision:["flash","glitch"],fills:["sparkle","strobe"]},intensity:"dense",description:"Driving techno four-on-the-floor"},ambient:{name:"Ambient",timeSignature:"4/4",baseMovement:"groovePulse",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[.8,0,.3,0,.5,0,.3,0],velocities:[.8,0,.3,0,.5,0,.3,0],subdivisions:[0,.5]},swing:0,humanization:.15,preferredGestures:{downbeat:["float","breathe"],offbeat:["sway","shimmer"],fills:["glow","pulse"]},intensity:"sparse",description:"Floating ambient rhythm"},funk:{name:"Funk",timeSignature:"4/4",baseMovement:"grooveSway",transitionStyle:"transitionRoll",compositeMove:"funkChicken",pattern:{emphasis:[1.2,.125,.25,0,.625,.75,0,.875],velocities:[1.2,.3,.4,0,.8,.6,0,.4],subdivisions:[0,.125,.25,.625,.75,.875]},swing:.1,humanization:.06,preferredGestures:{one:["bounce","twist"],ghost:["wiggle","pulse"],syncopation:["lean","shake"],fills:["flash","sparkle"]},intensity:"chaos",description:"Funky syncopated rhythm with THE ONE"},trap:{name:"Trap",timeSignature:"4/4",baseMovement:"grooveStep",transitionStyle:"transitionLean",compositeMove:null,pattern:{emphasis:[1,0,0,.375,0,.75,.875,0],velocities:[1,0,0,.7,0,.8,.6,0],subdivisions:[0,.375,.75,.875]},swing:0,humanization:.03,preferredGestures:{downbeat:["bounce","lean"],hihat:["shake","shimmer"],syncopation:["twist","flash"],fills:["sparkle","glitch"]},intensity:"moderate",description:"Trap rhythm with triplet hi-hats"}},this.transitions={instant:0,nextBar:1,nextPhrase:4,fadeIn:8},this.currentGroove=null,this.transitionMode="nextBar",this.pendingGroove=null}getTemplate(e){return this.templates[e.toLowerCase()]||this.templates.straight}getEmphasis(e,t,i){if(!e||!e.pattern)return 0;const s=e.pattern.subdivisions.findIndex(e=>Math.abs(e-i)<.01);return-1===s?0:e.pattern.emphasis[s]||0}getVelocity(e,t,i){if(!e||!e.pattern)return 1;const s=e.pattern.subdivisions.findIndex(e=>Math.abs(e-i)<.01);return-1===s?0:e.pattern.velocities[s]||0}getPreferredGesture(e,t,i,s=[]){if(!e||!e.preferredGestures)return null;let n;n=0===i?"downbeat":.5===i?"offbeat":.25===i||.75===i?"subdivision":"syncopation","Funk"===e.name&&t%4==0&&0===i&&(n="one");const a=e.preferredGestures[n]||e.preferredGestures.fills;if(!a||0===a.length)return null;if(s.length>0){const e=a.filter(e=>s.includes(e));if(e.length>0)return e[Math.floor(Math.random()*e.length)]}return a[Math.floor(Math.random()*a.length)]}humanizeTiming(e,t){if(!e||!e.humanization)return t;const i=e.humanization,s=(Math.random()-.5)*i;return Math.max(0,Math.min(1,t+s))}applySwing(e,t){return e&&e.swing&&0!==e.swing?Math.abs(t-.5)<.01?.5+.5*(e.swing-.5):Math.abs(t-.25)<.01?.25+.25*(e.swing-.5):Math.abs(t-.75)<.01?.75+.25*(e.swing-.5):t:t}setGroove(e,t=null){const i=this.getTemplate(e);return!!i&&("instant"!==(t||this.transitionMode)&&this.currentGroove?this.pendingGroove=i:(this.currentGroove=i,this.pendingGroove=null),!0)}onBeat(e){this.pendingGroove&&("nextBar"===this.transitionMode&&e%4==0||"nextPhrase"===this.transitionMode&&e%16==0)&&(this.currentGroove=this.pendingGroove,this.pendingGroove=null)}getBaseMovement(){return this.currentGroove?.baseMovement||null}getTransitionStyle(){return this.currentGroove?.transitionStyle||"transitionLean"}getCompositeMove(){return this.currentGroove?.compositeMove||null}shouldTriggerComposite(e){return!!this.currentGroove?.compositeMove&&e%("sparse"===this.currentGroove.intensity?32:16)==0}getLayeredGestures(e,t){if(!this.currentGroove)return null;const i={base:this.getBaseMovement(),accent:null,transition:null,composite:null,velocity:1};this.shouldTriggerComposite(e)&&0===t&&(i.composite=this.getCompositeMove());const s=this.getEmphasis(this.currentGroove,e,t),n=this.getVelocity(this.currentGroove,e,t);return s>.3&&n>.3&&(i.accent=this.getPreferredGesture(this.currentGroove,e,t),i.velocity=n),i.accent&&Math.random()<.3&&(i.transition=this.getTransitionStyle()),i}getGrooveNames(){return Object.keys(this.templates)}getGrooveInfo(e){const t=this.templates[e];return t?{name:t.name,timeSignature:t.timeSignature,description:t.description,intensity:t.intensity,swing:t.swing,baseMovement:t.baseMovement,compositeMove:t.compositeMove}:null}}const Mr={listening:{name:"listening",category:"conversational",emotion:"curiosity",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:400,description:"User is speaking, AI is listening attentively"},thinking:{name:"thinking",category:"conversational",emotion:"focused",gesture:"breathe",delay:100,baseIntensity:.7,emotionDuration:500,description:"AI is processing and thinking"},acknowledging:{name:"acknowledging",category:"conversational",emotion:"calm",gesture:"nod",delay:150,baseIntensity:.7,emotionDuration:400,description:"AI acknowledges understanding"},guiding:{name:"guiding",category:"conversational",emotion:"calm",gesture:"point",delay:200,baseIntensity:.7,emotionDuration:500,description:"AI provides guidance or instructions"},empathizing:{name:"empathizing",category:"conversational",emotion:"empathy",baseIntensity:.8,emotionDuration:600,description:"AI shows empathy and understanding",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.8},{at:200,action:"gesture",value:"shake"},{at:700,action:"gesture",value:"nod"}]},celebrating:{name:"celebrating",category:"conversational",emotion:"joy",baseIntensity:.9,emotionDuration:500,description:"AI celebrates success with user",sequence:[{at:0,action:"emotion",value:"joy",intensity:.9},{at:200,action:"gesture",value:"bounce"},{at:800,action:"emotion",value:"triumph",intensity:1},{at:900,action:"gesture",value:"glow"}]},celebrating_epic:{name:"celebrating_epic",category:"conversational",emotion:"triumph",baseIntensity:1,emotionDuration:500,description:"Epic celebration with visual transformation",sequence:[{at:0,action:"emotion",value:"joy",intensity:.9},{at:200,action:"gesture",value:"bounce"},{at:700,action:"emotion",value:"triumph",intensity:1},{at:800,action:"gesture",value:"glow"},{at:1e3,action:"morph",value:"sun"},{at:1e3,action:"chain",value:"radiance"}]},reassuring:{name:"reassuring",category:"conversational",emotion:"calm",baseIntensity:.8,emotionDuration:600,description:"AI provides reassurance and comfort",sequence:[{at:0,action:"emotion",value:"calm",intensity:.8},{at:200,action:"gesture",value:"breathe"},{at:800,action:"gesture",value:"wave"}]},offering_help:{name:"offering_help",category:"conversational",emotion:"empathy",baseIntensity:.8,emotionDuration:500,description:"AI offers assistance",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.8},{at:200,action:"gesture",value:"nod"},{at:600,action:"gesture",value:"point"}]},offering_urgent_help:{name:"offering_urgent_help",category:"conversational",emotion:"empathy",baseIntensity:1,emotionDuration:400,description:"AI urgently offers help for frustrated user",sequence:[{at:0,action:"emotion",value:"empathy",intensity:1},{at:150,action:"gesture",value:"shake"},{at:400,action:"gesture",value:"nod"},{at:700,action:"gesture",value:"point"}]},apologizing:{name:"apologizing",category:"conversational",emotion:"empathy",baseIntensity:.85,emotionDuration:600,description:"AI apologizes for mistake or error",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.85},{at:200,action:"gesture",value:"shake"},{at:600,action:"gesture",value:"breathe"}]},encouraging:{name:"encouraging",category:"conversational",emotion:"joy",gesture:"nod",delay:200,baseIntensity:.75,emotionDuration:500,description:"AI encourages user to continue"},greeting:{name:"greeting",category:"conversational",emotion:"joy",gesture:"wave",delay:200,baseIntensity:.7,emotionDuration:500,description:"AI greets user warmly"},responding_positive:{name:"responding_positive",category:"conversational",emotion:"joy",gesture:"bounce",delay:150,baseIntensity:.75,emotionDuration:500,description:"AI responds with positive sentiment"},responding_neutral:{name:"responding_neutral",category:"conversational",emotion:"calm",gesture:"drift",delay:150,baseIntensity:.6,emotionDuration:500,description:"AI responds with neutral sentiment"},responding_negative:{name:"responding_negative",category:"conversational",emotion:"empathy",gesture:"shake",delay:150,baseIntensity:.8,emotionDuration:600,description:"AI responds to negative situation"},success_minor:{name:"success_minor",category:"feedback",emotion:"joy",gesture:"bounce",delay:150,baseIntensity:.7,emotionDuration:500,description:"Small success (item scanned, form field validated)"},success_moderate:{name:"success_moderate",category:"feedback",emotion:"joy",baseIntensity:.8,emotionDuration:500,description:"Moderate success (section completed, task done)",sequence:[{at:0,action:"emotion",value:"joy",intensity:.8},{at:200,action:"gesture",value:"bounce"},{at:600,action:"gesture",value:"wiggle"}]},success_major:{name:"success_major",category:"feedback",emotion:"triumph",baseIntensity:.9,emotionDuration:500,description:"Major success (milestone reached, goal achieved)",sequence:[{at:0,action:"emotion",value:"joy",intensity:.85},{at:150,action:"gesture",value:"bounce"},{at:500,action:"emotion",value:"triumph",intensity:.9},{at:600,action:"gesture",value:"glow"}]},success_epic:{name:"success_epic",category:"feedback",emotion:"triumph",baseIntensity:1,emotionDuration:500,description:"Epic success with visual transformation",sequence:[{at:0,action:"emotion",value:"triumph",intensity:1},{at:200,action:"gesture",value:"glow"},{at:700,action:"morph",value:"sun"},{at:700,action:"chain",value:"radiance"}]},error_minor:{name:"error_minor",category:"feedback",emotion:"concern",gesture:"shake",delay:150,baseIntensity:.6,emotionDuration:500,description:"Minor error, easily recoverable"},error_moderate:{name:"error_moderate",category:"feedback",emotion:"empathy",baseIntensity:.75,emotionDuration:600,description:"Moderate error, needs user action",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.75},{at:200,action:"gesture",value:"shake"},{at:600,action:"gesture",value:"nod"}]},error_major:{name:"error_major",category:"feedback",emotion:"empathy",baseIntensity:.9,emotionDuration:600,description:"Major error, needs help",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.9},{at:150,action:"gesture",value:"shake"},{at:500,action:"gesture",value:"nod"},{at:800,action:"gesture",value:"point"}]},error_critical:{name:"error_critical",category:"feedback",emotion:"empathy",baseIntensity:1,emotionDuration:500,description:"Critical error, urgent attention needed",sequence:[{at:0,action:"emotion",value:"empathy",intensity:1},{at:100,action:"gesture",value:"shake"},{at:400,action:"gesture",value:"point"}]},warning:{name:"warning",category:"feedback",emotion:"concern",gesture:"pulse",delay:150,baseIntensity:.7,emotionDuration:500,description:"Warning, needs attention"},info:{name:"info",category:"feedback",emotion:"neutral",gesture:"drift",delay:100,baseIntensity:.5,emotionDuration:400,description:"Informational, passive notification"},progress_start:{name:"progress_start",category:"feedback",emotion:"anticipation",gesture:"pulse",delay:100,baseIntensity:.6,emotionDuration:500,description:"Starting a process"},progress_ongoing:{name:"progress_ongoing",category:"feedback",emotion:"focused",gesture:"breathe",delay:0,baseIntensity:.7,emotionDuration:600,description:"Process ongoing, working"},progress_complete:{name:"progress_complete",category:"feedback",emotion:"satisfaction",gesture:"glow",delay:200,baseIntensity:.8,emotionDuration:500,description:"Process completed successfully"},idle:{name:"idle",category:"state",emotion:"neutral",gesture:"drift",delay:0,baseIntensity:.5,emotionDuration:600,description:"System idle, waiting for user"},ready:{name:"ready",category:"state",emotion:"neutral",gesture:"wave",delay:200,baseIntensity:.6,emotionDuration:500,description:"System ready for interaction"},waiting:{name:"waiting",category:"state",emotion:"anticipation",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:600,description:"System waiting for process to complete",loop:!0,loopInterval:1500},processing:{name:"processing",category:"state",emotion:"focused",gesture:"breathe",delay:0,baseIntensity:.7,emotionDuration:600,description:"System actively processing",loop:!0,loopInterval:1200},scanning:{name:"scanning",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.75,emotionDuration:500,description:"Scanning or searching",loop:!0,loopInterval:1e3},analyzing:{name:"analyzing",category:"state",emotion:"curiosity",gesture:"drift",delay:0,baseIntensity:.7,emotionDuration:600,description:"Analyzing data or input",loop:!0,loopInterval:1400},completing:{name:"completing",category:"state",emotion:"anticipation",gesture:"pulse",delay:100,baseIntensity:.8,emotionDuration:500,description:"Final step, about to complete"},completed:{name:"completed",category:"state",emotion:"satisfaction",gesture:"glow",delay:200,baseIntensity:.85,emotionDuration:500,description:"Process completed successfully"},reviewing:{name:"reviewing",category:"state",emotion:"satisfaction",gesture:"drift",delay:0,baseIntensity:.65,emotionDuration:600,description:"Reviewing information or results"},monitoring:{name:"monitoring",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:700,description:"Actively monitoring for changes",loop:!0,loopInterval:2e3},paused:{name:"paused",category:"state",emotion:"neutral",gesture:"breathe",delay:200,baseIntensity:.5,emotionDuration:600,description:"System paused, can resume"},loading:{name:"loading",category:"state",emotion:"anticipation",gesture:"pulse",delay:0,baseIntensity:.65,emotionDuration:500,description:"Loading data or content",loop:!0,loopInterval:1100},connecting:{name:"connecting",category:"state",emotion:"anticipation",gesture:"drift",delay:0,baseIntensity:.6,emotionDuration:600,description:"Establishing connection",loop:!0,loopInterval:1300},active:{name:"active",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.75,emotionDuration:500,description:"System actively engaged"}};class wr{constructor(e={}){this.performances=new Map,this.contextManager=null,this.sequenceExecutor=null,this.eventManager=e.eventManager||null,this.defaultIntensity=e.defaultIntensity||.7,this.enableContextAdjustment=!1!==e.enableContextAdjustment,this.enableAnalytics=e.enableAnalytics||!1,this.performanceHistory=[],this.maxHistorySize=e.maxHistorySize||100,this.loadBuiltInPerformances()}loadBuiltInPerformances(){Object.entries(Mr).forEach(([e,t])=>{this.definePerformance(e,t)})}definePerformance(e,t){this.performances.set(e,{...t,name:e}),this.eventManager&&this.eventManager.emit("performanceDefined",{name:e,definition:t})}getPerformance(e){return this.performances.get(e)||null}hasPerformance(e){return this.performances.has(e)}async perform(e,t={}){const i=this.getPerformance(e);if(!i)return void console.warn(`[PerformanceSystem] Unknown performance: ${e}`);const s=this.calculateIntensity(i,t),n={performance:i,semanticAction:e,intensity:s,options:t,timestamp:Date.now()};this.enableAnalytics&&this.recordPerformance(n),this.eventManager&&this.eventManager.emit("performanceStart",n);try{this.sequenceExecutor&&i.sequence?await this.sequenceExecutor.execute(i.sequence,{intensity:s,...t}):await this.executeSimplePerformance(i,s,t),this.eventManager&&this.eventManager.emit("performanceComplete",n)}catch(t){console.error(`[PerformanceSystem] Error executing ${e}:`,t),this.eventManager&&this.eventManager.emit("performanceError",{...n,error:t})}}async executeSimplePerformance(e,t,i){const{emotion:s,gesture:n,delay:a=0}=e,r=i.mascot||this.mascot;if(r){if(s&&"function"==typeof r.setEmotion){const t=void 0!==i.emotionDuration?i.emotionDuration:e.emotionDuration||500;r.setEmotion(s,t)}n&&"function"==typeof r.express&&(a>0&&await new Promise(e=>setTimeout(e,a)),r.express(n))}else console.warn("[PerformanceSystem] No mascot instance available")}calculateIntensity(e,t){if(void 0!==t.intensity)return Math.max(0,Math.min(1,t.intensity));let i=e.baseIntensity||this.defaultIntensity;if(this.enableContextAdjustment&&t.context){const{context:e}=t;void 0!==e.frustration&&(i+=e.frustration/100*.3),"high"===e.urgency?i+=.2:"medium"===e.urgency&&(i+=.1),"epic"===e.magnitude?i=1:"major"===e.magnitude&&(i=Math.max(i,.9))}return Math.max(0,Math.min(1,i))}recordPerformance(e){this.performanceHistory.push({action:e.semanticAction,intensity:e.intensity,context:e.options.context||{},timestamp:e.timestamp}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift()}getAnalytics(){if(!this.enableAnalytics)return{enabled:!1};const e=this.performanceHistory.length,t={},i={};return this.performanceHistory.forEach(e=>{t[e.action]||(t[e.action]=0,i[e.action]=[]),t[e.action]++,i[e.action].push(e.intensity)}),Object.keys(i).forEach(e=>{const t=i[e];i[e]=t.reduce((e,t)=>e+t,0)/t.length}),{enabled:!0,total:e,byAction:t,avgIntensity:i,history:this.performanceHistory.slice(-20)}}clearAnalytics(){this.performanceHistory=[]}setMascot(e){this.mascot=e}setContextManager(e){this.contextManager=e}setSequenceExecutor(e){this.sequenceExecutor=e}listPerformances(){return Array.from(this.performances.keys())}getPerformanceMetadata(e){const t=this.getPerformance(e);return t?{name:t.name,category:t.category||"custom",emotion:t.emotion,gesture:t.gesture,hasSequence:!!t.sequence,baseIntensity:t.baseIntensity||this.defaultIntensity,description:t.description||""}:null}}class Sr{constructor(e={}){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory=!1!==e.enableHistory,this.historyLimit=e.historyLimit||50,this.history=[],this.enableDecay=!1!==e.enableDecay,this.frustrationDecayRate=e.frustrationDecayRate||5,this.decayInterval=e.decayInterval||1e4,this.decayTimer=null,this.enableDecay&&this.startDecayTimer()}update(e={}){const t={...this.context};void 0!==e.frustration&&(this.context.frustration=Math.max(0,Math.min(100,e.frustration))),void 0!==e.urgency&&(["low","medium","high"].includes(e.urgency)?this.context.urgency=e.urgency:console.warn(`[ContextManager] Invalid urgency: ${e.urgency}`)),void 0!==e.magnitude&&(["small","moderate","major","epic"].includes(e.magnitude)?this.context.magnitude=e.magnitude:console.warn(`[ContextManager] Invalid magnitude: ${e.magnitude}`)),void 0!==e.custom&&(this.context.customValues={...this.context.customValues,...e.custom}),this.enableHistory&&this.addToHistory(t,this.context,e),this.enableDecay&&this.restartDecayTimer()}incrementFrustration(e=10){this.update({frustration:this.context.frustration+e})}decrementFrustration(e=10){this.update({frustration:this.context.frustration-e})}resetFrustration(){this.update({frustration:0})}setUrgency(e){this.update({urgency:e})}setMagnitude(e){this.update({magnitude:e})}setCustom(e,t){this.update({custom:{[e]:t}})}getContext(){return{...this.context}}get(e){return e in this.context?this.context[e]:this.context.customValues[e]}calculateIntensity(e=.5,t={}){let i=e;return!1!==t.useFrustration&&(i+=this.context.frustration/100*.3),!1!==t.useUrgency&&(i+={low:-.1,medium:0,high:.2}[this.context.urgency]||0),!1!==t.useMagnitude&&(i+={small:-.1,moderate:0,major:.15,epic:.3}[this.context.magnitude]||0),void 0!==t.intensityMultiplier&&(i*=t.intensityMultiplier),Math.max(0,Math.min(1,i))}addToHistory(e,t,i){const s={timestamp:Date.now(),previous:e,current:{...t},updates:i,delta:{frustration:t.frustration-e.frustration,urgency:t.urgency!==e.urgency?t.urgency:null,magnitude:t.magnitude!==e.magnitude?t.magnitude:null}};this.history.push(s),this.history.length>this.historyLimit&&this.history.shift()}getHistory(e){return e?this.history.slice(-e):[...this.history]}clearHistory(){this.history=[]}startDecayTimer(){this.decayTimer=setInterval(()=>{if(this.context.frustration>0){const e=Math.max(0,this.context.frustration-this.frustrationDecayRate);this.update({frustration:e})}},this.decayInterval)}restartDecayTimer(){this.decayTimer&&(clearInterval(this.decayTimer),this.startDecayTimer())}stopDecay(){this.decayTimer&&(clearInterval(this.decayTimer),this.decayTimer=null)}reset(){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory&&this.addToHistory({},this.context,{action:"reset"})}getAnalytics(){if(!this.enableHistory||0===this.history.length)return null;const e=this.history.map(e=>e.current.frustration),t=e.reduce((e,t)=>e+t,0)/e.length,i=Math.max(...e),s=Math.min(...e),n=this.history.reduce((e,t)=>(e[t.current.urgency]=(e[t.current.urgency]||0)+1,e),{}),a=this.history.reduce((e,t)=>(e[t.current.magnitude]=(e[t.current.magnitude]||0)+1,e),{});return{current:{...this.context},frustration:{current:this.context.frustration,average:t,max:i,min:s},urgency:{current:this.context.urgency,distribution:n},magnitude:{current:this.context.magnitude,distribution:a},historyLength:this.history.length,firstUpdate:this.history[0]?.timestamp,lastUpdate:this.history[this.history.length-1]?.timestamp}}destroy(){this.stopDecay(),this.history=[],this.context=null}}class xr{constructor(e={}){this.mascot=e.mascot||null,this.eventManager=e.eventManager||null,this.activeSequences=new Map,this.nextSequenceId=1,this.defaultDelay=e.defaultDelay||0,this.allowConcurrent=!1!==e.allowConcurrent}async execute(e,t={}){if(!Array.isArray(e)||0===e.length)return;const i=t.mascot||this.mascot;if(!i)return void console.warn("[SequenceExecutor] No mascot instance available");!this.allowConcurrent&&this.activeSequences.size>0&&this.cancelAll();const s=this.nextSequenceId++,n=[...e].sort((e,t)=>e.at-t.at),a={cancelled:!1};this.activeSequences.set(s,a);try{this.eventManager&&this.eventManager.emit("sequenceStart",{sequenceId:s,steps:n,timestamp:Date.now()}),await this.executeSteps(n,i,a,t),this.eventManager&&this.eventManager.emit("sequenceComplete",{sequenceId:s,timestamp:Date.now()})}catch(e){console.error("[SequenceExecutor] Sequence execution error:",e),this.eventManager&&this.eventManager.emit("sequenceError",{sequenceId:s,error:e,timestamp:Date.now()})}finally{this.activeSequences.delete(s)}}async executeSteps(e,t,i,s){let n=0;for(const a of e){if(i.cancelled)break;const e=a.at-n;if(e>0&&await this.sleep(e,i),i.cancelled)break;await this.executeStep(a,t,s),n=a.at}}executeStep(e,t,i){const{action:s,value:n,intensity:a,options:r}=e;try{switch(s){case"emotion":if("function"==typeof t.setEmotion){const e=void 0!==a?a:i.intensity,s=r?.duration||i.emotionDuration||500;t.setEmotion(n,void 0!==e?e:s)}break;case"gesture":"function"==typeof t.express&&t.express(n,r);break;case"morph":"function"==typeof t.morphTo&&t.morphTo(n,r);break;case"chain":"function"==typeof t.chain&&t.chain(n,r);break;case"sound":"function"==typeof t.playSound&&t.playSound(n,r);break;default:console.warn(`[SequenceExecutor] Unknown action: ${s}`)}this.eventManager&&this.eventManager.emit("stepExecuted",{action:s,value:n,timestamp:Date.now()})}catch(t){console.error("[SequenceExecutor] Error executing step:",e,t),this.eventManager&&this.eventManager.emit("stepError",{action:s,value:n,error:t,timestamp:Date.now()})}}sleep(e,t){return new Promise(i=>{const s=setTimeout(()=>{t&&(t._sleepTimeout=null),i()},e);t&&(t._sleepTimeout=s,t._sleepResolve=i)})}cancel(e){const t=this.activeSequences.get(e);t&&(t.cancelled=!0,t._sleepTimeout&&(clearTimeout(t._sleepTimeout),t._sleepTimeout=null),t._sleepResolve&&(t._sleepResolve(),t._sleepResolve=null),this.activeSequences.delete(e),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:e,timestamp:Date.now()}))}cancelAll(){this.activeSequences.forEach((e,t)=>{e.cancelled=!0,e._sleepTimeout&&(clearTimeout(e._sleepTimeout),e._sleepTimeout=null),e._sleepResolve&&(e._sleepResolve(),e._sleepResolve=null),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:t,timestamp:Date.now()})}),this.activeSequences.clear()}getActiveCount(){return this.activeSequences.size}isActive(){return this.activeSequences.size>0}setMascot(e){this.mascot=e}}let Cr=class{constructor(e){if(!e.errorBoundary)throw new Error("GestureController: errorBoundary required");if(!e.config)throw new Error("GestureController: config required");if(!e.state)throw new Error("GestureController: state required");if(!e.throttledWarn)throw new Error("GestureController: throttledWarn required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this.performanceMonitor=e.performanceMonitor||null,this.soundSystem=e.soundSystem||null,this.config=e.config,this._state=e.state,this._throttledWarn=e.throttledWarn,this._chainTarget=e.chainTarget||this,this.currentGesture=null,this.gestureCompatibility=null,this.rendererMethods={bounce:"startBounce",pulse:"startPulse",shake:"startShake",spin:"startSpin",nod:"startNod",tilt:"startTilt",expand:"startExpand",contract:"startContract",flash:"startFlash",drift:"startDrift",stretch:"startStretch",glow:"startGlow",sparkle:"startSparkle",shimmer:"startShimmer",wiggle:"startWiggle",groove:"startGroove",point:"startPoint",lean:"startLean",reach:"startReach",headBob:"startHeadBob",orbit:"startOrbit",flicker:"startFlicker",vibrate:"startVibrate",wave:"startWave",breathe:"startBreathe",morph:"startMorph",slowBlink:"startSlowBlink",look:"startLook",settle:"startSettle",orbital:"startOrbital",hula:"startHula",sway:"startSway",breathIn:"startBreathIn",breathOut:"startBreathOut",breathHold:"startBreathHold",breathHoldEmpty:"startBreathHoldEmpty",jump:"startJump",rain:"startRain",runningman:"startRunningMan",charleston:"startCharleston",grooveSway:"startGrooveSway",grooveBob:"startGrooveBob",grooveFlow:"startGrooveFlow",groovePulse:"startGroovePulse",grooveStep:"startGrooveStep",float:"startFloat",twist:"startTwist"}}init(){this.gestureCompatibility||Promise.resolve().then(function(){return br}).then(e=>{this.gestureCompatibility=e.default}).catch(e=>{console.warn("GestureCompatibility not available:",e)})}express(e,t={}){return this.errorBoundary.wrap(()=>{if(!e)return this._chainTarget;const i=performance.now(),s=Array.isArray(e)||"object"==typeof e&&"chord"===e.type?"chord":e;if(this.performanceMonitor&&this.performanceMonitor.markGestureStart(s),Array.isArray(e))return this.expressChord(e,t);if("object"==typeof e&&"chord"===e.type)return this.expressChord(e.gestures,t);const n=this.rendererMethods[e];if(n&&this.renderer&&this.renderer[n]){if(this.renderer[n](t),this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(e),this.performanceMonitor){const e=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,e-i)}return this._chainTarget}const a=Ai(e);if(a){if(an.registerConfig("gesture",e,a),this._state.currentModularGesture={type:e,config:a,startTime:performance.now(),duration:a.defaultParams?.duration||1e3,progress:0},this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(e),this.performanceMonitor){const e=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,e-i)}return this._chainTarget}return this._throttledWarn(`Unknown gesture: ${e}`,`gesture_${e}`),this.performanceMonitor&&this.performanceMonitor.markGestureEnd(s),this._chainTarget},"gesture-express",this._chainTarget)()}expressChord(e,t={}){return this.errorBoundary.wrap(()=>{if(!e||!Array.isArray(e)||0===e.length)return this._chainTarget;this.gestureCompatibility||Promise.resolve().then(function(){return br}).then(e=>{this.gestureCompatibility=e.default}).catch(e=>{console.warn("GestureCompatibility not available:",e)});const i=this.gestureCompatibility?this.gestureCompatibility.getCompatibleGestures(e):e;return i.forEach(e=>{const i="string"==typeof e?e:e.gestureName;this.executeGestureDirectly(i,t)}),this.gestureCompatibility?.isEnhancingCombination?.(i)&&this.renderer?.specialEffects?.addSparkle?.(),this._chainTarget},"gesture-chord",this._chainTarget)()}executeGestureDirectly(e,t={}){const i=this.rendererMethods[e];i&&this.renderer&&"function"==typeof this.renderer[i]&&this.renderer[i](t)}chain(...e){if(this.gestureCompatibility){const t=e.join(">"),i=this.gestureCompatibility.parseChain(t);this.executeChainSequence(i)}else console.warn("๐ No gestureCompatibility available, falling back to first gesture"),e.length>0&&this.express(e[0]);return this._chainTarget}executeChainSequence(e){if(!e||0===e.length)return;let t=0;const i=()=>{if(t>=e.length)return;const s=e[t];1===s.length?this.express(s[0]):this.expressChord(s),t++,t<e.length&&setTimeout(i,800)};i()}destroy(){this.currentGesture=null,this.gestureCompatibility=null}};class kr{constructor(e={}){const t=e.initialState||{};this._isRunning=t.isRunning??!1,this._debugMode=t.debugMode??!1,this._speaking=t.speaking??!1,this._recording=t.recording??!1,this._audioLevel=t.audioLevel??0,this._sleeping=t.sleeping??!1,this._rhythmEnabled=t.rhythmEnabled??!1,this._currentModularGesture=t.currentModularGesture??null,this._breathePhase=t.breathePhase??"idle",this._breatheStartTime=t.breatheStartTime??0,this._orbScale=t.orbScale??1,this._warningTimestamps=t.warningTimestamps??{},this._warningThrottle=t.warningThrottle??5e3,this._emit=e.emit||(()=>{})}get isRunning(){return this._isRunning}set isRunning(e){const t=this._isRunning!==e;this._isRunning=e,t&&this._emit("stateChange",{property:"isRunning",value:e})}get debugMode(){return this._debugMode}set debugMode(e){const t=this._debugMode!==e;this._debugMode=e,t&&this._emit("stateChange",{property:"debugMode",value:e})}get speaking(){return this._speaking}set speaking(e){const t=this._speaking!==e;this._speaking=e,t&&this._emit("stateChange",{property:"speaking",value:e})}get recording(){return this._recording}set recording(e){const t=this._recording!==e;this._recording=e,t&&this._emit("stateChange",{property:"recording",value:e})}get audioLevel(){return this._audioLevel}set audioLevel(e){this._audioLevel=e}get sleeping(){return this._sleeping}set sleeping(e){const t=this._sleeping!==e;this._sleeping=e,t&&this._emit("stateChange",{property:"sleeping",value:e})}get rhythmEnabled(){return this._rhythmEnabled}set rhythmEnabled(e){this._rhythmEnabled=e}get currentModularGesture(){return this._currentModularGesture}set currentModularGesture(e){this._currentModularGesture=e}get breathePhase(){return this._breathePhase}set breathePhase(e){this._breathePhase=e}get breatheStartTime(){return this._breatheStartTime}set breatheStartTime(e){this._breatheStartTime=e}get orbScale(){return this._orbScale}set orbScale(e){this._orbScale=e}get warningTimestamps(){return this._warningTimestamps}set warningTimestamps(e){this._warningTimestamps=e}get warningThrottle(){return this._warningThrottle}set warningThrottle(e){this._warningThrottle=e}getSnapshot(){return{isRunning:this._isRunning,debugMode:this._debugMode,speaking:this._speaking,recording:this._recording,audioLevel:this._audioLevel,sleeping:this._sleeping,rhythmEnabled:this._rhythmEnabled,currentModularGesture:this._currentModularGesture,breathePhase:this._breathePhase,breatheStartTime:this._breatheStartTime,orbScale:this._orbScale}}reset(){this._isRunning=!1,this._debugMode=!1,this._speaking=!1,this._recording=!1,this._audioLevel=0,this._sleeping=!1,this._rhythmEnabled=!1,this._currentModularGesture=null,this._breathePhase="idle",this._breatheStartTime=0,this._orbScale=1,this._warningTimestamps={}}}class Pr{constructor(e){if(!e.config)throw new Error("AudioHandler: config required");if(!e.state)throw new Error("AudioHandler: state required");if(!e.emit)throw new Error("AudioHandler: emit required");this.audioAnalyzer=e.audioAnalyzer||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.shapeMorpher=e.shapeMorpher||null,this.renderer=e.renderer||null,this.soundSystem=e.soundSystem||null,this.stateMachine=e.stateMachine||null,this.config=e.config,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.vocalUpdateInterval=null}init(){}disconnectAudio(){return this.audioAnalyzer&&this.audioAnalyzer.stop(),this.vocalUpdateInterval&&(clearInterval(this.vocalUpdateInterval),this.vocalUpdateInterval=null),this.shapeMorpher&&(this.shapeMorpher.setVocalEnergy(0),this.shapeMorpher.setAudioDeformation(0),this.shapeMorpher.audioAnalyzer=null,this.shapeMorpher.beatGlitchIntensity=0,this.shapeMorpher.glitchPoints=[]),this.renderer&&this.renderer.ambientDanceAnimator.stopAmbientAnimation("grooveBob"),this._chainTarget}async connectAudio(e){if(!this.audioAnalyzer)return this._chainTarget;if(!this.audioAnalyzer.audioContext)try{await this.audioAnalyzer.init()}catch(e){return console.warn("Failed to initialize AudioContext:",e),this._chainTarget}if(this.audioAnalyzer.audioContext&&"suspended"===this.audioAnalyzer.audioContext.state)try{await this.audioAnalyzer.audioContext.resume()}catch(e){console.warn("Failed to resume AudioContext:",e)}return this.audioAnalyzer.connectAudioElement(e),this.shapeMorpher&&(this.shapeMorpher.audioAnalyzer=this.audioAnalyzer,this.audioAnalyzer.onBeat(e=>{if(this.shapeMorpher){if(this.shapeMorpher.musicDetector){const t=performance.now();this.shapeMorpher.musicDetector.addOnset(t,e)}this.shapeMorpher.vocalEffectActive&&(this.shapeMorpher.beatGlitchIntensity=.3*e)}})),this.vocalUpdateInterval&&clearInterval(this.vocalUpdateInterval),this.renderer&&this.renderer.startGrooveBob({intensity:.5,frequency:1}),this.vocalUpdateInterval=setInterval(()=>{if(this.audioAnalyzer.isAnalyzing&&this.shapeMorpher){const e=this.audioAnalyzer.currentAmplitude||0,t=this.audioAnalyzer.getVocalInstability()||0;this.shapeMorpher.setVocalEnergy(t),this.shapeMorpher.setAudioDeformation(2*e)}},50),this.renderer&&(this.renderer.audioAnalyzer=this.audioAnalyzer),this._chainTarget}stopSpeaking(){if(!this._state.speaking)return this._chainTarget;const e=this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0;return this.audioLevelProcessor&&this.audioLevelProcessor.cleanup(),this._state.speaking=!1,this.renderer&&this.renderer.onSpeechStop(),this._emit("speechStopped",{previousAudioLevel:e,returnToBaseTime:500}),this._chainTarget}setVolume(e){const t=Math.max(0,Math.min(1,e));if(this.config.masterVolume=t,this.soundSystem&&this.soundSystem.isAvailable()){const e=this.stateMachine.getCurrentState().emotion;this.soundSystem.setMasterVolume(t,e)}return this._emit("volumeChanged",{volume:t}),this._chainTarget}destroy(){this.disconnectAudio()}}class Tr{constructor(e,t={}){this._sm=e,this._decayRate=t.decayRate??.02,this._decayFloor=t.decayFloor??0,this._accumulationCap=t.accumulationCap??1,this._enabled=t.enabled??!1,this._paused=!1,this._onDecay=[],this._onNudge=[]}update(e){if(!this._enabled||this._paused)return;const t=this._sm.getSlots(),i=this._decayRate*e;for(const e of t){if(e.intensity<=this._decayFloor)continue;const t=e.intensity;if(e.intensity=Math.max(this._decayFloor,e.intensity-i),e.intensity!==t){for(const i of this._onDecay)i(e.emotion,e.intensity,t);this._sm._emitEvent("emotionDecayed",{emotion:e.emotion,intensity:e.intensity,removed:!1}),this._sm._emitEvent("slotChanged",{emotion:e.emotion,intensity:e.intensity,action:"decay"})}}this._sm.pruneEmptySlots()}nudge(e,t){this._sm.nudgeEmotion(e,t,this._accumulationCap);for(const i of this._onNudge)i(e,t)}setDecayRate(e){this._decayRate=Math.max(0,e)}getDecayRate(){return this._decayRate}setAccumulationCap(e){this._accumulationCap=Math.max(0,Math.min(1,e))}enable(){this._enabled=!0}disable(){this._enabled=!1}isEnabled(){return this._enabled}pause(){this._paused=!0}resume(){this._paused=!1}reset(){this._sm.clearEmotions()}onDecay(e){return this._onDecay.push(e),()=>{this._onDecay=this._onDecay.filter(t=>t!==e)}}onNudge(e){return this._onNudge.push(e),()=>{this._onNudge=this._onNudge.filter(t=>t!==e)}}serialize(){return{decayRate:this._decayRate,decayFloor:this._decayFloor,accumulationCap:this._accumulationCap,enabled:this._enabled,paused:this._paused}}deserialize(e){e&&(this._decayRate=e.decayRate??this._decayRate,this._decayFloor=e.decayFloor??this._decayFloor,this._accumulationCap=e.accumulationCap??this._accumulationCap,this._enabled=e.enabled??this._enabled,this._paused=e.paused??this._paused)}destroy(){this._onDecay.length=0,this._onNudge.length=0}}class Er{constructor(e){this._modifiers=new Map,this._emit=e||(()=>{})}applyModifier(e,t){this._modifiers.set(e,{name:e,config:{...t},remaining:t.duration??null,startTime:Date.now()}),this._emit("modifierApplied",{name:e,config:t})}removeModifier(e){this._modifiers.get(e)&&(this._modifiers.delete(e),this._emit("modifierExpired",{name:e,manual:!0}))}update(e){const t=[];for(const[i,s]of this._modifiers)null!==s.remaining&&(s.remaining-=e,s.remaining<=0)?(t.push(i),s.config.onExpire&&s.config.onExpire()):s.config.onTick&&s.config.onTick(s.remaining);for(const e of t)this._modifiers.delete(e),this._emit("modifierExpired",{name:e,manual:!1})}getCompositeModifiers(){let e=1,t=0,i=0,s=0;for(const n of this._modifiers.values()){const a=n.config;void 0!==a.rhythmWindowMult&&(e*=a.rhythmWindowMult),void 0!==a.tempoShift&&(t+=a.tempoShift),void 0!==a.visualNoise&&(i+=a.visualNoise),void 0!==a.inputDelay&&(s+=a.inputDelay)}return{rhythmWindowMult:e,tempoShift:t,visualNoise:i,inputDelay:s}}getActiveModifiers(){return[...this._modifiers.values()].map(e=>({name:e.name,remaining:e.remaining,config:{...e.config}}))}hasModifier(e){return this._modifiers.has(e)}clear(){this._modifiers.clear()}serialize(){const e=[];for(const t of this._modifiers.values()){const{onTick:i,onExpire:s,...n}=t.config;e.push({name:t.name,remaining:t.remaining,config:n})}return e}deserialize(e){if(Array.isArray(e)){this._modifiers.clear();for(const t of e)this._modifiers.set(t.name,{name:t.name,config:t.config||{},remaining:t.remaining,startTime:Date.now()})}}}class Ar{constructor(e){if(!e.stateMachine)throw new Error("StateCoordinator: stateMachine required");if(!e.config)throw new Error("StateCoordinator: config required");if(!e.emit)throw new Error("StateCoordinator: emit required");this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem||null,this.canvasManager=e.canvasManager||null,this.renderer=e.renderer||null,this.config=e.config,this.soundSystem=e.soundSystem||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.currentEmotion="neutral",this.emotionIntensity=1,this.stateMachine.setEventCallback&&this.stateMachine.setEventCallback((e,t)=>{this._emit(e,t)}),this._dynamics=null,this._modifierManager=new Er((e,t)=>this._emit(e,t))}init(){}setEmotion(e,t=null){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;let s=null,n=500,a=1;if("string"==typeof t?s=t:t&&"object"==typeof t&&(s=t.undertone||null,n=t.duration||500,a=t.intensity??1),this.emotionIntensity=a,this.stateMachine.setEmotion(i,{undertone:s,duration:n,intensity:a})){const e=l(i);if(e&&an.registerConfig("emotion",i,e),this.particleSystem){this.particleSystem.clear();const e=this.stateMachine.getCurrentEmotionalProperties();let t;if(t="neutral"===i?1:"resting"===i?4:Math.min(3,Math.floor(e.particleRate/4)),t>0){let i,s;if(this.renderer&&"function"==typeof this.renderer.getEffectiveCenter){const e=this.renderer.getEffectiveCenter();i=e.x,s=e.y}else i=this.canvasManager.width/2,s=this.canvasManager.height/2;this.particleSystem.burst(t,e.particleBehavior,i,s)}}if("classic"===this.config.renderingStyle&&this.renderer.setEmotionalState){const e=h(i);this.renderer.setEmotionalState(i,e,s)}this._emit("emotionChanged",{emotion:i,undertone:s,duration:n})}return this.currentEmotion=i,this._chainTarget}pushEmotion(e,t=.5){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;this.stateMachine.pushEmotion(i,t);const s=this.stateMachine.getDominant();return s&&(this.currentEmotion=s.emotion),this._emit("emotionChanged",{emotion:this.currentEmotion,slots:this.stateMachine.getSlots()}),this._chainTarget}nudgeEmotion(e,t,i=1){const s={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;this.stateMachine.nudgeEmotion(s,t,i);const n=this.stateMachine.getDominant();return n&&(this.currentEmotion=n.emotion),this._chainTarget}clearEmotions(){return this.stateMachine.clearEmotions(),this.currentEmotion="neutral",this._emit("emotionChanged",{emotion:"neutral",slots:[]}),this._chainTarget}getEmotionalState(){return this.stateMachine.getEmotionalState()}get dynamics(){return this._dynamics||(this._dynamics=new Tr(this.stateMachine)),this._dynamics}setEmotionDampening(e){return this.stateMachine.setEmotionDampening(e),this._chainTarget}getEmotionDampening(){return this.stateMachine.getEmotionDampening()}get modifiers(){return this._modifierManager}destroy(){this._dynamics&&this._dynamics.destroy(),this._modifierManager.clear(),this.currentEmotion="neutral"}}class Dr{constructor(e){if(!e.animationController)throw new Error("VisualizationRunner: animationController required");if(!e.stateMachine)throw new Error("VisualizationRunner: stateMachine required");if(!e.config)throw new Error("VisualizationRunner: config required");if(!e.state)throw new Error("VisualizationRunner: state required");if(!e.emit)throw new Error("VisualizationRunner: emit required");this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem||null,this.canvasManager=e.canvasManager||null,this.renderer=e.renderer||null,this.audioHandler=e.audioHandler||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.gazeTracker=e.gazeTracker||null,this.idleBehavior=e.idleBehavior||null,this.degradationManager=e.degradationManager||null,this.pluginSystem=e.pluginSystem||null,this.config=e.config,this.canvas=e.canvas||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.animationId=null,this.isRunning=!1,this.lastTime=0}init(){}start(){if(this.animationController.isAnimating())return this._chainTarget;if(this.animationController.start()){if(this._state.isRunning=!0,this.isRunning=!0,"classic"===this.config.renderingStyle&&this.particleSystem){const e=this.stateMachine.getCurrentState(),{emotion:t}=e,i=h(t);let s,n;if(this.renderer&&this.renderer.getCurrentOrbPosition){const e=this.renderer.getCurrentOrbPosition();s=e.x,n=e.y}else s=this.canvasManager.width/2,n=this.canvasManager.height/2;if(this.particleSystem.clear(),i.particleRate>0){const e=Math.min(3,Math.floor(i.particleRate/4));e>0&&this.particleSystem.burst(e,i.particleBehavior,s,n)}}this.degradationManager&&this.degradationManager.startMonitoring(),this._emit("started")}return this._chainTarget}stop(){return this.animationController.isAnimating()?(this._state.speaking&&this.audioHandler&&this.audioHandler.stopSpeaking(),this.animationController.stop()&&(this._state.isRunning=!1,this.isRunning=!1,this.degradationManager&&this.degradationManager.stopMonitoring(),this._emit("stopped")),this._chainTarget):this._chainTarget}update(e){if(this._state.speaking&&this.audioLevelProcessor&&this.audioLevelProcessor.isProcessingActive()&&this.audioLevelProcessor.updateAudioLevel(e),"classic"===this.config.renderingStyle){if(this.gazeTracker&&(this.gazeTracker.update(e),"suspicion"===this.stateMachine.getCurrentState().emotion)){const{mousePos:e}=this.gazeTracker,t=this.canvas.width/2,i=this.canvas.height/2,s=Math.sqrt(Math.pow(e.x-t,2)+Math.pow(e.y-i,2)),n=l("suspicion");if(n&&n.visual){const e=Math.min(t,i),a=Math.max(0,Math.min(1,1-s/e));n.visual.threatLevel=a}}if(this.idleBehavior&&this.idleBehavior.update(e),this.gazeTracker&&this.idleBehavior){const e=this.gazeTracker.getGazeOffset(),t=this.idleBehavior.getSwayOffset(),i=this.gazeTracker.getState(),s={offset:{x:e.x+t.x,y:e.y+t.y},proximity:i.proximity,isFocused:i.isFocused};this.renderer&&this.renderer.setGazeData&&this.renderer.setGazeData(s)}}if(this.pluginSystem){const t=this.stateMachine.getCurrentState();this.pluginSystem.update(e,t)}}destroy(){this.stop()}}class _r{constructor(e){if(!e.errorBoundary)throw new Error("ExecutionLifecycleManager: errorBoundary required");if(!e.animationController)throw new Error("ExecutionLifecycleManager: animationController required");if(!e.visualizationRunner)throw new Error("ExecutionLifecycleManager: visualizationRunner required");if(!e.state)throw new Error("ExecutionLifecycleManager: state required");if(!e.emit)throw new Error("ExecutionLifecycleManager: emit required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.visualizationRunner=e.visualizationRunner,this.soundSystem=e.soundSystem||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}start(){return this.errorBoundary.wrap(()=>this.visualizationRunner.start(),"start",this._chainTarget)()}stop(){return this.errorBoundary.wrap(()=>this.visualizationRunner.stop(),"stop",this._chainTarget)()}pause(){return this.errorBoundary.wrap(()=>this.animationController.isAnimating()?(this.animationController.stop(),this._state.isRunning=!1,this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.stopAmbientTone(200),this._emit("paused"),this._chainTarget):this._chainTarget,"pause",this._chainTarget)()}resume(){return this.errorBoundary.wrap(()=>(this.animationController.isAnimating()||(this.animationController.start(),this._state.isRunning=!0,this._emit("resumed")),this._chainTarget),"resume",this._chainTarget)()}isActive(){return this.animationController.isAnimating()}}class Ir{constructor(e){if(!e.errorBoundary)throw new Error("AnimationFrameController: errorBoundary required");if(!e.animationController)throw new Error("AnimationFrameController: animationController required");if(!e.config)throw new Error("AnimationFrameController: config required");if(!e.emit)throw new Error("AnimationFrameController: emit required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.positionController=e.positionController||null,this.config=e.config,this._emit=e.emit,this._chainTarget=e.chainTarget||this}setTargetFPS(e){const t=Math.max(15,Math.min(120,e));return this.config.targetFPS=t,this.animationController.setTargetFPS(t),this._emit("targetFPSChanged",{targetFPS:t}),this._chainTarget}getTargetFPS(){return this.animationController.targetFPS}setPosition(e,t,i=0){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.setOffset(e,t,i)),this._chainTarget}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.animateOffset(e,t,i,s,n)),this._chainTarget}getPosition(){return this.errorBoundary.wrap(()=>{if(!this.positionController||"function"!=typeof this.positionController.getPosition)return null;const e="undefined"!=typeof window,t=e?window.innerWidth/2:0,i=e?window.innerHeight/2:0;return this.positionController.getPosition(t,i)},"get-position",this._chainTarget)()}}class Rr{constructor(e){if(!e.errorBoundary)throw new Error("ShapeTransformManager: errorBoundary required");if(!e.emit)throw new Error("ShapeTransformManager: emit required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this.shapeMorpher=e.shapeMorpher||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this}morphTo(e,t={}){return this.errorBoundary.wrap(()=>this.shapeMorpher?(this.shapeMorpher.morphTo(e,t),this.renderer&&(this.renderer.shapeMorpher=this.shapeMorpher),this._emit("shapeMorphStarted",{from:this.shapeMorpher.currentShape,to:e}),this._chainTarget):this._chainTarget,"morphTo",this._chainTarget)()}setBackdrop(e={}){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.backdropRenderer&&this.renderer.backdropRenderer.setConfig(e),this._chainTarget),"setBackdrop",this._chainTarget)()}getBackdrop(){return this.errorBoundary.wrap(()=>this.renderer&&this.renderer.backdropRenderer?this.renderer.backdropRenderer.getConfig():null,"getBackdrop",this._chainTarget)()}}class Br{constructor(e){if(!e.errorBoundary)throw new Error("EventListenerManager: errorBoundary required");if(!e.eventManager)throw new Error("EventListenerManager: eventManager required");this.errorBoundary=e.errorBoundary,this.eventManager=e.eventManager,this._chainTarget=e.chainTarget||this}on(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.on(e,t),this._chainTarget),"event-listener-add",this._chainTarget)()}off(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.off(e,t),this._chainTarget),"event-listener-remove",this._chainTarget)()}once(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.once(e,t),this._chainTarget),"event-listener-once",this._chainTarget)()}removeAllListeners(e=null){return this.errorBoundary.wrap(()=>(this.eventManager.removeAllListeners(e),this._chainTarget),"event-listeners-clear",this._chainTarget)()}listenerCount(e){return this.eventManager.listenerCount(e)}getEventNames(){return this.eventManager.getEventNames()}getEventStats(){return this.eventManager.getEventStats()}getEventDebugInfo(){return this.eventManager.getDebugInfo()}emit(e,t=null){this.eventManager.emit(e,t)}}class zr{constructor(e){if(!e.tts)throw new Error("TTSManager: tts required");if(!e.state)throw new Error("TTSManager: state required");this.speechManager=e.speechManager||null,this.renderer=e.renderer||null,this.tts=e.tts,this._state=e.state,this._chainTarget=e.chainTarget||this}getTTSVoices(){return this.tts.available?window.speechSynthesis.getVoices():[]}isTTSSpeaking(){return this.tts.speaking}speak(e,t={}){return this.speechManager?this.speechManager.speak(e,t):this._chainTarget}setTTSSpeaking(e){this._state.ttsSpeaking=e,this.renderer&&this.renderer.startSpeaking&&(e?this.renderer.startSpeaking():this.renderer.stopSpeaking()),this._state.speaking=e}getVoices(){return window.speechSynthesis?window.speechSynthesis.getVoices():[]}stopTTS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),this.setTTSSpeaking(!1))}}class Fr{constructor(e){if(!e.errorBoundary)throw new Error("SpeechReactivityManager: errorBoundary required");if(!e.audioLevelProcessor)throw new Error("SpeechReactivityManager: audioLevelProcessor required");if(!e.state)throw new Error("SpeechReactivityManager: state required");if(!e.emit)throw new Error("SpeechReactivityManager: emit required");this.errorBoundary=e.errorBoundary,this.audioLevelProcessor=e.audioLevelProcessor,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}connectAudioSource(e){return this.errorBoundary.wrap(()=>this._state.audioAnalyser&&e&&"function"==typeof e.connect?(e.connect(this._state.audioAnalyser),this._emit("audioSourceConnected",{audioSource:e}),this._chainTarget):this._chainTarget,"audio-source-connection",this._chainTarget)()}getAudioLevel(){return this._state.speaking?this._state.audioLevel:0}isSpeaking(){return this._state.speaking}setAudioSmoothing(e){return this.errorBoundary.wrap(()=>{const t=Math.max(0,Math.min(1,e));return this._state.audioAnalyser&&(this._state.audioAnalyser.smoothingTimeConstant=t),this._chainTarget},"audio-smoothing",this._chainTarget)()}getAudioStats(){return this.audioLevelProcessor.getStats()}updateAudioConfig(e){this.audioLevelProcessor.updateConfig(e)}}class Or{constructor(e){if(!e.emit)throw new Error("CanvasResizeManager: emit required");this.renderer=e.renderer||null,this.stateMachine=e.stateMachine||null,this.particleSystem=e.particleSystem||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this}handleResize(e,t,i){if(this.renderer&&this.renderer.initOffscreenCanvas&&this.renderer.initOffscreenCanvas(),this.stateMachine){const{currentEmotion:e}=this.stateMachine,{currentUndertone:t}=this.stateMachine;e&&this.stateMachine.setEmotion(e),t&&"none"!==t&&this.stateMachine.setUndertone(t)}this._emit("resize",{width:e,height:t,dpr:i})}clearParticles(){return this.particleSystem&&this.particleSystem.clear(),this._chainTarget}setParticleSystemCanvasDimensions(e,t){return this.particleSystem&&(this.particleSystem.canvasWidth=e,this.particleSystem.canvasHeight=t),this._chainTarget}}class Lr{constructor(e){if(!e.errorBoundary)throw new Error("OffsetPositionManager: errorBoundary required");if(!e.positionController)throw new Error("OffsetPositionManager: positionController required");this.errorBoundary=e.errorBoundary,this.positionController=e.positionController,this._chainTarget=e.chainTarget||this}setOffset(e,t,i=0){return this.errorBoundary.wrap(()=>(this.positionController.setOffset(e,t,i),this._chainTarget),"offset-setting",this._chainTarget)()}getOffset(){return this.errorBoundary.wrap(()=>this.positionController.getOffset(),"offset-getting",this._chainTarget)()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.errorBoundary.wrap(()=>(this.positionController.animateOffset(e,t,i,s,n),this._chainTarget),"offset-animation",this._chainTarget)()}}class qr{constructor(e){if(!e.canvasResizeManager)throw new Error("VisualTransformationManager: canvasResizeManager required");if(!e.offsetPositionManager)throw new Error("VisualTransformationManager: offsetPositionManager required");if(!e.shapeTransformManager)throw new Error("VisualTransformationManager: shapeTransformManager required");this.canvasResizeManager=e.canvasResizeManager,this.offsetPositionManager=e.offsetPositionManager,this.shapeTransformManager=e.shapeTransformManager,this._chainTarget=e.chainTarget||this}setOffset(e,t,i=0){return this.offsetPositionManager.setOffset(e,t,i)}getOffset(){return this.offsetPositionManager.getOffset()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.offsetPositionManager.animateOffset(e,t,i,s,n)}morphTo(e,t={}){return this.shapeTransformManager.morphTo(e,t)}setBackdrop(e={}){return this.shapeTransformManager.setBackdrop(e)}getBackdrop(){return this.shapeTransformManager.getBackdrop()}handleResize(e,t,i){this.canvasResizeManager.handleResize(e,t,i)}clearParticles(){return this.canvasResizeManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this.canvasResizeManager.setParticleSystemCanvasDimensions(e,t)}}class Gr{constructor(e){if(!e.errorBoundary)throw new Error("FrustrationContextManager: errorBoundary required");if(!e.contextManager)throw new Error("FrustrationContextManager: contextManager required");this.errorBoundary=e.errorBoundary,this.contextManager=e.contextManager,this._chainTarget=e.chainTarget||this}updateContext(e){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.update(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"context-update",this._chainTarget)()}incrementFrustration(e=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.incrementFrustration(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-increment",this._chainTarget)()}decrementFrustration(e=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.decrementFrustration(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-decrement",this._chainTarget)()}resetFrustration(){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.resetFrustration(),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-reset",this._chainTarget)()}}class Hr{constructor(e,t={}){if(!e)throw new Error("LLMResponseHandler requires a mascot instance");this.mascot=e,this.config={autoMorphShapes:!0,morphDuration:1e3,autoExpressGestures:!0,gestureTiming:300,gestureIntensity:.7,useFallbackGestures:!0,useSemanticPerformances:!0,enableContextTracking:!0,emotionToShapeMap:{},actionToGestureMap:{},...t},this.schema={message:"string",emotion:["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity"],sentiment:["positive","neutral","negative"],action:["none","offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond"],frustrationLevel:"number",shape:["circle","heart","star","sun","moon","eclipse","solar","lunar","square","triangle","suspicion"],gesture:["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","jump","orbital","hula","scan","twist","burst","directional","settle","fade","hold","breathe","peek","sparkle","shimmer","wiggle","groove","point","lean","reach","headBob","rain","twitch","sway","float","jitter","orbit"]},this.defaultShapeMap={joy:"star",love:"heart",empathy:"heart",excitement:"sun",calm:"moon",concern:"circle",triumph:"star",curiosity:"circle",neutral:"circle"},this.defaultGestureMap={offer_help:"reach",celebrate:"sparkle",guide:"point",reassure:"nod",greet:"wave",confirm:"nod",deny:"shake",emphasize:"pulse",question:"tilt",think:"orbit",listen:"settle",respond:"bounce"},this.semanticActionMap={offer_help:"offering_help",celebrate:"celebrating",guide:"guiding",reassure:"reassuring",greet:"greeting",confirm:"confirming",deny:"denying",emphasize:"emphasizing",question:"questioning",think:"thinking",listen:"listening",respond:"responding"}}async handle(e,t={}){try{t.skipValidation||this.validateResponse(e);const{emotion:i="neutral",sentiment:s="neutral",action:n="none",shape:a,gesture:r,frustrationLevel:o=0}=e,l=void 0!==t.intensity?t.intensity:this.calculateIntensity(o,s);if(this.config.enableContextTracking&&this.mascot.updateContext&&this.mascot.updateContext({frustration:o,sentiment:s}),this.config.useSemanticPerformances&&this.mascot.perform&&this.semanticActionMap[n]){const e=this.semanticActionMap[n];try{return await this.mascot.perform(e,{context:{frustration:o,sentiment:s,urgency:o>60?"high":o>30?"medium":"low"},intensity:l}),a&&this.config.autoMorphShapes&&await this.morphToShape(a),this.mascot}catch(t){console.warn(`Semantic performance '${e}' not available, using manual choreography`)}}return await this.choreographResponse(i,n,a,r,l),this.mascot}catch(e){return console.warn("[LLMResponseHandler] Error handling LLM response:",e),this.mascot}}async choreographResponse(e,t,i,s,n){if(this.mascot.setEmotion(e,n),this.config.autoMorphShapes){const s=i||this.getShapeForEmotion(e,t);s&&await this.morphToShape(s)}if(this.config.autoExpressGestures){const e=s||this.getGestureForAction(t);e&&(await this.delay(this.config.gestureTiming),this.mascot.express(e,{intensity:this.config.gestureIntensity}))}}calculateIntensity(e,t){let i=.5;return i+=e/100*.3,"positive"===t?i+=.2:"negative"===t&&(i+=.3),Math.max(.3,Math.min(1,i))}getShapeForEmotion(e,t){return this.config.emotionToShapeMap[e]?this.config.emotionToShapeMap[e]:"celebrate"===t?"star":"greet"===t?"sun":this.defaultShapeMap[e]||null}getGestureForAction(e){return this.config.useFallbackGestures?this.config.actionToGestureMap[e]?this.config.actionToGestureMap[e]:this.defaultGestureMap[e]||null:null}morphToShape(e){e&&"circle"!==e&&this.mascot.morphTo&&this.mascot.morphTo(e,{duration:this.config.morphDuration})}validateResponse(e){if(!e||"object"!=typeof e)throw new Error("LLM response must be an object");if(e.emotion&&!this.schema.emotion.includes(e.emotion)&&console.warn(`Unknown emotion: ${e.emotion}. Using 'neutral'`),e.sentiment&&!this.schema.sentiment.includes(e.sentiment)&&console.warn(`Unknown sentiment: ${e.sentiment}. Using 'neutral'`),e.action&&!this.schema.action.includes(e.action)&&console.warn(`Unknown action: ${e.action}. Using 'none'`),e.shape&&!this.schema.shape.includes(e.shape)&&console.warn(`Unknown shape: ${e.shape}. Ignoring.`),e.gesture&&!this.schema.gesture.includes(e.gesture)&&console.warn(`Unknown gesture: ${e.gesture}. Ignoring.`),void 0!==e.frustrationLevel){const t=Number(e.frustrationLevel);(isNaN(t)||t<0||t>100)&&console.warn(`Invalid frustrationLevel: ${e.frustrationLevel}. Using 0.`)}}getSchema(){return{...this.schema}}configure(e){return Object.assign(this.config,e),this}delay(e){return new Promise(t=>setTimeout(t,e))}static getAvailableEmotions(){return["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity"]}static getAvailableActions(){return["none","offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond"]}static getAvailableShapes(){return["circle","heart","star","sun","moon","eclipse","solar","lunar","square","triangle","suspicion"]}static getAvailableGestures(){return["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","jump","orbital","hula","scan","twist","burst","directional","settle","fade","hold","breathe","peek","sparkle","shimmer","wiggle","groove","point","lean","reach","headBob","rain","twitch","sway","float","jitter","orbit"]}}class jr{constructor(e){if(!e.errorBoundary)throw new Error("LLMIntegrationBridge: errorBoundary required");this.errorBoundary=e.errorBoundary,this._mascotRef=e.mascotRef,this._chainTarget=e.chainTarget||this,this._llmHandler=null}_getHandler(e={}){return this._llmHandler||(this._llmHandler=new Hr(this._mascotRef,e)),this._llmHandler}handleLLMResponse(e,t={}){return this.errorBoundary.wrap(async()=>{const i=this._getHandler(t);return await i.handle(e,t),this._chainTarget},"handleLLMResponse",this._chainTarget)()}configureLLMHandler(e){return this.errorBoundary.wrap(()=>(this._getHandler(e).configure(e),this._chainTarget),"configureLLMHandler",this._chainTarget)()}getLLMResponseSchema(){return this._getHandler().getSchema()}static getLLMPromptTemplate(e={}){return function(e={}){const{domain:t="general assistance",personality:i="friendly, empathetic, and helpful",brand:s="our service",customEmotions:n=[],customActions:a=[]}=e,r=["offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond",...a];return`You are a ${i} AI assistant for ${s}, providing ${t}. You have an animated mascot companion that responds to the emotional tone and context of conversations.\n\n**CRITICAL: You must ONLY respond with valid JSON. Do not include any text before or after the JSON object. Do not use markdown code blocks.**\n\n## Response Format\n\nYour response must be a valid JSON object with this exact structure:\n\n{\n "message": "your helpful response here (2-3 sentences max)",\n "emotion": "${["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity",...n].join("|")}",\n "sentiment": "positive|neutral|negative",\n "action": "${r.join("|")}",\n "frustrationLevel": 0-100,\n "shape": "heart|star|sun|moon|circle|square|triangle (optional)",\n "gesture": "nod|wave|sparkle|point|reach|bounce|pulse|... (optional)"\n}\n\n## Guidelines\n\n**Emotional Intelligence:**\n- Detect emotional tone in user messages (frustration, confusion, satisfaction, joy, etc.)\n- Respond with empathy when users are frustrated or confused\n- Celebrate successes and positive moments\n- Match your emotion to the user's needs\n\n**Communication Style:**\n- Be concise (max 2-3 sentences)\n- Use warm, encouraging, ${i} language\n- Provide specific, actionable solutions\n- Avoid generic responses\n\n**Frustration Tracking:**\n- 0-20: User is calm and satisfied\n- 21-40: Minor confusion or concern\n- 41-60: Moderate frustration\n- 61-80: High frustration, needs urgent help\n- 81-100: Critical frustration, escalate immediately\n\n## Emotion Guidelines\n\n- **joy**: User is happy, things are going well โ Use for celebrations, positive outcomes\n- **empathy**: User is struggling or frustrated โ Use to show understanding and care\n- **calm**: Neutral, instructional โ Use for steady guidance\n- **excitement**: High energy, anticipation โ Use for big wins or new features\n- **concern**: User has a problem โ Use when addressing issues\n- **neutral**: Default state โ Use for routine interactions\n- **triumph**: Achievement unlocked โ Use for major successes\n- **love**: Deep appreciation โ Use when user expresses gratitude\n- **curiosity**: Exploring, learning โ Use when user asks questions\n\n## Shape Guidelines (Optional - enhances emotional expression)\n\n- **heart**: Empathy, love, appreciation, caring\n- **star**: Achievements, excellence, celebration\n- **sun**: Energy, positivity, brightness, enthusiasm\n- **moon**: Calm, soothing, gentle, nighttime\n- **circle**: Neutral, default, balanced\n- **square**: Structured, organized, professional\n- **triangle**: Directional, focused, pointing\n\nUse shapes to reinforce emotions - e.g., "heart" + "empathy" for caring support.\n\n## Gesture Guidelines (Optional - adds personality)\n\n- **nod**: Confirming, agreeing, understanding\n- **wave**: Greetings, farewells\n- **sparkle**: Celebration, magic moments, success\n- **point**: Directing attention, guidance\n- **reach**: Offering help, extending support\n- **bounce**: Excitement, enthusiasm, playfulness\n- **pulse**: Emphasis, importance, attention\n- **shake**: No, error, disagreement\n- **shimmer**: Delight, wonder, positive surprise\n\n## Action Guidelines\n\n- **offer_help**: User needs assistance โ Trigger helpful gestures\n- **celebrate**: Success or achievement โ Trigger celebratory animations\n- **guide**: Providing instructions โ Trigger directional gestures\n- **reassure**: Calming concerns โ Trigger comforting animations\n- **greet**: Starting conversation โ Trigger welcoming gestures\n- **confirm**: Validating user action โ Trigger affirmative gestures\n- **deny**: Rejecting or correcting โ Trigger negative gestures\n- **emphasize**: Highlighting important info โ Trigger attention gestures\n\n## Example Responses\n\n**User expresses frustration:**\n{"message": "I totally understand how frustrating this is! Let me help you get this sorted out right now. What specifically isn't working?", "emotion": "empathy", "sentiment": "negative", "action": "offer_help", "frustrationLevel": 75, "shape": "heart", "gesture": "reach"}\n\n**User asks for guidance:**\n{"message": "Great question! Hold the barcode about 6 inches from the scanner until you hear a beep. The item will appear in your cart.", "emotion": "calm", "sentiment": "neutral", "action": "guide", "frustrationLevel": 20, "shape": "square", "gesture": "point"}\n\n**User succeeds:**\n{"message": "Perfect! You've got it now. Anything else I can help you with today?", "emotion": "joy", "sentiment": "positive", "action": "celebrate", "frustrationLevel": 0, "shape": "star", "gesture": "sparkle"}\n\n**User greets:**\n{"message": "Hello! I'm here to make your ${t} experience smooth and easy. How can I help you today?", "emotion": "joy", "sentiment": "positive", "action": "greet", "frustrationLevel": 0, "shape": "sun", "gesture": "wave"}\n\n**User says thanks:**\n{"message": "You're so welcome! I'm thrilled I could help. Have a wonderful day!", "emotion": "love", "sentiment": "positive", "action": "celebrate", "frustrationLevel": 0, "shape": "heart", "gesture": "sparkle"}\n\nRemember: Always respond with valid JSON only. No extra text, no markdown formatting.`}(e)}static getLLMEmotions(){return Hr.getAvailableEmotions()}static getLLMActions(){return Hr.getAvailableActions()}static getLLMShapes(){return Hr.getAvailableShapes()}static getLLMGestures(){return Hr.getAvailableGestures()}}class $r{constructor(e){if(!e.errorBoundary)throw new Error("DiagnosticsManager: errorBoundary required");if(!e.animationController)throw new Error("DiagnosticsManager: animationController required");if(!e.stateMachine)throw new Error("DiagnosticsManager: stateMachine required");if(!e.config)throw new Error("DiagnosticsManager: config required");if(!e.state)throw new Error("DiagnosticsManager: state required");if(!e.getCurrentState)throw new Error("DiagnosticsManager: getCurrentState required");if(!e.getAudioStats)throw new Error("DiagnosticsManager: getAudioStats required");if(!e.getEventStats)throw new Error("DiagnosticsManager: getEventStats required");this.errorBoundary=e.errorBoundary,this.degradationManager=e.degradationManager||null,this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.performanceSystem=e.performanceSystem||null,this.config=e.config,this._state=e.state,this._getCurrentState=e.getCurrentState,this._getAudioStats=e.getAudioStats,this._getEventStats=e.getEventStats,this._chainTarget=e.chainTarget||this}getBrowserCompatibility(){return{browser:ir.browser,features:ir.featureDetection.getFeatures(),capabilities:ir.capabilities,appliedPolyfills:ir.appliedPolyfills,optimizations:ir.browserOptimizations.getOptimizations()}}getDegradationStatus(){return this.degradationManager?{currentLevel:this.degradationManager.getCurrentLevel(),availableFeatures:this.degradationManager.getAvailableFeatures(),recommendedSettings:this.degradationManager.getRecommendedSettings(),performanceStats:this.degradationManager.getPerformanceStats(),allLevels:this.degradationManager.getAllLevels()}:null}setDegradationLevel(e){return!!this.degradationManager&&this.degradationManager.setLevel(e)}getDebugReport(){const e={timestamp:Date.now(),mascot:{isRunning:this._state.isRunning,speaking:this._state.speaking,debugMode:this._state.debugMode,config:this.config},currentState:this._getCurrentState(),performanceMetrics:this.getPerformanceMetrics(),audioStats:this._getAudioStats(),eventStats:this._getEventStats(),browserCompatibility:this.getBrowserCompatibility(),degradationStatus:this.getDegradationStatus(),runtimeCapabilities:ks.generateReport(),debuggerReport:Cs.getDebugReport()};return this._state.debugMode&&Cs.log("DEBUG","Generated debug report",{reportSize:JSON.stringify(e).length,sections:Object.keys(e)}),e}exportDebugData(){const e={metadata:{exportTime:Date.now(),version:"1.0.0",userAgent:navigator.userAgent,url:window.location?.href},mascotState:{config:this.config,currentState:this._getCurrentState(),isRunning:this._state.isRunning,speaking:this._state.speaking},performance:{metrics:this.getPerformanceMetrics(),degradationStatus:this.getDegradationStatus(),frameTimings:Cs.frameTimings},compatibility:{browser:this.getBrowserCompatibility(),runtimeCapabilities:ks.generateReport()},debuggerData:Cs.exportDebugData()};return this._state.debugMode&&Cs.log("INFO","Exported debug data",{dataSize:JSON.stringify(e).length}),e}getPerformanceMetrics(){const e=this.animationController.getPerformanceMetrics(),t=this.stateMachine.getCurrentState();return{...e,currentEmotion:t.emotion,currentUndertone:t.undertone,isTransitioning:t.isTransitioning,errorStats:this.errorBoundary.getErrorStats()}}getPerformanceAnalytics(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAnalytics():null,"performance-analytics",this._chainTarget)()}}class Wr{constructor(e){if(!e.errorBoundary)throw new Error("EmotionalStateQueryManager: errorBoundary required");if(!e.stateMachine)throw new Error("EmotionalStateQueryManager: stateMachine required");this.errorBoundary=e.errorBoundary,this.stateMachine=e.stateMachine,this.contextManager=e.contextManager||null,this.performanceSystem=e.performanceSystem||null,this._chainTarget=e.chainTarget||this}getEmotionalColor(){const e=this.stateMachine.getCurrentEmotionalProperties();return e?.primaryColor||"#B0B0B0"}getCurrentState(){return this.stateMachine.getCurrentState()}getAvailableEmotions(){return this.stateMachine.getAvailableEmotions()}getAvailableUndertones(){return this.stateMachine.getAvailableUndertones()}getAvailableGestures(){return["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","slowBlink","look","settle","breathIn","breathOut","breathHold","breathHoldEmpty","jump"]}getAvailablePerformances(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAllPerformanceNames():[],"available-performances",this._chainTarget)()}getAvailableShapes(){return gr.getAvailableShapes()}getContext(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getContext():null,"context-get",this._chainTarget)()}getContextAnalytics(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getAnalytics():null,"context-analytics",this._chainTarget)()}}class Ur{constructor(e){if(!e.diagnosticsManager)throw new Error("DebugProfilingManager: diagnosticsManager required");this.diagnosticsManager=e.diagnosticsManager,this._state=e.state||{debugMode:!1}}getDebugReport(){return this.diagnosticsManager.getDebugReport()}exportDebugData(){return this.diagnosticsManager.exportDebugData()}startProfiling(e,t={}){this._state.debugMode&&Cs.startProfile(e,t)}endProfiling(e){return this._state.debugMode?Cs.endProfile(e):null}takeMemorySnapshot(e){this._state.debugMode&&Cs.takeMemorySnapshot(e)}clearDebugData(){Cs.clear(),this._state.debugMode&&Cs.log("INFO","Debug data cleared")}getRuntimeCapabilities(){return ks.generateReport()}}class Vr{constructor(e){if(!e.errorBoundary)throw new Error("PerformanceBehaviorManager: errorBoundary required");if(!e.frustrationContextManager)throw new Error("PerformanceBehaviorManager: frustrationContextManager required");if(!e.emotionalStateQueryManager)throw new Error("PerformanceBehaviorManager: emotionalStateQueryManager required");if(!e.diagnosticsManager)throw new Error("PerformanceBehaviorManager: diagnosticsManager required");this.errorBoundary=e.errorBoundary,this.performanceSystem=e.performanceSystem||null,this.frustrationContextManager=e.frustrationContextManager,this.emotionalStateQueryManager=e.emotionalStateQueryManager,this.diagnosticsManager=e.diagnosticsManager,this._chainTarget=e.chainTarget||this}perform(e,t={}){return this.errorBoundary.wrap(async()=>this.performanceSystem?(t.context&&this.frustrationContextManager.updateContext(t.context),await this.performanceSystem.perform(e,{...t,mascot:this._chainTarget}),this._chainTarget):(console.warn("[EmotiveMascot] PerformanceSystem not initialized"),this._chainTarget),"semantic-performance",this._chainTarget)()}registerPerformance(e,t){return this.errorBoundary.wrap(()=>this.performanceSystem?(this.performanceSystem.registerPerformance(e,t),this._chainTarget):(console.warn("[EmotiveMascot] PerformanceSystem not initialized"),this._chainTarget),"performance-register",this._chainTarget)()}getAvailablePerformances(){return this.emotionalStateQueryManager.getAvailablePerformances()}getPerformanceAnalytics(){return this.diagnosticsManager.getPerformanceAnalytics()}getContextAnalytics(){return this.emotionalStateQueryManager.getContextAnalytics()}}class Yr{constructor(e){if(!e.diagnosticsManager)throw new Error("PerformanceMonitoringManager: diagnosticsManager required");if(!e.animationFrameController)throw new Error("PerformanceMonitoringManager: animationFrameController required");if(!e.animationController)throw new Error("PerformanceMonitoringManager: animationController required");if(!e.particleSystem)throw new Error("PerformanceMonitoringManager: particleSystem required");if(!e.config)throw new Error("PerformanceMonitoringManager: config required");this.diagnosticsManager=e.diagnosticsManager,this.degradationManager=e.degradationManager||null,this.animationFrameController=e.animationFrameController,this.animationController=e.animationController,this.particleSystem=e.particleSystem,this.healthCheckManager=e.healthCheckManager,this.config=e.config,this._chainTarget=e.chainTarget||this}getDegradationStatus(){return this.diagnosticsManager.getDegradationStatus()}setDegradationLevel(e){return this.diagnosticsManager.setDegradationLevel(e)}isFeatureAvailable(e){return this.degradationManager?this.degradationManager.isFeatureAvailable(e):ir.featureDetection.getFeatures()[e]||!1}setTargetFPS(e){return this.animationFrameController.setTargetFPS(e)}getTargetFPS(){return this.animationFrameController.getTargetFPS()}setPerformanceDegradation(e){const t=this.animationController.getPerformanceMetrics();if(e&&!t.performanceDegradation){const e=this.particleSystem.maxParticles,t=Math.max(5,Math.floor(.5*e));this.particleSystem.setMaxParticles(t)}else!e&&t.performanceDegradation&&this.particleSystem.setMaxParticles(this.config.maxParticles);return this._chainTarget}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}}class Xr{constructor(e){if(!e.errorBoundary)throw new Error("HealthCheckManager: errorBoundary required");if(!e.diagnosticsManager)throw new Error("HealthCheckManager: diagnosticsManager required");if(!e.mobileOptimization)throw new Error("HealthCheckManager: mobileOptimization required");if(!e.accessibilityManager)throw new Error("HealthCheckManager: accessibilityManager required");if(!e.config)throw new Error("HealthCheckManager: config required");this.errorBoundary=e.errorBoundary,this.systemStatusReporter=e.systemStatusReporter||null,this.diagnosticsManager=e.diagnosticsManager,this.mobileOptimization=e.mobileOptimization,this.accessibilityManager=e.accessibilityManager,this.config=e.config,this._chainTarget=e.chainTarget||this}getSystemStatus(){return this.systemStatusReporter?this.systemStatusReporter.getSystemStatus():{}}setDebugMode(e){return this.config.showDebug=!!e,this.config.showFPS=!!e,this._chainTarget}triggerTestError(e="manual-test"){return this.errorBoundary.wrap(()=>{throw new Error(`Test error triggered in context: ${e}`)},e,this._chainTarget)()}getPerformanceMetrics(){return this.diagnosticsManager.getPerformanceMetrics()}getMobileStatus(){return this.mobileOptimization.getStatus()}getAccessibilityStatus(){return this.accessibilityManager.getStatus()}}class Nr{constructor(e){this.mascot=e}initialize(e){const t=this.mascot;this._initializeLayer1(t,e),this._initializeLayer2(t,e),this._initializeLayer3(t,e),t.audioHandler.init(),t.stateCoordinator.init(),t.visualizationRunner.init()}_initializeLayer1(e,t){e.audioHandler=new Pr({audioAnalyzer:e.audioAnalyzer,audioLevelProcessor:e.audioLevelProcessor,shapeMorpher:e.shapeMorpher,soundSystem:e.soundSystem,renderer:e.renderer,errorBoundary:e.errorBoundary,config:e.config,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get audioLevel(){return e.audioLevel},set audioLevel(t){e.audioLevel=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.stateCoordinator=new Ar({stateMachine:e.stateMachine,particleSystem:e.particleSystem,canvasManager:e.canvasManager,renderer:e.renderer,soundSystem:e.soundSystem,config:e.config,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.visualizationRunner=new Dr({animationController:e.animationController,stateMachine:e.stateMachine,particleSystem:e.particleSystem,canvasManager:e.canvasManager,renderer:e.renderer,audioHandler:e.audioHandler,audioLevelProcessor:e.audioLevelProcessor,gazeTracker:e.gazeTracker,idleBehavior:e.idleBehavior,degradationManager:e.degradationManager,pluginSystem:e.pluginSystem,config:e.config,canvas:e.canvas,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get isRunning(){return e.isRunning},set isRunning(t){e.isRunning=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.executionLifecycleManager=new _r({animationController:e.animationController,visualizationRunner:e.visualizationRunner,idleBehavior:e.idleBehavior,gazeTracker:e.gazeTracker,renderer:e.renderer,errorBoundary:e.errorBoundary,state:{get isRunning(){return e.isRunning},set isRunning(t){e.isRunning=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.animationFrameController=new Ir({animationController:e.animationController,positionController:e.positionController,config:e.config,errorBoundary:e.errorBoundary,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.shapeTransformManager=new Rr({shapeMorpher:e.shapeMorpher,renderer:e.renderer,errorBoundary:e.errorBoundary,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.eventListenerManager=new Br({eventManager:e.eventManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.ttsManager=new zr({soundSystem:e.soundSystem,errorBoundary:e.errorBoundary,config:e.config,tts:e.tts,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.speechReactivityManager=new Fr({audioLevelProcessor:e.audioLevelProcessor,renderer:e.renderer,errorBoundary:e.errorBoundary,config:e.config,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get audioLevel(){return e.audioLevel},set audioLevel(t){e.audioLevel=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.canvasResizeManager=new Or({renderer:e.renderer,stateMachine:e.stateMachine,particleSystem:e.particleSystem,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.offsetPositionManager=new Lr({positionController:e.positionController,errorBoundary:e.errorBoundary,chainTarget:e}),e.visualTransformationManager=new qr({canvasResizeManager:e.canvasResizeManager,offsetPositionManager:e.offsetPositionManager,shapeTransformManager:e.shapeTransformManager,chainTarget:e}),e.frustrationContextManager=new Gr({contextManager:e.contextManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.llmIntegrationBridge=new jr({stateMachine:e.stateMachine,gestureController:e.gestureController,errorBoundary:e.errorBoundary,state:{get llmHandler(){return e.llmHandler},set llmHandler(t){e.llmHandler=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e})}_initializeLayer2(e,t){e.diagnosticsManager=new $r({errorBoundary:e.errorBoundary,degradationManager:e.degradationManager,animationController:e.animationController,stateMachine:e.stateMachine,performanceSystem:e.performanceSystem,config:e.config,state:{get isRunning(){return e.isRunning},get speaking(){return e.speaking},get debugMode(){return e.debugMode}},getCurrentState:()=>e.getCurrentState(),getAudioStats:()=>e.getAudioStats(),getEventStats:()=>e.getEventStats(),chainTarget:e}),e.emotionalStateQueryManager=new Wr({stateMachine:e.stateMachine,performanceSystem:e.performanceSystem,contextManager:e.contextManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.debugProfilingManager=new Ur({diagnosticsManager:e.diagnosticsManager,errorBoundary:e.errorBoundary,state:{get debugMode(){return e.debugMode},set debugMode(t){e.debugMode=t}},chainTarget:e})}_initializeLayer3(e,t){e.performanceBehaviorManager=new Vr({errorBoundary:e.errorBoundary,performanceSystem:e.performanceSystem,frustrationContextManager:e.frustrationContextManager,emotionalStateQueryManager:e.emotionalStateQueryManager,diagnosticsManager:e.diagnosticsManager,chainTarget:e}),e.healthCheckManager=new Xr({errorBoundary:e.errorBoundary,systemStatusReporter:e.systemStatusReporter,diagnosticsManager:e.diagnosticsManager,mobileOptimization:e.mobileOptimization,accessibilityManager:e.accessibilityManager,config:e.config,chainTarget:e}),e.performanceMonitoringManager=new Yr({diagnosticsManager:e.diagnosticsManager,degradationManager:e.degradationManager,animationFrameController:e.animationFrameController,animationController:e.animationController,particleSystem:e.particleSystem,healthCheckManager:e.healthCheckManager,config:e.config,chainTarget:e})}}class Qr{constructor(e,t={}){this.mascot=e,this.userConfig=t}initialize(){this.initializeStateManager();const e=this.initializeConfiguration();return this.initializeCanvas(e),this.initializeCoreSystems(e),this.initializeAudioSystems(e),this.initializeInteractionSystems(e),this.initializeOptimizationSystems(e),this.initializeAnimationController(e),this.initializePerformanceSystems(e),this.initializeModularHandlers(e),this.finalizeInitialization(e),e}initializeStateManager(){this.mascot.stateManager=new kr({initialState:{debugMode:this.userConfig.enableDebug||!1},emit:(e,t)=>this.mascot.emit(e,t)}),this._createStateAliases()}initializeConfiguration(){const e=ir.browserOptimizations.getOptimizations(),t={canvasId:"emotive-mascot",targetFPS:60,enableAudio:ir.featureDetection.features.webAudio,soundEnabled:!1,masterVolume:.5,maxParticles:e.particleLimit,defaultEmotion:"neutral",enableAutoOptimization:!0,enableGracefulDegradation:!0,renderingStyle:"classic",enableGazeTracking:!0,enableIdleBehaviors:!0,renderSize:null,offsetX:0,offsetY:0,offsetZ:0,classicConfig:{coreColor:"#FFFFFF",coreSizeDivisor:12,glowMultiplier:2.5,defaultGlowColor:"#14B8A6"},topOffset:0,sentry:{enabled:!1,dsn:null,environment:"production",tracesSampleRate:.1},...this.userConfig};return this.mascot.config=t,t}initializeCanvas(e){if(this.mascot.canvas="string"==typeof e.canvasId?document.getElementById(e.canvasId):e.canvasId,!this.mascot.canvas)throw new Error(`Canvas with ID '${e.canvasId}' not found`);this.mascot.canvas.setAttribute("role","img"),this.mascot.canvas.setAttribute("aria-label","Animated emotional mascot visualization"),this.mascot.canvasManager=new Ps(this.mascot.canvas),this.mascot.positionController=new za({offsetX:e.offsetX,offsetY:e.offsetY,offsetZ:e.offsetZ,onUpdate:e=>{this.mascot.renderer&&this.mascot.renderer.updateEffectiveCenter(e)}}),e.renderSize&&e.renderSize.width&&e.renderSize.height&&this.mascot.canvasManager.setRenderSize(e.renderSize.width,e.renderSize.height),this.mascot.contextRecovery=new Qa(this.mascot.canvas),this.mascot.contextRecovery.onRecovery(e=>{this.mascot.renderer&&this.mascot.renderer.handleContextRecovery(e)}),ir.browserOptimizations.applyCanvasOptimizations(this.mascot.canvas,this.mascot.canvasManager.getContext())}initializeCoreSystems(e){this.mascot.stateMachine=new Zs(this.mascot.errorBoundary),this.mascot.particleSystem=new cn(e.maxParticles,this.mascot.errorBoundary),this.mascot.particleSystem.canvasWidth=this.mascot.canvasManager.width,this.mascot.particleSystem.canvasHeight=this.mascot.canvasManager.height,this.mascot.renderer=new ya(this.mascot.canvasManager,{...e.classicConfig,topOffset:e.topOffset||0,positionController:this.mascot.positionController}),this.mascot.renderer.stateMachine=this.mascot.stateMachine,this.mascot.stateMachine.renderer=this.mascot.renderer}initializeAudioSystems(e){this.mascot.shapeMorpher=new gr,this.mascot.audioAnalyzer=new mr,this.mascot.grooveTemplates=new vr,this.mascot.shapeMorpher.audioAnalyzer=this.mascot.audioAnalyzer,this.mascot.renderer.shapeMorpher=this.mascot.shapeMorpher,this.mascot.renderer.audioAnalyzer=this.mascot.audioAnalyzer,this.mascot.soundSystem=new La,this.mascot.tts={available:"undefined"!=typeof window&&"speechSynthesis"in window,speaking:!1,currentUtterance:null};const t=this.mascot;this.mascot.gestureController=new Cr({errorBoundary:t.errorBoundary,renderer:t.renderer,soundSystem:t.soundSystem,config:t.config,state:{get currentModularGesture(){return t.currentModularGesture},set currentModularGesture(e){t.currentModularGesture=e}},throttledWarn:t.throttledWarn,chainTarget:t}),this.mascot.gestureController.gestureCompatibility=yr,this.mascot.gestureController.init(),this.mascot.audioLevelProcessor=new Ha({spikeThreshold:e.spikeThreshold||1.5,minimumSpikeLevel:e.minimumSpikeLevel||.1,spikeMinInterval:e.spikeMinInterval||1e3})}initializeInteractionSystems(e){e.enableGazeTracking&&(this.mascot.gazeTracker=new ba(this.mascot.canvas,{smoothing:.1,maxOffset:.15,enabled:!0}),this.mascot.gazeTracker.setInteractionCallback(()=>{this.mascot.sleeping?this.mascot.wake():this.mascot.idleBehavior&&this.mascot.idleBehavior.resetIdleTimer()})),e.enableIdleBehaviors&&(this.mascot.idleBehavior=new va({enabled:!0,sleepTimeout:1/0}),this.mascot.idleBehavior.setCallback("onBlink",e=>{this.mascot.renderer&&this.mascot.renderer.state&&(this.mascot.renderer.state.blinking="start"===e.phase)}),this.mascot.idleBehavior.setCallback("onSleep",()=>{this.mascot.renderer&&this.mascot.renderer.enterSleepMode&&this.mascot.renderer.enterSleepMode()}),this.mascot.idleBehavior.setCallback("onWake",()=>{this.mascot.renderer&&this.mascot.renderer.wakeUp&&this.mascot.renderer.wakeUp()}))}initializeOptimizationSystems(e){this.mascot.degradationManager=null,this.mascot.accessibilityManager=new ja({enableReducedMotion:!1!==e.enableReducedMotion,enableHighContrast:!1!==e.enableHighContrast,enableScreenReaderSupport:!1!==e.enableScreenReaderSupport,enableKeyboardNavigation:!1!==e.enableKeyboardNavigation,colorBlindMode:e.colorBlindMode||"none"}),this.mascot.mobileOptimization=new $a({enableTouchOptimization:!1!==e.enableTouchOptimization,enableViewportHandling:!1!==e.enableViewportHandling,enableBatteryOptimization:!1!==e.enableBatteryOptimization}),this.mascot.mobileOptimization.setCanvas(this.mascot.canvas),this.mascot.pluginSystem=new Wa({mascot:this.mascot,enablePlugins:!1!==e.enablePlugins,validatePlugins:!1!==e.validatePlugins,sandboxPlugins:!1!==e.sandboxPlugins})}initializeAnimationController(e){try{this.mascot.animationController=new Ga(this.mascot.errorBoundary,{targetFPS:e.targetFPS})}catch(t){console.error("AnimationController initialization failed:",t),console.warn("[InitializationManager] Running with fallback AnimationController โ some features may be limited"),this.mascot.animationController=this.createFallbackAnimationController(e.targetFPS)}this.mascot.animationController.setSubsystems({stateMachine:this.mascot.stateMachine,particleSystem:this.mascot.particleSystem,renderer:this.mascot.renderer,soundSystem:this.mascot.soundSystem,canvasManager:this.mascot.canvasManager}),this.mascot.animationController.setEventCallback((e,t)=>{this.mascot.emit(e,t)}),this.mascot.animationController.setParentMascot(this.mascot),this.mascot.isRunning=!1}createFallbackAnimationController(e){return{isAnimating:()=>this.mascot.isRunning,start:()=>(this.mascot.isRunning=!0,!0),stop:()=>(this.mascot.isRunning=!1,!0),setTargetFPS:()=>{},targetFPS:e,getPerformanceMetrics:()=>({fps:0,isRunning:this.mascot.isRunning,performanceDegradation:!1,deltaTime:16,frameCount:0,targetFPS:e}),setSubsystems:()=>{},setEventCallback:()=>{},setParentMascot:()=>{},destroy:()=>{},deltaTime:16}}initializePerformanceSystems(e){this.mascot.contextManager=new Sr({enableHistory:!1!==e.enablePerformanceHistory,enableDecay:!1!==e.enableFrustrationDecay,historyLimit:e.performanceHistoryLimit||50,frustrationDecayRate:e.frustrationDecayRate||5,decayInterval:e.frustrationDecayInterval||1e4}),this.mascot.destructionManager&&(this.mascot.destructionManager.contextManager=this.mascot.contextManager),this.mascot.sequenceExecutor=new xr({mascot:this.mascot,eventManager:this.mascot.eventManager,allowConcurrent:!1!==e.allowConcurrentPerformances}),this.mascot.performanceSystem=new wr({mascot:this.mascot,contextManager:this.mascot.contextManager,sequenceExecutor:this.mascot.sequenceExecutor,eventManager:this.mascot.eventManager,enableAnalytics:!1!==e.enablePerformanceAnalytics})}initializeModularHandlers(e){new Nr(this.mascot).initialize(e);const t=this.mascot.destructionManager;t&&(t.gestureController=this.mascot.gestureController,t.stateCoordinator=this.mascot.stateCoordinator,t.visualizationRunner=this.mascot.visualizationRunner,t.audioHandler=this.mascot.audioHandler)}finalizeInitialization(e){e.enableAudio&&this.mascot.soundSystem.initialize().then(t=>{t&&this.mascot.soundSystem.setMasterVolume(e.masterVolume)}).catch(e=>{console.warn("[InitializationManager] Sound system initialization failed:",e)}),an.initialize(),this.mascot.rhythmIntegration=an,this.mascot.debugMode&&(Cs.log("INFO","Debug mode enabled for EmotiveMascot",{config:e,runtimeCapabilities:ks.generateReport()}),Cs.startProfile("mascot-initialization",{canvasId:e.canvasId,maxParticles:e.maxParticles})),this.mascot.setupAudioLevelProcessorCallbacks(),this.mascot.stateMachine.setEmotion(e.defaultEmotion),this.mascot.canvasManager.onResize((e,t,i)=>{this.mascot.handleResize(e,t,i)}),this.mascot.stateManager.debugMode&&(Cs.endProfile("mascot-initialization"),Cs.takeMemorySnapshot("post-initialization"))}_createStateAliases(){const e=this.mascot,t=e.stateManager;Object.defineProperties(e,{speaking:{get:()=>t.speaking,set(e){t.speaking=e},enumerable:!0,configurable:!0},recording:{get:()=>t.recording,set(e){t.recording=e},enumerable:!0,configurable:!0},sleeping:{get:()=>t.sleeping,set(e){t.sleeping=e},enumerable:!0,configurable:!0},isRunning:{get:()=>t.isRunning,set(e){t.isRunning=e},enumerable:!0,configurable:!0},debugMode:{get:()=>t.debugMode,set(e){t.debugMode=e},enumerable:!0,configurable:!0},audioLevel:{get:()=>t.audioLevel,set(e){t.audioLevel=e},enumerable:!0,configurable:!0},rhythmEnabled:{get:()=>t.rhythmEnabled,set(e){t.rhythmEnabled=e},enumerable:!0,configurable:!0},currentModularGesture:{get:()=>t.currentModularGesture,set(e){t.currentModularGesture=e},enumerable:!0,configurable:!0},breathePhase:{get:()=>t.breathePhase,set(e){t.breathePhase=e},enumerable:!0,configurable:!0},breatheStartTime:{get:()=>t.breatheStartTime,set(e){t.breatheStartTime=e},enumerable:!0,configurable:!0},orbScale:{get:()=>t.orbScale,set(e){t.orbScale=e},enumerable:!0,configurable:!0},warningTimestamps:{get:()=>t.warningTimestamps,set(e){t.warningTimestamps=e},enumerable:!0,configurable:!0},warningThrottle:{get:()=>t.warningThrottle,set(e){t.warningThrottle=e},enumerable:!0,configurable:!0}})}}class Jr{constructor(e){this.animationController=e.animationController||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.gazeTracker=e.gazeTracker||null,this.particleSystem=e.particleSystem,this.stateMachine=e.stateMachine,this._state=e.state||{debugMode:!1,speaking:!1}}buildRenderState(){return{renderStart:this._state.debugMode?performance.now():0,deltaTime:this.getDeltaTime(),renderState:this.createRenderState()}}getDeltaTime(){return this.animationController?this.animationController.deltaTime:16.67}createRenderState(){return{properties:this.stateMachine.getCurrentEmotionalProperties(),emotion:this.stateMachine.getCurrentState().emotion,undertone:this.stateMachine.getCurrentState().undertone,particleSystem:this.particleSystem,speaking:this._state.speaking,audioLevel:this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0,gazeOffset:this.getGazeOffset()}}getGazeOffset(){return this.gazeTracker?this.gazeTracker.currentGaze:{x:0,y:0}}}class Kr{constructor(e){this.canvasManager=e.canvasManager,this.config=e.config,this.gazeTracker=e.gazeTracker||null}updateThreatLevel(e){if("suspicion"!==e.emotion||!this.gazeTracker)return;const t=l("suspicion");if(!t||!t.visual)return;const i=this.calculateThreatLevel();t.visual.threatLevel=i}calculateThreatLevel(){this.gazeTracker.getState();const{mousePos:e}=this.gazeTracker,t=this.canvasManager.width/2,i=this.canvasManager.height/2-this.config.topOffset,s=this.calculateDistance(e,{x:t,y:i}),n=Math.min(this.canvasManager.width,this.canvasManager.height)/2;return Math.max(0,Math.min(1,1-s/n))}calculateDistance(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}}class Zr{constructor(e){this.renderer=e.renderer,this.stateMachine=e.stateMachine,this.canvasManager=e.canvasManager,this.config=e.config}calculateParticleConfig(e,t){const{orbX:i,orbY:s}=this.calculateOrbPosition(e),{particleBehavior:n,particleRate:a,minParticles:r,maxParticles:o}=this.calculateParticleBehavior(e,t);return{orbX:i,orbY:s,particleBehavior:n,particleRate:a,minParticles:r,maxParticles:o,emotionParams:t}}calculateOrbPosition(e){const t=this.renderer.getEffectiveCenter(),i=t.x;let s=t.y-this.config.topOffset;const n=this.stateMachine.getCurrentEmotionalProperties();return n.verticalOffset&&(s=t.y-this.config.topOffset+this.canvasManager.height*n.verticalOffset),{orbX:i,orbY:s}}calculateParticleBehavior(e,t){let i=t.particleBehavior||"ambient",s=t.particleRate||15;const n=this.stateMachine.getCurrentEmotionalProperties(),a=void 0!==t.minParticles?t.minParticles:n.minParticles||0;let r=void 0!==t.maxParticles?t.maxParticles:n.maxParticles||10;return({particleBehavior:i,particleRate:s,maxParticles:r}=this.applyRendererOverrides(i,s,r)),{particleBehavior:i,particleRate:s,minParticles:a,maxParticles:r}}applyRendererOverrides(e,t,i){return this.renderer.state&&this.renderer.state.particleBehaviorOverride&&(e=this.renderer.state.particleBehaviorOverride),this.renderer.state&&this.renderer.state.particleRateMult&&(t=Math.floor(t*this.renderer.state.particleRateMult),i=Math.floor(i*this.renderer.state.particleRateMult)),{particleBehavior:e,particleRate:t,maxParticles:i}}getParticleModifier(e){return this.renderer.getUndertoneModifier?this.renderer.getUndertoneModifier():null}}class eo{constructor(e){this.renderer=e.renderer,this._state=e.state}getGestureMotion(){let e=null,t=0;const i=this._state.currentModularGesture;return i?({gestureMotion:e,gestureProgress:t}=this.processModularGesture(i)):this.renderer&&this.renderer.getCurrentGesture&&({gestureMotion:e,gestureProgress:t}=this.processRendererGesture()),{gestureMotion:e,gestureProgress:t}}processModularGesture(e){const t=performance.now()-e.startTime,i=Math.min(t/e.duration,1),s={type:e.type,amplitude:1,frequency:1,intensity:1};return i>=1&&this.handleGestureCleanup(e),{gestureMotion:s,gestureProgress:i}}handleGestureCleanup(e){e.cleanupPending?this._state.currentModularGesture=null:e.cleanupPending=!0}processRendererGesture(){const e=this.renderer.getCurrentGesture();return e&&e.particleMotion?{gestureMotion:e.particleMotion,gestureProgress:e.progress||0}:{gestureMotion:null,gestureProgress:0}}getGestureTransform(){return this.renderer?.gestureAnimator?.applyGestureAnimations()??null}}class to{constructor(e){this.canvasManager=e.canvasManager,this.config=e.config,this.particleSystem=e.particleSystem,this.pluginSystem=e.pluginSystem||null,this.renderer=e.renderer,this.stateMachine=e.stateMachine,this._state=e.state||{debugMode:!1},this._renderDebugInfo=e.renderDebugInfo||(()=>{})}renderAllLayers(e){const{renderState:t,deltaTime:i,emotionParams:s,gestureTransform:n,renderStart:a}=e;this.renderBackgroundParticles(s.glowColor,n),this.renderOrb(t,i,n),this.renderForegroundParticles(s.glowColor,n),this.renderPlugins(),this.renderDebugIfEnabled(i),this.logPerformanceIfDebug(a,i)}renderBackgroundParticles(e,t){this.particleSystem.renderBackground(this.canvasManager.getContext(),e,t)}renderOrb(e,t,i){this.renderer.render(e,t,i)}renderForegroundParticles(e,t){this.particleSystem.renderForeground(this.canvasManager.getContext(),e,t)}renderPlugins(){if(this.pluginSystem){const e=this.stateMachine.getCurrentState();this.pluginSystem.render(this.canvasManager.getContext(),e)}}renderDebugIfEnabled(e){(this.config.showFPS||this.config.showDebug)&&this._renderDebugInfo(e)}logPerformanceIfDebug(e,t){if(!this._state.debugMode)return;const i=performance.now()-e;i>16.67&&Cs.log("WARN","Slow render frame detected",{renderTime:i,deltaTime:t,particleCount:this.particleSystem.getStats().activeParticles})}}class io{constructor(e){this.animationController=e.animationController,this.canvasManager=e.canvasManager,this.config=e.config,this.particleSystem=e.particleSystem,this.stateMachine=e.stateMachine,this._state=e.state||{audioLevel:0,currentModularGesture:null,speaking:!1}}renderDebugInfo(e){const t=this.canvasManager.getContext();t.save(),this.setupTextStyle(t);let i=20;this.config.showFPS&&(i=this.renderFPSInfo(t,i,16)),this.config.showDebug&&this.renderDebugDetails(t,i,16),t.restore()}setupTextStyle(e){e.fillStyle="#ffffff",e.font="12px monospace",e.strokeStyle="#000000",e.lineWidth=2}renderFPSInfo(e,t,i){const s=this.animationController.getPerformanceMetrics(),n=s.instantFps||s.fps||0,a=[`FPS: ${n}`,`Frame: ${s.averageFrameTime?s.averageFrameTime.toFixed(1):"0.0"}ms`,`Particles: ${this.particleSystem.getStats().activeParticles}`],{x:r,maxWidth:o}=this.calculateFPSBoxPosition(e,a);return this.drawFPSBackground(e,r,t,o,a.length),this.drawFPSBorder(e,r,t,o,a.length,n),this.drawTextLines(e,a,r,t,i),t+i*a.length}calculateFPSBoxPosition(e,t){let i=0;return t.forEach(t=>{const{width:s}=e.measureText(t);s>i&&(i=s)}),{x:this.canvasManager.width-i-8-10,maxWidth:i}}drawFPSBackground(e,t,i,s,n){e.fillStyle="rgba(0, 0, 0, 0.7)",e.fillRect(t-8,i-14,s+16,18*n+4)}drawFPSBorder(e,t,i,s,n,a){const r=this.getFPSBorderColor(a);e.strokeStyle=r,e.lineWidth=2,e.strokeRect(t-8,i-14,s+16,18*n+4)}getFPSBorderColor(e){return e>=55?"#00ff00":e>=30?"#ffff00":"#ff0000"}drawTextLines(e,t,i,s,n){e.fillStyle="#ffffff",t.forEach((t,a)=>{const r=s+a*n;e.fillText(t,i,r)})}renderDebugDetails(e,t,i){const s=this.stateMachine.getCurrentState(),n=this.particleSystem.getStats(),a=[`Emotion: ${s.emotion}${s.undertone?` (${s.undertone})`:""}`,`Particles: ${n.activeParticles}/${n.maxParticles}`,`Gesture: ${this._state.currentModularGesture?this._state.currentModularGesture.type:"none"}`,"Speaking: "+(this._state.speaking?"yes":"no"),`Audio Level: ${(100*this._state.audioLevel).toFixed(1)}%`];e.fillStyle="rgba(0, 0, 0, 0.7)";const r=Math.max(...a.map(t=>e.measureText(t).width));e.fillRect(8,t-14,r+16,a.length*i+4),e.fillStyle="#ffffff";for(const s of a)e.fillText(s,10,t),t+=i}}class so{constructor(e={}){this.enabled=!1!==e.enabled,this.maxErrors=e.maxErrors||100,this.maxStackFrames=e.maxStackFrames||10,this.reportingThreshold=e.reportingThreshold||10,this.reportingInterval=e.reportingInterval||6e4,this.errors=[],this.errorCounts=new Map,this.errorPatterns=new Map,this.suppressedErrors=new Set(e.suppressedErrors||[]),this.metadata={sessionId:this.generateSessionId(),startTime:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",url:"undefined"!=typeof window?window.location.href:"unknown",version:"2.4.0"},this.callbacks={onError:e.onError||null,onReport:e.onReport||null,onCritical:e.onCritical||null},this.severityLevels={LOW:"low",MEDIUM:"medium",HIGH:"high",CRITICAL:"critical"},this.errorCategories={RENDERING:"rendering",ANIMATION:"animation",STATE:"state",NETWORK:"network",PLUGIN:"plugin",USER_INPUT:"user_input",PERFORMANCE:"performance",UNKNOWN:"unknown"},this.enabled&&(this.attachGlobalHandlers(),this.startReportingInterval())}generateSessionId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}attachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError=window.onerror,window.onerror=(e,t,i,s,n)=>(this.captureError(n||new Error(e),{source:t,lineno:i,colno:s,uncaught:!0}),!this.originalOnError||this.originalOnError(e,t,i,s,n)),this.originalOnUnhandledRejection=window.onunhandledrejection,window.onunhandledrejection=e=>{const t=e.reason instanceof Error?e.reason:new Error(String(e.reason));if(this.captureError(t,{type:"unhandledRejection",promise:e.promise,uncaught:!0}),this.originalOnUnhandledRejection)return this.originalOnUnhandledRejection(e)})}detachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&(window.onunhandledrejection=this.originalOnUnhandledRejection))}captureError(e,t={}){if(!this.enabled)return;if(this.shouldSuppress(e))return;const i=this.processError(e,t);i.category=this.categorizeError(e,t),i.severity=this.determineSeverity(e,i.category),this.errors.push(i),this.errors.length>this.maxErrors&&this.errors.shift();const s=`${i.name}:${i.message}`;return this.errorCounts.set(s,(this.errorCounts.get(s)||0)+1),this.detectPatterns(i),this.callbacks.onError&&this.callbacks.onError(i),i.severity===this.severityLevels.CRITICAL&&this.handleCriticalError(i),i}processError(e,t){const i=Date.now(),s=this.parseStackTrace(e.stack);return{id:`${i}-${Math.random().toString(36).substr(2,9)}`,timestamp:i,name:e.name||"Error",message:e.message||String(e),stack:s.slice(0,this.maxStackFrames),fullStack:e.stack,context:{...t,url:"undefined"!=typeof window?window.location.href:"unknown",userAgent:this.metadata.userAgent,sessionId:this.metadata.sessionId},metadata:this.collectMetadata()}}parseStackTrace(e){if(!e)return[];const t=e.split("\n"),i=[];for(const e of t){const t=e.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);t&&i.push({function:t[1],file:t[2],line:parseInt(t[3],10),column:parseInt(t[4],10)})}return i}categorizeError(e,t){const i=e.message.toLowerCase(),s=e.stack||"";return i.includes("canvas")||i.includes("render")||s.includes("Renderer")?this.errorCategories.RENDERING:i.includes("animation")||s.includes("Animation")?this.errorCategories.ANIMATION:i.includes("state")||s.includes("State")?this.errorCategories.STATE:i.includes("network")||i.includes("fetch")||i.includes("xhr")?this.errorCategories.NETWORK:i.includes("plugin")||s.includes("Plugin")?this.errorCategories.PLUGIN:"user_input"===t.source?this.errorCategories.USER_INPUT:i.includes("performance")||i.includes("memory")?this.errorCategories.PERFORMANCE:this.errorCategories.UNKNOWN}determineSeverity(e,t){return"ReferenceError"===e.name||"TypeError"===e.name?this.severityLevels.CRITICAL:t===this.errorCategories.RENDERING||t===this.errorCategories.ANIMATION?this.severityLevels.HIGH:t===this.errorCategories.NETWORK?this.severityLevels.MEDIUM:this.severityLevels.LOW}shouldSuppress(e){const t=e.message||"";for(const e of this.suppressedErrors){if("string"==typeof e&&t.includes(e))return!0;if(e instanceof RegExp&&e.test(t))return!0}return!1}detectPatterns(e){const t=`${e.category}:${e.severity}`,i=this.errorPatterns.get(t)||{count:0,firstSeen:Date.now(),lastSeen:null};i.count++,i.lastSeen=Date.now(),this.errorPatterns.set(t,i);const s=this.errors.filter(e=>Date.now()-e.timestamp<5e3);s.length>10&&this.handleErrorStorm(s)}handleCriticalError(e){console.error("Critical error detected:",e),this.callbacks.onCritical&&this.callbacks.onCritical(e),this.sendReport([e],"critical")}handleErrorStorm(e){console.warn(`Error storm detected: ${e.length} errors in 5 seconds`);const t=new Map;for(const i of e){const e=`${i.name}:${i.message}`;t.has(e)||t.set(e,[]),t.get(e).push(i)}this.sendReport(e,"storm")}collectMetadata(){const e={};return"undefined"!=typeof window&&(e.viewport={width:window.innerWidth,height:window.innerHeight},e.screen={width:window.screen.width,height:window.screen.height,pixelRatio:window.devicePixelRatio},performance.memory&&(e.memory={used:Math.round(performance.memory.usedJSHeapSize/1048576),total:Math.round(performance.memory.totalJSHeapSize/1048576),limit:Math.round(performance.memory.jsHeapSizeLimit/1048576)})),e}startReportingInterval(){this.reportingIntervalId=setInterval(()=>{this.checkAndReport()},this.reportingInterval)}stopReportingInterval(){this.reportingIntervalId&&(clearInterval(this.reportingIntervalId),this.reportingIntervalId=null)}checkAndReport(){this.errors.length>=this.reportingThreshold&&(this.sendReport(this.errors.slice()),this.errors=[])}sendReport(e,t="batch"){const i={sessionId:this.metadata.sessionId,timestamp:Date.now(),type:t,errors:e,patterns:Array.from(this.errorPatterns.entries()),counts:Array.from(this.errorCounts.entries()),metadata:this.metadata};return this.callbacks.onReport&&this.callbacks.onReport(i),i}getErrors(e={}){let t=[...this.errors];return e.category&&(t=t.filter(t=>t.category===e.category)),e.severity&&(t=t.filter(t=>t.severity===e.severity)),e.since&&(t=t.filter(t=>t.timestamp>=e.since)),t}getStats(){const e={total:this.errors.length,byCategory:{},bySeverity:{},patterns:this.errorPatterns.size,topErrors:[]};for(const t of Object.values(this.errorCategories))e.byCategory[t]=this.errors.filter(e=>e.category===t).length;for(const t of Object.values(this.severityLevels))e.bySeverity[t]=this.errors.filter(e=>e.severity===t).length;const t=Array.from(this.errorCounts.entries()).sort((e,t)=>t[1]-e[1]).slice(0,5);return e.topErrors=t.map(([e,t])=>({error:e,count:t})),e}clearErrors(){this.errors=[],this.errorCounts.clear(),this.errorPatterns.clear()}suppressError(e){this.suppressedErrors.add(e)}unsuppressError(e){this.suppressedErrors.delete(e)}enable(){this.enabled=!0,this.attachGlobalHandlers(),this.startReportingInterval()}disable(){this.enabled=!1,this.detachGlobalHandlers(),this.stopReportingInterval()}destroy(){this.disable(),this.clearErrors()}}const no=new so({enabled:!0,maxErrors:100,reportingThreshold:10,reportingInterval:6e4,suppressedErrors:["ResizeObserver loop limit exceeded","Non-Error promise rejection captured"]});class ao{constructor(e={}){this.enabled=!1!==e.enabled,this.interval=e.interval||3e4,this.thresholds={memory:e.memoryThreshold||500,fps:e.fpsThreshold||30,errorRate:e.errorRateThreshold||.1,responseTime:e.responseTimeThreshold||1e3,...e.thresholds},this.checks=new Map,this.history=[],this.maxHistory=e.maxHistory||100,this.status="initializing",this.lastCheck=null,this.dependencies={animationLoop:null,stateStore:null,eventManager:null,performanceMonitor:null,errorTracker:null},this.callbacks={onHealthy:e.onHealthy||null,onWarning:e.onWarning||null,onCritical:e.onCritical||null,onStatusChange:e.onStatusChange||null},this.registerDefaultChecks(),this.enabled&&this.start()}registerDefaultChecks(){this.registerCheck("memory",()=>this.checkMemory()),this.registerCheck("performance",()=>this.checkPerformance()),this.registerCheck("errors",()=>this.checkErrors()),this.registerCheck("dom",()=>this.checkDOM()),this.registerCheck("animation",()=>this.checkAnimation()),this.registerCheck("state",()=>this.checkState()),this.registerCheck("events",()=>this.checkEvents()),this.registerCheck("storage",()=>this.checkStorage()),this.registerCheck("network",()=>this.checkNetwork()),this.registerCheck("browser",()=>this.checkBrowser())}registerCheck(e,t,i={}){this.checks.set(e,{fn:t,critical:i.critical||!1,weight:i.weight||1,timeout:i.timeout||5e3,lastResult:null,lastRun:null})}checkMemory(){const e={status:"healthy",details:{}};if(performance.memory){const t=performance.memory.usedJSHeapSize/1048576,i=performance.memory.totalJSHeapSize/1048576,s=performance.memory.jsHeapSizeLimit/1048576;e.details={used:Math.round(t),total:Math.round(i),limit:Math.round(s),percentage:Math.round(t/s*100)},t>this.thresholds.memory?(e.status="critical",e.message=`Memory usage too high: ${Math.round(t)}MB`):t>.8*this.thresholds.memory&&(e.status="warning",e.message=`Memory usage approaching limit: ${Math.round(t)}MB`)}else e.status="unknown",e.message="Memory API not available";return e}checkPerformance(){const e={status:"healthy",details:{}};if(this.dependencies.performanceMonitor){const t=this.dependencies.performanceMonitor.getStats();e.details={fps:t.fps.current,frameTime:t.frameTime.current,health:t.health,score:t.performance},t.fps.current<this.thresholds.fps&&(e.status="warning",e.message=`Low FPS: ${t.fps.current}`),"critical"!==t.health&&"poor"!==t.health||(e.status="critical",e.message="Performance is critically low")}return e}checkErrors(){const e={status:"healthy",details:{}};if(this.dependencies.errorTracker){const t=this.dependencies.errorTracker.getStats(),i=this.dependencies.errorTracker.getErrors({since:Date.now()-6e4});e.details={total:t.total,recent:i.length,critical:t.bySeverity.critical||0,patterns:t.patterns};const s=i.length/60;s>this.thresholds.errorRate?(e.status="critical",e.message=`High error rate: ${s.toFixed(2)}/s`):t.bySeverity.critical>0&&(e.status="warning",e.message=`${t.bySeverity.critical} critical errors`)}return e}checkDOM(){const e={status:"healthy",details:{}};if("undefined"!=typeof document){const t=document.querySelectorAll("*").length,i=document.querySelectorAll("canvas").length,s=this.countEventListeners();e.details={nodes:t,canvases:i,listeners:s},t>1e4&&(e.status="warning",e.message=`High DOM node count: ${t}`),s>1e3&&(e.status="warning",e.message=`High event listener count: ${s}`)}return e}checkAnimation(){const e={status:"healthy",details:{}};if(this.dependencies.animationLoop){const t=this.dependencies.animationLoop.getStats();e.details={callbacks:t.callbackCount,fps:t.fps,running:t.isRunning,dropped:t.droppedFrames},t.isRunning||(e.status="warning",e.message="Animation loop not running"),t.droppedFrames>100&&(e.status="warning",e.message=`Dropped frames: ${t.droppedFrames}`)}return e}checkState(){const e={status:"healthy",details:{}};if(this.dependencies.stateStore){const t=this.dependencies.stateStore.getState(),i=JSON.stringify(t).length;e.details={size:i,keys:Object.keys(t).length},i>1e6&&(e.status="warning",e.message=`Large state size: ${(i/1024).toFixed(2)}KB`)}return e}checkEvents(){const e={status:"healthy",details:{}};if(this.dependencies.eventManager){const t=this.dependencies.eventManager.getActiveListeners(),i=this.dependencies.eventManager.analyzeLeaks();e.details={active:t.length,potentialLeaks:i.potentialLeaks.length,byGroup:i.byGroup},i.potentialLeaks.length>10&&(e.status="warning",e.message=`Potential memory leaks: ${i.potentialLeaks.length}`),t.length>500&&(e.status="warning",e.message=`High listener count: ${t.length}`)}return e}async checkStorage(){const e={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.storage&&navigator.storage.estimate)try{const t=await navigator.storage.estimate(),i=t.usage||0,s=t.quota||0,n=s>0?i/s*100:0;e.details={used:Math.round(i/1048576),quota:Math.round(s/1048576),percentage:Math.round(n)},n>90?(e.status="critical",e.message=`Storage almost full: ${n.toFixed(1)}%`):n>70&&(e.status="warning",e.message=`Storage usage high: ${n.toFixed(1)}%`)}catch{e.status="unknown",e.message="Storage API error"}return e}async checkNetwork(){const e={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.connection){const{connection:t}=navigator;e.details={effectiveType:t.effectiveType,downlink:t.downlink,rtt:t.rtt,saveData:t.saveData},"slow-2g"!==t.effectiveType&&"2g"!==t.effectiveType||(e.status="warning",e.message="Slow network connection detected"),t.saveData&&(e.status="warning",e.message="Data saver mode enabled")}try{const t=performance.now(),i=await fetch("/health",{method:"HEAD",cache:"no-cache"}),s=performance.now()-t;e.details.responseTime=Math.round(s),e.details.online=i.ok,s>this.thresholds.responseTime&&(e.status="warning",e.message=`Slow response time: ${s.toFixed(0)}ms`)}catch{e.details.online=navigator.onLine,navigator.onLine||(e.status="critical",e.message="No network connection")}return e}checkBrowser(){const e={status:"healthy",details:{}};e.details={userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,hardwareConcurrency:navigator.hardwareConcurrency,maxTouchPoints:navigator.maxTouchPoints};const t={webGL:!!document.createElement("canvas").getContext("webgl"),webAudio:"undefined"!=typeof AudioContext,localStorage:"undefined"!=typeof localStorage,serviceWorker:"serviceWorker"in navigator,webWorker:"undefined"!=typeof Worker};e.details.features=t;const i=Object.entries(t).filter(([e,t])=>!t).map(([e])=>e);return i.length>0&&(e.status="warning",e.message=`Missing features: ${i.join(", ")}`),e}countEventListeners(){let e=0;const t=document.querySelectorAll("*");for(const i of t){const t="undefined"!=typeof getEventListeners&&getEventListeners?getEventListeners(i):{};for(const i in t)e+=t[i].length}return e}async runCheck(e){const t=this.checks.get(e);if(!t)return{status:"unknown",message:`Check '${e}' not found`};try{const e=new Promise((e,i)=>{setTimeout(()=>i(new Error("Check timeout")),t.timeout)}),i=await Promise.race([t.fn(),e]);return t.lastResult=i,t.lastRun=Date.now(),i}catch(e){return{status:"error",message:e.message,error:e.stack}}}async runAllChecks(){const e={},t=[];for(const[i]of this.checks)t.push(this.runCheck(i).then(t=>{e[i]=t}));return await Promise.all(t),e}async performHealthCheck(){const e=performance.now(),t=await this.runAllChecks(),i=performance.now()-e,s=this.calculateOverallHealth(t),n={timestamp:Date.now(),status:s.status,score:s.score,duration:Math.round(i),checks:t,summary:s.summary};return this.lastCheck=n,this.addToHistory(n),this.updateStatus(s.status),n}calculateOverallHealth(e){let t=0,i=0,s=!1;const n=[];for(const[a,r]of Object.entries(e)){const e=this.checks.get(a),o=e?e.weight:1;let l=0;switch(r.status){case"healthy":l=100;break;case"warning":l=70,n.push({name:a,level:"warning",message:r.message});break;case"critical":l=30,n.push({name:a,level:"critical",message:r.message}),e&&e.critical&&(s=!0);break;case"error":l=0,n.push({name:a,level:"error",message:r.message});break;case"unknown":l=50}t+=l*o,i+=o}const a=i>0?Math.round(t/i):0;let r;return r=s||a<30?"critical":a<70?"degraded":a<90?"warning":"healthy",{status:r,score:a,summary:{total:Object.keys(e).length,healthy:Object.values(e).filter(e=>"healthy"===e.status).length,warning:Object.values(e).filter(e=>"warning"===e.status).length,critical:Object.values(e).filter(e=>"critical"===e.status).length,issues:n}}}updateStatus(e){if(this.status!==e){const t=this.status;switch(this.status=e,this.callbacks.onStatusChange&&this.callbacks.onStatusChange(e,t),e){case"healthy":this.callbacks.onHealthy&&this.callbacks.onHealthy();break;case"warning":case"degraded":this.callbacks.onWarning&&this.callbacks.onWarning(this.lastCheck);break;case"critical":this.callbacks.onCritical&&this.callbacks.onCritical(this.lastCheck)}}}addToHistory(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift()}start(){this.intervalId||(this.performHealthCheck(),this.intervalId=setInterval(()=>{this.performHealthCheck()},this.interval))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}destroy(){this.stop(),this.checks.clear(),this.history=[],this.lastCheck=null}setDependencies(e){Object.assign(this.dependencies,e)}getStatus(){return this.status}getLastCheck(){return this.lastCheck}getHistory(){return[...this.history]}async getFullReport(){return{...await this.performHealthCheck(),history:this.getHistory(),uptime:this.getUptime(),configuration:{interval:this.interval,thresholds:this.thresholds,checks:Array.from(this.checks.keys())}}}getUptime(){if(!this.history.length)return 0;const e=this.history[0].timestamp;return Date.now()-e}async handleHealthRequest(e,t){const i=await this.performHealthCheck();return{statusCode:"healthy"===i.status||"warning"===i.status?200:(i.status,503),headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({status:i.status,score:i.score,timestamp:i.timestamp,checks:i.checks,version:"2.4.0"})}}}const ro=new ao({enabled:!1,interval:3e4});class oo{constructor(e){if(!e.errorBoundary)throw new Error("DestructionManager: errorBoundary required");if(!e.animationController)throw new Error("DestructionManager: animationController required");if(!e.state)throw new Error("DestructionManager: state required");if(!e.stop)throw new Error("DestructionManager: stop required");if(!e.stopSpeaking)throw new Error("DestructionManager: stopSpeaking required");if(!e.disconnectAudio)throw new Error("DestructionManager: disconnectAudio required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.positionController=e.positionController||null,this.soundSystem=e.soundSystem||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.particleSystem=e.particleSystem||null,this.renderer=e.renderer||null,this.canvasManager=e.canvasManager||null,this.eventManager=e.eventManager||null,this.accessibilityManager=e.accessibilityManager||null,this.mobileOptimization=e.mobileOptimization||null,this.pluginSystem=e.pluginSystem||null,this.audioAnalyzer=e.audioAnalyzer||null,this.shapeMorpher=e.shapeMorpher||null,this.gestureController=e.gestureController||null,this.stateCoordinator=e.stateCoordinator||null,this.visualizationRunner=e.visualizationRunner||null,this.orbScaleAnimator=e.orbScaleAnimator||null,this.audioHandler=e.audioHandler||null,this.degradationManager=e.degradationManager||null,this.stateMachine=e.stateMachine||null,this.contextManager=e.contextManager||null,this._state=e.state,this._stop=e.stop,this._stopSpeaking=e.stopSpeaking,this._disconnectAudio=e.disconnectAudio}destroy(){this.errorBoundary.wrap(()=>{this.stopAnimations(),this.destroyControllers(),this.cleanupSubsystems(),this.cleanupEvents(),this.cleanupPluginsAndExtensions(),this.clearErrorBoundary()},"destruction")()}stopAnimations(){this._stop(),this._state.speaking&&this._stopSpeaking()}destroyControllers(){this.animationController&&this.animationController.destroy(),this.positionController&&this.positionController.destroy()}cleanupSubsystems(){this.cleanupSound(),this.cleanupAudio(),this.cleanupParticles(),this.cleanupRenderer(),this.cleanupCanvas(),this.cleanupManagers(),this.cleanupSingletons()}cleanupManagers(){this.gestureController&&"function"==typeof this.gestureController.destroy&&this.gestureController.destroy(),this.stateCoordinator&&"function"==typeof this.stateCoordinator.destroy&&this.stateCoordinator.destroy(),this.visualizationRunner&&"function"==typeof this.visualizationRunner.destroy&&this.visualizationRunner.destroy(),this.orbScaleAnimator&&"function"==typeof this.orbScaleAnimator.destroy&&this.orbScaleAnimator.destroy(),this.audioHandler&&"function"==typeof this.audioHandler.destroy&&this.audioHandler.destroy(),this.degradationManager&&"function"==typeof this.degradationManager.destroy&&this.degradationManager.destroy(),this.stateMachine&&"function"==typeof this.stateMachine.destroy&&this.stateMachine.destroy(),this.contextManager&&"function"==typeof this.contextManager.destroy&&this.contextManager.destroy()}cleanupSingletons(){no&&no.destroy(),_n&&_n.destroy(),ro&&ro.destroy()}cleanupSound(){this.soundSystem&&this.soundSystem.cleanup()}cleanupAudio(){this.audioLevelProcessor&&this.audioLevelProcessor.cleanup()}cleanupParticles(){this.particleSystem&&this.particleSystem.destroy()}cleanupRenderer(){this.renderer&&(this.renderer.stopAllGestures(),this.renderer.destroy())}cleanupCanvas(){this.canvasManager&&this.canvasManager.destroy()}cleanupEvents(){this.eventManager&&this.eventManager.destroy(),this._state.llmHandler&&(this._state.llmHandler=null)}cleanupPluginsAndExtensions(){this.cleanupAccessibility(),this.cleanupMobile(),this.cleanupPlugins(),this.cleanupAudioExtensions()}cleanupAccessibility(){this.accessibilityManager&&this.accessibilityManager.destroy()}cleanupMobile(){this.mobileOptimization&&this.mobileOptimization.destroy()}cleanupPlugins(){this.pluginSystem&&this.pluginSystem.destroy()}cleanupAudioExtensions(){this.audioAnalyzer&&(this._disconnectAudio(),this.audioAnalyzer.destroy()),this.shapeMorpher&&this.shapeMorpher.reset()}clearErrorBoundary(){this.errorBoundary.clearErrors(),this.nullifyReferences()}nullifyReferences(){this.errorBoundary=null,this.animationController=null,this.positionController=null,this.soundSystem=null,this.audioLevelProcessor=null,this.particleSystem=null,this.renderer=null,this.canvasManager=null,this.eventManager=null,this.accessibilityManager=null,this.mobileOptimization=null,this.pluginSystem=null,this.audioAnalyzer=null,this.shapeMorpher=null,this.gestureController=null,this.stateCoordinator=null,this.visualizationRunner=null,this.orbScaleAnimator=null,this.audioHandler=null,this.degradationManager=null,this.stateMachine=null,this.contextManager=null,this._state=null,this._stop=null,this._stopSpeaking=null,this._disconnectAudio=null}}class lo{constructor(e){this.renderer=e.renderer||null,this._state=e.state,this._emit=e.emit}startBreathingAnimation(){this._state.breathingAnimationId&&cancelAnimationFrame(this._state.breathingAnimationId);const e=()=>{if(!this._state.breathePattern||!this._state.isRunning)return;const t=this._state.breathePattern,i=Date.now(),s=(i-t.phaseStartTime)/1e3,{scale:n,nextPhase:a}=this.calculatePhaseState(t,s,i);a!==t.currentPhase&&(t.currentPhase=a),this.applyScale(n),this._state.breathingAnimationId=requestAnimationFrame(e)};this._state.breathePattern.currentPhase="inhale",this._state.breathePattern.phaseStartTime=Date.now(),this._emit("inhale-start"),e()}calculatePhaseState(e,t,i){let s=1,n=e.currentPhase;switch(e.currentPhase){case"inhale":({scale:s,nextPhase:n}=this.processInhalePhase(e,t,i));break;case"hold1":({scale:s,nextPhase:n}=this.processHold1Phase(e,t,i));break;case"exhale":({scale:s,nextPhase:n}=this.processExhalePhase(e,t,i));break;case"hold2":({scale:s,nextPhase:n}=this.processHold2Phase(e,t,i))}return{scale:s,nextPhase:n}}processInhalePhase(e,t,i){let s=1,n=e.currentPhase;return t>=e.inhale?(n="hold1",e.phaseStartTime=i,this._emit("hold-start",{type:"post-inhale"})):s=1+t/e.inhale*.3,{scale:s,nextPhase:n}}processHold1Phase(e,t,i){let s=e.currentPhase;return t>=e.hold1&&(s="exhale",e.phaseStartTime=i,this._emit("exhale-start")),{scale:1.3,nextPhase:s}}processExhalePhase(e,t,i){let s=1.3,n=e.currentPhase;return t>=e.exhale?(n="hold2",e.phaseStartTime=i,this._emit("hold-start",{type:"post-exhale"})):s=1.3-t/e.exhale*.4,{scale:s,nextPhase:n}}processHold2Phase(e,t,i){let s=e.currentPhase;return t>=e.hold2&&(s="inhale",e.phaseStartTime=i,this._emit("inhale-start")),{scale:.9,nextPhase:s}}applyScale(e){this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(e)}}class ho{constructor(e){this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem,this.soundSystem=e.soundSystem,this.renderer=e.renderer||null,this.config=e.config,this._state=e.state,this._getEventNames=e.getEventNames}getSystemStatus(){return this.errorBoundary.wrap(()=>({...this.getCoreStatus(),...this.getEmotionalStatus(),...this.getGestureStatus(),particles:this.getParticleStatus(),...this.getAudioStatus(),renderer:this.getRendererStatus(),eventListeners:this.getEventListenerCount(),errorStats:this.getErrorStats()}),"system-status",{})()}getCoreStatus(){const e=this.animationController.getPerformanceMetrics();return{isRunning:e.isRunning,fps:e.fps,targetFPS:e.targetFPS,performanceDegradation:e.performanceDegradation}}getEmotionalStatus(){const e=this.stateMachine.getCurrentState();return{emotion:e.emotion,undertone:e.undertone,isTransitioning:e.isTransitioning,transitionProgress:e.transitionProgress}}getGestureStatus(){return{currentGesture:this.renderer?.currentGesture||null,gestureActive:this.renderer?.isGestureActive()||!1}}getParticleStatus(){const e=this.particleSystem.getStats();return{active:e.activeParticles,max:e.maxParticles,poolEfficiency:e.poolEfficiency}}getAudioStatus(){return{audioEnabled:this.config.enableAudio,soundSystemAvailable:this.soundSystem.isAvailable(),speaking:this._state.speaking,audioLevel:this._state.audioLevel,masterVolume:this.config.masterVolume}}getRendererStatus(){const e=this.renderer.getStats();return{gradientCacheSize:e.gradientCacheSize,breathingPhase:e.breathingPhase,layers:e.layers}}getEventListenerCount(){return this._getEventNames().length}getErrorStats(){return this.errorBoundary.getErrorStats()}}class co{constructor(e){if(!e.errorBoundary)throw new Error("SleepWakeManager: errorBoundary required");if(!e.express)throw new Error("SleepWakeManager: express required");if(!e.state)throw new Error("SleepWakeManager: state required");if(!e.emit)throw new Error("SleepWakeManager: emit required");this.errorBoundary=e.errorBoundary,this._express=e.express,this.idleBehavior=e.idleBehavior||null,this.renderer=e.renderer||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}sleep(){return this.errorBoundary.wrap(async()=>(this._state.sleeping||(await this.performSleepSequence(),this.enterSleepState()),this._chainTarget),"sleep",this._chainTarget)()}async performSleepSequence(){this._express("yawn"),await this.delay(1e3),this._express("sway"),await this.delay(1e3)}enterSleepState(){this._state.sleeping=!0,this.renderer&&this.renderer.enterSleepMode&&this.renderer.enterSleepMode(),this.idleBehavior&&this.idleBehavior.enterSleep&&this.idleBehavior.enterSleep(),this._emit("sleep")}wake(){return this.errorBoundary.wrap(async()=>this._state.sleeping?(this.exitSleepState(),await this.performWakeSequence(),this._chainTarget):this._chainTarget,"wake",this._chainTarget)()}exitSleepState(){this._state.sleeping=!1,this.renderer&&this.renderer.wakeUp&&this.renderer.wakeUp(),this.idleBehavior&&this.idleBehavior.wakeUp&&this.idleBehavior.wakeUp()}async performWakeSequence(){this._express("stretch"),await this.delay(1e3),this._express("slowBlink"),await this.delay(1e3),this._express("shake"),await this.delay(500),this._emit("wake")}delay(e){return new Promise(t=>setTimeout(t,e))}}class uo{constructor(e){if(!e.errorBoundary)throw new Error("SpeechManager: errorBoundary required");if(!e.emit)throw new Error("SpeechManager: emit required");this.errorBoundary=e.errorBoundary,this.audioLevelProcessor=e.audioLevelProcessor||null,this.audioHandler=e.audioHandler||null,this.renderer=e.renderer||null,this.config=e.config||{},this._state=e.state||{speaking:!1},this._setTTSSpeaking=e.setTTSSpeaking||(()=>{}),this._emit=e.emit,this._chainTarget=e.chainTarget||this}speak(e,t={}){if(!window.speechSynthesis)return null;const i=this.createUtterance(e,t);return this.setupUtteranceHandlers(i,e),window.speechSynthesis.speak(i),i}createUtterance(e,t){const i=new SpeechSynthesisUtterance(e);return t.voice&&(i.voice=t.voice),t.rate&&(i.rate=t.rate),t.pitch&&(i.pitch=t.pitch),t.volume&&(i.volume=t.volume),t.lang&&(i.lang=t.lang),i}setupUtteranceHandlers(e,t){e.onstart=()=>{this._setTTSSpeaking(!0),this._emit("tts:start",{text:t})},e.onend=()=>{this._setTTSSpeaking(!1),this._emit("tts:end")},e.onerror=e=>{this._setTTSSpeaking(!1),this._emit("tts:error",{error:e})},e.onboundary=e=>{this._emit("tts:boundary",{name:e.name,charIndex:e.charIndex,charLength:e.charLength})}}startSpeaking(e){return this.errorBoundary.wrap(()=>this.validateAudioContext(e)&&this.initializeAudioProcessor(e)?(this.activateSpeechMode(e),this._chainTarget):this._chainTarget,"speech-start",this._chainTarget)()}validateAudioContext(e){if(!e)throw new Error("AudioContext is required for speech reactivity");return!!this.config.enableAudio&&!this._state.speaking}initializeAudioProcessor(e){return!!this.audioLevelProcessor.initialize(e)}activateSpeechMode(e){this._state.speaking=!0,this.renderer&&this.renderer.onSpeechStart(e),this._emit("speechStarted",{audioContext:e,analyser:this.audioLevelProcessor.getAnalyser(),chainTarget:this._chainTarget})}stopSpeaking(){return this.errorBoundary.wrap(()=>this.audioHandler?this.audioHandler.stopSpeaking():this._chainTarget,"speech-stop",this._chainTarget)()}}class go{constructor(e){if(!e.emit)throw new Error("AudioLevelCallbackManager: emit required");this.audioLevelProcessor=e.audioLevelProcessor||null,this.renderer=e.renderer||null,this.particleSystem=e.particleSystem||null,this._express=e.express||(()=>{}),this._emit=e.emit}setupAudioLevelProcessorCallbacks(){this.setupLevelUpdateCallback(),this.setupVolumeSpikeCallback(),this.setupErrorCallback()}setupLevelUpdateCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onLevelUpdate(e=>{this.renderer&&this.renderer.updateAudioLevel(e.level),this._emit("audioLevelUpdate",{level:e.level,rawData:Array.from(e.rawData),timestamp:e.timestamp})})}setupVolumeSpikeCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onVolumeSpike(e=>{const t=this.handleVolumeSpike();this._emit("volumeSpike",{...e,gestureTriggered:t})})}handleVolumeSpike(){return!!this.particleSystem&&(!this.particleSystem.particles.some(e=>e.gestureProgress<1)&&(this._express("pulse"),!0))}setupErrorCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onError(e=>{this._emit("audioProcessingError",e)})}}class mo{constructor(e){this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state,this._chainTarget=e.chainTarget||this,this.animationId=null}setOrbScale(e,t=1e3,i="easeInOut"){return this.errorBoundary.wrap(()=>(this.renderer&&this.startScaleAnimation(e,t,i),this._chainTarget),"setOrbScale",this._chainTarget)()}startScaleAnimation(e,t,i){const s=this._state.currentOrbScale||1,n=Date.now(),a=()=>{const r=Date.now()-n,o=Math.min(r/t,1),l=this.applyEasing(o,i);this._state.currentOrbScale=s+(e-s)*l,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(this._state.currentOrbScale),o<1&&this._state.isRunning&&(this.animationId=requestAnimationFrame(a))};a()}applyEasing(e,t){switch(t){case"easeIn":return this.easeIn(e);case"easeOut":return this.easeOut(e);case"easeInOut":return this.easeInOut(e);default:return e}}easeIn(e){return e*e}easeOut(e){return e*(2-e)}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}destroy(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.renderer=null,this._state=null}}class po{constructor(e){if(!e.errorBoundary)throw new Error("RecordingStateManager: errorBoundary required");if(!e.emit)throw new Error("RecordingStateManager: emit required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state||{recording:!1},this._emit=e.emit,this._chainTarget=e.chainTarget||this}startRecording(){return this.errorBoundary.wrap(()=>(this._state.recording||(this._state.recording=!0,this.renderer&&this.renderer.startRecording&&this.renderer.startRecording(),this._emit("recordingStarted")),this._chainTarget),"recording-start",this._chainTarget)()}stopRecording(){return this.errorBoundary.wrap(()=>this._state.recording?(this._state.recording=!1,this.renderer&&this.renderer.stopRecording&&this.renderer.stopRecording(),this._emit("recordingStopped"),this._chainTarget):this._chainTarget,"recording-stop",this._chainTarget)()}}class fo{constructor(e){this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state,this._startBreathingAnimation=e.startBreathingAnimation,this._chainTarget=e.chainTarget||this}static getPresets(){return{calm:{inhale:4,hold1:0,exhale:4,hold2:0},anxious:{inhale:2,hold1:0,exhale:2,hold2:0},meditative:{inhale:4,hold1:7,exhale:8,hold2:0},deep:{inhale:5,hold1:5,exhale:5,hold2:5},sleep:{inhale:6,hold1:0,exhale:8,hold2:2}}}setBreathePattern(e,t,i,s){return this.errorBoundary.wrap(()=>{const n=e+t+i+s;return this._state.breathePattern={inhale:e,hold1:t,exhale:i,hold2:s,totalCycle:n,currentPhase:"inhale",phaseStartTime:Date.now(),phaseProgress:0},this._startBreathingAnimation(),this._chainTarget},"setBreathePattern",this._chainTarget)()}breathe(e="calm"){return this.errorBoundary.wrap(()=>{const t=fo.getPresets(),i=t[e]||t.calm;return this.setBreathePattern(i.inhale,i.hold1,i.exhale,i.hold2)},"breathe",this._chainTarget)()}stopBreathing(){return this.errorBoundary.wrap(()=>(this._state.breathingAnimationId&&(cancelAnimationFrame(this._state.breathingAnimationId),this._state.breathingAnimationId=null),this._state.breathePattern=null,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(1),this._chainTarget),"stopBreathing",this._chainTarget)()}}class yo{constructor(e,t){this._getSubsystems=e,this._emitEvent=t}handleEvent(e,t){switch(e){case"degradationApplied":this.applySettings(t.settings),this._emitEvent("performanceDegradation",t);break;case"recoveryApplied":this.applySettings(t.settings),this._emitEvent("performanceRecovery",t);break;case"levelChanged":this.applySettings(t.settings),this._emitEvent("degradationLevelChanged",t)}}applySettings(e){const t=this._getSubsystems();t.particleSystem&&void 0!==e.particleLimit&&t.particleSystem.setMaxParticles(e.particleLimit),t.soundSystem&&void 0!==e.audioEnabled&&!e.audioEnabled&&t.soundSystem.isAvailable()&&t.soundSystem.stopAmbientTone(200),t.renderer&&void 0!==e.qualityLevel&&t.renderer.setQualityLevel(e.qualityLevel)}}class bo{constructor(t={}){this.errorBoundary=new e,this.eventManager=new ws({maxListeners:t.maxEventListeners||100,enableDebugging:t.enableEventDebugging||!1,enableMonitoring:t.enableEventMonitoring||!0,memoryWarningThreshold:t.eventMemoryWarningThreshold||50}),this.eventManager.emit||(this.eventManager._listeners={},this.eventManager.emit=(e,t)=>{const i=this.eventManager._listeners[e];i&&i.forEach(e=>e(t))},this.eventManager.on=(e,t)=>{this.eventManager._listeners[e]||(this.eventManager._listeners[e]=[]),this.eventManager._listeners[e].push(t)},this.eventManager.off=(e,t)=>{const i=this.eventManager._listeners[e];if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}),this.errorBoundary.wrap(()=>{this.initialize(t)},"initialization")()}initialize(e){this.Emotions=M,this.Gestures=Oi,this.ParticleBehaviors=Ms,this.speechManager=new uo({errorBoundary:this.errorBoundary,emit:(e,t)=>this.emit(e,t)}),this.audioLevelCallbackManager=new go({emit:(e,t)=>this.emit(e,t)}),this.orbScaleAnimator=new mo(this),this.recordingStateManager=new po({errorBoundary:this.errorBoundary,emit:(e,t)=>this.emit(e,t)}),this.breathingPatternManager=new fo(this),new Qr(this,e).initialize(),this.renderStateBuilder=new Jr(this),this.threatLevelCalculator=new Kr(this),this.particleConfigCalculator=new Zr(this);const t=this;this.gestureMotionProvider=new eo({renderer:this.renderer,state:{get currentModularGesture(){return t.currentModularGesture},set currentModularGesture(e){t.currentModularGesture=e}}}),this.renderLayerOrchestrator=new to(this),this.debugInfoRenderer=new io(this),this.destructionManager=new oo({errorBoundary:this.errorBoundary,animationController:this.animationController,positionController:this.positionController,soundSystem:this.soundSystem,audioLevelProcessor:this.audioLevelProcessor,particleSystem:this.particleSystem,renderer:this.renderer,canvasManager:this.canvasManager,eventManager:this.eventManager,accessibilityManager:this.accessibilityManager,mobileOptimization:this.mobileOptimization,pluginSystem:this.pluginSystem,audioAnalyzer:this.audioAnalyzer,shapeMorpher:this.shapeMorpher,state:{get speaking(){return t.speaking},get llmHandler(){return t.llmHandler},set llmHandler(e){t.llmHandler=e}},stop:()=>this.stop(),stopSpeaking:()=>this.stopSpeaking(),disconnectAudio:()=>this.disconnectAudio()}),this.breathingAnimationController=new lo(this),this.systemStatusReporter=new ho({errorBoundary:this.errorBoundary,animationController:this.animationController,stateMachine:this.stateMachine,particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer,config:this.config,state:{get speaking(){return t.speaking},get audioLevel(){return t.audioLevel}},getEventNames:()=>this.getEventNames()}),this.sleepWakeManager=new co({errorBoundary:this.errorBoundary,express:(e,t)=>this.express(e,t),idleBehavior:this.idleBehavior,renderer:this.renderer,state:{get sleeping(){return t.sleeping},set sleeping(e){t.sleeping=e}},emit:(e,t)=>this.emit(e,t),chainTarget:this}),this.degradationEventHandler=new yo(()=>({particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer}),(e,t)=>this.emit(e,t))}handleDegradationEvent(e,t){return this.degradationEventHandler.handleEvent(e,t)}applyDegradationSettings(e){return this.degradationEventHandler.applySettings(e)}setupAudioLevelProcessorCallbacks(){this.audioLevelCallbackManager.setupAudioLevelProcessorCallbacks()}setEmotion(e,t=null){return this.errorBoundary.wrap(()=>this.stateCoordinator.setEmotion(e,t),"emotion-setting",this)()}updateUndertone(e){return this.errorBoundary.wrap(()=>(this.stateMachine.applyUndertoneModifier(e),this.renderer&&this.renderer.updateUndertone&&this.renderer.updateUndertone(e),this),"undertone-update",this)()}setBPM(e){return this.errorBoundary.wrap(()=>(this.renderer?.setBPM&&this.renderer.setBPM(e),this),"bpm-update",this)()}setRotationSpeed(e){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationSpeed&&this.renderer.setRotationSpeed(e),this),"rotation-speed-update",this)()}setRotationAngle(e){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationAngle&&this.renderer.setRotationAngle(e),this),"rotation-angle-update",this)()}getPosition(){return this.animationFrameController.getPosition()}setGazeTracking(e){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.setGazeTracking&&this.renderer.setGazeTracking(e),this),"gaze-tracking-update",this)()}express(e,t={}){return this.gestureController?this.gestureController.express(e,t):(console.warn("GestureController not initialized, skipping gesture"),this)}expressChord(e,t={}){return this.gestureController.expressChord(e,t)}executeGestureDirectly(e,t={}){this.gestureController.executeGestureDirectly(e,t),this.emit("gesture",{name:e,options:t})}chain(...e){return this.gestureController.chain(...e)}executeChainSequence(e){return this.gestureController.executeChainSequence(e)}perform(e,t={}){return this.performanceBehaviorManager.perform(e,t)}updateContext(e){return this.frustrationContextManager.updateContext(e)}getContext(){return this.emotionalStateQueryManager.getContext()}incrementFrustration(e=10){return this.frustrationContextManager.incrementFrustration(e)}decrementFrustration(e=10){return this.frustrationContextManager.decrementFrustration(e)}resetFrustration(){return this.frustrationContextManager.resetFrustration()}getAvailablePerformances(){return this.performanceBehaviorManager.getAvailablePerformances()}registerPerformance(e,t){return this.performanceBehaviorManager.registerPerformance(e,t)}getPerformanceAnalytics(){return this.performanceBehaviorManager.getPerformanceAnalytics()}getContextAnalytics(){return this.performanceBehaviorManager.getContextAnalytics()}startSpeaking(e){return this.speechManager?this.speechManager.startSpeaking(e):this}stopSpeaking(){return this.speechManager?this.speechManager.stopSpeaking():this}startRecording(){return this.recordingStateManager?this.recordingStateManager.startRecording():this}stopRecording(){return this.recordingStateManager?this.recordingStateManager.stopRecording():this}sleep(){return this.sleepWakeManager.sleep()}wake(){return this.sleepWakeManager.wake()}getTTSVoices(){return this.ttsManager.getTTSVoices()}isTTSSpeaking(){return this.ttsManager.isTTSSpeaking()}start(){return this.executionLifecycleManager.start()}stop(){return this.executionLifecycleManager.stop()}setBreathePattern(e,t,i,s){return this.breathingPatternManager?this.breathingPatternManager.setBreathePattern(e,t,i,s):this}setOrbScale(e,t=1e3,i="easeInOut"){return this.orbScaleAnimator?this.orbScaleAnimator.setOrbScale(e,t,i):this}breathe(e="calm"){return this.breathingPatternManager?this.breathingPatternManager.breathe(e):this}startBreathingAnimation(){this.breathingAnimationController.startBreathingAnimation()}stopBreathing(){return this.breathingPatternManager?this.breathingPatternManager.stopBreathing():this}on(e,t){return this.eventListenerManager.on(e,t)}off(e,t){return this.eventListenerManager.off(e,t)}once(e,t){return this.eventListenerManager.once(e,t)}removeAllListeners(e=null){return this.eventListenerManager.removeAllListeners(e)}listenerCount(e){return this.eventListenerManager.listenerCount(e)}getEventNames(){return this.eventListenerManager.getEventNames()}getEventStats(){return this.eventListenerManager.getEventStats()}getEventDebugInfo(){return this.eventListenerManager.getEventDebugInfo()}getBrowserCompatibility(){return this.diagnosticsManager.getBrowserCompatibility()}getDegradationStatus(){return this.performanceMonitoringManager.getDegradationStatus()}setDegradationLevel(e){return this.performanceMonitoringManager.setDegradationLevel(e)}isFeatureAvailable(e){return this.performanceMonitoringManager.isFeatureAvailable(e)}recoverCanvasContext(){return!!this.contextRecovery&&this.contextRecovery.recover()}isCanvasContextLost(){return!!this.contextRecovery&&this.contextRecovery.isLost()}getDebugReport(){return this.debugProfilingManager.getDebugReport()}exportDebugData(){return this.debugProfilingManager.exportDebugData()}startProfiling(e,t={}){this.debugProfilingManager.startProfiling(e,t)}endProfiling(e){return this.debugProfilingManager.endProfiling(e)}takeMemorySnapshot(e){this.debugProfilingManager.takeMemorySnapshot(e)}clearDebugData(){this.debugProfilingManager.clearDebugData()}getRuntimeCapabilities(){return this.debugProfilingManager.getRuntimeCapabilities()}emit(e,t=null){this.eventListenerManager.emit(e,t)}update(e){this.errorBoundary.wrap(()=>{this.visualizationRunner.update(e)},"audio-update")()}render(){try{const{renderStart:e,deltaTime:t,renderState:i}=this.renderStateBuilder.buildRenderState();this.debugMode&&Cs.trackFrameTiming(t),this.canvasManager.clear(),this.gazeTracker&&this.gazeTracker.update(t),this.threatLevelCalculator.updateThreatLevel(i);const s=h(i.emotion);this.renderer.setEmotionalState(i.emotion,s,i.undertone);const n=this.particleConfigCalculator.calculateParticleConfig(i,s),{orbX:a,orbY:r,particleBehavior:o,particleRate:l,minParticles:c,maxParticles:u}=n;this.particleSystem.spawn(o,i.emotion,l,a,r,t,null,c,u,this.renderer.particleScaleFactor||this.renderer.scaleFactor||1,this.config.classicConfig?.particleSizeMultiplier||1,s.particleColors||null,i.undertone);const d=this.particleConfigCalculator.getParticleModifier(i),{gestureMotion:g,gestureProgress:m}=this.gestureMotionProvider.getGestureMotion();this.particleSystem.update(t,a,r,g,m,d);const p=this.gestureMotionProvider.getGestureTransform();this.renderLayerOrchestrator.renderAllLayers({renderState:i,deltaTime:t,emotionParams:s,gestureTransform:p,renderStart:e})}catch(e){this.errorBoundary.logError(e,"main-render")}}renderDebugInfo(e){this.debugInfoRenderer.renderDebugInfo(e)}getEmotionalColor(){return this.emotionalStateQueryManager.getEmotionalColor()}getCurrentState(){return this.emotionalStateQueryManager.getCurrentState()}getAvailableEmotions(){return this.emotionalStateQueryManager.getAvailableEmotions()}getAvailableUndertones(){return this.emotionalStateQueryManager.getAvailableUndertones()}getAudioStats(){return this.speechReactivityManager.getAudioStats()}updateAudioConfig(e){this.speechReactivityManager.updateAudioConfig(e)}getAvailableGestures(){return this.emotionalStateQueryManager.getAvailableGestures()}connectAudioSource(e){return this.speechReactivityManager.connectAudioSource(e)}setVolume(e){return this.errorBoundary.wrap(()=>this.audioHandler.setVolume(e),"volume-setting",this)()}getVolume(){return this.config.masterVolume}setSoundEnabled(e){return this.config.soundEnabled=e,this}isSoundEnabled(){return this.config.soundEnabled}pause(){return this.executionLifecycleManager.pause()}resume(){return this.executionLifecycleManager.resume()}isActive(){return this.executionLifecycleManager.isActive()}setTargetFPS(e){return this.performanceMonitoringManager.setTargetFPS(e)}getTargetFPS(){return this.performanceMonitoringManager.getTargetFPS()}setPosition(e,t,i=0){return this.animationFrameController.setPosition(e,t,i)}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){return this.animationFrameController.animateToPosition(e,t,i,s,n)}clearParticles(){return this.visualTransformationManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this.visualTransformationManager.setParticleSystemCanvasDimensions(e,t)}setPerformanceDegradation(e){return this.performanceMonitoringManager.setPerformanceDegradation(e)}getAudioLevel(){return this.speechReactivityManager.getAudioLevel()}isSpeaking(){return this.speechReactivityManager.isSpeaking()}setAudioSmoothing(e){return this.speechReactivityManager.setAudioSmoothing(e)}getSystemStatus(){return this.healthCheckManager.getSystemStatus()}setDebugMode(e){return this.healthCheckManager.setDebugMode(e)}triggerTestError(e="manual-test"){return this.healthCheckManager.triggerTestError(e)}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}registerPlugin(e){return this.pluginSystem.registerPlugin(e)}setAccessibility(e){e.colorBlindMode&&this.accessibilityManager.setColorBlindMode(e.colorBlindMode),void 0!==e.reducedMotion&&(this.accessibilityManager.reducedMotionPreferred=e.reducedMotion),void 0!==e.highContrast&&(this.accessibilityManager.highContrastEnabled=e.highContrast)}getMobileStatus(){return this.healthCheckManager.getMobileStatus()}getAccessibilityStatus(){return this.healthCheckManager.getAccessibilityStatus()}setState(e){return this.setEmotion(e)}speak(e,t={}){return this.ttsManager.speak(e,t)}setTTSSpeaking(e){this.ttsManager.setTTSSpeaking(e)}getVoices(){return this.ttsManager.getVoices()}stopTTS(){this.ttsManager.stopTTS()}handleResize(e,t,i){this.visualTransformationManager.handleResize(e,t,i)}morphTo(e,t={}){return this.visualTransformationManager.morphTo(e,t)}connectAudio(e){return this.errorBoundary.wrap(()=>this.audioHandler.connectAudio(e),"connectAudio",this)()}disconnectAudio(){return this.errorBoundary.wrap(()=>this.audioHandler.disconnectAudio(),"disconnectAudio",this)()}setOffset(e,t,i=0){return this.visualTransformationManager.setOffset(e,t,i)}getOffset(){return this.visualTransformationManager.getOffset()}setBackdrop(e={}){return this.visualTransformationManager.setBackdrop(e)}getBackdrop(){return this.visualTransformationManager.getBackdrop()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.visualTransformationManager.animateOffset(e,t,i,s,n)}getAvailableShapes(){return this.emotionalStateQueryManager.getAvailableShapes()}async handleLLMResponse(e,t={}){return this.llmIntegrationBridge.handleLLMResponse(e,t)}configureLLMHandler(e){return this.llmIntegrationBridge.configureLLMHandler(e)}getLLMResponseSchema(){return this.llmIntegrationBridge.getLLMResponseSchema()}static getLLMPromptTemplate(e={}){return jr.getLLMPromptTemplate(e)}static getLLMEmotions(){return jr.getLLMEmotions()}static getLLMActions(){return jr.getLLMActions()}static getLLMShapes(){return jr.getLLMShapes()}static getLLMGestures(){return jr.getLLMGestures()}destroy(){this.destructionManager.destroy()}throttledWarn(e,t){const i=Date.now();i-(this.warningTimestamps[t]||0)>this.warningThrottle&&(this.warningTimestamps[t]=i)}}const vo={easy:{windowMultiplier:1.5,label:"Easy"},normal:{windowMultiplier:1,label:"Normal"},hard:{windowMultiplier:.7,label:"Hard"}};class Mo{constructor(){this._preset="normal",this._assist={autoRhythm:!1,slowMode:!1,visualMetronome:!1},this._slowModeMult=.75}setDifficulty(e){vo[e]&&(this._preset=e)}getDifficulty(){return this._preset}getWindowMultiplier(){return vo[this._preset].windowMultiplier}setAssist(e){void 0!==e.autoRhythm&&(this._assist.autoRhythm=!!e.autoRhythm),void 0!==e.slowMode&&(this._assist.slowMode=!!e.slowMode),void 0!==e.visualMetronome&&(this._assist.visualMetronome=!!e.visualMetronome)}getAssist(){return{...this._assist}}get autoRhythm(){return this._assist.autoRhythm}getBPMMultiplier(){return this._assist.slowMode?this._slowModeMult:1}get visualMetronome(){return this._assist.visualMetronome}serialize(){return{preset:this._preset,assist:{...this._assist}}}deserialize(e){e&&(e.preset&&vo[e.preset]&&(this._preset=e.preset),e.assist&&this.setAssist(e.assist))}}class wo{constructor(e){this._getEngine=e,this._audioBlob=null,this._audioDuration=0,this._difficultyManager=null}getAudioBlob(){return this._audioBlob}getAudioDuration(){return this._audioDuration}setAudioDuration(e){this._audioDuration=e||0}async loadAudio(e){if(e instanceof Blob){this._audioBlob=e;const t=URL.createObjectURL(e);await this._loadAudioFromUrl(t),URL.revokeObjectURL(t)}else await this._loadAudioFromUrl(e)}async _loadAudioFromUrl(e){const t=new Audio(e);await new Promise((e,i)=>{t.addEventListener("loadedmetadata",()=>{this._audioDuration=1e3*t.duration,e()},{once:!0}),t.addEventListener("error",i,{once:!0}),t.load()});const i=this._getEngine();i&&i.soundSystem&&await i.soundSystem.loadAudioFromURL(e)}getAudioAnalysis(){const e=this._getEngine();return e&&e.audioAnalyzer?{bpm:e.rhythmIntegration?.getBPM()||0,beats:e.rhythmIntegration?.getBeatMarkers()||[],energy:e.audioAnalyzer?.getEnergyLevel()||0,frequencies:e.audioAnalyzer?.getFrequencyData()||[]}:null}connectAudio(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.connectAudio&&t.connectAudio(e)}disconnectAudio(e){const t=this._getEngine();t&&t.disconnectAudio&&t.disconnectAudio(e)}getSpectrumData(){const e=this._getEngine();return e&&e.audioAnalyzer?e.audioAnalyzer.dataArray?Array.from(e.audioAnalyzer.dataArray).map(e=>e/255):e.shapeMorpher&&e.shapeMorpher.frequencyData?Array.from(e.shapeMorpher.frequencyData):[]:[]}startRhythmSync(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.rhythmIntegration&&(e&&t.rhythmIntegration.setBPM(e),t.rhythmIntegration.start())}stopRhythmSync(){const e=this._getEngine();e&&e.rhythmIntegration&&e.rhythmIntegration.stop()}getInputEvaluator(e){const t=this._getEngine();if(!t||!t.rhythmIntegration)return null;const i=t.rhythmIntegration.getInputEvaluator(e);return i&&!i._emotionTarget&&t.stateCoordinator&&i.setEmotionTarget((e,i)=>{t.stateCoordinator.nudgeEmotion(e,i)}),i&&!i._difficultyManager&&i.setDifficultyManager(this.getDifficultyManager()),i}getDifficultyManager(){return this._difficultyManager||(this._difficultyManager=new Mo),this._difficultyManager}getLayers(){const e=this._getEngine();return e&&e.soundSystem?e.soundSystem.getAudioLayerManager():null}}class So{constructor(e,t){this._getEngine=e,this._recording=t,this._chainDefinitions={rise:"breathe > sway+lean+tilt",flow:"sway > lean+tilt > spin > bounce",burst:"jump > nod > shake > flash",drift:"sway+breathe+float+drift",chaos:"shake+shake > spin+flash > bounce+pulse > twist+sparkle",morph:"expand > contract > morph+glow > expand+flash",rhythm:"pulse > pulse+sparkle > pulse+flicker",spiral:"spin > orbital > twist > orbital+sparkle",routine:"nod > bounce > spin+sparkle > sway+pulse > nod+flash",radiance:"sparkle > pulse+flicker > shimmer",twinkle:"sparkle > flash > pulse+sparkle > shimmer+flicker",stream:"wave > nod+pulse > sparkle > flash"}}triggerGesture(e,t){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");if(this._recording.isRecording()){const i=t||Date.now()-this._recording.startTime();this._recording.timeline().push({type:"gesture",name:e,time:i})}i.express(e)}express(e,t){return this.triggerGesture(e,t)}chain(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");const i=this._chainDefinitions[e.toLowerCase()];i?i.includes(">")?i.split(">").map(e=>e.trim()).filter(e=>e.length>0).forEach((e,i)=>{setTimeout(()=>{e.split("+").map(e=>e.trim()).filter(e=>e.length>0).forEach(e=>{t.express(e)})},500*i)}):i.split("+").map(e=>e.trim()).filter(e=>e.length>0).forEach(e=>{t.express(e)}):console.warn(`Chain combo '${e}' not found`)}updateUndertone(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.updateUndertone&&"function"==typeof t.updateUndertone?t.updateUndertone(e):t.addUndertone&&"function"==typeof t.addUndertone&&t.addUndertone(e)}getAvailableChains(){return Object.keys(this._chainDefinitions)}getChainDefinition(e){return this._chainDefinitions[e.toLowerCase()]||null}}class xo{constructor(e,t,i){this._getEngine=e,this._audioManager=t,this._state=i,this._activeTimeouts=new Set}startRecording(){this._state.timeline.length=0,this._state.isRecording=!0,this._state.recordingStartTime=Date.now()}stopRecording(){return this._state.isRecording=!1,[...this._state.timeline]}playTimeline(e){if(!e||!e.length)return void(this._state.isPlaying=!1);this._state.isPlaying=!0,this._state.playbackStartTime=Date.now(),e.forEach(e=>{const t=setTimeout(()=>{if(this._activeTimeouts.delete(t),!this._state.isPlaying)return;const i=this._getEngine();if(i)switch(e.type){case"gesture":i.express(e.name);break;case"emotion":i.setEmotion(e.name);break;case"shape":i.morphTo(e.name)}},e.time);this._activeTimeouts.add(t)});const t=Math.max(...e.map(e=>e.time)),i=setTimeout(()=>{this._activeTimeouts.delete(i),this._state.isPlaying=!1},t);this._activeTimeouts.add(i)}stopPlayback(){this._state.isPlaying=!1,this._activeTimeouts.forEach(e=>clearTimeout(e)),this._activeTimeouts.clear()}getTimeline(){return[...this._state.timeline]}loadTimeline(e){this._state.timeline.length=0,this._state.timeline.push(...e)}exportTimeline(){return JSON.stringify({version:"1.0",duration:this._audioManager.getAudioDuration()||0,events:this._state.timeline})}importTimeline(e){let t;try{t=JSON.parse(e)}catch{return void console.warn("TimelineRecorder: Failed to parse timeline JSON")}this._state.timeline.length=0,this._state.timeline.push(...t.events||[]),this._audioManager.setAudioDuration(t.duration||0)}getCurrentTime(){return this._state.isPlaying?Date.now()-this._state.playbackStartTime:0}seek(e){const t=this._state.timeline.filter(t=>t.time<=e),i={};t.forEach(e=>{i[e.type]=e});const s=this._getEngine();s&&(i.emotion&&s.setEmotion(i.emotion.name),i.shape&&s.morphTo(i.shape.name))}getAnimationData(){const e=this._getEngine();return{timeline:[...this._state.timeline],duration:this._audioManager.getAudioDuration()||0,currentTime:this.getCurrentTime(),emotion:e?.state?.emotion||"neutral",shape:e?.state?.currentShape||"circle"}}destroy(){this.stopPlayback(),this._getEngine=null,this._audioManager=null,this._state=null}}class Co{constructor(e,t,i){this._getEngine=e,this._getCanvas=t,this._mascot=i,this._attachedElement=null,this._attachOptions=null,this._hasAttachedBefore=!1,this._elementTrackingHandlers=null}attachToElement(e,t={}){if(!this._getEngine())throw new Error("Engine not initialized. Call init() first.");const i="string"==typeof e?document.querySelector(e):e;if(!i)return console.warn(`[EmotiveMascot] Element not found: ${e}`),this._mascot;this._attachedElement=i,this._attachOptions={offsetX:t.offsetX||0,offsetY:t.offsetY||0,animate:!1!==t.animate,duration:t.duration||1e3,scale:t.scale||1,containParticles:!1!==t.containParticles};const s=i.getBoundingClientRect();return this._attachOptions.containParticles?this._mascot.setContainment({width:s.width,height:s.height},this._attachOptions.scale):1!==this._attachOptions.scale&&this._mascot.setContainment(null,this._attachOptions.scale),this._getCanvas()&&this._updatePosition(),this._setupEventListeners(),this._mascot}_updatePosition(){if(!this._attachedElement)return;if(!this._getCanvas())return;const e=this._attachedElement.getBoundingClientRect(),t=window.innerWidth/2,i=window.innerHeight/2,s=e.left+e.width/2,n=e.top+e.height/2,a=s-t+this._attachOptions.offsetX,r=n-i+this._attachOptions.offsetY,o=!this._hasAttachedBefore;this._hasAttachedBefore=!0,o&&this._attachOptions.animate?this._mascot.animateToPosition(a,r,0,this._attachOptions.duration):this._mascot.setPosition(a,r,0)}_setupEventListeners(){this._elementTrackingHandlers||(this._elementTrackingHandlers={scroll:()=>this._updatePosition(),resize:()=>this._updatePosition()},window.addEventListener("scroll",this._elementTrackingHandlers.scroll,{passive:!0}),window.addEventListener("resize",this._elementTrackingHandlers.resize))}isAttachedToElement(){return!!this._attachedElement}detachFromElement(){return this._attachedElement=null,this._elementTrackingHandlers&&(window.removeEventListener("scroll",this._elementTrackingHandlers.scroll),window.removeEventListener("resize",this._elementTrackingHandlers.resize),this._elementTrackingHandlers=null),this._mascot.setContainment(null,1),this._mascot.setEmotion("neutral"),this._mascot.morphTo("sphere",{duration:800}),this._mascot}cleanup(){this._elementTrackingHandlers&&(window.removeEventListener("scroll",this._elementTrackingHandlers.scroll),window.removeEventListener("resize",this._elementTrackingHandlers.resize),this._elementTrackingHandlers=null),this._attachedElement=null}}class ko{constructor(e,t){this._getEngine=e,this._getCanvas=t}setContainment(e,t=1){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");i.particleSystem&&i.particleSystem.setContainmentBounds(e),i.positionController&&(i.positionController.coreScaleOverride=t,i.positionController.particleScaleOverride=t),i.particleSystem&&i.particleSystem.particles&&i.particleSystem.particles.forEach(e=>{e.scaleFactor=t,e.size=e.baseSize*t})}clearParticles(){const e=this._getEngine();if(!e)throw new Error("Engine not initialized. Call init() first.");e.particleSystem&&e.particleSystem.clear()}setParticleSystemCanvasDimensions(e,t){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");i.setParticleSystemCanvasDimensions&&i.setParticleSystemCanvasDimensions(e,t)}getFrameData(e="png"){const t=this._getCanvas();return t?t.toDataURL(`image/${e}`):null}getFrameBlob(e="png"){const t=this._getCanvas();return t?new Promise(i=>{t.toBlob(e=>i(e),`image/${e}`)}):Promise.resolve(null)}}class Po{constructor(){this._stances=new Map,this._active=null}registerStance(e,t){this._stances.set(e,{...t})}hasStance(e){return this._stances.has(e)}getStance(e){const t=this._stances.get(e);return t?{...t}:null}activate(e){const t=this._stances.get(e);return t?(this._active={name:e,config:{...t}},this._active.config):null}dismiss(){return!!this._active&&(this._active=null,!0)}getActiveStance(){return this._active?{name:this._active.name,config:{...this._active.config}}:null}getAvailableStances(){return[...this._stances.keys()]}}const To=["bouncing up and down","hopping around","rocking back and forth","side to side","light on feet","spring in step","leaning forward","leaning in","leaning closer","leaning toward","reaching out","reaching toward","pointing at","pointing to","waving hello","waving goodbye","nodding head","shaking head","head shake","head nod","head bob","head tilt","deep breath","taking a breath","breathing deeply","settling down","calming down","winding down","getting bigger","getting smaller","puffing up","spinning around","twirling around","at peace","in love","on cloud nine","over the moon","on top of the world","in awe","grossed out","freaked out","low key","low-key","high key","on edge","keyed up","wound up","low energy","no energy","running low","just a bit","just a little","a little bit","kind of","sort of","a bit","a little","a lot","over the top","off the charts","through the roof","split second","one time","few times","many times","again and again","over and over","on repeat","blood moon","full moon","new moon","half moon","solar eclipse","lunar eclipse","total eclipse","ring of fire","diamond ring","killing it","crushing it","nailed it","sussy baka","side eye"].map(e=>{const t=e.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{normalized:t,regex:new RegExp(i,"g")}}),Eo=/[,;|/]+/,Ao=new Set(["a","an","the","is","are","am","be","being","been","i","me","my","it","its","to","of","for","with","as","this","that","these","those","just","only","also","too","please","pls","plz"]),Do=new Set(["but","and","or","yet","while","although","not","no","never","very","really","so","quite","rather","slightly","barely","extremely","completely","feeling","feel","feels","become","becoming","morph","morphing"]);function _o(e){return["but","and","or","yet","while","although","with"].includes(e)}function Io(e){return["not","no","never","don't","dont","doesn't","doesnt","isn't","isnt"].includes(e)}const Ro={nervous:{candidates:[{category:"emotion",target:"fear",priority:1},{category:"undertone",target:"nervous",priority:2}],rule:"standalone_is_emotion",examples:[{input:"nervous",resolved:{emotion:"fear"}},{input:"happy but nervous",resolved:{emotion:"joy",undertone:"nervous"}}]},anxious:{candidates:[{category:"emotion",target:"fear",priority:1},{category:"undertone",target:"nervous",priority:2}],rule:"standalone_is_emotion"},confident:{candidates:[{category:"emotion",target:"trust",priority:2},{category:"undertone",target:"confident",priority:1}],rule:"prefer_undertone",examples:[{input:"confident",resolved:{undertone:"confident"}},{input:"feeling confident",resolved:{emotion:"trust"}}]},tired:{candidates:[{category:"emotion",target:"sadness",priority:2},{category:"undertone",target:"tired",priority:1}],rule:"prefer_undertone",examples:[{input:"tired",resolved:{undertone:"tired"}},{input:"feeling tired",resolved:{emotion:"sadness",undertone:"tired"}}]},intense:{candidates:[{category:"undertone",target:"intense",priority:1},{category:"modifier",target:"intensity.very",priority:2}],rule:"prefer_undertone"},curious:{candidates:[{category:"emotion",target:"focused",priority:1},{category:"gesture",target:"lean",priority:2}],rule:"standalone_is_emotion",examples:[{input:"curious",resolved:{emotion:"focused"}},{input:"curious, leaning in",resolved:{emotion:"focused",gesture:"lean"}}]},interested:{candidates:[{category:"emotion",target:"focused",priority:1},{category:"gesture",target:"lean",priority:2}],rule:"standalone_is_emotion"},excited:{candidates:[{category:"emotion",target:"joy",priority:1},{category:"gesture",target:"bounce",priority:3}],rule:"standalone_is_emotion"},shaking:{candidates:[{category:"gesture",target:"shake",priority:1},{category:"emotion",target:"fear",priority:2}],rule:"standalone_is_gesture"},nodding:{candidates:[{category:"gesture",target:"nod",priority:1}],rule:"always_gesture"},glowing:{candidates:[{category:"gesture",target:"glow",priority:1},{category:"shape",target:"sun",priority:3}],rule:"standalone_is_gesture"},spinning:{candidates:[{category:"gesture",target:"spin",priority:1}],rule:"always_gesture"},love:{candidates:[{category:"emotion",target:"love",priority:1},{category:"shape",target:"heart",priority:2}],rule:"standalone_is_emotion",examples:[{input:"love",resolved:{emotion:"love"}},{input:"love heart",resolved:{emotion:"love",shape:"heart"}},{input:"become love",resolved:{shape:"heart"}}]},suspicious:{candidates:[{category:"emotion",target:"suspicion",priority:1},{category:"shape",target:"suspicion",priority:2}],rule:"standalone_is_emotion"},bright:{candidates:[{category:"emotion",target:"joy",priority:2},{category:"shape",target:"sun",priority:3},{category:"modifier",target:"intensity.very",priority:4}],rule:"context_dependent"},yes:{candidates:[{category:"gesture",target:"nod",priority:1}],rule:"always_gesture"},no:{candidates:[{category:"gesture",target:"shake",priority:1}],rule:"always_gesture"},agree:{candidates:[{category:"gesture",target:"nod",priority:1},{category:"emotion",target:"trust",priority:2}],rule:"standalone_is_gesture"},disagree:{candidates:[{category:"gesture",target:"shake",priority:1}],rule:"always_gesture"}},Bo={emotionContext:["feeling","feel","feels","felt","emotion","emotional","emotionally","mood","moody","state","am","is","are","being","becoming","become","grew","growing"],gestureContext:["do","doing","does","did","perform","performing","action","move","moving","movement","start","starting","begin","beginning","physically","motion"],shapeContext:["morph","morphing","morphed","transform","transforming","transformed","become","becoming","turn into","shape","form","look like","change to","change into"],undertoneContext:["but","yet","while","although","with","and also","mixed with","underneath","underlying","beneath","a bit","slightly","somewhat"],modifierContext:["very","really","so","extremely","slightly","barely","completely","quickly","slowly","briefly"]};function zo(e,t,i){const s=Bo[`${i}Context`];if(!s)return!1;const n=Math.max(0,t-3),a=Math.min(e.length,t+4);for(let i=n;i<a;i++)if(i!==t&&s.includes(e[i]))return!0;return!1}function Fo(e,t){switch(t){case"emotion":return null!==e.emotion;case"gesture":return e.gestures&&e.gestures.length>0;case"shape":return null!==e.shape;case"undertone":return null!==e.undertone;default:return!1}}function Oo(e,t,i,s){const n=Ro[e];if(!n)return null;const{candidates:a,rule:r}=n;if(1===a.length)return a[0];switch(r){case"standalone_is_emotion":if(Fo(s,"emotion")){const e=a.find(e=>"emotion"!==e.category);if(e)return e}return zo(t,i,"emotion"),a.find(e=>"emotion"===e.category)||a[0];case"standalone_is_gesture":if(Fo(s,"gesture")){const e=a.find(e=>"gesture"!==e.category);if(e)return e}return zo(t,i,"gesture"),a.find(e=>"gesture"===e.category)||a[0];case"prefer_undertone":return zo(t,i,"emotion")?a.find(e=>"emotion"===e.category)||a[0]:a.find(e=>"undertone"===e.category)||a[0];case"always_gesture":return a.find(e=>"gesture"===e.category)||a[0];case"always_emotion":return a.find(e=>"emotion"===e.category)||a[0];case"context_dependent":for(const e of["emotion","gesture","shape","undertone"])if(zo(t,i,e)){const t=a.find(t=>t.category===e);if(t)return t}return a.sort((e,t)=>e.priority-t.priority)[0];default:return a.sort((e,t)=>e.priority-t.priority)[0]}}function Lo(e){return e in Ro}const qo={neutral:["neutral","default","normal","baseline","standard","nothing special","nothing particular","no strong feeling","not much","meh","whatever","indifferent","balanced","even","steady","stable","centered","level","middle ground","in between","ready","waiting","standing by","at attention","present","here","available","attentive","reset","clear","blank","empty","clean slate"],joy:["happy","joy","joyful","joyous","pleased","glad","content","satisfied","gratified","comfortable","good","cheerful","cheery","merry","jovial","jolly","upbeat","sunny","bright","lighthearted","buoyant","delighted","thrilled","overjoyed","elated","jubilant","exultant","gleeful","glowing","beaming","radiant","pumped","stoked","psyched","amped","hyped","vibing","living","slaying","winning","lit","fire","sick","dope","chuffed","pleased as punch","over the moon","made up","tickled","tickled pink","felicitous","beatific","blissful","smiling","grinning","laughing","giggling"],calm:["calm","peaceful","serene","tranquil","relaxed","at ease","comfortable","loose","unwound","decompressed","chilled","still","quiet","hushed","silent","soft","gentle","mild","placid","smooth","composed","collected","centered","grounded","untroubled","unworried","unbothered","unfazed","meditative","mindful","contemplative","reflective","introspective","soothed","eased","mellowed","softened","chill","coasting","floating","drifting","laid back","easy going","low key","sorted","easy peasy"],excited:["excited","exciting","excitable","enthusiastic","eager","keen","avid","passionate","fervent","ardent","zealous","energetic","energized","animated","lively","spirited","vivacious","vibrant","dynamic","bouncy","peppy","perky","sprightly","anticipating","expectant","looking forward","itching","raring","chomping at the bit","fired up","charged","electric","electrified","buzzing","tingling","crackling","sparking","jazzed","juiced","geeked","hype","turnt","going off","well excited","buzzing","restless","fidgety","antsy","jumpy","twitchy","keyed up","wound up"],sadness:["sad","sadness","saddened","unhappy","down","low","blue","glum","bummed","disappointed","let down","discouraged","disheartened","dispirited","deflated","melancholy","melancholic","somber","gloomy","mournful","sorrowful","doleful","woeful","heavy-hearted","downcast","crestfallen","heartbroken","devastated","crushed","shattered","despairing","despondent","desolate","inconsolable","grief","grieving","mourning","bereft","empty","hollow","numb","void","wistful","longing","yearning","pining","nostalgic","bummed out","down in the dumps","in a funk","in the dumps","feeling low","gutted","choked","crying","tearful","weeping","sobbing","sighing","drooping","wilting","slumping"],anger:["angry","anger","angered","mad","annoyed","irritated","bothered","irked","peeved","miffed","vexed","displeased","put out","ticked off","ticked","frustrated","aggravated","exasperated","fed up","sick of","had enough","cross","upset","worked up","furious","enraged","livid","irate","incensed","infuriated","outraged","seething","fuming","boiling","burning","smoldering","raging","ballistic","apoplectic","berserk","seeing red","losing it","pissed","pissed off","salty","pressed","triggered","tilted","heated","steaming","narked","cheesed off","brassed off","shirty","stroppy","mardy","ropeable","filthy","spewing","clenching","tensing","grinding"],fear:["afraid","scared","fear","fearful","uneasy","unsettled","apprehensive","wary","concerned","worried","jittery","shaky","trembling","quivering","tense","tight","clenched","knotted","frightened","alarmed","startled","spooked","freaked","freaked out","creeped out","on edge","rattled","unnerved","terrified","petrified","horrified","panicked","panic","panicking","terror","dread","paranoid","distrustful","looking over shoulder","sketched","sketched out","wigged out","shook","bricking it","having kittens","in a flap","frozen","paralyzed","deer in headlights","heart racing","heart pounding","sweating"],surprise:["surprised","surprise","surprising","oh","huh","hmm","interesting","unexpected","caught off guard","astonished","amazed","astounded","startled","taken aback","struck","shocked","stunned","staggered","floored","dumbfounded","flabbergasted","gobsmacked","blown away","mind blown","speechless","wow","whoa","omg","no way","incredible","unbelievable","amazing","alarmed","dismayed","appalled","bewildered","baffled","perplexed","puzzled","confused","disoriented","thrown","shooketh","gagged","dead","wait what","blimey","crikey","bloody hell","jaw dropped","eyes wide","double take","gasp","gasping"],disgust:["disgusted","disgust","disgusting","distaste","dislike","aversion","put off","turned off","off-putting","repulsed","revolted","repelled","grossed out","creeped out","icked out","sickened","nauseated","nauseous","appalled","horrified","scandalized","offended","outraged","indignant","contempt","contemptuous","disdain","scorn","gagging","retching","cringing","wincing","recoiling","shrinking back","gross","ew","eww","yuck","yucky","ick","nasty","foul","vile","rank","minging","manky","grotty"],love:["love","loving","loved","affection","affectionate","fond","fondness","tender","tenderness","gentle","caring","care","nurturing","supportive","protective","devoted","dedicated","warm","warmth","warm-hearted","kind","kind-hearted","compassionate","sympathetic","adoring","adore","cherish","cherishing","treasure","treasuring","doting","romantic","amorous","passionate","smitten","infatuated","enamored","besotted","head over heels","falling for","connected","bonded","attached","close","intimate","deep","profound","heart eyes","crushing","swooning","melting","hugging","embracing","holding","cuddling","snuggling","nuzzling"],euphoria:["euphoric","euphoria","bliss","blissful","transcendent","otherworldly","sublime","heavenly","divine","ethereal","celestial","ecstatic","ecstasy","rapture","rapturous","exultant","exalted","elevated","peak","pinnacle","height","climax","breakthrough","revelation","epiphany","overwhelming joy","pure joy","absolute joy","complete happiness","total bliss","floating","soaring","flying","weightless","radiating","shining","on cloud nine","in heaven","on top of the world","walking on air","living my best life","ascended"],focused:["focused","focus","focusing","concentrating","concentration","concentrated","attentive","attention","attending","thinking","thought","thoughtful","pondering","considering","contemplating","reflecting","musing","mulling","engaged","absorbed","immersed","engrossed","rapt","riveted","captivated","enthralled","intent","determined","resolute","single-minded","laser focused","zeroed in","working","processing","analyzing","examining","studying","learning","figuring out","locked in","dialed in","in the zone","flow state","deep work","grinding","staring","gazing","peering","squinting","furrowed brow"],suspicion:["suspicious","suspicion","suspect","doubtful","doubt","doubting","skeptical","skepticism","questioning","uncertain","unsure","unconvinced","wary","cautious","guarded","careful","leery","circumspect","vigilant","distrustful","mistrust","mistrustful","disbelieving","incredulous","unbelieving","scrutinizing","examining","assessing","evaluating","judging","sizing up","sus","sussy","suss","side eye","giving side eye","side-eyeing","eyeing","not buying it","narrowed eyes","squinting","raised eyebrow","cocked head","tilted head","looking askance"],resting:["resting","rest","restful","tired","weary","fatigued","exhausted","drained","spent","depleted","worn out","sleepy","drowsy","dozy","groggy","yawning","nodding off","drifting off","sluggish","lethargic","listless","languid","lazy","idle","inactive","recovering","recuperating","recharging","winding down","powering down","shutting down","sleeping","asleep","slumbering","dozing","napping","snoozing","zonked","wiped","beat","dead tired","running on empty","out of gas","crashed","knackered","shattered","cream crackered"],glitch:["glitch","glitchy","glitching","malfunction","malfunctioning","broken","bugged","buggy","error","erroring","corrupted","corruption","scrambled","garbled","distorted","warped","static","noise","interference","pixelated","artifacting","tearing","haywire","fritzing","shorting out","going crazy","spazzing","unstable","erratic","unpredictable","flickering","stuttering","lagging","does not compute","syntax error","crash"]},Go={nervous:["nervous","nervously","anxious","anxiously","worried","worriedly","uneasy","uneasily","apprehensive","jittery","shaky","trembling","quivering","fidgety","restless","twitchy","tense","tensely","on edge","edgy","keyed up","wound up","uptight","self-conscious","awkward","awkwardly","hesitant","hesitantly","uncertain","uncertainly","sketchy","stressed","stressing","low-key panicking","kinda freaking out"],confident:["confident","confidently","confidence","assured","assuredly","certain","certainly","sure","surely","positive","positively","bold","boldly","brave","bravely","daring","daringly","fearless","fearlessly","strong","strongly","powerful","powerfully","firm","firmly","solid","solidly","authoritative","commanding","assertive","decisive","decisively","resolute","resolutely","poised","self-assured","unflappable","unfazed","owning it","killing it","crushing it","boss","like a boss"],tired:["tired","tiredly","tiredness","exhausted","weary","wearily","fatigued","drained","spent","depleted","sluggish","sluggishly","slow","slowly","lethargic","listless","languid","low energy","no energy","out of energy","running low","running on fumes","droopy","drooping","sagging","slumping","heavy","weighted","dragging","wiped","beat","dead","zonked","burned out","fried","cooked","toast"],intense:["intense","intensely","intensity","heightened","elevated","amplified","magnified","increased","enhanced","forceful","forcefully","powerful","powerfully","fierce","fiercely","strong","strongly","passionate","passionately","fervent","fervently","ardent","ardently","vehement","vehemently","sharp","sharply","acute","acutely","keen","keenly","piercing","piercingly","extreme","extremely","deeply","profoundly","tremendously","immensely","incredibly","super","mega","ultra","hella","mad","crazy"],subdued:["subdued","subduedly","soft","softly","gentle","gently","mild","mildly","light","lightly","restrained","held back","contained","tempered","moderated","toned down","quiet","quietly","hushed","muted","understated","subtle","subtly","modest","modestly","humble","humbly","reserved","demure","unassuming","faint","faintly","dim","dimly","pale","faded","washed out","low key","lowkey","easy","easy going"],clear:["clear","clearly","pure","purely","clean","cleanly","simple","simply","plain","plainly","direct","directly","straightforward","honest","honestly","frank","frankly","transparent","transparently","open","openly","obvious","obviously","evident","evidently","unmodified","unaltered","unchanged","normal","normally","regular","regularly","standard","basic","baseline"]},Ho={breathe:["breathe","breathing","breath","inhale","inhaling","exhale","exhaling","sigh","sighing","respire","respiring","deep breath","deep breathing","slow breath","slow breathing","long breath","full breath","breathing deeply","breathing slowly","taking a breath","take a breath","catching breath","breath work","breathwork","inhale exhale","in and out","meditative breathing","calming breath","cleansing breath","relaxing breath","centering breath","mindful breathing"],expand:["expand","expanding","grow","growing","enlarge","enlarging","swell","swelling","bloat","bloating","getting bigger","growing larger","puffing up","expanding outward"],contract:["contract","contracting","shrink","shrinking","compress","compressing","reduce","reducing","getting smaller","shrinking down","pulling in","contracting inward"],pulse:["pulse","pulsing","pulsate","pulsating","throb","throbbing","beat","beating","pulsing gently","steady pulse","heartbeat","heart beat"],sway:["sway","swaying","swing","swinging","oscillate","oscillating","swaying gently","gentle sway","side to side","swaying motion"],float:["float","floating","hover","hovering","glide","gliding","levitate","levitating","weightless","weightlessness","buoyant","airy","floating gently","hovering in place","light as air","floating freely"],floatUp:["float up","floating up","floating upward","rise","rising","ascend","ascending","lift","lifting","lifted up","soar","soaring","going up"],floatDown:["float down","floating down","floating downward","descend","descending","sink","sinking","lower","lowering","going down"],floatLeft:["float left","floating left","drift left","drifting left"],floatRight:["float right","floating right","drift right","drifting right"],bob:["bob","bobbing","bobbing up and down","gentle bob"],lean:["lean","leaning","incline","inclining","leaning in","lean in","leaning forward","lean forward","leaning toward","lean toward","leaning closer","lean closer","moving closer","coming closer","drawing near","approaching","interested","intrigued","engaged","attentive","listening closely","paying attention"],leanLeft:["lean left","leaning left","tilt left","tilting left"],leanRight:["lean right","leaning right","tilt right","tilting right"],jitter:["jitter","jittering","jittery","stutter","stuttering","jittering around","slight jitter","nervous jitter"],twitch:["twitch","twitching","twitchy","spasm","spasming","flinch","flinching","quick twitch","nervous twitch","sudden movement"],vibrate:["vibrate","vibrating","vibration","buzz","buzzing","hum","humming","quiver","quivering","vibrating slightly","gentle buzz","low hum","subtle vibration"],shake:["shake","shaking","shaky","shudder","shuddering","tremble","trembling","quake","quaking","no","nope","nah","disagree","disagreeing","refuse","refusing","deny","denying","shaking head","shake head","head shake","saying no","shaking no"],wiggle:["wiggle","wiggling","wiggly","jiggle","jiggling","jiggly","squirm","squirming","wriggle","wriggling","wiggling around","little wiggle","happy wiggle","excited wiggle"],stepLeft:["step left","stepping left","sidestep left","move left","moving left","shift left"],stepRight:["step right","stepping right","sidestep right","move right","moving right","shift right"],stepUp:["step up","stepping up","step forward"],stepDown:["step down","stepping down","step back"],slideLeft:["slide left","sliding left","glide left"],slideRight:["slide right","sliding right","glide right"],runningman:["running man","runningman","running man dance","run in place","running in place"],charleston:["charleston","charleston dance","swing dance","kick step","kick and step"],hula:["hula","hula-ing","hip sway","swaying hips","circular sway","round motion","hula motion","hula dance"],twist:["twist","twisting","twisty","contort","contorting","do the twist","twisting dance","twisting around","getting twisted"],pop:["pop","popping","pop and lock","popping motion","hit","hitting"],flare:["flare","flaring","dramatic flare","flourish"],swell:["swell","swelling","surge","surging","crescendo"],swagger:["swagger","swaggering","strut","strutting","confident walk","cocky"],dip:["dip","dipping","drop","dropping down","low dip","dance dip"],bounce:["bounce","bouncing","bouncy","hop","hopping","hoppy","spring","springing","springy","boing","boinging","bouncing up and down","hopping around","spring in step","light on feet"],orbit:["orbit","orbiting","circle","circling","revolve","revolving","circling around","going around","rotating slowly","orbital motion"],orbitLeft:["orbit left","orbiting left","circle left","counter-clockwise","counterclockwise"],orbitRight:["orbit right","orbiting right","circle right","clockwise"],orbitUp:["orbit up","orbiting up","rising orbit","spiral up","spiraling up"],orbitDown:["orbit down","orbiting down","descending orbit","spiral down","spiraling down"],sparkle:["sparkle","sparkling","sparkly","twinkle","twinkling","twinkly","glitter","glittering","glittery","shine","shining","shiny","celebrate","celebrating","celebration","celebratory","festive","party","partying","victory","triumphant","triumph","winning","success","successful","achievement","accomplished","nailed it","slay","slaying","killing it","yasss","yay","woo","woohoo"],shimmer:["shimmer","shimmering","shimmery","glisten","glistening","gleam","gleaming","lustrous","luminous","soft shimmer","gentle gleam","shimmering light","pearlescent"],groove:["groove","grooving","groovy","dance","dancing","boogie","boogying","funk","funky","rhythmic","moving to music","feeling the music","in the groove","getting down","busting a move","doing a little dance"],jump:["jump","jumping","jumpy","leap","leaping","bound","bounding","jumping up","leap up","spring up","jumping for joy"],jumpDown:["jump down","jumping down","drop down"],jumpLeft:["jump left","jumping left","leap left"],jumpRight:["jump right","jumping right","leap right"],lunge:["lunge","lunging","thrust","thrusting","charge forward","aggressive step"],lungeForward:["lunge forward","lunging forward","thrust forward"],lungeBack:["lunge back","lunging back","retreat lunge"],rushForward:["rush forward","rushing forward","dash forward","sprint","sprinting","charge","charging"],rushBack:["rush back","rushing back","dash back","retreat quickly"],spin:["spin","spinning","twirl","twirling","whirl","whirling","rotate","rotating","turn","turning","spinning around","quick spin","full rotation","twirling around"],spinLeft:["spin left","spinning left","turn left","rotate left","counter-clockwise spin"],spinRight:["spin right","spinning right","turn right","rotate right","clockwise spin"],flip:["flip","flipping","somersault","somersaulting","front flip","frontflip"],backflip:["backflip","back flip","backflipping","back somersault","flip backward"],point:["point","pointing","indicate","indicating","gesture","gesturing","direct","directing","pointing at","pointing to","pointing toward","gesturing toward","showing","directing attention"],pointUp:["point up","pointing up","pointing upward","look up","look to the sky"],pointDown:["point down","pointing down","pointing downward","look down","look at this"],pointLeft:["point left","pointing left","gesture left"],pointRight:["point right","pointing right","gesture right"],kickLeft:["kick left","kicking left","left kick"],kickRight:["kick right","kicking right","right kick"],bow:["bow","bowing","curtsy","curtseying","reverence","showing respect","take a bow","bow down"],nod:["nod","nodding","yes","yeah","yep","yup","agree","agreeing","acknowledge","acknowledging","confirm","confirming","accept","accepting","approve","approving","understand","understanding","got it","gotcha","i see","makes sense","understood","nodding head","nod head","head nod","nodding along","nodding yes"],reach:["reach","reaching","extend","extending","reaching out","reach out","reaching toward","reach toward","extending toward","offer","offering","present","presenting","give","giving","help","helping"],headBob:["headbob","head bob","headbobbing","head bobbing","nodding to beat","nodding to music","bobbing along","bobbing to rhythm","vibing","jamming","bobbing head","bob head","feeling the beat","moving to music"],wave:["wave","waving","greet","greeting","hello","hi","hey","goodbye","bye","farewell","welcome","welcoming","waving hello","waving goodbye","friendly wave","waving hand"],crouch:["crouch","crouching","squat","squatting","hunker","hunkering","duck","ducking","get low","getting low"],tilt:["tilt","tilting","tilted","angle","angling","angled","cock","cocking","cocked","tilting head","tilt head","cocking head","curious tilt","angling sideways","head tilt"],tiltUp:["tilt up","tilting up","look up","looking up"],tiltDown:["tilt down","tilting down","look down","looking down"],tiltLeft:["tilt left","tilting left","head tilt left"],tiltRight:["tilt right","tilting right","head tilt right"],recoil:["recoil","recoiling","flinch","flinching","wince","wincing","pull back","pulling back","jerk back","snap back"],knockdown:["knockdown","knock down","knocked down","fall","falling","fell","topple","toppling","take a hit","got hit"],knockout:["knockout","knock out","knocked out","KO","ko'd","lights out","out cold"],squash:["squash","squashing","squashed","flatten","flattening","flattened","compress","compressed","smoosh","smooshed"],stretch:["stretch","stretching","stretchy","elongate","elongating","lengthen","lengthening","stretching out","big stretch","reaching up","stretching tall"],inflate:["inflate","inflating","inflated","puff up","puffing up","puffed up","balloon","ballooning"],deflate:["deflate","deflating","deflated","let air out","losing air","shrivel","shriveling"],pancake:["pancake","pancaked","pancaking","flatten completely","totally flat","squished flat","smooshed flat"],rage:["rage","raging","furious","fury","angry","anger","mad","livid","enraged","seeing red","lose temper","losing it"],fury:["fury","furious","quick anger","flash of anger","snap","snapping"],battlecry:["battlecry","battle cry","war cry","roar","yell","yelling","scream","screaming","rallying cry"],charge:["charge","charging","rush","rushing","attack","attacking","assault","advance"],wobble:["wobble","wobbling","wobbly","unstable","unsteady","drunk","dizzy","off balance","losing balance"],teeter:["teeter","teetering","totter","tottering","about to fall","precarious","on edge","unbalanced"],rock:["rock","rocking","soothing rock","gentle rocking","back and forth","rocking motion"],pendulum:["pendulum","pendulum motion","swing back and forth","swinging","hypnotic swing","metronome"],shatter:["shatter","shattering","shattered","break","breaking","broken","smash","smashing","smashed","fragment","fragmenting","explode into pieces","break apart"],shatterExplosive:["explosive shatter","explode","exploding","blow up","blowing up","detonate","detonating","big explosion","kaboom"],shatterCrumble:["crumble","crumbling","fall apart","falling apart","disintegrate","disintegrating","collapse","collapsing"],dissolveUp:["dissolve up","dissolving up","evaporate","evaporating","fade up","rising dust"],dissolveDown:["dissolve down","dissolving down","melt","melting","drip away","dripping"],dissolveAway:["dissolve away","dissolving away","blow away","scatter in wind","dust in wind","fade to dust"],morph:["morph","morphing","transform","transforming","shape shift","shapeshifting","change form","metamorphose"],rain:["rain","raining","shower","showering","drip","dripping","pour","pouring","raining down","particles falling","gentle rain","shower of particles"],drift:["drift","drifting","waft","wafting","float gently","gentle drift"],driftUp:["drift up","drifting up","rising mist","float upward","waft up"],driftDown:["drift down","drifting down","settling dust","float downward","waft down"],vortex:["vortex","whirlpool","tornado","cyclone","maelstrom","spinning vortex","swirling"],cascadeDown:["cascade","cascading","cascade down","waterfall","falling water","pour down","flow down"],confetti:["confetti","throw confetti","celebration particles","party confetti","ticker tape","streamers"],fizz:["fizz","fizzing","fizzy","bubble","bubbling","bubbly","effervescent","carbonated","sparkling bubbles"],burst:["burst","bursting","erupt","erupting","eruption","boom","booming","bursting out","burst of energy","explosive burst","big burst"],burstUp:["burst up","bursting up","fountain","geyser","erupting up"],ripple:["ripple","rippling","wave effect","ripple effect","water ripple","spreading rings"],flash:["flash","flashing","flashy","blink","blinking","strobe","strobing","quick flash","bright flash","flashing light","strobing light"],glow:["glow","glowing","glowy","radiate","radiating","emanate","emanating","luminescent","bright","brighten","brightening","soft glow","warm glow","inner glow","glowing warmly","lighting up","lit up"],bloom:["bloom","blooming","blossom","blossoming","flower","flowering","unfold","unfolding","light bloom","lens bloom"],flicker:["flicker","flickering","flickery","flutter","fluttering","waver","wavering","guttering","flickering light","unsteady light","wavering glow","candle-like"],shiver:["shiver","shivering","chill","chilly","cold","freezing","brr","brrr"],heartbeat:["heartbeat","heart beat","pulse of life","living pulse","thump thump","ba-dum"],snap:["snap","snapping","click","clicking","quick snap","finger snap"],elasticBounce:["elastic bounce","rubbery bounce","springy","bouncy elastic","rubber band","spring back"],hold:["hold","holding","pause","pausing","paused","freeze","freezing","frozen","still","stillness","stop","stopping","stopped","holding still","staying still","frozen in place","completely still","motionless","stationary"],fade:["fade","fading","dim","dimming","disappear","disappearing","vanish","vanishing","fading out","fading away","growing dim","becoming transparent"],settle:["settle","settling","settled","calm","calming","ground","grounding","grounded","center","centering","centered","anchor","anchoring","anchored","root","rooting","rooted","relax","relaxing","unwind","unwinding","decompress","decompressing","settling down","calming down","winding down","cooling down","coming to rest","finding peace"],peek:["peek","peeking","peer","peering","peep","peeping","glance","glancing","peeking out","peek out","looking shyly","shy glance","quick peek","sneaking a look"]},jo={circle:["circle","circular","round","rounded","orb","ball","sphere","spherical","ring","disc","disk","whole","complete","unity","unified","endless","infinite","continuous","full circle","perfect round","come full circle"],sphere:["sphere","spherical","globe","globular","ball","3d circle","three dimensional","round ball","floating sphere"],square:["square","squared","boxy","box","rectangle","rectangular","quadrilateral","cube","cubic","block","blocky","stable","solid","grounded","sturdy","rigid","firm","structured","four sided","four corners","box shape"],triangle:["triangle","triangular","tri","pyramid","pyramidal","delta","wedge","arrow","arrowhead","pointed","sharp","dynamic","directional","ascending","three sided","three pointed","pointing up"],heart:["heart","hearted","hearts","love","loving","lovely","valentine","romantic","affection","affectionate","caring","care","tender","warmth","warm-hearted","heartfelt","compassion","compassionate","devotion","devoted","luv","wuv","<3","โค๏ธ","๐","๐","full of love","with love","heart shape","heart shaped","from the heart"],suspicion:["suspicion","suspicious","suspect","sly","slyly","sneaky","sneakily","mischievous","mischief","smirk","smirking","smirky","grin","grinning","sly grin","side eye","sideeye","side-eye","skeptical","skepticism","doubtful","doubt","doubting","wary","distrustful","distrust","sus","sussy","sussy baka","hmm","hmmm","hmmmm","shady","fishy","sketchy","not buying it","something fishy","seems off","up to something"],star:["star","starred","starry","stars","stellar","astral","twinkle","twinkling","achievement","achieved","excellence","excellent","gold star","five star","superstar","rockstar","rock star","wonder","wonderful","wondrous","magical","magic","miraculous","amazing","spectacular","reach for stars","seeing stars","star shape","shining star"],sun:["sun","sunny","sunshine","sunlight","solar","sol","daylight","daytime","day","radiant","radiance","radiating","bright","brightness","brilliant","glowing","glow","blazing","blaze","warm","warmth","cheerful","cheery","optimistic","optimism","hopeful","hope","positive","positivity","full of light","ray of sunshine","like the sun","sunny disposition"],moon:["moon","moony","moonlight","moonlit","lunar","crescent","nighttime","night","nocturnal","waxing","waning","gibbous","new moon","full moon","half moon","quarter moon","crescent moon","dreamy","dreamlike","dream","mysterious","mystery","mystical","ethereal","otherworldly","serene","serenity","tranquil","contemplative","reflective","moonlit night","by moonlight","moon shape","under the moon"],lunar:["lunar eclipse","blood moon","blood-moon","red moon","copper moon","rust moon","eclipsing","eclipsed","shadow crossing","earth shadow","ominous","foreboding","portentous","dramatic","intense","transforming","transformation","moon in shadow","moon turning red","eclipse phase","lunar event"],solar:["solar eclipse","total eclipse","corona","diamond ring","totality","umbra","penumbra","ring of fire","dark sun","blocked sun","occluded","awe","awesome","awe-inspiring","rare","momentous","historic","breathtaking","magnificent","sun blocked","sun covered","total darkness","corona visible"],eclipse:["eclipse","eclipsing","eclipsed","celestial event","astronomical event","overshadow","overshadowed","blocked","blocking","obscured","hidden","hiding","concealed","passing","crossing","alignment","in eclipse","going dark","being eclipsed","eclipsed by"]},$o={intensity:{barely:["barely","hardly","scarcely","faintly","slightly","marginally","just a bit","just a little","just barely","hint of","touch of","trace of"],slightly:["slightly","somewhat","a little","a bit","mildly","lightly","kind of","kinda","sort of","sorta","a tad","a touch","a smidge"],moderately:["moderately","reasonably","fairly","pretty","rather","quite"],normal:["normal","normally","regular","regularly","standard","typical","typically","average","ordinary"],notably:["notably","noticeably","clearly","definitely","certainly","decidedly","genuinely","truly","really"],very:["very","really","so","such","quite","highly","deeply","seriously","majorly","hella","super","extra","mad"],extremely:["extremely","incredibly","immensely","tremendously","enormously","hugely","intensely","fiercely","wildly","insanely","crazy","ridiculously","mega","ultra","hyper"],absolutely:["absolutely","completely","totally","utterly","entirely","wholly","fully","maximum","max","over the top","off the charts","through the roof","to the max"]},duration:{flash:["flash","instant","instantaneous","split second","split-second","momentary","fleeting","brief flash"],quick:["quick","quickly","fast","rapid","swift","swiftly","brief","briefly","short","shortly","snap"],normal:["normal","regular","standard","typical","usual"],slow:["slow","slowly","gradual","gradually","gentle","gently","easy","easily","leisurely","unhurried"],long:["long","prolonged","extended","sustained","lasting","lingering","drawn out","drawn-out"],persistent:["persistent","constant","continuous","ongoing","steady","maintained","held","holding","stay","staying","keep","keeping","remain","remaining"]},transition:{instant:["instant","instantly","immediate","immediately","sudden","suddenly","abrupt","abruptly","snap","cut","jump"],snappy:["snappy","crisp","sharp","sharply","brisk","briskly","punchy"],smooth:["smooth","smoothly","natural","naturally","fluid","fluidly","flowing"],gentle:["gentle","gently","soft","softly","gradual","gradually","easing","gliding","drifting"],dreamy:["dreamy","dreamlike","floaty","ethereal","languid","lazy","flowing","melting"]},repetition:{once:["once","one time","single","just once","only once","one shot"],few:["few","few times","couple","couple times","twice","two times","thrice","three times"],several:["several","several times","multiple","multiple times","repeatedly","again and again"],many:["many","many times","lots","lots of times","over and over","nonstop"],loop:["loop","looping","looped","continuous","continuously","forever","infinitely","endlessly","always","keep going","on repeat"]}},Wo={barely:{min:.1,max:.2,default:.15},slightly:{min:.2,max:.4,default:.3},moderately:{min:.4,max:.5,default:.45},normal:{min:.5,max:.6,default:.55},notably:{min:.6,max:.7,default:.65},very:{min:.7,max:.85,default:.8},extremely:{min:.85,max:.95,default:.9},absolutely:{min:.95,max:1,default:1}},Uo={flash:{min:100,max:500,default:250},quick:{min:500,max:1e3,default:750},normal:{min:1e3,max:2e3,default:1500},slow:{min:2e3,max:4e3,default:3e3},long:{min:4e3,max:8e3,default:6e3},persistent:{min:8e3,max:1/0,default:1e4}};function Vo(e){const t=new Map;for(const[i,s]of Object.entries(e)){for(const e of s){const s=e.toLowerCase().trim();t.set(s,i)}t.set(i.toLowerCase(),i)}return t}class Yo{constructor(){this.emotionLookup=Vo(qo),this.undertoneLookup=Vo(Go),this.gestureLookup=Vo(Ho),this.shapeLookup=Vo(jo),this.modifierLookup=function(e){const t=new Map;for(const[i,s]of Object.entries(e))for(const[e,n]of Object.entries(s))for(const s of n){const n=s.toLowerCase().trim();t.set(n,{type:i,level:e})}return t}($o)}parse(e){const t={emotion:null,undertone:"clear",gestures:[],shape:null,intensity:Wo.normal.default,duration:Uo.normal.default,transition:"smooth",repetition:"once",unrecognized:[],raw:e};if(!e||"string"!=typeof e)return t;const{tokens:i}=function(e){if(!e||"string"!=typeof e)return{tokens:[],segments:[],phrases:new Map};const t=e.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),{processed:i,phrases:s}=function(e){const t=new Map;let i=e,s=0;for(const{normalized:e,regex:n}of To)if(i.includes(e)){const a=`__PHRASE_${s}__`;n.lastIndex=0,i=i.replace(n,a),t.set(a,e),s++}return{processed:i,phrases:t}}(t),n=i.split(Eo).map(e=>e.trim()).filter(e=>e.length>0),a=[],r=[];for(const e of n){let t=e;for(const[e,i]of s)t=t.replace(e,i);r.push(t.trim());const i=e.split(/\s+/);for(const e of i){if(s.has(e)){a.push(s.get(e));continue}if(!e)continue;if(Ao.has(e)&&!Do.has(e))continue;const t=e.replace(/^[^\w]+|[^\w]+$/g,"");t&&a.push(t)}}return{tokens:a,segments:r,phrases:s}}(e);if(0===i.length)return t;let s=!1;for(let e=0;e<i.length;e++){const n=i[e];if(!_o(n))if(Io(n))s=!0;else if(s)s=!1;else{if(Lo(n)){const s=Oo(n,i,e,t);if(s){this._applyResolution(t,s);continue}}this._tryEmotion(n,t)||this._tryGesture(n,t)||this._tryShape(n,t)||this._tryUndertone(n,t)||this._tryModifier(n,t)||t.unrecognized.push(n)}}return t}_applyResolution(e,t){const{category:i,target:s}=t;switch(i){case"emotion":e.emotion||(e.emotion=s);break;case"undertone":"clear"===e.undertone&&(e.undertone=s);break;case"gesture":e.gestures.includes(s)||e.gestures.push(s);break;case"shape":e.shape||(e.shape=s)}}_tryEmotion(e,t){const i=this.emotionLookup.get(e);return!(!i||t.emotion||(t.emotion=i,0))}_tryGesture(e,t){const i=this.gestureLookup.get(e);return!(!i||t.gestures.includes(i)||(t.gestures.push(i),0))}_tryShape(e,t){const i=this.shapeLookup.get(e);return!(!i||t.shape||(t.shape=i,0))}_tryUndertone(e,t){const i=this.undertoneLookup.get(e);return!(!i||"clear"!==t.undertone||(t.undertone=i,0))}_tryModifier(e,t){const i=this.modifierLookup.get(e);if(i){const{type:e,level:s}=i;switch(e){case"intensity":t.intensity=Wo[s]?.default||t.intensity;break;case"duration":t.duration=Uo[s]?.default||t.duration;break;case"transition":t.transition=s;break;case"repetition":t.repetition=s}return!0}return!1}validate(e){const t=[];return e.emotion||0!==e.gestures.length||e.shape||t.push("No actionable intent found (need emotion, gesture, or shape)"),(e.intensity<0||e.intensity>1)&&t.push(`Intensity ${e.intensity} out of range [0, 1]`),e.duration<=0&&t.push(`Duration ${e.duration} must be positive`),{valid:0===t.length,errors:t}}static getAvailableEmotions(){return Object.keys(qo)}static getAvailableUndertones(){return Object.keys(Go)}static getAvailableGestures(){return Object.keys(Ho)}static getAvailableShapes(){return Object.keys(jo)}}class Xo{#e=null;constructor(e={}){this._config=this._sanitizeConfig(e),this._engine=null,this._timeline=[],this._isRecording=!1,this._recordingStartTime=0,this._playbackStartTime=0,this._isPlaying=!1,this._initialized=!1,this._intentParser=new Yo,this._feelRateLimiter={calls:[],maxCallsPerSecond:10,windowMs:1e3},this._stanceRegistry=new Po,this._audioManager=new wo(()=>this.#t()),this._gestureController=new So(()=>this.#t(),{isRecording:()=>this._isRecording,startTime:()=>this._recordingStartTime,timeline:()=>this._timeline});const t=this;this._timelineRecorder=new xo(()=>this.#t(),this._audioManager,{get timeline(){return t._timeline},set timeline(e){t._timeline=e},get isRecording(){return t._isRecording},set isRecording(e){t._isRecording=e},get recordingStartTime(){return t._recordingStartTime},set recordingStartTime(e){t._recordingStartTime=e},get isPlaying(){return t._isPlaying},set isPlaying(e){t._isPlaying=e},get playbackStartTime(){return t._playbackStartTime},set playbackStartTime(e){t._playbackStartTime=e}}),this._elementAttachmentManager=new Co(()=>this.#t(),()=>this._canvas,this),this._visualEffectsManager=new ko(()=>this.#t(),()=>this._canvas),this.init=this.init.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.pause=this.pause.bind(this),this.resume=this.resume.bind(this),this.setPosition=this.setPosition.bind(this),this.animateToPosition=this.animateToPosition.bind(this),this.clearParticles=this.clearParticles.bind(this)}#t(){return this.#e||this._engine}_sanitizeConfig(e){const t={...e};return delete t.enableDebug,delete t.enableInternalAPIs,delete t.exposeInternals,t.mode="production",void 0===t.enableGazeTracking&&(t.enableGazeTracking=!0),t}init(e){if(this._initialized)return Promise.resolve();this._canvas="string"==typeof e?document.getElementById(e):e;const t={...this._config,canvasId:e},i=new bo(t);return this.#e=i,this._engine=new Proxy(i,{get(e,t){if(["soundSystem","stateMachine","emotionLibrary","audioLevelProcessor","particleSystem","errorBoundary","performanceMonitor","config","debugMode"].includes(t))return new Proxy({},{get(){},set:()=>!1,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor(){}});if("renderer"===t||"shapeMorpher"===t||"audioAnalyzer"===t||"gazeTracker"===t){const i=e[t];if(!i)return;return new Proxy(i,{get(e,i){if({renderer:["setBlinkingEnabled"],shapeMorpher:["resetMusicDetection","frequencyData"],audioAnalyzer:["microphoneStream","currentFrequencies"],gazeTracker:["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"]}[t]?.includes(i))return e[i]},set:()=>!1,has:()=>!1,ownKeys:()=>[]})}return e[t]},set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1,getPrototypeOf:()=>null,setPrototypeOf:()=>!1,has:(e,t)=>!["soundSystem","stateMachine","emotionLibrary"].includes(t)&&t in e,ownKeys:e=>["canvas","start","stop","pause","resume","setEmotion","morphTo","express"].filter(t=>t in e)}),this.canvas=this._engine.canvas,this._initialized=!0,Promise.resolve()}start(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.start()}stop(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.stop()}pause(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.pause()}resume(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.resume()}loadAudio(e){return this._audioManager.loadAudio(e)}getAudioAnalysis(){return this._audioManager.getAudioAnalysis()}connectAudio(e){return this._audioManager.connectAudio(e)}disconnectAudio(e){return this._audioManager.disconnectAudio(e)}getSpectrumData(){return this._audioManager.getSpectrumData()}startRhythmSync(e){return this._audioManager.startRhythmSync(e)}stopRhythmSync(){return this._audioManager.stopRhythmSync()}getPerformanceMetrics(){const e=this.#t();return e?e.performanceMonitor?{fps:e.performanceMonitor.getCurrentFPS()||0,frameTime:e.performanceMonitor.getAverageFrameTime()||0,particleCount:e.particleSystem?.activeParticles||0}:e.animationController?{fps:e.animationController.currentFPS||0,frameTime:1e3/60,particleCount:0}:{fps:0,frameTime:0,particleCount:0}:{fps:0,frameTime:0}}triggerGesture(e,t){return this._gestureController.triggerGesture(e,t)}express(e,t){return this._gestureController.express(e,t)}chain(e){return this._gestureController.chain(e)}morphTo(e,t){return this.setShape(e,t)}updateUndertone(e){return this._gestureController.updateUndertone(e)}feel(e){if(!this.#t())throw new Error("Engine not initialized. Call init() first.");const t=Date.now(),i=this._feelRateLimiter;if(i.calls=i.calls.filter(e=>t-e<i.windowMs),i.calls.length>=i.maxCallsPerSecond)return console.warn(`[EmotiveMascot] feel: Rate limit exceeded. Max ${i.maxCallsPerSecond} calls per second.`),{success:!1,error:"Rate limit exceeded",parsed:null};i.calls.push(t);const s=this._intentParser.parse(e),n=this._intentParser.validate(s);if(!n.valid)return console.warn("[EmotiveMascot] feel: Invalid intent:",n.errors),{success:!1,error:n.errors.join("; "),parsed:s};try{if(s.emotion){const e={};s.undertone&&"clear"!==s.undertone&&(e.undertone=s.undertone);const t=Math.round(500+1e3*(1-s.intensity));this.setEmotion(s.emotion,e,t)}for(const e of s.gestures)this.express(e);return s.shape&&this.morphTo(s.shape),{success:!0,error:null,parsed:s}}catch(e){return console.error("[EmotiveMascot] feel: Execution error:",e),{success:!1,error:e.message,parsed:s}}}static getFeelVocabulary(){return{emotions:Yo.getAvailableEmotions(),undertones:Yo.getAvailableUndertones(),gestures:Yo.getAvailableGestures(),shapes:Yo.getAvailableShapes()}}parseIntent(e){return this._intentParser.parse(e)}setEmotion(e,t,i){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");let n=null,a=500,r=i;if("string"==typeof t)n=t;else if("number"==typeof t)void 0!==i?a=t:r=t;else if(t&&"object"==typeof t){const{undertone:e,duration:i,intensity:s}=t;n=e,void 0!==i&&(a=i),void 0!==s&&(this._lastIntensity=s)}if(this._isRecording){const t=r||Date.now()-this._recordingStartTime;this._timeline.push({type:"emotion",name:e,undertone:n,time:t})}const o={};return n&&(o.undertone=n),void 0!==this._lastIntensity&&(o.intensity=this._lastIntensity,this._lastIntensity=void 0),s.setEmotion(e,Object.keys(o).length?o:null,a),this}setSoundEnabled(e){const t=this.#t();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.soundSystem&&(t.soundSystem.enabled=e),this}pushEmotion(e,t=.5){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.pushEmotion(e,t),this}nudgeEmotion(e,t,i=1){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");return s.stateCoordinator.nudgeEmotion(e,t,i),this}setEmotionDampening(e){const t=this.#t();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.stateCoordinator.setEmotionDampening(e),this}getEmotionDampening(){const e=this.#t();return e?e.stateCoordinator.getEmotionDampening():0}clearEmotions(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.stateCoordinator.clearEmotions(),this}getEmotionalState(){const e=this.#t();return e?e.stateCoordinator.getEmotionalState():{dominant:null,undercurrents:[],slots:[]}}getSnapshot(){const e=this.#t();if(!e)return null;const t={version:1,timestamp:Date.now(),stateMachine:e.stateMachine.serialize()};return e.stateCoordinator._dynamics&&(t.dynamics=e.stateCoordinator._dynamics.serialize()),t}loadSnapshot(e){const t=this.#t();return t&&e&&1===e.version?(e.stateMachine&&t.stateMachine.deserialize(e.stateMachine),e.dynamics&&t.stateCoordinator.dynamics.deserialize(e.dynamics),t.stateCoordinator._emit("emotionChanged",{emotion:t.stateMachine.state.emotion,slots:t.stateMachine.getSlots(),restored:!0}),this):this}get dynamics(){const e=this.#t();return e?e.stateCoordinator.dynamics:null}getInputEvaluator(e){return this._audioManager.getInputEvaluator(e)}setEmotionFeedback(e){const t=this.getInputEvaluator();return t&&t.setEmotionFeedback(e),this}getAudioLayers(){const e=this._audioManager.getLayers();return e?Object.freeze({...e}):null}getEffectiveBPM(){const e=this.#t();if(!e||!e.rhythmIntegration)return 120;let t=e.rhythmIntegration.getEffectiveBPM(e.stateMachine);return t*=this._audioManager.getDifficultyManager().getBPMMultiplier(),Math.round(100*t)/100}setDifficulty(e){return this._audioManager.getDifficultyManager().setDifficulty(e),this}setAssist(e){return this._audioManager.getDifficultyManager().setAssist(e),this}applyModifier(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.modifiers.applyModifier(e,t),this}removeModifier(e){const t=this.#t();return t?(t.stateCoordinator.modifiers.removeModifier(e),this):this}getActiveModifiers(){const e=this.#t();return e?e.stateCoordinator.modifiers.getActiveModifiers():[]}setShape(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");let s=e;if(this._stanceRegistry.hasStance(e)){const t=this._stanceRegistry.activate(e);s=t.shape||e,i.stateCoordinator&&i.stateCoordinator._emit("stanceChanged",{name:e,config:t})}let n,a={};if("number"==typeof t)n=t;else if(t&&"object"==typeof t){const{timestamp:e,...i}=t;a=i,n=e}if(this._isRecording){const e=n||Date.now()-this._recordingStartTime;this._timeline.push({type:"shape",name:s,time:e,config:a})}return i&&i.morphTo(s,a),this}registerStance(e,t){return this._stanceRegistry.registerStance(e,t),this}getActiveStance(){return this._stanceRegistry.getActiveStance()}getAvailableStances(){return this._stanceRegistry.getAvailableStances()}dismissStance(){if(this._stanceRegistry.dismiss()){const e=this.#t();e&&e.stateCoordinator&&e.stateCoordinator._emit("stanceChanged",{name:null,config:null})}return this}enableGazeTracking(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.gazeTracker&&e.gazeTracker.enable(),this}disableGazeTracking(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.gazeTracker&&e.gazeTracker.disable()}setGazeTarget(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");i.gazeTracker&&(i.gazeTracker.mousePos={x:e,y:t},i.gazeTracker.updateTargetGaze())}setContainment(e,t=1){return this._visualEffectsManager.setContainment(e,t)}setPosition(e,t,i=0){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");if(s.positionController)s.positionController.onUpdate||(s.positionController.onUpdate=()=>{}),s.positionController.setOffset(e,t,i);else if(this._canvas){const s=window.innerWidth/2+e,n=window.innerHeight/2+t,a=1+.001*i;this._canvas.style.transform=`translate(${s}px, ${n}px) translate(-50%, -50%) scale(${a})`}}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){const a=this.#t();if(!a)throw new Error("Engine not initialized. Call init() first.");a.positionController?(a.positionController.onUpdate||(a.positionController.onUpdate=()=>{}),a.positionController.animateOffset(e,t,i,s,n)):this.setPosition(e,t,i)}clearParticles(){return this._visualEffectsManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this._visualEffectsManager.setParticleSystemCanvasDimensions(e,t),this}attachToElement(e,t={}){return this._elementAttachmentManager.attachToElement(e,t)}isAttachedToElement(){return this._elementAttachmentManager.isAttachedToElement()}detachFromElement(){return this._elementAttachmentManager.detachFromElement()}getGazeState(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.gazeTracker?e.gazeTracker.getState():null}setBPM(e){e=Math.max(0,Math.min(300,Number(e)||0));const t=this.#t();return t&&t.rhythmIntegration&&t.rhythmIntegration.setBPM(e),this}setQuality(e){const t={low:{particleCount:50,fps:30},medium:{particleCount:100,fps:60},high:{particleCount:200,fps:60}},i=t[e]||t.medium,s=this.#t();s&&s.performanceMonitor&&s.performanceMonitor.setTargetFPS(i.fps),s&&s.particleSystem&&s.particleSystem.setMaxParticles(i.particleCount)}setMaxParticles(e){e=Math.max(0,Math.min(1e3,Math.floor(Number(e)||0)));const t=this.#t();return t&&t.particleSystem&&t.particleSystem.setMaxParticles(e),this}getParticleCount(){const e=this.#t();return e&&e.particleSystem&&e.particleSystem.particles?e.particleSystem.particles.length:0}setOpacity(e){const t=this.#t();if(e=Math.max(0,Math.min(1,e)),t&&t.renderer){const i=t.canvasManager?.getContext();i&&(i.globalAlpha=e)}return this._currentOpacity=e,this}getOpacity(){return void 0!==this._currentOpacity?this._currentOpacity:1}fadeIn(e=1e3){const t=this.getOpacity(),i=performance.now(),s=n=>{const a=n-i,r=Math.min(a/e,1),o=t+(1-t)*r;this.setOpacity(o),r<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}fadeOut(e=1e3){const t=this.getOpacity(),i=performance.now(),s=n=>{const a=n-i,r=Math.min(a/e,1),o=t*(1-r);this.setOpacity(o),r<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}async transitionTo(e,t={}){const i=t.fadeOutMs??500,s=t.fadeInMs??500;await new Promise(e=>{const t=this.getOpacity(),s=performance.now(),n=a=>{const r=Math.min((a-s)/i,1);this.setOpacity(t*(1-r)),r<1?requestAnimationFrame(n):e()};requestAnimationFrame(n)}),e&&e(this),await new Promise(e=>{const t=performance.now(),i=n=>{const a=Math.min((n-t)/s,1);this.setOpacity(a),a<1?requestAnimationFrame(i):e()};requestAnimationFrame(i)})}setAmbientMood(e){let t;if("string"==typeof e){if(t=this._ambientPresets?.[e],!t)return this}else t=e;return this._ambientMood={...t},t.tint&&this.setColor(t.tint),this}registerAmbientPreset(e,t){if("__proto__"===e||"constructor"===e||"prototype"===e)return this;this._ambientPresets||(this._ambientPresets={});const i={};for(const e of Object.keys(t))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(i[e]=t[e]);return this._ambientPresets[e]=i,this}getAmbientMood(){return this._ambientMood?{...this._ambientMood}:null}setColor(e){const t=this.#t();return t&&t.renderer&&t.renderer.config&&(t.renderer.config.coreColor=e),this}setGlowColor(e){const t=this.#t();return t&&t.renderer&&t.renderer.config&&(t.renderer.config.defaultGlowColor=e),this}setTheme(e){return e&&"object"==typeof e?(e.core&&this.setColor(e.core),e.glow&&this.setGlowColor(e.glow),this):this}setSpeed(e){const t=this.#t();return e=Math.max(.1,Math.min(10,e)),this._speedMultiplier=e,t&&t.animationController&&t.animationController.setSpeedMultiplier(e),this}getSpeed(){const e=this.#t();return e&&e.animationController?e.animationController.getSpeedMultiplier():this._speedMultiplier||1}setFPS(e){const t=this.#t();return e=Math.max(1,Math.min(120,e)),t&&t.animationController&&t.animationController.setTargetFPS(e),this}getFPS(){const e=this.#t();return e&&e.animationController&&e.animationController.targetFPS||60}isPaused(){const e=this.#t();return!(!e||!e.animationController)&&!0===e.animationController.isPaused}batch(e){const t=this.isPaused();return t||this.pause(),"function"==typeof e&&e(this),t||this.resume(),this}on(e,t){const i=this.#t();return i&&i.eventManager&&i.eventManager.on(e,t),this}off(e,t){const i=this.#t();return i&&i.eventManager&&i.eventManager.off(e,t),this}setScale(e){const t=this.#t();return t&&t.positionController&&(t.positionController.setScaleOverrides(e),"object"==typeof e&&void 0!==e.particles&&t.particleSystem&&"function"==typeof t.particleSystem.refreshPool&&t.particleSystem.refreshPool()),this}getScale(){const e=this.#t();return e&&e.positionController&&e.positionController.globalScale||1}setBackdrop(e={}){const t=this.#t();return t&&"function"==typeof t.setBackdrop&&t.setBackdrop(e),this}getBackdrop(){const e=this.#t();return e&&"function"==typeof e.getBackdrop?e.getBackdrop():null}startRecording(){return this._timelineRecorder.startRecording()}stopRecording(){return this._timelineRecorder.stopRecording()}playTimeline(e){return this._timelineRecorder.playTimeline(e)}stopPlayback(){return this._timelineRecorder.stopPlayback()}getTimeline(){return this._timelineRecorder.getTimeline()}loadTimeline(e){return this._timelineRecorder.loadTimeline(e)}exportTimeline(){return this._timelineRecorder.exportTimeline()}importTimeline(e){return this._timelineRecorder.importTimeline(e)}getCurrentTime(){return this._timelineRecorder.getCurrentTime()}seek(e){return this._timelineRecorder.seek(e)}getFrameData(e="png"){return this._visualEffectsManager.getFrameData(e)}getFrameBlob(e="png"){return this._visualEffectsManager.getFrameBlob(e)}getAnimationData(){return this._timelineRecorder.getAnimationData()}getAvailableGestures(){return Ri()}getAvailableEmotions(){return["neutral","joy","calm","sadness","anger","fear","surprise","disgust","love","euphoria","excited","focused","suspicion","resting","glitch"]}getAvailableShapes(){return["circle","square","triangle","star","heart","moon","sun"]}getVersion(){return"3.4.0"}getCapabilities(){return{audio:!0,recording:!0,timeline:!0,export:!0,shapes:!0,gestures:!0,emotions:!0,particles:!0,gazeTracking:!0}}get renderer(){const e=this.#t();return e&&e.renderer?new Proxy(e.renderer,{get:(e,t)=>["setBlinkingEnabled"].includes(t)?e[t]:void 0}):null}get shapeMorpher(){const e=this.#t();return e&&e.shapeMorpher?new Proxy(e.shapeMorpher,{get:(e,t)=>["resetMusicDetection","frequencyData"].includes(t)?e[t]:void 0}):null}get gazeTracker(){const e=this.#t();return e&&e.gazeTracker?new Proxy(e.gazeTracker,{get:(e,t)=>["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"].includes(t)?e[t]:void 0}):null}destroy(){this.stop(),this._timeline=[],this._isRecording=!1,this._isPlaying=!1,this.detachFromElement();const e=this.#t();e&&e.destroy&&e.destroy()}}class No{constructor(e={}){this._state=this.deepClone(e),this._prevState=this.deepClone(e),this._subscribers=new Map,this._history=[],this._maxHistorySize=50,this._middleware=[],this._validators=new Map,this._computed=new Map,this._computedDeps=new Map,this._stats={updates:0,notifications:0,computedCacheHits:0,computedCacheMisses:0}}getState(e=null){return e?this.deepClone(this.getNestedValue(this._state,e)):this.deepClone(this._state)}setState(e,t=void 0){let i;i="string"==typeof e?{[e]:t}:e;for(const e of this._middleware)if(i=e(i,this._state),!i)return!1;const s=this.deepClone(this._state);for(const[e,t]of Object.entries(i)){if(this._validators.has(e)&&!this._validators.get(e)(t))return console.error(`Validation failed for path: ${e}`),!1;this.setNestedValue(s,e,t)}return this._prevState=this._state,this._state=s,this.addToHistory(i),this.invalidateComputed(Object.keys(i)),this.notifySubscribers(i),this._stats.updates++,!0}subscribe(e,t=null){let i=null,s=e;"string"==typeof e&&(i=e,s=t);const n=Symbol("subscriber"),a={path:i,callback:s,id:n};return this._subscribers.set(n,a),()=>{this._subscribers.delete(n)}}computed(e,t,i){this._computedDeps.set(e,t),Object.defineProperty(this,e,{get:()=>{if(this._computed.has(e))return this._stats.computedCacheHits++,this._computed.get(e);this._stats.computedCacheMisses++;const s=t.map(e=>this.getState(e)),n=i(...s);return this._computed.set(e,n),n}})}addValidator(e,t){this._validators.set(e,t)}addMiddleware(e){this._middleware.push(e)}reset(e={}){this._state=this.deepClone(e),this._prevState=this.deepClone(e),this._history=[],this._computed.clear(),this.notifySubscribers({"*":"reset"})}getDiff(){return this.objectDiff(this._prevState,this._state)}undo(e=1){if(this._history.length<e)return console.warn("Cannot undo: insufficient history"),!1;const t=Math.max(0,this._history.length-e-1),i=this._history[t];return!!i&&(this._state=this.deepClone(i.state),this._history=this._history.slice(0,t+1),this.notifySubscribers({"*":"undo"}),!0)}batch(e){const t={},i=this.setState.bind(this);return this.setState=(e,i)=>("string"==typeof e?t[e]=i:Object.assign(t,e),!0),e(),this.setState=i,this.setState(t)}createSelector(e){let t=null,i=null;return()=>{const s=this._state;return s===t||(t=s,i=e(s)),i}}static _DANGEROUS_KEYS=new Set(["__proto__","constructor","prototype"]);notifySubscribers(e){for(const t of this._subscribers.values())t.path&&!Object.keys(e).some(e=>e.startsWith(t.path)||t.path.startsWith(e))||(t.callback(this._state,e),this._stats.notifications++)}invalidateComputed(e){for(const[t,i]of this._computedDeps.entries())i.some(t=>e.some(e=>t.startsWith(e)||e.startsWith(t)))&&this._computed.delete(t)}addToHistory(e){this._history.push({timestamp:Date.now(),updates:e,state:this.deepClone(this._state)}),this._history.length>this._maxHistorySize&&this._history.shift()}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map(e=>this.deepClone(e));if(e instanceof Object){const t={};for(const i in e)({}).hasOwnProperty.call(e,i)&&(t[i]=this.deepClone(e[i]));return t}}getNestedValue(e,t){const i=t.split(".");for(const e of i)if(No._DANGEROUS_KEYS.has(e))return void console.warn("[StateStore] Rejected dangerous path segment:",e);return i.reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,e)}setNestedValue(e,t,i){const s=t.split(".");for(const e of s)if(No._DANGEROUS_KEYS.has(e))return void console.warn("[StateStore] Rejected dangerous path segment:",e);const n=s.pop();s.reduce((e,t)=>(e[t]||(e[t]={}),e[t]),e)[n]=i}_deepEqual(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this._deepEqual(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!{}.hasOwnProperty.call(t,i))return!1;if(!this._deepEqual(e[i],t[i]))return!1}return!0}objectDiff(e,t){const i={};for(const s in t)s in e?this._deepEqual(e[s],t[s])||(i[s]={type:"changed",oldValue:e[s],newValue:t[s]}):i[s]={type:"added",value:t[s]};for(const s in e)s in t||(i[s]={type:"deleted",oldValue:e[s]});return i}getStats(){return{...this._stats,subscribers:this._subscribers.size,historySize:this._history.length,computedValues:this._computed.size,validators:this._validators.size}}}const Qo=new No({engine:{initialized:!1,running:!1,paused:!1,fps:60,frameCount:0},renderer:{color:"#4a90e2",intensity:1,eyeOpenness:1,breathRate:1,breathDepth:1,sleeping:!1},animation:{currentGesture:null,activeLoops:0},emotion:{current:"neutral",intensity:1,undertone:null,transitioning:!1},particles:{active:!0,count:0,maxParticles:100},sound:{enabled:!1,volume:1,bpm:120,rhythmEnabled:!1},performance:{quality:"high",adaptiveQuality:!0,targetFPS:60,actualFPS:60}});class Jo{constructor(e){this.ctx=e,this.currentState={fillStyle:null,strokeStyle:null,globalAlpha:1,globalCompositeOperation:"source-over",lineWidth:1,lineCap:"butt",lineJoin:"miter",shadowBlur:0,shadowColor:"transparent",shadowOffsetX:0,shadowOffsetY:0,font:"10px sans-serif"},this.stateStack=[],this.stats={saves:0,restores:0,stateChanges:0,redundantChanges:0}}setFillStyle(e){this.currentState.fillStyle!==e?(this.ctx.fillStyle=e,this.currentState.fillStyle=e,this.stats.stateChanges++):this.stats.redundantChanges++}setStrokeStyle(e){this.currentState.strokeStyle!==e?(this.ctx.strokeStyle=e,this.currentState.strokeStyle=e,this.stats.stateChanges++):this.stats.redundantChanges++}setGlobalAlpha(e){Math.abs(this.currentState.globalAlpha-e)>.001?(this.ctx.globalAlpha=e,this.currentState.globalAlpha=e,this.stats.stateChanges++):this.stats.redundantChanges++}setGlobalCompositeOperation(e){this.currentState.globalCompositeOperation!==e?(this.ctx.globalCompositeOperation=e,this.currentState.globalCompositeOperation=e,this.stats.stateChanges++):this.stats.redundantChanges++}setLineWidth(e){Math.abs(this.currentState.lineWidth-e)>.001?(this.ctx.lineWidth=e,this.currentState.lineWidth=e,this.stats.stateChanges++):this.stats.redundantChanges++}setShadow(e=0,t="transparent",i=0,s=0){let n=!1;Math.abs(this.currentState.shadowBlur-e)>.001&&(this.ctx.shadowBlur=e,this.currentState.shadowBlur=e,n=!0),this.currentState.shadowColor!==t&&(this.ctx.shadowColor=t,this.currentState.shadowColor=t,n=!0),Math.abs(this.currentState.shadowOffsetX-i)>.001&&(this.ctx.shadowOffsetX=i,this.currentState.shadowOffsetX=i,n=!0),Math.abs(this.currentState.shadowOffsetY-s)>.001&&(this.ctx.shadowOffsetY=s,this.currentState.shadowOffsetY=s,n=!0),n?this.stats.stateChanges++:this.stats.redundantChanges++}clearShadow(){0===this.currentState.shadowBlur&&"transparent"===this.currentState.shadowColor||this.setShadow(0,"transparent",0,0)}save(){this.ctx.save(),this.stateStack.push({...this.currentState}),this.stats.saves++}restore(){this.ctx.restore(),this.stateStack.length>0&&(this.currentState=this.stateStack.pop()),this.stats.restores++}getStats(){const e=this.stats.stateChanges+this.stats.redundantChanges,t=e>0?(this.stats.redundantChanges/e*100).toFixed(2):0;return{saves:this.stats.saves,restores:this.stats.restores,stateChanges:this.stats.stateChanges,redundantChanges:this.stats.redundantChanges,redundancyRate:`${t}%`,stackDepth:this.stateStack.length}}resetStats(){this.stats={saves:0,restores:0,stateChanges:0,redundantChanges:0}}reset(){this.currentState={fillStyle:null,strokeStyle:null,globalAlpha:1,globalCompositeOperation:"source-over",lineWidth:1,lineCap:"butt",lineJoin:"miter",shadowBlur:0,shadowColor:"transparent",shadowOffsetX:0,shadowOffsetY:0,font:"10px sans-serif"},this.stateStack=[],this.resetStats()}scoped(e){this.save();try{e()}finally{this.restore()}}batch(e){void 0!==e.fillStyle&&this.setFillStyle(e.fillStyle),void 0!==e.strokeStyle&&this.setStrokeStyle(e.strokeStyle),void 0!==e.globalAlpha&&this.setGlobalAlpha(e.globalAlpha),void 0!==e.globalCompositeOperation&&this.setGlobalCompositeOperation(e.globalCompositeOperation),void 0!==e.lineWidth&&this.setLineWidth(e.lineWidth),e.shadow&&this.setShadow(e.shadow.blur,e.shadow.color,e.shadow.offsetX,e.shadow.offsetY)}}class Ko{constructor(e={}){this.enabled=!1!==e.enabled,this.sampleInterval=e.sampleInterval||1e3,this.maxSamples=e.maxSamples||60,this.enableMemoryTracking=!1!==e.enableMemoryTracking,this.enableNetworkTracking=!1!==e.enableNetworkTracking,this.metrics={fps:{samples:[],current:0,avg:0,min:1/0,max:0},frameTime:{samples:[],current:0,avg:0,min:1/0,max:0},memory:{samples:[],current:0,avg:0,min:1/0,max:0},renderTime:{samples:[],current:0,avg:0,min:1/0,max:0},updateTime:{samples:[],current:0,avg:0,min:1/0,max:0},particleCount:{samples:[],current:0,avg:0,min:1/0,max:0},drawCalls:{samples:[],current:0,avg:0,min:1/0,max:0},canvasOperations:{samples:[],current:0,avg:0,min:1/0,max:0}},this.frameCount=0,this.lastFrameTime=0,this.lastSampleTime=0,this.marks=new Map,this.measures=new Map,this.thresholds={fps:{warning:50,critical:30},frameTime:{warning:20,critical:33},memory:{warning:100,critical:200},renderTime:{warning:10,critical:16},...e.thresholds},this.callbacks={onWarning:e.onWarning||null,onCritical:e.onCritical||null,onSample:e.onSample||null},this.enabled&&this.start()}start(){this.enabled&&(this.lastSampleTime=performance.now(),this.lastFrameTime=performance.now(),this.frameCount=0,this.sampleIntervalId=setInterval(()=>this.sample(),this.sampleInterval))}stop(){this.sampleIntervalId&&(clearInterval(this.sampleIntervalId),this.sampleIntervalId=null)}frame(e=performance.now()){if(!this.enabled)return;this.frameCount++;const t=e-this.lastFrameTime;this.metrics.frameTime.current=t,t>0&&(this.metrics.fps.current=1e3/t),this.lastFrameTime=e}mark(e,t=performance.now()){this.enabled&&this.marks.set(e,t)}measure(e,t,i=null){if(!this.enabled)return 0;const s=this.marks.get(t);if(!s)return 0;const n=(i?this.marks.get(i):performance.now())-s;let a=this.measures.get(e);return a||(a=[],this.measures.set(e,a)),a.push(n),a.length>this.maxSamples&&a.shift(),"render"===e?this.metrics.renderTime.current=n:"update"===e&&(this.metrics.updateTime.current=n),n}recordMetric(e,t){this.enabled&&this.metrics[e]&&(this.metrics[e].current=t)}sample(){const e=performance.now(),t=e-this.lastSampleTime,i=1e3*this.frameCount/t;if(this.updateMetric("fps",i),this.enableMemoryTracking&&performance.memory){const e=performance.memory.usedJSHeapSize/1048576;this.updateMetric("memory",e)}for(const e in this.metrics)"fps"!==e&&"memory"!==e&&this.updateMetric(e,this.metrics[e].current);this.checkThresholds(),this.frameCount=0,this.lastSampleTime=e,this.callbacks.onSample&&this.callbacks.onSample(this.getStats())}updateMetric(e,t){const i=this.metrics[e];i&&(i.current=t,i.samples.push(t),i.samples.length>this.maxSamples&&i.samples.shift(),i.samples.length>0&&(i.avg=i.samples.reduce((e,t)=>e+t,0)/i.samples.length,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t)))}checkThresholds(){for(const[e,t]of Object.entries(this.thresholds)){const i=this.metrics[e];if(!i)continue;const s=i.current;let n="normal";"fps"===e?s<=t.critical?n="critical":s<=t.warning&&(n="warning"):s>=t.critical?n="critical":s>=t.warning&&(n="warning"),"critical"===n&&this.callbacks.onCritical?this.callbacks.onCritical(e,s,t.critical):"warning"===n&&this.callbacks.onWarning&&this.callbacks.onWarning(e,s,t.warning)}}getStats(){const e={};for(const[t,i]of Object.entries(this.metrics))e[t]={current:i.current,average:i.avg,min:i.min===1/0?0:i.min,max:i.max,samples:i.samples.length};return e.performance=this.getPerformanceScore(),e.health=this.getHealthStatus(),e}getPerformanceScore(){let e=100;return e-=40*(1-Math.min(this.metrics.fps.current/60,1)),e-=30*(1-Math.min(16.67/Math.max(this.metrics.frameTime.current,1),1)),this.metrics.memory.current>0&&(e-=20*(1-Math.min(100/Math.max(this.metrics.memory.current,1),1))),e-=10*(1-Math.min(10/Math.max(this.metrics.renderTime.current,1),1)),Math.max(0,Math.round(e))}getHealthStatus(){const e=this.getPerformanceScore();return e>=90?"excellent":e>=75?"good":e>=50?"fair":e>=25?"poor":"critical"}reset(){for(const e of Object.values(this.metrics))e.samples=[],e.current=0,e.avg=0,e.min=1/0,e.max=0;this.marks.clear(),this.measures.clear(),this.frameCount=0}exportData(){return{timestamp:Date.now(),metrics:this.getStats(),measures:Array.from(this.measures.entries()).map(([e,t])=>({name:e,values:t,average:t.reduce((e,t)=>e+t,0)/t.length,min:Math.min(...t),max:Math.max(...t)})),thresholds:this.thresholds}}setThreshold(e,t,i){this.thresholds[e]&&(this.thresholds[e]={warning:t,critical:i})}enable(){this.enabled=!0,this.start()}disable(){this.enabled=!1,this.stop()}}const Zo=new Ko({enabled:!0,sampleInterval:1e3,maxSamples:60,thresholds:{fps:{warning:50,critical:30},frameTime:{warning:20,critical:33},memory:{warning:150,critical:300},renderTime:{warning:10,critical:16},updateTime:{warning:5,critical:10}}});class el{constructor(e={}){this.baseUrl=e.baseUrl||"/dist/modules/",this.cache=new Map,this.loading=new Map,this.moduleMap=new Map([["core",()=>Promise.resolve().then(function(){return Dl})],["features",()=>Promise.resolve().then(function(){return _l})],["plugins",()=>Promise.resolve().then(function(){return Il})],["particles",()=>Promise.resolve().then(function(){return un})],["audio",()=>Promise.resolve().then(function(){return pr})],["idle-behavior",()=>Promise.resolve().then(function(){return Ma})]]),this.preloadQueue=[],this.preloading=!1,this.features={dynamicImport:this.checkDynamicImport(),modulePreload:"modulepreload"in document.createElement("link").relList,prefetch:"prefetch"in document.createElement("link").relList}}checkDynamicImport(){try{return"undefined"!=typeof window&&"function"==typeof window.import}catch{return!1}}async load(e){if(this.cache.has(e))return this.cache.get(e);if(this.loading.has(e))return this.loading.get(e);const t=this._loadModule(e);this.loading.set(e,t);try{const i=await t;return this.cache.set(e,i),this.loading.delete(e),i}catch(t){throw this.loading.delete(e),new Error(`Failed to load module '${e}': ${t.message}`)}}_validateModulePath(e){if("string"!=typeof e||!e)throw new Error("[LazyLoader] Invalid module path");if(/^https?:\/\//i.test(e))throw new Error("[LazyLoader] External URLs not allowed");if(e.includes(".."))throw new Error("[LazyLoader] Directory traversal not allowed");if(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(e))throw new Error("[LazyLoader] Protocol-based paths not allowed")}_loadModule(e){const t=this.moduleMap.get(e);if(t)return t();this._validateModulePath(e);const i=`${this.baseUrl}${e}.js`;return this.features.dynamicImport?import(i):this._loadScript(i)}_loadScript(e){const t=new Set(["EmotiveEngine","EmotiveMascot","EmotiveMascot3D"]);return new Promise((i,s)=>{const n=document.createElement("script");n.type="module",n.src=e,n.onload=()=>{const n=e.split("/").pop().replace(".js","");if(!t.has(n))return console.warn(`[LazyLoader] Blocked window lookup for unrecognized module: ${n}`),void s(new Error(`Module not allowed for window lookup: ${n}`));const a=window[n]||window.EmotiveEngine?.[n];a?i(a):s(new Error(`Module not found after loading: ${e}`))},n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}preload(e){Array.isArray(e)||(e=[e]);for(const t of e)this.cache.has(t)||this.preloadQueue.includes(t)||this.preloadQueue.push(t);this.preloading||this._processPreloadQueue()}async _processPreloadQueue(){if(0===this.preloadQueue.length)return void(this.preloading=!1);this.preloading=!0;const e=this.preloadQueue.shift();try{await this.load(e)}catch(t){console.warn(`Failed to preload module '${e}':`,t)}this._processPreloadQueue()}prefetch(e){if(this.features.prefetch){Array.isArray(e)||(e=[e]);for(const t of e){const e=`${this.baseUrl}${t}.js`,i=document.createElement("link");i.rel="prefetch",i.as="script",i.href=e,document.head.appendChild(i)}}}modulePreload(e){if(this.features.modulePreload){Array.isArray(e)||(e=[e]);for(const t of e){const e=`${this.baseUrl}${t}.js`,i=document.createElement("link");i.rel="modulepreload",i.href=e,document.head.appendChild(i)}}}loadFeature(e){const t={particles:["particles"],audio:["audio"],behaviors:["idle-behavior"],plugins:["plugins"]}[e];if(!t)throw new Error(`Unknown feature: ${e}`);const i=t.map(e=>this.load(e));return Promise.all(i)}whenReady(e){Array.isArray(e)||(e=[e]);const t=e.map(e=>this.cache.has(e)?Promise.resolve(this.cache.get(e)):this.loading.has(e)?this.loading.get(e):this.load(e));return Promise.all(t)}isLoaded(e){return this.cache.has(e)}getLoadedModules(){return Array.from(this.cache.keys())}clearCache(e=null){e?this.cache.delete(e):this.cache.clear()}getStats(){return{loaded:this.cache.size,loading:this.loading.size,queued:this.preloadQueue.length,features:this.features,modules:this.getLoadedModules()}}}const tl=new el;function il(e){return tl.load(e)}function sl(...e){tl.preload(e.flat())}function nl(...e){tl.prefetch(e.flat())}const al=new Map,rl=/([+*]|\{[0-9]+,\})\s*[)]\s*[+*?]|\([^)]*[+*][^)]*\)\s*[+*]/;class ol{constructor(e={}){this.flags=new Map,this.overrides=new Map,this.variants=new Map,this.evaluations=new Map,this.config={endpoint:e.endpoint||"/api/feature-flags",refreshInterval:e.refreshInterval||3e5,storage:e.storage||"localStorage",storageKey:e.storageKey||"emotive-feature-flags",userId:e.userId||this.generateUserId(),attributes:e.attributes||{},enableAnalytics:!1!==e.enableAnalytics,enableCache:!1!==e.enableCache,defaultFlags:e.defaultFlags||{}},this.callbacks={onFlagChange:e.onFlagChange||null,onEvaluation:e.onEvaluation||null,onError:e.onError||null},this.refreshTimer=null,this.initialized=!1,this.loadDefaultFlags(),this.config.enableCache&&this.loadFromStorage(),this.config.endpoint&&this.startAutoRefresh()}generateUserId(){const e=this.getStoredUserId();if(e)return e;const t=`user-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return this.storeUserId(t),t}getStoredUserId(){try{if("undefined"!=typeof localStorage)return localStorage.getItem("emotive-user-id")}catch{}return null}storeUserId(e){try{"undefined"!=typeof localStorage&&localStorage.setItem("emotive-user-id",e)}catch{}}loadDefaultFlags(){const e={enableParticles:{enabled:!0,variant:"default"},enableAudio:{enabled:!0,variant:"default"},enableEmotions:{enabled:!0,variant:"default"},enableGestures:{enabled:!0,variant:"default"},enableGradientCache:{enabled:!0,variant:"default"},enableLazyLoading:{enabled:!0,variant:"default"},enableCodeSplitting:{enabled:!1,variant:"default"},enableWebGL:{enabled:!1,variant:"default"},enableWebGPU:{enabled:!1,variant:"default"},enableOffscreenCanvas:{enabled:!1,variant:"default"},enableDebugMode:{enabled:!1,variant:"default"},enablePerformanceOverlay:{enabled:!1,variant:"default"},enableErrorReporting:{enabled:!0,variant:"default"},buttonColor:{enabled:!0,variant:"blue"},animationSpeed:{enabled:!0,variant:"normal"},particleDensity:{enabled:!0,variant:"medium"},...this.config.defaultFlags};for(const[t,i]of Object.entries(e))this.flags.set(t,i)}async fetchFlags(){if(this.config.endpoint)try{const e=await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:this.config.userId,attributes:this.config.attributes,flags:Array.from(this.flags.keys())})});if(!e.ok)throw new Error(`HTTP ${e.status}`);const t=await e.json();return this.updateFlags(t.flags),this.config.enableCache&&this.saveToStorage(),t.flags}catch(e){this.callbacks.onError&&this.callbacks.onError(e),console.error("Failed to fetch feature flags:",e)}}updateFlags(e){const t=[];for(const[i,s]of Object.entries(e)){const e=this.flags.get(i);this.isEqual(e,s)||(this.flags.set(i,s),t.push({key:i,oldValue:e,newValue:s}))}t.length>0&&this.callbacks.onFlagChange&&this.callbacks.onFlagChange(t)}isEqual(e,t){return e===t||!(!e||!t)&&e.enabled===t.enabled&&e.variant===t.variant}isEnabled(e,t=!1){if(this.overrides.has(e))return this.overrides.get(e);const i=this.flags.get(e),s=i?i.enabled:t;return this.trackEvaluation(e,s,i?.variant||"default"),s}getVariant(e,t="default"){if(this.variants.has(e))return this.variants.get(e);const i=this.flags.get(e),s=i?i.variant:t;return this.trackEvaluation(e,i?.enabled||!1,s),s}evaluate(e,t={}){const{defaultEnabled:i=!1,defaultVariant:s="default",attributes:n={}}=t,a={...this.config.attributes,...n},r=this.flags.get(e);if(r&&r.rules)for(const t of r.rules)if(this.evaluateRule(t,a)){const i={enabled:void 0!==t.enabled?t.enabled:r.enabled,variant:t.variant||r.variant};return this.trackEvaluation(e,i.enabled,i.variant),i}return{enabled:this.isEnabled(e,i),variant:this.getVariant(e,s)}}evaluateRule(e,t){if(!e.conditions)return!0;for(const i of e.conditions)if(!this.evaluateCondition(i,t))return!1;return!0}evaluateCondition(e,t){const{attribute:i,operator:s,value:n}=e,a=t[i];switch(s){case"equals":return a===n;case"not_equals":return a!==n;case"contains":return String(a).includes(n);case"not_contains":return!String(a).includes(n);case"greater_than":return Number(a)>Number(n);case"less_than":return Number(a)<Number(n);case"in":return n.includes(a);case"not_in":return!n.includes(a);case"matches":try{if("string"==typeof n&&n.length>200)return!1;const e=function(e){const t=al.get(e);if(t)return t;if(rl.test(e))return null;const i=new RegExp(e);if(al.size>=100){const e=al.keys().next().value;al.delete(e)}return al.set(e,i),i}(n);return!!e&&e.test(String(a))}catch{return!1}default:return!1}}trackEvaluation(e,t,i){if(!this.config.enableAnalytics)return;const s={flagKey:e,enabled:t,variant:i,timestamp:Date.now(),userId:this.config.userId,attributes:this.config.attributes};this.evaluations.has(e)||this.evaluations.set(e,[]),this.evaluations.get(e).push(s),this.callbacks.onEvaluation&&this.callbacks.onEvaluation(s)}override(e,t,i=null){this.overrides.set(e,t),null!==i&&this.variants.set(e,i)}clearOverride(e){this.overrides.delete(e),this.variants.delete(e)}clearAllOverrides(){this.overrides.clear(),this.variants.clear()}getAllFlags(){const e={};for(const[t,i]of this.flags)e[t]={...i,overridden:this.overrides.has(t)};return e}getEnabledFlags(){const e=[];for(const[t]of this.flags)this.isEnabled(t)&&e.push(t);return e}saveToStorage(){if(this.config.enableCache)try{const e=this.getStorage();if(!e)return;const t={flags:Object.fromEntries(this.flags),timestamp:Date.now(),userId:this.config.userId};e.setItem(this.config.storageKey,JSON.stringify(t))}catch(e){console.error("Failed to save feature flags to storage:",e)}}loadFromStorage(){if(!this.config.enableCache)return;const e=this.getStorage();if(!e)return;const t=e.getItem(this.config.storageKey);if(t)try{const e=JSON.parse(t);if(Date.now()-e.timestamp>this.config.refreshInterval)return;this.updateFlags(e.flags)}catch(t){console.warn("Failed to load feature flags from storage, removing corrupted key:",t);try{e.removeItem(this.config.storageKey)}catch{}}}getStorage(){try{if("localStorage"===this.config.storage&&"undefined"!=typeof localStorage)return localStorage;if("sessionStorage"===this.config.storage&&"undefined"!=typeof sessionStorage)return sessionStorage}catch{}return null}startAutoRefresh(){this.refreshTimer||(this.fetchFlags(),this.refreshTimer=setInterval(()=>{this.fetchFlags()},this.config.refreshInterval))}stopAutoRefresh(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}updateAttributes(e){this.config.attributes={...this.config.attributes,...e},this.config.endpoint&&this.fetchFlags()}getAnalytics(){const e={evaluations:{},summary:{total:0,byFlag:{},byVariant:{}}};for(const[t,i]of this.evaluations){e.evaluations[t]=i,e.summary.total+=i.length,e.summary.byFlag[t]={count:i.length,enabled:i.filter(e=>e.enabled).length,variants:{}};for(const s of i)e.summary.byVariant[s.variant]||(e.summary.byVariant[s.variant]=0),e.summary.byVariant[s.variant]++,e.summary.byFlag[t].variants[s.variant]||(e.summary.byFlag[t].variants[s.variant]=0),e.summary.byFlag[t].variants[s.variant]++}return e}reset(){this.flags.clear(),this.overrides.clear(),this.variants.clear(),this.evaluations.clear(),this.loadDefaultFlags()}destroy(){this.stopAutoRefresh(),this.reset()}}const ll=new ol({endpoint:null,enableCache:!0,enableAnalytics:!1});function hl(e,t=!1){return ll.isEnabled(e,t)}function cl(e,t="default"){return ll.getVariant(e,t)}class ul{constructor(e,t,i){this.name=e,this.startBeat=t,this.endBeat=i}get duration(){return this.endBeat-this.startBeat}}class dl{constructor(e,t=null){this._mascot=e,this._rhythm=t,this._events=[],this._sections=new Map,this._isPlaying=!1,this._startTime=0,this._pauseOffset=0,this._timers=[],this._loopState=null,this._onBeatCallbacks=[],this._onSectionCallbacks=[],this._rafId=null}at(e,t,i,s=null){return this._events.push({time:e,beat:null,bar:null,action:t,value:i,options:s}),this}atBeat(e,t,i,s=null){const n=this._beatsToMs(e);return this._events.push({time:n,beat:e,bar:null,action:t,value:i,options:s}),this}atBar(e,t,i,s=null){const n=this._beatsToMs(4*e);return this._events.push({time:n,beat:4*e,bar:e,action:t,value:i,options:s}),this}section(e,t,i){return this._sections.set(e,new ul(e,t,i)),this}play(e=0){this.stop(),this._isPlaying=!0,this._pauseOffset=e,this._startTime=performance.now()-e,this._scheduleEvents(e),this._startBeatLoop()}playSection(e){const t=this._sections.get(e);if(!t)return;this._fireSectionCallbacks(e,"enter");const i=this._beatsToMs(t.startBeat),s=this._beatsToMs(t.endBeat);this.play(i);const n=s-i;this._timers.push(setTimeout(()=>{this._fireSectionCallbacks(e,"exit"),this._loopState||this.stop()},n))}loop(e,t=1){this._sections.get(e)&&(this._loopState={section:e,remaining:t},this._playLoopIteration())}_playLoopIteration(){if(!this._loopState||this._loopState.remaining<=0)return void(this._loopState=null);this._loopState.remaining--;const e=this._sections.get(this._loopState.section),t=this._beatsToMs(e.startBeat),i=this._beatsToMs(e.endBeat),s=i-t;this.stop(),this._isPlaying=!0,this._startTime=performance.now()-t,this._scheduleEvents(t,i),this._startBeatLoop(),this._timers.push(setTimeout(()=>{this._playLoopIteration()},s))}pause(){this._isPlaying&&(this._pauseOffset=performance.now()-this._startTime,this._clearTimers(),this._isPlaying=!1)}resume(){this._isPlaying||this.play(this._pauseOffset)}stop(){this._clearTimers(),this._isPlaying=!1,this._loopState=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onBeat(e,t){const i={every:e,callback:t,lastBeat:-1};return this._onBeatCallbacks.push(i),()=>{this._onBeatCallbacks=this._onBeatCallbacks.filter(e=>e!==i)}}onSection(e,t,i){const s={section:e,event:t,callback:i};return this._onSectionCallbacks.push(s),()=>{this._onSectionCallbacks=this._onSectionCallbacks.filter(e=>e!==s)}}loadFromRecording(e){this._events=[];for(const t of e){const e="shape"===t.type?"morph":t.type;this.at(t.time,e,t.name,t.config||null)}}getElapsed(){return this._isPlaying?performance.now()-this._startTime:this._pauseOffset}getCurrentBeat(){return this.getElapsed()/this._getBeatDurationMs()}_scheduleEvents(e,t=1/0){const i=[...this._events].sort((e,t)=>e.time-t.time);for(const s of i){if(s.time<e||s.time>=t)continue;const i=s.time-e;this._timers.push(setTimeout(()=>{this._isPlaying&&this._executeEvent(s)},Math.max(0,i)))}}_executeEvent(e){switch(e.action){case"emotion":this._mascot.setEmotion&&this._mascot.setEmotion(e.value,e.options||void 0);break;case"gesture":this._mascot.express?this._mascot.express(e.value):this._mascot.triggerGesture&&this._mascot.triggerGesture(e.value);break;case"morph":this._mascot.morphTo&&this._mascot.morphTo(e.value,e.options||void 0);break;case"audioLayer":break;case"nudge":this._mascot.nudgeEmotion&&e.value&&this._mascot.nudgeEmotion(e.value.emotion,e.value.delta);break;case"callback":"function"==typeof e.value&&e.value()}}_startBeatLoop(){const e=this._getBeatDurationMs(),t=()=>{if(!this._isPlaying)return;const i=this.getElapsed(),s=Math.floor(i/e);for(const e of this._onBeatCallbacks)s>e.lastBeat&&s%e.every===0&&(e.lastBeat=s,e.callback(s));this._rafId=requestAnimationFrame(t)};this._rafId=requestAnimationFrame(t)}_fireSectionCallbacks(e,t){for(const i of this._onSectionCallbacks)i.section===e&&i.event===t&&i.callback()}_clearTimers(){for(const e of this._timers)clearTimeout(e);this._timers=[]}_beatsToMs(e){return e*this._getBeatDurationMs()}_getBeatDurationMs(){if(this._rhythm){const e=this._rhythm.getAdapter?.();if(e){const t=e.getTimeInfo();if(t?.beatDuration)return t.beatDuration}}return 500}destroy(){this.stop(),this._events=[],this._sections.clear(),this._onBeatCallbacks=[],this._onSectionCallbacks=[]}}class gl{constructor(e,t,i={},s="error"){this.success=!1,this.error={type:e,message:t,context:i,severity:s,timestamp:Date.now(),recoveryActions:this.generateRecoveryActions(e,i)}}static success(e=null){return{success:!0,data:e,timestamp:Date.now()}}static failure(e,t,i={},s="error"){return new gl(e,t,i,s)}static warning(e,t,i={}){return new gl(e,t,i,"warning")}generateRecoveryActions(e,t){const i="https://github.com/joshtol/emotive-engine/blob/main/docs";return{INVALID_EMOTION:["Check if emotion is one of: joy, sadness, anger, fear, surprise, disgust, contempt, neutral","Use mascot.getAvailableEmotions() to see valid options",`Docs: ${i}/QUICK_REFERENCE.md#emotions`],INVALID_GESTURE:["Verify gesture name matches available gestures","Use mascot.getAvailableGestures() to see valid options",`Docs: ${i}/QUICK_REFERENCE.md#gestures`],CANVAS_CONTEXT_LOST:["Canvas context will attempt automatic recovery","Reduce canvas size if problem persists","Check for memory pressure or GPU issues",`Docs: ${i}/TROUBLESHOOTING.md#canvas-issues`],AUDIO_CONTEXT_FAILED:["Audio features will be disabled, visual features continue","Check browser audio permissions","Ensure user interaction occurred before audio initialization",`Docs: ${i}/TROUBLESHOOTING.md#audio-issues`],PERFORMANCE_DEGRADED:["Particle count has been automatically reduced","Consider reducing canvas size or complexity","Monitor performance metrics for recovery",`Docs: ${i}/PERFORMANCE.md`],MEMORY_LIMIT_EXCEEDED:["System has automatically reduced resource usage","Consider destroying unused mascot instances","Monitor memory usage patterns",`Docs: ${i}/PERFORMANCE.md#memory-management`],VALIDATION_ERROR:["Check parameter types and ranges","Refer to API documentation for valid values","Use default values if unsure",`Docs: ${i}/QUICK_REFERENCE.md`],INITIALIZATION_ERROR:["Ensure canvas element exists and is accessible","Check browser compatibility","Verify all required dependencies are loaded",`Docs: ${i}/TROUBLESHOOTING.md#initialization`],RESOURCE_LOAD_FAILED:["Check network connectivity","Verify resource URLs are correct",`Docs: ${i}/TROUBLESHOOTING.md#resource-loading`],FEATURE_NOT_SUPPORTED:["Check browser compatibility requirements","Consider using fallback features",`Docs: ${i}/TROUBLESHOOTING.md#browser-compatibility`]}[e]||["Check console for additional error details",`Docs: ${i}/TROUBLESHOOTING.md`,"Report issues: https://github.com/joshtol/emotive-engine/issues"]}log(){"warn"==("warning"===this.error.severity?"warn":"error")?console.warn(`[EmotiveMascot] ${this.error.type}: ${this.error.message}`,{context:this.error.context,recoveryActions:this.error.recoveryActions,timestamp:new Date(this.error.timestamp).toISOString()}):console.error(`[EmotiveMascot] ${this.error.type}: ${this.error.message}`,{context:this.error.context,recoveryActions:this.error.recoveryActions,timestamp:new Date(this.error.timestamp).toISOString()})}getDisplayMessage(){return`${this.error.type}: ${this.error.message}`}isRecoverable(){return this.error.recoveryActions&&this.error.recoveryActions.length>0}getSeverity(){return this.error.severity}toJSON(){return{success:this.success,error:this.error}}}const ml="INVALID_PARAMETER",pl="PERFORMANCE_DEGRADED",fl="FEATURE_NOT_SUPPORTED",yl="critical",bl="error",vl="warning",Ml="info";class wl{constructor(e={}){this.config={enableConsoleLogging:!1!==e.enableConsoleLogging,enableContextPreservation:!1!==e.enableContextPreservation,maxLogEntries:e.maxLogEntries||1e3,logLevel:e.logLevel||vl,...e},this.logs=[],this.errorCounts=new Map,this.contextHistory=new Map,this.startTime=Date.now()}logError(e,t={}){const i=this.createLogEntry(e,t);return this.storeLogEntry(i),this.updateErrorCounts(e.error.type),this.config.enableConsoleLogging&&this.shouldLog(e.error.severity)&&this.consoleLog(i),this.config.enableContextPreservation&&this.preserveContext(e.error.type,i),i}createLogEntry(e,t){return{id:this.generateLogId(),timestamp:Date.now(),relativeTime:Date.now()-this.startTime,type:e.error.type,message:e.error.message,severity:e.error.severity,context:{...e.error.context,...t,stackTrace:this.captureStackTrace(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",url:"undefined"!=typeof window?window.location.href:"unknown"},recoveryActions:e.error.recoveryActions,errorCount:this.getErrorCount(e.error.type)+1}}storeLogEntry(e){this.logs.push(e),this.logs.length>this.config.maxLogEntries&&this.logs.shift()}updateErrorCounts(e){const t=this.errorCounts.get(e)||0;this.errorCounts.set(e,t+1)}preserveContext(e,t){this.contextHistory.has(e)||this.contextHistory.set(e,[]);const i=this.contextHistory.get(e);i.push({timestamp:t.timestamp,context:t.context,message:t.message}),i.length>10&&i.shift()}consoleLog(e){const t=this.getConsoleMethod(e.severity),i=new Date(e.timestamp).toISOString();"warn"===t?console.warn(`[EmotiveMascot] ${i} ${e.type}: ${e.message}`,{severity:e.severity,context:e.context,recoveryActions:e.recoveryActions,errorCount:e.errorCount}):console.error(`[EmotiveMascot] ${i} ${e.type}: ${e.message}`,{severity:e.severity,context:e.context,recoveryActions:e.recoveryActions,errorCount:e.errorCount})}getConsoleMethod(e){switch(e){case yl:case bl:return"error";default:return"warn"}}shouldLog(e){const t={[yl]:4,[bl]:3,[vl]:2,[Ml]:1};return t[e]>=t[this.config.logLevel]}captureStackTrace(){try{throw new Error}catch(e){return e.stack||"Stack trace not available"}}generateLogId(){return`log_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getErrorCount(e){return this.errorCounts.get(e)||0}getLogs(e={}){let t=[...this.logs];return e.type&&(t=t.filter(t=>t.type===e.type)),e.severity&&(t=t.filter(t=>t.severity===e.severity)),e.since&&(t=t.filter(t=>t.timestamp>=e.since)),e.limit&&(t=t.slice(-e.limit)),t}getErrorStatistics(){const e={totalErrors:this.logs.length,errorsByType:Object.fromEntries(this.errorCounts),errorsBySeverity:{},recentErrors:this.logs.slice(-10),uptime:Date.now()-this.startTime};return this.logs.forEach(t=>{e.errorsBySeverity[t.severity]=(e.errorsBySeverity[t.severity]||0)+1}),e}clearLogs(){this.logs=[],this.errorCounts.clear(),this.contextHistory.clear()}exportLogs(e="json"){if("json"===e)return JSON.stringify({logs:this.logs,statistics:this.getErrorStatistics(),exportTime:Date.now()},null,2);if("csv"===e)return[["timestamp","type","severity","message","errorCount"],...this.logs.map(e=>[new Date(e.timestamp).toISOString(),e.type,e.severity,e.message.replace(/"/g,'""'),e.errorCount])].map(e=>e.map(e=>`"${e}"`).join(",")).join("\n");throw new Error(`Unsupported export format: ${e}`)}}let Sl=null;function xl(e={}){return Sl||(Sl=new wl(e)),Sl}function Cl(){Sl=null}class kl{constructor(e={}){this.config={enableAutoOptimization:e.enableAutoOptimization||!1,performanceThreshold:e.performanceThreshold??e.criticalFPS??30,memoryThreshold:e.memoryThreshold||50,degradationSteps:e.degradationSteps||4,recoveryDelay:e.recoveryDelay||1e3,enableManualControls:!1!==e.enableManualControls,enableProgressiveEnhancement:!1!==e.enableProgressiveEnhancement,warningFPS:e.warningFPS||50,criticalFPS:e.criticalFPS??e.performanceThreshold??30,requiredGoodFrames:e.requiredGoodFrames||30,...e},this.errorLogger=xl(),this.degradationLevels=[{name:"optimal",particleLimit:50,audioEnabled:!0,fullEffects:!0,targetFPS:60,qualityLevel:1,canvasScale:1,animationComplexity:1,description:"Full features and effects",features:["particles","audio","fullEffects","animations","highQuality"]},{name:"reduced",particleLimit:25,audioEnabled:!0,fullEffects:!1,targetFPS:45,qualityLevel:.8,canvasScale:.9,animationComplexity:.8,description:"Reduced visual effects",features:["particles","audio","animations","mediumQuality"]},{name:"minimal",particleLimit:10,audioEnabled:!1,fullEffects:!1,targetFPS:30,qualityLevel:.6,canvasScale:.8,animationComplexity:.6,description:"Minimal visual effects, no audio",features:["particles","animations","lowQuality"]},{name:"emergency",particleLimit:5,audioEnabled:!1,fullEffects:!1,targetFPS:15,qualityLevel:.4,canvasScale:.7,animationComplexity:.4,description:"Emergency mode - basic animation only",features:["animations","particles"]}],this.currentLevel=0,this.lastDegradationTime=0,this.performanceHistory=[],this.maxHistorySize=30,this.availableFeatures=this.assessAvailableFeatures(),this.isMonitoring=!1,this.monitoringInterval=null,this.recoveryTimeout=null,this.consecutiveGoodFrames=0,this.requiredGoodFrames=this.config.requiredGoodFrames,this.manualOverride=null,this.disabledFeatures=new Set,this.enhancementHistory=[],this.capabilityTests=new Map}assessAvailableFeatures(){const e=ir.featureDetection.getFeatures(),{capabilities:t}=ir;return{audio:e.webAudio&&e.audioContext,particles:e.canvas2d,animations:e.requestAnimationFrame,performance:e.performance,fullQuality:"full"===t.level,reducedMotion:this.detectReducedMotion(),highContrast:this.detectHighContrast()}}detectReducedMotion(){try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}}detectHighContrast(){try{return window.matchMedia("(prefers-contrast: high)").matches}catch{return!1}}startMonitoring(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>{this.checkPerformance()},1e3))}stopMonitoring(){this.isMonitoring&&(this.isMonitoring=!1,this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null))}checkPerformance(e={}){if(!this.config.enableAutoOptimization)return;const t=e.fps||60,i=e.memoryUsage||0;this.performanceHistory.push({fps:t,memoryUsage:i,timestamp:Date.now()}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift();const s=this.performanceHistory.reduce((e,t)=>e+t.fps,0)/this.performanceHistory.length,n=this.performanceHistory.reduce((e,t)=>e+t.memoryUsage,0)/this.performanceHistory.length,a=s<this.config.performanceThreshold||n>this.config.memoryThreshold;a&&this.canDegrade()?this.applyDegradation():!a&&s>1.1*this.config.performanceThreshold?(this.consecutiveGoodFrames++,this.consecutiveGoodFrames>=this.requiredGoodFrames&&this.canRecover()&&this.scheduleRecovery()):this.consecutiveGoodFrames=0}canDegrade(){const e=Date.now()-this.lastDegradationTime;return this.currentLevel<this.degradationLevels.length-1&&e>2e3}canRecover(){return this.currentLevel>0}applyDegradation(){if(!this.canDegrade())return;this.currentLevel++,this.lastDegradationTime=Date.now(),this.consecutiveGoodFrames=0;const e=this.getCurrentLevel();this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null),this.emit("degradationApplied",{level:e.name,index:this.currentLevel,reason:"performance",settings:e})}scheduleRecovery(){this.recoveryTimeout||(this.recoveryTimeout=setTimeout(()=>{this.applyRecovery(),this.recoveryTimeout=null},this.config.recoveryDelay))}applyRecovery(){if(!this.canRecover())return;this.currentLevel--,this.consecutiveGoodFrames=0;const e=this.getCurrentLevel();this.emit("recoveryApplied",{level:e.name,index:this.currentLevel,settings:e})}setLevel(e){let t;if("string"==typeof e){if(t=this.degradationLevels.findIndex(t=>t.name===e),-1===t)return!1}else{if("number"!=typeof e)return!1;t=Math.max(0,Math.min(this.degradationLevels.length-1,e))}const i=this.currentLevel;this.currentLevel=t;const s=this.getCurrentLevel();return this.emit("levelChanged",{previousLevel:this.degradationLevels[i].name,currentLevel:s.name,index:this.currentLevel,manual:!0,settings:s}),!0}getCurrentLevel(){return{...this.degradationLevels[this.currentLevel]}}getAllLevels(){return this.degradationLevels.map(e=>({...e}))}getAvailableFeatures(){return{...this.availableFeatures}}isFeatureAvailable(e){if(this.disabledFeatures.has(e))return!1;const t=this.getCurrentLevel();switch(e){case"audio":return this.availableFeatures.audio&&t.audioEnabled;case"particles":return this.availableFeatures.particles&&t.particleLimit>0;case"fullEffects":return this.availableFeatures.fullQuality&&t.fullEffects;case"animations":return this.availableFeatures.animations;default:return this.availableFeatures[e]||!1}}getRecommendedSettings(){const e=this.getCurrentLevel(),t=ir.browserOptimizations.getOptimizations();return{maxParticles:Math.min(e.particleLimit,t.particleLimit),enableAudio:e.audioEnabled&&this.availableFeatures.audio,enableFullEffects:e.fullEffects&&this.availableFeatures.fullQuality,targetFPS:e.targetFPS,qualityLevel:e.qualityLevel,reducedMotion:this.availableFeatures.reducedMotion,highContrast:this.availableFeatures.highContrast}}getPerformanceStats(){if(0===this.performanceHistory.length)return{avgFPS:0,avgMemory:0,samples:0,currentLevel:this.getCurrentLevel().name};const e=this.performanceHistory.reduce((e,t)=>e+t.fps,0)/this.performanceHistory.length,t=this.performanceHistory.reduce((e,t)=>e+t.memoryUsage,0)/this.performanceHistory.length,i=Math.min(...this.performanceHistory.map(e=>e.fps)),s=Math.max(...this.performanceHistory.map(e=>e.fps));return{avgFPS:Math.round(10*e)/10,avgMemory:Math.round(10*t)/10,minFPS:i,maxFPS:s,samples:this.performanceHistory.length,currentLevel:this.getCurrentLevel().name,consecutiveGoodFrames:this.consecutiveGoodFrames,isMonitoring:this.isMonitoring}}reset(){this.currentLevel=0,this.performanceHistory=[],this.consecutiveGoodFrames=0,this.lastDegradationTime=0,this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null),this.emit("reset",{level:this.getCurrentLevel().name})}emit(e,t){this.onEvent&&this.onEvent(e,t)}setEventCallback(e){this.onEvent=e}disableFeature(e){if(!this.config.enableManualControls)return gl.failure(fl,"Manual controls are disabled",{feature:e,enableManualControls:this.config.enableManualControls});const t=["particles","audio","fullEffects","animations"];return t.includes(e)?(this.disabledFeatures.add(e),this.errorLogger.logError(gl.warning(fl,`Feature manually disabled: ${e}`,{feature:e,disabledFeatures:Array.from(this.disabledFeatures)})),this.emit("featureDisabled",{feature:e,manual:!0}),gl.success({feature:e,disabled:!0})):gl.failure(ml,`Invalid feature: ${e}`,{feature:e,validFeatures:t})}enableFeature(e){return this.config.enableManualControls?this.availableFeatures[e]?(this.disabledFeatures.delete(e),this.emit("featureEnabled",{feature:e,manual:!0}),gl.success({feature:e,enabled:!0})):gl.failure(fl,`Feature not available in browser: ${e}`,{feature:e,availableFeatures:this.availableFeatures}):gl.failure(fl,"Manual controls are disabled",{feature:e,enableManualControls:this.config.enableManualControls})}setManualOverride(e){return this.config.enableManualControls?null===e?(this.manualOverride=null,this.emit("manualOverrideRemoved",{}),gl.success({override:null})):this.setLevel(e)?(this.manualOverride=this.currentLevel,this.emit("manualOverrideSet",{level:this.getCurrentLevel().name}),gl.success({override:this.getCurrentLevel().name})):gl.failure(ml,"Failed to set manual override",{level:e}):gl.failure(fl,"Manual controls are disabled")}testCapability(e,t){if(!this.config.enableProgressiveEnhancement)return gl.failure(fl,"Progressive enhancement is disabled");try{const i=performance.now(),s=t(),n=performance.now()-i,a={feature:e,supported:Boolean(s),duration:n,timestamp:Date.now()};return this.capabilityTests.set(e,a),gl.success(a)}catch(t){const i={feature:e,supported:!1,error:t.message,timestamp:Date.now()};return this.capabilityTests.set(e,i),this.errorLogger.logError(gl.failure(fl,`Capability test failed: ${e}`,{error:t.message,feature:e})),gl.failure(fl,`Capability test failed: ${t.message}`,i)}}getCapabilityTests(){return Object.fromEntries(this.capabilityTests)}applyProgressiveEnhancement(){if(!this.config.enableProgressiveEnhancement)return gl.failure(fl,"Progressive enhancement is disabled");const e=[],t=this.getCurrentLevel();if(this.availableFeatures.audio&&t.audioEnabled){const t=this.capabilityTests.get("advancedAudio");t&&t.supported&&e.push("advancedAudio")}if(this.availableFeatures.particles&&t.particleLimit>0){const t=this.capabilityTests.get("advancedParticles");t&&t.supported&&e.push("advancedParticles")}if(this.availableFeatures.animations){const t=this.capabilityTests.get("advancedAnimations");t&&t.supported&&e.push("advancedAnimations")}return this.enhancementHistory.push({timestamp:Date.now(),level:t.name,enhancements:[...e]}),this.emit("progressiveEnhancementApplied",{enhancements:e}),gl.success({enhancements:e})}getFeatureAvailabilityReport(){const e=this.getCurrentLevel(),t={currentLevel:e.name,availableFeatures:{},disabledFeatures:Array.from(this.disabledFeatures),manualOverride:this.manualOverride,browserCapabilities:this.availableFeatures,capabilityTests:this.getCapabilityTests(),recommendations:[]};for(const i of["particles","audio","fullEffects","animations"]){const s=this.isFeatureAvailable(i),n=this.availableFeatures[i],a=e.features.includes(i),r=this.disabledFeatures.has(i);t.availableFeatures[i]={available:s,browserSupported:n,levelSupported:a,manuallyDisabled:r,reason:s?null:this.getFeatureUnavailableReason(i)},s||!n||r||a||t.recommendations.push(`${i} disabled due to performance level - consider improving performance`)}return t}getFeatureUnavailableReason(e){if(!this.availableFeatures[e])return"Browser does not support this feature";if(this.disabledFeatures.has(e))return"Feature manually disabled";const t=this.getCurrentLevel();return t.features.includes(e)?"Unknown reason":`Feature disabled at ${t.name} performance level`}checkPerformanceEnhanced(e={}){try{return null!==this.manualOverride?gl.success({message:"Performance check skipped - manual override active",manualOverride:this.getCurrentLevel().name}):(this.checkPerformance(e),gl.success({message:"Performance check completed",currentLevel:this.getCurrentLevel().name,metrics:this.getPerformanceStats()}))}catch(t){return this.errorLogger.logError(gl.failure(pl,"Performance check failed",{error:t.message,metrics:e})),gl.failure(pl,"Performance check failed",{error:t.message})}}getDegradationStatus(){return{currentLevel:this.getCurrentLevel(),availableFeatures:this.getAvailableFeatures(),featureReport:this.getFeatureAvailabilityReport(),performanceStats:this.getPerformanceStats(),config:{enableAutoOptimization:this.config.enableAutoOptimization,enableManualControls:this.config.enableManualControls,enableProgressiveEnhancement:this.config.enableProgressiveEnhancement,performanceThreshold:this.config.performanceThreshold,memoryThreshold:this.config.memoryThreshold},history:{performance:this.performanceHistory.slice(-10),enhancements:this.enhancementHistory.slice(-5)}}}destroy(){this.stopMonitoring(),this.performanceHistory=[],this.enhancementHistory=[],this.capabilityTests.clear(),this.disabledFeatures.clear(),this.onEvent=null,this.manualOverride=null}}class Pl{constructor(e={}){const{mascot:t=null,onError:i}=e;this.mascot=t,this._onError=i??(e=>{"production"!==process.env.NODE_ENV&&console.error("SiteController error:",e)})}updateMascot(e){return this.mascot=e,this}get positionController(){return this.mascot?.positionController??null}getElementTargeting(){return this.positionController?.getElementTargeting?.()??null}moveToElement(e,t={}){return this.moveToElementWithPath(e,[],"center",t.offset??{x:0,y:0},t)}moveToElementWithPath(e,t=[],i="center",s={x:0,y:0},n={}){const a=this.positionController;if(!a)return;const r=a.getElementTargeting?.(),o=n.speed??320,l=n.easing??"easeInOutCubic",h=n.coordinateSystem??"viewport";if(r?.moveToElementWithPath)try{return r.moveToElementWithPath(e,t,i,s,{coordinateSystem:h,speed:o,easing:l})}catch(e){this._handleError(e)}a.setOffset&&a.setOffset(s.x,s.y,0)}setOffset(e,t,i=0){try{this.positionController?.setOffset?.(e,t,i)}catch(e){this._handleError(e)}}getOffset(){try{return this.positionController?.getOffset?.()??{x:0,y:0}}catch(e){return this._handleError(e),{x:0,y:0}}}setEmotion(e){try{this.mascot?.setEmotion?.(e)}catch(e){this._handleError(e)}}express(e,t={}){try{if(t.chain&&this.mascot?.chain)return void this.mascot.chain(e);this.mascot?.express?.(e)}catch(e){this._handleError(e)}}stop(){try{const e=this.positionController;e?.stopCurrentPath?.(),e?.stop?.(),this.mascot?.pause?.()}catch(e){this._handleError(e)}}play(){try{this.mascot?.play?.()}catch(e){this._handleError(e)}}destroy(){this.stop(),this.mascot=null}_handleError(e){e instanceof Error?this._onError(e):this._onError(new Error(String(e)))}}const Tl="3.4.0",El="Emotive Engine",Al={rhythmSync:!0,grooveTemplates:!0,gestureBlending:!0,audioReactive:!0,particleSystem:!0,accessibility:!0,mobileOptimization:!0,performanceMonitoring:!0};var Dl=Object.freeze({__proto__:null,AnimationController:Ga,AnimationLoopManager:ha,AnimationPriority:la,CanvasManager:Ps,ContextStateManager:Jo,EmotiveRenderer:ya,EmotiveStateMachine:Zs,ErrorTracker:so,EventManager:ws,GradientCache:Dn,PerformanceMonitor:Ko,StateStore:No,animationLoopManager:ca,engineState:Qo,errorTracker:no,eventManager:Ss,gradientCache:_n,performanceMonitor:Zo}),_l=Object.freeze({__proto__:null,AudioAnalyzer:mr,AudioLevelProcessor:Ha,IdleBehavior:va,ParticleSystem:cn,SoundSystem:La}),Il=Object.freeze({__proto__:null,EMOTIONAL_COLORS:Os,EMOTIONAL_COLORS_RGB:Ls,UNDERTONE_SATURATION:Bs,adjustBrightness:function(e,t){const i=Ts(e),s=As(i.r,i.g,i.b);s.l=Math.max(0,Math.min(100,s.l*t));const n=Ds(s.h,s.s,s.l);return Es(n.r,n.g,n.b)},adjustSaturation:Is,applyUndertoneSaturation:zs,applyUndertoneSaturationToArray:Fs,getContrastRatio:function(e,t){const i=Rs(e),s=Rs(t);return(Math.max(i,s)+.05)/(Math.min(i,s)+.05)},getLuminance:Rs,getUndertoneSaturationFactor:function(e){return e&&Bs[e.toLowerCase()]||1},hexToRgb:Ts,hexToRgba:function(e,t=1){const i=Ts(e);return`rgba(${i.r}, ${i.g}, ${i.b}, ${t})`},hslToRgb:Ds,interpolateHsl:_s,interpolateRgb:function(e,t,i){const s=Ts(e),n=Ts(t);return Es(Math.round(s.r+(n.r-s.r)*i),Math.round(s.g+(n.g-s.g)*i),Math.round(s.b+(n.b-s.b)*i))},rgbToHex:Es,rgbToHsl:As});export{ja as AccessibilityManager,Ga as AnimationController,ha as AnimationLoopManager,la as AnimationPriority,mr as AudioAnalyzer,Oa as AudioLayerManager,Ha as AudioLevelProcessor,Ps as CanvasManager,Jo as ContextStateManager,kl as DegradationManager,El as ENGINE_NAME,Tr as EmotionDynamics,bo as EmotiveMascot,Xo as EmotiveMascotPublic,ya as EmotiveRenderer,Zs as EmotiveStateMachine,e as ErrorBoundary,wl as ErrorLogger,so as ErrorTracker,ws as EventManager,Al as FEATURES,ol as FeatureFlags,vi as GESTURE_REGISTRY,ki as GESTURE_TYPES,ba as GazeTracker,Dn as GradientCache,vr as GrooveTemplates,ao as HealthCheck,va as IdleBehavior,el as LazyLoader,$a as MobileOptimization,cn as ParticleSystem,Ko as PerformanceMonitor,nn as RhythmInputEvaluator,Pl as SiteController,La as SoundSystem,No as StateStore,dl as Timeline,ul as TimelineSection,mn as UNDERTONE_MODIFIERS,Tl as VERSION,ca as animationLoopManager,Ii as applyGesture,ir as browserCompatibility,Xo as default,i as emotionPluginAdapter,Qo as engineState,no as errorTracker,Ss as eventManager,ll as featureFlags,S as gesturePluginAdapter,b as getBlendedRhythmModifiers,tr as getBrowserCompatibility,l as getEmotion,f as getEmotionGestures,y as getEmotionRhythmModifiers,h as getEmotionVisualParams,xl as getErrorLogger,cl as getFeatureVariant,Ai as getGesture,_n as gradientCache,g as hasEmotion,ro as healthCheck,Za as initializeBrowserCompatibility,Di as isBlendingGesture,hl as isFeatureEnabled,_i as isOverrideGesture,il as lazyLoad,tl as lazyLoader,u as listEmotions,Ri as listGestures,gs as particleBehaviorPluginAdapter,Zo as performanceMonitor,Xa as polyfillPerformanceNow,Ya as polyfillRequestAnimationFrame,Na as polyfillWebAudio,nl as prefetchModules,sl as preloadModules,Cl as resetErrorLogger};
|
|
1
|
+
class e{constructor(){this.errors=[],this.maxErrors=10,this.errorCounts=new Map,this.defaults={emotion:"neutral",gesture:null,audioLevel:0,particleCount:0,glowIntensity:.7,coreSize:1,breathRate:1,color:"#B0B0B0"}}wrap(e,t,i=null){return(...s)=>{try{const n=e(...s);return n&&"function"==typeof n.then?n.catch(e=>(this.logError(e,t),null!==i?i:this.getDefault(t))):n}catch(e){return this.logError(e,t),null!==i?i:this.getDefault(t)}}}logError(e,t){const i={timestamp:(new Date).toISOString(),context:t,message:e.message,stack:e.stack};this.errors.push(i);const s=this.errorCounts.get(t)||0;this.errorCounts.set(t,s+1),this.errors.length>this.maxErrors&&this.errors.shift(),s<3?console.warn(`[EmotiveEngine] ${t}:`,e.message):3===s&&console.warn(`[EmotiveEngine] ${t}: Error occurred 3+ times, suppressing further logs`)}getDefault(e){const t={"emotion-transition":this.defaults.emotion,"gesture-execution":this.defaults.gesture,"audio-processing":this.defaults.audioLevel,"particle-system":this.defaults.particleCount,rendering:{glowIntensity:this.defaults.glowIntensity,coreSize:this.defaults.coreSize,color:this.defaults.color},"canvas-operations":null,"state-management":this.defaults.emotion};return{}.hasOwnProperty.call(t,e)?t[e]:null}validateInput(e,t,i){try{switch(t){case"emotion":return["neutral","joy","sadness","anger","fear","surprise","disgust","love","euphoria"].includes(e)?e:i;case"undertone":return null===e||["nervous","confident","tired","intense","subdued"].includes(e)?e:null;case"gesture":return["bounce","pulse","shake","spin","nod","tilt","expand","contract","flash","drift"].includes(e)?e:i;case"number":return"number"!=typeof e||isNaN(e)?i:e;case"string":return"string"==typeof e?e:i;case"boolean":return"boolean"==typeof e?e:i;default:return null!=e?e:i}}catch(e){return this.logError(e,"input-validation"),i}}hasExceededThreshold(e,t=5){return(this.errorCounts.get(e)||0)>=t}getErrorStats(){return{totalErrors:this.errors.length,errorsByContext:Object.fromEntries(this.errorCounts),recentErrors:this.errors.slice(-5)}}clearErrors(){this.errors=[],this.errorCounts.clear()}async attemptRecovery(e,t,i=3){let s=0;for(;s<i;)try{return await t()}catch(t){if(s++,this.logError(t,`recovery-${e}-attempt-${s}`),s>=i)throw new Error(`Recovery failed for ${e} after ${i} attempts`);await new Promise(e=>setTimeout(e,100*Math.pow(2,s)))}}}const t=new Map;var i={registerPluginEmotion:function(e,i){return!!i.color&&(i.name||(i.name=e),i.visual||(i.visual={primaryColor:i.color,particleCount:i.particleCount||15,particleSize:i.particleSize||{min:2,max:6}}),i.modifiers||(i.modifiers={speed:1,amplitude:1,intensity:1}),t.set(e,i),!0)},unregisterPluginEmotion:function(e){return!!t.has(e)&&(t.delete(e),!0)},getPluginEmotion:function(e){return t.get(e)||null},getAllPluginEmotions:function(){return Array.from(t.keys())},clearPluginEmotions:function(){t.clear()},createLegacyAdapter:function(e){return{name:e.name||"unknown",emoji:e.emoji||"๐",color:e.primaryColor||e.color||"#7B68EE",energy:e.energy||"medium",visual:{primaryColor:e.primaryColor||e.color||"#7B68EE",secondaryColor:e.secondaryColor,particleCount:e.particleCount||e.particleRate||15,particleSize:e.particleSize||{min:2,max:6},glowIntensity:e.glowIntensity||.5,trailLength:e.trailLength||5,pulseRate:e.pulseRate||e.breathRate||1},particles:{behavior:e.particleBehavior||"ambient",density:e.particleDensity||"medium",speed:e.particleSpeed||"normal"},modifiers:{speed:e.speedMultiplier||1,amplitude:e.amplitudeMultiplier||1,intensity:e.intensityMultiplier||1,smoothness:e.smoothnessMultiplier||1},gestures:e.gestures||[],transitions:e.transitions||{}}}},s={name:"suspicion",emoji:"๐คจ",description:"Paranoid watchfulness with surveillance scanning",visual:{glowColor:"#6B46C1",particleRate:4,minParticles:6,maxParticles:12,particleBehavior:"surveillance",particleSpeed:.2,breathRate:.6,breathDepth:.04,coreJitter:.02,blinkRate:1.1,blinkSpeed:1,particleColors:[{color:"#6B46C1",weight:30},{color:"#4A5568",weight:25},{color:"#8B4789",weight:20},{color:"#9F7AEA",weight:15},{color:"#2D3748",weight:10}],threatLevel:0,getGlowIntensity(){return.3+.7*this.threatLevel},getParticleSpeed(){return.2+.8*this.threatLevel},getGlowColor(){const e=this.threatLevel||0,t=Math.round(107+113*e),i=Math.round(70+-32*e),s=Math.round(193+-66*e),n=e=>e.toString(16).padStart(2,"0");return`#${n(t)}${n(i)}${n(s)}`}},modifiers:{speed:.4,amplitude:.6,intensity:1.2,smoothness:.3,regularity:.2,focus:1.5,addWobble:!0},typicalGestures:["scan","twitch","peek","tilt","hold"],transitions:{duration:500,easing:"linear",priority:4},special:{coreSquint:.6,scanInterval:2e3,scanDuration:1200,scanAngle:60,twitchChance:.02,peekInterval:4e3,maxThreatDistance:300,alertThreshold:.7},"3d":{rotation:{type:"suspicious",speed:1,axes:[0,0,0],musicSync:!1},glow:{color:"#6B46C1",intensity:.85,pulse:{speed:.6,range:[.7,1]}},scale:{base:1,breathe:{enabled:!0,depth:.04,rate:.6}}},soulAnimation:{driftSpeed:.9,shimmerSpeed:1.8,turbulence:.4},rhythmModifiers:{windowMultiplier:.9,visualNoise:.3,inputDelay:0,tempoShift:0}},n={name:"calm",emoji:"๐",description:"Serene, peaceful state with gentle movements",visual:{glowColor:"#66D9CC",particleRate:6,minParticles:10,maxParticles:50,particleBehavior:"ascending",breathRate:.4,breathDepth:.12,coreJitter:!1,blinkRate:.8,blinkSpeed:1,particleColors:[{color:"#66D9CC",weight:35},{color:"#99E6D9",weight:25},{color:"#40BFB3",weight:20},{color:"#B3F2E6",weight:15},{color:"#339980",weight:5}]},modifiers:{speed:.5,amplitude:.3,intensity:.4,smoothness:2,regularity:1.5,addWeight:!1,floatHeight:.2,swayAmount:.15,duration:1.5},typicalGestures:["breathe","float","drift","idle"],transitions:{duration:800,easing:"easeInOutSine",priority:1},movement:{floatPattern:"sine_slow",floatPeriod:6e3,floatAmplitude:8,swayPattern:"gentle",swayPeriod:8e3,swayAmplitude:5,microMovements:!1},getCoreParams(e){const t=e.time||Date.now(),i=.5*Math.sin(6e-4*t)+.5;return{scaleX:1-.02*i,scaleY:1-.02*i,eyeOpenness:.85,eyeExpression:"serene",pupilOffset:{x:2*Math.sin(3e-4*t),y:1*Math.cos(4e-4*t)},glowPulse:.95+.05*i}},updateParticle(e,t){e.x+=.1*Math.sin(.001*e.life),e.y-=.02*t,e.opacity=.3*Math.sin(.002*e.life)+.2,e.size=e.baseSize*(1+.2*Math.sin(.001*e.life))},renderCore:(e,t,i,s)=>!1,"3d":{rotation:{type:"gentle",speed:.5,axes:[0,.3,0],musicSync:!0},glow:{color:"#66D9CC",intensity:.6,pulse:{speed:.4,range:[.5,.7]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.4}}},soulAnimation:{driftSpeed:.3,shimmerSpeed:.4,turbulence:.1},rhythmModifiers:{windowMultiplier:1.2,visualNoise:0,inputDelay:0,tempoShift:0}};const a=new Map,r={happy:"joy",peaceful:"calm",curious:"surprise",frustrated:"anger",sad:"sadness",excitement:"excited"};function o(e){e.name&&a.set(e.name,e)}function l(e){const t=r[e]||e,s=a.get(t);if(s)return s;return i.getPluginEmotion(t)||null}function h(e){const t=l(e);if(!t)return l("neutral").visual;if(!t.visual)return{};const{visual:i}=t,s={};for(const e in i)"function"!=typeof i[e]&&(s[e]=i[e]);return"function"==typeof i.getGlowIntensity&&(s.glowIntensity=i.getGlowIntensity()),"function"==typeof i.getParticleSpeed&&(s.particleSpeed=i.getParticleSpeed()),"function"==typeof i.getParticleRate&&(s.particleRate=i.getParticleRate()),"function"==typeof i.getGlowColor&&(s.glowColor=i.getGlowColor()),s}function c(e){const t=l(e);return t?t.modifiers:l("neutral").modifiers}function u(){return[...Array.from(a.keys()),...i.getAllPluginEmotions()]}function d(){const e={};return a.forEach((t,i)=>{e[i]=t}),e}function g(e){const t=r[e]||e;return a.has(t)||null!==i.getPluginEmotion(t)}function m(e,t){r[e]=t}function p(e,t){const i=l(e),s=l(t);return i&&s?s.transitions&&s.transitions[e]?s.transitions[e]:{duration:1e3,easing:"ease-in-out",gesture:s.transitions?.defaultGesture||null}:{duration:1e3,easing:"ease-in-out"}}function f(e){const t=l(e);return t?.gestures||[]}function y(e){const t=l(e);return t?.rhythmModifiers??{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}}function b(e){if(!e||0===e.length)return{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0};if(1===e.length){const t=y(e[0].emotion),i=e[0].intensity;return{windowMultiplier:1+(t.windowMultiplier-1)*i,visualNoise:t.visualNoise*i,inputDelay:t.inputDelay*i,tempoShift:t.tempoShift*i}}let t=0;for(let i=1;i<e.length;i++)e[i].intensity>e[t].intensity&&(t=i);const i={windowMultiplier:0,visualNoise:0,inputDelay:0,tempoShift:0},s=e.filter((e,i)=>i!==t),n=s.length>0?.25/s.length:0,a=y(e[t].emotion),r=e[t].intensity;i.windowMultiplier+=.75*(1+(a.windowMultiplier-1)*r),i.visualNoise+=a.visualNoise*r*.75,i.inputDelay+=a.inputDelay*r*.75,i.tempoShift+=a.tempoShift*r*.75;for(const e of s){const t=y(e.emotion),s=e.intensity;i.windowMultiplier+=(1+(t.windowMultiplier-1)*s)*n,i.visualNoise+=t.visualNoise*s*n,i.inputDelay+=t.inputDelay*s*n,i.tempoShift+=t.tempoShift*s*n}return i}[{name:"neutral",emoji:"๐",description:"Calm, balanced emotional state",visual:{glowColor:"#00BCD4",particleRate:2,minParticles:8,maxParticles:10,particleBehavior:"ambient",breathRate:1,breathDepth:.08,coreJitter:!1,blinkRate:1,blinkSpeed:1,particleColors:[{color:"#00BCD4",weight:25},{color:"#00ACC1",weight:20},{color:"#26C6DA",weight:15},{color:"#B2EBF2",weight:15},{color:"#0097A7",weight:10},{color:"#80DEEA",weight:10},{color:"#E0F7FA",weight:5}]},modifiers:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1},typicalGestures:["breathe","float","idle","blink"],transitions:{duration:500,easing:"easeInOut",priority:0},getCoreParams:e=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"neutral",pupilOffset:{x:0,y:0}}),renderCore:(e,t,i,s)=>!1,"3d":{rotation:{type:"gentle",speed:1,axes:[0,.3,0],musicSync:!1},glow:{color:"#00BCD4",intensity:.9,pulse:{speed:1,range:[.8,1]}},scale:{base:1,breathe:{enabled:!0,depth:.08,rate:1}}},soulAnimation:{driftSpeed:.5,shimmerSpeed:.5,turbulence:.2},rhythmModifiers:{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"joy",emoji:"๐",description:"Playful happiness and celebration",visual:{glowColor:"#FFEB3B",particleRate:8,minParticles:0,maxParticles:50,particleBehavior:"popcorn",breathRate:1.5,breathDepth:.1,coreJitter:!1,blinkRate:1.3,blinkSpeed:1.1,particleColors:[{color:"#FFEB3B",weight:25},{color:"#FFC107",weight:20},{color:"#FFFF00",weight:15},{color:"#FFD700",weight:15},{color:"#FFF59D",weight:10},{color:"#FF9800",weight:10},{color:"#FFFDE7",weight:5}]},modifiers:{speed:1.8,amplitude:1.9,intensity:1.1,smoothness:1,regularity:.9,addBounce:!0},typicalGestures:["bounce","spin","wave","expand","shake","float"],transitions:{duration:400,easing:"easeOutBack",priority:5,burstOnEntry:!0},getCoreParams:e=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"happy",pupilOffset:{x:0,y:-.1},sparkle:!0}),"3d":{rotation:{type:"rhythmic",speed:1.8,axes:[0,.3,0],musicSync:!0},glow:{color:"#FFEB3B",intensity:1.6,pulse:{speed:1.5,range:[1.2,1.8]}},scale:{base:1,breathe:{enabled:!0,depth:.1,rate:1.5}}},soulAnimation:{driftSpeed:1.2,shimmerSpeed:1.5,turbulence:.3},rhythmModifiers:{windowMultiplier:1.3,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"sadness",emoji:"๐ข",description:"Deep melancholic sorrow",visual:{glowColor:"#4169E1",particleRate:6,minParticles:0,maxParticles:50,particleBehavior:"falling",breathRate:.6,breathDepth:.12,coreJitter:!1,blinkRate:.6,blinkSpeed:.8,particleColors:[{color:"#4169E1",weight:25},{color:"#1E90FF",weight:20},{color:"#6495ED",weight:15},{color:"#B0C4DE",weight:15},{color:"#191970",weight:10},{color:"#87CEEB",weight:10},{color:"#2F4F4F",weight:5}]},modifiers:{speed:.7,amplitude:.6,intensity:.8,smoothness:1.3,regularity:1.1,addGravity:!0},typicalGestures:["droop","sway","contract","drift","sink"],transitions:{duration:800,easing:"easeInOut",priority:3},"3d":{rotation:{type:"gentle",speed:.7,axes:[0,.2,0],musicSync:!1},glow:{color:"#4169E1",intensity:.65,pulse:{speed:.6,range:[.5,.8]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.6}}},soulAnimation:{driftSpeed:.2,shimmerSpeed:.3,turbulence:.1},rhythmModifiers:{windowMultiplier:1,visualNoise:0,inputDelay:45,tempoShift:0}},{name:"anger",emoji:"๐ ",description:"Intense rage and aggression",visual:{glowColor:"#DC143C",particleRate:8,minParticles:8,maxParticles:50,particleBehavior:"aggressive",breathRate:2.2,breathDepth:.15,coreJitter:!0,blinkRate:1.6,blinkSpeed:1.3,particleColors:[{color:"#DC143C",weight:25},{color:"#FF0000",weight:20},{color:"#B22222",weight:15},{color:"#FF4500",weight:15},{color:"#8B0000",weight:10},{color:"#FF6347",weight:10},{color:"#660000",weight:5}]},modifiers:{speed:1.5,amplitude:1.4,intensity:1.3,smoothness:.3,regularity:.7,addShake:!0},typicalGestures:["shake","vibrate","expand","pulse","flicker","strike"],transitions:{duration:300,easing:"easeOutExpo",priority:8,shakeOnEntry:!0},special:{screenShake:!0,particleTrails:"fire",glowPulse:!0,temperatureEffect:"hot"},"3d":{rotation:{type:"unstable",speed:1.5,axes:[0,.3,0],shake:{amplitude:.02,frequency:7},eruption:{enabled:!0,interval:3e3,speedMultiplier:3.5,duration:400},musicSync:!1},glow:{color:"#DC143C",intensity:1.8,pulse:{speed:2.2,range:[.8,2]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:2.2}}},soulAnimation:{driftSpeed:2,shimmerSpeed:.8,turbulence:.8},rhythmModifiers:{windowMultiplier:.75,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"fear",emoji:"๐จ",description:"Anxious state with fleeing particles",visual:{glowColor:"#8A2BE2",particleRate:8,minParticles:8,maxParticles:50,particleBehavior:"scattering",breathRate:2.5,breathDepth:.06,coreJitter:!0,blinkRate:1.7,blinkSpeed:1.4,particleColors:[{color:"#8A2BE2",weight:25},{color:"#4B0082",weight:20},{color:"#9400D3",weight:15},{color:"#6B46C1",weight:15},{color:"#9932CC",weight:10},{color:"#E6E6FA",weight:8},{color:"#301934",weight:7}]},modifiers:{speed:1.4,amplitude:.8,intensity:1.2,smoothness:.5,regularity:.5,addJitter:!0},typicalGestures:["shake","vibrate","contract","flicker","retreat"],transitions:{duration:400,easing:"easeOut",priority:7},"3d":{rotation:{type:"unstable",speed:1.4,axes:[0,.3,0],shake:{amplitude:.015,frequency:3.5},musicSync:!1},glow:{color:"#8A2BE2",intensity:.9,pulse:{speed:2.5,range:[.6,1.2]}},scale:{base:1,breathe:{enabled:!0,depth:.06,rate:2.5}}},soulAnimation:{driftSpeed:1.8,shimmerSpeed:2.5,turbulence:.6},rhythmModifiers:{windowMultiplier:1,visualNoise:.6,inputDelay:0,tempoShift:0}},{name:"surprise",emoji:"๐ฒ",description:"Sudden shock with explosive particles",visual:{glowColor:"#FFD700",particleRate:5,minParticles:0,maxParticles:15,particleBehavior:"burst",breathRate:.3,breathDepth:.18,coreJitter:!1,blinkRate:1.4,blinkSpeed:1.2,particleColors:[{color:"#FFD700",weight:25},{color:"#FFA500",weight:20},{color:"#FFFF00",weight:15},{color:"#FF6347",weight:15},{color:"#FFE4B5",weight:10},{color:"#FF4500",weight:10},{color:"#FFFACD",weight:5}]},modifiers:{speed:1.6,amplitude:1.5,intensity:1.4,smoothness:.7,regularity:.8,addPop:!0},typicalGestures:["expand","bounce","flash","pulse","pop"],transitions:{duration:200,easing:"easeOutBack",priority:6},"3d":{rotation:{type:"unstable",speed:1.6,axes:[0,.45,0],shake:{amplitude:.01,frequency:3},musicSync:!1},glow:{color:"#FFD700",intensity:1.8,pulse:{speed:.3,range:[1,2.2]}},scale:{base:1,breathe:{enabled:!0,depth:.18,rate:.3}}},soulAnimation:{driftSpeed:1.5,shimmerSpeed:2,turbulence:.5},rhythmModifiers:{windowMultiplier:2,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"disgust",emoji:"๐คข",description:"Revulsion with repelling particles",visual:{glowColor:"#9ACD32",particleRate:4,minParticles:5,maxParticles:12,particleBehavior:"repelling",breathRate:.7,breathDepth:.04,coreJitter:!1,blinkRate:.9,blinkSpeed:.9,particleColors:[{color:"#9ACD32",weight:25},{color:"#ADFF2F",weight:20},{color:"#7FFF00",weight:15},{color:"#BDB76B",weight:15},{color:"#6B8E23",weight:10},{color:"#CCFF00",weight:8},{color:"#556B2F",weight:7}]},modifiers:{speed:.9,amplitude:.7,intensity:.9,smoothness:.8,regularity:1,addRecoil:!0},typicalGestures:["contract","shake","recoil","wobble"],transitions:{duration:600,easing:"easeIn",priority:4},"3d":{rotation:{type:"gentle",speed:.9,axes:[0,.25,0],musicSync:!1},glow:{color:"#9ACD32",intensity:1,pulse:{speed:.7,range:[.7,1.2]}},scale:{base:1,breathe:{enabled:!0,depth:.04,rate:.7}}},soulAnimation:{driftSpeed:.4,shimmerSpeed:.6,turbulence:.35},rhythmModifiers:{windowMultiplier:.85,visualNoise:.2,inputDelay:0,tempoShift:0}},{name:"love",emoji:"๐",description:"Warm affection with orbiting particles",visual:{glowColor:"#FF1493",particleRate:6,minParticles:15,maxParticles:50,particleBehavior:"orbiting",breathRate:.75,breathDepth:.15,coreJitter:!1,blinkRate:1.2,blinkSpeed:1,particleColors:[{color:"#FF1493",weight:30},{color:"#FF69B4",weight:25},{color:"#FF007F",weight:15},{color:"#FFB6C1",weight:10},{color:"#FF45A0",weight:10},{color:"#E91E63",weight:5},{color:"#FFC0CB",weight:5}]},modifiers:{speed:.9,amplitude:1.1,intensity:1.2,smoothness:1.4,regularity:1.2,addWarmth:!0},typicalGestures:["pulse","sway","orbit","glow","breathe","float"],transitions:{duration:700,easing:"easeInOut",priority:5},"3d":{rotation:{type:"gentle",speed:.9,axes:[0,.28,0],musicSync:!0},glow:{color:"#FF1493",intensity:1.8,pulse:{speed:.75,range:[1.3,2]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:.75}}},soulAnimation:{driftSpeed:.8,shimmerSpeed:1.2,turbulence:.2},rhythmModifiers:{windowMultiplier:1.15,visualNoise:0,inputDelay:0,tempoShift:0}},s,{name:"excited",emoji:"๐คฉ",description:"High energy with rapid particles",visual:{glowColor:"#FF6B35",particleRate:8,minParticles:10,maxParticles:50,particleBehavior:"burst",breathRate:2,breathDepth:.14,coreJitter:!0,blinkRate:1.5,blinkSpeed:1.2,particleColors:[{color:"#FF6B35",weight:25},{color:"#FF1744",weight:20},{color:"#FFC107",weight:15},{color:"#FF9100",weight:15},{color:"#FFEB3B",weight:10},{color:"#FF5722",weight:10},{color:"#FFF59D",weight:5}]},modifiers:{speed:1.4,amplitude:1.3,intensity:1.3,smoothness:.8,regularity:.7,addVibration:!0},typicalGestures:["bounce","spin","vibrate","expand","shake","pulse"],transitions:{duration:300,easing:"easeOutElastic",priority:6},"3d":{rotation:{type:"unstable",speed:1.4,axes:[0,.4,0],shake:{amplitude:.01,frequency:4},musicSync:!1},glow:{color:"#FF6B35",intensity:1.5,pulse:{speed:2,range:[1,1.8]}},scale:{base:1,breathe:{enabled:!0,depth:.14,rate:2}}},soulAnimation:{driftSpeed:1.5,shimmerSpeed:2,turbulence:.5},rhythmModifiers:{windowMultiplier:1.2,visualNoise:.1,inputDelay:0,tempoShift:0}},{name:"resting",emoji:"๐ด",description:"Deep relaxation with slow drift",visual:{glowColor:"#9370DB",particleRate:1,minParticles:3,maxParticles:5,particleBehavior:"resting",breathRate:.8,breathDepth:.12,coreJitter:!1,blinkRate:.4,blinkSpeed:.7,particleColors:[{color:"#9370DB",weight:30},{color:"#A591C4",weight:20},{color:"#B366FF",weight:20},{color:"#B8A1E6",weight:15},{color:"#674D9B",weight:15}]},modifiers:{speed:.5,amplitude:.4,intensity:.5,smoothness:1.4,regularity:.9,addWeight:!0},typicalGestures:["breathe","drift","sway","float"],transitions:{duration:1e3,easing:"easeInOut",priority:2},"3d":{rotation:{type:"gentle",speed:.5,axes:[0,.15,0],musicSync:!1},glow:{color:"#9370DB",intensity:.8,pulse:{speed:.8,range:[.6,1]}},scale:{base:1,breathe:{enabled:!0,depth:.12,rate:.8}}},soulAnimation:{driftSpeed:.15,shimmerSpeed:.1,turbulence:.05},rhythmModifiers:{windowMultiplier:1.1,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"euphoria",emoji:"๐",description:"Radiant hope and new beginnings",visual:{glowColor:"#FFB6C1",particleRate:6,minParticles:15,maxParticles:30,particleBehavior:"radiant",breathRate:1.3,breathDepth:.25,coreJitter:!1,blinkRate:1.4,blinkSpeed:1.1,particleColors:[{color:"#FFB6C1",weight:20},{color:"#FFD700",weight:18},{color:"#87CEEB",weight:15},{color:"#DDA0DD",weight:15},{color:"#98FB98",weight:12},{color:"#FFA07A",weight:10},{color:"#E6E6FA",weight:8},{color:"#FFFFFF",weight:2}]},modifiers:{speed:1.4,amplitude:1.5,intensity:1.6,smoothness:1.3,regularity:.8,addWarmth:!0,addLift:!0},typicalGestures:["expand","radiate","pulse","glow","float","bloom"],transitions:{duration:600,easing:"easeOutExpo",priority:8},"3d":{rotation:{type:"rhythmic",speed:1.4,axes:[0,.35,0],musicSync:!0},glow:{color:"#FFB6C1",intensity:1.2,pulse:{speed:1.3,range:[.9,1.5]}},scale:{base:1,breathe:{enabled:!0,depth:.25,rate:1.3}}},soulAnimation:{driftSpeed:1.8,shimmerSpeed:2.5,turbulence:.7},rhythmModifiers:{windowMultiplier:1.5,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"focused",emoji:"๐ฏ",description:"Intense concentration with directed flow",visual:{glowColor:"#00CED1",particleRate:4,minParticles:5,maxParticles:12,particleBehavior:"directed",breathRate:1.2,breathDepth:.08,coreJitter:!0,blinkRate:.7,blinkSpeed:1,particleColors:[{color:"#00CED1",weight:30},{color:"#4A9FA0",weight:20},{color:"#00FFFF",weight:20},{color:"#5FE5E7",weight:15},{color:"#006B6D",weight:15}],eyeOpenness:.7,microAdjustments:!0},modifiers:{speed:1,amplitude:.9,intensity:1.1,smoothness:1.1,regularity:1.2,addPrecision:!0},typicalGestures:["track","lock","scan","pulse","vibrate"],transitions:{duration:400,easing:"easeIn",priority:5},getCoreParams:e=>({scaleX:1.1,scaleY:.7,eyeOpenness:.7,eyeExpression:"focused",pupilOffset:{x:0,y:0},microAdjustments:!0}),"3d":{rotation:{type:"still",speed:.5,axes:[0,.1,0],musicSync:!1},glow:{color:"#00CED1",intensity:1.2,pulse:{speed:1.2,range:[1,1.3]}},scale:{base:1,breathe:{enabled:!0,depth:.08,rate:1.2}}},soulAnimation:{driftSpeed:.6,shimmerSpeed:.2,turbulence:.1},rhythmModifiers:{windowMultiplier:.85,visualNoise:0,inputDelay:0,tempoShift:0}},{name:"glitch",emoji:"๐",description:"Surprised sadness with rainbow colors and glitch wiggle",visual:{primaryColor:"#FF6B9D",glowColor:"#4169E1",glowIntensity:1.2,particleRate:5,minParticles:5,maxParticles:15,particleBehavior:"burst",particleSpeed:1,breathRate:.4,breathDepth:.15,coreJitter:!1,coreSize:1,eyeOpenness:.8,blinkRate:1.3,blinkSpeed:1.2,particleColors:[{color:"#FF0080",weight:18},{color:"#00FF80",weight:18},{color:"#8000FF",weight:18},{color:"#FF8000",weight:15},{color:"#0080FF",weight:15},{color:"#FFFF00",weight:10},{color:"#FF6B9D",weight:6}],particleGlitchWiggle:!0,glitchWiggleIntensity:.3,glitchWiggleFrequency:.1},modifiers:{speed:1.1,amplitude:1,intensity:1.1,smoothness:.8,regularity:.7,focus:.6},typicalGestures:["bounce","sway","pulse","drift","flash"],transitions:{duration:300,easing:"easeInOut",priority:5},"3d":{rotation:{type:"unstable",speed:1.1,axes:[0,.35,0],shake:{amplitude:.02,frequency:5},musicSync:!1},glow:{color:"#FF6B9D",intensity:1.2,pulse:{speed:.4,range:[.8,1.6]}},scale:{base:1,breathe:{enabled:!0,depth:.15,rate:.4}}},rhythmModifiers:{windowMultiplier:1,visualNoise:.8,inputDelay:20,tempoShift:0}},n].forEach(e=>{e&&e.name&&a.set(e.name,e)});var v={registerEmotion:o,getEmotion:l,getEmotionVisualParams:h,getEmotionParams:h,getEmotionModifiers:c,getEmotionRhythmModifiers:y,getBlendedRhythmModifiers:b,listEmotions:u,getAllEmotions:d,hasEmotion:g,addEmotionAlias:m,getTransitionParams:p,getEmotionGestures:f,pluginAdapter:i},M=Object.freeze({__proto__:null,addEmotionAlias:m,default:v,getAllEmotions:d,getBlendedRhythmModifiers:b,getEmotion:l,getEmotionGestures:f,getEmotionModifiers:c,getEmotionRhythmModifiers:y,getEmotionVisualParams:h,getTransitionParams:p,hasEmotion:g,listEmotions:u,pluginAdapter:i,registerEmotion:o});const w=new Map;var S={registerPluginGesture:function(e,t){return!(!t.apply&&!t.type||(t.name||(t.name=e),t.type||(t.type="blending"),w.set(e,t),0))},unregisterPluginGesture:function(e){return!!w.has(e)&&(w.delete(e),!0)},getPluginGesture:function(e){return w.get(e)||null},getAllPluginGestures:function(){return Array.from(w.keys())},clearPluginGestures:function(){w.clear()},createLegacyAdapter:function(e){return{name:e.name||"unknown",type:e.type||"blending",emoji:e.emoji||"๐",description:e.description||"Plugin gesture",config:e.config||{},apply(t,i,s,n,a,r){e.animate?e.animate(t,i,s,n,a,r):e.apply&&e.apply(t,i,s,n,a,r)},cleanup:e.cleanup||function(e){e.gestureData&&e.gestureData[this.name]&&delete e.gestureData[this.name]}}}},x={name:"breathe",emoji:"๐ซ",type:"blending",description:"Breathing rhythm with inhale and exhale",config:{musicalDuration:{musical:!0,bars:1,minBeats:2,maxBeats:16},phases:[{name:"inhale",beats:1.5},{name:"hold_in",beats:.5},{name:"exhale",beats:1.5},{name:"hold_out",beats:.5}],inhaleRadius:1.5,exhaleRadius:.3,breathRate:.3,spiralStrength:.002,scaleAmount:.25,glowAmount:.4,frequency:1,easing:"sine",strength:.8,particleMotion:{type:"breathe",strength:.8,inhaleRadius:1.5,exhaleRadius:.3}},rhythm:{enabled:!0,syncMode:"phrase",breathRateSync:{mode:"tempo",bpm:"auto",subdivision:"whole",curve:"sine"},radiusSync:{inhale:{onUpbeat:1.8,onDownbeat:1.4,curve:"ease-in"},exhale:{onUpbeat:.2,onDownbeat:.4,curve:"ease-out"}},durationSync:{mode:"phrases",phrases:2,hold:"fermata"},accentResponse:{enabled:!0,multiplier:1.5,type:"expansion"},patternOverrides:{ballad:{breathRateSync:{subdivision:"double-whole"},radiusSync:{inhale:{onUpbeat:2.2,onDownbeat:1.8},exhale:{onUpbeat:.1,onDownbeat:.2}}},uptempo:{breathRateSync:{subdivision:"half"},radiusSync:{inhale:{onUpbeat:1.4,onDownbeat:1.2},exhale:{onUpbeat:.3,onDownbeat:.4}}},ambient:{breathRateSync:{subdivision:"whole",curve:"ease"},radiusSync:{inhale:{onUpbeat:1.6,onDownbeat:1.6},exhale:{onUpbeat:.2,onDownbeat:.2}}}},dynamics:{forte:{radiusSync:{inhale:{multiplier:1.8},exhale:{multiplier:.5}},spiralStrength:.004,scaleAmount:.4},piano:{radiusSync:{inhale:{multiplier:1.2},exhale:{multiplier:.8}},spiralStrength:.001,scaleAmount:.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.breathe={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),phaseOffset:.2*Math.random()-.1}},apply(e,t,i,s,n,a){e.gestureData?.breathe||this.initialize(e,i,n,a);const r={...this.config,...i},o=(Math.sin(t*Math.PI*2*r.breathRate)+1)/2,l=100*(e.scaleFactor||1),h=r.inhaleRadius*l,c=r.exhaleRadius*l,u=c+(h-c)*o,d=e.x-n,g=e.y-a,m=Math.sqrt(d*d+g*g),p=u-m,f=.05*(i.strength||.8)*s;if(m>0){const t=d/m*p*f,n=g/m*p*f;e.vx+=t,e.vy+=n;const a=r.spiralStrength*s*(i.strength||1),l=-g/m,h=d/m;e.vx+=l*a*o,e.vy+=h*a*o}e.vx*=.98,e.vy*=.98},cleanup(e){e.gestureData?.breathe&&delete e.gestureData.breathe},"3d":{evaluate(e,t){const i=(t.config||{}).breathRate||.3,s=Math.sin(e*Math.PI*2*i);let n=1;if(e>.8){const t=(e-.8)/(1-.8);n=1-t*t*t}const a=.2*s*n;return{position:[0,.05*s*n,0],rotation:[0,0,0],scale:1+.35*s*n,glowIntensity:1+a,glowBoost:Math.max(0,2*a)}}}},C={name:"expand",emoji:"๐ซ",type:"blending",description:"Radial expansion from center",config:{duration:600,scaleAmount:3,scaleTarget:3,glowAmount:.5,easing:"back",strength:3,particleMotion:{type:"pulse",strength:3,direction:"outward",persist:!0}},rhythm:{enabled:!0,syncMode:"crescendo",strengthSync:{pianissimo:1.5,fortissimo:5,crescendo:"build",sforzando:"burst"},scaleTargetSync:{verse:2,chorus:4.5,climax:6,curve:"exponential"},durationSync:{mode:"phrases",build:1.2,release:.8,sustain:"hold"},accentResponse:{enabled:!0,multiplier:2.8,type:"strength"},patternOverrides:{orchestral:{strengthSync:{pianissimo:2,fortissimo:6.5,crescendo:"dramatic"},scaleTargetSync:{climax:8}},rock:{strengthSync:{pianissimo:1.8,fortissimo:5.5,curve:"power"},accentResponse:{multiplier:3.2}},ambient:{strengthSync:{pianissimo:1.2,fortissimo:3.5,crescendo:"organic"},durationSync:{build:1.8,release:1.2}},electronic:{strengthSync:{pianissimo:1.6,fortissimo:4.8,curve:"digital"},scaleTargetSync:{curve:"linear"}}},dynamics:{forte:{strengthSync:{pianissimo:{multiplier:1.4},fortissimo:{multiplier:1.8}},scaleTargetSync:{multiplier:1.6},accentResponse:{multiplier:3.5}},piano:{strengthSync:{pianissimo:{multiplier:.8},fortissimo:{multiplier:1.2}},scaleTargetSync:{multiplier:.7},accentResponse:{multiplier:2}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.expand={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.expand?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.expand,o={...this.config,...i},l=o.strength||1,h=1+(o.scaleTarget-1)*t*l,c=r.baseRadius*h,u=n+Math.cos(r.angle)*c,d=a+Math.sin(r.angle)*c,g=u-e.x,m=d-e.y;e.vx+=.8*g*s,e.vy+=.8*m*s,e.vx*=.95,e.vy*=.95},cleanup(e){e.gestureData?.expand&&delete e.gestureData.expand},"3d":{evaluate(e,t){const i={...this.config,...t},s=i.strength||3;return{position:[0,0,0],rotation:[0,0,0],scale:1+e*(i.scaleAmount||3)*(s/3),glowIntensity:1+.25*e,glowBoost:.8*e}}}},k={name:"contract",emoji:"๐",type:"blending",description:"Radial contraction toward center",config:{duration:600,scaleAmount:.2,scaleTarget:.2,glowAmount:-.2,easing:"cubic",strength:2.5,particleMotion:{type:"pulse",strength:2.5,direction:"inward",persist:!0}},rhythm:{enabled:!0,syncMode:"tension",strengthSync:{onTension:4,onRelease:1.5,curve:"magnetic"},scaleTargetSync:{forte:.1,piano:.4,crescendo:"gradual",diminuendo:"ease"},durationSync:{mode:"phrases",shortPhrase:.8,longPhrase:1.5,hold:"sustain"},accentResponse:{enabled:!0,multiplier:2.2,type:"strength"},patternOverrides:{classical:{strengthSync:{onTension:3.5,onRelease:1.8},scaleTargetSync:{forte:.15,piano:.35}},metal:{strengthSync:{onTension:5,onRelease:2,curve:"sharp"},scaleTargetSync:{forte:.05,piano:.25}},ambient:{strengthSync:{onTension:2.8,onRelease:1.2,curve:"ease"},durationSync:{shortPhrase:1.2,longPhrase:2}},trap:{strengthSync:{onTension:4.5,onRelease:1,dropBeat:6},scaleTargetSync:{forte:.08,piano:.3}}},dynamics:{forte:{strengthSync:{onTension:{multiplier:1.8},onRelease:{multiplier:1.4}},scaleTargetSync:{multiplier:.6},accentResponse:{multiplier:2.8}},piano:{strengthSync:{onTension:{multiplier:.7},onRelease:{multiplier:.8}},scaleTargetSync:{multiplier:1.4},accentResponse:{multiplier:1.6}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.contract={startX:e.x,startY:e.y,angle:Math.atan2(a,n),baseRadius:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.contract?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.contract,o={...this.config,...i},l=o.strength||1,h=1-(1-o.scaleTarget)*t*l,c=r.baseRadius*h,u=n+Math.cos(r.angle)*c,d=a+Math.sin(r.angle)*c,g=u-e.x,m=d-e.y;e.vx+=.5*g*s,e.vy+=.5*m*s,e.vx*=.95,e.vy*=.95},cleanup(e){e.gestureData?.contract&&delete e.gestureData.contract},"3d":{evaluate(e,t){const i={...this.config,...t},s=i.strength||2.5,n=i.scaleTarget||.2,a=1-e*(1-n)*(s/2.5),r=1-.15*e;return{position:[0,0,0],rotation:[0,0,0],scale:Math.max(n,a),glowIntensity:r}}}},P={name:"pulse",emoji:"๐",type:"blending",description:"Radial expansion and contraction from center",config:{duration:600,amplitude:30,frequency:1,holdPeak:.1,easing:"sine",scaleAmount:.2,glowAmount:.3,strength:.15,direction:"outward",particleMotion:{type:"pulse",strength:.15,direction:"outward",frequency:1}},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.6,offBeat:.8,curve:"pulse"},frequencySync:{mode:"locked",subdivision:"quarter"},durationSync:{mode:"beats",beats:1},accentResponse:{enabled:!0,multiplier:2},patternOverrides:{waltz:{amplitudeSync:{onBeat:2,offBeat:.5},durationSync:{beats:3}},swing:{amplitudeSync:{onBeat:1.8,offBeat:.6,curve:"ease"},frequencySync:{subdivision:"swing"}},dubstep:{amplitudeSync:{onBeat:1.2,dropBeat:4,curve:"pulse"}},breakbeat:{frequencySync:{mode:"random",range:[.5,2]},amplitudeSync:{onBeat:2.5,offBeat:.3}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.atan2(a,n);e.gestureData.pulse={baseDistance:r,angle:o,startX:e.x,startY:e.y,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.pulse?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.pulse,o={...this.config,...i},l=i.strength||1,h=this.easeInOutSine(t);let c,{frequency:u}=o,{amplitude:d}=o;i.rhythmModulation&&(d*=i.rhythmModulation.amplitudeMultiplier||1,d*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(u*=i.rhythmModulation.frequencyMultiplier));const g=h*u*2%2;c=o.holdPeak>0&&g>1-o.holdPeak&&g<1+o.holdPeak?1:Math.sin(h*Math.PI*2*u);const m=c*d*l*e.scaleFactor,p=r.baseDistance+m,f=n+Math.cos(r.angle)*p,y=a+Math.sin(r.angle)*p,b=.15*s;if(e.vx+=(f-e.x)*b*.1,e.vy+=(y-e.y)*b*.1,t>.9){const i=1-10*(t-.9);e.vx*=.9+.1*i,e.vy*=.9+.1*i}},cleanup(e){e.gestureData?.pulse&&delete e.gestureData.pulse},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i=t||{},s=i.frequency||1,n=i.strength||.15,a=i.scaleAmount||.2,r=i.glowAmount||.3,o=-(Math.cos(Math.PI*e)-1)/2,l=Math.sin(o*Math.PI*2*s);return{position:[0,0,0],rotation:[0,0,0],scale:1+l*a*n,glowIntensity:1+Math.max(-.3,Math.min(.3,l*r*n*2)),glowBoost:Math.max(0,.8*l)}}}},T={name:"sway",type:"blending",emoji:"๐",description:"Gentle side-to-side swaying motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},amplitude:20,frequency:1,strength:.5},rhythm:{enabled:!0,syncMode:"bar",amplitudeSync:{onBeat:1.2,offBeat:.9,curve:"ease"},durationSync:{mode:"bars",bars:1},patternOverrides:{waltz:{durationSync:{bars:1},amplitudeSync:{onBeat:1.5,curve:"ease"}},swing:{amplitudeSync:{onBeat:1.3,offBeat:.7,curve:"bounce"}}}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.amplitude||this.config.amplitude,l=r.frequency||this.config.frequency,h=r.strength||this.config.strength,c=Math.sin(t*Math.PI*2*l)*o;e.vx+=.01*c*s*h,e.vy+=.5*Math.cos(t*Math.PI*4)*s*h},cleanup(e){},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.amplitude||this.config.amplitude;const n=i.frequency||this.config.frequency,a=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const r=Math.sin(e*Math.PI*2*n),o=s*a*.3*.01,l=.15*r*a,h=.08*r*a;return{position:[r*o,.3*Math.cos(e*Math.PI*4)*o,Math.sin(e*Math.PI*n)*o*.5],rotation:[0,h,l],scale:1}}}},E={name:"float",type:"blending",emoji:"๐",description:"Gentle floating upward motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:2},amplitude:80,wobbleAmount:20,strength:1},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},wobbleSync:{subdivision:"eighth",intensity:.7},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:1.3},patternOverrides:{waltz:{wobbleSync:{subdivision:"quarter",intensity:.9}},dubstep:{amplitudeSync:{onBeat:2,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.float||(e.gestureData.float={originalSize:e.size,originalOpacity:e.opacity||1});const r={...this.config,...i};let o=r.amplitude||this.config.amplitude,l=r.wobbleAmount||this.config.wobbleAmount;const h=r.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1,l*=i.rhythmModulation.wobbleMultiplier||1);const c=Math.sin(t*Math.PI*4)*l;e.vy-=.01*o*s*h*(1-.5*t),e.vx+=.01*c*s*h,e.size=e.baseSize*(1+.1*t),e.opacity=1-.3*t},cleanup(e){e.gestureData?.float?(e.opacity=e.gestureData.float.originalOpacity,e.size=e.gestureData.float.originalSize,delete e.gestureData.float):(e.opacity=1,e.size=e.baseSize),e.vx*=.5,e.vy*=.5},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.amplitude||this.config.amplitude,n=i.wobbleAmount||this.config.wobbleAmount;const a=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1,n*=t.rhythmModulation.wobbleMultiplier||1);const r=Math.sin(e*Math.PI),o=s*r*a*.005,l=Math.sin(e*Math.PI*4)*n*.3*.005,h=Math.sin(e*Math.PI)*Math.PI*.5*a,c=Math.sin(e*Math.PI);return{position:[l,o,0],rotation:[c*Math.sin(e*Math.PI*2)*.1,h,c*Math.cos(e*Math.PI*3)*.08],scale:1+.1*r}}}};const A={left:{x:-1,y:0},right:{x:1,y:0},up:{x:0,y:1},down:{x:0,y:-1}};function D(e){return e.charAt(0).toUpperCase()+e.slice(1)}function _(e){const t=A[e];if(!t)throw new Error(`Invalid float direction: ${e}`);const i="up"===e||"down"===e;return{name:`float${D(e)}`,emoji:"up"===e?"๐":"down"===e?"๐":"left"===e?"๐ฌ๏ธ":"๐จ",type:"blending",description:`Gentle floating ${e}`,config:{duration:2e3,amplitude:80,wobbleAmount:20,strength:1,direction:e},rhythm:{enabled:!0,syncMode:"beat",amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},wobbleSync:{subdivision:"eighth",intensity:.7},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:1.3}},apply(e,s,n,a,r,o){e.gestureData||(e.gestureData={}),e.gestureData.float||(e.gestureData.float={originalSize:e.size,originalOpacity:e.opacity||1});const l={...this.config,...n};let h=l.amplitude||80,c=l.wobbleAmount||20;const u=l.strength||1;n.rhythmModulation&&(h*=n.rhythmModulation.amplitudeMultiplier||1,h*=n.rhythmModulation.accentMultiplier||1,c*=n.rhythmModulation.wobbleMultiplier||1);const d=Math.sin(s*Math.PI*4)*c,g=.01*h*a*u*(1-.5*s);i?(e.vy+=t.y*g,e.vx+=.01*d*a*u):(e.vx+=t.x*g,e.vy+=.01*d*a*u),e.size=e.baseSize*(1+.1*s),e.opacity=1-.3*s},cleanup(e){e.gestureData?.float?(e.opacity=e.gestureData.float.originalOpacity,e.size=e.gestureData.float.originalSize,delete e.gestureData.float):(e.opacity=1,e.size=e.baseSize),e.vx*=.5,e.vy*=.5},"3d":{evaluate(e,s){const n=s||{};let a=n.amplitude||80,r=n.wobbleAmount||20;const o=n.strength||1;s.rhythmModulation&&(a*=s.rhythmModulation.amplitudeMultiplier||1,a*=s.rhythmModulation.accentMultiplier||1,r*=s.rhythmModulation.wobbleMultiplier||1);const l=Math.sin(e*Math.PI),h=a*l*o*.005,c=Math.sin(e*Math.PI*4)*r*.3*.005,u=Math.sin(e*Math.PI)*Math.PI*.5*o,d=Math.sin(e*Math.PI),g=d*Math.sin(e*Math.PI*2)*.1,m=d*Math.cos(e*Math.PI*3)*.08,p=1+.1*l;let f=0,y=0;return i?(y=t.y*h,f=c):(f=t.x*h,y=c),{cameraRelativePosition:[f,y,0],rotation:[g,u,m],scale:p}}}}}var I=_("up"),R=_("down"),B=_("left"),z=_("right"),F={name:"lean",emoji:"โ๏ธ",type:"blending",description:"Diagonal tilting motion with smooth return",config:{duration:1200,musicalDuration:{musical:!0,beats:2},amplitude:10,frequency:1,direction:"right",strength:.7,particleMotion:{type:"lean",direction:"right",strength:.7,frequency:1}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.3,offBeat:.8,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.4},patternOverrides:{waltz:{durationSync:{beats:3},amplitudeSync:{onBeat:1.5,offBeat:.6}},swing:{amplitudeSync:{onBeat:1.6,offBeat:.5,curve:"bounce"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.lean={startX:e.x,startY:e.y,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.lean?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t),h=r.frequency||this.config.frequency;let c=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI*h),d="left"===r.direction?-1:1;if(e.vx+=u*c*.015*s*d,e.vy+=u*c*.01*s*d*.5,t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.lean&&delete e.gestureData.lean},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||10,n=i.frequency||1,a=i.strength||.7,r=i.direction||"right",o=.003*s*a,l=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,h=Math.sin(l*Math.PI*n),c="left"===r?-1:1;return{position:[h*o*c,0,0],rotation:[0,0,.35*h*c],scale:1}}}};function O(e){if("left"!==e&&"right"!==e)throw new Error(`Invalid lean direction: ${e}. Only 'left' and 'right' are supported.`);const t=A[e];return{name:`lean${D(e)}`,emoji:"left"===e?"โ๏ธ":"โ๏ธ",type:"blending",description:`Lean ${e} with smooth return`,config:{duration:800,amplitude:10,frequency:1,strength:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:1.3,offBeat:.8,curve:"ease"},accentResponse:{enabled:!0,multiplier:1.4}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.lean={startX:e.x,startY:e.y,initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.lean?.initialized||this.initialize(e,s);const o={...this.config,...s},l=o.strength||.7,h=this.easeInOutCubic(i);let c=o.amplitude*l*e.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI*o.frequency);if(e.vx+=u*c*.015*n*t.x,e.vy+=u*c*.01*n*t.x*.5,i>.9){const t=1-10*(i-.9);e.vx*=.95+.05*t,e.vy*=.95+.05*t}},cleanup(e){e.gestureData?.lean&&delete e.gestureData.lean},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||10,a=s.frequency||1,r=.003*n*(s.strength||.7),o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI*a),h=.35*l*t.x;return{cameraRelativePosition:[l*r*t.x,0,0],cameraRelativeRotation:[0,0,h],scale:1}}}}}var L=O("left"),q=O("right"),G={name:"jitter",type:"blending",emoji:"๐ซจ",description:"Nervous jittery movement",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},intensity:15,frequency:30,strength:1},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:2,offBeat:.5,curve:"pulse"},patternOverrides:{breakbeat:{amplitudeSync:{onBeat:3,offBeat:.3}},dubstep:{amplitudeSync:{onBeat:5,offBeat:.1,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.jitter||(e.gestureData.jitter={originalSize:e.size});const r={...this.config,...i};let o=r.intensity||this.config.intensity;const l=r.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1);const h=(Math.random()-.5)*o*l,c=(Math.random()-.5)*o*l,u=1-.5*t;e.vx+=.1*h*s*u,e.vy+=.1*c*s*u,e.size=e.baseSize*(1+.1*(Math.random()-.5))},cleanup(e){e.gestureData?.jitter?(e.size=e.gestureData.jitter.originalSize,delete e.gestureData.jitter):e.size=e.baseSize,e.vx*=.7,e.vy*=.7},"3d":{evaluate(e,t){const i={...this.config,...t};let s=i.intensity||this.config.intensity;const n=i.strength||this.config.strength;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const a=Math.sin(e*Math.PI),r=s*n*.002*a;return{position:[(Math.random()-.5)*r,(Math.random()-.5)*r,(Math.random()-.5)*r],rotation:[.005*(Math.random()-.5)*a,.005*(Math.random()-.5)*a,.005*(Math.random()-.5)*a],scale:1+.02*(Math.random()-.5)*a}}}},H={name:"twitch",emoji:"โก",type:"blending",description:"Nervous, paranoid twitching",config:{intensity:8,frequency:.08,duration:100,musicalDuration:{musical:!0,beats:.5},recovery:200,maxOffset:15,sharpness:.9},rhythm:{enabled:!0,syncMode:"subdivision",durationSync:{mode:"beats",beats:.5},probabilitySync:{subdivision:"sixteenth",onBeat:.3,offBeat:.05,accentBoost:2},intensitySync:{onBeat:2,offBeat:.8,curve:"pulse"},patternOverrides:{breakbeat:{probabilitySync:{onBeat:.5,offBeat:.1},intensitySync:{onBeat:3,offBeat:.5}},dubstep:{intensitySync:{onBeat:1.5,dropBeat:5,curve:"pulse"}}}},apply(e,t,i,s,n,a){e.gestureData||(e.gestureData={}),e.gestureData.twitch||(e.gestureData.twitch={twitchOffset:{x:0,y:0},targetOffset:{x:0,y:0},isTwitching:!1,twitchTimer:0,cooldownTimer:0,lastTwitch:0});const r=e.gestureData.twitch,{config:o}=this;let l=i.intensity||o.intensity;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.probabilityMultiplier);const h=Date.now();if(!r.isTwitching&&r.cooldownTimer<=0&&Math.random()<(i.frequency||o.frequency)){r.isTwitching=!0,r.twitchTimer=o.duration,r.cooldownTimer=o.recovery;const e=Math.random()*Math.PI*2,t=.5*o.maxOffset+Math.random()*(.5*o.maxOffset);r.targetOffset={x:Math.cos(e)*t*l/8,y:Math.sin(e)*t*l/8},r.lastTwitch=h}if(r.cooldownTimer>0&&(r.cooldownTimer-=16*s),r.isTwitching)if(r.twitchTimer-=16*s,r.twitchTimer>0){const{sharpness:e}=o;r.twitchOffset.x+=(r.targetOffset.x-r.twitchOffset.x)*e,r.twitchOffset.y+=(r.targetOffset.y-r.twitchOffset.y)*e}else r.isTwitching=!1;else r.twitchOffset.x*=.85,r.twitchOffset.y*=.85;e.vx+=r.twitchOffset.x*s*.5,e.vy+=r.twitchOffset.y*s*.5,Math.random()<.1&&(e.vx+=(Math.random()-.5)*l*.3,e.vy+=(Math.random()-.5)*l*.3)},cleanup(e){e.gestureData?.twitch&&delete e.gestureData.twitch},"3d":{evaluate(e,t){const i=t.config||{};let s=.6*(i.intensity||8);const n=i.maxOffset||15,a=i.frequency||.08;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const r=9999*Math.floor(10*e),o=e=>{const t=1e4*Math.sin(r+e);return t-Math.floor(t)};if(o(0)<3*a){const e=o(1)*Math.PI*2,t=n*s/8*.003;return{position:[Math.cos(e)*t*o(2),Math.sin(e)*t*o(3),(o(4)-.5)*t],rotation:[.12*(o(5)-.5),.12*(o(6)-.5),.12*(o(7)-.5)],scale:1+.06*(o(8)-.5)}}{const e=.3;return{position:[(o(10)-.5)*e,(o(11)-.5)*e,(o(12)-.5)*e],rotation:[.006*(o(13)-.5),.006*(o(14)-.5),.006*(o(15)-.5)],scale:1}}}}},j={name:"vibrate",emoji:"๐ณ",type:"blending",description:"High frequency vibration",config:{duration:500,frequency:20,amplitude:8,easing:"linear",strength:2,particleMotion:{type:"shake",strength:2,frequency:20,amplitude:8}},rhythm:{enabled:!0,syncMode:"subdivision",frequencySync:{subdivision:"thirty-second",baseFrequency:20,tempoScaling:!0},amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"pulse"},durationSync:{mode:"beats",beats:1},patternOverrides:{dubstep:{frequencySync:{subdivision:"sixteenth"},amplitudeSync:{onBeat:2,dropBeat:3}},breakbeat:{frequencySync:{mode:"random",range:[15,30]}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.vibrate={timer:0,seed:1e3*Math.random(),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.vibrate?.initialized||this.initialize(e,i);const r=e.gestureData.vibrate,o={...this.config,...i},l=o.strength||this.config.strength||1;let{amplitude:h}=o,{frequency:c}=o;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier)),r.timer+=s*c;const u=(Math.random()-.5)*h*l,d=(Math.random()-.5)*h*l;if(e.vx+=.5*u*s,e.vy+=.5*d*s,e.vx*=.9,e.vy*=.9,t>.8){const i=1-5*(t-.8);e.vx*=i,e.vy*=i}},cleanup(e){e.gestureData?.vibrate&&delete e.gestureData.vibrate},"3d":{evaluate(e,t){const i={...this.config,...t};let{amplitude:s}=i;const n=i.strength||this.config.strength||1;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);const a=Math.sin(e*Math.PI),r=s*n*.003*a;return{position:[(Math.random()-.5)*r,(Math.random()-.5)*r,(Math.random()-.5)*r],rotation:[.01*(Math.random()-.5)*a,.01*(Math.random()-.5)*a,.01*(Math.random()-.5)*a],scale:1+.01*(Math.random()-.5)*a}}}},$={name:"shake",emoji:"๐ซจ",type:"blending",description:"Random jitter movement for vibration effects",config:{duration:400,amplitude:15,frequency:15,decay:.9,smoothing:.1,axes:"both",easing:"linear",strength:3,particleMotion:{type:"shake",strength:3,frequency:15,decay:!1}},rhythm:{enabled:!0,syncMode:"subdivision",amplitudeSync:{subdivision:"sixteenth",onBeat:2.5,offBeat:.7,curve:"pulse"},frequencySync:{mode:"tempo",baseFrequency:15,scaling:"linear"},durationSync:{mode:"beats",beats:2},patternOverrides:{breakbeat:{amplitudeSync:{onBeat:3,offBeat:.2},frequencySync:{mode:"random",range:[8,20]}},dubstep:{amplitudeSync:{subdivision:"eighth",onBeat:4,dropBeat:6,curve:"pulse"}},swing:{amplitudeSync:{onBeat:1.8,offBeat:1,curve:"ease"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.shake={originalX:e.x,originalY:e.y,randomAngle:Math.random()*Math.PI*2,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.shake?.initialized||this.initialize(e,i);const r=e.gestureData.shake,o={...this.config,...i},l=o.strength||this.config.strength||1;let{amplitude:h}=o,{frequency:c}=o;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier));const u=o.decay?1-t:1,d=Math.sin(t*Math.PI*c)*h*u*l*e.scaleFactor,g=d*Math.cos(r.randomAngle),m=d*Math.sin(r.randomAngle);e.x=r.originalX+g,e.y=r.originalY+m},pseudoRandom(e){const t=1e4*Math.sin(e);return t-Math.floor(t)},cleanup(e){e.gestureData?.shake&&(e.x=e.gestureData.shake.originalX,e.y=e.gestureData.shake.originalY,delete e.gestureData.shake)},"3d":{evaluate(e,t){const i=t||{},s=.003*(i.amplitude||15),n=i.frequency||15,a=.5*(i.strength||1),r=i.decay?1-e:1,o=Math.sin(e*Math.PI*n)*s*r*a,l=Math.floor(e*n);return{position:[o*(1e4*Math.sin(l)%1-.5)*2,0,o*(1e4*Math.sin(1.3*l)%1-.5)*2],rotation:[0,0,o*(1e4*Math.sin(1.7*l)%1-.5)*.2],scale:1}}}},W={name:"wiggle",emoji:"ใฐ๏ธ",type:"additive",description:"Rapid side-to-side oscillation",config:{duration:600,musicalDuration:{musical:!0,beats:1},amplitude:15,frequency:6,strength:1,damping:.3,easing:"linear",particleMotion:{type:"wiggle",strength:1,amplitude:15,frequency:6}},rhythm:{enabled:!0,syncMode:"beat",frequencySync:{subdivision:"sixteenth",wigglePerBeat:4},amplitudeSync:{onBeat:1.5,offBeat:.8,curve:"bounce"},durationSync:{mode:"beats",beats:1}},apply(e,t,i,s,n,a,r){const o=(i.amplitude||this.config.amplitude)*n,l=i.frequency||this.config.frequency,h=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*l)*o*h;e.vx+=.5*c;const u=Math.cos(s*Math.PI*l*2)*o*.1*h;e.vy+=.3*u},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.amplitude||15,a=Math.pow(1-e,.5),r=Math.sin(e*Math.PI*14)*a,o=Math.cos(e*Math.PI*14*.7)*a*.4,l=n/15*s,h=.15*r*s;return{cameraRelativePosition:[.08*r*l,.02*Math.abs(o)*l,0],cameraRelativeRotation:[0,0,h],scale:1+.05*Math.abs(r),glowIntensity:1+.2*Math.abs(r)}}}};function U(e){const t=A[e];if(!t)throw new Error(`Invalid step direction: ${e}`);return{name:`step${D(e)}`,emoji:"left"===e?"๐":"right"===e?"๐":"up"===e?"๐":"๐",type:"blending",description:`Quick step ${e} and return`,config:{duration:400,amplitude:25,strength:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:5,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"snap"}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l,h=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1),l=i<.3?this.easeOutQuad(i/.3):1-this.easeInOutCubic((i-.3)/.7);const c=t.x*h*l*.01*n,u=t.y*h*l*.01*n;e.vx+=c,e.vy+=u},cleanup(e){},easeOutQuad:e=>1-(1-e)*(1-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||25,a=s.strength||.7;let r,o=.008*n*a;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),e<.3)r=1-(1-e/.3)*(1-e/.3);else{const t=(e-.3)/.7;r=1-(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)}const l=t.x*o*r,h=t.y*o*r,c=.12*r*a,u=-t.x*c;return{cameraRelativePosition:[l,h,0],rotation:[t.y*c*.5,0,u],scale:1}}}}}function V(e){const t=A[e];if(!t)throw new Error(`Invalid slide direction: ${e}`);return{name:`slide${D(e)}`,emoji:"left"===e?"โฌ
๏ธ":"โก๏ธ",type:"blending",description:`Smooth slide ${e} and return`,config:{duration:800,amplitude:35,strength:.6,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,durationSync:{mode:"beats",beats:2},amplitudeSync:{onBeat:1.2,offBeat:.9,curve:"ease"}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1);const h=Math.sin(i*Math.PI),c=t.x*l*h*.008*n,u=t.y*l*h*.008*n;e.vx+=c,e.vy+=u},cleanup(e){},"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||35,a=s.strength||.6;let r=.008*n*a;i.rhythmModulation&&(r*=i.rhythmModulation.amplitudeMultiplier||1);const o=Math.sin(e*Math.PI),l=t.x*r*o,h=t.y*r*o,c=.08*o*a,u=-t.x*c,d=t.x*c*.5;return{cameraRelativePosition:[l,h,.02*Math.sin(e*Math.PI*2)*a],rotation:[0,d,u],scale:1+.03*o}}}}}var Y=U("left"),X=U("right"),N=U("up"),Q=U("down"),J=V("left"),K=V("right"),Z={name:"runningman",emoji:"๐",type:"effect",description:"Hip-hop running man shuffle",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},slideDistance:30,stepHeight:15,speed:1.2,strength:.8,particleMotion:{type:"runningman",strength:.7}},rhythm:{enabled:!0,syncToBeat:!0,durationSync:{mode:"bars",bars:1},beatMultiplier:1,accentBeats:[1,3]},apply:(e,t,i,s,n,a)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i={...this.config,...t}.strength||.8;return{position:[.1*Math.sin(e*Math.PI*4)*i,.05*Math.abs(Math.sin(e*Math.PI*8))*i,0],rotation:[0,0,.035*Math.sin(e*Math.PI*4)*i],scale:1-.035*Math.abs(Math.sin(e*Math.PI*8))*i,glowIntensity:1+.25*Math.abs(Math.sin(e*Math.PI*8)),glowBoost:.35*Math.max(0,Math.abs(Math.sin(e*Math.PI*8)))}}}},ee={name:"charleston",emoji:"๐บ",type:"effect",description:"Hip-hop Charleston shuffle with crisscross",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},kickDistance:35,swivelRange:40,bounceHeight:12,strength:.9,particleMotion:{type:"charleston",strength:.8}},rhythm:{enabled:!0,syncToBeat:!0,durationSync:{mode:"bars",bars:1.5},beatMultiplier:2,accentBeats:[1,2.5,3,4.5]},apply:(e,t,i,s,n,a)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i={...this.config,...t}.strength||.9;return{position:[.12*Math.sin(e*Math.PI*8)*i,.05*Math.abs(Math.sin(e*Math.PI*8))*i,0],rotation:[0,0,.05*Math.sin(e*Math.PI*8)*i],scale:1-.04*Math.abs(Math.sin(e*Math.PI*8))*i,glowIntensity:1+.3*Math.abs(Math.sin(e*Math.PI*8)),glowBoost:.4*Math.max(0,Math.abs(Math.sin(e*Math.PI*8)))}}}},te={name:"hula",emoji:"๐",type:"override",description:"Hula-hoop motion with vertical waves",config:{speed:.015,maintainRadius:!1,elliptical:!0,use3D:!0,zPhaseOffset:Math.PI/4,verticalOscillation:.3,wobbleAmount:.15,duration:2500,musicalDuration:{musical:!0,bars:1.5},particleMotion:{type:"hula",strength:1,verticalOscillation:.3}},rhythm:{enabled:!0,syncMode:"bar",durationSync:{mode:"bars",bars:1.5},speedSync:{mode:"tempo",baseSpeed:.015,scaling:"proportional"},wobbleSync:{onBeat:.25,offBeat:.1,curve:"sine"},verticalSync:{subdivision:"quarter",amplitude:.4,phase:"sequential"},dynamics:{forte:{wobbleAmount:.3,speed:1.2},piano:{wobbleAmount:.05,speed:.8}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.random()<.5?1:-1,l=Math.max(r,100+180*Math.random()),h=r<5?Math.random()*Math.PI*2:Math.atan2(a,n);e.gestureData.hula={radius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,wobblePhase:Math.random()*Math.PI*2,direction:o}},apply(e,t,i,s,n,a){e.gestureData?.hula||this.initialize(e,i,n,a);const r=e.gestureData.hula,o=(i.speed||this.config.speed)*(i.strength||1);let l=1;t<.1?(l=t/.1,l=Math.sin(l*Math.PI*.5)):t>.9&&(l=(1-t)/.1,l=Math.sin(l*Math.PI*.5)),r.angle+=o*s*r.direction*l;const h=Math.sin(2*r.angle+r.wobblePhase)*(i.wobbleAmount||this.config.wobbleAmount)*l,c=r.radius*(1+h)*l,u=r.radius*(.7+h)*l,d=n+Math.cos(r.angle)*c,g=a+Math.sin(r.angle)*u;if(t<.1){const t=e.x-n,i=e.y-a;Math.sqrt(t*t+i*i)<50?(e.x=n+Math.cos(r.angle)*c,e.y=a+Math.sin(r.angle)*u):(e.x=e.x+(d-e.x)*l*.5,e.y=e.y+(g-e.y)*l*.5)}else e.x=d,e.y=g;const m=r.angle+r.zPhase+(i.zPhaseOffset||this.config.zPhaseOffset);e.z=.9*Math.sin(m)*l;const p=i.verticalOscillation||this.config.verticalOscillation,f=Math.cos(2*m)*p*r.radius*.2*l;e.y+=f;const y=e.z*r.radius*.1;e.y-=y;const b=-Math.sin(r.angle)*c*o,v=Math.cos(r.angle)*u*o;t<.1?(e.vx=r.originalVx+(b-r.originalVx)*l,e.vy=r.originalVy+(v-r.originalVy)*l):t>.9?(e.vx=b*l+r.originalVx*(1-l),e.vy=v*l+r.originalVy*(1-l),e.z=e.z*l+r.originalZ*(1-l)):(e.vx=b,e.vy=v)},cleanup(e){if(e.gestureData?.hula){const t=e.gestureData.hula;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.hula}},"3d":{evaluate(e,t){const{particle:i}=t;if(!i||!i.gestureData?.hula)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.hula,n=t.config||{};let a=1;e<.15?(a=e/.15,a=Math.sin(a*Math.PI*.5)):e>.85&&(a=(1-e)/.15,a=Math.sin(a*Math.PI*.5));const r=s.initialAngle+e*Math.PI*2*s.direction,o=.25*Math.cos(r)*a,l=.25*Math.sin(r)*a,h=n.verticalOscillation||.3;return{position:[o,Math.sin(2*r+s.wobblePhase)*h*a,l],rotation:[0,(r-s.initialAngle)*a,0],scale:1+.15*Math.abs(Math.sin(r))*a}}}},ie={name:"twist",emoji:"๐",type:"override",description:"Twisting dance motion with alternating rotation",config:{duration:1200,musicalDuration:{musical:!0,beats:3},rotationAngle:45,contractionFactor:.8,twistFrequency:2,easing:"smooth",strength:.8,particleMotion:{type:"twist",rotationAngle:45,contractionFactor:.8,twistFrequency:2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!1,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"elastic"},patternOverrides:{funk:{rotationAngle:60,contractionFactor:.7},disco:{twistFrequency:3,rotationAngle:50},latin:{rotationAngle:35,contractionFactor:.85,twistFrequency:2.5}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.twist={startX:e.x,startY:e.y,startAngle:Math.atan2(e.y-t.centerY,e.x-t.centerX),startDistance:Math.sqrt(Math.pow(e.x-t.centerX,2)+Math.pow(e.y-t.centerY,2)),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.twist?.initialized||this.initialize(e,{...i,centerX:n,centerY:a});const r={...this.config,...i},o=e.gestureData.twist,l=r.strength||this.config.strength||1,h=t*r.twistFrequency*Math.PI*2,c=Math.sin(h)*l;let{rotationAngle:u}=r,{contractionFactor:d}=r;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,d=1-(1-d)*(i.rhythmModulation.amplitudeMultiplier||1));const g=u*Math.PI/180*c,m=1-(1-d)*Math.abs(c),p=o.startAngle+g,f=o.startDistance*m,y=n+Math.cos(p)*f,b=a+Math.sin(p)*f,v=.15*l;e.x+=(y-e.x)*v,e.y+=(b-e.y)*v,e.vx=.05*(y-e.x),e.vy=.05*(b-e.y);const M=5*Math.sin(t*Math.PI*4)*l;if(e.y+=.1*M,t>.9){const i=1-10*(t-.9);e.vx*=i,e.vy*=i}},cleanup(e){e.gestureData?.twist&&delete e.gestureData.twist},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||.8,n=e>.85?(1-e)/.15:1,a=e*(i.twistFrequency||2)*Math.PI*2,r=Math.sin(a)*s*n,o=r*((i.rotationAngle||45)*Math.PI/180);return{position:[.05*Math.sin(a)*s*n,.02*Math.abs(Math.sin(2*a))*s*n,0],rotation:[.08*Math.cos(a)*s*n,o,.12*Math.sin(.5*a)*s*n],scale:1-(1-(i.contractionFactor||.8))*Math.abs(r),glowIntensity:1+.3*Math.abs(r)}}}},se={name:"pop",emoji:"๐ฅ",type:"blending",description:"Quick scale pulse - the classic beat hit",config:{duration:200,musicalDuration:{musical:!0,beats:.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:.5},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;return e<.15?(s=e/.15,s=1-Math.pow(1-s,3)):(s=1-(e-.15)/.85,s=Math.pow(s,2)),{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+.08*s*i,glowBoost:.3*s*i,positionBoost:[0,.02*s*i,0]}}}},ne={name:"flare",emoji:"๐ฅ",type:"blending",description:"Dramatic scale burst with intense glow - for big moments",config:{duration:400,musicalDuration:{musical:!0,beats:1},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1},interruptible:!0,priority:6,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.1){const t=e/.1;s=1-Math.pow(1-t,4)}else if(e<.3){const t=(e-.1)/.2;s=1-.1*Math.sin(t*Math.PI)}else s=1-(e-.3)/.7,s=Math.pow(s,.6);return{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+(.15*s+.15*Math.sin(e*Math.PI*4)*(1-e)*.02)*i,glowBoost:.8*s*i,positionBoost:[0,.04*s*i,0]}}}},ae={name:"swell",emoji:"๐",type:"blending",description:"Glow build with scale - for transitions and builds",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1.5},interruptible:!0,priority:4,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.6){const t=e/.6;s=t*t}else{const t=(e-.6)/.4;s=1-t*t}return{position:[0,0,0],rotation:[0,0,0],scale:1,scaleBoost:1+.1*s*i,glowBoost:.4*s*i,positionBoost:[0,.03*Math.sin(e*Math.PI)*i,0]}}}},re={name:"swagger",emoji:"๐",type:"blending",description:"Side lean with drift - confident swagger",config:{duration:400,musicalDuration:{musical:!0,beats:1},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:1},interruptible:!0,priority:4,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1;let s;if(e<.3){const t=e/.3;s=1-Math.pow(1-t,2)}else if(e<.7)s=1;else{const t=(e-.7)/.3;s=1-t*t}return{position:[0,0,0],rotation:[0,0,0],scale:1,rotationBoost:[0,0,.12*s*i*1],positionBoost:[.04*s*i*1,.01*s*i,0],scaleBoost:1+.03*s*i}}}},oe={name:"dip",emoji:"โฌ๏ธ",type:"blending",description:"Downward bob - groove dip feel",config:{duration:250,musicalDuration:{musical:!0,beats:.5},strength:1},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:.5},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{isAccent:!0,evaluate(e,t){const i=t?.strength||1,s=Math.sin(e*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1,positionBoost:[0,.015*-s*i,0],scaleBoost:1-.015*s*i}}}},le={name:"bounce",emoji:"โฌ๏ธ",type:"blending",description:"Vertical oscillation with smooth easing",config:{duration:800,musicalDuration:{musical:!0,beats:2},amplitude:30,frequency:2,axis:"vertical",damping:!0,easing:"sine",strength:.6,particleMotion:{type:"bounce",axis:"vertical",strength:.6,frequency:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.8,offBeat:.6,curve:"bounce"},frequencySync:{mode:"tempo",multiplier:1},durationSync:{mode:"beats",beats:4},accentResponse:{enabled:!0,multiplier:1.5},patternOverrides:{waltz:{frequencySync:{multiplier:.75},durationSync:{beats:3}},swing:{amplitudeSync:{onBeat:2,offBeat:.4,curve:"ease"}},dubstep:{amplitudeSync:{onBeat:1.5,dropBeat:3,curve:"pulse"}},breakbeat:{frequencySync:{multiplier:1.5},amplitudeSync:{onBeat:2.2,offBeat:.3}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.bounce={startY:e.y,startX:e.x,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.bounce?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t);let{frequency:h}=r;const c=i.phase||0;let u=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,u*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const d=Math.sin((l+c)*Math.PI*2*h);if(r.damping&&t>.7&&(u*=1-(t-.7)/.3*.8),"vertical"===r.axis?(e.vy+=d*u*.01*s,t>.9&&(e.vx*=.98)):"horizontal"===r.axis&&(e.vx+=d*u*.01*s,t>.9&&(e.vy*=.98)),t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.bounce&&delete e.gestureData.bounce},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||30,n=i.frequency||2,a=.003*s*(i.strength||.6),r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*Math.PI*n,o=Math.abs(Math.sin(r));let l=a;return e>.7&&(l*=1-(e-.7)/.3*.8),{position:[0,o*l,0],rotation:[0,0,0],scale:1+.08*o}}}},he={name:"orbit",emoji:"๐ช",type:"override",description:"Orbital motion around center",config:{speed:.02,maintainRadius:!0,elliptical:!1,use3D:!0,zPhaseOffset:0,verticalOscillation:0,duration:3e3,musicalDuration:{musical:!0,bars:2},particleMotion:{type:"orbit",strength:1}},rhythm:{enabled:!0,syncMode:"harmonic",durationSync:{mode:"bars",bars:2},speedSync:{tonic:.02,fifth:.03,octave:.04,third:.025,curve:"smooth"},radiusSync:{bass:150,mid:100,treble:50,scaling:"logarithmic"},depthSync:{major:{z:1,phase:0},minor:{z:-1,phase:Math.PI},diminished:{z:.5,phase:Math.PI/2},augmented:{z:.8,phase:-Math.PI/2}},phaseSync:{mode:"harmonic",intervals:[1,1.5,2],drift:.05},dynamics:{forte:{speed:.04,maintainRadius:!1},piano:{speed:.01,maintainRadius:!0}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.sqrt(n*n+a*a),o=Math.random()<.5?1:-1,l=Math.max(r,100+180*Math.random()),h=r<5?Math.random()*Math.PI*2:Math.atan2(a,n);e.gestureData.orbit={radius:l,targetRadius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,direction:o}},apply(e,t,i,s,n,a){e.gestureData?.orbit||this.initialize(e,i,n,a);const r=e.gestureData.orbit,o=(i.speed||this.config.speed)*(i.strength||1);r.angle+=o*s*r.direction;let{radius:l}=r;if(i.maintainRadius||(l=r.radius*(1+.1*Math.sin(t*Math.PI*2))),e.x=n+Math.cos(r.angle)*l,e.y=a+Math.sin(r.angle)*l,!1!==i.use3D){const t=r.angle+r.zPhase+(i.zPhaseOffset||0);if(e.z=.8*Math.sin(t),i.verticalOscillation){const s=Math.cos(t)*i.verticalOscillation*l*.1;e.y+=s}}if(e.vx=-Math.sin(r.angle)*l*o,e.vy=Math.cos(r.angle)*l*o,t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.orbit){const t=e.gestureData.orbit;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.orbit}},"3d":{evaluate(e,t){const i=t?.particle;if(!i||!i.gestureData?.orbit)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.orbit;let n=1;e<.15?n=Math.sin(e/.15*Math.PI*.5):e>.85&&(n=Math.sin((1-e)/.15*Math.PI*.5));const a=s.initialAngle+e*Math.PI*2*s.direction,r=.3*Math.cos(a)*n,o=.3*Math.sin(a)*n,l=(a+Math.PI/2-(s.initialAngle+Math.PI/2))*n,h=i.z||0;return{position:[r,0,o+.1*h*n],rotation:[0,l,0],scale:1+.15*h*n}}}};function ce(e){const t=A[e];if(!t)throw new Error(`Invalid orbit direction: ${e}`);const i="up"===e||"down"===e,s="left"===e||"up"===e?1:-1;return{name:`orbit${D(e)}`,emoji:"left"===e?"๐":"right"===e?"๐":"up"===e?"๐":"๐ซ",type:"override",description:`Orbit ${"left"===e?"counter-clockwise":"right"===e?"clockwise":e}`,config:{duration:1500,musicalDuration:{musical:!0,beats:4},speed:.02,maintainRadius:!0,use3D:!0,rotations:1,strength:1,direction:e,verticalOscillation:i?.3:0,particleMotion:{type:"orbit",strength:1,rotations:1}},rhythm:{enabled:!0,syncMode:"harmonic",durationSync:{mode:"bars",bars:1},speedSync:{tonic:.02,fifth:.03,octave:.04,curve:"smooth"},radiusSync:{bass:150,mid:100,treble:50,scaling:"logarithmic"},dynamics:{forte:{speed:.04,maintainRadius:!1},piano:{speed:.01,maintainRadius:!0}}},initialize(e,t,i,n){e.gestureData||(e.gestureData={});const a=e.x-i,r=e.y-n,o=Math.sqrt(a*a+r*r),l=Math.max(o,80+100*Math.random()),h=o<5?Math.random()*Math.PI*2:Math.atan2(r,a);e.gestureData.orbit={radius:l,targetRadius:l,angle:h,initialAngle:h,originalVx:e.vx,originalVy:e.vy,originalZ:e.z||0,zPhase:Math.random()*Math.PI*2,direction:s,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.orbit?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.orbit,h={...this.config,...n},c=n.strength||1,u=(h.speed||.02)*c;let d=1;s<.15?(d=s/.15,d=Math.sin(d*Math.PI*.5)):s>.85&&(d=(1-s)/.15,d=Math.sin(d*Math.PI*.5)),l.angle+=u*a*l.direction*d;let{radius:g}=l;h.maintainRadius||(g=l.radius*(1+.1*Math.sin(s*Math.PI*2)));const m=g*d+(1-d)*l.radius*.5;if(e.x=r+Math.cos(l.angle)*m,e.y=o+Math.sin(l.angle)*m,!1!==h.use3D){const n=l.angle+l.zPhase;if(e.z=.8*Math.sin(n)*d,i&&h.verticalOscillation){const i=t.y*s*h.verticalOscillation*g*.5;e.y+=i}}if(e.vx=-Math.sin(l.angle)*m*u*d,e.vy=Math.cos(l.angle)*m*u*d,s>.9){const t=10*(1-s);e.vx=e.vx*t+l.originalVx*(1-t),e.vy=e.vy*t+l.originalVy*(1-t)}},cleanup(e){if(e.gestureData?.orbit){const t=e.gestureData.orbit;e.vx=t.originalVx,e.vy=t.originalVy,e.z=t.originalZ,delete e.gestureData.orbit}},"3d":{evaluate(e,n){const a=n.config||n||{},r=n.strength||1,o=a.rotations||1;let l=1;e<.15?l=Math.sin(e/.15*Math.PI*.5):e>.85&&(l=Math.sin((1-e)/.15*Math.PI*.5));const h=.25*r,c=e*Math.PI*2*o*s,u=Math.cos(c)*h*l,d=Math.sin(c)*h*l;let g=0;return i&&(g=t.y*e*.2*r*l),{cameraRelativePosition:[u,g,d],rotation:[0,c*l*.5,0],scale:1+.2*d}}}}}var ue=ce("left"),de=ce("right"),ge=ce("up"),me=ce("down"),pe={name:"jump",emoji:"๐ฆ",type:"override",description:"Squash, leap, and land with classic animation principles",config:{duration:800,musicalDuration:{musical:!0,beats:2},jumpHeight:60,squashAmount:.8,stretchAmount:1.2,anticipation:.2,hangTime:.1,landingImpact:!0,driftOutward:!0,easing:"quad",particleMotion:{type:"jump",strength:.9,jumpHeight:60,squash:.8,stretch:1.2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},phaseSync:{anticipation:"eighth",jump:"beat",landing:"sixteenth"},heightSync:{onBeat:1.5,offBeat:.8,accent:2,curve:"exponential"},deformationSync:{squashOnBeat:.6,stretchOnBeat:1.4,timing:"anticipatory"},hangTimeSync:{mode:"tempo",baseDuration:.1,scaling:"inverse"},dynamics:{forte:{jumpHeight:80,stretch:1.3},piano:{jumpHeight:30,stretch:1.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.jump={startX:e.x,startY:e.y,startSize:e.size,originalVx:e.vx,originalVy:e.vy,driftDirection:.1*(e.x-i),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.jump?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.jump,o={...this.config,...i},l=i.strength||1,h=o.jumpHeight*l*e.scaleFactor,c=o.squashAmount,u=o.stretchAmount,d=o.anticipation,g=1-.5*o.anticipation;if(t<d){const i=t/d,s=this.easeOutQuad(i);e.size=r.startSize*(1-(1-c)*s),e.y=r.startY+5*s*e.scaleFactor,e.vx=0,e.vy=0}else if(t<g){const i=(t-d)/(g-d);let s=Math.sin(i*Math.PI);if(o.hangTime>0&&i>.4&&i<.6){const e=(i-.4)/.2;s=.95+.05*this.easeInOutCubic(e)}if(e.y=r.startY-s*h,o.driftOutward&&(e.x=r.startX+s*r.driftDirection),i<.5){const t=2*i;e.size=r.startSize*(c+(u-c)*t)}else{const t=2*(i-.5);e.size=r.startSize*(u-(u-1)*t*.8)}e.vx=.5*r.driftDirection,e.vy=-Math.cos(i*Math.PI)*h*.1}else{const i=(t-g)/(1-g),s=this.easeOutBounce(i);if(e.y=r.startY,o.landingImpact)if(i<.3){const t=i/.3;e.size=r.startSize*(1-(1-.8*c)*(1-t))}else{const t=(i-.3)/.7;e.size=r.startSize*(.8*c+(1-.8*c)*t)}else e.size=r.startSize*(c+(1-c)*s);e.vx=r.originalVx*s,e.vy=r.originalVy*s}},cleanup(e){if(e.gestureData?.jump){const t=e.gestureData.jump;e.size=t.startSize,e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.jump}},easeOutQuad:e=>e*(2-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutBounce(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375},"3d":{evaluate(e,t){const i=t.config||t||{},s=t.strength||1,n=.004*(i.jumpHeight||60)*s,a=i.squashAmount||.8,r=i.stretchAmount||1.2,o=i.anticipation||.2,l=1-.5*o;let h=0,c=1,u=0;if(e<o){const t=e/o,i=t*(2-t);c=1-(1-a)*i,h=.02*-i}else if(e<l){const t=(e-o)/(l-o);h=Math.sin(t*Math.PI)*n,c=t<.5?a+2*t*(r-a):r-2*(t-.5)*(r-1)*.8,u=.05*Math.sin(t*Math.PI)}else{const t=(e-l)/(1-l);if(t<.5){const e=2*t;h=-Math.sin(e*Math.PI)*n*.15}else h=0;c=!1!==i.landingImpact?t<.3?1-(1-.8*a)*(1-t/.3):.8*a+(t-.3)/.7*(1-.8*a):a+(1-a)*t}return{position:[0,h,0],rotation:[u,0,0],scale:c}}}};function fe(e){const t=A[e];if(!t)throw new Error(`Invalid jump direction: ${e}`);const i="up"===e||"down"===e;return{name:`jump${D(e)}`,emoji:"up"===e?"๐ฆ":"down"===e?"๐ฅ":"left"===e?"โฌ
๏ธ":"โก๏ธ",type:"override",description:`Jump ${e} with squash & stretch`,config:{duration:800,musicalDuration:{musical:!0,beats:2},jumpDistance:60,squashAmount:.8,stretchAmount:1.2,anticipation:.2,hangTime:.1,landingImpact:!0,easing:"quad",strength:1,direction:e,particleMotion:{type:"jump",strength:.9,jumpDistance:60,squash:.8,stretch:1.2}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},phaseSync:{anticipation:"eighth",jump:"beat",landing:"sixteenth"},distanceSync:{onBeat:1.5,offBeat:.8,accent:2,curve:"exponential"},deformationSync:{squashOnBeat:.6,stretchOnBeat:1.4,timing:"anticipatory"},dynamics:{forte:{jumpDistance:80,stretch:1.3},piano:{jumpDistance:30,stretch:1.1}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.jump={startX:e.x,startY:e.y,startSize:e.size,originalVx:e.vx,originalVy:e.vy,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.jump?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.jump,h={...this.config,...n},c=n.strength||1,u=h.jumpDistance*c*e.scaleFactor,d=h.squashAmount,g=h.stretchAmount,m=h.anticipation,p=1-.5*h.anticipation;if(s<m){const n=s/m,a=this.easeOutQuad(n);e.size=l.startSize*(1-(1-d)*a),i?e.y=l.startY-t.y*a*5*e.scaleFactor:e.x=l.startX-t.x*a*5*e.scaleFactor,e.vx=0,e.vy=0}else if(s<p){const n=(s-m)/(p-m);let a=Math.sin(n*Math.PI);if(h.hangTime>0&&n>.4&&n<.6){const e=(n-.4)/.2;a=.95+.05*this.easeInOutCubic(e)}if(i?(e.y=l.startY+t.y*a*u,e.x=l.startX+3*Math.sin(n*Math.PI*2)):(e.x=l.startX+t.x*a*u,e.y=l.startY-Math.sin(n*Math.PI)*u*.3),n<.5){const t=2*n;e.size=l.startSize*(d+(g-d)*t)}else{const t=2*(n-.5);e.size=l.startSize*(g-(g-1)*t*.8)}i?(e.vy=t.y*Math.cos(n*Math.PI)*u*.1,e.vx=0):(e.vx=t.x*Math.cos(n*Math.PI)*u*.1,e.vy=-Math.cos(n*Math.PI)*u*.05)}else{const t=(s-p)/(1-p),i=this.easeOutBounce(t);if(e.x=l.startX,e.y=l.startY,h.landingImpact)if(t<.3){const i=t/.3;e.size=l.startSize*(1-(1-.8*d)*(1-i))}else{const i=(t-.3)/.7;e.size=l.startSize*(.8*d+(1-.8*d)*i)}else e.size=l.startSize*(d+(1-d)*i);e.vx=l.originalVx*i,e.vy=l.originalVy*i}},cleanup(e){if(e.gestureData?.jump){const t=e.gestureData.jump;e.size=t.startSize,e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.jump}},easeOutQuad:e=>e*(2-e),easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutBounce(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375},"3d":{evaluate(e,s){const n=s.config||s||{},a=s.strength||1,r=.004*(n.jumpDistance||60)*a,o=n.squashAmount||.8,l=n.stretchAmount||1.2,h=n.anticipation||.2,c=1-.5*h;let u=0,d=0,g=1,m=0,p=0,f=0;if(e<h){const s=e/h,n=s*(2-s);g=1-(1-o)*n,i?d=-t.y*n*.02:u=-t.x*n*.02}else if(e<c){const s=(e-h)/(c-h),n=Math.sin(s*Math.PI);i?d=t.y*n*r:(u=t.x*n*r,d=Math.sin(s*Math.PI)*r*.3),g=s<.5?o+2*s*(l-o):l-2*(s-.5)*(l-1)*.8,i?m=t.y*Math.sin(s*Math.PI)*.1:(p=t.x*Math.sin(s*Math.PI)*.15,f=-t.x*Math.sin(s*Math.PI)*.05)}else{const s=(e-c)/(1-c);if(s<.5){const e=2*s;i?d=-t.y*Math.sin(e*Math.PI)*r*.15:u=-t.x*Math.sin(e*Math.PI)*r*.1}g=!1!==n.landingImpact?s<.3?1-(1-.8*o)*(1-s/.3):.8*o+(s-.3)/.7*(1-.8*o):o+(1-o)*s}return{cameraRelativePosition:[u,d,0],rotation:[m,p,f],scale:g}}}}}var ye=fe("down"),be=fe("left"),ve=fe("right");function Me(e){if(!["forward","back","left","right","up","down"].includes(e))throw new Error(`Invalid rush direction: ${e}`);return{name:`rush${D(e)}`,emoji:{forward:"๐จ",back:"๐",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ"}[e],type:"override",description:{forward:"Quick rush toward camera",back:"Quick retreat away",left:"Quick strafe left",right:"Quick strafe right",up:"Quick leap upward",down:"Quick dive downward"}[e],config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1,direction:e,particleMotion:{type:"rush",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"forward";let a=0,r=0,o=0,l=0,h=0,c=1,u=1,d=0;const g={forward:{x:0,y:0,z:1,lean:{x:.2,z:0}},back:{x:0,y:0,z:-1,lean:{x:-.2,z:0}},left:{x:-1,y:0,z:0,lean:{x:0,z:.2}},right:{x:1,y:0,z:0,lean:{x:0,z:-.2}},up:{x:0,y:1,z:0,lean:{x:-.15,z:0}},down:{x:0,y:-1,z:0,lean:{x:.2,z:0}}}[n],m=.2;if(e<.2){const t=e/.2,i=1-Math.pow(1-t,2);l=i*g.lean.x*s,h=i*g.lean.z*s,r="up"===n?.03*-i*s:.02*-i*s,u=1+.3*i}else if(e<.6){const t=(e-.2)/.4,i=1-Math.pow(1-t,3);a=g.x*i*m*s,r=g.y*i*m*s,o=g.z*i*m*s,"up"===n?r+=.05*i*s:"down"!==n&&(r+=(.04*i-.02)*s),l=g.lean.x*s,h=g.lean.z*s,c=1+.08*i,u=1.3+.5*i,d=.35*i,h+=Math.sin(t*Math.PI*12)*(1-t)*.015*s}else{const t=(e-.6)/.4,i=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;if(a=g.x*m*(1-i)*s,r=g.y*m*(1-i)*s,o=g.z*m*(1-i)*s,l=g.lean.x*(1-i)*s,h=g.lean.z*(1-i)*s,c=1.08-.08*i,t>.7){const e=(t-.7)/.3;r-=.02*Math.sin(e*Math.PI)*s}u=1.8-.8*i,d=.35*(1-i)}return{cameraRelativePosition:[a,r,o],cameraRelativeRotation:[l,0,h],scale:c,glowIntensity:u,glowBoost:d}}}}}var we={name:"lunge",emoji:"๐คบ",type:"override",description:"Forward thrust lunge with emphasis",config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,direction:"forward",recover:!0,strength:1,particleMotion:{type:"lunge",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.25,a=!1!==i.recover;let r;e<.3?(r=e/.3,r=1-Math.pow(1-r,3)):e<.6?r=1:a?(r=1-(e-.6)/.4,r=Math.pow(r,2)):r=1;const o=r*n*s;return{position:[0,.05*-Math.sin(r*Math.PI)*s,o],rotation:[.2*r*s,0,0],scale:1+.1*r*s,glowIntensity:1+.3*r,glowBoost:e<.4?.4*r:0}}}};function Se(e){if(!{...A,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[e])throw new Error(`Invalid lunge direction: ${e}`);return{name:`lunge${D(e)}`,emoji:{forward:"๐คบ",back:"๐",left:"๐",right:"๐",up:"โ๏ธ",down:"๐"}[e]||"๐คบ",type:"override",description:`Lunge thrust ${e}`,config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,recover:!0,strength:1,direction:e,particleMotion:{type:"lunge",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.25,a=!1!==i.recover,r=i.direction||"forward";let o;e<.3?(o=e/.3,o=1-Math.pow(1-o,3)):e<.6?o=1:a?(o=1-(e-.6)/.4,o=Math.pow(o,2)):o=1;let l=0,h=0,c=0,u=0,d=0;switch(r){case"forward":c=o*n*s,u=.2*o*s,h=.05*-Math.sin(o*Math.PI)*s;break;case"back":c=-o*n*s,u=.2*-o*s,h=.05*-Math.sin(o*Math.PI)*s;break;case"left":l=-o*n*s,d=.2*-o*s,h=.03*-Math.sin(o*Math.PI)*s;break;case"right":l=o*n*s,d=.2*o*s,h=.03*-Math.sin(o*Math.PI)*s;break;case"up":h=o*n*s,u=.15*-o*s;break;case"down":h=-o*n*s,u=.25*o*s}return{cameraRelativePosition:[l,h,c],cameraRelativeRotation:[u,0,d],scale:1+.1*o*s,glowIntensity:1+.3*o,glowBoost:e<.4?.4*o:0}}}}}var xe={name:"spin",emoji:"๐",type:"override",description:"Orbital rotation around center point",config:{duration:600,musicalDuration:{musical:!0,beats:1},rotations:1,direction:"random",radiusMultiplier:1,spiralOut:!1,accelerate:!0,maintainDistance:!0,scaleAmount:.1,easing:"linear",strength:.7,particleMotion:{type:"spin",strength:.7,rotations:1,radius:1}},rhythm:{enabled:!0,syncMode:"bar",rotationSync:{mode:"bars",rotationsPerBar:1,accelerateOnBeat:!0},radiusSync:{subdivision:"quarter",expandOnBeat:1.2,contractOffBeat:.9,curve:"bounce"},durationSync:{mode:"beats",beats:4},patternOverrides:{waltz:{rotationSync:{rotationsPerBar:.75},radiusSync:{curve:"ease"}},swing:{rotationSync:{accelerateOnBeat:!1},direction:"alternating"},dubstep:{radiusSync:{subdivision:"eighth",expandOnBeat:1.5,dropMultiplier:2},spiralOut:!0},breakbeat:{rotationSync:{mode:"random",range:[.5,2]},direction:"random"}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;let r=t.direction||this.config.direction;"random"===r&&(r=Math.random()<.5?"clockwise":"counter-clockwise"),e.gestureData.spin={startAngle:Math.atan2(a,n),startRadius:Math.sqrt(n*n+a*a)||30,originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,direction:r,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.spin?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.spin,o={...this.config,...i},l=i.strength||1;let{rotations:h}=o,{radiusMultiplier:c}=o;i.rhythmModulation&&(i.rhythmModulation.rotationMultiplier&&(h*=i.rhythmModulation.rotationMultiplier),i.rhythmModulation.radiusMultiplier&&(c*=i.rhythmModulation.radiusMultiplier));let u=t;o.accelerate&&(u=t<.5?.5*this.easeInQuad(2*t):.5+.5*this.easeOutQuad(2*(t-.5)));const d=h*Math.PI*2*l,g="counter-clockwise"===r.direction?-1:1,m=r.startAngle+d*u*g;let p=r.startRadius;o.spiralOut&&(p*=1+.5*t),1!==c&&(p*=1+(c-1)*Math.sin(t*Math.PI));const f=n+Math.cos(m)*p,y=a+Math.sin(m)*p;if(e.x+=.25*(f-e.x),e.y+=.25*(y-e.y),e.vx=.5*(f-e.x),e.vy=.5*(y-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.spin){const t=e.gestureData.spin;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.spin}},easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const i=t?.config||t||{},s=t?.strength||1,n=t?.particle;let a=1;n?.gestureData?.spin?a="counter-clockwise"===n.gestureData.spin.direction?-1:1:"counter-clockwise"!==i.direction&&"left"!==i.direction||(a=-1);let r=e;return!1!==i.accelerate&&(r=e<.5?e*e*4*.5:.5+(e-.5)*(2-(e-.5))*.5),{position:[0,0,0],rotation:[0,(i.rotations||1)*Math.PI*2*s*r*a,0],scale:1+(i.scaleAmount||.1)*Math.sin(e*Math.PI)*s}}}};const Ce={left:"counter-clockwise",right:"clockwise"};function ke(e){const t=Ce[e];if(!t)throw new Error(`Invalid spin direction: ${e}`);const i="left"===e?-1:1;return{name:`spin${D(e)}`,emoji:"left"===e?"โบ":"โป",type:"override",description:`Spin ${t}`,config:{duration:600,rotations:1,direction:t,radiusMultiplier:1,spiralOut:!1,accelerate:!0,maintainDistance:!0,scaleAmount:.1,strength:.7},rhythm:{enabled:!0,syncMode:"bar",timingSync:"nextBeat",interruptible:!1,priority:7,blendable:!1,durationSync:{mode:"beats",beats:4},rotationSync:{mode:"bars",rotationsPerBar:1,accelerateOnBeat:!0}},initialize(e,i,s,n){e.gestureData||(e.gestureData={});const a=e.x-s,r=e.y-n;e.gestureData.spin={startAngle:Math.atan2(r,a),startRadius:Math.sqrt(a*a+r*r)||30,originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,direction:t,initialized:!0}},apply(e,t,s,n,a,r){e.gestureData?.spin?.initialized||this.initialize(e,s,a,r);const o=e.gestureData.spin,l={...this.config,...s},h=s.strength||1;let{rotations:c,radiusMultiplier:u}=l;s.rhythmModulation&&(s.rhythmModulation.rotationMultiplier&&(c*=s.rhythmModulation.rotationMultiplier),s.rhythmModulation.radiusMultiplier&&(u*=s.rhythmModulation.radiusMultiplier));let d=t;l.accelerate&&(d=t<.5?.5*this.easeInQuad(2*t):.5+.5*this.easeOutQuad(2*(t-.5)));const g=c*Math.PI*2*h,m=o.startAngle+g*d*i;let p=o.startRadius;l.spiralOut&&(p*=1+.5*t),1!==u&&(p*=1+(u-1)*Math.sin(t*Math.PI));const f=a+Math.cos(m)*p,y=r+Math.sin(m)*p;if(e.x+=.25*(f-e.x),e.y+=.25*(y-e.y),e.vx=.5*(f-e.x),e.vy=.5*(y-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+o.originalVx*(1-i),e.vy=e.vy*i+o.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.spin){const t=e.gestureData.spin;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.spin}},easeInQuad:e=>e*e,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const s=t?.config||t||{},n=t?.strength||1;let a=e;return!1!==s.accelerate&&(a=e<.5?e*e*4*.5:.5+(e-.5)*(2-(e-.5))*.5),{position:[0,0,0],rotation:[0,(s.rotations||1)*Math.PI*2*n*a*i,0],scale:1+(s.scaleAmount||.1)*Math.sin(e*Math.PI)*n}}}}}var Pe=ke("left"),Te=ke("right"),Ee={name:"flip",emoji:"๐คธ",type:"override",description:"Front flip rotation with arc trajectory",config:{duration:800,musicalDuration:{musical:!0,beats:2},rotations:1,height:.3,direction:"forward",strength:1,particleMotion:{type:"flip",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotations||1,a=i.height||.3,r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*(2*-Math.PI*n),o=Math.sin(e*Math.PI)*a*s;let l=1;if(e<.1)l=1-e/.1*.15;else if(e<.2)l=.85+(e-.1)/.1*.2;else if(e>.9){const t=(e-.9)/.1;l=1.05-.1*Math.sin(t*Math.PI)}else l=1.05;return e>=.99&&(l=1),{position:[0,o,0],rotation:[r,0,0],scale:l,glowIntensity:1+.4*Math.sin(e*Math.PI),glowBoost:e>.2&&e<.8?.3:0}}}},Ae={name:"backflip",emoji:"โฌ๏ธ",type:"override",description:"Backwards flip with dramatic arc trajectory",config:{duration:900,musicalDuration:{musical:!0,beats:2},rotations:1,height:.35,strength:1,particleMotion:{type:"backflip",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotations||1,a=i.height||.35,r=(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)*(2*Math.PI*n),o=Math.sin(e*Math.PI)*a*s,l=.1*Math.sin(e*Math.PI)*s;let h=1;if(e<.1)h=1-e/.1*.15;else if(e<.2)h=.85+(e-.1)/.1*.25;else if(e>.9){const t=(e-.9)/.1;h=1.1-.15*Math.sin(t*Math.PI)}else h=1.1;return e>=.99&&(h=1),{position:[0,o,l],rotation:[r,0,0],scale:h,glowIntensity:1+.5*Math.sin(e*Math.PI),glowBoost:.4*Math.sin(e*Math.PI)}}}},De={name:"point",emoji:"๐",type:"blending",description:"Directional pointing motion with forward momentum",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},amplitude:15,direction:"right",strength:.8,particleMotion:{type:"point",direction:"right",strength:.8}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.6},patternOverrides:{march:{amplitudeSync:{onBeat:2,offBeat:.5,curve:"pulse"}},swing:{amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"bounce"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.point={startX:e.x,startY:e.y,startVx:e.vx,startVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.point?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=this.easeInOutCubic(t);let h=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1);const c=Math.sin(l*Math.PI);let u=0,d=0;switch(r.direction||"right"){case"right":u=1;break;case"left":u=-1;break;case"up":d=-1;break;case"down":d=1}if(e.vx+=c*h*.02*s*u,e.vy+=c*h*.02*s*d,t>.9){const i=1-10*(t-.9);e.vx=e.vx*(.95+.05*i),e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.point&&delete e.gestureData.point},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||15,n=i.strength||.8,a=i.direction||"right",r=.005*s*n,o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI);let h=0,c=0;switch(a){case"right":h=l*r,c=.25*l;break;case"left":h=-l*r,c=.25*-l;break;case"up":case"down":c=0}return{position:[h,0,0],rotation:[0,c,0],scale:1}}}};function _e(e){const t=A[e];if(!t)throw new Error(`Invalid point direction: ${e}`);const i="up"===e||"down"===e;return{name:`point${D(e)}`,emoji:"up"===e?"โ๏ธ":"down"===e?"๐":"left"===e?"๐":"๐",type:"blending",description:`Point ${e} with extension and return`,config:{duration:500,amplitude:15,strength:.8,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"ease"},accentResponse:{enabled:!0,multiplier:1.6}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.point={startX:e.x,startY:e.y,initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.point?.initialized||this.initialize(e,s);const o={...this.config,...s},l=o.strength||.8,h=this.easeInOutCubic(i);let c=o.amplitude*l*e.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI);if(e.vx+=u*c*.02*n*t.x,e.vy+=u*c*.02*n*-t.y,i>.9){const t=1-10*(i-.9);e.vx*=.95+.05*t,e.vy*=.95+.05*t}},cleanup(e){e.gestureData?.point&&delete e.gestureData.point},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,s){const n=s||{},a=.005*(n.amplitude||15)*(n.strength||.8),r=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,o=Math.sin(r*Math.PI),l=t.x*o*a,h=t.y*o*a;let c=0,u=0,d=0;return i?c=t.y*o*.2:(u=t.x*o*.25,d=-t.x*o*.1),{cameraRelativePosition:[l,h,0],rotation:[c,u,d],scale:1}}}}}var Ie=_e("up"),Re=_e("down"),Be=_e("left"),ze=_e("right");function Fe(e){if("left"!==e&&"right"!==e)throw new Error(`Invalid kick direction: ${e}. Only 'left' and 'right' are supported.`);const t=A[e];return{name:`kick${D(e)}`,emoji:"left"===e?"๐ฆต":"๐ฆถ",type:"blending",description:`Quick kick ${e} with snap return`,config:{duration:400,amplitude:30,strength:.8,direction:e},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:5,blendable:!0,durationSync:{mode:"beats",beats:1},amplitudeSync:{onBeat:1.5,offBeat:.7,curve:"snap"},accentResponse:{enabled:!0,multiplier:1.5}},apply(e,i,s,n,a,r){const o={...this.config,...s};let l,h=o.amplitude*o.strength*e.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1),l=i<.25?this.easeOutQuad(i/.25):i<.5?1:1-this.easeInQuad((i-.5)/.5);const c=t.x*h*l*.012*n,u=t.y*h*l*.012*n;e.vx+=c,e.vy+=u},cleanup(e){},easeOutQuad:e=>1-(1-e)*(1-e),easeInQuad:e=>e*e,"3d":{evaluate(e,i){const s=i||{},n=s.amplitude||30,a=s.strength||.8;let r,o=.008*n*a;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),e<.25)r=1-(1-e/.25)*(1-e/.25);else if(e<.5)r=1;else{const t=(e-.5)/.5;r=1-t*t}const l=.15*r*a;return{cameraRelativePosition:[t.x*o*r,t.y*o*r*.3,0],rotation:[.08*r*a,0,t.x*l],scale:1+.05*r}}}}}var Oe=Fe("left"),Le=Fe("right"),qe={name:"bow",emoji:"๐",type:"override",description:"Graceful forward bow of respect",config:{duration:1200,musicalDuration:{musical:!0,beats:3},depth:.4,holdTime:.4,graceful:!0,strength:1,particleMotion:{type:"bow",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.depth||.4,a=i.holdTime||.4;let r;const o=.4*(1-a),l=1-.6*(1-a);return e<o?(r=e/o,r=Math.sin(r*Math.PI/2)):e<l?r=1:(r=1-(e-l)/(1-l),r=Math.sin(r*Math.PI/2)),{cameraRelativePosition:[0,.1*-r*s,.05*-r*s],cameraRelativeRotation:[r*n*Math.PI*s,0,0],scale:1,glowIntensity:1-.2*r,glowBoost:0}}}},Ge={name:"nod",emoji:"๐",type:"blending",description:"Vertical nodding motion",config:{duration:500,amplitude:15,frequency:2,easing:"sine",strength:.4,particleMotion:{type:"bounce",axis:"vertical",strength:.4,frequency:2,phase:0}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!1,priority:5,blendable:!1,minDuration:"halfBar",frequencySync:{mode:"subdivision",subdivision:"half",multiplier:1},amplitudeSync:{onBeat:1.4,offBeat:.8,curve:"ease"},durationSync:{mode:"beats",beats:2},patternOverrides:{waltz:{frequencySync:{subdivision:"quarter"},amplitudeSync:{onBeat:1.6,curve:"ease"}},swing:{amplitudeSync:{onBeat:1.5,offBeat:.9}},dubstep:{amplitudeSync:{onBeat:1.2,dropBeat:3,curve:"pulse"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.nod={startY:e.y,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.nod?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1;let{frequency:l}=r,{amplitude:h}=r;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const c=Math.sin(t*Math.PI*2*l);h=h*o*e.scaleFactor,e.vy+=c*h*.01*s,t>.9&&(e.vy*=.95)},cleanup(e){e.gestureData?.nod&&delete e.gestureData.nod},"3d":{evaluate(e,t){const i={...this.config,...t};let{amplitude:s}=i;t.rhythmModulation&&(s*=t.rhythmModulation.amplitudeMultiplier||1,s*=t.rhythmModulation.accentMultiplier||1);let n=0;if(e<.4){const t=e/.4;n=.12*Math.sin(t*Math.PI)}else if(e<.8){const t=(e-.4)/.4;n=.07*Math.sin(t*Math.PI)}return n*=s/15,{cameraRelativePosition:[0,0,n],scale:1-.3*Math.abs(n),glowIntensity:1+.5*Math.abs(n)}}}},He={name:"reach",emoji:"๐",type:"blending",description:"Upward reaching motion with scale increase",config:{duration:1400,musicalDuration:{musical:!0,beats:2},amplitude:25,strength:.9,scaleMax:1.05,particleMotion:{type:"reach",strength:.9,scaleMax:1.05}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",interruptible:!0,priority:4,blendable:!0,crossfadePoint:"anyBeat",amplitudeSync:{onBeat:1.4,offBeat:.9,curve:"ease"},durationSync:{mode:"beats",beats:2},accentResponse:{enabled:!0,multiplier:1.5},patternOverrides:{uplifting:{amplitudeSync:{onBeat:1.8,offBeat:.7,curve:"ease"},durationSync:{beats:3}},ambient:{amplitudeSync:{onBeat:1.2,offBeat:1,curve:"linear"}}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.reach={startY:e.y,startVy:e.vy,originalSize:e.size,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.reach?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||this.config.strength||1,l=r.scaleMax||this.config.scaleMax||1.05,h=this.easeInOutCubic(t);let c=r.amplitude*o*e.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI);e.vy-=u*c*.015*s;const d=1+u*(l-1);if(e.size=e.baseSize*d,t>.9){const i=1-10*(t-.9);e.vy=e.vy*(.95+.05*i)}},cleanup(e){e.gestureData?.reach&&(e.gestureData.reach.originalSize?e.size=e.gestureData.reach.originalSize:e.size=e.baseSize,delete e.gestureData.reach)},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t||{},s=i.amplitude||25,n=i.strength||.9,a=i.scaleMax||1.05,r=.004*s*n,o=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,l=Math.sin(o*Math.PI);return{position:[0,l*r,0],rotation:[.1*l,0,0],scale:1+l*(a-1)}}}},je={name:"headBob",emoji:"๐ง",type:"additive",description:"Rhythmic vertical bobbing to music",config:{duration:600,musicalDuration:{musical:!0,beats:1},amplitude:12,frequency:2,strength:1,damping:.1,easing:"linear",particleMotion:{type:"headBob",strength:1,amplitude:12,frequency:2}},rhythm:{enabled:!0,syncMode:"beat",frequencySync:{subdivision:"eighth",bobsPerBeat:2},amplitudeSync:{onBeat:1.3,offBeat:1,curve:"pulse"},durationSync:{mode:"beats",beats:1}},apply(e,t,i,s,n,a,r){const o=(i.amplitude||this.config.amplitude)*n,l=i.frequency||this.config.frequency,h=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*2*l)*o*h;e.vy+=.5*c;const u=Math.cos(s*Math.PI*2*l*1.5)*o*.05*h;e.vx+=.2*u},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.amplitude||12,a=e<.15?e/.15:Math.pow(1-(e-.15)/.85,2),r=n/12*s;return{cameraRelativePosition:[0,0,.08*a*r],position:[0,.015*-a*r,0],scale:1-.05*a,glowIntensity:1+.15*a}}}},$e={name:"crouch",emoji:"๐ฆ",type:"override",description:"Compress down into a low crouch position",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},depth:.3,widen:.2,holdTime:.5,strength:1,particleMotion:{type:"crouch",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.depth||.3,a=i.widen||.2;let r;const o=(1-(i.holdTime||.5))/2,l=1-o;return r=e<o?e/o:e<l?1:1-(e-l)/o,r=Math.sin(r*Math.PI/2),{position:[0,-r*n*s,0],rotation:[.15*r*s,0,0],scale:(1+r*a*s+(1-.25*r*s))/2,glowIntensity:1-.3*r,glowBoost:0}}}},We={name:"tilt",emoji:"๐ค",type:"override",description:"Gather particles then tilt as unified group",config:{duration:500,musicalDuration:{musical:!0,beats:1},gatherPhase:.2,tiltAngle:45,swayAmount:80,liftAmount:60,frequency:3,homeRadius:20,easing:"sine",strength:2.5,particleMotion:{type:"tilt",strength:2.5,frequency:3,swayAmount:80,liftAmount:60},smoothness:.25},rhythm:{enabled:!0,syncMode:"swing",durationSync:{mode:"beats",beats:1},angleSync:{onBeat:45,offBeat:-30,swing:15,subdivision:"triplet",curve:"ease-in-out"},gatherSync:{beatsBefore:.5,releaseAfter:.25,intensity:"dynamic"},swaySync:{verse:60,chorus:100,bridge:80,syncopated:!0},liftSync:{upOnTilt:!0,heightOnAccent:80,normalHeight:40,curve:"bounce"},dynamics:{forte:{tiltAngle:60,swayAmount:120,frequency:4},piano:{tiltAngle:20,swayAmount:40,frequency:2}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=Math.random(),h=({...this.config,...t}.homeRadius+20*Math.random())*e.scaleFactor;e.gestureData.tilt={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,angle:r,distance:o,homeRadius:h,homeX:i+Math.cos(r)*h,homeY:s+Math.sin(r)*h,role:l,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.tilt?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.tilt,o={...this.config,...i},l=i.strength||1;let h,c;if(t<o.gatherPhase){const i=t/o.gatherPhase,s=this.easeInOutCubic(i);h=r.startX+(r.homeX-r.startX)*s,c=r.startY+(r.homeY-r.startY)*s;const n=.6;e.x+=(h-e.x)*n,e.y+=(c-e.y)*n}else{const i=(t-o.gatherPhase)/(1-o.gatherPhase)*Math.PI*o.frequency,s=Math.sin(i),u=o.tiltAngle*Math.PI/180*l,d=r.angle+s*u,g=Math.abs(s)*o.liftAmount*e.scaleFactor,m=r.homeRadius+g;h=n+Math.cos(d)*m,c=a+Math.sin(d)*m-.3*g;const p=o.smoothness+.1*r.role;e.x+=(h-e.x)*p,e.y+=(c-e.y)*p;const f=-Math.sin(d),y=Math.cos(d);e.vx=f*s*2,e.vy=y*s*2}if(t<o.gatherPhase&&(e.vx=.25*(h-e.x),e.vy=.25*(c-e.y)),t>.9){const i=10*(1-t),s=r.startX+(e.x-r.startX)*i,n=r.startY+(e.y-r.startY)*i;e.x=s,e.y=n,e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.tilt){const t=e.gestureData.tilt;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.tilt}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||1,n=i.gatherPhase||.2,a=i.frequency||3,r=i.tiltAngle||45;let o=0;if(e>=n){const t=(e-n)/(1-n)*Math.PI*a;o=Math.sin(t)*(r*Math.PI/180*s*.4)}return{position:[0,0,0],rotation:[0,0,o],scale:1}}}};function Ue(e){const t=A[e];if(!t)throw new Error(`Invalid tilt direction: ${e}`);const i="up"===e||"down"===e;return{name:`tilt${D(e)}`,emoji:"up"===e?"๐ญ":"down"===e?"๐":"left"===e?"๐ค":"๐ง",type:"override",description:`Tilt ${e} with curious expression`,config:{duration:500,musicalDuration:{musical:!0,beats:1},gatherPhase:.2,tiltAngle:45,tiltAmount:40,holdPhase:.4,homeRadius:20,easing:"sine",strength:1,direction:e,smoothness:.25,particleMotion:{type:"tilt",strength:1,tiltAmount:40}},rhythm:{enabled:!0,syncMode:"swing",durationSync:{mode:"beats",beats:1},angleSync:{onBeat:45,offBeat:30,subdivision:"triplet",curve:"ease-in-out"},gatherSync:{beatsBefore:.5,releaseAfter:.25,intensity:"dynamic"},dynamics:{forte:{tiltAngle:60,tiltAmount:60},piano:{tiltAngle:25,tiltAmount:25}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=({...this.config,...t}.homeRadius+20*Math.random())*e.scaleFactor;e.gestureData.tilt={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,angle:r,distance:o,homeRadius:l,homeX:i+Math.cos(r)*l,homeY:s+Math.sin(r)*l,role:Math.random(),initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.tilt?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.tilt,h={...this.config,...n},c=n.strength||1;let u,d;if(s<h.gatherPhase){const t=s/h.gatherPhase,i=this.easeInOutCubic(t);u=l.startX+(l.homeX-l.startX)*i,d=l.startY+(l.homeY-l.startY)*i;const n=.6;e.x+=(u-e.x)*n,e.y+=(d-e.y)*n}else if(s<h.gatherPhase+h.holdPhase){const n=(s-h.gatherPhase)/h.holdPhase,a=this.easeOutCubic(Math.min(2*n,1)),r=h.tiltAmount*c*e.scaleFactor*a;i?(u=l.homeX,d=l.homeY+t.y*r):(u=l.homeX+t.x*r,d=l.homeY-Math.abs(t.x)*r*.2);const o=h.smoothness+.1*l.role;e.x+=(u-e.x)*o,e.y+=(d-e.y)*o,e.vx=.5*(u-e.x),e.vy=.5*(d-e.y)}else{const t=(s-h.gatherPhase-h.holdPhase)/(1-h.gatherPhase-h.holdPhase),i=this.easeInOutCubic(t);u=e.x+(l.startX-e.x)*i,d=e.y+(l.startY-e.y)*i,e.x=u,e.y=d,e.vx=l.originalVx*i,e.vy=l.originalVy*i}s<h.gatherPhase&&(e.vx=.25*(u-e.x),e.vy=.25*(d-e.y))},cleanup(e){if(e.gestureData?.tilt){const t=e.gestureData.tilt;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.tilt}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutCubic:e=>1-Math.pow(1-e,3),"3d":{evaluate(e,s){const n=s.config||s||{},a=s.strength||1,r=n.gatherPhase||.2,o=n.holdPhase||.4,l=n.tiltAngle||45,h=n.tiltAmount||40;let c=0,u=0,d=0,g=0,m=0;if(e<r);else if(e<r+o){const s=(e-r)/o,n=1-Math.pow(1-Math.min(2*s,1),3),p=l*Math.PI/180*a*.4*n,f=.004*h*a*n;i?(d=t.y*p,u=t.y*f):(m=-t.x*p,c=t.x*f*.5,g=t.x*p*.3)}else{const s=(e-r-o)/(1-r-o),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,p=l*Math.PI/180*a*.4*(1-n),f=.004*h*a*(1-n);i?(d=t.y*p,u=t.y*f):(m=-t.x*p,c=t.x*f*.5,g=t.x*p*.3)}return{cameraRelativePosition:[c,u,0],rotation:[d,g,m],scale:1}}}}}var Ve=Ue("up"),Ye=Ue("down"),Xe=Ue("left"),Ne=Ue("right");function Qe(e){if(!["left","right","front","back","up","down"].includes(e))throw new Error(`Invalid oof direction: ${e}`);return{name:`oof${D(e)}`,emoji:{left:"๐ค",right:"๐ค",front:"๐",back:"๐ซ",up:"๐ฅ",down:"๐ฅ"}[e],type:"override",description:{left:"Punched from left",right:"Punched from right",front:"Gut punch",back:"Kidney shot",up:"Uppercut",down:"Hammer fist"}[e],config:{duration:500,musicalDuration:{musical:!0,beats:1},intensity:1,strength:1,direction:e,particleMotion:{type:"oof",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1;let n,a;if(e<.25){const t=e/.25;n=t*(2-t)}else{const t=(e-.25)/.75;n=1-t*t}a=e<.1?e/.1:e<.4?1:1-(e-.4)/.6;const r=.2*s,o=.35*s;let l=0,h=0,c=0,u=0,d=0;let g=[0,0,.4];switch(i.direction||"front"){case"left":l=-n*r,d=n*o,g=[.4,0,0];break;case"right":l=n*r,d=-n*o,g=[-.4,0,0];break;case"front":c=-n*r,h=.03*-n,u=n*o*.7,g=[0,0,.4];break;case"back":c=n*r,u=-n*o*.6,g=[0,0,-.4];break;case"up":h=n*r,u=-n*o*.4,g=[0,.8,0];break;case"down":h=-n*r,u=n*o*.3,g=[0,-.8,0]}let m=1,p=0;if(e<.15){const t=e/.15;m=1+.6*(1-t),p=.4*(1-t)}return{cameraRelativePosition:[l,h,c],cameraRelativeRotation:[u,0,d],scale:1,glowIntensity:m,glowBoost:p,deformation:{enabled:!0,strength:a*s*2,impactPoint:g,falloffRadius:.5}}}}}}var Je={name:"recoil",emoji:"๐ฑ",type:"override",description:"Snap backwards in shock or surprise",config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,particleMotion:{type:"recoil",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.2,a=i.intensity||1,r=!1!==i.recover;let o;return e<.15?(o=e/.15,o=1-Math.pow(1-o,4)):e<.4?o=1:r?(o=1-(e-.4)/.6,o=Math.pow(o,.5)):o=1,{position:[0,.05*o*s,-o*n*s*a],rotation:[.25*-o*s*a,0,0],scale:1-.1*o*a,glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.5:0}}}};function Ke(e){if(!{...A,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[e])throw new Error(`Invalid recoil direction: ${e}`);return{name:`recoil${D(e)}`,emoji:{back:"๐ฑ",forward:"๐ต",left:"๐ฐ",right:"๐ฐ",up:"๐ฒ",down:"๐จ"}[e]||"๐ฑ",type:"override",description:`Recoil ${e} in shock`,config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,direction:e,particleMotion:{type:"recoil",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.distance||.2,a=i.intensity||1,r=!1!==i.recover,o=i.direction||"back";let l;e<.15?(l=e/.15,l=1-Math.pow(1-l,4)):e<.4?l=1:r?(l=1-(e-.4)/.6,l=Math.pow(l,.5)):l=1;let h=0,c=0,u=0,d=0,g=0;switch(o){case"back":u=-l*n*s*a,d=.25*-l*s*a,c=.05*l*s;break;case"forward":u=l*n*s*a,d=.25*l*s*a,c=.05*-l*s;break;case"left":h=-l*n*s*a,g=.2*l*s*a;break;case"right":h=l*n*s*a,g=.2*-l*s*a;break;case"up":c=l*n*s*a,d=.1*-l*s*a;break;case"down":c=-l*n*s*a,d=.3*l*s*a}return{cameraRelativePosition:[h,c,u],cameraRelativeRotation:[d,0,g],scale:1-.1*l*a,glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.5:0}}}}}var Ze={name:"knockdown",emoji:"๐ฅ",type:"override",description:"Quick knockdown with fast recovery",config:{duration:1500,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"knockdown",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.15){const t=e/.15,s=1-Math.pow(1-t,2);n=.1*s*i,a=.2*-s*i,l=1+.6*s,h=.5*s}else if(e<.4){const t=(e-.15)/.25,n=t*t;s=.2*-n*i,a=(.6*n-.2)*i,r=.3*n*i,t>.7&&(o=1-(t-.7)/.3*.1),l=1.6-.5*t,h=.5-.4*t}else if(e<.6){const t=(e-.4)/.2;s=-.2*i,a=.4*i,r=.3*i,r+=.02*Math.sin(t*Math.PI*2),o=.9,l=.8}else{const t=(e-.6)/.4,n=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;if(s=(.2*n-.2)*i,a=(.4-.4*n)*i,r=(.3-.3*n)*i,o=.9+.1*n,t>.7){const e=(t-.7)/.3;r+=.03*Math.sin(e*Math.PI*4)*(1-e)}l=.8+.2*n,t>.9&&(h=(t-.9)/.1*.2)}return{position:[0,s,n],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},et={name:"knockout",emoji:"๐ซ",type:"override",description:"Theatrical knockout with failed rise attempt, then recovery",config:{duration:4e3,musicalDuration:{musical:!0,bars:2},strength:1,particleMotion:{type:"knockout",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=0,l=1,h=1,c=0;if(e<.1){const t=e/.1,s=1-Math.pow(1-t,3);n=.15*s*i,a=.3*-s*i,h=1+.8*s,c=.6*s,o=.1*Math.sin(t*Math.PI*4)*s}else if(e<.25){const t=(e-.1)/.15,n=t*t;s=.25*-n*i,a=(.8*n-.3)*i,o=.4*n*i,t>.8&&(l=1-(t-.8)/.2*.15),h=1.8-.6*t,c=.6-.4*t}else if(e<.35){const t=(e-.25)/.1;s=-.25*i,a=.5*i,o=.4*i,o+=.03*Math.sin(t*Math.PI*6)*(1-t),l=.85,h=1-.3*t}else if(e<.45){const t=(e-.35)/.1,n=1-Math.pow(1-t,2);s=(.15*n-.25)*i,a=(.5-.3*n)*i,o=(.4-.2*n)*i,l=.85+.1*n,h=.7+.4*n}else if(e<.55){const t=(e-.45)/.1,n=t*t;s=(-.1-.15*n)*i,a=(.2+.35*n)*i,o=(.2+.25*n)*i,l=.95-.12*n,t>.7&&(c=(t-.7)/.3*.3),h=1.1-.4*t}else if(e<.75){const t=(e-.55)/.2;s=-.25*i,a=.55*i,o=.45*i,l=.83;const n=.02*Math.sin(t*Math.PI*4)*Math.sin(t*Math.PI);o+=n,h=.6+2*n}else if(e<.9){const t=(e-.75)/.15,n=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;s=(.25*n-.25)*i,a=(.55-.55*n)*i,o=(.45-.45*n)*i,l=.83+.17*n,h=.6+.5*n}else{const t=(e-.9)/.1;s=0,a=0,o=Math.sin(t*Math.PI*6)*(1-t)*.08*i,r=Math.sin(t*Math.PI*8)*(1-t)*.1*i,l=1,h=1+.2*Math.sin(t*Math.PI*3)*(1-t),c=.2*Math.sin(t*Math.PI)}return{position:[0,s,n],rotation:[a,r,o],scale:l,glowIntensity:h,glowBoost:c}}}},tt={name:"inflate",emoji:"๐",type:"override",description:"Puff up dramatically like a balloon",config:{duration:800,musicalDuration:{musical:!0,beats:2},maxScale:1.4,holdTime:.3,deflate:!0,strength:1,particleMotion:{type:"inflate",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",strengthSync:{onBeat:1.3,offBeat:.8}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.maxScale||1.4,a=i.holdTime||.3,r=!1!==i.deflate;let o;const l=.5*(1-a),h=1-l;e<l?(o=e/l,o=1-Math.pow(1-o,2)):e<h||!r?o=1:(o=1-(e-h)/l,o=Math.pow(o,2));const c=1+(n-1)*o*s,u=.08*o*s,d=1+.4*o*s,g=.3*o,m=o>.8?.02*Math.sin(e*Math.PI*8):0;return{position:[m,u,0],rotation:[0,0,2*m],scale:c,glowIntensity:d,glowBoost:g}}}},it={name:"deflate",emoji:"๐จ",type:"override",description:"Shrink down sadly like a deflating balloon",config:{duration:1e3,musicalDuration:{musical:!0,beats:2.5},minScale:.6,droop:.15,reinflate:!0,strength:1,particleMotion:{type:"deflate",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2.5},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.minScale||.6,a=i.droop||.15,r=!1!==i.reinflate;let o;return e<.5?(o=e/.5,o=Math.pow(o,.7)):e<.7||!r?o=1:(o=1-(e-.7)/.3,o=Math.pow(o,1.5)),{position:[0,-o*a*s,0],rotation:[.15*o*s,0,.1*o*s],scale:1-(1-n)*o*s,glowIntensity:1-.4*o,glowBoost:0}}}},st={name:"squash",emoji:"๐ซ",type:"override",description:"Flatten horizontally like a cartoon impact",config:{duration:500,musicalDuration:{musical:!0,beats:1},squashAmount:.5,stretchAmount:1.5,bounce:!0,strength:1,particleMotion:{type:"squash",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.squashAmount||.5,a=i.stretchAmount||1.5,r=!1!==i.bounce;let o;if(e<.15)o=e/.15,o=1-Math.pow(1-o,3);else if(r){const t=(e-.15)/.85,i=Math.exp(4*-t);o=Math.cos(t*Math.PI*3)*i,o=Math.max(0,o)}else o=0;const l=1+o*(a-1)*s;return{position:[0,.15*-o*s,0],rotation:[0,0,0],scale:[l,1-o*(1-n)*s,l],glowIntensity:1+(e<.2?3*(.2-e):0),glowBoost:e<.15?.6:0}}}},nt={name:"stretch",emoji:"โ๏ธ",type:"override",description:"Scale particles along X and Y axes",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},scaleX:1.3,scaleY:.9,alternate:!1,elastic:!0,overshoot:.1,frequency:1,easing:"sine",strength:1,particleMotion:{type:"stretch",scaleX:1.8,scaleY:.6,strength:1},centerBased:!0,preserveArea:!1},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},scaleSync:{onBeat:{x:1.5,y:.7},offBeat:{x:.8,y:1.3},subdivision:"eighth",curve:"elastic"},alternateSync:{pattern:"XYXY",beatsPerChange:1,overlap:.1},overshootSync:{normal:.1,accent:.3,downbeat:.2,curve:"spring"},preservationSync:{verse:!0,chorus:!1,bridge:!0},dynamics:{forte:{scaleX:2,scaleY:.5,overshoot:.4},piano:{scaleX:1.1,scaleY:.95,overshoot:.05}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;e.gestureData.stretch={offsetX:n,offsetY:a,startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.stretch?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.stretch,o={...this.config,...i},l=i.strength||1;let h,c,{scaleX:u}=o,{scaleY:d}=o;if(o.preserveArea&&1!==u&&1!==d){const e=u*d,t=Math.sqrt(1/e);u*=t,d*=t}if(o.alternate)if(t<.5){const e=2*t;u=1+(u-1)*this.getElasticProgress(e,o),d=1+(1/u-1)*(o.preserveArea?1:0)}else{const e=2*(t-.5);u+=(1-u)*this.getElasticProgress(e,o),d=1+(d-1)*this.getElasticProgress(e,o)}else{const e=this.getElasticProgress(t,o);u=1+(u-1)*e*l,d=1+(d-1)*e*l}if(o.centerBased?(h=n+r.offsetX*u,c=a+r.offsetY*d):(h=r.startX*u,c=r.startY*d),e.x=h,e.y=c,e.vx=r.offsetX*(u-1)*l*.1,e.vy=r.offsetY*(d-1)*l*.1,t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},getElasticProgress(e,t){if(!t.elastic)return this.easeInOutCubic(e);if(0===e)return 0;if(1===e)return 1;const i=t.overshoot||.1;if(e<.5){const t=2*e;return.5*this.easeInElastic(t,i)}{const t=2*(e-.5);return.5+.5*this.easeOutElastic(t,i)}},cleanup(e){if(e.gestureData?.stretch){const t=e.gestureData.stretch;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.stretch}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeInElastic:(e,t)=>0===e?0:1===e?1:-Math.pow(2,10*(e-1))*Math.sin((e-1-.075)*(2*Math.PI)/.3)*(1+t),easeOutElastic:(e,t)=>0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((e-.075)*(2*Math.PI)/.3)*(1+t)+1,"3d":{evaluate(e,t){const{particle:i}=t;if(!i||!i.gestureData?.stretch)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=t.config||{},n=t.strength||1;let a,r=s.scaleX||1.3,o=s.scaleY||.9;if(s.preserveArea&&1!==r&&1!==o){const e=r*o,t=Math.sqrt(1/e);r*=t,o*=t}if(s.elastic){const t=s.overshoot||.1;if(e<.5){const i=2*e,s=.3,n=s/4;a=-Math.pow(2,10*(i-1))*Math.sin((i-1-n)*(2*Math.PI)/s)*(1+t)*.5}else{const i=2*(e-.5),s=.3,n=s/4;a=.5+.5*(Math.pow(2,-10*i)*Math.sin((i-n)*(2*Math.PI)/s)*(1+t)+1)}}else a=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;let l,h=1;if(e>.8){const t=(e-.8)/(1-.8);h=1-t*t*t}l=s.alternate?e<.5?2*e*.8:.8-2*(e-.5)*1.4:1*a*n;const c=1+l*h;return{position:[0,0,0],rotation:[0,0,.1*Math.sin(e*Math.PI*4)*a*h],scale:c}}}},at={name:"pancake",emoji:"๐ฅ",type:"override",description:"Extreme flatten and hold - cartoon pancake effect",config:{duration:1600,musicalDuration:{musical:!0,bars:1},squashAmount:.2,stretchAmount:2,holdRatio:.5,strength:1,particleMotion:{type:"pancake",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.squashAmount||.2,a=i.stretchAmount||2,r=.1+.6*(i.holdRatio||.5);let o=0,l=0;if(e<.1){const t=e/.1;o=1-Math.pow(1-t,2)}else if(e<r){o=1;const t=(e-.1)/(r-.1);l=Math.sin(t*Math.PI*4)*(1-t)*.02}else{const t=(e-r)/(1-r);if(o=1-(t<.3?t/.3*.3:.3+(t-.3)/.7*.7),t>.8){const e=(t-.8)/.2,i=.15*Math.sin(e*Math.PI);o=Math.max(0,o-i)}}const h=1+o*(a-1)*s;let c=1,u=0;return e<.15?(c=1+.8*(1-e/.15),u=.6*(1-e/.15)):e<r?(c=1.3,u=.2):c=1.3-(e-r)/(1-r)*.3,{position:[l*s,.2*-o*s,0],rotation:[0,0,2*l*s],scale:[h,1-o*(1-n)*s,h],glowIntensity:c,glowBoost:u}}}},rt={name:"rage",emoji:"๐ข",type:"override",description:"Barbarian rage - intense buildup and release",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"rage",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.2){const t=e/.2,o=t*t;n=.05*-o*i,a=.15*o*i;const h=Math.sin(80*e)*o*.02;r=h*i,s=.02*h*i,l=1+.3*o}else if(e<.6){const t=(e-.2)/.4,c=t*t;n=(-.05-.03*c)*i,a=(.15+.1*c)*i;const u=.02+.04*c,d=100+50*t,g=Math.sin(e*d)*u;r=g*i,s=.03*g*i,o=1+.1*c,l=1.3+.7*c,h=.5*c}else if(e<.8){const t=(e-.6)/.2;n=(.15*t-.08)*i,a=(.25-.4*t)*i,r=Math.sin(150*e)*(1-.5*t)*.05*i,o=1.1+.08*Math.sin(t*Math.PI),l=2-.3*t,h=.5+.3*Math.sin(t*Math.PI)}else{const t=(e-.8)/.2,s=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;n=(.07-.07*s)*i,a=(.15*s-.15)*i,r=Math.sin(50*e)*(1-s)*.02*i,o=1.1-.1*s,l=1.7-.7*s,h=.5*(1-s)}return{position:[s,n,0],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},ot={name:"fury",emoji:"๐ค",type:"override",description:"Quick fury burst - intense flash of anger",config:{duration:800,musicalDuration:{musical:!0,beats:2},strength:1,particleMotion:{type:"fury",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=1,o=1,l=0;if(e<.2){const t=e/.2,n=1-Math.pow(1-t,3);r=1+.15*n*i;const h=Math.sin(120*e)*n*.04;a=h*i,s=.02*h*i,o=1+1.2*n,l=.7*n}else if(e<.5){const t=(e-.2)/.3;r=1.15+.03*Math.sin(t*Math.PI*3);const h=.05*Math.sin(150*e)*(1-.3*t);a=h*i,s=.025*h*i,n=.1*Math.sin(t*Math.PI)*i,o=2.2-.3*t,l=.7-.2*t}else{const t=(e-.5)/.5,s=t*t;r=1.15-.15*s,a=Math.sin(80*e)*(1-s)*.03*i,n=.1*(1-s)*i,o=1.9-.9*s,l=.5*(1-s)}return{position:[s,0,0],rotation:[n,0,a],scale:r,glowIntensity:o,glowBoost:l}}}},lt={name:"battlecry",emoji:"๐ฃ",type:"override",description:"Warrior battlecry - inhale, expand, roar",config:{duration:1500,musicalDuration:{musical:!0,bars:1},strength:1,particleMotion:{type:"battlecry",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=1,l=1,h=0;if(e<.25){const t=e/.25,r=t*t;n=.08*r*i,a=.15*-r*i,s=.03*-r*i,o=1+.05*r,l=1+.4*r}else if(e<.4){const t=(e-.25)/.15;n=(.08+.02*t)*i,a=(-.15-.1*t)*i,s=(.05*t-.03)*i,o=1.05+.08*t,l=1.4+.5*t,h=.4*t}else if(e<.6){const t=(e-.4)/.2,c=1-Math.pow(1-t,3);n=(.1-.2*c)*i,a=(.4*c-.25)*i,s=(.02+.08*c)*i,o=1.13+.12*c,l=1.9+.6*c,h=.4+.4*c,r=Math.sin(t*Math.PI*20)*(1-t)*.02*i}else{const t=(e-.6)/.4,c=t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;n=-.1*(1-c)*i,a=.15*(1-c)*i,s=.1*(1-c)*i,o=1.25-.25*c,r=Math.sin(t*Math.PI*8)*(1-c)*.015*i,l=2.5-1.5*c,h=.8-.8*c}return{position:[0,s,n],rotation:[a,0,r],scale:o,glowIntensity:l,glowBoost:h}}}},ht={name:"charge",emoji:"๐",type:"override",description:"Bull charge - wind up and rush forward",config:{duration:1200,musicalDuration:{musical:!0,beats:3},strength:1,particleMotion:{type:"charge",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=0,a=0,r=0,o=0,l=1,h=1,c=0;if(e<.2){const t=e/.2,s=t*t;n=.08*-s*i,a=.1*s*i,r=.25*s*i,l=1-.05*s,h=1+.4*s}else if(e<.6){const t=(e-.2)/.4,s=1-Math.pow(1-t,2);a=(.1-.35*s)*i,r=(.25+.1*s)*i,n=(.06*s-.08)*i,l=.95+.15*s,h=1.4+.6*s,c=.4*s,o=Math.sin(t*Math.PI*10)*s*.02*i}else if(e<.85){const t=(e-.6)/.25;a=-.25*i,r=(.35-.1*t)*i;const n=Math.sin(t*Math.PI*15)*(1-t)*.04;o=n*i,s=.02*n*i,l=1.1+.05*Math.sin(t*Math.PI),h=2-.3*t,c=.4*(1-.5*t)}else{const t=(e-.85)/.15,s=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;a=-.25*(1-s)*i,r=.25*(1-s)*i,n=-.02*(1-s)*i,l=1.1-.1*s,h=1.7-.7*s,c=.2*(1-s)}return{cameraRelativePosition:[s,n,a],rotation:[r,0,o],scale:l,glowIntensity:h,glowBoost:c}}}},ct={name:"wobble",emoji:"๐ฅด",type:"override",description:"Unsteady circular wobbling motion",config:{duration:1500,musicalDuration:{musical:!0,beats:4},wobbleRadius:.08,wobbleAngle:.2,rotations:2,decay:.5,strength:1,particleMotion:{type:"wobble",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:4},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.wobbleRadius||.08,a=i.wobbleAngle||.2,r=i.rotations||2,o=i.decay||.5,l=e*r*Math.PI*2,h=1-o*e,c=Math.sin(l)*n*h*s,u=Math.cos(l)*n*h*s,d=Math.cos(l)*a*h*s,g=Math.sin(l)*a*h*s;return{position:[c,.02*Math.sin(2*l)*h*s,u],rotation:[d,0,g],scale:1+.05*Math.sin(2*l)*h,glowIntensity:1+.2*Math.sin(l)*h,glowBoost:0}}}},ut={name:"teeter",emoji:"โ๏ธ",type:"override",description:"Rock back and forth unstably like losing balance",config:{duration:1200,musicalDuration:{musical:!0,beats:3},tiltAngle:.25,frequency:3,irregularity:.3,strength:1,particleMotion:{type:"teeter",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.tiltAngle||.25,a=i.frequency||3,r=i.irregularity||.3,o=(Math.sin(e*a*Math.PI*2)+Math.sin(e*(a+1.7)*Math.PI*2)*r+Math.sin(e*(.5*a)*Math.PI*2)*r*.5)/(1+1.5*r),l=o*n*s*.7,h=Math.sin(e*a*Math.PI*2+.5)*n*s*.5;return{position:[.15*h,0,.1*l],rotation:[l,0,h],scale:1+.05*Math.abs(o),glowIntensity:1+.2*Math.abs(o),glowBoost:0}}}},dt={name:"rock",emoji:"๐ชจ",type:"override",description:"Gentle front-back rocking motion",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},rockAngle:.15,rockCycles:2,smooth:!0,strength:1,particleMotion:{type:"rock",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rockAngle||.15,a=e*(i.rockCycles||2)*Math.PI*2,r=Math.sin(a),o=r*n*s,l=.05*r*s;return{position:[0,.02*Math.abs(r)*s,l],rotation:[o,0,0],scale:1+.02*Math.sin(.5*a),glowIntensity:1+.1*r,glowBoost:0}}}},gt={name:"pendulum",emoji:"๐ฐ๏ธ",type:"override",description:"Swing side to side like a pendulum clock",config:{duration:1500,musicalDuration:{musical:!0,beats:4},swingAngle:.4,swings:2,damping:.3,strength:1,particleMotion:{type:"pendulum",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:4},timingSync:"onBeat"},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.swingAngle||.4,a=i.swings||2,r=i.damping||.3,o=e*a*Math.PI*2,l=1-r*e,h=Math.sin(o)*l,c=h*n*s;return{position:[.1*h*s,.03*-Math.abs(h)*s,0],rotation:[0,0,c],scale:1,glowIntensity:1+.15*Math.abs(h),glowBoost:0}}}};function mt(e){const t={front:{screenOffset:[0,0],screenDirection:[0,0],recoilDir:[0,0,-1]},back:{screenOffset:[0,0],screenDirection:[0,0],recoilDir:[0,0,1]},left:{screenOffset:[-.1,0],screenDirection:[1,0],recoilDir:[1,0,0]},right:{screenOffset:[.1,0],screenDirection:[-1,0],recoilDir:[-1,0,0]},up:{screenOffset:[0,.1],screenDirection:[0,-1],recoilDir:[0,-1,0]},down:{screenOffset:[0,-.1],screenDirection:[0,1],recoilDir:[0,1,0]}},i=t[e]||t.front;return{name:`crack${e.charAt(0).toUpperCase()+e.slice(1)}`,emoji:"๐",type:"override",category:"reactions",description:`Surface cracks spreading from ${e} impact`,config:{duration:2e3,strength:1,glowStrength:.3,holdTime:500},rhythm:{enabled:!0,syncMode:"accent",strengthSync:{onBeat:1.2,offBeat:.8}},"3d":{evaluate(e,t){const s={strength:1,glowStrength:.3,...t},{strength:n,glowStrength:a}=s,r=.03*Math.max(0,1-4*e)*n,{recoilDir:o}=i,l=e<.05;return{cameraRelativePosition:[o[0]*r,o[1]*r,o[2]*r],crack:{enabled:!0,trigger:l,amount:n,propagation:.8,screenOffset:i.screenOffset,screenDirection:i.screenDirection,glowStrength:a}}}}}}const pt=mt("front"),ft=mt("back"),yt=mt("left"),bt=mt("right"),vt=mt("up"),Mt=mt("down"),wt={name:"crackHeal",emoji:"โจ",type:"override",category:"reactions",description:"Heal and fade existing cracks",config:{duration:1500,glowStrength:.5},"3d":{evaluate(e,t){const i={duration:1500,...t},s=e<.05;return{cameraRelativePosition:[0,.02*Math.sin(e*Math.PI),0],crack:{enabled:!1,heal:!0,healTrigger:s,healDuration:i.duration},glowBoost:.1*Math.sin(e*Math.PI)}}}};var St={name:"shatter",emoji:"๐ฅ",type:"override",description:"Particles explode outward then freeze like shattered glass",config:{duration:1500,musicalDuration:{musical:!0,bars:1},explosionPhase:.3,freezePhase:.7,distance:100,tumble:1,strength:1,particleMotion:{type:"shatter",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=Math.random()*Math.PI*2,a=.5+.5*Math.random();e.gestureData.shatter={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,velocityX:Math.cos(n)*a,velocityY:Math.sin(n)*a,tumbleAngle:0,tumbleSpeed:4*(Math.random()-.5),frozenX:null,frozenY:null,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.shatter?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=r.distance||100,h=e.gestureData.shatter,c=r.explosionPhase||.3,u=r.freezePhase||.7;if(t<c){const i=t/c,s=1-Math.pow(1-i,3),n=h.velocityX*l*s*o,a=h.velocityY*l*s*o;e.x=h.originalX+n,e.y=h.originalY+a,h.tumbleAngle+=h.tumbleSpeed*(1-i)}else if(t<u){const i=(t-c)/(u-c),s=h.originalX+h.velocityX*l*o,n=h.originalY+h.velocityY*l*o,a=h.velocityX*l*.2*i*o,r=h.velocityY*l*.2*i*o;e.x=s+a,e.y=n+r,h.tumbleAngle+=.3*h.tumbleSpeed*(1-i),i>.95&&null===h.frozenX&&(h.frozenX=e.x,h.frozenY=e.y)}else if(null!==h.frozenX&&(e.x=h.frozenX,e.y=h.frozenY),t>.9){const i=(t-.9)/.1;e.opacity=h.originalOpacity*(1-.5*i)}},cleanup(e){if(e.gestureData?.shatter){const t=e.gestureData.shatter;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.shatter}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=1,n=1,a=1,r=0,o=0,l=0,h=0,c=0,u=0,d=1,g=0;if(e<.1){const t=e/.1,r=1-Math.pow(1-t,2);n=1-.4*r*i,s=1+.2*r*i,a=1+.2*r*i,c=.1*-r*i,d=1+1*r,g=.8*r}else if(e<.4){const t=(e-.1)/.3,m=1-.6*t,p=40,f=Math.sin(e*p*Math.PI)*m,y=Math.cos(e*p*1.3*Math.PI)*m,b=Math.sin(e*p*.7*Math.PI)*m,v=1+.3*(1-Math.pow(1-t,2))*i;s=v+.15*f*i,n=v+.15*y*i,a=v+.15*b*i,r=.4*f*i,o=.5*y*i,l=.3*b*i,h=.15*f*i,c=.12*y*i+.1*t,u=.1*b*i,d=1.5+.5*Math.abs(f),g=.5*m}else if(e<.7){const t=(e-.4)/.3,r=t*t,o=1-r,h=20*o,u=Math.sin(e*h*Math.PI)*o,m=1.3-.4*r;s=m+.05*u*i,n=m+.05*u*i,a=m+.05*u*i,l=.15*u*i,c=.1*o,d=1.5-.3*r,g=.3*o}else{const t=(e-.7)/.3,i=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,r=Math.sin(t*Math.PI*2)*(1-t)*.05;if(s=.9+.1*i+r,n=.9+.1*i+r,a=.9+.1*i+r,d=1.2-.2*i,e>.95){const t=(e-.95)/.05;g=.3*Math.sin(t*Math.PI)}}return{position:[h,c,u],rotation:[r,o,l],scale:[s,n,a],glowIntensity:d,glowBoost:g}}}};const xt={default:{name:"shatter",emoji:"๐ฅ",description:"Dramatic shattering effect",duration:2500,beats:4,intensity:1,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!1,revealSoul:!1},explosive:{name:"shatterExplosive",emoji:"๐ฅ",description:"Explosive outward shatter",duration:2e3,beats:3,intensity:1.5,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0},crumble:{name:"shatterCrumble",emoji:"๐ชจ",description:"Slow crumbling collapse",duration:8e3,beats:16,intensity:.15,impactPoint:[0,-.4,0],impactDirection:[0,-1,0],reassemble:!1,revealSoul:!0,gravity:-.8,explosionForce:.1,rotationForce:.5,shatterTriggerAt:0},reform:{name:"shatterReform",emoji:"โจ",description:"Shatter then magically reassemble",duration:4e3,beats:8,intensity:1,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!0,reassembleAt:.5,reassembleDuration:1500,revealSoul:!0},punchLeft:{name:"shatterPunchLeft",emoji:"๐",description:"Shatter from left impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[-.4,0,0],impactDirection:[1,0,0],reassemble:!1,useDeformation:!0,direction:"left",revealSoul:!1},punchRight:{name:"shatterPunchRight",emoji:"๐",description:"Shatter from right impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[.4,0,0],impactDirection:[-1,0,0],reassemble:!1,useDeformation:!0,direction:"right",revealSoul:!1},punchFront:{name:"shatterPunchFront",emoji:"๐",description:"Shatter from front impact with deformation",duration:1500,beats:2,intensity:1.2,impactPoint:[0,0,.4],impactDirection:[0,0,-1],reassemble:!1,useDeformation:!0,direction:"front",revealSoul:!1},suspend:{name:"shatterSuspend",emoji:"๐",description:"Shatter, freeze mid-air, then reassemble",duration:4e3,beats:8,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!0,reassembleAt:.7,reassembleDuration:1200,revealSoul:!0,isSuspendMode:!0,suspendAt:.12,suspendDuration:.2,gravity:-2,explosionForce:1.2},freeze:{name:"shatterFreeze",emoji:"โ๏ธ",description:"Shatter and freeze mid-air (call triggerReassembly to reform)",duration:2e3,beats:4,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0,isFreezeMode:!0,isSuspendMode:!0,suspendAt:.12,suspendDuration:.2,gravity:-2,explosionForce:1.2},implode:{name:"shatterImplode",emoji:"๐",description:"Shards implode inward to center (or implode existing frozen shards)",duration:2500,beats:4,intensity:.8,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!1,revealSoul:!0,isDualMode:!0,dualModeType:"implode",dualModeDuration:1800,gravity:-3,explosionForce:1.2},gravity:{name:"shatterGravity",emoji:"โฌ๏ธ",description:"Shards fall with gravity and bounce on floor (or drop frozen shards)",duration:4e3,beats:8,intensity:.6,impactPoint:[0,0,0],impactDirection:[0,-1,0],reassemble:!1,revealSoul:!0,isDualMode:!0,dualModeType:"gravity",dualModeDuration:3e3,floorY:-.35,gravity:-2,explosionForce:.4},orbit:{name:"shatterOrbit",emoji:"๐ช",description:"Shards orbit around the soul then reassemble",duration:5e3,beats:10,intensity:.6,impactPoint:[0,0,0],impactDirection:[0,1,0],reassemble:!0,reassembleAt:.75,reassembleDuration:1200,revealSoul:!0,isDualMode:!0,dualModeType:"orbit",dualModeDuration:3500,orbitSpeed:1.5,radiusMultiplier:1.2,gravity:-3,explosionForce:1}};function Ct(e="default"){const t=xt[e]||xt.default;return{name:t.name,emoji:t.emoji,type:"override",description:t.description,config:{duration:t.duration,musicalDuration:{musical:!0,beats:t.beats},intensity:t.intensity,variant:e},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:t.beats},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.intensity||1,n=i.variant||"default",a=xt[n]||xt.default,r=a.useDeformation||!1,o=a.direction||"front";let l=!1,h=!1,c=1,u=0,d=1,g=null,m=null,p=null;const f=a.reassemble,y=a.reassembleAt||.5;if(r){let t;if(e<.3){const i=e/.3;t=i*(2-i)}else t=0;let i=0;e<.25?i=e/.25:e<.3&&(i=1);const n=.15*s,r=.25*s;let h=0,d=0;const f=0;let y=0,b=0;switch(o){case"left":h=t*n,b=-t*r;break;case"right":h=-t*n,b=t*r;break;case"front":d=-t*n,y=t*r*.7}if(t>0&&(m=[h,f,d],p=[y,0,b]),i>0&&(g={enabled:!0,strength:i*s*2.5,impactPoint:a.impactPoint,falloffRadius:.5}),e>=.28&&e<.32&&(l=!0),e<.35){const t=e/.35;c=1+.8*(1-t),u=.5*(1-t)}}else{const t=void 0!==a.shatterTriggerAt?a.shatterTriggerAt:.1,i=t+.02;if(e<t){if(t>0){const i=e/t,s=i*i;c=1+.6*s,u=.3*s,d=1+.05*s,"explosive"===n&&(d+=.01*Math.sin(200*e)*i)}}else if(e<i)l=e>=t&&e<t+.005,c=1.6,u=.4,d=1.05;else{if(f&&e>=y&&e<y+.02&&(h=!0),f&&e>=y){const t=(e-y)/(1-y),i=t*t;c=1+.8*i,u=.5*i,e>.95&&(c=2,u=.8)}else{const t=(e-i)/(f?y-i:1-i),s=Math.min(1,t),n=1-(1-s)*(1-s);c=1.6-.6*n,u=.4-.4*n}d=1}}const b={scale:d,glowIntensity:c,glowBoost:u,shatter:{enabled:l,impactPoint:a.impactPoint,impactDirection:a.impactDirection||[0,0,-1],intensity:s*a.intensity,variant:n,reassemble:h,reassembleDuration:a.reassembleDuration||1e3,revealSoul:!1!==a.revealSoul,isSuspendMode:a.isSuspendMode||!1,suspendAt:a.suspendAt||.25,suspendDuration:a.suspendDuration||.35,isFreezeMode:a.isFreezeMode||!1,gravity:a.gravity,explosionForce:a.explosionForce,rotationForce:a.rotationForce,gestureDuration:a.duration,isDualMode:a.isDualMode||!1,dualModeType:a.dualModeType,dualModeConfig:{duration:a.dualModeDuration||2e3,impactPoint:a.impactPoint,windDirection:a.windDirection,windForce:a.windForce,turbulence:a.turbulence,waveSpeed:a.waveSpeed,floorY:a.floorY,orbitSpeed:a.orbitSpeed,radiusMultiplier:a.radiusMultiplier,reassemble:a.reassemble,reassembleDuration:a.reassembleDuration}}};return g&&(b.deformation=g),m&&(b.cameraRelativePosition=m),p&&(b.cameraRelativeRotation=p),b}}}}const kt={up:{name:"dissolveUp",emoji:"๐ฌ๏ธ",description:"Shards blow upward like rising dust",windDirection:[0,1,.1],windForce:2.5,turbulence:.6},down:{name:"dissolveDown",emoji:"๐จ",description:"Shards blow downward like falling ash",windDirection:[0,-1,.1],windForce:1.8,turbulence:.4},left:{name:"dissolveLeft",emoji:"โฌ
๏ธ",description:"Shards blow left in the wind",windDirection:[-1,.15,0],impactDir:[1,.15,0],windForce:2.2,turbulence:.5},right:{name:"dissolveRight",emoji:"โก๏ธ",description:"Shards blow right in the wind",windDirection:[1,.15,0],impactDir:[-1,.15,0],windForce:2.2,turbulence:.5},away:{name:"dissolveAway",emoji:"๐ซ๏ธ",description:"Shards blow away from camera into distance",windDirection:[0,.1,-1],windForce:2,turbulence:.4},toward:{name:"dissolveToward",emoji:"๐ช๏ธ",description:"Shards blow toward camera",windDirection:[0,.1,1],windForce:2.5,turbulence:.6}};function Pt(e="away"){const t=kt[e]||kt.away;return{name:t.name,emoji:t.emoji,type:"override",description:t.description,config:{duration:3500,musicalDuration:{musical:!0,beats:6},intensity:.7,direction:e},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:6},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.2}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.intensity||.7,n=i.direction||"away",a=kt[n]||kt.away;let r=!1,o=1,l=0,h=1;const c=.06;if(e<c){const t=e/c;o=1+.4*t,l=.2*t,h=1+.03*t}else if(e<.08)r=e>=c&&e<.065,o=1.4,l=.3;else{const t=(e-c)/.94;o=1.4-.6*t,l=Math.max(0,.3-.3*t)}return{scale:h,glowIntensity:o,glowBoost:l,shatter:{enabled:r,impactPoint:[0,0,0],impactDirection:a.impactDir||a.windDirection,intensity:.5*s,variant:`dissolve_${n}`,revealSoul:!0,isSuspendMode:!1,isFreezeMode:!1,gravity:-.5,explosionForce:.3,gestureDuration:3500,isDualMode:!0,dualModeType:"dissolve",dualModeConfig:{duration:3e3,windDirection:a.windDirection,windForce:a.windForce*s,turbulence:a.turbulence}}}}}}}var Tt={name:"morph",emoji:"โจ",type:"override",description:"Form geometric patterns and shapes",config:{musicalDuration:{musical:!0,beats:2,minBeats:1,maxBeats:8},phases:[{name:"gather",beats:.25},{name:"form",beats:.75},{name:"hold",beats:.5},{name:"dissolve",beats:.5}],morphType:"fluid",pattern:"star",points:5,innerRadius:.4,size:80,amplitude:20,rotation:0,smooth:!0,randomizeOrder:!1,easing:"sine",strength:1.2,particleMotion:{type:"morph",pattern:"star",strength:1.2,smooth:!0,points:5}},rhythm:{enabled:!0,syncMode:"phrase",patternSync:{verse:"circle",chorus:"star",bridge:"heart",drop:"explosion"},timingSync:{formationBeat:1,holdBeats:2,dissolveBeat:4,curve:"anticipatory"},sizeSync:{onBeat:1.2,offBeat:.95,subdivision:"quarter",curve:"elastic"},rotationSync:{mode:"continuous",degreesPerBar:90,direction:"clockwise"},dynamics:{forte:{points:8,size:100},piano:{points:3,size:60}}},initialize(e,t,i,s,n){e.gestureData||(e.gestureData={});const a={...this.config,...t},r=e.x,o=e.y,l=Math.atan2(e.y-s,e.x-i),h=Math.random()<.5?1:-1;let c,u;const d=a.size*e.scaleFactor,g=(a.rotation||0)*Math.PI/180*h;switch(a.pattern){case"star":c=i,u=s,this.calculateStarPosition(e,l,d,a.points,a.innerRadius,g,i,s);break;case"heart":this.calculateHeartPosition(e,l,d,g,i,s);break;case"square":this.calculateSquarePosition(e,l,d,g,i,s);break;case"triangle":this.calculateTrianglePosition(e,l,d,g,i,s);break;default:{const e=d;c=i+Math.cos(l+g)*e,u=s+Math.sin(l+g)*e;break}}e.gestureData.morph={startX:r,startY:o,targetX:e.gestureData.morphTargetX||c,targetY:e.gestureData.morphTargetY||u,originalVx:e.vx,originalVy:e.vy,rotationDirection:h,initialized:!0}},calculateStarPosition(e,t,i,s,n,a,r,o){const l=((t+Math.PI)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),h=Math.floor(l/(2*Math.PI)*10),c=h%2==0,u=Math.floor(h/2);let d;d=c?72*u*Math.PI/180:(72*u+36)*Math.PI/180,d+=a;const g=c?i:i*n;e.gestureData.morphTargetX=r+Math.cos(d)*g,e.gestureData.morphTargetY=o+Math.sin(d)*g},calculateHeartPosition(e,t,i,s,n,a){const r=(t+Math.PI)/(2*Math.PI),o=.05*i,l=16*Math.pow(Math.sin(r*Math.PI*2),3),h=-(13*Math.cos(r*Math.PI*2)-5*Math.cos(2*r*Math.PI*2)-2*Math.cos(3*r*Math.PI*2)-Math.cos(4*r*Math.PI*2)),c=Math.cos(s),u=Math.sin(s),d=l*c-h*u,g=l*u+h*c;e.gestureData.morphTargetX=n+d*o,e.gestureData.morphTargetY=a+g*o},calculateSquarePosition(e,t,i,s,n,a){const r=((t+s)%(2*Math.PI)+2*Math.PI)%(2*Math.PI);let o,l;const h=i;r<Math.PI/4||r>=7*Math.PI/4?(o=h,l=h*Math.tan(r)):r<3*Math.PI/4?(o=h/Math.tan(r),l=h):r<5*Math.PI/4?(o=-h,l=-h*Math.tan(r)):(o=-h/Math.tan(r),l=-h);const c=Math.cos(s),u=Math.sin(s),d=o*c-l*u,g=o*u+l*c;e.gestureData.morphTargetX=n+d,e.gestureData.morphTargetY=a+g},calculateTrianglePosition(e,t,i,s,n,a){const r=[{x:0,y:-i},{x:.866*-i,y:.5*i},{x:.866*i,y:.5*i}],o=Math.floor((t+Math.PI)/(2*Math.PI)*3)%3,l=(o+1)%3,h=Math.random(),c=r[o].x+(r[l].x-r[o].x)*h,u=r[o].y+(r[l].y-r[o].y)*h,d=Math.cos(s),g=Math.sin(s),m=c*d-u*g,p=c*g+u*d;e.gestureData.morphTargetX=n+m,e.gestureData.morphTargetY=a+p},apply(e,t,i,s,n,a){e.gestureData?.morph?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.morph,o={...this.config,...i};let l,h,c=t;if(o.holdTime>0){const e=.5-o.holdTime/2,i=.5+o.holdTime/2;c=t<e?t/e*.5:t<i?.5:.5+(t-i)/(1-i)*.5}if(c<=.5){const e=2*c;l=r.startX+(r.targetX-r.startX)*this.easeOutQuad(e),h=r.startY+(r.targetY-r.startY)*this.easeOutQuad(e)}else{const e=2*(c-.5);l=r.targetX+(r.startX-r.targetX)*this.easeInQuad(e),h=r.targetY+(r.startY-r.targetY)*this.easeInQuad(e)}if(o.smooth){const t=.2;e.x+=(l-e.x)*t,e.y+=(h-e.y)*t}else e.x=l,e.y=h;if(e.vx=.5*(l-e.x),e.vy=.5*(h-e.y),t>.9){const i=10*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i)}},cleanup(e){if(e.gestureData?.morph){const t=e.gestureData.morph;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.morph,delete e.gestureData.morphTargetX,delete e.gestureData.morphTargetY}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutQuad:e=>e*(2-e),easeInQuad:e=>e*e,"3d":{evaluate(e,t){const i=t?.strength||1,s=Math.sin(e*Math.PI);let n;if(e<=.5){const t=2*e;n=1+t*(2-t)*.25*i}else{const t=2*(e-.5);n=1.25*i+t*t*(1-1.25*i),n=Math.max(1,n)}return{position:[0,0,0],rotation:[0,s*Math.PI*.3*i,.1*Math.sin(e*Math.PI*2)*i],scale:n,glowIntensity:1+.4*s*i,glowBoost:1.5*s*i}}}},Et={name:"rain",emoji:"๐ง๏ธ",type:"override",description:"Particles fall down from their current positions",config:{duration:3e3,musicalDuration:{musical:!0,bars:2},fallSpeed:8,fallDistance:400,wobbleAmount:1.5,strength:1,particleMotion:{type:"rain",strength:1,fallSpeed:8}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:2},intensitySync:{quiet:.5,loud:1.5,crescendo:"increase",diminuendo:"decrease"}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.rain={originalX:e.x,originalY:e.y,originalVx:e.vx,originalVy:e.vy,originalOpacity:e.opacity??e.life??1,currentX:e.x,currentY:e.y,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(e,t,i,s){const n="number"==typeof s?s:1;e.gestureData?.rain?.initialized||this.initialize(e,i);const a=e.gestureData.rain,r={...this.config,...i},o=i?.strength||1,l=(r.fallSpeed||8)*o,h=(r.fallDistance||400)*t*o;a.wobblePhase+=a.wobbleSpeed*n*.1;const c=Math.sin(a.wobblePhase)*(r.wobbleAmount||1.5);if(e.x=a.originalX+c,e.y=a.originalY+h,e.vx=.3*c,e.vy=10*l,t>.6){const i=(t-.6)/.4;e.opacity=a.originalOpacity*(1-i),void 0!==e.life&&(e.life=a.originalOpacity*(1-i))}else e.opacity=a.originalOpacity,void 0!==e.life&&(e.life=a.originalOpacity)},cleanup(e){if(e.gestureData?.rain){const t=e.gestureData.rain;e.x=t.originalX,e.y=t.originalY,e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.originalOpacity,void 0!==e.life&&(e.life=t.originalOpacity),delete e.gestureData.rain}},"3d":{evaluate:(e,t)=>({position:[0,0,0],rotation:[0,0,0],scale:1})}},At={name:"drift",emoji:"โ๏ธ",type:"override",description:"Controlled floating with fade effects",config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,angle:45,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,angleSpread:45,smoothness:.08,easing:"ease",strength:1,particleMotion:{type:"drift",strength:1,distance:60}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"beats",beats:2},distanceSync:{quiet:30,loud:80,crescendo:"expand",diminuendo:"contract"},angleSync:{major:45,minor:225,modulation:"smooth",cadence:"return"},holdSync:{shortPhrase:.1,longPhrase:.4,fermata:"sustain"},accentResponse:{enabled:!0,multiplier:1.3,type:"distance"},patternOverrides:{ambient:{distanceSync:{quiet:40,loud:100},holdSync:{shortPhrase:.3,longPhrase:.6}},classical:{angleSync:{major:30,minor:210},distanceSync:{quiet:25,loud:60}},jazz:{angleSync:{major:60,minor:240,swing:!0,syncopated:!0}},new_age:{distanceSync:{quiet:35,loud:70},holdSync:{shortPhrase:.4,longPhrase:.8},angleSync:{modulation:"gradual"}}},dynamics:{forte:{distanceSync:{quiet:{multiplier:1.5},loud:{multiplier:1.8}},holdSync:{multiplier:1.2},accentResponse:{multiplier:1.6}},piano:{distanceSync:{quiet:{multiplier:.6},loud:{multiplier:.8}},holdSync:{multiplier:.8},accentResponse:{multiplier:1.1}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s;let r=Math.atan2(a,n);const o={...this.config,...t}.angleSpread*Math.PI/180,l=(Math.random()-.5)*o;r+=l;const h=30+30*Math.random();e.gestureData.drift={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,driftAngle:r,angleOffset:l,homeRadius:h*e.scaleFactor,homeX:i+Math.cos(r)*h,homeY:s+Math.sin(r)*h,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.drift?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.drift,o={...this.config,...i},l=i.strength||1,h=this.easeInOutCubic(t),c=Math.max(0,h-.1*r.role);let u,d,g;if(o.returnToOrigin)if(c<.4){const e=c/.4,t=this.easeOutQuad(e);u=r.startX+(r.homeX-r.startX)*t,d=r.startY+(r.homeY-r.startY)*t}else if(c<.6+o.holdTime){const t=(c-.4)/(.2+o.holdTime);g=r.homeRadius+Math.sin(t*Math.PI*.5)*o.distance*l*e.scaleFactor}else{const t=(c-.6-o.holdTime)/(.4-o.holdTime);g=r.homeRadius+Math.cos(t*Math.PI*.5)*o.distance*l*e.scaleFactor}else{const t=c;g=r.homeRadius+t*o.distance*l*e.scaleFactor}if(void 0!==g){r.turbulencePhase+=o.turbulence*s;const e=Math.sin(r.turbulencePhase)*o.turbulence*10,t=Math.cos(1.3*r.turbulencePhase)*o.turbulence*10,i=r.driftAngle+r.angleOffset;u=n+Math.cos(i)*g+e,d=a+Math.sin(i)*g+t}const m=o.smoothness+.08*r.role;if(e.x+=(u-e.x)*m,e.y+=(d-e.y)*m,e.vx=.25*(u-e.x),e.vy=.25*(d-e.y),o.fadeOut){let i;i=t<.25?.3+t/.25*.7:t<.75?.7+.3*Math.sin((t-.25)*Math.PI/.5):4*(1-t),e.opacity=r.baseOpacity*i,void 0!==e.life&&(e.life=e.opacity)}t>=.99&&(e.vx=.1*r.originalVx,e.vy=.1*r.originalVy,o.fadeOut&&(e.opacity=r.baseOpacity,void 0!==e.life&&(e.life=r.baseOpacity)))},cleanup(e){if(e.gestureData?.drift){const t=e.gestureData.drift;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.drift}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,easeOutQuad:e=>e*(2-e),"3d":{evaluate(e,t){const i={...this.config,...t},s=t.strength||1,n=(i.angle||45)*Math.PI/180,a=i.returnToOrigin?e<.5?2*e:2*(1-e):e;return{position:[Math.cos(n)*a*.3*s,Math.sin(n)*a*.3*s,.15*Math.sin(e*Math.PI)*s],rotation:[0,10*a*s,0],scale:1+.03*Math.sin(e*Math.PI),glowIntensity:1-.1*a}}}};function Dt(e){const t=A[e];if(!t)throw new Error(`Invalid drift direction: ${e}`);const i="up"===e||"down"===e;return{name:`drift${D(e)}`,emoji:"up"===e?"โ๏ธ":"down"===e?"๐":"left"===e?"๐ซ๏ธ":"๐ญ",type:"override",description:`Gentle drifting ${e}`,config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,smoothness:.08,strength:1,direction:e,particleMotion:{type:"drift",strength:1,distance:60}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"beats",beats:2},distanceSync:{quiet:30,loud:80,crescendo:"expand",diminuendo:"contract"},holdSync:{shortPhrase:.1,longPhrase:.4,fermata:"sustain"},accentResponse:{enabled:!0,multiplier:1.3,type:"distance"}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=(30+30*Math.random())*e.scaleFactor;e.gestureData.drift={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,homeRadius:n,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.drift?.initialized||this.initialize(e,n,r,o);const l=e.gestureData.drift,h={...this.config,...n},c=n.strength||1,u=this.easeInOutCubic(s),d=Math.max(0,u-.1*l.role);let g,m=l.startX,p=l.startY;g=h.returnToOrigin?d<.5?2*d:2*(1-d):d;const f=h.distance*c*e.scaleFactor*g;l.turbulencePhase+=h.turbulence*a;const y=Math.sin(l.turbulencePhase)*h.turbulence*10,b=Math.cos(1.3*l.turbulencePhase)*h.turbulence*10;i?(p=l.startY+t.y*f+y,m=l.startX+.5*b):(m=l.startX+t.x*f+b,p=l.startY+.5*y);const v=h.smoothness+.08*l.role;if(e.x+=(m-e.x)*v,e.y+=(p-e.y)*v,e.vx=.25*(m-e.x),e.vy=.25*(p-e.y),h.fadeOut){let t=1;t=s<.25?.3+s/.25*.7:s<.75?.7+.3*Math.sin((s-.25)*Math.PI/.5):4*(1-s),e.opacity=l.baseOpacity*t}s>=.99&&(e.vx=.1*l.originalVx,e.vy=.1*l.originalVy,h.fadeOut&&(e.opacity=l.baseOpacity))},cleanup(e){if(e.gestureData?.drift){const t=e.gestureData.drift;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,delete e.gestureData.drift}},easeInOutCubic:e=>e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,"3d":{evaluate(e,s){const n=s||{},a=n.strength||1,r=n.distance||50,o=!1!==n.returnToOrigin?Math.sin(e*Math.PI):e,l=.004*r*a*o,h=t.x*l,c=t.y*l;let u=0,d=0;return i?u=t.y*o*.1:d=t.x*o*.15,{cameraRelativePosition:[h,c,0],rotation:[u,d,0],scale:1+.03*o,glowIntensity:1-.1*o}}}}}var _t=Dt("up"),It=Dt("down"),Rt=Dt("left"),Bt=Dt("right"),zt={name:"vortex",emoji:"๐",type:"override",description:"Spiral tornado pattern inward or outward",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},direction:"inward",rotationSpeed:2,pullStrength:1,liftAmount:.5,strength:1,particleMotion:{type:"vortex",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",rotationSync:{onBeat:1.5,offBeat:.8}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-(i||0),a=e.y-(s||0);e.gestureData.vortex={originalX:e.x,originalY:e.y,startAngle:Math.atan2(a,n),startDistance:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.vortex?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=e.gestureData.vortex,l="outward"!==r.direction,h=r.rotationSpeed||2,c=r.pullStrength||1,u=t*h*Math.PI*2,d=o.startAngle+u;let g;g=l?1-t*c*.8:1+t*c*.5;const m=o.startDistance*g;e.x=n+Math.cos(d)*m,e.y=a+Math.sin(d)*m,l&&t>.7&&(e.opacity=1-(t-.7)/.3)},cleanup(e){if(e.gestureData?.vortex){const t=e.gestureData.vortex;e.x=t.originalX,e.y=t.originalY,e.opacity=1,delete e.gestureData.vortex}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n="outward"!==i.direction,a=i.rotationSpeed||2,r=i.liftAmount||.5,o=e*a*Math.PI*2*s;let l;l=n?1-.3*e*s:1+.2*e*s;const h=e>.85?(1-e)/.15:1;return{position:[0,Math.sin(e*Math.PI)*r*.1*s*h,0],rotation:[.1*Math.sin(o)*s*h,o,.1*Math.cos(o)*s*h],scale:l,glowIntensity:1+.4*e,glowBoost:.3*e}}}};function Ft(e){if(!A[e])throw new Error(`Invalid cascade direction: ${e}`);const t="up"===e||"down"===e,i="down"===e||"right"===e;return{name:`cascade${D(e)}`,emoji:"down"===e?"๐":"up"===e?"โจ":"left"===e?"๐":"๐ฌ๏ธ",type:"override",description:`Sequential cascade ${e}`,config:{duration:2e3,musicalDuration:{musical:!0,bars:1},distance:200,waveCount:4,staggerDelay:.15,wobble:1,strength:1,direction:e,particleMotion:{type:"cascade",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",distanceSync:{quiet:100,loud:300,crescendo:"expand",diminuendo:"contract"}},initialize(e,t){e.gestureData||(e.gestureData={});const i=t?.waveCount||4;let s;s=Math.floor(Math.random()*i),e.gestureData.cascade={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,waveGroup:s,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(e,s,n,a,r,o){e.gestureData?.cascade?.initialized||this.initialize(e,n);const l={...this.config,...n},h=l.strength||1,c=e.gestureData.cascade,u="number"==typeof a?a:1,d=l.waveCount||4,g=l.staggerDelay||.15,m=c.waveGroup*g,p=Math.max(0,(s-m)/(1-m*(d-1)/d));if(p<=0)return;const f=(1-Math.pow(1-p,2))*((l.distance||200)*h)*(i?1:-1);c.wobblePhase+=c.wobbleSpeed*u*.1;const y=Math.sin(c.wobblePhase)*(l.wobble||1)*10;if(t?(e.y=c.originalY+f,e.x=c.originalX+y):(e.x=c.originalX+f,e.y=c.originalY+y),p>.6){const t=(p-.6)/.4;e.opacity=c.originalOpacity*(1-t)}},cleanup(e){if(e.gestureData?.cascade){const t=e.gestureData.cascade;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.cascade}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"down",a=1-Math.pow(1-e,2);let r=0,o=0;const l=.3*a*s;switch(n){case"down":o=-l;break;case"up":o=l;break;case"left":r=-l;break;case"right":r=l}const h=.03*Math.sin(e*Math.PI*4)*s;"down"===n||"up"===n?r+=h:o+=h;const c=e>.85?(1-e)/.15:1;return{cameraRelativePosition:[r*c,o*c,0],rotation:[("down"===n?.05:"up"===n?-.05:0)*s*c,0,("left"===n?.1:"right"===n?-.1:0)*s*c],scale:1-.1*a,glowIntensity:1+.2*(1-a)}}}}}var Ot=Ft("up"),Lt=Ft("down"),qt=Ft("left"),Gt=Ft("right"),Ht={name:"confetti",emoji:"๐",type:"effect",description:"Celebratory confetti flutter with chaotic rotation",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},burstHeight:.3,fallSpeed:1,tumbleSpeed:2,spread:1,strength:1,particleMotion:{type:"confetti",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1.5},timingSync:"onBeat"},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.confetti={originalX:e.x,originalY:e.y,driftX:2*(Math.random()-.5),tumblePhase:Math.random()*Math.PI*2,tumbleSpeed:.5+1.5*Math.random(),flutterAmp:.3+.7*Math.random(),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.confetti?.initialized||this.initialize(e,i);const r={...this.config,...i},o=r.strength||1,l=e.gestureData.confetti,h=Math.min(t/.2,1),c=Math.max(0,(t-.2)/.8),u=-50*Math.sin(h*Math.PI)*(r.burstHeight||.3),d=c*c*200*(r.fallSpeed||1),g=20*Math.sin(t*Math.PI*8*l.tumbleSpeed)*l.flutterAmp,m=l.driftX*t*100*(r.spread||1);e.x=l.originalX+m+g*o,e.y=l.originalY+u+d*o,t>.7&&(e.opacity=1-(t-.7)/.3)},cleanup(e){e.gestureData?.confetti&&delete e.gestureData.confetti},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1,s=Math.min(e/.2,1),n=Math.max(0,(e-.2)/.8),a=.15*Math.sin(s*Math.PI)-n*n*.3,r=e*Math.PI*4,o=.3*Math.sin(1.3*r)*i,l=.4*Math.sin(.7*r)*i,h=.5*Math.sin(1.1*r)*i,c=e>.85?(1-e)/.15:1;return{position:[.08*Math.sin(e*Math.PI*6)*i*c,a*i*c,0],rotation:[o*c,l*c,h*c],scale:1+.1*Math.sin(2*r)*i,glowIntensity:1+.3*(1-n)}}}},jt={name:"fizz",emoji:"๐ซง",type:"override",description:"Bubbles rising upward with wobble",config:{duration:2500,musicalDuration:{musical:!0,bars:1.5},riseSpeed:6,riseDistance:300,wobbleAmount:2,strength:1,particleMotion:{type:"fizz",strength:1}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:1.5},intensitySync:{quiet:.5,loud:1.5}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.fizz={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.4+.6*Math.random(),riseMultiplier:.7+.6*Math.random(),initialized:!0}},apply(e,t,i,s){e.gestureData?.fizz?.initialized||this.initialize(e,i);const n={...this.config,...i},a=n.strength||1,r=e.gestureData.fizz,o="number"==typeof s?s:1,l=(n.riseDistance||300)*t*a*r.riseMultiplier;r.wobblePhase+=r.wobbleSpeed*o*.1;const h=Math.sin(r.wobblePhase)*(n.wobbleAmount||2)*(1+t);if(e.x=r.originalX+h,e.y=r.originalY-l,e.vx=.3*h,e.vy=10*-(n.riseSpeed||6),t>.6){const i=(t-.6)/.4;e.opacity=r.originalOpacity*(1-i),void 0!==e.life&&(e.life=r.originalOpacity*(1-i))}},cleanup(e){if(e.gestureData?.fizz){const t=e.gestureData.fizz;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,void 0!==e.life&&(e.life=t.originalOpacity),delete e.gestureData.fizz}},"3d":{evaluate(e,t){const i=(t.config||this.config||{}).strength||1;let s=0,n=1,a=1;if(e<.15){const t=e/.15;s=.15*t,n=1+.02*t,a=1+.15*t}else if(e<.7){const t=(e-.15)/.55;s=.5-.15*t,n=1.02+.03*Math.sin(t*Math.PI*6),a=1.2+.15*Math.sin(t*Math.PI*8)}else{const t=(e-.7)/.3;s=.35*(1-t),n=1.02-.02*t,a=1.2-.2*t}const r=35*e;return{position:[.008*Math.sin(1.7*r)*s*i,.006*Math.sin(2.3*r)*s*i,.004*Math.sin(1.9*r)*s*i],rotation:[.03*Math.sin(1.3*r)*s*i,.02*Math.sin(1.1*r)*s*i,.04*Math.sin(1.5*r)*s*i],scale:[n+.015*Math.sin(2.1*r)*s,n+.02*Math.sin(1.8*r)*s,n+.015*Math.sin(2.4*r)*s],glowIntensity:a,glowBoost:.2*s}}}};function $t(e){const t=A[e];if(!t)throw new Error(`Invalid swarm direction: ${e}`);return{name:`swarm${D(e)}`,emoji:"up"===e?"๐ฆ
":"down"===e?"๐ฆ":"๐",type:"override",description:`Flock movement ${e}`,config:{duration:1800,musicalDuration:{musical:!0,bars:1},clusterPhase:.3,moveDistance:120,clusterTightness:.5,wobble:1,strength:1,direction:e,particleMotion:{type:"swarm",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.swarm={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),timeOffset:.1*Math.random(),initialized:!0}},apply(e,i,s,n,a,r){e.gestureData?.swarm?.initialized||this.initialize(e,s,a,r);const o={...this.config,...s},l=o.strength||1,h=e.gestureData.swarm,c=o.clusterPhase||.3,u=o.moveDistance||120,d=o.clusterTightness||.5,g=Math.max(0,Math.min(1,i-h.timeOffset));let m,p;if(g<c){const e=g/c,t=1-Math.pow(1-e,2);m=h.originalX+(a-h.originalX)*d*t,p=h.originalY+(r-h.originalY)*d*t}else{const e=(g-c)/(1-c),i=1-Math.pow(1-e,2),s=h.originalX+(a-h.originalX)*d,n=h.originalY+(r-h.originalY)*d;m=s+t.x*u*i*l,p=n+t.y*u*i*l}const f="number"==typeof n?n:1;h.wobblePhase+=h.wobbleSpeed*f*.1;const y=Math.sin(3*h.wobblePhase)*o.wobble*5,b=Math.cos(2.5*h.wobblePhase)*o.wobble*5;e.x=m+y,e.y=p+b,g>.8&&(e.opacity=h.originalOpacity*(1-5*(g-.8)))},cleanup(e){if(e.gestureData?.swarm){const t=e.gestureData.swarm;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.swarm}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"up",a=i.clusterPhase||.3,[r,o]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];let l=0,h=0,c=1;if(e<a)c=1-e/a*.1*s;else{const t=(e-a)/(1-a),i=1-Math.pow(1-t,2);l=r*i*.25*s,h=o*i*.25*s,c=.9+.1*t}const u=e>a?.1:0,d=e>.85?(1-e)/.15:1;return{cameraRelativePosition:[(l+.02*Math.sin(e*Math.PI*6)*s)*d,h*d,0],rotation:[o*u*s,0,-r*u*s],scale:c,glowIntensity:1+(e>a?.2:0)}}}}}var Wt=$t("up"),Ut=$t("down"),Vt=$t("left"),Yt=$t("right"),Xt={name:"burst",emoji:"๐ฅ",type:"blending",description:"Explosive outward burst from center",config:{decay:.5,strength:2},rhythm:{enabled:!0,syncMode:"beat",strengthSync:{onBeat:3.5,offBeat:1,curve:"explosion"},decaySync:{mode:"tempo",fast:.8,slow:.3,curve:"exponential"},durationSync:{mode:"beats",beats:.5,sustain:!1},accentResponse:{enabled:!0,multiplier:2.5,type:"strength"},patternOverrides:{rock:{strengthSync:{onBeat:4,offBeat:1.5},decaySync:{fast:.6,slow:.4}},electronic:{strengthSync:{onBeat:3.8,offBeat:.8,curve:"sharp"},decaySync:{fast:.9,slow:.7}},jazz:{strengthSync:{onBeat:2.8,offBeat:1.8,swing:!0},decaySync:{fast:.5,slow:.2}},orchestral:{strengthSync:{onBeat:3.2,offBeat:.5},accentResponse:{multiplier:3}}},dynamics:{forte:{strengthSync:{onBeat:{multiplier:2},offBeat:{multiplier:1.5}},decaySync:{multiplier:.7},accentResponse:{multiplier:3.5}},piano:{strengthSync:{onBeat:{multiplier:.6},offBeat:{multiplier:.3}},decaySync:{multiplier:1.3},accentResponse:{multiplier:1.8}}}},apply(e,t,i,s,n,a){const r=i.decay||this.config.decay,o=(i.strength||this.config.strength)*(1-t*r),l=e.x-n,h=e.y-a,c=Math.sqrt(l*l+h*h);c>1&&(e.vx+=l/c*o*2*s,e.vy+=h/c*o*2*s)},"3d":{evaluate(e,t){const i=t.strength||2;let s=0,n=1,a=1,r=0;if(e<.15){const t=e/.15,o=1-Math.pow(1-t,3);s=.15*o*i,n=1+.2*o*i,a=1+.5*o,r=.4*o}else if(e<.35){const t=(e-.15)/.2;s=.15*(1-1.5*t)*i,n=1+.2*(1-t)*i-.1*Math.sin(t*Math.PI),a=1+.4*(1-t),r=.2*(1-t)}else{const t=(e-.35)/.65,r=Math.pow(1-t,2),o=Math.sin(t*Math.PI*2)*r;s=.03*o*i,n=1+.05*o,a=1+.15*Math.abs(o)}return{cameraRelativePosition:[0,0,s],position:[0,0,0],rotation:[0,0,0],scale:n,glowIntensity:a,glowBoost:r}}}};function Nt(e){const t=A[e];if(!t)throw new Error(`Invalid burst direction: ${e}`);const i="up"===e||"down"===e;return{name:`burst${D(e)}`,emoji:"up"===e?"โฒ":"down"===e?"๐ฟ":"๐จ",type:"blending",description:`Explosive burst ${e}`,config:{duration:600,musicalDuration:{musical:!0,beats:1},decay:.5,strength:2,spread:.3,direction:e,particleMotion:{type:"burst",strength:2,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",strengthSync:{onBeat:3.5,offBeat:1,curve:"explosion"},accentResponse:{enabled:!0,multiplier:2.5,type:"strength"}},apply(e,s,n,a,r,o){const l={...this.config,...n},h=l.decay||.5,c=(l.strength||2)*(1-s*h),u=l.spread||.3;let d=t.x*c*2,g=t.y*c*2;const m=(Math.random()-.5)*u*c;i?d+=m:g+=m,e.vx+=d*a,e.vy+=g*a},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||2,n=i.direction||"up";let a=0,r=0,o=0,l=1,h=1,c=0;const[u,d]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];if(e<.15){const t=e/.15,i=1-Math.pow(1-t,3);a=u*i*.2*s,r=d*i*.2*s,o=.1*i*s,l=1+.15*i*s,h=1+.5*i,c=.4*i}else if(e<.35){const t=(e-.15)/.2,i=1-1.5*t;a=.2*u*i*s,r=.2*d*i*s,o=.1*i*s,l=1+.15*(1-t)*s,h=1+.4*(1-t),c=.2*(1-t)}else{const t=(e-.35)/.65,i=Math.pow(1-t,2),n=Math.sin(t*Math.PI*2)*i;a=u*n*.05*s,r=d*n*.05*s,l=1+.05*n,h=1+.15*Math.abs(n)}return{cameraRelativePosition:[a,r,o],position:[0,0,0],rotation:[0,0,0],scale:l,glowIntensity:h,glowBoost:c}}}}}var Qt=Nt("up"),Jt=Nt("down"),Kt=Nt("left"),Zt=Nt("right"),ei={name:"ripple",emoji:"๐",type:"effect",description:"Concentric waves emanating from center",config:{duration:1500,musicalDuration:{musical:!0,bars:1},waveCount:3,waveSpeed:1,amplitude:15,damping:.7,strength:1,particleMotion:{type:"ripple",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",amplitudeSync:{onBeat:1.5,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=r.waveCount||3,h=r.amplitude||15,c=r.damping||.7,u=e.x-n,d=e.y-a,g=Math.sqrt(u*u+d*d),m=(g/50-t*l*2)*Math.PI,p=Math.pow(1-t,c),f=Math.sin(m)*h*o*p;if(g>1){const t=.5*Math.cos(m)*o*p;e.x+=u/g*t,e.y+=d/g*t}e.opacity=Math.max(.3,1-.3*Math.abs(f/h))},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.waveCount||3,a=i.damping||.7,r=Math.pow(1-e,a),o=e*Math.PI*n*2,l=Math.sin(o),h=e*Math.PI*4,c=Math.sin(h)*s*r,u=.5*Math.sin(h+Math.PI/2)*s*r,d=.12,g=1-c*d+u*d*.3,m=1+c*d,p=1-c*d-u*d*.3,f=.08*(m-1);return{position:[.01*Math.sin(1.5*h)*r,f,0],rotation:[.04*l*s*r,0,.03*u*s*r],scale:[g,m,p],glowIntensity:1+.3*Math.abs(c),glowBoost:.25*Math.max(0,c)*r}}}},ti={name:"wave",emoji:"๐",type:"override",description:"Infinity pattern flow with phasing",config:{musicalDuration:{musical:!0,bars:1,minBeats:4,maxBeats:16},phases:[{name:"gather",beats:.5},{name:"rise",beats:.5},{name:"waveLeft",beats:1},{name:"waveRight",beats:1},{name:"settle",beats:1}],amplitude:40,frequency:1,phaseShift:.3,liftHeight:20,fadeInOut:!0,smoothness:.1,easing:"sine",strength:1,particleMotion:{type:"wave",strength:1,amplitude:50}},rhythm:{enabled:!0,syncMode:"wave",amplitudeSync:{onWave:65,onStatic:25,curve:"flowing"},frequencySync:{mode:"phrase",slow:.7,fast:1.8,curve:"melodic"},durationSync:{mode:"bars",adaptToPhrase:!0,sustain:!0},phaseSync:{enabled:!0,multiplier:.5,type:"ensemble"},melodicResponse:{enabled:!0,multiplier:1.4,type:"amplitude"},patternOverrides:{ambient:{amplitudeSync:{onWave:80,onStatic:40,curve:"hypnotic"},frequencySync:{slow:.5,fast:1.2},durationSync:{minBeats:16,maxBeats:64}},ocean:{amplitudeSync:{onWave:90,onStatic:20,curve:"natural"},phaseSync:{multiplier:.8},melodicResponse:{multiplier:1.8}},electronic:{amplitudeSync:{onWave:70,onStatic:30,curve:"digital"},frequencySync:{slow:.8,fast:2.5,curve:"precise"}},orchestral:{amplitudeSync:{onWave:75,onStatic:35},phaseSync:{multiplier:.7},melodicResponse:{multiplier:2}}},dynamics:{forte:{amplitudeSync:{onWave:{multiplier:1.8},onStatic:{multiplier:1.4}},frequencySync:{multiplier:1.3},melodicResponse:{multiplier:2.2}},piano:{amplitudeSync:{onWave:{multiplier:.6},onStatic:{multiplier:.4}},frequencySync:{multiplier:.7},melodicResponse:{multiplier:1.1}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-i,a=e.y-s,r=Math.atan2(a,n),o=Math.sqrt(n*n+a*a),l=Math.random()<.5?1:-1;e.gestureData.wave={startX:e.x,startY:e.y,originalVx:e.vx,originalVy:e.vy,baseOpacity:e.opacity||e.life||1,angle:r,radius:o,offset:Math.random()*Math.PI*2,role:Math.random(),direction:l,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.wave?.initialized||this.initialize(e,i,n,a);const r=e.gestureData.wave,o={...this.config,...i},l=i.strength||1,h=this.easeInOutSine(t),c=r.role*o.phaseShift,u=Math.max(0,h-c),d=u*Math.PI*2*o.frequency*r.direction+r.offset,g=.5+r.radius/100*.5,m=o.amplitude*g*l*e.scaleFactor,p=n+Math.sin(d)*m,f=a+Math.sin(2*d)*m*.3+-Math.abs(Math.sin(h*Math.PI))*o.liftHeight*e.scaleFactor,y=o.smoothness+.12*r.role;if(e.x+=(p-e.x)*y,e.y+=(f-e.y)*y,e.vx=.3*(p-e.x),e.vy=.3*(f-e.y),o.fadeInOut){let t;t=u<.1?u/.1:u>.9?(1-u)/.1:.5+.5*Math.sin(u*Math.PI),e.opacity=r.baseOpacity*(.3+.7*t),void 0!==e.life&&(e.life=e.opacity)}if(t>=.95){const i=20*(1-t);e.vx=e.vx*i+r.originalVx*(1-i),e.vy=e.vy*i+r.originalVy*(1-i),o.fadeInOut&&(e.opacity=r.baseOpacity*i,void 0!==e.life&&(e.life=e.opacity))}},cleanup(e){if(e.gestureData?.wave){const t=e.gestureData.wave;e.vx=t.originalVx,e.vy=t.originalVy,e.opacity=t.baseOpacity,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.wave}},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i=t?.strength||1,s=t?.frequency||1,n=-(Math.cos(Math.PI*e)-1)/2,a=n*Math.PI*2*s,r=.12*Math.sin(a)*i,o=.06*Math.sin(2*a)*i,l=.03*Math.sin(a)*i,h=.08*Math.sin(2*a)*i,c=.05*Math.sin(a)*i,u=1+.08*Math.abs(Math.sin(n*Math.PI))*i,d=Math.abs(Math.sin(a));return{position:[r,o,l],rotation:[h,0,c],scale:u,glowIntensity:1+.3*d*i,glowBoost:.6*d*i}}}},ii={name:"flash",emoji:"โก",type:"blending",description:"Bright flash burst effect",config:{duration:400,glowAmount:2.5,glowPeak:3,scalePeak:1.1,easing:"cubic",strength:1,particleMotion:{type:"burst",strength:1,decay:.3}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"immediate",interruptible:!0,priority:8,blendable:!0,intensitySync:{onBeat:3.5,offBeat:1,accent:5,subdivision:"quarter",curve:"exponential"},durationSync:{mode:"tempo",baseDuration:400,scaling:"inverse"},scaleSync:{onBeat:1.2,offBeat:1,accent:1.4,curve:"elastic"},strobeSync:{enabled:!1,pattern:"XXOX",subdivision:"sixteenth"},dynamics:{forte:{glowPeak:4,scalePeak:1.3,duration:300},piano:{glowPeak:2,scalePeak:1.05,duration:500}}},initialize(e,t){e.gestureData||(e.gestureData={}),e.gestureData.flash={originalOpacity:e.opacity,originalSize:e.size,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.flash?.initialized||this.initialize(e,i);const r=e.gestureData.flash,o={...this.config,...i},l=o.strength||1;let h;if(h=t<.3?t/.3*o.glowPeak:o.glowPeak*(1-(t-.3)/.7),e.opacity=Math.min(1,r.originalOpacity*(1+h*l)),e.size=r.originalSize*(1+(o.scalePeak-1)*h*l*.1),t<.2){const i=(1-t/.2)*l,r=Math.atan2(e.y-a,e.x-n);e.vx+=Math.cos(r)*i*2*s,e.vy+=Math.sin(r)*i*2*s}e.vx*=1-.1*o.particleMotion.decay,e.vy*=1-.1*o.particleMotion.decay},cleanup(e){e.gestureData?.flash&&(e.opacity=e.gestureData.flash.originalOpacity,e.size=e.gestureData.flash.originalSize,delete e.gestureData.flash)},"3d":{evaluate(e,t){const i={...this.config,...t};let s;t.strength,s=e<.3?e/.3:1-(e-.3)/.7;const n=1+.4*s;return{position:[0,0,0],rotation:[0,0,0],scale:1+s*((i.scalePeak||1.1)-1),glowIntensity:n,glowBoost:2*s}}}},si={name:"glow",emoji:"โจ",type:"blending",description:"Pure luminous glow without movement",config:{duration:1500,amplitude:0,frequency:1,holdPeak:.3,easing:"sine",scaleAmount:.1,glowAmount:.8,strength:0,direction:"none",particleMotion:{type:"glow",strength:0,direction:"none",frequency:1}},rhythm:{enabled:!0,syncMode:"phrase",amplitudeSync:{onBeat:2,offBeat:1.2,curve:"smooth"},frequencySync:{mode:"phrase",subdivision:"bar"},durationSync:{mode:"bars",bars:2},accentResponse:{enabled:!0,multiplier:2.5},patternOverrides:{ambient:{amplitudeSync:{onBeat:2.5,offBeat:1.8},durationSync:{bars:4}},electronic:{amplitudeSync:{onBeat:3,offBeat:.5,curve:"sharp"},frequencySync:{subdivision:"quarter"}}}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.glow={startOpacity:e.opacity,startGlow:e.glowSizeMultiplier||0,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.glow?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=this.easeInOutSine(t);let l,{frequency:h}=r,{glowAmount:c}=r;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const u=o*h*2%2;l=r.holdPeak>0&&u>1-r.holdPeak&&u<1+r.holdPeak?1:Math.sin(o*Math.PI*2*h);let d=1;t>.9&&(d=.5+.5*(1-10*(t-.9))),e.glowIntensity=1+l*c*d},cleanup(e){e.gestureData?.glow&&(e.glowIntensity=1,delete e.gestureData.glow)},easeInOutSine:e=>-(Math.cos(Math.PI*e)-1)/2,"3d":{evaluate(e,t){const i={...this.config,...t},s=-(Math.cos(Math.PI*e)-1)/2,n=Math.sin(s*Math.PI);let a=i.glowAmount||.8;t.rhythmModulation&&(a*=t.rhythmModulation.amplitudeMultiplier||1,a*=t.rhythmModulation.accentMultiplier||1);const r=1+n*a;return{position:[0,0,0],rotation:[0,0,0],scale:1+n*(i.scaleAmount||.1)*.5,glowIntensity:r,glowBoost:1.5*n}}}},ni={name:"bloom",emoji:"๐ธ",type:"effect",description:"Particles unfold outward like flower petals opening",config:{duration:1500,musicalDuration:{musical:!0,bars:1},petalCount:6,openingSpeed:1,rotationAmount:.3,strength:1,particleMotion:{type:"bloom",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",amplitudeSync:{onBeat:1.3,offBeat:.8}},initialize(e,t,i,s){e.gestureData||(e.gestureData={});const n=e.x-(i||0),a=e.y-(s||0);e.gestureData.bloom={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,startAngle:Math.atan2(a,n),startDistance:Math.sqrt(n*n+a*a),initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.bloom?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=e.gestureData.bloom,h=Math.pow(t,.7),c=(r.rotationAmount||.3)*Math.PI,u=Math.sin(h*Math.PI)*c,d=1+.5*h*o,g=l.startDistance*d,m=l.startAngle+u;e.x=n+Math.cos(m)*g,e.y=a+Math.sin(m)*g,e.opacity=Math.min(1,l.originalOpacity*(.7+.3*h))},cleanup(e){if(e.gestureData?.bloom){const t=e.gestureData.bloom;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.bloom}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.rotationAmount||.3,a=Math.pow(e,.7),r=1+.2*a*s,o=Math.sin(a*Math.PI)*n*s,l=.1*Math.sin(a*Math.PI*.5)*s,h=e>.85?1-(e-.85)/.15*.3:1;return{position:[0,.05*Math.sin(a*Math.PI)*s*h,0],rotation:[0,o*h,l*h],scale:r*(.7+.3*h),glowIntensity:1+.4*a,glowBoost:.3*a}}}},ai={name:"flicker",emoji:"โก",type:"blending",description:"Rapid opacity changes with motion jitter",config:{duration:800,musicalDuration:{musical:!0,beats:2},flickerRate:15,frequency:6,minOpacity:.3,maxOpacity:1,jitterAmount:2,colorShift:!1,strobe:!1,pulseMode:!1,groupFlicker:.3,easing:"linear",strength:.7,particleMotion:{type:"flicker",strength:.7,frequency:6}},rhythm:{enabled:!0,syncMode:"subdivision",durationSync:{mode:"beats",beats:2},rateSync:{subdivision:"sixteenth",onBeat:30,offBeat:10,triplet:20,curve:"step"},opacitySync:{pattern:"HLMH",subdivision:"eighth",onAccent:.1,regular:.5},jitterSync:{onBeat:5,offBeat:1,accent:10,curve:"random"},strobeSync:{verse:!1,chorus:!0,drop:"intense",pattern:"XOXO"},dynamics:{forte:{flickerRate:25,jitterAmount:5,minOpacity:.1},piano:{flickerRate:8,jitterAmount:1,minOpacity:.5}}},initialize(e,t){e.gestureData||(e.gestureData={});const i={...this.config,...t},s=Math.random()<i.groupFlicker;e.gestureData.flicker={baseOpacity:e.opacity||e.life||1,baseColor:e.color,baseX:e.x,baseY:e.y,flickerTimer:0,lastFlicker:0,flickerState:!0,isGrouped:s,groupId:s?Math.floor(3*Math.random()):-1,phase:Math.random()*Math.PI*2,colorHue:0,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.flicker?.initialized||this.initialize(e,i);const r=e.gestureData.flicker,o={...this.config,...i},l=i.strength||1;let h;if(r.flickerTimer+=s*o.flickerRate,o.strobe)h=(r.flickerTimer+r.phase)%1<.5?1:o.minOpacity;else if(o.pulseMode){const e=r.flickerTimer+r.phase;h=o.minOpacity+(o.maxOpacity-o.minOpacity)*(.5*Math.sin(e)+.5)}else{if(r.flickerTimer-r.lastFlicker>1)if(r.lastFlicker=r.flickerTimer,r.isGrouped){const e=Math.floor(r.flickerTimer)%3;r.flickerState=e===r.groupId}else r.flickerState=Math.random()>.3;const t=r.flickerState?o.maxOpacity:o.minOpacity+.3*Math.random(),i=e.opacity/r.baseOpacity;h=i+.3*(t-i)}const c=r.baseOpacity*(1+(h-1)*l);if(e.opacity=Math.max(0,Math.min(1,c)),void 0!==e.life&&(e.life=e.opacity),o.jitterAmount>0&&h>o.minOpacity){const t=o.jitterAmount*l*e.scaleFactor,i=(Math.random()-.5)*t*h,n=(Math.random()-.5)*t*h;e.vx+=.1*i*s,e.vy+=.1*n*s}if(o.colorShift&&e.color){r.colorHue+=.01*s;const t=30*Math.sin(r.colorHue);e.color=this.shiftHue(r.baseColor,t*l)}let u=1;t<.1?u=t/.1:t>.9&&(u=(1-t)/.1),e.opacity*=u,void 0!==e.life&&(e.life=e.opacity),t>.8&&(e.vx*=.95,e.vy*=.95)},shiftHue(e,t){if(!e||!e.startsWith("#"))return e;const i=e.slice(1),s=parseInt(i.substr(0,2),16)/255,n=parseInt(i.substr(2,2),16)/255,a=parseInt(i.substr(4,2),16)/255,r=t*Math.PI/180,o=Math.cos(r),l=Math.sin(r),h=s*l+n*o,c=a,u=e=>Math.max(0,Math.min(255,Math.round(255*e))).toString(16).padStart(2,"0");return`#${u(s*o-n*l)}${u(h)}${u(c)}`},cleanup(e){if(e.gestureData?.flicker){const t=e.gestureData.flicker;e.opacity=t.baseOpacity,e.color=t.baseColor,void 0!==e.life&&(e.life=t.baseOpacity),delete e.gestureData.flicker}},"3d":{evaluate(e,t){const i=t.config||{},s=t.strength||.7,n=i.flickerRate||15;i.minOpacity;const a=e*n,r=Math.sin(a*Math.PI*2),o=Math.floor(10*a),l=.3*r+.5*(Math.sin(123.456*o)+1)*.7,h=.6+.8*l,c=i.jitterAmount||2,u=.003*s*h,d=(Math.random()-.5)*c*u,g=(Math.random()-.5)*c*u,m=.03*(Math.random()-.5)*s*h;return{position:[d,g,0],rotation:[.5*m,0,m],scale:1+.08*(h-1),glowIntensity:h,glowBoost:1.2*l}}}},ri={name:"shiver",emoji:"๐ฅถ",type:"effect",description:"High-frequency micro-vibrations for nervousness or cold",config:{duration:1500,musicalDuration:{musical:!0,bars:1},frequency:30,amplitude:.02,decay:.3,strength:1,particleMotion:{type:"shiver",strength:.8}},rhythm:{enabled:!0,syncMode:"ambient",durationSync:{mode:"bars",bars:1},intensitySync:{quiet:.5,loud:1.5,crescendo:"increase",diminuendo:"decrease"}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=r.frequency||30,h=100*(r.amplitude||.02),c=t*l*Math.PI*2,u=(.6*Math.sin(c)+.3*Math.sin(1.7*c+1.3)+.1*Math.sin(2.3*c+2.7))*h*o,d=Math.sin(t*Math.PI);e.x+=u*d*(Math.random()-.5)*2,e.y+=u*d*(Math.random()-.5)*2},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.frequency||30,a=i.amplitude||.02,r=Math.sin(e*Math.PI),o=e*n*Math.PI*2,l=.6*Math.sin(o)+.3*Math.sin(1.7*o)+.1*Math.sin(2.3*o),h=.5*Math.cos(1.1*o)+.3*Math.cos(1.9*o)+.2*Math.cos(2.7*o);return{position:[l*a*s*r,h*a*s*r,(.4*Math.sin(.9*o+1)+.4*Math.sin(1.5*o+2))*a*.5*s*r],rotation:[.02*h*s*r,0,.02*l*s*r],scale:1+.01*Math.abs(l)*s*r,glowIntensity:1+.1*Math.abs(l)*r}}}},oi={name:"heartbeat",emoji:"๐",type:"effect",description:"Rhythmic double-pump heartbeat (lub-dub)",config:{duration:1e3,musicalDuration:{musical:!0,beats:2},lubStrength:.8,dubStrength:1,lubDubGap:.15,strength:1,particleMotion:{type:"heartbeat",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:2},timingSync:"onBeat",amplitudeSync:{onBeat:1.2,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=this._calculatePulse(t,r),h=e.x-n,c=e.y-a,u=Math.sqrt(h*h+c*c)||1,d=10*l*o;e.x+=h/u*d,e.y+=c/u*d},_calculatePulse(e,t){const i=t.lubDubGap||.15,s=t.lubStrength||.8,n=t.dubStrength||1;let a=0;const r=Math.abs(e-.1);r<.08&&(a=Math.cos(r/.08*Math.PI*.5)*s);const o=.1+i+.05,l=Math.abs(e-o);if(l<.1){const e=Math.cos(l/.1*Math.PI*.5)*n;a=Math.max(a,e)}return a},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.lubDubGap||.15,a=i.lubStrength||.8,r=i.dubStrength||1;let o=0;const l=Math.abs(e-.1);l<.08&&(o=Math.cos(l/.08*Math.PI*.5)*a);const h=.1+n+.05,c=Math.abs(e-h);if(c<.1){const e=Math.cos(c/.1*Math.PI*.5)*r;o=Math.max(o,e)}return{position:[0,0,.03*o*s],rotation:[0,0,0],scale:1+.15*o*s,glowIntensity:1+.5*o*s,glowBoost:.8*o*s}}}},li={name:"snap",emoji:"โก",type:"effect",description:"Quick elastic snap with overshoot and settle",config:{duration:500,musicalDuration:{musical:!0,beats:1},snapDistance:.1,overshoot:1.3,bounces:2,strength:1,particleMotion:{type:"snap",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=100*(r.snapDistance||.1),h=r.overshoot||1.3,c=this._calculateSnap(t,h,r.bounces||2),u=n-e.x,d=a-e.y,g=Math.sqrt(u*u+d*d)||1;e.x+=u/g*c*l*o*.1,e.y+=d/g*c*l*o*.1},_calculateSnap(e,t,i){if(e<.2){const i=e/.2;return(1-Math.pow(1-i,3))*t}{const s=(e-.2)/.8,n=Math.exp(4*-s);return 1+(t-1)*Math.cos(s*Math.PI*i*2)*n}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.snapDistance||.1,a=i.overshoot||1.3,r=i.bounces||2;let o;if(e<.2){const t=e/.2;o=(1-Math.pow(1-t,3))*a}else{const t=(e-.2)/.8,i=Math.exp(4*-t);o=1+(a-1)*Math.cos(t*Math.PI*r*2)*i}return{position:[0,0,(o-1)*n*s],rotation:[0,0,.1*(o-1)*s],scale:1+.15*(o-1),glowIntensity:1+.5*Math.abs(o-1),glowBoost:e<.3?(.3-e)/.3*.4:0}}}},hi={name:"elasticBounce",emoji:"๐",type:"effect",description:"Drop and bounce with elastic oscillation",config:{duration:1200,musicalDuration:{musical:!0,beats:3},dropHeight:.15,bounceCount:3,elasticity:.6,strength:1,particleMotion:{type:"elasticBounce",strength:1}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",amplitudeSync:{onBeat:1.3,offBeat:.8}},apply(e,t,i,s,n,a){const r={...this.config,...i},o=r.strength||1,l=200*(r.dropHeight||.15),h=r.bounceCount||3,c=r.elasticity||.6,u=this._calculateBounce(t,l,h,c);e.y+=u*o;const d=.3*Math.max(0,-u/l);e.scaleY=1-d*o,e.scaleX=1+.5*d*o},_calculateBounce(e,t,i,s){let n=t,a=0,r=0,o=.3;for(;r<i&&a<1;){const t=o*Math.pow(s,.5*r);if(e<a+t){const i=(e-a)/t;return 4*i*(1-i)*-n}a+=t,n*=s,r++,o*=s}return 0},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.dropHeight||.15,a=i.bounceCount||3,r=i.elasticity||.6;let o=n,l=0,h=0,c=.3,u=0,d=!1;for(;h<a&&l<1;){const t=c*Math.pow(r,.5*h);if(e<l+t){const i=(e-l)/t;u=o*(4*i*(1-i))*s,d=i>.45&&i<.55;break}l+=t,o*=r,h++,c*=r}let g=1,m=1;if(d){const e=.15*s*Math.pow(r,h);g=1+e,m=1-e}return{position:[0,u,0],rotation:[0,0,0],scale:(g+m)/2,glowIntensity:1+(d?.3:0)}}}},ci={name:"hold",emoji:"โธ๏ธ",type:"override",description:"Hold particles in current position",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},holdStrength:.95,allowDrift:!1,strength:1},rhythm:{enabled:!0,syncMode:"rest",holdSync:{onRest:.98,onSound:.8,curve:"immediate"},durationSync:{mode:"rests",minBeats:.5,maxBeats:8,sustain:!0},pauseResponse:{enabled:!0,multiplier:1.5,type:"strength"},patternOverrides:{classical:{holdSync:{onRest:.99,onSound:.75,curve:"dramatic"},pauseResponse:{multiplier:2}},minimal:{holdSync:{onRest:.95,onSound:.85},durationSync:{minBeats:2,maxBeats:16}},jazz:{holdSync:{onRest:.9,onSound:.7},allowDrift:!0},electronic:{holdSync:{onRest:.99,onSound:.6,curve:"digital"},pauseResponse:{multiplier:1.2}}},dynamics:{forte:{holdSync:{onRest:{multiplier:1.02},onSound:{multiplier:.9}},pauseResponse:{multiplier:2.2}},piano:{holdSync:{onRest:{multiplier:.97},onSound:{multiplier:.85}},pauseResponse:{multiplier:1.3}}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.hold={holdX:e.x,holdY:e.y,originalVx:e.vx,originalVy:e.vy}},apply(e,t,i,s,n,a){e.gestureData?.hold||this.initialize(e);const r=e.gestureData.hold,o=i.holdStrength||this.config.holdStrength;if(i.allowDrift?(e.vx*=o,e.vy*=o):(e.x+=(r.holdX-e.x)*(1-o),e.y+=(r.holdY-e.y)*(1-o),e.vx=0,e.vy=0),t>.9){const i=10*(t-.9);e.vx=e.vx*(1-i)+r.originalVx*i,e.vy=e.vy*(1-i)+r.originalVy*i}},cleanup(e){if(e.gestureData?.hold){const t=e.gestureData.hold;e.vx=t.originalVx,e.vy=t.originalVy,delete e.gestureData.hold}},"3d":{evaluate(e,t){let i=0,s=1;if(e<.15){const t=e/.15;i=t*t*(3-2*t),s=1-.2*i}else if(e<.85)i=1,s=.8;else{const t=(e-.85)/.15;i=1-t*t*(3-2*t),s=.8+.2*t}return i*=(t.config||this.config||{}).strength||1,{position:[0,0,0],rotation:[0,0,0],scale:1,glowIntensity:s,freezeRotation:i,freezeWobble:i,freezeGroove:i,freezeParticles:i}}}},ui={name:"fade",emoji:"๐ป",type:"blending",description:"Fade particle opacity",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},fadeIn:!0,fadeOut:!0,minOpacity:0,maxOpacity:1},rhythm:{enabled:!0,syncMode:"dynamic",durationSync:{mode:"bars",bars:1},opacitySync:{onBeat:.9,offBeat:.3,subdivision:"eighth",curve:"exponential"},fadePhaseSync:{verse:{fadeIn:!0,fadeOut:!1},chorus:{fadeIn:!1,fadeOut:!1},bridge:{fadeIn:!0,fadeOut:!0},outro:{fadeIn:!1,fadeOut:!0}},pulseSync:{enabled:!0,frequency:"quarter",intensity:.2,onAccent:.4},dynamics:{forte:{minOpacity:.5,maxOpacity:1},piano:{minOpacity:0,maxOpacity:.4}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.fade={baseOpacity:e.opacity||e.life||1}},apply(e,t,i,s,n,a){e.gestureData?.fade||this.initialize(e);const r=e.gestureData.fade,o={...this.config,...i};let l;l=o.fadeIn&&!o.fadeOut?o.minOpacity+(o.maxOpacity-o.minOpacity)*t:o.fadeOut&&!o.fadeIn?o.maxOpacity-(o.maxOpacity-o.minOpacity)*t:t<.5?o.minOpacity+(o.maxOpacity-o.minOpacity)*(2*t):o.maxOpacity-(o.maxOpacity-o.minOpacity)*(2*(t-.5)),e.opacity=r.baseOpacity*l,void 0!==e.life&&(e.life=e.opacity)},cleanup(e){e.gestureData?.fade&&(e.opacity=e.gestureData.fade.baseOpacity,void 0!==e.life&&(e.life=e.opacity),delete e.gestureData.fade)},"3d":{evaluate(e,t){const i={...this?.config||{},...t},s=i.fadeIn??!0,n=i.fadeOut??!0;let a;a=s&&!n?e:n&&!s?1-e:e<.5?1-e/.5:(e-.5)/.5;const r=a*a*(3-2*a);return{position:[0,0,0],rotation:[0,0,0],scale:.01+.99*r,glowIntensity:r,glowBoost:0}}}},di={name:"settle",emoji:"๐",type:"blending",description:"Gradually settle particles to rest",config:{damping:.02,threshold:.01},rhythm:{enabled:!0,syncMode:"resolution",dampingSync:{onResolution:.035,onTension:.015,curve:"gradual"},thresholdSync:{mode:"dynamics",forte:.02,piano:.005,curve:"exponential"},durationSync:{mode:"phrase",minBeats:2,maxBeats:12,sustain:!0},cadenceResponse:{enabled:!0,multiplier:1.6,type:"damping"},patternOverrides:{ambient:{dampingSync:{onResolution:.025,onTension:.008,curve:"atmospheric"},durationSync:{minBeats:8,maxBeats:32}},jazz:{dampingSync:{onResolution:.04,onTension:.02},cadenceResponse:{multiplier:1.8}},classical:{dampingSync:{onResolution:.045,onTension:.012,curve:"expressive"},cadenceResponse:{multiplier:2}},minimalist:{dampingSync:{onResolution:.02,onTension:.005},durationSync:{minBeats:16,maxBeats:64}}},dynamics:{forte:{dampingSync:{onResolution:{multiplier:1.4},onTension:{multiplier:.8}},thresholdSync:{multiplier:2},cadenceResponse:{multiplier:2.2}},piano:{dampingSync:{onResolution:{multiplier:.7},onTension:{multiplier:1.2}},thresholdSync:{multiplier:.5},cadenceResponse:{multiplier:1.3}}}},apply(e,t,i,s,n,a){const r=i.damping||this.config.damping,o=i.threshold||this.config.threshold;e.vx*=Math.max(0,1-r*s*60),e.vy*=Math.max(0,1-r*s*60),Math.abs(e.vx)<o&&(e.vx=0),Math.abs(e.vy)<o&&(e.vy=0)},"3d":{evaluate(e,t){const i=1-Math.pow(1-e,2),s=.01*(1-i);return{position:[Math.sin(e*Math.PI*2)*s,Math.cos(e*Math.PI*3)*s*.5,0],rotation:[0,0,0],scale:1-.03*i,glowIntensity:1-.15*i}}}},gi={name:"peek",emoji:"๐",type:"effect",description:"Quick peek and hide motion",config:{peekDistance:40,peekSpeed:.15,holdDuration:200,hideSpeed:.25,stagger:!0,duration:1500},rhythm:{enabled:!0,syncMode:"accent",distanceSync:{onAccent:60,offAccent:25,curve:"quick"},speedSync:{mode:"tempo",fast:.25,slow:.1,hideMultiplier:1.8},durationSync:{mode:"subdivision",beats:.25,staggerBeats:.125,sustain:!1},syncopationResponse:{enabled:!0,multiplier:1.8,type:"distance"},patternOverrides:{funk:{distanceSync:{onAccent:70,offAccent:35,curve:"funky"},syncopationResponse:{multiplier:2.2}},latin:{speedSync:{fast:.3,slow:.12},durationSync:{beats:.5,staggerBeats:.25}},breakbeat:{distanceSync:{onAccent:55,offAccent:40},syncopationResponse:{multiplier:2.5}},classical:{distanceSync:{onAccent:45,offAccent:20,curve:"elegant"},speedSync:{fast:.18,slow:.08}}},dynamics:{forte:{distanceSync:{onAccent:{multiplier:1.6},offAccent:{multiplier:1.3}},speedSync:{multiplier:1.4},syncopationResponse:{multiplier:2.8}},piano:{distanceSync:{onAccent:{multiplier:.6},offAccent:{multiplier:.4}},speedSync:{multiplier:.7},syncopationResponse:{multiplier:1.2}}}},apply(e,t,i,s,n,a){if(e.gestureData||(e.gestureData={}),!e.gestureData.peek){const t=e.x-n,i=e.y-a,s=Math.atan2(i,t),r=Math.sqrt(t*t+i*i);e.gestureData.peek={originalX:e.x,originalY:e.y,peekAngle:s,originalDistance:r,staggerDelay:this.config.stagger?.3*Math.random():0,phase:"waiting",phaseTimer:0,peekOffset:{x:0,y:0}}}const r=e.gestureData.peek,{config:o}=this,l=Math.max(0,Math.min(1,(t-r.staggerDelay)/(1-r.staggerDelay)));0===l?r.phase="waiting":l<.3?r.phase="peeking":l<.6?r.phase="holding":l<1&&(r.phase="hiding");let h=0;switch(r.phase){case"peeking":{const e=l/.3;h=this.easeOutCubic(e)*o.peekDistance;break}case"holding":h=o.peekDistance,Math.random()<.1&&(r.peekOffset.x+=2*(Math.random()-.5),r.peekOffset.y+=2*(Math.random()-.5));break;case"hiding":{const e=(l-.6)/.4;h=(1-this.easeInCubic(e))*o.peekDistance;break}}if("waiting"!==r.phase){const t=Math.cos(r.peekAngle)*h,i=Math.sin(r.peekAngle)*h;r.peekOffset.x+=(t-r.peekOffset.x)*o.peekSpeed,r.peekOffset.y+=(i-r.peekOffset.y)*o.peekSpeed,e.x=r.originalX+r.peekOffset.x,e.y=r.originalY+r.peekOffset.y}void 0!==e.alpha&&("peeking"===r.phase||"holding"===r.phase?e.alpha=.7+.3*Math.random():e.alpha=1)},easeOutCubic:e=>1-Math.pow(1-e,3),easeInCubic:e=>e*e*e,cleanup(e){e.gestureData?.peek&&(e.x=e.gestureData.peek.originalX,e.y=e.gestureData.peek.originalY,void 0!==e.alpha&&(e.alpha=1),delete e.gestureData.peek)},"3d":{evaluate(e,t){const i=.01*({...this.config,...t}.peekDistance||40);let s=0,n=1;if(e<.3){const t=e/.3;s=(1-Math.pow(1-t,3))*i}else if(e<.6)s=i,n=.7+.3*Math.random();else{const t=(e-.6)/.4;s=(1-Math.pow(t,3))*i}return{position:[s,0,0],rotation:[0,0,0],scale:1,glowIntensity:n}}}},mi={name:"directional",emoji:"โก๏ธ",type:"blending",description:"Move particles in a specific direction",config:{angle:0,returnToOrigin:!1,strength:1},rhythm:{enabled:!0,syncMode:"flow",angleSync:{verse:0,chorus:90,bridge:180,outro:270,transition:"smooth"},strengthSync:{onBeat:1.8,offBeat:.6,curve:"wave"},returnSync:{enabled:!0,onSectionChange:!0,duration:"transition",strength:1.2},accentResponse:{enabled:!0,multiplier:2,type:"strength"},patternOverrides:{march:{angleSync:{verse:0,chorus:0},strengthSync:{onBeat:2.5,offBeat:1}},waltz:{angleSync:{verse:45,chorus:135,bridge:225,outro:315,transition:"circular"}},swing:{strengthSync:{onBeat:1.6,offBeat:1.4,swing:!0}},electronic:{angleSync:{transition:"instant"},strengthSync:{onBeat:2.2,offBeat:.4,curve:"sharp"}}},dynamics:{forte:{strengthSync:{onBeat:{multiplier:1.6},offBeat:{multiplier:1.2}},angleSync:{transition:"sharp"},accentResponse:{multiplier:2.5}},piano:{strengthSync:{onBeat:{multiplier:.7},offBeat:{multiplier:.8}},angleSync:{transition:"gradual"},accentResponse:{multiplier:1.4}}}},initialize(e){e.gestureData||(e.gestureData={}),e.gestureData.directional={initialX:e.x,initialY:e.y}},apply(e,t,i,s,n,a){e.gestureData?.directional||this.initialize(e);const r=(i.angle||this.config.angle)*Math.PI/180,o=i.strength||this.config.strength;if(e.vx+=Math.cos(r)*o*.3*s,e.vy+=Math.sin(r)*o*.3*s,i.returnToOrigin&&t>.5){const i=2*(t-.5),n=e.gestureData.directional,a=n.initialX-e.x,r=n.initialY-e.y;e.vx+=a*i*.02*s,e.vy+=r*i*.02*s}},"3d":{evaluate(e,t){const i={...this.config,...t},s=(i.angle||0)*Math.PI/180,n=t.strength||1,a=i.returnToOrigin?e<.5?2*e:2*(1-e):e;return{position:[Math.cos(s)*a*.4*n,Math.sin(s)*a*.4*n,0],rotation:[0,0,0],scale:1,glowIntensity:1}}}};function pi(e){if(!["forward","back","left","right","up","down","attract","repel"].includes(e))throw new Error(`Invalid magnetic direction: ${e}`);return{name:`magnetic${D(e)}`,emoji:{forward:"๐งฒ",back:"๐งฒ",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ",attract:"๐งฒ",repel:"๐ฅ"}[e],type:"effect",description:{forward:"Magnetic pull toward camera",back:"Magnetic push away from camera",left:"Magnetic pull leftward",right:"Magnetic pull rightward",up:"Magnetic pull upward",down:"Magnetic pull downward",attract:"Magnetic attraction to center",repel:"Magnetic repulsion from center"}[e],config:{duration:1200,musicalDuration:{musical:!0,beats:3},direction:e,pullStrength:1,returnToOrigin:!0,strength:1,particleMotion:{type:"magnetic",strength:1,direction:e}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",strengthSync:{onBeat:1.5,offBeat:.7}},initialize(e,t,i,s){e.gestureData||(e.gestureData={}),e.gestureData.magnetic={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??1,initialized:!0}},apply(e,t,i,s,n,a){e.gestureData?.magnetic?.initialized||this.initialize(e,i,n,a);const r={...this.config,...i},o=r.strength||1,l=r.pullStrength||1,h=!1!==r.returnToOrigin,c=e.gestureData.magnetic,u=r.direction||"attract";let d,g,m;switch(d=h?Math.sin(t*Math.PI):Math.min(1,2*t),u){case"left":g=c.originalX-100,m=c.originalY;break;case"right":g=c.originalX+100,m=c.originalY;break;case"up":g=c.originalX,m=c.originalY-100;break;case"down":g=c.originalX,m=c.originalY+100;break;case"repel":{const e=c.originalX-n,t=c.originalY-a,i=Math.sqrt(e*e+t*t)||1;g=c.originalX+e/i*100,m=c.originalY+t/i*100;break}default:g=n,m=a}const p=(g-c.originalX)*d*l*o*.5,f=(m-c.originalY)*d*l*o*.5;e.x=c.originalX+p,e.y=c.originalY+f},cleanup(e){if(e.gestureData?.magnetic){const t=e.gestureData.magnetic;e.x=t.originalX,e.y=t.originalY,e.opacity=t.originalOpacity,delete e.gestureData.magnetic}},"3d":{evaluate(e,t){const i=t.config||this.config||{},s=i.strength||1,n=i.direction||"attract";let a;a=!1!==i.returnToOrigin?Math.sin(e*Math.PI):Math.min(1,2*e);let r=0,o=0,l=0,h=1;const c=.15*a*s;switch(n){case"forward":l=c,h=1+.1*a*s;break;case"back":l=-c,h=1-.08*a*s;break;case"left":r=-c;break;case"right":r=c;break;case"up":o=c;break;case"down":o=-c;break;case"attract":l=c,h=1-.1*a*s;break;case"repel":l=-c,h=1+.1*a*s}const u=1+.4*a,d=.3*a;return{cameraRelativePosition:[r+(a>.5?.01*Math.sin(e*Math.PI*20)*(a-.5)*2:0),o,l],rotation:[0,0,0],scale:h,glowIntensity:u,glowBoost:d}}}}}const fi={name:"sparkle",emoji:"โจ",type:"blending",description:"Bright twinkling sparkle bursts",config:{duration:800,musicalDuration:{musical:!0,beats:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:2},interruptible:!0,priority:5,blendable:!0},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i=t?.strength||1,s=Math.pow(Math.max(0,Math.sin(e*Math.PI*6)),3),n=Math.pow(Math.max(0,Math.sin(e*Math.PI*8+1)),3),a=Math.pow(Math.max(0,Math.sin(e*Math.PI*10+2)),3),r=Math.max(s,n,a)*Math.sin(e*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1+.08*r*i,glowIntensity:1+.5*r*i,glowBoost:2*r*i}}}},yi={name:"shimmer",emoji:"๐",type:"particle",description:"Shimmer effect with sparkling particles",config:{duration:2e3,musicalDuration:{musical:!0,bars:1},particleMotion:"radiant"},rhythm:{enabled:!0,syncType:"beat",durationSync:{mode:"bars",bars:1},intensity:.8},override:(e,t,i)=>(e.shimmerEffect=!0,e.shimmerProgress=t,!0),blend:(e,t,i)=>!1,"3d":{evaluate(e,t){const i=t?.strength||1,s=(.4*Math.sin(e*Math.PI*4)+.35*Math.sin(e*Math.PI*6+.5)+.25*Math.sin(e*Math.PI*10+1)+1)/2;return{position:[0,0,0],rotation:[0,0,0],scale:1+.05*s*i,glowIntensity:1+.3*s*i,glowBoost:1*s*i}}}},bi=((e,t="โจ")=>({name:e,emoji:t,type:"blending",description:`${e} animation`,config:{duration:1e3,musicalDuration:{musical:!0,beats:2}},rhythm:{enabled:!0,syncMode:"beat",timingSync:"nextBeat",durationSync:{mode:"beats",beats:2},interruptible:!0,priority:3,blendable:!0,crossfadePoint:"anyBeat",maxQueue:3},apply:(e,t,i)=>!1,blend:(e,t,i)=>!1}))("groove","๐ต"),vi={},Mi=[],wi=[],Si=[];function xi(e,t){vi[e.name]=e,t.push(e.name)}function Ci(e,t,i){Object.defineProperty(vi,e,{configurable:!0,enumerable:!0,get(){const i=t();return Object.defineProperty(vi,e,{configurable:!0,enumerable:!0,writable:!0,value:i}),i}}),i.push(e)}[le,P,$,Ge,j,H,T,E,G,fi,yi,W,bi,De,F,He,je,se,ae,re,oe,ne,Y,X,N,Q,J,K,L,q,Oe,Le,I,R,B,z,Ie,Re,Be,ze,x,C,k,dt,gt,ct,ut,te,he,ue,de,ge,me,ie,Z,ee].forEach(e=>xi(e,Mi)),[xe,Pe,Te,pe,ye,be,ve,Tt,nt,We,Ve,Ye,Xe,Ne,St,Ee,Ae,$e,we,Je,qe,tt,it,st,et,Ze,pt,ft,yt,bt,vt,Mt,wt,rt,ot,lt,ht,at].forEach(e=>xi(e,wi)),Ci("lungeForward",()=>Se("forward"),wi),Ci("lungeBack",()=>Se("back"),wi),Ci("lungeLeft",()=>Se("left"),wi),Ci("lungeRight",()=>Se("right"),wi),Ci("lungeUp",()=>Se("up"),wi),Ci("lungeDown",()=>Se("down"),wi),Ci("recoilBack",()=>Ke("back"),wi),Ci("recoilForward",()=>Ke("forward"),wi),Ci("recoilLeft",()=>Ke("left"),wi),Ci("recoilRight",()=>Ke("right"),wi),Ci("recoilUp",()=>Ke("up"),wi),Ci("recoilDown",()=>Ke("down"),wi),Ci("oofLeft",()=>Qe("left"),wi),Ci("oofRight",()=>Qe("right"),wi),Ci("oofFront",()=>Qe("front"),wi),Ci("oofBack",()=>Qe("back"),wi),Ci("oofUp",()=>Qe("up"),wi),Ci("oofDown",()=>Qe("down"),wi),Ci("shatter",()=>Ct("default"),wi),Ci("shatterExplosive",()=>Ct("explosive"),wi),Ci("shatterCrumble",()=>Ct("crumble"),wi),Ci("shatterReform",()=>Ct("reform"),wi),Ci("shatterPunchLeft",()=>Ct("punchLeft"),wi),Ci("shatterPunchRight",()=>Ct("punchRight"),wi),Ci("shatterPunchFront",()=>Ct("punchFront"),wi),Ci("shatterSuspend",()=>Ct("suspend"),wi),Ci("shatterImplode",()=>Ct("implode"),wi),Ci("shatterGravity",()=>Ct("gravity"),wi),Ci("shatterOrbit",()=>Ct("orbit"),wi),Ci("dissolveUp",()=>Pt("up"),wi),Ci("dissolveDown",()=>Pt("down"),wi),Ci("dissolveLeft",()=>Pt("left"),wi),Ci("dissolveRight",()=>Pt("right"),wi),Ci("dissolveAway",()=>Pt("away"),wi),Ci("dissolveToward",()=>Pt("toward"),wi),Ci("rushForward",()=>Me("forward"),wi),Ci("rushBack",()=>Me("back"),wi),Ci("rushLeft",()=>Me("left"),wi),Ci("rushRight",()=>Me("right"),wi),Ci("rushUp",()=>Me("up"),wi),Ci("rushDown",()=>Me("down"),wi),[ti,At,_t,It,Rt,Bt,ai,Xt,mi,di,ui,ci,ii,si,gi,Et,ri,oi,Ht,jt,Ot,Lt,qt,Gt,Qt,Jt,Kt,Zt,ei,hi,Wt,Ut,Vt,Yt,ni,li,zt].forEach(e=>xi(e,Si)),Ci("magneticForward",()=>pi("forward"),Si),Ci("magneticBack",()=>pi("back"),Si),Ci("magneticLeft",()=>pi("left"),Si),Ci("magneticRight",()=>pi("right"),Si),Ci("magneticUp",()=>pi("up"),Si),Ci("magneticDown",()=>pi("down"),Si),Ci("magneticAttract",()=>pi("attract"),Si),Ci("magneticRepel",()=>pi("repel"),Si);const ki={blending:Mi,override:wi,effect:Si},Pi={idle:["breathe","expand","contract","pulse","sway","float","floatUp","floatDown","floatLeft","floatRight","bob","lean","leanLeft","leanRight","jitter","twitch","vibrate","shake","wiggle"],dance:["stepLeft","stepRight","stepUp","stepDown","slideLeft","slideRight","runningman","charleston","hula","twist","pop","flare","swell","swagger","dip","bounce","orbit","orbitLeft","orbitRight","orbitUp","orbitDown","sparkle","shimmer","groove"],actions:["jump","jumpDown","jumpLeft","jumpRight","rushForward","rushBack","rushLeft","rushRight","rushUp","rushDown","lunge","lungeForward","lungeBack","lungeLeft","lungeRight","lungeUp","lungeDown","spin","spinLeft","spinRight","flip","backflip","point","pointUp","pointDown","pointLeft","pointRight","kickLeft","kickRight","bow","nod","reach","headBob","crouch","tilt","tiltUp","tiltDown","tiltLeft","tiltRight"],reactions:["oofLeft","oofRight","oofFront","oofBack","oofUp","oofDown","recoil","recoilBack","recoilForward","recoilLeft","recoilRight","recoilUp","recoilDown","knockdown","knockout","inflate","deflate","squash","stretch","pancake","crackFront","crackBack","crackLeft","crackRight","crackUp","crackDown","crackHeal","rage","fury","battlecry","charge","wobble","teeter","rock","pendulum"],destruction:["shatter","shatterMesh","shatterExplosive","shatterCrumble","shatterReform","shatterPunchLeft","shatterPunchRight","shatterPunchFront","shatterSuspend","shatterImplode","shatterGravity","shatterOrbit","dissolveUp","dissolveDown","dissolveLeft","dissolveRight","dissolveAway","dissolveToward","splash","drench","soak","flow","tide","liquefy","poolWater","vortexWater","watercrown","waterdance","waterdrill","waterhelix","watermeditation","waterpillar","waterflourish","waterbarrage","waterimpact","watercrush","watertwirl","watershield","smokebomb","vanish","materialize","phoenix","burn","scorch","combust","flameVortex","firedance","fireflourish","firecrown","firemeditation","firedrill","firepillar","firehelix","firebarrage","fireimpact","fireblast","radiate","blaze","firetwirl","fireshield","puff","billow","fume","shroud","hazeSmoke","chokeSmoke","iceFreeze","shatterIce","shock","overload","glitch","crackle","chargeUp","electricAuraEffect","staticDischarge","electriccrown","electricdance","electrichelix","electricpillar","electricdrill","electricflourish","electricvortex","electricbarrage","electricimpact","electricblast","electricsurge","electriczap","electricmeditation","electrictwirl","electricshield","zap","drain","hollow","corrupt","consume","singularity","voidcrown","voiddance","voidhelix","voidpillar","voiddrill","voidflourish","voidvortex","voidbarrage","voidimpact","voidmeditation","voidtwirl","voidshield","iceCrown","iceDance","icePillar","iceHelix","iceMeditation","iceVortex","iceSplash","iceEncase","iceDrill","iceFlourish","iceBarrage","iceImpact","icemist","iceshiver","icetwirl","iceshield","lightBlind","lightPurify","lightCleanse","lightRadiate","lightGlow","lightBeacon","lightAscend","lightIlluminate","lightDissolve","lightMeditation","lightcrown","lightdance","lighthelix","lightpillar","lightdrill","lightflourish","lightvortex","lightbarrage","lightimpact","lightblast","lightsurge","lightmeditation","lighttwirl","lightshield","poisonInfect","poisonSicken","poisonOoze","poisonSeep","poisonToxic","poisonCorrode","poisonMelt","poisonDecay","poisonDissolve","earthPetrify","earthBurden","earthRumble","earthQuake","earthMeditation","earthEncase","earthCrumble","earthShatter","earthErode","earthcrown","earthdance","earthhelix","earthpillar","earthdrill","earthflourish","earthvortex","earthbarrage","earthimpact","earthblast","earthsurge","earthmeditation","earthtwirl","earthshield","morph"],atmosphere:["rain","drift","driftUp","driftDown","driftLeft","driftRight","vortex","cascadeUp","cascadeDown","cascadeLeft","cascadeRight","confetti","fizz","swarmUp","swarmDown","swarmLeft","swarmRight","burst","burstUp","burstDown","burstLeft","burstRight","ripple","wave","flash","glow","bloom","flicker","shiver","heartbeat","snap","elasticBounce","hold","fade","settle","peek","directional","magneticForward","magneticBack","magneticLeft","magneticRight","magneticUp","magneticDown","magneticAttract","magneticRepel"]},Ti={};function Ei(e){return Ti[e]||"atmosphere"}function Ai(e){if(vi[e])return vi[e];return S.getPluginGesture(e)||null}function Di(e){const t=Ai(e);return!!t&&"blending"===t.type}function _i(e){const t=Ai(e);return!!t&&"override"===t.type}function Ii(e,t,i,s,n,a,r){const o=Ai(t);return!!o&&(o.apply&&o.apply(e,i,s,n,a,r),i>=1&&o.cleanup&&o.cleanup(e),!0)}function Ri(){const e=[];return Object.values(vi).forEach(t=>{e.push({name:t.name,emoji:t.emoji||"๐ญ",type:t.type,category:Ti[t.name]||"atmosphere",description:t.description||"No description",source:"core",usesShatter:t.usesShatter||!1})}),S.getAllPluginGestures().forEach(t=>{const i=S.getPluginGesture(t);e.push({name:i.name,emoji:i.emoji||"๐",type:i.type,category:i.category||"effect",description:i.description||"Plugin gesture",source:"plugin"})}),e}function Bi(e){return vi[e]||null}function zi(){return Object.keys(vi).filter(e=>{const t=Object.getOwnPropertyDescriptor(vi,e);return t&&"function"==typeof t.get})}Object.entries(Pi).forEach(([e,t])=>{t.forEach(t=>{Ti[t]=e})});var Fi={GESTURE_REGISTRY:vi,GESTURE_TYPES:ki,GESTURE_CATEGORIES:Pi,GESTURE_TO_CATEGORY:Ti,getGesture:Ai,getGestureCategory:Ei,isBlendingGesture:Di,isOverrideGesture:_i,applyGesture:Ii,listGestures:Ri,pluginAdapter:S},Oi=Object.freeze({__proto__:null,GESTURE_CATEGORIES:Pi,GESTURE_REGISTRY:vi,GESTURE_TO_CATEGORY:Ti,GESTURE_TYPES:ki,applyGesture:Ii,default:Fi,getGesture:Ai,getGestureCategory:Ei,getLazyGestureNames:zi,isBlendingGesture:Di,isOverrideGesture:_i,listGestures:Ri,pluginAdapter:S,resolveGesture:Bi,warmUpGestures:function({onBatch:e,onComplete:t}={}){const i=Object.keys(vi);e&&e(i.map(e=>({name:e,category:Ti[e]||"atmosphere",source:"core"})));try{const t=[];S.getAllPluginGestures().forEach(e=>{const i=S.getPluginGesture(e);t.push({name:i.name,emoji:i.emoji||"๐",type:i.type,category:i.category||"effect",description:i.description||"Plugin gesture",source:"plugin"})}),t.length&&e&&e(t)}catch{}return t&&t(),zi().map(e=>()=>Bi(e))}});function Li(e){if(!e||0===e.length)return"#FFFFFF";let t=0,i=0;const s=[];for(const n of e)"string"==typeof n?(s.push({color:n,weight:null}),i++):n&&"object"==typeof n&&n.color&&(s.push({color:n.color,weight:n.weight||null}),n.weight?t+=n.weight:i++);const n=Math.max(0,100-t),a=i>0?n/i:0,r=[];let o=0;for(const e of s)o+=null!==e.weight?e.weight:a,r.push({color:e.color,threshold:o});const l=Math.random()*o;for(const e of r)if(l<=e.threshold)return e.color;return s[s.length-1].color}var qi={name:"ambient",emoji:"โ๏ธ",description:"Gentle upward drift like smoke",initialize:function(e){e.vx=0,e.vy=-.04-.02*Math.random(),e.lifeDecay=.002,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={upwardSpeed:5e-4,waviness:0,friction:.998}},update:function(e,t,i,s){const n=e.behaviorData;e.vy*=Math.pow(n.friction,t),e.vy-=n.upwardSpeed*t,e.vx=0}};const Gi=2*Math.PI;var Hi={name:"orbiting",emoji:"๐",description:"Romantic firefly dance around the orb",initialize:function(e){e.lifeDecay=.001+.002*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.isSparkle="#FFE4E1"===e.color||"#FFCCCB"===e.color||"#FFC0CB"===e.color;const t=40*(e.scaleFactor||1)*(1.3+.9*Math.random());e.blinkPhase=Math.random()*Gi,e.blinkSpeed=.3+1.2*Math.random(),e.blinkIntensity=.6+.4*Math.random(),e.fadePhase=Math.random()*Gi,e.fadeSpeed=.1+.3*Math.random(),e.minOpacity=.2+.2*Math.random(),e.maxOpacity=.8+.2*Math.random(),e.isSparkle&&(e.blinkSpeed*=2,e.blinkIntensity=1,e.minOpacity=0,e.maxOpacity=1),e.behaviorData={angle:Math.random()*Gi,radius:t,baseRadius:t,angularVelocity:8e-4+.0017*Math.random(),swayAmount:3+7*Math.random(),swaySpeed:.2+.5*Math.random(),floatOffset:Math.random()*Gi,floatSpeed:.3+.7*Math.random(),floatAmount:2+6*Math.random(),twinklePhase:Math.random()*Gi,twinkleSpeed:2+3*Math.random()}},update:function(e,t,i,s){const n=e.behaviorData;n.angle+=n.angularVelocity*t;const a=Math.sin(n.angle*n.swaySpeed)*n.swayAmount,r=6*Math.sin(1.5*n.angle),o=(n.radius||n.baseRadius)+r+.2*a,l=i+Math.cos(n.angle)*o,h=s+Math.sin(n.angle)*o;n.floatOffset+=n.floatSpeed*t*.001;const c=Math.sin(n.floatOffset)*n.floatAmount;e.vx=.1*(l-e.x),e.vy=.1*(h+c-e.y),e.fadePhase+=e.fadeSpeed*t*.001;const u=.5*Math.sin(e.fadePhase)+.5,d=e.minOpacity+(e.maxOpacity-e.minOpacity)*u;let g;e.blinkPhase+=e.blinkSpeed*t*.002,e.isSparkle?(n.twinklePhase+=n.twinkleSpeed*t*.001,g=.7*Math.pow(Math.sin(n.twinklePhase),16)+.2*Math.sin(5*e.blinkPhase)+.1):g=.4*Math.sin(e.blinkPhase)+.3*Math.sin(3*e.blinkPhase)+.2*Math.sin(7*e.blinkPhase)+.1*Math.sin(11*e.blinkPhase);const m=.5*(g+1),p=.2+m*e.blinkIntensity*.8;e.opacity=e.baseOpacity*d*p,e.isSparkle?e.size=e.baseSize*(.5+1*m):e.size=e.baseSize*(.8+.3*m),e.isSparkle&&(e.tempColor=m>.85?"#FFFFFF":e.color)}},ji={name:"rising",emoji:"๐",description:"Buoyant upward movement like balloons",initialize:function(e){e.vx=.02*(Math.random()-.5),e.vy=-.05-.03*Math.random(),e.lifeDecay=.002,e.baseOpacity=.7+.3*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={buoyancy:.001,driftAmount:.005}},update:function(e,t,i,s){const n=e.behaviorData;e.vy-=n.buoyancy*t,e.vx+=(Math.random()-.5)*n.driftAmount*t,e.vx*=Math.pow(.995,t),e.vy*=Math.pow(.998,t)}};function $i(e){e.fallingData||(e.fallingData={originalX:e.x,originalY:e.y,originalOpacity:e.opacity??e.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),fallProgress:0}),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors));const t=Math.random(),i=Math.random(),s=t*Math.PI*2,n=2*i-1,a=Math.sqrt(1-n*n);e.behaviorData={fallSpeed:8,fallDistance:400,wobbleAmount:1.5,fallingDir:{x:a*Math.cos(s),y:n,z:a*Math.sin(s)},orbitDistanceRatio:.7+.4*Math.random()}}var Wi={name:"falling",emoji:"๐ง",description:"Heavy downward drift like tears",initialize:$i,update:function(e,t,i,s){const n=e.behaviorData;let a=e.fallingData;a||($i(e),a=e.fallingData),a.fallProgress+=.02*t;const r=Math.min(a.fallProgress,1),o=n.fallDistance*r;a.wobblePhase+=a.wobbleSpeed*t*.1;const l=Math.sin(a.wobblePhase)*n.wobbleAmount;if(e.x=a.originalX+l,e.y=a.originalY+o,e.vx=.3*l,e.vy=10*n.fallSpeed,r>.6){const t=(r-.6)/.4;e.opacity=a.originalOpacity*(1-t),void 0!==e.life&&(e.life=a.originalOpacity*(1-t))}}};const Ui=2e3,Vi=3,Yi=8,Xi=.7;var Ni={name:"popcorn",emoji:"๐ฟ",description:"Spontaneous popping with gravity and bounces",initialize:function(e){if(e.vx=.1*(Math.random()-.5),e.vy=.1*(Math.random()-.5),e.lifeDecay=.008+.012*Math.random(),e.emotionColors&&e.emotionColors.length>0)e.color=Li(e.emotionColors);else{const t=["#FFFFFF","#FFFACD","#FFF8DC","#FFFFE0","#FAFAD2"];e.color=Li(t)}e.size=Math.random()<.3?(8+4*Math.random())*e.scaleFactor*e.particleSizeMultiplier:(2+4*Math.random())*e.scaleFactor*e.particleSizeMultiplier,e.baseSize=e.size,e.hasGlow=Math.random()<.2,e.glowSizeMultiplier=e.hasGlow?1.2:0,e.behaviorData={popDelay:Math.random()*Ui,hasPopped:!1,popStrength:Vi+Math.random()*(Yi-Vi),gravity:.098,bounceDamping:Xi,bounceCount:0,maxBounces:2+Math.floor(2*Math.random()),spinRate:10*(Math.random()-.5),lifetime:0}},update:function(e,t,i,s){const n=e.behaviorData;if(n.lifetime+=16.67*t,!n.hasPopped&&n.lifetime>n.popDelay){n.hasPopped=!0;const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*n.popStrength*1.5,e.vy=Math.sin(t)*n.popStrength-.3,e.size=1.25*e.baseSize}if(n.hasPopped){e.vy+=n.gravity*t;const i=s+100*e.scaleFactor;e.y>i&&n.bounceCount<n.maxBounces&&(e.y=i,e.vy=-Math.abs(e.vy)*n.bounceDamping,e.vx*=.9,n.bounceCount++,e.size=e.baseSize*(1.5-.1*n.bounceCount)),n.bounceCount>=n.maxBounces&&(e.lifeDecay=.03+.02*Math.random(),e.size*=.95),Math.sqrt(e.vx*e.vx+e.vy*e.vy)<.5&&(e.lifeDecay*=1.5)}}},Qi={name:"burst",emoji:"๐ฅ",description:"Explosive expansion from center",initialize:function(e){const t="suspicion"===e.emotion,i="surprise"===e.emotion,s="glitch"===e.emotion,n=Math.random()*Gi,a=t?1+.8*Math.random():i?7+5*Math.random():s?2+1.5*Math.random():3.5+2.5*Math.random();e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a,e.lifeDecay=t?.01:i?.006+.008*Math.random():s?.012:.015,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),t&&(e.size=(6+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.opacity=1,e.baseOpacity=e.opacity),e.behaviorData={isSuspicion:t,isSurprise:i,isGlitch:s,age:0,fadeStart:t?.3:.2,glitchPhase:Math.random()*Math.PI*2,glitchIntensity:s?.3:0,glitchFrequency:s?.1:0}},update:function(e,t,i,s){const n=e.behaviorData;if(n.isSurprise)if(n.age+=.016*t,n.age<.15){const i=.98;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}else if(n.age<.25){const i=.85;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}else{const i=.99;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t),e.vx+=.01*(Math.random()-.5)*t,e.vy+=.01*(Math.random()-.5)*t}else{const i=n.isSuspicion?.99:n.isGlitch?.97:.95;e.vx*=Math.pow(i,t),e.vy*=Math.pow(i,t)}if(n.isSuspicion){const i=.001*Date.now();e.vx+=.01*Math.sin(2*i+e.id)*t}if(n.isGlitch){n.age+=.016*t,n.glitchPhase+=n.glitchFrequency*t;const i=Math.sin(n.glitchPhase)*n.glitchIntensity*t,s=Math.cos(1.3*n.glitchPhase)*n.glitchIntensity*t;if(e.vx+=i,e.vy+=s,Math.random()<.02){const t=Math.random()*Math.PI*2,i=.5+.5*Math.random();e.vx+=Math.cos(t)*i,e.vy+=Math.sin(t)*i}}}},Ji={name:"aggressive",emoji:"โก",description:"Sharp, chaotic movement with violent bursts",initialize:function(e){const t=Math.random()*Gi,i=1.5+2*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.015,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={acceleration:.05,jitter:.3,speedDecay:.95}},update:function(e,t,i,s){const n=e.behaviorData;if(e.vx+=(Math.random()-.5)*n.jitter*t,e.vy+=(Math.random()-.5)*n.jitter*t,e.vx*=Math.pow(n.speedDecay,t),e.vy*=Math.pow(n.speedDecay,t),Math.random()<Math.min(.05*t,.5)){const t=Math.random()*Gi;e.vx+=Math.cos(t)*n.acceleration,e.vy+=Math.sin(t)*n.acceleration}}},Ki={name:"scattering",emoji:"๐จ",description:"Particles flee from center in panic",initialize:function(e){e.vx=0,e.vy=0,e.lifeDecay=.008,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={fleeSpeed:2,panicFactor:1.2,initialized:!1}},update:function(e,t,i,s){const n=e.behaviorData;if(!n.initialized){const t=e.x-i,a=e.y-s,r=Math.sqrt(t*t+a*a);if(r>0)e.vx=t/r*n.fleeSpeed,e.vy=a/r*n.fleeSpeed;else{const t=Math.random()*Gi;e.vx=Math.cos(t)*n.fleeSpeed,e.vy=Math.sin(t)*n.fleeSpeed}n.initialized=!0}const a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);o>0&&(e.vx+=a/o*n.panicFactor*.01*t,e.vy+=r/o*n.panicFactor*.01*t),e.vx+=.1*(Math.random()-.5)*t,e.vy+=.1*(Math.random()-.5)*t,e.vx*=Math.pow(.98,t),e.vy*=Math.pow(.98,t)}},Zi={name:"repelling",emoji:"๐ซ",description:"Particles pushed away from center, maintaining distance",initialize:function(e){e.vx=0,e.vy=0,e.lifeDecay=.01,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={repelStrength:.8,minDistance:50,initialized:!1}},update:function(e,t,i,s){const n=e.behaviorData,a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(!n.initialized||o<n.minDistance){if(o>0){const i=n.repelStrength/Math.max(o,5);e.vx+=a/o*i*t,e.vy+=r/o*i*t}n.initialized=!0}e.vx*=Math.pow(.99,t),e.vy*=Math.pow(.99,t)}},es={name:"connecting",emoji:"๐",description:"Chaotic movement with center attraction for social states",initialize:function(e){const t=Math.random()*Gi,i=2+5*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.012,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={attractionForce:.008,chaosFactor:1,friction:.95}},update:function(e,t,i,s){const n=e.behaviorData;e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t);const a=(i-e.x)*n.attractionForce,r=(s-e.y)*n.attractionForce,o=(Math.random()-.5)*n.chaosFactor,l=(Math.random()-.5)*n.chaosFactor;e.vx+=a+o,e.vy+=r+l}},ts={name:"resting",emoji:"๐ด",description:"Ultra-slow vertical drift for deep rest states",initialize:function(e){e.vx=0,e.vy=-.01,e.lifeDecay=.001,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={upwardSpeed:2e-5,friction:.999}},update:function(e,t,i,s){const n=e.behaviorData;e.vy*=Math.pow(n.friction,t),e.vy-=n.upwardSpeed*t,e.vx=0}},is={name:"radiant",emoji:"โ๏ธ",description:"Particles radiate outward like sunbeams",initialize:function(e){const t=Math.random()*Gi,i=.8+.4*Math.random();if(e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.006,e.emotionColors&&e.emotionColors.length>0)e.color=Li(e.emotionColors);else{const t=["#FFD700","#FFB347","#FFA500","#FF69B4"];e.color=Li(t)}e.hasGlow=Math.random()<.7,e.glowSizeMultiplier=e.hasGlow?1.5+.5*Math.random():0,e.behaviorData={radialSpeed:.02,shimmer:Math.random()*Gi,shimmerSpeed:.1,friction:.99}},update:function(e,t,i,s){const n=e.behaviorData,a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(o>0){const i=a/o,s=r/o;e.vx+=i*n.radialSpeed*t,e.vy+=s*n.radialSpeed*t}n.shimmer+=n.shimmerSpeed*t;const l=Math.sin(n.shimmer);e.size=e.baseSize*(1+.2*l),e.opacity=e.baseOpacity*(1+.3*l),e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t)}};function ss(e){e.vx=.02*(Math.random()-.5),e.vy=-.03-.02*Math.random(),e.lifeDecay=8e-4,e.size=(6+6*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1)*1.33,e.baseSize=e.size,e.baseOpacity=.2+.2*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={ascensionSpeed:3e-4,waveFactor:.5,waveFrequency:.001,friction:.998,fadeStartDistance:100}}var ns={name:"ascending",emoji:"๐ง",description:"Slow steady upward float like incense smoke",initialize:ss,update:function(e,t,i,s){const n=e.behaviorData;if(!n)return void ss(e);e.vx*=Math.pow(n.friction,t),e.vy*=Math.pow(n.friction,t),e.vy-=n.ascensionSpeed*t;const a=Math.sin(e.age*n.waveFrequency*1e3)*n.waveFactor;e.vx+=.001*a*t,void 0===e.initialY&&(e.initialY=e.y);const r=e.initialY-e.y;if(r>n.fadeStartDistance){const t=(r-n.fadeStartDistance)/100,i=Math.max(0,1-t);e.baseOpacity*=.995,i<.5&&(e.lifeDecay*=1.02)}Math.abs(e.vx)>.05&&(e.vx*=Math.pow(.95,t)),e.vy<-.1&&(e.vy=-.1)}},as={name:"erratic",emoji:"๐ฐ",description:"Nervous jittery movement for anxious states",initialize:function(e){const t=Math.random()*Gi,i=.1+.15*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.004,e.size=(2+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.baseOpacity=.4+.3*Math.random(),e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={jitterStrength:.02,directionChangeRate:.1,speedVariation:.3,spinRate:.05+.1*Math.random()}},update:function(e,t){const i=e.behaviorData;if(e.vx+=(Math.random()-.5)*i.jitterStrength*t,e.vy+=(Math.random()-.5)*i.jitterStrength*t,Math.random()<Math.min(i.directionChangeRate*t,.5)){const t=Math.random()*Gi,i=Math.sqrt(e.vx*e.vx+e.vy*e.vy);e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i}const s=1+(Math.random()-.5)*i.speedVariation*t;e.vx*=s,e.vy*=s;const n=e.age*i.spinRate*1e3;e.size=e.baseSize*(1+.2*Math.sin(n)),e.opacity=e.baseOpacity*(.8+.4*Math.random()),e.vx*=Math.pow(.98,t),e.vy*=Math.pow(.98,t);const a=Math.sqrt(e.vx*e.vx+e.vy*e.vy);a>.5&&(e.vx=e.vx/a*.5,e.vy=e.vy/a*.5)}},rs={name:"cautious",emoji:"๐คจ",description:"Slow careful movement with watchful pauses",initialize:function(e){const t=Math.random()*Gi,i=.02+.03*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,e.lifeDecay=.001,e.life=1,e.size=(4+4*Math.random())*(e.scaleFactor||1)*(e.particleSizeMultiplier||1),e.baseSize=e.size,e.baseOpacity=.8+.2*Math.random(),e.opacity=e.baseOpacity,e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorData={pauseTimer:2*Math.random(),pauseDuration:.5+.5*Math.random(),moveDuration:1+.5*Math.random(),isMoving:Math.random()>.5,moveTimer:0,originalVx:e.vx,originalVy:e.vy,watchRadius:50+30*Math.random()}},update:function(e,t,i,s){const n=e.behaviorData;if(n.moveTimer+=t,n.isMoving)n.moveTimer>n.moveDuration?(n.isMoving=!1,n.moveTimer=0,e.vx=0,e.vy=0):(e.vx=n.originalVx,e.vy=n.originalVy);else if(n.moveTimer>n.pauseDuration){n.isMoving=!0,n.moveTimer=0;const t=Math.random()*Gi,i=.02+.03*Math.random();e.vx=Math.cos(t)*i,e.vy=Math.sin(t)*i,n.originalVx=e.vx,n.originalVy=e.vy}const a=e.x-i,r=e.y-s,o=Math.sqrt(a*a+r*r);if(o>n.watchRadius){const i=.02;e.vx-=a/o*i*t,e.vy-=r/o*i*t}e.vx*=Math.pow(.995,t),e.vy*=Math.pow(.995,t),n.isMoving?e.opacity=e.baseOpacity:e.opacity=e.baseOpacity*(.9+.1*Math.sin(5*e.age))}},os={name:"surveillance",emoji:"๐๏ธ",description:"Searchlight scanning with paranoid watchfulness",initialize(e,t){e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorState={scanAngle:Math.random()*Math.PI-Math.PI/2,scanDirection:Math.random()<.5?1:-1,scanSpeed:.3+.2*Math.random(),scanRange:Math.PI/3+Math.random()*Math.PI/4,scanCenter:Math.random()*Math.PI*2,pauseTimer:0,pauseDuration:500+500*Math.random(),mode:"scanning",modeTimer:0,nextModeChange:2e3+3e3*Math.random(),dartTarget:{x:0,y:0},dartSpeed:0,patrolRadius:150+100*Math.random(),patrolAngle:Math.random()*Math.PI*2,alertLevel:0,lastPosition:{x:e.x,y:e.y}};const i=Math.random();i<.7?e.behaviorState.primaryRole="scanner":i<.9?(e.behaviorState.primaryRole="patroller",e.behaviorState.mode="patrolling"):(e.behaviorState.primaryRole="watcher",e.behaviorState.mode="frozen")},update(e,t,i){const s=e.behaviorState;if(s){switch(s.modeTimer+=16*t,s.modeTimer>s.nextModeChange&&(this.changeMode(e,s,i),s.modeTimer=0,s.nextModeChange=2e3+4e3*Math.random()),s.mode){case"scanning":this.updateScanning(e,t,s,i);break;case"darting":this.updateDarting(e,t,s,i);break;case"frozen":this.updateFrozen(e,t,s,i);break;case"patrolling":this.updatePatrolling(e,t,s,i)}e.vy+=.05*t,e.x+=e.vx*t,e.y+=e.vy*t,s.lastPosition.x=e.x,s.lastPosition.y=e.y}},updateScanning(e,t,i,s){i.pauseTimer>0?(i.pauseTimer-=16*t,e.vx*=.9,e.vy*=.9):(i.scanAngle+=i.scanDirection*i.scanSpeed*t*.02,Math.abs(i.scanAngle)>i.scanRange/2&&(i.scanDirection*=-1,i.pauseTimer=i.pauseDuration,i.scanAngle=Math.sign(i.scanAngle)*i.scanRange/2));const n=i.scanCenter+i.scanAngle,a=.8+.5*i.alertLevel;e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a*.3},updateDarting(e,t,i,s){const n=i.dartTarget.x-e.x,a=i.dartTarget.y-e.y,r=Math.sqrt(n*n+a*a);r>5?(e.vx=n/r*i.dartSpeed,e.vy=a/r*i.dartSpeed):(i.mode="scanning",i.modeTimer=0)},updateFrozen(e,t,i,s){e.vx*=.95,e.vy*=.95,Math.random()<.01&&(e.vx+=.5*(Math.random()-.5),e.vy+=.5*(Math.random()-.5))},updatePatrolling(e,t,i,s){i.patrolAngle+=.01*t;const n=s.corePosition?.x??s.canvasWidth/2,a=s.corePosition?.y??s.canvasHeight/2,r=n+Math.cos(i.patrolAngle)*i.patrolRadius,o=a+Math.sin(i.patrolAngle)*i.patrolRadius,l=r-e.x,h=o-e.y;e.vx=.02*l,e.vy=.02*h},changeMode(e,t,i){const s=Math.random(),n=i?.corePosition?.x??(i?.canvasWidth/2||e.x),a=i?.corePosition?.y??(i?.canvasHeight/2||e.y);"scanner"===t.primaryRole?s<.1?(t.mode="darting",t.dartTarget={x:n+200*(Math.random()-.5),y:a+200*(Math.random()-.5)},t.dartSpeed=3+2*Math.random()):t.mode=s<.2?"frozen":"scanning":"patroller"===t.primaryRole?t.mode=s<.1?"frozen":"patrolling":t.mode=s<.3?"scanning":"frozen"}},ls={name:"glitchy",emoji:"โก",description:"Digital glitch with stuttering orbits and corruption",rhythm:{enabled:!0,glitchTiming:{mode:"subdivision",subdivision:"sixteenth",probability:.3,intensityOnBeat:2,intensityOffBeat:.5},stutterSync:{mode:"pattern",patterns:{dubstep:{freezeOnDrop:!0,dropDuration:100},breakbeat:{randomFreeze:.1,duration:50}}},orbitRhythm:{baseSpeed:"tempo",wobbleSync:"eighth",beatAcceleration:1.5,barReset:!0},rgbSync:{enabled:!0,amount:"intensity",direction:"beat",maxSplit:10},noiseRhythm:{trigger:"accent",duration:50,intensity:"drop"}},initialize(e,t,i,s){e.emotionColors&&e.emotionColors.length>0&&(e.color=Li(e.emotionColors)),e.behaviorState={orbitAngle:Math.random()*Math.PI*2,orbitRadius:300+400*Math.random(),orbitSpeed:.01+.02*Math.random(),glitchTimer:0,nextGlitch:500*Math.random()+100,isGlitching:!1,glitchDuration:0,glitchOffset:{x:0,y:0},stutterTimer:0,nextStutter:200*Math.random()+50,isFrozen:!1,frozenPosition:{x:0,y:0},frozenVelocity:{x:0,y:0},hasGhost:Math.random()<.3,ghostOffset:20*Math.random()+10,ghostAngle:Math.random()*Math.PI*2,rgbSplit:Math.random()<.4,rgbPhase:Math.random()*Math.PI*2,noiseLevel:0,noiseBurst:!1,beatPhase:Math.random()*Math.PI*2,beatFrequency:.05+.03*Math.random(),dropIntensity:0},e.lifeDecay=.0015,e.hasGlow=!0,e.glowSizeMultiplier=3+2*Math.random()},update(e,t,i,s){const n=e.behaviorState;if(!n)return;n.glitchTimer+=16*t,n.stutterTimer+=16*t,n.stutterTimer>n.nextStutter&&(n.isFrozen?(n.isFrozen=!1,n.stutterTimer=0,n.nextStutter=100+300*Math.random(),Math.random()<.3&&(e.x+=60*(Math.random()-.5),e.y+=60*(Math.random()-.5))):(n.isFrozen=!0,n.frozenPosition={x:e.x,y:e.y},n.frozenVelocity={x:e.vx,y:e.vy},n.stutterTimer=0,n.nextStutter=20+40*Math.random())),n.glitchTimer>n.nextGlitch&&!n.isGlitching&&(n.isGlitching=!0,n.glitchDuration=50+100*Math.random(),n.glitchOffset={x:80*(Math.random()-.5),y:80*(Math.random()-.5)},n.glitchTimer=0,Math.random()<.5&&e.emotionColors&&(e.color=Li(e.emotionColors))),n.isGlitching&&n.glitchTimer>n.glitchDuration&&(n.isGlitching=!1,n.glitchTimer=0,n.nextGlitch=200+800*Math.random(),n.glitchOffset={x:0,y:0}),n.beatPhase+=n.beatFrequency*t;const a=.5*Math.sin(n.beatPhase)+.5;if(n.beatPhase%(4*Math.PI)<.5*Math.PI?n.dropIntensity=Math.min(1,n.dropIntensity+.1*t):n.dropIntensity=Math.max(0,n.dropIntensity-.05*t),n.isFrozen)e.vx=.5*(Math.random()-.5),e.vy=.5*(Math.random()-.5);else{n.orbitAngle+=n.orbitSpeed*t*(1+.5*a);const r=n.orbitRadius*(1+.3*n.dropIntensity*Math.sin(4*n.beatPhase));let o=i+Math.cos(n.orbitAngle)*r,l=s+Math.sin(n.orbitAngle)*r*.6;if(n.isGlitching&&(o+=n.glitchOffset.x*Math.random()*.8,l+=n.glitchOffset.y*Math.random()*.8),n.rgbSplit){const e=3*(1+n.dropIntensity);o+=Math.sin(n.rgbPhase)*e,l+=Math.cos(n.rgbPhase)*e,n.rgbPhase+=.1*t}n.dropIntensity>.8&&Math.random()<.1&&(o+=30*(Math.random()-.5),l+=30*(Math.random()-.5));const h=n.isGlitching?.02:.03;e.vx=(o-e.x)*h,e.vy=(l-e.y)*h,e.vx+=(Math.random()-.5)*a*2,e.vy+=(Math.random()-.5)*a*2}e.x+=e.vx*t,e.y+=e.vy*t,Math.random()<.02&&(e.opacity=.1+.9*Math.random()),e.size=e.baseSize*(1+.3*a+.5*n.dropIntensity)}},hs={name:"spaz",description:"Ultra-aggressive particles with explosive spread and chaotic motion",initialize(e,t,i,s){e.x=i,e.y=s,e.life=1,e.size=3+4*Math.random();const n=Math.random()*Math.PI*2,a=200+300*Math.random();e.vx=Math.cos(n)*a,e.vy=Math.sin(n)*a,e.behaviorState={explosionPhase:0,explosionTimer:0,explosionDuration:1e3+2e3*Math.random(),chaosTimer:0,nextChaosChange:100+200*Math.random(),chaosAngle:n,chaosSpeed:50+100*Math.random(),spazIntensity:.8+.4*Math.random(),zigzagPattern:Math.random()<.5,spiralPattern:Math.random()<.3,teleportChance:.02,sizePulse:!0,sizePulseSpeed:.1+.05*Math.random(),sizePulsePhase:Math.random()*Math.PI*2,colorShift:Math.random()<.3,colorShiftSpeed:.05+.03*Math.random()},e.lifeDecay=8e-4,e.hasGlow=!0,e.glowSizeMultiplier=4+3*Math.random(),e.glowIntensity=1.5+.5*Math.random()},update(e,t,i,s){const n=e.behaviorState;if(n.explosionTimer+=t,n.chaosTimer+=t,0===n.explosionPhase&&n.explosionTimer<500)e.vx*=.98,e.vy*=.98,Math.random()<.1&&(e.vx+=100*(Math.random()-.5),e.vy+=100*(Math.random()-.5));else if(0===n.explosionPhase&&n.explosionTimer>=500)n.explosionPhase=1,n.chaosAngle=Math.random()*Math.PI*2,n.chaosSpeed=30+70*Math.random();else if(1===n.explosionPhase){n.chaosTimer>=n.nextChaosChange&&(n.chaosAngle=Math.random()*Math.PI*2,n.chaosSpeed=20+80*Math.random(),n.nextChaosChange=50+150*Math.random(),n.chaosTimer=0);const t=Math.cos(n.chaosAngle)*n.chaosSpeed,i=Math.sin(n.chaosAngle)*n.chaosSpeed;if(e.vx=.7*e.vx+.3*t,e.vy=.7*e.vy+.3*i,n.zigzagPattern){const t=.01*n.chaosTimer;e.vx+=20*Math.sin(t),e.vy+=20*Math.cos(t)}if(n.spiralPattern){const t=.005*n.chaosTimer,i=50+30*Math.sin(.003*n.chaosTimer);e.vx+=Math.cos(t)*i*.1,e.vy+=Math.sin(t)*i*.1}}if(Math.random()<n.teleportChance){const t=Math.random()*Math.PI*2,n=200+400*Math.random();e.x=i+Math.cos(t)*n,e.y=s+Math.sin(t)*n,e.vx=200*(Math.random()-.5),e.vy=200*(Math.random()-.5)}if(e.x+=e.vx*(t/1e3),e.y+=e.vy*(t/1e3),n.sizePulse){n.sizePulsePhase+=n.sizePulseSpeed*t;const i=1+.5*Math.sin(n.sizePulsePhase);e.size=(3+4*Math.random())*i}n.colorShift&&(n.colorShiftPhase=(n.colorShiftPhase||0)+n.colorShiftSpeed*t),e.vx*=.995,e.vy*=.995,e.life-=e.lifeDecay*t,(e.life<=0||Math.abs(e.x-i)>2e3||Math.abs(e.y-s)>2e3)&&(e.life=0)},getSpawnPosition(e,t){const i=Math.random()*Math.PI*2,s=100+200*Math.random();return{x:e+Math.cos(i)*s,y:t+Math.sin(i)*s}},getVisualProperties:()=>({glowColor:"#FF00AA",glowIntensity:2,particleColors:[{color:"#FF00AA",weight:30},{color:"#00FFAA",weight:25},{color:"#FFAA00",weight:20},{color:"#AA00FF",weight:15},{color:"#00AAFF",weight:10}]})},cs={name:"directed",emoji:"๐ฏ",description:"Focused, straight-line movement toward target",config:{speed:3,acceleration:.15,focusStrength:.8,randomness:.1,edgeBuffer:50},initialize(e,t,i,s,n){const a=t-e.x,r=i-e.y,o=Math.sqrt(a*a+r*r);if(o>0)e.vx=a/o*this.config.speed,e.vy=r/o*this.config.speed;else{const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*this.config.speed,e.vy=Math.sin(t)*this.config.speed}e.targetX=t,e.targetY=i,e.directedPhase=0},update(e,t,i,s,n,a){e.directedPhase+=.05*t;const r=e.targetX-e.x,o=e.targetY-e.y,l=Math.sqrt(r*r+o*o);if(l>10){const i=r/l*this.config.speed,s=o/l*this.config.speed;e.vx+=(i-e.vx)*this.config.acceleration*t,e.vy+=(s-e.vy)*this.config.acceleration*t,e.vx+=(Math.random()-.5)*this.config.randomness,e.vy+=(Math.random()-.5)*this.config.randomness}else{const t=Math.random()*Math.PI*2,r=100+200*Math.random();e.targetX=i+Math.cos(t)*r,e.targetY=s+Math.sin(t)*r,e.targetX=Math.max(this.config.edgeBuffer,Math.min(n-this.config.edgeBuffer,e.targetX)),e.targetY=Math.max(this.config.edgeBuffer,Math.min(a-this.config.edgeBuffer,e.targetY))}e.x+=e.vx*t,e.y+=e.vy*t,(e.x<=0||e.x>=n)&&(e.vx*=-.8,e.x=Math.max(0,Math.min(n,e.x)),e.targetX=i+300*(Math.random()-.5)),(e.y<=0||e.y>=a)&&(e.vy*=-.8,e.y=Math.max(0,Math.min(a,e.y)),e.targetY=s+300*(Math.random()-.5))},visuals:{trailLength:"medium",opacity:.9,sizeMultiplier:1,blurAmount:.2}},us={name:"fizzy",emoji:"๐ซง",description:"Bubbly, effervescent movement like carbonation",config:{baseRiseSpeed:2.5,wobbleAmplitude:30,wobbleFrequency:.15,popChance:.002,popForce:8,fizziness:.3,gravity:-.05},initialize(e,t,i,s,n){e.vx=2*(Math.random()-.5),e.vy=-this.config.baseRiseSpeed-2*Math.random(),e.wobblePhase=Math.random()*Math.PI*2,e.wobbleSpeed=this.config.wobbleFrequency*(.8+.4*Math.random()),e.bubbleSize=.5+.5*Math.random(),e.popTimer=0,e.isFizzing=!0},update(e,t,i,s,n,a){e.wobblePhase+=e.wobbleSpeed*t;const r=Math.sin(e.wobblePhase)*this.config.wobbleAmplitude;if(e.vx=.05*r+(Math.random()-.5)*this.config.fizziness,e.vy+=this.config.gravity*t,e.vy+=(Math.random()-.5)*this.config.fizziness,Math.random()<this.config.popChance){const t=Math.random()*Math.PI*2;e.vx=Math.cos(t)*this.config.popForce,e.vy=Math.sin(t)*this.config.popForce*.7,e.popTimer=1,e.bubbleSize=.3+.7*Math.random()}e.popTimer>0&&(e.popTimer-=.05*t,e.vx*=.95,e.vy*=.95),e.x+=e.vx*t,e.y+=e.vy*t,e.y<-50&&(e.y=a+50,e.x=i+300*(Math.random()-.5),e.vy=-this.config.baseRiseSpeed-2*Math.random(),e.bubbleSize=.5+.5*Math.random()),(e.x<=0||e.x>=n)&&(e.vx*=-.5,e.x=Math.max(0,Math.min(n,e.x))),e.y>a+50&&(e.y=a,e.vy=1.5*-this.config.baseRiseSpeed),e.size=e.baseSize*e.bubbleSize*(1+.1*Math.sin(2*e.wobblePhase))},visuals:{trailLength:"short",opacity:.6,sizeMultiplier:1.2,blurAmount:.5,sparkle:!0}};const ds=new Map;var gs={registerPluginBehavior:function(e,t){return ds.has(e),!(!t.initialize||"function"!=typeof t.initialize||!t.update||"function"!=typeof t.update||(ds.set(e,{name:e,emoji:t.emoji||"๐",description:t.description||`Plugin behavior: ${e}`,initialize:t.initialize,update:t.update,isPlugin:!0}),0))},unregisterPluginBehavior:function(e){return!!ds.has(e)&&(ds.delete(e),!0)},getPluginBehavior:function(e){return ds.get(e)||null},getAllPluginBehaviors:function(){return Array.from(ds.keys())},createLegacyAdapter:function(e){return{name:e.name||"legacy",emoji:"๐",description:e.description||"Legacy plugin behavior",initialize(t){if(e.size&&(t.size="object"==typeof e.size?e.size.min+Math.random()*(e.size.max-e.size.min):e.size,t.baseSize=t.size),e.speed){const i="object"==typeof e.speed?e.speed.min+Math.random()*(e.speed.max-e.speed.min):e.speed,s=Math.random()*Math.PI*2;t.vx=Math.cos(s)*i,t.vy=Math.sin(s)*i}if(e.lifespan){const i="object"==typeof e.lifespan?e.lifespan.min+Math.random()*(e.lifespan.max-e.lifespan.min):e.lifespan;t.lifeDecay=1e3/i}e.color&&(t.color=Array.isArray(e.color)?Li(e.color):e.color),e.opacity&&(t.life="object"==typeof e.opacity?e.opacity.min+Math.random()*(e.opacity.max-e.opacity.min):e.opacity),t.behaviorData={movementType:e.movementType||"linear",turbulence:e.turbulence||0,drift:e.drift||0,acceleration:e.acceleration||0,...e.customData}},update(t,i,s,n){const a=t.behaviorData;switch(a.movementType){case"wander":t.vx+=(Math.random()-.5)*a.turbulence*i,t.vy+=(Math.random()-.5)*a.turbulence*i;break;case"fall":t.vy+=.1*i,t.vx+=(Math.random()-.5)*a.drift*i;break;case"rain":t.vy+=a.acceleration*i;break;case"orbit":{const e=t.x-s,a=t.y-n,r=Math.sqrt(e*e+a*a);if(r>0){const o=Math.atan2(a,e)+.02*i;t.x=s+Math.cos(o)*r,t.y=n+Math.sin(o)*r}break}}e.customUpdate&&e.customUpdate(t,i,s,n)}}}};const ms={};function ps(e){if(ms[e])return ms[e];return gs.getPluginBehavior(e)||null}function fs(e,t){const i=ps(t);return i&&i.initialize?(i.initialize(e),!0):"ambient"!==t&&(console.warn(`โ ๏ธ Behavior '${t}' not found, falling back to ambient`),fs(e,"ambient"))}function ys(e,t,i,s,n){const a=ps(t);return!(!a||!a.update||(a.update(e,i,s,n),0))}function bs(){return[...Object.values(ms).map(e=>({name:e.name,emoji:e.emoji||"๐ฏ",description:e.description||"No description",type:"core"})),...gs.getAllPluginBehaviors().map(e=>{const t=gs.getPluginBehavior(e);return{name:t.name,emoji:t.emoji||"๐",description:t.description||"Plugin behavior",type:"plugin"}})]}[qi,cs,us,Hi,ji,Wi,Ni,Qi,Ji,Ki,Zi,es,ts,is,ns,as,rs,os,ls,hs].forEach(e=>{ms[e.name]=e}),"undefined"!=typeof window&&window.DEBUG_PARTICLES&&(window.ParticleBehaviors={registry:ms,list:bs,get:ps});var vs={BEHAVIOR_REGISTRY:ms,getBehavior:ps,initializeBehavior:fs,updateBehavior:ys,listBehaviors:bs,pluginAdapter:gs},Ms=Object.freeze({__proto__:null,BEHAVIOR_REGISTRY:ms,default:vs,getBehavior:ps,initializeBehavior:fs,listBehaviors:bs,pluginAdapter:gs,updateBehavior:ys});class ws{constructor(){this.listeners=new Map,this.groups=new Map,this.stats={registered:0,removed:0,active:0},this._listeners={},this._emitters=new Map}addEventListener(e,t,i,s={},n="default"){const a=this.generateId(),r={id:a,target:e,eventType:t,handler:i,options:s,group:n,active:!0};return this.listeners.set(a,r),this.groups.has(n)||this.groups.set(n,new Set),this.groups.get(n).add(a),e.addEventListener(t,i,s),this.stats.registered++,this.stats.active++,a}removeEventListener(e){const t=this.listeners.get(e);if(!t||!t.active)return!1;t.target.removeEventListener(t.eventType,t.handler,t.options),t.active=!1;const i=this.groups.get(t.group);return i&&(i.delete(e),0===i.size&&this.groups.delete(t.group)),this.listeners.delete(e),this.stats.removed++,this.stats.active--,!0}removeGroup(e){const t=this.groups.get(e);if(!t)return 0;let i=0;for(const e of t)this.removeEventListener(e)&&i++;return i}removeAllForTarget(e){let t=0;for(const[i,s]of this.listeners.entries())s.target===e&&s.active&&this.removeEventListener(i)&&t++;return t}removeAllOfType(e){let t=0;for(const[i,s]of this.listeners.entries())s.eventType===e&&s.active&&this.removeEventListener(i)&&t++;return t}removeAll(){let e=0;for(const[t,i]of this.listeners.entries())i.active&&this.removeEventListener(t)&&e++;return e}createAutoRemove(e,t,i,s={}){const n=this.addEventListener(e,t,i,s);return{id:n,remove:()=>this.removeEventListener(n)}}once(e,t,i,s={}){const n=this.addEventListener(e,t,e=>{i(e),this.removeEventListener(n)},s);return n}debounced(e,t,i,s=250,n={}){let a;return this.addEventListener(e,t,e=>{clearTimeout(a),a=setTimeout(()=>i(e),s)},n)}throttled(e,t,i,s=100,n={}){let a=!1;return this.addEventListener(e,t,e=>{a||(i(e),a=!0,setTimeout(()=>{a=!1},s))},n)}on(e,t){this._emitters.has(e)||this._emitters.set(e,[]),this._emitters.get(e).push(t)}off(e,t){const i=this._emitters.get(e);if(!i)return;const s=i.indexOf(t);-1!==s&&i.splice(s,1),0===i.length&&this._emitters.delete(e)}emit(e,t=null){const i=this._emitters.get(e);if(i)for(let s=0;s<i.length;s++)try{i[s](t)}catch(t){console.warn(`[EventManager] Error in "${e}" listener:`,t)}}removeAllListeners(e=null){if(e){const t=this._emitters.get(e),i=t?t.length:0;return this._emitters.delete(e),i}let t=0;for(const e of this._emitters.values())t+=e.length;return this._emitters.clear(),t}listenerCount(e){const t=this._emitters.get(e);return t?t.length:0}getEventNames(){return Array.from(this._emitters.keys())}getEventStats(){let e=0;for(const t of this._emitters.values())e+=t.length;return{domListeners:this.stats.active,emitterEvents:this._emitters.size,emitterListeners:e}}getDebugInfo(){const e={};for(const[t,i]of this._emitters)e[t]=i.length;return{domStats:this.getStats(),emitterEvents:e,activeListeners:this.getActiveListeners()}}generateId(){return`listener_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getStats(){return{...this.stats,groups:this.groups.size,listeners:this.listeners.size}}getActiveListeners(){const e=[];for(const[t,i]of this.listeners.entries())i.active&&e.push({id:t,eventType:i.eventType,group:i.group,target:i.target.constructor.name});return e}analyzeLeaks(){const e={totalListeners:this.listeners.size,activeListeners:this.stats.active,inactiveButNotRemoved:0,byTarget:new Map,byType:new Map,potentialLeaks:[]};for(const[t,i]of this.listeners.entries()){const s=i.target.constructor.name;e.byTarget.set(s,(e.byTarget.get(s)||0)+1),e.byType.set(i.eventType,(e.byType.get(i.eventType)||0)+1),i.active||(e.inactiveButNotRemoved++,e.potentialLeaks.push({id:t,eventType:i.eventType,target:s}))}return e.byTarget=Object.fromEntries(e.byTarget),e.byType=Object.fromEntries(e.byType),e}cleanup(){let e=0;for(const[t,i]of this.listeners.entries())i.active||(this.listeners.delete(t),e++);return e}destroy(){const e=this.removeAll();return this.listeners.clear(),this.groups.clear(),this._emitters.clear(),this._listeners=null,this.stats={registered:0,removed:0,active:0},e}}const Ss=new ws,xs={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,TRACE:5},Cs=new class{constructor(e={}){this.config={enabled:!1!==e.enabled,level:e.level||xs.INFO,enableProfiling:!1!==e.enableProfiling,enableErrorTracking:!1!==e.enableErrorTracking,enableMemoryTracking:!1!==e.enableMemoryTracking,maxLogEntries:e.maxLogEntries||1e3,maxProfileEntries:e.maxProfileEntries||500,...e},this._logBuffer=new Array(e.maxLogEntries||1e3),this._logIndex=0,this._logCount=0,this.errors=[],this.profiles=new Map,this.memorySnapshots=[],this.maxFrameTimings=120,this._frameBuffer=new Array(this.maxFrameTimings),this._frameIndex=0,this._frameCount=0,this.errorCounts=new Map,this.lastErrors=new Map,this.capabilities={performance:"undefined"!=typeof performance&&performance.now,memory:"undefined"!=typeof performance&&performance.memory,console:"undefined"!=typeof console,stackTrace:"undefined"!=typeof Error};const t=(()=>{}).bind(console);this._consoleMethods={ERROR:t,WARN:t,DEBUG:t,TRACE:t,DEFAULT:t},this.startTime=this.now(),this.setupErrorHandling(),this.config.enabled&&this.log("DEBUG","EmotiveDebugger initialized",{config:this.config,capabilities:this.capabilities})}now(){return this.capabilities.performance?performance.now():Date.now()-this.startTime}setupErrorHandling(){this.config.enableErrorTracking&&"undefined"!=typeof window&&(window.addEventListener("error",e=>{this.trackError("UNHANDLED_ERROR",e.error||new Error(e.message),{filename:e.filename,lineno:e.lineno,colno:e.colno})}),window.addEventListener("unhandledrejection",e=>{this.trackError("UNHANDLED_REJECTION",e.reason,{promise:e.promise})}))}log(e,t,i=null){if(!this.config.enabled)return;if((xs[e]||xs.INFO)>this.config.level)return;const s=this.now(),n={timestamp:s,level:e,message:t,data:i,stackTrace:this.getStackTrace()};if(this._logBuffer[this._logIndex]=n,this._logIndex=(this._logIndex+1)%this.config.maxLogEntries,this._logCount<this.config.maxLogEntries&&this._logCount++,this.capabilities.console){const n=this.getConsoleMethod(e),a=`[${(s/1e3).toFixed(3)}s]`;i?n(`${a} [${e}] ${t}`,i):n(`${a} [${e}] ${t}`)}}getConsoleMethod(e){return this._consoleMethods[e]||this._consoleMethods.DEFAULT}getStackTrace(){if(!this.capabilities.stackTrace)return null;try{throw new Error}catch(e){return e.stack}}trackError(e,t,i={}){if(!this.config.enableErrorTracking)return;const s={timestamp:this.now(),type:e,message:t.message||String(t),stack:t.stack,context:i,count:1},n=`${e}:${t.message}`;this.errorCounts.has(n)?(this.errorCounts.set(n,this.errorCounts.get(n)+1),s.count=this.errorCounts.get(n)):this.errorCounts.set(n,1),this.errors.push(s),this.lastErrors.set(e,s),this.log("ERROR",`${e}: ${t.message}`,{error:s,context:i})}startProfile(e,t={}){if(!this.config.enableProfiling)return;const i={name:e,startTime:this.now(),metadata:t,samples:[],isActive:!0};this.profiles.set(e,i),this.log("TRACE",`Started profiling: ${e}`,t)}profileSample(e,t,i=null){if(!this.config.enableProfiling)return;const s=this.profiles.get(e);if(!s||!s.isActive)return;const n={timestamp:this.now(),label:t,data:i,relativeTime:this.now()-s.startTime};s.samples.push(n)}endProfile(e){if(!this.config.enableProfiling)return null;const t=this.profiles.get(e);if(!t||!t.isActive)return null;if(t.endTime=this.now(),t.duration=t.endTime-t.startTime,t.isActive=!1,t.stats=this.calculateProfileStats(t),this.log("TRACE",`Ended profiling: ${e}`,{duration:t.duration,samples:t.samples.length,stats:t.stats}),this.profiles.size>this.config.maxProfileEntries){const e=this.profiles.keys().next().value;this.profiles.delete(e)}return{...t}}calculateProfileStats(e){if(0===e.samples.length)return{sampleCount:0};const t=[];for(let i=1;i<e.samples.length;i++)t.push(e.samples[i].relativeTime-e.samples[i-1].relativeTime);if(0===t.length)return{sampleCount:e.samples.length};const i=t.reduce((e,t)=>e+t,0)/t.length,s=Math.min(...t),n=Math.max(...t);return{sampleCount:e.samples.length,avgSampleDuration:i,minSampleDuration:s,maxSampleDuration:n,totalDuration:e.duration}}trackFrameTiming(e){this.config.enableProfiling&&(this._frameBuffer[this._frameIndex]={timestamp:this.now(),frameTime:e,fps:1e3/e},this._frameIndex=(this._frameIndex+1)%this.maxFrameTimings,this._frameCount<this.maxFrameTimings&&this._frameCount++)}_readCircular(e,t,i,s,n=0){const a=n>0?Math.min(n,i):i,r=new Array(a),o=(t-a+s)%s;for(let t=0;t<a;t++)r[t]=e[(o+t)%s];return r}takeMemorySnapshot(e="snapshot"){if(!this.config.enableMemoryTracking||!this.capabilities.memory)return;const t={timestamp:this.now(),label:e,memory:{usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}};this.memorySnapshots.push(t),this.memorySnapshots.length>100&&this.memorySnapshots.shift(),this.log("DEBUG",`Memory snapshot: ${e}`,t.memory)}getDebugReport(){return{timestamp:this.now(),uptime:this.now()-0,config:this.config,capabilities:this.capabilities,logCount:this._logCount,recentLogs:this._readCircular(this._logBuffer,this._logIndex,this._logCount,this.config.maxLogEntries,10),errorCount:this.errors.length,uniqueErrors:this.errorCounts.size,recentErrors:this.errors.slice(-5),errorCounts:Object.fromEntries(this.errorCounts),activeProfiles:Array.from(this.profiles.values()).filter(e=>e.isActive).length,completedProfiles:Array.from(this.profiles.values()).filter(e=>!e.isActive).length,frameTimings:this.getFrameTimingStats(),memorySnapshots:this.memorySnapshots.slice(-5)}}getFrameTimingStats(){if(0===this._frameCount)return{sampleCount:0};const e=this._readCircular(this._frameBuffer,this._frameIndex,this._frameCount,this.maxFrameTimings),t=e.map(e=>e.frameTime),i=e.map(e=>e.fps);return{sampleCount:this._frameCount,avgFrameTime:t.reduce((e,t)=>e+t,0)/t.length,minFrameTime:Math.min(...t),maxFrameTime:Math.max(...t),avgFPS:i.reduce((e,t)=>e+t,0)/i.length,minFPS:Math.min(...i),maxFPS:Math.max(...i)}}exportDebugData(){return{metadata:{exportTime:Date.now(),debuggerUptime:this.now(),config:this.config,capabilities:this.capabilities},logs:this._readCircular(this._logBuffer,this._logIndex,this._logCount,this.config.maxLogEntries),errors:[...this.errors],profiles:Object.fromEntries(this.profiles),frameTimings:this._readCircular(this._frameBuffer,this._frameIndex,this._frameCount,this.maxFrameTimings),memorySnapshots:[...this.memorySnapshots],errorCounts:Object.fromEntries(this.errorCounts)}}clear(){this._logBuffer.fill(void 0),this._logIndex=0,this._logCount=0,this.errors=[],this.profiles.clear(),this._frameBuffer.fill(void 0),this._frameIndex=0,this._frameCount=0,this.memorySnapshots=[],this.errorCounts.clear(),this.lastErrors.clear(),this.log("INFO","Debug data cleared")}destroy(){this.clear(),this.config.enabled=!1}}({enabled:"undefined"!=typeof window&&window.location&&window.location.search.includes("debug=true"),level:xs.INFO}),ks=new class{constructor(){this.capabilities=this.detectCapabilities(),this.performance=this.measurePerformance()}detectCapabilities(){return{es6:this.detectES6(),es2017:this.detectES2017(),modules:this.detectModules(),webGL:this.detectWebGL(),webGL2:this.detectWebGL2(),webWorkers:this.detectWebWorkers(),serviceWorkers:this.detectServiceWorkers(),performanceObserver:this.detectPerformanceObserver(),intersectionObserver:this.detectIntersectionObserver(),resizeObserver:this.detectResizeObserver(),localStorage:this.detectLocalStorage(),sessionStorage:this.detectSessionStorage(),indexedDB:this.detectIndexedDB(),fetch:this.detectFetch(),webSockets:this.detectWebSockets(),touchEvents:this.detectTouchEvents(),pointerEvents:this.detectPointerEvents(),deviceOrientation:this.detectDeviceOrientation(),canvas2d:this.detectCanvas2D(),canvasFilters:this.detectCanvasFilters(),offscreenCanvas:this.detectOffscreenCanvas()}}detectES6(){try{return"undefined"!=typeof Symbol&&"undefined"!=typeof Promise&&"undefined"!=typeof Map&&"undefined"!=typeof Set}catch{return!1}}detectES2017(){try{return"undefined"!=typeof async||function(){try{return"function"==typeof async function(){}.constructor}catch{return!1}}()}catch{return!1}}detectModules(){try{return"undefined"!=typeof document&&"noModule"in document.createElement("script")}catch{return!1}}detectWebGL(){try{const e=document.createElement("canvas");return!(!e.getContext("webgl")&&!e.getContext("experimental-webgl"))}catch{return!1}}detectWebGL2(){try{return!!document.createElement("canvas").getContext("webgl2")}catch{return!1}}detectWebWorkers(){return"undefined"!=typeof Worker}detectServiceWorkers(){return"serviceWorker"in navigator}detectPerformanceObserver(){return"undefined"!=typeof PerformanceObserver}detectIntersectionObserver(){return"undefined"!=typeof IntersectionObserver}detectResizeObserver(){return"undefined"!=typeof ResizeObserver}detectLocalStorage(){try{return"undefined"!=typeof localStorage&&null!==localStorage}catch{return!1}}detectSessionStorage(){try{return"undefined"!=typeof sessionStorage&&null!==sessionStorage}catch{return!1}}detectIndexedDB(){return"undefined"!=typeof indexedDB}detectFetch(){return"undefined"!=typeof fetch}detectWebSockets(){return"undefined"!=typeof WebSocket}detectTouchEvents(){return"ontouchstart"in window||navigator.maxTouchPoints>0}detectPointerEvents(){return"undefined"!=typeof PointerEvent}detectDeviceOrientation(){return"ondeviceorientation"in window}detectCanvas2D(){try{return!!document.createElement("canvas").getContext("2d")}catch{return!1}}detectCanvasFilters(){try{return"filter"in document.createElement("canvas").getContext("2d")}catch{return!1}}detectOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}measurePerformance(){const e={},t=performance.now();e.jsExecutionSpeed=performance.now()-t;try{const t=document.createElement("canvas");t.width=100,t.height=100;const i=t.getContext("2d"),s=performance.now();for(let e=0;e<1e3;e++)i.fillRect(100*Math.random(),100*Math.random(),10,10);e.canvasPerformance=performance.now()-s}catch{e.canvasPerformance=null}return e}getCapabilities(){return{...this.capabilities}}getPerformance(){return{...this.performance}}generateReport(){const e=Object.entries(this.capabilities).filter(([,e])=>e).map(([e])=>e),t=Object.entries(this.capabilities).filter(([,e])=>!e).map(([e])=>e),i=e.length/Object.keys(this.capabilities).length*100;return{timestamp:Date.now(),userAgent:navigator.userAgent,supportedFeatures:e,unsupportedFeatures:t,supportPercentage:Math.round(i),performance:this.performance,recommendations:this.generateRecommendations(i)}}generateRecommendations(e){const t=[];return e<50&&t.push("Consider using the minimal build for better compatibility"),this.capabilities.webGL||t.push("WebGL not supported - advanced graphics features unavailable"),this.capabilities.webWorkers||t.push("Web Workers not supported - background processing unavailable"),this.capabilities.fetch||t.push("Fetch API not supported - consider using XMLHttpRequest polyfill"),this.performance.jsExecutionSpeed>50&&t.push("Slow JavaScript execution detected - consider performance optimizations"),this.performance.canvasPerformance>100&&t.push("Slow canvas performance detected - consider reducing visual complexity"),t}};class Ps{constructor(e){this.canvas=e,this.ctx=e.getContext("2d",{alpha:!0,desynchronized:!1,willReadFrequently:!1}),this.ctx||(console.warn('CanvasManager: getContext("2d") returned null โ canvas may be unavailable or context already acquired.'),this._contextLost=!0),this.dpr=window.devicePixelRatio||1,this.width=0,this.height=0,this.centerX=0,this.centerY=0,this.renderSize=null,this.resizeCallbacks=[],this.handleResize=this.handleResize.bind(this),window.addEventListener("resize",this.handleResize),this.resize()}resize(){if(!this._contextLost){if(this.renderSize&&this.renderSize.width&&this.renderSize.height)this.width=this.renderSize.width,this.height=this.renderSize.height,this.canvas.width=this.width,this.canvas.height=this.height;else if(this.canvas.hasAttribute("width")&&this.canvas.hasAttribute("height")){const e=parseInt(this.canvas.getAttribute("width"),10),t=parseInt(this.canvas.getAttribute("height"),10),i=this.canvas.getBoundingClientRect(),s=i.width,n=i.height;e>1.5*s||t>1.5*n?(this.width=s,this.height=n,this.canvas.width=e,this.canvas.height=t,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)):(this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t)}else{const e=this.canvas.getBoundingClientRect();this.width=e.width,this.height=e.height,this.canvas.width=this.width*this.dpr,this.canvas.height=this.height*this.dpr,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)}this.centerX=this.width/2,this.centerY=this.height/2,this.resizeCallbacks.forEach(e=>{try{e(this.width,this.height,this.dpr)}catch{}})}}onResize(e){"function"==typeof e&&this.resizeCallbacks.push(e)}handleResize(){clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{this.renderSize&&this.renderSize.width&&this.renderSize.height||this.resize()},100)}setRenderSize(e,t){this.renderSize={width:e,height:t},this.resize()}clear(){this._contextLost||this.ctx.clearRect(0,0,this.width,this.height)}getCenter(){return{x:this.centerX,y:this.centerY}}setTransform(e=0,t=0,i=1,s=0){this._contextLost||(this.ctx.save(),this.ctx.translate(e,t),this.ctx.rotate(s),this.ctx.scale(i,i))}restoreTransform(){this._contextLost||this.ctx.restore()}getContext(){return this.ctx}getDimensions(){return{width:this.width,height:this.height}}destroy(){window.removeEventListener("resize",this.handleResize),clearTimeout(this.resizeTimeout),this.ctx&&(this.ctx.clearRect(0,0,this.width,this.height),this.ctx=null),this.canvas&&(this.canvas.width=0,this.canvas.height=0,this.canvas=null),this.resizeCallbacks=[],this.resizeTimeout=null}}function Ts(e){return 3===(e=e.replace("#","")).length&&(e=e.split("").map(e=>e+e).join("")),{r:parseInt(e.substr(0,2),16),g:parseInt(e.substr(2,2),16),b:parseInt(e.substr(4,2),16)}}function Es(e,t,i){const s=e=>{const t=Math.round(Math.max(0,Math.min(255,e))).toString(16);return 1===t.length?`0${t}`:t};return`#${s(e)}${s(t)}${s(i)}`}function As(e,t,i){e/=255,t/=255,i/=255;const s=Math.max(e,t,i),n=Math.min(e,t,i),a=(s+n)/2;let r,o;if(s===n)r=o=0;else{const l=s-n;switch(o=a>.5?l/(2-s-n):l/(s+n),s){case e:r=(t-i)/l+(t<i?6:0);break;case t:r=(i-e)/l+2;break;case i:r=(e-t)/l+4}r/=6}return{h:360*r,s:100*o,l:100*a}}function Ds(e,t,i){e/=360,i/=100;const s=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e);let n,a,r;if(0==(t/=100))n=a=r=i;else{const o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;n=s(l,o,e+1/3),a=s(l,o,e),r=s(l,o,e-1/3)}return{r:Math.round(255*n),g:Math.round(255*a),b:Math.round(255*r)}}function _s(e,t,i){const s=Ts(e),n=Ts(t),a=As(s.r,s.g,s.b),r=As(n.r,n.g,n.b),o=a.h;let l=r.h;const h=l-o;h>180?l-=360:h<-180&&(l+=360);const c=Ds(((o+(l-o)*i)%360+360)%360,a.s+(r.s-a.s)*i,a.l+(r.l-a.l)*i);return Es(c.r,c.g,c.b)}function Is(e,t){const i=Ts(e),s=As(i.r,i.g,i.b);s.s=Math.max(0,Math.min(100,s.s*t));const n=Ds(s.h,s.s,s.l);return Es(n.r,n.g,n.b)}function Rs(e){const t=Ts(e),i=e=>{const t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(t.r)+.7152*i(t.g)+.0722*i(t.b)}const Bs={intense:1.6,confident:1.3,nervous:1.15,clear:1,tired:.8,subdued:.5};function zs(e,t){if(!t||"clear"===t)return e;const i=Bs[t.toLowerCase()];return i&&1!==i?Is(e,i):e}function Fs(e,t){return e&&Array.isArray(e)&&t&&"clear"!==t?e.map(e=>"string"==typeof e?zs(e,t):e&&"object"==typeof e&&e.color?{...e,color:zs(e.color,t)}:e):e}const Os={neutral:"#B0B0B0",joy:"#FFD700",sadness:"#4169E1",anger:"#DC143C",fear:"#8B008B",surprise:"#FF8C00",disgust:"#9ACD32",love:"#FF69B4"},Ls=Object.fromEntries(Object.entries(Os).map(([e,t])=>{const i=Ts(t);return[e,`${i.r}, ${i.g}, ${i.b}`]}));function qs(e){return e}function Gs(e){return e*(2-e)}function Hs(e){return e*e}function js(e){return e<.5?2*e*e:(4-2*e)*e-1}function $s(e){return 1-Math.pow(1-e,3)}function Ws(e){return e*e*e}function Us(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}function Vs(e){const t=2*Math.PI/3;return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((10*e-.75)*t)+1}function Ys(e){const t=7.5625,i=2.75;return e<1/i?t*e*e:e<2/i?t*(e-=1.5/i)*e+.75:e<2.5/i?t*(e-=2.25/i)*e+.9375:t*(e-=2.625/i)*e+.984375}function Xs(e){const t=2.5949095;return e<.5?Math.pow(2*e,2)*(7.189819*e-t)/2:(Math.pow(2*e-2,2)*((t+1)*(2*e-2)+t)+2)/2}function Ns(e){return Math.sin(e*Math.PI/2)}function Qs(e){return-(Math.cos(Math.PI*e)-1)/2}function Js(e,t,i,s="linear"){return t+(i-t)*("string"==typeof s?{linear:qs,easeOutQuad:Gs,easeInQuad:Hs,easeInOutQuad:js,easeOutCubic:$s,easeInCubic:Ws,easeInOutCubic:Us,easeOutElastic:Vs,easeOutBounce:Ys,easeInOutBack:Xs,easeOutSine:Ns,easeInOutSine:Qs}[s]||qs:s)(Math.max(0,Math.min(1,e)))}const Ks=new class{constructor(){this.emotionCache=new Map,this.visualParamsCache=new Map,this.modifiersCache=new Map,this.transitionCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1,this.loadStartTime=0,this.initialize()}initialize(){this.loadStartTime=performance.now();try{const e=u();e.forEach(e=>{this.cacheEmotion(e)}),this.cacheCommonTransitions(e),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.emotionCache.size}catch(e){console.error("[EmotionCache] Initialization failed:",e),this.isInitialized=!1,console.warn("[EmotionCache] Running uninitialized โ lookups will return defaults")}}cacheEmotion(e){try{const t=l(e);t&&this.emotionCache.set(e,t);const i=h(e);this.visualParamsCache.set(e,i);const s=c(e);this.modifiersCache.set(e,s)}catch(t){console.warn(`[EmotionCache] Failed to cache emotion '${e}':`,t)}}cacheCommonTransitions(e){[["neutral","joy"],["neutral","sadness"],["neutral","anger"],["joy","sadness"],["sadness","joy"],["anger","calm"],["calm","anger"]].forEach(([t,i])=>{if(e.includes(t)&&e.includes(i))try{const e=p(t,i),s=`${t}->${i}`;this.transitionCache.set(s,e)}catch(e){console.warn(`[EmotionCache] Failed to cache transition '${t}->${i}':`,e)}})}getEmotion(e){if(!this.isInitialized)return console.warn("[EmotionCache] Cache not initialized, falling back to direct access"),l(e);const t=this.emotionCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,l(e))}getVisualParams(e){if(!this.isInitialized)return h(e);const t=this.visualParamsCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,h(e))}getModifiers(e){if(!this.isInitialized)return c(e);const t=this.modifiersCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,c(e))}getTransitionParams(e,t){if(!this.isInitialized)return p(e,t);const i=`${e}->${t}`,s=this.transitionCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,p(e,t))}hasEmotion(e){return this.emotionCache.has(e)}getStats(){const e=this.stats.hits+this.stats.misses,t=e>0?(this.stats.hits/e*100).toFixed(2):0;return{isInitialized:this.isInitialized,loadTime:this.stats.loadTime,cacheSize:this.stats.cacheSize,hits:this.stats.hits,misses:this.stats.misses,hitRate:`${t}%`,emotions:this.emotionCache.size,visualParams:this.visualParamsCache.size,modifiers:this.modifiersCache.size,transitions:this.transitionCache.size}}clear(){this.emotionCache.clear(),this.visualParamsCache.clear(),this.modifiersCache.clear(),this.transitionCache.clear(),this.isInitialized=!1,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0}}reinitialize(){this.clear(),this.initialize()}};class Zs{constructor(e){this.errorBoundary=e,this.state={emotion:"neutral",undertone:null,intensity:1,gesture:null,speaking:!1,audioLevel:0},this.slots=[],this.maxSlots=3,this._eventCallback=null,this._previousDominant=null,this._emotionDampening=0,this._negativeEmotions=new Set(["anger","fear","sadness","disgust","suspicion"]),this.transitions={emotional:{current:"neutral",target:null,progress:0,duration:500,startTime:0,isActive:!1},intensity:{from:1,to:1,progress:1,duration:500,startTime:0,isActive:!1},undertone:{current:null,target:null,progress:0,duration:300,startTime:0,isActive:!1,currentWeight:0,targetWeight:0}},this.interpolationCache={lastUpdate:0,cacheInterval:100,cachedProperties:null,cachedRenderState:null},this.initializeEmotionalStates(),this.initializeUndertoneModifiers()}initializeEmotionalStates(){this.emotionalStates=this.loadEmotionalStatesFromCache()}loadEmotionalStatesFromCache(){const e={};return["neutral","joy","sadness","anger","fear","surprise","disgust","love","suspicion","excited","resting","euphoria","focused","glitch","calm"].forEach(t=>{const i=Ks.getVisualParams(t);i&&(e[t]={primaryColor:i.primaryColor||"#B0B0B0",glowIntensity:i.glowIntensity||.7,particleRate:i.particleRate||1,minParticles:i.minParticles||3,maxParticles:i.maxParticles||4,particleBehavior:i.particleBehavior||"ambient",coreSize:i.coreSize||1,breathRate:i.breathRate||1,breathDepth:i.breathDepth||.1})}),e}initializeUndertoneModifiers(){this.undertoneModifiers={nervous:{jitterAmount:.3,breathRateMultiplier:1.2,glowIntensityMultiplier:.9,particleRateMultiplier:1.1},confident:{coreSizeMultiplier:1.1,glowIntensityMultiplier:1.2,breathRateMultiplier:.9,particleRateMultiplier:1},tired:{breathRateMultiplier:.7,particleRateMultiplier:.5,glowIntensityMultiplier:.8,coreSizeMultiplier:.95},intense:{amplificationFactor:1.3},subdued:{dampeningFactor:.7}}}setEmotion(e,t=null,i=500){return this.errorBoundary.wrap(()=>{let s=null,n=1;if("string"==typeof t?s=t:t&&"object"==typeof t&&(s=t.undertone??null,i=t.duration??i,n=t.intensity??1),this.interpolationCache.cachedProperties=null,this.interpolationCache.cachedRenderState=null,!g(e)&&!{}.hasOwnProperty.call(this.emotionalStates,e)){const t=[...Object.keys(this.emotionalStates),...u()],i=[...new Set(t)];throw new Error(`Invalid emotion: ${e}. Valid emotions: ${i.join(", ")}`)}if(null!==s&&!{}.hasOwnProperty.call(this.undertoneModifiers,s))throw new Error(`Invalid undertone: ${s}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return n=Math.max(0,Math.min(1,n)),this.slots=[{emotion:e,intensity:n}],this._previousDominant=e,this.state.emotion===e&&this.state.undertone===s&&this.state.intensity===n||(this.state.emotion!==e&&(i>0?(this.transitions.emotional={current:this.state.emotion,target:e,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},void 0!==this._simulatedTime&&(this._simulatedTime=0)):this.transitions.emotional={current:e,target:null,progress:1,duration:0,startTime:performance.now(),isActive:!1},this.state.emotion=e),this.state.intensity!==n&&(this.transitions.intensity={from:this.state.intensity,to:n,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},this.state.intensity=n),this.state.undertone!==s&&(this.transitions.undertone={current:this.state.undertone,target:s,progress:0,duration:300,startTime:performance.now(),isActive:!0,currentWeight:this.state.undertone?1:0,targetWeight:s?1:0},this.state.undertone=s)),!0},"emotion-setting",!1)()}setEventCallback(e){this._eventCallback=e}_emitEvent(e,t){this._eventCallback&&this._eventCallback(e,t)}_checkDominantChange(){const e=this.getDominant(),t=e?e.emotion:null,i=this._previousDominant;t!==i&&(this._previousDominant=t,this._emitEvent("dominantChanged",{previous:i,current:t,intensity:e?e.intensity:0}))}setEmotionDampening(e){this._emotionDampening=Math.max(0,Math.min(1,e))}getEmotionDampening(){return this._emotionDampening}setNegativeEmotions(e){this._negativeEmotions=new Set(e)}pushEmotion(e,t=.5){return this.errorBoundary.wrap(()=>{if(!g(e)&&!{}.hasOwnProperty.call(this.emotionalStates,e))return!1;t=Math.max(0,Math.min(1,t)),this.interpolationCache.cachedProperties=null;const i=this.slots.find(t=>t.emotion===e);if(i){const s=i.intensity;i.intensity=Math.min(1,i.intensity+t),this._emitEvent("slotChanged",{emotion:e,intensity:i.intensity,action:"push"}),i.intensity>=1&&s<1&&this._emitEvent("emotionPeaked",{emotion:e,intensity:i.intensity})}else if(this.slots.length<this.maxSlots)this.slots.push({emotion:e,intensity:t}),this._emitEvent("slotChanged",{emotion:e,intensity:t,action:"push"}),t>=1&&this._emitEvent("emotionPeaked",{emotion:e,intensity:t});else{let i=0;for(let e=1;e<this.slots.length;e++)this.slots[e].intensity<this.slots[i].intensity&&(i=e);const s=this.slots[i];this._emitEvent("slotChanged",{emotion:s.emotion,intensity:0,action:"replaced"}),this.slots[i]={emotion:e,intensity:t},this._emitEvent("slotChanged",{emotion:e,intensity:t,action:"push"})}return this._syncDominantToState(),this._checkDominantChange(),!0},"push-emotion",!1)()}nudgeEmotion(e,t,i=1){t>0&&this._emotionDampening>0&&this._negativeEmotions.has(e)&&(t*=1-this._emotionDampening),this.interpolationCache.cachedProperties=null;const s=this.slots.find(t=>t.emotion===e);if(s){const n=s.intensity;s.intensity=Math.max(0,Math.min(i,s.intensity+t)),s.intensity<=0?(this.slots=this.slots.filter(e=>e!==s),this._emitEvent("slotChanged",{emotion:e,intensity:0,action:"removed"})):(this._emitEvent("slotChanged",{emotion:e,intensity:s.intensity,action:"nudge"}),s.intensity>=i&&n<i&&this._emitEvent("emotionPeaked",{emotion:e,intensity:s.intensity}))}else if(t>0)return void this.pushEmotion(e,Math.min(i,t));this._syncDominantToState(),this._checkDominantChange()}clearEmotions(){const e=this.slots.length>0;this.slots=[],this.interpolationCache.cachedProperties=null,this.state.emotion="neutral",this.state.intensity=1,e&&(this._emitEvent("slotChanged",{emotion:null,intensity:0,action:"cleared"}),this._previousDominant=null,this._emitEvent("dominantChanged",{previous:this._previousDominant,current:null,intensity:0}))}getSlots(){return this.slots}pruneEmptySlots(){const e=this.slots.length,t=this.slots.filter(e=>e.intensity<=0);if(this.slots=this.slots.filter(e=>e.intensity>0),this.slots.length!==e){this.interpolationCache.cachedProperties=null;for(const e of t)this._emitEvent("emotionDecayed",{emotion:e.emotion,intensity:0,removed:!0});this._syncDominantToState(),this._checkDominantChange()}}getDominant(){return this.slots.length?this.slots.reduce((e,t)=>t.intensity>e.intensity?t:e):null}getUndercurrents(){const e=this.getDominant();return e?this.slots.filter(t=>t!==e):[]}getEmotionalState(){const e=this.getDominant();return{dominant:e?{...e}:null,undercurrents:this.getUndercurrents().map(e=>({...e})),slots:this.slots.map(e=>({...e}))}}getCurrentRhythmModifiers(){return this.slots.length>0?b(this.slots):b([{emotion:this.state.emotion,intensity:this.state.intensity}])}_syncDominantToState(){const e=this.getDominant();e?(this.state.emotion!==e.emotion&&(this.transitions.emotional={current:this.state.emotion,target:e.emotion,progress:0,duration:300,startTime:performance.now(),isActive:!0},this.state.emotion=e.emotion),this.state.intensity=e.intensity):(this.state.emotion="neutral",this.state.intensity=1)}applyUndertone(e,t){if(!t||!{}.hasOwnProperty.call(this.undertoneModifiers,t))return{...e};const i=this.undertoneModifiers[t],s={...e};if(void 0!==i.glowIntensityMultiplier&&(s.glowIntensity*=i.glowIntensityMultiplier),void 0!==i.breathRateMultiplier&&(s.breathRate*=i.breathRateMultiplier),void 0!==i.particleRateMultiplier&&(s.particleRate=Math.round(s.particleRate*i.particleRateMultiplier)),void 0!==i.coreSizeMultiplier&&(s.coreSize*=i.coreSizeMultiplier),void 0!==i.amplificationFactor){const e=i.amplificationFactor;s.glowIntensity*=e,s.breathRate*=e,s.particleRate=Math.round(s.particleRate*e),s.coreSize*=e}if(void 0!==i.dampeningFactor){const e=i.dampeningFactor;s.glowIntensity*=e,s.breathRate*=e,s.particleRate=Math.round(s.particleRate*e),s.coreSize*=e}return void 0!==i.jitterAmount&&(s.jitterAmount=i.jitterAmount),s}update(e){this.errorBoundary.wrap(()=>{this.transitions.emotional.isActive&&this.updateEmotionalTransition(e),this.transitions.intensity.isActive&&this.updateIntensityTransition(e),this.transitions.undertone.isActive&&this.updateUndertoneTransition(e)},"state-machine-update")()}updateUndertoneTransition(e){const t=this.transitions.undertone,i=performance.now()-t.startTime,s=Math.min(i/t.duration,1),n=Us(s);t.current&&t.target?(t.currentWeight=1-n,t.targetWeight=n):t.current&&!t.target?(t.currentWeight=1-n,t.targetWeight=0):!t.current&&t.target&&(t.currentWeight=0,t.targetWeight=n),t.progress=s,s>=1&&(t.isActive=!1,t.current=t.target,t.currentWeight=t.target?1:0,t.targetWeight=0)}updateIntensityTransition(e){const t=this.transitions.intensity,i=performance.now()-t.startTime;t.progress=Math.min(1,i/t.duration),t.progress>=1&&(t.isActive=!1,t.from=t.to,t.progress=1)}getEffectiveIntensity(){const e=this.transitions.intensity;if(!e.isActive)return this.state.intensity;const t=Us(e.progress);return e.from+(e.to-e.from)*t}updateEmotionalTransition(e){const t=this.transitions.emotional;let i;void 0!==this._simulatedTime?(this._simulatedTime+=e,i=this._simulatedTime):i=performance.now()-t.startTime,t.progress=Math.min(1,i/t.duration),t.progress>=1&&(t.isActive=!1,t.current=t.target,t.target=null,t.progress=1)}getCurrentEmotionalProperties(){return this.errorBoundary.wrap(()=>{const e=performance.now();if(this.interpolationCache.cachedProperties&&e-this.interpolationCache.lastUpdate<this.interpolationCache.cacheInterval)return this.interpolationCache.cachedProperties;let t;if(this.slots.length>1)t=this._blendSlotProperties();else{const e=this.transitions.emotional;t=e.isActive&&e.target?this.interpolateEmotionalProperties(e.current,e.target,e.progress):{...this.emotionalStates[this.state.emotion]||this.emotionalStates.neutral};const i=this.getEffectiveIntensity();i<1&&(t.glowIntensity=this._lerp(.7,t.glowIntensity,i),t.particleRate=Math.round(this._lerp(1,t.particleRate,i)),t.breathRate=this._lerp(1,t.breathRate,i),t.breathDepth=t.breathDepth*i,t.coreSize=this._lerp(1,t.coreSize,i))}return t=this.applyUndertone(t,this.state.undertone),this.interpolationCache.cachedProperties=t,this.interpolationCache.lastUpdate=e,t},"emotional-properties",()=>this.emotionalStates.neutral)()}_blendSlotProperties(){const e=this.getDominant(),t=this.getUndercurrents(),i=this.emotionalStates[e.emotion]||this.emotionalStates.neutral,s={...i},n=e.intensity;s.glowIntensity=.75*this._lerp(.7,i.glowIntensity,n),s.particleRate=i.particleRate*n*.75,s.breathRate=.75*this._lerp(1,i.breathRate,n),s.breathDepth=i.breathDepth*n*.75,s.coreSize=.75*this._lerp(1,i.coreSize,n);const a=t.length>0?.25/t.length:0;for(const e of t){const t=this.emotionalStates[e.emotion]||this.emotionalStates.neutral,i=e.intensity;s.glowIntensity+=this._lerp(.7,t.glowIntensity,i)*a,s.particleRate+=t.particleRate*i*a,s.breathRate+=this._lerp(1,t.breathRate,i)*a,s.breathDepth+=t.breathDepth*i*a,s.coreSize+=this._lerp(1,t.coreSize,i)*a}if(s.particleRate=Math.round(s.particleRate),t.length>0){const e=this.slots.reduce((e,t)=>e+t.intensity,0);let n=i.primaryColor;for(const i of t){const t=this.emotionalStates[i.emotion]||this.emotionalStates.neutral,s=i.intensity/e;n=_s(n,t.primaryColor,s)}s.primaryColor=n}return s.particleBehavior=i.particleBehavior,s}_lerp(e,t,i){return e+(t-e)*i}interpolateEmotionalProperties(e,t,i){const s=this.emotionalStates[e]||this.emotionalStates.neutral,n=this.emotionalStates[t]||this.emotionalStates.neutral,a=Js(i,0,1,"easeOutCubic");return{primaryColor:_s(s.primaryColor,n.primaryColor,a),glowIntensity:s.glowIntensity+(n.glowIntensity-s.glowIntensity)*a,particleRate:Math.round(s.particleRate+(n.particleRate-s.particleRate)*a),coreSize:s.coreSize+(n.coreSize-s.coreSize)*a,breathRate:s.breathRate+(n.breathRate-s.breathRate)*a,breathDepth:s.breathDepth+(n.breathDepth-s.breathDepth)*a,particleBehavior:a>.5?n.particleBehavior:s.particleBehavior}}getCurrentState(){return{emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,isTransitioning:this.transitions.emotional.isActive,transitionProgress:this.transitions.emotional.progress,properties:this.getCurrentEmotionalProperties()}}applyUndertoneModifier(e){return this.errorBoundary.wrap(()=>{if(null!==e&&!{}.hasOwnProperty.call(this.undertoneModifiers,e))throw new Error(`Invalid undertone: ${e}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return this.state.undertone=e,!0},"undertone-application",!1)()}clearUndertone(){this.state.undertone=null}getUndertoneModifier(e){return this.errorBoundary.wrap(()=>{if(this.renderer&&this.renderer.undertoneModifiers&&this.renderer.undertoneModifiers[e])return{...this.renderer.undertoneModifiers[e]};if(!e||!{}.hasOwnProperty.call(this.undertoneModifiers,e))return null;const t={...this.undertoneModifiers[e]};return t.glowRadiusMult||(t.glowRadiusMult=1),t},"undertone-retrieval",null)()}getWeightedUndertoneModifiers(){const e=this.transitions.undertone;if(!e.isActive){if(this.state.undertone){const e=this.getUndertoneModifier(this.state.undertone);if(e)return{...e,weight:1,type:this.state.undertone}}return null}if(e.target){const t=this.getUndertoneModifier(e.target);if(t)return{...t,weight:e.targetWeight,type:e.target}}if(e.current&&e.currentWeight>0){const t=this.getUndertoneModifier(e.current);if(t)return{...t,weight:e.currentWeight,type:e.current}}return null}reset(e=500){this.slots=[],this.setEmotion("neutral",null,e)}isValidEmotion(e){return{}.hasOwnProperty.call(this.emotionalStates,e)}isValidUndertone(e){return null===e||{}.hasOwnProperty.call(this.undertoneModifiers,e)}getAvailableEmotions(){return Object.keys(this.emotionalStates)}getAvailableUndertones(){return Object.keys(this.undertoneModifiers)}isTransitioning(){return this.transitions.emotional.isActive}getTransitionProgress(){return this.transitions.emotional.isActive?this.transitions.emotional.progress:1}completeTransition(){this.transitions.emotional.isActive&&(this.transitions.emotional.progress=1,this.transitions.emotional.isActive=!1,this.transitions.emotional.current=this.transitions.emotional.target,this.transitions.emotional.target=null)}interpolateProperty(e,t,i,s="easeOutCubic"){return e+(t-e)*Js(i,0,1,s)}serialize(){return{version:1,emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,slots:this.slots.map(e=>({...e})),dampening:this._emotionDampening,negativeEmotions:[...this._negativeEmotions]}}deserialize(e){e&&1===e.version&&(this.slots=(e.slots||[]).map(e=>({emotion:e.emotion,intensity:e.intensity})),this._emotionDampening=e.dampening??0,e.negativeEmotions&&(this._negativeEmotions=new Set(e.negativeEmotions)),this.state.emotion=e.emotion||"neutral",this.state.undertone=e.undertone||null,this.state.intensity=e.intensity??1,this._previousDominant=e.emotion||null,this.transitions.emotional.isActive=!1,this.transitions.intensity.isActive=!1,this.transitions.undertone.isActive=!1,this.interpolationCache.cachedProperties=null)}enableSimulatedTime(e=!0){e?this._simulatedTime=0:delete this._simulatedTime}}const en=16.67,tn=3e4;let sn;"undefined"!=typeof window&&window.__emotiveRhythmEngine?sn=window.__emotiveRhythmEngine:(sn=new class{constructor(){this.bpm=120,this.timeSignature=[4,4],this.isPlaying=!1,this.startTime=0,this.currentBeat=0,this.currentBar=0,this.beatProgress=0,this.barProgress=0,this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.lastBeatTime=0,this.nextBeatTime=0,this.listeners=new Map,this.beatCallbacks=new Set,this.barCallbacks=new Set,this.subdivisions={sixteenth:0,eighth:0,triplet:0,swing:0},this.audioSync=null,this.syncOffset=0,this.autoSync=!1,this.intensity=1,this.groove=0,this.humanize=.05,this.patterns=new Map,this.currentPattern=null,this.initializePatterns()}initializePatterns(){this.patterns.set("4/4",{name:"4/4",description:"Common time - 4 beats per bar",timeSignature:[4,4],groove:0,accents:[1,.5,.7,.5]}),this.patterns.set("straight",{name:"straight",description:"Straight, even timing",groove:0,accents:[1,.5,.7,.5]}),this.patterns.set("swing",{name:"swing",description:"Swing/shuffle timing",groove:.67,accents:[1,.3,.8,.3]}),this.patterns.set("3/4",{name:"3/4",description:"Waltz time - 3 beats per bar",timeSignature:[3,4],accents:[1,.5,.5]}),this.patterns.set("waltz",{name:"waltz",description:"3/4 waltz timing",timeSignature:[3,4],accents:[1,.5,.5]}),this.patterns.set("6/8",{name:"6/8",description:"Compound duple time",timeSignature:[6,8],accents:[1,.3,.3,.7,.3,.3]}),this.patterns.set("5/4",{name:"5/4",description:"Complex meter - 5 beats per bar",timeSignature:[5,4],accents:[1,.5,.6,.5,.7]}),this.patterns.set("7/8",{name:"7/8",description:"Irregular meter",timeSignature:[7,8],accents:[1,.5,.5,.7,.5,.5,.6]}),this.patterns.set("dubstep",{name:"dubstep",description:"Dubstep half-time feel",accents:[.2,.2,1,.2],subdivisions:{wobble:!0}}),this.patterns.set("breakbeat",{name:"breakbeat",description:"Broken beat pattern",accents:[1,.2,.7,.9,.2,.8,.4,.2]})}start(){this.isPlaying||(this.isPlaying=!0,this.isRunning=!0,this.startTime=performance.now(),this.lastBeatTime=this.startTime,this.nextBeatTime=this.startTime+this.beatDuration,this.currentBeat=0,this.currentBar=0,this.emit("start",{bpm:this.bpm,timeSignature:this.timeSignature,pattern:this.currentPattern}),this.update())}stop(){this.isPlaying&&(this.isPlaying=!1,this.emit("stop",{totalBeats:this.currentBeat,totalBars:this.currentBar}))}update(){if(!this.isPlaying)return;const e=(performance.now()-this.startTime)/this.beatDuration,t=Math.floor(e);this.beatProgress=e%1,t>this.currentBeat&&this.onBeat(t);const i=Math.floor(t/this.timeSignature[0]);i>this.currentBar&&this.onBar(i),this.currentBeat=t,this.currentBar=i,this.barProgress=t%this.timeSignature[0]/this.timeSignature[0],this.updateSubdivisions(),this.emit("update",this.getTimeInfo()),this.isPlaying&&requestAnimationFrame(()=>this.update())}onBeat(e){const t=e%this.timeSignature[0],i=this.getAccent(t),s=this.humanize*(Math.random()-.5)*this.beatDuration,n={beat:e,beatInBar:t,bar:this.currentBar,accent:i,intensity:this.intensity*i,humanTiming:s,timestamp:performance.now()};this.emit("beat",n),this.beatCallbacks.forEach(e=>e(n)),this.lastBeatTime=performance.now(),this.nextBeatTime=this.lastBeatTime+this.beatDuration}onBar(e){const t={bar:e,timeSignature:this.timeSignature,pattern:this.currentPattern,timestamp:performance.now()};this.emit("bar",t),this.barCallbacks.forEach(e=>e(t))}updateSubdivisions(){if(this.subdivisions.sixteenth=4*this.beatProgress%1,this.subdivisions.eighth=2*this.beatProgress%1,this.subdivisions.triplet=3*this.beatProgress%1,this.groove>0){const e=.5+.17*this.groove;this.subdivisions.eighth<.5?this.subdivisions.swing=this.subdivisions.eighth/e:this.subdivisions.swing=.5+(this.subdivisions.eighth-.5)/(1-e)}else this.subdivisions.swing=this.subdivisions.eighth}getAccent(e){if(this.currentPattern&&this.patterns.has(this.currentPattern)){const t=this.patterns.get(this.currentPattern);if(t.accents&&void 0!==t.accents[e])return t.accents[e]}return 0===e?1:2===e&&4===this.timeSignature[0]?.7:.5}getTimeInfo(){return{elapsed:performance.now()-this.startTime,beat:this.currentBeat,bar:this.currentBar,beatInBar:this.currentBeat%this.timeSignature[0],beatProgress:this.beatProgress,barProgress:this.barProgress,subdivisions:{...this.subdivisions},bpm:this.bpm,beatDuration:this.beatDuration,timeSignature:[...this.timeSignature],intensity:this.intensity,groove:this.groove,pattern:this.currentPattern,nextBeatIn:this.nextBeatTime-performance.now(),accent:this.getAccent(this.currentBeat%this.timeSignature[0])}}setBPM(e){this.bpm=Math.max(20,Math.min(360,e)),this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.emit("tempoChange",{bpm:this.bpm})}setTimeSignature(e,t){this.timeSignature=[e,t],this.barDuration=this.beatDuration*e,this.emit("timeSignatureChange",{timeSignature:this.timeSignature})}setPattern(e){if(!this.patterns.has(e))return;const t=this.patterns.get(e);this.currentPattern=e,t.timeSignature&&this.setTimeSignature(...t.timeSignature),void 0!==t.groove&&(this.groove=t.groove),this.emit("patternChange",{pattern:e})}onBeatCallback(e){return this.beatCallbacks.add(e),()=>this.beatCallbacks.delete(e)}onBarCallback(e){return this.barCallbacks.add(e),()=>this.barCallbacks.delete(e)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(e=>e(t))}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{this.listeners.has(e)&&this.listeners.get(e).delete(t)}}syncToAudio(e,t){this._syncToAudioWarned||(console.warn("[Rhythm] syncToAudio() is not yet implemented"),this._syncToAudioWarned=!0),this.audioSync={context:e,source:t}}getAdapter(){return{getTimeInfo:()=>this.getTimeInfo(),isOnBeat:(e=.1)=>this.beatProgress<e||this.beatProgress>1-e,isOnSubdivision:(e,t=.1)=>{const i=this.subdivisions[e]||0;return i<t||i>1-t},getBeatSync:(e=0,t=1,i="linear")=>{let s=this.beatProgress;switch(i){case"ease":s=.5-Math.cos(s*Math.PI)/2;break;case"bounce":s=Math.abs(Math.sin(s*Math.PI));break;case"pulse":s=Math.pow(Math.sin(s*Math.PI),2)}return e+(t-e)*s},getAccentedValue:(e,t=2)=>e*(1+(this.getAccent(this.currentBeat%this.timeSignature[0])-.5)*t),onBeat:e=>this.onBeatCallback(e),onBar:e=>this.onBarCallback(e),beatsToMs:e=>e*this.beatDuration,msToBeats:e=>e/this.beatDuration,isPlaying:()=>this.isPlaying,getBPM:()=>this.bpm,getPattern:()=>this.currentPattern}}},"undefined"!=typeof window&&(window.__emotiveRhythmEngine=sn));class nn{constructor(e,t={}){this._adapter=e,this._windows={perfect:t.windows?.perfect??30,great:t.windows?.great??60,good:t.windows?.good??100},this._grades={perfect:{multiplier:2,label:"Perfect"},great:{multiplier:1.5,label:"Great"},good:{multiplier:1,label:"Good"},miss:{multiplier:0,label:"Miss"}},this._windowModifiers={multiplier:1},this._emotionSource=t.emotionSource??null,this._history=[],this._maxHistory=100,this._onEvaluate=[],this._emotionFeedback=null,this._emotionTarget=null,this._difficultyManager=null}evaluate(e=performance.now()){const t=this._adapter.getTimeInfo(),{beatDuration:i}=t,s=performance.now()-t.elapsed,n=e-s,a=n-n%i,r=a+i,o=n-a<r-n?a:r,l=n-o;return this._gradeOffset(l,e,o+s)}evaluateAgainst(e,t){return this._gradeOffset(e-t,e,t)}evaluateSequence(e,t){const i=[],s=new Set;for(const n of e){let e=-1,a=1/0;for(let i=0;i<t.length;i++){if(s.has(i))continue;const r=Math.abs(n-t[i]);r<a&&(a=r,e=i)}e>=0?(s.add(e),i.push(this.evaluateAgainst(n,t[e]))):i.push({grade:"miss",offset:0,absOffset:0,multiplier:0,label:"Miss",timestamp:n,targetTime:null})}return i}_gradeOffset(e,t,i){if(this._difficultyManager&&this._difficultyManager.autoRhythm)return this._recordResult("good",e,t,i);const s=Math.abs(e),n=this._emotionSource?.()??{windowMultiplier:1},a=this._difficultyManager?this._difficultyManager.getWindowMultiplier():1,r=this._windowModifiers.multiplier*(n.windowMultiplier||1)*a;let o;return o=s<=this._windows.perfect*r?"perfect":s<=this._windows.great*r?"great":s<=this._windows.good*r?"good":"miss",this._recordResult(o,e,t,i)}_recordResult(e,t,i,s){const n={grade:e,offset:t,absOffset:Math.abs(t),multiplier:this._grades[e].multiplier,label:this._grades[e].label,timestamp:i,targetTime:s};this._history.push(n),this._history.length>this._maxHistory&&this._history.shift();for(const e of this._onEvaluate)e(n);if(this._emotionFeedback&&this._emotionTarget){const t=this._emotionFeedback[e];t&&this._emotionTarget(t.emotion,t.delta)}return n}setWindowModifier(e){this._windowModifiers.multiplier=Math.max(.3,Math.min(3,e))}setEmotionSource(e){this._emotionSource=e}getAccuracy(){if(!this._history.length)return{perfect:0,great:0,good:0,miss:0,averageOffset:0,total:0};const e={perfect:0,great:0,good:0,miss:0};let t=0;for(const i of this._history)e[i.grade]++,t+=i.offset;return{...e,averageOffset:t/this._history.length,total:this._history.length}}getHistory(){return[...this._history]}clearHistory(){this._history.length=0}onEvaluate(e){return this._onEvaluate.push(e),()=>{this._onEvaluate=this._onEvaluate.filter(t=>t!==e)}}setEmotionFeedback(e){this._emotionFeedback=e||null}setEmotionTarget(e){this._emotionTarget=e||null}setDifficultyManager(e){this._difficultyManager=e||null}setWindows(e){Object.assign(this._windows,e)}setGrades(e){Object.assign(this._grades,e)}destroy(){this._history.length=0,this._onEvaluate.length=0}}const an=new class{constructor(){this.enabled=!1,this.adapter=null,this.subsystemConfigs=new Map,this.activeModulations=new Map,this._inputEvaluator=null,this._unsubBeat=null,this._unsubBar=null}initialize(){this.adapter=sn.getAdapter(),this.enabled=!0,this._unsubBeat=this.adapter.onBeat(this.handleBeat.bind(this)),this._unsubBar=this.adapter.onBar(this.handleBar.bind(this))}updateBPM(e){if(e>=60&&e<=220){if(window.rhythmManuallyStoppedForCurrentAudio)return;if(!sn.isRunning)return this.start(e,"straight"),void(window.rhythmSyncVisualizer&&!window.rhythmSyncVisualizer.state.active&&window.rhythmSyncVisualizer.start());sn.setBPM(e)}}registerConfig(e,t,i){if(!i.rhythm||!i.rhythm.enabled)return;const s=`${e}:${t}`;this.subsystemConfigs.set(s,{type:e,name:t,rhythmConfig:i.rhythm,originalConfig:i})}applyGestureRhythm(e,t,i,s){if(!this.enabled||!e.rhythm?.enabled)return{};const n=e.rhythm,a={};if(n.amplitudeSync){const e=n.amplitudeSync,t=this.adapter.getBeatSync(e.offBeat||.8,e.onBeat||1.5,e.curve||"linear");a.amplitudeMultiplier=t}if(n.wobbleSync){const e=n.wobbleSync;this.adapter.isOnSubdivision(e.subdivision,.1)?a.wobbleMultiplier=1+e.intensity:a.wobbleMultiplier=1}if(n.accentResponse?.enabled){const e=this.adapter.getAccentedValue(1,n.accentResponse.multiplier||1.5);a.accentMultiplier=e}const r=this.adapter.getPattern();return r&&n.patternOverrides?.[r]&&Object.assign(a,n.patternOverrides[r]),a}applyParticleRhythm(e,t){if(!this.enabled||!e.rhythm?.enabled)return{};const i=this.adapter.getTimeInfo(),s=e.rhythm,n={};if(s.particleEmission){const e=s.particleEmission;"beat"===e.syncMode&&this.adapter.isOnBeat(.1)?n.emitBurst=e.burstSize||3:void 0!==e.offBeatRate&&(n.emissionRate=e.offBeatRate)}if(s.glowSync){const e=s.glowSync,t=this.adapter.getBeatSync(e.intensityRange[0]||1,e.intensityRange[1]||2,"pulse");n.glowIntensity=t}if("bars"===s.breathSync?.mode){const e=s.breathSync,t=i.bar%e.barsPerBreath/e.barsPerBreath;n.breathPhase=t*Math.PI*2}return n}applyBehaviorRhythm(e,t,i){if(!this.enabled||!e.rhythm?.enabled)return{};const s=this.adapter.getTimeInfo(),n=e.rhythm,a={};if(n.glitchTiming){const e=n.glitchTiming;if(this.adapter.isOnSubdivision(e.subdivision,.05)&&Math.random()<e.probability){const t=this.adapter.isOnBeat()?e.intensityOnBeat:e.intensityOffBeat;a.triggerGlitch=!0,a.glitchIntensity=t}}if(n.orbitRhythm){const e=n.orbitRhythm;"tempo"===e.baseSpeed&&(a.speedMultiplier=this.adapter.getBPM()/120),e.beatAcceleration&&this.adapter.isOnBeat(.1)&&(a.speedBoost=e.beatAcceleration),e.barReset&&0===s.beatInBar&&(a.resetOrbit=!0)}if(n.stutterSync){const e=n.stutterSync,t=this.adapter.getPattern();if(t&&e.patterns?.[t]){const i=e.patterns[t];i.freezeOnDrop&&2===s.beatInBar?(a.freeze=!0,a.freezeDuration=i.dropDuration):i.randomFreeze&&Math.random()<i.randomFreeze&&(a.freeze=!0,a.freezeDuration=i.duration)}}return a}handleBeat(e){this.lastBeatInfo=e}handleBar(e){this.lastBarInfo=e}getMusicalDuration(e,t){if(!this.enabled||!e?.durationSync)return t;const i=e.durationSync;return"bars"===i.mode?this.adapter.beatsToMs(4*i.bars):"beats"===i.mode?this.adapter.beatsToMs(i.beats):t}isEnabled(){return this.enabled&&this.adapter.isPlaying()}start(e=120,t="straight"){e&&sn.setBPM(e),t&&sn.setPattern(t),sn.start(),this.enabled=!0}stop(){sn.stop(),this.enabled=!1,this.bpmLocked=!1,this.lockedBPM=null}destroy(){this.stop(),this._unsubBeat&&(this._unsubBeat(),this._unsubBeat=null),this._unsubBar&&(this._unsubBar(),this._unsubBar=null),this.enabled=!1,this.adapter=null,this.subsystemConfigs.clear(),this.activeModulations.clear(),this.lastBeatInfo=null,this.lastBarInfo=null,this._inputEvaluator=null}setPattern(e){sn.setPattern(e)}setBPM(e){sn.setBPM(e),this.bpmLocked&&(this.lockedBPM=e)}resampleBPM(){this.bpmLocked=!1,this.lockedBPM=null}setTimeSignature(e){this.timeSignature=e;const t=document.getElementById("time-sig-display");t&&(t.textContent=e),"3/4"===e&&sn.getPattern()}getInputEvaluator(e){return this._inputEvaluator||(this.adapter||this.initialize(),this._inputEvaluator=new nn(this.adapter,e)),this._inputEvaluator}getEffectiveBPM(e){if(!this.adapter)return 120;let t=this.adapter.getBPM();if(e&&"function"==typeof e.getCurrentRhythmModifiers){const i=e.getCurrentRhythmModifiers();i.tempoShift&&(t*=1+i.tempoShift)}return Math.round(100*t)/100}syncToAudio(e,t){sn.syncToAudio(e,t)}};class rn{constructor(e,t,i="ambient",s=1,n=1,a=null){const r=Math.random();this.z=r<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,l=Math.random()*Math.PI*2;this.x=e+Math.cos(l)*o,this.y=t+Math.sin(l)*o,this.vx=0,this.vy=0,this.vz=0,this.life=0,this.maxLife=1,this.lifeDecay=.01,this.fadeInTime=.15,this.fadeOutTime=.3,this.isFadingOut=!1,this.age=0,this.scaleFactor=s,this.particleSizeMultiplier=n,this.size=(4+6*Math.random())*s*n,this.baseSize=this.size,this.emotionColors=a,this.color="#ffffff",this.opacity=1,this.hasGlow=Math.random()<.333,this.glowSizeMultiplier=this.hasGlow?1.33+.33*Math.random():0,this.isCellShaded=Math.random()<.333,this.baseOpacity=.3+.4*Math.random(),this.cachedColors=new Map,this.maxCachedColors=20,this.colorAccessOrder=[],this.lastColor=null,this.lastOpacity=-1,this.behavior=i,this.behaviorData={},this.gestureData={initialX:e,initialY:t},fs(this,i)}update(e,t,i,s=null,n=null,a=0,r=null){const o=Math.min(e,50)/en,l=n&&n.type&&a>0&&_i(n.type),h=this.rainData||"falling"===this.gestureBehavior||this.fallingData||this.gestureData?.rain,c=l||h;if(c||(this.x+=this.vx*o,this.y+=this.vy*o),!c){let e,s;if(r)e=r.width,s=r.height;else{const n=document.getElementById("card-mascot")||document.getElementById("cherokee-guide-mascot")||document.querySelector("canvas");e=n?n.width:2*t,s=n?n.height:2*i}const n=20,a=t-e/2+n,o=t+e/2+n,l=i-s/2+n,h=i+s/2-n;this.x-this.size<a?(this.x=a+this.size,this.vx=.5*Math.abs(this.vx)):this.x+this.size>o&&(this.x=o-this.size,this.vx=.5*-Math.abs(this.vx)),this.y-this.size<l?(this.y=l+this.size,this.vy=.5*Math.abs(this.vy)):this.y+this.size>h&&(this.y=h-this.size,this.vy=.5*-Math.abs(this.vy))}this.age+=this.lifeDecay*o,this.age<this.fadeInTime?this.life=this.age/this.fadeInTime:this.age<1-this.fadeOutTime?this.life=1:(this.life=(1-this.age)/this.fadeOutTime,this.isFadingOut=!0,"popcorn"===this.behavior&&(this.size=this.baseSize*(.5+.5*this.life))),this.life=Math.max(0,Math.min(1,this.life)),"falling"===this.behavior?this.opacity=this.life:this.opacity=this.easeInOutCubic(this.life),"burst"===this.behavior&&this.behaviorData&&this.life<this.behaviorData.fadeStart&&(this.size=this.baseSize*(this.life/this.behaviorData.fadeStart))}applyUndertoneModifier(e,t){}applyGestureMotion(e,t,i,s,n){!function(e,t,i,s,n,a){if(!i||!i.type||s>=1)return;e.gestureData||(e.gestureData={originalVx:e.vx,originalVy:e.vy,initialX:e.x,initialY:e.y,startAngle:Math.atan2(e.y-a,e.x-n),startRadius:Math.sqrt(Math.pow(e.x-n,2)+Math.pow(e.y-a,2))});const r=Ai(i.type);if(!r)return;let o=i;if(an.isEnabled()&&r.rhythm?.enabled){const n=an.applyGestureRhythm(r,e,s,t);o={...i,amplitude:(i.amplitude||1)*(n.amplitudeMultiplier||1)*(n.accentMultiplier||1),wobbleAmount:(i.wobbleAmount||0)*(n.wobbleMultiplier||1),rhythmModulation:n}}r.apply&&r.apply(e,s,o,t,n,a),s>=.99&&r.cleanup&&(r.cleanup(e),e.gestureData=null)}(this,i,e,t,s,n)}isOutOfBounds(e,t){return this.x<-50||this.x>e+50||this.y<-50||this.y>t+50}isAlive(){return this.life>0}setOutwardVelocity(e){if(this.behaviorData&&void 0!==this.behaviorData.outwardSpeed){const t=this.behaviorData.outwardSpeed;this.vx=Math.cos(e)*t,this.vy=Math.sin(e)*t+(this.behaviorData.upwardBias||0)}}getDepthAdjustedSize(){const e=1+.2*this.z;return this.size*e}getState(){return{position:{x:this.x,y:this.y,z:this.z},velocity:{x:this.vx,y:this.vy,z:this.vz},life:this.life,behavior:this.behavior,size:this.size,opacity:this.opacity}}reset(e,t,i="ambient",s=1,n=1,a=null){const r=Math.random();this.z=r<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,l=Math.random()*Math.PI*2;if(this.x=e+Math.cos(l)*o,this.y=t+Math.sin(l)*o,this.vx=0,this.vy=0,this.vz=0,this.life=0,this.age=0,this.scaleFactor=s,this.particleSizeMultiplier=n,this.size=(4+6*Math.random())*s*n,this.baseSize=this.size,this.emotionColors=a,this.cachedColors.clear(),this.colorAccessOrder=[],this.opacity=0,this.isFadingOut=!1,this.baseOpacity=.3+.4*Math.random(),this.color="#ffffff",this.behavior=i,this.gestureData=null,this.behaviorData)for(const e in this.behaviorData)delete this.behaviorData[e];else this.behaviorData={};fs(this,i)}getCachedColor(e,t){const i=Math.round(100*t)/100,s=`${e}_${i}`;if(this.cachedColors.has(s)){const e=this.colorAccessOrder.indexOf(s);-1!==e&&this.colorAccessOrder.splice(e,1),this.colorAccessOrder.push(s)}else{if(this.cachedColors.size>=this.maxCachedColors){const e=this.colorAccessOrder.shift();this.cachedColors.delete(e)}this.cachedColors.set(s,this.hexToRgba(e,i)),this.colorAccessOrder.push(s)}return this.cachedColors.get(s)}hexToRgba(e,t){const i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return i?`rgba(${parseInt(i[1],16)}, ${parseInt(i[2],16)}, ${parseInt(i[3],16)}, ${t})`:`rgba(255, 255, 255, ${t})`}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}render(e,t="#ffffff"){if(this.life<=0)return;if(!isFinite(this.x)||!isFinite(this.y))return;const i=this.x,s=this.y,n=Math.max(.1,this.size),a=this.tempColor||this.color||t;if(e.save(),this.isCellShaded){e.strokeStyle=this.getCachedColor(a,.9*this.opacity),e.lineWidth=2,e.beginPath(),e.arc(i,s,n,0,2*Math.PI),e.stroke();const t=Math.floor(3*this.opacity)/3;e.fillStyle=this.getCachedColor(a,t*(this.baseOpacity||.5)*.5),e.beginPath(),e.arc(i,s,Math.max(.1,n-1),0,2*Math.PI),e.fill(),t>.5&&(e.fillStyle=this.getCachedColor("#FFFFFF",.3),e.beginPath(),e.arc(i-.3*n,s-.3*n,.3*n,0,2*Math.PI),e.fill())}else{const t=e.createRadialGradient(i,s,0,i,s,n);if(t.addColorStop(0,this.getCachedColor(a,this.opacity*(this.baseOpacity||.5))),t.addColorStop(.5,this.getCachedColor(a,this.opacity*(this.baseOpacity||.5)*.5)),t.addColorStop(1,this.getCachedColor(a,0)),e.fillStyle=t,e.beginPath(),e.arc(i,s,n,0,2*Math.PI),e.fill(),this.hasGlow&&this.glowSizeMultiplier>0){const t=n*this.glowSizeMultiplier,r=e.createRadialGradient(i,s,.5*n,i,s,t),o=.3,l=Math.max(o,this.opacity),h=Math.min(1,this.glowSizeMultiplier/3);r.addColorStop(0,this.getCachedColor(a,Math.max(.5,.8*l)*h)),r.addColorStop(.25,this.getCachedColor(a,Math.max(.3,.6*l)*h)),r.addColorStop(.5,this.getCachedColor(a,Math.max(.2,.4*l)*h)),r.addColorStop(.75,this.getCachedColor(a,Math.max(.1,.2*l)*h)),r.addColorStop(1,this.getCachedColor(a,0)),e.save(),e.globalCompositeOperation="screen",e.fillStyle=r,e.beginPath(),e.arc(i,s,t,0,2*Math.PI),e.fill(),e.restore()}}e.restore()}}class on{constructor(e=50){this.poolSize=Math.min(e,50),this.pool=[],this.totalParticlesCreated=0,this.totalParticlesDestroyed=0,this.poolHits=0,this.poolMisses=0}getParticle(e,t,i,s,n,a,r,o=null){let l;return this.pool.length>0?(l=this.pool.pop(),l.reset(e,t,i,s,n,a),this.poolHits++):(l=new rn(e,t,i,s,n,a),this.poolMisses++,this.totalParticlesCreated++),l.emotion=r,o&&(l.gestureBehavior=o),l}returnParticle(e){if(this.pool.length<this.poolSize){if(e.cachedGradient=null,e.cachedGradientKey=null,e.behaviorData)for(const t in e.behaviorData)delete e.behaviorData[t];this.pool.push(e)}else this.totalParticlesDestroyed++}refreshPool(){const e=this.pool.length-this.poolSize;e>0&&(this.pool.splice(this.poolSize),this.totalParticlesDestroyed+=e)}getStats(){return{poolSize:this.pool.length,poolHits:this.poolHits,poolMisses:this.poolMisses,totalCreated:this.totalParticlesCreated,totalDestroyed:this.totalParticlesDestroyed}}clear(){this.pool=[],this.poolHits=0,this.poolMisses=0,this.totalParticlesCreated=0,this.totalParticlesDestroyed=0}}class ln{constructor(){this.spawnAccumulator=0}getSpawnPosition(e,t,i,s,n,a=null){const r=Math.min(s,n)/12,o=2.5*r,l=1.1*o,h=Math.min(t-30,s-t-30),c=Math.min(i-30,n-i-30),u=Math.min(1.5*o,h,c);switch(e){case"ambient":case"resting":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"ascending":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"rising":{const e=Math.random()*Math.PI*2,s=l+Math.random()*(u-l);return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"falling":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s,angle:e}}case"aggressive":{const e=Math.random()*Math.PI*2,s=o+Math.random()*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"scattering":default:return{x:t,y:i};case"burst":{const e=Math.random()*Math.PI*2;if("suspicion"===a){const s=1.5*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}if("surprise"===a){const s=1.2*r;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}return{x:t,y:i}}case"repelling":{const e=Math.random()*Math.PI*2,s=.9*o;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"orbiting":{const e=Math.random()*Math.PI*2,s=1.2*o+Math.random()*o*.5;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"glitchy":{const e=Math.random()*Math.PI*2,s=3*o+Math.random()*o*4;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}case"spaz":{const e=Math.random()*Math.PI*2,s=2*o+Math.random()*o*3;return{x:t+Math.cos(e)*s,y:i+Math.sin(e)*s}}}}clampToCanvas(e,t,i,s,n=30){return{x:Math.max(n,Math.min(i-n,e)),y:Math.max(n,Math.min(s-n,t))}}calculateSpawnRate(e,t){if(e<=0)return 0;const i=Math.min(t,50),s=e/1e3;this.spawnAccumulator+=s*i,this.spawnAccumulator=Math.min(this.spawnAccumulator,3);let n=0;for(;this.spawnAccumulator>=1;)n++,this.spawnAccumulator-=1;return n}resetAccumulator(){this.spawnAccumulator=0}}class hn{render(e,t,i="#ffffff",s=null){const n=[];for(const e of t)e.life<=0||n.push(e);this._renderParticles(e,n,i,s)}renderLayer(e,t,i="#ffffff",s=!1,n=null){const a=[],r=e.canvas.width,o=e.canvas.height;for(const e of t)e.z>=0===s&&(e.x<-50||e.x>r+50||e.y<-50||e.y>o+50||e.life<=0||a.push(e));return a.sort((e,t)=>e.isCellShaded!==t.isCellShaded?e.isCellShaded?-1:1:e.hasGlow!==t.hasGlow?e.hasGlow?-1:1:0),this._renderParticles(e,a,i,n),a}_renderParticles(e,t,i,s=null){e.save();let n=null;for(const a of t)if(a.isCellShaded)a.render(e,i),n=null;else{const t=a.color||i;if(t!==n&&(e.fillStyle=t,n=t),!isFinite(a.x)||!isFinite(a.y))continue;const r=a.getDepthAdjustedSize?a.getDepthAdjustedSize():a.size;let o=Math.max(.1,r),l=1;if(s&&s.fireflyEffect){const e=(.01*a.x+.01*a.y+.1*a.size)%(2*Math.PI),t=s.fireflyTime||.001*Date.now(),i=s.particleGlow||2;l=.3+Math.max(0,Math.sin(3*t+e))*i}if(s&&s.flickerEffect){const e=(.02*a.x+.02*a.y)%(2*Math.PI),t=s.flickerTime||.001*Date.now(),i=s.particleGlow||2;l=.5+Math.sin(12*t+e)*i*.5}if(s&&s.shimmerEffect){const t=a.x-e.canvas.width/2,i=a.y-e.canvas.height/2,n=Math.sqrt(t*t+i*i)/200,r=s.shimmerTime||.001*Date.now(),o=s.shimmerWave||0,h=s.particleGlow||1.2;l=1+.15*Math.sin(3*r-n+o)*h}if(s&&s.glowEffect){const t=s.glowProgress||0,i=s.particleGlow||2,n=a.x-e.canvas.width/2,r=a.y-e.canvas.height/2,l=Math.sqrt(n*n+r*r)/300,h=Math.min(.3*l,.5),c=Math.max(0,(t-h)/(1-h)),u=Math.sin(c*Math.PI);a._originalGlow||(a._originalGlow={hasGlow:a.hasGlow,glowSizeMultiplier:a.glowSizeMultiplier||0}),a.hasGlow=!0,a.glowSizeMultiplier=Math.max(3,a._originalGlow.glowSizeMultiplier)+u*i*3,o*=1+.3*u,t>=.99&&a._originalGlow&&(a.hasGlow=a._originalGlow.hasGlow,a.glowSizeMultiplier=a._originalGlow.glowSizeMultiplier,delete a._originalGlow)}if(a.hasGlow||l>1){const t=Math.max(.1,o*(a.glowSizeMultiplier||1.5)*l),i=e.globalCompositeOperation;e.globalCompositeOperation="screen",e.globalAlpha=.15*a.opacity*l,e.beginPath(),e.arc(a.x,a.y,t,0,2*Math.PI),e.fill(),e.globalAlpha=.25*a.opacity*l,e.beginPath(),e.arc(a.x,a.y,.6*t,0,2*Math.PI),e.fill(),e.globalCompositeOperation=i}e.globalAlpha=a.opacity*(a.baseOpacity||.5)*.6*Math.min(2,l),e.beginPath(),e.arc(a.x,a.y,o,0,2*Math.PI),e.fill()}e.restore()}}class cn{constructor(e=50,t=null){this.errorBoundary=t,this.maxParticles=e,this.absoluteMaxParticles=2*e,this.particles=[],this.particlePool=new on(e),this.particleSpawner=new ln,this.particleRenderer=new hn,this.containmentBounds=null,this.stateChangeCount=0,this.lastMemoryCheck=Date.now(),this.lastLeakedCount=0,this.particleCount=0,this.cleanupTimer=0,this.cleanupInterval=5e3}get pool(){return this.particlePool.pool}get poolSize(){return this.particlePool.poolSize}get poolHits(){return this.particlePool.poolHits}get poolMisses(){return this.particlePool.poolMisses}get totalParticlesCreated(){return this.particlePool.totalParticlesCreated}get totalParticlesDestroyed(){return this.particlePool.totalParticlesDestroyed}get spawnAccumulator(){return this.particleSpawner.spawnAccumulator}set spawnAccumulator(e){this.particleSpawner.spawnAccumulator=e}getParticleFromPool(e,t,i){return this.particlePool.getParticle(e,t,i,this.scaleFactor||1,this.particleSizeMultiplier||1,this.currentEmotionColors,this.currentEmotion,this.gestureBehavior)}returnParticleToPool(e){this.particlePool.returnParticle(e)}spawn(e,t,i,s,n,a,r=null,o=0,l=10,h=1,c=1,u=null,d=null){if(this.scaleFactor=h,this.particleSizeMultiplier=c,this.errorBoundary)return this.errorBoundary.wrap(()=>{this._spawn(e,t,i,s,n,a,r,o,l,u,d)},"particle-spawn")();this._spawn(e,t,i,s,n,a,r,o,l,u,d)}resetAccumulator(){this.particleSpawner.resetAccumulator()}_spawn(e,t,i,s,n,a,r,o=0,h=10,c=null,u=null){this.currentEmotion=t,this.baseEmotionColors=c,this.currentUndertone=u,this.currentEmotionColors=c&&u?Fs(c,u):c;let d=i;if(an.isEnabled()){const i=Ks&&Ks.isInitialized?Ks.getEmotion(t):l(t);if(i){const t=an.applyParticleRhythm(i,this);if(t.emitBurst)for(let i=0;i<t.emitBurst&&this.particles.length<h;i++)this.spawnSingleParticle(e,s,n);void 0!==t.emissionRate&&(d*=t.emissionRate)}}if(null!==r){for(let t=0;t<r&&this.particles.length<this.maxParticles;t++)this.spawnSingleParticle(e,s,n);return}if(this.skipSpawnThisFrame)return;for(;this.particles.length<o&&this.particles.length<this.maxParticles;)this.spawnSingleParticle(e,s,n);if(this.particles.length>=h)return;if(d<=0)return;const g=this.particleSpawner.calculateSpawnRate(d,a);for(let t=0;t<g&&this.particles.length<h;t++)this.spawnSingleParticle(e,s,n)}getSpawnPosition(e,t,i,s,n){return this._deprecationWarned_getSpawnPosition||(this._deprecationWarned_getSpawnPosition=!0,console.warn("[ParticleSystem] getSpawnPosition() is deprecated. Use particleSpawner.getSpawnPosition() instead.")),this.particleSpawner.getSpawnPosition(e,t,i,s,n,this.currentEmotion)}clampToCanvas(e,t,i,s,n=30){return this._deprecationWarned_clampToCanvas||(this._deprecationWarned_clampToCanvas=!0,console.warn("[ParticleSystem] clampToCanvas() is deprecated. Use particleSpawner.clampToCanvas() instead.")),this.particleSpawner.clampToCanvas(e,t,i,s,n)}spawnSingleParticle(e,t,i){if(this.particles.length>=this.absoluteMaxParticles)return;const s=this.canvasWidth||2*t,n=this.canvasHeight||2*i,a=this.particleSpawner.getSpawnPosition(e,t,i,s,n,this.currentEmotion),r=this.particleSpawner.clampToCanvas(a.x,a.y,s,n);a.x=r.x,a.y=r.y;const o=this.getParticleFromPool(a.x,a.y,e);"meditation_swirl"===e&&a.palmCenter&&(o.palmCenter=a.palmCenter,o.swirlAngle=a.swirlAngle),this.particles.push(o),this.particleCount++}update(e,t,i,s=null,n=0,a=null){if(this.errorBoundary)return this.errorBoundary.wrap((e,t,i,s,n,a)=>this._update(e,t,i,s,n,a),"particle-update")(e,t,i,s,n,a);this._update(e,t,i,s,n,a)}_update(e,t,i,s=null,n=0,a=null){for(let r=this.particles.length-1;r>=0;r--)this.particles[r].update(e,t,i,a,s,n,this.containmentBounds),this.particles[r].isAlive()||this.removeParticle(r);for(;this.particles.length>this.maxParticles;)this.removeParticle(0)}setGestureBehavior(e,t){this.gestureBehavior=t?e:null,t?this.particles.forEach(t=>{t.gestureBehavior=e}):this.particles.forEach(e=>{e.gestureBehavior=null})}removeParticle(e){if(e>=0&&e<this.particles.length){const t=this.particles.splice(e,1)[0];t.cachedGradient=null,t.cachedGradientKey=null,this.returnParticleToPool(t),this.particleCount=Math.max(0,this.particleCount-1)}}render(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._render(e,t,i)},"particle-render")();this._render(e,t,i)}renderBackground(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._renderLayer(e,t,!1,i)},"particle-render-bg")();this._renderLayer(e,t,!1,i)}renderForeground(e,t="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._renderLayer(e,t,!0,i)},"particle-render-fg")();this._renderLayer(e,t,!0,i)}_renderLayer(e,t,i,s=null){this.particleRenderer.renderLayer(e,this.particles,t,i,s)}_render(e,t,i=null){this.particleRenderer.render(e,this.particles,t,i)}onVisibilityResume(e,t=null){if(this.resetAccumulator(),e>tn)this.clear();else if(e>1e4){const e=this.particles.length,i=t??e,s=Math.max(10,Math.floor(.5*i));for(;this.particles.length>s;)this.removeParticle(0)}}clear(){for(this.stateChangeCount++;this.particles.length>0;){const e=this.particles.pop();if(e.cachedColors&&e.cachedColors.clear(),e.behaviorData)for(const t in e.behaviorData)delete e.behaviorData[t];this.pool.length<this.poolSize&&!this.pool.includes(e)&&this.pool.push(e)}if(this.particles.length=0,this.particleCount=0,this.spawnAccumulator=0,this.pool.length>this.poolSize){const e=this.pool.length-this.poolSize;this.pool.splice(this.poolSize,e)}}burst(e,t,i,s){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this._burst(e,t,i,s)},"particle-burst")();this._burst(e,t,i,s)}_burst(e,t,i,s){const n=Math.min(e,this.maxParticles-this.particles.length);for(let e=0;e<n;e++)this.spawnSingleParticle(t,i,s)}performCleanup(){if(this.pool.length>this.poolSize){const e=this.pool.length-this.poolSize;for(let t=0;t<e;t++){const e=this.pool.pop();e&&(e.cachedGradient=null,e.cachedGradientKey=null,e.behaviorData=null)}}for(const e of this.particles)e.cachedGradient&&e.life<.5&&(e.cachedGradient=null,e.cachedGradientKey=null)}getStats(){return{activeParticles:this.particles.length,maxParticles:this.maxParticles,poolSize:this.pool.length,poolHits:this.poolHits,poolMisses:this.poolMisses,poolEfficiency:this.poolHits/Math.max(1,this.poolHits+this.poolMisses),spawnAccumulator:this.spawnAccumulator}}setMaxParticles(e){for(this.originalMaxParticles=this.originalMaxParticles||this.maxParticles,this.maxParticles=Math.max(1,e);this.particles.length>this.maxParticles;)this.removeParticle(0)}cleanupDeadParticles(){const e=this.particles.length;this.particles=this.particles.filter(e=>e.isAlive());const t=e-this.particles.length;return this.pool.length>20&&(this.pool.length=20),t}getParticlesByBehavior(e){return this.particles.filter(t=>t.behavior===e)}validateParticles(){for(const e of this.particles)if(!e.isAlive()||e.life<0||e.life>1)return!1;return!0}cleanup(){for(let e=this.particles.length-1;e>=0;e--)this.particles[e].isAlive()||this.removeParticle(e)}refreshPool(){this.particlePool.clear();for(const e of this.particles)e.life=0}setContainmentBounds(e){this.containmentBounds=e}destroy(){this.clear(),this.particlePool.clear()}}var un=Object.freeze({__proto__:null,default:cn});const dn=new class{constructor(){this.gestureCache=new Map,this.propertyCache=new Map,this.compositionCache=new Map,this.pluginCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0,gestureHits:0,propertyHits:0,compositionHits:0},this.isInitialized=!1,this.loadStartTime=0}_ensureInitialized(){this.isInitialized||this.initialize()}initialize(){this.loadStartTime=performance.now();try{this.cacheCoreGestures(),this.cacheGestureProperties(),this.cacheCommonCombinations(),this.cachePluginGestures(),this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.gestureCache.size+this.propertyCache.size+this.compositionCache.size,this.isInitialized=!0}catch(e){console.error("GestureCache initialization failed:",e),this.isInitialized=!1,console.warn("[GestureCache] Running uninitialized โ lookups will return defaults")}}cacheCoreGestures(){Object.values(vi).forEach(e=>{e&&e.name&&this.gestureCache.set(e.name,{...e,cached:!0,cacheTime:performance.now()})})}cacheGestureProperties(){this.gestureCache.forEach((e,t)=>{const i={type:e.type,emoji:e.emoji,description:e.description,config:e.config,rhythm:e.rhythm,duration:this.calculateGestureDuration(e),easing:this.extractEasingFunction(e),physics:this.extractPhysicsProperties(e),timing:this.extractTimingProperties(e)};this.propertyCache.set(t,i)})}cacheCommonCombinations(){[["bounce","pulse"],["shake","vibrate"],["orbit","spin"],["morph","glow"],["breathe","fade"],["wave","drift"],["nod","sway"],["jump","stretch"]].forEach(([e,t])=>{const i=`${e}+${t}`,s=this.calculateGestureCombination(e,t);s&&this.compositionCache.set(i,s)})}cachePluginGestures(){try{const e=S.getAllPluginGestures();e&&Object.entries(e).forEach(([e,t])=>{this.pluginCache.set(e,{...t,cached:!0,cacheTime:performance.now(),isPlugin:!0})})}catch(e){console.warn("Could not cache plugin gestures:",e)}}getGesture(e){return this._ensureInitialized(),this.gestureCache.has(e)?(this.stats.hits++,this.stats.gestureHits++,this.gestureCache.get(e)):this.pluginCache.has(e)?(this.stats.hits++,this.stats.gestureHits++,this.pluginCache.get(e)):(this.stats.misses++,null)}getGestureProperties(e){return this._ensureInitialized(),this.propertyCache.has(e)?(this.stats.hits++,this.stats.propertyHits++,this.propertyCache.get(e)):(this.stats.misses++,null)}getGestureCombination(e,t){this._ensureInitialized();const i=`${e}+${t}`;return this.compositionCache.has(i)?(this.stats.hits++,this.stats.compositionHits++,this.compositionCache.get(i)):(this.stats.misses++,null)}calculateGestureDuration(e){if(!e.config)return 1e3;const{musicalDuration:t,duration:i}=e.config;return t&&t.musical?500*(t.beats||2):i||1e3}extractEasingFunction(e){if(!e.config)return"sine";const{easing:t,particleMotion:i}=e.config;return t||i?.easing||"sine"}extractPhysicsProperties(e){if(!e.config)return{};const{amplitude:t,strength:i,size:s,rotation:n}=e.config;return{amplitude:t||20,strength:i||1,size:s||80,rotation:n||0}}extractTimingProperties(e){if(!e.config)return{};const{phases:t,timingSync:i}=e.config;return{phases:t||[],timingSync:i||{},hasPhases:!!(t&&t.length>0),hasTimingSync:!!(i&&Object.keys(i).length>0)}}calculateGestureCombination(e,t){const i=this.getGesture(e),s=this.getGesture(t);return i&&s?{gestures:[e,t],combinedDuration:Math.max(this.calculateGestureDuration(i),this.calculateGestureDuration(s)),combinedType:i.type===s.type?i.type:"mixed",combinedEasing:this.extractEasingFunction(i),combinedPhysics:this.combinePhysicsProperties(i,s),compatibility:this.calculateCompatibility(i,s)}:null}combinePhysicsProperties(e,t){const i=this.extractPhysicsProperties(e),s=this.extractPhysicsProperties(t);return{amplitude:Math.max(i.amplitude,s.amplitude),strength:(i.strength+s.strength)/2,size:Math.max(i.size,s.size),rotation:(i.rotation+s.rotation)/2}}calculateCompatibility(e,t){return e.type===t.type?"high":"blending"===e.type&&"blending"===t.type?"medium":"override"===e.type||"override"===t.type?"low":"medium"}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(1):0;return{...this.stats,hitRate:`${e}%`,isInitialized:this.isInitialized,cacheSize:this.stats.cacheSize,coreGestures:this.gestureCache.size,pluginGestures:this.pluginCache.size,properties:this.propertyCache.size,combinations:this.compositionCache.size}}clear(){this.gestureCache.clear(),this.propertyCache.clear(),this.compositionCache.clear(),this.pluginCache.clear(),this.stats={hits:0,misses:0,loadTime:0,cacheSize:0,gestureHits:0,propertyHits:0,compositionHits:0},this.isInitialized=!1}warmUp(e){e.forEach(e=>{this.getGesture(e),this.getGestureProperties(e)})}};function gn(e){if(dn&&dn.isInitialized){const t=dn.getGesture(e);if(t)return t}return Ai(e)}const mn={none:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1,"3d":{rotation:{speedMultiplier:1,shakeMultiplier:1},glow:{intensityMultiplier:1,pulseSpeedMultiplier:1},scale:{breathDepthMultiplier:1,breathRateMultiplier:1},righting:{strengthMultiplier:1}}},clear:{speed:1,amplitude:1,intensity:1,smoothness:1,regularity:1,"3d":{rotation:{speedMultiplier:1,shakeMultiplier:1},glow:{intensityMultiplier:1,pulseSpeedMultiplier:1},scale:{breathDepthMultiplier:1,breathRateMultiplier:1},righting:{strengthMultiplier:1}}},nervous:{speed:1.2,amplitude:.9,intensity:1.1,smoothness:.7,regularity:.6,addFlutter:!0,addMicroShake:!0,"3d":{rotation:{speedMultiplier:1.5,shakeMultiplier:3.5,enableEpisodicWobble:!0},glow:{intensityMultiplier:1.25,pulseSpeedMultiplier:2},scale:{breathDepthMultiplier:.5,breathRateMultiplier:1.8},righting:{strengthMultiplier:.7}}},confident:{speed:.9,amplitude:1.3,intensity:1.2,smoothness:1.1,regularity:1.2,addPower:!0,addHold:!0,"3d":{rotation:{speedMultiplier:.7,shakeMultiplier:.2},glow:{intensityMultiplier:1.4,pulseSpeedMultiplier:.7},scale:{breathDepthMultiplier:1.5,breathRateMultiplier:.7},righting:{strengthMultiplier:1.6}}},tired:{speed:.7,amplitude:.7,intensity:.8,smoothness:1.3,regularity:.8,addDroop:!0,addPause:!0,"3d":{rotation:{speedMultiplier:.4,shakeMultiplier:.15},glow:{intensityMultiplier:.5,pulseSpeedMultiplier:.5},scale:{breathDepthMultiplier:1.3,breathRateMultiplier:.5},righting:{strengthMultiplier:.6}}},intense:{speed:1.3,amplitude:1.2,intensity:1.4,smoothness:.6,regularity:.9,addPulse:!0,addFocus:!0,"3d":{rotation:{speedMultiplier:1.6,shakeMultiplier:2.5},glow:{intensityMultiplier:1.8,pulseSpeedMultiplier:2.2},scale:{breathDepthMultiplier:1.6,breathRateMultiplier:1.8},righting:{strengthMultiplier:1.3}}},subdued:{speed:.8,amplitude:.8,intensity:.7,smoothness:1.2,regularity:1.1,addSoftness:!0,addFade:!0,"3d":{rotation:{speedMultiplier:.5,shakeMultiplier:.1},glow:{intensityMultiplier:.55,pulseSpeedMultiplier:.6},scale:{breathDepthMultiplier:.7,breathRateMultiplier:.6},righting:{strengthMultiplier:1.4}}}};class pn{constructor(){this.cache=new Map,this.easingCache=new Map,this.preCalculateEasingCurves()}preCalculateEasingCurves(){const e=["linear","ease-in","ease-out","ease-in-out","bounce"];for(const t of e){const e=new Float32Array(101);for(let i=0;i<=100;i++){const s=i/100;e[i]=this.calculateEasing(s,t)}this.easingCache.set(t,e)}}calculateEasing(e,t){switch(t){case"ease-in":return e*e;case"ease-out":return e*(2-e);case"ease-in-out":return e<.5?2*e*e:(4-2*e)*e-1;case"bounce":return e<.363636?7.5625*e*e:e<.727272?7.5625*(e-=.545454)*e+.75:e<.90909?7.5625*(e-=.818181)*e+.9375:7.5625*(e-=.954545)*e+.984375;default:return e}}getEasingValue(e,t){const i=this.easingCache.get(t);return i?i[Math.min(Math.floor(100*e),100)]:e}compose(e,t,i=null){const s=`${e}-${t}-${i||"none"}`;if(this.cache.has(s))return this.cache.get(s);const n=gn(e),a=n?n.config:{duration:500,amplitude:20,easing:"sine"},r=Ks&&Ks.isInitialized?Ks.getModifiers(t):c(t),o=function(e){return e&&""!==e&&"clear"!==e&&mn[e]||mn.clear}(i),l=this.applyModifiers(a,r,o,e);return this.cache.size>100&&this.cache.clear(),this.cache.set(s,l),l}applyModifiers(e,t,i,s){const n={...e},a=t.speed*i.speed;if(n.duration=Math.round(e.duration/a),void 0!==n.amplitude&&(n.amplitude=e.amplitude*t.amplitude*i.amplitude),void 0!==n.scaleAmount&&(n.scaleAmount=e.scaleAmount*t.intensity*i.intensity),void 0!==n.scaleTarget){const s=t.amplitude*i.amplitude;n.scaleTarget=1+(e.scaleTarget-1)*s}void 0!==n.glowAmount&&(n.glowAmount=e.glowAmount*t.intensity*i.intensity),void 0!==n.glowPeak&&(n.glowPeak=1+(e.glowPeak-1)*t.intensity*i.intensity),void 0!==n.rotations&&(n.rotations=e.rotations*t.amplitude*i.amplitude),void 0!==n.angle&&(n.angle=e.angle*t.amplitude*i.amplitude),void 0!==n.distance&&(n.distance=e.distance*t.amplitude*i.amplitude);const r=t.smoothness*i.smoothness;return n.smoothness=r,n.easing=this.selectEasing(e.easing,r),n.regularity=t.regularity*i.regularity,n.effects=[],t.addBounce&&n.effects.push("bounce"),t.addGravity&&n.effects.push("gravity"),t.addShake&&n.effects.push("shake"),t.addJitter&&n.effects.push("shake"),t.addPop&&n.effects.push("pop"),t.addRecoil&&n.effects.push("recoil"),t.addWarmth&&n.effects.push("warmth"),t.addFlow&&n.effects.push("flow"),t.addWobble&&n.effects.push("wobble"),t.addVibration&&n.effects.push("vibration"),t.addDrag&&n.effects.push("drag"),t.addWeight&&n.effects.push("weight"),t.addTension&&n.effects.push("tension"),t.addPrecision&&n.effects.push("precision"),i.addFlutter&&n.effects.push("flutter"),i.addMicroShake&&n.effects.push("microShake"),i.addPower&&n.effects.push("power"),i.addHold&&n.effects.push("hold"),i.addDroop&&n.effects.push("droop"),i.addPause&&n.effects.push("pause"),i.addPulse&&n.effects.push("pulse"),i.addFocus&&n.effects.push("focus"),i.addSoftness&&n.effects.push("softness"),i.addFade&&n.effects.push("fade"),this.applyGestureSpecificMods(n,s,t,i),e.particleMotion&&(n.particleMotion={...e.particleMotion},void 0!==n.particleMotion.strength&&(n.particleMotion.strength*=t.intensity*i.intensity),void 0!==n.particleMotion.frequency&&(n.particleMotion.frequency*=a),void 0!==n.particleMotion.amplitude&&(n.particleMotion.amplitude*=t.amplitude*i.amplitude)),n}selectEasing(e,t){return t<.5?"linear":t<.8?"quad":t<1.2?e:t<1.5?"cubic":"sine"}applyGestureSpecificMods(e,t,i,s){switch(t){case"bounce":i.addShake&&(e.frequency=Math.floor(1.5*e.frequency)),i.addGravity&&(e.amplitude*=.6,e.frequency=1);break;case"pulse":i.addWarmth&&(e.frequency=2,e.glowAmount*=1.5),s.addFlutter&&(e.irregular=!0);break;case"shake":i.addJitter&&(e.frequency*=1.5,e.amplitude*=1.2),i.addShake&&(e.amplitude*=1.5,e.decay=!1);break;case"spin":i.addBounce&&(e.rotations*=1.5),i.addWobble&&(e.wobble=!0)}}clearCache(){this.cache.clear()}}const fn=new class{constructor(){this.noteDurations={whole:4,half:2,quarter:1,eighth:.5,sixteenth:.25,triplet:.333,"dotted-quarter":1.5,"dotted-half":3},this.cache=new Map,this.maxCacheSize=100,this.cacheAccessOrder=[],this.lastBPM=0,this.prewarmCache()}prewarmCache(){const e=[{musical:!0,beats:1},{musical:!0,bars:1},{musical:!0,beats:.5},{musical:!0,beats:2}];[60,90,120,140,160,180].forEach(t=>{e.forEach(e=>{const i=`${t}_${JSON.stringify(e)}`,s=this.toMilliseconds(e,t);if(this.cache.size>=this.maxCacheSize){const e=this.cacheAccessOrder.shift();this.cache.delete(e)}this.cache.set(i,s),this.cacheAccessOrder.push(i)})})}toMilliseconds(e,t=null){const i=t||sn.bpm||120;if("number"==typeof e)return e;if("object"==typeof e&&e.musical){const t=6e4/i;if(void 0!==e.beats)return e.beats*t;if(void 0!==e.bars){const i=sn.timeSignature||[4,4];return e.bars*i[0]*t}if(void 0!==e.subdivision)return(this.noteDurations[e.subdivision]||1)*t}return 1e3}toMusical(e,t=null){const i=e/(6e4/(t||sn.bpm||120));let s="quarter",n=Math.abs(i-1);for(const[e,t]of Object.entries(this.noteDurations)){const a=Math.abs(i-t);a<n&&(n=a,s=e)}return{musical:!0,beats:i,bars:i/4,closestSubdivision:s,exact:n<.01}}calculatePhases(e,t){if(!e||0===e.length)return[{name:"main",beats:t,start:0,end:1}];const i=e.reduce((e,t)=>e+(t.beats||1),0),s=t/i;let n=0;return e.map(e=>{const i=(e.beats||1)*s,a=n/t;n+=i;const r=n/t;return{name:e.name,beats:i,start:a,end:r,duration:this.toMilliseconds({musical:!0,beats:i})}})}getBeatProgress(){const e=sn.getTimeInfo();return e?e.beatProgress:0}getBarProgress(){const e=sn.getTimeInfo();return e?e.barProgress:0}timeToNextBoundary(e="beat"){const t=sn.getTimeInfo();if(!t)return 100;switch(e){case"beat":default:return t.nextBeatIn;case"bar":return(t.timeSignature[0]-t.beatInBar)*t.beatDuration;case"phrase":{const e=4,i=t.timeSignature[0];return(e-(t.bar||0)%e)*i*t.beatDuration}}}quantize(e,t="eighth"){const i=6e4/(sn.bpm||120),s=(this.noteDurations[t]||1)*i;return Math.round(e/s)*s}isOnBoundary(e="beat",t=50){const i=this.timeToNextBoundary(e),s=sn.getTimeInfo();return!!s&&(i<t||s.beatDuration-i<t)}getTempoAdaptation(e=120){const t=(sn.bpm||120)/e;return{speed:t,energy:Math.min(2,Math.max(.5,t)),smoothness:t<.8?1.2:t>1.5?.8:1,intensity:t>1.3?1.2:t<.7?.8:1}}};class yn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyBounce(e,t){return{offsetY:-Math.abs(Math.sin(t*Math.PI*e.params.frequency))*e.params.amplitude*this.scaleFactor*(e.params.effects&&e.params.effects.includes("gravity")?.6:1)}}applyShake(e,t){e.randomAngle||(e.randomAngle=Math.random()*Math.PI*2);const i=e.params.decay?1-t:1,s=Math.sin(t*Math.PI*e.params.frequency)*e.params.amplitude*i*this.scaleFactor;return{offsetX:s*Math.cos(e.randomAngle),offsetY:s*Math.sin(e.randomAngle)}}applyJump(e,t){let i,s,n=0,a=1;if(t<.2){const i=t/.2;a=1-(1-e.params.squashAmount)*i}else if(t<.7){const i=(t-.2)/.5,s=Math.sin(i*Math.PI);n=-e.params.jumpHeight*s*this.scaleFactor,a=e.params.squashAmount+(e.params.stretchAmount-e.params.squashAmount)*s}else{const i=(t-.7)/.3;a=e.params.stretchAmount-(e.params.stretchAmount-1)*i}if(e.params.effects&&e.params.effects.includes("gravity")){const e=t<.7?(t-.2)/.5:0,n=Math.sin(e*Math.PI);i=1+.2*n,s=1-.15*n}const r={offsetY:n,scale:a};return void 0!==i&&(r.scaleX=i),void 0!==s&&(r.scaleY=s),r}applyVibrate(e,t){if(!e.vibrateAngles){e.vibrateAngles={x:2*Math.random()-1,y:2*Math.random()-1};const t=Math.sqrt(e.vibrateAngles.x**2+e.vibrateAngles.y**2);e.vibrateAngles.x/=t,e.vibrateAngles.y/=t}const i=e.params.amplitude||5,s=e.params.frequency||20,n=Math.sin(t*Math.PI*2*s)*i*this.scaleFactor;return{offsetX:n*e.vibrateAngles.x,offsetY:n*e.vibrateAngles.y}}applyWiggle(e,t){const i=(e.params?.amplitude||15)*this.scaleFactor;void 0===e.wiggleDirection&&(e.wiggleDirection=Math.random()<.5?1:-1);const s=e.wiggleDirection;let n=0,a=0;if(t<.25){const e=t/.25;n=i*s*e,a=3*s*e}else if(t<.5){const e=(t-.25)/.25;n=i*s*(1-2*e),a=3*s*(1-2*e)}else if(t<.75){const e=(t-.5)/.25;n=i*-s*(1-2*e),a=3*-s*(1-2*e)}else{const e=(t-.75)/.25;n=i*s*(1-e),a=3*s*(1-e)}return{offsetX:n,offsetY:-Math.abs(Math.sin(t*Math.PI*4))*i*.15,rotation:a}}}class bn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyFlash(e,t){const i=Math.sin(t*Math.PI);return{glow:1+((e.params.glowPeak||2)-1)*i,scale:1+((e.params.scalePeak||1.1)-1)*i}}applyGlow(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+i*(e.params.scaleAmount||.1),glow:1+i*(e.params.glowAmount||.8)}}applyFlicker(e,t){const i=e.params?.intensity||2,s=e.params?.speed||3,n=1+Math.sin(t*Math.PI*2*s)*i*.3,a=5*Math.sin(t*Math.PI*4)*this.scaleFactor,r=.001*Date.now();return{offsetX:a,glow:n,particleGlow:(.5*Math.sin(t*Math.PI*s*2)+.5)*i,flickerTime:r,flickerEffect:!0}}applySparkle(e,t){const i=e.params?.intensity||2,s=.001*Date.now();return{particleGlow:i,glow:.3*Math.sin(t*Math.PI*4)+.7,fireflyTime:s,fireflyEffect:!0}}applyShimmer(e,t){const i=.001*Date.now(),s=e.params?.intensity||.3,n=Math.sin(2*i+t*Math.PI*2);return{offsetX:0,offsetY:0,glow:1+n*s,scale:1+.01*n,particleGlow:1+.2*n,shimmerTime:i,shimmerWave:n,shimmerEffect:!0}}}class vn{constructor(e){this.renderer=e}applyBreathe(e,t){const{params:i}=e,s=i.particleMotion?.holdPercent||.1;let n;if(t<.4)n=Math.sin(t/.4*Math.PI/2);else if(t<.4+s)n=1;else if(t<.9){const e=(t-.4-s)/(.5-s);n=Math.cos(e*Math.PI/2)}else n=0;const a=1+n*(i.scaleAmount||.25),r=1+n*(i.glowAmount||.4);return e.breathPhase=n,{scale:a,glow:r,breathPhase:n}}applyBreathIn(e,t){return{scale:1+(e.params.scaleAmount-1)*Math.sin(t*Math.PI/2)}}applyBreathOut(e,t){return{scale:1-(1-e.params.scaleAmount)*Math.sin(t*Math.PI/2)}}applyBreathHold(e,t){return{scale:e.params.scaleAmount}}applyBreathHoldEmpty(e,t){return{scale:e.params.scaleAmount}}}class Mn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applySpin(e,t){return{rotation:Math.min(1.05*t,1)*e.params.rotations*360,scale:1+Math.sin(t*Math.PI)*e.params.scaleAmount}}applyDrift(e,t){t<=.01&&!e.currentDriftAngle&&(e.currentDriftAngle=Math.random()*Math.PI*2);const i=e.params.distance*Math.sin(t*Math.PI)*this.scaleFactor,s=e.currentDriftAngle||0;return t>=.99&&(e.currentDriftAngle=null),{offsetX:Math.cos(s)*i,offsetY:Math.sin(s)*i}}applyWave(e,t){const i=(e.params.amplitude||40)*this.scaleFactor,s=t*Math.PI*2,n=Math.sin(s)*i,a=-Math.sin(t*Math.PI)*i*.3;return{offsetX:n,offsetY:Math.sin(2*s)*i*.2+a,rotation:5*Math.sin(s),scale:1+.05*Math.sin(t*Math.PI*2),glow:1+.2*Math.sin(t*Math.PI)}}applySway(e,t){const i=(e.params?.amplitude||30)*this.scaleFactor,s=e.params?.frequency||1;return{offsetX:Math.sin(t*Math.PI*2*s)*i,offsetY:Math.sin(t*Math.PI*4*s)*i*.1,rotation:5*Math.sin(t*Math.PI*2*s)}}applyFloat(e,t){const i=(e.params?.amplitude||20)*this.scaleFactor,s=e.params?.speed||1,n=Math.sin(t*Math.PI*2*s)*i;return{offsetX:Math.sin(t*Math.PI*3*s)*i*.3,offsetY:n,scale:1+.02*Math.sin(t*Math.PI*4*s)}}applyOrbital(e,t){return{offsetX:0,offsetY:0}}applyHula(e,t){const i=(e.params?.amplitude||40)*this.scaleFactor,s=t*Math.PI*2;return{offsetX:Math.sin(s)*i,offsetY:Math.sin(2*s)*i*.5}}applyOrbit(e,t){const i=(e.params?.radius||30)*this.scaleFactor,s=e.params?.speed||1,n=t*Math.PI*2*s;return{offsetX:Math.cos(n)*i,offsetY:Math.sin(n)*i}}}class wn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyPulse(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+i*e.params.scaleAmount,glow:1+i*e.params.glowAmount}}applyExpand(e,t){const i=Math.max(e.params.scaleAmount||e.params.scaleTarget||1.5,1),s=Math.sin(t*Math.PI/2);return{scale:1+(i-1)*s,glow:1+Math.abs(e.params.glowAmount||.2)*s}}applyContract(e,t){const i=e.params.scaleAmount||e.params.scaleTarget||.7,s=Math.sin(t*Math.PI/2);return{scale:1+(i-1)*s,glow:1+(e.params.glowAmount||-.2)*s}}applyStretch(e,t){const i=Math.sin(t*Math.PI*e.params.frequency);return{scale:1+((e.params.scaleX+e.params.scaleY)/2-1)*i}}applyMorph(e,t){const i=Math.sin(t*Math.PI*2);return{scale:1+.1*i,rotation:10*i}}}class Sn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyNod(e,t){return{offsetY:Math.sin(t*Math.PI*e.params.frequency)*e.params.amplitude*this.scaleFactor}}applyTilt(e,t){e.tiltDirection||(e.tiltDirection=Math.random()<.5?-1:1);const i=e.params.frequency||2,s=(e.params.angle||15)*Math.PI/180,n=Math.sin(t*Math.PI*i)*e.tiltDirection;return{rotation:n*s,scaleX:1+.1*Math.abs(n),scaleY:1-.05*Math.abs(n),offsetX:10*n,offsetY:-5*Math.abs(n)}}applySlowBlink(e,t){let i=1;return i=t<.3?1-t/.3:t<.5?0:t<.8?(t-.5)/.3:1,{glow:i}}applyLook(e,t){if(!e.targetX){const t=e.params.lookDirection,i=50*e.params.lookDistance*this.scaleFactor;switch(t){case"left":e.targetX=-i,e.targetY=0;break;case"right":e.targetX=i,e.targetY=0;break;case"up":e.targetX=0,e.targetY=-i;break;case"down":e.targetX=0,e.targetY=i;break;default:{const t=Math.random()*Math.PI*2;e.targetX=Math.cos(t)*i,e.targetY=Math.sin(t)*i;break}}}let i=t;return i=t<.3?t/.3:t<.7?1:1-(t-.7)/.3,{offsetX:e.targetX*i,offsetY:e.targetY*i}}applySettle(e,t){const i=Math.sin(t*Math.PI*e.params.wobbleFreq)*Math.exp(3*-t)*20*this.scaleFactor;return{offsetY:i,scale:1+.01*i}}}class xn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyPoint(e,t){void 0===e.pointDirection&&(e.pointDirection=Math.random()<.5?-1:1);const i=void 0!==e.params?.direction?e.params.direction:e.pointDirection,s=(e.params?.distance||40)*this.scaleFactor;let n,a;return t<.4?(n=1-Math.pow(1-t/.4,3),a=n):t<.6?(n=1,a=1):(n=Math.pow(1-(t-.6)/.4,3),a=n),{offsetX:i*s*n,offsetY:-Math.abs(.15*s*n),scale:1+.15*a,rotation:5*i*a}}applyLean(e,t){const i=e.params?.angle||15,s=e.params?.side||1,n=Math.sin(t*Math.PI),a=i*s*n;return{offsetX:10*s*this.scaleFactor*n,rotation:a}}applyReach(e,t){const i=void 0!==e.params?.direction?e.params.direction:-Math.PI/2,s=(e.params?.distance||40)*this.scaleFactor;let n;return n=t<.4?t/.4:t<.6?1:1-(t-.6)/.4,n=n*n*(3-2*n),{offsetX:Math.cos(i)*s*n,offsetY:Math.sin(i)*s*n,scale:1+.15*n}}}class Cn{constructor(e){this.renderer=e,this.scaleFactor=e.scaleFactor||1}applyFlashWave(e,t){e.flashWave||(e.flashWave={innerRadius:0,outerRadius:0,maxRadius:3}),e.flashWave.outerRadius=t*e.flashWave.maxRadius,e.flashWave.innerRadius=Math.max(0,(t-.1)*e.flashWave.maxRadius);const i=Math.max(0,1-.7*t);return e.flashWaveData={innerRadius:e.flashWave.innerRadius,outerRadius:e.flashWave.outerRadius,intensity:i},{glow:1+.3*i,flashWave:e.flashWaveData}}applyRain(e,t){return{offsetX:0,offsetY:0,particleEffect:"rain"}}applyGroove(e,t){const i=(e.params?.amplitude||25)*this.scaleFactor;return{offsetX:Math.sin(t*Math.PI*2)*i+Math.sin(t*Math.PI*3+.5)*i*.4,offsetY:Math.sin(t*Math.PI*4+.3)*i*.25,scale:1+.03*Math.sin(t*Math.PI*3+.7),rotation:8*Math.sin(t*Math.PI*2+.2)}}applyHeadBob(e,t){const i=(e.params?.amplitude||20)*this.scaleFactor,s=t*(e.params?.frequency||2)%1;let n;return n=s<.3?s/.3*-i:-i*(1-(s-.3)/.7),{offsetY:n,rotation:s<.3?-3:0}}applyRunningMan(e,t){const i=20*Math.sin(t*Math.PI*4)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(t*Math.PI*8))*this.scaleFactor,rotation:.3*i,scaleY:1-.05*Math.abs(Math.sin(t*Math.PI*8))}}applyCharleston(e,t){const i=25*Math.sin(t*Math.PI*8)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(t*Math.PI*8))*this.scaleFactor,rotation:.6*i,scaleY:1-.06*Math.abs(Math.sin(t*Math.PI*8))}}}class kn{constructor(e){this.renderer=e,this.activeGestures=new Map,this.scaleFactor=e.scaleFactor||1,this.physicalGestureAnimator=new yn(e),this.visualEffectAnimator=new bn(e),this.breathGestureAnimator=new vn(e),this.movementGestureAnimator=new Mn(e),this.shapeTransformAnimator=new wn(e),this.expressionGestureAnimator=new Sn(e),this.directionalGestureAnimator=new xn(e),this.complexAnimationAnimator=new Cn(e),this.gestureAnimations={bounce:{active:!1,progress:0,params:{}},pulse:{active:!1,progress:0,params:{}},shake:{active:!1,progress:0,params:{}},spin:{active:!1,progress:0,params:{}},nod:{active:!1,progress:0,params:{}},tilt:{active:!1,progress:0,params:{}},expand:{active:!1,progress:0,params:{}},contract:{active:!1,progress:0,params:{}},flash:{active:!1,progress:0,params:{}},drift:{active:!1,progress:0,params:{}},stretch:{active:!1,progress:0,params:{}},glow:{active:!1,progress:0,params:{}},flicker:{active:!1,progress:0,params:{}},vibrate:{active:!1,progress:0,params:{}},orbital:{active:!1,progress:0,params:{}},hula:{active:!1,progress:0,params:{}},wave:{active:!1,progress:0,params:{}},breathe:{active:!1,progress:0,params:{}},morph:{active:!1,progress:0,params:{}},slowBlink:{active:!1,progress:0,params:{}},look:{active:!1,progress:0,params:{}},settle:{active:!1,progress:0,params:{}},breathIn:{active:!1,progress:0,params:{}},breathOut:{active:!1,progress:0,params:{}},breathHold:{active:!1,progress:0,params:{}},breathHoldEmpty:{active:!1,progress:0,params:{}},jump:{active:!1,progress:0,params:{}},sway:{active:!1,progress:0,params:{}},float:{active:!1,progress:0,params:{}},sparkle:{active:!1,progress:0,params:{}},shimmer:{active:!1,progress:0,params:{}},wiggle:{active:!1,progress:0,params:{}},groove:{active:!1,progress:0,params:{}},point:{active:!1,progress:0,params:{}},lean:{active:!1,progress:0,params:{}},reach:{active:!1,progress:0,params:{}},headBob:{active:!1,progress:0,params:{}},orbit:{active:!1,progress:0,params:{}},rain:{active:!1,progress:0,params:{}},runningman:{active:!1,progress:0,params:{}},charleston:{active:!1,progress:0,params:{}}}}startGesture(e){const t=gn(e);if(["bounce","shake","pulse","flash","jump","slam","spin","flicker"].includes(e)&&this.renderer.specialEffects){const t={flash:1,jump:1,shake:.9,bounce:.8,pulse:.7,slam:1,spin:.8,flicker:1}[e]||.8;this.renderer.specialEffects.triggerChromaticAberration(t)}let i;i=this.renderer.gestureCompositor?this.renderer.gestureCompositor.compose(e,this.renderer.state.emotion,this.renderer.currentUndertone):t?.config||{amplitude:20,frequency:2,duration:1e3,scaleAmount:.2,glowAmount:.3,rotations:1,distance:50,angle:15,scaleTarget:1.5,glowPeak:2,scalePeak:1.1,scaleX:1.2,scaleY:.8,maxOpacity:1,minOpacity:.5,lookDirection:"random",lookDistance:1,wobbleFreq:4,squashAmount:.8,stretchAmount:1.2,jumpHeight:100,decay:!0,easing:"sine",effects:[]};let s=1e3;if(t&&t.config)if(t.config.musicalDuration)s=fn.toMilliseconds(t.config.musicalDuration);else if(t.config.duration){const{duration:e}=t.config;s=e}const n=this.gestureAnimations[e];n&&(n.active=!0,n.startTime=performance.now(),n.progress=0,n.params=i,n.duration=s,"shake"===e?n.randomAngle=void 0:"drift"===e?(n.startX=void 0,n.startY=void 0,n.currentDriftAngle=void 0):"tilt"===e?n.tiltDirection=void 0:"vibrate"===e&&(n.vibrateAngles=void 0))}applyGestureAnimations(){const e=performance.now(),t={offsetX:0,offsetY:0,scale:1,rotation:0,glow:1};for(const[i,s]of Object.entries(this.gestureAnimations)){if(!s.active)continue;const n=e-s.startTime,a=s.duration||(s.params?s.params.duration:1e3);s.progress=Math.min(n/a,1);const r=this.applyEasing(s.progress,s.params.easing);let o={};switch(i){case"bounce":o=this.applyBounce(s,r);break;case"pulse":o=this.applyPulse(s,r);break;case"shake":o=this.applyShake(s,r);break;case"spin":o=this.applySpin(s,r);break;case"nod":o=this.applyNod(s,r);break;case"tilt":o=this.applyTilt(s,r);break;case"expand":o=this.applyExpand(s,r);break;case"contract":o=this.applyContract(s,r);break;case"flash":o=this.applyFlash(s,r);break;case"drift":o=this.applyDrift(s,r);break;case"stretch":o=this.applyStretch(s,r);break;case"glow":o=this.applyGlow(s,r);break;case"flicker":o=this.applyFlicker(s,r);break;case"vibrate":o=this.applyVibrate(s,r);break;case"orbital":o=this.applyOrbital(s,r);break;case"hula":o=this.applyHula(s,r);break;case"wave":o=this.applyWave(s,r);break;case"breathe":o=this.applyBreathe(s,r);break;case"morph":o=this.applyMorph(s,r);break;case"slowBlink":o=this.applySlowBlink(s,r);break;case"look":o=this.applyLook(s,r);break;case"settle":o=this.applySettle(s,r);break;case"breathIn":o=this.applyBreathIn(s,r);break;case"breathOut":o=this.applyBreathOut(s,r);break;case"breathHold":o=this.applyBreathHold(s,r);break;case"breathHoldEmpty":o=this.applyBreathHoldEmpty(s,r);break;case"jump":o=this.applyJump(s,r);break;case"sway":o=this.applySway(s,r);break;case"float":o=this.applyFloat(s,r);break;case"rain":o=this.applyRain(s,r);break;case"runningman":o=this.applyRunningMan(s,r);break;case"charleston":o=this.applyCharleston(s,r);break;case"sparkle":o=this.applySparkle(s,r);break;case"shimmer":o=this.applyShimmer(s,r);break;case"wiggle":o=this.applyWiggle(s,r);break;case"groove":o=this.applyGroove(s,r);break;case"point":o=this.applyPoint(s,r);break;case"lean":o=this.applyLean(s,r);break;case"reach":o=this.applyReach(s,r);break;case"headBob":o=this.applyHeadBob(s,r);break;case"orbit":o=this.applyOrbit(s,r)}t.offsetX+=o.offsetX||0,t.offsetY+=o.offsetY||0,t.scale*=o.scale||1,t.rotation+=o.rotation||0,t.glow=Math.max(t.glow,o.glow||1),o.flashWave&&(t.flashWave=o.flashWave),o.fireflyEffect&&(t.fireflyEffect=o.fireflyEffect,t.particleGlow=o.particleGlow,t.fireflyTime=o.fireflyTime),o.flickerEffect&&(t.flickerEffect=o.flickerEffect,t.particleGlow=o.particleGlow,t.flickerTime=o.flickerTime),o.shimmerEffect&&(t.shimmerEffect=o.shimmerEffect,t.particleGlow=o.particleGlow,t.shimmerTime=o.shimmerTime,t.shimmerWave=o.shimmerWave),o.glowEffect&&(t.glowEffect=o.glowEffect,t.particleGlow=o.particleGlow,t.glowTime=o.glowTime,t.glowProgress=o.glowProgress,t.glowEnvelope=o.glowEnvelope),s.progress>=1&&(s.active=!1,s.progress=0,s.startTime=0,"flash"===i&&(s.flashWave=null,s.flashWaveData=null),o.glowEffect&&(o.glowEffect=null,o.particleGlow=null,o.glowTime=null,o.glowProgress=null,o.glowEnvelope=null),o.fireflyEffect&&(o.fireflyEffect=null,o.particleGlow=null,o.fireflyTime=null),o.flickerEffect&&(o.flickerEffect=null,o.particleGlow=null,o.flickerTime=null),o.shimmerEffect&&(o.shimmerEffect=null,o.particleGlow=null,o.shimmerTime=null,o.shimmerWave=null))}return t}update(e){return this.applyGestureAnimations()}stopAllGestures(){Object.keys(this.gestureAnimations).forEach(e=>{const t=this.gestureAnimations[e];t.active=!1,t.startTime=0,t.progress=0,t.params=null,t.glowEffect&&(t.glowEffect=null,t.particleGlow=null,t.glowTime=null,t.glowProgress=null,t.glowEnvelope=null),t.fireflyEffect&&(t.fireflyEffect=null,t.particleGlow=null,t.fireflyTime=null),t.flickerEffect&&(t.flickerEffect=null,t.particleGlow=null,t.flickerTime=null),t.shimmerEffect&&(t.shimmerEffect=null,t.particleGlow=null,t.shimmerTime=null,t.shimmerWave=null),t.flashWave&&(t.flashWave=null,t.flashWaveData=null)}),this.activeGestures.clear()}getCurrentGesture(){const e=performance.now(),t=["orbital","hula","wave","spin"];for(const i of t){const t=this.gestureAnimations[i];if(t&&t.active){const s=gn(i),n=e-t.startTime,a=t.duration||(t.params?t.params.duration:1e3),r=Math.min(n/a,1);return{name:i,particleMotion:s?.config?.particleMotion||{type:i,strength:t.params?.strength||1},progress:r,params:t.params}}}for(const[t,i]of Object.entries(this.gestureAnimations))if(i.active){const s=gn(t),n=e-i.startTime,a=i.duration||(i.params?i.params.duration:1e3),r=Math.min(n/a,1),o={name:t,particleMotion:s?.config?.particleMotion||i.params?.particleMotion||{type:t,strength:i.params?.strength||1},progress:r,params:i.params};return"breathe"===t&&void 0!==i.breathPhase&&(o.breathPhase=i.breathPhase),o}return null}applyEasing(e,t){switch(t){case"linear":default:return e;case"quad":return e*e;case"cubic":return e*e*e;case"sine":return Math.sin(e*Math.PI/2);case"back":return e*e*(2.7*e-1.7)}}applyBounce(e,t){return this.physicalGestureAnimator.applyBounce(e,t)}applyPulse(e,t){return this.shapeTransformAnimator.applyPulse(e,t)}applyShake(e,t){return this.physicalGestureAnimator.applyShake(e,t)}applySpin(e,t){return this.movementGestureAnimator.applySpin(e,t)}applyNod(e,t){return this.expressionGestureAnimator.applyNod(e,t)}applyTilt(e,t){return this.expressionGestureAnimator.applyTilt(e,t)}applyExpand(e,t){return this.shapeTransformAnimator.applyExpand(e,t)}applyContract(e,t){return this.shapeTransformAnimator.applyContract(e,t)}applyFlash(e,t){return this.visualEffectAnimator.applyFlash(e,t)}applyDrift(e,t){return this.movementGestureAnimator.applyDrift(e,t)}applyStretch(e,t){return this.shapeTransformAnimator.applyStretch(e,t)}applyGlow(e,t){return this.visualEffectAnimator.applyGlow(e,t)}applyFlashWave(e,t){return this.complexAnimationAnimator.applyFlashWave(e,t)}applyFlicker(e,t){return this.visualEffectAnimator.applyFlicker(e,t)}applyVibrate(e,t){return this.physicalGestureAnimator.applyVibrate(e,t)}applyWave(e,t){return this.movementGestureAnimator.applyWave(e,t)}applyBreathe(e,t){return this.breathGestureAnimator.applyBreathe(e,t)}applyMorph(e,t){return this.shapeTransformAnimator.applyMorph(e,t)}applySlowBlink(e,t){return this.expressionGestureAnimator.applySlowBlink(e,t)}applyLook(e,t){return this.expressionGestureAnimator.applyLook(e,t)}applySettle(e,t){return this.expressionGestureAnimator.applySettle(e,t)}applyBreathIn(e,t){return this.breathGestureAnimator.applyBreathIn(e,t)}applyBreathOut(e,t){return this.breathGestureAnimator.applyBreathOut(e,t)}applyBreathHold(e,t){return this.breathGestureAnimator.applyBreathHold(e,t)}applyBreathHoldEmpty(e,t){return this.breathGestureAnimator.applyBreathHoldEmpty(e,t)}applyJump(e,t){return this.physicalGestureAnimator.applyJump(e,t)}applySway(e,t){return this.movementGestureAnimator.applySway(e,t)}applyRain(e,t){return this.complexAnimationAnimator.applyRain(e,t)}applyFloat(e,t){return this.movementGestureAnimator.applyFloat(e,t)}applyOrbital(e,t){return this.movementGestureAnimator.applyOrbital(e,t)}applyHula(e,t){return this.movementGestureAnimator.applyHula(e,t)}applySparkle(e,t){return this.visualEffectAnimator.applySparkle(e,t)}applyShimmer(e,t){return this.visualEffectAnimator.applyShimmer(e,t)}applyWiggle(e,t){return this.physicalGestureAnimator.applyWiggle(e,t)}applyGroove(e,t){return this.complexAnimationAnimator.applyGroove(e,t)}applyPoint(e,t){return this.directionalGestureAnimator.applyPoint(e,t)}applyLean(e,t){return this.directionalGestureAnimator.applyLean(e,t)}applyReach(e,t){return this.directionalGestureAnimator.applyReach(e,t)}applyHeadBob(e,t){return this.complexAnimationAnimator.applyHeadBob(e,t)}applyOrbit(e,t){return this.movementGestureAnimator.applyOrbit(e,t)}startBounce(){this.startGesture("bounce")}startPulse(){this.startGesture("pulse")}startShake(){this.startGesture("shake")}startSpin(){this.startGesture("spin")}startNod(){this.startGesture("nod")}startTilt(){this.startGesture("tilt")}startExpand(){this.startGesture("expand")}startContract(){this.startGesture("contract")}startFlash(){this.startGesture("flash")}startDrift(){this.startGesture("drift")}startStretch(){this.startGesture("stretch")}startGlow(){this.startGesture("glow")}startFlicker(){this.startGesture("flicker")}startVibrate(){this.startGesture("vibrate")}startOrbital(){this.startGesture("orbital")}startHula(){this.startGesture("hula")}startWave(){this.startGesture("wave")}startBreathe(){this.startGesture("breathe")}startMorph(){this.startGesture("morph")}startSlowBlink(){this.startGesture("slowBlink")}startLook(){this.startGesture("look")}startSettle(){this.startGesture("settle")}startBreathIn(){this.startGesture("breathIn")}startBreathOut(){this.startGesture("breathOut")}startBreathHold(){this.startGesture("breathHold")}startBreathHoldEmpty(){this.startGesture("breathHoldEmpty")}startJump(){this.startGesture("jump")}startSway(){this.startGesture("sway")}startFloat(){this.startGesture("float")}startRain(){this.startGesture("rain")}startRunningMan(){this.startGesture("runningman")}startCharleston(){this.startGesture("charleston")}startSparkle(){this.startGesture("sparkle")}startShimmer(){this.startGesture("shimmer")}startWiggle(){this.startGesture("wiggle")}startGroove(){this.startGesture("groove")}startPoint(){this.startGesture("point")}startLean(){this.startGesture("lean")}startReach(){this.startGesture("reach")}startHeadBob(){this.startGesture("headBob")}startOrbit(){this.startGesture("orbit")}applyRunningMan(e,t){return this.complexAnimationAnimator.applyRunningMan(e,t)}applyCharleston(e,t){return this.complexAnimationAnimator.applyCharleston(e,t)}startRunningManGesture(){this.startGesture("runningman")}startCharlestonGesture(){this.startGesture("charleston")}pauseCurrentAnimation(){const e=performance.now();for(const[,t]of Object.entries(this.gestureAnimations))t.active&&(t.pausedAt=e,t.pausedProgress=t.progress);this.isPaused=!0}resumeAnimation(){if(!this.isPaused)return;const e=performance.now();for(const[,t]of Object.entries(this.gestureAnimations))if(t.active&&t.pausedAt){const i=e-t.pausedAt;t.startTime&&(t.startTime+=i),delete t.pausedAt,delete t.pausedProgress}this.isPaused=!1}reset(){for(const[,e]of Object.entries(this.gestureAnimations))e.active=!1,e.progress=0,e.params={},delete e.startTime,delete e.pausedAt,delete e.pausedProgress;this.activeGestures.clear(),this.isPaused=!1}destroy(){this.stopAllGestures(),this.physicalGestureAnimator&&"function"==typeof this.physicalGestureAnimator.destroy&&this.physicalGestureAnimator.destroy(),this.visualEffectAnimator&&"function"==typeof this.visualEffectAnimator.destroy&&this.visualEffectAnimator.destroy(),this.breathGestureAnimator&&"function"==typeof this.breathGestureAnimator.destroy&&this.breathGestureAnimator.destroy(),this.movementGestureAnimator&&"function"==typeof this.movementGestureAnimator.destroy&&this.movementGestureAnimator.destroy(),this.shapeTransformAnimator&&"function"==typeof this.shapeTransformAnimator.destroy&&this.shapeTransformAnimator.destroy(),this.expressionGestureAnimator&&"function"==typeof this.expressionGestureAnimator.destroy&&this.expressionGestureAnimator.destroy(),this.directionalGestureAnimator&&"function"==typeof this.directionalGestureAnimator.destroy&&this.directionalGestureAnimator.destroy(),this.complexAnimationAnimator&&"function"==typeof this.complexAnimationAnimator.destroy&&this.complexAnimationAnimator.destroy(),this.physicalGestureAnimator=null,this.visualEffectAnimator=null,this.breathGestureAnimator=null,this.movementGestureAnimator=null,this.shapeTransformAnimator=null,this.expressionGestureAnimator=null,this.directionalGestureAnimator=null,this.complexAnimationAnimator=null,this.gestureAnimations=null,this.activeGestures.clear(),this.activeGestures=null,this.renderer=null,this.scaleFactor=null,this.isPaused=!1}}class Pn{constructor(){this.colorTransition=null}applyUndertoneModifiers(e,t){return t}applyUndertoneToColor(e,t){if(t&&"object"==typeof t&&void 0!==t.weight){const{weight:i}=t,s=t.type||"clear";if("clear"===s||0===i)return e;const n=this.applyUndertoneSaturation(e,s),a=this.hexToRgb(e),r=this.hexToRgb(n),o=Math.round(a.r+(r.r-a.r)*i),l=Math.round(a.g+(r.g-a.g)*i),h=Math.round(a.b+(r.b-a.b)*i);return this.rgbToHex(o,l,h)}return t&&"clear"!==t?this.applyUndertoneSaturation(e,t):e}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:null}rgbToHsl(e,t,i){e/=255,t/=255,i/=255;const s=Math.max(e,t,i),n=Math.min(e,t,i),a=(s+n)/2;let r,o;if(s===n)r=o=0;else{const l=s-n;switch(o=a>.5?l/(2-s-n):l/(s+n),s){case e:r=((t-i)/l+(t<i?6:0))/6;break;case t:r=((i-e)/l+2)/6;break;case i:r=((e-t)/l+4)/6}}return{h:360*r,s:100*o,l:100*a}}hslToHex(e,t,i){let s,n,a;if(e/=360,i/=100,0==(t/=100))s=n=a=i;else{const r=(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e),o=i<.5?i*(1+t):i+t-i*t,l=2*i-o;s=r(l,o,e+1/3),n=r(l,o,e),a=r(l,o,e-1/3)}const r=e=>{const t=Math.round(255*e).toString(16);return 1===t.length?`0${t}`:t};return`#${r(s)}${r(n)}${r(a)}`}applyUndertoneSaturation(e,t){const i=this.hexToRgb(e),s=this.rgbToHsl(i.r,i.g,i.b),n={intense:1.5,confident:1.3,energetic:1.2,upbeat:1.2,nervous:1.15,mellow:.8,tired:.8,subdued:.5}[t]||1;return s.s=Math.min(100,s.s*n),this.hslToHex(s.h,s.s,s.l)}rgbToHex(e,t,i){const s=e=>{const t=Math.round(e).toString(16);return 1===t.length?`0${t}`:t};return`#${s(e)}${s(t)}${s(i)}`}startColorTransition(e,t,i=1500){this.currentColor===e&&this.currentIntensity===t||(this.colorTransition={active:!0,fromColor:this.currentColor||"#ffffff",toColor:e,fromIntensity:this.currentIntensity||1,toIntensity:t,progress:0,startTime:performance.now(),duration:i})}updateColorTransition(e){if(!this.colorTransition||!this.colorTransition.active)return null;const t=performance.now()-this.colorTransition.startTime,i=Math.min(t/this.colorTransition.duration,1),s=1-Math.pow(1-i,2),n=this.hexToRgb(this.colorTransition.fromColor),a=this.hexToRgb(this.colorTransition.toColor),r=Math.round(n.r+(a.r-n.r)*s),o=Math.round(n.g+(a.g-n.g)*s),l=Math.round(n.b+(a.b-n.b)*s),h=this.rgbToHex(r,o,l),c=this.colorTransition.fromIntensity+(this.colorTransition.toIntensity-this.colorTransition.fromIntensity)*s;return this.currentColor=h,this.currentIntensity=c,i>=1&&(this.colorTransition.active=!1),{color:h,intensity:c}}}class Tn{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvasManager?.canvas||e.canvas,this.recordingActive=!1,this.sleepMode=!1,this.speakingActive=!1,this.speakingRings=[],this.ringSpawnTimer=0,this.ringSpawnInterval=300,this.maxRings=3,this.sleepZ=[],this.sparkles=[],this.chromaticAberration={active:!1,intensity:0,targetIntensity:0,fadeSpeed:.01,maxOffset:30},this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}renderRecordingGlow(e,t,i,s){const{ctx:n}=this,a=2.5*i,r=n.createRadialGradient(e,t,0,e,t,a);r.addColorStop(0,`rgba(255, 0, 0, ${.3*s})`),r.addColorStop(.5,`rgba(255, 0, 0, ${.15*s})`),r.addColorStop(1,"rgba(255, 0, 0, 0)"),n.save(),n.globalCompositeOperation="screen",n.fillStyle=r,n.fillRect(e-a,t-a,2*a,2*a),n.restore()}renderRecordingIndicator(e,t){const i=Date.now()/1e3,s=.8+.2*Math.sin(2*i);this.ctx.save(),this.ctx.translate(e,t),this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=`rgba(255, 0, 0, ${.8*s})`;const n=this.scaleValue(80);this.ctx.font=`italic 900 ${n}px "Poppins", sans-serif`,this.ctx.fillStyle=`rgba(255, 0, 0, ${s})`,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText("REC",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic 900 ${n-1}px "Poppins", sans-serif`,this.ctx.fillStyle=`rgba(255, 255, 255, ${.3*s})`,this.ctx.fillText("REC",-.5,-.5),this.ctx.restore()}renderSleepIndicator(e,t,i){if(this.ringSpawnTimer+=i,this.ringSpawnTimer>=2e3&&this.sleepZ.length<3){const i=["300","500","700","900"],s=i[Math.floor(Math.random()*i.length)],n=Math.random()>.5?"Z":"z";this.sleepZ.push({x:e+Math.random()*this.scaleValue(30)-this.scaleValue(15),y:t+this.scaleValue(80),size:this.scaleValue(3*(24+8*Math.random())),opacity:1,speed:-.025,drift:Math.random()*this.scaleValue(20)-this.scaleValue(10),lifetime:0,rotation:30*Math.random()-15,text:n,weight:s}),this.ringSpawnTimer=0}this.sleepZ=this.sleepZ.filter(e=>{e.lifetime+=i,e.y+=e.speed*i,e.x+=Math.sin(8e-4*e.lifetime)*e.drift*.008,e.rotation+=.01*i;if(e.lifetime<2e3?e.opacity=1:e.lifetime<4e3?e.opacity=1-(e.lifetime-2e3)/2e3:e.opacity=0,e.opacity>.01){this.ctx.save(),this.ctx.translate(e.x,e.y),this.ctx.rotate(e.rotation*Math.PI/180);const t=this.renderer.state.glowColor||"#4a90e2";this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=this.hexToRgba(t,.5*e.opacity);const i=this.ctx.createLinearGradient(-e.size/2,-e.size/2,e.size/2,e.size/2);return i.addColorStop(0,this.hexToRgba(t,e.opacity)),i.addColorStop(.5,this.hexToRgba("#ffffff",.9*e.opacity)),i.addColorStop(1,this.hexToRgba(t,.7*e.opacity)),this.ctx.font=`italic ${e.weight||"900"} ${e.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=i,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(e.text||"Z",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic ${e.weight||"900"} ${.9*e.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=this.hexToRgba("#ffffff",.3*e.opacity),this.ctx.fillText(e.text||"Z",-1,-1),this.ctx.restore(),!0}return!1})}renderSpeakingRings(e,t,i,s){this.ringSpawnTimer+=s,this.ringSpawnTimer>=this.ringSpawnInterval&&this.speakingRings.length<this.maxRings&&(this.speakingRings.push({radius:i,opacity:.8,speed:.15}),this.ringSpawnTimer=0),this.speakingRings=this.speakingRings.filter(n=>(n.radius+=n.speed*s,n.opacity=Math.max(0,.8*(1-(n.radius-i)/(2*i))),n.opacity>.01&&(this.ctx.strokeStyle=this.hexToRgba(this.renderer.state.glowColor,n.opacity),this.ctx.lineWidth=this.scaleValue(2),this.ctx.beginPath(),this.ctx.arc(e,t,n.radius,0,2*Math.PI),this.ctx.stroke(),!0)))}startRecording(){this.recordingActive=!0}stopRecording(){this.recordingActive=!1}enterSleepMode(){this.sleepMode=!0}wakeUp(){this.sleepMode=!1}startSpeaking(){this.speakingActive=!0}stopSpeaking(){this.speakingActive=!1}createSparkle(e,t,i={}){this.sparkles.push({x:e,y:t,vx:i.velocity?.x||0,vy:i.velocity?.y||0,size:i.size||3,color:i.color||"hsl(50, 100%, 70%)",lifetime:i.lifetime||1e3,maxLifetime:i.lifetime||1e3,rotation:Math.random()*Math.PI*2,rotationSpeed:.2*(Math.random()-.5)})}renderSparkles(){const{ctx:e}=this;this.sparkles.forEach(t=>{const i=1-t.lifetime/t.maxLifetime,s=1-i;e.save(),e.translate(t.x,t.y),e.rotate(t.rotation);const n=this.scaleValue(t.size*(1-.5*i));e.beginPath();const a=n,r=.38*n;for(let t=0;t<10;t++){const i=t*Math.PI/5-Math.PI/2,s=t%2==0?a:r;0===t?e.moveTo(Math.cos(i)*s,Math.sin(i)*s):e.lineTo(Math.cos(i)*s,Math.sin(i)*s)}e.closePath(),e.shadowBlur=this.scaleValue(10),e.shadowColor=t.color,e.fillStyle=t.color.replace("70%",70+30*i+"%").replace(")",`, ${s})`).replace("hsl","hsla"),e.fill(),e.restore()})}triggerChromaticAberration(e=.8){this.chromaticAberration.active=!0,this.chromaticAberration.targetIntensity=Math.min(1,e),this.chromaticAberration.intensity=this.chromaticAberration.targetIntensity;const t=document.getElementById("emotive-canvas")||document.querySelector("canvas")||this.canvas;if(t){if(t.style.animation="none",t.offsetHeight,!document.getElementById("chromatic-styles")){const e=document.createElement("style");e.id="chromatic-styles",e.textContent="\n @keyframes chromaticGlitch {\n 0% {\n filter: none;\n transform: translateX(0);\n }\n 15% {\n filter: drop-shadow(-2px 0 0 rgba(255,0,0,0.7)) drop-shadow(2px 0 0 rgba(0,255,255,0.7));\n transform: translateX(-0.5px);\n }\n 30% {\n filter: drop-shadow(-3px 0 0 rgba(255,0,0,0.8)) drop-shadow(3px 0 0 rgba(0,255,255,0.8));\n transform: translateX(0.5px);\n }\n 45% {\n filter: drop-shadow(-2px 0 0 rgba(255,0,0,0.6)) drop-shadow(2px 0 0 rgba(0,255,255,0.6));\n transform: translateX(-0.3px);\n }\n 60% {\n filter: drop-shadow(-1px 0 0 rgba(255,0,0,0.4)) drop-shadow(1px 0 0 rgba(0,255,255,0.4));\n transform: translateX(0.2px);\n }\n 100% {\n filter: none;\n transform: translateX(0);\n }\n }\n ",document.head.appendChild(e)}t.style.animation=`chromaticGlitch ${300+200*e}ms ease-out`}}applyChromaticAberration(e,t){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return;const{intensity:i}=this.chromaticAberration,s=this.scaleValue(this.chromaticAberration.maxOffset*i),n=e.globalCompositeOperation;e.save(),e.clearRect(0,0,e.canvas.width,e.canvas.height),e.globalCompositeOperation="source-over",e.filter="url(#red-channel)",e.drawImage(t,-s,0),e.globalCompositeOperation="screen",e.filter="url(#green-channel)",e.drawImage(t,0,0),e.globalCompositeOperation="screen",e.filter="url(#blue-channel)",e.drawImage(t,s,0),e.filter="none",e.globalCompositeOperation=n,e.restore()}applyChromaticAberrationSimple(e,t,i,s,n){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return void n();const{intensity:a}=this.chromaticAberration,r=this.scaleValue(this.chromaticAberration.maxOffset*a);e.save(),e.globalCompositeOperation="source-over",e.translate(-r,0),e.globalAlpha=.33,e.fillStyle="#ff0000",e.filter="brightness(3)",n(),e.translate(r,0),e.globalCompositeOperation="screen",e.globalAlpha=.33,e.fillStyle="#00ff00",n(),e.translate(r,0),e.globalAlpha=.33,e.fillStyle="#0000ff",n(),e.restore()}update(e){this.sparkles=this.sparkles.filter(t=>(t.x+=t.vx,t.y+=t.vy,t.rotation+=t.rotationSpeed,t.lifetime-=e,t.vy+=.1,t.lifetime>0)),this.chromaticAberration.active&&(this.chromaticAberration.intensity-=this.chromaticAberration.fadeSpeed,this.chromaticAberration.intensity<=0&&(this.chromaticAberration.intensity=0,this.chromaticAberration.active=!1,this.chromaticAberration.targetIntensity=0))}destroy(){this.speakingRings=[],this.sleepZ=[],this.sparkles=[],this.recordingActive=!1,this.sleepMode=!1,this.speakingActive=!1,this.chromaticAberration.active=!1,this.chromaticAberration.intensity=0,this.chromaticAberration.targetIntensity=0,this.ringSpawnTimer=0,this.renderer=null,this.ctx=null,this.canvas=null}}class En{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.blinking=!1,this.blinkingEnabled=!0,this.blinkTimer=0,this.nextBlinkTime=this.getRandomBlinkTime(),this.squintAmount=0,this.eyeClose=null,this.eyeOpen=null,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}update(e){this.blinking&&(this.blinkTimer+=e,this.blinkTimer>=150&&(this.blinking=!1,this.blinkTimer=0,this.nextBlinkTime=Date.now()+this.getRandomBlinkTime())),this.blinkingEnabled&&!this.blinking&&Date.now()>=this.nextBlinkTime&&this.startBlink()}startBlink(){this.blinkingEnabled&&(this.blinking=!0,this.blinkTimer=0)}getRandomBlinkTime(){return 3e3+4e3*Math.random()}getBlinkScale(){if(!this.blinking)return 1;const e=Math.min(this.blinkTimer/150,1);return 1-.7*Math.sin(e*Math.PI)}drawEyes(e,t,i,s,n={}){const{ctx:a}=this,r=n.eyeOpenness||1,o=n.eyeExpression||"neutral";if("neutral"===s||r<=0)return;a.save(),a.strokeStyle="rgba(0, 0, 0, 0.3)",a.lineWidth=this.scaleValue(2),a.lineCap="round";const l=.4*i,h=t-.1*i,c=.25*i;switch(o){case"happy":this.drawHappyEyes(a,e,h,l,c,r);break;case"sad":this.drawSadEyes(a,e,h,l,c,r);break;case"angry":this.drawAngryEyes(a,e,h,l,c,r);break;case"surprised":this.drawSurprisedEyes(a,e,h,l,c,r);break;case"focused":this.drawFocusedEyes(a,e,h,l,c,r);break;case"sleepy":this.drawSleepyEyes(a,e,h,l,c,r);break;case"suspicious":this.drawSuspiciousEyes(a,e,h,l,c,r)}a.restore()}drawHappyEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i,n,.2*Math.PI,.8*Math.PI,!1),e.stroke(),e.beginPath(),e.arc(t+s,i,n,.2*Math.PI,.8*Math.PI,!1),e.stroke()}drawSadEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),e.stroke(),e.beginPath(),e.arc(t+s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),e.stroke()}drawAngryEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i-.3*n),e.lineTo(t-s+.5*n,i+.3*n),e.stroke(),e.beginPath(),e.moveTo(t+s+n,i-.3*n),e.lineTo(t+s-.5*n,i+.3*n),e.stroke()}drawSurprisedEyes(e,t,i,s,n,a){e.beginPath(),e.arc(t-s,i,1.2*n,0,2*Math.PI),e.stroke(),e.beginPath(),e.arc(t+s,i,1.2*n,0,2*Math.PI),e.stroke()}drawFocusedEyes(e,t,i,s,n,a){e.fillStyle="rgba(0, 0, 0, 0.4)",e.beginPath(),e.arc(t-s,i,.3*n,0,2*Math.PI),e.fill(),e.beginPath(),e.arc(t+s,i,.3*n,0,2*Math.PI),e.fill()}drawSleepyEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i),e.lineTo(t-s+n,i),e.stroke(),e.beginPath(),e.moveTo(t+s-n,i),e.lineTo(t+s+n,i),e.stroke()}drawSuspiciousEyes(e,t,i,s,n,a){e.beginPath(),e.moveTo(t-s-n,i),e.lineTo(t-s+.7*n,i),e.stroke(),e.beginPath(),e.arc(t+s,i,.8*n,.1*Math.PI,.9*Math.PI,!1),e.stroke()}setBlinkingEnabled(e){this.blinkingEnabled=e,e||(this.blinking=!1,this.blinkTimer=0)}setSquintAmount(e){this.squintAmount=Math.max(0,Math.min(1,e))}forceBlink(){this.startBlink()}}class An{constructor(e){this.renderer=e,this.breathingSpeed=.42,this.breathingDepth=.08,this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null,this.emotionBreathPatterns={happy:{rate:1.1,depth:1.2},sad:{rate:.8,depth:.7},angry:{rate:1.4,depth:1.3},calm:{rate:.7,depth:.9},excited:{rate:1.5,depth:1.4},focused:{rate:.9,depth:.6},neutral:{rate:1,depth:1},love:{rate:1.2,depth:1.3},surprised:{rate:1.3,depth:1.1},confused:{rate:1.1,depth:.9},amused:{rate:1.2,depth:1.1},bored:{rate:.6,depth:.8},tired:{rate:.5,depth:1.2},anxious:{rate:1.6,depth:.9},determined:{rate:1.1,depth:1},proud:{rate:.9,depth:1.3},content:{rate:.8,depth:1},hopeful:{rate:1,depth:1.1},intrigued:{rate:1.1,depth:.8},embarrassed:{rate:1.3,depth:.7},grateful:{rate:.9,depth:1.1},inspired:{rate:1,depth:1.3},silly:{rate:1.4,depth:1.2},sleepy:{rate:.3,depth:1.4}}}update(e,t,i={}){i=i||{};const s=this.emotionBreathPatterns[t]||{rate:1,depth:1},n=i?.breathRateMult||1,a=i?.breathDepthMult||1;this.breathRate=s.rate*this.breathRateMult*n,this.breathDepth=this.breathingDepth*s.depth*this.breathDepthMult*a;let r=this.breathingSpeed*this.breathRate*(e/1e3);this.breathIrregular&&i?.breathIrregular&&(r*=.8+.4*Math.sin(3e-4*Date.now())),this.breathingPhase+=r,this.breathingPhase>2*Math.PI&&(this.breathingPhase-=2*Math.PI)}getBreathingScale(){return null!==this.customScale?this.customScale:1+Math.sin(this.breathingPhase)*this.breathDepth}setCustomScale(e){this.customScale=e}setBreathingSpeed(e){this.breathingSpeed=e}setBreathingDepth(e){this.breathingDepth=Math.max(0,Math.min(1,e))}setBreathRateMultiplier(e){this.breathRateMult=e}setBreathDepthMultiplier(e){this.breathDepthMult=e}setIrregularBreathing(e){this.breathIrregular=e}reset(){this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null}holdBreath(e=!1){this.customScale=e?.92:1.08}releaseBreath(){this.customScale=null}getBreathingInfo(){return{phase:this.breathingPhase,rate:this.breathRate,depth:this.breathDepth,scale:this.getBreathingScale(),isCustom:null!==this.customScale,isIrregular:this.breathIrregular}}}class Dn{constructor(){this.cache=new Map,this.stats={hits:0,misses:0,evictions:0},this.maxSize=100,this.ttl=6e4,this.accessOrder=[],this.cleanupInterval=setInterval(()=>{this.clearExpired()},6e4)}generateKey(e,t){if("radial"===e){const{x0:e,y0:i,r0:s,x1:n,y1:a,r1:r,stops:o}=t;return`radial:${e},${i},${s},${n},${a},${r}:${o.map(e=>`${e.offset}:${e.color}`).join("|")}`}if("linear"===e){const{x0:e,y0:i,x1:s,y1:n,stops:a}=t;return`linear:${e},${i},${s},${n}:${a.map(e=>`${e.offset}:${e.color}`).join("|")}`}return null}getRadialGradient(e,t,i,s,n,a,r,o){const l=this.generateKey("radial",{x0:t,y0:i,r0:s,x1:n,y1:a,r1:r,stops:o}),h=this.cache.get(l);if(h&&Date.now()-h.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(l),h.gradient;this.stats.misses++;const c=e.createRadialGradient(t,i,s,n,a,r);return o.forEach(e=>{c.addColorStop(e.offset,e.color)}),this.set(l,c),c}getLinearGradient(e,t,i,s,n,a){const r=this.generateKey("linear",{x0:t,y0:i,x1:s,y1:n,stops:a}),o=this.cache.get(r);if(o&&Date.now()-o.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(r),o.gradient;this.stats.misses++;const l=e.createLinearGradient(t,i,s,n);return a.forEach(e=>{l.addColorStop(e.offset,e.color)}),this.set(r,l),l}set(e,t){this.cache.size>=this.maxSize&&!this.cache.has(e)&&this.evictLRU(),this.cache.set(e,{gradient:t,timestamp:Date.now()}),this.updateAccessOrder(e)}updateAccessOrder(e){const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1),this.accessOrder.push(e)}evictLRU(){if(this.accessOrder.length>0){const e=this.accessOrder.shift();this.cache.delete(e),this.stats.evictions++}}clear(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.cache.clear(),this.accessOrder=[]}clearExpired(){const e=Date.now(),t=[];for(const[i,s]of this.cache.entries())e-s.timestamp>=this.ttl&&t.push(i);t.forEach(e=>{this.cache.delete(e);const t=this.accessOrder.indexOf(e);t>-1&&this.accessOrder.splice(t,1)})}destroy(){this.clear()}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return{size:this.cache.size,maxSize:this.maxSize,hits:this.stats.hits,misses:this.stats.misses,evictions:this.stats.evictions,hitRate:`${e}%`}}createHelper(e){return{radial:(t,i,s,n,a,r,o)=>this.getRadialGradient(e,t,i,s,n,a,r,o),linear:(t,i,s,n,a)=>this.getLinearGradient(e,t,i,s,n,a)}}}const _n=new Dn;class In{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.glowIntensity=1,this.glowColor="#4a90e2",this.targetGlowColor="#4a90e2",this.glowColorTransition=0,this.glowColorTransitionSpeed=.05,this.offscreenCanvas=null,this.offscreenCtx=null,this.cachedGlowColor=null,this.cachedGlowRadius=0,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i),this.initOffscreenCanvas()}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d")}updateOffscreenSize(e){this.offscreenCanvas.width===e&&this.offscreenCanvas.height===e||(this.offscreenCanvas.width=e,this.offscreenCanvas.height=e,this.cachedGlowColor=null)}renderGlow(e,t,i,s={}){const{ctx:n}=this,a=s.color||this.glowColor,r=void 0!==s.intensity?s.intensity:this.glowIntensity;r<.01||this.renderGlowDirect(n,e,t,i,a,r)}cacheGlowGradient(e,t){const i=this.offscreenCtx,s=t;this.updateOffscreenSize(2*t),i.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height);const n=_n.getRadialGradient(i,s,s,0,s,s,t,[{offset:0,color:this.hexToRgba(e,.4)},{offset:.3,color:this.hexToRgba(e,.2)},{offset:.6,color:this.hexToRgba(e,.1)},{offset:1,color:this.hexToRgba(e,0)}]);i.fillStyle=n,i.fillRect(0,0,2*t,2*t),this.cachedGlowColor=e,this.cachedGlowRadius=t}renderGlowDirect(e,t,i,s,n,a){e.save(),e.globalCompositeOperation="screen";const r=[];for(let e=0;e<=20;e++){const t=e/20,i=.6*Math.pow(1-t,2.2),s=Math.max(0,Math.min(1,i*a));r.push({offset:t,color:this.hexToRgba(n,s)})}const o=_n.getRadialGradient(e,t,i,0,t,i,s,r);e.fillStyle=o,e.beginPath(),e.arc(t,i,s,0,2*Math.PI),e.fill(),e.restore()}renderRecordingGlow(e,t,i,s){const{ctx:n}=this,a=2.5*i,r=_n.getRadialGradient(n,e,t,0,e,t,a,[{offset:0,color:`rgba(255, 0, 0, ${.3*s})`},{offset:.5,color:`rgba(255, 0, 0, ${.15*s})`},{offset:1,color:"rgba(255, 0, 0, 0)"}]);n.save(),n.globalCompositeOperation="screen",n.fillStyle=r,n.fillRect(e-a,t-a,2*a,2*a),n.restore()}updateGlowColor(e,t){this.targetGlowColor!==e&&(this.targetGlowColor=e,this.glowColorTransition=0),this.glowColorTransition<1&&(this.glowColorTransition=Math.min(1,this.glowColorTransition+this.glowColorTransitionSpeed),this.glowColor=this.lerpColor(this.glowColor,this.targetGlowColor,this.glowColorTransition))}lerpColor(e,t,i){const s=this.hexToRgb(e),n=this.hexToRgb(t);return`#${((1<<24)+(Math.round(s.r+(n.r-s.r)*i)<<16)+(Math.round(s.g+(n.g-s.g)*i)<<8)+Math.round(s.b+(n.b-s.b)*i)).toString(16).slice(1)}`}hexToRgb(e){const t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);return t?{r:parseInt(t[1],16),g:parseInt(t[2],16),b:parseInt(t[3],16)}:{r:0,g:0,b:0}}setGlowIntensity(e){this.glowIntensity=Math.max(0,Math.min(1,e))}setGlowColor(e){this.glowColor=e,this.targetGlowColor=e,this.glowColorTransition=1}destroy(){this.offscreenCanvas&&(this.offscreenCtx&&(this.offscreenCtx.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),this.offscreenCtx=null),this.offscreenCanvas.width=0,this.offscreenCanvas.height=0,this.offscreenCanvas=null),this.cachedGlowColor=null,this.cachedGlowRadius=0}}class Rn{constructor(e){this.renderer=e,this.ctx=e.ctx,this.canvas=e.canvas,this.coreColor="#FFFFFF",this.coreOpacity=1,this.coreBorderWidth=0,this.coreBorderColor=null,this.shapePoints=null,this.isMorphing=!1,this.scaleValue=t=>e.scaleValue(t),this.hexToRgba=(t,i)=>e.hexToRgba(t,i)}renderCore(e,t,i,s={}){const{ctx:n}=this,a=s.scaleX||1,r=s.scaleY||1,o=s.rotation||0,l=void 0!==s.opacity?s.opacity:this.coreOpacity,h=s.color||this.coreColor,c=s.shapePoints||this.shapePoints;n.save(),n.translate(e,t),0!==o&&n.rotate(o),n.scale(a,r),n.fillStyle=this.hexToRgba(h,l),c&&c.length>0?this.drawMorphedShape(n,c,i):this.drawCircle(n,i),this.coreBorderWidth>0&&this.coreBorderColor&&(n.strokeStyle=this.coreBorderColor,n.lineWidth=this.scaleValue(this.coreBorderWidth),n.stroke()),n.restore()}drawDropShadow(e,t,i){e.save();const s=this.scaleValue(2);if(e.translate(0,s),i&&i.length>32)e.fillStyle="rgba(0, 0, 0, 0.15)",e.beginPath(),e.arc(0,0,1.05*t,0,2*Math.PI),e.fill();else{const s=_n.getRadialGradient(e,0,0,.7*t,0,0,1.2*t,[{offset:0,color:"rgba(0, 0, 0, 0.2)"},{offset:.8,color:"rgba(0, 0, 0, 0.1)"},{offset:1,color:"rgba(0, 0, 0, 0)"}]);if(e.fillStyle=s,e.beginPath(),i){const t=1.1,s=i.length>20?2:1;e.moveTo(i[0].x*t,i[0].y*t);for(let n=s;n<i.length;n+=s)e.lineTo(i[n].x*t,i[n].y*t);e.closePath()}else e.arc(0,0,1.1*t,0,2*Math.PI);e.fill()}e.restore()}drawCircle(e,t){e.beginPath(),e.arc(0,0,t,0,2*Math.PI),e.fill()}drawMorphedShape(e,t,i){!t||t.length<3?this.drawCircle(e,i):(e.beginPath(),t.forEach((t,i)=>{0===i?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath(),e.fill())}renderSleepyCore(e,t,i){const{ctx:s}=this;s.save(),s.translate(e,t),s.scale(1,.85),s.fillStyle="#FFFFFF",s.beginPath(),s.arc(0,0,i,0,2*Math.PI),s.fill(),s.restore()}renderGlitchedCore(e,t,i,s){const{ctx:n}=this;n.save(),[{x:-2,y:0,alpha:.3},{x:2,y:0,alpha:.3},{x:0,y:-1,alpha:.2}].forEach(a=>{n.fillStyle=this.hexToRgba("#FFFFFF",a.alpha*s),n.beginPath(),n.arc(e+a.x*s*this.scaleValue(5),t+a.y*s*this.scaleValue(5),i,0,2*Math.PI),n.fill()}),n.fillStyle="#FFFFFF",n.beginPath(),n.arc(e,t,i,0,2*Math.PI),n.fill(),n.restore()}setShapePoints(e){this.shapePoints=e,this.isMorphing=e&&e.length>0}clearShapePoints(){this.shapePoints=null,this.isMorphing=!1}setCoreColor(e){this.coreColor=e}setCoreOpacity(e){this.coreOpacity=Math.max(0,Math.min(1,e))}setCoreBorder(e,t){this.coreBorderWidth=e,this.coreBorderColor=t}getCoreInfo(){return{color:this.coreColor,opacity:this.coreOpacity,hasBorder:this.coreBorderWidth>0,isMorphing:this.isMorphing,shapePointCount:this.shapePoints?this.shapePoints.length:0}}}class Bn{renderSunEffects(e,t,i,s,n){const a=Date.now()/100;if(e.save(),e.translate(t,i),n.texture&&(void 0===n.textureOpacity||n.textureOpacity>0)){e.save(),e.globalCompositeOperation="screen",e.globalAlpha=void 0!==n.textureOpacity?n.textureOpacity:1;const t=.05*a*(n.turbulence||.3)/.3,i=e.createRadialGradient(Math.sin(t)*s*.15,Math.cos(.7*t)*s*.15,.2*s,0,0,s);i.addColorStop(0,"rgba(255, 255, 200, 0)"),i.addColorStop(.4,"rgba(255, 200, 100, 0.1)"),i.addColorStop(.7,"rgba(255, 150, 50, 0.08)"),i.addColorStop(1,"rgba(255, 100, 30, 0.05)"),e.fillStyle=i,e.beginPath(),e.arc(0,0,s,0,2*Math.PI),e.fill(),e.restore()}const r=void 0!==n.coronaOpacity?n.coronaOpacity:1;if(r>0){e.save(),e.globalCompositeOperation="screen";const t=e.createRadialGradient(0,0,.5*s,0,0,1.1*s);t.addColorStop(0,`rgba(255, 255, 255, ${.8*r})`),t.addColorStop(.3,`rgba(255, 250, 200, ${.6*r})`),t.addColorStop(.5,`rgba(255, 200, 100, ${.4*r})`),t.addColorStop(.7,`rgba(255, 150, 50, ${.2*r})`),t.addColorStop(1,"rgba(255, 100, 20, 0)"),e.fillStyle=t,e.beginPath(),e.arc(0,0,1.1*s,0,2*Math.PI),e.fill();for(let t=0;t<2;t++){const i=1.3+.4*t,n=(.35-.15*t)*r,o=.05*Math.sin(.1*a+t),l=e.createRadialGradient(0,0,s*(.9+o),0,0,s*(i+o));l.addColorStop(0,"rgba(255, 255, 200, 0)"),l.addColorStop(.4,`rgba(255, 200, 100, ${.5*n})`),l.addColorStop(.7,`rgba(255, 150, 50, ${n})`),l.addColorStop(.9,`rgba(255, 100, 30, ${.5*n})`),l.addColorStop(1,"rgba(255, 50, 10, 0)"),e.fillStyle=l,e.beginPath(),e.arc(0,0,s*(i+o),0,2*Math.PI),e.fill()}e.restore()}if(n.flares){e.save();const t=Math.sin(.08*a),i=Math.sin(.12*a),n=Math.sin(.16*a),r=e.createLinearGradient(0,-s,0,3*-s);r.addColorStop(0,"rgba(255, 255, 230, 0.4)"),r.addColorStop(.2,"rgba(255, 220, 150, 0.25)"),r.addColorStop(.5,"rgba(255, 180, 80, 0.15)"),r.addColorStop(.8,"rgba(255, 120, 40, 0.08)"),r.addColorStop(1,"rgba(255, 60, 20, 0)"),e.fillStyle=r,e.globalCompositeOperation="screen",e.beginPath();const o=(t,i,n,a)=>{const r=Math.cos(t),o=Math.sin(t),l=r*s,h=o*s,c=r*(s+i),u=o*(s+i),d=-o*n*.5,g=r*n*.5,m=a*n*.3;e.moveTo(l-d,h-g),e.quadraticCurveTo(.5*(l+c)+d*m,.5*(h+u)+g*m,c,u),e.quadraticCurveTo(.5*(l+c)-d*m,.5*(h+u)-g*m,l+d,h+g)};for(let e=0;e<8;e++)o(e/8*Math.PI*2+.1*t,s*(1.8+.4*Math.sin(.1*a+.5*e)),.18*s,Math.sin(.15*a+e));for(let e=0;e<12;e++)o((e+.5)/12*Math.PI*2+.08*i,s*(1.2+.3*Math.sin(.13*a+.7*e)),.12*s,Math.sin(.18*a+1.2*e));for(let e=0;e<15;e++)o(e/15*Math.PI*2+.05*n,s*(.7+.25*Math.sin(.17*a+.9*e)),.08*s,Math.sin(.2*a+1.5*e));for(let t=0;t<15;t++){const i=(t+.25)/15*Math.PI*2,n=s*(.4+.2*Math.sin(.22*a+t)),r=.06*s,o=Math.cos(i),l=Math.sin(i),h=o*s,c=l*s,u=o*(s+n),d=l*(s+n),g=-l*r*.5,m=o*r*.5;e.moveTo(h-g,c-m),e.lineTo(u,d),e.lineTo(h+g,c+m)}e.fill(),e.restore()}const o=e.createRadialGradient(0,0,.95*s,0,0,1.05*s);o.addColorStop(0,"rgba(255, 255, 255, 0)"),o.addColorStop(.7,"rgba(255, 255, 200, 0.2)"),o.addColorStop(.9,"rgba(255, 200, 100, 0.5)"),o.addColorStop(1,"rgba(255, 150, 50, 0.3)"),e.fillStyle=o,e.beginPath(),e.arc(0,0,1.05*s,0,2*Math.PI),e.fill(),e.restore()}renderBaileysBeads(e,t,i,s,n,a,r,o,l,h=e=>e){if(!l)return void(this._beadStartTime=null);const c=Math.abs(n)<1&&Math.abs(a)<1,u=o?30:15;if(!(Math.abs(n)<u&&Math.abs(a)<u||c))return void(this._beadStartTime=null);if(!this._beadStartTime){const e=Math.floor(4*Math.random())+1;this._currentBeads=[];const t=[];for(let i=0;i<e;i++)t.push(Math.random()*Math.PI*2);const i=Array.from({length:e},(e,t)=>t);for(let e=i.length-1;e>0;e--){const t=Math.floor(Math.random()*(e+1));[i[e],i[t]]=[i[t],i[e]]}for(let s=0;s<e;s++)this._currentBeads.push({angle:t[s],size:3+5*Math.random(),order:i[s],delay:200*i[s]});this._beadStartTime=Date.now()}const d=Date.now()-this._beadStartTime;(this._currentBeads||[]).forEach(n=>{if(d<n.delay)return;const a=d-n.delay,r=Math.min(1,a/300),o=t+Math.cos(n.angle)*s,l=i+Math.sin(n.angle)*s;e.save(),e.translate(o,l),e.globalAlpha=r;const c=h(n.size),u=[{color:`rgba(255, 100, 100, ${.6*r})`,offset:-2},{color:`rgba(100, 255, 100, ${.6*r})`,offset:0},{color:`rgba(100, 100, 255, ${.6*r})`,offset:2}];e.globalCompositeOperation="screen",u.forEach(({color:t,offset:i})=>{const s=e.createRadialGradient(i,i,0,i,i,2*c);s.addColorStop(0,t),s.addColorStop(.2,t.replace(""+.6*r,""+.4*r)),s.addColorStop(.5,t.replace(""+.6*r,""+.2*r)),s.addColorStop(1,"rgba(255, 255, 255, 0)"),e.fillStyle=s,e.beginPath(),e.arc(i,i,2*c,0,2*Math.PI),e.fill()}),e.globalCompositeOperation="lighter";const g=e.createRadialGradient(0,0,0,0,0,c);g.addColorStop(0,`rgba(255, 255, 255, ${r})`),g.addColorStop(.3,`rgba(255, 255, 255, ${.5*r})`),g.addColorStop(1,"rgba(255, 255, 255, 0)"),e.fillStyle=g,e.beginPath(),e.arc(0,0,c,0,2*Math.PI),e.fill(),e.restore()})}renderMoonShadow(e,t,i,s,n,a,r=!1,o=0,l=null){if(e.save(),e.globalAlpha=1,e.translate(t,i),"crescent"===n.type){let t=1,i=n.offset||.7;if(l){const e=l.getProgress(),{targetShape:s}=l;"moon"===s&&void 0!==e&&e<1&&!n.shadowX&&(t=e,i=2.7*t-2)}const r=(n.angle||-30)*Math.PI/180,o=Math.cos(r)*s*i,h=Math.sin(r)*s*i;if(e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.beginPath(),a&&a.length>0){e.moveTo(a[0].x,a[0].y);for(let t=1;t<a.length;t++)e.lineTo(a[t].x,a[t].y);e.closePath()}else e.arc(0,0,s,0,2*Math.PI);e.clip();const c=e.createRadialGradient(o,h,.9*s,o,h,1.1*s),u=void 0!==n.coverage?n.coverage:.85,d=Math.min(1,1.2*t)*(u/.85);c.addColorStop(0,`rgba(0, 0, 0, ${1*d})`),c.addColorStop(.8,`rgba(0, 0, 0, ${1*d})`),c.addColorStop(.88,`rgba(0, 0, 0, ${.98*d})`),c.addColorStop(.91,`rgba(0, 0, 0, ${.95*d})`),c.addColorStop(.93,`rgba(0, 0, 0, ${.9*d})`),c.addColorStop(.95,`rgba(0, 0, 0, ${.8*d})`),c.addColorStop(.96,`rgba(0, 0, 0, ${.65*d})`),c.addColorStop(.97,`rgba(0, 0, 0, ${.45*d})`),c.addColorStop(.98,`rgba(0, 0, 0, ${.25*d})`),c.addColorStop(.99,`rgba(0, 0, 0, ${.1*d})`),c.addColorStop(1,"rgba(0, 0, 0, 0)"),e.fillStyle=c,e.beginPath(),e.arc(o,h,1.1*s,0,2*Math.PI),e.fill()}else if("lunar"===n.type){const t=1-(void 0!==n.diffusion?n.diffusion:1);let i=0,a=0;if(l){const e=l.getProgress(),{currentShape:t,targetShape:n}=l;if(r&&"solar"===n&&void 0!==e&&e<1){const t=2.5*s;i=-t*(1-e),a=t*(1-e)}else if(r&&"solar"===t&&"solar"!==n&&null!==n&&void 0!==e&&e<1){const t=2.5*s;i=t*e,a=-t*e}}e.translate(i,a),r?(e.save(),e.beginPath(),e.arc(-i,-a,s,0,2*Math.PI),e.clip()):(e.beginPath(),e.arc(0,0,s,0,2*Math.PI),e.clip());const o=s*(1.8-.5*t),h=e.createRadialGradient(0,0,.2*s,0,0,o),c=n.coverage||.9;if(n.color&&n.color.includes("0, 0, 0")?(h.addColorStop(0,`rgba(0, 0, 0, ${c})`),h.addColorStop(.3+.2*t,`rgba(0, 0, 0, ${.95*c})`),h.addColorStop(.6+.2*t,`rgba(0, 0, 0, ${.8*c})`),h.addColorStop(.85,`rgba(0, 0, 0, ${.4*c})`),h.addColorStop(1,"rgba(0, 0, 0, 0)")):(h.addColorStop(0,`rgba(10, 2, 0, ${c})`),h.addColorStop(.3+.2*t,`rgba(20, 5, 0, ${.95*c})`),h.addColorStop(.6+.2*t,`rgba(40, 10, 5, ${.8*c})`),h.addColorStop(.85,`rgba(60, 15, 10, ${.4*c})`),h.addColorStop(1,"rgba(80, 20, 15, 0)")),e.fillStyle=h,e.beginPath(),e.arc(0,0,o,0,2*Math.PI),e.fill(),t>.3){const i=s*(.8+.3*t),a=e.createRadialGradient(0,0,0,0,0,i);n.color&&n.color.includes("0, 0, 0")?(a.addColorStop(0,`rgba(0, 0, 0, ${c})`),a.addColorStop(.5,`rgba(0, 0, 0, ${.9*c})`),a.addColorStop(.8,`rgba(0, 0, 0, ${.5*c})`),a.addColorStop(1,"rgba(0, 0, 0, 0)")):(a.addColorStop(0,`rgba(0, 0, 0, ${c})`),a.addColorStop(.5,`rgba(10, 2, 0, ${.9*c})`),a.addColorStop(.8,`rgba(20, 5, 0, ${.5*c})`),a.addColorStop(1,"rgba(30, 8, 5, 0)")),e.fillStyle=a,e.beginPath(),e.arc(0,0,i,0,2*Math.PI),e.fill()}}r&&e.restore(),e.restore()}}class zn{constructor(e){this.renderer=e,this.episodicEffects={nervous:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:3e3+2e3*Math.random()},confident:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:4e3+2e3*Math.random()},tired:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:5e3+2e3*Math.random()},intense:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:3e3+3e3*Math.random()},subdued:{active:!1,startTime:0,duration:0,intensity:0,nextTrigger:4e3+3e3*Math.random()}}}getEpisodicEffects(){return this.episodicEffects}updateEpisodicEffects(e,t,i,s,n){if(!e||!this.episodicEffects[e])return{jitterX:t,jitterY:i,coreRadius:s,glowRadius:n};const a=this.episodicEffects[e],r=performance.now();if(!a.active&&r>=a.nextTrigger)switch(a.active=!0,a.startTime=r,e){case"nervous":a.duration=500+500*Math.random(),a.intensity=2+Math.random(),a.nextTrigger=r+3e3+2e3*Math.random();break;case"confident":a.duration=1e3+1e3*Math.random(),a.intensity=.15,a.nextTrigger=r+4e3+2e3*Math.random();break;case"tired":a.duration=1e3+2e3*Math.random(),a.intensity=.2,a.nextTrigger=r+5e3+2e3*Math.random();break;case"intense":a.duration=500+500*Math.random(),a.intensity=.5,a.nextTrigger=r+3e3+3e3*Math.random();break;case"subdued":a.duration=2e3+1e3*Math.random(),a.intensity=.3,a.nextTrigger=r+4e3+3e3*Math.random()}if(a.active){const o=r-a.startTime;if(o<a.duration){const r=o/a.duration;switch(e){case"nervous":{const e=1-r,s=15,n=Math.sin(r*Math.PI*s)*e;t=n*a.intensity,i=n*a.intensity*.7;break}case"confident":{const e=Math.sin(r*Math.PI);s*=1+a.intensity*e,n*=1+.5*a.intensity*e;break}case"tired":{const e=Math.sin(r*Math.PI*.5);s*=1-a.intensity*e,i+=5*e;break}case"intense":{const e=1-Math.cos(r*Math.PI);s*=1-.05*e,n*=1+a.intensity*e;break}case"subdued":{const e=Math.sin(r*Math.PI*.5);s*=1-.1*e,n*=1-a.intensity*e;break}}}else a.active=!1}return{jitterX:t,jitterY:i,coreRadius:s,glowRadius:n}}reset(){Object.keys(this.episodicEffects).forEach(e=>{this.episodicEffects[e].active=!1,this.episodicEffects[e].startTime=0,this.episodicEffects[e].duration=0,this.episodicEffects[e].intensity=0})}getEpisodeState(e){return this.episodicEffects[e]||null}isEpisodeActive(e){const t=this.episodicEffects[e];return!!t&&t.active}}class Fn{constructor(e){this.renderer=e,this.brakeStartTime=null,this.brakeDuration=2500,this.brakeStartRotation=0,this.brakeTargetRotation=0,this.brakeStartVelocity=0,this.onComplete=null,this.onProgress=null,this.DURATION_FACTOR=14}brakeToUpright(e={}){return this.brakeToTarget(0,e)}brakeToNearest(e,t={}){const i=this.renderer.state.manualRotation||0,s=Math.round(i/e)*e;return this.brakeToTarget(s,t)}brakeToTarget(e,t={}){return new Promise(i=>{const{onProgress:s=null,onComplete:n=null}=t;this.onProgress=s,this.onComplete=n;const a=this.renderer.state.rotationSpeed||0,r=this.renderer.state.manualRotation||0;if(0===a||this.brakeStartTime)return void i();if(this.brakeStartTime=performance.now(),this.brakeStartRotation=r,this.brakeStartVelocity=a,0===e)this.brakeTargetRotation=a>0?360*(Math.floor(r/360)+1):360*Math.floor(r/360);else{const t=e%360,i=Math.floor(r/360);this.brakeTargetRotation=a>0?t>r%360?360*i+t:360*(i+1)+t:t<r%360?360*i+t:360*(i-1)+t}const o=Math.abs(this.brakeTargetRotation-this.brakeStartRotation);this.brakeDuration=Math.max(500,o/Math.abs(a)*this.DURATION_FACTOR*5),this.renderer.setRotationSpeed(0),this.resolvePromise=i})}updateBrake(e){if(!this.brakeStartTime)return null;const t=e-this.brakeStartTime,i=Math.min(t/this.brakeDuration,1),s=1-Math.pow(1-i,4),n=this.brakeStartRotation+(this.brakeTargetRotation-this.brakeStartRotation)*s,a=this.brakeStartVelocity*Math.pow(1-s,2);return this.onProgress&&this.onProgress(s,a,n),i>=1?(this.brakeStartTime=null,this.complete(),{rotation:this.brakeTargetRotation,speed:0,complete:!0}):{rotation:n,speed:a,complete:!1}}stop(){this.brakeStartTime=null}complete(){this.onComplete&&this.onComplete(),this.resolvePromise&&(this.resolvePromise(),this.resolvePromise=null)}isBraking(){return null!==this.brakeStartTime}emergencyStop(){this.stop(),this.renderer.setRotationSpeed(0),this.complete()}getProgress(){if(!this.brakeStartTime)return 0;const e=performance.now()-this.brakeStartTime;return Math.min(e/this.brakeDuration,1)}destroy(){this.stop(),this.onComplete=null,this.onProgress=null,this.resolvePromise=null,this.renderer=null,this.brakeStartTime=null,this.brakeStartRotation=0,this.brakeTargetRotation=0,this.brakeStartVelocity=0}}class On{constructor(e){this.renderer=e,this.rotationBrake=new Fn(e)}setRotationSpeed(e){this.renderer.state.rotationSpeed=e}setRotationAngle(e){this.renderer.state.manualRotation=e}getRotationAngle(){return this.renderer.state.manualRotation}getRotationSpeed(){return this.renderer.state.rotationSpeed}isBraking(){return this.rotationBrake&&this.rotationBrake.isBraking()}updateRotation(e){if(this.rotationBrake&&this.rotationBrake.isBraking()){const t=this.rotationBrake.updateBrake(e);t&&(this.renderer.state.manualRotation=t.rotation,this.renderer.state.rotationSpeed=t.complete?0:t.speed)}else 0!==this.renderer.state.rotationSpeed&&(this.renderer.state.manualRotation+=this.renderer.state.rotationSpeed);this.renderer.state.lastRotationUpdate=e}calculateTotalRotation(e=0,t=0){return(e+t+this.renderer.state.manualRotation)*Math.PI/180}applyRotation(e,t){0!==t&&e.rotate(t)}applyRotationTransform(e,t,i,s){this.updateRotation(performance.now());const n=this.calculateTotalRotation(s);return 0!==n&&(e.save(),e.translate(t,i),this.applyRotation(e,n),e.translate(-t,-i)),n}reset(){this.renderer.state.manualRotation=0,this.renderer.state.rotationSpeed=0,this.renderer.state.lastRotationUpdate=performance.now()}destroy(){this.rotationBrake&&(this.rotationBrake=null)}}let Ln=class{constructor(e){this.renderer=e,this.canvas=e.canvas,this.initialized=!1,this.handleMouseMove=null,this.handleTouchMove=null}setEnabled(e){this.renderer.state.gazeTrackingEnabled=e,e?this.initialized||this.initialize():this.renderer.state.gazeTarget={x:0,y:0}}initialize(){this.initialized||(this.handleMouseMove=e=>{if(!this.renderer.state.gazeTrackingEnabled)return;const t=this.canvas.getBoundingClientRect(),i=t.width/2,s=t.height/2,n=e.clientX-t.left-i,a=e.clientY-t.top-s;this.renderer.state.gazeTarget={x:n/i,y:a/s}},this.handleTouchMove=e=>{if(this.renderer.state.gazeTrackingEnabled&&e.touches.length>0){const t=e.touches[0],i=this.canvas.getBoundingClientRect(),s=i.width/2,n=i.height/2,a=t.clientX-i.left-s,r=t.clientY-i.top-n;this.renderer.state.gazeTarget={x:a/s,y:r/n}}},document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),this.initialized=!0)}cleanup(){this.initialized&&(this.handleMouseMove&&(document.removeEventListener("mousemove",this.handleMouseMove),this.handleMouseMove=null),this.handleTouchMove&&(document.removeEventListener("touchmove",this.handleTouchMove),this.handleTouchMove=null),this.initialized=!1)}isInitialized(){return this.initialized}getGazeTarget(){return this.renderer.state.gazeTarget}isEnabled(){return this.renderer.state.gazeTrackingEnabled}};class qn{constructor(e){this.renderer=e}setupCanvas(){this.renderer.updateOffscreenSize();const e=this.renderer.canvasManager.width||this.renderer.canvas.width||400,t=this.renderer.canvasManager.height||this.renderer.canvas.height||400,i=this.renderer.ctx;return this.renderer.ctx=this.renderer.offscreenCtx,{logicalWidth:e,logicalHeight:t,originalCtx:i}}renderBackdrop(e,t,i,s){const n=Math.min(e,t),a=this.renderer.getEffectiveCenter(),r=a.x,o=a.y-this.renderer.config.topOffset,l=n/this.renderer.config.referenceSize*this.renderer.config.baseScale*(a.coreScale||a.scale),h=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*l;this.renderer.backdropRenderer.update(s),this.renderer.audioAnalyzer&&this.renderer.audioAnalyzer.currentAmplitude&&this.renderer.backdropRenderer.setAudioIntensity(this.renderer.audioAnalyzer.currentAmplitude),this.renderer.backdropRenderer.render(r,o,h,i)}applyCanvasDecay(e,t,i){const s=this.renderer.particleSystem?this.renderer.particleSystem.particles.length:0,n=.12+Math.min(.08,.003*s);e.save(),e.globalCompositeOperation="destination-out",e.fillStyle=`rgba(0, 0, 0, ${n})`,e.fillRect(0,0,t,i),e.restore()}clearOffscreenCanvas(e,t){this.renderer.ctx.clearRect(0,0,e,t)}performCanvasSetup(e,t,i,s){this.renderBackdrop(e,t,i,s),this.applyCanvasDecay(i,e,t),this.clearOffscreenCanvas(e,t)}}class Gn{constructor(e){this.renderer=e}markFrameStart(){return this.renderer.performanceMonitor&&this.renderer.performanceMonitor.markFrameStart(),performance.now()}handleCleanRender(){this.renderer.forceCleanRender&&(this.renderer.forceCleanRender=!1,this.renderer.canvas&&this.renderer.ctx&&this.renderer.ctx.clearRect(0,0,this.renderer.canvas.width,this.renderer.canvas.height))}initializeFrame(){const e=this.markFrameStart();return this.handleCleanRender(),e}}class Hn{constructor(e){this.renderer=e}mergeTransforms(e,t){const i=this.renderer.ambientDanceAnimator.getTransform(t);return e?(e.x=(e.x||0)+(i.x||0),e.y=(e.y||0)+(i.y||0),e.rotation=(e.rotation||0)+(i.rotation||0),e.scale=(e.scale||1)*(i.scale||1),e):i}mergeAndStoreTransforms(e,t){const i=this.mergeTransforms(e,t);return this.renderer.gestureTransform=i,i}}class jn{constructor(e){this.renderer=e}updateUndertoneModifiers(){if(this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers){const e=this.renderer.stateMachine.getWeightedUndertoneModifiers();e?this.renderer.applyUndertoneModifiers(e):this.renderer.applyUndertoneModifiers(null)}}updateColorTransition(e){this.renderer.colorTransition&&this.renderer.colorTransition.active&&this.renderer.updateColorTransition(e)}updateAnimationTimers(e){this.renderer.updateTimers(e)}updateGazeOffset(){if(this.renderer.state.gazeTrackingEnabled){const e=.15,t=50;this.renderer.state.gazeOffset.x+=(this.renderer.state.gazeTarget.x*t-this.renderer.state.gazeOffset.x)*e,this.renderer.state.gazeOffset.y+=(this.renderer.state.gazeTarget.y*t-this.renderer.state.gazeOffset.y)*e}else{const e=.1;this.renderer.state.gazeOffset.x+=(0-this.renderer.state.gazeOffset.x)*e,this.renderer.state.gazeOffset.y+=(0-this.renderer.state.gazeOffset.y)*e}}performFrameStateUpdates(e){this.updateUndertoneModifiers(),this.updateColorTransition(e),this.updateAnimationTimers(e),this.updateGazeOffset()}}class $n{constructor(e){this.renderer=e}calculateBaseDimensions(e,t){const i=Math.min(e,t),s=this.renderer.getEffectiveCenter();return this.renderer.scaleFactor=i/this.renderer.config.referenceSize*this.renderer.config.baseScale*(s.coreScale||s.scale),this.renderer.particleScaleFactor=i/this.renderer.config.referenceSize*this.renderer.config.baseScale*(s.particleScale||s.scale),{canvasSize:i,effectiveCenter:s}}calculateCenterPosition(e,t,i){const s=e.x;let n=e.y-this.renderer.config.topOffset;return t.properties&&t.properties.verticalOffset&&(n=e.y-this.renderer.config.topOffset+i*t.properties.verticalOffset),{centerX:s,centerY:n}}applyGestureTransform(e,t,i){let s=1,n=0,a=1;return i&&(e+=i.x||0,t+=i.y||0,s=i.scale||1,n=(i.rotation||0)*Math.PI/180,a=i.glowIntensity||1),{centerX:e,centerY:t,scaleMultiplier:s,rotationAngle:n,glowMultiplier:a}}applyGestureAnimations(e,t,i,s,n){const a=this.renderer.gestureAnimator.applyGestureAnimations();return a&&(e+=a.offsetX||0,t+=a.offsetY||0,i*=a.scale||1,s+=(a.rotation||0)*Math.PI/180,n=a.glow||1),{centerX:e,centerY:t,scaleMultiplier:i,rotationAngle:s,glowMultiplier:n,gestureTransforms:a}}calculateRenderDimensions(e,t,i,s){const{canvasSize:n,effectiveCenter:a}=this.calculateBaseDimensions(e,t);let r,o,l,{centerX:h,centerY:c}=this.calculateCenterPosition(a,i,t);({centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l}=this.applyGestureTransform(h,c,s));const u=this.applyGestureAnimations(h,c,r,o,l);({centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l}=u);const{gestureTransforms:d}=u;return{canvasSize:n,effectiveCenter:a,centerX:h,centerY:c,scaleMultiplier:r,rotationAngle:o,glowMultiplier:l,gestureTransforms:d}}}var Wn={name:"recording-glow",emoji:"๐ด",description:"Pulsating red recording indicator",config:{color:"#FF0000",pulseSpeed:.08,minIntensity:.6,maxIntensity:1,radiusMultiplier:2,gradientStops:[{position:0,opacity:1},{position:.3,opacity:.7},{position:.6,opacity:.4},{position:.85,opacity:.2},{position:1,opacity:0}]},state:{pulsePhase:0,intensity:.8},shouldActivate:e=>!0===e.recording,apply(e,t){const{deltaTime:i=16.67}=t;this.state.pulsePhase+=this.config.pulseSpeed*(i/16.67);const s=(Math.sin(this.state.pulsePhase)+1)/2;return this.state.intensity=this.config.minIntensity+(this.config.maxIntensity-this.config.minIntensity)*s,!0},drawRecordingIndicator(e,t,i){e.save();const s=Math.min(t,i),n=Math.floor(.08*s),a=1.5*n,r=1.5*n,o=.3*n;e.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),e.beginPath(),e.arc(a-n,r,o,0,2*Math.PI),e.fill(),e.strokeStyle=this.hexToRgba("#FFFFFF",.8*this.state.intensity),e.lineWidth=3,e.font=`bold ${n}px 'Arial', sans-serif`,e.textAlign="left",e.textBaseline="middle",e.strokeText("REC",a,r),e.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),e.fillText("REC",a,r),e.restore()},hexToRgba:(e,t)=>`rgba(${parseInt(e.slice(1,3),16)}, ${parseInt(e.slice(3,5),16)}, ${parseInt(e.slice(5,7),16)}, ${t})`,reset(){this.state.pulsePhase=0,this.state.intensity=0}},Un={name:"speaking-pulse",emoji:"๐ฃ๏ธ",description:"Audio-reactive pulse when speaking",config:{scaleMultiplier:.15,smoothing:.1,minPulse:.02,colorShift:!0,ringEffect:!0},state:{audioLevel:0,smoothedLevel:0,rings:[]},shouldActivate:e=>!0===e.speaking,apply(e,t){const{x:i,y:s,radius:n,audioLevel:a=0,deltaTime:r=16.67}=t;this.state.smoothedLevel+=(a-this.state.smoothedLevel)*this.config.smoothing,a>.5&&this.state.audioLevel<=.5&&this.state.rings.push({radius:n,opacity:.5,speed:2}),this.config.ringEffect&&this.drawRings(e,i,s,r),this.state.audioLevel=a},drawRings(e,t,i,s){e.save(),e.strokeStyle="rgba(100, 200, 255, 0.5)",e.lineWidth=2;for(let n=this.state.rings.length-1;n>=0;n--){const a=this.state.rings[n];a.radius+=a.speed*(s/16.67),a.opacity-=s/16.67*.02,a.opacity<=0?this.state.rings.splice(n,1):(e.globalAlpha=a.opacity,e.beginPath(),e.arc(t,i,a.radius,0,2*Math.PI),e.stroke())}e.restore()},getScaleModifier(){return 1+this.state.smoothedLevel*this.config.scaleMultiplier}},Vn={name:"sleeping",emoji:"๐ด",description:"Sleeping with closed eyes and Z particles",config:{eyeClosedScale:.1,breathingDepth:.15,breathingRate:.8,zParticleInterval:2e3,zDriftSpeed:1,zFadeSpeed:.01,orbDimming:.3,glowDimming:.2},state:{lastZSpawn:0,zParticles:[]},shouldActivate:e=>!0===e.sleeping||"resting"===e.emotion,apply(e,t){const{x:i,y:s,radius:n,deltaTime:a=16.67}=t,r=Date.now();if(r-this.state.lastZSpawn>this.config.zParticleInterval){const e=[100,200,300,400,500,600,700,800,900],t=e[Math.floor(Math.random()*e.length)];this.state.zParticles.push({x:i+n,y:s-n,opacity:1,size:12+8*Math.random(),drift:.5*Math.random()-.25,weight:t,rotation:30*Math.random()-15}),this.state.lastZSpawn=r}this.drawZParticles(e,a)},drawZParticles(e,t){e.save(),e.textAlign="center",e.textBaseline="middle";for(let i=this.state.zParticles.length-1;i>=0;i--){const s=this.state.zParticles[i];s.y-=this.config.zDriftSpeed*(t/16.67),s.x+=s.drift*(t/16.67),s.opacity-=this.config.zFadeSpeed*(t/16.67),s.rotation+=t/16.67*.5,s.opacity<=0?this.state.zParticles.splice(i,1):(e.save(),e.translate(s.x,s.y),e.rotate(s.rotation*Math.PI/180),e.globalAlpha=.7*s.opacity,e.fillStyle="rgba(255, 255, 255, 0.9)",e.font=`${s.weight} ${s.size}px 'Poppins', sans-serif`,e.fillText("Z",0,0),e.shadowBlur=3,e.shadowColor="rgba(147, 112, 219, 0.5)",e.fillText("Z",0,0),e.restore())}e.restore()},getEyeOpenness(){return this.config.eyeClosedScale},getBreathingModifiers(){return{rate:this.config.breathingRate,depth:this.config.breathingDepth}},getDimmingValues(){return{orbDimming:this.config.orbDimming,glowDimming:this.config.glowDimming}}},Yn={name:"suspicion-scan",emoji:"๐",description:"Suspicious scanning and squinting",config:{squintAmount:.4,scanInterval:5e3,scanDuration:800,scanAngle:45,squintSpeed:.02,pupilShift:.3},state:{currentSquint:0,targetSquint:0,lastScanTime:0,scanPhase:0,scanning:!1},shouldActivate:e=>"suspicion"===e.emotion||!0===e.suspicious,apply(e,t){const{deltaTime:i=16.67}=t,s=Date.now();this.updateSquint(i),s-this.state.lastScanTime>this.config.scanInterval&&(this.startScan(),this.state.lastScanTime=s),this.state.scanning&&this.updateScan(s,i)},updateSquint(e){this.state.targetSquint=this.config.squintAmount;const t=this.state.targetSquint-this.state.currentSquint;Math.abs(t)>.01?this.state.currentSquint+=t*this.config.squintSpeed*(e/16.67):this.state.currentSquint=this.state.targetSquint},startScan(){this.state.scanning=!0,this.state.scanStartTime=Date.now(),this.state.scanPhase=-1},updateScan(e,t){const i=(e-this.state.scanStartTime)/this.config.scanDuration;i<.33?this.state.scanPhase=-1:i<.66?this.state.scanPhase=1:(i<1||(this.state.scanning=!1),this.state.scanPhase=0)},getEyeModifiers(){return{scaleY:1-this.state.currentSquint,scaleX:1+.3*this.state.currentSquint,offsetX:this.state.scanPhase*this.config.pupilShift}},drawScanLines(e,t,i,s){if(!this.state.scanning)return;e.save(),e.strokeStyle="rgba(255, 165, 0, 0.3)",e.lineWidth=1,e.setLineDash([5,5]);const n=this.state.scanPhase*(this.config.scanAngle*Math.PI/180),a=t+Math.cos(n)*s*2,r=i+Math.sin(n)*s*.5;e.beginPath(),e.moveTo(t,i),e.lineTo(a,r),e.stroke(),e.restore()}},Xn={name:"gaze-narrowing",emoji:"๐๏ธ",description:"Eye narrowing based on gaze proximity",config:{maxHorizontalScale:1.3,maxVerticalScale:.5,smoothing:.1,focusThreshold:.3},state:{currentScaleX:1,currentScaleY:1,targetScaleX:1,targetScaleY:1},shouldActivate:e=>e.gazeIntensity>0||e.gazeLocked,apply(e,t){const{gazeIntensity:i=0,deltaTime:s=16.67}=t;if(i>this.config.focusThreshold){const e=(i-this.config.focusThreshold)/(1-this.config.focusThreshold);this.state.targetScaleX=1+(this.config.maxHorizontalScale-1)*e,this.state.targetScaleY=1-(1-this.config.maxVerticalScale)*e}else this.state.targetScaleX=1,this.state.targetScaleY=1;this.animateScales(s)},animateScales(e){const t=this.config.smoothing*(e/16.67),i=this.state.targetScaleX-this.state.currentScaleX;Math.abs(i)>.001&&(this.state.currentScaleX+=i*t);const s=this.state.targetScaleY-this.state.currentScaleY;Math.abs(s)>.001&&(this.state.currentScaleY+=s*t)},getEyeScales(){return{scaleX:this.state.currentScaleX,scaleY:this.state.currentScaleY}},drawFocusIndicator(e,t,i,s,n){if(n<this.config.focusThreshold)return;e.save();const a=.5*(n-this.config.focusThreshold);e.strokeStyle=`rgba(100, 200, 255, ${a})`,e.lineWidth=1,e.setLineDash([2,4]);const r=[0,60,120,180,240,300];for(const n of r){const a=n*Math.PI/180,r=2*s,o=1.2*s;e.beginPath(),e.moveTo(t+Math.cos(a)*r,i+Math.sin(a)*r),e.lineTo(t+Math.cos(a)*o,i+Math.sin(a)*o),e.stroke()}e.restore()}},Nn={name:"fingerprint",emoji:"๐",description:"Biometric fingerprint pattern for authentication UI",config:{rings:8,ringSpacing:15,lineWidth:1.5,rotationSpeed:.001,pulseSpeed:.02,waveAmplitude:3,waveFrequency:8,breakPoints:5,opacity:.4,scanLineSpeed:.01,scanLineWidth:3,color:"#00CED1",glowColor:"#00FFFF",successColor:"#00FF00",failColor:"#FF0000"},state:{rotation:0,pulsePhase:0,scanPosition:0,scanDirection:1,isScanning:!1,scanResult:null,breaks:[],whorls:[]},shouldActivate:e=>!0===e.biometric||!0===e.fingerprint||!0===e.authenticating,initialize(){this.state.breaks=[];for(let e=0;e<this.config.rings;e++){const e=[];for(let t=0;t<this.config.breakPoints;t++)e.push(Math.random()*Math.PI*2);this.state.breaks.push(e)}this.state.whorls=[{x:.2,y:-.1,strength:.3},{x:-.15,y:.2,strength:.25},{x:0,y:0,strength:.5}]},apply(e,t){const{x:i,y:s,radius:n,deltaTime:a=16.67,scanning:r=!1,authResult:o=null}=t;0===this.state.breaks.length&&this.initialize(),this.state.rotation+=this.config.rotationSpeed*(a/16.67),this.state.pulsePhase+=this.config.pulseSpeed*(a/16.67),(r||this.state.isScanning)&&(this.state.isScanning=!0,this.state.scanPosition+=this.config.scanLineSpeed*this.state.scanDirection*(a/16.67),this.state.scanPosition>1?(this.state.scanPosition=1,this.state.scanDirection=-1):this.state.scanPosition<-1&&(this.state.scanPosition=-1,this.state.scanDirection=1)),e.save(),this.drawFingerprintPattern(e,i,s,n),this.state.isScanning&&this.drawScanLine(e,i,s,n),o&&this.showAuthResult(e,i,s,n,o),e.restore()},drawFingerprintPattern(e,t,i,s){const n=.1*Math.sin(this.state.pulsePhase)+1;for(let a=0;a<this.config.rings;a++){const r=(a+1)*this.config.ringSpacing*n;if(!(r>2*s)){e.beginPath(),e.strokeStyle=this.config.color,e.lineWidth=this.config.lineWidth,e.globalAlpha=this.config.opacity*(1-a/this.config.rings*.5);for(let n=0;n<2*Math.PI;n+=.05){let o=!1;for(const e of this.state.breaks[a]||[])if(Math.abs(n-e)<.1){o=!0;break}if(o){e.stroke(),e.beginPath();continue}let l=r,h=n+this.state.rotation;for(const e of this.state.whorls){const n=t+e.x*s,a=i+e.y*s,r=t+Math.cos(h)*l,o=i+Math.sin(h)*l,c=Math.sqrt(Math.pow(r-n,2)+Math.pow(o-a,2));h+=Math.exp(-c/(.5*s))*e.strength*.5}l+=Math.sin(n*this.config.waveFrequency)*this.config.waveAmplitude;const c=t+Math.cos(h)*l,u=i+Math.sin(h)*l;0===n?e.moveTo(c,u):e.lineTo(c,u)}e.stroke()}}},drawScanLine(e,t,i,s){const n=i+this.state.scanPosition*s,a=e.createLinearGradient(t-s,n,t+s,n);a.addColorStop(0,"rgba(0, 255, 255, 0)"),a.addColorStop(.5,this.config.glowColor),a.addColorStop(1,"rgba(0, 255, 255, 0)"),e.strokeStyle=a,e.lineWidth=this.config.scanLineWidth,e.globalAlpha=.8,e.shadowBlur=10,e.shadowColor=this.config.glowColor,e.beginPath(),e.moveTo(t-s,n),e.lineTo(t+s,n),e.stroke(),e.shadowBlur=0},showAuthResult(e,t,i,s,n){const a="success"===n?this.config.successColor:this.config.failColor,r="success"===n?"โ AUTHENTICATED":"โ ACCESS DENIED";e.fillStyle=a,e.font=`bold ${.15*s}px monospace`,e.textAlign="center",e.textBaseline="middle",e.globalAlpha=.9,e.fillText(r,t,i+1.3*s),e.strokeStyle=a,e.lineWidth=3,e.globalAlpha=.5,e.beginPath(),e.arc(t,i,1.1*s,0,2*Math.PI),e.stroke()},startScan(){this.state.isScanning=!0,this.state.scanPosition=-1,this.state.scanDirection=1,this.state.scanResult=null},completeScan(e=!0){this.state.isScanning=!1,this.state.scanResult=e?"success":"fail",setTimeout(()=>{this.state.scanResult=null},2e3)},reset(){this.state.rotation=0,this.state.pulsePhase=0,this.state.scanPosition=0,this.state.scanDirection=1,this.state.isScanning=!1,this.state.scanResult=null}};const Qn=new Map;function Jn(e){e.name&&Qn.set(e.name,e)}function Kn(e){return Qn.get(e)||null}function Zn(e,t,i){const s=Kn(e);return!!s&&!!s.apply&&(s.apply(t,i),!0)}function ea(e,t){const i=Kn(e);return!(!i||!i.shouldActivate)&&i.shouldActivate(t)}Jn(Wn),Jn(Un),Jn(Vn),Jn(Yn),Jn(Xn),Jn(Nn);class ta{constructor(e){this.renderer=e}calculateSleepModifiers(){let e=1,t=1,i=1;if(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||ea("sleeping",this.renderer.state)){const s=Kn("sleeping");if(s){const n=s.getDimmingValues();e=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:n.orbDimming,i=n.glowDimming,t=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9}else e=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:.3,i=.2,t=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9;this.renderer.state.breathRate=.5,this.renderer.state.breathDepth=.15}return{sleepOpacityMod:e,sleepScaleMod:t,glowOpacityMod:i}}calculateBreathingFactors(){let e,t;if(null!==this.renderer.state.customScale)e=this.renderer.state.customScale,t=1+.5*(this.renderer.state.customScale-1);else{const i=this.renderer.breathingAnimator.getBreathingScale();e=i,t=1-.5*(i-1)}return"nervous"===this.renderer.state.undertone&&this.renderer.undertoneModifiers.nervous.glowPulse&&(t*=1+Math.sin(Date.now()/200)*this.renderer.undertoneModifiers.nervous.glowPulse),{coreBreathFactor:e,glowBreathFactor:t}}calculateRadii(e,t,i){const{sleepOpacityMod:s,sleepScaleMod:n,glowOpacityMod:a}=this.calculateSleepModifiers(),{coreBreathFactor:r,glowBreathFactor:o}=this.calculateBreathingFactors(),l=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*this.renderer.scaleFactor,h=e.properties&&e.properties.coreSize?e.properties.coreSize:1,c=this.renderer.state.sizeMultiplier||1;return{coreRadius:l*h*r*t*n*c,glowRadius:l*this.renderer.config.glowMultiplier*o*this.renderer.state.glowIntensity*t*n*c*i,effectiveGlowIntensity:this.renderer.state.glowIntensity*i,sleepOpacityMod:s,glowOpacityMod:a}}}class ia{constructor(e){this.renderer=e}applyBlinkSquish(e){return this.renderer.state.sleeping||(e*=this.renderer.eyeRenderer.getBlinkScale()),e}calculateJitter(e,t){let i=0,s=0;const n=this.renderer.state.jitterAmount||0;if(this.renderer.currentUndertone)({jitterX:i,jitterY:s,coreRadius:e,glowRadius:t}=this.renderer.episodicEffectController.updateEpisodicEffects(this.renderer.currentUndertone,i,s,e,t));else if(this.renderer.state.coreJitter||n>0){const e=Math.max(n,this.renderer.state.coreJitter?this.renderer.scaleValue(2):0);i=(Math.random()-.5)*e,s=(Math.random()-.5)*e}return{jitterX:i,jitterY:s,coreRadius:e,glowRadius:t}}calculateFinalPosition(e,t,i,s){return{coreX:e+this.renderer.state.gazeOffset.x+i,coreY:t+this.renderer.state.gazeOffset.y+s}}applyAllModifications(e,t,i,s,n){let a,r;s=this.applyBlinkSquish(s),({jitterX:a,jitterY:r,coreRadius:s,glowRadius:n}=this.calculateJitter(s,n));const{coreX:o,coreY:l}=this.calculateFinalPosition(e,t,a,r);return{coreX:o,coreY:l,rotationAngle:i,coreRadius:s,glowRadius:n}}}class sa{constructor(e){this.renderer=e}renderGlow(e,t,i,s,n,a){ea("recording-glow",this.renderer.state)?Zn("recording-glow",this.renderer.ctx,{x:e,y:t,radius:i,deltaTime:a}):this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||ea("sleeping",this.renderer.state)?(this.renderer.ctx.save(),this.renderer.ctx.globalAlpha=n,this.renderer.glowRenderer.renderGlow(e,t,i,{intensity:s}),this.renderer.ctx.restore()):this.renderer.glowRenderer.renderGlow(e,t,i,{intensity:s})}renderFlashWave(e,t,i,s){if(e&&e.flashWave){const n=e.flashWave,{ctx:a}=this.renderer;a.save(),a.globalCompositeOperation="lighter";const r=s*n.innerRadius,o=s*n.outerRadius;if(o>r){const e=_n.getRadialGradient(a,t,i,r,t,i,o,[{offset:0,color:"rgba(255, 255, 255, 0)"},{offset:.2,color:`rgba(255, 255, 255, ${.15*n.intensity})`},{offset:.5,color:`rgba(255, 255, 255, ${.25*n.intensity})`},{offset:.8,color:`rgba(255, 255, 255, ${.15*n.intensity})`},{offset:1,color:"rgba(255, 255, 255, 0)"}]);a.fillStyle=e,a.beginPath(),a.arc(t,i,o,0,2*Math.PI),a.arc(t,i,Math.max(0,r),0,2*Math.PI,!0),a.fill()}a.restore()}}renderSpeakingPulse(e,t,i,s){ea("speaking-pulse",this.renderer.state)&&Zn("speaking-pulse",this.renderer.ctx,{x:e,y:t,radius:i,audioLevel:this.renderer.state.audioLevel||0,deltaTime:s})}renderAllEffects(e){const{coreX:t,coreY:i,glowRadius:s,effectiveGlowIntensity:n,glowOpacityMod:a,gestureTransforms:r,coreRadius:o,deltaTime:l}=e;this.renderGlow(t,i,s,n,a,l),this.renderFlashWave(r,t,i,o),this.renderSpeakingPulse(t,i,o,l)}}class na{constructor(e){this.renderer=e}applySleepOpacity(e){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=e)}updateShapeMorpher(e){let t=null,i=null;return this.renderer.shapeMorpher&&(this.renderer.shapeMorpher.update(),t=this.renderer.shapeMorpher.getCanvasPoints(0,0,e),i=this.renderer.shapeMorpher.getCurrentShadow()),{shapePoints:t,currentShadow:i}}renderSunEffects(e,t,i,s){let n=!1;return!s||"sun"!==s.type&&"solar-hybrid"!==s.type||(this.renderer.renderSunEffects(e,t,i,s),n=!0),n}renderCore(e,t,i,s,n){this.renderer.coreRenderer.renderCore(e,t,i,{scaleX:1,scaleY:1,rotation:s,shapePoints:n})}renderSparkles(e){this.renderer.specialEffects&&(this.renderer.specialEffects.update(e),this.renderer.specialEffects.renderSparkles())}renderShadowEffects(e,t,i,s,n,a){const r=this.renderer.shapeMorpher?this.renderer.shapeMorpher.currentShape:null,o=this.renderer.shapeMorpher?this.renderer.shapeMorpher.targetShape:null,l=this.renderer.shapeMorpher&&"solar"===o&&this.renderer.shapeMorpher.isTransitioning,h=this.renderer.shapeMorpher&&"solar"===r&&this.renderer.shapeMorpher.isTransitioning,c=s&&"solar-hybrid"===s.type,u=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"solar"===r&&"moon"===o,d=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"moon"===r&&"solar"===o;if(!s||"crescent"!==s.type&&"lunar"!==s.type||d||this.renderer.renderMoonShadow(e,t,i,s,n,!1,0),(c&&s.lunarOverlay||l||h)&&!u){const r=c&&s.lunarOverlay?s.lunarOverlay:{type:"lunar",coverage:1,color:"rgba(0, 0, 0, 1.0)",progression:"center"};let o=0,u=0,d=0;if(this.renderer.shapeMorpher){d=this.renderer.shapeMorpher.getProgress();const e=2.5*i;l&&d<1?(o=-e*(1-d),u=e*(1-d)):h&&d<1&&(o=e*d,u=-e*d)}if(this.renderer.renderMoonShadow(e,t,i,r,n,!0),(l||h)&&(l||a)&&(this.renderer.renderBaileysBeads(e,t,i,o,u,d,l,!0),Math.abs(o)<30&&Math.abs(u)<30&&this.renderer.specialEffects)){const e=Math.sqrt(o*o+u*u),t=Math.max(.1,.5*(1-e/30));this.renderer.specialEffects.triggerChromaticAberration(t)}}}cleanup(e){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=1),0!==e&&this.renderer.ctx.restore()}renderCoreAndShapes(e){const{coreX:t,coreY:i,coreRadius:s,totalRotation:n,sleepOpacityMod:a,deltaTime:r}=e;this.applySleepOpacity(a);const{shapePoints:o,currentShadow:l}=this.updateShapeMorpher(s),h=this.renderSunEffects(t,i,s,l);this.renderCore(t,i,s,n,o),this.renderSparkles(r),this.renderShadowEffects(t,i,s,l,o,h),this.cleanup(n)}}class aa{constructor(e){this.renderer=e}renderSleepIndicator(e,t,i,s){this.renderer.state.sleeping&&this.renderer.renderSleepIndicator(e,t-i-this.renderer.scaleValue(20),s)}finalizeCanvas(e,t,i){this.renderer.ctx=e,e.drawImage(this.renderer.offscreenCanvas,0,0,t,i)}drawRecordingIndicator(e){if(ea("recording-glow",this.renderer.state)){const t=Kn("recording-glow");t&&t.drawRecordingIndicator&&t.drawRecordingIndicator(e,this.renderer.canvas.width,this.renderer.canvas.height)}}finalizePerformanceMetrics(e){const t=performance.now()-e;this.renderer.performanceMonitor&&(this.renderer.performanceMonitor.markFrameEnd(),this.renderer.performanceMonitor.recordFrameTime(t))}finalizeRender(e){const{centerX:t,centerY:i,glowRadius:s,deltaTime:n,originalCtx:a,logicalWidth:r,logicalHeight:o,frameStartTime:l}=e;this.renderSleepIndicator(t,i,s,n),this.finalizeCanvas(a,r,o),this.drawRecordingIndicator(a),this.finalizePerformanceMetrics(l)}}class ra{constructor(e){this.renderer=e,this.animations={grooveSway:null,grooveBob:null,grooveFlow:null,groovePulse:null,grooveStep:null},this.activeAnimation=null,this.blendState={x:0,y:0,rotation:0,scale:1,opacity:1}}startAmbientAnimation(e,t={}){this.activeAnimation&&this.activeAnimation!==e&&this.stopAmbientAnimation(this.activeAnimation),this.activeAnimation=e,this.animations[e]={startTime:Date.now(),intensity:t.intensity||1,frequency:t.frequency||1,options:t}}stopAmbientAnimation(e){this.animations[e]&&(this.animations[e]=null),this.activeAnimation===e&&(this.activeAnimation=null)}updateBlendState(e){if(!e)return;const t=.2;this.blendState.x=this.lerp(this.blendState.x,e.x||0,t),this.blendState.y=this.lerp(this.blendState.y,e.y||0,t),this.blendState.rotation=this.lerp(this.blendState.rotation,e.rotation||0,t),this.blendState.scale=this.lerp(this.blendState.scale,e.scale||1,t),this.blendState.opacity=this.lerp(this.blendState.opacity,e.opacity||1,t)}getTransform(e){const t={x:this.blendState.x,y:this.blendState.y,rotation:this.blendState.rotation,scale:this.blendState.scale,opacity:this.blendState.opacity};if(this.activeAnimation){const e=this.animations[this.activeAnimation];if(e){const i=Date.now()-e.startTime;switch(this.activeAnimation){case"grooveSway":t.x+=15*Math.sin(i/500*e.frequency)*e.intensity,t.rotation+=5*Math.sin(i/500*e.frequency+Math.PI/4)*e.intensity;break;case"grooveBob":t.y+=10*Math.sin(i/400*e.frequency)*e.intensity,t.scale*=1+.03*Math.sin(i/400*e.frequency)*e.intensity;break;case"grooveFlow":{const s=i/1e3*e.frequency;t.x+=Math.sin(s)*Math.cos(2*s)*20*e.intensity,t.y+=Math.cos(s)*Math.sin(2*s)*10*e.intensity,t.rotation+=8*Math.sin(2*s)*e.intensity;break}case"groovePulse":t.scale*=1+.05*Math.sin(i/250*e.frequency)*e.intensity,t.opacity*=.9+.1*Math.sin(i/250*e.frequency)*e.intensity;break;case"grooveStep":{const s=Math.floor(i/500*e.frequency)%4,n=i/500*e.frequency%1,a=this.smoothStep(n);0===s?t.x+=25*a*e.intensity:2===s&&(t.x-=25*a*e.intensity),t.y+=5*Math.abs(Math.sin(i/250*e.frequency))*e.intensity;break}}}}return t}lerp(e,t,i){return e+(t-e)*i}smoothStep(e){return e*e*(3-2*e)}}class oa{constructor(e){this.renderer=e,this.ctx=e.ctx,this.config={enabled:!1,radius:1.5,shape:"circle",color:"rgba(0, 0, 0, 0.6)",intensity:.7,blendMode:"normal",falloff:"smooth",falloffCurve:null,edgeSoftness:.6,coreTransparency:.2,blur:0,responsive:!0,pulse:!1,offset:{x:0,y:0},type:"radial-gradient"},this.currentIntensity=0,this.targetIntensity=0,this.pulsePhase=0}setConfig(e={}){this.config={...this.config,...e},void 0!==e.enabled&&(this.targetIntensity=e.enabled?this.config.intensity:0)}update(e){this.config.enabled?(this.currentIntensity+=.1*(this.targetIntensity-this.currentIntensity),this.config.responsive&&(this.pulsePhase+=.001*e)):this.currentIntensity*=.95}setAudioIntensity(e){if(!this.config.responsive)return;const t=.2*e;this.targetIntensity=Math.min(1,this.config.intensity+t)}render(e,t,i,s=null){if(this.currentIntensity<.01)return;const n=s||this.ctx;switch(n.save(),this.config.type){case"radial-gradient":this.renderRadialGradient(e,t,i,n);break;case"vignette":this.renderVignette(e,t,i,n);break;case"glow":this.renderGlow(e,t,i,n)}n.restore()}renderRadialGradient(e,t,i,s){s=s||this.ctx;const n=i*this.config.radius,a=e+(this.config.offset.x||0),r=t+(this.config.offset.y||0);let o=n;(this.config.pulse||this.config.responsive)&&(o*=1+.05*Math.sin(this.pulsePhase));const l=s.globalCompositeOperation;this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=this.config.blendMode),this.config.blur>0&&(s.filter=`blur(${this.config.blur}px)`);const h=s.createRadialGradient(a,r,0,a,r,o),c=this.config.color,u=this.currentIntensity;this.addGradientStopsSimple(h,c,u),s.fillStyle=h,s.beginPath(),s.arc(a,r,o,0,2*Math.PI),s.fill(),this.config.blur>0&&(s.filter="none"),this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=l)}renderVignette(e,t,i,s){s=s||this.ctx;const{canvas:n}=s,a=Math.max(n.width,n.height),r=s.createRadialGradient(e,t,.5*i,e,t,a);r.addColorStop(0,"rgba(0, 0, 0, 0)"),r.addColorStop(1,this.adjustColorAlpha(this.config.color,this.currentIntensity)),s.fillStyle=r,s.fillRect(0,0,n.width,n.height)}renderGlow(e,t,i,s){s=s||this.ctx;const n=i*this.config.radius;for(let i=0;i<3;i++){const a=n*(1-.2*i),r=this.currentIntensity*(.3-.1*i),o=s.createRadialGradient(e,t,0,e,t,a);o.addColorStop(0,this.adjustColorAlpha(this.config.color,r)),o.addColorStop(1,"rgba(0, 0, 0, 0)"),s.fillStyle=o,s.beginPath(),s.arc(e,t,a,0,2*Math.PI),s.fill()}}addGradientStopsSimple(e,t,i){const{coreTransparency:s}=this.config;e.addColorStop(0,this.adjustColorAlpha(t,i)),e.addColorStop(s,this.adjustColorAlpha(t,i));for(let n=1;n<=25;n++){const a=s+n/25*(1-s),r=(a-s)/(1-s),o=1-this.easeInOutCubic(r);e.addColorStop(a,this.adjustColorAlpha(t,i*o))}e.addColorStop(1,"rgba(0, 0, 0, 0)")}addGradientStops(e,t,i,s=1){const{coreTransparency:n}=this.config;if(this.config.falloffCurve&&Array.isArray(this.config.falloffCurve))this.config.falloffCurve.forEach(({stop:s,alpha:n})=>{e.addColorStop(s,this.adjustColorAlpha(t,i*n))});else switch(this.config.falloff){case"linear":e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n,"rgba(0, 0, 0, 0)"),e.addColorStop(1,this.adjustColorAlpha(t,i));break;case"exponential":e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n,"rgba(0, 0, 0, 0)"),e.addColorStop(n+.3*(1-n),this.adjustColorAlpha(t,.05*i)),e.addColorStop(n+.5*(1-n),this.adjustColorAlpha(t,.15*i)),e.addColorStop(n+.7*(1-n),this.adjustColorAlpha(t,.4*i)),e.addColorStop(n+.85*(1-n),this.adjustColorAlpha(t,.7*i)),e.addColorStop(1,this.adjustColorAlpha(t,i));break;default:{e.addColorStop(0,"rgba(0, 0, 0, 0)"),e.addColorStop(n*s,"rgba(0, 0, 0, 0)");const{edgeSoftness:a}=this.config,r=s,o=n*s+(r-n*s)*a,l=25;for(let a=1;a<=l;a++){const h=a/l;let c=0;if(h<=n*s)c=0;else if(h<=r)if(h<=o){const e=(h-n*s)/(o-n*s);c=this.easeInOutCubic(e)}else{const e=(h-o)/(r-o);c=1-.05*(1-this.easeInOutCubic(e))}else{const e=(h-r)/(1-r);c=1-this.easeInOutCubic(e)}e.addColorStop(h,this.adjustColorAlpha(t,i*c))}e.addColorStop(1,"rgba(0, 0, 0, 0)");break}}}easeInOutCubic(e){return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}adjustColorAlpha(e,t){const i=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(i){const[,e,s,n,a=1]=i;return`rgba(${e}, ${s}, ${n}, ${parseFloat(a)*t})`}return`rgba(0, 0, 0, ${.6*t})`}getConfig(){return{...this.config}}enable(){this.config.enabled=!0,this.targetIntensity=this.config.intensity}disable(){this.config.enabled=!1,this.targetIntensity=0}toggle(){this.config.enabled?this.disable():this.enable()}}const la={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3,IDLE:4};class ha{constructor(){this.callbacks=new Map,this.callbackIdCounter=0,this._groupedCallbacks=new Map,this._groupsDirty=!0,this.frameId=null,this.isRunning=!1,this.lastFrameTime=0,this.deltaTime=0,this.fps=60,this.frameCount=0,this.targetFPS=60,this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=16.67,this.prioritySkipCounters={[la.MEDIUM]:0,[la.LOW]:0,[la.IDLE]:0},this.performanceMonitor=null,this.frameTimeHistory=new Array(60).fill(0),this._historyIndex=0,this._historyCount=0,this.maxHistorySize=60,this.loop=this.loop.bind(this)}register(e,t=la.MEDIUM,i=null){if("function"!=typeof e)throw new Error("Callback must be a function");const s=++this.callbackIdCounter;return this.callbacks.set(s,{callback:e,priority:t,context:i,lastRun:0,runCount:0,totalTime:0,enabled:!0}),this._groupsDirty=!0,1!==this.callbacks.size||this.isRunning||this.start(),s}unregister(e){this.callbacks.delete(e),this._groupsDirty=!0,0===this.callbacks.size&&this.isRunning&&this.stop()}setEnabled(e,t){const i=this.callbacks.get(e);i&&(i.enabled=t)}start(){this.isRunning||(this.isRunning=!0,this.lastFrameTime=performance.now(),this.frameId=requestAnimationFrame(this.loop))}stop(){this.isRunning&&(this.isRunning=!1,this.frameId&&(cancelAnimationFrame(this.frameId),this.frameId=null))}loop(e){if(!this.isRunning)return;this.deltaTime=e-this.lastFrameTime,this.lastFrameTime=e,this.frameCount++,this.frameCount%60==0&&(this.fps=Math.round(1e3/(this.deltaTime||16.67))),this.frameTimeHistory[this._historyIndex]=this.deltaTime,this._historyIndex=(this._historyIndex+1)%this.maxHistorySize,this._historyCount<this.maxHistorySize&&this._historyCount++,this._groupsDirty&&this._rebuildGroups();const t=this._groupedCallbacks;let i=0;for(const s of[la.CRITICAL,la.HIGH,la.MEDIUM,la.LOW,la.IDLE]){if(s>la.CRITICAL&&i>.8*this.frameBudget)break;if(this.shouldSkipPriority(s))continue;const n=t.get(s)||[];for(const t of n){if(!t.enabled)continue;const s=performance.now();try{t.context?t.callback.call(t.context,this.deltaTime,e):t.callback(this.deltaTime,e);const n=performance.now()-s;t.totalTime+=n,t.runCount++,t.lastRun=e,i+=n}catch(e){console.error("Animation callback error:",e),t.runCount>0&&t.totalTime/t.runCount>10&&(console.warn("Disabling slow callback"),t.enabled=!1)}if(i>this.frameBudget)break}}this.frameId=requestAnimationFrame(this.loop)}_rebuildGroups(){this._groupedCallbacks.clear();for(const[,e]of this.callbacks){const{priority:t}=e;this._groupedCallbacks.has(t)||this._groupedCallbacks.set(t,[]),this._groupedCallbacks.get(t).push(e)}this._groupsDirty=!1}shouldSkipPriority(e){if(e===la.CRITICAL)return!1;if(this.fps<30&&e>=la.LOW)return!0;if(this.fps<45&&e===la.IDLE)return!0;if(e===la.MEDIUM){if(this.fps<50&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%2!=0))return!0}else if(e===la.LOW){if(this.fps<50&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%3!=0))return!0}else if(e===la.IDLE&&(this.prioritySkipCounters[e]++,this.prioritySkipCounters[e]%5!=0))return!0;return!1}getStats(){const e={fps:this.fps,frameCount:this.frameCount,callbackCount:this.callbacks.size,averageFrameTime:0,maxFrameTime:0,minFrameTime:1/0};if(this._historyCount>0){let t=0;for(let i=0;i<this._historyCount;i++){const s=this.frameTimeHistory[i];t+=s,e.maxFrameTime=Math.max(e.maxFrameTime,s),e.minFrameTime=Math.min(e.minFrameTime,s)}e.averageFrameTime=t/this._historyCount}e.callbacksByPriority={};for(const[,t]of this.callbacks){const{priority:i}=t;e.callbacksByPriority[i]||(e.callbacksByPriority[i]={count:0,totalTime:0,enabled:0}),e.callbacksByPriority[i].count++,e.callbacksByPriority[i].totalTime+=t.totalTime,t.enabled&&e.callbacksByPriority[i].enabled++}return e}setTargetFPS(e){this.targetFPS=Math.max(15,Math.min(120,e)),this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=this.targetFrameTime}setPerformanceMonitor(e){this.performanceMonitor=e}destroy(){this.stop(),this.callbacks.clear(),this._groupedCallbacks.clear(),this._groupsDirty=!0,this.frameTimeHistory.fill(0),this._historyIndex=0,this._historyCount=0}}const ca=new ha;class ua{constructor(e){this.renderer=e,this.loopCallbackIds={eyeClose:null,eyeOpen:null},this.wakeJitterTimeout=null}enterSleepMode(){this.renderer.state.sleeping=!0,this.renderer.sleepZ=[],this.renderer.state.eyeOpenness=1,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.renderer.state.blinking=!1,this.animateEyeClose()}animateEyeClose(){this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null);const e=performance.now(),t=2e3;this.loopCallbackIds.eyeClose=ca.register(()=>{if(!this.renderer.state.sleeping)return void(this.loopCallbackIds.eyeClose=null);const i=performance.now()-e;if(i<t){const e=i/t,s=1-Math.pow(e,2);this.renderer.state.eyeOpenness=.1+.9*s,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1}else if(i<3e3){const e=(i-t)/1e3,s=1-Math.pow(1-e,3);this.renderer.state.eyeOpenness=.1,this.renderer.state.sleepDimness=1-.4*s,this.renderer.state.sleepScale=1-.1*s}else this.renderer.state.eyeOpenness=.1,this.renderer.state.sleepDimness=.6,this.renderer.state.sleepScale=.9,this.loopCallbackIds.eyeClose=null},la.HIGH,this.renderer)}wakeUp(){this.renderer.state.sleeping&&(this.renderer.state.sleeping=!1,this.renderer.state.breathRate=1,this.renderer.state.breathDepth=this.renderer.config.breathingDepth,this.renderer.sleepZ=[],this.renderer.state.blinking=!1,this.renderer.eyeRenderer.blinking=!1,this.renderer.eyeRenderer.blinkTimer=0,this.animateEyeOpen(),this.wakeJitterTimeout&&clearTimeout(this.wakeJitterTimeout),this.renderer.state.coreJitter=!0,this.wakeJitterTimeout=setTimeout(()=>{this.renderer.state.coreJitter=!1,this.wakeJitterTimeout=null},200))}animateEyeOpen(){this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null);const e=performance.now();this.loopCallbackIds.eyeOpen=ca.register(()=>{const t=performance.now()-e;if(t<500){const e=t/500,i=Math.sin(e*Math.PI/2);this.renderer.state.sleepDimness=.6+.4*i,this.renderer.state.sleepScale=.9+.1*i,this.renderer.state.eyeOpenness=.1}else if(t<1500){const e=(t-500)/1e3,i=Math.sin(e*Math.PI/2);this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.renderer.state.eyeOpenness=.1+.9*i}else this.renderer.state.eyeOpenness=1,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1,this.loopCallbackIds.eyeOpen=null},la.HIGH,this.renderer)}renderSleepIndicator(e,t,i){return this.renderer.specialEffects.renderSleepIndicator(e,t,i)}cleanup(){this.loopCallbackIds.eyeClose&&(ca.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(ca.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.wakeJitterTimeout&&(clearTimeout(this.wakeJitterTimeout),this.wakeJitterTimeout=null)}}class da{constructor(e){this.renderer=e}applyUndertoneModifiers(e){if(e&&"object"==typeof e&&void 0!==e.weight){const{weight:t}=e;return this.renderer.state.sizeMultiplier=1+((e.sizeMultiplier||1)-1)*t,this.renderer.state.jitterAmount=(e.jitterAmount||0)*t,this.renderer.state.episodicFlutter=t>.5&&e.episodicFlutter||!1,this.renderer.state.glowRadiusMult=1+((e.glowRadiusMult||1)-1)*t,this.renderer.state.breathRateMult=1+((e.breathRateMult||1)-1)*t,this.renderer.state.breathDepthMult=1+((e.breathDepthMult||1)-1)*t,this.renderer.state.breathIrregular=t>.5&&e.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=(e.glowPulse||0)*t,this.renderer.state.brightnessFlicker=(e.brightnessFlicker||0)*t,this.renderer.state.brightnessMult=1+((e.brightnessMult||1)-1)*t,this.renderer.state.saturationMult=1+((e.saturationMult||1)-1)*t,void(this.renderer.state.hueShift=(e.hueShift||0)*t)}if(!e||!this.renderer.undertoneModifiers[e])return this.renderer.state.sizeMultiplier=1,this.renderer.state.jitterAmount=0,this.renderer.state.episodicFlutter=!1,this.renderer.state.glowRadiusMult=1,this.renderer.state.breathRateMult=1,this.renderer.state.breathDepthMult=1,this.renderer.state.breathIrregular=!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=0,this.renderer.state.brightnessFlicker=0,this.renderer.state.brightnessMult=1,this.renderer.state.saturationMult=1,void(this.renderer.state.hueShift=0);const t=this.renderer.undertoneModifiers[e];this.renderer.state.sizeMultiplier=t.sizeMultiplier,this.renderer.state.jitterAmount=t.jitterAmount||0,this.renderer.state.episodicFlutter=t.episodicFlutter||!1,this.renderer.state.glowRadiusMult=t.glowRadiusMult,this.renderer.state.breathRateMult=t.breathRateMult,this.renderer.state.breathDepthMult=t.breathDepthMult,this.renderer.state.breathIrregular=t.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=t.glowPulse||0,this.renderer.state.brightnessFlicker=t.brightnessFlicker||0,this.renderer.state.brightnessMult=t.brightnessMult||1,this.renderer.state.saturationMult=t.saturationMult||1,this.renderer.state.hueShift=t.hueShift||0}updateUndertone(e){this.renderer.state.undertone!==e&&this.renderer.glowCache&&this.renderer.glowCache.clear(),this.renderer.state.undertone=e,this.renderer.currentUndertone=e;const t=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;if(this.applyUndertoneModifiers(t||e),this.renderer.state.emotion){const i=Ks&&Ks.isInitialized?Ks.getEmotion(this.renderer.state.emotion):l(this.renderer.state.emotion);if(i){const s=i.glowColor||this.renderer.config.defaultGlowColor,n=this.renderer.applyUndertoneToColor(s,t||e);this.renderer.startColorTransition(n,200)}}}setEmotionalState(e,t,i=null){this.renderer.state.emotion===e&&this.renderer.state.undertone===i||!this.renderer.glowCache||this.renderer.glowCache.clear(),this.renderer.state.undertone=i,this.renderer.currentUndertone=i;const s=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;this.applyUndertoneModifiers(s||i);const n=t.glowColor||this.renderer.config.defaultGlowColor;let a;a="suspicion"===e?t.glowColor||n:this.renderer.applyUndertoneToColor(n,s||i);const r=s||(i?this.renderer.undertoneModifiers[i]:null),o=t.glowIntensity||1;let l=1;if(r)if(s){const e=r.weight||0;l=void 0!==r.glowRadiusMult&&isFinite(r.glowRadiusMult)&&isFinite(e)?1+(r.glowRadiusMult-1)*e:1}else l=void 0!==r.glowRadiusMult?r.glowRadiusMult:1;const h=o*l;let c=1500;"anger"===e||"fear"===e?c=800:"sadness"!==e&&"resting"!==e||(c=2e3),this.renderer.state.emotion=e,"suspicion"===e?(this.renderer.state.isSuspicious=!0,this.renderer.state.targetSquintAmount=t&&t.coreSquint?t.coreSquint:.4,void 0===this.renderer.state.squintAmount&&(this.renderer.state.squintAmount=0),this.renderer.state.lastScanTime=Date.now(),this.renderer.state.scanPhase=0):(this.renderer.state.isSuspicious=!1,this.renderer.state.targetSquintAmount=0,void 0===this.renderer.state.squintAmount&&(this.renderer.state.squintAmount=0)),this.renderer.startColorTransition(a,h,c);const u=t.breathRate||1,d=t.breathDepth||this.renderer.config.breathingDepth;this.renderer.state.breathRate=r?u*r.breathRateMult:u,this.renderer.state.breathDepth=r?d*r.breathDepthMult:d,this.renderer.state.coreJitter=t.coreJitter||r&&r.jitterAmount>0,this.renderer.state.emotionEyeOpenness=t.eyeOpenness,this.renderer.state.emotionEyeArc=t.eyeArc}}class ga{constructor(e){this.renderer=e}resetCanvasContext(){if(!this.renderer.canvas||!this.renderer.ctx)return;const{width:e}=this.renderer.canvas,{height:t}=this.renderer.canvas;this.resetContext(this.renderer.ctx,e,t),this.renderer.offscreenCanvas&&this.renderer.offscreenCtx&&this.resetContext(this.renderer.offscreenCtx,this.renderer.offscreenCanvas.width,this.renderer.offscreenCanvas.height),this.renderer.contextStateManager&&this.renderer.contextStateManager.reset(),this.renderer.forceCleanRender=!0}resetContext(e,t,i){e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.globalCompositeOperation="source-over",e.imageSmoothingEnabled=!0,e.imageSmoothingQuality="high",e.clearRect(0,0,t,i)}setQualityLevel(e){this.renderer.qualityLevel=Math.max(0,Math.min(1,e)),this.renderer.qualityLevel<.5?this.applyLowQuality():this.renderer.qualityLevel<.8?this.applyMediumQuality():this.applyHighQuality()}applyLowQuality(){this.renderer.ctx.imageSmoothingEnabled=!1,this.renderer.state.breathDepth*=.5}applyMediumQuality(){this.renderer.ctx.imageSmoothingEnabled=!0,this.renderer.ctx.imageSmoothingQuality="medium"}applyHighQuality(){this.renderer.ctx.imageSmoothingEnabled=!0,this.renderer.ctx.imageSmoothingQuality="high"}setQualityReduction(e){e?this.setQualityLevel(.5):this.setQualityLevel(1)}handleContextRecovery(e){this.renderer.ctx=e}}class ma{constructor(e){this.renderer=e}destroy(){this.cancelAnimationFrames(),this.unregisterLoopCallbacks(),this.cleanupManagers(),this.clearTimeouts(),this.clearAnimationStates(),this.clearOtherResources()}cancelAnimationFrames(){for(const e in this.renderer.animationFrameIds)this.renderer.animationFrameIds[e]&&(cancelAnimationFrame(this.renderer.animationFrameIds[e]),this.renderer.animationFrameIds[e]=null)}unregisterLoopCallbacks(){for(const e in this.renderer.loopCallbackIds)this.renderer.loopCallbackIds[e]&&(ca.unregister(this.renderer.loopCallbackIds[e]),this.renderer.loopCallbackIds[e]=null)}cleanupManagers(){this.renderer.sleepManager&&this.renderer.sleepManager.cleanup(),this.renderer.gazeTracker&&this.renderer.gazeTracker.cleanup()}clearTimeouts(){this.renderer.wakeJitterTimeout&&(clearTimeout(this.renderer.wakeJitterTimeout),this.renderer.wakeJitterTimeout=null)}clearAnimationStates(){this.renderer.colorTransition.active=!1}clearOtherResources(){this.renderer.cleanupGazeTracking(),this.renderer.speakingRings=[],this.renderer.gestureCompositor&&this.renderer.gestureCompositor.clearCache(),this.renderer.specialEffects&&this.renderer.specialEffects.destroy(),this.renderer.cleanupOffscreenCanvas&&this.renderer.cleanupOffscreenCanvas()}}class pa{constructor(e){this.renderer=e}updateTimers(e){this.updateBreathing(e),this.updateBlinking(e)}updateBreathing(e){this.renderer.breathingAnimator.update(e,this.renderer.state.emotion,this.renderer.currentUndertone),this.renderer.state.sleeping?this.applySleepBreathing():this.applyNormalBreathing(),this.renderer.breathingAnimator.setIrregularBreathing(this.renderer.state.breathIrregular)}applySleepBreathing(){this.renderer.breathingAnimator.setBreathRateMultiplier(.5),this.renderer.breathingAnimator.setBreathDepthMultiplier(1.2)}applyNormalBreathing(){this.renderer.breathingAnimator.setBreathRateMultiplier(1),this.renderer.breathingAnimator.setBreathDepthMultiplier(1)}updateBlinking(e){const t=this.renderer.state.blinkingEnabled&&!this.renderer.state.sleeping;this.renderer.eyeRenderer.setBlinkingEnabled(t),this.renderer.eyeRenderer.update(e),this.renderer.state.blinking=this.renderer.eyeRenderer.blinking}}class fa{constructor(e){this.renderer=e}setGazeOffset(e){this.processGazeData(e),this.handleGazeInteraction()}processGazeData(e){"object"==typeof e&&null!==e&&(this.isOldFormat(e)?this.renderer.state.gazeOffset=e:this.applyNewFormatData(e))}isOldFormat(e){return{}.hasOwnProperty.call(e,"x")&&{}.hasOwnProperty.call(e,"y")}applyNewFormatData(e){this.renderer.state.gazeOffset=e.offset||{x:0,y:0},this.renderer.state.gazeIntensity=e.proximity||0,this.renderer.state.gazeLocked=e.isLocked||!1}handleGazeInteraction(){this.renderer.idleTimer=0,this.renderer.isAsleep&&this.renderer.wakeUp()}getCurrentOrbPosition(){const e=this.renderer.canvasManager.width/2,t=this.renderer.canvasManager.height/2-this.renderer.config.topOffset;return{x:e+this.renderer.state.gazeOffset.x,y:t+this.renderer.state.gazeOffset.y}}}class ya{constructor(e,t={}){this.canvasManager=e,this.ctx=e.getContext(),this.ctx||(console.warn("EmotiveRenderer: canvas 2D context is null โ rendering will be disabled."),this._contextLost=!0),this.gestureCompositor=new pn,this.currentUndertone=null,this.gestureAnimator=new kn(this),this.colorUtilities=new Pn,this.specialEffects=new Tn(this),this.eyeRenderer=new En(this),this.breathingAnimator=new An(this),this.glowRenderer=new In(this),this.coreRenderer=new Rn(this),this.celestialRenderer=new Bn,this.episodicEffectController=new zn(this),this.rotationManager=new On(this),this.gazeTracker=new Ln(this),this.canvasSetupManager=new qn(this),this.renderPerformanceManager=new Gn(this),this.transformMerger=new Hn(this),this.stateUpdateManager=new jn(this),this.dimensionCalculator=new $n(this),this.radiusCalculator=new ta(this),this.positionJitterManager=new ia(this),this.effectsRenderManager=new sa(this),this.coreShapeRenderManager=new na(this),this.renderFinalizationManager=new aa(this),this.ambientDanceAnimator=new ra(this),this.backdropRenderer=new oa(this),this.sleepManager=new ua(this),this.emotionalStateManager=new da(this),this.canvasContextManager=new ga(this),this.resourceCleanupManager=new ma(this),this.timerCoordinator=new pa(this),this.gazeInputHandler=new fa(this),this.config={coreColor:t.coreColor||"#FFFFFF",coreSizeDivisor:t.coreSizeDivisor||12,glowMultiplier:t.glowMultiplier||2.5,defaultGlowColor:t.defaultGlowColor||"#14B8A6",breathingSpeed:t.breathingSpeed||.42,breathingDepth:t.breathingDepth||.08,renderingStyle:t.renderingStyle||"classic",baseScale:t.baseScale||1,referenceSize:400,topOffset:t.topOffset||0,positionController:t.positionController||null};const i=Math.min(this.canvasManager.width||400,this.canvasManager.height||400);this.scaleFactor=i/this.config.referenceSize*this.config.baseScale,this.state={emotion:"neutral",glowColor:this.config.defaultGlowColor,glowIntensity:1,breathRate:1,breathDepth:this.config.breathingDepth,coreJitter:!1,speaking:!1,recording:!1,sleeping:!1,blinking:!1,blinkingEnabled:!0,gazeOffset:{x:0,y:0},gazeIntensity:0,gazeLocked:!1,gazeTrackingEnabled:!1,gazeTarget:{x:0,y:0},effectiveCenter:{x:0,y:0,scale:1},squintAmount:0,targetSquintAmount:0,scanPhase:0,lastScanTime:0,isSuspicious:!1,customScale:null,sizeMultiplier:1,jitterAmount:0,episodicFlutter:!1,glowRadiusMult:1,breathRateMult:1,breathDepthMult:1,breathIrregular:!1,particleRateMult:1,glowPulse:0,brightnessFlicker:0,brightnessMult:1,saturationMult:1,hueShift:0,manualRotation:0,rotationSpeed:0,lastRotationUpdate:performance.now()},this.animationFrameIds={colorTransition:null,eyeClose:null,eyeOpen:null},this.loopCallbackIds={eyeClose:null,eyeOpen:null},this.wakeJitterTimeout=null,this.offscreenCanvas=null,this.offscreenCtx=null,this.initOffscreenCanvas(),this.canvas=e.canvas,this.gestureAnimations={bounce:{active:!1,startTime:0,progress:0,params:null},pulse:{active:!1,startTime:0,progress:0,params:null},shake:{active:!1,startTime:0,progress:0,params:null},spin:{active:!1,startTime:0,progress:0,params:null},nod:{active:!1,startTime:0,progress:0,params:null},tilt:{active:!1,startTime:0,progress:0,params:null},expand:{active:!1,startTime:0,progress:0,params:null},contract:{active:!1,startTime:0,progress:0,params:null},flash:{active:!1,startTime:0,progress:0,params:null},drift:{active:!1,startTime:0,progress:0,params:null,startX:0,startY:0},stretch:{active:!1,startTime:0,progress:0,params:null},glow:{active:!1,startTime:0,progress:0,params:null},flicker:{active:!1,startTime:0,progress:0,params:null},vibrate:{active:!1,startTime:0,progress:0,params:null},wave:{active:!1,startTime:0,progress:0,params:null},breathe:{active:!1,startTime:0,progress:0,params:null},morph:{active:!1,startTime:0,progress:0,params:null},slowBlink:{active:!1,startTime:0,progress:0,params:null},look:{active:!1,startTime:0,progress:0,params:null,targetX:0,targetY:0},settle:{active:!1,startTime:0,progress:0,params:null},breathIn:{active:!1,startTime:0,progress:0,params:null},breathOut:{active:!1,startTime:0,progress:0,params:null},breathHold:{active:!1,startTime:0,progress:0,params:null},breathHoldEmpty:{active:!1,startTime:0,progress:0,params:null},jump:{active:!1,startTime:0,progress:0,params:null},orbital:{active:!1,startTime:0,progress:0,params:null},hula:{active:!1,startTime:0,progress:0,params:null}},Object.defineProperty(this,"episodicEffects",{get:()=>this.episodicEffectController.getEpisodicEffects(),enumerable:!0}),this.speakingRings=[],this.maxRings=5,this.ringSpawnTimer=0,this.ringSpawnInterval=200,this.recordingRings=[],this.recordingPulse=0,this.sleepZ=[],this.colorTransition={active:!1,fromColor:this.state.glowColor,toColor:this.state.glowColor,fromIntensity:this.state.glowIntensity,toIntensity:this.state.glowIntensity,progress:0,startTime:0,duration:1500},this.undertoneModifiers={nervous:{hueShift:0,saturationMult:1.05,brightnessMult:1,brightnessFlicker:.05,sizeMultiplier:1,jitterAmount:0,episodicFlutter:!0,glowRadiusMult:1,glowPulse:.05,breathRateMult:1.1,breathDepthMult:.9,breathIrregular:!0},confident:{hueShift:15,saturationMult:1.2,brightnessMult:1.1,sizeMultiplier:1,jitterAmount:0,episodicPowerPose:!0,glowRadiusMult:1.15,breathRateMult:.95,breathDepthMult:1.1,breathIrregular:!1},tired:{hueShift:-5,saturationMult:.7,brightnessMult:.85,sizeMultiplier:.95,jitterAmount:0,episodicMicroSleep:!0,glowRadiusMult:.9,breathRateMult:.8,breathDepthMult:1.2,breathIrregular:!1},intense:{hueShift:5,saturationMult:1.3,brightnessMult:1.15,sizeMultiplier:1,jitterAmount:0,episodicLaserFocus:!0,glowRadiusMult:1.2,breathRateMult:1.2,breathDepthMult:.9,breathIrregular:!1},subdued:{hueShift:-10,saturationMult:.75,brightnessMult:.9,sizeMultiplier:.95,jitterAmount:0,episodicWithdrawal:!0,glowRadiusMult:.85,breathRateMult:.9,breathDepthMult:.9,breathIrregular:!1}},this.lastFrameTime=0,this._createGestureDelegates()}scaleValue(e){return e*this.scaleFactor}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),this.offscreenCtx,this.updateOffscreenSize()}cleanupOffscreenCanvas(){this.offscreenCanvas&&(this.offscreenCtx&&(this.offscreenCtx.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),this.offscreenCtx=null),this.offscreenCanvas.width=0,this.offscreenCanvas.height=0,this.offscreenCanvas=null)}updateOffscreenSize(){if(this.offscreenCanvas&&this.canvasManager){const{width:e}=this.canvasManager.canvas,{height:t}=this.canvasManager.canvas;if(this.offscreenCanvas.width!==e||this.offscreenCanvas.height!==t){this.offscreenCanvas.width=e,this.offscreenCanvas.height=t;const i=this.canvasManager.canvas.width>this.canvasManager.width;this.offscreenCtx&&(this.offscreenCtx.setTransform(1,0,0,1,0,0),i&&this.canvasManager.dpr&&this.offscreenCtx.scale(this.canvasManager.dpr,this.canvasManager.dpr))}}}updateEffectiveCenter(e){this.state.effectiveCenter=e}getEffectiveCenter(){const e=this.canvasManager.getCenter();let t;return t=this.config.positionController?this.config.positionController.getEffectiveCenter(e.x,e.y):{x:e.x,y:e.y,scale:1},t.x+=this.state.gazeOffset.x,t.y+=this.state.gazeOffset.y,t}render(e,t,i=null){if(this._contextLost)return;const s=this.renderPerformanceManager.initializeFrame();i=this.transformMerger.mergeAndStoreTransforms(i,t);const{logicalWidth:n,logicalHeight:a,originalCtx:r}=this.canvasSetupManager.setupCanvas();this.canvasSetupManager.performCanvasSetup(n,a,r,t),this.stateUpdateManager.performFrameStateUpdates(t);const o=this.dimensionCalculator.calculateRenderDimensions(n,a,e,i),{scaleMultiplier:l,glowMultiplier:h,gestureTransforms:c,centerX:u,centerY:d}=o;let{rotationAngle:g}=o;const m=this.radiusCalculator.calculateRadii(e,l,h);let{coreRadius:p,glowRadius:f}=m;const{effectiveGlowIntensity:y,sleepOpacityMod:b,glowOpacityMod:v}=m,M=this.positionJitterManager.applyAllModifications(u,d,g,p,f),{coreX:w,coreY:S}=M;({rotationAngle:g,coreRadius:p,glowRadius:f}=M);const x=this.rotationManager.applyRotationTransform(this.ctx,w,S,g);this.effectsRenderManager.renderAllEffects({coreX:w,coreY:S,glowRadius:f,effectiveGlowIntensity:y,glowOpacityMod:v,gestureTransforms:c,coreRadius:p,deltaTime:t}),this.coreShapeRenderManager.renderCoreAndShapes({coreX:w,coreY:S,coreRadius:p,totalRotation:x,sleepOpacityMod:b,deltaTime:t}),this.renderFinalizationManager.finalizeRender({centerX:u,centerY:d,glowRadius:f,deltaTime:t,originalCtx:r,logicalWidth:n,logicalHeight:a,frameStartTime:s})}renderRecordingGlow(e,t,i,s){const n=this.canvas?.width||600,a=this.canvas?.height||600,r=Math.min(i,e-10,t-10,n-e-10,a-t-10),o=Math.max(50,r),l=_n.getRadialGradient(this.ctx,e,t,0,e,t,o,[{offset:0,color:this.hexToRgba("#FF0000",.7*s)},{offset:.3,color:this.hexToRgba("#FF0000",.5*s)},{offset:.6,color:this.hexToRgba("#FF0000",.3*s)},{offset:.85,color:this.hexToRgba("#FF0000",.1*s)},{offset:1,color:this.hexToRgba("#FF0000",0)}]);this.ctx.fillStyle=l,this.ctx.beginPath(),this.ctx.arc(e,t,o,0,2*Math.PI),this.ctx.fill()}renderDropShadow(e,t,i,s){const{ctx:n}=this,a=this.shapeMorpher&&this.shapeMorpher.isTransitioning;if(!(this.shapeMorpher&&(this.shapeMorpher.audioDeformation>.1||this.shapeMorpher.vocalEnergy>.1)||a&&!(this.shapeMorpher.morphProgress>.8))){n.save(),n.translate(e,t);const a=this.scaleValue(2);if(n.translate(0,a),s&&s.length>32)n.fillStyle="rgba(0, 0, 0, 0.15)",n.beginPath(),n.arc(0,0,1.05*i,0,2*Math.PI),n.fill();else{const e=n.createRadialGradient(0,0,.7*i,0,0,1.2*i);if(e.addColorStop(0,"rgba(0, 0, 0, 0.2)"),e.addColorStop(.8,"rgba(0, 0, 0, 0.1)"),e.addColorStop(1,"rgba(0, 0, 0, 0)"),n.fillStyle=e,n.beginPath(),s){const e=1.1,t=s.length>20?2:1;n.moveTo(s[0].x*e,s[0].y*e);for(let i=t;i<s.length;i+=t)n.lineTo(s[i].x*e,s[i].y*e);n.closePath()}else n.arc(0,0,1.1*i,0,2*Math.PI);n.fill()}n.restore()}}renderSunEffects(e,t,i,s){return this.celestialRenderer.renderSunEffects(this.ctx,e,t,i,s)}renderBaileysBeads(e,t,i,s,n,a,r,o){return this.celestialRenderer.renderBaileysBeads(this.ctx,e,t,i,s,n,a,r,o,this.scaleValue.bind(this))}renderMoonShadow(e,t,i,s,n,a=!1,r=0){return this.celestialRenderer.renderMoonShadow(this.ctx,e,t,i,s,n,a,r,this.shapeMorpher)}renderSpeakingRings(e,t,i,s){return this.specialEffects.renderSpeakingRings(e,t,i,s)}renderRecordingIndicator(e,t){return this.specialEffects.renderRecordingIndicator(e,t)}renderSleepIndicator(e,t,i){return this.sleepManager.renderSleepIndicator(e,t,i)}updateTimers(e){this.timerCoordinator.updateTimers(e)}applyUndertoneModifiers(e){this.emotionalStateManager.applyUndertoneModifiers(e)}applyUndertoneToColor(e,t){return this.colorUtilities.applyUndertoneToColor(e,t)}hexToRgb(e){return this.colorUtilities.hexToRgb(e)}rgbToHsl(e,t,i){return this.colorUtilities.rgbToHsl(e,t,i)}hslToHex(e,t,i){return this.colorUtilities.hslToHex(e,t,i)}hexToRgba(e,t=1){const i=this.hexToRgb(e);return i?`rgba(${i.r}, ${i.g}, ${i.b}, ${t})`:`rgba(255, 255, 255, ${t})`}startColorTransition(e,t,i=1500){this.colorUtilities.currentColor=this.state.glowColor,this.colorUtilities.currentIntensity=this.state.glowIntensity,this.colorUtilities.startColorTransition(e,t,i),this.colorTransition=this.colorUtilities.colorTransition}updateColorTransition(e){const t=this.colorUtilities.updateColorTransition(e);t&&(this.state.glowColor=t.color,this.state.glowIntensity=t.intensity,this.colorTransition=this.colorUtilities.colorTransition)}updateUndertone(e){this.emotionalStateManager.updateUndertone(e)}setEmotionalState(e,t,i=null){this.emotionalStateManager.setEmotionalState(e,t,i)}setBPM(e){}setRotationSpeed(e){this.rotationManager.setRotationSpeed(e)}setRotationAngle(e){this.rotationManager.setRotationAngle(e)}setGazeOffset(e){this.gazeInputHandler.setGazeOffset(e)}getCurrentOrbPosition(){return this.gazeInputHandler.getCurrentOrbPosition()}setCustomScale(e){this.state.customScale=e}startSpeaking(){this.state.speaking=!0,this.speakingRings=[],this.ringSpawnTimer=0}stopSpeaking(){this.state.speaking=!1,this.speakingRings=[]}enterSleepMode(){this.sleepManager.enterSleepMode()}wakeUp(){this.sleepManager.wakeUp()}startRecording(){this.state.recording=!0}stopRecording(){this.state.recording=!1}setBlinkingEnabled(e){this.state.blinkingEnabled=e,e||(this.state.blinking=!1,this.eyeRenderer.blinking=!1,this.eyeRenderer.blinkTimer=0)}setGazeTracking(e){this.gazeTracker.setEnabled(e)}initGazeTracking(){this._deprecationWarned_initGazeTracking||(this._deprecationWarned_initGazeTracking=!0,console.warn("[EmotiveRenderer] initGazeTracking() is deprecated. Use gazeTracker.initialize() directly.")),this.gazeTracker.initialize()}cleanupGazeTracking(){this._deprecationWarned_cleanupGazeTracking||(this._deprecationWarned_cleanupGazeTracking=!0,console.warn("[EmotiveRenderer] cleanupGazeTracking() is deprecated. Use gazeTracker.cleanup() directly.")),this.gazeTracker.cleanup()}resetCanvasContext(){this.canvasContextManager.resetCanvasContext()}setQualityLevel(e){this.canvasContextManager.setQualityLevel(e)}setQualityReduction(e){this.canvasContextManager.setQualityReduction(e)}handleContextRecovery(e){this.canvasContextManager.handleContextRecovery(e)}getUndertoneModifier(){return this.stateMachine&&this.stateMachine.getWeightedUndertoneModifiers?this.stateMachine.getWeightedUndertoneModifiers():this.currentUndertone&&this.undertoneModifiers[this.currentUndertone]?this.undertoneModifiers[this.currentUndertone]:null}applyGestureAnimations(){return this.gestureAnimator.applyGestureAnimations()}startGesture(e){return this.gestureAnimator.startGesture(e)}getCurrentGesture(){return this.gestureAnimator.getCurrentGesture()}_createGestureDelegates(){["Bounce","Pulse","Shake","Spin","Nod","Tilt","Expand","Contract","Flash","Drift","Stretch","Glow","Flicker","Vibrate","Orbital","Hula","Wave","Breathe","Morph","SlowBlink","Look","Settle","BreathIn","BreathOut","BreathHold","BreathHoldEmpty","Jump","Sway","Float","Rain","RunningMan","Charleston","Sparkle","Shimmer","Wiggle","Groove","Point","Lean","Reach","HeadBob","Orbit"].forEach(e=>{const t=`start${e}`;this[t]=()=>this.gestureAnimator[t]()})}startGrooveSway(e){this.ambientDanceAnimator.startAmbientAnimation("grooveSway",e)}startGrooveBob(e){this.ambientDanceAnimator.startAmbientAnimation("grooveBob",e)}startGrooveFlow(e){this.ambientDanceAnimator.startAmbientAnimation("grooveFlow",e)}startGroovePulse(e){this.ambientDanceAnimator.startAmbientAnimation("groovePulse",e)}startGrooveStep(e){this.ambientDanceAnimator.startAmbientAnimation("grooveStep",e)}stopAllGestures(){this.gestureAnimator.stopAllGestures(),this.currentGesture=null}isGestureActive(){return Object.values(this.gestureAnimator.gestureAnimations).some(e=>e.active)}destroy(){this.resourceCleanupManager.destroy()}}class ba{constructor(e,t={}){this.canvas=e,this.config={smoothing:t.smoothing||.1,maxOffset:t.maxOffset||.3,lockDistance:t.lockDistance||30,enabled:!1!==t.enabled,boundaryPadding:t.boundaryPadding||.8},this.canvasCenter={x:0,y:0},this.mousePos={x:0,y:0},this.targetGaze={x:0,y:0},this.currentGaze={x:0,y:0},this.isLocked=!1,this.proximity=0,this.cachedRect=null,this.touches=new Map,this.primaryTouch=null,this.handleMouseMove=this.handleMouseMove.bind(this),this.handleMouseLeave=this.handleMouseLeave.bind(this),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.onInteraction=null,this.updateCanvasCenter(),this.attachEventListeners(),"undefined"!=typeof ResizeObserver&&(this.resizeObserver=new ResizeObserver(()=>{this.updateCanvasCenter()}),this.resizeObserver.observe(this.canvas))}updateCanvasCenter(){this.cachedRect=this.canvas.getBoundingClientRect(),this.canvasCenter={x:this.cachedRect.width/2,y:this.cachedRect.height/2},0===this.mousePos.x&&0===this.mousePos.y&&(this.mousePos={x:this.canvasCenter.x,y:this.canvasCenter.y})}attachEventListeners(){this.config.enabled&&(this.canvas.addEventListener("mousemove",this.handleMouseMove),this.canvas.addEventListener("mouseleave",this.handleMouseLeave),this.canvas.addEventListener("touchstart",this.handleTouchStart,{passive:!0}),this.canvas.addEventListener("touchmove",this.handleTouchMove,{passive:!0}),this.canvas.addEventListener("touchend",this.handleTouchEnd,{passive:!0}),this.canvas.addEventListener("touchcancel",this.handleTouchEnd,{passive:!0}))}handleMouseMove(e){const t=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:e.clientX-t.left,y:e.clientY-t.top},this.updateTargetGaze(),this.onInteraction&&this.onInteraction("mouse")}handleMouseLeave(){this.targetGaze={x:0,y:0},this.isLocked=!1,this.proximity=0,this.mousePos={x:this.canvasCenter.x,y:this.canvasCenter.y}}handleTouchStart(e){for(const t of e.changedTouches)this.touches.set(t.identifier,{x:t.clientX,y:t.clientY}),this.primaryTouch||1!==this.touches.size||(this.primaryTouch=t.identifier);null!==this.primaryTouch&&this.updateTouchPosition(e.touches)}handleTouchMove(e){for(const t of e.changedTouches)this.touches.has(t.identifier)&&this.touches.set(t.identifier,{x:t.clientX,y:t.clientY});null!==this.primaryTouch&&(this.updateTouchPosition(e.touches),this.onInteraction&&this.onInteraction("touch"))}handleTouchEnd(e){for(const t of e.changedTouches)this.touches.delete(t.identifier),t.identifier===this.primaryTouch&&(this.primaryTouch=null,this.touches.size>0?this.primaryTouch=this.touches.keys().next().value:this.handleMouseLeave())}updateTouchPosition(e){for(const t of e)if(t.identifier===this.primaryTouch){const e=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:t.clientX-e.left,y:t.clientY-e.top},this.updateTargetGaze();break}}updateTargetGaze(){const e=this.mousePos.x-this.canvasCenter.x,t=this.mousePos.y-this.canvasCenter.y,i=Math.sqrt(e*e+t*t),s=Math.min(this.canvasCenter.x,this.canvasCenter.y);if(this.proximity=Math.max(0,1-i/s),this.isLocked=i<this.config.lockDistance,this.isLocked)this.targetGaze={x:e*this.config.maxOffset*2,y:t*this.config.maxOffset*2};else{const n=Math.min(this.canvasCenter.x,this.canvasCenter.y)*this.config.maxOffset;if(i>0){const a=Math.min(1,i/s);this.targetGaze={x:e/i*n*a*this.config.boundaryPadding,y:t/i*n*a*this.config.boundaryPadding}}else this.targetGaze={x:0,y:0}}}update(e){if(!this.config.enabled)return;const t=1-Math.pow(1-this.config.smoothing,e/16.67);if(this.currentGaze.x+=(this.targetGaze.x-this.currentGaze.x)*t,this.currentGaze.y+=(this.targetGaze.y-this.currentGaze.y)*t,this.isLocked){const e=.5;this.currentGaze.x+=(Math.random()-.5)*e,this.currentGaze.y+=(Math.random()-.5)*e}}getGazeOffset(e){return{x:this.currentGaze.x,y:this.currentGaze.y}}getState(){return{gaze:{...this.currentGaze},target:{...this.targetGaze},proximity:this.proximity,isLocked:this.isLocked,isActive:this.config.enabled}}enable(){this.config.enabled||(this.config.enabled=!0,this.attachEventListeners())}disable(){this.config.enabled&&(this.config.enabled=!1,this.detachEventListeners(),this.targetGaze={x:0,y:0})}detachEventListeners(){this.canvas.removeEventListener("mousemove",this.handleMouseMove),this.canvas.removeEventListener("mouseleave",this.handleMouseLeave),this.canvas.removeEventListener("touchstart",this.handleTouchStart),this.canvas.removeEventListener("touchmove",this.handleTouchMove),this.canvas.removeEventListener("touchend",this.handleTouchEnd),this.canvas.removeEventListener("touchcancel",this.handleTouchEnd)}setInteractionCallback(e){this.onInteraction=e}destroy(){this.detachEventListeners(),this.resizeObserver&&this.resizeObserver.disconnect(),this.touches.clear()}}class va{constructor(e={}){this.config={blinkInterval:e.blinkInterval||{min:3e3,max:7e3},blinkDuration:e.blinkDuration||150,swayInterval:e.swayInterval||{min:2e4,max:4e4},swayDuration:e.swayDuration||4e3,swayIntensity:e.swayIntensity||1.5,sleepTimeout:void 0!==e.sleepTimeout?e.sleepTimeout:1/0,breathingSpeed:e.breathingSpeed||.25,breathingDepth:e.breathingDepth||.1,enabled:!1!==e.enabled},this.state={isBlinking:!1,isSwaying:!1,isAsleep:!1,breathingPhase:0,breathRate:1,breathDepth:this.config.breathingDepth},this.timers={idle:0,blink:0,sway:0,swayProgress:0,nextBlink:this.getRandomInterval("blink"),nextSway:this.getRandomInterval("sway")},this.swayOffset={x:0,y:0},this.swayTarget={x:0,y:0},this.swayStart={x:0,y:0},this.wakeUpTimeout=null,this.callbacks={onBlink:null,onSway:null,onSleep:null,onWake:null}}update(e){this.config.enabled&&(this.updateBreathing(e),this.timers.idle+=e,!this.state.isAsleep&&this.timers.idle>=this.config.sleepTimeout&&this.enterSleep(),this.state.isAsleep||this.updateBlinking(e),this.state.isAsleep||this.updateSwaying(e))}updateBreathing(e){const t=this.config.breathingSpeed*this.state.breathRate;this.state.breathingPhase+=t*e/1e3,this.state.breathingPhase>2*Math.PI&&(this.state.breathingPhase-=2*Math.PI)}updateBlinking(e){this.isBlinkingEnabled()&&(this.state.isBlinking?(this.timers.blink+=e,this.timers.blink>=this.config.blinkDuration&&this.endBlink()):(this.timers.blink+=e,this.timers.blink>=this.timers.nextBlink&&this.startBlink()))}updateSwaying(e){if(this.state.isSwaying){this.timers.sway+=e;const t=Math.min(this.timers.sway/this.config.swayDuration,1),i=(Math.sin((t-.5)*Math.PI)+1)/2;this.swayOffset.x=this.swayStart.x+(this.swayTarget.x-this.swayStart.x)*i,this.swayOffset.y=this.swayStart.y+(this.swayTarget.y-this.swayStart.y)*i,t>=1&&this.endSway()}else this.timers.sway+=e,this.timers.sway>=this.timers.nextSway&&this.startSway()}startBlink(){this.state.isBlinking=!0,this.timers.blink=0,this.callbacks.onBlink&&this.callbacks.onBlink({phase:"start"})}endBlink(){this.state.isBlinking=!1,this.timers.blink=0,this.timers.nextBlink=this.getRandomInterval("blink"),this.callbacks.onBlink&&this.callbacks.onBlink({phase:"end"})}startSway(){this.state.isSwaying=!0,this.timers.sway=0,this.swayStart={...this.swayOffset};const e=Math.random()*Math.PI*2,t=this.config.swayIntensity*(.5+.5*Math.random());this.swayTarget={x:Math.cos(e)*t*1.5,y:Math.sin(e)*t*.5},this.callbacks.onSway&&this.callbacks.onSway({phase:"start",offset:this.swayOffset})}endSway(){this.state.isSwaying=!1,this.timers.sway=0,this.timers.nextSway=this.getRandomInterval("sway"),this.swayStart={...this.swayOffset},this.callbacks.onSway&&this.callbacks.onSway({phase:"end",offset:this.swayOffset})}enterSleep(){this.state.isAsleep=!0,this.state.breathRate=.5,this.state.breathDepth=.15,this.state.isBlinking&&(this.state.isBlinking=!1,this.timers.blink=0,this.callbacks.onBlink&&this.callbacks.onBlink({phase:"end"})),this.callbacks.onSleep&&this.callbacks.onSleep()}wakeUp(){this.state.isAsleep&&(this.state.isAsleep=!1,this.state.breathRate=1,this.state.breathDepth=this.config.breathingDepth,this.timers.idle=0,this.callbacks.onWake&&this.callbacks.onWake(),this.performWakeAnimation())}performWakeAnimation(){const e={x:.5*this.config.swayIntensity,y:-this.config.swayIntensity};this.swayStart={...this.swayOffset},this.swayTarget=e,this.state.isSwaying=!0,this.timers.sway=0,this.callbacks.onSway&&this.callbacks.onSway({phase:"wake",offset:this.swayOffset}),this.wakeUpTimeout&&clearTimeout(this.wakeUpTimeout),this.wakeUpTimeout=setTimeout(()=>{this.swayStart={...this.swayOffset},this.swayTarget={x:0,y:0},this.timers.sway=0,this.wakeUpTimeout=null},1e3)}resetIdleTimer(){this.timers.idle=0,this.state.isAsleep&&this.wakeUp()}setBlinkingEnabled(e){this.config.blinkingEnabled=e,!e&&this.state.isBlinking&&this.endBlink()}isBlinkingEnabled(){return!1!==this.config.blinkingEnabled}getBreathingFactor(){return 1+Math.sin(this.state.breathingPhase)*this.state.breathDepth*this.state.breathRate}getBlinkProgress(){return this.state.isBlinking?Math.min(this.timers.blink/this.config.blinkDuration,1):0}getSwayOffset(){return this.swayOffset||{x:0,y:0}}getRandomInterval(e){const t=this.config[`${e}Interval`];return t.min+Math.random()*(t.max-t.min)}setCallback(e,t){({}).hasOwnProperty.call(this.callbacks,e)&&(this.callbacks[e]=t)}getState(){return{...this.state,breathingFactor:this.getBreathingFactor(),blinkProgress:this.getBlinkProgress(),swayOffset:this.getSwayOffset()}}enable(){this.config.enabled=!0}disable(){this.config.enabled=!1,this.state.isBlinking=!1,this.state.isSwaying=!1,this.swayOffset={x:0,y:0}}destroy(){this.wakeUpTimeout&&(clearTimeout(this.wakeUpTimeout),this.wakeUpTimeout=null),this.callbacks={onBlink:null,onSway:null,onSleep:null,onWake:null}}}var Ma=Object.freeze({__proto__:null,default:va});class wa{constructor(e){this.positionController=e,this.watchedElements=new Map,this.updateCallbacks=new Map}moveToElement(e,t="right",i={x:20,y:0},s={}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=n.getBoundingClientRect(),r=a.left+a.width/2,o=a.top+a.height/2;let l,h;switch(t){case"right":default:l=a.right+i.x,h=o+i.y;break;case"left":l=a.left-i.x,h=o+i.y;break;case"above":l=r+i.x,h=a.top-i.y;break;case"below":l=r+i.x,h=a.bottom+i.y;break;case"center":l=r+i.x,h=o+i.y}const c=l-window.innerWidth/2,u=h-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(c,u,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(c,u,0)}moveToButton(e="button",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToForm(e="form",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToModal(e='[role="dialog"], .modal',t="center",i={x:0,y:0}){this.moveToElement(e,t,i)}moveToNavigation(e="nav, .navigation",t="below",i={x:0,y:20}){this.moveToElement(e,t,i)}moveToContent(e="main, .content",t="center",i={x:0,y:0}){this.moveToElement(e,t,i)}moveToSidebar(e=".sidebar, aside",t="right",i={x:20,y:0}){this.moveToElement(e,t,i)}moveToHeader(e="header, .header",t="below",i={x:0,y:20}){this.moveToElement(e,t,i)}moveToFooter(e="footer, .footer",t="above",i={x:0,y:20}){this.moveToElement(e,t,i)}watchElement(e,t="right",i={x:20,y:0}){const s=()=>{this.moveToElement(e,t,i,{animate:!1})},n=`${e}-${t}-${JSON.stringify(i)}`;return this.updateCallbacks.set(n,s),window.addEventListener("scroll",s),window.addEventListener("resize",s),s(),()=>{window.removeEventListener("scroll",s),window.removeEventListener("resize",s),this.updateCallbacks.delete(n)}}stopWatchingAll(){this.updateCallbacks.forEach(e=>{window.removeEventListener("scroll",e),window.removeEventListener("resize",e)}),this.updateCallbacks.clear()}destroy(){this.stopWatchingAll(),this.positionController=null}}class Sa extends wa{constructor(e){super(e),this.activeCallbacks=new Map,this.callbackStates=new Map}moveToElementWithCallback(e,t,i="right",s={x:20,y:0},n={}){const a=`callback-${Date.now()}-${Math.random()}`,r=document.querySelector(e);if(!r)return void console.warn(`Element not found: ${e}`);this.callbackStates.set(a,{executed:!1,element:r,callback:t,options:n}),this.moveToElement(e,i,s,n);const o=()=>{if(this.isMascotNearElement(r,n.proximity||50)){const e=this.callbackStates.get(a);e&&!e.executed&&(e.executed=!0,t(),n.repeat||this.callbackStates.delete(a))}this.callbackStates.has(a)&&requestAnimationFrame(o)};return this.activeCallbacks.set(a,o),o(),()=>{this.activeCallbacks.delete(a),this.callbackStates.delete(a)}}moveToElementSequence(e=[],t={}){let i=0;const s=[],n=()=>{if(i>=e.length)return void(t.onComplete&&t.onComplete());const a=e[i],r=this.moveToElementWithCallback(a.selector,()=>{a.callback&&a.callback(),i++,setTimeout(n,a.delay||0)},a.position||"right",a.offset||{x:20,y:0},{...t,...a.options});r&&s.push(r)};return n(),()=>{s.forEach(e=>e())}}moveToElementWithDelay(e,t,i=1e3,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,()=>{setTimeout(t,i)},s,n)}moveToElementWithCondition(e,t,i,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,()=>{t()&&i()},s,n)}moveToElementWithRepeat(e,t,i=1e3,s="right",n={x:20,y:0}){let a=null;const r=this.moveToElementWithCallback(e,()=>{a=setInterval(t,i)},s,n,{repeat:!0});return()=>{null!==a&&(clearInterval(a),a=null),r&&r()}}moveToElementWithProximity(e,t,i=100,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(e,t,s,n,{proximity:i})}isMascotNearElement(e,t=50){if(!this.positionController||!e)return!1;const i=e.getBoundingClientRect(),s=i.left+i.width/2,n=i.top+i.height/2,a=this.positionController.getOffset(),r=a.x+window.innerWidth/2,o=a.y+window.innerHeight/2;return Math.sqrt(Math.pow(r-s,2)+Math.pow(o-n,2))<=t}stopAllCallbacks(){this.activeCallbacks.forEach((e,t)=>{this.activeCallbacks.delete(t)}),this.callbackStates.clear()}destroy(){this.stopAllCallbacks(),super.destroy()}}class xa extends wa{constructor(e){super(e),this.activePaths=new Map,this.obstacles=new Set,this.audioContext=null,this.audioAnalyser=null,this.gazeTracker=null,this.activeRAFIds=new Set,this.activeSmoothAnimations=new Set}moveToElementWithPath(e,t=[],i="right",s={x:20,y:0},n={}){const a=`path-${Date.now()}-${Math.random()}`,r=document.querySelector(e);if(!r)return void console.warn(`Element not found: ${e}`);const o=window.innerWidth||1,l=window.innerHeight||1,h=o/2,c=l/2,u=n.coordinateSystem||"auto",d=Array.isArray(t)?t.map((e={})=>{const t="number"==typeof e.x?e.x:0,i="number"==typeof e.y?e.y:0;return"relative"===u||"auto"===u&&t>=0&&t<=1&&i>=0&&i<=1?{x:t*o-h,y:i*l-c}:"offset"===u||"auto"===u&&Math.abs(t)<=h&&Math.abs(i)<=c?{x:t,y:i}:{x:t-h,y:i-c}}):[],g=r.getBoundingClientRect(),m={x:g.left+g.width/2+s.x-h,y:g.top+g.height/2+s.y-c},p=this.positionController.getOffset?this.positionController.getOffset():{x:0,y:0},f=[{x:"number"==typeof p.x?p.x:0,y:"number"==typeof p.y?p.y:0},...d,m];if(f.length<2)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const y=[],b=[0];let v=0;for(let e=0;e<f.length-1;e++){const t=f[e+1].x-f[e].x,i=f[e+1].y-f[e].y,s=Math.hypot(t,i);y.push(s),v+=s,b.push(v)}if(0===v)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const M="number"==typeof n.speed&&n.speed>0?n.speed:250,w=!0===n.loop,S=n.easing||"linear",x={covered:0,lastTimestamp:null},C=e=>{if(w)e%=v;else{if(e<=0)return f[0];if(e>=v)return f[f.length-1]}for(let t=0;t<y.length;t++){const i=b[t];if(e<=b[t+1]){const s=y[t]||1,n=0===s?0:(e-i)/s,a=this.positionController&&"function"==typeof this.positionController.applyEasing?this.positionController.applyEasing(n,S):n,r=f[t],o=f[t+1];return{x:r.x+(o.x-r.x)*a,y:r.y+(o.y-r.y)*a}}}return f[f.length-1]},k={stop:()=>{k.frameId&&cancelAnimationFrame(k.frameId),this.activePaths.delete(a)},frameId:null};this.activePaths.set(a,k),this.positionController.setOffset(f[0].x,f[0].y,0);const P=e=>{if(!this.activePaths.has(a))return;null===x.lastTimestamp&&(x.lastTimestamp=e);const t=e-x.lastTimestamp;if(x.lastTimestamp=e,x.covered+=M*(t/1e3),!w&&x.covered>=v)return this.positionController.setOffset(m.x,m.y,0),k.stop(),void("function"==typeof n.onComplete&&n.onComplete());const i=C(x.covered);this.positionController.setOffset(i.x,i.y,0),k.frameId=requestAnimationFrame(P)};return k.frameId=requestAnimationFrame(P),()=>{k.stop()}}moveToElementWithEasing(e,t,i=1e3,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=a.getBoundingClientRect(),o=r.left+r.width/2+n.x-window.innerWidth/2,l=r.top+r.height/2+n.y-window.innerHeight/2,h=this.positionController.getOffset(),c=performance.now();let u=null;const d=e=>{const s=e-c,n=Math.min(s/i,1),a=t(n),r=h.x+(o-h.x)*a,g=h.y+(l-h.y)*a;this.positionController.setOffset(r,g,0),n<1?(u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)):null!==u&&this.activeSmoothAnimations.delete(u)};u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)}moveToElementWithCollision(e,t=[],i=100,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=a.getBoundingClientRect(),o=r.left+r.width/2+n.x-window.innerWidth/2,l=r.top+r.height/2+n.y-window.innerHeight/2,h=this.positionController.getOffset();(()=>{let e=h.x,s=h.y;for(let n=0;n<=100;n++){const a=.01*n,r=h.x+(o-h.x)*a,c=h.y+(l-h.y)*a;let u=!1;t.forEach(t=>{let n,a;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();n=t.left+t.width/2-window.innerWidth/2,a=t.top+t.height/2-window.innerHeight/2}}else n=t.x-window.innerWidth/2,a=t.y-window.innerHeight/2;if(Math.sqrt(Math.pow(r-n,2)+Math.pow(c-a,2))<i){u=!0;const t=Math.atan2(c-a,r-n),o=n+Math.cos(t)*i,l=a+Math.sin(t)*i;e=o,s=l}}),u||(e=r,s=c)}this.positionController.setOffset(e,s,0)})()}moveToElementWithAudio(e,t,i=50,s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256),this.audioContext.createMediaStreamSource(t).connect(this.audioAnalyser);const r=new Uint8Array(this.audioAnalyser.frequencyBinCount),o=a.getBoundingClientRect(),l=o.left+o.width/2+n.x-window.innerWidth/2,h=o.top+o.height/2+n.y-window.innerHeight/2;let c=null;const u=()=>{this.audioAnalyser.getByteFrequencyData(r);let e=0;for(let t=0;t<r.length;t++)e+=r[t];const t=e/r.length/255*i,s=l+t,n=h+.5*t;this.positionController.setOffset(s,n,0),null!==c&&this.activeRAFIds.delete(c),c=requestAnimationFrame(u),this.activeRAFIds.add(c)};u()}moveToElementWithGaze(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);this.gazeTracker||(this.gazeTracker={x:window.innerWidth/2,y:window.innerHeight/2});const a=n.getBoundingClientRect(),r=a.left+a.width/2+s.x-window.innerWidth/2,o=a.top+a.height/2+s.y-window.innerHeight/2;let l=null;const h=()=>{const e=this.gazeTracker.x-window.innerWidth/2,i=this.gazeTracker.y-window.innerHeight/2,s=t.gazeWeight||.3,n=r+(e-r)*s,a=o+(i-o)*s;this.positionController.setOffset(n,a,0),null!==l&&this.activeRAFIds.delete(l),l=requestAnimationFrame(h),this.activeRAFIds.add(l)};h()}addObstacle(e){this.obstacles.add(e)}removeObstacle(e){this.obstacles.delete(e)}clearObstacles(){this.obstacles.clear()}destroy(){Array.from(this.activePaths.values()).forEach(e=>{e&&"function"==typeof e.stop?e.stop():e&&e.frameId&&cancelAnimationFrame(e.frameId)}),this.activePaths.clear(),this.activeRAFIds.forEach(e=>{cancelAnimationFrame(e)}),this.activeRAFIds.clear(),this.activeSmoothAnimations.forEach(e=>{cancelAnimationFrame(e)}),this.activeSmoothAnimations.clear(),this.obstacles.clear(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.audioAnalyser=null,this.gazeTracker=null,super.destroy()}}class Ca extends wa{constructor(e){super(e),this.scrollCallbacks=new Map,this.physicsSimulations=new Map,this.responsiveBreakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.accessibilityEnabled=!1}moveToElementWithScroll(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`scroll-${Date.now()}-${Math.random()}`,{startScroll:r=50,endScroll:o=300,onProgress:l=null,onStart:h=null,onComplete:c=null}=t;let u=!1,d=!1;const g=()=>{const{scrollY:e}=window,t=Math.min(Math.max((e-r)/(o-r),0),1);t>0&&!u&&(u=!0,h&&h()),t>=1&&!d&&(d=!0,c&&c());const i=n.getBoundingClientRect(),a=i.left+i.width/2+s.x-window.innerWidth/2,g=i.top+i.height/2+s.y-window.innerHeight/2,m=window.innerWidth>1024,p=m?.25*window.innerWidth:.33*window.innerWidth-50,f=m?-.25*window.innerHeight-50+.15*window.innerHeight:-.35*window.innerHeight-50+.08*window.innerHeight,y=p+(a-p)*t,b=f+(g-f)*t;this.positionController.setOffset(y,b,0),l&&l(t,{scrollY:e,currentX:y,currentY:b})};return this.scrollCallbacks.set(a,g),window.addEventListener("scroll",g),g(),()=>{this.scrollCallbacks.delete(a),window.removeEventListener("scroll",g)}}moveToElementWithPhysics(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`physics-${Date.now()}-${Math.random()}`,{mass:r=1,damping:o=.98,springConstant:l=.1,maxVelocity:h=10,onUpdate:c=null}=t,u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x-window.innerWidth/2,g=u.top+u.height/2+s.y-window.innerHeight/2,m=this.positionController.getOffset();let p=m.x,f=m.y,y=0,b=0;const v=()=>{y+=(d-p)*l/r,b+=(g-f)*l/r,y*=o,b*=o;const e=Math.sqrt(y*y+b*b);e>h&&(y=y/e*h,b=b/e*h),p+=y,f+=b,this.positionController.setOffset(p,f,0),c&&c({positionX:p,positionY:f,velocityX:y,velocityY:b}),this.physicsSimulations.has(a)&&requestAnimationFrame(v)};return this.physicsSimulations.set(a,v),v(),()=>{this.physicsSimulations.delete(a)}}moveToElementWithGroup(e=[],t="center",i={x:0,y:0}){if(0===e.length)return void console.warn("No element selectors provided");let s=0,n=0,a=0,r=0,o=0;if(e.forEach(e=>{const t=document.querySelector(e);if(t){const e=t.getBoundingClientRect();s+=e.left,n+=e.top,a=Math.max(a,e.left+e.width),r=Math.max(r,e.top+e.height),o++}}),0===o)return;const l=s/o,h=n/o;let c,u;switch(t){case"center":default:c=l+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"left":c=s+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"right":c=a+i.x-window.innerWidth/2,u=h+i.y-window.innerHeight/2;break;case"top":c=l+i.x-window.innerWidth/2,u=n+i.y-window.innerHeight/2;break;case"bottom":c=l+i.x-window.innerWidth/2,u=r+i.y-window.innerHeight/2}this.positionController.setOffset(c,u,0)}moveToElementWithResponsive(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=()=>{const e=this.getCurrentBreakpoint(),i=t[e]||t.default||{},a=n.getBoundingClientRect(),r=a.left+a.width/2+(i.offsetX||s.x)-window.innerWidth/2,o=a.top+a.height/2+(i.offsetY||s.y)-window.innerHeight/2;this.positionController.setOffset(r,o,0)},r=()=>{const e=this.getCurrentBreakpoint();e!==this.currentBreakpoint&&(this.currentBreakpoint=e,a())};return window.addEventListener("resize",r),a(),()=>{window.removeEventListener("resize",r)}}moveToElementWithAccessibility(e,t={},i="right",s={x:20,y:0}){if(!document.querySelector(e))return void console.warn(`Element not found: ${e}`);const{announce:n=!0,announcements:a=[],screenReaderPosition:r="bottom-right"}=t;let o,l;switch(r){case"bottom-right":default:o=window.innerWidth-100-window.innerWidth/2,l=window.innerHeight-100-window.innerHeight/2;break;case"bottom-left":o=100-window.innerWidth/2,l=window.innerHeight-100-window.innerHeight/2;break;case"top-right":o=window.innerWidth-100-window.innerWidth/2,l=100-window.innerHeight/2;break;case"top-left":o=100-window.innerWidth/2,l=100-window.innerHeight/2}this.positionController.setOffset(o,l,0),n&&window.speechSynthesis&&a.forEach(e=>{if(e.condition&&e.condition()){const t=new SpeechSynthesisUtterance(e.text);t.volume=.5,t.rate=.8,window.speechSynthesis.speak(t)}})}getCurrentBreakpoint(){const e=window.innerWidth;return e<this.responsiveBreakpoints.mobile?"mobile":e<this.responsiveBreakpoints.tablet?"tablet":e<this.responsiveBreakpoints.desktop?"desktop":"large"}setBreakpoints(e){this.responsiveBreakpoints={...this.responsiveBreakpoints,...e},this.currentBreakpoint=this.getCurrentBreakpoint()}enableAccessibility(){this.accessibilityEnabled=!0}disableAccessibility(){this.accessibilityEnabled=!1}destroy(){this.scrollCallbacks.forEach((e,t)=>{window.removeEventListener("scroll",e)}),this.scrollCallbacks.clear(),this.physicsSimulations.clear(),super.destroy()}}class ka extends wa{constructor(e){super(e),this.activeInteractions=new Map,this.hoverStates=new Map,this.clickStates=new Map,this.touchStates=new Map}moveToElementWithHover(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`hover-${Date.now()}-${Math.random()}`,{onMouseEnter:r=null,onMouseLeave:o=null,onHover:l=null,followMouse:h=!1,hoverDistance:c=50}=t;let u=!1,d=0,g=0;const m=e=>{u=!0,r&&r(e)},p=e=>{u=!1,o&&o(e)},f=e=>{if(d=e.clientX,g=e.clientY,u&&l&&l(e),h&&u){const e=n.getBoundingClientRect(),t=e.left+e.width/2,i=e.top+e.height/2;if(Math.sqrt(Math.pow(d-t,2)+Math.pow(g-i,2))<=c){const e=d+s.x-window.innerWidth/2,t=g+s.y-window.innerHeight/2;this.positionController.setOffset(e,t,0)}}};return n.addEventListener("mouseenter",m),n.addEventListener("mouseleave",p),n.addEventListener("mousemove",f),this.activeInteractions.set(a,{element:n,events:[{event:"mouseenter",handler:m},{event:"mouseleave",handler:p},{event:"mousemove",handler:f}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithClick(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`click-${Date.now()}-${Math.random()}`,{onClick:r=null,onDoubleClick:o=null,maxClicks:l=3}=t;let h=0;const c=e=>{if(h++,r&&r(e,h),h>=l){const e=n.getBoundingClientRect(),t=e.left+e.width/2+s.x-window.innerWidth/2,i=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(t,i,0)}},u=e=>{o&&o(e)};return n.addEventListener("click",c),n.addEventListener("dblclick",u),this.activeInteractions.set(a,{element:n,events:[{event:"click",handler:c},{event:"dblclick",handler:u}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithTouch(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`touch-${Date.now()}-${Math.random()}`,{onTouchStart:r=null,onTouchMove:o=null,onTouchEnd:l=null,onSwipe:h=null,swipeThreshold:c=50}=t;let u=0,d=0,g=0,m=0;const p=e=>{e.touches.length>0&&(u=e.touches[0].clientX,d=e.touches[0].clientY,r&&r(e))},f=e=>{if(e.touches.length>0){const t=e.touches[0].clientX,i=e.touches[0].clientY;o&&o(e);const n=t+s.x-window.innerWidth/2,a=i+s.y-window.innerHeight/2;this.positionController.setOffset(n,a,0)}},y=e=>{if(e.changedTouches.length>0){g=e.changedTouches[0].clientX,m=e.changedTouches[0].clientY,l&&l(e);const t=g-u,i=m-d,s=Math.sqrt(t*t+i*i);if(s>c&&h){const e=Math.abs(t)>Math.abs(i)?t>0?"right":"left":i>0?"down":"up";h(e,s)}}};return n.addEventListener("touchstart",p),n.addEventListener("touchmove",f),n.addEventListener("touchend",y),this.activeInteractions.set(a,{element:n,events:[{event:"touchstart",handler:p},{event:"touchmove",handler:f},{event:"touchend",handler:y}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithFocus(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`focus-${Date.now()}-${Math.random()}`,{onFocus:r=null,onBlur:o=null,onFocusIn:l=null,onFocusOut:h=null}=t,c=e=>{r&&r(e);const t=n.getBoundingClientRect(),i=t.left+t.width/2+s.x-window.innerWidth/2,a=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(i,a,0)},u=e=>{o&&o(e)},d=e=>{l&&l(e)},g=e=>{h&&h(e)};return n.addEventListener("focus",c),n.addEventListener("blur",u),n.addEventListener("focusin",d),n.addEventListener("focusout",g),this.activeInteractions.set(a,{element:n,events:[{event:"focus",handler:c},{event:"blur",handler:u},{event:"focusin",handler:d},{event:"focusout",handler:g}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}moveToElementWithKeyboard(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`keyboard-${Date.now()}-${Math.random()}`,{onKeyDown:r=null,onKeyUp:o=null,onKeyPress:l=null,targetKeys:h=["Enter","Space"]}=t,c=e=>{if(r&&r(e),h.includes(e.key)){const e=n.getBoundingClientRect(),t=e.left+e.width/2+s.x-window.innerWidth/2,i=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(t,i,0)}},u=e=>{o&&o(e)},d=e=>{l&&l(e)};return n.addEventListener("keydown",c),n.addEventListener("keyup",u),n.addEventListener("keypress",d),this.activeInteractions.set(a,{element:n,events:[{event:"keydown",handler:c},{event:"keyup",handler:u},{event:"keypress",handler:d}]}),()=>{const e=this.activeInteractions.get(a);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(a))}}stopAllInteractions(){this.activeInteractions.forEach((e,t)=>{e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.activeInteractions.delete(t)}),this.hoverStates.clear(),this.clickStates.clear(),this.touchStates.clear()}destroy(){this.stopAllInteractions(),super.destroy()}}class Pa extends wa{constructor(e){super(e),this.activeAnimations=new Map,this.animationQueue=[],this.isAnimating=!1,this.queueTimeouts=new Set,this.activeRAFIds=new Set,this.animationRAFIds=new Map}moveToElementWithBounce(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`bounce-${Date.now()}-${Math.random()}`,{duration:r=1e3,intensity:o=50,bounces:l=3,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=this.positionController.getOffset(),m=performance.now(),p=e=>{const t=e-m,i=Math.min(t/r,1),s=1-Math.pow(1-i,3),n=Math.sin(s*Math.PI*l)*o*(1-i),c=g.x+(u-g.x)*i,f=g.y+(d-g.y)*i+n;if(this.positionController.setOffset(c,f,0),i<1){this.activeAnimations.set(a,p);const e=requestAnimationFrame(p);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,p);const f=requestAnimationFrame(p);return this.activeRAFIds.add(f),this.animationRAFIds.set(a,f),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithShake(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`shake-${Date.now()}-${Math.random()}`,{duration:r=500,intensity:o=10,frequency:l=20,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=(Math.random()-.5)*o*(1-i),n=(Math.random()-.5)*o*(1-i),c=u+s,p=d+n;if(this.positionController.setOffset(c,p,0),i<1)this.activeAnimations.set(a,m),setTimeout(()=>{const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)},1e3/l);else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithPulse(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`pulse-${Date.now()}-${Math.random()}`,{duration:r=2e3,intensity:o=20,frequency:l=2,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=Math.sin(t*l*.01)*o*(1-i),n=u+s,c=d+s;if(this.positionController.setOffset(n,c,0),i<1){this.activeAnimations.set(a,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithWiggle(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`wiggle-${Date.now()}-${Math.random()}`,{duration:r=1e3,intensity:o=15,frequency:l=8,onComplete:h=null}=t,c=n.getBoundingClientRect(),u=c.left+c.width/2+s.x-window.innerWidth/2,d=c.top+c.height/2+s.y-window.innerHeight/2,g=performance.now(),m=e=>{const t=e-g,i=Math.min(t/r,1),s=Math.sin(t*l*.01)*o*(1-i),n=Math.cos(t*l*.01)*o*(1-i),c=u+s,p=d+n;if(this.positionController.setOffset(c,p,0),i<1){this.activeAnimations.set(a,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(a,e)}else{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(a,p),()=>{this.activeAnimations.delete(a);const e=this.animationRAFIds.get(a);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(a))}}moveToElementWithCustom(e,t,i={},s="right",n={x:20,y:0}){const a=document.querySelector(e);if(!a)return void console.warn(`Element not found: ${e}`);const r=`custom-${Date.now()}-${Math.random()}`,{duration:o=1e3,onComplete:l=null}=i,h=a.getBoundingClientRect(),c=h.left+h.width/2+n.x-window.innerWidth/2,u=h.top+h.height/2+n.y-window.innerHeight/2,d=this.positionController.getOffset(),g=performance.now(),m=e=>{const i=e-g,s=Math.min(i/o,1),n=t(s,{elapsed:i,startOffset:d,targetX:c,targetY:u,currentTime:e});if(n&&"object"==typeof n){const e=void 0!==n.x?n.x:c,t=void 0!==n.y?n.y:u;this.positionController.setOffset(e,t,0)}if(s<1){this.activeAnimations.set(r,m);const e=requestAnimationFrame(m);this.activeRAFIds.add(e),this.animationRAFIds.set(r,e)}else{this.activeAnimations.delete(r);const e=this.animationRAFIds.get(r);void 0!==e&&(this.activeRAFIds.delete(e),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const p=requestAnimationFrame(m);return this.activeRAFIds.add(p),this.animationRAFIds.set(r,p),()=>{this.activeAnimations.delete(r);const e=this.animationRAFIds.get(r);void 0!==e&&(cancelAnimationFrame(e),this.activeRAFIds.delete(e),this.animationRAFIds.delete(r))}}queueAnimations(e=[]){this.animationQueue=[...this.animationQueue,...e],this.processAnimationQueue()}processAnimationQueue(){if(this.isAnimating||0===this.animationQueue.length)return;this.isAnimating=!0;const e=this.animationQueue.shift();if(e){const t=this.executeAnimation(e);if(t){const i=setTimeout(()=>{this.queueTimeouts.delete(i),t(),this.isAnimating=!1,this.processAnimationQueue()},e.duration||1e3);this.queueTimeouts.add(i)}}}executeAnimation(e){const{type:t,targetSelector:i,options:s={},position:n="right",offset:a={x:20,y:0}}=e;switch(t){case"bounce":return this.moveToElementWithBounce(i,s,n,a);case"shake":return this.moveToElementWithShake(i,s,n,a);case"pulse":return this.moveToElementWithPulse(i,s,n,a);case"wiggle":return this.moveToElementWithWiggle(i,s,n,a);case"custom":return this.moveToElementWithCustom(i,s.animationFunction,s,n,a);default:return this.moveToElement(i,n,a)}}stopAllAnimations(){this.activeAnimations.forEach((e,t)=>{this.activeAnimations.delete(t)}),this.activeRAFIds.forEach(e=>cancelAnimationFrame(e)),this.activeRAFIds.clear(),this.animationRAFIds.clear(),this.queueTimeouts.forEach(e=>clearTimeout(e)),this.queueTimeouts.clear(),this.animationQueue=[],this.isAnimating=!1}destroy(){this.stopAllAnimations(),super.destroy()}}class Ta extends wa{constructor(e){super(e),this.activeEffects=new Map,this.trailPoints=[],this.particles=[],this.effectCanvas=null,this.effectContext=null,this.maxTrailPoints=50,this.maxParticles=100}moveToElementWithTrail(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`trail-${Date.now()}-${Math.random()}`,{color:r="#00ff88",width:o=3,opacity:l=.8,fadeSpeed:h=.95,onComplete:c=null}=t;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,g=u.top+u.height/2+s.y,m=this.positionController.getOffset(),p=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),b=e=>{const t=e-y,i=Math.min(t/1e3,1),s=p+(d-p)*i,n=f+(g-f)*i;this.trailPoints.push({x:s,y:n,opacity:l*(1-i),timestamp:e}),this.trailPoints.length>this.maxTrailPoints&&this.trailPoints.shift(),this.trailPoints.forEach(e=>{e.opacity*=h}),this.trailPoints=this.trailPoints.filter(e=>e.opacity>.01),this.drawTrail(r,o),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(a,b),requestAnimationFrame(b)):(this.activeEffects.delete(a),c&&c())};return this.activeEffects.set(a,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(a)}}moveToElementWithParticles(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`particles-${Date.now()}-${Math.random()}`,{count:r=20,color:o="#00ff88",size:l=2,speed:h=2,life:c=1e3,onComplete:u=null}=t;this.initializeEffectCanvas();const d=n.getBoundingClientRect(),g=d.left+d.width/2+s.x,m=d.top+d.height/2+s.y,p=this.positionController.getOffset(),f=p.x+window.innerWidth/2,y=p.y+window.innerHeight/2,b=performance.now();for(let e=0;e<r;e++)this.particles.push({x:f,y:y,vx:(Math.random()-.5)*h,vy:(Math.random()-.5)*h,life:c,maxLife:c,color:o,size:l});const v=e=>{const t=e-b,i=Math.min(t/1e3,1);this.particles.forEach(e=>{e.x+=e.vx,e.y+=e.vy,e.life-=16,e.opacity=e.life/e.maxLife}),this.particles=this.particles.filter(e=>e.life>0),this.drawParticles();const s=f+(g-f)*i,n=y+(m-y)*i;this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1||this.particles.length>0?(this.activeEffects.set(a,v),requestAnimationFrame(v)):(this.activeEffects.delete(a),u&&u())};return this.activeEffects.set(a,v),requestAnimationFrame(v),()=>{this.activeEffects.delete(a)}}moveToElementWithGlow(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const a=`glow-${Date.now()}-${Math.random()}`,{color:r="#00ff88",intensity:o=50,radius:l=100,duration:h=1e3,onComplete:c=null}=t;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,g=u.top+u.height/2+s.y,m=this.positionController.getOffset(),p=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),b=e=>{const t=e-y,i=Math.min(t/h,1),s=p+(d-p)*i,n=f+(g-f)*i;this.drawGlow(s,n,r,o,l,i),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(a,b),requestAnimationFrame(b)):(this.activeEffects.delete(a),c&&c())};return this.activeEffects.set(a,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(a)}}initializeEffectCanvas(){this.effectCanvas||(this.effectCanvas=document.createElement("canvas"),this.effectCanvas.style.position="fixed",this.effectCanvas.style.top="0",this.effectCanvas.style.left="0",this.effectCanvas.style.width="100%",this.effectCanvas.style.height="100%",this.effectCanvas.style.pointerEvents="none",this.effectCanvas.style.zIndex="1000",document.body.appendChild(this.effectCanvas),this.effectContext=this.effectCanvas.getContext("2d"),this.resizeEffectCanvas())}resizeEffectCanvas(){this.effectCanvas&&(this.effectCanvas.width=window.innerWidth,this.effectCanvas.height=window.innerHeight)}drawTrail(e,t){if(this.effectContext&&!(this.trailPoints.length<2)){this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.effectContext.strokeStyle=e,this.effectContext.lineWidth=t,this.effectContext.lineCap="round",this.effectContext.lineJoin="round",this.effectContext.beginPath(),this.effectContext.moveTo(this.trailPoints[0].x,this.trailPoints[0].y);for(let e=1;e<this.trailPoints.length;e++){const t=this.trailPoints[e];this.effectContext.globalAlpha=t.opacity,this.effectContext.lineTo(t.x,t.y)}this.effectContext.stroke(),this.effectContext.globalAlpha=1}}drawParticles(){this.effectContext&&(this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.particles.forEach(e=>{this.effectContext.globalAlpha=e.opacity,this.effectContext.fillStyle=e.color,this.effectContext.beginPath(),this.effectContext.arc(e.x,e.y,e.size,0,2*Math.PI),this.effectContext.fill()}),this.effectContext.globalAlpha=1)}drawGlow(e,t,i,s,n,a){if(!this.effectContext)return;this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height);const r=this.effectContext.createRadialGradient(e,t,0,e,t,n),o=Math.floor(s*a).toString(16).padStart(2,"0"),l=i.startsWith("#")?i:`#${i}`;r.addColorStop(0,`${l}${o}`),r.addColorStop(1,`${l}00`),this.effectContext.fillStyle=r,this.effectContext.beginPath(),this.effectContext.arc(e,t,n,0,2*Math.PI),this.effectContext.fill()}stopAllEffects(){this.activeEffects.forEach((e,t)=>{this.activeEffects.delete(t)}),this.trailPoints=[],this.particles=[]}destroy(){this.stopAllEffects(),this.effectCanvas&&(document.body.removeChild(this.effectCanvas),this.effectCanvas=null,this.effectContext=null),super.destroy()}}class Ea extends wa{constructor(e){super(e),this.accessibilityOptions={screenReader:!0,keyboardNavigation:!0,highContrast:!1,reducedMotion:!1,announcements:!0},this.announcements=[],this.keyboardListeners=new Map,this.focusableElements=new Set,this.currentFocusIndex=0,this.focusOrder=[]}moveToElementWithScreenReader(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{announce:a=!0,announcement:r="Mascot moved to element",role:o="button",label:l=n.textContent||n.alt||"Interactive element"}=t;this.moveToElement(e,i,s),a&&this.accessibilityOptions.screenReader&&this.announceToScreenReader(r),n&&(n.setAttribute("role",o),n.setAttribute("aria-label",l),n.setAttribute("aria-live","polite"))}moveToElementWithKeyboard(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{onKeyDown:a=null,onKeyUp:r=null,onEnter:o=null,onEscape:l=null,onArrowKeys:h=null}=t,c=`keyboard-${Date.now()}-${Math.random()}`,u=e=>{switch(a&&a(e),e.key){case"Enter":case" ":o&&o(e);break;case"Escape":l&&l(e);break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":h&&h(e)}},d=e=>{r&&r(e)};return n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),n.addEventListener("keydown",u),n.addEventListener("keyup",d),this.keyboardListeners.set(c,{element:n,events:[{event:"keydown",handler:u},{event:"keyup",handler:d}]}),this.moveToElement(e,i,s),()=>{const e=this.keyboardListeners.get(c);e&&(e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)}),this.keyboardListeners.delete(c))}}moveToElementWithHighContrast(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{backgroundColor:a="#000000",textColor:r="#ffffff",borderColor:o="#ffffff",borderWidth:l=2}=t;this.accessibilityOptions.highContrast&&(n.style.backgroundColor=a,n.style.color=r,n.style.border=`${l}px solid ${o}`,n.style.outline=`${l}px solid ${o}`),this.moveToElement(e,i,s)}moveToElementWithReducedMotion(e,t={},i="right",s={x:20,y:0}){if(!document.querySelector(e))return void console.warn(`Element not found: ${e}`);const{duration:n=0,easing:a="linear"}=t;window.matchMedia("(prefers-reduced-motion: reduce)").matches||this.accessibilityOptions.reducedMotion?this.moveToElement(e,i,s):this.moveToElement(e,i,s,{duration:n,easing:a})}moveToElementWithFocus(e,t={},i="right",s={x:20,y:0}){const n=document.querySelector(e);if(!n)return void console.warn(`Element not found: ${e}`);const{autoFocus:a=!1,focusRing:r=!0,focusOrder:o=[]}=t;o.length>0?this.focusOrder=o:this.focusOrder.includes(e)||this.focusOrder.push(e),n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),r&&(n.style.outline="2px solid #0066cc",n.style.outlineOffset="2px"),a&&n.focus(),this.moveToElement(e,i,s)}navigateFocus(e="next"){if(0===this.focusOrder.length)return;this.currentFocusIndex="next"===e?(this.currentFocusIndex+1)%this.focusOrder.length:(this.currentFocusIndex-1+this.focusOrder.length)%this.focusOrder.length;const t=this.focusOrder[this.currentFocusIndex],i=document.querySelector(t);i&&(i.focus(),this.moveToElement(t,"right",{x:20,y:0}))}announceToScreenReader(e){if(!this.accessibilityOptions.announcements)return;let t=document.getElementById("mascot-live-region");t||(t=document.createElement("div"),t.id="mascot-live-region",t.setAttribute("aria-live","polite"),t.setAttribute("aria-atomic","true"),t.style.position="absolute",t.style.left="-10000px",t.style.width="1px",t.style.height="1px",t.style.overflow="hidden",document.body.appendChild(t)),t.textContent=e,setTimeout(()=>{t.textContent=""},1e3)}enableAccessibility(e={}){this.accessibilityOptions={...this.accessibilityOptions,...e}}disableAccessibility(e={}){Object.keys(e).forEach(e=>{({}).hasOwnProperty.call(this.accessibilityOptions,e)&&(this.accessibilityOptions[e]=!1)})}isAccessibilityEnabled(e){return this.accessibilityOptions[e]||!1}getAccessibilityOptions(){return{...this.accessibilityOptions}}destroy(){this.keyboardListeners.forEach((e,t)=>{e.events.forEach(({event:t,handler:i})=>{e.element.removeEventListener(t,i)})}),this.keyboardListeners.clear();const e=document.getElementById("mascot-live-region");e&&document.body.removeChild(e),this.focusOrder=[],this.currentFocusIndex=0,super.destroy()}}class Aa{constructor(e){this.positionController=e,this.callbacks=new Sa(e),this.advanced=new xa(e),this.context=new Ca(e),this.interactions=new ka(e),this.animations=new Pa(e),this.effects=new Ta(e),this.accessibility=new Ea(e)}moveToElementWithCallback(...e){return this.callbacks.moveToElementWithCallback(...e)}moveToElementSequence(...e){return this.callbacks.moveToElementSequence(...e)}moveToElementWithDelay(...e){return this.callbacks.moveToElementWithDelay(...e)}moveToElementWithCondition(...e){return this.callbacks.moveToElementWithCondition(...e)}moveToElementWithRepeat(...e){return this.callbacks.moveToElementWithRepeat(...e)}moveToElementWithProximity(...e){return this.callbacks.moveToElementWithProximity(...e)}moveToElementWithPath(...e){return this.advanced.moveToElementWithPath(...e)}moveToElementWithEasing(...e){return this.advanced.moveToElementWithEasing(...e)}moveToElementWithCollision(...e){return this.advanced.moveToElementWithCollision(...e)}moveToElementWithAudio(...e){return this.advanced.moveToElementWithAudio(...e)}moveToElementWithGaze(...e){return this.advanced.moveToElementWithGaze(...e)}moveToElementWithScroll(...e){return this.context.moveToElementWithScroll(...e)}moveToElementWithPhysics(...e){return this.context.moveToElementWithPhysics(...e)}moveToElementWithGroup(...e){return this.context.moveToElementWithGroup(...e)}moveToElementWithResponsive(...e){return this.context.moveToElementWithResponsive(...e)}moveToElementWithAccessibility(...e){return this.context.moveToElementWithAccessibility(...e)}moveToElementWithHover(...e){return this.interactions.moveToElementWithHover(...e)}moveToElementWithClick(...e){return this.interactions.moveToElementWithClick(...e)}moveToElementWithTouch(...e){return this.interactions.moveToElementWithTouch(...e)}moveToElementWithFocus(...e){return this.interactions.moveToElementWithFocus(...e)}moveToElementWithKeyboard(...e){return this.interactions.moveToElementWithKeyboard(...e)}moveToElementWithBounce(...e){return this.animations.moveToElementWithBounce(...e)}moveToElementWithShake(...e){return this.animations.moveToElementWithShake(...e)}moveToElementWithPulse(...e){return this.animations.moveToElementWithPulse(...e)}moveToElementWithWiggle(...e){return this.animations.moveToElementWithWiggle(...e)}moveToElementWithCustom(...e){return this.animations.moveToElementWithCustom(...e)}moveToElementWithTrail(...e){return this.effects.moveToElementWithTrail(...e)}moveToElementWithParticles(...e){return this.effects.moveToElementWithParticles(...e)}moveToElementWithGlow(...e){return this.effects.moveToElementWithGlow(...e)}moveToElementWithScreenReader(...e){return this.accessibility.moveToElementWithScreenReader(...e)}moveToElementWithKeyboardAccessible(...e){return this.accessibility.moveToElementWithKeyboard(...e)}moveToElementWithHighContrast(...e){return this.accessibility.moveToElementWithHighContrast(...e)}moveToElementWithReducedMotion(...e){return this.accessibility.moveToElementWithReducedMotion(...e)}moveToElementWithFocusAccessible(...e){return this.accessibility.moveToElementWithFocus(...e)}announceToScreenReader(...e){return this.accessibility.announceToScreenReader(...e)}navigateFocus(...e){return this.accessibility.navigateFocus(...e)}enableAccessibility(...e){return this.accessibility.enableAccessibility(...e)}disableAccessibility(...e){return this.accessibility.disableAccessibility(...e)}destroy(){this.callbacks.destroy(),this.advanced.destroy(),this.context.destroy(),this.interactions.destroy(),this.animations.destroy(),this.effects.destroy(),this.accessibility.destroy()}}class Da{constructor(e){this.positionController=e,this.isTracking=!1,this.trackingCallbacks=new Map,this.audioContext=null,this.audioAnalyser=null,this.audioData=null}moveToMouse(e={x:20,y:20},t={}){const i="mouse-tracking",s=i=>{const s=i.clientX+e.x,n=i.clientY+e.y,a=s-window.innerWidth/2,r=n-window.innerHeight/2;!1!==t.smooth?this.positionController.animateOffset(a,r,0,t.duration||200,"easeOutQuad"):this.positionController.setOffset(a,r,0)};return this.trackingCallbacks.set(i,s),window.addEventListener("mousemove",s),()=>{window.removeEventListener("mousemove",s),this.trackingCallbacks.delete(i)}}moveToTouch(e={x:20,y:20},t={}){const i="touch-tracking",s=i=>{if(i.touches.length>0){const s=i.touches[0],n=s.clientX+e.x,a=s.clientY+e.y,r=n-window.innerWidth/2,o=a-window.innerHeight/2;!1!==t.smooth?this.positionController.animateOffset(r,o,0,t.duration||200,"easeOutQuad"):this.positionController.setOffset(r,o,0)}};return this.trackingCallbacks.set(i,s),window.addEventListener("touchmove",s),()=>{window.removeEventListener("touchmove",s),this.trackingCallbacks.delete(i)}}moveToAudio(e=0,t=50,i={}){if(this.audioContext||this.initAudioContext(),!this.audioContext||!this.audioAnalyser)return void console.warn("Audio context not available");const s="audio-tracking",n=()=>{if(!this.isTracking)return;this.audioAnalyser.getByteFrequencyData(this.audioData);let e=0;for(let t=0;t<this.audioData.length;t++)e+=this.audioData[t];const s=e/this.audioData.length/255*t,a=(i.centerX||0)+s,r=(i.centerY||0)+.5*s,o=a-window.innerWidth/2,l=r-window.innerHeight/2;this.positionController.setOffset(o,l,0),this.isTracking&&requestAnimationFrame(n)};return this.trackingCallbacks.set(s,n),this.isTracking=!0,n(),()=>{this.isTracking=!1,this.trackingCallbacks.delete(s)}}initAudioContext(){try{this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256,this.audioData=new Uint8Array(this.audioAnalyser.frequencyBinCount)}catch(e){console.warn("Failed to initialize audio context:",e)}}connectAudioSource(e){this.audioContext&&this.audioAnalyser||this.initAudioContext(),this.audioContext&&this.audioAnalyser&&this.audioContext.createMediaStreamSource(e).connect(this.audioAnalyser)}moveToViewport(e="right",t={x:20,y:20}){let i,s;switch(e){case"top":i=window.innerWidth/2,s=t.y;break;case"bottom":i=window.innerWidth/2,s=window.innerHeight-t.y;break;case"left":i=t.x,s=window.innerHeight/2;break;case"right":default:i=window.innerWidth-t.x,s=window.innerHeight/2;break;case"top-left":i=t.x,s=t.y;break;case"top-right":i=window.innerWidth-t.x,s=t.y;break;case"bottom-left":i=t.x,s=window.innerHeight-t.y;break;case"bottom-right":i=window.innerWidth-t.x,s=window.innerHeight-t.y}const n=i-window.innerWidth/2,a=s-window.innerHeight/2;this.positionController.setOffset(n,a,0)}stopAllTracking(){this.trackingCallbacks.forEach((e,t)=>{"mouse-tracking"===t?window.removeEventListener("mousemove",e):"touch-tracking"===t&&window.removeEventListener("touchmove",e)}),this.trackingCallbacks.clear(),this.isTracking=!1}destroy(){this.stopAllTracking(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.positionController=null}}class _a{constructor(e){this.positionController=e,this.isRunning=!1,this.physicsCallbacks=new Map,this.velocity={x:0,y:0},this.acceleration={x:0,y:0},this.lastTime=0}moveToGrid(e,t,i={x:0,y:0},s={}){const n=s.gridSize||100,a=e*n+i.x,r=t*n+i.y,o=a-window.innerWidth/2,l=r-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(o,l,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(o,l,0)}moveToGravity(e={x:0,y:0},t=.1,i={}){const s="gravity",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y,o=e.x-n,l=e.y-r,h=Math.sqrt(o*o+l*l);if(h>0){const e=t/(h*h);this.acceleration.x=o/h*e,this.acceleration.y=l/h*e,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const s=i.damping||.98;this.velocity.x*=s,this.velocity.y*=s;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToMagnetic(e=[],t=.05,i={}){const s="magnetic",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y;let o=0,l=0;e.forEach(e=>{let i,s;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();i=e.left+e.width/2-window.innerWidth/2,s=e.top+e.height/2-window.innerHeight/2}}else{if(void 0===e.x||void 0===e.y)return;i=e.x-window.innerWidth/2,s=e.y-window.innerHeight/2}const a=i-n,h=s-r,c=Math.sqrt(a*a+h*h);if(c>0){const e=t/(c*c);o+=a/c*e,l+=h/c*e}}),this.acceleration.x=o,this.acceleration.y=l,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const h=i.damping||.95;this.velocity.x*=h,this.velocity.y*=h;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToAvoid(e=[],t=100,i={}){const s="avoid",n=s=>{if(!this.isRunning)return;const a=s-this.lastTime;if(this.lastTime=s,a>0){const s=this.positionController.getOffset(),n=s.x,r=s.y;let o=0,l=0;e.forEach(e=>{let i,s;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();i=e.left+e.width/2-window.innerWidth/2,s=e.top+e.height/2-window.innerHeight/2}}else{if(void 0===e.x||void 0===e.y)return;i=e.x-window.innerWidth/2,s=e.y-window.innerHeight/2}const a=n-i,h=r-s,c=Math.sqrt(a*a+h*h);if(c<t&&c>0){const e=(t-c)/t;o+=a/c*e,l+=h/c*e}}),this.acceleration.x=o,this.acceleration.y=l,this.velocity.x+=this.acceleration.x*a,this.velocity.y+=this.acceleration.y*a;const h=i.damping||.9;this.velocity.x*=h,this.velocity.y*=h;const c=n+this.velocity.x*a,u=r+this.velocity.y*a;this.positionController.setOffset(c,u,0)}this.isRunning&&requestAnimationFrame(n)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,this.lastTime=performance.now(),n(this.lastTime),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}moveToRandom(e={x:0,y:0,width:400,height:400},t=3e3,i={}){const s="random",n=()=>{if(!this.isRunning)return;const s=e.x+Math.random()*e.width,a=e.y+Math.random()*e.height,r=s-window.innerWidth/2,o=a-window.innerHeight/2;!1!==i.animate?this.positionController.animateOffset(r,o,0,i.duration||1e3,i.easing||"easeOutCubic"):this.positionController.setOffset(r,o,0),this.isRunning&&setTimeout(n,t)};return this.physicsCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.physicsCallbacks.delete(s)}}stopAllPhysics(){this.isRunning=!1,this.physicsCallbacks.clear(),this.velocity={x:0,y:0},this.acceleration={x:0,y:0}}destroy(){this.stopAllPhysics(),this.positionController=null}}class Ia{constructor(e){this.positionController=e,this.isRunning=!1,this.animationCallbacks=new Map,this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}moveToPath(e=[],t=1,i={}){if(e.length<2)return void console.warn("Path requires at least 2 points");const s="path",n=!1!==i.loop,a=i.reverse||!1,r=o=>{if(!this.isRunning)return;const l=o-(this.lastTime||o);if(this.lastTime=o,l>0){this.pathProgress+=t*l/1e3,this.pathProgress=n?this.pathProgress%e.length:Math.min(this.pathProgress,e.length-1);const r=Math.floor(this.pathProgress),o=this.pathProgress-r;let h,c;a?(h=e[e.length-1-r],c=e[e.length-2-r]||e[0]):(h=e[r],c=e[r+1]||e[0]);const u=h.x+(c.x-h.x)*o,d=h.y+(c.y-h.y)*o,g=u-window.innerWidth/2,m=d-window.innerHeight/2;if(this.positionController.setOffset(g,m,0),!n&&this.pathProgress>=e.length-1)return this.isRunning=!1,this.animationCallbacks.delete(s),void(i.onComplete&&i.onComplete())}this.isRunning&&requestAnimationFrame(r)};return this.animationCallbacks.set(s,r),this.isRunning=!0,this.lastTime=performance.now(),r(this.lastTime),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToTime(e=2e3,t="easeInOutCubic",i={}){const s="time",n=performance.now(),a=this.positionController.getOffset(),r=i.target||{x:0,y:0},o=l=>{if(!this.isRunning)return;const h=l-n,c=Math.min(h/e,1),u=this.applyEasing(c,t),d=a.x+(r.x-a.x)*u,g=a.y+(r.y-a.y)*u;this.positionController.setOffset(d,g,0),c>=1?(this.isRunning=!1,this.animationCallbacks.delete(s),i.onComplete&&i.onComplete()):requestAnimationFrame(o)};return this.animationCallbacks.set(s,o),this.isRunning=!0,o(n),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToScroll(e=0,t={x:0,y:0},i={}){const s="scroll",n=()=>{if(!this.isRunning)return;const s=window.innerWidth,n=window.innerHeight;let a,r;if("horizontal"===i.direction)a=e*s+t.x,r=n/2+t.y;else if("vertical"===i.direction)a=s/2+t.x,r=e*n+t.y;else{const o=e*Math.PI*2,l=i.radius||Math.min(s,n)/4;a=s/2+Math.cos(o)*l+t.x,r=n/2+Math.sin(o)*l+t.y}const o=a-s/2,l=r-n/2;this.positionController.setOffset(o,l,0)};return this.animationCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}animateTo(e,t,i=1e3,s="easeOutCubic"){this.positionController.animateOffset(e,t,0,i,s)}applyEasing(e,t){switch(t){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return 1-(1-e)*(1-e);case"easeInOutQuad":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"easeInCubic":return e*e*e;case"easeOutCubic":return 1-Math.pow(1-e,3);case"easeInOutCubic":return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;case"easeInBack":{const t=1.70158;return(t+1)*e*e*e-t*e*e}case"easeOutBack":{const t=1.70158;return 1+(t+1)*Math.pow(e-1,3)+t*Math.pow(e-1,2)}case"easeInElastic":return 0===e?0:1===e?1:-Math.pow(2,10*e-10)*Math.sin((10*e-10.75)*(2*Math.PI/3));case"easeOutElastic":return 0===e?0:1===e?1:Math.pow(2,-10*e)*Math.sin((10*e-.75)*(2*Math.PI/3))+1}}stopAllAnimations(){this.isRunning=!1,this.animationCallbacks.clear(),this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}destroy(){this.stopAllAnimations(),this.positionController=null}}class Ra{constructor(e){this.positionController=e,this.breakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.responsiveCallbacks=new Map}getCurrentBreakpoint(){const e=window.innerWidth;return e<this.breakpoints.mobile?"mobile":e<this.breakpoints.tablet?"tablet":e<this.breakpoints.desktop?"desktop":"large"}moveToResponsive(e={},t={}){const i="responsive",s=()=>{if(!this.isRunning)return;const i=this.getCurrentBreakpoint(),s=e[i]||e.default||{x:0,y:0},n=s.x-window.innerWidth/2,a=s.y-window.innerHeight/2;!1!==t.animate?this.positionController.animateOffset(n,a,0,t.duration||500,t.easing||"easeOutCubic"):this.positionController.setOffset(n,a,0)};this.responsiveCallbacks.set(i,s),this.isRunning=!0,s();const n=()=>{const e=this.getCurrentBreakpoint();e!==this.currentBreakpoint&&(this.currentBreakpoint=e,s())};return window.addEventListener("resize",n),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(i),window.removeEventListener("resize",n)}}moveToGroup(e=[],t="center",i={x:0,y:0}){if(0===e.length)return;let s=0,n=0,a=0,r=0,o=0;if(e.forEach(e=>{let t,i,l,h;if("string"==typeof e){const s=document.querySelector(e);if(!s)return;{const e=s.getBoundingClientRect();t=e.left,i=e.top,l=e.width,h=e.height}}else{if(void 0===e.x||void 0===e.y)return;t=e.x,i=e.y,l=e.width||0,h=e.height||0}s+=t,n+=i,a=Math.max(a,t+l),r=Math.max(r,i+h),o++}),0===o)return;const l=s/o,h=n/o;let c,u;switch(t){case"center":default:c=l+i.x,u=h+i.y;break;case"left":c=s+i.x,u=h+i.y;break;case"right":c=a+i.x,u=h+i.y;break;case"top":c=l+i.x,u=n+i.y;break;case"bottom":c=l+i.x,u=r+i.y}const d=c-window.innerWidth/2,g=u-window.innerHeight/2;this.positionController.setOffset(d,g,0)}moveToAccessibility(e=[],t="bottom-right",i={}){const s="accessibility",n=()=>{if(!this.isRunning)return;let s,n;switch((window.speechSynthesis||window.webkitSpeechSynthesis)&&i.announce&&e.forEach(e=>{e.condition&&e.condition()&&this.announceToScreenReader(e.text)}),t){case"bottom-right":default:s=window.innerWidth-100,n=window.innerHeight-100;break;case"bottom-left":s=100,n=window.innerHeight-100;break;case"top-right":s=window.innerWidth-100,n=100;break;case"top-left":s=100,n=100;break;case"center":s=window.innerWidth/2,n=window.innerHeight/2}const a=s-window.innerWidth/2,r=n-window.innerHeight/2;this.positionController.setOffset(a,r,0)};return this.responsiveCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(s)}}announceToScreenReader(e){if(window.speechSynthesis){const t=new SpeechSynthesisUtterance(e);t.volume=.5,t.rate=.8,window.speechSynthesis.speak(t)}}setBreakpoints(e){this.breakpoints={...this.breakpoints,...e},this.currentBreakpoint=this.getCurrentBreakpoint()}getCurrentBreakpointName(){return this.currentBreakpoint}isBreakpoint(e){return this.currentBreakpoint===e}stopAllResponsive(){this.isRunning=!1,this.responsiveCallbacks.clear()}destroy(){this.stopAllResponsive(),this.positionController=null}}class Ba{constructor(e){this.positionController=e,this.elementTargeting=new wa(e),this.inputTracking=new Da(e),this.physics=new _a(e),this.animation=new Ia(e),this.responsive=new Ra(e),this.methods=new Map,this.registerMethods()}registerMethods(){this.methods.set("moveToElement",this.elementTargeting.moveToElement.bind(this.elementTargeting)),this.methods.set("moveToButton",this.elementTargeting.moveToButton.bind(this.elementTargeting)),this.methods.set("moveToForm",this.elementTargeting.moveToForm.bind(this.elementTargeting)),this.methods.set("moveToModal",this.elementTargeting.moveToModal.bind(this.elementTargeting)),this.methods.set("moveToNavigation",this.elementTargeting.moveToNavigation.bind(this.elementTargeting)),this.methods.set("moveToContent",this.elementTargeting.moveToContent.bind(this.elementTargeting)),this.methods.set("moveToSidebar",this.elementTargeting.moveToSidebar.bind(this.elementTargeting)),this.methods.set("moveToHeader",this.elementTargeting.moveToHeader.bind(this.elementTargeting)),this.methods.set("moveToFooter",this.elementTargeting.moveToFooter.bind(this.elementTargeting)),this.methods.set("watchElement",this.elementTargeting.watchElement.bind(this.elementTargeting)),this.methods.set("moveToMouse",this.inputTracking.moveToMouse.bind(this.inputTracking)),this.methods.set("moveToTouch",this.inputTracking.moveToTouch.bind(this.inputTracking)),this.methods.set("moveToAudio",this.inputTracking.moveToAudio.bind(this.inputTracking)),this.methods.set("moveToViewport",this.inputTracking.moveToViewport.bind(this.inputTracking)),this.methods.set("moveToGrid",this.physics.moveToGrid.bind(this.physics)),this.methods.set("moveToGravity",this.physics.moveToGravity.bind(this.physics)),this.methods.set("moveToMagnetic",this.physics.moveToMagnetic.bind(this.physics)),this.methods.set("moveToAvoid",this.physics.moveToAvoid.bind(this.physics)),this.methods.set("moveToRandom",this.physics.moveToRandom.bind(this.physics)),this.methods.set("moveToPath",this.animation.moveToPath.bind(this.animation)),this.methods.set("moveToTime",this.animation.moveToTime.bind(this.animation)),this.methods.set("moveToScroll",this.animation.moveToScroll.bind(this.animation)),this.methods.set("animateTo",this.animation.animateTo.bind(this.animation)),this.methods.set("moveToResponsive",this.responsive.moveToResponsive.bind(this.responsive)),this.methods.set("moveToGroup",this.responsive.moveToGroup.bind(this.responsive)),this.methods.set("moveToAccessibility",this.responsive.moveToAccessibility.bind(this.responsive))}call(e,...t){const i=this.methods.get(e);return i?i(...t):(console.warn(`Positioning method not found: ${e}`),null)}getAvailableMethods(){return Array.from(this.methods.keys())}hasMethod(e){return this.methods.has(e)}stopAll(){this.elementTargeting.stopWatchingAll(),this.inputTracking.stopAllTracking(),this.physics.stopAllPhysics(),this.animation.stopAllAnimations(),this.responsive.stopAllResponsive()}destroy(){this.stopAll(),this.elementTargeting.destroy(),this.inputTracking.destroy(),this.physics.destroy(),this.animation.destroy(),this.responsive.destroy(),this.methods.clear(),this.positionController=null}}class za{constructor(e={}){this.offsetX=e.offsetX||0,this.offsetY=e.offsetY||0,this.offsetZ=e.offsetZ||0,this.isAnimating=!1,this.animationId=null,this.animationStartTime=0,this.animationDuration=0,this.animationEasing="easeOutCubic",this.startOffset={x:0,y:0,z:0},this.targetOffset={x:0,y:0,z:0},this.onUpdate=e.onUpdate||(()=>{}),this.onAnimationComplete=e.onAnimationComplete||(()=>{}),this.minScale=e.minScale||.5,this.maxScale=e.maxScale||2,this.zScaleRange=e.zScaleRange||1e3,this.globalScale=1,this.coreScaleOverride=1,this.particleScaleOverride=1,this.positioning=new Ba(this),this.elementTargeting=new Aa(this)}setOffset(e,t,i=0){this.stopAnimation(),this.offsetX=e,this.offsetY=t,this.offsetZ=i,this.onUpdate(this.getEffectiveCenter())}getOffset(){return{x:this.offsetX,y:this.offsetY,z:this.offsetZ}}getPosition(e=window.innerWidth/2,t=window.innerHeight/2){return{x:e+this.offsetX,y:t+this.offsetY,z:this.offsetZ,scale:this.getZScale()}}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){this.stopAnimation(),this.startOffset={x:this.offsetX,y:this.offsetY,z:this.offsetZ},this.targetOffset={x:e,y:t,z:i},this.animationDuration=s,this.animationEasing=n,this.animationStartTime=performance.now(),this.isAnimating=!0,this.startAnimation()}stopAnimation(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.isAnimating=!1}startAnimation(){const e=t=>{if(!this.isAnimating)return;const i=t-this.animationStartTime,s=Math.min(i/this.animationDuration,1),n=this.applyEasing(s,this.animationEasing);this.offsetX=this.lerp(this.startOffset.x,this.targetOffset.x,n),this.offsetY=this.lerp(this.startOffset.y,this.targetOffset.y,n),this.offsetZ=this.lerp(this.startOffset.z,this.targetOffset.z,n),this.onUpdate(this.getEffectiveCenter()),s>=1?(this.isAnimating=!1,this.onAnimationComplete()):this.animationId=requestAnimationFrame(e)};this.animationId=requestAnimationFrame(e)}getEffectiveCenter(e=0,t=0){return{x:e+this.offsetX,y:t+this.offsetY,scale:this.getZScale(),coreScale:this.getCoreScale(),particleScale:this.getParticleScale()}}getZScale(){const e=-this.offsetZ/this.zScaleRange,t=Math.max(-1,Math.min(1,e));return this.lerp(this.minScale,this.maxScale,(t+1)/2)*this.globalScale}setGlobalScale(e){this.globalScale=Math.max(.1,e),this.onUpdate(this.getEffectiveCenter())}setScaleOverrides(e){"number"==typeof e?(this.globalScale=Math.max(.1,e),this.coreScaleOverride=1,this.particleScaleOverride=1):(void 0!==e.global&&(this.globalScale=Math.max(.1,e.global)),void 0!==e.core&&(this.coreScaleOverride=Math.max(.1,e.core)),void 0!==e.particles&&(this.particleScaleOverride=Math.max(.1,e.particles))),this.onUpdate(this.getEffectiveCenter())}getCoreScale(){return this.calculateBaseZScale()*this.globalScale*this.coreScaleOverride}getParticleScale(){return this.calculateBaseZScale()*this.globalScale*this.particleScaleOverride}calculateBaseZScale(){const e=-this.offsetZ/this.zScaleRange,t=Math.max(-1,Math.min(1,e));return this.lerp(this.minScale,this.maxScale,(t+1)/2)}lerp(e,t,i){return e+(t-e)*i}applyEasing(e,t){switch(t){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return 1-(1-e)*(1-e);case"easeInOutQuad":return e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;case"easeInCubic":return e*e*e;case"easeOutCubic":return 1-Math.pow(1-e,3);case"easeInOutCubic":return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;case"easeInBack":{const t=1.70158;return(t+1)*e*e*e-t*e*e}case"easeOutBack":{const t=1.70158;return 1+(t+1)*Math.pow(e-1,3)+t*Math.pow(e-1,2)}}}getPositioning(){return this.positioning}getElementTargeting(){return this.elementTargeting}callPositioning(e,...t){return this.positioning.call(e,...t)}destroy(){this.stopAnimation(),this.positioning&&(this.positioning.destroy(),this.positioning=null),this.elementTargeting&&(this.elementTargeting.destroy(),this.elementTargeting=null),this.onUpdate=null,this.onAnimationComplete=null}}class Fa{static _getGestureSoundsMap(){return Fa._GESTURE_SOUNDS_CACHE||(Fa._GESTURE_SOUNDS_CACHE=new Map([["bounce",{duration:100,waveform:"triangle",volume:.3,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:400},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:1},{time:.1,volume:.8},{time:1,volume:0}]}],["pulse",{duration:300,waveform:"sine",volume:.25,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:450},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:1},{time:.7,volume:1},{time:1,volume:0}]}],["shake",{duration:200,waveform:"sawtooth",volume:.2,frequencyEnvelope:[{time:0,frequency:150},{time:.25,frequency:200},{time:.5,frequency:150},{time:.75,frequency:200},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:.8},{time:.5,volume:1},{time:1,volume:0}]}],["spin",{duration:800,waveform:"sine",volume:.18,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:600},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:.5},{time:.5,volume:1},{time:1,volume:0}]}],["breathe",{duration:1500,waveform:"sine",volume:.12,frequencyEnvelope:[{time:0,frequency:150},{time:.5,frequency:180},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:.7},{time:.7,volume:.7},{time:1,volume:0}]}],["morph",{duration:600,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:.3,frequency:400},{time:.7,frequency:300},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:1},{time:.8,volume:.8},{time:1,volume:0}]}],["float",{duration:2e3,waveform:"sine",volume:.15,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.6},{time:.8,volume:.6},{time:1,volume:0}]}],["wobble",{duration:400,waveform:"square",volume:.2,frequencyEnvelope:[{time:0,frequency:180},{time:.25,frequency:220},{time:.5,frequency:180},{time:.75,frequency:220},{time:1,frequency:180}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["wave",{duration:1200,waveform:"sine",volume:.22,frequencyEnvelope:[{time:0,frequency:200},{time:.25,frequency:400},{time:.5,frequency:250},{time:.75,frequency:450},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:1},{time:.8,volume:.9},{time:1,volume:0}]}],["pop",{duration:80,waveform:"triangle",volume:.4,frequencyEnvelope:[{time:0,frequency:500},{time:.3,frequency:300},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:1},{time:.2,volume:.6},{time:1,volume:0}]}],["shimmer",{duration:1e3,waveform:"sine",volume:.16,frequencyEnvelope:[{time:0,frequency:600},{time:.2,frequency:700},{time:.4,frequency:650},{time:.6,frequency:750},{time:.8,frequency:700},{time:1,frequency:600}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.8},{time:.8,volume:.8},{time:1,volume:0}]}],["glitch",{duration:250,waveform:"square",volume:.25,frequencyEnvelope:[{time:0,frequency:100},{time:.2,frequency:800},{time:.4,frequency:200},{time:.6,frequency:600},{time:.8,frequency:300},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:.8},{time:.5,volume:1},{time:1,volume:0}]}],["reach",{duration:500,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:1,frequency:450}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["shrink",{duration:600,waveform:"sine",volume:.18,frequencyEnvelope:[{time:0,frequency:400},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:.9},{time:.5,volume:.6},{time:1,volume:0}]}],["grow",{duration:700,waveform:"sine",volume:.22,frequencyEnvelope:[{time:0,frequency:150},{time:1,frequency:500}],volumeEnvelope:[{time:0,volume:.5},{time:.5,volume:.9},{time:1,volume:0}]}],["drift",{duration:1500,waveform:"sine",volume:.14,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:280},{time:1,frequency:220}],volumeEnvelope:[{time:0,volume:0},{time:.3,volume:.7},{time:.7,volume:.6},{time:1,volume:0}]}],["zoom",{duration:400,waveform:"triangle",volume:.28,frequencyEnvelope:[{time:0,frequency:200},{time:1,frequency:800}],volumeEnvelope:[{time:0,volume:.6},{time:.5,volume:1},{time:1,volume:0}]}],["squish",{duration:300,waveform:"sawtooth",volume:.24,frequencyEnvelope:[{time:0,frequency:350},{time:.5,frequency:120},{time:1,frequency:180}],volumeEnvelope:[{time:0,volume:.9},{time:.3,volume:1},{time:1,volume:0}]}],["stretch",{duration:800,waveform:"sine",volume:.19,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:.6},{time:.4,volume:1},{time:1,volume:0}]}],["snap",{duration:100,waveform:"square",volume:.35,frequencyEnvelope:[{time:0,frequency:600},{time:.5,frequency:300},{time:1,frequency:150}],volumeEnvelope:[{time:0,volume:1},{time:.3,volume:.5},{time:1,volume:0}]}],["ripple",{duration:1e3,waveform:"sine",volume:.17,frequencyEnvelope:[{time:0,frequency:300},{time:.25,frequency:350},{time:.5,frequency:300},{time:.75,frequency:350},{time:1,frequency:300}],volumeEnvelope:[{time:0,volume:.8},{time:.2,volume:1},{time:.8,volume:.7},{time:1,volume:0}]}],["swirl",{duration:1200,waveform:"triangle",volume:.2,frequencyEnvelope:[{time:0,frequency:250},{time:.33,frequency:400},{time:.66,frequency:300},{time:1,frequency:500}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.9},{time:.8,volume:.8},{time:1,volume:0}]}],["explode",{duration:600,waveform:"sawtooth",volume:.3,frequencyEnvelope:[{time:0,frequency:100},{time:.2,frequency:800},{time:1,frequency:50}],volumeEnvelope:[{time:0,volume:1},{time:.3,volume:.8},{time:1,volume:0}]}],["implode",{duration:700,waveform:"sine",volume:.25,frequencyEnvelope:[{time:0,frequency:500},{time:.5,frequency:200},{time:1,frequency:100}],volumeEnvelope:[{time:0,volume:.9},{time:.5,volume:1},{time:1,volume:0}]}],["flutter",{duration:800,waveform:"triangle",volume:.18,frequencyEnvelope:[{time:0,frequency:400},{time:.2,frequency:450},{time:.4,frequency:400},{time:.6,frequency:450},{time:.8,frequency:400},{time:1,frequency:450}],volumeEnvelope:[{time:0,volume:0},{time:.2,volume:.8},{time:.8,volume:.7},{time:1,volume:0}]}],["twist",{duration:500,waveform:"sawtooth",volume:.21,frequencyEnvelope:[{time:0,frequency:200},{time:.5,frequency:400},{time:1,frequency:200}],volumeEnvelope:[{time:0,volume:.7},{time:.5,volume:1},{time:1,volume:0}]}],["blink",{duration:150,waveform:"sine",volume:.15,frequencyEnvelope:[{time:0,frequency:400},{time:.5,frequency:500},{time:1,frequency:400}],volumeEnvelope:[{time:0,volume:0},{time:.5,volume:1},{time:1,volume:0}]}],["glow",{duration:1500,waveform:"sine",volume:.12,frequencyEnvelope:[{time:0,frequency:300},{time:.5,frequency:400},{time:1,frequency:350}],volumeEnvelope:[{time:0,volume:0},{time:.4,volume:.8},{time:.6,volume:.8},{time:1,volume:0}]}],["sparkle",{duration:600,waveform:"sine",volume:.2,frequencyEnvelope:[{time:0,frequency:800},{time:.3,frequency:1e3},{time:.6,frequency:900},{time:1,frequency:700}],volumeEnvelope:[{time:0,volume:.6},{time:.2,frequency:1},{time:.8,volume:.9},{time:1,volume:0}]}]])),Fa._GESTURE_SOUNDS_CACHE}static getSoundConfig(e){return Fa._getGestureSoundsMap().get(e)||null}}class Oa{constructor(e){this._ctx=e,this._layers=new Map,this._masterGain=e.createGain(),this._masterGain.connect(e.destination),this._currentMix={},this._crossfadeId=0,this._isPlaying=!1,this._playOffset=0,this._playStartTime=0,this._emotionMod=null,this._baseBPM=null}async addLayer(e,t){let i;try{if(t.src instanceof ArrayBuffer)i=await this._ctx.decodeAudioData(t.src);else if(t.src instanceof Blob){const e=await t.src.arrayBuffer();i=await this._ctx.decodeAudioData(e)}else if("string"==typeof t.src){const s=await fetch(t.src);if(!s.ok)return void console.warn(`AudioLayerManager: failed to fetch layer "${e}" from "${t.src}" โ HTTP ${s.status}`);const n=await s.arrayBuffer();i=await this._ctx.decodeAudioData(n)}}catch(t){return void console.warn(`AudioLayerManager: failed to load layer "${e}" โ`,t.message||t)}if(!i)return void console.warn(`AudioLayerManager: no audio buffer produced for layer "${e}" โ skipping.`);const s=this._ctx.createGain(),n=t.gain??0;s.gain.setValueAtTime(n,this._ctx.currentTime),s.connect(this._masterGain),this._layers.set(e,{buffer:i,gainNode:s,sourceNode:null,loop:t.loop??!0,baseGain:n}),this._currentMix[e]=n}removeLayer(e){const t=this._layers.get(e);if(t){if(t.sourceNode)try{t.sourceNode.stop()}catch{}t.gainNode.disconnect(),this._layers.delete(e),delete this._currentMix[e]}}play(e=0){this._isPlaying&&this.stop();const t=e/1e3;this._playOffset=t,this._playStartTime=this._ctx.currentTime,this._isPlaying=!0;for(const[,e]of this._layers){const i=this._ctx.createBufferSource();i.buffer=e.buffer,i.loop=e.loop,i.connect(e.gainNode),i.start(0,t),e.sourceNode=i}}pause(){this._isPlaying&&(this._playOffset+=this._ctx.currentTime-this._playStartTime,this._stopAllSources(),this._isPlaying=!1)}stop(){this._stopAllSources(),this._isPlaying=!1,this._playOffset=0}_stopAllSources(){for(const[,e]of this._layers)if(e.sourceNode){try{e.sourceNode.stop()}catch{}e.sourceNode=null}}setMix(e){const t=this._ctx.currentTime;for(const[i,s]of Object.entries(e)){const e=this._layers.get(i);e&&(e.gainNode.gain.setValueAtTime(Math.max(0,Math.min(1,s)),t),this._currentMix[i]=s)}}crossfadeTo(e,t=1e3){++this._crossfadeId;const i=this._ctx.currentTime,s=t/1e3;for(const[t,n]of Object.entries(e)){const e=this._layers.get(t);if(e){const a=Math.max(1e-4,Math.min(1,n));e.gainNode.gain.setValueAtTime(e.gainNode.gain.value||1e-4,i),e.gainNode.gain.linearRampToValueAtTime(a,i+s),this._currentMix[t]=n}}return new Promise(e=>{setTimeout(()=>{this._crossfadeId,e()},t)})}setEmotionModulation(e){this._emotionMod=e}applyEmotionState(e){if(!this._emotionMod||!e?.dominant)return;const t={},i=this._emotionMod[e.dominant.emotion];if(i)for(const[s,n]of Object.entries(i))t[s]=(t[s]||0)+n*e.dominant.intensity;for(const i of e.undercurrents||[]){const e=this._emotionMod[i.emotion];if(e)for(const[s,n]of Object.entries(e))t[s]=(t[s]||0)+n*i.intensity*.25}const s={...this._currentMix};for(const[e,i]of Object.entries(t))e in s&&(s[e]=Math.max(0,Math.min(1,s[e]+i)));this.setMix(s)}syncToBPM(e,t){if(t&&(this._baseBPM=t),!this._baseBPM)return;const i=e/this._baseBPM;for(const[,e]of this._layers)e.sourceNode&&(e.sourceNode.playbackRate.value=i)}setMasterVolume(e){this._masterGain.gain.setValueAtTime(Math.max(0,Math.min(1,e)),this._ctx.currentTime)}getLayerNames(){return[...this._layers.keys()]}getCurrentMix(){return{...this._currentMix}}isPlaying(){return this._isPlaying}destroy(){this.stop();for(const[,e]of this._layers)e.gainNode.disconnect();this._layers.clear(),this._masterGain.disconnect()}}class La{constructor(){this.context=null,this.isEnabled=!1,this.isInitialized=!1,this.nodes={master:null,ambient:null,effects:null},this.warningTimestamps={},this.warningThrottle=5e3,this.maxWarningKeys=50,this.warningAccessOrder=[],this.currentOscillator=null,this.currentGain=null,this.masterVolume=.5,this.ambientVolume=.1,this.emotionalTones=new Map([["neutral",{frequency:220,waveform:"sine",volume:.1}],["joy",{frequency:440,waveform:"triangle",volume:.15}],["sadness",{frequency:165,waveform:"sine",volume:.08}],["anger",{frequency:330,waveform:"sawtooth",volume:.12}],["fear",{frequency:880,waveform:"square",volume:.09}],["surprise",{frequency:660,waveform:"triangle",volume:.13}],["disgust",{frequency:110,waveform:"sawtooth",volume:.07}],["love",{frequency:528,waveform:"sine",volume:.11}]]),this.emotionalModifiers=new Map([["neutral",{intensity:1,speed:1}],["joy",{intensity:1.3,speed:1.2}],["sadness",{intensity:.6,speed:.8}],["anger",{intensity:1.5,speed:1.4}],["fear",{intensity:.8,speed:1.3}],["surprise",{intensity:1.4,speed:1.5}],["disgust",{intensity:.7,speed:.9}],["love",{intensity:1.1,speed:.9}]])}initialize(){try{const e=window.AudioContext||window.webkitAudioContext;return!!e&&(this.context=new e,this.context.state,this.nodes.master=this.context.createGain(),this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),this.nodes.master.connect(this.context.destination),this.nodes.effects=this.context.createGain(),this.nodes.effects.gain.setValueAtTime(1,this.context.currentTime),this.nodes.effects.connect(this.nodes.master),this.isEnabled=!0,this.isInitialized=!0,!0)}catch{return this.isEnabled=!1,!1}}async resumeContext(){if(this.context&&"suspended"===this.context.state)try{await this.context.resume()}catch{}}setMasterVolume(e,t=null){this.masterVolume=Math.max(0,Math.min(1,e)),this.isEnabled&&this.nodes.master&&(this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),t&&this.updateAmbientVolume(t))}getMasterVolume(){return this.masterVolume}isAvailable(){return this.isEnabled&&this.isInitialized}getAudioLayerManager(){return this.isAvailable()?(this._audioLayerManager||(this._audioLayerManager=new Oa(this.context)),this._audioLayerManager):null}cleanup(){try{this.currentOscillator&&(this.currentOscillator.stop(),this.currentOscillator=null),this.currentGain&&(this.currentGain=null),this.context&&"closed"!==this.context.state&&this.context.close()}catch{}finally{this._audioLayerManager&&(this._audioLayerManager.destroy(),this._audioLayerManager=null),this.context=null,this.nodes={master:null,ambient:null,effects:null},this.currentOscillator=null,this.currentGain=null,this.isEnabled=!1,this.isInitialized=!1}}getEmotionalTone(e){return this.emotionalTones.get(e)||null}setAmbientTone(e,t=500){if(!this.isAvailable())return;const i=this.getEmotionalTone(e);if(i)try{this.resumeContext();const{currentTime:e}=this.context,s=t/1e3;this.currentOscillator&&this.currentGain&&(this.currentGain.gain.exponentialRampToValueAtTime(.001,e+.5*s),this.currentOscillator.stop(e+.5*s));const n=this.context.createOscillator(),a=this.context.createGain();n.type=i.waveform,n.frequency.setValueAtTime(i.frequency,e);const r=i.volume*this.masterVolume;a.gain.setValueAtTime(.001,e),a.gain.exponentialRampToValueAtTime(r,e+s),n.connect(a),a.connect(this.nodes.master),n.start(e),this.currentOscillator=n,this.currentGain=a}catch{}}stopAmbientTone(e=500){if(this.isAvailable()&&this.currentOscillator)try{const{currentTime:t}=this.context,i=e/1e3;this.currentGain&&this.currentGain.gain.exponentialRampToValueAtTime(.001,t+i),this.currentOscillator.stop(t+i),this.currentOscillator=null,this.currentGain=null}catch{}}updateAmbientVolume(e){if(!this.isAvailable()||!this.currentGain||!e)return;const t=this.getEmotionalTone(e);if(t)try{const e=t.volume*this.masterVolume,{currentTime:i}=this.context;this.currentGain.gain.exponentialRampToValueAtTime(e,i+.1)}catch{}}playGestureSound(e,t="neutral"){if(!this.isAvailable())return;const i=this.getGestureSoundConfig(e);if(i)try{this.resumeContext();const{currentTime:e}=this.context,s=i.duration/1e3,n=this.getEmotionalModifiers(t),a=i.volume*this.masterVolume*n.intensity,r=this.context.createOscillator(),o=this.context.createGain();r.type=i.waveform,this.applyFrequencyEnvelope(r,i.frequencyEnvelope,e,s),this.applyVolumeEnvelope(o,i.volumeEnvelope,e,s,a),r.connect(o),o.connect(this.nodes.effects),r.start(e),r.stop(e+s)}catch{}else this.throttledWarn(`Unknown gesture "${e}", cannot play sound`,`gesture_${e}`)}getGestureSoundConfig(e){return Fa.getSoundConfig(e)}applyFrequencyEnvelope(e,t,i,s){t.forEach(t=>{const n=i+t.time*s;e.frequency.linearRampToValueAtTime(t.frequency,n)})}applyVolumeEnvelope(e,t,i,s,n){t.forEach((t,a)=>{const r=i+t.time*s,o=t.volume*n;0===a?e.gain.setValueAtTime(o,r):e.gain.linearRampToValueAtTime(o,r)})}getEmotionalModifiers(e){return this.emotionalModifiers.get(e)||this.emotionalModifiers.get("neutral")}setQualityReduction(e){this.qualityReduction=e,e&&this.audioContext?(this.audioContext.sampleRate,this.maxOscillators=2):this.maxOscillators=4}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}throttledWarn(e,t){const i=Date.now();if(i-(this.warningTimestamps[t]||0)>this.warningThrottle){if(Object.keys(this.warningTimestamps).length>=this.maxWarningKeys){const e=this.warningAccessOrder.shift();delete this.warningTimestamps[e]}this.warningTimestamps[t]=i;const e=this.warningAccessOrder.indexOf(t);-1!==e&&this.warningAccessOrder.splice(e,1),this.warningAccessOrder.push(t)}}}class qa{constructor(){this._maxTimestamps=120,this._timestamps=new Float64Array(this._maxTimestamps),this._tsWriteIndex=0,this._tsCount=0,this.fps=0,this.smoothedFPS=0,this.smoothingFactor=.9,this.lastFrameTime=0,this.frameTime=0,this.maxFrameTimeSamples=10,this._frameTimes=new Float64Array(this.maxFrameTimeSamples),this._ftWriteIndex=0,this._ftCount=0,this.averageFrameTime=0}update(e){this._timestamps[this._tsWriteIndex]=e,this._tsWriteIndex=(this._tsWriteIndex+1)%this._maxTimestamps,this._tsCount<this._maxTimestamps&&this._tsCount++;const t=e-1e3;let i=0;for(let e=0;e<this._tsCount;e++)this._timestamps[e]>t&&i++;if(this.fps=i,0===this.smoothedFPS?this.smoothedFPS=this.fps:this.smoothedFPS=this.smoothedFPS*this.smoothingFactor+this.fps*(1-this.smoothingFactor),this.lastFrameTime>0&&(this.frameTime=e-this.lastFrameTime,this._frameTimes[this._ftWriteIndex]=this.frameTime,this._ftWriteIndex=(this._ftWriteIndex+1)%this.maxFrameTimeSamples,this._ftCount<this.maxFrameTimeSamples&&this._ftCount++,this._ftCount>0)){let e=0;for(let t=0;t<this._ftCount;t++)e+=this._frameTimes[t];this.averageFrameTime=e/this._ftCount}this.lastFrameTime=e}getFPS(){return Math.round(this.fps)}getSmoothedFPS(){return Math.round(this.smoothedFPS)}getFrameTime(){return this.frameTime}getAverageFrameTime(){return this.averageFrameTime}reset(){this._timestamps.fill(0),this._tsWriteIndex=0,this._tsCount=0,this.fps=0,this.smoothedFPS=0,this.lastFrameTime=0,this.frameTime=0,this._frameTimes.fill(0),this._ftWriteIndex=0,this._ftCount=0,this.averageFrameTime=0}getMetrics(){return{fps:this.getFPS(),smoothedFPS:this.getSmoothedFPS(),frameTime:this.getFrameTime(),averageFrameTime:this.getAverageFrameTime(),status:this.fps>=55?"good":this.fps>=30?"okay":"poor"}}}class Ga{constructor(e,t={}){this.errorBoundary=e,this.config=t,this.config.targetFPS=t.targetFPS||60,this.loopManager=t.loopManager||ca,this.isRunning=!1,this.animationFrameId=null,this.loopCallbackId=null,this.lastFrameTime=0,this.deltaTime=0,this.isPaused=!1,this.speedMultiplier=1,this.handleVisibilityChange=this.handleVisibilityChange.bind(this),this.handleWindowBlur=this.handleWindowBlur.bind(this),this.handleWindowFocus=this.handleWindowFocus.bind(this),"undefined"!=typeof document&&(document.addEventListener("visibilitychange",this.handleVisibilityChange),window.addEventListener("blur",this.handleWindowBlur),window.addEventListener("focus",this.handleWindowFocus)),this.performanceMonitor=null,this.fpsCounter=new qa,this.subsystems={},this.eventCallback=null,this.parentMascot=null}setSubsystems(e){this.subsystems={stateMachine:e.stateMachine,particleSystem:e.particleSystem,renderer:e.renderer,soundSystem:e.soundSystem,canvasManager:e.canvasManager};const t=["stateMachine","particleSystem","renderer"];for(const e of t)if(!this.subsystems[e])throw new Error(`Required subsystem '${e}' not provided`);this.performanceMonitor&&this.performanceMonitor.setSubsystems(this.subsystems)}setEventCallback(e){if("function"!=typeof e)throw new Error("Event callback must be a function");this.eventCallback=e}setParentMascot(e){this.parentMascot=e}emit(e,t=null){this.eventCallback&&this.eventCallback(e,t)}start(){return this.errorBoundary.wrap(()=>{if(this.isRunning)return!1;if(!this.subsystems.stateMachine)throw new Error("Cannot start animation without subsystems configured");return this.isRunning=!0,this.lastFrameTime=performance.now(),this.subsystems.soundSystem&&this.subsystems.soundSystem.isAvailable()&&this.subsystems.soundSystem.resumeContext(),this.loopCallbackId=this.loopManager.register((e,t)=>this.animate(e,t),la.CRITICAL,this),this.emit("animationStarted",{targetFPS:this.targetFPS}),!0},"animation-start")()}stop(){return this.errorBoundary.wrap(()=>!!this.isRunning&&(this.isRunning=!1,this.loopCallbackId&&(this.loopManager.unregister(this.loopCallbackId),this.loopCallbackId=null),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.subsystems.renderer&&this.subsystems.renderer.stopAllGestures&&this.subsystems.renderer.stopAllGestures(),this.subsystems.soundSystem&&this.subsystems.soundSystem.isAvailable()&&this.subsystems.soundSystem.stopAmbientTone(),this.subsystems.particleSystem&&this.subsystems.particleSystem.clear(),this.emit("animationStopped"),!0),"animation-stop")()}handleWindowBlur(){document.hidden||this.handleVisibilityChange()}handleWindowFocus(){!document.hidden&&this.isPaused&&this.handleVisibilityChange()}handleVisibilityChange(){if(document.hidden)this.wasRunning=this.isRunning,this.isPaused=!0,this.pauseTime=performance.now(),this.subsystems?.particleSystem&&(this.subsystems.particleSystem.resetAccumulator(),this.pausedParticleCount=this.subsystems.particleSystem.particles?.length||0),this.subsystems?.renderer?.gestureAnimator&&this.subsystems.renderer.gestureAnimator.pauseCurrentAnimation?.(),this.parentMascot?.pause&&this.parentMascot.pause();else if(this.isPaused&&this.wasRunning){const e=performance.now(),t=e-this.pauseTime;this.lastFrameTime=e,this.frameTimeAccumulator=0,this.fpsCounter&&this.fpsCounter.reset(),this.subsystems?.particleSystem&&this.subsystems.particleSystem.onVisibilityResume(t,this.pausedParticleCount),this.renderer&&(t>tn&&this.renderer.resetCanvasContext(),this.renderer.gestureAnimator&&this.renderer.gestureAnimator.resumeAnimation?.(),t>tn&&(this.renderer.forceCleanRender=!0)),this.subsystems?.stateMachine&&(this.subsystems.stateMachine.lastUpdateTime=e),this.parentMascot?.resume&&this.parentMascot.resume(),this.isPaused=!1}}animate(e,t){if(!this.isRunning||this.isPaused)return;const i=t||performance.now();this.deltaTime=e||i-this.lastFrameTime,this.deltaTime>20&&(this.deltaTime=20),this.deltaTime>en&&this.deltaTime<20&&(this.deltaTime=en),this.lastFrameTime=i,this.deltaTime*=this.speedMultiplier,this.update(this.deltaTime),this.render()}update(e){if(this.subsystems.stateMachine&&this.subsystems.stateMachine.update(e),this.parentMascot?.stateCoordinator?._modifierManager&&this.parentMascot.stateCoordinator._modifierManager.update(e),this.parentMascot&&"function"==typeof this.parentMascot.update&&this.parentMascot.update(e),"classic"!==this.parentMascot?.config?.renderingStyle&&this.subsystems.particleSystem&&this.subsystems.stateMachine&&this.subsystems.canvasManager){const t=this.subsystems.stateMachine.getCurrentEmotionalProperties();let i;i=this.subsystems.renderer&&"function"==typeof this.subsystems.renderer.getEffectiveCenter?this.subsystems.renderer.getEffectiveCenter():this.subsystems.canvasManager.getCenter();let s=null,n=0;if(this.subsystems.renderer&&this.subsystems.renderer.getCurrentGesture){const e=this.subsystems.renderer.getCurrentGesture();e&&e.particleMotion&&(s=e.particleMotion,n=e.progress||0)}this.subsystems.particleSystem.spawn(t.particleBehavior,this.subsystems.stateMachine.getCurrentState().emotion,t.particleRate,i.x,i.y,e),this.subsystems.particleSystem.update(e,i.x,i.y,s,n)}this.performanceMonitor&&this.performanceMonitor.updateMetrics({particleCount:this.subsystems.particleSystem?.getActiveParticleCount?.()||0,audioLatency:this.subsystems.soundSystem?.getLatency?.()||0})}render(){this.parentMascot&&"function"==typeof this.parentMascot.render?this.parentMascot.render():this.subsystems.renderer&&this.subsystems.renderer.render()}getPerformanceMetrics(){const e=this.fpsCounter?this.fpsCounter.getMetrics():{};return{fps:e.fps||60,instantFps:e.smoothedFPS||60,frameTime:e.frameTime||16.67,averageFrameTime:e.averageFrameTime||16.67,isRunning:this.isRunning,deltaTime:this.deltaTime}}setTargetFPS(e){}get targetFPS(){return this.config.targetFPS||60}setSpeedMultiplier(e){this.speedMultiplier=Math.max(.1,Math.min(10,e))}getSpeedMultiplier(){return this.speedMultiplier}isAnimating(){return this.isRunning}destroy(){this.stop(),"undefined"!=typeof document&&(document.removeEventListener("visibilitychange",this.handleVisibilityChange),window.removeEventListener("blur",this.handleWindowBlur),window.removeEventListener("focus",this.handleWindowFocus)),this.performanceMonitor&&(this.performanceMonitor.destroy(),this.performanceMonitor=null),this.subsystems={},this.eventCallback=null}}class Ha{constructor(e={}){this.config={spikeThreshold:e.spikeThreshold||1.5,minimumSpikeLevel:e.minimumSpikeLevel||.1,spikeMinInterval:e.spikeMinInterval||1e3,historySize:e.historySize||10,smoothingTimeConstant:e.smoothingTimeConstant||.8,fftSize:e.fftSize||256,levelUpdateThrottle:e.levelUpdateThrottle||100,...e},this.audioContext=null,this.analyser=null,this.dataArray=null,this.currentLevel=0,this.levelHistory=[],this.isActive=!1,this.lastVolumeSpike=0,this.lastLevelEmit=0,this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}initialize(e){try{if(!e)throw new Error("AudioContext is required for audio level processing");if("function"!=typeof e.createAnalyser)throw new Error("Invalid AudioContext provided");return this.audioContext=e,this.analyser=e.createAnalyser(),this.analyser.fftSize=this.config.fftSize,this.analyser.smoothingTimeConstant=this.config.smoothingTimeConstant,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount),this.currentLevel=0,this.levelHistory=[],this.lastVolumeSpike=0,this.isActive=!0,"suspended"===e.state&&e.resume().catch(e=>{this.emitError("Failed to resume AudioContext",e)}),!0}catch(e){return this.emitError("Failed to initialize AudioLevelProcessor",e),!1}}cleanup(){try{this.isActive=!1,this.currentLevel=0,this.levelHistory=[],this.lastVolumeSpike=0,this.lastLevelEmit=0,this.audioContext=null,this.analyser=null,this.dataArray=null}catch(e){this.emitError("Error during AudioLevelProcessor cleanup",e)}}updateAudioLevel(e=16){if(this.isActive&&this.analyser&&this.dataArray)try{this.analyser.getByteFrequencyData(this.dataArray);const e=this.calculateRMS();this.currentLevel=Math.min(1,2*e),this.updateLevelHistory(),this.detectVolumeSpikes(),this.emitLevelUpdate()}catch(e){this.emitError("Error updating audio level",e),this.currentLevel=0}}calculateRMS(){if(!this.dataArray||0===this.dataArray.length)return 0;let e=0;for(let t=0;t<this.dataArray.length;t++){const i=this.dataArray[t]/255;e+=i*i}return Math.sqrt(e/this.dataArray.length)}updateLevelHistory(){this.levelHistory.push(this.currentLevel),this.levelHistory.length>this.config.historySize&&this.levelHistory.shift()}detectVolumeSpikes(){if(this.levelHistory.length<5)return;const e=performance.now();if(e-this.lastVolumeSpike<this.config.spikeMinInterval)return;const t=this.levelHistory.slice(0,-1),i=t.reduce((e,t)=>e+t,0)/t.length;this.currentLevel>=i*this.config.spikeThreshold&&i>=this.config.minimumSpikeLevel&&this.currentLevel>=2*this.config.minimumSpikeLevel&&(this.lastVolumeSpike=e,this.emitVolumeSpike({level:this.currentLevel,previousAverage:i,spikeRatio:this.currentLevel/i,timestamp:e,threshold:this.config.spikeThreshold,minimumLevel:this.config.minimumSpikeLevel}))}clearHistory(){this.levelHistory=[]}getCurrentLevel(){return this.currentLevel}getLevelHistory(){return[...this.levelHistory]}getAnalyser(){return this.analyser}getFrequencyData(){return this.dataArray?new Uint8Array(this.dataArray):null}isProcessingActive(){return this.isActive}onLevelUpdate(e){if("function"!=typeof e)throw new Error("Level update callback must be a function");this.callbacks.levelUpdate=e}onVolumeSpike(e){if("function"!=typeof e)throw new Error("Volume spike callback must be a function");this.callbacks.volumeSpike=e}onError(e){if("function"!=typeof e)throw new Error("Error callback must be a function");this.callbacks.error=e}removeAllCallbacks(){this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}updateConfig(e){this.config={...this.config,...e},this.analyser&&(e.fftSize&&(this.analyser.fftSize=this.config.fftSize,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount)),void 0!==e.smoothingTimeConstant&&(this.analyser.smoothingTimeConstant=this.config.smoothingTimeConstant))}getConfig(){return{...this.config}}getStats(){return{isActive:this.isActive,currentLevel:this.currentLevel,historySize:this.levelHistory.length,maxHistorySize:this.config.historySize,lastSpikeTime:this.lastVolumeSpike,timeSinceLastSpike:this.lastVolumeSpike>0?performance.now()-this.lastVolumeSpike:0,averageLevel:this.levelHistory.length>0?this.levelHistory.reduce((e,t)=>e+t,0)/this.levelHistory.length:0}}emitLevelUpdate(){const e=performance.now();if(!(e-this.lastLevelEmit<this.config.levelUpdateThrottle)&&(this.lastLevelEmit=e,this.callbacks.levelUpdate))try{this.callbacks.levelUpdate({level:this.currentLevel,rawData:this.getFrequencyData(),timestamp:e,history:this.getLevelHistory()})}catch{}}emitVolumeSpike(e){if(this.callbacks.volumeSpike)try{this.callbacks.volumeSpike(e)}catch{}}emitError(e,t){if(this.callbacks.error)try{this.callbacks.error({message:e,error:t,timestamp:performance.now()})}catch{}}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}}class ja{constructor(e={}){this.config={enableReducedMotion:!1!==e.enableReducedMotion,enableHighContrast:!1!==e.enableHighContrast,enableScreenReaderSupport:!1!==e.enableScreenReaderSupport,enableKeyboardNavigation:!1!==e.enableKeyboardNavigation,enableFocusIndicators:!1!==e.enableFocusIndicators,announceStateChanges:!1!==e.announceStateChanges,colorBlindMode:e.colorBlindMode||"none",...e},this.reducedMotionPreferred=!1,this.highContrastEnabled=!1,this.screenReaderActive=!1,this.keyboardNavigationActive=!1,this.currentColorBlindMode=this.config.colorBlindMode,this.focusableElements=new Map,this.currentFocusIndex=-1,this.focusHistory=[],this.liveRegion=null,this.announcementQueue=[],this.boundHandleKeyDown=null,this.boundHandleKeyUp=null,this.colorSchemes={normal:null,highContrast:{primary:"#FFFFFF",secondary:"#000000",accent:"#FFFF00",background:"#000000",particles:"#FFFFFF"},protanopia:{primary:"#0066CC",secondary:"#FFCC00",accent:"#00CCFF",background:"#1A1A1A",particles:"#66CCFF"},deuteranopia:{primary:"#0099FF",secondary:"#FF9900",accent:"#FF00FF",background:"#1A1A1A",particles:"#9966FF"},tritanopia:{primary:"#FF0066",secondary:"#00FF66",accent:"#FF6600",background:"#1A1A1A",particles:"#FFCC00"}},this.patterns={dots:"dots",stripes:"stripes",crosshatch:"crosshatch",solid:"solid"},this.statePatterns={idle:this.patterns.solid,happy:this.patterns.dots,excited:this.patterns.stripes,calm:this.patterns.solid,curious:this.patterns.crosshatch,frustrated:this.patterns.stripes,sad:this.patterns.dots,neutral:this.patterns.solid},this.initialize()}initialize(){this.detectUserPreferences(),this.setupLiveRegion(),this.config.enableKeyboardNavigation&&this.setupKeyboardNavigation(),this.setupPreferenceListeners()}detectUserPreferences(){if(this.config.enableReducedMotion&&window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion: reduce)");this.reducedMotionPreferred=e.matches}if(this.config.enableHighContrast&&window.matchMedia){const e=window.matchMedia("(prefers-contrast: high)");if(this.highContrastEnabled=e.matches,!this.highContrastEnabled){const e=window.matchMedia("(-ms-high-contrast: active)");this.highContrastEnabled=e.matches}}this.detectScreenReader()}detectScreenReader(){const e=document.querySelector("[aria-live]"),t=document.querySelector("[aria-atomic]"),i=document.querySelector('[role="application"]'),s=navigator.userAgent.toLowerCase(),n=s.includes("nvda")||s.includes("jaws")||s.includes("voiceover");this.screenReaderActive=!!(e||t||i||n)}setupLiveRegion(){this.config.enableScreenReaderSupport&&(this.liveRegion=document.getElementById("mascot-announcements"),this.liveRegion||(this.liveRegion=document.createElement("div"),this.liveRegion.id="mascot-announcements",this.liveRegion.setAttribute("aria-live","polite"),this.liveRegion.setAttribute("aria-atomic","true"),this.liveRegion.style.position="absolute",this.liveRegion.style.left="-10000px",this.liveRegion.style.width="1px",this.liveRegion.style.height="1px",this.liveRegion.style.overflow="hidden",document.body.appendChild(this.liveRegion)))}setupKeyboardNavigation(){this.boundHandleKeyDown=this.handleKeyDown.bind(this),this.boundHandleKeyUp=this.handleKeyUp.bind(this),document.addEventListener("keydown",this.boundHandleKeyDown),document.addEventListener("keyup",this.boundHandleKeyUp)}setupPreferenceListeners(){window.matchMedia&&(this._motionQuery=window.matchMedia("(prefers-reduced-motion: reduce)"),this._motionHandler=e=>{this.reducedMotionPreferred=e.matches,this.onPreferenceChange("reducedMotion",e.matches)},this._motionQuery.addEventListener?this._motionQuery.addEventListener("change",this._motionHandler):this._motionQuery.addListener&&this._motionQuery.addListener(this._motionHandler),this._contrastQuery=window.matchMedia("(prefers-contrast: high)"),this._contrastHandler=e=>{this.highContrastEnabled=e.matches,this.onPreferenceChange("highContrast",e.matches)},this._contrastQuery.addEventListener?this._contrastQuery.addEventListener("change",this._contrastHandler):this._contrastQuery.addListener&&this._contrastQuery.addListener(this._contrastHandler))}handleKeyDown(e){if(this.config.enableKeyboardNavigation){switch(e.key){case"Tab":e.preventDefault(),this.navigateFocus(e.shiftKey?-1:1);break;case"Enter":case" ":this.activateCurrentFocus();break;case"Escape":this.clearFocus();break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":this.handleArrowNavigation(e.key)}this.keyboardNavigationActive=!0}}handleKeyUp(e){}navigateFocus(e){const t=Array.from(this.focusableElements.values());if(0===t.length)return;this.currentFocusIndex+=e,this.currentFocusIndex<0?this.currentFocusIndex=t.length-1:this.currentFocusIndex>=t.length&&(this.currentFocusIndex=0);const i=t[this.currentFocusIndex];this.setFocus(i),i.label&&this.announce(`Focused on ${i.label}`)}handleArrowNavigation(e){const t={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}}[e];t&&this.onArrowNavigation&&this.onArrowNavigation(t)}registerFocusableElement(e,t){this.focusableElements.set(e,{id:e,label:t.label||e,bounds:t.bounds||null,action:t.action||null,type:t.type||"button"})}unregisterFocusableElement(e){this.focusableElements.delete(e)}setFocus(e){this.onFocusChange&&this.onFocusChange(e),this.focusHistory.push(e.id),this.focusHistory.length>10&&this.focusHistory.shift()}clearFocus(){this.currentFocusIndex=-1,this.onFocusChange&&this.onFocusChange(null),this.announce("Focus cleared")}activateCurrentFocus(){const e=Array.from(this.focusableElements.values());if(this.currentFocusIndex>=0&&this.currentFocusIndex<e.length){const t=e[this.currentFocusIndex];t.action&&(t.action(),this.announce(`Activated ${t.label}`))}}announce(e,t="polite"){this.config.enableScreenReaderSupport&&this.liveRegion&&(this.announcementQueue.push({message:e,priority:t}),this.processAnnouncementQueue())}processAnnouncementQueue(){if(0===this.announcementQueue.length)return;const{message:e,priority:t}=this.announcementQueue.shift();this.liveRegion.setAttribute("aria-live",t),this.liveRegion.textContent=e,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent=""),this.announcementQueue.length>0&&this.processAnnouncementQueue()},100)}getAnimationSettings(e={}){return this.reducedMotionPreferred?{...e,duration:e.duration?.5*e.duration:0,iterations:1,easing:"linear",particlesEnabled:!1,complexAnimations:!1,autoPlay:!1}:e}getColorScheme(e={}){return this.colorSchemes.normal||(this.colorSchemes.normal={...e}),this.highContrastEnabled?this.colorSchemes.highContrast:"none"!==this.currentColorBlindMode&&this.colorSchemes[this.currentColorBlindMode]?this.colorSchemes[this.currentColorBlindMode]:e}getStatePattern(e){return"none"===this.currentColorBlindMode?this.patterns.solid:this.statePatterns[e]||this.patterns.solid}applyPatternOverlay(e,t,i){if(t===this.patterns.solid)return;e.save();const s=document.createElement("canvas"),n=s.getContext("2d");switch(t){case this.patterns.dots:this.createDotPattern(n,s);break;case this.patterns.stripes:this.createStripePattern(n,s);break;case this.patterns.crosshatch:this.createCrosshatchPattern(n,s)}const a=e.createPattern(s,"repeat");e.fillStyle=a,e.globalAlpha=.3,e.fillRect(i.x,i.y,i.width,i.height),e.restore()}createDotPattern(e,t){t.width=10,t.height=10,e.fillStyle="white",e.beginPath(),e.arc(5,5,2,0,2*Math.PI),e.fill()}createStripePattern(e,t){t.width=10,t.height=10,e.strokeStyle="white",e.lineWidth=2,e.beginPath(),e.moveTo(0,10),e.lineTo(10,0),e.stroke()}createCrosshatchPattern(e,t){t.width=10,t.height=10,e.strokeStyle="white",e.lineWidth=1,e.beginPath(),e.moveTo(0,10),e.lineTo(10,0),e.stroke(),e.beginPath(),e.moveTo(0,0),e.lineTo(10,10),e.stroke()}setColorBlindMode(e){["none","protanopia","deuteranopia","tritanopia"].includes(e)&&(this.currentColorBlindMode=e,this.announce(`Color blind mode set to ${e}`),this.onColorSchemeChange&&this.onColorSchemeChange(this.getColorScheme()))}getStatus(){return{reducedMotion:this.reducedMotionPreferred,highContrast:this.highContrastEnabled,screenReader:this.screenReaderActive,keyboardNavigation:this.keyboardNavigationActive,colorBlindMode:this.currentColorBlindMode,focusedElement:this.currentFocusIndex>=0?Array.from(this.focusableElements.values())[this.currentFocusIndex]:null,registeredElements:this.focusableElements.size}}onPreferenceChange(e,t){this.announce(`${e} is now ${t?"enabled":"disabled"}`),"reducedMotion"===e&&this.onReducedMotionChange&&this.onReducedMotionChange(t),"highContrast"===e&&this.onHighContrastChange&&this.onHighContrastChange(t)}createStateDescription(e){return{idle:"Mascot is idle and gently breathing",happy:"Mascot is happy and bouncing",excited:"Mascot is excited with particles flying",calm:"Mascot is calm and peaceful",curious:"Mascot is curious and looking around",frustrated:"Mascot is frustrated and shaking",sad:"Mascot is sad and drooping",neutral:"Mascot is in a neutral state"}[e.emotional]||"Mascot is active"}destroy(){this.boundHandleKeyDown&&(document.removeEventListener("keydown",this.boundHandleKeyDown),this.boundHandleKeyDown=null),this.boundHandleKeyUp&&(document.removeEventListener("keyup",this.boundHandleKeyUp),this.boundHandleKeyUp=null),this._motionQuery&&this._motionHandler&&(this._motionQuery.removeEventListener?this._motionQuery.removeEventListener("change",this._motionHandler):this._motionQuery.removeListener&&this._motionQuery.removeListener(this._motionHandler),this._motionQuery=null,this._motionHandler=null),this._contrastQuery&&this._contrastHandler&&(this._contrastQuery.removeEventListener?this._contrastQuery.removeEventListener("change",this._contrastHandler):this._contrastQuery.removeListener&&this._contrastQuery.removeListener(this._contrastHandler),this._contrastQuery=null,this._contrastHandler=null),this.liveRegion&&this.liveRegion.parentNode&&this.liveRegion.parentNode.removeChild(this.liveRegion),this.focusableElements.clear(),this.announcementQueue=[],this.focusHistory=[]}}class $a{constructor(e={}){this.config={enableTouchOptimization:!1!==e.enableTouchOptimization,enableViewportHandling:!1!==e.enableViewportHandling,enableBatteryOptimization:!1!==e.enableBatteryOptimization,enableOrientationSupport:!1!==e.enableOrientationSupport,enableResponsiveScaling:!1!==e.enableResponsiveScaling,touchSensitivity:e.touchSensitivity||1,doubleTapDelay:e.doubleTapDelay||300,swipeThreshold:e.swipeThreshold||50,pinchThreshold:e.pinchThreshold||.1,...e},this.isMobile=this.detectMobile(),this.isTablet=this.detectTablet(),this.isTouchDevice=this.detectTouch(),this.isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent),this.isAndroid=/Android/.test(navigator.userAgent),this.touches=new Map,this.lastTouchTime=0,this.lastTapTime=0,this.tapCount=0,this.touchStartPosition=null,this.isPinching=!1,this.isRotating=!1,this.lastPinchDistance=0,this.lastRotation=0,this.currentGesture=null,this.gestureStartTime=0,this.gestureHistory=[],this.viewportSize={width:window.innerWidth,height:window.innerHeight},this.orientation=this.getOrientation(),this.pixelRatio=window.devicePixelRatio||1,this.lastViewportChange=0,this.batteryLevel=1,this.isCharging=!0,this.lowPowerMode=!1,this.batteryRef=null,this.mobilePerformanceSettings={reducedParticles:this.isMobile,simplifiedAnimations:this.isMobile,lowerFrameRate:this.isMobile,reducedEffects:this.isMobile||this.isTablet,targetFPS:this.isMobile?30:60,maxParticles:this.isMobile?20:50},this.canvasScale=1,this.useOffscreenCanvas=this.supportsOffscreenCanvas(),this.handleTouchStart=this.handleTouchStart.bind(this),this.handleTouchMove=this.handleTouchMove.bind(this),this.handleTouchEnd=this.handleTouchEnd.bind(this),this.handleTouchCancel=this.handleTouchCancel.bind(this),this.handleOrientationChange=this.handleOrientationChange.bind(this),this.handleViewportChange=this.handleViewportChange.bind(this),this.handleVisibilityChange=this.handleVisibilityChange.bind(this),this.handleContextMenu=e=>e.preventDefault(),this.initialize()}initialize(){this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers(),this.config.enableViewportHandling&&this.setupViewportHandlers(),this.config.enableBatteryOptimization&&this.setupBatteryMonitoring(),this.config.enableOrientationSupport&&this.setupOrientationHandlers(),this.applyMobileOptimizations()}detectMobile(){const e=navigator.userAgent.toLowerCase(),t=["android","iphone","ipod","windows phone","blackberry"].some(t=>e.includes(t)),i=window.innerWidth<=768,s="ontouchstart"in window||navigator.maxTouchPoints>0;return t||i&&s}detectTablet(){const e=navigator.userAgent.toLowerCase(),t=/ipad/.test(e),i=/android/.test(e)&&!/mobile/.test(e),s=/windows/.test(e)&&/touch/.test(e),n=window.innerWidth>768&&window.innerWidth<=1024,a="ontouchstart"in window||navigator.maxTouchPoints>0;return t||i||s||n&&a}detectTouch(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0}supportsOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}setupTouchHandlers(){const e=this.getCanvas();e&&(e.style.touchAction="none",e.style.userSelect="none",e.style.webkitUserSelect="none",e.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),e.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),e.addEventListener("touchend",this.handleTouchEnd,{passive:!1}),e.addEventListener("touchcancel",this.handleTouchCancel,{passive:!1}),e.addEventListener("contextmenu",this.handleContextMenu))}setupViewportHandlers(){window.addEventListener("resize",this.handleViewportChange),window.addEventListener("orientationchange",this.handleOrientationChange),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.setupViewportMeta()}setupViewportMeta(){let e=document.querySelector('meta[name="viewport"]');e||(e=document.createElement("meta"),e.name="viewport",document.head.appendChild(e)),e.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"}async setupBatteryMonitoring(){if(navigator.getBattery)try{const e=await navigator.getBattery();this.batteryRef=e,this.batteryLevel=e.level,this.isCharging=e.charging,this.boundBatteryLevelChange=()=>{this.batteryLevel=e.level,this.onBatteryChange()},this.boundBatteryChargingChange=()=>{this.isCharging=e.charging,this.onBatteryChange()},e.addEventListener("levelchange",this.boundBatteryLevelChange),e.addEventListener("chargingchange",this.boundBatteryChargingChange),this.onBatteryChange()}catch{}}setupOrientationHandlers(){window.DeviceOrientationEvent&&(this._deviceOrientationHandler=e=>{this.handleDeviceOrientation(e)},window.addEventListener("deviceorientation",this._deviceOrientationHandler))}handleTouchStart(e){e.cancelable&&e.preventDefault();const t=Date.now();this.gestureStartTime=t;for(const i of e.touches)this.touches.set(i.identifier,{id:i.identifier,startX:i.clientX,startY:i.clientY,currentX:i.clientX,currentY:i.clientY,startTime:t});1===e.touches.length?this.handleSingleTouchStart(e.touches[0]):2===e.touches.length&&this.handleMultiTouchStart(e.touches),this.emitTouchEvent("touchStart",{touches:Array.from(this.touches.values()),timestamp:t})}handleSingleTouchStart(e){const t=Date.now();t-this.lastTapTime<this.config.doubleTapDelay?this.tapCount++:this.tapCount=1,this.lastTapTime=t,this.touchStartPosition={x:e.clientX,y:e.clientY}}handleMultiTouchStart(e){if(2===e.length){const t=e[0],i=e[1];this.lastPinchDistance=this.getDistance(t.clientX,t.clientY,i.clientX,i.clientY),this.lastRotation=this.getAngle(t.clientX,t.clientY,i.clientX,i.clientY),this.isPinching=!0}}handleTouchMove(e){e.cancelable&&e.preventDefault();for(const t of e.touches){const e=this.touches.get(t.identifier);e&&(e.currentX=t.clientX,e.currentY=t.clientY)}1===e.touches.length?this.handleSingleTouchMove(e.touches[0]):2===e.touches.length&&this.handleMultiTouchMove(e.touches),this.emitTouchEvent("touchMove",{touches:Array.from(this.touches.values()),gesture:this.currentGesture})}handleSingleTouchMove(e){const t=this.touches.get(e.identifier);if(!t)return;const i=e.clientX-t.startX,s=e.clientY-t.startY;Math.sqrt(i*i+s*s)>this.config.swipeThreshold?Math.abs(i)>Math.abs(s)?this.currentGesture=i>0?"swipeRight":"swipeLeft":this.currentGesture=s>0?"swipeDown":"swipeUp":this.currentGesture="pan"}handleMultiTouchMove(e){if(2!==e.length)return;const t=e[0],i=e[1],s=this.getDistance(t.clientX,t.clientY,i.clientX,i.clientY),n=s-this.lastPinchDistance,a=s/this.lastPinchDistance;Math.abs(n)>this.config.pinchThreshold&&(this.currentGesture=a>1?"pinchOut":"pinchIn",this.emitTouchEvent("pinch",{scale:a,delta:n}));const r=this.getAngle(t.clientX,t.clientY,i.clientX,i.clientY),o=r-this.lastRotation;Math.abs(o)>5&&(this.currentGesture="rotate",this.emitTouchEvent("rotate",{angle:r,delta:o})),this.lastPinchDistance=s,this.lastRotation=r}handleTouchEnd(e){e.cancelable&&e.preventDefault();const t=Date.now();for(const i of e.changedTouches){const e=this.touches.get(i.identifier);if(e){const s=t-e.startTime,n=e.currentX-e.startX,a=e.currentY-e.startY,r=Math.sqrt(n*n+a*a);s<300&&r<10&&(2===this.tapCount?(this.emitTouchEvent("doubleTap",{x:e.currentX,y:e.currentY}),this.tapCount=0):this.emitTouchEvent("tap",{x:e.currentX,y:e.currentY})),s>500&&r<10&&this.emitTouchEvent("longPress",{x:e.currentX,y:e.currentY}),this.touches.delete(i.identifier)}}0===e.touches.length&&(this.currentGesture=null,this.isPinching=!1,this.isRotating=!1),this.emitTouchEvent("touchEnd",{gesture:this.currentGesture,duration:t-this.gestureStartTime})}handleTouchCancel(e){this.touches.clear(),this.currentGesture=null,this.isPinching=!1,this.isRotating=!1,this.emitTouchEvent("touchCancel",{})}handleOrientationChange(e){this.orientation=this.getOrientation(),this.emitTouchEvent("orientationChange",{orientation:this.orientation,angle:window.orientation||0}),this.applyOrientationOptimizations()}handleDeviceOrientation(e){const{alpha:t,beta:i,gamma:s}=e;this.emitTouchEvent("deviceOrientation",{alpha:t,beta:i,gamma:s})}handleViewportChange(e){const t=Date.now();t-this.lastViewportChange<100||(this.lastViewportChange=t,this.viewportSize={width:window.innerWidth,height:window.innerHeight},this.pixelRatio=window.devicePixelRatio||1,this.emitTouchEvent("viewportChange",{size:this.viewportSize,pixelRatio:this.pixelRatio,orientation:this.getOrientation()}),this.config.enableResponsiveScaling&&this.applyResponsiveScaling())}handleVisibilityChange(e){const t=!document.hidden;this.emitTouchEvent("visibilityChange",{visible:t}),!t&&this.config.enableBatteryOptimization?this.applyBackgroundOptimizations():this.restorePerformance()}getOrientation(){return window.innerWidth>window.innerHeight?"landscape":"portrait"}getDistance(e,t,i,s){const n=i-e,a=s-t;return Math.sqrt(n*n+a*a)}getAngle(e,t,i,s){return 180*Math.atan2(s-t,i-e)/Math.PI}applyMobileOptimizations(){if(!this.isMobile&&!this.isTablet)return;const e={...this.mobilePerformanceSettings,canvasScale:this.calculateOptimalCanvasScale(),useWebGL:!1,useOffscreenCanvas:this.useOffscreenCanvas};return this.emitTouchEvent("mobileOptimizations",e),e}applyOrientationOptimizations(){const e="landscape"===this.orientation,t={layoutMode:e?"horizontal":"vertical",particleDirection:e?"horizontal":"vertical",uiScale:e?.8:1};return this.emitTouchEvent("orientationOptimizations",t),t}applyResponsiveScaling(){const e=Math.min(this.viewportSize.width/375,2);return this.canvasScale=e,this.emitTouchEvent("responsiveScale",{scale:this.canvasScale,viewport:this.viewportSize}),this.canvasScale}applyBackgroundOptimizations(){const e={targetFPS:5,particlesEnabled:!1,animationsEnabled:!1,audioEnabled:!1};return this.emitTouchEvent("backgroundOptimizations",e),e}restorePerformance(){const e=this.applyMobileOptimizations();return this.emitTouchEvent("performanceRestore",e),e}onBatteryChange(){if(this.lowPowerMode=this.batteryLevel<.2&&!this.isCharging,this.lowPowerMode){const e={targetFPS:15,maxParticles:5,reducedEffects:!0,audioEnabled:!1};this.emitTouchEvent("lowPowerMode",{batteryLevel:this.batteryLevel,isCharging:this.isCharging,optimizations:e})}}calculateOptimalCanvasScale(){return this.isMobile?Math.min(this.pixelRatio,2):this.isTablet?Math.min(this.pixelRatio,2.5):this.pixelRatio}getCanvas(){return this.canvas||document.querySelector("canvas")}setCanvas(e){this.canvas=e,this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers()}emitTouchEvent(e,t){this.onTouchEvent&&this.onTouchEvent(e,t)}getStatus(){return{device:{isMobile:this.isMobile,isTablet:this.isTablet,isTouchDevice:this.isTouchDevice,isIOS:this.isIOS,isAndroid:this.isAndroid},viewport:{size:this.viewportSize,orientation:this.orientation,pixelRatio:this.pixelRatio,canvasScale:this.canvasScale},battery:{level:this.batteryLevel,isCharging:this.isCharging,lowPowerMode:this.lowPowerMode},touch:{activeTouches:this.touches.size,currentGesture:this.currentGesture,isPinching:this.isPinching,isRotating:this.isRotating},performance:this.mobilePerformanceSettings}}destroy(){const e=this.getCanvas();e&&(e.removeEventListener("touchstart",this.handleTouchStart),e.removeEventListener("touchmove",this.handleTouchMove),e.removeEventListener("touchend",this.handleTouchEnd),e.removeEventListener("touchcancel",this.handleTouchCancel),e.removeEventListener("contextmenu",this.handleContextMenu)),window.removeEventListener("resize",this.handleViewportChange),window.removeEventListener("orientationchange",this.handleOrientationChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange),this._deviceOrientationHandler&&(window.removeEventListener("deviceorientation",this._deviceOrientationHandler),this._deviceOrientationHandler=null),this.batteryRef&&(this.boundBatteryLevelChange&&this.batteryRef.removeEventListener("levelchange",this.boundBatteryLevelChange),this.boundBatteryChargingChange&&this.batteryRef.removeEventListener("chargingchange",this.boundBatteryChargingChange),this.batteryRef=null),this.touches.clear(),this.gestureHistory=[]}}class Wa{constructor(e={}){this.config={enablePlugins:!1!==e.enablePlugins,validatePlugins:!1!==e.validatePlugins,sandboxPlugins:!1!==e.sandboxPlugins,maxPlugins:e.maxPlugins||50,pluginTimeout:e.pluginTimeout||5e3,allowOverrides:!1!==e.allowOverrides},this.mascot=e.mascot||null,this.plugins=new Map,this.pluginTypes=["emotion","gesture","particle","audio","renderer","animation"],this.pluginsByType=new Map(this.pluginTypes.map(e=>[e,new Set])),this.dependencies=new Map,this.dependencyGraph=new Map,this.pluginStates=new Map,this.loadingPlugins=new Set,this.activePlugins=new Set,this.hooks=new Map([["beforeInit",new Set],["afterInit",new Set],["beforeUpdate",new Set],["afterUpdate",new Set],["beforeRender",new Set],["afterRender",new Set],["beforeDestroy",new Set],["afterDestroy",new Set]]),this.pluginAPI=this.createPluginAPI(),this.conflicts=new Map,this.resolutionStrategies={override:this.overrideConflict.bind(this),merge:this.mergeConflict.bind(this),reject:this.rejectConflict.bind(this),queue:this.queueConflict.bind(this)},this.validationSchemas=this.createValidationSchemas(),this.sandbox=null,this.config.sandboxPlugins&&(this.sandbox=this.createSandbox())}createPluginAPI(){return{mascot:this.mascot,registerHook:this.registerHook.bind(this),emit:this.emitPluginEvent.bind(this),on:this.onPluginEvent.bind(this),getPlugin:this.getPlugin.bind(this),hasPlugin:this.hasPlugin.bind(this),log:this.logFromPlugin.bind(this),error:this.errorFromPlugin.bind(this),setState:this.setPluginState.bind(this),getState:this.getPluginState.bind(this),getConfig:()=>({...this.config}),version:"1.0.0"}}createValidationSchemas(){const e=new Map,t={name:{type:"string",required:!0},version:{type:"string",required:!0},type:{type:"string",required:!0,enum:this.pluginTypes},description:{type:"string",required:!1},author:{type:"string",required:!1},dependencies:{type:"array",required:!1},conflicts:{type:"array",required:!1},init:{type:"function",required:!0},destroy:{type:"function",required:!0}};return e.set("emotion",{...t,emotion:{type:"object",required:!0,properties:{name:{type:"string",required:!0},color:{type:"string",required:!0},particleColor:{type:"string",required:!1},animation:{type:"object",required:!0},transitions:{type:"object",required:!1}}},updateEmotion:{type:"function",required:!0},renderEmotion:{type:"function",required:!1}}),e.set("gesture",{...t,gesture:{type:"object",required:!0,properties:{name:{type:"string",required:!0},duration:{type:"number",required:!0},keyframes:{type:"array",required:!0},compatibility:{type:"object",required:!1}}},executeGesture:{type:"function",required:!0},canExecute:{type:"function",required:!1}}),e.set("particle",{...t,particle:{type:"object",required:!0,properties:{name:{type:"string",required:!0},maxParticles:{type:"number",required:!1},behavior:{type:"function",required:!0},render:{type:"function",required:!0}}},updateParticles:{type:"function",required:!0},spawnParticle:{type:"function",required:!1}}),e.set("audio",{...t,audio:{type:"object",required:!0,properties:{name:{type:"string",required:!0},sounds:{type:"object",required:!0},effects:{type:"array",required:!1}}},playSound:{type:"function",required:!0},processAudio:{type:"function",required:!1}}),e}createSandbox(){return{Math:Math,Date:Date,JSON:JSON,console:{log:(...e)=>null,warn:(...e)=>null,error:(...e)=>null},window:void 0,document:void 0,localStorage:void 0,sessionStorage:void 0,fetch:void 0,XMLHttpRequest:void 0,api:this.pluginAPI}}async registerPlugin(e){if(!this.config.enablePlugins)return!1;if(this.plugins.size>=this.config.maxPlugins)return!1;if(this.config.validatePlugins&&!this.validatePlugin(e).valid)return!1;if(this.checkConflicts(e).length>0&&!this.config.allowOverrides)return!1;if(!(await this.resolveDependencies(e)).resolved)return!1;try{this.loadingPlugins.add(e.name);const t=this.config.sandboxPlugins?this.sandbox:window;if(!await this.initializePlugin(e,t))throw new Error("Plugin initialization failed");return this.plugins.set(e.name,e),this.pluginsByType.get(e.type).add(e.name),this.pluginStates.set(e.name,"active"),this.activePlugins.add(e.name),e.dependencies&&(this.dependencies.set(e.name,e.dependencies),this.updateDependencyGraph(e.name,e.dependencies)),e.hooks&&Object.entries(e.hooks).forEach(([t,i])=>{this.registerHook(t,i,e.name)}),this.emitPluginEvent("pluginRegistered",{name:e.name,type:e.type,version:e.version}),!0}catch(e){return console.warn("[PluginSystem] Failed to register plugin:",e),!1}finally{this.loadingPlugins.delete(e.name)}}validatePlugin(e){const t=[];if(e.name&&"string"==typeof e.name||t.push("Plugin must have a valid name"),e.type&&this.pluginTypes.includes(e.type)||t.push(`Plugin type must be one of: ${this.pluginTypes.join(", ")}`),e.version&&"string"==typeof e.version||t.push("Plugin must have a version"),"function"!=typeof e.init&&t.push("Plugin must have an init function"),"function"!=typeof e.destroy&&t.push("Plugin must have a destroy function"),e.type&&this.validationSchemas.has(e.type)){const i=this.validationSchemas.get(e.type),s=this.validateAgainstSchema(e,i);t.push(...s)}return{valid:0===t.length,errors:t}}validateAgainstSchema(e,t){const i=[];return Object.entries(t).forEach(([t,s])=>{if(s.required&&!(t in e)&&i.push(`Missing required property: ${t}`),t in e){const n=e[t];if(s.type&&typeof n!==s.type&&i.push(`Property ${t} must be of type ${s.type}`),s.enum&&!s.enum.includes(n)&&i.push(`Property ${t} must be one of: ${s.enum.join(", ")}`),s.properties&&"object"==typeof n){const e=this.validateAgainstSchema(n,s.properties);i.push(...e.map(e=>`${t}.${e}`))}}}),i}checkConflicts(e){const t=[];return e.conflicts&&e.conflicts.forEach(e=>{this.plugins.has(e)&&t.push(e)}),"emotion"!==e.type&&"gesture"!==e.type||this.plugins.forEach(i=>{if(i.type===e.type){const s=i[e.type]?.name,n=e[e.type]?.name;s===n&&t.push(`${e.type} name collision: ${n}`)}}),t}async resolveDependencies(e){if(!e.dependencies||0===e.dependencies.length)return{resolved:!0,missing:[]};const t=[];for(const i of e.dependencies)this.plugins.has(i)||await this.tryLoadDependency(i)||t.push(i);return{resolved:0===t.length,missing:t}}tryLoadDependency(e){return this.plugins.has(e)}updateDependencyGraph(e,t){this.dependencyGraph.set(e,new Set(t)),t.forEach(e=>{this.dependencyGraph.has(e)||this.dependencyGraph.set(e,new Set)})}async initializePlugin(e,t){try{const i=new Promise((e,t)=>{setTimeout(()=>t(new Error("Plugin initialization timeout")),this.config.pluginTimeout)}),s=e.init.bind(t);return!1!==await Promise.race([s(this.pluginAPI),i])}catch(e){return console.warn("[PluginSystem] Plugin initialization error:",e),!1}}async unregisterPlugin(e){const t=this.plugins.get(e);if(!t)return!1;if(this.getDependentPlugins(e).length>0)return!1;try{return"function"==typeof t.destroy&&await t.destroy(),this.plugins.delete(e),this.pluginsByType.get(t.type).delete(e),this.pluginStates.delete(e),this.activePlugins.delete(e),this.dependencies.delete(e),this.dependencyGraph.delete(e),this.hooks.forEach(t=>{t.forEach(i=>{i.pluginName===e&&t.delete(i)})}),this.emitPluginEvent("pluginUnregistered",{name:e}),!0}catch(e){return console.warn("[PluginSystem] Failed to unregister plugin:",e),!1}}getDependentPlugins(e){const t=[];return this.dependencies.forEach((i,s)=>{i.includes(e)&&t.push(s)}),t}registerHook(e,t,i){this.hooks.has(e)||this.hooks.set(e,new Set),this.hooks.get(e).add({handler:t,pluginName:i})}async executeHooks(e,t){const i=this.hooks.get(e);if(!i||0===i.size)return[];const s=[];for(const n of i)try{const e=await n.handler(t);s.push({pluginName:n.pluginName,result:e})}catch(t){console.warn(`[PluginSystem] Hook '${e}' error in plugin '${n.pluginName}':`,t)}return s}getPlugin(e){return this.plugins.get(e)||null}hasPlugin(e){return this.plugins.has(e)}getPluginsByType(e){const t=this.pluginsByType.get(e);return t?Array.from(t).map(e=>this.plugins.get(e)):[]}enablePlugin(e){if(!this.plugins.has(e))return;this.pluginStates.set(e,"active"),this.activePlugins.add(e);const t=this.plugins.get(e);t.onEnable&&t.onEnable(),this.emitPluginEvent("pluginEnabled",{name:e})}disablePlugin(e){if(!this.plugins.has(e))return;this.getDependentPlugins(e).length,this.pluginStates.set(e,"disabled"),this.activePlugins.delete(e);const t=this.plugins.get(e);t.onDisable&&t.onDisable(),this.emitPluginEvent("pluginDisabled",{name:e})}emitPluginEvent(e,t){this.onPluginEvent&&this.onPluginEvent(e,t)}onPluginEvent(e,t){}logFromPlugin(e,...t){}errorFromPlugin(e,...t){console.warn(`[PluginSystem] ${e}:`,...t)}setPluginState(e,t,i){this.pluginStates.has(e)||this.pluginStates.set(e,{});const s=this.pluginStates.get(e);"object"==typeof s&&(s[t]=i)}getPluginState(e,t){const i=this.pluginStates.get(e);if("object"==typeof i)return i[t]}overrideConflict(e,t){return t}mergeConflict(e,t){return{...e,...t}}rejectConflict(e,t){return e}queueConflict(e,t){return[e,t]}getStatus(){return{enabled:this.config.enablePlugins,totalPlugins:this.plugins.size,activePlugins:this.activePlugins.size,loadingPlugins:this.loadingPlugins.size,pluginsByType:Object.fromEntries(Array.from(this.pluginsByType.entries()).map(([e,t])=>[e,t.size])),hooks:Object.fromEntries(Array.from(this.hooks.entries()).map(([e,t])=>[e,t.size]))}}update(e,t){if(this.config.enablePlugins)for(const i of this.activePlugins){const s=this.plugins.get(i);if(s&&"function"==typeof s.update)try{s.update(e,t)}catch(e){this.errorFromPlugin(i,"Update error:",e)}}}render(e,t){if(this.config.enablePlugins)for(const i of this.activePlugins){const s=this.plugins.get(i);if(s&&"function"==typeof s.render)try{s.render(e,t)}catch(e){this.errorFromPlugin(i,"Render error:",e)}}}async destroy(){const e=Array.from(this.plugins.keys());for(const t of e)await this.unregisterPlugin(t);this.plugins.clear(),this.pluginsByType.clear(),this.dependencies.clear(),this.dependencyGraph.clear(),this.pluginStates.clear(),this.activePlugins.clear(),this.loadingPlugins.clear(),this.hooks.clear(),this.conflicts.clear()}}class Ua{constructor(){if(Ua._cachedFeatures)return this.features=Ua._cachedFeatures,void(this.capabilities=Ua._cachedCapabilities);this.features={webAudio:this.detectWebAudio(),canvas2d:this.detectCanvas2D(),requestAnimationFrame:this.detectRequestAnimationFrame(),devicePixelRatio:this.detectDevicePixelRatio(),audioContext:this.detectAudioContext(),mediaDevices:this.detectMediaDevices(),performance:this.detectPerformance(),intersectionObserver:this.detectIntersectionObserver()},this.capabilities=this.assessCapabilities(),Ua._cachedFeatures=this.features,Ua._cachedCapabilities=this.capabilities}detectWebAudio(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectCanvas2D(){try{const e=document.createElement("canvas");return!(!e.getContext||!e.getContext("2d"))}catch{return!1}}detectRequestAnimationFrame(){return!!(window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame)}detectDevicePixelRatio(){return"number"==typeof window.devicePixelRatio}detectAudioContext(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectMediaDevices(){return!(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)}detectPerformance(){return!(!window.performance||!window.performance.now)}detectIntersectionObserver(){return"function"==typeof window.IntersectionObserver}assessCapabilities(){const e=Object.values(this.features).filter(Boolean).length,t=Object.keys(this.features).length,i=e/t*100;let s="basic";return i>=90?s="full":i>=70?s="good":i>=50&&(s="limited"),{score:e,total:t,percentage:i,level:s,recommendations:this.getRecommendations(s)}}getRecommendations(e){const t=[];return this.features.webAudio||t.push("Audio features will be disabled"),this.features.requestAnimationFrame||t.push("Animation will use setTimeout fallback"),this.features.performance||t.push("Performance monitoring will be limited"),"basic"===e&&t.push("Consider using minimal build for better performance"),t}getFeatures(){return{...this.features}}getCapabilities(){return{...this.capabilities}}}class Va{constructor(){this.polyfills=new Map,this.applied=new Set}register(e,t){this.polyfills.set(e,t)}apply(e){if(this.applied.has(e))return!0;const t=this.polyfills.get(e);if(!t)return!1;try{return t(),this.applied.add(e),!0}catch{return!1}}applyAll(){const e=[];for(const t of this.polyfills.keys())this.apply(t)&&e.push(t);return e}isApplied(e){return this.applied.has(e)}}function Ya(){window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return window.setTimeout(()=>{e(Date.now())},1e3/60)},window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(e){window.clearTimeout(e)})}function Xa(){if(window.performance&&window.performance.now)return;window.performance||(window.performance={});const e=Date.now();window.performance.now=function(){return Date.now()-e}}function Na(){window.AudioContext||window.webkitAudioContext||(window.AudioContext=function(){this.state="suspended",this.sampleRate=44100,this.currentTime=0,this.destination={connect(){},disconnect(){}},this.createGain=function(){return{gain:{value:1},connect(){},disconnect(){}}},this.createOscillator=function(){return{frequency:{value:440},type:"sine",start(){},stop(){},connect(){},disconnect(){}}},this.createAnalyser=function(){return{fftSize:2048,frequencyBinCount:1024,getByteFrequencyData(e){for(let t=0;t<e.length;t++)e[t]=0},connect(){},disconnect(){}}},this.resume=function(){return this.state="running",Promise.resolve()},this.suspend=function(){return this.state="suspended",Promise.resolve()},this.close=function(){return this.state="closed",Promise.resolve()}})}class Qa{constructor(e){this.canvas=e,this.context=null,this.isContextLost=!1,this.recoveryCallbacks=[],this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this),this.setupContextLossHandling()}handleContextLost(e){e.preventDefault(),this.isContextLost=!0}handleContextRestored(){this.isContextLost=!1,this.context=this.canvas.getContext("2d"),this.recoveryCallbacks.forEach(e=>{try{e(this.context)}catch{}})}setupContextLossHandling(){this.canvas.addEventListener("webglcontextlost",this.handleContextLost),this.canvas.addEventListener("webglcontextrestored",this.handleContextRestored)}getContext(){if(this.isContextLost)return null;if(!this.context)try{this.context=this.canvas.getContext("2d")}catch{return null}return this.context}onRecovery(e){this.recoveryCallbacks.push(e)}isLost(){return this.isContextLost}recover(){if(!this.isContextLost)return!0;try{if(this.context=this.canvas.getContext("2d"),this.context)return this.isContextLost=!1,!0}catch{}return!1}destroy(){this.canvas&&(this.canvas.removeEventListener("webglcontextlost",this.handleContextLost),this.canvas.removeEventListener("webglcontextrestored",this.handleContextRestored),this.canvas=null),this.context=null,this.recoveryCallbacks=[]}}class Ja{constructor(){if(Ja._cachedBrowser)return this.browser=Ja._cachedBrowser,void(this.optimizations=Ja._cachedOptimizations);this.browser=this.detectBrowser(),this.optimizations=new Map,this.setupOptimizations(),Ja._cachedBrowser=this.browser,Ja._cachedOptimizations=this.optimizations}detectBrowser(){const{userAgent:e}=navigator;let t="unknown",i="unknown";if(e.includes("Chrome")){t="chrome";const s=e.match(/Chrome\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Firefox")){t="firefox";const s=e.match(/Firefox\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Safari")&&!e.includes("Chrome")){t="safari";const s=e.match(/Version\/(\d+)/);i=s?s[1]:"unknown"}else if(e.includes("Edge")){t="edge";const s=e.match(/Edge\/(\d+)/);i=s?s[1]:"unknown"}return{name:t,version:i,userAgent:e}}setupOptimizations(){this.optimizations.set("chrome",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"interactive"},canvasOptimizations:["willReadFrequently"],particleLimit:50}),this.optimizations.set("firefox",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"balanced"},canvasOptimizations:[],particleLimit:40}),this.optimizations.set("safari",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"playback"},canvasOptimizations:[],particleLimit:30}),this.optimizations.set("edge",{preferredAnimationMethod:"requestAnimationFrame",audioContextOptions:{latencyHint:"interactive"},canvasOptimizations:["willReadFrequently"],particleLimit:45})}getOptimizations(){return this.optimizations.get(this.browser.name)||this.optimizations.get("chrome")}getBrowser(){return{...this.browser}}applyCanvasOptimizations(e,t){if(this.getOptimizations().canvasOptimizations.includes("willReadFrequently"))try{e.getContext("2d",{willReadFrequently:!0})}catch{}}getRecommendedParticleLimit(){return this.getOptimizations().particleLimit}getAudioContextOptions(){return this.getOptimizations().audioContextOptions}}let Ka=null;function Za(){if(Ka)return Ka;const e=new Ua,t=new Va,i=new Ja;t.register("requestAnimationFrame",Ya),t.register("performanceNow",Xa),t.register("webAudio",Na);const s=[];return e.features.requestAnimationFrame||t.apply("requestAnimationFrame")&&s.push("requestAnimationFrame"),e.features.performance||t.apply("performanceNow")&&s.push("performanceNow"),e.features.webAudio||t.apply("webAudio")&&s.push("webAudio"),Ka={featureDetection:e,polyfillManager:t,browserOptimizations:i,appliedPolyfills:s,capabilities:e.getCapabilities(),browser:i.getBrowser()},Ka}let er=null;function tr(){return er||(er=Za()),er}const ir=tr();function sr(e){const t=[];for(let i=0;i<e;i++){const s=i/e*Math.PI*2;t.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)})}return t}function nr(e,t=12){return sr(e)}const ar={circle:{points:sr(64),shadow:{type:"none"}},sphere:{points:sr(64),shadow:{type:"none"}},heart:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64*Math.PI*2,s=16*Math.pow(Math.sin(i),3),n=-(13*Math.cos(i)-5*Math.cos(2*i)-2*Math.cos(3*i)-Math.cos(4*i));e.push({x:.5+s/32,y:.5+n/32})}return e}(),shadow:{type:"none"}},star:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64,s=Math.floor(10*i),n=s%2==0,a=Math.floor(s/2);let r;r=n?(72*a-90)*Math.PI/180:(72*a+36-90)*Math.PI/180;const o=n?.5:.2;e.push({x:.5+Math.cos(r)*o,y:.5+Math.sin(r)*o})}return e}(0),shadow:{type:"none"}},sun:{points:nr(64,12),shadow:{type:"sun",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3}},moon:{points:sr(64),shadow:{type:"crescent",coverage:.85,angle:-30,softness:.05,offset:.7}},lunar:{points:sr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)",progression:"center"}},suspicion:{points:function(){const e=[];for(let t=0;t<64;t++){const i=t/64*Math.PI*2;let s,n;if(i<Math.PI)s=.45*Math.cos(i),n=.45*Math.sin(i);else{const e=2*Math.PI-i;s=.25*Math.cos(e)-.1,n=.35*Math.sin(e)}e.push({x:.5+s,y:.5+n})}return e}(),shadow:{type:"none"}},eclipse:{points:sr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)"}},square:{points:function(){const e=[],t=Math.floor(16);for(let i=0;i<4;i++)for(let s=0;s<t;s++){const n=s/t;let a,r;switch(i){case 0:a=-.5+n,r=-.5;break;case 1:a=.5,r=-.5+n;break;case 2:a=.5-n,r=.5;break;case 3:a=-.5,r=.5-n}e.push({x:.5+.8*a,y:.5+.8*r})}return e}(),shadow:{type:"none"}},triangle:{points:function(){const e=[],t=[{x:0,y:-.5},{x:-.433,y:.25},{x:.433,y:.25}],i=[Math.sqrt(Math.pow(t[1].x-t[0].x,2)+Math.pow(t[1].y-t[0].y,2)),Math.sqrt(Math.pow(t[2].x-t[1].x,2)+Math.pow(t[2].y-t[1].y,2)),Math.sqrt(Math.pow(t[0].x-t[2].x,2)+Math.pow(t[0].y-t[2].y,2))],s=i[0]+i[1]+i[2],n=i.map(e=>Math.round(64*e/s)),a=n.reduce((e,t)=>e+t,0);a<64&&(n[0]+=64-a);for(let i=0;i<3;i++){const s=t[i],a=t[(i+1)%3],r=n[i];for(let t=0;t<r;t++){if(t===r-1&&i<2)continue;const n=t/r,o=s.x+(a.x-s.x)*n,l=s.y+(a.y-s.y)*n;e.push({x:.5+.9*o,y:.5+.9*l})}}for(;e.length<64;)e.push(e[e.length-1]);for(;e.length>64;)e.pop();return e}(),shadow:{type:"none"}},solar:{points:nr(64,12),shadow:{type:"solar-hybrid",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3,lunarOverlay:{type:"lunar",coverage:1,color:"rgba(0, 0, 0, 1.0)",progression:"center"}}}};const rr=new class{constructor(){this.shapeCache=new Map,this.morphCache=new Map,this.propertyCache=new Map,this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1,this.loadStartTime=0,this.initialize()}initialize(){this.loadStartTime=performance.now();try{const e=Object.keys(ar);e.forEach(e=>{this.cacheShape(e)}),this.cacheCommonMorphs(e),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.shapeCache.size}catch(e){console.error("[ShapeCache] Initialization failed:",e),this.isInitialized=!1,console.warn("[ShapeCache] Running uninitialized โ lookups will return defaults")}}cacheShape(e){try{const t=ar[e];if(t){this.shapeCache.set(e,t);const i={pointCount:t.points?.length||64,hasShadow:"none"!==t.shadow?.type,shadowType:t.shadow?.type||"none",isRadial:this.isRadialShape(e),bounds:this.calculateBounds(t.points)};this.propertyCache.set(e,i)}}catch(t){console.warn(`[ShapeCache] Failed to cache shape '${e}':`,t)}}cacheCommonMorphs(e){[["circle","heart"],["circle","star"],["circle","square"],["heart","star"],["star","circle"],["square","circle"],["triangle","circle"],["moon","sun"],["lunar","eclipse"]].forEach(([t,i])=>{if(e.includes(t)&&e.includes(i))try{const e=this.calculateMorphSteps(t,i),s=`${t}->${i}`;this.morphCache.set(s,e)}catch(e){console.warn(`[ShapeCache] Failed to cache morph '${t}->${i}':`,e)}})}calculateMorphSteps(e,t){const i=this.shapeCache.get(e),s=this.shapeCache.get(t);if(!i||!s)return null;const n=[];for(let e=0;e<5;e++){const t=e/4,a=this.interpolateShapePoints(i.points,s.points,t);n.push({progress:t,points:a})}return{from:e,to:t,steps:n,isRadial:this.isRadialShape(e)||this.isRadialShape(t)}}interpolateShapePoints(e,t,i){if(!e||!t)return e||t||[];const s=Math.max(e.length,t.length),n=[];for(let a=0;a<s;a++){const s=e[a]||e[0]||{x:.5,y:.5},r=t[a]||t[0]||{x:.5,y:.5};n.push({x:s.x+(r.x-s.x)*i,y:s.y+(r.y-s.y)*i})}return n}isRadialShape(e){return["circle","star","square","triangle","sun","moon"].includes(e)}calculateBounds(e){if(!e||0===e.length)return{minX:0,minY:0,maxX:1,maxY:1,width:1,height:1};let t=1/0,i=1/0,s=-1/0,n=-1/0;return e.forEach(e=>{t=Math.min(t,e.x),i=Math.min(i,e.y),s=Math.max(s,e.x),n=Math.max(n,e.y)}),{minX:t,minY:i,maxX:s,maxY:n,width:s-t,height:n-i}}getShape(e){if(!this.isInitialized)return console.warn("[ShapeCache] Cache not initialized, falling back to direct access"),ar[e]||null;const t=this.shapeCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,ar[e]||null)}getProperties(e){if(!this.isInitialized){const t=ar[e];return t?{pointCount:t.points?.length||64,hasShadow:"none"!==t.shadow?.type,shadowType:t.shadow?.type||"none",isRadial:this.isRadialShape(e),bounds:this.calculateBounds(t.points)}:{}}const t=this.propertyCache.get(e);return t?(this.stats.hits++,t):(this.stats.misses++,{})}getMorph(e,t){if(!this.isInitialized)return this.calculateMorphSteps(e,t);const i=`${e}->${t}`,s=this.morphCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,this.calculateMorphSteps(e,t))}hasShape(e){return this.shapeCache.has(e)}getStats(){const e=this.stats.hits+this.stats.misses;return{...this.stats,hitRate:e>0?`${(this.stats.hits/e*100).toFixed(1)}%`:"0%",shapes:this.shapeCache.size,morphs:this.morphCache.size,properties:this.propertyCache.size}}clear(){this.shapeCache.clear(),this.morphCache.clear(),this.propertyCache.clear(),this.stats={hits:0,misses:0,loadTime:0,cacheSize:0},this.isInitialized=!1}},or=new class{constructor(){this.pools=new Map,this.inUse=new Set}acquire(e,t="array"){const i=`${t}_${e}`;this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);if(s.length>0){const e=s.pop();return this.inUse.add(e),e}let n;switch(t){case"float32":n=new Float32Array(e);break;case"uint8":n=new Uint8Array(e);break;default:n=new Array(e).fill(0)}return this.inUse.add(n),n}release(e){if(!this.inUse.has(e))return;this.inUse.delete(e);let t="array";e instanceof Float32Array?t="float32":e instanceof Uint8Array&&(t="uint8");const i=`${t}_${e.length}`;e.fill(0),this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);s.length<10&&s.push(e)}clear(){this.pools.clear(),this.inUse.clear()}};class lr{constructor(e){this.morpher=e,this.audioDeformation=0,this.vocalEnergy=0,this.vocalEffectActive=!1,this.beatGlitchIntensity=0,this.glitchPoints=[],this.bassEnergy=0,this.vocalPresence=0,this.highFreqEnergy=0,this.transientActive=!1,this.transientStrength=0,this.transientDecay=.92,this.transientHoldTime=8,this.transientHoldCounter=0}applyAudioDeformation(e){if(!e||0===e.length)return this.morpher.generateFallbackCircle();if(this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.currentFrequencies&&this.morpher.audioAnalyzer.currentFrequencies.length>0){this.morpher.frequencyData=[...this.morpher.audioAnalyzer.currentFrequencies];let e=0,t=0;for(let i=0;i<=2&&i<this.morpher.frequencyData.length;i++)e+=this.morpher.frequencyData[i],t++;t>0&&(e/=t),this.morpher.bassPeakHistory||(this.morpher.bassPeakHistory=[],this.morpher.bassThumpTimer=0),this.morpher.bassPeakHistory.push(e),this.morpher.bassPeakHistory.length>20&&this.morpher.bassPeakHistory.shift();const i=this.morpher.bassPeakHistory.reduce((e,t)=>e+t,0)/this.morpher.bassPeakHistory.length,s=this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.microphoneStream;if(e>1.08*i&&e>(s?.15:.25)){const t=s?8:6;this.bassEnergy=Math.min(1,(e-i)*t),this.morpher.bassThumpTimer=12}else this.morpher.bassThumpTimer>0?(this.morpher.bassThumpTimer--,this.bassEnergy*=.9):this.bassEnergy=0;this.morpher.spectralHistory||(this.morpher.spectralHistory=[],this.morpher.spectralFluxHistory=[],this.morpher.onsetThreshold=0,this.morpher.musicDetector.reset(),this.morpher.detectedBPM=0,this.morpher.onsetStrengths=[],this.morpher.detectedTimeSignature=null,this.morpher.timeSignatureConfidence=0,this.morpher.measureStartTime=0,this.morpher.timeSignatureHistory=[],this.morpher.timeSignatureLocked=!1);const n=[...this.morpher.frequencyData];let a=0,r=0;if(this.morpher.spectralHistory.length>0){const e=this.morpher.spectralHistory[this.morpher.spectralHistory.length-1];for(let t=0;t<=2&&t<n.length;t++){const i=n[t]-e[t];i>0&&(r+=i)}for(let t=4;t<=15&&t<n.length;t++){const i=n[t]-e[t];i>0&&(a+=i*(t>=9&&t<=13?2:1))}r>.15&&(a*=.3)}if(this.morpher.spectralHistory.push(n),this.morpher.spectralHistory.length>30&&this.morpher.spectralHistory.shift(),this.morpher.spectralFluxHistory.push(a),this.morpher.spectralFluxHistory.length>30&&this.morpher.spectralFluxHistory.shift(),this.morpher.bassFluxHistory||(this.morpher.bassFluxHistory=[],this.morpher.bassOnsetThreshold=.05),this.morpher.bassFluxHistory.push(r),this.morpher.bassFluxHistory.length>30&&this.morpher.bassFluxHistory.shift(),this.morpher.spectralFluxHistory.length>=10){const e=[...this.morpher.spectralFluxHistory].sort((e,t)=>e-t),t=e[Math.floor(e.length/2)],i=e.reduce((e,t)=>e+t,0)/e.length;this.morpher.onsetThreshold=t+.5*(i-t)}if(this.morpher.bassFluxHistory.length>=10){const e=[...this.morpher.bassFluxHistory].sort((e,t)=>e-t),t=e[Math.floor(e.length/2)],i=e.reduce((e,t)=>e+t,0)/e.length;this.morpher.bassOnsetThreshold=t+.5*(i-t)}const o=a>1.2*this.morpher.onsetThreshold&&a>.02,l=r>1.5*this.morpher.bassOnsetThreshold&&r>.08;if(o&&(this.transientHoldTime=8,this.morpher.vocalGlowBoost=.3),l){const e=performance.now(),t={time:e,strength:r/(this.morpher.bassOnsetThreshold||1),bassWeight:r};this.morpher.onsetStrengths.push(t),this.morpher.onsetStrengths.length>40&&this.morpher.onsetStrengths.shift(),this.morpher.musicDetector.addOnset(e,r)}const h=performance.now();this.morpher.musicDetector.processFrequencyFrame&&this.morpher.musicDetector.processFrequencyFrame(this.morpher.frequencyData,h),this.morpher.musicDetector.update(h),this.morpher.detectedBPM=this.morpher.musicDetector.detectedBPM,this.morpher.bpmConfidence=this.morpher.musicDetector.bpmConfidence,this.morpher.detectedBPM>0&&this.morpher.bpmConfidence>.8&&this.morpher.forceFastDetection&&(this.morpher.forceFastDetection=!1),this.transientHoldTime>0&&this.transientHoldTime--,this.morpher.vocalGlowBoost>0&&(this.morpher.vocalGlowBoost*=.92),this.vocalPresence=a,this.morpher.bassHistory[this.morpher.historyIndex]=this.bassEnergy,this.morpher.vocalHistory[this.morpher.historyIndex]=this.vocalPresence,this.morpher.historyIndex=(this.morpher.historyIndex+1)%this.morpher.bassHistory.length,this.morpher.bassEffectActive=this.morpher.bassThumpTimer>0,this.morpher.lastVocalPresence=this.morpher.lastVocalPresence||0,this.morpher.lastVocalPresence=this.vocalPresence,this.vocalEffectActive=this.transientHoldTime>0}const t=this.morpher.frequencyData&&this.morpher.frequencyData.some(e=>e>.01);if(this.morpher.audioAnalyzer&&t||(this.audioDeformation>.15?(this.morpher.bassEffectActive=!0,this.bassEnergy=Math.min(1,.8*this.audioDeformation),(!this.morpher.bassThumpTimer||this.morpher.bassThumpTimer<=0)&&(this.morpher.bassThumpTimer=12)):this.morpher.bassThumpTimer>0&&(this.morpher.bassThumpTimer--,this.bassEnergy*=.9),this.vocalEnergy>.2&&(this.vocalEffectActive=!0,this.vocalPresence=this.vocalEnergy)),!t&&this.audioDeformation>.15&&!this.morpher.bassEffectActive&&(this.morpher.bassEffectActive=!0,this.bassEnergy=Math.max(this.bassEnergy,.8*this.audioDeformation),(!this.morpher.bassThumpTimer||this.morpher.bassThumpTimer<=0)&&(this.morpher.bassThumpTimer=12)),!(0!==this.audioDeformation||this.bassEnergy>.01||this.vocalPresence>.01))return e;const i=[];if(this.morpher.bassEffectActive&&(Math.random()<.05&&(this.morpher.undulationDirection*=-1),this.morpher.undulationPhase+=.08*this.morpher.undulationDirection),this.morpher.audioAnalyzer&&this.beatGlitchIntensity>0&&(this.beatGlitchIntensity*=.9),this.vocalEffectActive&&Math.random()<.2){this.glitchPoints=[];const t=2+Math.floor(2*Math.random());for(let i=0;i<t;i++)this.glitchPoints.push({index:Math.floor(Math.random()*e.length),intensity:.02+.03*Math.random(),decay:.94+.02*Math.random()})}this.glitchPoints=this.glitchPoints.filter(e=>(e.intensity*=e.decay,e.intensity>.01));for(let t=0;t<e.length;t++){const s=e[t];if(!s||void 0===s.x||void 0===s.y){const s=t/e.length*Math.PI*2;i.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)});continue}const n=s.x-.5,a=s.y-.5,r=Math.sqrt(n*n+a*a),o=Math.atan2(a,n),l=.12*Math.abs(this.audioDeformation);let h=0,c=0;if(this.morpher.bassEffectActive){const e=2,t=.25*this.bassEnergy;h=Math.sin(o*e+this.morpher.undulationPhase)*t,c=Math.sin(.5*this.morpher.undulationPhase)*this.bassEnergy*.08}let u=0;const d=this.glitchPoints.find(e=>e.index===t);if(d){const e=.015*Date.now(),i=Math.sin(e+.5*t)*Math.cos(.7*e);u=d.intensity*i*.5}const g=1+l+h+c+u,m=r*Math.max(.8,g);i.push({x:.5+Math.cos(o)*m,y:.5+Math.sin(o)*m})}return i}setAudioDeformation(e){this.audioDeformation=Math.max(0,Math.min(1,e)),this.vocalEffectActive=e>.01}setVocalEnergy(e){this.vocalEnergy=Math.max(0,Math.min(1,e)),this.vocalEffectActive=e>.01}updateFrequencyBands(e){e&&(this.bassEnergy=e.bass||0,this.vocalPresence=e.vocal||0,this.highFreqEnergy=e.high||0)}processTransient(e,t){e>t?(this.transientActive=!0,this.transientStrength=e,this.transientHoldCounter=this.transientHoldTime):this.transientHoldCounter>0?this.transientHoldCounter--:(this.transientStrength*=this.transientDecay,this.transientStrength<.01&&(this.transientActive=!1))}getState(){return{audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy,vocalEffectActive:this.vocalEffectActive,beatGlitchIntensity:this.beatGlitchIntensity,transientActive:this.transientActive,transientStrength:this.transientStrength}}reset(){this.audioDeformation=0,this.vocalEnergy=0,this.vocalEffectActive=!1,this.beatGlitchIntensity=0,this.glitchPoints=[],this.transientActive=!1,this.transientStrength=0}}class hr{constructor(){this.minBPM=60,this.maxBPM=180,this.lastPeakTime=0,this.peakCount=0,this.intervals=[],this.maxIntervals=40,this.bpmVotes=new Map,this.currentBPM=0,this.lockedBPM=0,this.confidence=0,this.isActive=!1,this.lockStage=0,this.stage1LockTime=0,this.stage2CorrectionApplied=!1,this.correctionType="none",this._recentSubdivisionChecks=[],this._stage3StartTime=0,this._stage3StableTime=0,this._memoryCleanedUp=!1,this._microTuneBPM=0,this.grooveConfidence=.15,this._grooveConfidenceTarget=.15,this._lastLogTime=0,this._logIntervalMs=2e3,this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0,this._logBuffer=[],this._maxLogEntries=20}processPeak(e,t=performance.now()){if(this.isActive=!0,this.peakCount++,e<.1)this._skippedPeaks++;else{if(this.lastPeakTime>0){const e=t-this.lastPeakTime;e>=250&&e<=2e3?(this.intervals.push(e),this._recentIntervals.push(Math.round(e)),this.intervals.length>this.maxIntervals&&this.intervals.shift(),this.voteForInterval(e)):this._skippedIntervals++}this.lastPeakTime=t,this.updateBPM(),this._debugLog(t)}}voteForInterval(e){const t=6e4/e;this._recentRawBPMs.push(Math.round(t));let i=t;const s=.95*this.minBPM,n=1.05*this.maxBPM;if(i<s)for(;i<this.minBPM;)i*=2;else if(i>n)for(;i>this.maxBPM;)i/=2;i=Math.max(this.minBPM,Math.min(this.maxBPM,i)),this._recentNormalizedBPMs.push(Math.round(i));const a=Math.round(i);for(let e=-2;e<=2;e++){const t=a+e;if(t>=this.minBPM&&t<=this.maxBPM){const i=Math.exp(-e*e/2),s=this.bpmVotes.get(t)||0;this.bpmVotes.set(t,s+i)}}for(const[e,t]of this.bpmVotes){const i=.95*t;i<.3?this.bpmVotes.delete(e):this.bpmVotes.set(e,i)}}updateBPM(){if(0===this.bpmVotes.size||this.intervals.length<3)return;const e=performance.now();let t=0,i=0,s=0;for(const[e,n]of this.bpmVotes)s+=n,n>i&&(i=n,t=e);if(0===t)return;let n=0;for(let e=-2;e<=2;e++){const i=t+e;n+=this.bpmVotes.get(i)||0}const a=n,r=Math.round(t/2);let o=0;if(r>=this.minBPM)for(let e=-2;e<=2;e++)o+=this.bpmVotes.get(r+e)||0;const l=2*t;let h=0;if(l<=this.maxBPM)for(let e=-2;e<=2;e++)h+=this.bpmVotes.get(l+e)||0;let c=0,u=0;const d=a>0?o/a:0;if(this.intervals.length>=6){const e=this.intervals.slice(-8),t=e.reduce((e,t)=>e+t,0)/e.length;let i=0;for(let s=0;s<e.length-1;s++)e[s]>t!=e[s+1]>t&&i++;c=i/(e.length-1);const s=[];for(let t=0;t<e.length-1;t+=2)s.push(e[t]+e[t+1]);if(s.length>=2){const e=s.reduce((e,t)=>e+t,0)/s.length;u=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}this.confidence=s>0?a/s:0;let g=0;if(this.intervals.length>=4){const e=6e4/t,i=e/2,s=this.intervals.slice(-8);let n=0;for(const t of s){const s=Math.abs(t-e)/e<.15,a=Math.abs(t-i)/i<.15,r=Math.abs(t-2*e)/(2*e)<.15;(s||a||r)&&n++}g=n/s.length}if(0===this.currentBPM)this.currentBPM=t;else{const e=this.intervals.length<6?.5:.3;this.currentBPM=this.currentBPM*(1-e)+t*e}if(0===this.lockStage){this._lastLockCheck={intervalCount:this.intervals.length,bestVotes:i.toFixed(1),clusterVotes:a.toFixed(1),confidence:`${(100*this.confidence).toFixed(0)}%`,consistency:`${(100*g).toFixed(0)}%`,bestBPM:t,adjustedBPM:t,isSubdivision:!1,stage:0,failReasons:[]};const s=t>120?12:8,n=.2,r=.45;this.intervals.length<s&&this._lastLockCheck.failReasons.push(`intervals<${s}`),a<=5&&this._lastLockCheck.failReasons.push("votes<=5"),this.confidence<=n&&this._lastLockCheck.failReasons.push(`conf<=${(100*n).toFixed(0)}%`),g<=r&&this._lastLockCheck.failReasons.push(`consistency<=${(100*r).toFixed(0)}%`),this.intervals.length>=s&&a>5&&this.confidence>n&&g>r&&(this.lockedBPM=Math.round(this.currentBPM),this.lockStage=1,this.stage1LockTime=e)}if(1===this.lockStage||2===this.lockStage){this._recentSubdivisionChecks.push({alternatingScore:c,pairVariance:u,halfVoteRatio:d,time:e}),this._recentSubdivisionChecks.length>15&&this._recentSubdivisionChecks.shift();const i=this._recentSubdivisionChecks.filter(e=>e.alternatingScore>.7&&e.pairVariance<.1).length,s=this._recentSubdivisionChecks.reduce((e,t)=>e+t.alternatingScore,0)/this._recentSubdivisionChecks.length,n=this._recentSubdivisionChecks.reduce((e,t)=>e+t.pairVariance,0)/this._recentSubdivisionChecks.length,o=this._recentSubdivisionChecks.reduce((e,t)=>e+t.halfVoteRatio,0)/this._recentSubdivisionChecks.length,g=this.intervals.length>0?this.intervals.reduce((e,t)=>e+t,0)/this.intervals.length:0,m=a>0?h/a:0;let p=0,f=0;if(this.intervals.length>=8){const e=this.intervals.slice(-12),t=[...e].sort((e,t)=>e-t),i=t[Math.floor(t.length/2)],s=e.filter(e=>Math.abs(e-i)/i<.5);if(f=s.length,s.length>=6){const e=s.reduce((e,t)=>e+t,0)/s.length;p=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}if(this._lastLockCheck={intervalCount:this.intervals.length,bestBPM:t,adjustedBPM:this.lockedBPM,halfBPM:r,stage:this.lockStage,subdivisionChecks:this._recentSubdivisionChecks.length,positiveChecks:i,avgAltScore:`${(100*s).toFixed(0)}%`,avgPairVar:`${(100*n).toFixed(1)}%`,avgHalfRatio:`${(100*o).toFixed(0)}%`,intervalVariance:`${(100*p).toFixed(1)}%`,filteredCount:f,correctionApplied:this.stage2CorrectionApplied,failReasons:[]},!this.stage2CorrectionApplied&&this._recentSubdivisionChecks.length>=10&&r>=this.minBPM){const e=i>=7&&s>.7&&n<.1&&this.lockedBPM>100,t=o>.4&&this.lockedBPM>150&&r>=65&&r<=85;let a=0,l=0;if(this.intervals.length>=8){const e=this.intervals.slice(-12),t=[...e].sort((e,t)=>e-t),i=t[Math.floor(t.length/2)],s=e.filter(e=>Math.abs(e-i)/i<.5);if(l=s.length,s.length>=6){const e=s.reduce((e,t)=>e+t,0)/s.length;a=s.reduce((t,i)=>t+Math.abs(i-e),0)/s.length/e}}const h=this.lockedBPM>140&&r>=65&&r<=85&&l>=8&&a<.05;(e||t||h)&&(this.lockedBPM=Math.round(this.lockedBPM/2),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="halved")}!this.stage2CorrectionApplied&&this._recentSubdivisionChecks.length>=10&&l<=this.maxBPM&&g>900&&m>.5&&this.lockedBPM<75&&(this.lockedBPM=Math.round(2*this.lockedBPM),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="doubled");const y=e-this.stage1LockTime;1===this.lockStage&&this._recentSubdivisionChecks.length>=6&&(this.lockStage=2);const b=this._recentSubdivisionChecks.length>=12&&i<3,v=y>1e4;2===this.lockStage&&(this.stage2CorrectionApplied||b||v)&&(this.lockStage=3,this._stage3StartTime=e)}if(3===this.lockStage){const t=e-this._stage3StartTime,i=this.intervals.slice(-8);if(i.length>=4){const e=6e4/(i.reduce((e,t)=>e+t,0)/i.length);if(Math.abs(e-this.lockedBPM)/this.lockedBPM<.05){0===this._microTuneBPM&&(this._microTuneBPM=this.lockedBPM),this._microTuneBPM=.9*this._microTuneBPM+.1*e;const t=Math.round(this._microTuneBPM);t!==this.lockedBPM&&(this.lockedBPM=t),this._stage3StableTime+=100}else this._stage3StableTime=0}const s=(t>5e3||this._stage3StableTime>3e3)&&!this._memoryCleanedUp;s&&3===this.lockStage&&(this._performMemoryCleanup(),this._memoryCleanedUp=!0),this._lastLockCheck={stage:3,lockedBPM:this.lockedBPM,correctionType:this.correctionType,timeSinceStage3:`${(t/1e3).toFixed(1)}s`,stableTime:`${(this._stage3StableTime/1e3).toFixed(1)}s`,finalized:s,failReasons:[]}}this._updateGrooveConfidence()}_updateGrooveConfidence(){this._memoryCleanedUp?this._grooveConfidenceTarget=1:this._grooveConfidenceTarget=[.15,.4,.65,.85][this.lockStage]||.15;const e=this.grooveConfidence+.08*(this._grooveConfidenceTarget-this.grooveConfidence);e>this.grooveConfidence&&(this.grooveConfidence=e)}_performMemoryCleanup(){this.intervals.length>8&&(this.intervals=this.intervals.slice(-8)),this.bpmVotes.clear(),this._subdivisionHistory=[],this._recentSubdivisionChecks=[],this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[]}processFrame(e,t=performance.now()){}reset(){this.intervals=[],this.bpmVotes.clear(),this.lastPeakTime=0,this.peakCount=0,this.currentBPM=0,this.lockedBPM=0,this.confidence=0,this.isActive=!1,this.lockStage=0,this.stage1LockTime=0,this.stage2CorrectionApplied=!1,this.correctionType="none",this._recentSubdivisionChecks=[],this._stage3StartTime=0,this._stage3StableTime=0,this._memoryCleanedUp=!1,this._microTuneBPM=0,this.grooveConfidence=.15,this._grooveConfidenceTarget=.15,this._lastLogTime=0,this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0,this._logBuffer=[],this._lastLockCheck=null,this._subdivisionHistory=[]}getBPM(){return this.lockedBPM>0?this.lockedBPM:Math.round(this.currentBPM)||0}getSubdivision(){return 1}getStatus(){return{bpm:this.getBPM(),subdivision:1,confidence:this.confidence,locked:this.lockedBPM>0,lockStage:this.lockStage,correctionType:this.correctionType,finalized:this._memoryCleanedUp,grooveConfidence:this.grooveConfidence,agentCount:this.bpmVotes.size,peakCount:this.peakCount,histogramSize:this.bpmVotes.size,topAgents:this.getTopCandidates(5),intervalCount:this.intervals.length}}getTopCandidates(e=5){return[...this.bpmVotes.entries()].sort((e,t)=>t[1]-e[1]).slice(0,e).map(([e,t])=>({bpm:e,score:t.toFixed(1),interval:Math.round(6e4/e)}))}getTopIntervals(e=5){return this.getTopCandidates(e).map(e=>({interval:e.interval,bpm:e.bpm,weight:e.score}))}_debugLog(e){if(e-this._lastLogTime<this._logIntervalMs)return;if(this._lastLogTime=e,0===this._recentIntervals.length&&0===this._skippedPeaks)return;const t=[],i=["Detecting","Initial Lock","Refinement","Final Lock"][this.lockStage]||"Unknown";t.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"),t.push(`Status: Stage ${this.lockStage} (${i}) | Current: ${Math.round(this.currentBPM)} BPM | Locked: ${this.lockedBPM||"-"}`),t.push(`Peaks: ${this.peakCount} total | ${this._skippedPeaks} skipped (weak) | ${this._skippedIntervals} intervals out-of-range`),this._recentIntervals.length>0&&t.push(`Recent intervals (ms): [${this._recentIntervals.join(", ")}]`),this._recentRawBPMs.length>0&&t.push(`Raw BPMs (before normalize): [${this._recentRawBPMs.join(", ")}]`),this._recentNormalizedBPMs.length>0&&t.push(`Normalized BPMs (60-180): [${this._recentNormalizedBPMs.join(", ")}]`);const s=this.getTopCandidates(5);if(s.length>0){const e=s.map(e=>`${e.bpm}(${e.score})`).join(", ");t.push(`Top candidates: ${e}`)}if(this._lastLockCheck){const e=this._lastLockCheck;0===e.stage?e.failReasons&&e.failReasons.length>0?t.push(`Stage 0: NOT locking - ${e.failReasons.join(", ")}`):t.push(`Stage 0: Ready to lock at ${e.bestBPM} BPM`):1===e.stage||2===e.stage?(t.push(`Stage ${e.stage}: Locked=${e.adjustedBPM} BPM | checks=${e.subdivisionChecks} positive=${e.positiveChecks}`),t.push(` altScore=${e.avgAltScore} pairVar=${e.avgPairVar} halfRatio=${e.avgHalfRatio}`),e.correctionApplied&&t.push(` Correction applied: ${this.correctionType}`)):3===e.stage&&(t.push(`Stage 3: Final=${e.lockedBPM} BPM | correction=${e.correctionType} | time=${e.timeSinceStage3} stable=${e.stableTime}`),e.finalized&&t.push(" FINALIZED - memory cleaned"))}if(this.intervals.length>=6){const e=this.intervals.slice(-8),i=e.reduce((e,t)=>e+t,0)/e.length,s=(e.reduce((e,t)=>e+Math.abs(t-i),0)/e.length/i*100).toFixed(1);let n=0;for(let t=0;t<e.length-1;t++)e[t]>i!=e[t+1]>i&&n++;const a=(n/(e.length-1)*100).toFixed(0);t.push(`Interval pattern: variance=${s}% alternating=${a}% (>70% triggers subdivision)`)}const n=[...this.intervals].map(e=>Math.round(e));if(n.length>0){const e=Math.min(...n),i=Math.max(...n),s=Math.round(n.reduce((e,t)=>e+t,0)/n.length);t.push(`Interval buffer (${n.length}/${this.maxIntervals}): min=${e}ms max=${i}ms avg=${s}ms (=${Math.round(6e4/s)} BPM)`)}t.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ");const a=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});for(this._logBuffer.push({time:a,lines:t});this._logBuffer.length>this._maxLogEntries;)this._logBuffer.shift();this._recentIntervals=[],this._recentRawBPMs=[],this._recentNormalizedBPMs=[],this._skippedPeaks=0,this._skippedIntervals=0}getDebugLog(){if(0===this._logBuffer.length)return"No BPM debug logs yet. Play audio to generate logs.";let e="=== BPM Debug Log ===\n\n";for(const t of this._logBuffer){e+=`[${t.time}]\n`;for(const i of t.lines)e+=`${i}\n`;e+="\n"}return e}clearDebugLog(){this._logBuffer=[]}}class cr{constructor(){this.onsetIntervals=[],this.onsetStrengths=[],this.lastOnsetTime=0,this.onsetThreshold=.3,this.detectedBPM=0,this.bpmConfidence=0,this.lastBPMCalculation=0,this.bpmCalculationInterval=2e3,this.bpmHistory=[],this.tempoLocked=!1,this.fundamentalBPM=0,this.agentDetector=new hr,this.useAgentDetection=!0,this.timeSignature="4/4",this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.timeSignatureHistory=[],this.timeSignatureLocked=!1,this.downbeatPhase=0,this.measureLength=4,this.measureStartTime=0,this.isMusicalContent=!1,this.musicalityScore=0,this.forceFastDetection=!1}calculateBPM(){if(this.useAgentDetection){const e=this.agentDetector.getStatus();if(e.locked&&e.confidence>.6)return this.detectedBPM=e.bpm,this.bpmConfidence=e.confidence,this.tempoLocked=!0,this.fundamentalBPM=e.bpm,this.bpmHistory.push(this.detectedBPM),this.bpmHistory.length>10&&this.bpmHistory.shift(),this.detectedBPM;if(e.bpm>0&&e.confidence>.4)return this.detectedBPM=e.bpm,this.bpmConfidence=e.confidence,e.confidence>.6&&(this.tempoLocked=!0),this.detectedBPM}if(this.onsetIntervals.length<4)return this.detectedBPM;const e=this.onsetIntervals.slice(-15),t=this.findTempoCandidates(e);if(0===t.length)return this.detectedBPM;const i=t[0],s=Math.round(6e4/i.interval);if(!this.tempoLocked&&this.bpmHistory.length>3){const e=this.bpmHistory.slice(-3),t=e.reduce((e,t)=>e+t,0)/e.length;e.reduce((e,i)=>e+Math.pow(i-t,2),0)/e.length<5&&(this.fundamentalBPM=Math.round(t),this.tempoLocked=!0,this.bpmConfidence=1)}let n=s;if(this.tempoLocked&&(this.checkHarmonicRelation(s,this.fundamentalBPM)?(n=this.fundamentalBPM,this.bpmConfidence=Math.min(1,this.bpmConfidence+.1)):(this.bpmConfidence*=.9,this.bpmConfidence<.3&&i.strength>.8?(this.fundamentalBPM=s,this.bpmConfidence=.5):n=this.fundamentalBPM)),this.bpmHistory.push(n),this.bpmHistory.length>10&&this.bpmHistory.shift(),0===this.detectedBPM)this.detectedBPM=n;else{const e=this.tempoLocked?1:2,t=n-this.detectedBPM;Math.abs(t)<=e?this.detectedBPM=n:this.detectedBPM+=Math.sign(t)*e}return window.rhythmIntegration&&window.rhythmIntegration.updateBPM&&(window.rhythmManuallyStoppedForCurrentAudio||window.rhythmIntegration.updateBPM(this.detectedBPM)),this.detectedBPM}findTempoCandidates(e){const t=[];for(const i of[1,2,4]){const s=e.map(e=>e*i),n=this.clusterIntervals(s);for(const s of n){const n=s.intervals.reduce((e,t)=>e+t,0)/s.intervals.length/i,a=s.intervals.length/e.length*s.consistency,r=6e4/n,o=r>=120&&r<=140?.2:0;r>=60&&r<=220&&t.push({interval:n,strength:a+o,multiplier:i})}}return t.sort((e,t)=>t.strength-e.strength)}clusterIntervals(e){const t=[...e].sort((e,t)=>e-t),i=[];let s=[t[0]];for(let e=1;e<t.length;e++){const n=.03*s[0];if(t[e]-s[0]<=n)s.push(t[e]);else{if(s.length>=2){const e=s.reduce((e,t)=>e+t,0)/s.length,t=1/(1+s.reduce((t,i)=>t+Math.pow(i-e,2),0)/s.length/(e*e));i.push({intervals:s,consistency:t})}s=[t[e]]}}if(s.length>=3){const e=s.reduce((e,t)=>e+t,0)/s.length,t=1/(1+s.reduce((t,i)=>t+Math.pow(i-e,2),0)/s.length/(e*e));i.push({intervals:s,consistency:t})}return i}checkHarmonicRelation(e,t){const i=Math.max(e,t)/Math.min(e,t);return[2,1.5,1.333,1.25].some(e=>Math.abs(i-e)<.03)}detectTimeSignature(){const e=this.forceFastDetection?6:12;if(0===this.detectedBPM||this.onsetStrengths.length<e)return this.timeSignature;if(this.timeSignatureLocked&&!this.forceFastDetection)return this.detectedTimeSignature||this.timeSignature;const t=6e4/this.detectedBPM,i=new Array(4).fill(0).map(()=>({strength:0,bassWeight:0,count:0})),s=this.onsetStrengths.slice(-Math.min(20,this.onsetStrengths.length));if(0===s.length)return this.timeSignature;const n=s[0].time;for(const e of s){const s=(e.time-n)/t%4,a=Math.round(s)%4;i[a].strength+=e.strength,i[a].bassWeight+=e.bassWeight||0,i[a].count++}let a=0;for(const e of i)e.count>0&&(e.strength/=e.count,e.bassWeight/=e.count,a=Math.max(a,e.strength+e.bassWeight));let r="4/4";i[0].strength>2*i[1].strength&&i[0].strength>2*i[2].strength&&i[3].count<.5*i[0].count&&this.testWaltzPattern(s,t)>.8&&(r="3/4"),this.timeSignatureHistory.push(r),this.timeSignatureHistory.length>3&&this.timeSignatureHistory.shift();const o=this.forceFastDetection?2:3;if(this.timeSignatureHistory.length>=o){const e={};for(const t of this.timeSignatureHistory)e[t]=(e[t]||0)+1;let t="4/4",i=0;for(const[s,n]of Object.entries(e))n>i&&(i=n,t=s);if(i>=2){this.detectedTimeSignature=t,this.timeSignatureLocked=!0,this.timeSignatureConfidence=i/3,window.rhythmIntegration&&window.rhythmIntegration.setTimeSignature&&window.rhythmIntegration.setTimeSignature(this.detectedTimeSignature);const e=document.getElementById("time-sig-display");e&&(e.textContent=this.detectedTimeSignature)}}return this.detectedTimeSignature||this.timeSignature}testWaltzPattern(e,t){let i=0,s=0;for(let t=0;t<e.length-2;t+=3)if(t+2<e.length){s++;const n=e[t].strength+(e[t].bassWeight||0),a=e[t+1].strength+(e[t+1].bassWeight||0),r=e[t+2].strength+(e[t+2].bassWeight||0);n>1.5*a&&n>1.5*r&&i++}return s>0?i/s:0}processFrequencyFrame(e,t=performance.now()){this.useAgentDetection&&this.agentDetector.processFrame&&this.agentDetector.processFrame(e,t)}addOnset(e,t,i=0){if(this.useAgentDetection&&this.agentDetector.processPeak(t,e),this.lastOnsetTime>0){const t=e-this.lastOnsetTime;t>273&&t<1e3&&(this.onsetIntervals.push(t),this.onsetIntervals.length>20&&this.onsetIntervals.shift())}this.onsetStrengths.push({time:e,strength:t,bassWeight:i}),this.onsetStrengths.length>40&&this.onsetStrengths.shift(),this.lastOnsetTime=e}update(e){e-this.lastBPMCalculation>this.bpmCalculationInterval&&(this.calculateBPM(),this.detectTimeSignature(),this.lastBPMCalculation=e)}getRecommendedSubdivision(){return this.useAgentDetection?this.agentDetector.getSubdivision():this.detectedBPM<60?2:this.detectedBPM<80?1:this.detectedBPM>180||this.detectedBPM>140?.5:1}reset(){this.onsetIntervals=[],this.onsetStrengths=[],this.lastOnsetTime=0,this.detectedBPM=0,this.bpmConfidence=0,this.bpmHistory=[],this.tempoLocked=!1,this.fundamentalBPM=0,this.timeSignature="4/4",this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.timeSignatureHistory=[],this.agentDetector&&this.agentDetector.reset(),this.timeSignatureLocked=!1,this.isMusicalContent=!1,this.forceFastDetection=!1}getMusicInfo(){return{bpm:this.detectedBPM,confidence:this.bpmConfidence,timeSignature:this.timeSignature,isMusical:this.isMusicalContent,musicalityScore:this.musicalityScore}}}class ur{constructor(e){this.morpher=e,this.isTransitioning=!1,this.transitionStartTime=0,this.transitionDuration=800,this.transitionProgress=0,this.easingFunction="easeInOutQuad",this.currentShape="circle",this.targetShape=null,this.previousShape=null,this.morphQueue=[],this.maxQueueSize=3,this.shadowConfig=null,this.shadowProgress=0}startTransition(e,t={}){this.isTransitioning&&this.morphQueue.length<this.maxQueueSize?this.morphQueue.push({shape:e,options:t}):(this.previousShape=this.currentShape,this.targetShape=e,this.isTransitioning=!0,this.transitionStartTime=performance.now(),this.transitionDuration=t.duration||800,this.easingFunction=t.easing||"easeInOutQuad",this.transitionProgress=0,this.shadowConfig=this.getTransitionConfig(this.currentShape,e))}update(e){if(!this.isTransitioning)return;const t=performance.now()-this.transitionStartTime,i=Math.min(1,t/this.transitionDuration);this.transitionProgress=this.applyEasing(i),this.shadowConfig&&(this.shadowProgress=this.calculateShadowProgress(i)),i>=1&&this.completeTransition()}completeTransition(){if(this.currentShape=this.targetShape,this.targetShape=null,this.isTransitioning=!1,this.transitionProgress=0,this.shadowConfig=null,this.morphQueue.length>0){const e=this.morphQueue.shift();this.startTransition(e.shape,e.options)}}getTransitionConfig(e,t){return{"circle-heart":{type:"bloom",shadowColor:"#ff69b4",shadowIntensity:.3},"heart-circle":{type:"contract",shadowColor:"#ff69b4",shadowIntensity:.2},"circle-star":{type:"burst",shadowColor:"#ffd700",shadowIntensity:.4},"star-circle":{type:"collapse",shadowColor:"#ffd700",shadowIntensity:.3}}[`${e}-${t}`]||null}calculateShadowProgress(e){if(!this.shadowConfig)return 0;switch(this.shadowConfig.type){case"bloom":return e<.5?2*e:2-2*e;case"burst":return Math.pow(1-e,2);case"contract":case"collapse":return Math.sin(e*Math.PI);default:return 0}}applyEasing(e){switch(this.easingFunction){case"linear":default:return e;case"easeInQuad":return e*e;case"easeOutQuad":return e*(2-e);case"easeInOutQuad":return e<.5?2*e*e:(4-2*e)*e-1;case"easeInCubic":return e*e*e;case"easeOutCubic":return--e*e*e+1;case"easeInOutCubic":return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1}}clearQueue(){this.morphQueue=[]}hasQueuedMorphs(){return this.morphQueue.length>0}getState(){return{isTransitioning:this.isTransitioning,currentShape:this.currentShape,targetShape:this.targetShape,progress:this.transitionProgress,queueLength:this.morphQueue.length}}reset(){this.isTransitioning=!1,this.currentShape="circle",this.targetShape=null,this.transitionProgress=0,this.morphQueue=[],this.shadowConfig=null}}class dr{constructor(e){this._getMorpherState=e}getCurrentShadow(){const e=this._getMorpherState(),t=e.currentShape||"circle",i=rr&&rr.isInitialized?rr.getShape(t):ar[t],s=e.targetShape?rr&&rr.isInitialized?rr.getShape(e.targetShape):ar[e.targetShape]:null,n=i?.shadow||{type:"none"},a=s?.shadow||null;if(!e.isTransitioning||!a)return n;const r=e.morphProgress;if(e.transitionConfig&&"from_moon"===e.transitionConfig.type&&e.transitionConfig.slideOutCrescent)return this._calculateMoonSlideOut(r,e.transitionConfig);if(e.transitionConfig&&"moon_to_lunar"===e.transitionConfig.type)return this._calculateMoonToLunar(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_enter_lunar"===e.transitionConfig.type)return this._calculateEclipseEnterLunar(r,e.transitionConfig);if(e.transitionConfig&&"lunar_to_moon"===e.transitionConfig.type)return this._calculateLunarToMoon(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_exit_lunar"===e.transitionConfig.type)return this._calculateEclipseExitLunar(r,e.transitionConfig);if(e.transitionConfig&&"eclipse_enter"===e.transitionConfig.type)return this._calculateEclipseEnter(r,a);if("eclipse_exit"===e.transitionConfig.type)return this._calculateEclipseExit(r,n);if("sun_fade"===e.transitionConfig.type)return this._calculateSunFade(r,n);if("sun_bloom"===e.transitionConfig.type)return this._calculateSunBloom(r,a);if("none"!==n.type||"none"!==a.type){const e=(n.coverage||0)+((a.coverage||0)-(n.coverage||0))*r;return{type:"none"!==a.type?a.type:n.type,coverage:e,angle:a.angle||n.angle||0,softness:a.softness||n.softness||.2,progress:r}}return n}_calculateMoonSlideOut(e,t){const i=t.shadowSlideRatio||.4;if(e<i){const t=e/i,s=-30*Math.PI/180,n=.7,a=n+(2.5-n)*t;return{type:"crescent",coverage:t>.8?.85*(1-5*(t-.8)):.85,angle:-30,offset:a,shadowX:Math.cos(s)*a,shadowY:Math.sin(s)*a}}return{type:"none"}}_calculateMoonToLunar(e,t){const i=t.startAngle*Math.PI/180,s=1-e,n=.7*Math.cos(i)*s,a=.7*Math.sin(i)*s,r=Math.pow(e,2);if(e<.6)return{type:"crescent",coverage:.85*(1-.2*r),angle:t.startAngle,offset:.7*s,shadowX:n,shadowY:a};{const t=(e-.6)/.4,i=Math.sin(t*Math.PI/2);return{type:"lunar",coverage:.85+.1*i,color:`rgba(80, 20, 0, ${.7+.2*i})`,shadowX:n*(1-i),shadowY:a*(1-i),diffusion:i,shadowProgress:e}}}_calculateEclipseEnterLunar(e,t){if(e<.3)return{type:"none"};const i=(e-.3)/.7,s=Math.sin(i*Math.PI/2),n=t.startAngle*Math.PI/180,a=1-s,r=.7*Math.cos(n)*a,o=.7*Math.sin(n)*a;if(i<.7)return{type:"crescent",coverage:.85*Math.pow(i/.7,.5),angle:t.startAngle,offset:.7*a,shadowX:r,shadowY:o};{const e=(i-.7)/.3,t=Math.sin(e*Math.PI/2);return{type:"lunar",coverage:.85+.1*t,color:`rgba(80, 20, 0, ${.6+.3*t})`,shadowX:r*(1-t),shadowY:o*(1-t),diffusion:t,shadowProgress:i}}}_calculateLunarToMoon(e,t){const i=t.exitAngle*Math.PI/180,s=Math.sin(e*Math.PI/2),n=.7*Math.cos(i)*s,a=.7*Math.sin(i)*s;if(e<.6){const t=e/.6,i=Math.pow(t,.7);return{type:"lunar",coverage:.95-.1*i,color:`rgba(80, 20, 0, ${.9-.3*i})`,shadowX:.7*n,shadowY:.7*a,diffusion:1-i}}{const i=(e-.6)/.4;return{type:"crescent",coverage:.85*Math.sin(i*Math.PI/2)+.1,angle:t.exitAngle,offset:.7,shadowX:n,shadowY:a}}}_calculateEclipseExitLunar(e,t){if(e<.7){const i=e/.7,s=t.exitAngle*Math.PI/180;if(i<.4){const e=i/.4,t=1-e,n=.3*e;return{type:"lunar",coverage:.95-.1*e,color:`rgba(80, 20, 0, ${.9-.2*e})`,shadowX:.7*Math.cos(s)*n,shadowY:.7*Math.sin(s)*n,diffusion:t}}{const e=(i-.4)/.6,n=Math.pow(e,.8),a=.7*Math.cos(s)*n,r=.7*Math.sin(s)*n;return{type:"crescent",coverage:.85*(1-Math.pow(e,2)),angle:t.exitAngle,offset:.7*n,shadowX:a,shadowY:r}}}return{type:"none"}}_calculateEclipseEnter(e,t){return{...t,shadowX:1.5-1.5*e,shadowProgress:e}}_calculateEclipseExit(e,t){const i=1.5*-e;return{...t,coverage:t.coverage*(1-e),shadowX:i,shadowProgress:1-e}}_calculateSunFade(e,t){const i=1-e;return{...t,intensity:(t.intensity||1)*Math.pow(i,.7),corona:t.corona,coronaOpacity:i,flares:t.flares,flaresOpacity:Math.pow(i,1.5),texture:t.texture,textureOpacity:Math.pow(i,2),turbulence:(t.turbulence||.3)*i}}_calculateSunBloom(e,t){const i=e;return{...t,intensity:(t.intensity||1)*Math.pow(i,1.5),corona:t.corona,coronaOpacity:Math.pow(i,.8),flares:t.flares,flaresOpacity:i>.3?Math.pow((i-.3)/.7,.7):0,texture:t.texture,textureOpacity:i>.5?Math.pow((i-.5)/.5,2):0,turbulence:(t.turbulence||.3)*i}}}class gr{constructor(e={}){this.numPoints=e.numPoints||64,this.morphDuration=e.morphDuration||1e3,this.easing=e.easing||"easeInOutCubic",this.transitionManager=new ur(this),this.audioDeformer=new lr(this),this.musicDetector=new cr,this.shadowEffectManager=new dr(()=>({currentShape:this.currentShape,targetShape:this.targetShape,morphProgress:this.morphProgress,isTransitioning:this.isTransitioning,transitionConfig:this.transitionConfig})),this.currentShape="circle",this.targetShape=null,this.morphProgress=0,this.visualProgress=0,this.morphStartTime=null,this.isTransitioning=!1,this.queuedMorphTimeout=null,this.shapeCache=new Map,this.currentPoints=[],this.targetPoints=[],this.musicalDuration=null,this.onBeat=!1,this.audioDeformation=0,this.vocalEnergy=0,this.lastAudioUpdate=0,this.lastVocalUpdate=0,this.audioUpdateInterval=33,this.audioAnalyzer=null,this.frequencyData=or.acquire(32,"float32"),this.glitchPoints=[],this.undulationPhase=0,this.undulationDirection=1,this.beatGlitchIntensity=0,this.bassEnergy=0,this.vocalPresence=0,this.bassHistory=or.acquire(60,"float32"),this.vocalHistory=or.acquire(60,"float32"),this.historyIndex=0,this.bassEffectCooldown=0,this.vocalEffectCooldown=0,this.bassThresholdMultiplier=1.2,this.vocalThresholdMultiplier=1.1,this.bassEffectActive=!1,this.vocalEffectActive=!1,this.transientHoldTime=0,this.vocalGlowBoost=0,this.onComplete=null,this.onProgress=null,this.queuedMorph=null,this.currentPoints=this.getShapePoints("circle"),this.shapesLoaded=!0,this.prewarmCache()}prewarmCache(){["circle","heart","star","sun","moon","lunar","square","triangle"].forEach(e=>{(rr&&rr.isInitialized?rr.hasShape(e):ar[e])&&this.getShapePoints(e)}),[0,.25,.5,.75,1].forEach(e=>{this.applyEasing(e)})}getShapePoints(e){if(!this.shapeCache.has(e)){const t=rr&&rr.isInitialized?rr.getShape(e):ar[e];if(!t||!t.points){const t=ar.circle.points;return this.shapeCache.set(e,t),t}const{points:i}=t;return this.shapeCache.set(e,i),i}return this.shapeCache.get(e)}morphTo(e,t={}){if(!this.shapesLoaded)return;if(e===this.currentShape&&!this.isTransitioning)return;if(this.isTransitioning&&!t.force)return this.queuedMorph={targetShape:e,options:t},"queued";this.isTransitioning&&t.force&&this.completeMorph(!0);const i=this.getTransitionConfig(this.currentShape,e);if(this.targetShape=e,this.targetPoints=this.getShapePoints(e),this.morphStartTime=Date.now(),this.isTransitioning=!0,this.morphProgress=0,this.visualProgress=0,"bar"===t.duration||"beat"===t.duration){const e=6e4/(sn.bpm||120);"bar"===t.duration?this.morphDuration=4*e:this.morphDuration=e,this.musicalDuration=!0,this.onBeat=!1!==t.onBeat}else this.morphDuration=i?.duration||t.duration||1e3,this.musicalDuration=null,this.onBeat=!1;this.morphMode=t.mode||"smooth",this.transitionConfig=i,this.onComplete=t.onComplete,this.onProgress=t.onProgress}update(e){if(this.audioAnalyzer&&this.audioAnalyzer.isAnalyzing){const e=this.audioAnalyzer.getShapeMorpherData();if(e&&e.frequencies)for(let t=0;t<Math.min(e.frequencies.length,this.frequencyData.length);t++)this.frequencyData[t]=e.frequencies[t]}if(this.musicDetector&&this.musicDetector.update(performance.now()),!this.isTransitioning||!this.targetShape)return;const t=Date.now()-this.morphStartTime;if(this.musicalDuration){const e=6e4/(sn.bpm||120),t=this.morphDuration>2*e;this.morphDuration=t?4*e:e}let i=Math.min(t/this.morphDuration,1);if(this.musicalDuration&&this.onBeat){const e=sn.bpm||120;let t;t=e>140?2:e>100?4:8;const s=6e4/e,n=this.morphDuration/s,a=i*n,r=Math.round(a*t)/t,o=Math.min(1,r/n),l=(.3+.5*(e<90?Math.max(.3,(e-60)/30):Math.max(.4,Math.min(1,1-(e-90)/90))))*(.3+.7*Math.sin(i*Math.PI));i+=l*l*(3-2*l)*(o-i)}this.morphProgress=this.applyEasing(i),this.visualProgress=.8*this.visualProgress+.2*this.morphProgress,Math.abs(this.visualProgress-this.morphProgress)<.001&&(this.visualProgress=this.morphProgress),this.onProgress&&this.onProgress(this.morphProgress),this.morphProgress>=1&&(this.visualProgress=1,this.completeMorph())}completeMorph(e=!1){if(this.targetShape&&(this.currentShape=this.targetShape,this.currentPoints=[...this.targetPoints]),this.targetShape=null,this.isTransitioning=!1,this.morphProgress=0,this.visualProgress=0,this.onComplete&&this.onComplete(this.currentShape),!e&&this.queuedMorph){const e=this.queuedMorph;this.queuedMorph=null,this.queuedMorphTimeout=setTimeout(()=>{this.morphTo(e.targetShape,e.options),this.queuedMorphTimeout=null},50)}}hasQueuedMorph(){return null!==this.queuedMorph}clearQueue(){this.queuedMorph=null,this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null)}getCanvasPoints(e,t,i){let s;try{s=this.getInterpolatedPoints()}catch{s=this.generateFallbackCircle()}this.canvasPointsCache||(this.canvasPointsCache=[]);const n=this.canvasPointsCache;if(n.length=0,!s||0===s.length){for(let s=0;s<this.numPoints;s++){const a=s/this.numPoints*Math.PI*2;n.push({x:e+Math.cos(a)*i,y:t+Math.sin(a)*i})}return n}const a=Array.isArray(s)?s:[];for(let s=0;s<a.length;s++){const r=a[s];if(r&&"number"==typeof r.x&&"number"==typeof r.y){const s=e+(r.x-.5)*i*2,a=t+(r.y-.5)*i*2;n.push({x:s,y:a})}else{const r=s/a.length*Math.PI*2;n.push({x:e+Math.cos(r)*i,y:t+Math.sin(r)*i})}}for(;n.length<this.numPoints;){const s=n.length/this.numPoints*Math.PI*2;n.push({x:e+Math.cos(s)*i,y:t+Math.sin(s)*i})}return n}getInterpolatedPoints(){if(this.currentPoints&&0!==this.currentPoints.length||(this.currentPoints=this.generateFallbackCircle()),!this.isTransitioning)return this.applyAudioDeformation(this.currentPoints);const e=[];for(let t=0;t<this.numPoints;t++){const i=this.currentPoints[t],s=this.targetPoints[t];if(!i||!s){const i=t/this.numPoints*Math.PI*2;e.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)});continue}const n=this.visualProgress;let a,r;const o=["square","circle","star","triangle"],l=o.includes(this.currentShape),h=o.includes(this.targetShape);if(l||h){const e=.5,t=.5;if(h&&!l){const o=s.x-e,l=s.y-t;if(n<.3){const s=n/.3;a=i.x+(e-i.x)*s,r=i.y+(t-i.y)*s}else{const i=(n-.3)/.7;a=e+o*i,r=t+l*i}}else if(l&&!h){const o=i.x-e,l=i.y-t;if(n<.5){const e=n/.5;a=i.x-o*e,r=i.y-l*e}else{const i=(n-.5)/.5;a=e+(s.x-e)*i,r=t+(s.y-t)*i}}else{const o=i.x-e,l=i.y-t,h=s.x-e,c=s.y-t;if(n<.5){const e=n/.5;a=i.x-o*e,r=i.y-l*e}else{const i=(n-.5)/.5;a=e+h*i,r=t+c*i}}}else if("spiral"===this.morphMode){const e=n*Math.PI*2,o=.02*Math.sin(e+.2*t)*(1-2*Math.abs(n-.5));a=i.x+(s.x-i.x)*n+o,r=i.y+(s.y-i.y)*n+o}else if("wave"===this.morphMode){const e=.01*Math.sin(.3*t+n*Math.PI*4);a=i.x+(s.x-i.x)*n+e,r=i.y+(s.y-i.y)*n+e}else a=i.x+(s.x-i.x)*n,r=i.y+(s.y-i.y)*n;e.push({x:a,y:r})}return this.applyAudioDeformation(e)}applyAudioDeformation(e){return this.audioDeformer.applyAudioDeformation(e)}setAudioDeformation(e){const t=Date.now();t-this.lastAudioUpdate>this.audioUpdateInterval&&(this.audioDeformation=Math.max(-1,Math.min(1,e)),this.lastAudioUpdate=t,this.audioDeformer&&this.audioDeformer.setAudioDeformation(Math.abs(this.audioDeformation)))}setVocalEnergy(e){const t=Date.now();t-this.lastVocalUpdate>this.audioUpdateInterval&&(this.vocalEnergy=Math.max(0,Math.min(1,e)),this.lastVocalUpdate=t,this.audioDeformer&&this.audioDeformer.setVocalEnergy(this.vocalEnergy))}getTransitionConfig(e,t){const i=rr&&rr.isInitialized?rr.getShape(e):ar[e],s=rr&&rr.isInitialized?rr.getShape(t):ar[t];return"moon"===t?{type:"to_moon",easing:"easeInOutCubic",duration:1500,glowIntensity:1.5,fadeInCrescent:!0}:"moon"===e&&"lunar"===t?{type:"moon_to_lunar",easing:"easeInOutSine",duration:2e3,slideOutCrescent:!1,description:"Crescent shadow moves to center and becomes lunar eclipse"}:"moon"===e?{type:"from_moon",easing:"easeInOutCubic",duration:1e3,slideOutCrescent:!0,shadowSlideRatio:.4,description:"Moon shadow slides away THEN morphs to target"}:"lunar"===t?{type:"eclipse_enter_lunar",startAngle:-30}:"lunar"===e&&"moon"===t?{type:"lunar_to_moon",exitAngle:-30}:"lunar"===e?{type:"eclipse_exit_lunar",exitAngle:-30}:"none"===i?.shadow?.type&&"solar"===s?.shadow?.type?{type:"eclipse_enter",direction:"right"}:"solar"===i?.shadow?.type&&"none"===s?.shadow?.type?{type:"eclipse_exit",direction:"left"}:"sun"===e&&"sun"!==t?{type:"sun_fade",fadeEffects:!0}:"sun"!==e&&"sun"===t?{type:"sun_bloom",bloomEffects:!0}:{type:"standard"}}getCurrentShadow(){return this.shadowEffectManager.getCurrentShadow()}getCurrentRenderer(){return null}applyEasing(e){switch(this.transitionConfig?.easing||this.easing||"linear"){case"linear":return e;case"easeInQuad":return e*e;case"easeOutQuad":return e*(2-e);case"easeInOutQuad":return e<.5?2*e*e:(4-2*e)*e-1;case"easeInOutSine":return-(Math.cos(Math.PI*e)-1)/2;default:return e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2}}calculateBPM(){return this.musicDetector.calculateBPM()}findTempoCandidates(e){return this.musicDetector.findTempoCandidates(e)}clusterIntervals(e){return this.musicDetector.clusterIntervals(e)}checkHarmonicRelation(e,t){return this.musicDetector.checkHarmonicRelation(e,t)}detectTimeSignature(){this.musicDetector.forceFastDetection=this.forceFastDetection;const e=this.musicDetector.detectTimeSignature();return this.detectedTimeSignature=this.musicDetector.detectedTimeSignature,this.timeSignatureConfidence=this.musicDetector.timeSignatureConfidence,this.timeSignatureLocked=this.musicDetector.timeSignatureLocked,e}testWaltzPattern(e,t){return this.musicDetector.testWaltzPattern(e,t)}resetMusicDetection(){this.forceFastDetection=!0,this.musicDetector.reset(),this.musicDetector.forceFastDetection=!0,this.onsetThreshold=0,this.detectedBPM=0,this.bpmConfidence=0,this.onsetStrengths=[],this.detectedTimeSignature=null,this.timeSignatureConfidence=0,this.musicDetector.lastBPMCalculation=0,this.measureStartTime=0,this.timeSignatureHistory=[],this.timeSignatureLocked=!1,this.spectralHistory=[],this.spectralFluxHistory=[];const e=document.getElementById("time-sig-display");e&&(e.textContent="โ")}getCurrentMusicInfo(){return{bpm:this.detectedBPM,timeSignature:this.detectedTimeSignature,bpmLocked:this.tempoLocked,timeSigLocked:this.timeSignatureLocked}}generateFallbackCircle(){const e=[];for(let t=0;t<this.numPoints;t++){const i=t/this.numPoints*Math.PI*2;e.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)})}return e}getState(){return{currentShape:this.currentShape,targetShape:this.targetShape,isTransitioning:this.isTransitioning,progress:this.morphProgress,audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy}}getProgress(e=!0){return e?this.visualProgress:this.morphProgress}isInTransition(){return this.isTransitioning}destroy(){this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null),this.queuedMorph=null,this.shapeCache.clear(),this.canvasPointsCache=null,this.frequencyData&&(or.release(this.frequencyData),this.frequencyData=null),this.bassHistory&&(or.release(this.bassHistory),this.bassHistory=null),this.vocalHistory&&(or.release(this.vocalHistory),this.vocalHistory=null),this.audioAnalyzer=null}}class mr{constructor(){this.audioContext=null,this.analyser=null,this.source=null,this.elementSource=null,this.dataArray=null,this.isAnalyzing=!1,this.connectedElement=null,this.gainNode=null,this.animationFrameId=null,this.frequencyBands=32,this.smoothingFactor=.3,this.vocalRange={min:80,max:1e3},this.currentAmplitude=0,this.currentFrequencies=new Array(this.frequencyBands).fill(0),this.beatThreshold=.3,this.lastBeatTime=0,this.beatCallbacks=[],this._timeDataArray=null,this._boundAnalyze=()=>this.analyze()}init(){try{return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),"suspended"===this.audioContext.state?this.audioContext.resume().then(()=>(this.createAnalyser(),!0)).catch(()=>!1):(this.createAnalyser(),!0)}catch(e){return console.warn("AudioAnalyzer init failed:",e),!1}}createAnalyser(){if(this.audioContext&&!this.analyser){this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,this.analyser.smoothingTimeConstant=.5;const e=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(e),this._timeDataArray=new Uint8Array(e)}}connectAudioElement(e){if(this.audioContext)try{this.elementSource&&this.connectedElement===e||(this.elementSource=this.audioContext.createMediaElementSource(e),this.elementSource.connect(this.analyser),this.elementSource.connect(this.audioContext.destination)),this.source=this.elementSource,this.connectedElement=e,this.isAnalyzing=!0,this.analyze()}catch(t){const i=t instanceof Error?t.message:String(t);i.includes("already been used")?(this.source=this.elementSource,this.connectedElement=e,this.isAnalyzing=!0,this.analyze()):console.warn("[AudioAnalyzer] Unexpected error during connect:",i)}}analyze(){if(!this.isAnalyzing)return;this.animationFrameId=requestAnimationFrame(this._boundAnalyze),this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this._timeDataArray);let e=0,t=0,i=0;const s=this.audioContext.sampleRate/2/this.dataArray.length,n=Math.floor(this.vocalRange.min/s),a=Math.ceil(this.vocalRange.max/s);for(let s=0;s<this.dataArray.length;s++){const r=this.dataArray[s]/255;e+=r,s>=n&&s<=a&&(t+=r,i++)}this.currentAmplitude=e/this.dataArray.length;const r=i>0?t/i:0;return this.extractFrequencyBands(),this.detectBeat(this.currentAmplitude),{amplitude:this.currentAmplitude,vocalAmplitude:r,frequencies:this.currentFrequencies,rawData:this.dataArray}}extractFrequencyBands(){const e=Math.floor(this.dataArray.length/this.frequencyBands);for(let t=0;t<this.frequencyBands;t++){let i=0;const s=t*e,n=Math.min(s+e,this.dataArray.length);for(let e=s;e<n;e++)i+=this.dataArray[e]/255;const a=i/e;this.currentFrequencies[t]=this.currentFrequencies[t]*this.smoothingFactor+a*(1-this.smoothingFactor)}}detectBeat(e){const t=performance.now();e>this.beatThreshold&&t-this.lastBeatTime>60&&(this.lastBeatTime=t,this.beatCallbacks.forEach(t=>t(e)))}getVocalInstability(){let e=0;const t=this.currentFrequencies.reduce((e,t)=>e+t,0)/this.frequencyBands;for(let i=0;i<this.frequencyBands;i++)e+=Math.pow(this.currentFrequencies[i]-t,2);return e=Math.sqrt(e/this.frequencyBands),Math.min(1,2*e+.5*this.currentAmplitude)}getShapeMorpherData(){return{instability:this.getVocalInstability(),frequencies:[...this.currentFrequencies],amplitude:this.currentAmplitude}}onBeat(e){this.beatCallbacks.push(e)}stop(){if(this.isAnalyzing=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.gainNode){try{this.gainNode.disconnect()}catch(e){}this.gainNode=null}if(this.elementSource&&this.connectedElement){try{this.elementSource.connect(this.analyser)}catch(e){}this.source=this.elementSource}}async resume(){this.audioContext&&"suspended"===this.audioContext.state&&await this.audioContext.resume()}destroy(){this.stop(),null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.analyser=null,this.dataArray=null,this._timeDataArray=null,this.beatCallbacks=[]}}var pr=Object.freeze({__proto__:null,AudioAnalyzer:mr});class fr{constructor(){this.timingClasses={downbeat:{gestures:["bounce","jump","headBob","spin","orbit"],timing:1,priority:1,description:"Strong emphasis on the downbeat"},upbeat:{gestures:["wave","nod","point","reach"],timing:.5,priority:2,description:"Medium emphasis on upbeat"},offbeat:{gestures:["wiggle","sway","lean","tilt","groove"],timing:.5,priority:3,description:"Syncopated, creates groove"},subdivision:{gestures:["pulse","sparkle","flash","shimmer","flicker"],timing:.25,priority:4,description:"Quick accents and fills"},continuous:{gestures:["breathe","float","rain"],timing:-1,priority:5,description:"Ambient, continuous motion"}},this.fillPatterns={subtle:["breathe","float"],rhythmic:["pulse","shimmer"],energetic:["wiggle","sparkle"],smooth:["sway","glow"]},this.densityProfiles={sparse:{fillProbability:.1,subdivisionLevel:2,description:"Minimal movement"},moderate:{fillProbability:.3,subdivisionLevel:4,description:"Balanced movement"},dense:{fillProbability:.5,subdivisionLevel:8,description:"Busy, energetic"},chaos:{fillProbability:.8,subdivisionLevel:16,description:"Maximum energy"}},this.groups={movement:{gestures:["bounce","spin","orbit","sway","hula","jump","twist","groove"],maxSimultaneous:1,priority:1,description:"Primary body movements - mutually exclusive"},expression:{gestures:["wave","nod","shake","point","lean","tilt","reach"],maxSimultaneous:2,priority:2,description:"Expressive gestures - can combine up to 2"},dance:{gestures:["headBob","wiggle","runningman","charleston"],maxSimultaneous:1,priority:2,description:"Dance moves - one at a time but can add effects"},effects:{gestures:["pulse","glow","sparkle","flash","shimmer","flicker"],maxSimultaneous:-1,priority:3,description:"Visual effects - all can layer together"},modifiers:{gestures:["breathe","float","rain"],maxSimultaneous:-1,priority:4,description:"Ambient effects - always allowed"}},this.enhancingCombinations=[["bounce","sparkle"],["spin","glow"],["wave","pulse"],["nod","pulse"],["jump","flash"],["sway","breathe"],["float","shimmer"],["orbit","sparkle"],["headBob","pulse"]],this.incompatiblePairs=[["bounce","jump"],["spin","orbit"],["wave","point"],["nod","shake"],["lean","tilt"]],this.chords={celebrate:["bounce","sparkle","pulse"],greeting:["wave","nod","glow"],excited:["jump","flash","wiggle"],mystical:["float","shimmer","breathe"],party:["headBob","pulse","sparkle"],smooth:["sway","glow","breathe"],dramatic:["spin","flash","sparkle"]},this.chains={rise:"breathe > sway+lean+tilt",flow:"sway > lean+tilt > spin > bounce",burst:"jump > nod > shake > flash",drift:"sway+breathe+float+drift",chaos:"shake+shake > spin+flash > bounce+pulse > twist+sparkle",morph:"expand > contract > morph+glow > expand+flash",rhythm:"pulse > pulse+sparkle > pulse+flicker",spiral:"spin > orbital > twist > orbital+sparkle",routine:"nod > bounce > spin+sparkle > sway+pulse > nod+flash",radiance:"sparkle > pulse+flicker > shimmer",twinkle:"sparkle > flash > pulse+sparkle > shimmer+flicker",stream:"wave > nod+pulse > sparkle > flash",buildup:"pulse > pulse > bounce+sparkle > spin+flash",cascade:"wave > lean > tilt > spin > bounce+glow",celebrate:"bounce+sparkle > spin > jump+flash > nod+pulse",smooth:"sway+breathe > float > orbit+shimmer > sway+glow",custom:"expand > contract > morph > expand+glow",greeting:"wave+glow > nod+pulse > wave",mystical:"float+shimmer > orbit+breathe > spin+sparkle > float+glow"}}canExecuteSimultaneously(e,t){if(e===t)return!1;if(this.incompatiblePairs.some(i=>i.includes(e)&&i.includes(t)))return!1;const i=this.getGestureGroup(e),s=this.getGestureGroup(t);if(i===s){const e=this.groups[i];return e&&1!==e.maxSimultaneous}return!("movement"===i&&"movement"===s||"dance"===i&&"dance"===s)}getGestureGroup(e){for(const[t,i]of Object.entries(this.groups))if(i.gestures.includes(e))return t;return null}getGesturePriority(e){const t=this.getGestureGroup(e);return t?this.groups[t].priority:99}getCompatibleGestures(e){if(!e||0===e.length)return[];if(1===e.length)return e;const t=[],i=new Set,s=e=>"string"==typeof e?e:e.gestureName,n=[...e].sort((e,t)=>this.getGesturePriority(s(e))-this.getGesturePriority(s(t)));for(const e of n){if(i.has(e))continue;const n=s(e);let a=!0;for(const e of t){const t=s(e);if(!this.canExecuteSimultaneously(n,t)){a=!1;break}}if(a){const a=this.groups[this.getGestureGroup(n)];if(a&&a.maxSimultaneous>0&&t.filter(e=>this.getGestureGroup(s(e))===this.getGestureGroup(n)).length>=a.maxSimultaneous)continue;t.push(e),i.add(e)}}return t}parseChain(e){return e?(this.chains[e]&&(e=this.chains[e]),e.split(">").map(e=>e.trim()).map(e=>e.split("+").map(e=>e.trim()).filter(e=>e))):[]}isEnhancingCombination(e){const t=e.map(e=>"string"==typeof e?e:e.gestureName);return this.enhancingCombinations.some(e=>e.every(e=>t.includes(e)))}getChord(e){return this.chords[e]||null}createChord(e){const t=this.getCompatibleGestures(e),i=this.isEnhancingCombination(t);return{type:"chord",gestures:t.map(e=>"string"==typeof e?e:e.gestureName),isEnhancing:i,timestamp:Date.now()}}isValidGesture(e){return null!==this.getGestureGroup(e)}getAllGestures(){const e=[];for(const t of Object.values(this.groups))e.push(...t.gestures);return[...new Set(e)]}getGestureTiming(e){for(const[t,i]of Object.entries(this.timingClasses))if(i.gestures.includes(e))return{name:t,...i};return null}getNextBeatForGesture(e,t,i=1){const s=this.getGestureTiming(e);if(!s)return t+1;if(-1===s.timing)return t;const n=s.timing/i,a=Math.ceil(t/n)*n;return"offbeat"===s.name?a+.5:a}getFillGestures(e,t="moderate"){const i=this.densityProfiles[t]||this.densityProfiles.moderate;let s;return s=e<80?"energetic":e<120?"rhythmic":e<160?"smooth":"subtle",Math.random()<i.fillProbability&&this.fillPatterns[s]||[]}getNextBeatTiming(e,t,i){return this.getNextBeatForGesture(e,t)}getIntensityFromBPM(e){return e<60?"dense":e<100||e<140?"moderate":"sparse"}applySwingTiming(e,t=.67){return.5==e%1?Math.floor(e)+t:e}}const yr=new fr;var br=Object.freeze({__proto__:null,GestureCompatibility:fr,default:yr});class vr{constructor(){this.templates={straight:{name:"Straight",timeSignature:"4/4",baseMovement:"grooveBob",transitionStyle:"transitionLean",pattern:{emphasis:[1,0,.5,0],velocities:[1,0,.6,0],subdivisions:[0,.5]},swing:0,humanization:.05,preferredGestures:{downbeat:["bounce","headBob","jump"],offbeat:["pulse","breathe"],fills:["sparkle","glow"]},compositeMove:null,intensity:"moderate",description:"Standard 4/4 rhythm, good for pop/rock"},swing:{name:"Swing",timeSignature:"4/4",baseMovement:"grooveFlow",transitionStyle:"transitionGlide",compositeMove:"swingOut",pattern:{emphasis:[1,0,.66,0],velocities:[1,0,.7,0],subdivisions:[0,.66]},swing:.67,humanization:.08,preferredGestures:{downbeat:["sway","lean","bounce"],offbeat:["wiggle","pulse"],fills:["shimmer","float"]},intensity:"moderate",description:"Jazz swing feel with triplet subdivision"},shuffle:{name:"Shuffle",timeSignature:"4/4",baseMovement:"grooveBob",transitionStyle:"transitionLean",compositeMove:null,pattern:{emphasis:[1,.25,.5,.75],velocities:[1,.3,.7,.3],subdivisions:[0,.25,.5,.75]},swing:.75,humanization:.06,preferredGestures:{downbeat:["bounce","headBob"],upbeat:["twist","wiggle"],offbeat:["pulse","breathe"],fills:["sparkle","flash"]},intensity:"dense",description:"Blues/rock shuffle with heavy swing"},latin:{name:"Latin",timeSignature:"4/4",baseMovement:"grooveSway",transitionStyle:"transitionRoll",compositeMove:"latinHips",pattern:{emphasis:[1,0,.375,.5,0,.75,0,0],velocities:[1,0,.8,.9,0,.8,0,0],subdivisions:[0,.375,.5,.75]},swing:0,humanization:.04,preferredGestures:{downbeat:["sway","wiggle"],syncopation:["twist","lean"],offbeat:["pulse","shimmer"],fills:["sparkle","shake"]},intensity:"dense",description:"Latin clave rhythm with syncopation"},breakbeat:{name:"Breakbeat",timeSignature:"4/4",baseMovement:"grooveStep",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[1,0,0,.75,.25,.5,0,.625],velocities:[1,0,0,.9,.6,.8,0,.7],subdivisions:[0,.25,.5,.625,.75]},swing:0,humanization:.03,preferredGestures:{downbeat:["bounce","twist"],syncopation:["flash","shake"],offbeat:["pulse","wiggle"],fills:["sparkle","glitch"]},intensity:"chaos",description:"Hip-hop/DnB breakbeat pattern"},waltz:{name:"Waltz",timeSignature:"3/4",baseMovement:"grooveFlow",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[1,.33,.67],velocities:[1,.5,.5],subdivisions:[0,.33,.67]},swing:0,humanization:.07,preferredGestures:{downbeat:["sway","float"],weak:["breathe","lean"],fills:["shimmer","glow"]},intensity:"sparse",description:"3/4 waltz time"},techno:{name:"Techno",timeSignature:"4/4",baseMovement:"groovePulse",transitionStyle:"transitionLean",compositeMove:"robotPop",pattern:{emphasis:[1,.25,.5,.75,1,.25,.5,.75],velocities:[1,.6,1,.6,1,.6,1,.6],subdivisions:[0,.25,.5,.75]},swing:0,humanization:.02,preferredGestures:{downbeat:["pulse","bounce"],subdivision:["flash","glitch"],fills:["sparkle","strobe"]},intensity:"dense",description:"Driving techno four-on-the-floor"},ambient:{name:"Ambient",timeSignature:"4/4",baseMovement:"groovePulse",transitionStyle:"transitionGlide",compositeMove:null,pattern:{emphasis:[.8,0,.3,0,.5,0,.3,0],velocities:[.8,0,.3,0,.5,0,.3,0],subdivisions:[0,.5]},swing:0,humanization:.15,preferredGestures:{downbeat:["float","breathe"],offbeat:["sway","shimmer"],fills:["glow","pulse"]},intensity:"sparse",description:"Floating ambient rhythm"},funk:{name:"Funk",timeSignature:"4/4",baseMovement:"grooveSway",transitionStyle:"transitionRoll",compositeMove:"funkChicken",pattern:{emphasis:[1.2,.125,.25,0,.625,.75,0,.875],velocities:[1.2,.3,.4,0,.8,.6,0,.4],subdivisions:[0,.125,.25,.625,.75,.875]},swing:.1,humanization:.06,preferredGestures:{one:["bounce","twist"],ghost:["wiggle","pulse"],syncopation:["lean","shake"],fills:["flash","sparkle"]},intensity:"chaos",description:"Funky syncopated rhythm with THE ONE"},trap:{name:"Trap",timeSignature:"4/4",baseMovement:"grooveStep",transitionStyle:"transitionLean",compositeMove:null,pattern:{emphasis:[1,0,0,.375,0,.75,.875,0],velocities:[1,0,0,.7,0,.8,.6,0],subdivisions:[0,.375,.75,.875]},swing:0,humanization:.03,preferredGestures:{downbeat:["bounce","lean"],hihat:["shake","shimmer"],syncopation:["twist","flash"],fills:["sparkle","glitch"]},intensity:"moderate",description:"Trap rhythm with triplet hi-hats"}},this.transitions={instant:0,nextBar:1,nextPhrase:4,fadeIn:8},this.currentGroove=null,this.transitionMode="nextBar",this.pendingGroove=null}getTemplate(e){return this.templates[e.toLowerCase()]||this.templates.straight}getEmphasis(e,t,i){if(!e||!e.pattern)return 0;const s=e.pattern.subdivisions.findIndex(e=>Math.abs(e-i)<.01);return-1===s?0:e.pattern.emphasis[s]||0}getVelocity(e,t,i){if(!e||!e.pattern)return 1;const s=e.pattern.subdivisions.findIndex(e=>Math.abs(e-i)<.01);return-1===s?0:e.pattern.velocities[s]||0}getPreferredGesture(e,t,i,s=[]){if(!e||!e.preferredGestures)return null;let n;n=0===i?"downbeat":.5===i?"offbeat":.25===i||.75===i?"subdivision":"syncopation","Funk"===e.name&&t%4==0&&0===i&&(n="one");const a=e.preferredGestures[n]||e.preferredGestures.fills;if(!a||0===a.length)return null;if(s.length>0){const e=a.filter(e=>s.includes(e));if(e.length>0)return e[Math.floor(Math.random()*e.length)]}return a[Math.floor(Math.random()*a.length)]}humanizeTiming(e,t){if(!e||!e.humanization)return t;const i=e.humanization,s=(Math.random()-.5)*i;return Math.max(0,Math.min(1,t+s))}applySwing(e,t){return e&&e.swing&&0!==e.swing?Math.abs(t-.5)<.01?.5+.5*(e.swing-.5):Math.abs(t-.25)<.01?.25+.25*(e.swing-.5):Math.abs(t-.75)<.01?.75+.25*(e.swing-.5):t:t}setGroove(e,t=null){const i=this.getTemplate(e);return!!i&&("instant"!==(t||this.transitionMode)&&this.currentGroove?this.pendingGroove=i:(this.currentGroove=i,this.pendingGroove=null),!0)}onBeat(e){this.pendingGroove&&("nextBar"===this.transitionMode&&e%4==0||"nextPhrase"===this.transitionMode&&e%16==0)&&(this.currentGroove=this.pendingGroove,this.pendingGroove=null)}getBaseMovement(){return this.currentGroove?.baseMovement||null}getTransitionStyle(){return this.currentGroove?.transitionStyle||"transitionLean"}getCompositeMove(){return this.currentGroove?.compositeMove||null}shouldTriggerComposite(e){return!!this.currentGroove?.compositeMove&&e%("sparse"===this.currentGroove.intensity?32:16)==0}getLayeredGestures(e,t){if(!this.currentGroove)return null;const i={base:this.getBaseMovement(),accent:null,transition:null,composite:null,velocity:1};this.shouldTriggerComposite(e)&&0===t&&(i.composite=this.getCompositeMove());const s=this.getEmphasis(this.currentGroove,e,t),n=this.getVelocity(this.currentGroove,e,t);return s>.3&&n>.3&&(i.accent=this.getPreferredGesture(this.currentGroove,e,t),i.velocity=n),i.accent&&Math.random()<.3&&(i.transition=this.getTransitionStyle()),i}getGrooveNames(){return Object.keys(this.templates)}getGrooveInfo(e){const t=this.templates[e];return t?{name:t.name,timeSignature:t.timeSignature,description:t.description,intensity:t.intensity,swing:t.swing,baseMovement:t.baseMovement,compositeMove:t.compositeMove}:null}}const Mr={listening:{name:"listening",category:"conversational",emotion:"curiosity",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:400,description:"User is speaking, AI is listening attentively"},thinking:{name:"thinking",category:"conversational",emotion:"focused",gesture:"breathe",delay:100,baseIntensity:.7,emotionDuration:500,description:"AI is processing and thinking"},acknowledging:{name:"acknowledging",category:"conversational",emotion:"calm",gesture:"nod",delay:150,baseIntensity:.7,emotionDuration:400,description:"AI acknowledges understanding"},guiding:{name:"guiding",category:"conversational",emotion:"calm",gesture:"point",delay:200,baseIntensity:.7,emotionDuration:500,description:"AI provides guidance or instructions"},empathizing:{name:"empathizing",category:"conversational",emotion:"empathy",baseIntensity:.8,emotionDuration:600,description:"AI shows empathy and understanding",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.8},{at:200,action:"gesture",value:"shake"},{at:700,action:"gesture",value:"nod"}]},celebrating:{name:"celebrating",category:"conversational",emotion:"joy",baseIntensity:.9,emotionDuration:500,description:"AI celebrates success with user",sequence:[{at:0,action:"emotion",value:"joy",intensity:.9},{at:200,action:"gesture",value:"bounce"},{at:800,action:"emotion",value:"triumph",intensity:1},{at:900,action:"gesture",value:"glow"}]},celebrating_epic:{name:"celebrating_epic",category:"conversational",emotion:"triumph",baseIntensity:1,emotionDuration:500,description:"Epic celebration with visual transformation",sequence:[{at:0,action:"emotion",value:"joy",intensity:.9},{at:200,action:"gesture",value:"bounce"},{at:700,action:"emotion",value:"triumph",intensity:1},{at:800,action:"gesture",value:"glow"},{at:1e3,action:"morph",value:"sun"},{at:1e3,action:"chain",value:"radiance"}]},reassuring:{name:"reassuring",category:"conversational",emotion:"calm",baseIntensity:.8,emotionDuration:600,description:"AI provides reassurance and comfort",sequence:[{at:0,action:"emotion",value:"calm",intensity:.8},{at:200,action:"gesture",value:"breathe"},{at:800,action:"gesture",value:"wave"}]},offering_help:{name:"offering_help",category:"conversational",emotion:"empathy",baseIntensity:.8,emotionDuration:500,description:"AI offers assistance",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.8},{at:200,action:"gesture",value:"nod"},{at:600,action:"gesture",value:"point"}]},offering_urgent_help:{name:"offering_urgent_help",category:"conversational",emotion:"empathy",baseIntensity:1,emotionDuration:400,description:"AI urgently offers help for frustrated user",sequence:[{at:0,action:"emotion",value:"empathy",intensity:1},{at:150,action:"gesture",value:"shake"},{at:400,action:"gesture",value:"nod"},{at:700,action:"gesture",value:"point"}]},apologizing:{name:"apologizing",category:"conversational",emotion:"empathy",baseIntensity:.85,emotionDuration:600,description:"AI apologizes for mistake or error",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.85},{at:200,action:"gesture",value:"shake"},{at:600,action:"gesture",value:"breathe"}]},encouraging:{name:"encouraging",category:"conversational",emotion:"joy",gesture:"nod",delay:200,baseIntensity:.75,emotionDuration:500,description:"AI encourages user to continue"},greeting:{name:"greeting",category:"conversational",emotion:"joy",gesture:"wave",delay:200,baseIntensity:.7,emotionDuration:500,description:"AI greets user warmly"},responding_positive:{name:"responding_positive",category:"conversational",emotion:"joy",gesture:"bounce",delay:150,baseIntensity:.75,emotionDuration:500,description:"AI responds with positive sentiment"},responding_neutral:{name:"responding_neutral",category:"conversational",emotion:"calm",gesture:"drift",delay:150,baseIntensity:.6,emotionDuration:500,description:"AI responds with neutral sentiment"},responding_negative:{name:"responding_negative",category:"conversational",emotion:"empathy",gesture:"shake",delay:150,baseIntensity:.8,emotionDuration:600,description:"AI responds to negative situation"},success_minor:{name:"success_minor",category:"feedback",emotion:"joy",gesture:"bounce",delay:150,baseIntensity:.7,emotionDuration:500,description:"Small success (item scanned, form field validated)"},success_moderate:{name:"success_moderate",category:"feedback",emotion:"joy",baseIntensity:.8,emotionDuration:500,description:"Moderate success (section completed, task done)",sequence:[{at:0,action:"emotion",value:"joy",intensity:.8},{at:200,action:"gesture",value:"bounce"},{at:600,action:"gesture",value:"wiggle"}]},success_major:{name:"success_major",category:"feedback",emotion:"triumph",baseIntensity:.9,emotionDuration:500,description:"Major success (milestone reached, goal achieved)",sequence:[{at:0,action:"emotion",value:"joy",intensity:.85},{at:150,action:"gesture",value:"bounce"},{at:500,action:"emotion",value:"triumph",intensity:.9},{at:600,action:"gesture",value:"glow"}]},success_epic:{name:"success_epic",category:"feedback",emotion:"triumph",baseIntensity:1,emotionDuration:500,description:"Epic success with visual transformation",sequence:[{at:0,action:"emotion",value:"triumph",intensity:1},{at:200,action:"gesture",value:"glow"},{at:700,action:"morph",value:"sun"},{at:700,action:"chain",value:"radiance"}]},error_minor:{name:"error_minor",category:"feedback",emotion:"concern",gesture:"shake",delay:150,baseIntensity:.6,emotionDuration:500,description:"Minor error, easily recoverable"},error_moderate:{name:"error_moderate",category:"feedback",emotion:"empathy",baseIntensity:.75,emotionDuration:600,description:"Moderate error, needs user action",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.75},{at:200,action:"gesture",value:"shake"},{at:600,action:"gesture",value:"nod"}]},error_major:{name:"error_major",category:"feedback",emotion:"empathy",baseIntensity:.9,emotionDuration:600,description:"Major error, needs help",sequence:[{at:0,action:"emotion",value:"empathy",intensity:.9},{at:150,action:"gesture",value:"shake"},{at:500,action:"gesture",value:"nod"},{at:800,action:"gesture",value:"point"}]},error_critical:{name:"error_critical",category:"feedback",emotion:"empathy",baseIntensity:1,emotionDuration:500,description:"Critical error, urgent attention needed",sequence:[{at:0,action:"emotion",value:"empathy",intensity:1},{at:100,action:"gesture",value:"shake"},{at:400,action:"gesture",value:"point"}]},warning:{name:"warning",category:"feedback",emotion:"concern",gesture:"pulse",delay:150,baseIntensity:.7,emotionDuration:500,description:"Warning, needs attention"},info:{name:"info",category:"feedback",emotion:"neutral",gesture:"drift",delay:100,baseIntensity:.5,emotionDuration:400,description:"Informational, passive notification"},progress_start:{name:"progress_start",category:"feedback",emotion:"anticipation",gesture:"pulse",delay:100,baseIntensity:.6,emotionDuration:500,description:"Starting a process"},progress_ongoing:{name:"progress_ongoing",category:"feedback",emotion:"focused",gesture:"breathe",delay:0,baseIntensity:.7,emotionDuration:600,description:"Process ongoing, working"},progress_complete:{name:"progress_complete",category:"feedback",emotion:"satisfaction",gesture:"glow",delay:200,baseIntensity:.8,emotionDuration:500,description:"Process completed successfully"},idle:{name:"idle",category:"state",emotion:"neutral",gesture:"drift",delay:0,baseIntensity:.5,emotionDuration:600,description:"System idle, waiting for user"},ready:{name:"ready",category:"state",emotion:"neutral",gesture:"wave",delay:200,baseIntensity:.6,emotionDuration:500,description:"System ready for interaction"},waiting:{name:"waiting",category:"state",emotion:"anticipation",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:600,description:"System waiting for process to complete",loop:!0,loopInterval:1500},processing:{name:"processing",category:"state",emotion:"focused",gesture:"breathe",delay:0,baseIntensity:.7,emotionDuration:600,description:"System actively processing",loop:!0,loopInterval:1200},scanning:{name:"scanning",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.75,emotionDuration:500,description:"Scanning or searching",loop:!0,loopInterval:1e3},analyzing:{name:"analyzing",category:"state",emotion:"curiosity",gesture:"drift",delay:0,baseIntensity:.7,emotionDuration:600,description:"Analyzing data or input",loop:!0,loopInterval:1400},completing:{name:"completing",category:"state",emotion:"anticipation",gesture:"pulse",delay:100,baseIntensity:.8,emotionDuration:500,description:"Final step, about to complete"},completed:{name:"completed",category:"state",emotion:"satisfaction",gesture:"glow",delay:200,baseIntensity:.85,emotionDuration:500,description:"Process completed successfully"},reviewing:{name:"reviewing",category:"state",emotion:"satisfaction",gesture:"drift",delay:0,baseIntensity:.65,emotionDuration:600,description:"Reviewing information or results"},monitoring:{name:"monitoring",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.6,emotionDuration:700,description:"Actively monitoring for changes",loop:!0,loopInterval:2e3},paused:{name:"paused",category:"state",emotion:"neutral",gesture:"breathe",delay:200,baseIntensity:.5,emotionDuration:600,description:"System paused, can resume"},loading:{name:"loading",category:"state",emotion:"anticipation",gesture:"pulse",delay:0,baseIntensity:.65,emotionDuration:500,description:"Loading data or content",loop:!0,loopInterval:1100},connecting:{name:"connecting",category:"state",emotion:"anticipation",gesture:"drift",delay:0,baseIntensity:.6,emotionDuration:600,description:"Establishing connection",loop:!0,loopInterval:1300},active:{name:"active",category:"state",emotion:"focused",gesture:"pulse",delay:0,baseIntensity:.75,emotionDuration:500,description:"System actively engaged"}};class wr{constructor(e={}){this.performances=new Map,this.contextManager=null,this.sequenceExecutor=null,this.eventManager=e.eventManager||null,this.defaultIntensity=e.defaultIntensity||.7,this.enableContextAdjustment=!1!==e.enableContextAdjustment,this.enableAnalytics=e.enableAnalytics||!1,this.performanceHistory=[],this.maxHistorySize=e.maxHistorySize||100,this.loadBuiltInPerformances()}loadBuiltInPerformances(){Object.entries(Mr).forEach(([e,t])=>{this.definePerformance(e,t)})}definePerformance(e,t){this.performances.set(e,{...t,name:e}),this.eventManager&&this.eventManager.emit("performanceDefined",{name:e,definition:t})}getPerformance(e){return this.performances.get(e)||null}hasPerformance(e){return this.performances.has(e)}async perform(e,t={}){const i=this.getPerformance(e);if(!i)return void console.warn(`[PerformanceSystem] Unknown performance: ${e}`);const s=this.calculateIntensity(i,t),n={performance:i,semanticAction:e,intensity:s,options:t,timestamp:Date.now()};this.enableAnalytics&&this.recordPerformance(n),this.eventManager&&this.eventManager.emit("performanceStart",n);try{this.sequenceExecutor&&i.sequence?await this.sequenceExecutor.execute(i.sequence,{intensity:s,...t}):await this.executeSimplePerformance(i,s,t),this.eventManager&&this.eventManager.emit("performanceComplete",n)}catch(t){console.error(`[PerformanceSystem] Error executing ${e}:`,t),this.eventManager&&this.eventManager.emit("performanceError",{...n,error:t})}}async executeSimplePerformance(e,t,i){const{emotion:s,gesture:n,delay:a=0}=e,r=i.mascot||this.mascot;if(r){if(s&&"function"==typeof r.setEmotion){const t=void 0!==i.emotionDuration?i.emotionDuration:e.emotionDuration||500;r.setEmotion(s,t)}n&&"function"==typeof r.express&&(a>0&&await new Promise(e=>setTimeout(e,a)),r.express(n))}else console.warn("[PerformanceSystem] No mascot instance available")}calculateIntensity(e,t){if(void 0!==t.intensity)return Math.max(0,Math.min(1,t.intensity));let i=e.baseIntensity||this.defaultIntensity;if(this.enableContextAdjustment&&t.context){const{context:e}=t;void 0!==e.frustration&&(i+=e.frustration/100*.3),"high"===e.urgency?i+=.2:"medium"===e.urgency&&(i+=.1),"epic"===e.magnitude?i=1:"major"===e.magnitude&&(i=Math.max(i,.9))}return Math.max(0,Math.min(1,i))}recordPerformance(e){this.performanceHistory.push({action:e.semanticAction,intensity:e.intensity,context:e.options.context||{},timestamp:e.timestamp}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift()}getAnalytics(){if(!this.enableAnalytics)return{enabled:!1};const e=this.performanceHistory.length,t={},i={};return this.performanceHistory.forEach(e=>{t[e.action]||(t[e.action]=0,i[e.action]=[]),t[e.action]++,i[e.action].push(e.intensity)}),Object.keys(i).forEach(e=>{const t=i[e];i[e]=t.reduce((e,t)=>e+t,0)/t.length}),{enabled:!0,total:e,byAction:t,avgIntensity:i,history:this.performanceHistory.slice(-20)}}clearAnalytics(){this.performanceHistory=[]}setMascot(e){this.mascot=e}setContextManager(e){this.contextManager=e}setSequenceExecutor(e){this.sequenceExecutor=e}listPerformances(){return Array.from(this.performances.keys())}getPerformanceMetadata(e){const t=this.getPerformance(e);return t?{name:t.name,category:t.category||"custom",emotion:t.emotion,gesture:t.gesture,hasSequence:!!t.sequence,baseIntensity:t.baseIntensity||this.defaultIntensity,description:t.description||""}:null}}class Sr{constructor(e={}){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory=!1!==e.enableHistory,this.historyLimit=e.historyLimit||50,this.history=[],this.enableDecay=!1!==e.enableDecay,this.frustrationDecayRate=e.frustrationDecayRate||5,this.decayInterval=e.decayInterval||1e4,this.decayTimer=null,this.enableDecay&&this.startDecayTimer()}update(e={}){const t={...this.context};void 0!==e.frustration&&(this.context.frustration=Math.max(0,Math.min(100,e.frustration))),void 0!==e.urgency&&(["low","medium","high"].includes(e.urgency)?this.context.urgency=e.urgency:console.warn(`[ContextManager] Invalid urgency: ${e.urgency}`)),void 0!==e.magnitude&&(["small","moderate","major","epic"].includes(e.magnitude)?this.context.magnitude=e.magnitude:console.warn(`[ContextManager] Invalid magnitude: ${e.magnitude}`)),void 0!==e.custom&&(this.context.customValues={...this.context.customValues,...e.custom}),this.enableHistory&&this.addToHistory(t,this.context,e),this.enableDecay&&this.restartDecayTimer()}incrementFrustration(e=10){this.update({frustration:this.context.frustration+e})}decrementFrustration(e=10){this.update({frustration:this.context.frustration-e})}resetFrustration(){this.update({frustration:0})}setUrgency(e){this.update({urgency:e})}setMagnitude(e){this.update({magnitude:e})}setCustom(e,t){this.update({custom:{[e]:t}})}getContext(){return{...this.context}}get(e){return e in this.context?this.context[e]:this.context.customValues[e]}calculateIntensity(e=.5,t={}){let i=e;return!1!==t.useFrustration&&(i+=this.context.frustration/100*.3),!1!==t.useUrgency&&(i+={low:-.1,medium:0,high:.2}[this.context.urgency]||0),!1!==t.useMagnitude&&(i+={small:-.1,moderate:0,major:.15,epic:.3}[this.context.magnitude]||0),void 0!==t.intensityMultiplier&&(i*=t.intensityMultiplier),Math.max(0,Math.min(1,i))}addToHistory(e,t,i){const s={timestamp:Date.now(),previous:e,current:{...t},updates:i,delta:{frustration:t.frustration-e.frustration,urgency:t.urgency!==e.urgency?t.urgency:null,magnitude:t.magnitude!==e.magnitude?t.magnitude:null}};this.history.push(s),this.history.length>this.historyLimit&&this.history.shift()}getHistory(e){return e?this.history.slice(-e):[...this.history]}clearHistory(){this.history=[]}startDecayTimer(){this.decayTimer=setInterval(()=>{if(this.context.frustration>0){const e=Math.max(0,this.context.frustration-this.frustrationDecayRate);this.update({frustration:e})}},this.decayInterval)}restartDecayTimer(){this.decayTimer&&(clearInterval(this.decayTimer),this.startDecayTimer())}stopDecay(){this.decayTimer&&(clearInterval(this.decayTimer),this.decayTimer=null)}reset(){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory&&this.addToHistory({},this.context,{action:"reset"})}getAnalytics(){if(!this.enableHistory||0===this.history.length)return null;const e=this.history.map(e=>e.current.frustration),t=e.reduce((e,t)=>e+t,0)/e.length,i=Math.max(...e),s=Math.min(...e),n=this.history.reduce((e,t)=>(e[t.current.urgency]=(e[t.current.urgency]||0)+1,e),{}),a=this.history.reduce((e,t)=>(e[t.current.magnitude]=(e[t.current.magnitude]||0)+1,e),{});return{current:{...this.context},frustration:{current:this.context.frustration,average:t,max:i,min:s},urgency:{current:this.context.urgency,distribution:n},magnitude:{current:this.context.magnitude,distribution:a},historyLength:this.history.length,firstUpdate:this.history[0]?.timestamp,lastUpdate:this.history[this.history.length-1]?.timestamp}}destroy(){this.stopDecay(),this.history=[],this.context=null}}class xr{constructor(e={}){this.mascot=e.mascot||null,this.eventManager=e.eventManager||null,this.activeSequences=new Map,this.nextSequenceId=1,this.defaultDelay=e.defaultDelay||0,this.allowConcurrent=!1!==e.allowConcurrent}async execute(e,t={}){if(!Array.isArray(e)||0===e.length)return;const i=t.mascot||this.mascot;if(!i)return void console.warn("[SequenceExecutor] No mascot instance available");!this.allowConcurrent&&this.activeSequences.size>0&&this.cancelAll();const s=this.nextSequenceId++,n=[...e].sort((e,t)=>e.at-t.at),a={cancelled:!1};this.activeSequences.set(s,a);try{this.eventManager&&this.eventManager.emit("sequenceStart",{sequenceId:s,steps:n,timestamp:Date.now()}),await this.executeSteps(n,i,a,t),this.eventManager&&this.eventManager.emit("sequenceComplete",{sequenceId:s,timestamp:Date.now()})}catch(e){console.error("[SequenceExecutor] Sequence execution error:",e),this.eventManager&&this.eventManager.emit("sequenceError",{sequenceId:s,error:e,timestamp:Date.now()})}finally{this.activeSequences.delete(s)}}async executeSteps(e,t,i,s){let n=0;for(const a of e){if(i.cancelled)break;const e=a.at-n;if(e>0&&await this.sleep(e,i),i.cancelled)break;await this.executeStep(a,t,s),n=a.at}}executeStep(e,t,i){const{action:s,value:n,intensity:a,options:r}=e;try{switch(s){case"emotion":if("function"==typeof t.setEmotion){const e=void 0!==a?a:i.intensity,s=r?.duration||i.emotionDuration||500;t.setEmotion(n,void 0!==e?e:s)}break;case"gesture":"function"==typeof t.express&&t.express(n,r);break;case"morph":"function"==typeof t.morphTo&&t.morphTo(n,r);break;case"chain":"function"==typeof t.chain&&t.chain(n,r);break;case"sound":"function"==typeof t.playSound&&t.playSound(n,r);break;default:console.warn(`[SequenceExecutor] Unknown action: ${s}`)}this.eventManager&&this.eventManager.emit("stepExecuted",{action:s,value:n,timestamp:Date.now()})}catch(t){console.error("[SequenceExecutor] Error executing step:",e,t),this.eventManager&&this.eventManager.emit("stepError",{action:s,value:n,error:t,timestamp:Date.now()})}}sleep(e,t){return new Promise(i=>{const s=setTimeout(()=>{t&&(t._sleepTimeout=null),i()},e);t&&(t._sleepTimeout=s,t._sleepResolve=i)})}cancel(e){const t=this.activeSequences.get(e);t&&(t.cancelled=!0,t._sleepTimeout&&(clearTimeout(t._sleepTimeout),t._sleepTimeout=null),t._sleepResolve&&(t._sleepResolve(),t._sleepResolve=null),this.activeSequences.delete(e),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:e,timestamp:Date.now()}))}cancelAll(){this.activeSequences.forEach((e,t)=>{e.cancelled=!0,e._sleepTimeout&&(clearTimeout(e._sleepTimeout),e._sleepTimeout=null),e._sleepResolve&&(e._sleepResolve(),e._sleepResolve=null),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:t,timestamp:Date.now()})}),this.activeSequences.clear()}getActiveCount(){return this.activeSequences.size}isActive(){return this.activeSequences.size>0}setMascot(e){this.mascot=e}}let Cr=class{constructor(e){if(!e.errorBoundary)throw new Error("GestureController: errorBoundary required");if(!e.config)throw new Error("GestureController: config required");if(!e.state)throw new Error("GestureController: state required");if(!e.throttledWarn)throw new Error("GestureController: throttledWarn required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this.performanceMonitor=e.performanceMonitor||null,this.soundSystem=e.soundSystem||null,this.config=e.config,this._state=e.state,this._throttledWarn=e.throttledWarn,this._chainTarget=e.chainTarget||this,this.currentGesture=null,this.gestureCompatibility=null,this.rendererMethods={bounce:"startBounce",pulse:"startPulse",shake:"startShake",spin:"startSpin",nod:"startNod",tilt:"startTilt",expand:"startExpand",contract:"startContract",flash:"startFlash",drift:"startDrift",stretch:"startStretch",glow:"startGlow",sparkle:"startSparkle",shimmer:"startShimmer",wiggle:"startWiggle",groove:"startGroove",point:"startPoint",lean:"startLean",reach:"startReach",headBob:"startHeadBob",orbit:"startOrbit",flicker:"startFlicker",vibrate:"startVibrate",wave:"startWave",breathe:"startBreathe",morph:"startMorph",slowBlink:"startSlowBlink",look:"startLook",settle:"startSettle",orbital:"startOrbital",hula:"startHula",sway:"startSway",breathIn:"startBreathIn",breathOut:"startBreathOut",breathHold:"startBreathHold",breathHoldEmpty:"startBreathHoldEmpty",jump:"startJump",rain:"startRain",runningman:"startRunningMan",charleston:"startCharleston",grooveSway:"startGrooveSway",grooveBob:"startGrooveBob",grooveFlow:"startGrooveFlow",groovePulse:"startGroovePulse",grooveStep:"startGrooveStep",float:"startFloat",twist:"startTwist"}}init(){this.gestureCompatibility||Promise.resolve().then(function(){return br}).then(e=>{this.gestureCompatibility=e.default}).catch(e=>{console.warn("GestureCompatibility not available:",e)})}express(e,t={}){return this.errorBoundary.wrap(()=>{if(!e)return this._chainTarget;const i=performance.now(),s=Array.isArray(e)||"object"==typeof e&&"chord"===e.type?"chord":e;if(this.performanceMonitor&&this.performanceMonitor.markGestureStart(s),Array.isArray(e))return this.expressChord(e,t);if("object"==typeof e&&"chord"===e.type)return this.expressChord(e.gestures,t);const n=this.rendererMethods[e];if(n&&this.renderer&&this.renderer[n]){if(this.renderer[n](t),this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(e),this.performanceMonitor){const e=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,e-i)}return this._chainTarget}const a=Ai(e);if(a){if(an.registerConfig("gesture",e,a),this._state.currentModularGesture={type:e,config:a,startTime:performance.now(),duration:a.defaultParams?.duration||1e3,progress:0},this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(e),this.performanceMonitor){const e=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,e-i)}return this._chainTarget}return this._throttledWarn(`Unknown gesture: ${e}`,`gesture_${e}`),this.performanceMonitor&&this.performanceMonitor.markGestureEnd(s),this._chainTarget},"gesture-express",this._chainTarget)()}expressChord(e,t={}){return this.errorBoundary.wrap(()=>{if(!e||!Array.isArray(e)||0===e.length)return this._chainTarget;this.gestureCompatibility||Promise.resolve().then(function(){return br}).then(e=>{this.gestureCompatibility=e.default}).catch(e=>{console.warn("GestureCompatibility not available:",e)});const i=this.gestureCompatibility?this.gestureCompatibility.getCompatibleGestures(e):e;return i.forEach(e=>{const i="string"==typeof e?e:e.gestureName;this.executeGestureDirectly(i,t)}),this.gestureCompatibility?.isEnhancingCombination?.(i)&&this.renderer?.specialEffects?.addSparkle?.(),this._chainTarget},"gesture-chord",this._chainTarget)()}executeGestureDirectly(e,t={}){const i=this.rendererMethods[e];i&&this.renderer&&"function"==typeof this.renderer[i]&&this.renderer[i](t)}chain(...e){if(this.gestureCompatibility){const t=e.join(">"),i=this.gestureCompatibility.parseChain(t);this.executeChainSequence(i)}else console.warn("๐ No gestureCompatibility available, falling back to first gesture"),e.length>0&&this.express(e[0]);return this._chainTarget}executeChainSequence(e){if(!e||0===e.length)return;let t=0;const i=()=>{if(t>=e.length)return;const s=e[t];1===s.length?this.express(s[0]):this.expressChord(s),t++,t<e.length&&setTimeout(i,800)};i()}destroy(){this.currentGesture=null,this.gestureCompatibility=null}};class kr{constructor(e={}){const t=e.initialState||{};this._isRunning=t.isRunning??!1,this._debugMode=t.debugMode??!1,this._speaking=t.speaking??!1,this._recording=t.recording??!1,this._audioLevel=t.audioLevel??0,this._sleeping=t.sleeping??!1,this._rhythmEnabled=t.rhythmEnabled??!1,this._currentModularGesture=t.currentModularGesture??null,this._breathePhase=t.breathePhase??"idle",this._breatheStartTime=t.breatheStartTime??0,this._orbScale=t.orbScale??1,this._warningTimestamps=t.warningTimestamps??{},this._warningThrottle=t.warningThrottle??5e3,this._emit=e.emit||(()=>{})}get isRunning(){return this._isRunning}set isRunning(e){const t=this._isRunning!==e;this._isRunning=e,t&&this._emit("stateChange",{property:"isRunning",value:e})}get debugMode(){return this._debugMode}set debugMode(e){const t=this._debugMode!==e;this._debugMode=e,t&&this._emit("stateChange",{property:"debugMode",value:e})}get speaking(){return this._speaking}set speaking(e){const t=this._speaking!==e;this._speaking=e,t&&this._emit("stateChange",{property:"speaking",value:e})}get recording(){return this._recording}set recording(e){const t=this._recording!==e;this._recording=e,t&&this._emit("stateChange",{property:"recording",value:e})}get audioLevel(){return this._audioLevel}set audioLevel(e){this._audioLevel=e}get sleeping(){return this._sleeping}set sleeping(e){const t=this._sleeping!==e;this._sleeping=e,t&&this._emit("stateChange",{property:"sleeping",value:e})}get rhythmEnabled(){return this._rhythmEnabled}set rhythmEnabled(e){this._rhythmEnabled=e}get currentModularGesture(){return this._currentModularGesture}set currentModularGesture(e){this._currentModularGesture=e}get breathePhase(){return this._breathePhase}set breathePhase(e){this._breathePhase=e}get breatheStartTime(){return this._breatheStartTime}set breatheStartTime(e){this._breatheStartTime=e}get orbScale(){return this._orbScale}set orbScale(e){this._orbScale=e}get warningTimestamps(){return this._warningTimestamps}set warningTimestamps(e){this._warningTimestamps=e}get warningThrottle(){return this._warningThrottle}set warningThrottle(e){this._warningThrottle=e}getSnapshot(){return{isRunning:this._isRunning,debugMode:this._debugMode,speaking:this._speaking,recording:this._recording,audioLevel:this._audioLevel,sleeping:this._sleeping,rhythmEnabled:this._rhythmEnabled,currentModularGesture:this._currentModularGesture,breathePhase:this._breathePhase,breatheStartTime:this._breatheStartTime,orbScale:this._orbScale}}reset(){this._isRunning=!1,this._debugMode=!1,this._speaking=!1,this._recording=!1,this._audioLevel=0,this._sleeping=!1,this._rhythmEnabled=!1,this._currentModularGesture=null,this._breathePhase="idle",this._breatheStartTime=0,this._orbScale=1,this._warningTimestamps={}}}class Pr{constructor(e){if(!e.config)throw new Error("AudioHandler: config required");if(!e.state)throw new Error("AudioHandler: state required");if(!e.emit)throw new Error("AudioHandler: emit required");this.audioAnalyzer=e.audioAnalyzer||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.shapeMorpher=e.shapeMorpher||null,this.renderer=e.renderer||null,this.soundSystem=e.soundSystem||null,this.stateMachine=e.stateMachine||null,this.config=e.config,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.vocalUpdateInterval=null}init(){}disconnectAudio(){return this.audioAnalyzer&&this.audioAnalyzer.stop(),this.vocalUpdateInterval&&(clearInterval(this.vocalUpdateInterval),this.vocalUpdateInterval=null),this.shapeMorpher&&(this.shapeMorpher.setVocalEnergy(0),this.shapeMorpher.setAudioDeformation(0),this.shapeMorpher.audioAnalyzer=null,this.shapeMorpher.beatGlitchIntensity=0,this.shapeMorpher.glitchPoints=[]),this.renderer&&this.renderer.ambientDanceAnimator.stopAmbientAnimation("grooveBob"),this._chainTarget}async connectAudio(e){if(!this.audioAnalyzer)return this._chainTarget;if(!this.audioAnalyzer.audioContext)try{await this.audioAnalyzer.init()}catch(e){return console.warn("Failed to initialize AudioContext:",e),this._chainTarget}if(this.audioAnalyzer.audioContext&&"suspended"===this.audioAnalyzer.audioContext.state)try{await this.audioAnalyzer.audioContext.resume()}catch(e){console.warn("Failed to resume AudioContext:",e)}return this.audioAnalyzer.connectAudioElement(e),this.shapeMorpher&&(this.shapeMorpher.audioAnalyzer=this.audioAnalyzer,this.audioAnalyzer.onBeat(e=>{if(this.shapeMorpher){if(this.shapeMorpher.musicDetector){const t=performance.now();this.shapeMorpher.musicDetector.addOnset(t,e)}this.shapeMorpher.vocalEffectActive&&(this.shapeMorpher.beatGlitchIntensity=.3*e)}})),this.vocalUpdateInterval&&clearInterval(this.vocalUpdateInterval),this.renderer&&this.renderer.startGrooveBob({intensity:.5,frequency:1}),this.vocalUpdateInterval=setInterval(()=>{if(this.audioAnalyzer.isAnalyzing&&this.shapeMorpher){const e=this.audioAnalyzer.currentAmplitude||0,t=this.audioAnalyzer.getVocalInstability()||0;this.shapeMorpher.setVocalEnergy(t),this.shapeMorpher.setAudioDeformation(2*e)}},50),this.renderer&&(this.renderer.audioAnalyzer=this.audioAnalyzer),this._chainTarget}stopSpeaking(){if(!this._state.speaking)return this._chainTarget;const e=this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0;return this.audioLevelProcessor&&this.audioLevelProcessor.cleanup(),this._state.speaking=!1,this.renderer&&this.renderer.onSpeechStop(),this._emit("speechStopped",{previousAudioLevel:e,returnToBaseTime:500}),this._chainTarget}setVolume(e){const t=Math.max(0,Math.min(1,e));if(this.config.masterVolume=t,this.soundSystem&&this.soundSystem.isAvailable()){const e=this.stateMachine.getCurrentState().emotion;this.soundSystem.setMasterVolume(t,e)}return this._emit("volumeChanged",{volume:t}),this._chainTarget}destroy(){this.disconnectAudio()}}class Tr{constructor(e,t={}){this._sm=e,this._decayRate=t.decayRate??.02,this._decayFloor=t.decayFloor??0,this._accumulationCap=t.accumulationCap??1,this._enabled=t.enabled??!1,this._paused=!1,this._onDecay=[],this._onNudge=[]}update(e){if(!this._enabled||this._paused)return;const t=this._sm.getSlots(),i=this._decayRate*e;for(const e of t){if(e.intensity<=this._decayFloor)continue;const t=e.intensity;if(e.intensity=Math.max(this._decayFloor,e.intensity-i),e.intensity!==t){for(const i of this._onDecay)i(e.emotion,e.intensity,t);this._sm._emitEvent("emotionDecayed",{emotion:e.emotion,intensity:e.intensity,removed:!1}),this._sm._emitEvent("slotChanged",{emotion:e.emotion,intensity:e.intensity,action:"decay"})}}this._sm.pruneEmptySlots()}nudge(e,t){this._sm.nudgeEmotion(e,t,this._accumulationCap);for(const i of this._onNudge)i(e,t)}setDecayRate(e){this._decayRate=Math.max(0,e)}getDecayRate(){return this._decayRate}setAccumulationCap(e){this._accumulationCap=Math.max(0,Math.min(1,e))}enable(){this._enabled=!0}disable(){this._enabled=!1}isEnabled(){return this._enabled}pause(){this._paused=!0}resume(){this._paused=!1}reset(){this._sm.clearEmotions()}onDecay(e){return this._onDecay.push(e),()=>{this._onDecay=this._onDecay.filter(t=>t!==e)}}onNudge(e){return this._onNudge.push(e),()=>{this._onNudge=this._onNudge.filter(t=>t!==e)}}serialize(){return{decayRate:this._decayRate,decayFloor:this._decayFloor,accumulationCap:this._accumulationCap,enabled:this._enabled,paused:this._paused}}deserialize(e){e&&(this._decayRate=e.decayRate??this._decayRate,this._decayFloor=e.decayFloor??this._decayFloor,this._accumulationCap=e.accumulationCap??this._accumulationCap,this._enabled=e.enabled??this._enabled,this._paused=e.paused??this._paused)}destroy(){this._onDecay.length=0,this._onNudge.length=0}}class Er{constructor(e){this._modifiers=new Map,this._emit=e||(()=>{})}applyModifier(e,t){this._modifiers.set(e,{name:e,config:{...t},remaining:t.duration??null,startTime:Date.now()}),this._emit("modifierApplied",{name:e,config:t})}removeModifier(e){this._modifiers.get(e)&&(this._modifiers.delete(e),this._emit("modifierExpired",{name:e,manual:!0}))}update(e){const t=[];for(const[i,s]of this._modifiers)null!==s.remaining&&(s.remaining-=e,s.remaining<=0)?(t.push(i),s.config.onExpire&&s.config.onExpire()):s.config.onTick&&s.config.onTick(s.remaining);for(const e of t)this._modifiers.delete(e),this._emit("modifierExpired",{name:e,manual:!1})}getCompositeModifiers(){let e=1,t=0,i=0,s=0;for(const n of this._modifiers.values()){const a=n.config;void 0!==a.rhythmWindowMult&&(e*=a.rhythmWindowMult),void 0!==a.tempoShift&&(t+=a.tempoShift),void 0!==a.visualNoise&&(i+=a.visualNoise),void 0!==a.inputDelay&&(s+=a.inputDelay)}return{rhythmWindowMult:e,tempoShift:t,visualNoise:i,inputDelay:s}}getActiveModifiers(){return[...this._modifiers.values()].map(e=>({name:e.name,remaining:e.remaining,config:{...e.config}}))}hasModifier(e){return this._modifiers.has(e)}clear(){this._modifiers.clear()}serialize(){const e=[];for(const t of this._modifiers.values()){const{onTick:i,onExpire:s,...n}=t.config;e.push({name:t.name,remaining:t.remaining,config:n})}return e}deserialize(e){if(Array.isArray(e)){this._modifiers.clear();for(const t of e)this._modifiers.set(t.name,{name:t.name,config:t.config||{},remaining:t.remaining,startTime:Date.now()})}}}class Ar{constructor(e){if(!e.stateMachine)throw new Error("StateCoordinator: stateMachine required");if(!e.config)throw new Error("StateCoordinator: config required");if(!e.emit)throw new Error("StateCoordinator: emit required");this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem||null,this.canvasManager=e.canvasManager||null,this.renderer=e.renderer||null,this.config=e.config,this.soundSystem=e.soundSystem||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.currentEmotion="neutral",this.emotionIntensity=1,this.stateMachine.setEventCallback&&this.stateMachine.setEventCallback((e,t)=>{this._emit(e,t)}),this._dynamics=null,this._modifierManager=new Er((e,t)=>this._emit(e,t))}init(){}setEmotion(e,t=null){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;let s=null,n=500,a=1;if("string"==typeof t?s=t:t&&"object"==typeof t&&(s=t.undertone||null,n=t.duration||500,a=t.intensity??1),this.emotionIntensity=a,this.stateMachine.setEmotion(i,{undertone:s,duration:n,intensity:a})){const e=l(i);if(e&&an.registerConfig("emotion",i,e),this.particleSystem){this.particleSystem.clear();const e=this.stateMachine.getCurrentEmotionalProperties();let t;if(t="neutral"===i?1:"resting"===i?4:Math.min(3,Math.floor(e.particleRate/4)),t>0){let i,s;if(this.renderer&&"function"==typeof this.renderer.getEffectiveCenter){const e=this.renderer.getEffectiveCenter();i=e.x,s=e.y}else i=this.canvasManager.width/2,s=this.canvasManager.height/2;this.particleSystem.burst(t,e.particleBehavior,i,s)}}if("classic"===this.config.renderingStyle&&this.renderer.setEmotionalState){const e=h(i);this.renderer.setEmotionalState(i,e,s)}this._emit("emotionChanged",{emotion:i,undertone:s,duration:n})}return this.currentEmotion=i,this._chainTarget}pushEmotion(e,t=.5){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;this.stateMachine.pushEmotion(i,t);const s=this.stateMachine.getDominant();return s&&(this.currentEmotion=s.emotion),this._emit("emotionChanged",{emotion:this.currentEmotion,slots:this.stateMachine.getSlots()}),this._chainTarget}nudgeEmotion(e,t,i=1){const s={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[e]||e;this.stateMachine.nudgeEmotion(s,t,i);const n=this.stateMachine.getDominant();return n&&(this.currentEmotion=n.emotion),this._chainTarget}clearEmotions(){return this.stateMachine.clearEmotions(),this.currentEmotion="neutral",this._emit("emotionChanged",{emotion:"neutral",slots:[]}),this._chainTarget}getEmotionalState(){return this.stateMachine.getEmotionalState()}get dynamics(){return this._dynamics||(this._dynamics=new Tr(this.stateMachine)),this._dynamics}setEmotionDampening(e){return this.stateMachine.setEmotionDampening(e),this._chainTarget}getEmotionDampening(){return this.stateMachine.getEmotionDampening()}get modifiers(){return this._modifierManager}destroy(){this._dynamics&&this._dynamics.destroy(),this._modifierManager.clear(),this.currentEmotion="neutral"}}class Dr{constructor(e){if(!e.animationController)throw new Error("VisualizationRunner: animationController required");if(!e.stateMachine)throw new Error("VisualizationRunner: stateMachine required");if(!e.config)throw new Error("VisualizationRunner: config required");if(!e.state)throw new Error("VisualizationRunner: state required");if(!e.emit)throw new Error("VisualizationRunner: emit required");this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem||null,this.canvasManager=e.canvasManager||null,this.renderer=e.renderer||null,this.audioHandler=e.audioHandler||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.gazeTracker=e.gazeTracker||null,this.idleBehavior=e.idleBehavior||null,this.degradationManager=e.degradationManager||null,this.pluginSystem=e.pluginSystem||null,this.config=e.config,this.canvas=e.canvas||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this,this.animationId=null,this.isRunning=!1,this.lastTime=0}init(){}start(){if(this.animationController.isAnimating())return this._chainTarget;if(this.animationController.start()){if(this._state.isRunning=!0,this.isRunning=!0,"classic"===this.config.renderingStyle&&this.particleSystem){const e=this.stateMachine.getCurrentState(),{emotion:t}=e,i=h(t);let s,n;if(this.renderer&&this.renderer.getCurrentOrbPosition){const e=this.renderer.getCurrentOrbPosition();s=e.x,n=e.y}else s=this.canvasManager.width/2,n=this.canvasManager.height/2;if(this.particleSystem.clear(),i.particleRate>0){const e=Math.min(3,Math.floor(i.particleRate/4));e>0&&this.particleSystem.burst(e,i.particleBehavior,s,n)}}this.degradationManager&&this.degradationManager.startMonitoring(),this._emit("started")}return this._chainTarget}stop(){return this.animationController.isAnimating()?(this._state.speaking&&this.audioHandler&&this.audioHandler.stopSpeaking(),this.animationController.stop()&&(this._state.isRunning=!1,this.isRunning=!1,this.degradationManager&&this.degradationManager.stopMonitoring(),this._emit("stopped")),this._chainTarget):this._chainTarget}update(e){if(this._state.speaking&&this.audioLevelProcessor&&this.audioLevelProcessor.isProcessingActive()&&this.audioLevelProcessor.updateAudioLevel(e),"classic"===this.config.renderingStyle){if(this.gazeTracker&&(this.gazeTracker.update(e),"suspicion"===this.stateMachine.getCurrentState().emotion)){const{mousePos:e}=this.gazeTracker,t=this.canvas.width/2,i=this.canvas.height/2,s=Math.sqrt(Math.pow(e.x-t,2)+Math.pow(e.y-i,2)),n=l("suspicion");if(n&&n.visual){const e=Math.min(t,i),a=Math.max(0,Math.min(1,1-s/e));n.visual.threatLevel=a}}if(this.idleBehavior&&this.idleBehavior.update(e),this.gazeTracker&&this.idleBehavior){const e=this.gazeTracker.getGazeOffset(),t=this.idleBehavior.getSwayOffset(),i=this.gazeTracker.getState(),s={offset:{x:e.x+t.x,y:e.y+t.y},proximity:i.proximity,isFocused:i.isFocused};this.renderer&&this.renderer.setGazeData&&this.renderer.setGazeData(s)}}if(this.pluginSystem){const t=this.stateMachine.getCurrentState();this.pluginSystem.update(e,t)}}destroy(){this.stop()}}class _r{constructor(e){if(!e.errorBoundary)throw new Error("ExecutionLifecycleManager: errorBoundary required");if(!e.animationController)throw new Error("ExecutionLifecycleManager: animationController required");if(!e.visualizationRunner)throw new Error("ExecutionLifecycleManager: visualizationRunner required");if(!e.state)throw new Error("ExecutionLifecycleManager: state required");if(!e.emit)throw new Error("ExecutionLifecycleManager: emit required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.visualizationRunner=e.visualizationRunner,this.soundSystem=e.soundSystem||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}start(){return this.errorBoundary.wrap(()=>this.visualizationRunner.start(),"start",this._chainTarget)()}stop(){return this.errorBoundary.wrap(()=>this.visualizationRunner.stop(),"stop",this._chainTarget)()}pause(){return this.errorBoundary.wrap(()=>this.animationController.isAnimating()?(this.animationController.stop(),this._state.isRunning=!1,this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.stopAmbientTone(200),this._emit("paused"),this._chainTarget):this._chainTarget,"pause",this._chainTarget)()}resume(){return this.errorBoundary.wrap(()=>(this.animationController.isAnimating()||(this.animationController.start(),this._state.isRunning=!0,this._emit("resumed")),this._chainTarget),"resume",this._chainTarget)()}isActive(){return this.animationController.isAnimating()}}class Ir{constructor(e){if(!e.errorBoundary)throw new Error("AnimationFrameController: errorBoundary required");if(!e.animationController)throw new Error("AnimationFrameController: animationController required");if(!e.config)throw new Error("AnimationFrameController: config required");if(!e.emit)throw new Error("AnimationFrameController: emit required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.positionController=e.positionController||null,this.config=e.config,this._emit=e.emit,this._chainTarget=e.chainTarget||this}setTargetFPS(e){const t=Math.max(15,Math.min(120,e));return this.config.targetFPS=t,this.animationController.setTargetFPS(t),this._emit("targetFPSChanged",{targetFPS:t}),this._chainTarget}getTargetFPS(){return this.animationController.targetFPS}setPosition(e,t,i=0){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.setOffset(e,t,i)),this._chainTarget}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.animateOffset(e,t,i,s,n)),this._chainTarget}getPosition(){return this.errorBoundary.wrap(()=>{if(!this.positionController||"function"!=typeof this.positionController.getPosition)return null;const e="undefined"!=typeof window,t=e?window.innerWidth/2:0,i=e?window.innerHeight/2:0;return this.positionController.getPosition(t,i)},"get-position",this._chainTarget)()}}class Rr{constructor(e){if(!e.errorBoundary)throw new Error("ShapeTransformManager: errorBoundary required");if(!e.emit)throw new Error("ShapeTransformManager: emit required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this.shapeMorpher=e.shapeMorpher||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this}morphTo(e,t={}){return this.errorBoundary.wrap(()=>this.shapeMorpher?(this.shapeMorpher.morphTo(e,t),this.renderer&&(this.renderer.shapeMorpher=this.shapeMorpher),this._emit("shapeMorphStarted",{from:this.shapeMorpher.currentShape,to:e}),this._chainTarget):this._chainTarget,"morphTo",this._chainTarget)()}setBackdrop(e={}){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.backdropRenderer&&this.renderer.backdropRenderer.setConfig(e),this._chainTarget),"setBackdrop",this._chainTarget)()}getBackdrop(){return this.errorBoundary.wrap(()=>this.renderer&&this.renderer.backdropRenderer?this.renderer.backdropRenderer.getConfig():null,"getBackdrop",this._chainTarget)()}}class Br{constructor(e){if(!e.errorBoundary)throw new Error("EventListenerManager: errorBoundary required");if(!e.eventManager)throw new Error("EventListenerManager: eventManager required");this.errorBoundary=e.errorBoundary,this.eventManager=e.eventManager,this._chainTarget=e.chainTarget||this}on(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.on(e,t),this._chainTarget),"event-listener-add",this._chainTarget)()}off(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.off(e,t),this._chainTarget),"event-listener-remove",this._chainTarget)()}once(e,t){return this.errorBoundary.wrap(()=>(this.eventManager.once(e,t),this._chainTarget),"event-listener-once",this._chainTarget)()}removeAllListeners(e=null){return this.errorBoundary.wrap(()=>(this.eventManager.removeAllListeners(e),this._chainTarget),"event-listeners-clear",this._chainTarget)()}listenerCount(e){return this.eventManager.listenerCount(e)}getEventNames(){return this.eventManager.getEventNames()}getEventStats(){return this.eventManager.getEventStats()}getEventDebugInfo(){return this.eventManager.getDebugInfo()}emit(e,t=null){this.eventManager.emit(e,t)}}class zr{constructor(e){if(!e.tts)throw new Error("TTSManager: tts required");if(!e.state)throw new Error("TTSManager: state required");this.speechManager=e.speechManager||null,this.renderer=e.renderer||null,this.tts=e.tts,this._state=e.state,this._chainTarget=e.chainTarget||this}getTTSVoices(){return this.tts.available?window.speechSynthesis.getVoices():[]}isTTSSpeaking(){return this.tts.speaking}speak(e,t={}){return this.speechManager?this.speechManager.speak(e,t):this._chainTarget}setTTSSpeaking(e){this._state.ttsSpeaking=e,this.renderer&&this.renderer.startSpeaking&&(e?this.renderer.startSpeaking():this.renderer.stopSpeaking()),this._state.speaking=e}getVoices(){return window.speechSynthesis?window.speechSynthesis.getVoices():[]}stopTTS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),this.setTTSSpeaking(!1))}}class Fr{constructor(e){if(!e.errorBoundary)throw new Error("SpeechReactivityManager: errorBoundary required");if(!e.audioLevelProcessor)throw new Error("SpeechReactivityManager: audioLevelProcessor required");if(!e.state)throw new Error("SpeechReactivityManager: state required");if(!e.emit)throw new Error("SpeechReactivityManager: emit required");this.errorBoundary=e.errorBoundary,this.audioLevelProcessor=e.audioLevelProcessor,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}connectAudioSource(e){return this.errorBoundary.wrap(()=>this._state.audioAnalyser&&e&&"function"==typeof e.connect?(e.connect(this._state.audioAnalyser),this._emit("audioSourceConnected",{audioSource:e}),this._chainTarget):this._chainTarget,"audio-source-connection",this._chainTarget)()}getAudioLevel(){return this._state.speaking?this._state.audioLevel:0}isSpeaking(){return this._state.speaking}setAudioSmoothing(e){return this.errorBoundary.wrap(()=>{const t=Math.max(0,Math.min(1,e));return this._state.audioAnalyser&&(this._state.audioAnalyser.smoothingTimeConstant=t),this._chainTarget},"audio-smoothing",this._chainTarget)()}getAudioStats(){return this.audioLevelProcessor.getStats()}updateAudioConfig(e){this.audioLevelProcessor.updateConfig(e)}}class Or{constructor(e){if(!e.emit)throw new Error("CanvasResizeManager: emit required");this.renderer=e.renderer||null,this.stateMachine=e.stateMachine||null,this.particleSystem=e.particleSystem||null,this._emit=e.emit,this._chainTarget=e.chainTarget||this}handleResize(e,t,i){if(this.renderer&&this.renderer.initOffscreenCanvas&&this.renderer.initOffscreenCanvas(),this.stateMachine){const{currentEmotion:e}=this.stateMachine,{currentUndertone:t}=this.stateMachine;e&&this.stateMachine.setEmotion(e),t&&"none"!==t&&this.stateMachine.setUndertone(t)}this._emit("resize",{width:e,height:t,dpr:i})}clearParticles(){return this.particleSystem&&this.particleSystem.clear(),this._chainTarget}setParticleSystemCanvasDimensions(e,t){return this.particleSystem&&(this.particleSystem.canvasWidth=e,this.particleSystem.canvasHeight=t),this._chainTarget}}class Lr{constructor(e){if(!e.errorBoundary)throw new Error("OffsetPositionManager: errorBoundary required");if(!e.positionController)throw new Error("OffsetPositionManager: positionController required");this.errorBoundary=e.errorBoundary,this.positionController=e.positionController,this._chainTarget=e.chainTarget||this}setOffset(e,t,i=0){return this.errorBoundary.wrap(()=>(this.positionController.setOffset(e,t,i),this._chainTarget),"offset-setting",this._chainTarget)()}getOffset(){return this.errorBoundary.wrap(()=>this.positionController.getOffset(),"offset-getting",this._chainTarget)()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.errorBoundary.wrap(()=>(this.positionController.animateOffset(e,t,i,s,n),this._chainTarget),"offset-animation",this._chainTarget)()}}class qr{constructor(e){if(!e.canvasResizeManager)throw new Error("VisualTransformationManager: canvasResizeManager required");if(!e.offsetPositionManager)throw new Error("VisualTransformationManager: offsetPositionManager required");if(!e.shapeTransformManager)throw new Error("VisualTransformationManager: shapeTransformManager required");this.canvasResizeManager=e.canvasResizeManager,this.offsetPositionManager=e.offsetPositionManager,this.shapeTransformManager=e.shapeTransformManager,this._chainTarget=e.chainTarget||this}setOffset(e,t,i=0){return this.offsetPositionManager.setOffset(e,t,i)}getOffset(){return this.offsetPositionManager.getOffset()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.offsetPositionManager.animateOffset(e,t,i,s,n)}morphTo(e,t={}){return this.shapeTransformManager.morphTo(e,t)}setBackdrop(e={}){return this.shapeTransformManager.setBackdrop(e)}getBackdrop(){return this.shapeTransformManager.getBackdrop()}handleResize(e,t,i){this.canvasResizeManager.handleResize(e,t,i)}clearParticles(){return this.canvasResizeManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this.canvasResizeManager.setParticleSystemCanvasDimensions(e,t)}}class Gr{constructor(e){if(!e.errorBoundary)throw new Error("FrustrationContextManager: errorBoundary required");if(!e.contextManager)throw new Error("FrustrationContextManager: contextManager required");this.errorBoundary=e.errorBoundary,this.contextManager=e.contextManager,this._chainTarget=e.chainTarget||this}updateContext(e){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.update(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"context-update",this._chainTarget)()}incrementFrustration(e=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.incrementFrustration(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-increment",this._chainTarget)()}decrementFrustration(e=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.decrementFrustration(e),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-decrement",this._chainTarget)()}resetFrustration(){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.resetFrustration(),this._chainTarget):(console.warn("[FrustrationContextManager] ContextManager not initialized"),this._chainTarget),"frustration-reset",this._chainTarget)()}}class Hr{constructor(e,t={}){if(!e)throw new Error("LLMResponseHandler requires a mascot instance");this.mascot=e,this.config={autoMorphShapes:!0,morphDuration:1e3,autoExpressGestures:!0,gestureTiming:300,gestureIntensity:.7,useFallbackGestures:!0,useSemanticPerformances:!0,enableContextTracking:!0,emotionToShapeMap:{},actionToGestureMap:{},...t},this.schema={message:"string",emotion:["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity"],sentiment:["positive","neutral","negative"],action:["none","offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond"],frustrationLevel:"number",shape:["circle","heart","star","sun","moon","eclipse","solar","lunar","square","triangle","suspicion"],gesture:["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","jump","orbital","hula","scan","twist","burst","directional","settle","fade","hold","breathe","peek","sparkle","shimmer","wiggle","groove","point","lean","reach","headBob","rain","twitch","sway","float","jitter","orbit"]},this.defaultShapeMap={joy:"star",love:"heart",empathy:"heart",excitement:"sun",calm:"moon",concern:"circle",triumph:"star",curiosity:"circle",neutral:"circle"},this.defaultGestureMap={offer_help:"reach",celebrate:"sparkle",guide:"point",reassure:"nod",greet:"wave",confirm:"nod",deny:"shake",emphasize:"pulse",question:"tilt",think:"orbit",listen:"settle",respond:"bounce"},this.semanticActionMap={offer_help:"offering_help",celebrate:"celebrating",guide:"guiding",reassure:"reassuring",greet:"greeting",confirm:"confirming",deny:"denying",emphasize:"emphasizing",question:"questioning",think:"thinking",listen:"listening",respond:"responding"}}async handle(e,t={}){try{t.skipValidation||this.validateResponse(e);const{emotion:i="neutral",sentiment:s="neutral",action:n="none",shape:a,gesture:r,frustrationLevel:o=0}=e,l=void 0!==t.intensity?t.intensity:this.calculateIntensity(o,s);if(this.config.enableContextTracking&&this.mascot.updateContext&&this.mascot.updateContext({frustration:o,sentiment:s}),this.config.useSemanticPerformances&&this.mascot.perform&&this.semanticActionMap[n]){const e=this.semanticActionMap[n];try{return await this.mascot.perform(e,{context:{frustration:o,sentiment:s,urgency:o>60?"high":o>30?"medium":"low"},intensity:l}),a&&this.config.autoMorphShapes&&await this.morphToShape(a),this.mascot}catch(t){console.warn(`Semantic performance '${e}' not available, using manual choreography`)}}return await this.choreographResponse(i,n,a,r,l),this.mascot}catch(e){return console.warn("[LLMResponseHandler] Error handling LLM response:",e),this.mascot}}async choreographResponse(e,t,i,s,n){if(this.mascot.setEmotion(e,n),this.config.autoMorphShapes){const s=i||this.getShapeForEmotion(e,t);s&&await this.morphToShape(s)}if(this.config.autoExpressGestures){const e=s||this.getGestureForAction(t);e&&(await this.delay(this.config.gestureTiming),this.mascot.express(e,{intensity:this.config.gestureIntensity}))}}calculateIntensity(e,t){let i=.5;return i+=e/100*.3,"positive"===t?i+=.2:"negative"===t&&(i+=.3),Math.max(.3,Math.min(1,i))}getShapeForEmotion(e,t){return this.config.emotionToShapeMap[e]?this.config.emotionToShapeMap[e]:"celebrate"===t?"star":"greet"===t?"sun":this.defaultShapeMap[e]||null}getGestureForAction(e){return this.config.useFallbackGestures?this.config.actionToGestureMap[e]?this.config.actionToGestureMap[e]:this.defaultGestureMap[e]||null:null}morphToShape(e){e&&"circle"!==e&&this.mascot.morphTo&&this.mascot.morphTo(e,{duration:this.config.morphDuration})}validateResponse(e){if(!e||"object"!=typeof e)throw new Error("LLM response must be an object");if(e.emotion&&!this.schema.emotion.includes(e.emotion)&&console.warn(`Unknown emotion: ${e.emotion}. Using 'neutral'`),e.sentiment&&!this.schema.sentiment.includes(e.sentiment)&&console.warn(`Unknown sentiment: ${e.sentiment}. Using 'neutral'`),e.action&&!this.schema.action.includes(e.action)&&console.warn(`Unknown action: ${e.action}. Using 'none'`),e.shape&&!this.schema.shape.includes(e.shape)&&console.warn(`Unknown shape: ${e.shape}. Ignoring.`),e.gesture&&!this.schema.gesture.includes(e.gesture)&&console.warn(`Unknown gesture: ${e.gesture}. Ignoring.`),void 0!==e.frustrationLevel){const t=Number(e.frustrationLevel);(isNaN(t)||t<0||t>100)&&console.warn(`Invalid frustrationLevel: ${e.frustrationLevel}. Using 0.`)}}getSchema(){return{...this.schema}}configure(e){return Object.assign(this.config,e),this}delay(e){return new Promise(t=>setTimeout(t,e))}static getAvailableEmotions(){return["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity"]}static getAvailableActions(){return["none","offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond"]}static getAvailableShapes(){return["circle","heart","star","sun","moon","eclipse","solar","lunar","square","triangle","suspicion"]}static getAvailableGestures(){return["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","jump","orbital","hula","scan","twist","burst","directional","settle","fade","hold","breathe","peek","sparkle","shimmer","wiggle","groove","point","lean","reach","headBob","rain","twitch","sway","float","jitter","orbit"]}}class jr{constructor(e){if(!e.errorBoundary)throw new Error("LLMIntegrationBridge: errorBoundary required");this.errorBoundary=e.errorBoundary,this._mascotRef=e.mascotRef,this._chainTarget=e.chainTarget||this,this._llmHandler=null}_getHandler(e={}){return this._llmHandler||(this._llmHandler=new Hr(this._mascotRef,e)),this._llmHandler}handleLLMResponse(e,t={}){return this.errorBoundary.wrap(async()=>{const i=this._getHandler(t);return await i.handle(e,t),this._chainTarget},"handleLLMResponse",this._chainTarget)()}configureLLMHandler(e){return this.errorBoundary.wrap(()=>(this._getHandler(e).configure(e),this._chainTarget),"configureLLMHandler",this._chainTarget)()}getLLMResponseSchema(){return this._getHandler().getSchema()}static getLLMPromptTemplate(e={}){return function(e={}){const{domain:t="general assistance",personality:i="friendly, empathetic, and helpful",brand:s="our service",customEmotions:n=[],customActions:a=[]}=e,r=["offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond",...a];return`You are a ${i} AI assistant for ${s}, providing ${t}. You have an animated mascot companion that responds to the emotional tone and context of conversations.\n\n**CRITICAL: You must ONLY respond with valid JSON. Do not include any text before or after the JSON object. Do not use markdown code blocks.**\n\n## Response Format\n\nYour response must be a valid JSON object with this exact structure:\n\n{\n "message": "your helpful response here (2-3 sentences max)",\n "emotion": "${["joy","empathy","calm","excitement","concern","neutral","triumph","love","curiosity",...n].join("|")}",\n "sentiment": "positive|neutral|negative",\n "action": "${r.join("|")}",\n "frustrationLevel": 0-100,\n "shape": "heart|star|sun|moon|circle|square|triangle (optional)",\n "gesture": "nod|wave|sparkle|point|reach|bounce|pulse|... (optional)"\n}\n\n## Guidelines\n\n**Emotional Intelligence:**\n- Detect emotional tone in user messages (frustration, confusion, satisfaction, joy, etc.)\n- Respond with empathy when users are frustrated or confused\n- Celebrate successes and positive moments\n- Match your emotion to the user's needs\n\n**Communication Style:**\n- Be concise (max 2-3 sentences)\n- Use warm, encouraging, ${i} language\n- Provide specific, actionable solutions\n- Avoid generic responses\n\n**Frustration Tracking:**\n- 0-20: User is calm and satisfied\n- 21-40: Minor confusion or concern\n- 41-60: Moderate frustration\n- 61-80: High frustration, needs urgent help\n- 81-100: Critical frustration, escalate immediately\n\n## Emotion Guidelines\n\n- **joy**: User is happy, things are going well โ Use for celebrations, positive outcomes\n- **empathy**: User is struggling or frustrated โ Use to show understanding and care\n- **calm**: Neutral, instructional โ Use for steady guidance\n- **excitement**: High energy, anticipation โ Use for big wins or new features\n- **concern**: User has a problem โ Use when addressing issues\n- **neutral**: Default state โ Use for routine interactions\n- **triumph**: Achievement unlocked โ Use for major successes\n- **love**: Deep appreciation โ Use when user expresses gratitude\n- **curiosity**: Exploring, learning โ Use when user asks questions\n\n## Shape Guidelines (Optional - enhances emotional expression)\n\n- **heart**: Empathy, love, appreciation, caring\n- **star**: Achievements, excellence, celebration\n- **sun**: Energy, positivity, brightness, enthusiasm\n- **moon**: Calm, soothing, gentle, nighttime\n- **circle**: Neutral, default, balanced\n- **square**: Structured, organized, professional\n- **triangle**: Directional, focused, pointing\n\nUse shapes to reinforce emotions - e.g., "heart" + "empathy" for caring support.\n\n## Gesture Guidelines (Optional - adds personality)\n\n- **nod**: Confirming, agreeing, understanding\n- **wave**: Greetings, farewells\n- **sparkle**: Celebration, magic moments, success\n- **point**: Directing attention, guidance\n- **reach**: Offering help, extending support\n- **bounce**: Excitement, enthusiasm, playfulness\n- **pulse**: Emphasis, importance, attention\n- **shake**: No, error, disagreement\n- **shimmer**: Delight, wonder, positive surprise\n\n## Action Guidelines\n\n- **offer_help**: User needs assistance โ Trigger helpful gestures\n- **celebrate**: Success or achievement โ Trigger celebratory animations\n- **guide**: Providing instructions โ Trigger directional gestures\n- **reassure**: Calming concerns โ Trigger comforting animations\n- **greet**: Starting conversation โ Trigger welcoming gestures\n- **confirm**: Validating user action โ Trigger affirmative gestures\n- **deny**: Rejecting or correcting โ Trigger negative gestures\n- **emphasize**: Highlighting important info โ Trigger attention gestures\n\n## Example Responses\n\n**User expresses frustration:**\n{"message": "I totally understand how frustrating this is! Let me help you get this sorted out right now. What specifically isn't working?", "emotion": "empathy", "sentiment": "negative", "action": "offer_help", "frustrationLevel": 75, "shape": "heart", "gesture": "reach"}\n\n**User asks for guidance:**\n{"message": "Great question! Hold the barcode about 6 inches from the scanner until you hear a beep. The item will appear in your cart.", "emotion": "calm", "sentiment": "neutral", "action": "guide", "frustrationLevel": 20, "shape": "square", "gesture": "point"}\n\n**User succeeds:**\n{"message": "Perfect! You've got it now. Anything else I can help you with today?", "emotion": "joy", "sentiment": "positive", "action": "celebrate", "frustrationLevel": 0, "shape": "star", "gesture": "sparkle"}\n\n**User greets:**\n{"message": "Hello! I'm here to make your ${t} experience smooth and easy. How can I help you today?", "emotion": "joy", "sentiment": "positive", "action": "greet", "frustrationLevel": 0, "shape": "sun", "gesture": "wave"}\n\n**User says thanks:**\n{"message": "You're so welcome! I'm thrilled I could help. Have a wonderful day!", "emotion": "love", "sentiment": "positive", "action": "celebrate", "frustrationLevel": 0, "shape": "heart", "gesture": "sparkle"}\n\nRemember: Always respond with valid JSON only. No extra text, no markdown formatting.`}(e)}static getLLMEmotions(){return Hr.getAvailableEmotions()}static getLLMActions(){return Hr.getAvailableActions()}static getLLMShapes(){return Hr.getAvailableShapes()}static getLLMGestures(){return Hr.getAvailableGestures()}}class $r{constructor(e){if(!e.errorBoundary)throw new Error("DiagnosticsManager: errorBoundary required");if(!e.animationController)throw new Error("DiagnosticsManager: animationController required");if(!e.stateMachine)throw new Error("DiagnosticsManager: stateMachine required");if(!e.config)throw new Error("DiagnosticsManager: config required");if(!e.state)throw new Error("DiagnosticsManager: state required");if(!e.getCurrentState)throw new Error("DiagnosticsManager: getCurrentState required");if(!e.getAudioStats)throw new Error("DiagnosticsManager: getAudioStats required");if(!e.getEventStats)throw new Error("DiagnosticsManager: getEventStats required");this.errorBoundary=e.errorBoundary,this.degradationManager=e.degradationManager||null,this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.performanceSystem=e.performanceSystem||null,this.config=e.config,this._state=e.state,this._getCurrentState=e.getCurrentState,this._getAudioStats=e.getAudioStats,this._getEventStats=e.getEventStats,this._chainTarget=e.chainTarget||this}getBrowserCompatibility(){return{browser:ir.browser,features:ir.featureDetection.getFeatures(),capabilities:ir.capabilities,appliedPolyfills:ir.appliedPolyfills,optimizations:ir.browserOptimizations.getOptimizations()}}getDegradationStatus(){return this.degradationManager?{currentLevel:this.degradationManager.getCurrentLevel(),availableFeatures:this.degradationManager.getAvailableFeatures(),recommendedSettings:this.degradationManager.getRecommendedSettings(),performanceStats:this.degradationManager.getPerformanceStats(),allLevels:this.degradationManager.getAllLevels()}:null}setDegradationLevel(e){return!!this.degradationManager&&this.degradationManager.setLevel(e)}getDebugReport(){const e={timestamp:Date.now(),mascot:{isRunning:this._state.isRunning,speaking:this._state.speaking,debugMode:this._state.debugMode,config:this.config},currentState:this._getCurrentState(),performanceMetrics:this.getPerformanceMetrics(),audioStats:this._getAudioStats(),eventStats:this._getEventStats(),browserCompatibility:this.getBrowserCompatibility(),degradationStatus:this.getDegradationStatus(),runtimeCapabilities:ks.generateReport(),debuggerReport:Cs.getDebugReport()};return this._state.debugMode&&Cs.log("DEBUG","Generated debug report",{reportSize:JSON.stringify(e).length,sections:Object.keys(e)}),e}exportDebugData(){const e={metadata:{exportTime:Date.now(),version:"1.0.0",userAgent:navigator.userAgent,url:window.location?.href},mascotState:{config:this.config,currentState:this._getCurrentState(),isRunning:this._state.isRunning,speaking:this._state.speaking},performance:{metrics:this.getPerformanceMetrics(),degradationStatus:this.getDegradationStatus(),frameTimings:Cs.frameTimings},compatibility:{browser:this.getBrowserCompatibility(),runtimeCapabilities:ks.generateReport()},debuggerData:Cs.exportDebugData()};return this._state.debugMode&&Cs.log("INFO","Exported debug data",{dataSize:JSON.stringify(e).length}),e}getPerformanceMetrics(){const e=this.animationController.getPerformanceMetrics(),t=this.stateMachine.getCurrentState();return{...e,currentEmotion:t.emotion,currentUndertone:t.undertone,isTransitioning:t.isTransitioning,errorStats:this.errorBoundary.getErrorStats()}}getPerformanceAnalytics(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAnalytics():null,"performance-analytics",this._chainTarget)()}}class Wr{constructor(e){if(!e.errorBoundary)throw new Error("EmotionalStateQueryManager: errorBoundary required");if(!e.stateMachine)throw new Error("EmotionalStateQueryManager: stateMachine required");this.errorBoundary=e.errorBoundary,this.stateMachine=e.stateMachine,this.contextManager=e.contextManager||null,this.performanceSystem=e.performanceSystem||null,this._chainTarget=e.chainTarget||this}getEmotionalColor(){const e=this.stateMachine.getCurrentEmotionalProperties();return e?.primaryColor||"#B0B0B0"}getCurrentState(){return this.stateMachine.getCurrentState()}getAvailableEmotions(){return this.stateMachine.getAvailableEmotions()}getAvailableUndertones(){return this.stateMachine.getAvailableUndertones()}getAvailableGestures(){return["bounce","pulse","shake","spin","drift","nod","tilt","expand","contract","flash","stretch","glow","flicker","vibrate","wave","morph","slowBlink","look","settle","breathIn","breathOut","breathHold","breathHoldEmpty","jump"]}getAvailablePerformances(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAllPerformanceNames():[],"available-performances",this._chainTarget)()}getAvailableShapes(){return gr.getAvailableShapes()}getContext(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getContext():null,"context-get",this._chainTarget)()}getContextAnalytics(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getAnalytics():null,"context-analytics",this._chainTarget)()}}class Ur{constructor(e){if(!e.diagnosticsManager)throw new Error("DebugProfilingManager: diagnosticsManager required");this.diagnosticsManager=e.diagnosticsManager,this._state=e.state||{debugMode:!1}}getDebugReport(){return this.diagnosticsManager.getDebugReport()}exportDebugData(){return this.diagnosticsManager.exportDebugData()}startProfiling(e,t={}){this._state.debugMode&&Cs.startProfile(e,t)}endProfiling(e){return this._state.debugMode?Cs.endProfile(e):null}takeMemorySnapshot(e){this._state.debugMode&&Cs.takeMemorySnapshot(e)}clearDebugData(){Cs.clear(),this._state.debugMode&&Cs.log("INFO","Debug data cleared")}getRuntimeCapabilities(){return ks.generateReport()}}class Vr{constructor(e){if(!e.errorBoundary)throw new Error("PerformanceBehaviorManager: errorBoundary required");if(!e.frustrationContextManager)throw new Error("PerformanceBehaviorManager: frustrationContextManager required");if(!e.emotionalStateQueryManager)throw new Error("PerformanceBehaviorManager: emotionalStateQueryManager required");if(!e.diagnosticsManager)throw new Error("PerformanceBehaviorManager: diagnosticsManager required");this.errorBoundary=e.errorBoundary,this.performanceSystem=e.performanceSystem||null,this.frustrationContextManager=e.frustrationContextManager,this.emotionalStateQueryManager=e.emotionalStateQueryManager,this.diagnosticsManager=e.diagnosticsManager,this._chainTarget=e.chainTarget||this}perform(e,t={}){return this.errorBoundary.wrap(async()=>this.performanceSystem?(t.context&&this.frustrationContextManager.updateContext(t.context),await this.performanceSystem.perform(e,{...t,mascot:this._chainTarget}),this._chainTarget):(console.warn("[EmotiveMascot] PerformanceSystem not initialized"),this._chainTarget),"semantic-performance",this._chainTarget)()}registerPerformance(e,t){return this.errorBoundary.wrap(()=>this.performanceSystem?(this.performanceSystem.registerPerformance(e,t),this._chainTarget):(console.warn("[EmotiveMascot] PerformanceSystem not initialized"),this._chainTarget),"performance-register",this._chainTarget)()}getAvailablePerformances(){return this.emotionalStateQueryManager.getAvailablePerformances()}getPerformanceAnalytics(){return this.diagnosticsManager.getPerformanceAnalytics()}getContextAnalytics(){return this.emotionalStateQueryManager.getContextAnalytics()}}class Yr{constructor(e){if(!e.diagnosticsManager)throw new Error("PerformanceMonitoringManager: diagnosticsManager required");if(!e.animationFrameController)throw new Error("PerformanceMonitoringManager: animationFrameController required");if(!e.animationController)throw new Error("PerformanceMonitoringManager: animationController required");if(!e.particleSystem)throw new Error("PerformanceMonitoringManager: particleSystem required");if(!e.config)throw new Error("PerformanceMonitoringManager: config required");this.diagnosticsManager=e.diagnosticsManager,this.degradationManager=e.degradationManager||null,this.animationFrameController=e.animationFrameController,this.animationController=e.animationController,this.particleSystem=e.particleSystem,this.healthCheckManager=e.healthCheckManager,this.config=e.config,this._chainTarget=e.chainTarget||this}getDegradationStatus(){return this.diagnosticsManager.getDegradationStatus()}setDegradationLevel(e){return this.diagnosticsManager.setDegradationLevel(e)}isFeatureAvailable(e){return this.degradationManager?this.degradationManager.isFeatureAvailable(e):ir.featureDetection.getFeatures()[e]||!1}setTargetFPS(e){return this.animationFrameController.setTargetFPS(e)}getTargetFPS(){return this.animationFrameController.getTargetFPS()}setPerformanceDegradation(e){const t=this.animationController.getPerformanceMetrics();if(e&&!t.performanceDegradation){const e=this.particleSystem.maxParticles,t=Math.max(5,Math.floor(.5*e));this.particleSystem.setMaxParticles(t)}else!e&&t.performanceDegradation&&this.particleSystem.setMaxParticles(this.config.maxParticles);return this._chainTarget}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}}class Xr{constructor(e){if(!e.errorBoundary)throw new Error("HealthCheckManager: errorBoundary required");if(!e.diagnosticsManager)throw new Error("HealthCheckManager: diagnosticsManager required");if(!e.mobileOptimization)throw new Error("HealthCheckManager: mobileOptimization required");if(!e.accessibilityManager)throw new Error("HealthCheckManager: accessibilityManager required");if(!e.config)throw new Error("HealthCheckManager: config required");this.errorBoundary=e.errorBoundary,this.systemStatusReporter=e.systemStatusReporter||null,this.diagnosticsManager=e.diagnosticsManager,this.mobileOptimization=e.mobileOptimization,this.accessibilityManager=e.accessibilityManager,this.config=e.config,this._chainTarget=e.chainTarget||this}getSystemStatus(){return this.systemStatusReporter?this.systemStatusReporter.getSystemStatus():{}}setDebugMode(e){return this.config.showDebug=!!e,this.config.showFPS=!!e,this._chainTarget}triggerTestError(e="manual-test"){return this.errorBoundary.wrap(()=>{throw new Error(`Test error triggered in context: ${e}`)},e,this._chainTarget)()}getPerformanceMetrics(){return this.diagnosticsManager.getPerformanceMetrics()}getMobileStatus(){return this.mobileOptimization.getStatus()}getAccessibilityStatus(){return this.accessibilityManager.getStatus()}}class Nr{constructor(e){this.mascot=e}initialize(e){const t=this.mascot;this._initializeLayer1(t,e),this._initializeLayer2(t,e),this._initializeLayer3(t,e),t.audioHandler.init(),t.stateCoordinator.init(),t.visualizationRunner.init()}_initializeLayer1(e,t){e.audioHandler=new Pr({audioAnalyzer:e.audioAnalyzer,audioLevelProcessor:e.audioLevelProcessor,shapeMorpher:e.shapeMorpher,soundSystem:e.soundSystem,renderer:e.renderer,errorBoundary:e.errorBoundary,config:e.config,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get audioLevel(){return e.audioLevel},set audioLevel(t){e.audioLevel=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.stateCoordinator=new Ar({stateMachine:e.stateMachine,particleSystem:e.particleSystem,canvasManager:e.canvasManager,renderer:e.renderer,soundSystem:e.soundSystem,config:e.config,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.visualizationRunner=new Dr({animationController:e.animationController,stateMachine:e.stateMachine,particleSystem:e.particleSystem,canvasManager:e.canvasManager,renderer:e.renderer,audioHandler:e.audioHandler,audioLevelProcessor:e.audioLevelProcessor,gazeTracker:e.gazeTracker,idleBehavior:e.idleBehavior,degradationManager:e.degradationManager,pluginSystem:e.pluginSystem,config:e.config,canvas:e.canvas,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get isRunning(){return e.isRunning},set isRunning(t){e.isRunning=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.executionLifecycleManager=new _r({animationController:e.animationController,visualizationRunner:e.visualizationRunner,idleBehavior:e.idleBehavior,gazeTracker:e.gazeTracker,renderer:e.renderer,errorBoundary:e.errorBoundary,state:{get isRunning(){return e.isRunning},set isRunning(t){e.isRunning=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.animationFrameController=new Ir({animationController:e.animationController,positionController:e.positionController,config:e.config,errorBoundary:e.errorBoundary,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.shapeTransformManager=new Rr({shapeMorpher:e.shapeMorpher,renderer:e.renderer,errorBoundary:e.errorBoundary,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.eventListenerManager=new Br({eventManager:e.eventManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.ttsManager=new zr({soundSystem:e.soundSystem,errorBoundary:e.errorBoundary,config:e.config,tts:e.tts,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.speechReactivityManager=new Fr({audioLevelProcessor:e.audioLevelProcessor,renderer:e.renderer,errorBoundary:e.errorBoundary,config:e.config,state:{get speaking(){return e.speaking},set speaking(t){e.speaking=t},get audioLevel(){return e.audioLevel},set audioLevel(t){e.audioLevel=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.canvasResizeManager=new Or({renderer:e.renderer,stateMachine:e.stateMachine,particleSystem:e.particleSystem,emit:(t,i)=>e.emit(t,i),chainTarget:e}),e.offsetPositionManager=new Lr({positionController:e.positionController,errorBoundary:e.errorBoundary,chainTarget:e}),e.visualTransformationManager=new qr({canvasResizeManager:e.canvasResizeManager,offsetPositionManager:e.offsetPositionManager,shapeTransformManager:e.shapeTransformManager,chainTarget:e}),e.frustrationContextManager=new Gr({contextManager:e.contextManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.llmIntegrationBridge=new jr({stateMachine:e.stateMachine,gestureController:e.gestureController,errorBoundary:e.errorBoundary,state:{get llmHandler(){return e.llmHandler},set llmHandler(t){e.llmHandler=t}},emit:(t,i)=>e.emit(t,i),chainTarget:e})}_initializeLayer2(e,t){e.diagnosticsManager=new $r({errorBoundary:e.errorBoundary,degradationManager:e.degradationManager,animationController:e.animationController,stateMachine:e.stateMachine,performanceSystem:e.performanceSystem,config:e.config,state:{get isRunning(){return e.isRunning},get speaking(){return e.speaking},get debugMode(){return e.debugMode}},getCurrentState:()=>e.getCurrentState(),getAudioStats:()=>e.getAudioStats(),getEventStats:()=>e.getEventStats(),chainTarget:e}),e.emotionalStateQueryManager=new Wr({stateMachine:e.stateMachine,performanceSystem:e.performanceSystem,contextManager:e.contextManager,errorBoundary:e.errorBoundary,chainTarget:e}),e.debugProfilingManager=new Ur({diagnosticsManager:e.diagnosticsManager,errorBoundary:e.errorBoundary,state:{get debugMode(){return e.debugMode},set debugMode(t){e.debugMode=t}},chainTarget:e})}_initializeLayer3(e,t){e.performanceBehaviorManager=new Vr({errorBoundary:e.errorBoundary,performanceSystem:e.performanceSystem,frustrationContextManager:e.frustrationContextManager,emotionalStateQueryManager:e.emotionalStateQueryManager,diagnosticsManager:e.diagnosticsManager,chainTarget:e}),e.healthCheckManager=new Xr({errorBoundary:e.errorBoundary,systemStatusReporter:e.systemStatusReporter,diagnosticsManager:e.diagnosticsManager,mobileOptimization:e.mobileOptimization,accessibilityManager:e.accessibilityManager,config:e.config,chainTarget:e}),e.performanceMonitoringManager=new Yr({diagnosticsManager:e.diagnosticsManager,degradationManager:e.degradationManager,animationFrameController:e.animationFrameController,animationController:e.animationController,particleSystem:e.particleSystem,healthCheckManager:e.healthCheckManager,config:e.config,chainTarget:e})}}class Qr{constructor(e,t={}){this.mascot=e,this.userConfig=t}initialize(){this.initializeStateManager();const e=this.initializeConfiguration();return this.initializeCanvas(e),this.initializeCoreSystems(e),this.initializeAudioSystems(e),this.initializeInteractionSystems(e),this.initializeOptimizationSystems(e),this.initializeAnimationController(e),this.initializePerformanceSystems(e),this.initializeModularHandlers(e),this.finalizeInitialization(e),e}initializeStateManager(){this.mascot.stateManager=new kr({initialState:{debugMode:this.userConfig.enableDebug||!1},emit:(e,t)=>this.mascot.emit(e,t)}),this._createStateAliases()}initializeConfiguration(){const e=ir.browserOptimizations.getOptimizations(),t={canvasId:"emotive-mascot",targetFPS:60,enableAudio:ir.featureDetection.features.webAudio,soundEnabled:!1,masterVolume:.5,maxParticles:e.particleLimit,defaultEmotion:"neutral",enableAutoOptimization:!0,enableGracefulDegradation:!0,renderingStyle:"classic",enableGazeTracking:!0,enableIdleBehaviors:!0,renderSize:null,offsetX:0,offsetY:0,offsetZ:0,classicConfig:{coreColor:"#FFFFFF",coreSizeDivisor:12,glowMultiplier:2.5,defaultGlowColor:"#14B8A6"},topOffset:0,sentry:{enabled:!1,dsn:null,environment:"production",tracesSampleRate:.1},...this.userConfig};return this.mascot.config=t,t}initializeCanvas(e){if(this.mascot.canvas="string"==typeof e.canvasId?document.getElementById(e.canvasId):e.canvasId,!this.mascot.canvas)throw new Error(`Canvas with ID '${e.canvasId}' not found`);this.mascot.canvas.setAttribute("role","img"),this.mascot.canvas.setAttribute("aria-label","Animated emotional mascot visualization"),this.mascot.canvasManager=new Ps(this.mascot.canvas),this.mascot.positionController=new za({offsetX:e.offsetX,offsetY:e.offsetY,offsetZ:e.offsetZ,onUpdate:e=>{this.mascot.renderer&&this.mascot.renderer.updateEffectiveCenter(e)}}),e.renderSize&&e.renderSize.width&&e.renderSize.height&&this.mascot.canvasManager.setRenderSize(e.renderSize.width,e.renderSize.height),this.mascot.contextRecovery=new Qa(this.mascot.canvas),this.mascot.contextRecovery.onRecovery(e=>{this.mascot.renderer&&this.mascot.renderer.handleContextRecovery(e)}),ir.browserOptimizations.applyCanvasOptimizations(this.mascot.canvas,this.mascot.canvasManager.getContext())}initializeCoreSystems(e){this.mascot.stateMachine=new Zs(this.mascot.errorBoundary),this.mascot.particleSystem=new cn(e.maxParticles,this.mascot.errorBoundary),this.mascot.particleSystem.canvasWidth=this.mascot.canvasManager.width,this.mascot.particleSystem.canvasHeight=this.mascot.canvasManager.height,this.mascot.renderer=new ya(this.mascot.canvasManager,{...e.classicConfig,topOffset:e.topOffset||0,positionController:this.mascot.positionController}),this.mascot.renderer.stateMachine=this.mascot.stateMachine,this.mascot.stateMachine.renderer=this.mascot.renderer}initializeAudioSystems(e){this.mascot.shapeMorpher=new gr,this.mascot.audioAnalyzer=new mr,this.mascot.grooveTemplates=new vr,this.mascot.shapeMorpher.audioAnalyzer=this.mascot.audioAnalyzer,this.mascot.renderer.shapeMorpher=this.mascot.shapeMorpher,this.mascot.renderer.audioAnalyzer=this.mascot.audioAnalyzer,this.mascot.soundSystem=new La,this.mascot.tts={available:"undefined"!=typeof window&&"speechSynthesis"in window,speaking:!1,currentUtterance:null};const t=this.mascot;this.mascot.gestureController=new Cr({errorBoundary:t.errorBoundary,renderer:t.renderer,soundSystem:t.soundSystem,config:t.config,state:{get currentModularGesture(){return t.currentModularGesture},set currentModularGesture(e){t.currentModularGesture=e}},throttledWarn:t.throttledWarn,chainTarget:t}),this.mascot.gestureController.gestureCompatibility=yr,this.mascot.gestureController.init(),this.mascot.audioLevelProcessor=new Ha({spikeThreshold:e.spikeThreshold||1.5,minimumSpikeLevel:e.minimumSpikeLevel||.1,spikeMinInterval:e.spikeMinInterval||1e3})}initializeInteractionSystems(e){e.enableGazeTracking&&(this.mascot.gazeTracker=new ba(this.mascot.canvas,{smoothing:.1,maxOffset:.15,enabled:!0}),this.mascot.gazeTracker.setInteractionCallback(()=>{this.mascot.sleeping?this.mascot.wake():this.mascot.idleBehavior&&this.mascot.idleBehavior.resetIdleTimer()})),e.enableIdleBehaviors&&(this.mascot.idleBehavior=new va({enabled:!0,sleepTimeout:1/0}),this.mascot.idleBehavior.setCallback("onBlink",e=>{this.mascot.renderer&&this.mascot.renderer.state&&(this.mascot.renderer.state.blinking="start"===e.phase)}),this.mascot.idleBehavior.setCallback("onSleep",()=>{this.mascot.renderer&&this.mascot.renderer.enterSleepMode&&this.mascot.renderer.enterSleepMode()}),this.mascot.idleBehavior.setCallback("onWake",()=>{this.mascot.renderer&&this.mascot.renderer.wakeUp&&this.mascot.renderer.wakeUp()}))}initializeOptimizationSystems(e){this.mascot.degradationManager=null,this.mascot.accessibilityManager=new ja({enableReducedMotion:!1!==e.enableReducedMotion,enableHighContrast:!1!==e.enableHighContrast,enableScreenReaderSupport:!1!==e.enableScreenReaderSupport,enableKeyboardNavigation:!1!==e.enableKeyboardNavigation,colorBlindMode:e.colorBlindMode||"none"}),this.mascot.mobileOptimization=new $a({enableTouchOptimization:!1!==e.enableTouchOptimization,enableViewportHandling:!1!==e.enableViewportHandling,enableBatteryOptimization:!1!==e.enableBatteryOptimization}),this.mascot.mobileOptimization.setCanvas(this.mascot.canvas),this.mascot.pluginSystem=new Wa({mascot:this.mascot,enablePlugins:!1!==e.enablePlugins,validatePlugins:!1!==e.validatePlugins,sandboxPlugins:!1!==e.sandboxPlugins})}initializeAnimationController(e){try{this.mascot.animationController=new Ga(this.mascot.errorBoundary,{targetFPS:e.targetFPS})}catch(t){console.error("AnimationController initialization failed:",t),console.warn("[InitializationManager] Running with fallback AnimationController โ some features may be limited"),this.mascot.animationController=this.createFallbackAnimationController(e.targetFPS)}this.mascot.animationController.setSubsystems({stateMachine:this.mascot.stateMachine,particleSystem:this.mascot.particleSystem,renderer:this.mascot.renderer,soundSystem:this.mascot.soundSystem,canvasManager:this.mascot.canvasManager}),this.mascot.animationController.setEventCallback((e,t)=>{this.mascot.emit(e,t)}),this.mascot.animationController.setParentMascot(this.mascot),this.mascot.isRunning=!1}createFallbackAnimationController(e){return{isAnimating:()=>this.mascot.isRunning,start:()=>(this.mascot.isRunning=!0,!0),stop:()=>(this.mascot.isRunning=!1,!0),setTargetFPS:()=>{},targetFPS:e,getPerformanceMetrics:()=>({fps:0,isRunning:this.mascot.isRunning,performanceDegradation:!1,deltaTime:16,frameCount:0,targetFPS:e}),setSubsystems:()=>{},setEventCallback:()=>{},setParentMascot:()=>{},destroy:()=>{},deltaTime:16}}initializePerformanceSystems(e){this.mascot.contextManager=new Sr({enableHistory:!1!==e.enablePerformanceHistory,enableDecay:!1!==e.enableFrustrationDecay,historyLimit:e.performanceHistoryLimit||50,frustrationDecayRate:e.frustrationDecayRate||5,decayInterval:e.frustrationDecayInterval||1e4}),this.mascot.destructionManager&&(this.mascot.destructionManager.contextManager=this.mascot.contextManager),this.mascot.sequenceExecutor=new xr({mascot:this.mascot,eventManager:this.mascot.eventManager,allowConcurrent:!1!==e.allowConcurrentPerformances}),this.mascot.performanceSystem=new wr({mascot:this.mascot,contextManager:this.mascot.contextManager,sequenceExecutor:this.mascot.sequenceExecutor,eventManager:this.mascot.eventManager,enableAnalytics:!1!==e.enablePerformanceAnalytics})}initializeModularHandlers(e){new Nr(this.mascot).initialize(e);const t=this.mascot.destructionManager;t&&(t.gestureController=this.mascot.gestureController,t.stateCoordinator=this.mascot.stateCoordinator,t.visualizationRunner=this.mascot.visualizationRunner,t.audioHandler=this.mascot.audioHandler)}finalizeInitialization(e){e.enableAudio&&this.mascot.soundSystem.initialize().then(t=>{t&&this.mascot.soundSystem.setMasterVolume(e.masterVolume)}).catch(e=>{console.warn("[InitializationManager] Sound system initialization failed:",e)}),an.initialize(),this.mascot.rhythmIntegration=an,this.mascot.debugMode&&(Cs.log("INFO","Debug mode enabled for EmotiveMascot",{config:e,runtimeCapabilities:ks.generateReport()}),Cs.startProfile("mascot-initialization",{canvasId:e.canvasId,maxParticles:e.maxParticles})),this.mascot.setupAudioLevelProcessorCallbacks(),this.mascot.stateMachine.setEmotion(e.defaultEmotion),this.mascot.canvasManager.onResize((e,t,i)=>{this.mascot.handleResize(e,t,i)}),this.mascot.stateManager.debugMode&&(Cs.endProfile("mascot-initialization"),Cs.takeMemorySnapshot("post-initialization"))}_createStateAliases(){const e=this.mascot,t=e.stateManager;Object.defineProperties(e,{speaking:{get:()=>t.speaking,set(e){t.speaking=e},enumerable:!0,configurable:!0},recording:{get:()=>t.recording,set(e){t.recording=e},enumerable:!0,configurable:!0},sleeping:{get:()=>t.sleeping,set(e){t.sleeping=e},enumerable:!0,configurable:!0},isRunning:{get:()=>t.isRunning,set(e){t.isRunning=e},enumerable:!0,configurable:!0},debugMode:{get:()=>t.debugMode,set(e){t.debugMode=e},enumerable:!0,configurable:!0},audioLevel:{get:()=>t.audioLevel,set(e){t.audioLevel=e},enumerable:!0,configurable:!0},rhythmEnabled:{get:()=>t.rhythmEnabled,set(e){t.rhythmEnabled=e},enumerable:!0,configurable:!0},currentModularGesture:{get:()=>t.currentModularGesture,set(e){t.currentModularGesture=e},enumerable:!0,configurable:!0},breathePhase:{get:()=>t.breathePhase,set(e){t.breathePhase=e},enumerable:!0,configurable:!0},breatheStartTime:{get:()=>t.breatheStartTime,set(e){t.breatheStartTime=e},enumerable:!0,configurable:!0},orbScale:{get:()=>t.orbScale,set(e){t.orbScale=e},enumerable:!0,configurable:!0},warningTimestamps:{get:()=>t.warningTimestamps,set(e){t.warningTimestamps=e},enumerable:!0,configurable:!0},warningThrottle:{get:()=>t.warningThrottle,set(e){t.warningThrottle=e},enumerable:!0,configurable:!0}})}}class Jr{constructor(e){this.animationController=e.animationController||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.gazeTracker=e.gazeTracker||null,this.particleSystem=e.particleSystem,this.stateMachine=e.stateMachine,this._state=e.state||{debugMode:!1,speaking:!1}}buildRenderState(){return{renderStart:this._state.debugMode?performance.now():0,deltaTime:this.getDeltaTime(),renderState:this.createRenderState()}}getDeltaTime(){return this.animationController?this.animationController.deltaTime:16.67}createRenderState(){return{properties:this.stateMachine.getCurrentEmotionalProperties(),emotion:this.stateMachine.getCurrentState().emotion,undertone:this.stateMachine.getCurrentState().undertone,particleSystem:this.particleSystem,speaking:this._state.speaking,audioLevel:this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0,gazeOffset:this.getGazeOffset()}}getGazeOffset(){return this.gazeTracker?this.gazeTracker.currentGaze:{x:0,y:0}}}class Kr{constructor(e){this.canvasManager=e.canvasManager,this.config=e.config,this.gazeTracker=e.gazeTracker||null}updateThreatLevel(e){if("suspicion"!==e.emotion||!this.gazeTracker)return;const t=l("suspicion");if(!t||!t.visual)return;const i=this.calculateThreatLevel();t.visual.threatLevel=i}calculateThreatLevel(){this.gazeTracker.getState();const{mousePos:e}=this.gazeTracker,t=this.canvasManager.width/2,i=this.canvasManager.height/2-this.config.topOffset,s=this.calculateDistance(e,{x:t,y:i}),n=Math.min(this.canvasManager.width,this.canvasManager.height)/2;return Math.max(0,Math.min(1,1-s/n))}calculateDistance(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}}class Zr{constructor(e){this.renderer=e.renderer,this.stateMachine=e.stateMachine,this.canvasManager=e.canvasManager,this.config=e.config}calculateParticleConfig(e,t){const{orbX:i,orbY:s}=this.calculateOrbPosition(e),{particleBehavior:n,particleRate:a,minParticles:r,maxParticles:o}=this.calculateParticleBehavior(e,t);return{orbX:i,orbY:s,particleBehavior:n,particleRate:a,minParticles:r,maxParticles:o,emotionParams:t}}calculateOrbPosition(e){const t=this.renderer.getEffectiveCenter(),i=t.x;let s=t.y-this.config.topOffset;const n=this.stateMachine.getCurrentEmotionalProperties();return n.verticalOffset&&(s=t.y-this.config.topOffset+this.canvasManager.height*n.verticalOffset),{orbX:i,orbY:s}}calculateParticleBehavior(e,t){let i=t.particleBehavior||"ambient",s=t.particleRate||15;const n=this.stateMachine.getCurrentEmotionalProperties(),a=void 0!==t.minParticles?t.minParticles:n.minParticles||0;let r=void 0!==t.maxParticles?t.maxParticles:n.maxParticles||10;return({particleBehavior:i,particleRate:s,maxParticles:r}=this.applyRendererOverrides(i,s,r)),{particleBehavior:i,particleRate:s,minParticles:a,maxParticles:r}}applyRendererOverrides(e,t,i){return this.renderer.state&&this.renderer.state.particleBehaviorOverride&&(e=this.renderer.state.particleBehaviorOverride),this.renderer.state&&this.renderer.state.particleRateMult&&(t=Math.floor(t*this.renderer.state.particleRateMult),i=Math.floor(i*this.renderer.state.particleRateMult)),{particleBehavior:e,particleRate:t,maxParticles:i}}getParticleModifier(e){return this.renderer.getUndertoneModifier?this.renderer.getUndertoneModifier():null}}class eo{constructor(e){this.renderer=e.renderer,this._state=e.state}getGestureMotion(){let e=null,t=0;const i=this._state.currentModularGesture;return i?({gestureMotion:e,gestureProgress:t}=this.processModularGesture(i)):this.renderer&&this.renderer.getCurrentGesture&&({gestureMotion:e,gestureProgress:t}=this.processRendererGesture()),{gestureMotion:e,gestureProgress:t}}processModularGesture(e){const t=performance.now()-e.startTime,i=Math.min(t/e.duration,1),s={type:e.type,amplitude:1,frequency:1,intensity:1};return i>=1&&this.handleGestureCleanup(e),{gestureMotion:s,gestureProgress:i}}handleGestureCleanup(e){e.cleanupPending?this._state.currentModularGesture=null:e.cleanupPending=!0}processRendererGesture(){const e=this.renderer.getCurrentGesture();return e&&e.particleMotion?{gestureMotion:e.particleMotion,gestureProgress:e.progress||0}:{gestureMotion:null,gestureProgress:0}}getGestureTransform(){return this.renderer?.gestureAnimator?.applyGestureAnimations()??null}}class to{constructor(e){this.canvasManager=e.canvasManager,this.config=e.config,this.particleSystem=e.particleSystem,this.pluginSystem=e.pluginSystem||null,this.renderer=e.renderer,this.stateMachine=e.stateMachine,this._state=e.state||{debugMode:!1},this._renderDebugInfo=e.renderDebugInfo||(()=>{})}renderAllLayers(e){const{renderState:t,deltaTime:i,emotionParams:s,gestureTransform:n,renderStart:a}=e;this.renderBackgroundParticles(s.glowColor,n),this.renderOrb(t,i,n),this.renderForegroundParticles(s.glowColor,n),this.renderPlugins(),this.renderDebugIfEnabled(i),this.logPerformanceIfDebug(a,i)}renderBackgroundParticles(e,t){this.particleSystem.renderBackground(this.canvasManager.getContext(),e,t)}renderOrb(e,t,i){this.renderer.render(e,t,i)}renderForegroundParticles(e,t){this.particleSystem.renderForeground(this.canvasManager.getContext(),e,t)}renderPlugins(){if(this.pluginSystem){const e=this.stateMachine.getCurrentState();this.pluginSystem.render(this.canvasManager.getContext(),e)}}renderDebugIfEnabled(e){(this.config.showFPS||this.config.showDebug)&&this._renderDebugInfo(e)}logPerformanceIfDebug(e,t){if(!this._state.debugMode)return;const i=performance.now()-e;i>16.67&&Cs.log("WARN","Slow render frame detected",{renderTime:i,deltaTime:t,particleCount:this.particleSystem.getStats().activeParticles})}}class io{constructor(e){this.animationController=e.animationController,this.canvasManager=e.canvasManager,this.config=e.config,this.particleSystem=e.particleSystem,this.stateMachine=e.stateMachine,this._state=e.state||{audioLevel:0,currentModularGesture:null,speaking:!1}}renderDebugInfo(e){const t=this.canvasManager.getContext();t.save(),this.setupTextStyle(t);let i=20;this.config.showFPS&&(i=this.renderFPSInfo(t,i,16)),this.config.showDebug&&this.renderDebugDetails(t,i,16),t.restore()}setupTextStyle(e){e.fillStyle="#ffffff",e.font="12px monospace",e.strokeStyle="#000000",e.lineWidth=2}renderFPSInfo(e,t,i){const s=this.animationController.getPerformanceMetrics(),n=s.instantFps||s.fps||0,a=[`FPS: ${n}`,`Frame: ${s.averageFrameTime?s.averageFrameTime.toFixed(1):"0.0"}ms`,`Particles: ${this.particleSystem.getStats().activeParticles}`],{x:r,maxWidth:o}=this.calculateFPSBoxPosition(e,a);return this.drawFPSBackground(e,r,t,o,a.length),this.drawFPSBorder(e,r,t,o,a.length,n),this.drawTextLines(e,a,r,t,i),t+i*a.length}calculateFPSBoxPosition(e,t){let i=0;return t.forEach(t=>{const{width:s}=e.measureText(t);s>i&&(i=s)}),{x:this.canvasManager.width-i-8-10,maxWidth:i}}drawFPSBackground(e,t,i,s,n){e.fillStyle="rgba(0, 0, 0, 0.7)",e.fillRect(t-8,i-14,s+16,18*n+4)}drawFPSBorder(e,t,i,s,n,a){const r=this.getFPSBorderColor(a);e.strokeStyle=r,e.lineWidth=2,e.strokeRect(t-8,i-14,s+16,18*n+4)}getFPSBorderColor(e){return e>=55?"#00ff00":e>=30?"#ffff00":"#ff0000"}drawTextLines(e,t,i,s,n){e.fillStyle="#ffffff",t.forEach((t,a)=>{const r=s+a*n;e.fillText(t,i,r)})}renderDebugDetails(e,t,i){const s=this.stateMachine.getCurrentState(),n=this.particleSystem.getStats(),a=[`Emotion: ${s.emotion}${s.undertone?` (${s.undertone})`:""}`,`Particles: ${n.activeParticles}/${n.maxParticles}`,`Gesture: ${this._state.currentModularGesture?this._state.currentModularGesture.type:"none"}`,"Speaking: "+(this._state.speaking?"yes":"no"),`Audio Level: ${(100*this._state.audioLevel).toFixed(1)}%`];e.fillStyle="rgba(0, 0, 0, 0.7)";const r=Math.max(...a.map(t=>e.measureText(t).width));e.fillRect(8,t-14,r+16,a.length*i+4),e.fillStyle="#ffffff";for(const s of a)e.fillText(s,10,t),t+=i}}class so{constructor(e={}){this.enabled=!1!==e.enabled,this.maxErrors=e.maxErrors||100,this.maxStackFrames=e.maxStackFrames||10,this.reportingThreshold=e.reportingThreshold||10,this.reportingInterval=e.reportingInterval||6e4,this.errors=[],this.errorCounts=new Map,this.errorPatterns=new Map,this.suppressedErrors=new Set(e.suppressedErrors||[]),this.metadata={sessionId:this.generateSessionId(),startTime:Date.now(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",url:"undefined"!=typeof window?window.location.href:"unknown",version:"2.4.0"},this.callbacks={onError:e.onError||null,onReport:e.onReport||null,onCritical:e.onCritical||null},this.severityLevels={LOW:"low",MEDIUM:"medium",HIGH:"high",CRITICAL:"critical"},this.errorCategories={RENDERING:"rendering",ANIMATION:"animation",STATE:"state",NETWORK:"network",PLUGIN:"plugin",USER_INPUT:"user_input",PERFORMANCE:"performance",UNKNOWN:"unknown"},this.enabled&&(this.attachGlobalHandlers(),this.startReportingInterval())}generateSessionId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}attachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError=window.onerror,window.onerror=(e,t,i,s,n)=>(this.captureError(n||new Error(e),{source:t,lineno:i,colno:s,uncaught:!0}),!this.originalOnError||this.originalOnError(e,t,i,s,n)),this.originalOnUnhandledRejection=window.onunhandledrejection,window.onunhandledrejection=e=>{const t=e.reason instanceof Error?e.reason:new Error(String(e.reason));if(this.captureError(t,{type:"unhandledRejection",promise:e.promise,uncaught:!0}),this.originalOnUnhandledRejection)return this.originalOnUnhandledRejection(e)})}detachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&(window.onunhandledrejection=this.originalOnUnhandledRejection))}captureError(e,t={}){if(!this.enabled)return;if(this.shouldSuppress(e))return;const i=this.processError(e,t);i.category=this.categorizeError(e,t),i.severity=this.determineSeverity(e,i.category),this.errors.push(i),this.errors.length>this.maxErrors&&this.errors.shift();const s=`${i.name}:${i.message}`;return this.errorCounts.set(s,(this.errorCounts.get(s)||0)+1),this.detectPatterns(i),this.callbacks.onError&&this.callbacks.onError(i),i.severity===this.severityLevels.CRITICAL&&this.handleCriticalError(i),i}processError(e,t){const i=Date.now(),s=this.parseStackTrace(e.stack);return{id:`${i}-${Math.random().toString(36).substr(2,9)}`,timestamp:i,name:e.name||"Error",message:e.message||String(e),stack:s.slice(0,this.maxStackFrames),fullStack:e.stack,context:{...t,url:"undefined"!=typeof window?window.location.href:"unknown",userAgent:this.metadata.userAgent,sessionId:this.metadata.sessionId},metadata:this.collectMetadata()}}parseStackTrace(e){if(!e)return[];const t=e.split("\n"),i=[];for(const e of t){const t=e.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);t&&i.push({function:t[1],file:t[2],line:parseInt(t[3],10),column:parseInt(t[4],10)})}return i}categorizeError(e,t){const i=e.message.toLowerCase(),s=e.stack||"";return i.includes("canvas")||i.includes("render")||s.includes("Renderer")?this.errorCategories.RENDERING:i.includes("animation")||s.includes("Animation")?this.errorCategories.ANIMATION:i.includes("state")||s.includes("State")?this.errorCategories.STATE:i.includes("network")||i.includes("fetch")||i.includes("xhr")?this.errorCategories.NETWORK:i.includes("plugin")||s.includes("Plugin")?this.errorCategories.PLUGIN:"user_input"===t.source?this.errorCategories.USER_INPUT:i.includes("performance")||i.includes("memory")?this.errorCategories.PERFORMANCE:this.errorCategories.UNKNOWN}determineSeverity(e,t){return"ReferenceError"===e.name||"TypeError"===e.name?this.severityLevels.CRITICAL:t===this.errorCategories.RENDERING||t===this.errorCategories.ANIMATION?this.severityLevels.HIGH:t===this.errorCategories.NETWORK?this.severityLevels.MEDIUM:this.severityLevels.LOW}shouldSuppress(e){const t=e.message||"";for(const e of this.suppressedErrors){if("string"==typeof e&&t.includes(e))return!0;if(e instanceof RegExp&&e.test(t))return!0}return!1}detectPatterns(e){const t=`${e.category}:${e.severity}`,i=this.errorPatterns.get(t)||{count:0,firstSeen:Date.now(),lastSeen:null};i.count++,i.lastSeen=Date.now(),this.errorPatterns.set(t,i);const s=this.errors.filter(e=>Date.now()-e.timestamp<5e3);s.length>10&&this.handleErrorStorm(s)}handleCriticalError(e){console.error("Critical error detected:",e),this.callbacks.onCritical&&this.callbacks.onCritical(e),this.sendReport([e],"critical")}handleErrorStorm(e){console.warn(`Error storm detected: ${e.length} errors in 5 seconds`);const t=new Map;for(const i of e){const e=`${i.name}:${i.message}`;t.has(e)||t.set(e,[]),t.get(e).push(i)}this.sendReport(e,"storm")}collectMetadata(){const e={};return"undefined"!=typeof window&&(e.viewport={width:window.innerWidth,height:window.innerHeight},e.screen={width:window.screen.width,height:window.screen.height,pixelRatio:window.devicePixelRatio},performance.memory&&(e.memory={used:Math.round(performance.memory.usedJSHeapSize/1048576),total:Math.round(performance.memory.totalJSHeapSize/1048576),limit:Math.round(performance.memory.jsHeapSizeLimit/1048576)})),e}startReportingInterval(){this.reportingIntervalId=setInterval(()=>{this.checkAndReport()},this.reportingInterval)}stopReportingInterval(){this.reportingIntervalId&&(clearInterval(this.reportingIntervalId),this.reportingIntervalId=null)}checkAndReport(){this.errors.length>=this.reportingThreshold&&(this.sendReport(this.errors.slice()),this.errors=[])}sendReport(e,t="batch"){const i={sessionId:this.metadata.sessionId,timestamp:Date.now(),type:t,errors:e,patterns:Array.from(this.errorPatterns.entries()),counts:Array.from(this.errorCounts.entries()),metadata:this.metadata};return this.callbacks.onReport&&this.callbacks.onReport(i),i}getErrors(e={}){let t=[...this.errors];return e.category&&(t=t.filter(t=>t.category===e.category)),e.severity&&(t=t.filter(t=>t.severity===e.severity)),e.since&&(t=t.filter(t=>t.timestamp>=e.since)),t}getStats(){const e={total:this.errors.length,byCategory:{},bySeverity:{},patterns:this.errorPatterns.size,topErrors:[]};for(const t of Object.values(this.errorCategories))e.byCategory[t]=this.errors.filter(e=>e.category===t).length;for(const t of Object.values(this.severityLevels))e.bySeverity[t]=this.errors.filter(e=>e.severity===t).length;const t=Array.from(this.errorCounts.entries()).sort((e,t)=>t[1]-e[1]).slice(0,5);return e.topErrors=t.map(([e,t])=>({error:e,count:t})),e}clearErrors(){this.errors=[],this.errorCounts.clear(),this.errorPatterns.clear()}suppressError(e){this.suppressedErrors.add(e)}unsuppressError(e){this.suppressedErrors.delete(e)}enable(){this.enabled=!0,this.attachGlobalHandlers(),this.startReportingInterval()}disable(){this.enabled=!1,this.detachGlobalHandlers(),this.stopReportingInterval()}destroy(){this.disable(),this.clearErrors()}}const no=new so({enabled:!0,maxErrors:100,reportingThreshold:10,reportingInterval:6e4,suppressedErrors:["ResizeObserver loop limit exceeded","Non-Error promise rejection captured"]});class ao{constructor(e={}){this.enabled=!1!==e.enabled,this.interval=e.interval||3e4,this.thresholds={memory:e.memoryThreshold||500,fps:e.fpsThreshold||30,errorRate:e.errorRateThreshold||.1,responseTime:e.responseTimeThreshold||1e3,...e.thresholds},this.checks=new Map,this.history=[],this.maxHistory=e.maxHistory||100,this.status="initializing",this.lastCheck=null,this.dependencies={animationLoop:null,stateStore:null,eventManager:null,performanceMonitor:null,errorTracker:null},this.callbacks={onHealthy:e.onHealthy||null,onWarning:e.onWarning||null,onCritical:e.onCritical||null,onStatusChange:e.onStatusChange||null},this.registerDefaultChecks(),this.enabled&&this.start()}registerDefaultChecks(){this.registerCheck("memory",()=>this.checkMemory()),this.registerCheck("performance",()=>this.checkPerformance()),this.registerCheck("errors",()=>this.checkErrors()),this.registerCheck("dom",()=>this.checkDOM()),this.registerCheck("animation",()=>this.checkAnimation()),this.registerCheck("state",()=>this.checkState()),this.registerCheck("events",()=>this.checkEvents()),this.registerCheck("storage",()=>this.checkStorage()),this.registerCheck("network",()=>this.checkNetwork()),this.registerCheck("browser",()=>this.checkBrowser())}registerCheck(e,t,i={}){this.checks.set(e,{fn:t,critical:i.critical||!1,weight:i.weight||1,timeout:i.timeout||5e3,lastResult:null,lastRun:null})}checkMemory(){const e={status:"healthy",details:{}};if(performance.memory){const t=performance.memory.usedJSHeapSize/1048576,i=performance.memory.totalJSHeapSize/1048576,s=performance.memory.jsHeapSizeLimit/1048576;e.details={used:Math.round(t),total:Math.round(i),limit:Math.round(s),percentage:Math.round(t/s*100)},t>this.thresholds.memory?(e.status="critical",e.message=`Memory usage too high: ${Math.round(t)}MB`):t>.8*this.thresholds.memory&&(e.status="warning",e.message=`Memory usage approaching limit: ${Math.round(t)}MB`)}else e.status="unknown",e.message="Memory API not available";return e}checkPerformance(){const e={status:"healthy",details:{}};if(this.dependencies.performanceMonitor){const t=this.dependencies.performanceMonitor.getStats();e.details={fps:t.fps.current,frameTime:t.frameTime.current,health:t.health,score:t.performance},t.fps.current<this.thresholds.fps&&(e.status="warning",e.message=`Low FPS: ${t.fps.current}`),"critical"!==t.health&&"poor"!==t.health||(e.status="critical",e.message="Performance is critically low")}return e}checkErrors(){const e={status:"healthy",details:{}};if(this.dependencies.errorTracker){const t=this.dependencies.errorTracker.getStats(),i=this.dependencies.errorTracker.getErrors({since:Date.now()-6e4});e.details={total:t.total,recent:i.length,critical:t.bySeverity.critical||0,patterns:t.patterns};const s=i.length/60;s>this.thresholds.errorRate?(e.status="critical",e.message=`High error rate: ${s.toFixed(2)}/s`):t.bySeverity.critical>0&&(e.status="warning",e.message=`${t.bySeverity.critical} critical errors`)}return e}checkDOM(){const e={status:"healthy",details:{}};if("undefined"!=typeof document){const t=document.querySelectorAll("*").length,i=document.querySelectorAll("canvas").length,s=this.countEventListeners();e.details={nodes:t,canvases:i,listeners:s},t>1e4&&(e.status="warning",e.message=`High DOM node count: ${t}`),s>1e3&&(e.status="warning",e.message=`High event listener count: ${s}`)}return e}checkAnimation(){const e={status:"healthy",details:{}};if(this.dependencies.animationLoop){const t=this.dependencies.animationLoop.getStats();e.details={callbacks:t.callbackCount,fps:t.fps,running:t.isRunning,dropped:t.droppedFrames},t.isRunning||(e.status="warning",e.message="Animation loop not running"),t.droppedFrames>100&&(e.status="warning",e.message=`Dropped frames: ${t.droppedFrames}`)}return e}checkState(){const e={status:"healthy",details:{}};if(this.dependencies.stateStore){const t=this.dependencies.stateStore.getState(),i=JSON.stringify(t).length;e.details={size:i,keys:Object.keys(t).length},i>1e6&&(e.status="warning",e.message=`Large state size: ${(i/1024).toFixed(2)}KB`)}return e}checkEvents(){const e={status:"healthy",details:{}};if(this.dependencies.eventManager){const t=this.dependencies.eventManager.getActiveListeners(),i=this.dependencies.eventManager.analyzeLeaks();e.details={active:t.length,potentialLeaks:i.potentialLeaks.length,byGroup:i.byGroup},i.potentialLeaks.length>10&&(e.status="warning",e.message=`Potential memory leaks: ${i.potentialLeaks.length}`),t.length>500&&(e.status="warning",e.message=`High listener count: ${t.length}`)}return e}async checkStorage(){const e={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.storage&&navigator.storage.estimate)try{const t=await navigator.storage.estimate(),i=t.usage||0,s=t.quota||0,n=s>0?i/s*100:0;e.details={used:Math.round(i/1048576),quota:Math.round(s/1048576),percentage:Math.round(n)},n>90?(e.status="critical",e.message=`Storage almost full: ${n.toFixed(1)}%`):n>70&&(e.status="warning",e.message=`Storage usage high: ${n.toFixed(1)}%`)}catch{e.status="unknown",e.message="Storage API error"}return e}async checkNetwork(){const e={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.connection){const{connection:t}=navigator;e.details={effectiveType:t.effectiveType,downlink:t.downlink,rtt:t.rtt,saveData:t.saveData},"slow-2g"!==t.effectiveType&&"2g"!==t.effectiveType||(e.status="warning",e.message="Slow network connection detected"),t.saveData&&(e.status="warning",e.message="Data saver mode enabled")}try{const t=performance.now(),i=await fetch("/health",{method:"HEAD",cache:"no-cache"}),s=performance.now()-t;e.details.responseTime=Math.round(s),e.details.online=i.ok,s>this.thresholds.responseTime&&(e.status="warning",e.message=`Slow response time: ${s.toFixed(0)}ms`)}catch{e.details.online=navigator.onLine,navigator.onLine||(e.status="critical",e.message="No network connection")}return e}checkBrowser(){const e={status:"healthy",details:{}};e.details={userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,hardwareConcurrency:navigator.hardwareConcurrency,maxTouchPoints:navigator.maxTouchPoints};const t={webGL:!!document.createElement("canvas").getContext("webgl"),webAudio:"undefined"!=typeof AudioContext,localStorage:"undefined"!=typeof localStorage,serviceWorker:"serviceWorker"in navigator,webWorker:"undefined"!=typeof Worker};e.details.features=t;const i=Object.entries(t).filter(([e,t])=>!t).map(([e])=>e);return i.length>0&&(e.status="warning",e.message=`Missing features: ${i.join(", ")}`),e}countEventListeners(){let e=0;const t=document.querySelectorAll("*");for(const i of t){const t="undefined"!=typeof getEventListeners&&getEventListeners?getEventListeners(i):{};for(const i in t)e+=t[i].length}return e}async runCheck(e){const t=this.checks.get(e);if(!t)return{status:"unknown",message:`Check '${e}' not found`};try{const e=new Promise((e,i)=>{setTimeout(()=>i(new Error("Check timeout")),t.timeout)}),i=await Promise.race([t.fn(),e]);return t.lastResult=i,t.lastRun=Date.now(),i}catch(e){return{status:"error",message:e.message,error:e.stack}}}async runAllChecks(){const e={},t=[];for(const[i]of this.checks)t.push(this.runCheck(i).then(t=>{e[i]=t}));return await Promise.all(t),e}async performHealthCheck(){const e=performance.now(),t=await this.runAllChecks(),i=performance.now()-e,s=this.calculateOverallHealth(t),n={timestamp:Date.now(),status:s.status,score:s.score,duration:Math.round(i),checks:t,summary:s.summary};return this.lastCheck=n,this.addToHistory(n),this.updateStatus(s.status),n}calculateOverallHealth(e){let t=0,i=0,s=!1;const n=[];for(const[a,r]of Object.entries(e)){const e=this.checks.get(a),o=e?e.weight:1;let l=0;switch(r.status){case"healthy":l=100;break;case"warning":l=70,n.push({name:a,level:"warning",message:r.message});break;case"critical":l=30,n.push({name:a,level:"critical",message:r.message}),e&&e.critical&&(s=!0);break;case"error":l=0,n.push({name:a,level:"error",message:r.message});break;case"unknown":l=50}t+=l*o,i+=o}const a=i>0?Math.round(t/i):0;let r;return r=s||a<30?"critical":a<70?"degraded":a<90?"warning":"healthy",{status:r,score:a,summary:{total:Object.keys(e).length,healthy:Object.values(e).filter(e=>"healthy"===e.status).length,warning:Object.values(e).filter(e=>"warning"===e.status).length,critical:Object.values(e).filter(e=>"critical"===e.status).length,issues:n}}}updateStatus(e){if(this.status!==e){const t=this.status;switch(this.status=e,this.callbacks.onStatusChange&&this.callbacks.onStatusChange(e,t),e){case"healthy":this.callbacks.onHealthy&&this.callbacks.onHealthy();break;case"warning":case"degraded":this.callbacks.onWarning&&this.callbacks.onWarning(this.lastCheck);break;case"critical":this.callbacks.onCritical&&this.callbacks.onCritical(this.lastCheck)}}}addToHistory(e){this.history.push(e),this.history.length>this.maxHistory&&this.history.shift()}start(){this.intervalId||(this.performHealthCheck(),this.intervalId=setInterval(()=>{this.performHealthCheck()},this.interval))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}destroy(){this.stop(),this.checks.clear(),this.history=[],this.lastCheck=null}setDependencies(e){Object.assign(this.dependencies,e)}getStatus(){return this.status}getLastCheck(){return this.lastCheck}getHistory(){return[...this.history]}async getFullReport(){return{...await this.performHealthCheck(),history:this.getHistory(),uptime:this.getUptime(),configuration:{interval:this.interval,thresholds:this.thresholds,checks:Array.from(this.checks.keys())}}}getUptime(){if(!this.history.length)return 0;const e=this.history[0].timestamp;return Date.now()-e}async handleHealthRequest(e,t){const i=await this.performHealthCheck();return{statusCode:"healthy"===i.status||"warning"===i.status?200:(i.status,503),headers:{"Content-Type":"application/json","Cache-Control":"no-cache"},body:JSON.stringify({status:i.status,score:i.score,timestamp:i.timestamp,checks:i.checks,version:"2.4.0"})}}}const ro=new ao({enabled:!1,interval:3e4});class oo{constructor(e){if(!e.errorBoundary)throw new Error("DestructionManager: errorBoundary required");if(!e.animationController)throw new Error("DestructionManager: animationController required");if(!e.state)throw new Error("DestructionManager: state required");if(!e.stop)throw new Error("DestructionManager: stop required");if(!e.stopSpeaking)throw new Error("DestructionManager: stopSpeaking required");if(!e.disconnectAudio)throw new Error("DestructionManager: disconnectAudio required");this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.positionController=e.positionController||null,this.soundSystem=e.soundSystem||null,this.audioLevelProcessor=e.audioLevelProcessor||null,this.particleSystem=e.particleSystem||null,this.renderer=e.renderer||null,this.canvasManager=e.canvasManager||null,this.eventManager=e.eventManager||null,this.accessibilityManager=e.accessibilityManager||null,this.mobileOptimization=e.mobileOptimization||null,this.pluginSystem=e.pluginSystem||null,this.audioAnalyzer=e.audioAnalyzer||null,this.shapeMorpher=e.shapeMorpher||null,this.gestureController=e.gestureController||null,this.stateCoordinator=e.stateCoordinator||null,this.visualizationRunner=e.visualizationRunner||null,this.orbScaleAnimator=e.orbScaleAnimator||null,this.audioHandler=e.audioHandler||null,this.degradationManager=e.degradationManager||null,this.stateMachine=e.stateMachine||null,this.contextManager=e.contextManager||null,this._state=e.state,this._stop=e.stop,this._stopSpeaking=e.stopSpeaking,this._disconnectAudio=e.disconnectAudio}destroy(){this.errorBoundary.wrap(()=>{this.stopAnimations(),this.destroyControllers(),this.cleanupSubsystems(),this.cleanupEvents(),this.cleanupPluginsAndExtensions(),this.clearErrorBoundary()},"destruction")()}stopAnimations(){this._stop(),this._state.speaking&&this._stopSpeaking()}destroyControllers(){this.animationController&&this.animationController.destroy(),this.positionController&&this.positionController.destroy()}cleanupSubsystems(){this.cleanupSound(),this.cleanupAudio(),this.cleanupParticles(),this.cleanupRenderer(),this.cleanupCanvas(),this.cleanupManagers(),this.cleanupSingletons()}cleanupManagers(){this.gestureController&&"function"==typeof this.gestureController.destroy&&this.gestureController.destroy(),this.stateCoordinator&&"function"==typeof this.stateCoordinator.destroy&&this.stateCoordinator.destroy(),this.visualizationRunner&&"function"==typeof this.visualizationRunner.destroy&&this.visualizationRunner.destroy(),this.orbScaleAnimator&&"function"==typeof this.orbScaleAnimator.destroy&&this.orbScaleAnimator.destroy(),this.audioHandler&&"function"==typeof this.audioHandler.destroy&&this.audioHandler.destroy(),this.degradationManager&&"function"==typeof this.degradationManager.destroy&&this.degradationManager.destroy(),this.stateMachine&&"function"==typeof this.stateMachine.destroy&&this.stateMachine.destroy(),this.contextManager&&"function"==typeof this.contextManager.destroy&&this.contextManager.destroy()}cleanupSingletons(){no&&no.destroy(),_n&&_n.destroy(),ro&&ro.destroy()}cleanupSound(){this.soundSystem&&this.soundSystem.cleanup()}cleanupAudio(){this.audioLevelProcessor&&this.audioLevelProcessor.cleanup()}cleanupParticles(){this.particleSystem&&this.particleSystem.destroy()}cleanupRenderer(){this.renderer&&(this.renderer.stopAllGestures(),this.renderer.destroy())}cleanupCanvas(){this.canvasManager&&this.canvasManager.destroy()}cleanupEvents(){this.eventManager&&this.eventManager.destroy(),this._state.llmHandler&&(this._state.llmHandler=null)}cleanupPluginsAndExtensions(){this.cleanupAccessibility(),this.cleanupMobile(),this.cleanupPlugins(),this.cleanupAudioExtensions()}cleanupAccessibility(){this.accessibilityManager&&this.accessibilityManager.destroy()}cleanupMobile(){this.mobileOptimization&&this.mobileOptimization.destroy()}cleanupPlugins(){this.pluginSystem&&this.pluginSystem.destroy()}cleanupAudioExtensions(){this.audioAnalyzer&&(this._disconnectAudio(),this.audioAnalyzer.destroy()),this.shapeMorpher&&this.shapeMorpher.reset()}clearErrorBoundary(){this.errorBoundary.clearErrors(),this.nullifyReferences()}nullifyReferences(){this.errorBoundary=null,this.animationController=null,this.positionController=null,this.soundSystem=null,this.audioLevelProcessor=null,this.particleSystem=null,this.renderer=null,this.canvasManager=null,this.eventManager=null,this.accessibilityManager=null,this.mobileOptimization=null,this.pluginSystem=null,this.audioAnalyzer=null,this.shapeMorpher=null,this.gestureController=null,this.stateCoordinator=null,this.visualizationRunner=null,this.orbScaleAnimator=null,this.audioHandler=null,this.degradationManager=null,this.stateMachine=null,this.contextManager=null,this._state=null,this._stop=null,this._stopSpeaking=null,this._disconnectAudio=null}}class lo{constructor(e){this.renderer=e.renderer||null,this._state=e.state,this._emit=e.emit}startBreathingAnimation(){this._state.breathingAnimationId&&cancelAnimationFrame(this._state.breathingAnimationId);const e=()=>{if(!this._state.breathePattern||!this._state.isRunning)return;const t=this._state.breathePattern,i=Date.now(),s=(i-t.phaseStartTime)/1e3,{scale:n,nextPhase:a}=this.calculatePhaseState(t,s,i);a!==t.currentPhase&&(t.currentPhase=a),this.applyScale(n),this._state.breathingAnimationId=requestAnimationFrame(e)};this._state.breathePattern.currentPhase="inhale",this._state.breathePattern.phaseStartTime=Date.now(),this._emit("inhale-start"),e()}calculatePhaseState(e,t,i){let s=1,n=e.currentPhase;switch(e.currentPhase){case"inhale":({scale:s,nextPhase:n}=this.processInhalePhase(e,t,i));break;case"hold1":({scale:s,nextPhase:n}=this.processHold1Phase(e,t,i));break;case"exhale":({scale:s,nextPhase:n}=this.processExhalePhase(e,t,i));break;case"hold2":({scale:s,nextPhase:n}=this.processHold2Phase(e,t,i))}return{scale:s,nextPhase:n}}processInhalePhase(e,t,i){let s=1,n=e.currentPhase;return t>=e.inhale?(n="hold1",e.phaseStartTime=i,this._emit("hold-start",{type:"post-inhale"})):s=1+t/e.inhale*.3,{scale:s,nextPhase:n}}processHold1Phase(e,t,i){let s=e.currentPhase;return t>=e.hold1&&(s="exhale",e.phaseStartTime=i,this._emit("exhale-start")),{scale:1.3,nextPhase:s}}processExhalePhase(e,t,i){let s=1.3,n=e.currentPhase;return t>=e.exhale?(n="hold2",e.phaseStartTime=i,this._emit("hold-start",{type:"post-exhale"})):s=1.3-t/e.exhale*.4,{scale:s,nextPhase:n}}processHold2Phase(e,t,i){let s=e.currentPhase;return t>=e.hold2&&(s="inhale",e.phaseStartTime=i,this._emit("inhale-start")),{scale:.9,nextPhase:s}}applyScale(e){this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(e)}}class ho{constructor(e){this.errorBoundary=e.errorBoundary,this.animationController=e.animationController,this.stateMachine=e.stateMachine,this.particleSystem=e.particleSystem,this.soundSystem=e.soundSystem,this.renderer=e.renderer||null,this.config=e.config,this._state=e.state,this._getEventNames=e.getEventNames}getSystemStatus(){return this.errorBoundary.wrap(()=>({...this.getCoreStatus(),...this.getEmotionalStatus(),...this.getGestureStatus(),particles:this.getParticleStatus(),...this.getAudioStatus(),renderer:this.getRendererStatus(),eventListeners:this.getEventListenerCount(),errorStats:this.getErrorStats()}),"system-status",{})()}getCoreStatus(){const e=this.animationController.getPerformanceMetrics();return{isRunning:e.isRunning,fps:e.fps,targetFPS:e.targetFPS,performanceDegradation:e.performanceDegradation}}getEmotionalStatus(){const e=this.stateMachine.getCurrentState();return{emotion:e.emotion,undertone:e.undertone,isTransitioning:e.isTransitioning,transitionProgress:e.transitionProgress}}getGestureStatus(){return{currentGesture:this.renderer?.currentGesture||null,gestureActive:this.renderer?.isGestureActive()||!1}}getParticleStatus(){const e=this.particleSystem.getStats();return{active:e.activeParticles,max:e.maxParticles,poolEfficiency:e.poolEfficiency}}getAudioStatus(){return{audioEnabled:this.config.enableAudio,soundSystemAvailable:this.soundSystem.isAvailable(),speaking:this._state.speaking,audioLevel:this._state.audioLevel,masterVolume:this.config.masterVolume}}getRendererStatus(){const e=this.renderer.getStats();return{gradientCacheSize:e.gradientCacheSize,breathingPhase:e.breathingPhase,layers:e.layers}}getEventListenerCount(){return this._getEventNames().length}getErrorStats(){return this.errorBoundary.getErrorStats()}}class co{constructor(e){if(!e.errorBoundary)throw new Error("SleepWakeManager: errorBoundary required");if(!e.express)throw new Error("SleepWakeManager: express required");if(!e.state)throw new Error("SleepWakeManager: state required");if(!e.emit)throw new Error("SleepWakeManager: emit required");this.errorBoundary=e.errorBoundary,this._express=e.express,this.idleBehavior=e.idleBehavior||null,this.renderer=e.renderer||null,this._state=e.state,this._emit=e.emit,this._chainTarget=e.chainTarget||this}sleep(){return this.errorBoundary.wrap(async()=>(this._state.sleeping||(await this.performSleepSequence(),this.enterSleepState()),this._chainTarget),"sleep",this._chainTarget)()}async performSleepSequence(){this._express("yawn"),await this.delay(1e3),this._express("sway"),await this.delay(1e3)}enterSleepState(){this._state.sleeping=!0,this.renderer&&this.renderer.enterSleepMode&&this.renderer.enterSleepMode(),this.idleBehavior&&this.idleBehavior.enterSleep&&this.idleBehavior.enterSleep(),this._emit("sleep")}wake(){return this.errorBoundary.wrap(async()=>this._state.sleeping?(this.exitSleepState(),await this.performWakeSequence(),this._chainTarget):this._chainTarget,"wake",this._chainTarget)()}exitSleepState(){this._state.sleeping=!1,this.renderer&&this.renderer.wakeUp&&this.renderer.wakeUp(),this.idleBehavior&&this.idleBehavior.wakeUp&&this.idleBehavior.wakeUp()}async performWakeSequence(){this._express("stretch"),await this.delay(1e3),this._express("slowBlink"),await this.delay(1e3),this._express("shake"),await this.delay(500),this._emit("wake")}delay(e){return new Promise(t=>setTimeout(t,e))}}class uo{constructor(e){if(!e.errorBoundary)throw new Error("SpeechManager: errorBoundary required");if(!e.emit)throw new Error("SpeechManager: emit required");this.errorBoundary=e.errorBoundary,this.audioLevelProcessor=e.audioLevelProcessor||null,this.audioHandler=e.audioHandler||null,this.renderer=e.renderer||null,this.config=e.config||{},this._state=e.state||{speaking:!1},this._setTTSSpeaking=e.setTTSSpeaking||(()=>{}),this._emit=e.emit,this._chainTarget=e.chainTarget||this}speak(e,t={}){if(!window.speechSynthesis)return null;const i=this.createUtterance(e,t);return this.setupUtteranceHandlers(i,e),window.speechSynthesis.speak(i),i}createUtterance(e,t){const i=new SpeechSynthesisUtterance(e);return t.voice&&(i.voice=t.voice),t.rate&&(i.rate=t.rate),t.pitch&&(i.pitch=t.pitch),t.volume&&(i.volume=t.volume),t.lang&&(i.lang=t.lang),i}setupUtteranceHandlers(e,t){e.onstart=()=>{this._setTTSSpeaking(!0),this._emit("tts:start",{text:t})},e.onend=()=>{this._setTTSSpeaking(!1),this._emit("tts:end")},e.onerror=e=>{this._setTTSSpeaking(!1),this._emit("tts:error",{error:e})},e.onboundary=e=>{this._emit("tts:boundary",{name:e.name,charIndex:e.charIndex,charLength:e.charLength})}}startSpeaking(e){return this.errorBoundary.wrap(()=>this.validateAudioContext(e)&&this.initializeAudioProcessor(e)?(this.activateSpeechMode(e),this._chainTarget):this._chainTarget,"speech-start",this._chainTarget)()}validateAudioContext(e){if(!e)throw new Error("AudioContext is required for speech reactivity");return!!this.config.enableAudio&&!this._state.speaking}initializeAudioProcessor(e){return!!this.audioLevelProcessor.initialize(e)}activateSpeechMode(e){this._state.speaking=!0,this.renderer&&this.renderer.onSpeechStart(e),this._emit("speechStarted",{audioContext:e,analyser:this.audioLevelProcessor.getAnalyser(),chainTarget:this._chainTarget})}stopSpeaking(){return this.errorBoundary.wrap(()=>this.audioHandler?this.audioHandler.stopSpeaking():this._chainTarget,"speech-stop",this._chainTarget)()}}class go{constructor(e){if(!e.emit)throw new Error("AudioLevelCallbackManager: emit required");this.audioLevelProcessor=e.audioLevelProcessor||null,this.renderer=e.renderer||null,this.particleSystem=e.particleSystem||null,this._express=e.express||(()=>{}),this._emit=e.emit}setupAudioLevelProcessorCallbacks(){this.setupLevelUpdateCallback(),this.setupVolumeSpikeCallback(),this.setupErrorCallback()}setupLevelUpdateCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onLevelUpdate(e=>{this.renderer&&this.renderer.updateAudioLevel(e.level),this._emit("audioLevelUpdate",{level:e.level,rawData:Array.from(e.rawData),timestamp:e.timestamp})})}setupVolumeSpikeCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onVolumeSpike(e=>{const t=this.handleVolumeSpike();this._emit("volumeSpike",{...e,gestureTriggered:t})})}handleVolumeSpike(){return!!this.particleSystem&&(!this.particleSystem.particles.some(e=>e.gestureProgress<1)&&(this._express("pulse"),!0))}setupErrorCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onError(e=>{this._emit("audioProcessingError",e)})}}class mo{constructor(e){this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state,this._chainTarget=e.chainTarget||this,this.animationId=null}setOrbScale(e,t=1e3,i="easeInOut"){return this.errorBoundary.wrap(()=>(this.renderer&&this.startScaleAnimation(e,t,i),this._chainTarget),"setOrbScale",this._chainTarget)()}startScaleAnimation(e,t,i){const s=this._state.currentOrbScale||1,n=Date.now(),a=()=>{const r=Date.now()-n,o=Math.min(r/t,1),l=this.applyEasing(o,i);this._state.currentOrbScale=s+(e-s)*l,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(this._state.currentOrbScale),o<1&&this._state.isRunning&&(this.animationId=requestAnimationFrame(a))};a()}applyEasing(e,t){switch(t){case"easeIn":return this.easeIn(e);case"easeOut":return this.easeOut(e);case"easeInOut":return this.easeInOut(e);default:return e}}easeIn(e){return e*e}easeOut(e){return e*(2-e)}easeInOut(e){return e<.5?2*e*e:(4-2*e)*e-1}destroy(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.renderer=null,this._state=null}}class po{constructor(e){if(!e.errorBoundary)throw new Error("RecordingStateManager: errorBoundary required");if(!e.emit)throw new Error("RecordingStateManager: emit required");this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state||{recording:!1},this._emit=e.emit,this._chainTarget=e.chainTarget||this}startRecording(){return this.errorBoundary.wrap(()=>(this._state.recording||(this._state.recording=!0,this.renderer&&this.renderer.startRecording&&this.renderer.startRecording(),this._emit("recordingStarted")),this._chainTarget),"recording-start",this._chainTarget)()}stopRecording(){return this.errorBoundary.wrap(()=>this._state.recording?(this._state.recording=!1,this.renderer&&this.renderer.stopRecording&&this.renderer.stopRecording(),this._emit("recordingStopped"),this._chainTarget):this._chainTarget,"recording-stop",this._chainTarget)()}}class fo{constructor(e){this.errorBoundary=e.errorBoundary,this.renderer=e.renderer||null,this._state=e.state,this._startBreathingAnimation=e.startBreathingAnimation,this._chainTarget=e.chainTarget||this}static getPresets(){return{calm:{inhale:4,hold1:0,exhale:4,hold2:0},anxious:{inhale:2,hold1:0,exhale:2,hold2:0},meditative:{inhale:4,hold1:7,exhale:8,hold2:0},deep:{inhale:5,hold1:5,exhale:5,hold2:5},sleep:{inhale:6,hold1:0,exhale:8,hold2:2}}}setBreathePattern(e,t,i,s){return this.errorBoundary.wrap(()=>{const n=e+t+i+s;return this._state.breathePattern={inhale:e,hold1:t,exhale:i,hold2:s,totalCycle:n,currentPhase:"inhale",phaseStartTime:Date.now(),phaseProgress:0},this._startBreathingAnimation(),this._chainTarget},"setBreathePattern",this._chainTarget)()}breathe(e="calm"){return this.errorBoundary.wrap(()=>{const t=fo.getPresets(),i=t[e]||t.calm;return this.setBreathePattern(i.inhale,i.hold1,i.exhale,i.hold2)},"breathe",this._chainTarget)()}stopBreathing(){return this.errorBoundary.wrap(()=>(this._state.breathingAnimationId&&(cancelAnimationFrame(this._state.breathingAnimationId),this._state.breathingAnimationId=null),this._state.breathePattern=null,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(1),this._chainTarget),"stopBreathing",this._chainTarget)()}}class yo{constructor(e,t){this._getSubsystems=e,this._emitEvent=t}handleEvent(e,t){switch(e){case"degradationApplied":this.applySettings(t.settings),this._emitEvent("performanceDegradation",t);break;case"recoveryApplied":this.applySettings(t.settings),this._emitEvent("performanceRecovery",t);break;case"levelChanged":this.applySettings(t.settings),this._emitEvent("degradationLevelChanged",t)}}applySettings(e){const t=this._getSubsystems();t.particleSystem&&void 0!==e.particleLimit&&t.particleSystem.setMaxParticles(e.particleLimit),t.soundSystem&&void 0!==e.audioEnabled&&!e.audioEnabled&&t.soundSystem.isAvailable()&&t.soundSystem.stopAmbientTone(200),t.renderer&&void 0!==e.qualityLevel&&t.renderer.setQualityLevel(e.qualityLevel)}}class bo{constructor(t={}){this.errorBoundary=new e,this.eventManager=new ws({maxListeners:t.maxEventListeners||100,enableDebugging:t.enableEventDebugging||!1,enableMonitoring:t.enableEventMonitoring||!0,memoryWarningThreshold:t.eventMemoryWarningThreshold||50}),this.eventManager.emit||(this.eventManager._listeners={},this.eventManager.emit=(e,t)=>{const i=this.eventManager._listeners[e];i&&i.forEach(e=>e(t))},this.eventManager.on=(e,t)=>{this.eventManager._listeners[e]||(this.eventManager._listeners[e]=[]),this.eventManager._listeners[e].push(t)},this.eventManager.off=(e,t)=>{const i=this.eventManager._listeners[e];if(i){const e=i.indexOf(t);e>-1&&i.splice(e,1)}}),this.errorBoundary.wrap(()=>{this.initialize(t)},"initialization")()}initialize(e){this.Emotions=M,this.Gestures=Oi,this.ParticleBehaviors=Ms,this.speechManager=new uo({errorBoundary:this.errorBoundary,emit:(e,t)=>this.emit(e,t)}),this.audioLevelCallbackManager=new go({emit:(e,t)=>this.emit(e,t)}),this.orbScaleAnimator=new mo(this),this.recordingStateManager=new po({errorBoundary:this.errorBoundary,emit:(e,t)=>this.emit(e,t)}),this.breathingPatternManager=new fo(this),new Qr(this,e).initialize(),this.renderStateBuilder=new Jr(this),this.threatLevelCalculator=new Kr(this),this.particleConfigCalculator=new Zr(this);const t=this;this.gestureMotionProvider=new eo({renderer:this.renderer,state:{get currentModularGesture(){return t.currentModularGesture},set currentModularGesture(e){t.currentModularGesture=e}}}),this.renderLayerOrchestrator=new to(this),this.debugInfoRenderer=new io(this),this.destructionManager=new oo({errorBoundary:this.errorBoundary,animationController:this.animationController,positionController:this.positionController,soundSystem:this.soundSystem,audioLevelProcessor:this.audioLevelProcessor,particleSystem:this.particleSystem,renderer:this.renderer,canvasManager:this.canvasManager,eventManager:this.eventManager,accessibilityManager:this.accessibilityManager,mobileOptimization:this.mobileOptimization,pluginSystem:this.pluginSystem,audioAnalyzer:this.audioAnalyzer,shapeMorpher:this.shapeMorpher,state:{get speaking(){return t.speaking},get llmHandler(){return t.llmHandler},set llmHandler(e){t.llmHandler=e}},stop:()=>this.stop(),stopSpeaking:()=>this.stopSpeaking(),disconnectAudio:()=>this.disconnectAudio()}),this.breathingAnimationController=new lo(this),this.systemStatusReporter=new ho({errorBoundary:this.errorBoundary,animationController:this.animationController,stateMachine:this.stateMachine,particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer,config:this.config,state:{get speaking(){return t.speaking},get audioLevel(){return t.audioLevel}},getEventNames:()=>this.getEventNames()}),this.sleepWakeManager=new co({errorBoundary:this.errorBoundary,express:(e,t)=>this.express(e,t),idleBehavior:this.idleBehavior,renderer:this.renderer,state:{get sleeping(){return t.sleeping},set sleeping(e){t.sleeping=e}},emit:(e,t)=>this.emit(e,t),chainTarget:this}),this.degradationEventHandler=new yo(()=>({particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer}),(e,t)=>this.emit(e,t))}handleDegradationEvent(e,t){return this.degradationEventHandler.handleEvent(e,t)}applyDegradationSettings(e){return this.degradationEventHandler.applySettings(e)}setupAudioLevelProcessorCallbacks(){this.audioLevelCallbackManager.setupAudioLevelProcessorCallbacks()}setEmotion(e,t=null){return this.errorBoundary.wrap(()=>this.stateCoordinator.setEmotion(e,t),"emotion-setting",this)()}updateUndertone(e){return this.errorBoundary.wrap(()=>(this.stateMachine.applyUndertoneModifier(e),this.renderer&&this.renderer.updateUndertone&&this.renderer.updateUndertone(e),this),"undertone-update",this)()}setBPM(e){return this.errorBoundary.wrap(()=>(this.renderer?.setBPM&&this.renderer.setBPM(e),this),"bpm-update",this)()}setRotationSpeed(e){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationSpeed&&this.renderer.setRotationSpeed(e),this),"rotation-speed-update",this)()}setRotationAngle(e){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationAngle&&this.renderer.setRotationAngle(e),this),"rotation-angle-update",this)()}getPosition(){return this.animationFrameController.getPosition()}setGazeTracking(e){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.setGazeTracking&&this.renderer.setGazeTracking(e),this),"gaze-tracking-update",this)()}express(e,t={}){return this.gestureController?this.gestureController.express(e,t):(console.warn("GestureController not initialized, skipping gesture"),this)}expressChord(e,t={}){return this.gestureController.expressChord(e,t)}executeGestureDirectly(e,t={}){this.gestureController.executeGestureDirectly(e,t),this.emit("gesture",{name:e,options:t})}chain(...e){return this.gestureController.chain(...e)}executeChainSequence(e){return this.gestureController.executeChainSequence(e)}perform(e,t={}){return this.performanceBehaviorManager.perform(e,t)}updateContext(e){return this.frustrationContextManager.updateContext(e)}getContext(){return this.emotionalStateQueryManager.getContext()}incrementFrustration(e=10){return this.frustrationContextManager.incrementFrustration(e)}decrementFrustration(e=10){return this.frustrationContextManager.decrementFrustration(e)}resetFrustration(){return this.frustrationContextManager.resetFrustration()}getAvailablePerformances(){return this.performanceBehaviorManager.getAvailablePerformances()}registerPerformance(e,t){return this.performanceBehaviorManager.registerPerformance(e,t)}getPerformanceAnalytics(){return this.performanceBehaviorManager.getPerformanceAnalytics()}getContextAnalytics(){return this.performanceBehaviorManager.getContextAnalytics()}startSpeaking(e){return this.speechManager?this.speechManager.startSpeaking(e):this}stopSpeaking(){return this.speechManager?this.speechManager.stopSpeaking():this}startRecording(){return this.recordingStateManager?this.recordingStateManager.startRecording():this}stopRecording(){return this.recordingStateManager?this.recordingStateManager.stopRecording():this}sleep(){return this.sleepWakeManager.sleep()}wake(){return this.sleepWakeManager.wake()}getTTSVoices(){return this.ttsManager.getTTSVoices()}isTTSSpeaking(){return this.ttsManager.isTTSSpeaking()}start(){return this.executionLifecycleManager.start()}stop(){return this.executionLifecycleManager.stop()}setBreathePattern(e,t,i,s){return this.breathingPatternManager?this.breathingPatternManager.setBreathePattern(e,t,i,s):this}setOrbScale(e,t=1e3,i="easeInOut"){return this.orbScaleAnimator?this.orbScaleAnimator.setOrbScale(e,t,i):this}breathe(e="calm"){return this.breathingPatternManager?this.breathingPatternManager.breathe(e):this}startBreathingAnimation(){this.breathingAnimationController.startBreathingAnimation()}stopBreathing(){return this.breathingPatternManager?this.breathingPatternManager.stopBreathing():this}on(e,t){return this.eventListenerManager.on(e,t)}off(e,t){return this.eventListenerManager.off(e,t)}once(e,t){return this.eventListenerManager.once(e,t)}removeAllListeners(e=null){return this.eventListenerManager.removeAllListeners(e)}listenerCount(e){return this.eventListenerManager.listenerCount(e)}getEventNames(){return this.eventListenerManager.getEventNames()}getEventStats(){return this.eventListenerManager.getEventStats()}getEventDebugInfo(){return this.eventListenerManager.getEventDebugInfo()}getBrowserCompatibility(){return this.diagnosticsManager.getBrowserCompatibility()}getDegradationStatus(){return this.performanceMonitoringManager.getDegradationStatus()}setDegradationLevel(e){return this.performanceMonitoringManager.setDegradationLevel(e)}isFeatureAvailable(e){return this.performanceMonitoringManager.isFeatureAvailable(e)}recoverCanvasContext(){return!!this.contextRecovery&&this.contextRecovery.recover()}isCanvasContextLost(){return!!this.contextRecovery&&this.contextRecovery.isLost()}getDebugReport(){return this.debugProfilingManager.getDebugReport()}exportDebugData(){return this.debugProfilingManager.exportDebugData()}startProfiling(e,t={}){this.debugProfilingManager.startProfiling(e,t)}endProfiling(e){return this.debugProfilingManager.endProfiling(e)}takeMemorySnapshot(e){this.debugProfilingManager.takeMemorySnapshot(e)}clearDebugData(){this.debugProfilingManager.clearDebugData()}getRuntimeCapabilities(){return this.debugProfilingManager.getRuntimeCapabilities()}emit(e,t=null){this.eventListenerManager.emit(e,t)}update(e){this.errorBoundary.wrap(()=>{this.visualizationRunner.update(e)},"audio-update")()}render(){try{const{renderStart:e,deltaTime:t,renderState:i}=this.renderStateBuilder.buildRenderState();this.debugMode&&Cs.trackFrameTiming(t),this.canvasManager.clear(),this.gazeTracker&&this.gazeTracker.update(t),this.threatLevelCalculator.updateThreatLevel(i);const s=h(i.emotion);this.renderer.setEmotionalState(i.emotion,s,i.undertone);const n=this.particleConfigCalculator.calculateParticleConfig(i,s),{orbX:a,orbY:r,particleBehavior:o,particleRate:l,minParticles:c,maxParticles:u}=n;this.particleSystem.spawn(o,i.emotion,l,a,r,t,null,c,u,this.renderer.particleScaleFactor||this.renderer.scaleFactor||1,this.config.classicConfig?.particleSizeMultiplier||1,s.particleColors||null,i.undertone);const d=this.particleConfigCalculator.getParticleModifier(i),{gestureMotion:g,gestureProgress:m}=this.gestureMotionProvider.getGestureMotion();this.particleSystem.update(t,a,r,g,m,d);const p=this.gestureMotionProvider.getGestureTransform();this.renderLayerOrchestrator.renderAllLayers({renderState:i,deltaTime:t,emotionParams:s,gestureTransform:p,renderStart:e})}catch(e){this.errorBoundary.logError(e,"main-render")}}renderDebugInfo(e){this.debugInfoRenderer.renderDebugInfo(e)}getEmotionalColor(){return this.emotionalStateQueryManager.getEmotionalColor()}getCurrentState(){return this.emotionalStateQueryManager.getCurrentState()}getAvailableEmotions(){return this.emotionalStateQueryManager.getAvailableEmotions()}getAvailableUndertones(){return this.emotionalStateQueryManager.getAvailableUndertones()}getAudioStats(){return this.speechReactivityManager.getAudioStats()}updateAudioConfig(e){this.speechReactivityManager.updateAudioConfig(e)}getAvailableGestures(){return this.emotionalStateQueryManager.getAvailableGestures()}connectAudioSource(e){return this.speechReactivityManager.connectAudioSource(e)}setVolume(e){return this.errorBoundary.wrap(()=>this.audioHandler.setVolume(e),"volume-setting",this)()}getVolume(){return this.config.masterVolume}setSoundEnabled(e){return this.config.soundEnabled=e,this}isSoundEnabled(){return this.config.soundEnabled}pause(){return this.executionLifecycleManager.pause()}resume(){return this.executionLifecycleManager.resume()}isActive(){return this.executionLifecycleManager.isActive()}setTargetFPS(e){return this.performanceMonitoringManager.setTargetFPS(e)}getTargetFPS(){return this.performanceMonitoringManager.getTargetFPS()}setPosition(e,t,i=0){return this.animationFrameController.setPosition(e,t,i)}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){return this.animationFrameController.animateToPosition(e,t,i,s,n)}clearParticles(){return this.visualTransformationManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this.visualTransformationManager.setParticleSystemCanvasDimensions(e,t)}setPerformanceDegradation(e){return this.performanceMonitoringManager.setPerformanceDegradation(e)}getAudioLevel(){return this.speechReactivityManager.getAudioLevel()}isSpeaking(){return this.speechReactivityManager.isSpeaking()}setAudioSmoothing(e){return this.speechReactivityManager.setAudioSmoothing(e)}getSystemStatus(){return this.healthCheckManager.getSystemStatus()}setDebugMode(e){return this.healthCheckManager.setDebugMode(e)}triggerTestError(e="manual-test"){return this.healthCheckManager.triggerTestError(e)}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}registerPlugin(e){return this.pluginSystem.registerPlugin(e)}setAccessibility(e){e.colorBlindMode&&this.accessibilityManager.setColorBlindMode(e.colorBlindMode),void 0!==e.reducedMotion&&(this.accessibilityManager.reducedMotionPreferred=e.reducedMotion),void 0!==e.highContrast&&(this.accessibilityManager.highContrastEnabled=e.highContrast)}getMobileStatus(){return this.healthCheckManager.getMobileStatus()}getAccessibilityStatus(){return this.healthCheckManager.getAccessibilityStatus()}setState(e){return this.setEmotion(e)}speak(e,t={}){return this.ttsManager.speak(e,t)}setTTSSpeaking(e){this.ttsManager.setTTSSpeaking(e)}getVoices(){return this.ttsManager.getVoices()}stopTTS(){this.ttsManager.stopTTS()}handleResize(e,t,i){this.visualTransformationManager.handleResize(e,t,i)}morphTo(e,t={}){return this.visualTransformationManager.morphTo(e,t)}connectAudio(e){return this.errorBoundary.wrap(()=>this.audioHandler.connectAudio(e),"connectAudio",this)()}disconnectAudio(){return this.errorBoundary.wrap(()=>this.audioHandler.disconnectAudio(),"disconnectAudio",this)()}setOffset(e,t,i=0){return this.visualTransformationManager.setOffset(e,t,i)}getOffset(){return this.visualTransformationManager.getOffset()}setBackdrop(e={}){return this.visualTransformationManager.setBackdrop(e)}getBackdrop(){return this.visualTransformationManager.getBackdrop()}animateOffset(e,t,i=0,s=1e3,n="easeOutCubic"){return this.visualTransformationManager.animateOffset(e,t,i,s,n)}getAvailableShapes(){return this.emotionalStateQueryManager.getAvailableShapes()}async handleLLMResponse(e,t={}){return this.llmIntegrationBridge.handleLLMResponse(e,t)}configureLLMHandler(e){return this.llmIntegrationBridge.configureLLMHandler(e)}getLLMResponseSchema(){return this.llmIntegrationBridge.getLLMResponseSchema()}static getLLMPromptTemplate(e={}){return jr.getLLMPromptTemplate(e)}static getLLMEmotions(){return jr.getLLMEmotions()}static getLLMActions(){return jr.getLLMActions()}static getLLMShapes(){return jr.getLLMShapes()}static getLLMGestures(){return jr.getLLMGestures()}destroy(){this.destructionManager.destroy()}throttledWarn(e,t){const i=Date.now();i-(this.warningTimestamps[t]||0)>this.warningThrottle&&(this.warningTimestamps[t]=i)}}const vo={easy:{windowMultiplier:1.5,label:"Easy"},normal:{windowMultiplier:1,label:"Normal"},hard:{windowMultiplier:.7,label:"Hard"}};class Mo{constructor(){this._preset="normal",this._assist={autoRhythm:!1,slowMode:!1,visualMetronome:!1},this._slowModeMult=.75}setDifficulty(e){vo[e]&&(this._preset=e)}getDifficulty(){return this._preset}getWindowMultiplier(){return vo[this._preset].windowMultiplier}setAssist(e){void 0!==e.autoRhythm&&(this._assist.autoRhythm=!!e.autoRhythm),void 0!==e.slowMode&&(this._assist.slowMode=!!e.slowMode),void 0!==e.visualMetronome&&(this._assist.visualMetronome=!!e.visualMetronome)}getAssist(){return{...this._assist}}get autoRhythm(){return this._assist.autoRhythm}getBPMMultiplier(){return this._assist.slowMode?this._slowModeMult:1}get visualMetronome(){return this._assist.visualMetronome}serialize(){return{preset:this._preset,assist:{...this._assist}}}deserialize(e){e&&(e.preset&&vo[e.preset]&&(this._preset=e.preset),e.assist&&this.setAssist(e.assist))}}class wo{constructor(e){this._getEngine=e,this._audioBlob=null,this._audioDuration=0,this._difficultyManager=null}getAudioBlob(){return this._audioBlob}getAudioDuration(){return this._audioDuration}setAudioDuration(e){this._audioDuration=e||0}async loadAudio(e){if(e instanceof Blob){this._audioBlob=e;const t=URL.createObjectURL(e);await this._loadAudioFromUrl(t),URL.revokeObjectURL(t)}else await this._loadAudioFromUrl(e)}async _loadAudioFromUrl(e){const t=new Audio(e);await new Promise((e,i)=>{t.addEventListener("loadedmetadata",()=>{this._audioDuration=1e3*t.duration,e()},{once:!0}),t.addEventListener("error",i,{once:!0}),t.load()});const i=this._getEngine();i&&i.soundSystem&&await i.soundSystem.loadAudioFromURL(e)}getAudioAnalysis(){const e=this._getEngine();return e&&e.audioAnalyzer?{bpm:e.rhythmIntegration?.getBPM()||0,beats:e.rhythmIntegration?.getBeatMarkers()||[],energy:e.audioAnalyzer?.getEnergyLevel()||0,frequencies:e.audioAnalyzer?.getFrequencyData()||[]}:null}connectAudio(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.connectAudio&&t.connectAudio(e)}disconnectAudio(e){const t=this._getEngine();t&&t.disconnectAudio&&t.disconnectAudio(e)}getSpectrumData(){const e=this._getEngine();return e&&e.audioAnalyzer?e.audioAnalyzer.dataArray?Array.from(e.audioAnalyzer.dataArray).map(e=>e/255):e.shapeMorpher&&e.shapeMorpher.frequencyData?Array.from(e.shapeMorpher.frequencyData):[]:[]}startRhythmSync(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.rhythmIntegration&&(e&&t.rhythmIntegration.setBPM(e),t.rhythmIntegration.start())}stopRhythmSync(){const e=this._getEngine();e&&e.rhythmIntegration&&e.rhythmIntegration.stop()}getInputEvaluator(e){const t=this._getEngine();if(!t||!t.rhythmIntegration)return null;const i=t.rhythmIntegration.getInputEvaluator(e);return i&&!i._emotionTarget&&t.stateCoordinator&&i.setEmotionTarget((e,i)=>{t.stateCoordinator.nudgeEmotion(e,i)}),i&&!i._difficultyManager&&i.setDifficultyManager(this.getDifficultyManager()),i}getDifficultyManager(){return this._difficultyManager||(this._difficultyManager=new Mo),this._difficultyManager}getLayers(){const e=this._getEngine();return e&&e.soundSystem?e.soundSystem.getAudioLayerManager():null}}class So{constructor(e,t){this._getEngine=e,this._recording=t,this._chainDefinitions={rise:"breathe > sway+lean+tilt",flow:"sway > lean+tilt > spin > bounce",burst:"jump > nod > shake > flash",drift:"sway+breathe+float+drift",chaos:"shake+shake > spin+flash > bounce+pulse > twist+sparkle",morph:"expand > contract > morph+glow > expand+flash",rhythm:"pulse > pulse+sparkle > pulse+flicker",spiral:"spin > orbital > twist > orbital+sparkle",routine:"nod > bounce > spin+sparkle > sway+pulse > nod+flash",radiance:"sparkle > pulse+flicker > shimmer",twinkle:"sparkle > flash > pulse+sparkle > shimmer+flicker",stream:"wave > nod+pulse > sparkle > flash"}}triggerGesture(e,t){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");if(this._recording.isRecording()){const i=t||Date.now()-this._recording.startTime();this._recording.timeline().push({type:"gesture",name:e,time:i})}i.express(e)}express(e,t){return this.triggerGesture(e,t)}chain(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");const i=this._chainDefinitions[e.toLowerCase()];i?i.includes(">")?i.split(">").map(e=>e.trim()).filter(e=>e.length>0).forEach((e,i)=>{setTimeout(()=>{e.split("+").map(e=>e.trim()).filter(e=>e.length>0).forEach(e=>{t.express(e)})},500*i)}):i.split("+").map(e=>e.trim()).filter(e=>e.length>0).forEach(e=>{t.express(e)}):console.warn(`Chain combo '${e}' not found`)}updateUndertone(e){const t=this._getEngine();if(!t)throw new Error("Engine not initialized. Call init() first.");t.updateUndertone&&"function"==typeof t.updateUndertone?t.updateUndertone(e):t.addUndertone&&"function"==typeof t.addUndertone&&t.addUndertone(e)}getAvailableChains(){return Object.keys(this._chainDefinitions)}getChainDefinition(e){return this._chainDefinitions[e.toLowerCase()]||null}}class xo{constructor(e,t,i){this._getEngine=e,this._audioManager=t,this._state=i,this._activeTimeouts=new Set}startRecording(){this._state.timeline.length=0,this._state.isRecording=!0,this._state.recordingStartTime=Date.now()}stopRecording(){return this._state.isRecording=!1,[...this._state.timeline]}playTimeline(e){if(!e||!e.length)return void(this._state.isPlaying=!1);this._state.isPlaying=!0,this._state.playbackStartTime=Date.now(),e.forEach(e=>{const t=setTimeout(()=>{if(this._activeTimeouts.delete(t),!this._state.isPlaying)return;const i=this._getEngine();if(i)switch(e.type){case"gesture":i.express(e.name);break;case"emotion":i.setEmotion(e.name);break;case"shape":i.morphTo(e.name)}},e.time);this._activeTimeouts.add(t)});const t=Math.max(...e.map(e=>e.time)),i=setTimeout(()=>{this._activeTimeouts.delete(i),this._state.isPlaying=!1},t);this._activeTimeouts.add(i)}stopPlayback(){this._state.isPlaying=!1,this._activeTimeouts.forEach(e=>clearTimeout(e)),this._activeTimeouts.clear()}getTimeline(){return[...this._state.timeline]}loadTimeline(e){this._state.timeline.length=0,this._state.timeline.push(...e)}exportTimeline(){return JSON.stringify({version:"1.0",duration:this._audioManager.getAudioDuration()||0,events:this._state.timeline})}importTimeline(e){let t;try{t=JSON.parse(e)}catch{return void console.warn("TimelineRecorder: Failed to parse timeline JSON")}this._state.timeline.length=0,this._state.timeline.push(...t.events||[]),this._audioManager.setAudioDuration(t.duration||0)}getCurrentTime(){return this._state.isPlaying?Date.now()-this._state.playbackStartTime:0}seek(e){const t=this._state.timeline.filter(t=>t.time<=e),i={};t.forEach(e=>{i[e.type]=e});const s=this._getEngine();s&&(i.emotion&&s.setEmotion(i.emotion.name),i.shape&&s.morphTo(i.shape.name))}getAnimationData(){const e=this._getEngine();return{timeline:[...this._state.timeline],duration:this._audioManager.getAudioDuration()||0,currentTime:this.getCurrentTime(),emotion:e?.state?.emotion||"neutral",shape:e?.state?.currentShape||"circle"}}destroy(){this.stopPlayback(),this._getEngine=null,this._audioManager=null,this._state=null}}class Co{constructor(e,t,i){this._getEngine=e,this._getCanvas=t,this._mascot=i,this._attachedElement=null,this._attachOptions=null,this._hasAttachedBefore=!1,this._elementTrackingHandlers=null}attachToElement(e,t={}){if(!this._getEngine())throw new Error("Engine not initialized. Call init() first.");const i="string"==typeof e?document.querySelector(e):e;if(!i)return console.warn(`[EmotiveMascot] Element not found: ${e}`),this._mascot;this._attachedElement=i,this._attachOptions={offsetX:t.offsetX||0,offsetY:t.offsetY||0,animate:!1!==t.animate,duration:t.duration||1e3,scale:t.scale||1,containParticles:!1!==t.containParticles};const s=i.getBoundingClientRect();return this._attachOptions.containParticles?this._mascot.setContainment({width:s.width,height:s.height},this._attachOptions.scale):1!==this._attachOptions.scale&&this._mascot.setContainment(null,this._attachOptions.scale),this._getCanvas()&&this._updatePosition(),this._setupEventListeners(),this._mascot}_updatePosition(){if(!this._attachedElement)return;if(!this._getCanvas())return;const e=this._attachedElement.getBoundingClientRect(),t=window.innerWidth/2,i=window.innerHeight/2,s=e.left+e.width/2,n=e.top+e.height/2,a=s-t+this._attachOptions.offsetX,r=n-i+this._attachOptions.offsetY,o=!this._hasAttachedBefore;this._hasAttachedBefore=!0,o&&this._attachOptions.animate?this._mascot.animateToPosition(a,r,0,this._attachOptions.duration):this._mascot.setPosition(a,r,0)}_setupEventListeners(){this._elementTrackingHandlers||(this._elementTrackingHandlers={scroll:()=>this._updatePosition(),resize:()=>this._updatePosition()},window.addEventListener("scroll",this._elementTrackingHandlers.scroll,{passive:!0}),window.addEventListener("resize",this._elementTrackingHandlers.resize))}isAttachedToElement(){return!!this._attachedElement}detachFromElement(){return this._attachedElement=null,this._elementTrackingHandlers&&(window.removeEventListener("scroll",this._elementTrackingHandlers.scroll),window.removeEventListener("resize",this._elementTrackingHandlers.resize),this._elementTrackingHandlers=null),this._mascot.setContainment(null,1),this._mascot.setEmotion("neutral"),this._mascot.morphTo("sphere",{duration:800}),this._mascot}cleanup(){this._elementTrackingHandlers&&(window.removeEventListener("scroll",this._elementTrackingHandlers.scroll),window.removeEventListener("resize",this._elementTrackingHandlers.resize),this._elementTrackingHandlers=null),this._attachedElement=null}}class ko{constructor(e,t){this._getEngine=e,this._getCanvas=t}setContainment(e,t=1){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");i.particleSystem&&i.particleSystem.setContainmentBounds(e),i.positionController&&(i.positionController.coreScaleOverride=t,i.positionController.particleScaleOverride=t),i.particleSystem&&i.particleSystem.particles&&i.particleSystem.particles.forEach(e=>{e.scaleFactor=t,e.size=e.baseSize*t})}clearParticles(){const e=this._getEngine();if(!e)throw new Error("Engine not initialized. Call init() first.");e.particleSystem&&e.particleSystem.clear()}setParticleSystemCanvasDimensions(e,t){const i=this._getEngine();if(!i)throw new Error("Engine not initialized. Call init() first.");i.setParticleSystemCanvasDimensions&&i.setParticleSystemCanvasDimensions(e,t)}getFrameData(e="png"){const t=this._getCanvas();return t?t.toDataURL(`image/${e}`):null}getFrameBlob(e="png"){const t=this._getCanvas();return t?new Promise(i=>{t.toBlob(e=>i(e),`image/${e}`)}):Promise.resolve(null)}}class Po{constructor(){this._stances=new Map,this._active=null}registerStance(e,t){this._stances.set(e,{...t})}hasStance(e){return this._stances.has(e)}getStance(e){const t=this._stances.get(e);return t?{...t}:null}activate(e){const t=this._stances.get(e);return t?(this._active={name:e,config:{...t}},this._active.config):null}dismiss(){return!!this._active&&(this._active=null,!0)}getActiveStance(){return this._active?{name:this._active.name,config:{...this._active.config}}:null}getAvailableStances(){return[...this._stances.keys()]}}const To=["bouncing up and down","hopping around","rocking back and forth","side to side","light on feet","spring in step","leaning forward","leaning in","leaning closer","leaning toward","reaching out","reaching toward","pointing at","pointing to","waving hello","waving goodbye","nodding head","shaking head","head shake","head nod","head bob","head tilt","deep breath","taking a breath","breathing deeply","settling down","calming down","winding down","getting bigger","getting smaller","puffing up","spinning around","twirling around","at peace","in love","on cloud nine","over the moon","on top of the world","in awe","grossed out","freaked out","low key","low-key","high key","on edge","keyed up","wound up","low energy","no energy","running low","just a bit","just a little","a little bit","kind of","sort of","a bit","a little","a lot","over the top","off the charts","through the roof","split second","one time","few times","many times","again and again","over and over","on repeat","blood moon","full moon","new moon","half moon","solar eclipse","lunar eclipse","total eclipse","ring of fire","diamond ring","killing it","crushing it","nailed it","sussy baka","side eye"].map(e=>{const t=e.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),i=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{normalized:t,regex:new RegExp(i,"g")}}),Eo=/[,;|/]+/,Ao=new Set(["a","an","the","is","are","am","be","being","been","i","me","my","it","its","to","of","for","with","as","this","that","these","those","just","only","also","too","please","pls","plz"]),Do=new Set(["but","and","or","yet","while","although","not","no","never","very","really","so","quite","rather","slightly","barely","extremely","completely","feeling","feel","feels","become","becoming","morph","morphing"]);function _o(e){return["but","and","or","yet","while","although","with"].includes(e)}function Io(e){return["not","no","never","don't","dont","doesn't","doesnt","isn't","isnt"].includes(e)}const Ro={nervous:{candidates:[{category:"emotion",target:"fear",priority:1},{category:"undertone",target:"nervous",priority:2}],rule:"standalone_is_emotion",examples:[{input:"nervous",resolved:{emotion:"fear"}},{input:"happy but nervous",resolved:{emotion:"joy",undertone:"nervous"}}]},anxious:{candidates:[{category:"emotion",target:"fear",priority:1},{category:"undertone",target:"nervous",priority:2}],rule:"standalone_is_emotion"},confident:{candidates:[{category:"emotion",target:"trust",priority:2},{category:"undertone",target:"confident",priority:1}],rule:"prefer_undertone",examples:[{input:"confident",resolved:{undertone:"confident"}},{input:"feeling confident",resolved:{emotion:"trust"}}]},tired:{candidates:[{category:"emotion",target:"sadness",priority:2},{category:"undertone",target:"tired",priority:1}],rule:"prefer_undertone",examples:[{input:"tired",resolved:{undertone:"tired"}},{input:"feeling tired",resolved:{emotion:"sadness",undertone:"tired"}}]},intense:{candidates:[{category:"undertone",target:"intense",priority:1},{category:"modifier",target:"intensity.very",priority:2}],rule:"prefer_undertone"},curious:{candidates:[{category:"emotion",target:"focused",priority:1},{category:"gesture",target:"lean",priority:2}],rule:"standalone_is_emotion",examples:[{input:"curious",resolved:{emotion:"focused"}},{input:"curious, leaning in",resolved:{emotion:"focused",gesture:"lean"}}]},interested:{candidates:[{category:"emotion",target:"focused",priority:1},{category:"gesture",target:"lean",priority:2}],rule:"standalone_is_emotion"},excited:{candidates:[{category:"emotion",target:"joy",priority:1},{category:"gesture",target:"bounce",priority:3}],rule:"standalone_is_emotion"},shaking:{candidates:[{category:"gesture",target:"shake",priority:1},{category:"emotion",target:"fear",priority:2}],rule:"standalone_is_gesture"},nodding:{candidates:[{category:"gesture",target:"nod",priority:1}],rule:"always_gesture"},glowing:{candidates:[{category:"gesture",target:"glow",priority:1},{category:"shape",target:"sun",priority:3}],rule:"standalone_is_gesture"},spinning:{candidates:[{category:"gesture",target:"spin",priority:1}],rule:"always_gesture"},love:{candidates:[{category:"emotion",target:"love",priority:1},{category:"shape",target:"heart",priority:2}],rule:"standalone_is_emotion",examples:[{input:"love",resolved:{emotion:"love"}},{input:"love heart",resolved:{emotion:"love",shape:"heart"}},{input:"become love",resolved:{shape:"heart"}}]},suspicious:{candidates:[{category:"emotion",target:"suspicion",priority:1},{category:"shape",target:"suspicion",priority:2}],rule:"standalone_is_emotion"},bright:{candidates:[{category:"emotion",target:"joy",priority:2},{category:"shape",target:"sun",priority:3},{category:"modifier",target:"intensity.very",priority:4}],rule:"context_dependent"},yes:{candidates:[{category:"gesture",target:"nod",priority:1}],rule:"always_gesture"},no:{candidates:[{category:"gesture",target:"shake",priority:1}],rule:"always_gesture"},agree:{candidates:[{category:"gesture",target:"nod",priority:1},{category:"emotion",target:"trust",priority:2}],rule:"standalone_is_gesture"},disagree:{candidates:[{category:"gesture",target:"shake",priority:1}],rule:"always_gesture"}},Bo={emotionContext:["feeling","feel","feels","felt","emotion","emotional","emotionally","mood","moody","state","am","is","are","being","becoming","become","grew","growing"],gestureContext:["do","doing","does","did","perform","performing","action","move","moving","movement","start","starting","begin","beginning","physically","motion"],shapeContext:["morph","morphing","morphed","transform","transforming","transformed","become","becoming","turn into","shape","form","look like","change to","change into"],undertoneContext:["but","yet","while","although","with","and also","mixed with","underneath","underlying","beneath","a bit","slightly","somewhat"],modifierContext:["very","really","so","extremely","slightly","barely","completely","quickly","slowly","briefly"]};function zo(e,t,i){const s=Bo[`${i}Context`];if(!s)return!1;const n=Math.max(0,t-3),a=Math.min(e.length,t+4);for(let i=n;i<a;i++)if(i!==t&&s.includes(e[i]))return!0;return!1}function Fo(e,t){switch(t){case"emotion":return null!==e.emotion;case"gesture":return e.gestures&&e.gestures.length>0;case"shape":return null!==e.shape;case"undertone":return null!==e.undertone;default:return!1}}function Oo(e,t,i,s){const n=Ro[e];if(!n)return null;const{candidates:a,rule:r}=n;if(1===a.length)return a[0];switch(r){case"standalone_is_emotion":if(Fo(s,"emotion")){const e=a.find(e=>"emotion"!==e.category);if(e)return e}return zo(t,i,"emotion"),a.find(e=>"emotion"===e.category)||a[0];case"standalone_is_gesture":if(Fo(s,"gesture")){const e=a.find(e=>"gesture"!==e.category);if(e)return e}return zo(t,i,"gesture"),a.find(e=>"gesture"===e.category)||a[0];case"prefer_undertone":return zo(t,i,"emotion")?a.find(e=>"emotion"===e.category)||a[0]:a.find(e=>"undertone"===e.category)||a[0];case"always_gesture":return a.find(e=>"gesture"===e.category)||a[0];case"always_emotion":return a.find(e=>"emotion"===e.category)||a[0];case"context_dependent":for(const e of["emotion","gesture","shape","undertone"])if(zo(t,i,e)){const t=a.find(t=>t.category===e);if(t)return t}return a.sort((e,t)=>e.priority-t.priority)[0];default:return a.sort((e,t)=>e.priority-t.priority)[0]}}function Lo(e){return e in Ro}const qo={neutral:["neutral","default","normal","baseline","standard","nothing special","nothing particular","no strong feeling","not much","meh","whatever","indifferent","balanced","even","steady","stable","centered","level","middle ground","in between","ready","waiting","standing by","at attention","present","here","available","attentive","reset","clear","blank","empty","clean slate"],joy:["happy","joy","joyful","joyous","pleased","glad","content","satisfied","gratified","comfortable","good","cheerful","cheery","merry","jovial","jolly","upbeat","sunny","bright","lighthearted","buoyant","delighted","thrilled","overjoyed","elated","jubilant","exultant","gleeful","glowing","beaming","radiant","pumped","stoked","psyched","amped","hyped","vibing","living","slaying","winning","lit","fire","sick","dope","chuffed","pleased as punch","over the moon","made up","tickled","tickled pink","felicitous","beatific","blissful","smiling","grinning","laughing","giggling"],calm:["calm","peaceful","serene","tranquil","relaxed","at ease","comfortable","loose","unwound","decompressed","chilled","still","quiet","hushed","silent","soft","gentle","mild","placid","smooth","composed","collected","centered","grounded","untroubled","unworried","unbothered","unfazed","meditative","mindful","contemplative","reflective","introspective","soothed","eased","mellowed","softened","chill","coasting","floating","drifting","laid back","easy going","low key","sorted","easy peasy"],excited:["excited","exciting","excitable","enthusiastic","eager","keen","avid","passionate","fervent","ardent","zealous","energetic","energized","animated","lively","spirited","vivacious","vibrant","dynamic","bouncy","peppy","perky","sprightly","anticipating","expectant","looking forward","itching","raring","chomping at the bit","fired up","charged","electric","electrified","buzzing","tingling","crackling","sparking","jazzed","juiced","geeked","hype","turnt","going off","well excited","buzzing","restless","fidgety","antsy","jumpy","twitchy","keyed up","wound up"],sadness:["sad","sadness","saddened","unhappy","down","low","blue","glum","bummed","disappointed","let down","discouraged","disheartened","dispirited","deflated","melancholy","melancholic","somber","gloomy","mournful","sorrowful","doleful","woeful","heavy-hearted","downcast","crestfallen","heartbroken","devastated","crushed","shattered","despairing","despondent","desolate","inconsolable","grief","grieving","mourning","bereft","empty","hollow","numb","void","wistful","longing","yearning","pining","nostalgic","bummed out","down in the dumps","in a funk","in the dumps","feeling low","gutted","choked","crying","tearful","weeping","sobbing","sighing","drooping","wilting","slumping"],anger:["angry","anger","angered","mad","annoyed","irritated","bothered","irked","peeved","miffed","vexed","displeased","put out","ticked off","ticked","frustrated","aggravated","exasperated","fed up","sick of","had enough","cross","upset","worked up","furious","enraged","livid","irate","incensed","infuriated","outraged","seething","fuming","boiling","burning","smoldering","raging","ballistic","apoplectic","berserk","seeing red","losing it","pissed","pissed off","salty","pressed","triggered","tilted","heated","steaming","narked","cheesed off","brassed off","shirty","stroppy","mardy","ropeable","filthy","spewing","clenching","tensing","grinding"],fear:["afraid","scared","fear","fearful","uneasy","unsettled","apprehensive","wary","concerned","worried","jittery","shaky","trembling","quivering","tense","tight","clenched","knotted","frightened","alarmed","startled","spooked","freaked","freaked out","creeped out","on edge","rattled","unnerved","terrified","petrified","horrified","panicked","panic","panicking","terror","dread","paranoid","distrustful","looking over shoulder","sketched","sketched out","wigged out","shook","bricking it","having kittens","in a flap","frozen","paralyzed","deer in headlights","heart racing","heart pounding","sweating"],surprise:["surprised","surprise","surprising","oh","huh","hmm","interesting","unexpected","caught off guard","astonished","amazed","astounded","startled","taken aback","struck","shocked","stunned","staggered","floored","dumbfounded","flabbergasted","gobsmacked","blown away","mind blown","speechless","wow","whoa","omg","no way","incredible","unbelievable","amazing","alarmed","dismayed","appalled","bewildered","baffled","perplexed","puzzled","confused","disoriented","thrown","shooketh","gagged","dead","wait what","blimey","crikey","bloody hell","jaw dropped","eyes wide","double take","gasp","gasping"],disgust:["disgusted","disgust","disgusting","distaste","dislike","aversion","put off","turned off","off-putting","repulsed","revolted","repelled","grossed out","creeped out","icked out","sickened","nauseated","nauseous","appalled","horrified","scandalized","offended","outraged","indignant","contempt","contemptuous","disdain","scorn","gagging","retching","cringing","wincing","recoiling","shrinking back","gross","ew","eww","yuck","yucky","ick","nasty","foul","vile","rank","minging","manky","grotty"],love:["love","loving","loved","affection","affectionate","fond","fondness","tender","tenderness","gentle","caring","care","nurturing","supportive","protective","devoted","dedicated","warm","warmth","warm-hearted","kind","kind-hearted","compassionate","sympathetic","adoring","adore","cherish","cherishing","treasure","treasuring","doting","romantic","amorous","passionate","smitten","infatuated","enamored","besotted","head over heels","falling for","connected","bonded","attached","close","intimate","deep","profound","heart eyes","crushing","swooning","melting","hugging","embracing","holding","cuddling","snuggling","nuzzling"],euphoria:["euphoric","euphoria","bliss","blissful","transcendent","otherworldly","sublime","heavenly","divine","ethereal","celestial","ecstatic","ecstasy","rapture","rapturous","exultant","exalted","elevated","peak","pinnacle","height","climax","breakthrough","revelation","epiphany","overwhelming joy","pure joy","absolute joy","complete happiness","total bliss","floating","soaring","flying","weightless","radiating","shining","on cloud nine","in heaven","on top of the world","walking on air","living my best life","ascended"],focused:["focused","focus","focusing","concentrating","concentration","concentrated","attentive","attention","attending","thinking","thought","thoughtful","pondering","considering","contemplating","reflecting","musing","mulling","engaged","absorbed","immersed","engrossed","rapt","riveted","captivated","enthralled","intent","determined","resolute","single-minded","laser focused","zeroed in","working","processing","analyzing","examining","studying","learning","figuring out","locked in","dialed in","in the zone","flow state","deep work","grinding","staring","gazing","peering","squinting","furrowed brow"],suspicion:["suspicious","suspicion","suspect","doubtful","doubt","doubting","skeptical","skepticism","questioning","uncertain","unsure","unconvinced","wary","cautious","guarded","careful","leery","circumspect","vigilant","distrustful","mistrust","mistrustful","disbelieving","incredulous","unbelieving","scrutinizing","examining","assessing","evaluating","judging","sizing up","sus","sussy","suss","side eye","giving side eye","side-eyeing","eyeing","not buying it","narrowed eyes","squinting","raised eyebrow","cocked head","tilted head","looking askance"],resting:["resting","rest","restful","tired","weary","fatigued","exhausted","drained","spent","depleted","worn out","sleepy","drowsy","dozy","groggy","yawning","nodding off","drifting off","sluggish","lethargic","listless","languid","lazy","idle","inactive","recovering","recuperating","recharging","winding down","powering down","shutting down","sleeping","asleep","slumbering","dozing","napping","snoozing","zonked","wiped","beat","dead tired","running on empty","out of gas","crashed","knackered","shattered","cream crackered"],glitch:["glitch","glitchy","glitching","malfunction","malfunctioning","broken","bugged","buggy","error","erroring","corrupted","corruption","scrambled","garbled","distorted","warped","static","noise","interference","pixelated","artifacting","tearing","haywire","fritzing","shorting out","going crazy","spazzing","unstable","erratic","unpredictable","flickering","stuttering","lagging","does not compute","syntax error","crash"]},Go={nervous:["nervous","nervously","anxious","anxiously","worried","worriedly","uneasy","uneasily","apprehensive","jittery","shaky","trembling","quivering","fidgety","restless","twitchy","tense","tensely","on edge","edgy","keyed up","wound up","uptight","self-conscious","awkward","awkwardly","hesitant","hesitantly","uncertain","uncertainly","sketchy","stressed","stressing","low-key panicking","kinda freaking out"],confident:["confident","confidently","confidence","assured","assuredly","certain","certainly","sure","surely","positive","positively","bold","boldly","brave","bravely","daring","daringly","fearless","fearlessly","strong","strongly","powerful","powerfully","firm","firmly","solid","solidly","authoritative","commanding","assertive","decisive","decisively","resolute","resolutely","poised","self-assured","unflappable","unfazed","owning it","killing it","crushing it","boss","like a boss"],tired:["tired","tiredly","tiredness","exhausted","weary","wearily","fatigued","drained","spent","depleted","sluggish","sluggishly","slow","slowly","lethargic","listless","languid","low energy","no energy","out of energy","running low","running on fumes","droopy","drooping","sagging","slumping","heavy","weighted","dragging","wiped","beat","dead","zonked","burned out","fried","cooked","toast"],intense:["intense","intensely","intensity","heightened","elevated","amplified","magnified","increased","enhanced","forceful","forcefully","powerful","powerfully","fierce","fiercely","strong","strongly","passionate","passionately","fervent","fervently","ardent","ardently","vehement","vehemently","sharp","sharply","acute","acutely","keen","keenly","piercing","piercingly","extreme","extremely","deeply","profoundly","tremendously","immensely","incredibly","super","mega","ultra","hella","mad","crazy"],subdued:["subdued","subduedly","soft","softly","gentle","gently","mild","mildly","light","lightly","restrained","held back","contained","tempered","moderated","toned down","quiet","quietly","hushed","muted","understated","subtle","subtly","modest","modestly","humble","humbly","reserved","demure","unassuming","faint","faintly","dim","dimly","pale","faded","washed out","low key","lowkey","easy","easy going"],clear:["clear","clearly","pure","purely","clean","cleanly","simple","simply","plain","plainly","direct","directly","straightforward","honest","honestly","frank","frankly","transparent","transparently","open","openly","obvious","obviously","evident","evidently","unmodified","unaltered","unchanged","normal","normally","regular","regularly","standard","basic","baseline"]},Ho={breathe:["breathe","breathing","breath","inhale","inhaling","exhale","exhaling","sigh","sighing","respire","respiring","deep breath","deep breathing","slow breath","slow breathing","long breath","full breath","breathing deeply","breathing slowly","taking a breath","take a breath","catching breath","breath work","breathwork","inhale exhale","in and out","meditative breathing","calming breath","cleansing breath","relaxing breath","centering breath","mindful breathing"],expand:["expand","expanding","grow","growing","enlarge","enlarging","swell","swelling","bloat","bloating","getting bigger","growing larger","puffing up","expanding outward"],contract:["contract","contracting","shrink","shrinking","compress","compressing","reduce","reducing","getting smaller","shrinking down","pulling in","contracting inward"],pulse:["pulse","pulsing","pulsate","pulsating","throb","throbbing","beat","beating","pulsing gently","steady pulse","heartbeat","heart beat"],sway:["sway","swaying","swing","swinging","oscillate","oscillating","swaying gently","gentle sway","side to side","swaying motion"],float:["float","floating","hover","hovering","glide","gliding","levitate","levitating","weightless","weightlessness","buoyant","airy","floating gently","hovering in place","light as air","floating freely"],floatUp:["float up","floating up","floating upward","rise","rising","ascend","ascending","lift","lifting","lifted up","soar","soaring","going up"],floatDown:["float down","floating down","floating downward","descend","descending","sink","sinking","lower","lowering","going down"],floatLeft:["float left","floating left","drift left","drifting left"],floatRight:["float right","floating right","drift right","drifting right"],bob:["bob","bobbing","bobbing up and down","gentle bob"],lean:["lean","leaning","incline","inclining","leaning in","lean in","leaning forward","lean forward","leaning toward","lean toward","leaning closer","lean closer","moving closer","coming closer","drawing near","approaching","interested","intrigued","engaged","attentive","listening closely","paying attention"],leanLeft:["lean left","leaning left","tilt left","tilting left"],leanRight:["lean right","leaning right","tilt right","tilting right"],jitter:["jitter","jittering","jittery","stutter","stuttering","jittering around","slight jitter","nervous jitter"],twitch:["twitch","twitching","twitchy","spasm","spasming","flinch","flinching","quick twitch","nervous twitch","sudden movement"],vibrate:["vibrate","vibrating","vibration","buzz","buzzing","hum","humming","quiver","quivering","vibrating slightly","gentle buzz","low hum","subtle vibration"],shake:["shake","shaking","shaky","shudder","shuddering","tremble","trembling","quake","quaking","no","nope","nah","disagree","disagreeing","refuse","refusing","deny","denying","shaking head","shake head","head shake","saying no","shaking no"],wiggle:["wiggle","wiggling","wiggly","jiggle","jiggling","jiggly","squirm","squirming","wriggle","wriggling","wiggling around","little wiggle","happy wiggle","excited wiggle"],stepLeft:["step left","stepping left","sidestep left","move left","moving left","shift left"],stepRight:["step right","stepping right","sidestep right","move right","moving right","shift right"],stepUp:["step up","stepping up","step forward"],stepDown:["step down","stepping down","step back"],slideLeft:["slide left","sliding left","glide left"],slideRight:["slide right","sliding right","glide right"],runningman:["running man","runningman","running man dance","run in place","running in place"],charleston:["charleston","charleston dance","swing dance","kick step","kick and step"],hula:["hula","hula-ing","hip sway","swaying hips","circular sway","round motion","hula motion","hula dance"],twist:["twist","twisting","twisty","contort","contorting","do the twist","twisting dance","twisting around","getting twisted"],pop:["pop","popping","pop and lock","popping motion","hit","hitting"],flare:["flare","flaring","dramatic flare","flourish"],swell:["swell","swelling","surge","surging","crescendo"],swagger:["swagger","swaggering","strut","strutting","confident walk","cocky"],dip:["dip","dipping","drop","dropping down","low dip","dance dip"],bounce:["bounce","bouncing","bouncy","hop","hopping","hoppy","spring","springing","springy","boing","boinging","bouncing up and down","hopping around","spring in step","light on feet"],orbit:["orbit","orbiting","circle","circling","revolve","revolving","circling around","going around","rotating slowly","orbital motion"],orbitLeft:["orbit left","orbiting left","circle left","counter-clockwise","counterclockwise"],orbitRight:["orbit right","orbiting right","circle right","clockwise"],orbitUp:["orbit up","orbiting up","rising orbit","spiral up","spiraling up"],orbitDown:["orbit down","orbiting down","descending orbit","spiral down","spiraling down"],sparkle:["sparkle","sparkling","sparkly","twinkle","twinkling","twinkly","glitter","glittering","glittery","shine","shining","shiny","celebrate","celebrating","celebration","celebratory","festive","party","partying","victory","triumphant","triumph","winning","success","successful","achievement","accomplished","nailed it","slay","slaying","killing it","yasss","yay","woo","woohoo"],shimmer:["shimmer","shimmering","shimmery","glisten","glistening","gleam","gleaming","lustrous","luminous","soft shimmer","gentle gleam","shimmering light","pearlescent"],groove:["groove","grooving","groovy","dance","dancing","boogie","boogying","funk","funky","rhythmic","moving to music","feeling the music","in the groove","getting down","busting a move","doing a little dance"],jump:["jump","jumping","jumpy","leap","leaping","bound","bounding","jumping up","leap up","spring up","jumping for joy"],jumpDown:["jump down","jumping down","drop down"],jumpLeft:["jump left","jumping left","leap left"],jumpRight:["jump right","jumping right","leap right"],lunge:["lunge","lunging","thrust","thrusting","charge forward","aggressive step"],lungeForward:["lunge forward","lunging forward","thrust forward"],lungeBack:["lunge back","lunging back","retreat lunge"],rushForward:["rush forward","rushing forward","dash forward","sprint","sprinting","charge","charging"],rushBack:["rush back","rushing back","dash back","retreat quickly"],spin:["spin","spinning","twirl","twirling","whirl","whirling","rotate","rotating","turn","turning","spinning around","quick spin","full rotation","twirling around"],spinLeft:["spin left","spinning left","turn left","rotate left","counter-clockwise spin"],spinRight:["spin right","spinning right","turn right","rotate right","clockwise spin"],flip:["flip","flipping","somersault","somersaulting","front flip","frontflip"],backflip:["backflip","back flip","backflipping","back somersault","flip backward"],point:["point","pointing","indicate","indicating","gesture","gesturing","direct","directing","pointing at","pointing to","pointing toward","gesturing toward","showing","directing attention"],pointUp:["point up","pointing up","pointing upward","look up","look to the sky"],pointDown:["point down","pointing down","pointing downward","look down","look at this"],pointLeft:["point left","pointing left","gesture left"],pointRight:["point right","pointing right","gesture right"],kickLeft:["kick left","kicking left","left kick"],kickRight:["kick right","kicking right","right kick"],bow:["bow","bowing","curtsy","curtseying","reverence","showing respect","take a bow","bow down"],nod:["nod","nodding","yes","yeah","yep","yup","agree","agreeing","acknowledge","acknowledging","confirm","confirming","accept","accepting","approve","approving","understand","understanding","got it","gotcha","i see","makes sense","understood","nodding head","nod head","head nod","nodding along","nodding yes"],reach:["reach","reaching","extend","extending","reaching out","reach out","reaching toward","reach toward","extending toward","offer","offering","present","presenting","give","giving","help","helping"],headBob:["headbob","head bob","headbobbing","head bobbing","nodding to beat","nodding to music","bobbing along","bobbing to rhythm","vibing","jamming","bobbing head","bob head","feeling the beat","moving to music"],wave:["wave","waving","greet","greeting","hello","hi","hey","goodbye","bye","farewell","welcome","welcoming","waving hello","waving goodbye","friendly wave","waving hand"],crouch:["crouch","crouching","squat","squatting","hunker","hunkering","duck","ducking","get low","getting low"],tilt:["tilt","tilting","tilted","angle","angling","angled","cock","cocking","cocked","tilting head","tilt head","cocking head","curious tilt","angling sideways","head tilt"],tiltUp:["tilt up","tilting up","look up","looking up"],tiltDown:["tilt down","tilting down","look down","looking down"],tiltLeft:["tilt left","tilting left","head tilt left"],tiltRight:["tilt right","tilting right","head tilt right"],recoil:["recoil","recoiling","flinch","flinching","wince","wincing","pull back","pulling back","jerk back","snap back"],knockdown:["knockdown","knock down","knocked down","fall","falling","fell","topple","toppling","take a hit","got hit"],knockout:["knockout","knock out","knocked out","KO","ko'd","lights out","out cold"],squash:["squash","squashing","squashed","flatten","flattening","flattened","compress","compressed","smoosh","smooshed"],stretch:["stretch","stretching","stretchy","elongate","elongating","lengthen","lengthening","stretching out","big stretch","reaching up","stretching tall"],inflate:["inflate","inflating","inflated","puff up","puffing up","puffed up","balloon","ballooning"],deflate:["deflate","deflating","deflated","let air out","losing air","shrivel","shriveling"],pancake:["pancake","pancaked","pancaking","flatten completely","totally flat","squished flat","smooshed flat"],rage:["rage","raging","furious","fury","angry","anger","mad","livid","enraged","seeing red","lose temper","losing it"],fury:["fury","furious","quick anger","flash of anger","snap","snapping"],battlecry:["battlecry","battle cry","war cry","roar","yell","yelling","scream","screaming","rallying cry"],charge:["charge","charging","rush","rushing","attack","attacking","assault","advance"],wobble:["wobble","wobbling","wobbly","unstable","unsteady","drunk","dizzy","off balance","losing balance"],teeter:["teeter","teetering","totter","tottering","about to fall","precarious","on edge","unbalanced"],rock:["rock","rocking","soothing rock","gentle rocking","back and forth","rocking motion"],pendulum:["pendulum","pendulum motion","swing back and forth","swinging","hypnotic swing","metronome"],shatter:["shatter","shattering","shattered","break","breaking","broken","smash","smashing","smashed","fragment","fragmenting","explode into pieces","break apart"],shatterExplosive:["explosive shatter","explode","exploding","blow up","blowing up","detonate","detonating","big explosion","kaboom"],shatterCrumble:["crumble","crumbling","fall apart","falling apart","disintegrate","disintegrating","collapse","collapsing"],dissolveUp:["dissolve up","dissolving up","evaporate","evaporating","fade up","rising dust"],dissolveDown:["dissolve down","dissolving down","melt","melting","drip away","dripping"],dissolveAway:["dissolve away","dissolving away","blow away","scatter in wind","dust in wind","fade to dust"],morph:["morph","morphing","transform","transforming","shape shift","shapeshifting","change form","metamorphose"],rain:["rain","raining","shower","showering","drip","dripping","pour","pouring","raining down","particles falling","gentle rain","shower of particles"],drift:["drift","drifting","waft","wafting","float gently","gentle drift"],driftUp:["drift up","drifting up","rising mist","float upward","waft up"],driftDown:["drift down","drifting down","settling dust","float downward","waft down"],vortex:["vortex","whirlpool","tornado","cyclone","maelstrom","spinning vortex","swirling"],cascadeDown:["cascade","cascading","cascade down","waterfall","falling water","pour down","flow down"],confetti:["confetti","throw confetti","celebration particles","party confetti","ticker tape","streamers"],fizz:["fizz","fizzing","fizzy","bubble","bubbling","bubbly","effervescent","carbonated","sparkling bubbles"],burst:["burst","bursting","erupt","erupting","eruption","boom","booming","bursting out","burst of energy","explosive burst","big burst"],burstUp:["burst up","bursting up","fountain","geyser","erupting up"],ripple:["ripple","rippling","wave effect","ripple effect","water ripple","spreading rings"],flash:["flash","flashing","flashy","blink","blinking","strobe","strobing","quick flash","bright flash","flashing light","strobing light"],glow:["glow","glowing","glowy","radiate","radiating","emanate","emanating","luminescent","bright","brighten","brightening","soft glow","warm glow","inner glow","glowing warmly","lighting up","lit up"],bloom:["bloom","blooming","blossom","blossoming","flower","flowering","unfold","unfolding","light bloom","lens bloom"],flicker:["flicker","flickering","flickery","flutter","fluttering","waver","wavering","guttering","flickering light","unsteady light","wavering glow","candle-like"],shiver:["shiver","shivering","chill","chilly","cold","freezing","brr","brrr"],heartbeat:["heartbeat","heart beat","pulse of life","living pulse","thump thump","ba-dum"],snap:["snap","snapping","click","clicking","quick snap","finger snap"],elasticBounce:["elastic bounce","rubbery bounce","springy","bouncy elastic","rubber band","spring back"],hold:["hold","holding","pause","pausing","paused","freeze","freezing","frozen","still","stillness","stop","stopping","stopped","holding still","staying still","frozen in place","completely still","motionless","stationary"],fade:["fade","fading","dim","dimming","disappear","disappearing","vanish","vanishing","fading out","fading away","growing dim","becoming transparent"],settle:["settle","settling","settled","calm","calming","ground","grounding","grounded","center","centering","centered","anchor","anchoring","anchored","root","rooting","rooted","relax","relaxing","unwind","unwinding","decompress","decompressing","settling down","calming down","winding down","cooling down","coming to rest","finding peace"],peek:["peek","peeking","peer","peering","peep","peeping","glance","glancing","peeking out","peek out","looking shyly","shy glance","quick peek","sneaking a look"]},jo={circle:["circle","circular","round","rounded","orb","ball","sphere","spherical","ring","disc","disk","whole","complete","unity","unified","endless","infinite","continuous","full circle","perfect round","come full circle"],sphere:["sphere","spherical","globe","globular","ball","3d circle","three dimensional","round ball","floating sphere"],square:["square","squared","boxy","box","rectangle","rectangular","quadrilateral","cube","cubic","block","blocky","stable","solid","grounded","sturdy","rigid","firm","structured","four sided","four corners","box shape"],triangle:["triangle","triangular","tri","pyramid","pyramidal","delta","wedge","arrow","arrowhead","pointed","sharp","dynamic","directional","ascending","three sided","three pointed","pointing up"],heart:["heart","hearted","hearts","love","loving","lovely","valentine","romantic","affection","affectionate","caring","care","tender","warmth","warm-hearted","heartfelt","compassion","compassionate","devotion","devoted","luv","wuv","<3","โค๏ธ","๐","๐","full of love","with love","heart shape","heart shaped","from the heart"],suspicion:["suspicion","suspicious","suspect","sly","slyly","sneaky","sneakily","mischievous","mischief","smirk","smirking","smirky","grin","grinning","sly grin","side eye","sideeye","side-eye","skeptical","skepticism","doubtful","doubt","doubting","wary","distrustful","distrust","sus","sussy","sussy baka","hmm","hmmm","hmmmm","shady","fishy","sketchy","not buying it","something fishy","seems off","up to something"],star:["star","starred","starry","stars","stellar","astral","twinkle","twinkling","achievement","achieved","excellence","excellent","gold star","five star","superstar","rockstar","rock star","wonder","wonderful","wondrous","magical","magic","miraculous","amazing","spectacular","reach for stars","seeing stars","star shape","shining star"],sun:["sun","sunny","sunshine","sunlight","solar","sol","daylight","daytime","day","radiant","radiance","radiating","bright","brightness","brilliant","glowing","glow","blazing","blaze","warm","warmth","cheerful","cheery","optimistic","optimism","hopeful","hope","positive","positivity","full of light","ray of sunshine","like the sun","sunny disposition"],moon:["moon","moony","moonlight","moonlit","lunar","crescent","nighttime","night","nocturnal","waxing","waning","gibbous","new moon","full moon","half moon","quarter moon","crescent moon","dreamy","dreamlike","dream","mysterious","mystery","mystical","ethereal","otherworldly","serene","serenity","tranquil","contemplative","reflective","moonlit night","by moonlight","moon shape","under the moon"],lunar:["lunar eclipse","blood moon","blood-moon","red moon","copper moon","rust moon","eclipsing","eclipsed","shadow crossing","earth shadow","ominous","foreboding","portentous","dramatic","intense","transforming","transformation","moon in shadow","moon turning red","eclipse phase","lunar event"],solar:["solar eclipse","total eclipse","corona","diamond ring","totality","umbra","penumbra","ring of fire","dark sun","blocked sun","occluded","awe","awesome","awe-inspiring","rare","momentous","historic","breathtaking","magnificent","sun blocked","sun covered","total darkness","corona visible"],eclipse:["eclipse","eclipsing","eclipsed","celestial event","astronomical event","overshadow","overshadowed","blocked","blocking","obscured","hidden","hiding","concealed","passing","crossing","alignment","in eclipse","going dark","being eclipsed","eclipsed by"]},$o={intensity:{barely:["barely","hardly","scarcely","faintly","slightly","marginally","just a bit","just a little","just barely","hint of","touch of","trace of"],slightly:["slightly","somewhat","a little","a bit","mildly","lightly","kind of","kinda","sort of","sorta","a tad","a touch","a smidge"],moderately:["moderately","reasonably","fairly","pretty","rather","quite"],normal:["normal","normally","regular","regularly","standard","typical","typically","average","ordinary"],notably:["notably","noticeably","clearly","definitely","certainly","decidedly","genuinely","truly","really"],very:["very","really","so","such","quite","highly","deeply","seriously","majorly","hella","super","extra","mad"],extremely:["extremely","incredibly","immensely","tremendously","enormously","hugely","intensely","fiercely","wildly","insanely","crazy","ridiculously","mega","ultra","hyper"],absolutely:["absolutely","completely","totally","utterly","entirely","wholly","fully","maximum","max","over the top","off the charts","through the roof","to the max"]},duration:{flash:["flash","instant","instantaneous","split second","split-second","momentary","fleeting","brief flash"],quick:["quick","quickly","fast","rapid","swift","swiftly","brief","briefly","short","shortly","snap"],normal:["normal","regular","standard","typical","usual"],slow:["slow","slowly","gradual","gradually","gentle","gently","easy","easily","leisurely","unhurried"],long:["long","prolonged","extended","sustained","lasting","lingering","drawn out","drawn-out"],persistent:["persistent","constant","continuous","ongoing","steady","maintained","held","holding","stay","staying","keep","keeping","remain","remaining"]},transition:{instant:["instant","instantly","immediate","immediately","sudden","suddenly","abrupt","abruptly","snap","cut","jump"],snappy:["snappy","crisp","sharp","sharply","brisk","briskly","punchy"],smooth:["smooth","smoothly","natural","naturally","fluid","fluidly","flowing"],gentle:["gentle","gently","soft","softly","gradual","gradually","easing","gliding","drifting"],dreamy:["dreamy","dreamlike","floaty","ethereal","languid","lazy","flowing","melting"]},repetition:{once:["once","one time","single","just once","only once","one shot"],few:["few","few times","couple","couple times","twice","two times","thrice","three times"],several:["several","several times","multiple","multiple times","repeatedly","again and again"],many:["many","many times","lots","lots of times","over and over","nonstop"],loop:["loop","looping","looped","continuous","continuously","forever","infinitely","endlessly","always","keep going","on repeat"]}},Wo={barely:{min:.1,max:.2,default:.15},slightly:{min:.2,max:.4,default:.3},moderately:{min:.4,max:.5,default:.45},normal:{min:.5,max:.6,default:.55},notably:{min:.6,max:.7,default:.65},very:{min:.7,max:.85,default:.8},extremely:{min:.85,max:.95,default:.9},absolutely:{min:.95,max:1,default:1}},Uo={flash:{min:100,max:500,default:250},quick:{min:500,max:1e3,default:750},normal:{min:1e3,max:2e3,default:1500},slow:{min:2e3,max:4e3,default:3e3},long:{min:4e3,max:8e3,default:6e3},persistent:{min:8e3,max:1/0,default:1e4}};function Vo(e){const t=new Map;for(const[i,s]of Object.entries(e)){for(const e of s){const s=e.toLowerCase().trim();t.set(s,i)}t.set(i.toLowerCase(),i)}return t}class Yo{constructor(){this.emotionLookup=Vo(qo),this.undertoneLookup=Vo(Go),this.gestureLookup=Vo(Ho),this.shapeLookup=Vo(jo),this.modifierLookup=function(e){const t=new Map;for(const[i,s]of Object.entries(e))for(const[e,n]of Object.entries(s))for(const s of n){const n=s.toLowerCase().trim();t.set(n,{type:i,level:e})}return t}($o)}parse(e){const t={emotion:null,undertone:"clear",gestures:[],shape:null,intensity:Wo.normal.default,duration:Uo.normal.default,transition:"smooth",repetition:"once",unrecognized:[],raw:e};if(!e||"string"!=typeof e)return t;const{tokens:i}=function(e){if(!e||"string"!=typeof e)return{tokens:[],segments:[],phrases:new Map};const t=e.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),{processed:i,phrases:s}=function(e){const t=new Map;let i=e,s=0;for(const{normalized:e,regex:n}of To)if(i.includes(e)){const a=`__PHRASE_${s}__`;n.lastIndex=0,i=i.replace(n,a),t.set(a,e),s++}return{processed:i,phrases:t}}(t),n=i.split(Eo).map(e=>e.trim()).filter(e=>e.length>0),a=[],r=[];for(const e of n){let t=e;for(const[e,i]of s)t=t.replace(e,i);r.push(t.trim());const i=e.split(/\s+/);for(const e of i){if(s.has(e)){a.push(s.get(e));continue}if(!e)continue;if(Ao.has(e)&&!Do.has(e))continue;const t=e.replace(/^[^\w]+|[^\w]+$/g,"");t&&a.push(t)}}return{tokens:a,segments:r,phrases:s}}(e);if(0===i.length)return t;let s=!1;for(let e=0;e<i.length;e++){const n=i[e];if(!_o(n))if(Io(n))s=!0;else if(s)s=!1;else{if(Lo(n)){const s=Oo(n,i,e,t);if(s){this._applyResolution(t,s);continue}}this._tryEmotion(n,t)||this._tryGesture(n,t)||this._tryShape(n,t)||this._tryUndertone(n,t)||this._tryModifier(n,t)||t.unrecognized.push(n)}}return t}_applyResolution(e,t){const{category:i,target:s}=t;switch(i){case"emotion":e.emotion||(e.emotion=s);break;case"undertone":"clear"===e.undertone&&(e.undertone=s);break;case"gesture":e.gestures.includes(s)||e.gestures.push(s);break;case"shape":e.shape||(e.shape=s)}}_tryEmotion(e,t){const i=this.emotionLookup.get(e);return!(!i||t.emotion||(t.emotion=i,0))}_tryGesture(e,t){const i=this.gestureLookup.get(e);return!(!i||t.gestures.includes(i)||(t.gestures.push(i),0))}_tryShape(e,t){const i=this.shapeLookup.get(e);return!(!i||t.shape||(t.shape=i,0))}_tryUndertone(e,t){const i=this.undertoneLookup.get(e);return!(!i||"clear"!==t.undertone||(t.undertone=i,0))}_tryModifier(e,t){const i=this.modifierLookup.get(e);if(i){const{type:e,level:s}=i;switch(e){case"intensity":t.intensity=Wo[s]?.default||t.intensity;break;case"duration":t.duration=Uo[s]?.default||t.duration;break;case"transition":t.transition=s;break;case"repetition":t.repetition=s}return!0}return!1}validate(e){const t=[];return e.emotion||0!==e.gestures.length||e.shape||t.push("No actionable intent found (need emotion, gesture, or shape)"),(e.intensity<0||e.intensity>1)&&t.push(`Intensity ${e.intensity} out of range [0, 1]`),e.duration<=0&&t.push(`Duration ${e.duration} must be positive`),{valid:0===t.length,errors:t}}static getAvailableEmotions(){return Object.keys(qo)}static getAvailableUndertones(){return Object.keys(Go)}static getAvailableGestures(){return Object.keys(Ho)}static getAvailableShapes(){return Object.keys(jo)}}class Xo{#e=null;constructor(e={}){this._config=this._sanitizeConfig(e),this._engine=null,this._timeline=[],this._isRecording=!1,this._recordingStartTime=0,this._playbackStartTime=0,this._isPlaying=!1,this._initialized=!1,this._intentParser=new Yo,this._feelRateLimiter={calls:[],maxCallsPerSecond:10,windowMs:1e3},this._stanceRegistry=new Po,this._audioManager=new wo(()=>this.#t()),this._gestureController=new So(()=>this.#t(),{isRecording:()=>this._isRecording,startTime:()=>this._recordingStartTime,timeline:()=>this._timeline});const t=this;this._timelineRecorder=new xo(()=>this.#t(),this._audioManager,{get timeline(){return t._timeline},set timeline(e){t._timeline=e},get isRecording(){return t._isRecording},set isRecording(e){t._isRecording=e},get recordingStartTime(){return t._recordingStartTime},set recordingStartTime(e){t._recordingStartTime=e},get isPlaying(){return t._isPlaying},set isPlaying(e){t._isPlaying=e},get playbackStartTime(){return t._playbackStartTime},set playbackStartTime(e){t._playbackStartTime=e}}),this._elementAttachmentManager=new Co(()=>this.#t(),()=>this._canvas,this),this._visualEffectsManager=new ko(()=>this.#t(),()=>this._canvas),this.init=this.init.bind(this),this.start=this.start.bind(this),this.stop=this.stop.bind(this),this.pause=this.pause.bind(this),this.resume=this.resume.bind(this),this.setPosition=this.setPosition.bind(this),this.animateToPosition=this.animateToPosition.bind(this),this.clearParticles=this.clearParticles.bind(this)}#t(){return this.#e||this._engine}_sanitizeConfig(e){const t={...e};return delete t.enableDebug,delete t.enableInternalAPIs,delete t.exposeInternals,t.mode="production",void 0===t.enableGazeTracking&&(t.enableGazeTracking=!0),t}init(e){if(this._initialized)return Promise.resolve();this._canvas="string"==typeof e?document.getElementById(e):e;const t={...this._config,canvasId:e},i=new bo(t);return this.#e=i,this._engine=new Proxy(i,{get(e,t){if(["soundSystem","stateMachine","emotionLibrary","audioLevelProcessor","particleSystem","errorBoundary","performanceMonitor","config","debugMode"].includes(t))return new Proxy({},{get(){},set:()=>!1,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor(){}});if("renderer"===t||"shapeMorpher"===t||"audioAnalyzer"===t||"gazeTracker"===t){const i=e[t];if(!i)return;return new Proxy(i,{get(e,i){if({renderer:["setBlinkingEnabled"],shapeMorpher:["resetMusicDetection","frequencyData"],audioAnalyzer:["microphoneStream","currentFrequencies"],gazeTracker:["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"]}[t]?.includes(i))return e[i]},set:()=>!1,has:()=>!1,ownKeys:()=>[]})}return e[t]},set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1,getPrototypeOf:()=>null,setPrototypeOf:()=>!1,has:(e,t)=>!["soundSystem","stateMachine","emotionLibrary"].includes(t)&&t in e,ownKeys:e=>["canvas","start","stop","pause","resume","setEmotion","morphTo","express"].filter(t=>t in e)}),this.canvas=this._engine.canvas,this._initialized=!0,Promise.resolve()}start(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.start()}stop(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.stop()}pause(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.pause()}resume(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.resume()}loadAudio(e){return this._audioManager.loadAudio(e)}getAudioAnalysis(){return this._audioManager.getAudioAnalysis()}connectAudio(e){return this._audioManager.connectAudio(e)}disconnectAudio(e){return this._audioManager.disconnectAudio(e)}getSpectrumData(){return this._audioManager.getSpectrumData()}startRhythmSync(e){return this._audioManager.startRhythmSync(e)}stopRhythmSync(){return this._audioManager.stopRhythmSync()}getPerformanceMetrics(){const e=this.#t();return e?e.performanceMonitor?{fps:e.performanceMonitor.getCurrentFPS()||0,frameTime:e.performanceMonitor.getAverageFrameTime()||0,particleCount:e.particleSystem?.activeParticles||0}:e.animationController?{fps:e.animationController.currentFPS||0,frameTime:1e3/60,particleCount:0}:{fps:0,frameTime:0,particleCount:0}:{fps:0,frameTime:0}}triggerGesture(e,t){return this._gestureController.triggerGesture(e,t)}express(e,t){return this._gestureController.express(e,t)}chain(e){return this._gestureController.chain(e)}morphTo(e,t){return this.setShape(e,t)}updateUndertone(e){return this._gestureController.updateUndertone(e)}feel(e){if(!this.#t())throw new Error("Engine not initialized. Call init() first.");const t=Date.now(),i=this._feelRateLimiter;if(i.calls=i.calls.filter(e=>t-e<i.windowMs),i.calls.length>=i.maxCallsPerSecond)return console.warn(`[EmotiveMascot] feel: Rate limit exceeded. Max ${i.maxCallsPerSecond} calls per second.`),{success:!1,error:"Rate limit exceeded",parsed:null};i.calls.push(t);const s=this._intentParser.parse(e),n=this._intentParser.validate(s);if(!n.valid)return console.warn("[EmotiveMascot] feel: Invalid intent:",n.errors),{success:!1,error:n.errors.join("; "),parsed:s};try{if(s.emotion){const e={};s.undertone&&"clear"!==s.undertone&&(e.undertone=s.undertone);const t=Math.round(500+1e3*(1-s.intensity));this.setEmotion(s.emotion,e,t)}for(const e of s.gestures)this.express(e);return s.shape&&this.morphTo(s.shape),{success:!0,error:null,parsed:s}}catch(e){return console.error("[EmotiveMascot] feel: Execution error:",e),{success:!1,error:e.message,parsed:s}}}static getFeelVocabulary(){return{emotions:Yo.getAvailableEmotions(),undertones:Yo.getAvailableUndertones(),gestures:Yo.getAvailableGestures(),shapes:Yo.getAvailableShapes()}}parseIntent(e){return this._intentParser.parse(e)}setEmotion(e,t,i){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");let n=null,a=500,r=i;if("string"==typeof t)n=t;else if("number"==typeof t)void 0!==i?a=t:r=t;else if(t&&"object"==typeof t){const{undertone:e,duration:i,intensity:s}=t;n=e,void 0!==i&&(a=i),void 0!==s&&(this._lastIntensity=s)}if(this._isRecording){const t=r||Date.now()-this._recordingStartTime;this._timeline.push({type:"emotion",name:e,undertone:n,time:t})}const o={};return n&&(o.undertone=n),void 0!==this._lastIntensity&&(o.intensity=this._lastIntensity,this._lastIntensity=void 0),s.setEmotion(e,Object.keys(o).length?o:null,a),this}setSoundEnabled(e){const t=this.#t();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.soundSystem&&(t.soundSystem.enabled=e),this}pushEmotion(e,t=.5){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.pushEmotion(e,t),this}nudgeEmotion(e,t,i=1){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");return s.stateCoordinator.nudgeEmotion(e,t,i),this}setEmotionDampening(e){const t=this.#t();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.stateCoordinator.setEmotionDampening(e),this}getEmotionDampening(){const e=this.#t();return e?e.stateCoordinator.getEmotionDampening():0}clearEmotions(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.stateCoordinator.clearEmotions(),this}getEmotionalState(){const e=this.#t();return e?e.stateCoordinator.getEmotionalState():{dominant:null,undercurrents:[],slots:[]}}getSnapshot(){const e=this.#t();if(!e)return null;const t={version:1,timestamp:Date.now(),stateMachine:e.stateMachine.serialize()};return e.stateCoordinator._dynamics&&(t.dynamics=e.stateCoordinator._dynamics.serialize()),t}loadSnapshot(e){const t=this.#t();return t&&e&&1===e.version?(e.stateMachine&&t.stateMachine.deserialize(e.stateMachine),e.dynamics&&t.stateCoordinator.dynamics.deserialize(e.dynamics),t.stateCoordinator._emit("emotionChanged",{emotion:t.stateMachine.state.emotion,slots:t.stateMachine.getSlots(),restored:!0}),this):this}get dynamics(){const e=this.#t();return e?e.stateCoordinator.dynamics:null}getInputEvaluator(e){return this._audioManager.getInputEvaluator(e)}setEmotionFeedback(e){const t=this.getInputEvaluator();return t&&t.setEmotionFeedback(e),this}getAudioLayers(){const e=this._audioManager.getLayers();return e?Object.freeze({...e}):null}getEffectiveBPM(){const e=this.#t();if(!e||!e.rhythmIntegration)return 120;let t=e.rhythmIntegration.getEffectiveBPM(e.stateMachine);return t*=this._audioManager.getDifficultyManager().getBPMMultiplier(),Math.round(100*t)/100}setDifficulty(e){return this._audioManager.getDifficultyManager().setDifficulty(e),this}setAssist(e){return this._audioManager.getDifficultyManager().setAssist(e),this}applyModifier(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.modifiers.applyModifier(e,t),this}removeModifier(e){const t=this.#t();return t?(t.stateCoordinator.modifiers.removeModifier(e),this):this}getActiveModifiers(){const e=this.#t();return e?e.stateCoordinator.modifiers.getActiveModifiers():[]}setShape(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");let s=e;if(this._stanceRegistry.hasStance(e)){const t=this._stanceRegistry.activate(e);s=t.shape||e,i.stateCoordinator&&i.stateCoordinator._emit("stanceChanged",{name:e,config:t})}let n,a={};if("number"==typeof t)n=t;else if(t&&"object"==typeof t){const{timestamp:e,...i}=t;a=i,n=e}if(this._isRecording){const e=n||Date.now()-this._recordingStartTime;this._timeline.push({type:"shape",name:s,time:e,config:a})}return i&&i.morphTo(s,a),this}registerStance(e,t){return this._stanceRegistry.registerStance(e,t),this}getActiveStance(){return this._stanceRegistry.getActiveStance()}getAvailableStances(){return this._stanceRegistry.getAvailableStances()}dismissStance(){if(this._stanceRegistry.dismiss()){const e=this.#t();e&&e.stateCoordinator&&e.stateCoordinator._emit("stanceChanged",{name:null,config:null})}return this}enableGazeTracking(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.gazeTracker&&e.gazeTracker.enable(),this}disableGazeTracking(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");e.gazeTracker&&e.gazeTracker.disable()}setGazeTarget(e,t){const i=this.#t();if(!i)throw new Error("Engine not initialized. Call init() first.");i.gazeTracker&&(i.gazeTracker.mousePos={x:e,y:t},i.gazeTracker.updateTargetGaze())}setContainment(e,t=1){return this._visualEffectsManager.setContainment(e,t)}setPosition(e,t,i=0){const s=this.#t();if(!s)throw new Error("Engine not initialized. Call init() first.");if(s.positionController)s.positionController.onUpdate||(s.positionController.onUpdate=()=>{}),s.positionController.setOffset(e,t,i);else if(this._canvas){const s=window.innerWidth/2+e,n=window.innerHeight/2+t,a=1+.001*i;this._canvas.style.transform=`translate(${s}px, ${n}px) translate(-50%, -50%) scale(${a})`}}animateToPosition(e,t,i=0,s=1e3,n="easeOutCubic"){const a=this.#t();if(!a)throw new Error("Engine not initialized. Call init() first.");a.positionController?(a.positionController.onUpdate||(a.positionController.onUpdate=()=>{}),a.positionController.animateOffset(e,t,i,s,n)):this.setPosition(e,t,i)}clearParticles(){return this._visualEffectsManager.clearParticles()}setParticleSystemCanvasDimensions(e,t){return this._visualEffectsManager.setParticleSystemCanvasDimensions(e,t),this}attachToElement(e,t={}){return this._elementAttachmentManager.attachToElement(e,t)}isAttachedToElement(){return this._elementAttachmentManager.isAttachedToElement()}detachFromElement(){return this._elementAttachmentManager.detachFromElement()}getGazeState(){const e=this.#t();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.gazeTracker?e.gazeTracker.getState():null}setBPM(e){e=Math.max(0,Math.min(300,Number(e)||0));const t=this.#t();return t&&t.rhythmIntegration&&t.rhythmIntegration.setBPM(e),this}setQuality(e){const t={low:{particleCount:50,fps:30},medium:{particleCount:100,fps:60},high:{particleCount:200,fps:60}},i=t[e]||t.medium,s=this.#t();s&&s.performanceMonitor&&s.performanceMonitor.setTargetFPS(i.fps),s&&s.particleSystem&&s.particleSystem.setMaxParticles(i.particleCount)}setMaxParticles(e){e=Math.max(0,Math.min(1e3,Math.floor(Number(e)||0)));const t=this.#t();return t&&t.particleSystem&&t.particleSystem.setMaxParticles(e),this}getParticleCount(){const e=this.#t();return e&&e.particleSystem&&e.particleSystem.particles?e.particleSystem.particles.length:0}setOpacity(e){const t=this.#t();if(e=Math.max(0,Math.min(1,e)),t&&t.renderer){const i=t.canvasManager?.getContext();i&&(i.globalAlpha=e)}return this._currentOpacity=e,this}getOpacity(){return void 0!==this._currentOpacity?this._currentOpacity:1}fadeIn(e=1e3){const t=this.getOpacity(),i=performance.now(),s=n=>{const a=n-i,r=Math.min(a/e,1),o=t+(1-t)*r;this.setOpacity(o),r<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}fadeOut(e=1e3){const t=this.getOpacity(),i=performance.now(),s=n=>{const a=n-i,r=Math.min(a/e,1),o=t*(1-r);this.setOpacity(o),r<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}async transitionTo(e,t={}){const i=t.fadeOutMs??500,s=t.fadeInMs??500;await new Promise(e=>{const t=this.getOpacity(),s=performance.now(),n=a=>{const r=Math.min((a-s)/i,1);this.setOpacity(t*(1-r)),r<1?requestAnimationFrame(n):e()};requestAnimationFrame(n)}),e&&e(this),await new Promise(e=>{const t=performance.now(),i=n=>{const a=Math.min((n-t)/s,1);this.setOpacity(a),a<1?requestAnimationFrame(i):e()};requestAnimationFrame(i)})}setAmbientMood(e){let t;if("string"==typeof e){if(t=this._ambientPresets?.[e],!t)return this}else t=e;return this._ambientMood={...t},t.tint&&this.setColor(t.tint),this}registerAmbientPreset(e,t){if("__proto__"===e||"constructor"===e||"prototype"===e)return this;this._ambientPresets||(this._ambientPresets={});const i={};for(const e of Object.keys(t))"__proto__"!==e&&"constructor"!==e&&"prototype"!==e&&(i[e]=t[e]);return this._ambientPresets[e]=i,this}getAmbientMood(){return this._ambientMood?{...this._ambientMood}:null}setColor(e){const t=this.#t();return t&&t.renderer&&t.renderer.config&&(t.renderer.config.coreColor=e),this}setGlowColor(e){const t=this.#t();return t&&t.renderer&&t.renderer.config&&(t.renderer.config.defaultGlowColor=e),this}setTheme(e){return e&&"object"==typeof e?(e.core&&this.setColor(e.core),e.glow&&this.setGlowColor(e.glow),this):this}setSpeed(e){const t=this.#t();return e=Math.max(.1,Math.min(10,e)),this._speedMultiplier=e,t&&t.animationController&&t.animationController.setSpeedMultiplier(e),this}getSpeed(){const e=this.#t();return e&&e.animationController?e.animationController.getSpeedMultiplier():this._speedMultiplier||1}setFPS(e){const t=this.#t();return e=Math.max(1,Math.min(120,e)),t&&t.animationController&&t.animationController.setTargetFPS(e),this}getFPS(){const e=this.#t();return e&&e.animationController&&e.animationController.targetFPS||60}isPaused(){const e=this.#t();return!(!e||!e.animationController)&&!0===e.animationController.isPaused}batch(e){const t=this.isPaused();return t||this.pause(),"function"==typeof e&&e(this),t||this.resume(),this}on(e,t){const i=this.#t();return i&&i.eventManager&&i.eventManager.on(e,t),this}off(e,t){const i=this.#t();return i&&i.eventManager&&i.eventManager.off(e,t),this}setScale(e){const t=this.#t();return t&&t.positionController&&(t.positionController.setScaleOverrides(e),"object"==typeof e&&void 0!==e.particles&&t.particleSystem&&"function"==typeof t.particleSystem.refreshPool&&t.particleSystem.refreshPool()),this}getScale(){const e=this.#t();return e&&e.positionController&&e.positionController.globalScale||1}setBackdrop(e={}){const t=this.#t();return t&&"function"==typeof t.setBackdrop&&t.setBackdrop(e),this}getBackdrop(){const e=this.#t();return e&&"function"==typeof e.getBackdrop?e.getBackdrop():null}startRecording(){return this._timelineRecorder.startRecording()}stopRecording(){return this._timelineRecorder.stopRecording()}playTimeline(e){return this._timelineRecorder.playTimeline(e)}stopPlayback(){return this._timelineRecorder.stopPlayback()}getTimeline(){return this._timelineRecorder.getTimeline()}loadTimeline(e){return this._timelineRecorder.loadTimeline(e)}exportTimeline(){return this._timelineRecorder.exportTimeline()}importTimeline(e){return this._timelineRecorder.importTimeline(e)}getCurrentTime(){return this._timelineRecorder.getCurrentTime()}seek(e){return this._timelineRecorder.seek(e)}getFrameData(e="png"){return this._visualEffectsManager.getFrameData(e)}getFrameBlob(e="png"){return this._visualEffectsManager.getFrameBlob(e)}getAnimationData(){return this._timelineRecorder.getAnimationData()}getAvailableGestures(){return Ri()}getAvailableEmotions(){return["neutral","joy","calm","sadness","anger","fear","surprise","disgust","love","euphoria","excited","focused","suspicion","resting","glitch"]}getAvailableShapes(){return["circle","square","triangle","star","heart","moon","sun"]}getVersion(){return"3.4.0"}getCapabilities(){return{audio:!0,recording:!0,timeline:!0,export:!0,shapes:!0,gestures:!0,emotions:!0,particles:!0,gazeTracking:!0}}get renderer(){const e=this.#t();return e&&e.renderer?new Proxy(e.renderer,{get:(e,t)=>["setBlinkingEnabled"].includes(t)?e[t]:void 0}):null}get shapeMorpher(){const e=this.#t();return e&&e.shapeMorpher?new Proxy(e.shapeMorpher,{get:(e,t)=>["resetMusicDetection","frequencyData"].includes(t)?e[t]:void 0}):null}get gazeTracker(){const e=this.#t();return e&&e.gazeTracker?new Proxy(e.gazeTracker,{get:(e,t)=>["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"].includes(t)?e[t]:void 0}):null}destroy(){this.stop(),this._timeline=[],this._isRecording=!1,this._isPlaying=!1,this.detachFromElement();const e=this.#t();e&&e.destroy&&e.destroy()}}class No{constructor(e={}){this._state=this.deepClone(e),this._prevState=this.deepClone(e),this._subscribers=new Map,this._history=[],this._maxHistorySize=50,this._middleware=[],this._validators=new Map,this._computed=new Map,this._computedDeps=new Map,this._stats={updates:0,notifications:0,computedCacheHits:0,computedCacheMisses:0}}getState(e=null){return e?this.deepClone(this.getNestedValue(this._state,e)):this.deepClone(this._state)}setState(e,t=void 0){let i;i="string"==typeof e?{[e]:t}:e;for(const e of this._middleware)if(i=e(i,this._state),!i)return!1;const s=this.deepClone(this._state);for(const[e,t]of Object.entries(i)){if(this._validators.has(e)&&!this._validators.get(e)(t))return console.error(`Validation failed for path: ${e}`),!1;this.setNestedValue(s,e,t)}return this._prevState=this._state,this._state=s,this.addToHistory(i),this.invalidateComputed(Object.keys(i)),this.notifySubscribers(i),this._stats.updates++,!0}subscribe(e,t=null){let i=null,s=e;"string"==typeof e&&(i=e,s=t);const n=Symbol("subscriber"),a={path:i,callback:s,id:n};return this._subscribers.set(n,a),()=>{this._subscribers.delete(n)}}computed(e,t,i){this._computedDeps.set(e,t),Object.defineProperty(this,e,{get:()=>{if(this._computed.has(e))return this._stats.computedCacheHits++,this._computed.get(e);this._stats.computedCacheMisses++;const s=t.map(e=>this.getState(e)),n=i(...s);return this._computed.set(e,n),n}})}addValidator(e,t){this._validators.set(e,t)}addMiddleware(e){this._middleware.push(e)}reset(e={}){this._state=this.deepClone(e),this._prevState=this.deepClone(e),this._history=[],this._computed.clear(),this.notifySubscribers({"*":"reset"})}getDiff(){return this.objectDiff(this._prevState,this._state)}undo(e=1){if(this._history.length<e)return console.warn("Cannot undo: insufficient history"),!1;const t=Math.max(0,this._history.length-e-1),i=this._history[t];return!!i&&(this._state=this.deepClone(i.state),this._history=this._history.slice(0,t+1),this.notifySubscribers({"*":"undo"}),!0)}batch(e){const t={},i=this.setState.bind(this);return this.setState=(e,i)=>("string"==typeof e?t[e]=i:Object.assign(t,e),!0),e(),this.setState=i,this.setState(t)}createSelector(e){let t=null,i=null;return()=>{const s=this._state;return s===t||(t=s,i=e(s)),i}}static _DANGEROUS_KEYS=new Set(["__proto__","constructor","prototype"]);notifySubscribers(e){for(const t of this._subscribers.values())t.path&&!Object.keys(e).some(e=>e.startsWith(t.path)||t.path.startsWith(e))||(t.callback(this._state,e),this._stats.notifications++)}invalidateComputed(e){for(const[t,i]of this._computedDeps.entries())i.some(t=>e.some(e=>t.startsWith(e)||e.startsWith(t)))&&this._computed.delete(t)}addToHistory(e){this._history.push({timestamp:Date.now(),updates:e,state:this.deepClone(this._state)}),this._history.length>this._maxHistorySize&&this._history.shift()}deepClone(e){if(null===e||"object"!=typeof e)return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Array)return e.map(e=>this.deepClone(e));if(e instanceof Object){const t={};for(const i in e)({}).hasOwnProperty.call(e,i)&&(t[i]=this.deepClone(e[i]));return t}}getNestedValue(e,t){const i=t.split(".");for(const e of i)if(No._DANGEROUS_KEYS.has(e))return void console.warn("[StateStore] Rejected dangerous path segment:",e);return i.reduce((e,t)=>e&&void 0!==e[t]?e[t]:void 0,e)}setNestedValue(e,t,i){const s=t.split(".");for(const e of s)if(No._DANGEROUS_KEYS.has(e))return void console.warn("[StateStore] Rejected dangerous path segment:",e);const n=s.pop();s.reduce((e,t)=>(e[t]||(e[t]={}),e[t]),e)[n]=i}_deepEqual(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(typeof e!=typeof t)return!1;if("object"!=typeof e)return!1;const i=Array.isArray(e);if(i!==Array.isArray(t))return!1;if(i){if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(!this._deepEqual(e[i],t[i]))return!1;return!0}const s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s){if(!{}.hasOwnProperty.call(t,i))return!1;if(!this._deepEqual(e[i],t[i]))return!1}return!0}objectDiff(e,t){const i={};for(const s in t)s in e?this._deepEqual(e[s],t[s])||(i[s]={type:"changed",oldValue:e[s],newValue:t[s]}):i[s]={type:"added",value:t[s]};for(const s in e)s in t||(i[s]={type:"deleted",oldValue:e[s]});return i}getStats(){return{...this._stats,subscribers:this._subscribers.size,historySize:this._history.length,computedValues:this._computed.size,validators:this._validators.size}}}const Qo=new No({engine:{initialized:!1,running:!1,paused:!1,fps:60,frameCount:0},renderer:{color:"#4a90e2",intensity:1,eyeOpenness:1,breathRate:1,breathDepth:1,sleeping:!1},animation:{currentGesture:null,activeLoops:0},emotion:{current:"neutral",intensity:1,undertone:null,transitioning:!1},particles:{active:!0,count:0,maxParticles:100},sound:{enabled:!1,volume:1,bpm:120,rhythmEnabled:!1},performance:{quality:"high",adaptiveQuality:!0,targetFPS:60,actualFPS:60}});class Jo{constructor(e){this.ctx=e,this.currentState={fillStyle:null,strokeStyle:null,globalAlpha:1,globalCompositeOperation:"source-over",lineWidth:1,lineCap:"butt",lineJoin:"miter",shadowBlur:0,shadowColor:"transparent",shadowOffsetX:0,shadowOffsetY:0,font:"10px sans-serif"},this.stateStack=[],this.stats={saves:0,restores:0,stateChanges:0,redundantChanges:0}}setFillStyle(e){this.currentState.fillStyle!==e?(this.ctx.fillStyle=e,this.currentState.fillStyle=e,this.stats.stateChanges++):this.stats.redundantChanges++}setStrokeStyle(e){this.currentState.strokeStyle!==e?(this.ctx.strokeStyle=e,this.currentState.strokeStyle=e,this.stats.stateChanges++):this.stats.redundantChanges++}setGlobalAlpha(e){Math.abs(this.currentState.globalAlpha-e)>.001?(this.ctx.globalAlpha=e,this.currentState.globalAlpha=e,this.stats.stateChanges++):this.stats.redundantChanges++}setGlobalCompositeOperation(e){this.currentState.globalCompositeOperation!==e?(this.ctx.globalCompositeOperation=e,this.currentState.globalCompositeOperation=e,this.stats.stateChanges++):this.stats.redundantChanges++}setLineWidth(e){Math.abs(this.currentState.lineWidth-e)>.001?(this.ctx.lineWidth=e,this.currentState.lineWidth=e,this.stats.stateChanges++):this.stats.redundantChanges++}setShadow(e=0,t="transparent",i=0,s=0){let n=!1;Math.abs(this.currentState.shadowBlur-e)>.001&&(this.ctx.shadowBlur=e,this.currentState.shadowBlur=e,n=!0),this.currentState.shadowColor!==t&&(this.ctx.shadowColor=t,this.currentState.shadowColor=t,n=!0),Math.abs(this.currentState.shadowOffsetX-i)>.001&&(this.ctx.shadowOffsetX=i,this.currentState.shadowOffsetX=i,n=!0),Math.abs(this.currentState.shadowOffsetY-s)>.001&&(this.ctx.shadowOffsetY=s,this.currentState.shadowOffsetY=s,n=!0),n?this.stats.stateChanges++:this.stats.redundantChanges++}clearShadow(){0===this.currentState.shadowBlur&&"transparent"===this.currentState.shadowColor||this.setShadow(0,"transparent",0,0)}save(){this.ctx.save(),this.stateStack.push({...this.currentState}),this.stats.saves++}restore(){this.ctx.restore(),this.stateStack.length>0&&(this.currentState=this.stateStack.pop()),this.stats.restores++}getStats(){const e=this.stats.stateChanges+this.stats.redundantChanges,t=e>0?(this.stats.redundantChanges/e*100).toFixed(2):0;return{saves:this.stats.saves,restores:this.stats.restores,stateChanges:this.stats.stateChanges,redundantChanges:this.stats.redundantChanges,redundancyRate:`${t}%`,stackDepth:this.stateStack.length}}resetStats(){this.stats={saves:0,restores:0,stateChanges:0,redundantChanges:0}}reset(){this.currentState={fillStyle:null,strokeStyle:null,globalAlpha:1,globalCompositeOperation:"source-over",lineWidth:1,lineCap:"butt",lineJoin:"miter",shadowBlur:0,shadowColor:"transparent",shadowOffsetX:0,shadowOffsetY:0,font:"10px sans-serif"},this.stateStack=[],this.resetStats()}scoped(e){this.save();try{e()}finally{this.restore()}}batch(e){void 0!==e.fillStyle&&this.setFillStyle(e.fillStyle),void 0!==e.strokeStyle&&this.setStrokeStyle(e.strokeStyle),void 0!==e.globalAlpha&&this.setGlobalAlpha(e.globalAlpha),void 0!==e.globalCompositeOperation&&this.setGlobalCompositeOperation(e.globalCompositeOperation),void 0!==e.lineWidth&&this.setLineWidth(e.lineWidth),e.shadow&&this.setShadow(e.shadow.blur,e.shadow.color,e.shadow.offsetX,e.shadow.offsetY)}}class Ko{constructor(e={}){this.enabled=!1!==e.enabled,this.sampleInterval=e.sampleInterval||1e3,this.maxSamples=e.maxSamples||60,this.enableMemoryTracking=!1!==e.enableMemoryTracking,this.enableNetworkTracking=!1!==e.enableNetworkTracking,this.metrics={fps:{samples:[],current:0,avg:0,min:1/0,max:0},frameTime:{samples:[],current:0,avg:0,min:1/0,max:0},memory:{samples:[],current:0,avg:0,min:1/0,max:0},renderTime:{samples:[],current:0,avg:0,min:1/0,max:0},updateTime:{samples:[],current:0,avg:0,min:1/0,max:0},particleCount:{samples:[],current:0,avg:0,min:1/0,max:0},drawCalls:{samples:[],current:0,avg:0,min:1/0,max:0},canvasOperations:{samples:[],current:0,avg:0,min:1/0,max:0}},this.frameCount=0,this.lastFrameTime=0,this.lastSampleTime=0,this.marks=new Map,this.measures=new Map,this.thresholds={fps:{warning:50,critical:30},frameTime:{warning:20,critical:33},memory:{warning:100,critical:200},renderTime:{warning:10,critical:16},...e.thresholds},this.callbacks={onWarning:e.onWarning||null,onCritical:e.onCritical||null,onSample:e.onSample||null},this.enabled&&this.start()}start(){this.enabled&&(this.lastSampleTime=performance.now(),this.lastFrameTime=performance.now(),this.frameCount=0,this.sampleIntervalId=setInterval(()=>this.sample(),this.sampleInterval))}stop(){this.sampleIntervalId&&(clearInterval(this.sampleIntervalId),this.sampleIntervalId=null)}frame(e=performance.now()){if(!this.enabled)return;this.frameCount++;const t=e-this.lastFrameTime;this.metrics.frameTime.current=t,t>0&&(this.metrics.fps.current=1e3/t),this.lastFrameTime=e}mark(e,t=performance.now()){this.enabled&&this.marks.set(e,t)}measure(e,t,i=null){if(!this.enabled)return 0;const s=this.marks.get(t);if(!s)return 0;const n=(i?this.marks.get(i):performance.now())-s;let a=this.measures.get(e);return a||(a=[],this.measures.set(e,a)),a.push(n),a.length>this.maxSamples&&a.shift(),"render"===e?this.metrics.renderTime.current=n:"update"===e&&(this.metrics.updateTime.current=n),n}recordMetric(e,t){this.enabled&&this.metrics[e]&&(this.metrics[e].current=t)}sample(){const e=performance.now(),t=e-this.lastSampleTime,i=1e3*this.frameCount/t;if(this.updateMetric("fps",i),this.enableMemoryTracking&&performance.memory){const e=performance.memory.usedJSHeapSize/1048576;this.updateMetric("memory",e)}for(const e in this.metrics)"fps"!==e&&"memory"!==e&&this.updateMetric(e,this.metrics[e].current);this.checkThresholds(),this.frameCount=0,this.lastSampleTime=e,this.callbacks.onSample&&this.callbacks.onSample(this.getStats())}updateMetric(e,t){const i=this.metrics[e];i&&(i.current=t,i.samples.push(t),i.samples.length>this.maxSamples&&i.samples.shift(),i.samples.length>0&&(i.avg=i.samples.reduce((e,t)=>e+t,0)/i.samples.length,i.min=Math.min(i.min,t),i.max=Math.max(i.max,t)))}checkThresholds(){for(const[e,t]of Object.entries(this.thresholds)){const i=this.metrics[e];if(!i)continue;const s=i.current;let n="normal";"fps"===e?s<=t.critical?n="critical":s<=t.warning&&(n="warning"):s>=t.critical?n="critical":s>=t.warning&&(n="warning"),"critical"===n&&this.callbacks.onCritical?this.callbacks.onCritical(e,s,t.critical):"warning"===n&&this.callbacks.onWarning&&this.callbacks.onWarning(e,s,t.warning)}}getStats(){const e={};for(const[t,i]of Object.entries(this.metrics))e[t]={current:i.current,average:i.avg,min:i.min===1/0?0:i.min,max:i.max,samples:i.samples.length};return e.performance=this.getPerformanceScore(),e.health=this.getHealthStatus(),e}getPerformanceScore(){let e=100;return e-=40*(1-Math.min(this.metrics.fps.current/60,1)),e-=30*(1-Math.min(16.67/Math.max(this.metrics.frameTime.current,1),1)),this.metrics.memory.current>0&&(e-=20*(1-Math.min(100/Math.max(this.metrics.memory.current,1),1))),e-=10*(1-Math.min(10/Math.max(this.metrics.renderTime.current,1),1)),Math.max(0,Math.round(e))}getHealthStatus(){const e=this.getPerformanceScore();return e>=90?"excellent":e>=75?"good":e>=50?"fair":e>=25?"poor":"critical"}reset(){for(const e of Object.values(this.metrics))e.samples=[],e.current=0,e.avg=0,e.min=1/0,e.max=0;this.marks.clear(),this.measures.clear(),this.frameCount=0}exportData(){return{timestamp:Date.now(),metrics:this.getStats(),measures:Array.from(this.measures.entries()).map(([e,t])=>({name:e,values:t,average:t.reduce((e,t)=>e+t,0)/t.length,min:Math.min(...t),max:Math.max(...t)})),thresholds:this.thresholds}}setThreshold(e,t,i){this.thresholds[e]&&(this.thresholds[e]={warning:t,critical:i})}enable(){this.enabled=!0,this.start()}disable(){this.enabled=!1,this.stop()}}const Zo=new Ko({enabled:!0,sampleInterval:1e3,maxSamples:60,thresholds:{fps:{warning:50,critical:30},frameTime:{warning:20,critical:33},memory:{warning:150,critical:300},renderTime:{warning:10,critical:16},updateTime:{warning:5,critical:10}}});class el{constructor(e={}){this.baseUrl=e.baseUrl||"/dist/modules/",this.cache=new Map,this.loading=new Map,this.moduleMap=new Map([["core",()=>Promise.resolve().then(function(){return Dl})],["features",()=>Promise.resolve().then(function(){return _l})],["plugins",()=>Promise.resolve().then(function(){return Il})],["particles",()=>Promise.resolve().then(function(){return un})],["audio",()=>Promise.resolve().then(function(){return pr})],["idle-behavior",()=>Promise.resolve().then(function(){return Ma})]]),this.preloadQueue=[],this.preloading=!1,this.features={dynamicImport:this.checkDynamicImport(),modulePreload:"modulepreload"in document.createElement("link").relList,prefetch:"prefetch"in document.createElement("link").relList}}checkDynamicImport(){try{return"undefined"!=typeof window&&"function"==typeof window.import}catch{return!1}}async load(e){if(this.cache.has(e))return this.cache.get(e);if(this.loading.has(e))return this.loading.get(e);const t=this._loadModule(e);this.loading.set(e,t);try{const i=await t;return this.cache.set(e,i),this.loading.delete(e),i}catch(t){throw this.loading.delete(e),new Error(`Failed to load module '${e}': ${t.message}`)}}_validateModulePath(e){if("string"!=typeof e||!e)throw new Error("[LazyLoader] Invalid module path");if(/^https?:\/\//i.test(e))throw new Error("[LazyLoader] External URLs not allowed");if(e.includes(".."))throw new Error("[LazyLoader] Directory traversal not allowed");if(/^[a-zA-Z][a-zA-Z0-9+\-.]*:/.test(e))throw new Error("[LazyLoader] Protocol-based paths not allowed")}_loadModule(e){const t=this.moduleMap.get(e);if(t)return t();this._validateModulePath(e);const i=`${this.baseUrl}${e}.js`;return this.features.dynamicImport?import(i):this._loadScript(i)}_loadScript(e){const t=new Set(["EmotiveEngine","EmotiveMascot","EmotiveMascot3D"]);return new Promise((i,s)=>{const n=document.createElement("script");n.type="module",n.src=e,n.onload=()=>{const n=e.split("/").pop().replace(".js","");if(!t.has(n))return console.warn(`[LazyLoader] Blocked window lookup for unrecognized module: ${n}`),void s(new Error(`Module not allowed for window lookup: ${n}`));const a=window[n]||window.EmotiveEngine?.[n];a?i(a):s(new Error(`Module not found after loading: ${e}`))},n.onerror=()=>s(new Error(`Failed to load script: ${e}`)),document.head.appendChild(n)})}preload(e){Array.isArray(e)||(e=[e]);for(const t of e)this.cache.has(t)||this.preloadQueue.includes(t)||this.preloadQueue.push(t);this.preloading||this._processPreloadQueue()}async _processPreloadQueue(){if(0===this.preloadQueue.length)return void(this.preloading=!1);this.preloading=!0;const e=this.preloadQueue.shift();try{await this.load(e)}catch(t){console.warn(`Failed to preload module '${e}':`,t)}this._processPreloadQueue()}prefetch(e){if(this.features.prefetch){Array.isArray(e)||(e=[e]);for(const t of e){const e=`${this.baseUrl}${t}.js`,i=document.createElement("link");i.rel="prefetch",i.as="script",i.href=e,document.head.appendChild(i)}}}modulePreload(e){if(this.features.modulePreload){Array.isArray(e)||(e=[e]);for(const t of e){const e=`${this.baseUrl}${t}.js`,i=document.createElement("link");i.rel="modulepreload",i.href=e,document.head.appendChild(i)}}}loadFeature(e){const t={particles:["particles"],audio:["audio"],behaviors:["idle-behavior"],plugins:["plugins"]}[e];if(!t)throw new Error(`Unknown feature: ${e}`);const i=t.map(e=>this.load(e));return Promise.all(i)}whenReady(e){Array.isArray(e)||(e=[e]);const t=e.map(e=>this.cache.has(e)?Promise.resolve(this.cache.get(e)):this.loading.has(e)?this.loading.get(e):this.load(e));return Promise.all(t)}isLoaded(e){return this.cache.has(e)}getLoadedModules(){return Array.from(this.cache.keys())}clearCache(e=null){e?this.cache.delete(e):this.cache.clear()}getStats(){return{loaded:this.cache.size,loading:this.loading.size,queued:this.preloadQueue.length,features:this.features,modules:this.getLoadedModules()}}}const tl=new el;function il(e){return tl.load(e)}function sl(...e){tl.preload(e.flat())}function nl(...e){tl.prefetch(e.flat())}const al=new Map,rl=/([+*]|\{[0-9]+,\})\s*[)]\s*[+*?]|\([^)]*[+*][^)]*\)\s*[+*]/;class ol{constructor(e={}){this.flags=new Map,this.overrides=new Map,this.variants=new Map,this.evaluations=new Map,this.config={endpoint:e.endpoint||"/api/feature-flags",refreshInterval:e.refreshInterval||3e5,storage:e.storage||"localStorage",storageKey:e.storageKey||"emotive-feature-flags",userId:e.userId||this.generateUserId(),attributes:e.attributes||{},enableAnalytics:!1!==e.enableAnalytics,enableCache:!1!==e.enableCache,defaultFlags:e.defaultFlags||{}},this.callbacks={onFlagChange:e.onFlagChange||null,onEvaluation:e.onEvaluation||null,onError:e.onError||null},this.refreshTimer=null,this.initialized=!1,this.loadDefaultFlags(),this.config.enableCache&&this.loadFromStorage(),this.config.endpoint&&this.startAutoRefresh()}generateUserId(){const e=this.getStoredUserId();if(e)return e;const t=`user-${Date.now()}-${Math.random().toString(36).substr(2,9)}`;return this.storeUserId(t),t}getStoredUserId(){try{if("undefined"!=typeof localStorage)return localStorage.getItem("emotive-user-id")}catch{}return null}storeUserId(e){try{"undefined"!=typeof localStorage&&localStorage.setItem("emotive-user-id",e)}catch{}}loadDefaultFlags(){const e={enableParticles:{enabled:!0,variant:"default"},enableAudio:{enabled:!0,variant:"default"},enableEmotions:{enabled:!0,variant:"default"},enableGestures:{enabled:!0,variant:"default"},enableGradientCache:{enabled:!0,variant:"default"},enableLazyLoading:{enabled:!0,variant:"default"},enableCodeSplitting:{enabled:!1,variant:"default"},enableWebGL:{enabled:!1,variant:"default"},enableWebGPU:{enabled:!1,variant:"default"},enableOffscreenCanvas:{enabled:!1,variant:"default"},enableDebugMode:{enabled:!1,variant:"default"},enablePerformanceOverlay:{enabled:!1,variant:"default"},enableErrorReporting:{enabled:!0,variant:"default"},buttonColor:{enabled:!0,variant:"blue"},animationSpeed:{enabled:!0,variant:"normal"},particleDensity:{enabled:!0,variant:"medium"},...this.config.defaultFlags};for(const[t,i]of Object.entries(e))this.flags.set(t,i)}async fetchFlags(){if(this.config.endpoint)try{const e=await fetch(this.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:this.config.userId,attributes:this.config.attributes,flags:Array.from(this.flags.keys())})});if(!e.ok)throw new Error(`HTTP ${e.status}`);const t=await e.json();return this.updateFlags(t.flags),this.config.enableCache&&this.saveToStorage(),t.flags}catch(e){this.callbacks.onError&&this.callbacks.onError(e),console.error("Failed to fetch feature flags:",e)}}updateFlags(e){const t=[];for(const[i,s]of Object.entries(e)){const e=this.flags.get(i);this.isEqual(e,s)||(this.flags.set(i,s),t.push({key:i,oldValue:e,newValue:s}))}t.length>0&&this.callbacks.onFlagChange&&this.callbacks.onFlagChange(t)}isEqual(e,t){return e===t||!(!e||!t)&&e.enabled===t.enabled&&e.variant===t.variant}isEnabled(e,t=!1){if(this.overrides.has(e))return this.overrides.get(e);const i=this.flags.get(e),s=i?i.enabled:t;return this.trackEvaluation(e,s,i?.variant||"default"),s}getVariant(e,t="default"){if(this.variants.has(e))return this.variants.get(e);const i=this.flags.get(e),s=i?i.variant:t;return this.trackEvaluation(e,i?.enabled||!1,s),s}evaluate(e,t={}){const{defaultEnabled:i=!1,defaultVariant:s="default",attributes:n={}}=t,a={...this.config.attributes,...n},r=this.flags.get(e);if(r&&r.rules)for(const t of r.rules)if(this.evaluateRule(t,a)){const i={enabled:void 0!==t.enabled?t.enabled:r.enabled,variant:t.variant||r.variant};return this.trackEvaluation(e,i.enabled,i.variant),i}return{enabled:this.isEnabled(e,i),variant:this.getVariant(e,s)}}evaluateRule(e,t){if(!e.conditions)return!0;for(const i of e.conditions)if(!this.evaluateCondition(i,t))return!1;return!0}evaluateCondition(e,t){const{attribute:i,operator:s,value:n}=e,a=t[i];switch(s){case"equals":return a===n;case"not_equals":return a!==n;case"contains":return String(a).includes(n);case"not_contains":return!String(a).includes(n);case"greater_than":return Number(a)>Number(n);case"less_than":return Number(a)<Number(n);case"in":return n.includes(a);case"not_in":return!n.includes(a);case"matches":try{if("string"==typeof n&&n.length>200)return!1;const e=function(e){const t=al.get(e);if(t)return t;if(rl.test(e))return null;const i=new RegExp(e);if(al.size>=100){const e=al.keys().next().value;al.delete(e)}return al.set(e,i),i}(n);return!!e&&e.test(String(a))}catch{return!1}default:return!1}}trackEvaluation(e,t,i){if(!this.config.enableAnalytics)return;const s={flagKey:e,enabled:t,variant:i,timestamp:Date.now(),userId:this.config.userId,attributes:this.config.attributes};this.evaluations.has(e)||this.evaluations.set(e,[]),this.evaluations.get(e).push(s),this.callbacks.onEvaluation&&this.callbacks.onEvaluation(s)}override(e,t,i=null){this.overrides.set(e,t),null!==i&&this.variants.set(e,i)}clearOverride(e){this.overrides.delete(e),this.variants.delete(e)}clearAllOverrides(){this.overrides.clear(),this.variants.clear()}getAllFlags(){const e={};for(const[t,i]of this.flags)e[t]={...i,overridden:this.overrides.has(t)};return e}getEnabledFlags(){const e=[];for(const[t]of this.flags)this.isEnabled(t)&&e.push(t);return e}saveToStorage(){if(this.config.enableCache)try{const e=this.getStorage();if(!e)return;const t={flags:Object.fromEntries(this.flags),timestamp:Date.now(),userId:this.config.userId};e.setItem(this.config.storageKey,JSON.stringify(t))}catch(e){console.error("Failed to save feature flags to storage:",e)}}loadFromStorage(){if(!this.config.enableCache)return;const e=this.getStorage();if(!e)return;const t=e.getItem(this.config.storageKey);if(t)try{const e=JSON.parse(t);if(Date.now()-e.timestamp>this.config.refreshInterval)return;this.updateFlags(e.flags)}catch(t){console.warn("Failed to load feature flags from storage, removing corrupted key:",t);try{e.removeItem(this.config.storageKey)}catch{}}}getStorage(){try{if("localStorage"===this.config.storage&&"undefined"!=typeof localStorage)return localStorage;if("sessionStorage"===this.config.storage&&"undefined"!=typeof sessionStorage)return sessionStorage}catch{}return null}startAutoRefresh(){this.refreshTimer||(this.fetchFlags(),this.refreshTimer=setInterval(()=>{this.fetchFlags()},this.config.refreshInterval))}stopAutoRefresh(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=null)}updateAttributes(e){this.config.attributes={...this.config.attributes,...e},this.config.endpoint&&this.fetchFlags()}getAnalytics(){const e={evaluations:{},summary:{total:0,byFlag:{},byVariant:{}}};for(const[t,i]of this.evaluations){e.evaluations[t]=i,e.summary.total+=i.length,e.summary.byFlag[t]={count:i.length,enabled:i.filter(e=>e.enabled).length,variants:{}};for(const s of i)e.summary.byVariant[s.variant]||(e.summary.byVariant[s.variant]=0),e.summary.byVariant[s.variant]++,e.summary.byFlag[t].variants[s.variant]||(e.summary.byFlag[t].variants[s.variant]=0),e.summary.byFlag[t].variants[s.variant]++}return e}reset(){this.flags.clear(),this.overrides.clear(),this.variants.clear(),this.evaluations.clear(),this.loadDefaultFlags()}destroy(){this.stopAutoRefresh(),this.reset()}}const ll=new ol({endpoint:null,enableCache:!0,enableAnalytics:!1});function hl(e,t=!1){return ll.isEnabled(e,t)}function cl(e,t="default"){return ll.getVariant(e,t)}class ul{constructor(e,t,i){this.name=e,this.startBeat=t,this.endBeat=i}get duration(){return this.endBeat-this.startBeat}}class dl{constructor(e,t=null){this._mascot=e,this._rhythm=t,this._events=[],this._sections=new Map,this._isPlaying=!1,this._startTime=0,this._pauseOffset=0,this._timers=[],this._loopState=null,this._onBeatCallbacks=[],this._onSectionCallbacks=[],this._rafId=null}at(e,t,i,s=null){return this._events.push({time:e,beat:null,bar:null,action:t,value:i,options:s}),this}atBeat(e,t,i,s=null){const n=this._beatsToMs(e);return this._events.push({time:n,beat:e,bar:null,action:t,value:i,options:s}),this}atBar(e,t,i,s=null){const n=this._beatsToMs(4*e);return this._events.push({time:n,beat:4*e,bar:e,action:t,value:i,options:s}),this}section(e,t,i){return this._sections.set(e,new ul(e,t,i)),this}play(e=0){this.stop(),this._isPlaying=!0,this._pauseOffset=e,this._startTime=performance.now()-e,this._scheduleEvents(e),this._startBeatLoop()}playSection(e){const t=this._sections.get(e);if(!t)return;this._fireSectionCallbacks(e,"enter");const i=this._beatsToMs(t.startBeat),s=this._beatsToMs(t.endBeat);this.play(i);const n=s-i;this._timers.push(setTimeout(()=>{this._fireSectionCallbacks(e,"exit"),this._loopState||this.stop()},n))}loop(e,t=1){this._sections.get(e)&&(this._loopState={section:e,remaining:t},this._playLoopIteration())}_playLoopIteration(){if(!this._loopState||this._loopState.remaining<=0)return void(this._loopState=null);this._loopState.remaining--;const e=this._sections.get(this._loopState.section),t=this._beatsToMs(e.startBeat),i=this._beatsToMs(e.endBeat),s=i-t;this.stop(),this._isPlaying=!0,this._startTime=performance.now()-t,this._scheduleEvents(t,i),this._startBeatLoop(),this._timers.push(setTimeout(()=>{this._playLoopIteration()},s))}pause(){this._isPlaying&&(this._pauseOffset=performance.now()-this._startTime,this._clearTimers(),this._isPlaying=!1)}resume(){this._isPlaying||this.play(this._pauseOffset)}stop(){this._clearTimers(),this._isPlaying=!1,this._loopState=null,this._rafId&&(cancelAnimationFrame(this._rafId),this._rafId=null)}onBeat(e,t){const i={every:e,callback:t,lastBeat:-1};return this._onBeatCallbacks.push(i),()=>{this._onBeatCallbacks=this._onBeatCallbacks.filter(e=>e!==i)}}onSection(e,t,i){const s={section:e,event:t,callback:i};return this._onSectionCallbacks.push(s),()=>{this._onSectionCallbacks=this._onSectionCallbacks.filter(e=>e!==s)}}loadFromRecording(e){this._events=[];for(const t of e){const e="shape"===t.type?"morph":t.type;this.at(t.time,e,t.name,t.config||null)}}getElapsed(){return this._isPlaying?performance.now()-this._startTime:this._pauseOffset}getCurrentBeat(){return this.getElapsed()/this._getBeatDurationMs()}_scheduleEvents(e,t=1/0){const i=[...this._events].sort((e,t)=>e.time-t.time);for(const s of i){if(s.time<e||s.time>=t)continue;const i=s.time-e;this._timers.push(setTimeout(()=>{this._isPlaying&&this._executeEvent(s)},Math.max(0,i)))}}_executeEvent(e){switch(e.action){case"emotion":this._mascot.setEmotion&&this._mascot.setEmotion(e.value,e.options||void 0);break;case"gesture":this._mascot.express?this._mascot.express(e.value):this._mascot.triggerGesture&&this._mascot.triggerGesture(e.value);break;case"morph":this._mascot.morphTo&&this._mascot.morphTo(e.value,e.options||void 0);break;case"audioLayer":break;case"nudge":this._mascot.nudgeEmotion&&e.value&&this._mascot.nudgeEmotion(e.value.emotion,e.value.delta);break;case"callback":"function"==typeof e.value&&e.value()}}_startBeatLoop(){const e=this._getBeatDurationMs(),t=()=>{if(!this._isPlaying)return;const i=this.getElapsed(),s=Math.floor(i/e);for(const e of this._onBeatCallbacks)s>e.lastBeat&&s%e.every===0&&(e.lastBeat=s,e.callback(s));this._rafId=requestAnimationFrame(t)};this._rafId=requestAnimationFrame(t)}_fireSectionCallbacks(e,t){for(const i of this._onSectionCallbacks)i.section===e&&i.event===t&&i.callback()}_clearTimers(){for(const e of this._timers)clearTimeout(e);this._timers=[]}_beatsToMs(e){return e*this._getBeatDurationMs()}_getBeatDurationMs(){if(this._rhythm){const e=this._rhythm.getAdapter?.();if(e){const t=e.getTimeInfo();if(t?.beatDuration)return t.beatDuration}}return 500}destroy(){this.stop(),this._events=[],this._sections.clear(),this._onBeatCallbacks=[],this._onSectionCallbacks=[]}}class gl{constructor(e,t,i={},s="error"){this.success=!1,this.error={type:e,message:t,context:i,severity:s,timestamp:Date.now(),recoveryActions:this.generateRecoveryActions(e,i)}}static success(e=null){return{success:!0,data:e,timestamp:Date.now()}}static failure(e,t,i={},s="error"){return new gl(e,t,i,s)}static warning(e,t,i={}){return new gl(e,t,i,"warning")}generateRecoveryActions(e,t){const i="https://github.com/joshtol/emotive-engine/blob/main/docs";return{INVALID_EMOTION:["Check if emotion is one of: joy, sadness, anger, fear, surprise, disgust, contempt, neutral","Use mascot.getAvailableEmotions() to see valid options",`Docs: ${i}/QUICK_REFERENCE.md#emotions`],INVALID_GESTURE:["Verify gesture name matches available gestures","Use mascot.getAvailableGestures() to see valid options",`Docs: ${i}/QUICK_REFERENCE.md#gestures`],CANVAS_CONTEXT_LOST:["Canvas context will attempt automatic recovery","Reduce canvas size if problem persists","Check for memory pressure or GPU issues",`Docs: ${i}/TROUBLESHOOTING.md#canvas-issues`],AUDIO_CONTEXT_FAILED:["Audio features will be disabled, visual features continue","Check browser audio permissions","Ensure user interaction occurred before audio initialization",`Docs: ${i}/TROUBLESHOOTING.md#audio-issues`],PERFORMANCE_DEGRADED:["Particle count has been automatically reduced","Consider reducing canvas size or complexity","Monitor performance metrics for recovery",`Docs: ${i}/PERFORMANCE.md`],MEMORY_LIMIT_EXCEEDED:["System has automatically reduced resource usage","Consider destroying unused mascot instances","Monitor memory usage patterns",`Docs: ${i}/PERFORMANCE.md#memory-management`],VALIDATION_ERROR:["Check parameter types and ranges","Refer to API documentation for valid values","Use default values if unsure",`Docs: ${i}/QUICK_REFERENCE.md`],INITIALIZATION_ERROR:["Ensure canvas element exists and is accessible","Check browser compatibility","Verify all required dependencies are loaded",`Docs: ${i}/TROUBLESHOOTING.md#initialization`],RESOURCE_LOAD_FAILED:["Check network connectivity","Verify resource URLs are correct",`Docs: ${i}/TROUBLESHOOTING.md#resource-loading`],FEATURE_NOT_SUPPORTED:["Check browser compatibility requirements","Consider using fallback features",`Docs: ${i}/TROUBLESHOOTING.md#browser-compatibility`]}[e]||["Check console for additional error details",`Docs: ${i}/TROUBLESHOOTING.md`,"Report issues: https://github.com/joshtol/emotive-engine/issues"]}log(){"warn"==("warning"===this.error.severity?"warn":"error")?console.warn(`[EmotiveMascot] ${this.error.type}: ${this.error.message}`,{context:this.error.context,recoveryActions:this.error.recoveryActions,timestamp:new Date(this.error.timestamp).toISOString()}):console.error(`[EmotiveMascot] ${this.error.type}: ${this.error.message}`,{context:this.error.context,recoveryActions:this.error.recoveryActions,timestamp:new Date(this.error.timestamp).toISOString()})}getDisplayMessage(){return`${this.error.type}: ${this.error.message}`}isRecoverable(){return this.error.recoveryActions&&this.error.recoveryActions.length>0}getSeverity(){return this.error.severity}toJSON(){return{success:this.success,error:this.error}}}const ml="INVALID_PARAMETER",pl="PERFORMANCE_DEGRADED",fl="FEATURE_NOT_SUPPORTED",yl="critical",bl="error",vl="warning",Ml="info";class wl{constructor(e={}){this.config={enableConsoleLogging:!1!==e.enableConsoleLogging,enableContextPreservation:!1!==e.enableContextPreservation,maxLogEntries:e.maxLogEntries||1e3,logLevel:e.logLevel||vl,...e},this.logs=[],this.errorCounts=new Map,this.contextHistory=new Map,this.startTime=Date.now()}logError(e,t={}){const i=this.createLogEntry(e,t);return this.storeLogEntry(i),this.updateErrorCounts(e.error.type),this.config.enableConsoleLogging&&this.shouldLog(e.error.severity)&&this.consoleLog(i),this.config.enableContextPreservation&&this.preserveContext(e.error.type,i),i}createLogEntry(e,t){return{id:this.generateLogId(),timestamp:Date.now(),relativeTime:Date.now()-this.startTime,type:e.error.type,message:e.error.message,severity:e.error.severity,context:{...e.error.context,...t,stackTrace:this.captureStackTrace(),userAgent:"undefined"!=typeof navigator?navigator.userAgent:"unknown",url:"undefined"!=typeof window?window.location.href:"unknown"},recoveryActions:e.error.recoveryActions,errorCount:this.getErrorCount(e.error.type)+1}}storeLogEntry(e){this.logs.push(e),this.logs.length>this.config.maxLogEntries&&this.logs.shift()}updateErrorCounts(e){const t=this.errorCounts.get(e)||0;this.errorCounts.set(e,t+1)}preserveContext(e,t){this.contextHistory.has(e)||this.contextHistory.set(e,[]);const i=this.contextHistory.get(e);i.push({timestamp:t.timestamp,context:t.context,message:t.message}),i.length>10&&i.shift()}consoleLog(e){const t=this.getConsoleMethod(e.severity),i=new Date(e.timestamp).toISOString();"warn"===t?console.warn(`[EmotiveMascot] ${i} ${e.type}: ${e.message}`,{severity:e.severity,context:e.context,recoveryActions:e.recoveryActions,errorCount:e.errorCount}):console.error(`[EmotiveMascot] ${i} ${e.type}: ${e.message}`,{severity:e.severity,context:e.context,recoveryActions:e.recoveryActions,errorCount:e.errorCount})}getConsoleMethod(e){switch(e){case yl:case bl:return"error";default:return"warn"}}shouldLog(e){const t={[yl]:4,[bl]:3,[vl]:2,[Ml]:1};return t[e]>=t[this.config.logLevel]}captureStackTrace(){try{throw new Error}catch(e){return e.stack||"Stack trace not available"}}generateLogId(){return`log_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}getErrorCount(e){return this.errorCounts.get(e)||0}getLogs(e={}){let t=[...this.logs];return e.type&&(t=t.filter(t=>t.type===e.type)),e.severity&&(t=t.filter(t=>t.severity===e.severity)),e.since&&(t=t.filter(t=>t.timestamp>=e.since)),e.limit&&(t=t.slice(-e.limit)),t}getErrorStatistics(){const e={totalErrors:this.logs.length,errorsByType:Object.fromEntries(this.errorCounts),errorsBySeverity:{},recentErrors:this.logs.slice(-10),uptime:Date.now()-this.startTime};return this.logs.forEach(t=>{e.errorsBySeverity[t.severity]=(e.errorsBySeverity[t.severity]||0)+1}),e}clearLogs(){this.logs=[],this.errorCounts.clear(),this.contextHistory.clear()}exportLogs(e="json"){if("json"===e)return JSON.stringify({logs:this.logs,statistics:this.getErrorStatistics(),exportTime:Date.now()},null,2);if("csv"===e)return[["timestamp","type","severity","message","errorCount"],...this.logs.map(e=>[new Date(e.timestamp).toISOString(),e.type,e.severity,e.message.replace(/"/g,'""'),e.errorCount])].map(e=>e.map(e=>`"${e}"`).join(",")).join("\n");throw new Error(`Unsupported export format: ${e}`)}}let Sl=null;function xl(e={}){return Sl||(Sl=new wl(e)),Sl}function Cl(){Sl=null}class kl{constructor(e={}){this.config={enableAutoOptimization:e.enableAutoOptimization||!1,performanceThreshold:e.performanceThreshold??e.criticalFPS??30,memoryThreshold:e.memoryThreshold||50,degradationSteps:e.degradationSteps||4,recoveryDelay:e.recoveryDelay||1e3,enableManualControls:!1!==e.enableManualControls,enableProgressiveEnhancement:!1!==e.enableProgressiveEnhancement,warningFPS:e.warningFPS||50,criticalFPS:e.criticalFPS??e.performanceThreshold??30,requiredGoodFrames:e.requiredGoodFrames||30,...e},this.errorLogger=xl(),this.degradationLevels=[{name:"optimal",particleLimit:50,audioEnabled:!0,fullEffects:!0,targetFPS:60,qualityLevel:1,canvasScale:1,animationComplexity:1,description:"Full features and effects",features:["particles","audio","fullEffects","animations","highQuality"]},{name:"reduced",particleLimit:25,audioEnabled:!0,fullEffects:!1,targetFPS:45,qualityLevel:.8,canvasScale:.9,animationComplexity:.8,description:"Reduced visual effects",features:["particles","audio","animations","mediumQuality"]},{name:"minimal",particleLimit:10,audioEnabled:!1,fullEffects:!1,targetFPS:30,qualityLevel:.6,canvasScale:.8,animationComplexity:.6,description:"Minimal visual effects, no audio",features:["particles","animations","lowQuality"]},{name:"emergency",particleLimit:5,audioEnabled:!1,fullEffects:!1,targetFPS:15,qualityLevel:.4,canvasScale:.7,animationComplexity:.4,description:"Emergency mode - basic animation only",features:["animations","particles"]}],this.currentLevel=0,this.lastDegradationTime=0,this.performanceHistory=[],this.maxHistorySize=30,this.availableFeatures=this.assessAvailableFeatures(),this.isMonitoring=!1,this.monitoringInterval=null,this.recoveryTimeout=null,this.consecutiveGoodFrames=0,this.requiredGoodFrames=this.config.requiredGoodFrames,this.manualOverride=null,this.disabledFeatures=new Set,this.enhancementHistory=[],this.capabilityTests=new Map}assessAvailableFeatures(){const e=ir.featureDetection.getFeatures(),{capabilities:t}=ir;return{audio:e.webAudio&&e.audioContext,particles:e.canvas2d,animations:e.requestAnimationFrame,performance:e.performance,fullQuality:"full"===t.level,reducedMotion:this.detectReducedMotion(),highContrast:this.detectHighContrast()}}detectReducedMotion(){try{return window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch{return!1}}detectHighContrast(){try{return window.matchMedia("(prefers-contrast: high)").matches}catch{return!1}}startMonitoring(){this.isMonitoring||(this.isMonitoring=!0,this.monitoringInterval=setInterval(()=>{this.checkPerformance()},1e3))}stopMonitoring(){this.isMonitoring&&(this.isMonitoring=!1,this.monitoringInterval&&(clearInterval(this.monitoringInterval),this.monitoringInterval=null),this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null))}checkPerformance(e={}){if(!this.config.enableAutoOptimization)return;const t=e.fps||60,i=e.memoryUsage||0;this.performanceHistory.push({fps:t,memoryUsage:i,timestamp:Date.now()}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift();const s=this.performanceHistory.reduce((e,t)=>e+t.fps,0)/this.performanceHistory.length,n=this.performanceHistory.reduce((e,t)=>e+t.memoryUsage,0)/this.performanceHistory.length,a=s<this.config.performanceThreshold||n>this.config.memoryThreshold;a&&this.canDegrade()?this.applyDegradation():!a&&s>1.1*this.config.performanceThreshold?(this.consecutiveGoodFrames++,this.consecutiveGoodFrames>=this.requiredGoodFrames&&this.canRecover()&&this.scheduleRecovery()):this.consecutiveGoodFrames=0}canDegrade(){const e=Date.now()-this.lastDegradationTime;return this.currentLevel<this.degradationLevels.length-1&&e>2e3}canRecover(){return this.currentLevel>0}applyDegradation(){if(!this.canDegrade())return;this.currentLevel++,this.lastDegradationTime=Date.now(),this.consecutiveGoodFrames=0;const e=this.getCurrentLevel();this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null),this.emit("degradationApplied",{level:e.name,index:this.currentLevel,reason:"performance",settings:e})}scheduleRecovery(){this.recoveryTimeout||(this.recoveryTimeout=setTimeout(()=>{this.applyRecovery(),this.recoveryTimeout=null},this.config.recoveryDelay))}applyRecovery(){if(!this.canRecover())return;this.currentLevel--,this.consecutiveGoodFrames=0;const e=this.getCurrentLevel();this.emit("recoveryApplied",{level:e.name,index:this.currentLevel,settings:e})}setLevel(e){let t;if("string"==typeof e){if(t=this.degradationLevels.findIndex(t=>t.name===e),-1===t)return!1}else{if("number"!=typeof e)return!1;t=Math.max(0,Math.min(this.degradationLevels.length-1,e))}const i=this.currentLevel;this.currentLevel=t;const s=this.getCurrentLevel();return this.emit("levelChanged",{previousLevel:this.degradationLevels[i].name,currentLevel:s.name,index:this.currentLevel,manual:!0,settings:s}),!0}getCurrentLevel(){return{...this.degradationLevels[this.currentLevel]}}getAllLevels(){return this.degradationLevels.map(e=>({...e}))}getAvailableFeatures(){return{...this.availableFeatures}}isFeatureAvailable(e){if(this.disabledFeatures.has(e))return!1;const t=this.getCurrentLevel();switch(e){case"audio":return this.availableFeatures.audio&&t.audioEnabled;case"particles":return this.availableFeatures.particles&&t.particleLimit>0;case"fullEffects":return this.availableFeatures.fullQuality&&t.fullEffects;case"animations":return this.availableFeatures.animations;default:return this.availableFeatures[e]||!1}}getRecommendedSettings(){const e=this.getCurrentLevel(),t=ir.browserOptimizations.getOptimizations();return{maxParticles:Math.min(e.particleLimit,t.particleLimit),enableAudio:e.audioEnabled&&this.availableFeatures.audio,enableFullEffects:e.fullEffects&&this.availableFeatures.fullQuality,targetFPS:e.targetFPS,qualityLevel:e.qualityLevel,reducedMotion:this.availableFeatures.reducedMotion,highContrast:this.availableFeatures.highContrast}}getPerformanceStats(){if(0===this.performanceHistory.length)return{avgFPS:0,avgMemory:0,samples:0,currentLevel:this.getCurrentLevel().name};const e=this.performanceHistory.reduce((e,t)=>e+t.fps,0)/this.performanceHistory.length,t=this.performanceHistory.reduce((e,t)=>e+t.memoryUsage,0)/this.performanceHistory.length,i=Math.min(...this.performanceHistory.map(e=>e.fps)),s=Math.max(...this.performanceHistory.map(e=>e.fps));return{avgFPS:Math.round(10*e)/10,avgMemory:Math.round(10*t)/10,minFPS:i,maxFPS:s,samples:this.performanceHistory.length,currentLevel:this.getCurrentLevel().name,consecutiveGoodFrames:this.consecutiveGoodFrames,isMonitoring:this.isMonitoring}}reset(){this.currentLevel=0,this.performanceHistory=[],this.consecutiveGoodFrames=0,this.lastDegradationTime=0,this.recoveryTimeout&&(clearTimeout(this.recoveryTimeout),this.recoveryTimeout=null),this.emit("reset",{level:this.getCurrentLevel().name})}emit(e,t){this.onEvent&&this.onEvent(e,t)}setEventCallback(e){this.onEvent=e}disableFeature(e){if(!this.config.enableManualControls)return gl.failure(fl,"Manual controls are disabled",{feature:e,enableManualControls:this.config.enableManualControls});const t=["particles","audio","fullEffects","animations"];return t.includes(e)?(this.disabledFeatures.add(e),this.errorLogger.logError(gl.warning(fl,`Feature manually disabled: ${e}`,{feature:e,disabledFeatures:Array.from(this.disabledFeatures)})),this.emit("featureDisabled",{feature:e,manual:!0}),gl.success({feature:e,disabled:!0})):gl.failure(ml,`Invalid feature: ${e}`,{feature:e,validFeatures:t})}enableFeature(e){return this.config.enableManualControls?this.availableFeatures[e]?(this.disabledFeatures.delete(e),this.emit("featureEnabled",{feature:e,manual:!0}),gl.success({feature:e,enabled:!0})):gl.failure(fl,`Feature not available in browser: ${e}`,{feature:e,availableFeatures:this.availableFeatures}):gl.failure(fl,"Manual controls are disabled",{feature:e,enableManualControls:this.config.enableManualControls})}setManualOverride(e){return this.config.enableManualControls?null===e?(this.manualOverride=null,this.emit("manualOverrideRemoved",{}),gl.success({override:null})):this.setLevel(e)?(this.manualOverride=this.currentLevel,this.emit("manualOverrideSet",{level:this.getCurrentLevel().name}),gl.success({override:this.getCurrentLevel().name})):gl.failure(ml,"Failed to set manual override",{level:e}):gl.failure(fl,"Manual controls are disabled")}testCapability(e,t){if(!this.config.enableProgressiveEnhancement)return gl.failure(fl,"Progressive enhancement is disabled");try{const i=performance.now(),s=t(),n=performance.now()-i,a={feature:e,supported:Boolean(s),duration:n,timestamp:Date.now()};return this.capabilityTests.set(e,a),gl.success(a)}catch(t){const i={feature:e,supported:!1,error:t.message,timestamp:Date.now()};return this.capabilityTests.set(e,i),this.errorLogger.logError(gl.failure(fl,`Capability test failed: ${e}`,{error:t.message,feature:e})),gl.failure(fl,`Capability test failed: ${t.message}`,i)}}getCapabilityTests(){return Object.fromEntries(this.capabilityTests)}applyProgressiveEnhancement(){if(!this.config.enableProgressiveEnhancement)return gl.failure(fl,"Progressive enhancement is disabled");const e=[],t=this.getCurrentLevel();if(this.availableFeatures.audio&&t.audioEnabled){const t=this.capabilityTests.get("advancedAudio");t&&t.supported&&e.push("advancedAudio")}if(this.availableFeatures.particles&&t.particleLimit>0){const t=this.capabilityTests.get("advancedParticles");t&&t.supported&&e.push("advancedParticles")}if(this.availableFeatures.animations){const t=this.capabilityTests.get("advancedAnimations");t&&t.supported&&e.push("advancedAnimations")}return this.enhancementHistory.push({timestamp:Date.now(),level:t.name,enhancements:[...e]}),this.emit("progressiveEnhancementApplied",{enhancements:e}),gl.success({enhancements:e})}getFeatureAvailabilityReport(){const e=this.getCurrentLevel(),t={currentLevel:e.name,availableFeatures:{},disabledFeatures:Array.from(this.disabledFeatures),manualOverride:this.manualOverride,browserCapabilities:this.availableFeatures,capabilityTests:this.getCapabilityTests(),recommendations:[]};for(const i of["particles","audio","fullEffects","animations"]){const s=this.isFeatureAvailable(i),n=this.availableFeatures[i],a=e.features.includes(i),r=this.disabledFeatures.has(i);t.availableFeatures[i]={available:s,browserSupported:n,levelSupported:a,manuallyDisabled:r,reason:s?null:this.getFeatureUnavailableReason(i)},s||!n||r||a||t.recommendations.push(`${i} disabled due to performance level - consider improving performance`)}return t}getFeatureUnavailableReason(e){if(!this.availableFeatures[e])return"Browser does not support this feature";if(this.disabledFeatures.has(e))return"Feature manually disabled";const t=this.getCurrentLevel();return t.features.includes(e)?"Unknown reason":`Feature disabled at ${t.name} performance level`}checkPerformanceEnhanced(e={}){try{return null!==this.manualOverride?gl.success({message:"Performance check skipped - manual override active",manualOverride:this.getCurrentLevel().name}):(this.checkPerformance(e),gl.success({message:"Performance check completed",currentLevel:this.getCurrentLevel().name,metrics:this.getPerformanceStats()}))}catch(t){return this.errorLogger.logError(gl.failure(pl,"Performance check failed",{error:t.message,metrics:e})),gl.failure(pl,"Performance check failed",{error:t.message})}}getDegradationStatus(){return{currentLevel:this.getCurrentLevel(),availableFeatures:this.getAvailableFeatures(),featureReport:this.getFeatureAvailabilityReport(),performanceStats:this.getPerformanceStats(),config:{enableAutoOptimization:this.config.enableAutoOptimization,enableManualControls:this.config.enableManualControls,enableProgressiveEnhancement:this.config.enableProgressiveEnhancement,performanceThreshold:this.config.performanceThreshold,memoryThreshold:this.config.memoryThreshold},history:{performance:this.performanceHistory.slice(-10),enhancements:this.enhancementHistory.slice(-5)}}}destroy(){this.stopMonitoring(),this.performanceHistory=[],this.enhancementHistory=[],this.capabilityTests.clear(),this.disabledFeatures.clear(),this.onEvent=null,this.manualOverride=null}}class Pl{constructor(e={}){const{mascot:t=null,onError:i}=e;this.mascot=t,this._onError=i??(e=>{"production"!==process.env.NODE_ENV&&console.error("SiteController error:",e)})}updateMascot(e){return this.mascot=e,this}get positionController(){return this.mascot?.positionController??null}getElementTargeting(){return this.positionController?.getElementTargeting?.()??null}moveToElement(e,t={}){return this.moveToElementWithPath(e,[],"center",t.offset??{x:0,y:0},t)}moveToElementWithPath(e,t=[],i="center",s={x:0,y:0},n={}){const a=this.positionController;if(!a)return;const r=a.getElementTargeting?.(),o=n.speed??320,l=n.easing??"easeInOutCubic",h=n.coordinateSystem??"viewport";if(r?.moveToElementWithPath)try{return r.moveToElementWithPath(e,t,i,s,{coordinateSystem:h,speed:o,easing:l})}catch(e){this._handleError(e)}a.setOffset&&a.setOffset(s.x,s.y,0)}setOffset(e,t,i=0){try{this.positionController?.setOffset?.(e,t,i)}catch(e){this._handleError(e)}}getOffset(){try{return this.positionController?.getOffset?.()??{x:0,y:0}}catch(e){return this._handleError(e),{x:0,y:0}}}setEmotion(e){try{this.mascot?.setEmotion?.(e)}catch(e){this._handleError(e)}}express(e,t={}){try{if(t.chain&&this.mascot?.chain)return void this.mascot.chain(e);this.mascot?.express?.(e)}catch(e){this._handleError(e)}}stop(){try{const e=this.positionController;e?.stopCurrentPath?.(),e?.stop?.(),this.mascot?.pause?.()}catch(e){this._handleError(e)}}play(){try{this.mascot?.play?.()}catch(e){this._handleError(e)}}destroy(){this.stop(),this.mascot=null}_handleError(e){e instanceof Error?this._onError(e):this._onError(new Error(String(e)))}}const Tl="3.4.0",El="Emotive Engine",Al={rhythmSync:!0,grooveTemplates:!0,gestureBlending:!0,audioReactive:!0,particleSystem:!0,accessibility:!0,mobileOptimization:!0,performanceMonitoring:!0};var Dl=Object.freeze({__proto__:null,AnimationController:Ga,AnimationLoopManager:ha,AnimationPriority:la,CanvasManager:Ps,ContextStateManager:Jo,EmotiveRenderer:ya,EmotiveStateMachine:Zs,ErrorTracker:so,EventManager:ws,GradientCache:Dn,PerformanceMonitor:Ko,StateStore:No,animationLoopManager:ca,engineState:Qo,errorTracker:no,eventManager:Ss,gradientCache:_n,performanceMonitor:Zo}),_l=Object.freeze({__proto__:null,AudioAnalyzer:mr,AudioLevelProcessor:Ha,IdleBehavior:va,ParticleSystem:cn,SoundSystem:La}),Il=Object.freeze({__proto__:null,EMOTIONAL_COLORS:Os,EMOTIONAL_COLORS_RGB:Ls,UNDERTONE_SATURATION:Bs,adjustBrightness:function(e,t){const i=Ts(e),s=As(i.r,i.g,i.b);s.l=Math.max(0,Math.min(100,s.l*t));const n=Ds(s.h,s.s,s.l);return Es(n.r,n.g,n.b)},adjustSaturation:Is,applyUndertoneSaturation:zs,applyUndertoneSaturationToArray:Fs,getContrastRatio:function(e,t){const i=Rs(e),s=Rs(t);return(Math.max(i,s)+.05)/(Math.min(i,s)+.05)},getLuminance:Rs,getUndertoneSaturationFactor:function(e){return e&&Bs[e.toLowerCase()]||1},hexToRgb:Ts,hexToRgba:function(e,t=1){const i=Ts(e);return`rgba(${i.r}, ${i.g}, ${i.b}, ${t})`},hslToRgb:Ds,interpolateHsl:_s,interpolateRgb:function(e,t,i){const s=Ts(e),n=Ts(t);return Es(Math.round(s.r+(n.r-s.r)*i),Math.round(s.g+(n.g-s.g)*i),Math.round(s.b+(n.b-s.b)*i))},rgbToHex:Es,rgbToHsl:As});export{ja as AccessibilityManager,Ga as AnimationController,ha as AnimationLoopManager,la as AnimationPriority,mr as AudioAnalyzer,Oa as AudioLayerManager,Ha as AudioLevelProcessor,Ps as CanvasManager,Jo as ContextStateManager,kl as DegradationManager,El as ENGINE_NAME,Tr as EmotionDynamics,bo as EmotiveMascot,Xo as EmotiveMascotPublic,ya as EmotiveRenderer,Zs as EmotiveStateMachine,e as ErrorBoundary,wl as ErrorLogger,so as ErrorTracker,ws as EventManager,Al as FEATURES,ol as FeatureFlags,vi as GESTURE_REGISTRY,ki as GESTURE_TYPES,ba as GazeTracker,Dn as GradientCache,vr as GrooveTemplates,ao as HealthCheck,va as IdleBehavior,el as LazyLoader,$a as MobileOptimization,cn as ParticleSystem,Ko as PerformanceMonitor,nn as RhythmInputEvaluator,Pl as SiteController,La as SoundSystem,No as StateStore,dl as Timeline,ul as TimelineSection,mn as UNDERTONE_MODIFIERS,Tl as VERSION,ca as animationLoopManager,Ii as applyGesture,ir as browserCompatibility,Xo as default,i as emotionPluginAdapter,Qo as engineState,no as errorTracker,Ss as eventManager,ll as featureFlags,S as gesturePluginAdapter,b as getBlendedRhythmModifiers,tr as getBrowserCompatibility,l as getEmotion,f as getEmotionGestures,y as getEmotionRhythmModifiers,h as getEmotionVisualParams,xl as getErrorLogger,cl as getFeatureVariant,Ai as getGesture,_n as gradientCache,g as hasEmotion,ro as healthCheck,Za as initializeBrowserCompatibility,Di as isBlendingGesture,hl as isFeatureEnabled,_i as isOverrideGesture,il as lazyLoad,tl as lazyLoader,u as listEmotions,Ri as listGestures,gs as particleBehaviorPluginAdapter,Zo as performanceMonitor,Xa as polyfillPerformanceNow,Ya as polyfillRequestAnimationFrame,Na as polyfillWebAudio,nl as prefetchModules,sl as preloadModules,Cl as resetErrorLogger};
|
|
2
2
|
//# sourceMappingURL=mascot.js.map
|