@joshtol/emotive-engine 3.4.1 โ 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 +0 -4
- 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/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).EmotiveMascotLean={})}(this,function(t){"use strict";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(t,e,i=null){return(...s)=>{try{const n=t(...s);return n&&"function"==typeof n.then?n.catch(t=>(this.logError(t,e),null!==i?i:this.getDefault(e))):n}catch(t){return this.logError(t,e),null!==i?i:this.getDefault(e)}}}logError(t,e){const i={timestamp:(new Date).toISOString(),context:e,message:t.message,stack:t.stack};this.errors.push(i);const s=this.errorCounts.get(e)||0;this.errorCounts.set(e,s+1),this.errors.length>this.maxErrors&&this.errors.shift()}getDefault(t){const e={"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(e,t)?e[t]:null}validateInput(t,e,i){try{switch(e){case"emotion":return["neutral","joy","sadness","anger","fear","surprise","disgust","love","euphoria"].includes(t)?t:i;case"undertone":return null===t||["nervous","confident","tired","intense","subdued"].includes(t)?t:null;case"gesture":return["bounce","pulse","shake","spin","nod","tilt","expand","contract","flash","drift"].includes(t)?t:i;case"number":return"number"!=typeof t||isNaN(t)?i:t;case"string":return"string"==typeof t?t:i;case"boolean":return"boolean"==typeof t?t:i;default:return null!=t?t:i}}catch(t){return this.logError(t,"input-validation"),i}}hasExceededThreshold(t,e=5){return(this.errorCounts.get(t)||0)>=e}getErrorStats(){return{totalErrors:this.errors.length,errorsByContext:Object.fromEntries(this.errorCounts),recentErrors:this.errors.slice(-5)}}clearErrors(){this.errors=[],this.errorCounts.clear()}async attemptRecovery(t,e,i=3){let s=0;for(;s<i;)try{return await e()}catch(e){if(s++,this.logError(e,`recovery-${t}-attempt-${s}`),s>=i)throw new Error(`Recovery failed for ${t} after ${i} attempts`);await new Promise(t=>setTimeout(t,100*Math.pow(2,s)))}}}const i=new Map;var s={registerPluginEmotion:function(t,e){return!!e.color&&(e.name||(e.name=t),e.visual||(e.visual={primaryColor:e.color,particleCount:e.particleCount||15,particleSize:e.particleSize||{min:2,max:6}}),e.modifiers||(e.modifiers={speed:1,amplitude:1,intensity:1}),i.set(t,e),!0)},unregisterPluginEmotion:function(t){return!!i.has(t)&&(i.delete(t),!0)},getPluginEmotion:function(t){return i.get(t)||null},getAllPluginEmotions:function(){return Array.from(i.keys())},clearPluginEmotions:function(){i.clear()},createLegacyAdapter:function(t){return{name:t.name||"unknown",emoji:t.emoji||"๐",color:t.primaryColor||t.color||"#7B68EE",energy:t.energy||"medium",visual:{primaryColor:t.primaryColor||t.color||"#7B68EE",secondaryColor:t.secondaryColor,particleCount:t.particleCount||t.particleRate||15,particleSize:t.particleSize||{min:2,max:6},glowIntensity:t.glowIntensity||.5,trailLength:t.trailLength||5,pulseRate:t.pulseRate||t.breathRate||1},particles:{behavior:t.particleBehavior||"ambient",density:t.particleDensity||"medium",speed:t.particleSpeed||"normal"},modifiers:{speed:t.speedMultiplier||1,amplitude:t.amplitudeMultiplier||1,intensity:t.intensityMultiplier||1,smoothness:t.smoothnessMultiplier||1},gestures:t.gestures||[],transitions:t.transitions||{}}}},n={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 t=this.threatLevel||0,e=Math.round(107+113*t),i=Math.round(70+-32*t),s=Math.round(193+-66*t),n=t=>t.toString(16).padStart(2,"0");return`#${n(e)}${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}},r={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(t){const e=t.time||Date.now(),i=.5*Math.sin(6e-4*e)+.5;return{scaleX:1-.02*i,scaleY:1-.02*i,eyeOpenness:.85,eyeExpression:"serene",pupilOffset:{x:2*Math.sin(3e-4*e),y:1*Math.cos(4e-4*e)},glowPulse:.95+.05*i}},updateParticle(t,e){t.x+=.1*Math.sin(.001*t.life),t.y-=.02*e,t.opacity=.3*Math.sin(.002*t.life)+.2,t.size=t.baseSize*(1+.2*Math.sin(.001*t.life))},renderCore:(t,e,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,o={happy:"joy",peaceful:"calm",curious:"surprise",frustrated:"anger",sad:"sadness",excitement:"excited"};function h(t){t.name&&a.set(t.name,t)}function l(t){const e=o[t]||t,i=a.get(e);return i||(s.getPluginEmotion(e)||null)}function c(t){const e=l(t);if(!e)return l("neutral").visual;if(!e.visual)return{};const{visual:i}=e,s={};for(const t in i)"function"!=typeof i[t]&&(s[t]=i[t]);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 u(t){const e=l(t);return e?e.modifiers:l("neutral").modifiers}function d(){return[...Array.from(a.keys()),...s.getAllPluginEmotions()]}function p(){const t={};return a.forEach((e,i)=>{t[i]=e}),t}function m(t){const e=o[t]||t;return a.has(e)||null!==s.getPluginEmotion(e)}function g(t,e){o[t]=e}function f(t,e){const i=l(t),s=l(e);return i&&s?s.transitions&&s.transitions[t]?s.transitions[t]:{duration:1e3,easing:"ease-in-out",gesture:s.transitions?.defaultGesture||null}:{duration:1e3,easing:"ease-in-out"}}function y(t){const e=l(t);return e?.gestures||[]}function M(t){const e=l(t);return e?.rhythmModifiers??{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}}function b(t){if(!t||0===t.length)return{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0};if(1===t.length){const e=M(t[0].emotion),i=t[0].intensity;return{windowMultiplier:1+(e.windowMultiplier-1)*i,visualNoise:e.visualNoise*i,inputDelay:e.inputDelay*i,tempoShift:e.tempoShift*i}}let e=0;for(let i=1;i<t.length;i++)t[i].intensity>t[e].intensity&&(e=i);const i={windowMultiplier:0,visualNoise:0,inputDelay:0,tempoShift:0},s=t.filter((t,i)=>i!==e),n=s.length>0?.25/s.length:0,r=M(t[e].emotion),a=t[e].intensity;i.windowMultiplier+=.75*(1+(r.windowMultiplier-1)*a),i.visualNoise+=r.visualNoise*a*.75,i.inputDelay+=r.inputDelay*a*.75,i.tempoShift+=r.tempoShift*a*.75;for(const t of s){const e=M(t.emotion),s=t.intensity;i.windowMultiplier+=(1+(e.windowMultiplier-1)*s)*n,i.visualNoise+=e.visualNoise*s*n,i.inputDelay+=e.inputDelay*s*n,i.tempoShift+=e.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:t=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"neutral",pupilOffset:{x:0,y:0}}),renderCore:(t,e,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:t=>({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}},n,{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:t=>({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}},r].forEach(t=>{t&&t.name&&a.set(t.name,t)});var w={registerEmotion:h,getEmotion:l,getEmotionVisualParams:c,getEmotionParams:c,getEmotionModifiers:u,getEmotionRhythmModifiers:M,getBlendedRhythmModifiers:b,listEmotions:d,getAllEmotions:p,hasEmotion:m,addEmotionAlias:g,getTransitionParams:f,getEmotionGestures:y,pluginAdapter:s},v=Object.freeze({__proto__:null,addEmotionAlias:g,default:w,getAllEmotions:p,getBlendedRhythmModifiers:b,getEmotion:l,getEmotionGestures:y,getEmotionModifiers:u,getEmotionRhythmModifiers:M,getEmotionVisualParams:c,getTransitionParams:f,hasEmotion:m,listEmotions:d,pluginAdapter:s,registerEmotion:h});const S=new Map;var k={registerPluginGesture:function(t,e){return!(!e.apply&&!e.type||(e.name||(e.name=t),e.type||(e.type="blending"),S.set(t,e),0))},unregisterPluginGesture:function(t){return!!S.has(t)&&(S.delete(t),!0)},getPluginGesture:function(t){return S.get(t)||null},getAllPluginGestures:function(){return Array.from(S.keys())},clearPluginGestures:function(){S.clear()},createLegacyAdapter:function(t){return{name:t.name||"unknown",type:t.type||"blending",emoji:t.emoji||"๐",description:t.description||"Plugin gesture",config:t.config||{},apply(e,i,s,n,r,a){t.animate?t.animate(e,i,s,n,r,a):t.apply&&t.apply(e,i,s,n,r,a)},cleanup:t.cleanup||function(t){t.gestureData&&t.gestureData[this.name]&&delete t.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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.breathe={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),phaseOffset:.2*Math.random()-.1}},apply(t,e,i,s,n,r){t.gestureData?.breathe||this.initialize(t,i,n,r);const a={...this.config,...i},o=(Math.sin(e*Math.PI*2*a.breathRate)+1)/2,h=100*(t.scaleFactor||1),l=a.inhaleRadius*h,c=a.exhaleRadius*h,u=c+(l-c)*o,d=t.x-n,p=t.y-r,m=Math.sqrt(d*d+p*p),g=u-m,f=.05*(i.strength||.8)*s;if(m>0){const e=d/m*g*f,n=p/m*g*f;t.vx+=e,t.vy+=n;const r=a.spiralStrength*s*(i.strength||1),h=-p/m,l=d/m;t.vx+=h*r*o,t.vy+=l*r*o}t.vx*=.98,t.vy*=.98},cleanup(t){t.gestureData?.breathe&&delete t.gestureData.breathe},"3d":{evaluate(t,e){const i=(e.config||{}).breathRate||.3,s=Math.sin(t*Math.PI*2*i);let n=1;if(t>.8){const e=(t-.8)/(1-.8);n=1-e*e*e}const r=.2*s*n;return{position:[0,.05*s*n,0],rotation:[0,0,0],scale:1+.35*s*n,glowIntensity:1+r,glowBoost:Math.max(0,2*r)}}}},E={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.expand={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.expand?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.expand,o={...this.config,...i},h=o.strength||1,l=1+(o.scaleTarget-1)*e*h,c=a.baseRadius*l,u=n+Math.cos(a.angle)*c,d=r+Math.sin(a.angle)*c,p=u-t.x,m=d-t.y;t.vx+=.8*p*s,t.vy+=.8*m*s,t.vx*=.95,t.vy*=.95},cleanup(t){t.gestureData?.expand&&delete t.gestureData.expand},"3d":{evaluate(t,e){const i={...this.config,...e},s=i.strength||3;return{position:[0,0,0],rotation:[0,0,0],scale:1+t*(i.scaleAmount||3)*(s/3),glowIntensity:1+.25*t,glowBoost:.8*t}}}},B={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.contract={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.contract?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.contract,o={...this.config,...i},h=o.strength||1,l=1-(1-o.scaleTarget)*e*h,c=a.baseRadius*l,u=n+Math.cos(a.angle)*c,d=r+Math.sin(a.angle)*c,p=u-t.x,m=d-t.y;t.vx+=.5*p*s,t.vy+=.5*m*s,t.vx*=.95,t.vy*=.95},cleanup(t){t.gestureData?.contract&&delete t.gestureData.contract},"3d":{evaluate(t,e){const i={...this.config,...e},s=i.strength||2.5,n=i.scaleTarget||.2,r=1-t*(1-n)*(s/2.5),a=1-.15*t;return{position:[0,0,0],rotation:[0,0,0],scale:Math.max(n,r),glowIntensity:a}}}},A={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.atan2(r,n);t.gestureData.pulse={baseDistance:a,angle:o,startX:t.x,startY:t.y,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.pulse?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.pulse,o={...this.config,...i},h=i.strength||1,l=this.easeInOutSine(e);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 p=l*u*2%2;c=o.holdPeak>0&&p>1-o.holdPeak&&p<1+o.holdPeak?1:Math.sin(l*Math.PI*2*u);const m=c*d*h*t.scaleFactor,g=a.baseDistance+m,f=n+Math.cos(a.angle)*g,y=r+Math.sin(a.angle)*g,M=.15*s;if(t.vx+=(f-t.x)*M*.1,t.vy+=(y-t.y)*M*.1,e>.9){const i=1-10*(e-.9);t.vx*=.9+.1*i,t.vy*=.9+.1*i}},cleanup(t){t.gestureData?.pulse&&delete t.gestureData.pulse},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i=e||{},s=i.frequency||1,n=i.strength||.15,r=i.scaleAmount||.2,a=i.glowAmount||.3,o=-(Math.cos(Math.PI*t)-1)/2,h=Math.sin(o*Math.PI*2*s);return{position:[0,0,0],rotation:[0,0,0],scale:1+h*r*n,glowIntensity:1+Math.max(-.3,Math.min(.3,h*a*n*2)),glowBoost:Math.max(0,.8*h)}}}},C={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.amplitude||this.config.amplitude,h=a.frequency||this.config.frequency,l=a.strength||this.config.strength,c=Math.sin(e*Math.PI*2*h)*o;t.vx+=.01*c*s*l,t.vy+=.5*Math.cos(e*Math.PI*4)*s*l},cleanup(t){},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.amplitude||this.config.amplitude;const n=i.frequency||this.config.frequency,r=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const a=Math.sin(t*Math.PI*2*n),o=s*r*.3*.01,h=.15*a*r,l=.08*a*r;return{position:[a*o,.3*Math.cos(t*Math.PI*4)*o,Math.sin(t*Math.PI*n)*o*.5],rotation:[0,l,h],scale:1}}}},T={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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.float||(t.gestureData.float={originalSize:t.size,originalOpacity:t.opacity||1});const a={...this.config,...i};let o=a.amplitude||this.config.amplitude,h=a.wobbleAmount||this.config.wobbleAmount;const l=a.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1,h*=i.rhythmModulation.wobbleMultiplier||1);const c=Math.sin(e*Math.PI*4)*h;t.vy-=.01*o*s*l*(1-.5*e),t.vx+=.01*c*s*l,t.size=t.baseSize*(1+.1*e),t.opacity=1-.3*e},cleanup(t){t.gestureData?.float?(t.opacity=t.gestureData.float.originalOpacity,t.size=t.gestureData.float.originalSize,delete t.gestureData.float):(t.opacity=1,t.size=t.baseSize),t.vx*=.5,t.vy*=.5},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.amplitude||this.config.amplitude,n=i.wobbleAmount||this.config.wobbleAmount;const r=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1,n*=e.rhythmModulation.wobbleMultiplier||1);const a=Math.sin(t*Math.PI),o=s*a*r*.005,h=Math.sin(t*Math.PI*4)*n*.3*.005,l=Math.sin(t*Math.PI)*Math.PI*.5*r,c=Math.sin(t*Math.PI);return{position:[h,o,0],rotation:[c*Math.sin(t*Math.PI*2)*.1,l,c*Math.cos(t*Math.PI*3)*.08],scale:1+.1*a}}}};const P={left:{x:-1,y:0},right:{x:1,y:0},up:{x:0,y:1},down:{x:0,y:-1}};function D(t){return t.charAt(0).toUpperCase()+t.slice(1)}function R(t){const e=P[t];if(!e)throw new Error(`Invalid float direction: ${t}`);const i="up"===t||"down"===t;return{name:`float${D(t)}`,emoji:"up"===t?"๐":"down"===t?"๐":"left"===t?"๐ฌ๏ธ":"๐จ",type:"blending",description:`Gentle floating ${t}`,config:{duration:2e3,amplitude:80,wobbleAmount:20,strength:1,direction:t},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(t,s,n,r,a,o){t.gestureData||(t.gestureData={}),t.gestureData.float||(t.gestureData.float={originalSize:t.size,originalOpacity:t.opacity||1});const h={...this.config,...n};let l=h.amplitude||80,c=h.wobbleAmount||20;const u=h.strength||1;n.rhythmModulation&&(l*=n.rhythmModulation.amplitudeMultiplier||1,l*=n.rhythmModulation.accentMultiplier||1,c*=n.rhythmModulation.wobbleMultiplier||1);const d=Math.sin(s*Math.PI*4)*c,p=.01*l*r*u*(1-.5*s);i?(t.vy+=e.y*p,t.vx+=.01*d*r*u):(t.vx+=e.x*p,t.vy+=.01*d*r*u),t.size=t.baseSize*(1+.1*s),t.opacity=1-.3*s},cleanup(t){t.gestureData?.float?(t.opacity=t.gestureData.float.originalOpacity,t.size=t.gestureData.float.originalSize,delete t.gestureData.float):(t.opacity=1,t.size=t.baseSize),t.vx*=.5,t.vy*=.5},"3d":{evaluate(t,s){const n=s||{};let r=n.amplitude||80,a=n.wobbleAmount||20;const o=n.strength||1;s.rhythmModulation&&(r*=s.rhythmModulation.amplitudeMultiplier||1,r*=s.rhythmModulation.accentMultiplier||1,a*=s.rhythmModulation.wobbleMultiplier||1);const h=Math.sin(t*Math.PI),l=r*h*o*.005,c=Math.sin(t*Math.PI*4)*a*.3*.005,u=Math.sin(t*Math.PI)*Math.PI*.5*o,d=Math.sin(t*Math.PI),p=d*Math.sin(t*Math.PI*2)*.1,m=d*Math.cos(t*Math.PI*3)*.08,g=1+.1*h;let f=0,y=0;return i?(y=e.y*l,f=c):(f=e.x*l,y=c),{cameraRelativePosition:[f,y,0],rotation:[p,u,m],scale:g}}}}}var F=R("up"),z=R("down"),q=R("left"),O=R("right"),j={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.lean={startX:t.x,startY:t.y,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.lean?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e),l=a.frequency||this.config.frequency;let c=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI*l),d="left"===a.direction?-1:1;if(t.vx+=u*c*.015*s*d,t.vy+=u*c*.01*s*d*.5,e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.lean&&delete t.gestureData.lean},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||10,n=i.frequency||1,r=i.strength||.7,a=i.direction||"right",o=.003*s*r,h=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,l=Math.sin(h*Math.PI*n),c="left"===a?-1:1;return{position:[l*o*c,0,0],rotation:[0,0,.35*l*c],scale:1}}}};function I(t){if("left"!==t&&"right"!==t)throw new Error(`Invalid lean direction: ${t}. Only 'left' and 'right' are supported.`);const e=P[t];return{name:`lean${D(t)}`,emoji:"left"===t?"โ๏ธ":"โ๏ธ",type:"blending",description:`Lean ${t} with smooth return`,config:{duration:800,amplitude:10,frequency:1,strength:.7,direction:t},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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.lean={startX:t.x,startY:t.y,initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.lean?.initialized||this.initialize(t,s);const o={...this.config,...s},h=o.strength||.7,l=this.easeInOutCubic(i);let c=o.amplitude*h*t.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI*o.frequency);if(t.vx+=u*c*.015*n*e.x,t.vy+=u*c*.01*n*e.x*.5,i>.9){const e=1-10*(i-.9);t.vx*=.95+.05*e,t.vy*=.95+.05*e}},cleanup(t){t.gestureData?.lean&&delete t.gestureData.lean},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||10,r=s.frequency||1,a=.003*n*(s.strength||.7),o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI*r),l=.35*h*e.x;return{cameraRelativePosition:[h*a*e.x,0,0],cameraRelativeRotation:[0,0,l],scale:1}}}}}var $=I("left"),L=I("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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.jitter||(t.gestureData.jitter={originalSize:t.size});const a={...this.config,...i};let o=a.intensity||this.config.intensity;const h=a.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1);const l=(Math.random()-.5)*o*h,c=(Math.random()-.5)*o*h,u=1-.5*e;t.vx+=.1*l*s*u,t.vy+=.1*c*s*u,t.size=t.baseSize*(1+.1*(Math.random()-.5))},cleanup(t){t.gestureData?.jitter?(t.size=t.gestureData.jitter.originalSize,delete t.gestureData.jitter):t.size=t.baseSize,t.vx*=.7,t.vy*=.7},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.intensity||this.config.intensity;const n=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const r=Math.sin(t*Math.PI),a=s*n*.002*r;return{position:[(Math.random()-.5)*a,(Math.random()-.5)*a,(Math.random()-.5)*a],rotation:[.005*(Math.random()-.5)*r,.005*(Math.random()-.5)*r,.005*(Math.random()-.5)*r],scale:1+.02*(Math.random()-.5)*r}}}},_={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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.twitch||(t.gestureData.twitch={twitchOffset:{x:0,y:0},targetOffset:{x:0,y:0},isTwitching:!1,twitchTimer:0,cooldownTimer:0,lastTwitch:0});const a=t.gestureData.twitch,{config:o}=this;let h=i.intensity||o.intensity;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1);const l=Date.now();if(!a.isTwitching&&a.cooldownTimer<=0&&Math.random()<(i.frequency||o.frequency)){a.isTwitching=!0,a.twitchTimer=o.duration,a.cooldownTimer=o.recovery;const t=Math.random()*Math.PI*2,e=.5*o.maxOffset+Math.random()*(.5*o.maxOffset);a.targetOffset={x:Math.cos(t)*e*h/8,y:Math.sin(t)*e*h/8},a.lastTwitch=l}if(a.cooldownTimer>0&&(a.cooldownTimer-=16*s),a.isTwitching)if(a.twitchTimer-=16*s,a.twitchTimer>0){const{sharpness:t}=o;a.twitchOffset.x+=(a.targetOffset.x-a.twitchOffset.x)*t,a.twitchOffset.y+=(a.targetOffset.y-a.twitchOffset.y)*t}else a.isTwitching=!1;else a.twitchOffset.x*=.85,a.twitchOffset.y*=.85;t.vx+=a.twitchOffset.x*s*.5,t.vy+=a.twitchOffset.y*s*.5,Math.random()<.1&&(t.vx+=(Math.random()-.5)*h*.3,t.vy+=(Math.random()-.5)*h*.3)},cleanup(t){t.gestureData?.twitch&&delete t.gestureData.twitch},"3d":{evaluate(t,e){const i=e.config||{};let s=.6*(i.intensity||8);const n=i.maxOffset||15,r=i.frequency||.08;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const a=9999*Math.floor(10*t),o=t=>{const e=1e4*Math.sin(a+t);return e-Math.floor(e)};if(o(0)<3*r){const t=o(1)*Math.PI*2,e=n*s/8*.003;return{position:[Math.cos(t)*e*o(2),Math.sin(t)*e*o(3),(o(4)-.5)*e],rotation:[.12*(o(5)-.5),.12*(o(6)-.5),.12*(o(7)-.5)],scale:1+.06*(o(8)-.5)}}{const t=.3;return{position:[(o(10)-.5)*t,(o(11)-.5)*t,(o(12)-.5)*t],rotation:[.006*(o(13)-.5),.006*(o(14)-.5),.006*(o(15)-.5)],scale:1}}}}},H={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.vibrate={timer:0,seed:1e3*Math.random(),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.vibrate?.initialized||this.initialize(t,i);const a=t.gestureData.vibrate,o={...this.config,...i},h=o.strength||this.config.strength||1;let{amplitude:l}=o,{frequency:c}=o;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier)),a.timer+=s*c;const u=(Math.random()-.5)*l*h,d=(Math.random()-.5)*l*h;if(t.vx+=.5*u*s,t.vy+=.5*d*s,t.vx*=.9,t.vy*=.9,e>.8){const i=1-5*(e-.8);t.vx*=i,t.vy*=i}},cleanup(t){t.gestureData?.vibrate&&delete t.gestureData.vibrate},"3d":{evaluate(t,e){const i={...this.config,...e};let{amplitude:s}=i;const n=i.strength||this.config.strength||1;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const r=Math.sin(t*Math.PI),a=s*n*.003*r;return{position:[(Math.random()-.5)*a,(Math.random()-.5)*a,(Math.random()-.5)*a],rotation:[.01*(Math.random()-.5)*r,.01*(Math.random()-.5)*r,.01*(Math.random()-.5)*r],scale:1+.01*(Math.random()-.5)*r}}}},U={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.shake={originalX:t.x,originalY:t.y,randomAngle:Math.random()*Math.PI*2,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.shake?.initialized||this.initialize(t,i);const a=t.gestureData.shake,o={...this.config,...i},h=o.strength||this.config.strength||1;let{amplitude:l}=o,{frequency:c}=o;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier));const u=o.decay?1-e:1,d=Math.sin(e*Math.PI*c)*l*u*h*t.scaleFactor,p=d*Math.cos(a.randomAngle),m=d*Math.sin(a.randomAngle);t.x=a.originalX+p,t.y=a.originalY+m},pseudoRandom(t){const e=1e4*Math.sin(t);return e-Math.floor(e)},cleanup(t){t.gestureData?.shake&&(t.x=t.gestureData.shake.originalX,t.y=t.gestureData.shake.originalY,delete t.gestureData.shake)},"3d":{evaluate(t,e){const i=e||{},s=.003*(i.amplitude||15),n=i.frequency||15,r=.5*(i.strength||1),a=i.decay?1-t:1,o=Math.sin(t*Math.PI*n)*s*a*r,h=Math.floor(t*n);return{position:[o*(1e4*Math.sin(h)%1-.5)*2,0,o*(1e4*Math.sin(1.3*h)%1-.5)*2],rotation:[0,0,o*(1e4*Math.sin(1.7*h)%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(t,e,i,s,n,r,a){const o=(i.amplitude||this.config.amplitude)*n,h=i.frequency||this.config.frequency,l=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*h)*o*l;t.vx+=.5*c;const u=Math.cos(s*Math.PI*h*2)*o*.1*l;t.vy+=.3*u},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.amplitude||15,r=Math.pow(1-t,.5),a=Math.sin(t*Math.PI*14)*r,o=Math.cos(t*Math.PI*14*.7)*r*.4,h=n/15*s,l=.15*a*s;return{cameraRelativePosition:[.08*a*h,.02*Math.abs(o)*h,0],cameraRelativeRotation:[0,0,l],scale:1+.05*Math.abs(a),glowIntensity:1+.2*Math.abs(a)}}}};function Y(t){const e=P[t];if(!e)throw new Error(`Invalid step direction: ${t}`);return{name:`step${D(t)}`,emoji:"left"===t?"๐":"right"===t?"๐":"up"===t?"๐":"๐",type:"blending",description:`Quick step ${t} and return`,config:{duration:400,amplitude:25,strength:.7,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h,l=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1),h=i<.3?this.easeOutQuad(i/.3):1-this.easeInOutCubic((i-.3)/.7);const c=e.x*l*h*.01*n,u=e.y*l*h*.01*n;t.vx+=c,t.vy+=u},cleanup(t){},easeOutQuad:t=>1-(1-t)*(1-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||25,r=s.strength||.7;let a,o=.008*n*r;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),t<.3)a=1-(1-t/.3)*(1-t/.3);else{const e=(t-.3)/.7;a=1-(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)}const h=e.x*o*a,l=e.y*o*a,c=.12*a*r,u=-e.x*c;return{cameraRelativePosition:[h,l,0],rotation:[e.y*c*.5,0,u],scale:1}}}}}function X(t){const e=P[t];if(!e)throw new Error(`Invalid slide direction: ${t}`);return{name:`slide${D(t)}`,emoji:"left"===t?"โฌ
๏ธ":"โก๏ธ",type:"blending",description:`Smooth slide ${t} and return`,config:{duration:800,amplitude:35,strength:.6,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1);const l=Math.sin(i*Math.PI),c=e.x*h*l*.008*n,u=e.y*h*l*.008*n;t.vx+=c,t.vy+=u},cleanup(t){},"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||35,r=s.strength||.6;let a=.008*n*r;i.rhythmModulation&&(a*=i.rhythmModulation.amplitudeMultiplier||1);const o=Math.sin(t*Math.PI),h=e.x*a*o,l=e.y*a*o,c=.08*o*r,u=-e.x*c,d=e.x*c*.5;return{cameraRelativePosition:[h,l,.02*Math.sin(t*Math.PI*2)*r],rotation:[0,d,u],scale:1+.03*o}}}}}var V=Y("left"),N=Y("right"),Q=Y("up"),J=Y("down"),K=X("left"),Z=X("right"),tt={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:(t,e,i,s,n,r)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i={...this.config,...e}.strength||.8;return{position:[.1*Math.sin(t*Math.PI*4)*i,.05*Math.abs(Math.sin(t*Math.PI*8))*i,0],rotation:[0,0,.035*Math.sin(t*Math.PI*4)*i],scale:1-.035*Math.abs(Math.sin(t*Math.PI*8))*i,glowIntensity:1+.25*Math.abs(Math.sin(t*Math.PI*8)),glowBoost:.35*Math.max(0,Math.abs(Math.sin(t*Math.PI*8)))}}}},et={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:(t,e,i,s,n,r)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i={...this.config,...e}.strength||.9;return{position:[.12*Math.sin(t*Math.PI*8)*i,.05*Math.abs(Math.sin(t*Math.PI*8))*i,0],rotation:[0,0,.05*Math.sin(t*Math.PI*8)*i],scale:1-.04*Math.abs(Math.sin(t*Math.PI*8))*i,glowIntensity:1+.3*Math.abs(Math.sin(t*Math.PI*8)),glowBoost:.4*Math.max(0,Math.abs(Math.sin(t*Math.PI*8)))}}}},it={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.random()<.5?1:-1,h=Math.max(a,100+180*Math.random()),l=a<5?Math.random()*Math.PI*2:Math.atan2(r,n);t.gestureData.hula={radius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,wobblePhase:Math.random()*Math.PI*2,direction:o}},apply(t,e,i,s,n,r){t.gestureData?.hula||this.initialize(t,i,n,r);const a=t.gestureData.hula,o=(i.speed||this.config.speed)*(i.strength||1);let h=1;e<.1?(h=e/.1,h=Math.sin(h*Math.PI*.5)):e>.9&&(h=(1-e)/.1,h=Math.sin(h*Math.PI*.5)),a.angle+=o*s*a.direction*h;const l=Math.sin(2*a.angle+a.wobblePhase)*(i.wobbleAmount||this.config.wobbleAmount)*h,c=a.radius*(1+l)*h,u=a.radius*(.7+l)*h,d=n+Math.cos(a.angle)*c,p=r+Math.sin(a.angle)*u;if(e<.1){const e=t.x-n,i=t.y-r;Math.sqrt(e*e+i*i)<50?(t.x=n+Math.cos(a.angle)*c,t.y=r+Math.sin(a.angle)*u):(t.x=t.x+(d-t.x)*h*.5,t.y=t.y+(p-t.y)*h*.5)}else t.x=d,t.y=p;const m=a.angle+a.zPhase+(i.zPhaseOffset||this.config.zPhaseOffset);t.z=.9*Math.sin(m)*h;const g=i.verticalOscillation||this.config.verticalOscillation,f=Math.cos(2*m)*g*a.radius*.2*h;t.y+=f;const y=t.z*a.radius*.1;t.y-=y;const M=-Math.sin(a.angle)*c*o,b=Math.cos(a.angle)*u*o;e<.1?(t.vx=a.originalVx+(M-a.originalVx)*h,t.vy=a.originalVy+(b-a.originalVy)*h):e>.9?(t.vx=M*h+a.originalVx*(1-h),t.vy=b*h+a.originalVy*(1-h),t.z=t.z*h+a.originalZ*(1-h)):(t.vx=M,t.vy=b)},cleanup(t){if(t.gestureData?.hula){const e=t.gestureData.hula;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.hula}},"3d":{evaluate(t,e){const{particle:i}=e;if(!i||!i.gestureData?.hula)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.hula,n=e.config||{};let r=1;t<.15?(r=t/.15,r=Math.sin(r*Math.PI*.5)):t>.85&&(r=(1-t)/.15,r=Math.sin(r*Math.PI*.5));const a=s.initialAngle+t*Math.PI*2*s.direction,o=.25*Math.cos(a)*r,h=.25*Math.sin(a)*r,l=n.verticalOscillation||.3;return{position:[o,Math.sin(2*a+s.wobblePhase)*l*r,h],rotation:[0,(a-s.initialAngle)*r,0],scale:1+.15*Math.abs(Math.sin(a))*r}}}},st={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.twist={startX:t.x,startY:t.y,startAngle:Math.atan2(t.y-e.centerY,t.x-e.centerX),startDistance:Math.sqrt(Math.pow(t.x-e.centerX,2)+Math.pow(t.y-e.centerY,2)),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.twist?.initialized||this.initialize(t,{...i,centerX:n,centerY:r});const a={...this.config,...i},o=t.gestureData.twist,h=a.strength||this.config.strength||1,l=e*a.twistFrequency*Math.PI*2,c=Math.sin(l)*h;let{rotationAngle:u}=a,{contractionFactor:d}=a;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,d=1-(1-d)*(i.rhythmModulation.amplitudeMultiplier||1));const p=u*Math.PI/180*c,m=1-(1-d)*Math.abs(c),g=o.startAngle+p,f=o.startDistance*m,y=n+Math.cos(g)*f,M=r+Math.sin(g)*f,b=.15*h;t.x+=(y-t.x)*b,t.y+=(M-t.y)*b,t.vx=.05*(y-t.x),t.vy=.05*(M-t.y);const w=5*Math.sin(e*Math.PI*4)*h;if(t.y+=.1*w,e>.9){const i=1-10*(e-.9);t.vx*=i,t.vy*=i}},cleanup(t){t.gestureData?.twist&&delete t.gestureData.twist},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||.8,n=t>.85?(1-t)/.15:1,r=t*(i.twistFrequency||2)*Math.PI*2,a=Math.sin(r)*s*n,o=a*((i.rotationAngle||45)*Math.PI/180);return{position:[.05*Math.sin(r)*s*n,.02*Math.abs(Math.sin(2*r))*s*n,0],rotation:[.08*Math.cos(r)*s*n,o,.12*Math.sin(.5*r)*s*n],scale:1-(1-(i.contractionFactor||.8))*Math.abs(a),glowIntensity:1+.3*Math.abs(a)}}}},nt={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;return t<.15?(s=t/.15,s=1-Math.pow(1-s,3)):(s=1-(t-.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]}}}},rt={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.1){const e=t/.1;s=1-Math.pow(1-e,4)}else if(t<.3){const e=(t-.1)/.2;s=1-.1*Math.sin(e*Math.PI)}else s=1-(t-.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(t*Math.PI*4)*(1-t)*.02)*i,glowBoost:.8*s*i,positionBoost:[0,.04*s*i,0]}}}},at={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.6){const e=t/.6;s=e*e}else{const e=(t-.6)/.4;s=1-e*e}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(t*Math.PI)*i,0]}}}},ot={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.3){const e=t/.3;s=1-Math.pow(1-e,2)}else if(t<.7)s=1;else{const e=(t-.7)/.3;s=1-e*e}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}}}},ht={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1,s=Math.sin(t*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1,positionBoost:[0,.015*-s*i,0],scaleBoost:1-.015*s*i}}}},lt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.bounce={startY:t.y,startX:t.x,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.bounce?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e);let{frequency:l}=a;const c=i.phase||0;let u=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,u*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const d=Math.sin((h+c)*Math.PI*2*l);if(a.damping&&e>.7&&(u*=1-(e-.7)/.3*.8),"vertical"===a.axis?(t.vy+=d*u*.01*s,e>.9&&(t.vx*=.98)):"horizontal"===a.axis&&(t.vx+=d*u*.01*s,e>.9&&(t.vy*=.98)),e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.bounce&&delete t.gestureData.bounce},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||30,n=i.frequency||2,r=.003*s*(i.strength||.6),a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*Math.PI*n,o=Math.abs(Math.sin(a));let h=r;return t>.7&&(h*=1-(t-.7)/.3*.8),{position:[0,o*h,0],rotation:[0,0,0],scale:1+.08*o}}}},ct={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.random()<.5?1:-1,h=Math.max(a,100+180*Math.random()),l=a<5?Math.random()*Math.PI*2:Math.atan2(r,n);t.gestureData.orbit={radius:h,targetRadius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,direction:o}},apply(t,e,i,s,n,r){t.gestureData?.orbit||this.initialize(t,i,n,r);const a=t.gestureData.orbit,o=(i.speed||this.config.speed)*(i.strength||1);a.angle+=o*s*a.direction;let{radius:h}=a;if(i.maintainRadius||(h=a.radius*(1+.1*Math.sin(e*Math.PI*2))),t.x=n+Math.cos(a.angle)*h,t.y=r+Math.sin(a.angle)*h,!1!==i.use3D){const e=a.angle+a.zPhase+(i.zPhaseOffset||0);if(t.z=.8*Math.sin(e),i.verticalOscillation){const s=Math.cos(e)*i.verticalOscillation*h*.1;t.y+=s}}if(t.vx=-Math.sin(a.angle)*h*o,t.vy=Math.cos(a.angle)*h*o,e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.orbit){const e=t.gestureData.orbit;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.orbit}},"3d":{evaluate(t,e){const i=e?.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;t<.15?n=Math.sin(t/.15*Math.PI*.5):t>.85&&(n=Math.sin((1-t)/.15*Math.PI*.5));const r=s.initialAngle+t*Math.PI*2*s.direction,a=.3*Math.cos(r)*n,o=.3*Math.sin(r)*n,h=(r+Math.PI/2-(s.initialAngle+Math.PI/2))*n,l=i.z||0;return{position:[a,0,o+.1*l*n],rotation:[0,h,0],scale:1+.15*l*n}}}};function ut(t){const e=P[t];if(!e)throw new Error(`Invalid orbit direction: ${t}`);const i="up"===t||"down"===t,s="left"===t||"up"===t?1:-1;return{name:`orbit${D(t)}`,emoji:"left"===t?"๐":"right"===t?"๐":"up"===t?"๐":"๐ซ",type:"override",description:`Orbit ${"left"===t?"counter-clockwise":"right"===t?"clockwise":t}`,config:{duration:1500,musicalDuration:{musical:!0,beats:4},speed:.02,maintainRadius:!0,use3D:!0,rotations:1,strength:1,direction:t,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(t,e,i,n){t.gestureData||(t.gestureData={});const r=t.x-i,a=t.y-n,o=Math.sqrt(r*r+a*a),h=Math.max(o,80+100*Math.random()),l=o<5?Math.random()*Math.PI*2:Math.atan2(a,r);t.gestureData.orbit={radius:h,targetRadius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,direction:s,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.orbit?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.orbit,l={...this.config,...n},c=n.strength||1,u=(l.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)),h.angle+=u*r*h.direction*d;let{radius:p}=h;l.maintainRadius||(p=h.radius*(1+.1*Math.sin(s*Math.PI*2)));const m=p*d+(1-d)*h.radius*.5;if(t.x=a+Math.cos(h.angle)*m,t.y=o+Math.sin(h.angle)*m,!1!==l.use3D){const n=h.angle+h.zPhase;if(t.z=.8*Math.sin(n)*d,i&&l.verticalOscillation){const i=e.y*s*l.verticalOscillation*p*.5;t.y+=i}}if(t.vx=-Math.sin(h.angle)*m*u*d,t.vy=Math.cos(h.angle)*m*u*d,s>.9){const e=10*(1-s);t.vx=t.vx*e+h.originalVx*(1-e),t.vy=t.vy*e+h.originalVy*(1-e)}},cleanup(t){if(t.gestureData?.orbit){const e=t.gestureData.orbit;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.orbit}},"3d":{evaluate(t,n){const r=n.config||n||{},a=n.strength||1,o=r.rotations||1;let h=1;t<.15?h=Math.sin(t/.15*Math.PI*.5):t>.85&&(h=Math.sin((1-t)/.15*Math.PI*.5));const l=.25*a,c=t*Math.PI*2*o*s,u=Math.cos(c)*l*h,d=Math.sin(c)*l*h;let p=0;return i&&(p=e.y*t*.2*a*h),{cameraRelativePosition:[u,p,d],rotation:[0,c*h*.5,0],scale:1+.2*d}}}}}var dt=ut("left"),pt=ut("right"),mt=ut("up"),gt=ut("down"),ft={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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.jump={startX:t.x,startY:t.y,startSize:t.size,originalVx:t.vx,originalVy:t.vy,driftDirection:.1*(t.x-i),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.jump?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.jump,o={...this.config,...i},h=i.strength||1,l=o.jumpHeight*h*t.scaleFactor,c=o.squashAmount,u=o.stretchAmount,d=o.anticipation,p=1-.5*o.anticipation;if(e<d){const i=e/d,s=this.easeOutQuad(i);t.size=a.startSize*(1-(1-c)*s),t.y=a.startY+5*s*t.scaleFactor,t.vx=0,t.vy=0}else if(e<p){const i=(e-d)/(p-d);let s=Math.sin(i*Math.PI);if(o.hangTime>0&&i>.4&&i<.6){const t=(i-.4)/.2;s=.95+.05*this.easeInOutCubic(t)}if(t.y=a.startY-s*l,o.driftOutward&&(t.x=a.startX+s*a.driftDirection),i<.5){const e=2*i;t.size=a.startSize*(c+(u-c)*e)}else{const e=2*(i-.5);t.size=a.startSize*(u-(u-1)*e*.8)}t.vx=.5*a.driftDirection,t.vy=-Math.cos(i*Math.PI)*l*.1}else{const i=(e-p)/(1-p),s=this.easeOutBounce(i);if(t.y=a.startY,o.landingImpact)if(i<.3){const e=i/.3;t.size=a.startSize*(1-(1-.8*c)*(1-e))}else{const e=(i-.3)/.7;t.size=a.startSize*(.8*c+(1-.8*c)*e)}else t.size=a.startSize*(c+(1-c)*s);t.vx=a.originalVx*s,t.vy=a.originalVy*s}},cleanup(t){if(t.gestureData?.jump){const e=t.gestureData.jump;t.size=e.startSize,t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.jump}},easeOutQuad:t=>t*(2-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},"3d":{evaluate(t,e){const i=e.config||e||{},s=e.strength||1,n=.004*(i.jumpHeight||60)*s,r=i.squashAmount||.8,a=i.stretchAmount||1.2,o=i.anticipation||.2,h=1-.5*o;let l=0,c=1,u=0;if(t<o){const e=t/o,i=e*(2-e);c=1-(1-r)*i,l=.02*-i}else if(t<h){const e=(t-o)/(h-o);l=Math.sin(e*Math.PI)*n,c=e<.5?r+2*e*(a-r):a-2*(e-.5)*(a-1)*.8,u=.05*Math.sin(e*Math.PI)}else{const e=(t-h)/(1-h);if(e<.5){const t=2*e;l=-Math.sin(t*Math.PI)*n*.15}else l=0;c=!1!==i.landingImpact?e<.3?1-(1-.8*r)*(1-e/.3):.8*r+(e-.3)/.7*(1-.8*r):r+(1-r)*e}return{position:[0,l,0],rotation:[u,0,0],scale:c}}}};function yt(t){const e=P[t];if(!e)throw new Error(`Invalid jump direction: ${t}`);const i="up"===t||"down"===t;return{name:`jump${D(t)}`,emoji:"up"===t?"๐ฆ":"down"===t?"๐ฅ":"left"===t?"โฌ
๏ธ":"โก๏ธ",type:"override",description:`Jump ${t} 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:t,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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.jump={startX:t.x,startY:t.y,startSize:t.size,originalVx:t.vx,originalVy:t.vy,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.jump?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.jump,l={...this.config,...n},c=n.strength||1,u=l.jumpDistance*c*t.scaleFactor,d=l.squashAmount,p=l.stretchAmount,m=l.anticipation,g=1-.5*l.anticipation;if(s<m){const n=s/m,r=this.easeOutQuad(n);t.size=h.startSize*(1-(1-d)*r),i?t.y=h.startY-e.y*r*5*t.scaleFactor:t.x=h.startX-e.x*r*5*t.scaleFactor,t.vx=0,t.vy=0}else if(s<g){const n=(s-m)/(g-m);let r=Math.sin(n*Math.PI);if(l.hangTime>0&&n>.4&&n<.6){const t=(n-.4)/.2;r=.95+.05*this.easeInOutCubic(t)}if(i?(t.y=h.startY+e.y*r*u,t.x=h.startX+3*Math.sin(n*Math.PI*2)):(t.x=h.startX+e.x*r*u,t.y=h.startY-Math.sin(n*Math.PI)*u*.3),n<.5){const e=2*n;t.size=h.startSize*(d+(p-d)*e)}else{const e=2*(n-.5);t.size=h.startSize*(p-(p-1)*e*.8)}i?(t.vy=e.y*Math.cos(n*Math.PI)*u*.1,t.vx=0):(t.vx=e.x*Math.cos(n*Math.PI)*u*.1,t.vy=-Math.cos(n*Math.PI)*u*.05)}else{const e=(s-g)/(1-g),i=this.easeOutBounce(e);if(t.x=h.startX,t.y=h.startY,l.landingImpact)if(e<.3){const i=e/.3;t.size=h.startSize*(1-(1-.8*d)*(1-i))}else{const i=(e-.3)/.7;t.size=h.startSize*(.8*d+(1-.8*d)*i)}else t.size=h.startSize*(d+(1-d)*i);t.vx=h.originalVx*i,t.vy=h.originalVy*i}},cleanup(t){if(t.gestureData?.jump){const e=t.gestureData.jump;t.size=e.startSize,t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.jump}},easeOutQuad:t=>t*(2-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},"3d":{evaluate(t,s){const n=s.config||s||{},r=s.strength||1,a=.004*(n.jumpDistance||60)*r,o=n.squashAmount||.8,h=n.stretchAmount||1.2,l=n.anticipation||.2,c=1-.5*l;let u=0,d=0,p=1,m=0,g=0,f=0;if(t<l){const s=t/l,n=s*(2-s);p=1-(1-o)*n,i?d=-e.y*n*.02:u=-e.x*n*.02}else if(t<c){const s=(t-l)/(c-l),n=Math.sin(s*Math.PI);i?d=e.y*n*a:(u=e.x*n*a,d=Math.sin(s*Math.PI)*a*.3),p=s<.5?o+2*s*(h-o):h-2*(s-.5)*(h-1)*.8,i?m=e.y*Math.sin(s*Math.PI)*.1:(g=e.x*Math.sin(s*Math.PI)*.15,f=-e.x*Math.sin(s*Math.PI)*.05)}else{const s=(t-c)/(1-c);if(s<.5){const t=2*s;i?d=-e.y*Math.sin(t*Math.PI)*a*.15:u=-e.x*Math.sin(t*Math.PI)*a*.1}p=!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,g,f],scale:p}}}}}var Mt=yt("down"),bt=yt("left"),wt=yt("right");function vt(t){if(!["forward","back","left","right","up","down"].includes(t))throw new Error(`Invalid rush direction: ${t}`);return{name:`rush${D(t)}`,emoji:{forward:"๐จ",back:"๐",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ"}[t],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"}[t],config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1,direction:t,particleMotion:{type:"rush",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"forward";let r=0,a=0,o=0,h=0,l=0,c=1,u=1,d=0;const p={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(t<.2){const e=t/.2,i=1-Math.pow(1-e,2);h=i*p.lean.x*s,l=i*p.lean.z*s,a="up"===n?.03*-i*s:.02*-i*s,u=1+.3*i}else if(t<.6){const e=(t-.2)/.4,i=1-Math.pow(1-e,3);r=p.x*i*m*s,a=p.y*i*m*s,o=p.z*i*m*s,"up"===n?a+=.05*i*s:"down"!==n&&(a+=(.04*i-.02)*s),h=p.lean.x*s,l=p.lean.z*s,c=1+.08*i,u=1.3+.5*i,d=.35*i,l+=Math.sin(e*Math.PI*12)*(1-e)*.015*s}else{const e=(t-.6)/.4,i=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;if(r=p.x*m*(1-i)*s,a=p.y*m*(1-i)*s,o=p.z*m*(1-i)*s,h=p.lean.x*(1-i)*s,l=p.lean.z*(1-i)*s,c=1.08-.08*i,e>.7){const t=(e-.7)/.3;a-=.02*Math.sin(t*Math.PI)*s}u=1.8-.8*i,d=.35*(1-i)}return{cameraRelativePosition:[r,a,o],cameraRelativeRotation:[h,0,l],scale:c,glowIntensity:u,glowBoost:d}}}}}var St={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.25,r=!1!==i.recover;let a;t<.3?(a=t/.3,a=1-Math.pow(1-a,3)):t<.6?a=1:r?(a=1-(t-.6)/.4,a=Math.pow(a,2)):a=1;const o=a*n*s;return{position:[0,.05*-Math.sin(a*Math.PI)*s,o],rotation:[.2*a*s,0,0],scale:1+.1*a*s,glowIntensity:1+.3*a,glowBoost:t<.4?.4*a:0}}}};function kt(t){if(!{...P,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[t])throw new Error(`Invalid lunge direction: ${t}`);return{name:`lunge${D(t)}`,emoji:{forward:"๐คบ",back:"๐",left:"๐",right:"๐",up:"โ๏ธ",down:"๐"}[t]||"๐คบ",type:"override",description:`Lunge thrust ${t}`,config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,recover:!0,strength:1,direction:t,particleMotion:{type:"lunge",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.25,r=!1!==i.recover,a=i.direction||"forward";let o;t<.3?(o=t/.3,o=1-Math.pow(1-o,3)):t<.6?o=1:r?(o=1-(t-.6)/.4,o=Math.pow(o,2)):o=1;let h=0,l=0,c=0,u=0,d=0;switch(a){case"forward":c=o*n*s,u=.2*o*s,l=.05*-Math.sin(o*Math.PI)*s;break;case"back":c=-o*n*s,u=.2*-o*s,l=.05*-Math.sin(o*Math.PI)*s;break;case"left":h=-o*n*s,d=.2*-o*s,l=.03*-Math.sin(o*Math.PI)*s;break;case"right":h=o*n*s,d=.2*o*s,l=.03*-Math.sin(o*Math.PI)*s;break;case"up":l=o*n*s,u=.15*-o*s;break;case"down":l=-o*n*s,u=.25*o*s}return{cameraRelativePosition:[h,l,c],cameraRelativeRotation:[u,0,d],scale:1+.1*o*s,glowIntensity:1+.3*o,glowBoost:t<.4?.4*o:0}}}}}var xt={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;let a=e.direction||this.config.direction;"random"===a&&(a=Math.random()<.5?"clockwise":"counter-clockwise"),t.gestureData.spin={startAngle:Math.atan2(r,n),startRadius:Math.sqrt(n*n+r*r)||30,originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,direction:a,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.spin?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.spin,o={...this.config,...i},h=i.strength||1;let{rotations:l}=o,{radiusMultiplier:c}=o;i.rhythmModulation&&(i.rhythmModulation.rotationMultiplier&&(l*=i.rhythmModulation.rotationMultiplier),i.rhythmModulation.radiusMultiplier&&(c*=i.rhythmModulation.radiusMultiplier));let u=e;o.accelerate&&(u=e<.5?.5*this.easeInQuad(2*e):.5+.5*this.easeOutQuad(2*(e-.5)));const d=l*Math.PI*2*h,p="counter-clockwise"===a.direction?-1:1,m=a.startAngle+d*u*p;let g=a.startRadius;o.spiralOut&&(g*=1+.5*e),1!==c&&(g*=1+(c-1)*Math.sin(e*Math.PI));const f=n+Math.cos(m)*g,y=r+Math.sin(m)*g;if(t.x+=.25*(f-t.x),t.y+=.25*(y-t.y),t.vx=.5*(f-t.x),t.vy=.5*(y-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.spin){const e=t.gestureData.spin;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.spin}},easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const i=e?.config||e||{},s=e?.strength||1,n=e?.particle;let r=1;n?.gestureData?.spin?r="counter-clockwise"===n.gestureData.spin.direction?-1:1:"counter-clockwise"!==i.direction&&"left"!==i.direction||(r=-1);let a=t;return!1!==i.accelerate&&(a=t<.5?t*t*4*.5:.5+(t-.5)*(2-(t-.5))*.5),{position:[0,0,0],rotation:[0,(i.rotations||1)*Math.PI*2*s*a*r,0],scale:1+(i.scaleAmount||.1)*Math.sin(t*Math.PI)*s}}}};const Et={left:"counter-clockwise",right:"clockwise"};function Bt(t){const e=Et[t];if(!e)throw new Error(`Invalid spin direction: ${t}`);const i="left"===t?-1:1;return{name:`spin${D(t)}`,emoji:"left"===t?"โบ":"โป",type:"override",description:`Spin ${e}`,config:{duration:600,rotations:1,direction:e,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(t,i,s,n){t.gestureData||(t.gestureData={});const r=t.x-s,a=t.y-n;t.gestureData.spin={startAngle:Math.atan2(a,r),startRadius:Math.sqrt(r*r+a*a)||30,originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,direction:e,initialized:!0}},apply(t,e,s,n,r,a){t.gestureData?.spin?.initialized||this.initialize(t,s,r,a);const o=t.gestureData.spin,h={...this.config,...s},l=s.strength||1;let{rotations:c,radiusMultiplier:u}=h;s.rhythmModulation&&(s.rhythmModulation.rotationMultiplier&&(c*=s.rhythmModulation.rotationMultiplier),s.rhythmModulation.radiusMultiplier&&(u*=s.rhythmModulation.radiusMultiplier));let d=e;h.accelerate&&(d=e<.5?.5*this.easeInQuad(2*e):.5+.5*this.easeOutQuad(2*(e-.5)));const p=c*Math.PI*2*l,m=o.startAngle+p*d*i;let g=o.startRadius;h.spiralOut&&(g*=1+.5*e),1!==u&&(g*=1+(u-1)*Math.sin(e*Math.PI));const f=r+Math.cos(m)*g,y=a+Math.sin(m)*g;if(t.x+=.25*(f-t.x),t.y+=.25*(y-t.y),t.vx=.5*(f-t.x),t.vy=.5*(y-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+o.originalVx*(1-i),t.vy=t.vy*i+o.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.spin){const e=t.gestureData.spin;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.spin}},easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const s=e?.config||e||{},n=e?.strength||1;let r=t;return!1!==s.accelerate&&(r=t<.5?t*t*4*.5:.5+(t-.5)*(2-(t-.5))*.5),{position:[0,0,0],rotation:[0,(s.rotations||1)*Math.PI*2*n*r*i,0],scale:1+(s.scaleAmount||.1)*Math.sin(t*Math.PI)*n}}}}}var At=Bt("left"),Ct=Bt("right"),Tt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotations||1,r=i.height||.3,a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*(2*-Math.PI*n),o=Math.sin(t*Math.PI)*r*s;let h=1;if(t<.1)h=1-t/.1*.15;else if(t<.2)h=.85+(t-.1)/.1*.2;else if(t>.9){const e=(t-.9)/.1;h=1.05-.1*Math.sin(e*Math.PI)}else h=1.05;return t>=.99&&(h=1),{position:[0,o,0],rotation:[a,0,0],scale:h,glowIntensity:1+.4*Math.sin(t*Math.PI),glowBoost:t>.2&&t<.8?.3:0}}}},Pt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotations||1,r=i.height||.35,a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*(2*Math.PI*n),o=Math.sin(t*Math.PI)*r*s,h=.1*Math.sin(t*Math.PI)*s;let l=1;if(t<.1)l=1-t/.1*.15;else if(t<.2)l=.85+(t-.1)/.1*.25;else if(t>.9){const e=(t-.9)/.1;l=1.1-.15*Math.sin(e*Math.PI)}else l=1.1;return t>=.99&&(l=1),{position:[0,o,h],rotation:[a,0,0],scale:l,glowIntensity:1+.5*Math.sin(t*Math.PI),glowBoost:.4*Math.sin(t*Math.PI)}}}},Dt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.point={startX:t.x,startY:t.y,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.point?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e);let l=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1);const c=Math.sin(h*Math.PI);let u=0,d=0;switch(a.direction||"right"){case"right":u=1;break;case"left":u=-1;break;case"up":d=-1;break;case"down":d=1}if(t.vx+=c*l*.02*s*u,t.vy+=c*l*.02*s*d,e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.point&&delete t.gestureData.point},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||15,n=i.strength||.8,r=i.direction||"right",a=.005*s*n,o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI);let l=0,c=0;switch(r){case"right":l=h*a,c=.25*h;break;case"left":l=-h*a,c=.25*-h;break;case"up":case"down":c=0}return{position:[l,0,0],rotation:[0,c,0],scale:1}}}};function Rt(t){const e=P[t];if(!e)throw new Error(`Invalid point direction: ${t}`);const i="up"===t||"down"===t;return{name:`point${D(t)}`,emoji:"up"===t?"โ๏ธ":"down"===t?"๐":"left"===t?"๐":"๐",type:"blending",description:`Point ${t} with extension and return`,config:{duration:500,amplitude:15,strength:.8,direction:t},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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.point={startX:t.x,startY:t.y,initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.point?.initialized||this.initialize(t,s);const o={...this.config,...s},h=o.strength||.8,l=this.easeInOutCubic(i);let c=o.amplitude*h*t.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI);if(t.vx+=u*c*.02*n*e.x,t.vy+=u*c*.02*n*-e.y,i>.9){const e=1-10*(i-.9);t.vx*=.95+.05*e,t.vy*=.95+.05*e}},cleanup(t){t.gestureData?.point&&delete t.gestureData.point},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,s){const n=s||{},r=.005*(n.amplitude||15)*(n.strength||.8),a=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,o=Math.sin(a*Math.PI),h=e.x*o*r,l=e.y*o*r;let c=0,u=0,d=0;return i?c=e.y*o*.2:(u=e.x*o*.25,d=-e.x*o*.1),{cameraRelativePosition:[h,l,0],rotation:[c,u,d],scale:1}}}}}var Ft=Rt("up"),zt=Rt("down"),qt=Rt("left"),Ot=Rt("right");function jt(t){if("left"!==t&&"right"!==t)throw new Error(`Invalid kick direction: ${t}. Only 'left' and 'right' are supported.`);const e=P[t];return{name:`kick${D(t)}`,emoji:"left"===t?"๐ฆต":"๐ฆถ",type:"blending",description:`Quick kick ${t} with snap return`,config:{duration:400,amplitude:30,strength:.8,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h,l=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1),h=i<.25?this.easeOutQuad(i/.25):i<.5?1:1-this.easeInQuad((i-.5)/.5);const c=e.x*l*h*.012*n,u=e.y*l*h*.012*n;t.vx+=c,t.vy+=u},cleanup(t){},easeOutQuad:t=>1-(1-t)*(1-t),easeInQuad:t=>t*t,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||30,r=s.strength||.8;let a,o=.008*n*r;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),t<.25)a=1-(1-t/.25)*(1-t/.25);else if(t<.5)a=1;else{const e=(t-.5)/.5;a=1-e*e}const h=.15*a*r;return{cameraRelativePosition:[e.x*o*a,e.y*o*a*.3,0],rotation:[.08*a*r,0,e.x*h],scale:1+.05*a}}}}}var It=jt("left"),$t=jt("right"),Lt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.depth||.4,r=i.holdTime||.4;let a;const o=.4*(1-r),h=1-.6*(1-r);return t<o?(a=t/o,a=Math.sin(a*Math.PI/2)):t<h?a=1:(a=1-(t-h)/(1-h),a=Math.sin(a*Math.PI/2)),{cameraRelativePosition:[0,.1*-a*s,.05*-a*s],cameraRelativeRotation:[a*n*Math.PI*s,0,0],scale:1,glowIntensity:1-.2*a,glowBoost:0}}}},Gt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.nod={startY:t.y,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.nod?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1;let{frequency:h}=a,{amplitude:l}=a;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const c=Math.sin(e*Math.PI*2*h);l=l*o*t.scaleFactor,t.vy+=c*l*.01*s,e>.9&&(t.vy*=.95)},cleanup(t){t.gestureData?.nod&&delete t.gestureData.nod},"3d":{evaluate(t,e){const i={...this.config,...e};let{amplitude:s}=i;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);let n=0;if(t<.4){const e=t/.4;n=.12*Math.sin(e*Math.PI)}else if(t<.8){const e=(t-.4)/.4;n=.07*Math.sin(e*Math.PI)}return n*=s/15,{cameraRelativePosition:[0,0,n],scale:1-.3*Math.abs(n),glowIntensity:1+.5*Math.abs(n)}}}},_t={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.reach={startY:t.y,startVy:t.vy,originalSize:t.size,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.reach?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=a.scaleMax||this.config.scaleMax||1.05,l=this.easeInOutCubic(e);let c=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI);t.vy-=u*c*.015*s;const d=1+u*(h-1);if(t.size=t.baseSize*d,e>.9){const i=1-10*(e-.9);t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.reach&&(t.gestureData.reach.originalSize?t.size=t.gestureData.reach.originalSize:t.size=t.baseSize,delete t.gestureData.reach)},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||25,n=i.strength||.9,r=i.scaleMax||1.05,a=.004*s*n,o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI);return{position:[0,h*a,0],rotation:[.1*h,0,0],scale:1+h*(r-1)}}}},Ht={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(t,e,i,s,n,r,a){const o=(i.amplitude||this.config.amplitude)*n,h=i.frequency||this.config.frequency,l=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*2*h)*o*l;t.vy+=.5*c;const u=Math.cos(s*Math.PI*2*h*1.5)*o*.05*l;t.vx+=.2*u},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.amplitude||12,r=t<.15?t/.15:Math.pow(1-(t-.15)/.85,2),a=n/12*s;return{cameraRelativePosition:[0,0,.08*r*a],position:[0,.015*-r*a,0],scale:1-.05*r,glowIntensity:1+.15*r}}}},Ut={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.depth||.3,r=i.widen||.2;let a;const o=(1-(i.holdTime||.5))/2,h=1-o;return a=t<o?t/o:t<h?1:1-(t-h)/o,a=Math.sin(a*Math.PI/2),{position:[0,-a*n*s,0],rotation:[.15*a*s,0,0],scale:(1+a*r*s+(1-.25*a*s))/2,glowIntensity:1-.3*a,glowBoost:0}}}},Wt={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=Math.random(),l=({...this.config,...e}.homeRadius+20*Math.random())*t.scaleFactor;t.gestureData.tilt={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,angle:a,distance:o,homeRadius:l,homeX:i+Math.cos(a)*l,homeY:s+Math.sin(a)*l,role:h,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.tilt?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.tilt,o={...this.config,...i},h=i.strength||1;let l,c;if(e<o.gatherPhase){const i=e/o.gatherPhase,s=this.easeInOutCubic(i);l=a.startX+(a.homeX-a.startX)*s,c=a.startY+(a.homeY-a.startY)*s;const n=.6;t.x+=(l-t.x)*n,t.y+=(c-t.y)*n}else{const i=(e-o.gatherPhase)/(1-o.gatherPhase)*Math.PI*o.frequency,s=Math.sin(i),u=o.tiltAngle*Math.PI/180*h,d=a.angle+s*u,p=Math.abs(s)*o.liftAmount*t.scaleFactor,m=a.homeRadius+p;l=n+Math.cos(d)*m,c=r+Math.sin(d)*m-.3*p;const g=o.smoothness+.1*a.role;t.x+=(l-t.x)*g,t.y+=(c-t.y)*g;const f=-Math.sin(d),y=Math.cos(d);t.vx=f*s*2,t.vy=y*s*2}if(e<o.gatherPhase&&(t.vx=.25*(l-t.x),t.vy=.25*(c-t.y)),e>.9){const i=10*(1-e),s=a.startX+(t.x-a.startX)*i,n=a.startY+(t.y-a.startY)*i;t.x=s,t.y=n,t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.tilt){const e=t.gestureData.tilt;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.tilt}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.gatherPhase||.2,r=i.frequency||3,a=i.tiltAngle||45;let o=0;if(t>=n){const e=(t-n)/(1-n)*Math.PI*r;o=Math.sin(e)*(a*Math.PI/180*s*.4)}return{position:[0,0,0],rotation:[0,0,o],scale:1}}}};function Yt(t){const e=P[t];if(!e)throw new Error(`Invalid tilt direction: ${t}`);const i="up"===t||"down"===t;return{name:`tilt${D(t)}`,emoji:"up"===t?"๐ญ":"down"===t?"๐":"left"===t?"๐ค":"๐ง",type:"override",description:`Tilt ${t} 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:t,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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=({...this.config,...e}.homeRadius+20*Math.random())*t.scaleFactor;t.gestureData.tilt={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,angle:a,distance:o,homeRadius:h,homeX:i+Math.cos(a)*h,homeY:s+Math.sin(a)*h,role:Math.random(),initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.tilt?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.tilt,l={...this.config,...n},c=n.strength||1;let u,d;if(s<l.gatherPhase){const e=s/l.gatherPhase,i=this.easeInOutCubic(e);u=h.startX+(h.homeX-h.startX)*i,d=h.startY+(h.homeY-h.startY)*i;const n=.6;t.x+=(u-t.x)*n,t.y+=(d-t.y)*n}else if(s<l.gatherPhase+l.holdPhase){const n=(s-l.gatherPhase)/l.holdPhase,r=this.easeOutCubic(Math.min(2*n,1)),a=l.tiltAmount*c*t.scaleFactor*r;i?(u=h.homeX,d=h.homeY+e.y*a):(u=h.homeX+e.x*a,d=h.homeY-Math.abs(e.x)*a*.2);const o=l.smoothness+.1*h.role;t.x+=(u-t.x)*o,t.y+=(d-t.y)*o,t.vx=.5*(u-t.x),t.vy=.5*(d-t.y)}else{const e=(s-l.gatherPhase-l.holdPhase)/(1-l.gatherPhase-l.holdPhase),i=this.easeInOutCubic(e);u=t.x+(h.startX-t.x)*i,d=t.y+(h.startY-t.y)*i,t.x=u,t.y=d,t.vx=h.originalVx*i,t.vy=h.originalVy*i}s<l.gatherPhase&&(t.vx=.25*(u-t.x),t.vy=.25*(d-t.y))},cleanup(t){if(t.gestureData?.tilt){const e=t.gestureData.tilt;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.tilt}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutCubic:t=>1-Math.pow(1-t,3),"3d":{evaluate(t,s){const n=s.config||s||{},r=s.strength||1,a=n.gatherPhase||.2,o=n.holdPhase||.4,h=n.tiltAngle||45,l=n.tiltAmount||40;let c=0,u=0,d=0,p=0,m=0;if(t<a);else if(t<a+o){const s=(t-a)/o,n=1-Math.pow(1-Math.min(2*s,1),3),g=h*Math.PI/180*r*.4*n,f=.004*l*r*n;i?(d=e.y*g,u=e.y*f):(m=-e.x*g,c=e.x*f*.5,p=e.x*g*.3)}else{const s=(t-a-o)/(1-a-o),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,g=h*Math.PI/180*r*.4*(1-n),f=.004*l*r*(1-n);i?(d=e.y*g,u=e.y*f):(m=-e.x*g,c=e.x*f*.5,p=e.x*g*.3)}return{cameraRelativePosition:[c,u,0],rotation:[d,p,m],scale:1}}}}}var Xt=Yt("up"),Vt=Yt("down"),Nt=Yt("left"),Qt=Yt("right");function Jt(t){if(!["left","right","front","back","up","down"].includes(t))throw new Error(`Invalid oof direction: ${t}`);return{name:`oof${D(t)}`,emoji:{left:"๐ค",right:"๐ค",front:"๐",back:"๐ซ",up:"๐ฅ",down:"๐ฅ"}[t],type:"override",description:{left:"Punched from left",right:"Punched from right",front:"Gut punch",back:"Kidney shot",up:"Uppercut",down:"Hammer fist"}[t],config:{duration:500,musicalDuration:{musical:!0,beats:1},intensity:1,strength:1,direction:t,particleMotion:{type:"oof",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1;let n,r;if(t<.25){const e=t/.25;n=e*(2-e)}else{const e=(t-.25)/.75;n=1-e*e}r=t<.1?t/.1:t<.4?1:1-(t-.4)/.6;const a=.2*s,o=.35*s;let h=0,l=0,c=0,u=0,d=0,p=[0,0,.4];switch(i.direction||"front"){case"left":h=-n*a,d=n*o,p=[.4,0,0];break;case"right":h=n*a,d=-n*o,p=[-.4,0,0];break;case"front":c=-n*a,l=.03*-n,u=n*o*.7,p=[0,0,.4];break;case"back":c=n*a,u=-n*o*.6,p=[0,0,-.4];break;case"up":l=n*a,u=-n*o*.4,p=[0,.8,0];break;case"down":l=-n*a,u=n*o*.3,p=[0,-.8,0]}let m=1,g=0;if(t<.15){const e=t/.15;m=1+.6*(1-e),g=.4*(1-e)}return{cameraRelativePosition:[h,l,c],cameraRelativeRotation:[u,0,d],scale:1,glowIntensity:m,glowBoost:g,deformation:{enabled:!0,strength:r*s*2,impactPoint:p,falloffRadius:.5}}}}}}var Kt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.2,r=i.intensity||1,a=!1!==i.recover;let o;return t<.15?(o=t/.15,o=1-Math.pow(1-o,4)):t<.4?o=1:a?(o=1-(t-.4)/.6,o=Math.pow(o,.5)):o=1,{position:[0,.05*o*s,-o*n*s*r],rotation:[.25*-o*s*r,0,0],scale:1-.1*o*r,glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.5:0}}}};function Zt(t){if(!{...P,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[t])throw new Error(`Invalid recoil direction: ${t}`);return{name:`recoil${D(t)}`,emoji:{back:"๐ฑ",forward:"๐ต",left:"๐ฐ",right:"๐ฐ",up:"๐ฒ",down:"๐จ"}[t]||"๐ฑ",type:"override",description:`Recoil ${t} in shock`,config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,direction:t,particleMotion:{type:"recoil",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.2,r=i.intensity||1,a=!1!==i.recover,o=i.direction||"back";let h;t<.15?(h=t/.15,h=1-Math.pow(1-h,4)):t<.4?h=1:a?(h=1-(t-.4)/.6,h=Math.pow(h,.5)):h=1;let l=0,c=0,u=0,d=0,p=0;switch(o){case"back":u=-h*n*s*r,d=.25*-h*s*r,c=.05*h*s;break;case"forward":u=h*n*s*r,d=.25*h*s*r,c=.05*-h*s;break;case"left":l=-h*n*s*r,p=.2*h*s*r;break;case"right":l=h*n*s*r,p=.2*-h*s*r;break;case"up":c=h*n*s*r,d=.1*-h*s*r;break;case"down":c=-h*n*s*r,d=.3*h*s*r}return{cameraRelativePosition:[l,c,u],cameraRelativeRotation:[d,0,p],scale:1-.1*h*r,glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.5:0}}}}}var te={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.15){const e=t/.15,s=1-Math.pow(1-e,2);n=.1*s*i,r=.2*-s*i,h=1+.6*s,l=.5*s}else if(t<.4){const e=(t-.15)/.25,n=e*e;s=.2*-n*i,r=(.6*n-.2)*i,a=.3*n*i,e>.7&&(o=1-(e-.7)/.3*.1),h=1.6-.5*e,l=.5-.4*e}else if(t<.6){const e=(t-.4)/.2;s=-.2*i,r=.4*i,a=.3*i,a+=.02*Math.sin(e*Math.PI*2),o=.9,h=.8}else{const e=(t-.6)/.4,n=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;if(s=(.2*n-.2)*i,r=(.4-.4*n)*i,a=(.3-.3*n)*i,o=.9+.1*n,e>.7){const t=(e-.7)/.3;a+=.03*Math.sin(t*Math.PI*4)*(1-t)}h=.8+.2*n,e>.9&&(l=(e-.9)/.1*.2)}return{position:[0,s,n],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},ee={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=0,h=1,l=1,c=0;if(t<.1){const e=t/.1,s=1-Math.pow(1-e,3);n=.15*s*i,r=.3*-s*i,l=1+.8*s,c=.6*s,o=.1*Math.sin(e*Math.PI*4)*s}else if(t<.25){const e=(t-.1)/.15,n=e*e;s=.25*-n*i,r=(.8*n-.3)*i,o=.4*n*i,e>.8&&(h=1-(e-.8)/.2*.15),l=1.8-.6*e,c=.6-.4*e}else if(t<.35){const e=(t-.25)/.1;s=-.25*i,r=.5*i,o=.4*i,o+=.03*Math.sin(e*Math.PI*6)*(1-e),h=.85,l=1-.3*e}else if(t<.45){const e=(t-.35)/.1,n=1-Math.pow(1-e,2);s=(.15*n-.25)*i,r=(.5-.3*n)*i,o=(.4-.2*n)*i,h=.85+.1*n,l=.7+.4*n}else if(t<.55){const e=(t-.45)/.1,n=e*e;s=(-.1-.15*n)*i,r=(.2+.35*n)*i,o=(.2+.25*n)*i,h=.95-.12*n,e>.7&&(c=(e-.7)/.3*.3),l=1.1-.4*e}else if(t<.75){const e=(t-.55)/.2;s=-.25*i,r=.55*i,o=.45*i,h=.83;const n=.02*Math.sin(e*Math.PI*4)*Math.sin(e*Math.PI);o+=n,l=.6+2*n}else if(t<.9){const e=(t-.75)/.15,n=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;s=(.25*n-.25)*i,r=(.55-.55*n)*i,o=(.45-.45*n)*i,h=.83+.17*n,l=.6+.5*n}else{const e=(t-.9)/.1;s=0,r=0,o=Math.sin(e*Math.PI*6)*(1-e)*.08*i,a=Math.sin(e*Math.PI*8)*(1-e)*.1*i,h=1,l=1+.2*Math.sin(e*Math.PI*3)*(1-e),c=.2*Math.sin(e*Math.PI)}return{position:[0,s,n],rotation:[r,a,o],scale:h,glowIntensity:l,glowBoost:c}}}},ie={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.maxScale||1.4,r=i.holdTime||.3,a=!1!==i.deflate;let o;const h=.5*(1-r),l=1-h;t<h?(o=t/h,o=1-Math.pow(1-o,2)):t<l||!a?o=1:(o=1-(t-l)/h,o=Math.pow(o,2));const c=1+(n-1)*o*s,u=.08*o*s,d=1+.4*o*s,p=.3*o,m=o>.8?.02*Math.sin(t*Math.PI*8):0;return{position:[m,u,0],rotation:[0,0,2*m],scale:c,glowIntensity:d,glowBoost:p}}}},se={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.minScale||.6,r=i.droop||.15,a=!1!==i.reinflate;let o;return t<.5?(o=t/.5,o=Math.pow(o,.7)):t<.7||!a?o=1:(o=1-(t-.7)/.3,o=Math.pow(o,1.5)),{position:[0,-o*r*s,0],rotation:[.15*o*s,0,.1*o*s],scale:1-(1-n)*o*s,glowIntensity:1-.4*o,glowBoost:0}}}},ne={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.squashAmount||.5,r=i.stretchAmount||1.5,a=!1!==i.bounce;let o;if(t<.15)o=t/.15,o=1-Math.pow(1-o,3);else if(a){const e=(t-.15)/.85,i=Math.exp(4*-e);o=Math.cos(e*Math.PI*3)*i,o=Math.max(0,o)}else o=0;const h=1+o*(r-1)*s;return{position:[0,.15*-o*s,0],rotation:[0,0,0],scale:[h,1-o*(1-n)*s,h],glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.6:0}}}},re={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.stretch={offsetX:n,offsetY:r,startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.stretch?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.stretch,o={...this.config,...i},h=i.strength||1;let l,c,{scaleX:u}=o,{scaleY:d}=o;if(o.preserveArea&&1!==u&&1!==d){const t=u*d,e=Math.sqrt(1/t);u*=e,d*=e}if(o.alternate)if(e<.5){const t=2*e;u=1+(u-1)*this.getElasticProgress(t,o),d=1+(1/u-1)*(o.preserveArea?1:0)}else{const t=2*(e-.5);u+=(1-u)*this.getElasticProgress(t,o),d=1+(d-1)*this.getElasticProgress(t,o)}else{const t=this.getElasticProgress(e,o);u=1+(u-1)*t*h,d=1+(d-1)*t*h}if(o.centerBased?(l=n+a.offsetX*u,c=r+a.offsetY*d):(l=a.startX*u,c=a.startY*d),t.x=l,t.y=c,t.vx=a.offsetX*(u-1)*h*.1,t.vy=a.offsetY*(d-1)*h*.1,e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},getElasticProgress(t,e){if(!e.elastic)return this.easeInOutCubic(t);if(0===t)return 0;if(1===t)return 1;const i=e.overshoot||.1;if(t<.5){const e=2*t;return.5*this.easeInElastic(e,i)}{const e=2*(t-.5);return.5+.5*this.easeOutElastic(e,i)}},cleanup(t){if(t.gestureData?.stretch){const e=t.gestureData.stretch;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.stretch}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeInElastic:(t,e)=>0===t?0:1===t?1:-Math.pow(2,10*(t-1))*Math.sin((t-1-.075)*(2*Math.PI)/.3)*(1+e),easeOutElastic:(t,e)=>0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((t-.075)*(2*Math.PI)/.3)*(1+e)+1,"3d":{evaluate(t,e){const{particle:i}=e;if(!i||!i.gestureData?.stretch)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=e.config||{},n=e.strength||1;let r;if(s.elastic){const e=s.overshoot||.1;if(t<.5){const i=2*t,s=.3,n=s/4;r=-Math.pow(2,10*(i-1))*Math.sin((i-1-n)*(2*Math.PI)/s)*(1+e)*.5}else{const i=2*(t-.5),s=.3,n=s/4;r=.5+.5*(Math.pow(2,-10*i)*Math.sin((i-n)*(2*Math.PI)/s)*(1+e)+1)}}else r=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;let a,o=1;if(t>.8){const e=(t-.8)/(1-.8);o=1-e*e*e}a=s.alternate?t<.5?2*t*.8:.8-2*(t-.5)*1.4:1*r*n;const h=1+a*o;return{position:[0,0,0],rotation:[0,0,.1*Math.sin(t*Math.PI*4)*r*o],scale:h}}}},ae={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.squashAmount||.2,r=i.stretchAmount||2,a=.1+.6*(i.holdRatio||.5);let o=0,h=0;if(t<.1){const e=t/.1;o=1-Math.pow(1-e,2)}else if(t<a){o=1;const e=(t-.1)/(a-.1);h=Math.sin(e*Math.PI*4)*(1-e)*.02}else{const e=(t-a)/(1-a);if(o=1-(e<.3?e/.3*.3:.3+(e-.3)/.7*.7),e>.8){const t=(e-.8)/.2,i=.15*Math.sin(t*Math.PI);o=Math.max(0,o-i)}}const l=1+o*(r-1)*s;let c=1,u=0;return t<.15?(c=1+.8*(1-t/.15),u=.6*(1-t/.15)):t<a?(c=1.3,u=.2):c=1.3-(t-a)/(1-a)*.3,{position:[h*s,.2*-o*s,0],rotation:[0,0,2*h*s],scale:[l,1-o*(1-n)*s,l],glowIntensity:c,glowBoost:u}}}},oe={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.2){const e=t/.2,o=e*e;n=.05*-o*i,r=.15*o*i;const l=Math.sin(80*t)*o*.02;a=l*i,s=.02*l*i,h=1+.3*o}else if(t<.6){const e=(t-.2)/.4,c=e*e;n=(-.05-.03*c)*i,r=(.15+.1*c)*i;const u=.02+.04*c,d=100+50*e,p=Math.sin(t*d)*u;a=p*i,s=.03*p*i,o=1+.1*c,h=1.3+.7*c,l=.5*c}else if(t<.8){const e=(t-.6)/.2;n=(.15*e-.08)*i,r=(.25-.4*e)*i,a=Math.sin(150*t)*(1-.5*e)*.05*i,o=1.1+.08*Math.sin(e*Math.PI),h=2-.3*e,l=.5+.3*Math.sin(e*Math.PI)}else{const e=(t-.8)/.2,s=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;n=(.07-.07*s)*i,r=(.15*s-.15)*i,a=Math.sin(50*t)*(1-s)*.02*i,o=1.1-.1*s,h=1.7-.7*s,l=.5*(1-s)}return{position:[s,n,0],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},he={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=1,o=1,h=0;if(t<.2){const e=t/.2,n=1-Math.pow(1-e,3);a=1+.15*n*i;const l=Math.sin(120*t)*n*.04;r=l*i,s=.02*l*i,o=1+1.2*n,h=.7*n}else if(t<.5){const e=(t-.2)/.3;a=1.15+.03*Math.sin(e*Math.PI*3);const l=.05*Math.sin(150*t)*(1-.3*e);r=l*i,s=.025*l*i,n=.1*Math.sin(e*Math.PI)*i,o=2.2-.3*e,h=.7-.2*e}else{const e=(t-.5)/.5,s=e*e;a=1.15-.15*s,r=Math.sin(80*t)*(1-s)*.03*i,n=.1*(1-s)*i,o=1.9-.9*s,h=.5*(1-s)}return{position:[s,0,0],rotation:[n,0,r],scale:a,glowIntensity:o,glowBoost:h}}}},le={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.25){const e=t/.25,a=e*e;n=.08*a*i,r=.15*-a*i,s=.03*-a*i,o=1+.05*a,h=1+.4*a}else if(t<.4){const e=(t-.25)/.15;n=(.08+.02*e)*i,r=(-.15-.1*e)*i,s=(.05*e-.03)*i,o=1.05+.08*e,h=1.4+.5*e,l=.4*e}else if(t<.6){const e=(t-.4)/.2,c=1-Math.pow(1-e,3);n=(.1-.2*c)*i,r=(.4*c-.25)*i,s=(.02+.08*c)*i,o=1.13+.12*c,h=1.9+.6*c,l=.4+.4*c,a=Math.sin(e*Math.PI*20)*(1-e)*.02*i}else{const e=(t-.6)/.4,c=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;n=-.1*(1-c)*i,r=.15*(1-c)*i,s=.1*(1-c)*i,o=1.25-.25*c,a=Math.sin(e*Math.PI*8)*(1-c)*.015*i,h=2.5-1.5*c,l=.8-.8*c}return{position:[0,s,n],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},ce={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=0,h=1,l=1,c=0;if(t<.2){const e=t/.2,s=e*e;n=.08*-s*i,r=.1*s*i,a=.25*s*i,h=1-.05*s,l=1+.4*s}else if(t<.6){const e=(t-.2)/.4,s=1-Math.pow(1-e,2);r=(.1-.35*s)*i,a=(.25+.1*s)*i,n=(.06*s-.08)*i,h=.95+.15*s,l=1.4+.6*s,c=.4*s,o=Math.sin(e*Math.PI*10)*s*.02*i}else if(t<.85){const e=(t-.6)/.25;r=-.25*i,a=(.35-.1*e)*i;const n=Math.sin(e*Math.PI*15)*(1-e)*.04;o=n*i,s=.02*n*i,h=1.1+.05*Math.sin(e*Math.PI),l=2-.3*e,c=.4*(1-.5*e)}else{const e=(t-.85)/.15,s=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;r=-.25*(1-s)*i,a=.25*(1-s)*i,n=-.02*(1-s)*i,h=1.1-.1*s,l=1.7-.7*s,c=.2*(1-s)}return{cameraRelativePosition:[s,n,r],rotation:[a,0,o],scale:h,glowIntensity:l,glowBoost:c}}}},ue={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.wobbleRadius||.08,r=i.wobbleAngle||.2,a=i.rotations||2,o=i.decay||.5,h=t*a*Math.PI*2,l=1-o*t,c=Math.sin(h)*n*l*s,u=Math.cos(h)*n*l*s,d=Math.cos(h)*r*l*s,p=Math.sin(h)*r*l*s;return{position:[c,.02*Math.sin(2*h)*l*s,u],rotation:[d,0,p],scale:1+.05*Math.sin(2*h)*l,glowIntensity:1+.2*Math.sin(h)*l,glowBoost:0}}}},de={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.tiltAngle||.25,r=i.frequency||3,a=i.irregularity||.3,o=(Math.sin(t*r*Math.PI*2)+Math.sin(t*(r+1.7)*Math.PI*2)*a+Math.sin(t*(.5*r)*Math.PI*2)*a*.5)/(1+1.5*a),h=o*n*s*.7,l=Math.sin(t*r*Math.PI*2+.5)*n*s*.5;return{position:[.15*l,0,.1*h],rotation:[h,0,l],scale:1+.05*Math.abs(o),glowIntensity:1+.2*Math.abs(o),glowBoost:0}}}},pe={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rockAngle||.15,r=t*(i.rockCycles||2)*Math.PI*2,a=Math.sin(r),o=a*n*s,h=.05*a*s;return{position:[0,.02*Math.abs(a)*s,h],rotation:[o,0,0],scale:1+.02*Math.sin(.5*r),glowIntensity:1+.1*a,glowBoost:0}}}},me={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.swingAngle||.4,r=i.swings||2,a=i.damping||.3,o=t*r*Math.PI*2,h=1-a*t,l=Math.sin(o)*h,c=l*n*s;return{position:[.1*l*s,.03*-Math.abs(l)*s,0],rotation:[0,0,c],scale:1,glowIntensity:1+.15*Math.abs(l),glowBoost:0}}}};function ge(t){const e={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=e[t]||e.front;return{name:`crack${t.charAt(0).toUpperCase()+t.slice(1)}`,emoji:"๐",type:"override",category:"reactions",description:`Surface cracks spreading from ${t} impact`,config:{duration:2e3,strength:1,glowStrength:.3,holdTime:500},rhythm:{enabled:!0,syncMode:"accent",strengthSync:{onBeat:1.2,offBeat:.8}},"3d":{evaluate(t,e){const s={strength:1,glowStrength:.3,...e},{strength:n,glowStrength:r}=s,a=.03*Math.max(0,1-4*t)*n,{recoilDir:o}=i,h=t<.05;return{cameraRelativePosition:[o[0]*a,o[1]*a,o[2]*a],crack:{enabled:!0,trigger:h,amount:n,propagation:.8,screenOffset:i.screenOffset,screenDirection:i.screenDirection,glowStrength:r}}}}}}const fe=ge("front"),ye=ge("back"),Me=ge("left"),be=ge("right"),we=ge("up"),ve=ge("down"),Se={name:"crackHeal",emoji:"โจ",type:"override",category:"reactions",description:"Heal and fade existing cracks",config:{duration:1500,glowStrength:.5},"3d":{evaluate(t,e){const i={duration:1500,...e},s=t<.05;return{cameraRelativePosition:[0,.02*Math.sin(t*Math.PI),0],crack:{enabled:!1,heal:!0,healTrigger:s,healDuration:i.duration},glowBoost:.1*Math.sin(t*Math.PI)}}}};var ke={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=Math.random()*Math.PI*2,r=.5+.5*Math.random();t.gestureData.shatter={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,velocityX:Math.cos(n)*r,velocityY:Math.sin(n)*r,tumbleAngle:0,tumbleSpeed:4*(Math.random()-.5),frozenX:null,frozenY:null,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.shatter?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=a.distance||100,l=t.gestureData.shatter,c=a.explosionPhase||.3,u=a.freezePhase||.7;if(e<c){const i=e/c,s=1-Math.pow(1-i,3),n=l.velocityX*h*s*o,r=l.velocityY*h*s*o;t.x=l.originalX+n,t.y=l.originalY+r,l.tumbleAngle+=l.tumbleSpeed*(1-i)}else if(e<u){const i=(e-c)/(u-c),s=l.originalX+l.velocityX*h*o,n=l.originalY+l.velocityY*h*o,r=l.velocityX*h*.2*i*o,a=l.velocityY*h*.2*i*o;t.x=s+r,t.y=n+a,l.tumbleAngle+=.3*l.tumbleSpeed*(1-i),i>.95&&null===l.frozenX&&(l.frozenX=t.x,l.frozenY=t.y)}else if(null!==l.frozenX&&(t.x=l.frozenX,t.y=l.frozenY),e>.9){const i=(e-.9)/.1;t.opacity=l.originalOpacity*(1-.5*i)}},cleanup(t){if(t.gestureData?.shatter){const e=t.gestureData.shatter;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.shatter}},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1;let s=1,n=1,r=1,a=0,o=0,h=0,l=0,c=0,u=0,d=1,p=0;if(t<.1){const e=t/.1,a=1-Math.pow(1-e,2);n=1-.4*a*i,s=1+.2*a*i,r=1+.2*a*i,c=.1*-a*i,d=1+1*a,p=.8*a}else if(t<.4){const e=(t-.1)/.3,m=1-.6*e,g=40,f=Math.sin(t*g*Math.PI)*m,y=Math.cos(t*g*1.3*Math.PI)*m,M=Math.sin(t*g*.7*Math.PI)*m,b=1+.3*(1-Math.pow(1-e,2))*i;s=b+.15*f*i,n=b+.15*y*i,r=b+.15*M*i,a=.4*f*i,o=.5*y*i,h=.3*M*i,l=.15*f*i,c=.12*y*i+.1*e,u=.1*M*i,d=1.5+.5*Math.abs(f),p=.5*m}else if(t<.7){const e=(t-.4)/.3,a=e*e,o=1-a,l=20*o,u=Math.sin(t*l*Math.PI)*o,m=1.3-.4*a;s=m+.05*u*i,n=m+.05*u*i,r=m+.05*u*i,h=.15*u*i,c=.1*o,d=1.5-.3*a,p=.3*o}else{const e=(t-.7)/.3,i=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,a=Math.sin(e*Math.PI*2)*(1-e)*.05;if(s=.9+.1*i+a,n=.9+.1*i+a,r=.9+.1*i+a,d=1.2-.2*i,t>.95){const e=(t-.95)/.05;p=.3*Math.sin(e*Math.PI)}}return{position:[l,c,u],rotation:[a,o,h],scale:[s,n,r],glowIntensity:d,glowBoost:p}}}};const xe={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 Ee(t="default"){const e=xe[t]||xe.default;return{name:e.name,emoji:e.emoji,type:"override",description:e.description,config:{duration:e.duration,musicalDuration:{musical:!0,beats:e.beats},intensity:e.intensity,variant:t},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:e.beats},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.intensity||1,n=i.variant||"default",r=xe[n]||xe.default,a=r.useDeformation||!1,o=r.direction||"front";let h=!1,l=!1,c=1,u=0,d=1,p=null,m=null,g=null;const f=r.reassemble,y=r.reassembleAt||.5;if(a){let e;if(t<.3){const i=t/.3;e=i*(2-i)}else e=0;let i=0;t<.25?i=t/.25:t<.3&&(i=1);const n=.15*s,a=.25*s;let l=0,d=0;const f=0;let y=0,M=0;switch(o){case"left":l=e*n,M=-e*a;break;case"right":l=-e*n,M=e*a;break;case"front":d=-e*n,y=e*a*.7}if(e>0&&(m=[l,f,d],g=[y,0,M]),i>0&&(p={enabled:!0,strength:i*s*2.5,impactPoint:r.impactPoint,falloffRadius:.5}),t>=.28&&t<.32&&(h=!0),t<.35){const e=t/.35;c=1+.8*(1-e),u=.5*(1-e)}}else{const e=void 0!==r.shatterTriggerAt?r.shatterTriggerAt:.1,i=e+.02;if(t<e){if(e>0){const i=t/e,s=i*i;c=1+.6*s,u=.3*s,d=1+.05*s,"explosive"===n&&(d+=.01*Math.sin(200*t)*i)}}else if(t<i)h=t>=e&&t<e+.005,c=1.6,u=.4,d=1.05;else{if(f&&t>=y&&t<y+.02&&(l=!0),f&&t>=y){const e=(t-y)/(1-y),i=e*e;c=1+.8*i,u=.5*i,t>.95&&(c=2,u=.8)}else{const e=(t-i)/(f?y-i:1-i),s=Math.min(1,e),n=1-(1-s)*(1-s);c=1.6-.6*n,u=.4-.4*n}d=1}}const M={scale:d,glowIntensity:c,glowBoost:u,shatter:{enabled:h,impactPoint:r.impactPoint,impactDirection:r.impactDirection||[0,0,-1],intensity:s*r.intensity,variant:n,reassemble:l,reassembleDuration:r.reassembleDuration||1e3,revealSoul:!1!==r.revealSoul,isSuspendMode:r.isSuspendMode||!1,suspendAt:r.suspendAt||.25,suspendDuration:r.suspendDuration||.35,isFreezeMode:r.isFreezeMode||!1,gravity:r.gravity,explosionForce:r.explosionForce,rotationForce:r.rotationForce,gestureDuration:r.duration,isDualMode:r.isDualMode||!1,dualModeType:r.dualModeType,dualModeConfig:{duration:r.dualModeDuration||2e3,impactPoint:r.impactPoint,windDirection:r.windDirection,windForce:r.windForce,turbulence:r.turbulence,waveSpeed:r.waveSpeed,floorY:r.floorY,orbitSpeed:r.orbitSpeed,radiusMultiplier:r.radiusMultiplier,reassemble:r.reassemble,reassembleDuration:r.reassembleDuration}}};return p&&(M.deformation=p),m&&(M.cameraRelativePosition=m),g&&(M.cameraRelativeRotation=g),M}}}}const Be={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 Ae(t="away"){const e=Be[t]||Be.away;return{name:e.name,emoji:e.emoji,type:"override",description:e.description,config:{duration:3500,musicalDuration:{musical:!0,beats:6},intensity:.7,direction:t},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:6},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.2}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.intensity||.7,n=i.direction||"away",r=Be[n]||Be.away;let a=!1,o=1,h=0,l=1;const c=.06;if(t<c){const e=t/c;o=1+.4*e,h=.2*e,l=1+.03*e}else if(t<.08)a=t>=c&&t<.065,o=1.4,h=.3;else{const e=(t-c)/.94;o=1.4-.6*e,h=Math.max(0,.3-.3*e)}return{scale:l,glowIntensity:o,glowBoost:h,shatter:{enabled:a,impactPoint:[0,0,0],impactDirection:r.impactDir||r.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:r.windDirection,windForce:r.windForce*s,turbulence:r.turbulence}}}}}}}var Ce={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(t,e,i,s,n){t.gestureData||(t.gestureData={});const r={...this.config,...e},a=t.x,o=t.y,h=Math.atan2(t.y-s,t.x-i),l=Math.random()<.5?1:-1;let c,u;const d=r.size*t.scaleFactor,p=(r.rotation||0)*Math.PI/180*l;switch(r.pattern){case"star":c=i,u=s,this.calculateStarPosition(t,h,d,r.points,r.innerRadius,p,i,s);break;case"heart":this.calculateHeartPosition(t,h,d,p,i,s);break;case"square":this.calculateSquarePosition(t,h,d,p,i,s);break;case"triangle":this.calculateTrianglePosition(t,h,d,p,i,s);break;default:{const t=d;c=i+Math.cos(h+p)*t,u=s+Math.sin(h+p)*t;break}}t.gestureData.morph={startX:a,startY:o,targetX:t.gestureData.morphTargetX||c,targetY:t.gestureData.morphTargetY||u,originalVx:t.vx,originalVy:t.vy,rotationDirection:l,initialized:!0}},calculateStarPosition(t,e,i,s,n,r,a,o){const h=((e+Math.PI)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),l=Math.floor(h/(2*Math.PI)*10),c=l%2==0,u=Math.floor(l/2);let d;d=c?72*u*Math.PI/180:(72*u+36)*Math.PI/180,d+=r;const p=c?i:i*n;t.gestureData.morphTargetX=a+Math.cos(d)*p,t.gestureData.morphTargetY=o+Math.sin(d)*p},calculateHeartPosition(t,e,i,s,n,r){const a=(e+Math.PI)/(2*Math.PI),o=.05*i,h=16*Math.pow(Math.sin(a*Math.PI*2),3),l=-(13*Math.cos(a*Math.PI*2)-5*Math.cos(2*a*Math.PI*2)-2*Math.cos(3*a*Math.PI*2)-Math.cos(4*a*Math.PI*2)),c=Math.cos(s),u=Math.sin(s),d=h*c-l*u,p=h*u+l*c;t.gestureData.morphTargetX=n+d*o,t.gestureData.morphTargetY=r+p*o},calculateSquarePosition(t,e,i,s,n,r){const a=((e+s)%(2*Math.PI)+2*Math.PI)%(2*Math.PI);let o,h;const l=i;a<Math.PI/4||a>=7*Math.PI/4?(o=l,h=l*Math.tan(a)):a<3*Math.PI/4?(o=l/Math.tan(a),h=l):a<5*Math.PI/4?(o=-l,h=-l*Math.tan(a)):(o=-l/Math.tan(a),h=-l);const c=Math.cos(s),u=Math.sin(s),d=o*c-h*u,p=o*u+h*c;t.gestureData.morphTargetX=n+d,t.gestureData.morphTargetY=r+p},calculateTrianglePosition(t,e,i,s,n,r){const a=[{x:0,y:-i},{x:.866*-i,y:.5*i},{x:.866*i,y:.5*i}],o=Math.floor((e+Math.PI)/(2*Math.PI)*3)%3,h=(o+1)%3,l=Math.random(),c=a[o].x+(a[h].x-a[o].x)*l,u=a[o].y+(a[h].y-a[o].y)*l,d=Math.cos(s),p=Math.sin(s),m=c*d-u*p,g=c*p+u*d;t.gestureData.morphTargetX=n+m,t.gestureData.morphTargetY=r+g},apply(t,e,i,s,n,r){t.gestureData?.morph?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.morph,o={...this.config,...i};let h,l,c=e;if(o.holdTime>0){const t=.5-o.holdTime/2,i=.5+o.holdTime/2;c=e<t?e/t*.5:e<i?.5:.5+(e-i)/(1-i)*.5}if(c<=.5){const t=2*c;h=a.startX+(a.targetX-a.startX)*this.easeOutQuad(t),l=a.startY+(a.targetY-a.startY)*this.easeOutQuad(t)}else{const t=2*(c-.5);h=a.targetX+(a.startX-a.targetX)*this.easeInQuad(t),l=a.targetY+(a.startY-a.targetY)*this.easeInQuad(t)}if(o.smooth){const e=.2;t.x+=(h-t.x)*e,t.y+=(l-t.y)*e}else t.x=h,t.y=l;if(t.vx=.5*(h-t.x),t.vy=.5*(l-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.morph){const e=t.gestureData.morph;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.morph,delete t.gestureData.morphTargetX,delete t.gestureData.morphTargetY}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutQuad:t=>t*(2-t),easeInQuad:t=>t*t,"3d":{evaluate(t,e){const i=e?.strength||1,s=Math.sin(t*Math.PI);let n;if(t<=.5){const e=2*t;n=1+e*(2-e)*.25*i}else{const e=2*(t-.5);n=1.25*i+e*e*(1-1.25*i),n=Math.max(1,n)}return{position:[0,0,0],rotation:[0,s*Math.PI*.3*i,.1*Math.sin(t*Math.PI*2)*i],scale:n,glowIntensity:1+.4*s*i,glowBoost:1.5*s*i}}}},Te={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.rain={originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,originalOpacity:t.opacity??t.life??1,currentX:t.x,currentY:t.y,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(t,e,i,s){const n="number"==typeof s?s:1;t.gestureData?.rain?.initialized||this.initialize(t,i);const r=t.gestureData.rain,a={...this.config,...i},o=i?.strength||1,h=(a.fallSpeed||8)*o,l=(a.fallDistance||400)*e*o;r.wobblePhase+=r.wobbleSpeed*n*.1;const c=Math.sin(r.wobblePhase)*(a.wobbleAmount||1.5);if(t.x=r.originalX+c,t.y=r.originalY+l,t.vx=.3*c,t.vy=10*h,e>.6){const i=(e-.6)/.4;t.opacity=r.originalOpacity*(1-i),void 0!==t.life&&(t.life=r.originalOpacity*(1-i))}else t.opacity=r.originalOpacity,void 0!==t.life&&(t.life=r.originalOpacity)},cleanup(t){if(t.gestureData?.rain){const e=t.gestureData.rain;t.x=e.originalX,t.y=e.originalY,t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.originalOpacity,void 0!==t.life&&(t.life=e.originalOpacity),delete t.gestureData.rain}},"3d":{evaluate:(t,e)=>({position:[0,0,0],rotation:[0,0,0],scale:1})}},Pe={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;let a=Math.atan2(r,n);const o={...this.config,...e}.angleSpread*Math.PI/180,h=(Math.random()-.5)*o;a+=h;const l=30+30*Math.random();t.gestureData.drift={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,driftAngle:a,angleOffset:h,homeRadius:l*t.scaleFactor,homeX:i+Math.cos(a)*l,homeY:s+Math.sin(a)*l,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.drift?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.drift,o={...this.config,...i},h=i.strength||1,l=this.easeInOutCubic(e),c=Math.max(0,l-.1*a.role);let u,d,p;if(o.returnToOrigin)if(c<.4){const t=c/.4,e=this.easeOutQuad(t);u=a.startX+(a.homeX-a.startX)*e,d=a.startY+(a.homeY-a.startY)*e}else if(c<.6+o.holdTime){const e=(c-.4)/(.2+o.holdTime);p=a.homeRadius+Math.sin(e*Math.PI*.5)*o.distance*h*t.scaleFactor}else{const e=(c-.6-o.holdTime)/(.4-o.holdTime);p=a.homeRadius+Math.cos(e*Math.PI*.5)*o.distance*h*t.scaleFactor}else{const e=c;p=a.homeRadius+e*o.distance*h*t.scaleFactor}if(void 0!==p){a.turbulencePhase+=o.turbulence*s;const t=Math.sin(a.turbulencePhase)*o.turbulence*10,e=Math.cos(1.3*a.turbulencePhase)*o.turbulence*10,i=a.driftAngle+a.angleOffset;u=n+Math.cos(i)*p+t,d=r+Math.sin(i)*p+e}const m=o.smoothness+.08*a.role;if(t.x+=(u-t.x)*m,t.y+=(d-t.y)*m,t.vx=.25*(u-t.x),t.vy=.25*(d-t.y),o.fadeOut){let i;i=e<.25?.3+e/.25*.7:e<.75?.7+.3*Math.sin((e-.25)*Math.PI/.5):4*(1-e),t.opacity=a.baseOpacity*i,void 0!==t.life&&(t.life=t.opacity)}e>=.99&&(t.vx=.1*a.originalVx,t.vy=.1*a.originalVy,o.fadeOut&&(t.opacity=a.baseOpacity,void 0!==t.life&&(t.life=a.baseOpacity)))},cleanup(t){if(t.gestureData?.drift){const e=t.gestureData.drift;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.drift}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const i={...this.config,...e},s=e.strength||1,n=(i.angle||45)*Math.PI/180,r=i.returnToOrigin?t<.5?2*t:2*(1-t):t;return{position:[Math.cos(n)*r*.3*s,Math.sin(n)*r*.3*s,.15*Math.sin(t*Math.PI)*s],rotation:[0,10*r*s,0],scale:1+.03*Math.sin(t*Math.PI),glowIntensity:1-.1*r}}}};function De(t){const e=P[t];if(!e)throw new Error(`Invalid drift direction: ${t}`);const i="up"===t||"down"===t;return{name:`drift${D(t)}`,emoji:"up"===t?"โ๏ธ":"down"===t?"๐":"left"===t?"๐ซ๏ธ":"๐ญ",type:"override",description:`Gentle drifting ${t}`,config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,smoothness:.08,strength:1,direction:t,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(t,e,i,s){t.gestureData||(t.gestureData={});const n=(30+30*Math.random())*t.scaleFactor;t.gestureData.drift={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,homeRadius:n,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.drift?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.drift,l={...this.config,...n},c=n.strength||1,u=this.easeInOutCubic(s),d=Math.max(0,u-.1*h.role);let p,m=h.startX,g=h.startY;p=l.returnToOrigin?d<.5?2*d:2*(1-d):d;const f=l.distance*c*t.scaleFactor*p;h.turbulencePhase+=l.turbulence*r;const y=Math.sin(h.turbulencePhase)*l.turbulence*10,M=Math.cos(1.3*h.turbulencePhase)*l.turbulence*10;i?(g=h.startY+e.y*f+y,m=h.startX+.5*M):(m=h.startX+e.x*f+M,g=h.startY+.5*y);const b=l.smoothness+.08*h.role;if(t.x+=(m-t.x)*b,t.y+=(g-t.y)*b,t.vx=.25*(m-t.x),t.vy=.25*(g-t.y),l.fadeOut){let e=1;e=s<.25?.3+s/.25*.7:s<.75?.7+.3*Math.sin((s-.25)*Math.PI/.5):4*(1-s),t.opacity=h.baseOpacity*e}s>=.99&&(t.vx=.1*h.originalVx,t.vy=.1*h.originalVy,l.fadeOut&&(t.opacity=h.baseOpacity))},cleanup(t){if(t.gestureData?.drift){const e=t.gestureData.drift;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,delete t.gestureData.drift}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,s){const n=s||{},r=n.strength||1,a=n.distance||50,o=!1!==n.returnToOrigin?Math.sin(t*Math.PI):t,h=.004*a*r*o,l=e.x*h,c=e.y*h;let u=0,d=0;return i?u=e.y*o*.1:d=e.x*o*.15,{cameraRelativePosition:[l,c,0],rotation:[u,d,0],scale:1+.03*o,glowIntensity:1-.1*o}}}}}var Re=De("up"),Fe=De("down"),ze=De("left"),qe=De("right"),Oe={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-(i||0),r=t.y-(s||0);t.gestureData.vortex={originalX:t.x,originalY:t.y,startAngle:Math.atan2(r,n),startDistance:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.vortex?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=t.gestureData.vortex,h="outward"!==a.direction,l=a.rotationSpeed||2,c=a.pullStrength||1,u=e*l*Math.PI*2,d=o.startAngle+u;let p;p=h?1-e*c*.8:1+e*c*.5;const m=o.startDistance*p;t.x=n+Math.cos(d)*m,t.y=r+Math.sin(d)*m,h&&e>.7&&(t.opacity=1-(e-.7)/.3)},cleanup(t){if(t.gestureData?.vortex){const e=t.gestureData.vortex;t.x=e.originalX,t.y=e.originalY,t.opacity=1,delete t.gestureData.vortex}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n="outward"!==i.direction,r=i.rotationSpeed||2,a=i.liftAmount||.5,o=t*r*Math.PI*2*s;let h;h=n?1-.3*t*s:1+.2*t*s;const l=t>.85?(1-t)/.15:1;return{position:[0,Math.sin(t*Math.PI)*a*.1*s*l,0],rotation:[.1*Math.sin(o)*s*l,o,.1*Math.cos(o)*s*l],scale:h,glowIntensity:1+.4*t,glowBoost:.3*t}}}};function je(t){if(!P[t])throw new Error(`Invalid cascade direction: ${t}`);const e="up"===t||"down"===t,i="down"===t||"right"===t;return{name:`cascade${D(t)}`,emoji:"down"===t?"๐":"up"===t?"โจ":"left"===t?"๐":"๐ฌ๏ธ",type:"override",description:`Sequential cascade ${t}`,config:{duration:2e3,musicalDuration:{musical:!0,bars:1},distance:200,waveCount:4,staggerDelay:.15,wobble:1,strength:1,direction:t,particleMotion:{type:"cascade",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",distanceSync:{quiet:100,loud:300,crescendo:"expand",diminuendo:"contract"}},initialize(t,e){t.gestureData||(t.gestureData={});const i=e?.waveCount||4;let s;s=Math.floor(Math.random()*i),t.gestureData.cascade={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,waveGroup:s,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.cascade?.initialized||this.initialize(t,n);const h={...this.config,...n},l=h.strength||1,c=t.gestureData.cascade,u="number"==typeof r?r:1,d=h.waveCount||4,p=h.staggerDelay||.15,m=c.waveGroup*p,g=Math.max(0,(s-m)/(1-m*(d-1)/d));if(g<=0)return;const f=(1-Math.pow(1-g,2))*((h.distance||200)*l)*(i?1:-1);c.wobblePhase+=c.wobbleSpeed*u*.1;const y=Math.sin(c.wobblePhase)*(h.wobble||1)*10;if(e?(t.y=c.originalY+f,t.x=c.originalX+y):(t.x=c.originalX+f,t.y=c.originalY+y),g>.6){const e=(g-.6)/.4;t.opacity=c.originalOpacity*(1-e)}},cleanup(t){if(t.gestureData?.cascade){const e=t.gestureData.cascade;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.cascade}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"down",r=1-Math.pow(1-t,2);let a=0,o=0;const h=.3*r*s;switch(n){case"down":o=-h;break;case"up":o=h;break;case"left":a=-h;break;case"right":a=h}const l=.03*Math.sin(t*Math.PI*4)*s;"down"===n||"up"===n?a+=l:o+=l;const c=t>.85?(1-t)/.15:1;return{cameraRelativePosition:[a*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*r,glowIntensity:1+.2*(1-r)}}}}}var Ie=je("up"),$e=je("down"),Le=je("left"),Ge=je("right"),_e={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.confetti={originalX:t.x,originalY:t.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(t,e,i,s,n,r){t.gestureData?.confetti?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||1,h=t.gestureData.confetti,l=Math.min(e/.2,1),c=Math.max(0,(e-.2)/.8),u=-50*Math.sin(l*Math.PI)*(a.burstHeight||.3),d=c*c*200*(a.fallSpeed||1),p=20*Math.sin(e*Math.PI*8*h.tumbleSpeed)*h.flutterAmp,m=h.driftX*e*100*(a.spread||1);t.x=h.originalX+m+p*o,t.y=h.originalY+u+d*o,e>.7&&(t.opacity=1-(e-.7)/.3)},cleanup(t){t.gestureData?.confetti&&delete t.gestureData.confetti},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1,s=Math.min(t/.2,1),n=Math.max(0,(t-.2)/.8),r=.15*Math.sin(s*Math.PI)-n*n*.3,a=t*Math.PI*4,o=.3*Math.sin(1.3*a)*i,h=.4*Math.sin(.7*a)*i,l=.5*Math.sin(1.1*a)*i,c=t>.85?(1-t)/.15:1;return{position:[.08*Math.sin(t*Math.PI*6)*i*c,r*i*c,0],rotation:[o*c,h*c,l*c],scale:1+.1*Math.sin(2*a)*i,glowIntensity:1+.3*(1-n)}}}},He={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.fizz={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.4+.6*Math.random(),riseMultiplier:.7+.6*Math.random(),initialized:!0}},apply(t,e,i,s){t.gestureData?.fizz?.initialized||this.initialize(t,i);const n={...this.config,...i},r=n.strength||1,a=t.gestureData.fizz,o="number"==typeof s?s:1,h=(n.riseDistance||300)*e*r*a.riseMultiplier;a.wobblePhase+=a.wobbleSpeed*o*.1;const l=Math.sin(a.wobblePhase)*(n.wobbleAmount||2)*(1+e);if(t.x=a.originalX+l,t.y=a.originalY-h,t.vx=.3*l,t.vy=10*-(n.riseSpeed||6),e>.6){const i=(e-.6)/.4;t.opacity=a.originalOpacity*(1-i),void 0!==t.life&&(t.life=a.originalOpacity*(1-i))}},cleanup(t){if(t.gestureData?.fizz){const e=t.gestureData.fizz;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,void 0!==t.life&&(t.life=e.originalOpacity),delete t.gestureData.fizz}},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=1,r=1;if(t<.15){const e=t/.15;s=.15*e,n=1+.02*e,r=1+.15*e}else if(t<.7){const e=(t-.15)/.55;s=.5-.15*e,n=1.02+.03*Math.sin(e*Math.PI*6),r=1.2+.15*Math.sin(e*Math.PI*8)}else{const e=(t-.7)/.3;s=.35*(1-e),n=1.02-.02*e,r=1.2-.2*e}const a=35*t;return{position:[.008*Math.sin(1.7*a)*s*i,.006*Math.sin(2.3*a)*s*i,.004*Math.sin(1.9*a)*s*i],rotation:[.03*Math.sin(1.3*a)*s*i,.02*Math.sin(1.1*a)*s*i,.04*Math.sin(1.5*a)*s*i],scale:[n+.015*Math.sin(2.1*a)*s,n+.02*Math.sin(1.8*a)*s,n+.015*Math.sin(2.4*a)*s],glowIntensity:r,glowBoost:.2*s}}}};function Ue(t){const e=P[t];if(!e)throw new Error(`Invalid swarm direction: ${t}`);return{name:`swarm${D(t)}`,emoji:"up"===t?"๐ฆ
":"down"===t?"๐ฆ":"๐",type:"override",description:`Flock movement ${t}`,config:{duration:1800,musicalDuration:{musical:!0,bars:1},clusterPhase:.3,moveDistance:120,clusterTightness:.5,wobble:1,strength:1,direction:t,particleMotion:{type:"swarm",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},initialize(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.swarm={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),timeOffset:.1*Math.random(),initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.swarm?.initialized||this.initialize(t,s,r,a);const o={...this.config,...s},h=o.strength||1,l=t.gestureData.swarm,c=o.clusterPhase||.3,u=o.moveDistance||120,d=o.clusterTightness||.5,p=Math.max(0,Math.min(1,i-l.timeOffset));let m,g;if(p<c){const t=p/c,e=1-Math.pow(1-t,2);m=l.originalX+(r-l.originalX)*d*e,g=l.originalY+(a-l.originalY)*d*e}else{const t=(p-c)/(1-c),i=1-Math.pow(1-t,2),s=l.originalX+(r-l.originalX)*d,n=l.originalY+(a-l.originalY)*d;m=s+e.x*u*i*h,g=n+e.y*u*i*h}const f="number"==typeof n?n:1;l.wobblePhase+=l.wobbleSpeed*f*.1;const y=Math.sin(3*l.wobblePhase)*o.wobble*5,M=Math.cos(2.5*l.wobblePhase)*o.wobble*5;t.x=m+y,t.y=g+M,p>.8&&(t.opacity=l.originalOpacity*(1-5*(p-.8)))},cleanup(t){if(t.gestureData?.swarm){const e=t.gestureData.swarm;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.swarm}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"up",r=i.clusterPhase||.3,[a,o]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];let h=0,l=0,c=1;if(t<r)c=1-t/r*.1*s;else{const e=(t-r)/(1-r),i=1-Math.pow(1-e,2);h=a*i*.25*s,l=o*i*.25*s,c=.9+.1*e}const u=t>r?.1:0,d=t>.85?(1-t)/.15:1;return{cameraRelativePosition:[(h+.02*Math.sin(t*Math.PI*6)*s)*d,l*d,0],rotation:[o*u*s,0,-a*u*s],scale:c,glowIntensity:1+(t>r?.2:0)}}}}}var We=Ue("up"),Ye=Ue("down"),Xe=Ue("left"),Ve=Ue("right"),Ne={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(t,e,i,s,n,r){const a=i.decay||this.config.decay,o=(i.strength||this.config.strength)*(1-e*a),h=t.x-n,l=t.y-r,c=Math.sqrt(h*h+l*l);c>1&&(t.vx+=h/c*o*2*s,t.vy+=l/c*o*2*s)},"3d":{evaluate(t,e){const i=e.strength||2;let s=0,n=1,r=1,a=0;if(t<.15){const e=t/.15,o=1-Math.pow(1-e,3);s=.15*o*i,n=1+.2*o*i,r=1+.5*o,a=.4*o}else if(t<.35){const e=(t-.15)/.2;s=.15*(1-1.5*e)*i,n=1+.2*(1-e)*i-.1*Math.sin(e*Math.PI),r=1+.4*(1-e),a=.2*(1-e)}else{const e=(t-.35)/.65,a=Math.pow(1-e,2),o=Math.sin(e*Math.PI*2)*a;s=.03*o*i,n=1+.05*o,r=1+.15*Math.abs(o)}return{cameraRelativePosition:[0,0,s],position:[0,0,0],rotation:[0,0,0],scale:n,glowIntensity:r,glowBoost:a}}}};function Qe(t){const e=P[t];if(!e)throw new Error(`Invalid burst direction: ${t}`);const i="up"===t||"down"===t;return{name:`burst${D(t)}`,emoji:"up"===t?"โฒ":"down"===t?"๐ฟ":"๐จ",type:"blending",description:`Explosive burst ${t}`,config:{duration:600,musicalDuration:{musical:!0,beats:1},decay:.5,strength:2,spread:.3,direction:t,particleMotion:{type:"burst",strength:2,direction:t}},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(t,s,n,r,a,o){const h={...this.config,...n},l=h.decay||.5,c=(h.strength||2)*(1-s*l),u=h.spread||.3;let d=e.x*c*2,p=e.y*c*2;const m=(Math.random()-.5)*u*c;i?d+=m:p+=m,t.vx+=d*r,t.vy+=p*r},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||2,n=i.direction||"up";let r=0,a=0,o=0,h=1,l=1,c=0;const[u,d]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];if(t<.15){const e=t/.15,i=1-Math.pow(1-e,3);r=u*i*.2*s,a=d*i*.2*s,o=.1*i*s,h=1+.15*i*s,l=1+.5*i,c=.4*i}else if(t<.35){const e=(t-.15)/.2,i=1-1.5*e;r=.2*u*i*s,a=.2*d*i*s,o=.1*i*s,h=1+.15*(1-e)*s,l=1+.4*(1-e),c=.2*(1-e)}else{const e=(t-.35)/.65,i=Math.pow(1-e,2),n=Math.sin(e*Math.PI*2)*i;r=u*n*.05*s,a=d*n*.05*s,h=1+.05*n,l=1+.15*Math.abs(n)}return{cameraRelativePosition:[r,a,o],position:[0,0,0],rotation:[0,0,0],scale:h,glowIntensity:l,glowBoost:c}}}}}var Je=Qe("up"),Ke=Qe("down"),Ze=Qe("left"),ti=Qe("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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=a.waveCount||3,l=a.amplitude||15,c=a.damping||.7,u=t.x-n,d=t.y-r,p=Math.sqrt(u*u+d*d),m=(p/50-e*h*2)*Math.PI,g=Math.pow(1-e,c),f=Math.sin(m)*l*o*g;if(p>1){const e=.5*Math.cos(m)*o*g;t.x+=u/p*e,t.y+=d/p*e}t.opacity=Math.max(.3,1-.3*Math.abs(f/l))},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.waveCount||3,r=i.damping||.7,a=Math.pow(1-t,r),o=t*Math.PI*n*2,h=Math.sin(o),l=t*Math.PI*4,c=Math.sin(l)*s*a,u=.5*Math.sin(l+Math.PI/2)*s*a,d=.12,p=1-c*d+u*d*.3,m=1+c*d,g=1-c*d-u*d*.3,f=.08*(m-1);return{position:[.01*Math.sin(1.5*l)*a,f,0],rotation:[.04*h*s*a,0,.03*u*s*a],scale:[p,m,g],glowIntensity:1+.3*Math.abs(c),glowBoost:.25*Math.max(0,c)*a}}}},ii={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=Math.random()<.5?1:-1;t.gestureData.wave={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,angle:a,radius:o,offset:Math.random()*Math.PI*2,role:Math.random(),direction:h,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.wave?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.wave,o={...this.config,...i},h=i.strength||1,l=this.easeInOutSine(e),c=a.role*o.phaseShift,u=Math.max(0,l-c),d=u*Math.PI*2*o.frequency*a.direction+a.offset,p=.5+a.radius/100*.5,m=o.amplitude*p*h*t.scaleFactor,g=n+Math.sin(d)*m,f=r+Math.sin(2*d)*m*.3+-Math.abs(Math.sin(l*Math.PI))*o.liftHeight*t.scaleFactor,y=o.smoothness+.12*a.role;if(t.x+=(g-t.x)*y,t.y+=(f-t.y)*y,t.vx=.3*(g-t.x),t.vy=.3*(f-t.y),o.fadeInOut){let e;e=u<.1?u/.1:u>.9?(1-u)/.1:.5+.5*Math.sin(u*Math.PI),t.opacity=a.baseOpacity*(.3+.7*e),void 0!==t.life&&(t.life=t.opacity)}if(e>=.95){const i=20*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i),o.fadeInOut&&(t.opacity=a.baseOpacity*i,void 0!==t.life&&(t.life=t.opacity))}},cleanup(t){if(t.gestureData?.wave){const e=t.gestureData.wave;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.wave}},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i=e?.strength||1,s=e?.frequency||1,n=-(Math.cos(Math.PI*t)-1)/2,r=n*Math.PI*2*s,a=.12*Math.sin(r)*i,o=.06*Math.sin(2*r)*i,h=.03*Math.sin(r)*i,l=.08*Math.sin(2*r)*i,c=.05*Math.sin(r)*i,u=1+.08*Math.abs(Math.sin(n*Math.PI))*i,d=Math.abs(Math.sin(r));return{position:[a,o,h],rotation:[l,0,c],scale:u,glowIntensity:1+.3*d*i,glowBoost:.6*d*i}}}},si={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.flash={originalOpacity:t.opacity,originalSize:t.size,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.flash?.initialized||this.initialize(t,i);const a=t.gestureData.flash,o={...this.config,...i},h=o.strength||1;let l;if(l=e<.3?e/.3*o.glowPeak:o.glowPeak*(1-(e-.3)/.7),t.opacity=Math.min(1,a.originalOpacity*(1+l*h)),t.size=a.originalSize*(1+(o.scalePeak-1)*l*h*.1),e<.2){const i=(1-e/.2)*h,a=Math.atan2(t.y-r,t.x-n);t.vx+=Math.cos(a)*i*2*s,t.vy+=Math.sin(a)*i*2*s}t.vx*=1-.1*o.particleMotion.decay,t.vy*=1-.1*o.particleMotion.decay},cleanup(t){t.gestureData?.flash&&(t.opacity=t.gestureData.flash.originalOpacity,t.size=t.gestureData.flash.originalSize,delete t.gestureData.flash)},"3d":{evaluate(t,e){let i;i=t<.3?t/.3:1-(t-.3)/.7;const s=1+.4*i;return{position:[0,0,0],rotation:[0,0,0],scale:1+i*(({...this.config,...e}.scalePeak||1.1)-1),glowIntensity:s,glowBoost:2*i}}}},ni={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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.glow={startOpacity:t.opacity,startGlow:t.glowSizeMultiplier||0,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.glow?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=this.easeInOutSine(e);let h,{frequency:l}=a,{glowAmount:c}=a;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const u=o*l*2%2;h=a.holdPeak>0&&u>1-a.holdPeak&&u<1+a.holdPeak?1:Math.sin(o*Math.PI*2*l);let d=1;e>.9&&(d=.5+.5*(1-10*(e-.9))),t.glowIntensity=1+h*c*d},cleanup(t){t.gestureData?.glow&&(t.glowIntensity=1,delete t.gestureData.glow)},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i={...this.config,...e},s=-(Math.cos(Math.PI*t)-1)/2,n=Math.sin(s*Math.PI);let r=i.glowAmount||.8;e.rhythmModulation&&(r*=e.rhythmModulation.amplitudeMultiplier||1,r*=e.rhythmModulation.accentMultiplier||1);const a=1+n*r;return{position:[0,0,0],rotation:[0,0,0],scale:1+n*(i.scaleAmount||.1)*.5,glowIntensity:a,glowBoost:1.5*n}}}},ri={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-(i||0),r=t.y-(s||0);t.gestureData.bloom={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,startAngle:Math.atan2(r,n),startDistance:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.bloom?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=t.gestureData.bloom,l=Math.pow(e,.7),c=(a.rotationAmount||.3)*Math.PI,u=Math.sin(l*Math.PI)*c,d=1+.5*l*o,p=h.startDistance*d,m=h.startAngle+u;t.x=n+Math.cos(m)*p,t.y=r+Math.sin(m)*p,t.opacity=Math.min(1,h.originalOpacity*(.7+.3*l))},cleanup(t){if(t.gestureData?.bloom){const e=t.gestureData.bloom;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.bloom}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotationAmount||.3,r=Math.pow(t,.7),a=1+.2*r*s,o=Math.sin(r*Math.PI)*n*s,h=.1*Math.sin(r*Math.PI*.5)*s,l=t>.85?1-(t-.85)/.15*.3:1;return{position:[0,.05*Math.sin(r*Math.PI)*s*l,0],rotation:[0,o*l,h*l],scale:a*(.7+.3*l),glowIntensity:1+.4*r,glowBoost:.3*r}}}},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(t,e){t.gestureData||(t.gestureData={});const i={...this.config,...e},s=Math.random()<i.groupFlicker;t.gestureData.flicker={baseOpacity:t.opacity||t.life||1,baseColor:t.color,baseX:t.x,baseY:t.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(t,e,i,s,n,r){t.gestureData?.flicker?.initialized||this.initialize(t,i);const a=t.gestureData.flicker,o={...this.config,...i},h=i.strength||1;let l;if(a.flickerTimer+=s*o.flickerRate,o.strobe)l=(a.flickerTimer+a.phase)%1<.5?1:o.minOpacity;else if(o.pulseMode){const t=a.flickerTimer+a.phase;l=o.minOpacity+(o.maxOpacity-o.minOpacity)*(.5*Math.sin(t)+.5)}else{if(a.flickerTimer-a.lastFlicker>1)if(a.lastFlicker=a.flickerTimer,a.isGrouped){const t=Math.floor(a.flickerTimer)%3;a.flickerState=t===a.groupId}else a.flickerState=Math.random()>.3;const e=a.flickerState?o.maxOpacity:o.minOpacity+.3*Math.random(),i=t.opacity/a.baseOpacity;l=i+.3*(e-i)}const c=a.baseOpacity*(1+(l-1)*h);if(t.opacity=Math.max(0,Math.min(1,c)),void 0!==t.life&&(t.life=t.opacity),o.jitterAmount>0&&l>o.minOpacity){const e=o.jitterAmount*h*t.scaleFactor,i=(Math.random()-.5)*e*l,n=(Math.random()-.5)*e*l;t.vx+=.1*i*s,t.vy+=.1*n*s}if(o.colorShift&&t.color){a.colorHue+=.01*s;const e=30*Math.sin(a.colorHue);t.color=this.shiftHue(a.baseColor,e*h)}let u=1;e<.1?u=e/.1:e>.9&&(u=(1-e)/.1),t.opacity*=u,void 0!==t.life&&(t.life=t.opacity),e>.8&&(t.vx*=.95,t.vy*=.95)},shiftHue(t,e){if(!t||!t.startsWith("#"))return t;const i=t.slice(1),s=parseInt(i.substr(0,2),16)/255,n=parseInt(i.substr(2,2),16)/255,r=parseInt(i.substr(4,2),16)/255,a=e*Math.PI/180,o=Math.cos(a),h=Math.sin(a),l=s*h+n*o,c=r,u=t=>Math.max(0,Math.min(255,Math.round(255*t))).toString(16).padStart(2,"0");return`#${u(s*o-n*h)}${u(l)}${u(c)}`},cleanup(t){if(t.gestureData?.flicker){const e=t.gestureData.flicker;t.opacity=e.baseOpacity,t.color=e.baseColor,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.flicker}},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||.7,n=t*(i.flickerRate||15),r=Math.sin(n*Math.PI*2),a=Math.floor(10*n),o=.3*r+.5*(Math.sin(123.456*a)+1)*.7,h=.6+.8*o,l=i.jitterAmount||2,c=.003*s*h,u=(Math.random()-.5)*l*c,d=(Math.random()-.5)*l*c,p=.03*(Math.random()-.5)*s*h;return{position:[u,d,0],rotation:[.5*p,0,p],scale:1+.08*(h-1),glowIntensity:h,glowBoost:1.2*o}}}},oi={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=a.frequency||30,l=100*(a.amplitude||.02),c=e*h*Math.PI*2,u=(.6*Math.sin(c)+.3*Math.sin(1.7*c+1.3)+.1*Math.sin(2.3*c+2.7))*l*o,d=Math.sin(e*Math.PI);t.x+=u*d*(Math.random()-.5)*2,t.y+=u*d*(Math.random()-.5)*2},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.frequency||30,r=i.amplitude||.02,a=Math.sin(t*Math.PI),o=t*n*Math.PI*2,h=.6*Math.sin(o)+.3*Math.sin(1.7*o)+.1*Math.sin(2.3*o),l=.5*Math.cos(1.1*o)+.3*Math.cos(1.9*o)+.2*Math.cos(2.7*o);return{position:[h*r*s*a,l*r*s*a,(.4*Math.sin(.9*o+1)+.4*Math.sin(1.5*o+2))*r*.5*s*a],rotation:[.02*l*s*a,0,.02*h*s*a],scale:1+.01*Math.abs(h)*s*a,glowIntensity:1+.1*Math.abs(h)*a}}}},hi={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=this.t(e,a),l=t.x-n,c=t.y-r,u=Math.sqrt(l*l+c*c)||1,d=10*h*o;t.x+=l/u*d,t.y+=c/u*d},t(t,e){const i=e.lubDubGap||.15,s=e.lubStrength||.8,n=e.dubStrength||1;let r=0;const a=Math.abs(t-.1);a<.08&&(r=Math.cos(a/.08*Math.PI*.5)*s);const o=.1+i+.05,h=Math.abs(t-o);if(h<.1){const t=Math.cos(h/.1*Math.PI*.5)*n;r=Math.max(r,t)}return r},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.lubDubGap||.15,r=i.lubStrength||.8,a=i.dubStrength||1;let o=0;const h=Math.abs(t-.1);h<.08&&(o=Math.cos(h/.08*Math.PI*.5)*r);const l=.1+n+.05,c=Math.abs(t-l);if(c<.1){const t=Math.cos(c/.1*Math.PI*.5)*a;o=Math.max(o,t)}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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=100*(a.snapDistance||.1),l=a.overshoot||1.3,c=this.i(e,l,a.bounces||2),u=n-t.x,d=r-t.y,p=Math.sqrt(u*u+d*d)||1;t.x+=u/p*c*h*o*.1,t.y+=d/p*c*h*o*.1},i(t,e,i){if(t<.2){const i=t/.2;return(1-Math.pow(1-i,3))*e}{const s=(t-.2)/.8,n=Math.exp(4*-s);return 1+(e-1)*Math.cos(s*Math.PI*i*2)*n}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.snapDistance||.1,r=i.overshoot||1.3,a=i.bounces||2;let o;if(t<.2){const e=t/.2;o=(1-Math.pow(1-e,3))*r}else{const e=(t-.2)/.8,i=Math.exp(4*-e);o=1+(r-1)*Math.cos(e*Math.PI*a*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:t<.3?(.3-t)/.3*.4:0}}}},ci={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=200*(a.dropHeight||.15),l=a.bounceCount||3,c=a.elasticity||.6,u=this.o(e,h,l,c);t.y+=u*o;const d=.3*Math.max(0,-u/h);t.scaleY=1-d*o,t.scaleX=1+.5*d*o},o(t,e,i,s){let n=e,r=0,a=0,o=.3;for(;a<i&&r<1;){const e=o*Math.pow(s,.5*a);if(t<r+e){const i=(t-r)/e;return 4*i*(1-i)*-n}r+=e,n*=s,a++,o*=s}return 0},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.dropHeight||.15,r=i.bounceCount||3,a=i.elasticity||.6;let o=n,h=0,l=0,c=.3,u=0,d=!1;for(;l<r&&h<1;){const e=c*Math.pow(a,.5*l);if(t<h+e){const i=(t-h)/e;u=o*(4*i*(1-i))*s,d=i>.45&&i<.55;break}h+=e,o*=a,l++,c*=a}let p=1,m=1;if(d){const t=.15*s*Math.pow(a,l);p=1+t,m=1-t}return{position:[0,u,0],rotation:[0,0,0],scale:(p+m)/2,glowIntensity:1+(d?.3:0)}}}},ui={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(t){t.gestureData||(t.gestureData={}),t.gestureData.hold={holdX:t.x,holdY:t.y,originalVx:t.vx,originalVy:t.vy}},apply(t,e,i,s,n,r){t.gestureData?.hold||this.initialize(t);const a=t.gestureData.hold,o=i.holdStrength||this.config.holdStrength;if(i.allowDrift?(t.vx*=o,t.vy*=o):(t.x+=(a.holdX-t.x)*(1-o),t.y+=(a.holdY-t.y)*(1-o),t.vx=0,t.vy=0),e>.9){const i=10*(e-.9);t.vx=t.vx*(1-i)+a.originalVx*i,t.vy=t.vy*(1-i)+a.originalVy*i}},cleanup(t){if(t.gestureData?.hold){const e=t.gestureData.hold;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.hold}},"3d":{evaluate(t,e){let i=0,s=1;if(t<.15){const e=t/.15;i=e*e*(3-2*e),s=1-.2*i}else if(t<.85)i=1,s=.8;else{const e=(t-.85)/.15;i=1-e*e*(3-2*e),s=.8+.2*e}return i*=(e.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}}}},di={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(t){t.gestureData||(t.gestureData={}),t.gestureData.fade={baseOpacity:t.opacity||t.life||1}},apply(t,e,i,s,n,r){t.gestureData?.fade||this.initialize(t);const a=t.gestureData.fade,o={...this.config,...i};let h;h=o.fadeIn&&!o.fadeOut?o.minOpacity+(o.maxOpacity-o.minOpacity)*e:o.fadeOut&&!o.fadeIn?o.maxOpacity-(o.maxOpacity-o.minOpacity)*e:e<.5?o.minOpacity+(o.maxOpacity-o.minOpacity)*(2*e):o.maxOpacity-(o.maxOpacity-o.minOpacity)*(2*(e-.5)),t.opacity=a.baseOpacity*h,void 0!==t.life&&(t.life=t.opacity)},cleanup(t){t.gestureData?.fade&&(t.opacity=t.gestureData.fade.baseOpacity,void 0!==t.life&&(t.life=t.opacity),delete t.gestureData.fade)},"3d":{evaluate(t,e){const i={...this?.config||{},...e},s=i.fadeIn??!0,n=i.fadeOut??!0;let r;r=s&&!n?t:n&&!s?1-t:t<.5?1-t/.5:(t-.5)/.5;const a=r*r*(3-2*r);return{position:[0,0,0],rotation:[0,0,0],scale:.01+.99*a,glowIntensity:a,glowBoost:0}}}},pi={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(t,e,i,s,n,r){const a=i.damping||this.config.damping,o=i.threshold||this.config.threshold;t.vx*=Math.max(0,1-a*s*60),t.vy*=Math.max(0,1-a*s*60),Math.abs(t.vx)<o&&(t.vx=0),Math.abs(t.vy)<o&&(t.vy=0)},"3d":{evaluate(t,e){const i=1-Math.pow(1-t,2),s=.01*(1-i);return{position:[Math.sin(t*Math.PI*2)*s,Math.cos(t*Math.PI*3)*s*.5,0],rotation:[0,0,0],scale:1-.03*i,glowIntensity:1-.15*i}}}},mi={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(t,e,i,s,n,r){if(t.gestureData||(t.gestureData={}),!t.gestureData.peek){const e=t.x-n,i=t.y-r,s=Math.atan2(i,e),a=Math.sqrt(e*e+i*i);t.gestureData.peek={originalX:t.x,originalY:t.y,peekAngle:s,originalDistance:a,staggerDelay:this.config.stagger?.3*Math.random():0,phase:"waiting",phaseTimer:0,peekOffset:{x:0,y:0}}}const a=t.gestureData.peek,{config:o}=this,h=Math.max(0,Math.min(1,(e-a.staggerDelay)/(1-a.staggerDelay)));0===h?a.phase="waiting":h<.3?a.phase="peeking":h<.6?a.phase="holding":h<1&&(a.phase="hiding");let l=0;switch(a.phase){case"peeking":{const t=h/.3;l=this.easeOutCubic(t)*o.peekDistance;break}case"holding":l=o.peekDistance,Math.random()<.1&&(a.peekOffset.x+=2*(Math.random()-.5),a.peekOffset.y+=2*(Math.random()-.5));break;case"hiding":{const t=(h-.6)/.4;l=(1-this.easeInCubic(t))*o.peekDistance;break}}if("waiting"!==a.phase){const e=Math.cos(a.peekAngle)*l,i=Math.sin(a.peekAngle)*l;a.peekOffset.x+=(e-a.peekOffset.x)*o.peekSpeed,a.peekOffset.y+=(i-a.peekOffset.y)*o.peekSpeed,t.x=a.originalX+a.peekOffset.x,t.y=a.originalY+a.peekOffset.y}void 0!==t.alpha&&("peeking"===a.phase||"holding"===a.phase?t.alpha=.7+.3*Math.random():t.alpha=1)},easeOutCubic:t=>1-Math.pow(1-t,3),easeInCubic:t=>t*t*t,cleanup(t){t.gestureData?.peek&&(t.x=t.gestureData.peek.originalX,t.y=t.gestureData.peek.originalY,void 0!==t.alpha&&(t.alpha=1),delete t.gestureData.peek)},"3d":{evaluate(t,e){const i=.01*({...this.config,...e}.peekDistance||40);let s=0,n=1;if(t<.3){const e=t/.3;s=(1-Math.pow(1-e,3))*i}else if(t<.6)s=i,n=.7+.3*Math.random();else{const e=(t-.6)/.4;s=(1-Math.pow(e,3))*i}return{position:[s,0,0],rotation:[0,0,0],scale:1,glowIntensity:n}}}},gi={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(t){t.gestureData||(t.gestureData={}),t.gestureData.directional={initialX:t.x,initialY:t.y}},apply(t,e,i,s,n,r){t.gestureData?.directional||this.initialize(t);const a=(i.angle||this.config.angle)*Math.PI/180,o=i.strength||this.config.strength;if(t.vx+=Math.cos(a)*o*.3*s,t.vy+=Math.sin(a)*o*.3*s,i.returnToOrigin&&e>.5){const i=2*(e-.5),n=t.gestureData.directional,r=n.initialX-t.x,a=n.initialY-t.y;t.vx+=r*i*.02*s,t.vy+=a*i*.02*s}},"3d":{evaluate(t,e){const i={...this.config,...e},s=(i.angle||0)*Math.PI/180,n=e.strength||1,r=i.returnToOrigin?t<.5?2*t:2*(1-t):t;return{position:[Math.cos(s)*r*.4*n,Math.sin(s)*r*.4*n,0],rotation:[0,0,0],scale:1,glowIntensity:1}}}};function fi(t){if(!["forward","back","left","right","up","down","attract","repel"].includes(t))throw new Error(`Invalid magnetic direction: ${t}`);return{name:`magnetic${D(t)}`,emoji:{forward:"๐งฒ",back:"๐งฒ",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ",attract:"๐งฒ",repel:"๐ฅ"}[t],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"}[t],config:{duration:1200,musicalDuration:{musical:!0,beats:3},direction:t,pullStrength:1,returnToOrigin:!0,strength:1,particleMotion:{type:"magnetic",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",strengthSync:{onBeat:1.5,offBeat:.7}},initialize(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.magnetic={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.magnetic?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=a.pullStrength||1,l=!1!==a.returnToOrigin,c=t.gestureData.magnetic,u=a.direction||"attract";let d,p,m;switch(d=l?Math.sin(e*Math.PI):Math.min(1,2*e),u){case"left":p=c.originalX-100,m=c.originalY;break;case"right":p=c.originalX+100,m=c.originalY;break;case"up":p=c.originalX,m=c.originalY-100;break;case"down":p=c.originalX,m=c.originalY+100;break;case"repel":{const t=c.originalX-n,e=c.originalY-r,i=Math.sqrt(t*t+e*e)||1;p=c.originalX+t/i*100,m=c.originalY+e/i*100;break}default:p=n,m=r}const g=(p-c.originalX)*d*h*o*.5,f=(m-c.originalY)*d*h*o*.5;t.x=c.originalX+g,t.y=c.originalY+f},cleanup(t){if(t.gestureData?.magnetic){const e=t.gestureData.magnetic;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.magnetic}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"attract";let r;r=!1!==i.returnToOrigin?Math.sin(t*Math.PI):Math.min(1,2*t);let a=0,o=0,h=0,l=1;const c=.15*r*s;switch(n){case"forward":h=c,l=1+.1*r*s;break;case"back":h=-c,l=1-.08*r*s;break;case"left":a=-c;break;case"right":a=c;break;case"up":o=c;break;case"down":o=-c;break;case"attract":h=c,l=1-.1*r*s;break;case"repel":h=-c,l=1+.1*r*s}const u=1+.4*r,d=.3*r;return{cameraRelativePosition:[a+(r>.5?.01*Math.sin(t*Math.PI*20)*(r-.5)*2:0),o,h],rotation:[0,0,0],scale:l,glowIntensity:u,glowBoost:d}}}}}const yi={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i=e?.strength||1,s=Math.pow(Math.max(0,Math.sin(t*Math.PI*6)),3),n=Math.pow(Math.max(0,Math.sin(t*Math.PI*8+1)),3),r=Math.pow(Math.max(0,Math.sin(t*Math.PI*10+2)),3),a=Math.max(s,n,r)*Math.sin(t*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1+.08*a*i,glowIntensity:1+.5*a*i,glowBoost:2*a*i}}}},Mi={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:(t,e,i)=>(t.shimmerEffect=!0,t.shimmerProgress=e,!0),blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i=e?.strength||1,s=(.4*Math.sin(t*Math.PI*4)+.35*Math.sin(t*Math.PI*6+.5)+.25*Math.sin(t*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=((t,e="โจ")=>({name:t,emoji:e,type:"blending",description:`${t} 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:(t,e,i)=>!1,blend:(t,e,i)=>!1}))("groove","๐ต"),wi={},vi=[],Si=[],ki=[];function xi(t,e){wi[t.name]=t,e.push(t.name)}function Ei(t,e,i){Object.defineProperty(wi,t,{configurable:!0,enumerable:!0,get(){const i=e();return Object.defineProperty(wi,t,{configurable:!0,enumerable:!0,writable:!0,value:i}),i}}),i.push(t)}[lt,A,U,Gt,H,_,C,T,G,yi,Mi,W,bi,Dt,j,_t,Ht,nt,at,ot,ht,rt,V,N,Q,J,K,Z,$,L,It,$t,F,z,q,O,Ft,zt,qt,Ot,x,E,B,pe,me,ue,de,it,ct,dt,pt,mt,gt,st,tt,et].forEach(t=>xi(t,vi)),[xt,At,Ct,ft,Mt,bt,wt,Ce,re,Wt,Xt,Vt,Nt,Qt,ke,Tt,Pt,Ut,St,Kt,Lt,ie,se,ne,ee,te,fe,ye,Me,be,we,ve,Se,oe,he,le,ce,ae].forEach(t=>xi(t,Si)),Ei("lungeForward",()=>kt("forward"),Si),Ei("lungeBack",()=>kt("back"),Si),Ei("lungeLeft",()=>kt("left"),Si),Ei("lungeRight",()=>kt("right"),Si),Ei("lungeUp",()=>kt("up"),Si),Ei("lungeDown",()=>kt("down"),Si),Ei("recoilBack",()=>Zt("back"),Si),Ei("recoilForward",()=>Zt("forward"),Si),Ei("recoilLeft",()=>Zt("left"),Si),Ei("recoilRight",()=>Zt("right"),Si),Ei("recoilUp",()=>Zt("up"),Si),Ei("recoilDown",()=>Zt("down"),Si),Ei("oofLeft",()=>Jt("left"),Si),Ei("oofRight",()=>Jt("right"),Si),Ei("oofFront",()=>Jt("front"),Si),Ei("oofBack",()=>Jt("back"),Si),Ei("oofUp",()=>Jt("up"),Si),Ei("oofDown",()=>Jt("down"),Si),Ei("shatter",()=>Ee("default"),Si),Ei("shatterExplosive",()=>Ee("explosive"),Si),Ei("shatterCrumble",()=>Ee("crumble"),Si),Ei("shatterReform",()=>Ee("reform"),Si),Ei("shatterPunchLeft",()=>Ee("punchLeft"),Si),Ei("shatterPunchRight",()=>Ee("punchRight"),Si),Ei("shatterPunchFront",()=>Ee("punchFront"),Si),Ei("shatterSuspend",()=>Ee("suspend"),Si),Ei("shatterImplode",()=>Ee("implode"),Si),Ei("shatterGravity",()=>Ee("gravity"),Si),Ei("shatterOrbit",()=>Ee("orbit"),Si),Ei("dissolveUp",()=>Ae("up"),Si),Ei("dissolveDown",()=>Ae("down"),Si),Ei("dissolveLeft",()=>Ae("left"),Si),Ei("dissolveRight",()=>Ae("right"),Si),Ei("dissolveAway",()=>Ae("away"),Si),Ei("dissolveToward",()=>Ae("toward"),Si),Ei("rushForward",()=>vt("forward"),Si),Ei("rushBack",()=>vt("back"),Si),Ei("rushLeft",()=>vt("left"),Si),Ei("rushRight",()=>vt("right"),Si),Ei("rushUp",()=>vt("up"),Si),Ei("rushDown",()=>vt("down"),Si),[ii,Pe,Re,Fe,ze,qe,ai,Ne,gi,pi,di,ui,si,ni,mi,Te,oi,hi,_e,He,Ie,$e,Le,Ge,Je,Ke,Ze,ti,ei,ci,We,Ye,Xe,Ve,ri,li,Oe].forEach(t=>xi(t,ki)),Ei("magneticForward",()=>fi("forward"),ki),Ei("magneticBack",()=>fi("back"),ki),Ei("magneticLeft",()=>fi("left"),ki),Ei("magneticRight",()=>fi("right"),ki),Ei("magneticUp",()=>fi("up"),ki),Ei("magneticDown",()=>fi("down"),ki),Ei("magneticAttract",()=>fi("attract"),ki),Ei("magneticRepel",()=>fi("repel"),ki);const Bi={blending:vi,override:Si,effect:ki},Ai={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"]},Ci={};function Ti(t){return Ci[t]||"atmosphere"}function Pi(t){return wi[t]?wi[t]:k.getPluginGesture(t)||null}function Di(t){const e=Pi(t);return!!e&&"blending"===e.type}function Ri(t){const e=Pi(t);return!!e&&"override"===e.type}function Fi(t,e,i,s,n,r,a){const o=Pi(e);return!!o&&(o.apply&&o.apply(t,i,s,n,r,a),i>=1&&o.cleanup&&o.cleanup(t),!0)}function zi(){const t=[];return Object.values(wi).forEach(e=>{t.push({name:e.name,emoji:e.emoji||"๐ญ",type:e.type,category:Ci[e.name]||"atmosphere",description:e.description||"No description",source:"core",usesShatter:e.usesShatter||!1})}),k.getAllPluginGestures().forEach(e=>{const i=k.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}function qi(t){return wi[t]||null}function Oi(){return Object.keys(wi).filter(t=>{const e=Object.getOwnPropertyDescriptor(wi,t);return e&&"function"==typeof e.get})}Object.entries(Ai).forEach(([t,e])=>{e.forEach(e=>{Ci[e]=t})});var ji={GESTURE_REGISTRY:wi,GESTURE_TYPES:Bi,GESTURE_CATEGORIES:Ai,GESTURE_TO_CATEGORY:Ci,getGesture:Pi,getGestureCategory:Ti,isBlendingGesture:Di,isOverrideGesture:Ri,applyGesture:Fi,listGestures:zi,pluginAdapter:k},Ii=Object.freeze({__proto__:null,GESTURE_CATEGORIES:Ai,GESTURE_REGISTRY:wi,GESTURE_TO_CATEGORY:Ci,GESTURE_TYPES:Bi,applyGesture:Fi,default:ji,getGesture:Pi,getGestureCategory:Ti,getLazyGestureNames:Oi,isBlendingGesture:Di,isOverrideGesture:Ri,listGestures:zi,pluginAdapter:k,resolveGesture:qi,warmUpGestures:function({onBatch:t,onComplete:e}={}){const i=Object.keys(wi);t&&t(i.map(t=>({name:t,category:Ci[t]||"atmosphere",source:"core"})));try{const e=[];k.getAllPluginGestures().forEach(t=>{const i=k.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.length&&t&&t(e)}catch{}return e&&e(),Oi().map(t=>()=>qi(t))}});function $i(t){if(!t||0===t.length)return"#FFFFFF";let e=0,i=0;const s=[];for(const n of t)"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?e+=n.weight:i++);const n=Math.max(0,100-e),r=i>0?n/i:0,a=[];let o=0;for(const t of s)o+=null!==t.weight?t.weight:r,a.push({color:t.color,threshold:o});const h=Math.random()*o;for(const t of a)if(h<=t.threshold)return t.color;return s[s.length-1].color}var Li={name:"ambient",emoji:"โ๏ธ",description:"Gentle upward drift like smoke",initialize:function(t){t.vx=0,t.vy=-.04-.02*Math.random(),t.lifeDecay=.002,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={upwardSpeed:5e-4,waviness:0,friction:.998}},update:function(t,e,i,s){const n=t.behaviorData;t.vy*=Math.pow(n.friction,e),t.vy-=n.upwardSpeed*e,t.vx=0}};const Gi=2*Math.PI;var _i={name:"orbiting",emoji:"๐",description:"Romantic firefly dance around the orb",initialize:function(t){t.lifeDecay=.001+.002*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.isSparkle="#FFE4E1"===t.color||"#FFCCCB"===t.color||"#FFC0CB"===t.color;const e=40*(t.scaleFactor||1)*(1.3+.9*Math.random());t.blinkPhase=Math.random()*Gi,t.blinkSpeed=.3+1.2*Math.random(),t.blinkIntensity=.6+.4*Math.random(),t.fadePhase=Math.random()*Gi,t.fadeSpeed=.1+.3*Math.random(),t.minOpacity=.2+.2*Math.random(),t.maxOpacity=.8+.2*Math.random(),t.isSparkle&&(t.blinkSpeed*=2,t.blinkIntensity=1,t.minOpacity=0,t.maxOpacity=1),t.behaviorData={angle:Math.random()*Gi,radius:e,baseRadius:e,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(t,e,i,s){const n=t.behaviorData;n.angle+=n.angularVelocity*e;const r=Math.sin(n.angle*n.swaySpeed)*n.swayAmount,a=6*Math.sin(1.5*n.angle),o=(n.radius||n.baseRadius)+a+.2*r,h=i+Math.cos(n.angle)*o,l=s+Math.sin(n.angle)*o;n.floatOffset+=n.floatSpeed*e*.001;const c=Math.sin(n.floatOffset)*n.floatAmount;t.vx=.1*(h-t.x),t.vy=.1*(l+c-t.y),t.fadePhase+=t.fadeSpeed*e*.001;const u=.5*Math.sin(t.fadePhase)+.5,d=t.minOpacity+(t.maxOpacity-t.minOpacity)*u;let p;t.blinkPhase+=t.blinkSpeed*e*.002,t.isSparkle?(n.twinklePhase+=n.twinkleSpeed*e*.001,p=.7*Math.pow(Math.sin(n.twinklePhase),16)+.2*Math.sin(5*t.blinkPhase)+.1):p=.4*Math.sin(t.blinkPhase)+.3*Math.sin(3*t.blinkPhase)+.2*Math.sin(7*t.blinkPhase)+.1*Math.sin(11*t.blinkPhase);const m=.5*(p+1),g=.2+m*t.blinkIntensity*.8;t.opacity=t.baseOpacity*d*g,t.isSparkle?t.size=t.baseSize*(.5+1*m):t.size=t.baseSize*(.8+.3*m),t.isSparkle&&(t.tempColor=m>.85?"#FFFFFF":t.color)}},Hi={name:"rising",emoji:"๐",description:"Buoyant upward movement like balloons",initialize:function(t){t.vx=.02*(Math.random()-.5),t.vy=-.05-.03*Math.random(),t.lifeDecay=.002,t.baseOpacity=.7+.3*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={buoyancy:.001,driftAmount:.005}},update:function(t,e,i,s){const n=t.behaviorData;t.vy-=n.buoyancy*e,t.vx+=(Math.random()-.5)*n.driftAmount*e,t.vx*=Math.pow(.995,e),t.vy*=Math.pow(.998,e)}};function Ui(t){t.fallingData||(t.fallingData={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),fallProgress:0}),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors));const e=Math.random(),i=Math.random(),s=e*Math.PI*2,n=2*i-1,r=Math.sqrt(1-n*n);t.behaviorData={fallSpeed:8,fallDistance:400,wobbleAmount:1.5,fallingDir:{x:r*Math.cos(s),y:n,z:r*Math.sin(s)},orbitDistanceRatio:.7+.4*Math.random()}}var Wi={name:"falling",emoji:"๐ง",description:"Heavy downward drift like tears",initialize:Ui,update:function(t,e,i,s){const n=t.behaviorData;let r=t.fallingData;r||(Ui(t),r=t.fallingData),r.fallProgress+=.02*e;const a=Math.min(r.fallProgress,1),o=n.fallDistance*a;r.wobblePhase+=r.wobbleSpeed*e*.1;const h=Math.sin(r.wobblePhase)*n.wobbleAmount;if(t.x=r.originalX+h,t.y=r.originalY+o,t.vx=.3*h,t.vy=10*n.fallSpeed,a>.6){const e=(a-.6)/.4;t.opacity=r.originalOpacity*(1-e),void 0!==t.life&&(t.life=r.originalOpacity*(1-e))}}};var Yi={name:"popcorn",emoji:"๐ฟ",description:"Spontaneous popping with gravity and bounces",initialize:function(t){if(t.vx=.1*(Math.random()-.5),t.vy=.1*(Math.random()-.5),t.lifeDecay=.008+.012*Math.random(),t.emotionColors&&t.emotionColors.length>0)t.color=$i(t.emotionColors);else{const e=["#FFFFFF","#FFFACD","#FFF8DC","#FFFFE0","#FAFAD2"];t.color=$i(e)}t.size=Math.random()<.3?(8+4*Math.random())*t.scaleFactor*t.particleSizeMultiplier:(2+4*Math.random())*t.scaleFactor*t.particleSizeMultiplier,t.baseSize=t.size,t.hasGlow=Math.random()<.2,t.glowSizeMultiplier=t.hasGlow?1.2:0,t.behaviorData={popDelay:2e3*Math.random(),hasPopped:!1,popStrength:3+5*Math.random(),gravity:.098,bounceDamping:.7,bounceCount:0,maxBounces:2+Math.floor(2*Math.random()),spinRate:10*(Math.random()-.5),lifetime:0}},update:function(t,e,i,s){const n=t.behaviorData;if(n.lifetime+=16.67*e,!n.hasPopped&&n.lifetime>n.popDelay){n.hasPopped=!0;const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*n.popStrength*1.5,t.vy=Math.sin(e)*n.popStrength-.3,t.size=1.25*t.baseSize}if(n.hasPopped){t.vy+=n.gravity*e;const i=s+100*t.scaleFactor;t.y>i&&n.bounceCount<n.maxBounces&&(t.y=i,t.vy=-Math.abs(t.vy)*n.bounceDamping,t.vx*=.9,n.bounceCount++,t.size=t.baseSize*(1.5-.1*n.bounceCount)),n.bounceCount>=n.maxBounces&&(t.lifeDecay=.03+.02*Math.random(),t.size*=.95),Math.sqrt(t.vx*t.vx+t.vy*t.vy)<.5&&(t.lifeDecay*=1.5)}}},Xi={name:"burst",emoji:"๐ฅ",description:"Explosive expansion from center",initialize:function(t){const e="suspicion"===t.emotion,i="surprise"===t.emotion,s="glitch"===t.emotion,n=Math.random()*Gi,r=e?1+.8*Math.random():i?7+5*Math.random():s?2+1.5*Math.random():3.5+2.5*Math.random();t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r,t.lifeDecay=e?.01:i?.006+.008*Math.random():s?.012:.015,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),e&&(t.size=(6+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.opacity=1,t.baseOpacity=t.opacity),t.behaviorData={isSuspicion:e,isSurprise:i,isGlitch:s,age:0,fadeStart:e?.3:.2,glitchPhase:Math.random()*Math.PI*2,glitchIntensity:s?.3:0,glitchFrequency:s?.1:0}},update:function(t,e,i,s){const n=t.behaviorData;if(n.isSurprise)if(n.age+=.016*e,n.age<.15){const i=.98;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}else if(n.age<.25){const i=.85;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}else{const i=.99;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e),t.vx+=.01*(Math.random()-.5)*e,t.vy+=.01*(Math.random()-.5)*e}else{const i=n.isSuspicion?.99:n.isGlitch?.97:.95;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}if(n.isSuspicion){const i=.001*Date.now();t.vx+=.01*Math.sin(2*i+t.id)*e}if(n.isGlitch){n.age+=.016*e,n.glitchPhase+=n.glitchFrequency*e;const i=Math.sin(n.glitchPhase)*n.glitchIntensity*e,s=Math.cos(1.3*n.glitchPhase)*n.glitchIntensity*e;if(t.vx+=i,t.vy+=s,Math.random()<.02){const e=Math.random()*Math.PI*2,i=.5+.5*Math.random();t.vx+=Math.cos(e)*i,t.vy+=Math.sin(e)*i}}}},Vi={name:"aggressive",emoji:"โก",description:"Sharp, chaotic movement with violent bursts",initialize:function(t){const e=Math.random()*Gi,i=1.5+2*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.015,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={acceleration:.05,jitter:.3,speedDecay:.95}},update:function(t,e,i,s){const n=t.behaviorData;if(t.vx+=(Math.random()-.5)*n.jitter*e,t.vy+=(Math.random()-.5)*n.jitter*e,t.vx*=Math.pow(n.speedDecay,e),t.vy*=Math.pow(n.speedDecay,e),Math.random()<Math.min(.05*e,.5)){const e=Math.random()*Gi;t.vx+=Math.cos(e)*n.acceleration,t.vy+=Math.sin(e)*n.acceleration}}},Ni={name:"scattering",emoji:"๐จ",description:"Particles flee from center in panic",initialize:function(t){t.vx=0,t.vy=0,t.lifeDecay=.008,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={fleeSpeed:2,panicFactor:1.2,initialized:!1}},update:function(t,e,i,s){const n=t.behaviorData;if(!n.initialized){const e=t.x-i,r=t.y-s,a=Math.sqrt(e*e+r*r);if(a>0)t.vx=e/a*n.fleeSpeed,t.vy=r/a*n.fleeSpeed;else{const e=Math.random()*Gi;t.vx=Math.cos(e)*n.fleeSpeed,t.vy=Math.sin(e)*n.fleeSpeed}n.initialized=!0}const r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);o>0&&(t.vx+=r/o*n.panicFactor*.01*e,t.vy+=a/o*n.panicFactor*.01*e),t.vx+=.1*(Math.random()-.5)*e,t.vy+=.1*(Math.random()-.5)*e,t.vx*=Math.pow(.98,e),t.vy*=Math.pow(.98,e)}},Qi={name:"repelling",emoji:"๐ซ",description:"Particles pushed away from center, maintaining distance",initialize:function(t){t.vx=0,t.vy=0,t.lifeDecay=.01,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={repelStrength:.8,minDistance:50,initialized:!1}},update:function(t,e,i,s){const n=t.behaviorData,r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(!n.initialized||o<n.minDistance){if(o>0){const i=n.repelStrength/Math.max(o,5);t.vx+=r/o*i*e,t.vy+=a/o*i*e}n.initialized=!0}t.vx*=Math.pow(.99,e),t.vy*=Math.pow(.99,e)}},Ji={name:"connecting",emoji:"๐",description:"Chaotic movement with center attraction for social states",initialize:function(t){const e=Math.random()*Gi,i=2+5*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.012,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={attractionForce:.008,chaosFactor:1,friction:.95}},update:function(t,e,i,s){const n=t.behaviorData;t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e);const r=(i-t.x)*n.attractionForce,a=(s-t.y)*n.attractionForce,o=(Math.random()-.5)*n.chaosFactor,h=(Math.random()-.5)*n.chaosFactor;t.vx+=r+o,t.vy+=a+h}},Ki={name:"resting",emoji:"๐ด",description:"Ultra-slow vertical drift for deep rest states",initialize:function(t){t.vx=0,t.vy=-.01,t.lifeDecay=.001,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={upwardSpeed:2e-5,friction:.999}},update:function(t,e,i,s){const n=t.behaviorData;t.vy*=Math.pow(n.friction,e),t.vy-=n.upwardSpeed*e,t.vx=0}},Zi={name:"radiant",emoji:"โ๏ธ",description:"Particles radiate outward like sunbeams",initialize:function(t){const e=Math.random()*Gi,i=.8+.4*Math.random();if(t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.006,t.emotionColors&&t.emotionColors.length>0)t.color=$i(t.emotionColors);else{const e=["#FFD700","#FFB347","#FFA500","#FF69B4"];t.color=$i(e)}t.hasGlow=Math.random()<.7,t.glowSizeMultiplier=t.hasGlow?1.5+.5*Math.random():0,t.behaviorData={radialSpeed:.02,shimmer:Math.random()*Gi,shimmerSpeed:.1,friction:.99}},update:function(t,e,i,s){const n=t.behaviorData,r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(o>0){const i=r/o,s=a/o;t.vx+=i*n.radialSpeed*e,t.vy+=s*n.radialSpeed*e}n.shimmer+=n.shimmerSpeed*e;const h=Math.sin(n.shimmer);t.size=t.baseSize*(1+.2*h),t.opacity=t.baseOpacity*(1+.3*h),t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e)}};function ts(t){t.vx=.02*(Math.random()-.5),t.vy=-.03-.02*Math.random(),t.lifeDecay=8e-4,t.size=(6+6*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1)*1.33,t.baseSize=t.size,t.baseOpacity=.2+.2*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={ascensionSpeed:3e-4,waveFactor:.5,waveFrequency:.001,friction:.998,fadeStartDistance:100}}var es={name:"ascending",emoji:"๐ง",description:"Slow steady upward float like incense smoke",initialize:ts,update:function(t,e,i,s){const n=t.behaviorData;if(!n)return void ts(t);t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e),t.vy-=n.ascensionSpeed*e;const r=Math.sin(t.age*n.waveFrequency*1e3)*n.waveFactor;t.vx+=.001*r*e,void 0===t.initialY&&(t.initialY=t.y);const a=t.initialY-t.y;if(a>n.fadeStartDistance){const e=(a-n.fadeStartDistance)/100,i=Math.max(0,1-e);t.baseOpacity*=.995,i<.5&&(t.lifeDecay*=1.02)}Math.abs(t.vx)>.05&&(t.vx*=Math.pow(.95,e)),t.vy<-.1&&(t.vy=-.1)}},is={name:"erratic",emoji:"๐ฐ",description:"Nervous jittery movement for anxious states",initialize:function(t){const e=Math.random()*Gi,i=.1+.15*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.004,t.size=(2+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.baseOpacity=.4+.3*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={jitterStrength:.02,directionChangeRate:.1,speedVariation:.3,spinRate:.05+.1*Math.random()}},update:function(t,e){const i=t.behaviorData;if(t.vx+=(Math.random()-.5)*i.jitterStrength*e,t.vy+=(Math.random()-.5)*i.jitterStrength*e,Math.random()<Math.min(i.directionChangeRate*e,.5)){const e=Math.random()*Gi,i=Math.sqrt(t.vx*t.vx+t.vy*t.vy);t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i}const s=1+(Math.random()-.5)*i.speedVariation*e;t.vx*=s,t.vy*=s;const n=t.age*i.spinRate*1e3;t.size=t.baseSize*(1+.2*Math.sin(n)),t.opacity=t.baseOpacity*(.8+.4*Math.random()),t.vx*=Math.pow(.98,e),t.vy*=Math.pow(.98,e);const r=Math.sqrt(t.vx*t.vx+t.vy*t.vy);r>.5&&(t.vx=t.vx/r*.5,t.vy=t.vy/r*.5)}},ss={name:"cautious",emoji:"๐คจ",description:"Slow careful movement with watchful pauses",initialize:function(t){const e=Math.random()*Gi,i=.02+.03*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.001,t.life=1,t.size=(4+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.baseOpacity=.8+.2*Math.random(),t.opacity=t.baseOpacity,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={pauseTimer:2*Math.random(),pauseDuration:.5+.5*Math.random(),moveDuration:1+.5*Math.random(),isMoving:Math.random()>.5,moveTimer:0,originalVx:t.vx,originalVy:t.vy,watchRadius:50+30*Math.random()}},update:function(t,e,i,s){const n=t.behaviorData;if(n.moveTimer+=e,n.isMoving)n.moveTimer>n.moveDuration?(n.isMoving=!1,n.moveTimer=0,t.vx=0,t.vy=0):(t.vx=n.originalVx,t.vy=n.originalVy);else if(n.moveTimer>n.pauseDuration){n.isMoving=!0,n.moveTimer=0;const e=Math.random()*Gi,i=.02+.03*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,n.originalVx=t.vx,n.originalVy=t.vy}const r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(o>n.watchRadius){const i=.02;t.vx-=r/o*i*e,t.vy-=a/o*i*e}t.vx*=Math.pow(.995,e),t.vy*=Math.pow(.995,e),n.isMoving?t.opacity=t.baseOpacity:t.opacity=t.baseOpacity*(.9+.1*Math.sin(5*t.age))}},ns={name:"surveillance",emoji:"๐๏ธ",description:"Searchlight scanning with paranoid watchfulness",initialize(t,e){t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.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:t.x,y:t.y}};const i=Math.random();i<.7?t.behaviorState.primaryRole="scanner":i<.9?(t.behaviorState.primaryRole="patroller",t.behaviorState.mode="patrolling"):(t.behaviorState.primaryRole="watcher",t.behaviorState.mode="frozen")},update(t,e,i){const s=t.behaviorState;if(s){switch(s.modeTimer+=16*e,s.modeTimer>s.nextModeChange&&(this.changeMode(t,s,i),s.modeTimer=0,s.nextModeChange=2e3+4e3*Math.random()),s.mode){case"scanning":this.updateScanning(t,e,s,i);break;case"darting":this.updateDarting(t,e,s,i);break;case"frozen":this.updateFrozen(t,e,s,i);break;case"patrolling":this.updatePatrolling(t,e,s,i)}t.vy+=.05*e,t.x+=t.vx*e,t.y+=t.vy*e,s.lastPosition.x=t.x,s.lastPosition.y=t.y}},updateScanning(t,e,i,s){i.pauseTimer>0?(i.pauseTimer-=16*e,t.vx*=.9,t.vy*=.9):(i.scanAngle+=i.scanDirection*i.scanSpeed*e*.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,r=.8+.5*i.alertLevel;t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r*.3},updateDarting(t,e,i,s){const n=i.dartTarget.x-t.x,r=i.dartTarget.y-t.y,a=Math.sqrt(n*n+r*r);a>5?(t.vx=n/a*i.dartSpeed,t.vy=r/a*i.dartSpeed):(i.mode="scanning",i.modeTimer=0)},updateFrozen(t,e,i,s){t.vx*=.95,t.vy*=.95,Math.random()<.01&&(t.vx+=.5*(Math.random()-.5),t.vy+=.5*(Math.random()-.5))},updatePatrolling(t,e,i,s){i.patrolAngle+=.01*e;const n=s.corePosition?.x??s.canvasWidth/2,r=s.corePosition?.y??s.canvasHeight/2,a=n+Math.cos(i.patrolAngle)*i.patrolRadius,o=r+Math.sin(i.patrolAngle)*i.patrolRadius,h=a-t.x,l=o-t.y;t.vx=.02*h,t.vy=.02*l},changeMode(t,e,i){const s=Math.random(),n=i?.corePosition?.x??(i?.canvasWidth/2||t.x),r=i?.corePosition?.y??(i?.canvasHeight/2||t.y);"scanner"===e.primaryRole?s<.1?(e.mode="darting",e.dartTarget={x:n+200*(Math.random()-.5),y:r+200*(Math.random()-.5)},e.dartSpeed=3+2*Math.random()):e.mode=s<.2?"frozen":"scanning":"patroller"===e.primaryRole?e.mode=s<.1?"frozen":"patrolling":e.mode=s<.3?"scanning":"frozen"}},rs={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(t,e,i,s){t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.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},t.lifeDecay=.0015,t.hasGlow=!0,t.glowSizeMultiplier=3+2*Math.random()},update(t,e,i,s){const n=t.behaviorState;if(!n)return;n.glitchTimer+=16*e,n.stutterTimer+=16*e,n.stutterTimer>n.nextStutter&&(n.isFrozen?(n.isFrozen=!1,n.stutterTimer=0,n.nextStutter=100+300*Math.random(),Math.random()<.3&&(t.x+=60*(Math.random()-.5),t.y+=60*(Math.random()-.5))):(n.isFrozen=!0,n.frozenPosition={x:t.x,y:t.y},n.frozenVelocity={x:t.vx,y:t.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&&t.emotionColors&&(t.color=$i(t.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*e;const r=.5*Math.sin(n.beatPhase)+.5;if(n.beatPhase%(4*Math.PI)<.5*Math.PI?n.dropIntensity=Math.min(1,n.dropIntensity+.1*e):n.dropIntensity=Math.max(0,n.dropIntensity-.05*e),n.isFrozen)t.vx=.5*(Math.random()-.5),t.vy=.5*(Math.random()-.5);else{n.orbitAngle+=n.orbitSpeed*e*(1+.5*r);const a=n.orbitRadius*(1+.3*n.dropIntensity*Math.sin(4*n.beatPhase));let o=i+Math.cos(n.orbitAngle)*a,h=s+Math.sin(n.orbitAngle)*a*.6;if(n.isGlitching&&(o+=n.glitchOffset.x*Math.random()*.8,h+=n.glitchOffset.y*Math.random()*.8),n.rgbSplit){const t=3*(1+n.dropIntensity);o+=Math.sin(n.rgbPhase)*t,h+=Math.cos(n.rgbPhase)*t,n.rgbPhase+=.1*e}n.dropIntensity>.8&&Math.random()<.1&&(o+=30*(Math.random()-.5),h+=30*(Math.random()-.5));const l=n.isGlitching?.02:.03;t.vx=(o-t.x)*l,t.vy=(h-t.y)*l,t.vx+=(Math.random()-.5)*r*2,t.vy+=(Math.random()-.5)*r*2}t.x+=t.vx*e,t.y+=t.vy*e,Math.random()<.02&&(t.opacity=.1+.9*Math.random()),t.size=t.baseSize*(1+.3*r+.5*n.dropIntensity)}},as={name:"spaz",description:"Ultra-aggressive particles with explosive spread and chaotic motion",initialize(t,e,i,s){t.x=i,t.y=s,t.life=1,t.size=3+4*Math.random();const n=Math.random()*Math.PI*2,r=200+300*Math.random();t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r,t.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()},t.lifeDecay=8e-4,t.hasGlow=!0,t.glowSizeMultiplier=4+3*Math.random(),t.glowIntensity=1.5+.5*Math.random()},update(t,e,i,s){const n=t.behaviorState;if(n.explosionTimer+=e,n.chaosTimer+=e,0===n.explosionPhase&&n.explosionTimer<500)t.vx*=.98,t.vy*=.98,Math.random()<.1&&(t.vx+=100*(Math.random()-.5),t.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 e=Math.cos(n.chaosAngle)*n.chaosSpeed,i=Math.sin(n.chaosAngle)*n.chaosSpeed;if(t.vx=.7*t.vx+.3*e,t.vy=.7*t.vy+.3*i,n.zigzagPattern){const e=.01*n.chaosTimer;t.vx+=20*Math.sin(e),t.vy+=20*Math.cos(e)}if(n.spiralPattern){const e=.005*n.chaosTimer,i=50+30*Math.sin(.003*n.chaosTimer);t.vx+=Math.cos(e)*i*.1,t.vy+=Math.sin(e)*i*.1}}if(Math.random()<n.teleportChance){const e=Math.random()*Math.PI*2,n=200+400*Math.random();t.x=i+Math.cos(e)*n,t.y=s+Math.sin(e)*n,t.vx=200*(Math.random()-.5),t.vy=200*(Math.random()-.5)}if(t.x+=t.vx*(e/1e3),t.y+=t.vy*(e/1e3),n.sizePulse){n.sizePulsePhase+=n.sizePulseSpeed*e;const i=1+.5*Math.sin(n.sizePulsePhase);t.size=(3+4*Math.random())*i}n.colorShift&&(n.colorShiftPhase=(n.colorShiftPhase||0)+n.colorShiftSpeed*e),t.vx*=.995,t.vy*=.995,t.life-=t.lifeDecay*e,(t.life<=0||Math.abs(t.x-i)>2e3||Math.abs(t.y-s)>2e3)&&(t.life=0)},getSpawnPosition(t,e){const i=Math.random()*Math.PI*2,s=100+200*Math.random();return{x:t+Math.cos(i)*s,y:e+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}]})},os={name:"directed",emoji:"๐ฏ",description:"Focused, straight-line movement toward target",config:{speed:3,acceleration:.15,focusStrength:.8,randomness:.1,edgeBuffer:50},initialize(t,e,i,s,n){const r=e-t.x,a=i-t.y,o=Math.sqrt(r*r+a*a);if(o>0)t.vx=r/o*this.config.speed,t.vy=a/o*this.config.speed;else{const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*this.config.speed,t.vy=Math.sin(e)*this.config.speed}t.targetX=e,t.targetY=i,t.directedPhase=0},update(t,e,i,s,n,r){t.directedPhase+=.05*e;const a=t.targetX-t.x,o=t.targetY-t.y,h=Math.sqrt(a*a+o*o);if(h>10){const i=a/h*this.config.speed,s=o/h*this.config.speed;t.vx+=(i-t.vx)*this.config.acceleration*e,t.vy+=(s-t.vy)*this.config.acceleration*e,t.vx+=(Math.random()-.5)*this.config.randomness,t.vy+=(Math.random()-.5)*this.config.randomness}else{const e=Math.random()*Math.PI*2,a=100+200*Math.random();t.targetX=i+Math.cos(e)*a,t.targetY=s+Math.sin(e)*a,t.targetX=Math.max(this.config.edgeBuffer,Math.min(n-this.config.edgeBuffer,t.targetX)),t.targetY=Math.max(this.config.edgeBuffer,Math.min(r-this.config.edgeBuffer,t.targetY))}t.x+=t.vx*e,t.y+=t.vy*e,(t.x<=0||t.x>=n)&&(t.vx*=-.8,t.x=Math.max(0,Math.min(n,t.x)),t.targetX=i+300*(Math.random()-.5)),(t.y<=0||t.y>=r)&&(t.vy*=-.8,t.y=Math.max(0,Math.min(r,t.y)),t.targetY=s+300*(Math.random()-.5))},visuals:{trailLength:"medium",opacity:.9,sizeMultiplier:1,blurAmount:.2}},hs={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(t,e,i,s,n){t.vx=2*(Math.random()-.5),t.vy=-this.config.baseRiseSpeed-2*Math.random(),t.wobblePhase=Math.random()*Math.PI*2,t.wobbleSpeed=this.config.wobbleFrequency*(.8+.4*Math.random()),t.bubbleSize=.5+.5*Math.random(),t.popTimer=0,t.isFizzing=!0},update(t,e,i,s,n,r){t.wobblePhase+=t.wobbleSpeed*e;const a=Math.sin(t.wobblePhase)*this.config.wobbleAmplitude;if(t.vx=.05*a+(Math.random()-.5)*this.config.fizziness,t.vy+=this.config.gravity*e,t.vy+=(Math.random()-.5)*this.config.fizziness,Math.random()<this.config.popChance){const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*this.config.popForce,t.vy=Math.sin(e)*this.config.popForce*.7,t.popTimer=1,t.bubbleSize=.3+.7*Math.random()}t.popTimer>0&&(t.popTimer-=.05*e,t.vx*=.95,t.vy*=.95),t.x+=t.vx*e,t.y+=t.vy*e,t.y<-50&&(t.y=r+50,t.x=i+300*(Math.random()-.5),t.vy=-this.config.baseRiseSpeed-2*Math.random(),t.bubbleSize=.5+.5*Math.random()),(t.x<=0||t.x>=n)&&(t.vx*=-.5,t.x=Math.max(0,Math.min(n,t.x))),t.y>r+50&&(t.y=r,t.vy=1.5*-this.config.baseRiseSpeed),t.size=t.baseSize*t.bubbleSize*(1+.1*Math.sin(2*t.wobblePhase))},visuals:{trailLength:"short",opacity:.6,sizeMultiplier:1.2,blurAmount:.5,sparkle:!0}};const ls=new Map;var cs={registerPluginBehavior:function(t,e){return ls.has(t),!(!e.initialize||"function"!=typeof e.initialize||!e.update||"function"!=typeof e.update||(ls.set(t,{name:t,emoji:e.emoji||"๐",description:e.description||`Plugin behavior: ${t}`,initialize:e.initialize,update:e.update,isPlugin:!0}),0))},unregisterPluginBehavior:function(t){return!!ls.has(t)&&(ls.delete(t),!0)},getPluginBehavior:function(t){return ls.get(t)||null},getAllPluginBehaviors:function(){return Array.from(ls.keys())},createLegacyAdapter:function(t){return{name:t.name||"legacy",emoji:"๐",description:t.description||"Legacy plugin behavior",initialize(e){if(t.size&&(e.size="object"==typeof t.size?t.size.min+Math.random()*(t.size.max-t.size.min):t.size,e.baseSize=e.size),t.speed){const i="object"==typeof t.speed?t.speed.min+Math.random()*(t.speed.max-t.speed.min):t.speed,s=Math.random()*Math.PI*2;e.vx=Math.cos(s)*i,e.vy=Math.sin(s)*i}if(t.lifespan){const i="object"==typeof t.lifespan?t.lifespan.min+Math.random()*(t.lifespan.max-t.lifespan.min):t.lifespan;e.lifeDecay=1e3/i}t.color&&(e.color=Array.isArray(t.color)?$i(t.color):t.color),t.opacity&&(e.life="object"==typeof t.opacity?t.opacity.min+Math.random()*(t.opacity.max-t.opacity.min):t.opacity),e.behaviorData={movementType:t.movementType||"linear",turbulence:t.turbulence||0,drift:t.drift||0,acceleration:t.acceleration||0,...t.customData}},update(e,i,s,n){const r=e.behaviorData;switch(r.movementType){case"wander":e.vx+=(Math.random()-.5)*r.turbulence*i,e.vy+=(Math.random()-.5)*r.turbulence*i;break;case"fall":e.vy+=.1*i,e.vx+=(Math.random()-.5)*r.drift*i;break;case"rain":e.vy+=r.acceleration*i;break;case"orbit":{const t=e.x-s,r=e.y-n,a=Math.sqrt(t*t+r*r);if(a>0){const o=Math.atan2(r,t)+.02*i;e.x=s+Math.cos(o)*a,e.y=n+Math.sin(o)*a}break}}t.customUpdate&&t.customUpdate(e,i,s,n)}}}};const us={};function ds(t){return us[t]?us[t]:cs.getPluginBehavior(t)||null}function ps(t,e){const i=ds(e);return i&&i.initialize?(i.initialize(t),!0):"ambient"!==e&&ps(t,"ambient")}function ms(t,e,i,s,n){const r=ds(e);return!(!r||!r.update||(r.update(t,i,s,n),0))}function gs(){return[...Object.values(us).map(t=>({name:t.name,emoji:t.emoji||"๐ฏ",description:t.description||"No description",type:"core"})),...cs.getAllPluginBehaviors().map(t=>{const e=cs.getPluginBehavior(t);return{name:e.name,emoji:e.emoji||"๐",description:e.description||"Plugin behavior",type:"plugin"}})]}[Li,os,hs,_i,Hi,Wi,Yi,Xi,Vi,Ni,Qi,Ji,Ki,Zi,es,is,ss,ns,rs,as].forEach(t=>{us[t.name]=t}),"undefined"!=typeof window&&window.DEBUG_PARTICLES&&(window.ParticleBehaviors={registry:us,list:gs,get:ds});var fs={BEHAVIOR_REGISTRY:us,getBehavior:ds,initializeBehavior:ps,updateBehavior:ms,listBehaviors:gs,pluginAdapter:cs},ys=Object.freeze({__proto__:null,BEHAVIOR_REGISTRY:us,default:fs,getBehavior:ds,initializeBehavior:ps,listBehaviors:gs,pluginAdapter:cs,updateBehavior:ms});class Ms{constructor(){this.listeners=new Map,this.groups=new Map,this.stats={registered:0,removed:0,active:0},this.u={},this.p=new Map}addEventListener(t,e,i,s={},n="default"){const r=this.generateId(),a={id:r,target:t,eventType:e,handler:i,options:s,group:n,active:!0};return this.listeners.set(r,a),this.groups.has(n)||this.groups.set(n,new Set),this.groups.get(n).add(r),t.addEventListener(e,i,s),this.stats.registered++,this.stats.active++,r}removeEventListener(t){const e=this.listeners.get(t);if(!e||!e.active)return!1;e.target.removeEventListener(e.eventType,e.handler,e.options),e.active=!1;const i=this.groups.get(e.group);return i&&(i.delete(t),0===i.size&&this.groups.delete(e.group)),this.listeners.delete(t),this.stats.removed++,this.stats.active--,!0}removeGroup(t){const e=this.groups.get(t);if(!e)return 0;let i=0;for(const t of e)this.removeEventListener(t)&&i++;return i}removeAllForTarget(t){let e=0;for(const[i,s]of this.listeners.entries())s.target===t&&s.active&&this.removeEventListener(i)&&e++;return e}removeAllOfType(t){let e=0;for(const[i,s]of this.listeners.entries())s.eventType===t&&s.active&&this.removeEventListener(i)&&e++;return e}removeAll(){let t=0;for(const[e,i]of this.listeners.entries())i.active&&this.removeEventListener(e)&&t++;return t}createAutoRemove(t,e,i,s={}){const n=this.addEventListener(t,e,i,s);return{id:n,remove:()=>this.removeEventListener(n)}}once(t,e,i,s={}){const n=this.addEventListener(t,e,t=>{i(t),this.removeEventListener(n)},s);return n}debounced(t,e,i,s=250,n={}){let r;return this.addEventListener(t,e,t=>{clearTimeout(r),r=setTimeout(()=>i(t),s)},n)}throttled(t,e,i,s=100,n={}){let r=!1;return this.addEventListener(t,e,t=>{r||(i(t),r=!0,setTimeout(()=>{r=!1},s))},n)}on(t,e){this.p.has(t)||this.p.set(t,[]),this.p.get(t).push(e)}off(t,e){const i=this.p.get(t);if(!i)return;const s=i.indexOf(e);-1!==s&&i.splice(s,1),0===i.length&&this.p.delete(t)}emit(t,e=null){const i=this.p.get(t);if(i)for(let t=0;t<i.length;t++)try{i[t](e)}catch(t){}}removeAllListeners(t=null){if(t){const e=this.p.get(t),i=e?e.length:0;return this.p.delete(t),i}let e=0;for(const t of this.p.values())e+=t.length;return this.p.clear(),e}listenerCount(t){const e=this.p.get(t);return e?e.length:0}getEventNames(){return Array.from(this.p.keys())}getEventStats(){let t=0;for(const e of this.p.values())t+=e.length;return{domListeners:this.stats.active,emitterEvents:this.p.size,emitterListeners:t}}getDebugInfo(){const t={};for(const[e,i]of this.p)t[e]=i.length;return{domStats:this.getStats(),emitterEvents:t,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 t=[];for(const[e,i]of this.listeners.entries())i.active&&t.push({id:e,eventType:i.eventType,group:i.group,target:i.target.constructor.name});return t}analyzeLeaks(){const t={totalListeners:this.listeners.size,activeListeners:this.stats.active,inactiveButNotRemoved:0,byTarget:new Map,byType:new Map,potentialLeaks:[]};for(const[e,i]of this.listeners.entries()){const s=i.target.constructor.name;t.byTarget.set(s,(t.byTarget.get(s)||0)+1),t.byType.set(i.eventType,(t.byType.get(i.eventType)||0)+1),i.active||(t.inactiveButNotRemoved++,t.potentialLeaks.push({id:e,eventType:i.eventType,target:s}))}return t.byTarget=Object.fromEntries(t.byTarget),t.byType=Object.fromEntries(t.byType),t}cleanup(){let t=0;for(const[e,i]of this.listeners.entries())i.active||(this.listeners.delete(e),t++);return t}destroy(){const t=this.removeAll();return this.listeners.clear(),this.groups.clear(),this.p.clear(),this.u=null,this.stats={registered:0,removed:0,active:0},t}}const bs=new Ms,ws={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,TRACE:5},vs=new class{constructor(t={}){this.config={enabled:!1!==t.enabled,level:t.level||ws.INFO,enableProfiling:!1!==t.enableProfiling,enableErrorTracking:!1!==t.enableErrorTracking,enableMemoryTracking:!1!==t.enableMemoryTracking,maxLogEntries:t.maxLogEntries||1e3,maxProfileEntries:t.maxProfileEntries||500,...t},this.m=new Array(t.maxLogEntries||1e3),this.M=0,this.v=0,this.errors=[],this.profiles=new Map,this.memorySnapshots=[],this.maxFrameTimings=120,this.S=new Array(this.maxFrameTimings),this.k=0,this.B=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 e=(()=>{}).bind(console);this.A={ERROR:e,WARN:e,DEBUG:e,TRACE:e,DEFAULT:e},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",t=>{this.trackError("UNHANDLED_ERROR",t.error||new Error(t.message),{filename:t.filename,lineno:t.lineno,colno:t.colno})}),window.addEventListener("unhandledrejection",t=>{this.trackError("UNHANDLED_REJECTION",t.reason,{promise:t.promise})}))}log(t,e,i=null){if(!this.config.enabled)return;if((ws[t]||ws.INFO)>this.config.level)return;const s=this.now(),n={timestamp:s,level:t,message:e,data:i,stackTrace:this.getStackTrace()};if(this.m[this.M]=n,this.M=(this.M+1)%this.config.maxLogEntries,this.v<this.config.maxLogEntries&&this.v++,this.capabilities.console){const n=this.getConsoleMethod(t),r=`[${(s/1e3).toFixed(3)}s]`;i?n(`${r} [${t}] ${e}`,i):n(`${r} [${t}] ${e}`)}}getConsoleMethod(t){return this.A[t]||this.A.DEFAULT}getStackTrace(){if(!this.capabilities.stackTrace)return null;try{throw new Error}catch(t){return t.stack}}trackError(t,e,i={}){if(!this.config.enableErrorTracking)return;const s={timestamp:this.now(),type:t,message:e.message||String(e),stack:e.stack,context:i,count:1},n=`${t}:${e.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(t,s),this.log("ERROR",`${t}: ${e.message}`,{error:s,context:i})}startProfile(t,e={}){if(!this.config.enableProfiling)return;const i={name:t,startTime:this.now(),metadata:e,samples:[],isActive:!0};this.profiles.set(t,i),this.log("TRACE",`Started profiling: ${t}`,e)}profileSample(t,e,i=null){if(!this.config.enableProfiling)return;const s=this.profiles.get(t);if(!s||!s.isActive)return;const n={timestamp:this.now(),label:e,data:i,relativeTime:this.now()-s.startTime};s.samples.push(n)}endProfile(t){if(!this.config.enableProfiling)return null;const e=this.profiles.get(t);if(!e||!e.isActive)return null;if(e.endTime=this.now(),e.duration=e.endTime-e.startTime,e.isActive=!1,e.stats=this.calculateProfileStats(e),this.log("TRACE",`Ended profiling: ${t}`,{duration:e.duration,samples:e.samples.length,stats:e.stats}),this.profiles.size>this.config.maxProfileEntries){const t=this.profiles.keys().next().value;this.profiles.delete(t)}return{...e}}calculateProfileStats(t){if(0===t.samples.length)return{sampleCount:0};const e=[];for(let i=1;i<t.samples.length;i++)e.push(t.samples[i].relativeTime-t.samples[i-1].relativeTime);if(0===e.length)return{sampleCount:t.samples.length};const i=e.reduce((t,e)=>t+e,0)/e.length,s=Math.min(...e),n=Math.max(...e);return{sampleCount:t.samples.length,avgSampleDuration:i,minSampleDuration:s,maxSampleDuration:n,totalDuration:t.duration}}trackFrameTiming(t){this.config.enableProfiling&&(this.S[this.k]={timestamp:this.now(),frameTime:t,fps:1e3/t},this.k=(this.k+1)%this.maxFrameTimings,this.B<this.maxFrameTimings&&this.B++)}C(t,e,i,s,n=0){const r=n>0?Math.min(n,i):i,a=new Array(r),o=(e-r+s)%s;for(let e=0;e<r;e++)a[e]=t[(o+e)%s];return a}takeMemorySnapshot(t="snapshot"){if(!this.config.enableMemoryTracking||!this.capabilities.memory)return;const e={timestamp:this.now(),label:t,memory:{usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}};this.memorySnapshots.push(e),this.memorySnapshots.length>100&&this.memorySnapshots.shift(),this.log("DEBUG",`Memory snapshot: ${t}`,e.memory)}getDebugReport(){return{timestamp:this.now(),uptime:this.now()-0,config:this.config,capabilities:this.capabilities,logCount:this.v,recentLogs:this.C(this.m,this.M,this.v,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(t=>t.isActive).length,completedProfiles:Array.from(this.profiles.values()).filter(t=>!t.isActive).length,frameTimings:this.getFrameTimingStats(),memorySnapshots:this.memorySnapshots.slice(-5)}}getFrameTimingStats(){if(0===this.B)return{sampleCount:0};const t=this.C(this.S,this.k,this.B,this.maxFrameTimings),e=t.map(t=>t.frameTime),i=t.map(t=>t.fps);return{sampleCount:this.B,avgFrameTime:e.reduce((t,e)=>t+e,0)/e.length,minFrameTime:Math.min(...e),maxFrameTime:Math.max(...e),avgFPS:i.reduce((t,e)=>t+e,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.C(this.m,this.M,this.v,this.config.maxLogEntries),errors:[...this.errors],profiles:Object.fromEntries(this.profiles),frameTimings:this.C(this.S,this.k,this.B,this.maxFrameTimings),memorySnapshots:[...this.memorySnapshots],errorCounts:Object.fromEntries(this.errorCounts)}}clear(){this.m.fill(void 0),this.M=0,this.v=0,this.errors=[],this.profiles.clear(),this.S.fill(void 0),this.k=0,this.B=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:ws.INFO}),Ss=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 t=document.createElement("canvas");return!(!t.getContext("webgl")&&!t.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 t={},e=performance.now();t.jsExecutionSpeed=performance.now()-e;try{const e=document.createElement("canvas");e.width=100,e.height=100;const i=e.getContext("2d"),s=performance.now();for(let t=0;t<1e3;t++)i.fillRect(100*Math.random(),100*Math.random(),10,10);t.canvasPerformance=performance.now()-s}catch{t.canvasPerformance=null}return t}getCapabilities(){return{...this.capabilities}}getPerformance(){return{...this.performance}}generateReport(){const t=Object.entries(this.capabilities).filter(([,t])=>t).map(([t])=>t),e=Object.entries(this.capabilities).filter(([,t])=>!t).map(([t])=>t),i=t.length/Object.keys(this.capabilities).length*100;return{timestamp:Date.now(),userAgent:navigator.userAgent,supportedFeatures:t,unsupportedFeatures:e,supportPercentage:Math.round(i),performance:this.performance,recommendations:this.generateRecommendations(i)}}generateRecommendations(t){const e=[];return t<50&&e.push("Consider using the minimal build for better compatibility"),this.capabilities.webGL||e.push("WebGL not supported - advanced graphics features unavailable"),this.capabilities.webWorkers||e.push("Web Workers not supported - background processing unavailable"),this.capabilities.fetch||e.push("Fetch API not supported - consider using XMLHttpRequest polyfill"),this.performance.jsExecutionSpeed>50&&e.push("Slow JavaScript execution detected - consider performance optimizations"),this.performance.canvasPerformance>100&&e.push("Slow canvas performance detected - consider reducing visual complexity"),e}};class ks{constructor(t){this.canvas=t,this.ctx=t.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),this.ctx||(this.T=!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.T){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 t=parseInt(this.canvas.getAttribute("width"),10),e=parseInt(this.canvas.getAttribute("height"),10),i=this.canvas.getBoundingClientRect(),s=i.width,n=i.height;t>1.5*s||e>1.5*n?(this.width=s,this.height=n,this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)):(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e)}else{const t=this.canvas.getBoundingClientRect();this.width=t.width,this.height=t.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(t=>{try{t(this.width,this.height,this.dpr)}catch{}})}}onResize(t){"function"==typeof t&&this.resizeCallbacks.push(t)}handleResize(){clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{this.renderSize&&this.renderSize.width&&this.renderSize.height||this.resize()},100)}setRenderSize(t,e){this.renderSize={width:t,height:e},this.resize()}clear(){this.T||this.ctx.clearRect(0,0,this.width,this.height)}getCenter(){return{x:this.centerX,y:this.centerY}}setTransform(t=0,e=0,i=1,s=0){this.T||(this.ctx.save(),this.ctx.translate(t,e),this.ctx.rotate(s),this.ctx.scale(i,i))}restoreTransform(){this.T||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 xs(t){return 3===(t=t.replace("#","")).length&&(t=t.split("").map(t=>t+t).join("")),{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16)}}function Es(t,e,i){const s=t=>{const e=Math.round(Math.max(0,Math.min(255,t))).toString(16);return 1===e.length?`0${e}`:e};return`#${s(t)}${s(e)}${s(i)}`}function Bs(t,e,i){t/=255,e/=255,i/=255;const s=Math.max(t,e,i),n=Math.min(t,e,i),r=(s+n)/2;let a,o;if(s===n)a=o=0;else{const h=s-n;switch(o=r>.5?h/(2-s-n):h/(s+n),s){case t:a=(e-i)/h+(e<i?6:0);break;case e:a=(i-t)/h+2;break;case i:a=(t-e)/h+4}a/=6}return{h:360*a,s:100*o,l:100*r}}function As(t,e,i){t/=360,i/=100;const s=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t);let n,r,a;if(0==(e/=100))n=r=a=i;else{const o=i<.5?i*(1+e):i+e-i*e,h=2*i-o;n=s(h,o,t+1/3),r=s(h,o,t),a=s(h,o,t-1/3)}return{r:Math.round(255*n),g:Math.round(255*r),b:Math.round(255*a)}}function Cs(t,e,i){const s=xs(t),n=xs(e),r=Bs(s.r,s.g,s.b),a=Bs(n.r,n.g,n.b),o=r.h;let h=a.h;const l=h-o;l>180?h-=360:l<-180&&(h+=360);const c=As(((o+(h-o)*i)%360+360)%360,r.s+(a.s-r.s)*i,r.l+(a.l-r.l)*i);return Es(c.r,c.g,c.b)}const Ts={intense:1.6,confident:1.3,nervous:1.15,clear:1,tired:.8,subdued:.5};function Ps(t,e){if(!e||"clear"===e)return t;const i=Ts[e.toLowerCase()];return i&&1!==i?function(t,e){const i=xs(t),s=Bs(i.r,i.g,i.b);s.s=Math.max(0,Math.min(100,s.s*e));const n=As(s.h,s.s,s.l);return Es(n.r,n.g,n.b)}(t,i):t}function Ds(t){return t}function Rs(t){return t*(2-t)}function Fs(t){return t*t}function zs(t){return t<.5?2*t*t:(4-2*t)*t-1}function qs(t){return 1-Math.pow(1-t,3)}function Os(t){return t*t*t}function js(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function Is(t){const e=2*Math.PI/3;return 0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((10*t-.75)*e)+1}function $s(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375}function Ls(t){const e=2.5949095;return t<.5?Math.pow(2*t,2)*(7.189819*t-e)/2:(Math.pow(2*t-2,2)*((e+1)*(2*t-2)+e)+2)/2}function Gs(t){return Math.sin(t*Math.PI/2)}function _s(t){return-(Math.cos(Math.PI*t)-1)/2}function Hs(t,e,i,s="linear"){return e+(i-e)*("string"==typeof s?{linear:Ds,easeOutQuad:Rs,easeInQuad:Fs,easeInOutQuad:zs,easeOutCubic:qs,easeInCubic:Os,easeInOutCubic:js,easeOutElastic:Is,easeOutBounce:$s,easeInOutBack:Ls,easeOutSine:Gs,easeInOutSine:_s}[s]||Ds:s)(Math.max(0,Math.min(1,t)))}Object.fromEntries(Object.entries({neutral:"#B0B0B0",joy:"#FFD700",sadness:"#4169E1",anger:"#DC143C",fear:"#8B008B",surprise:"#FF8C00",disgust:"#9ACD32",love:"#FF69B4"}).map(([t,e])=>{const i=xs(e);return[t,`${i.r}, ${i.g}, ${i.b}`]}));const Us=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 t=d();t.forEach(t=>{this.cacheEmotion(t)}),this.cacheCommonTransitions(t),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.emotionCache.size}catch(t){this.isInitialized=!1}}cacheEmotion(t){try{const e=l(t);e&&this.emotionCache.set(t,e);const i=c(t);this.visualParamsCache.set(t,i);const s=u(t);this.modifiersCache.set(t,s)}catch(t){}}cacheCommonTransitions(t){[["neutral","joy"],["neutral","sadness"],["neutral","anger"],["joy","sadness"],["sadness","joy"],["anger","calm"],["calm","anger"]].forEach(([e,i])=>{if(t.includes(e)&&t.includes(i))try{const t=f(e,i),s=`${e}->${i}`;this.transitionCache.set(s,t)}catch(t){}})}getEmotion(t){if(!this.isInitialized)return l(t);const e=this.emotionCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,l(t))}getVisualParams(t){if(!this.isInitialized)return c(t);const e=this.visualParamsCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,c(t))}getModifiers(t){if(!this.isInitialized)return u(t);const e=this.modifiersCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,u(t))}getTransitionParams(t,e){if(!this.isInitialized)return f(t,e);const i=`${t}->${e}`,s=this.transitionCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,f(t,e))}hasEmotion(t){return this.emotionCache.has(t)}getStats(){const t=this.stats.hits+this.stats.misses,e=t>0?(this.stats.hits/t*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:`${e}%`,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 Ws{constructor(t){this.errorBoundary=t,this.state={emotion:"neutral",undertone:null,intensity:1,gesture:null,speaking:!1,audioLevel:0},this.slots=[],this.maxSlots=3,this.P=null,this.D=null,this.R=0,this.F=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 t={};return["neutral","joy","sadness","anger","fear","surprise","disgust","love","suspicion","excited","resting","euphoria","focused","glitch","calm"].forEach(e=>{const i=Us.getVisualParams(e);i&&(t[e]={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})}),t}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(t,e=null,i=500){return this.errorBoundary.wrap(()=>{let s=null,n=1;if("string"==typeof e?s=e:e&&"object"==typeof e&&(s=e.undertone??null,i=e.duration??i,n=e.intensity??1),this.interpolationCache.cachedProperties=null,this.interpolationCache.cachedRenderState=null,!m(t)&&!{}.hasOwnProperty.call(this.emotionalStates,t)){const e=[...Object.keys(this.emotionalStates),...d()],i=[...new Set(e)];throw new Error(`Invalid emotion: ${t}. 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:t,intensity:n}],this.D=t,this.state.emotion===t&&this.state.undertone===s&&this.state.intensity===n||(this.state.emotion!==t&&(i>0?(this.transitions.emotional={current:this.state.emotion,target:t,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},void 0!==this.q&&(this.q=0)):this.transitions.emotional={current:t,target:null,progress:1,duration:0,startTime:performance.now(),isActive:!1},this.state.emotion=t),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(t){this.P=t}O(t,e){this.P&&this.P(t,e)}j(){const t=this.getDominant(),e=t?t.emotion:null,i=this.D;e!==i&&(this.D=e,this.O("dominantChanged",{previous:i,current:e,intensity:t?t.intensity:0}))}setEmotionDampening(t){this.R=Math.max(0,Math.min(1,t))}getEmotionDampening(){return this.R}setNegativeEmotions(t){this.F=new Set(t)}pushEmotion(t,e=.5){return this.errorBoundary.wrap(()=>{if(!m(t)&&!{}.hasOwnProperty.call(this.emotionalStates,t))return!1;e=Math.max(0,Math.min(1,e)),this.interpolationCache.cachedProperties=null;const i=this.slots.find(e=>e.emotion===t);if(i){const s=i.intensity;i.intensity=Math.min(1,i.intensity+e),this.O("slotChanged",{emotion:t,intensity:i.intensity,action:"push"}),i.intensity>=1&&s<1&&this.O("emotionPeaked",{emotion:t,intensity:i.intensity})}else if(this.slots.length<this.maxSlots)this.slots.push({emotion:t,intensity:e}),this.O("slotChanged",{emotion:t,intensity:e,action:"push"}),e>=1&&this.O("emotionPeaked",{emotion:t,intensity:e});else{let i=0;for(let t=1;t<this.slots.length;t++)this.slots[t].intensity<this.slots[i].intensity&&(i=t);const s=this.slots[i];this.O("slotChanged",{emotion:s.emotion,intensity:0,action:"replaced"}),this.slots[i]={emotion:t,intensity:e},this.O("slotChanged",{emotion:t,intensity:e,action:"push"})}return this.I(),this.j(),!0},"push-emotion",!1)()}nudgeEmotion(t,e,i=1){e>0&&this.R>0&&this.F.has(t)&&(e*=1-this.R),this.interpolationCache.cachedProperties=null;const s=this.slots.find(e=>e.emotion===t);if(s){const n=s.intensity;s.intensity=Math.max(0,Math.min(i,s.intensity+e)),s.intensity<=0?(this.slots=this.slots.filter(t=>t!==s),this.O("slotChanged",{emotion:t,intensity:0,action:"removed"})):(this.O("slotChanged",{emotion:t,intensity:s.intensity,action:"nudge"}),s.intensity>=i&&n<i&&this.O("emotionPeaked",{emotion:t,intensity:s.intensity}))}else if(e>0)return void this.pushEmotion(t,Math.min(i,e));this.I(),this.j()}clearEmotions(){const t=this.slots.length>0;this.slots=[],this.interpolationCache.cachedProperties=null,this.state.emotion="neutral",this.state.intensity=1,t&&(this.O("slotChanged",{emotion:null,intensity:0,action:"cleared"}),this.D=null,this.O("dominantChanged",{previous:this.D,current:null,intensity:0}))}getSlots(){return this.slots}pruneEmptySlots(){const t=this.slots.length,e=this.slots.filter(t=>t.intensity<=0);if(this.slots=this.slots.filter(t=>t.intensity>0),this.slots.length!==t){this.interpolationCache.cachedProperties=null;for(const t of e)this.O("emotionDecayed",{emotion:t.emotion,intensity:0,removed:!0});this.I(),this.j()}}getDominant(){return this.slots.length?this.slots.reduce((t,e)=>e.intensity>t.intensity?e:t):null}getUndercurrents(){const t=this.getDominant();return t?this.slots.filter(e=>e!==t):[]}getEmotionalState(){const t=this.getDominant();return{dominant:t?{...t}:null,undercurrents:this.getUndercurrents().map(t=>({...t})),slots:this.slots.map(t=>({...t}))}}getCurrentRhythmModifiers(){return this.slots.length>0?b(this.slots):b([{emotion:this.state.emotion,intensity:this.state.intensity}])}I(){const t=this.getDominant();t?(this.state.emotion!==t.emotion&&(this.transitions.emotional={current:this.state.emotion,target:t.emotion,progress:0,duration:300,startTime:performance.now(),isActive:!0},this.state.emotion=t.emotion),this.state.intensity=t.intensity):(this.state.emotion="neutral",this.state.intensity=1)}applyUndertone(t,e){if(!e||!{}.hasOwnProperty.call(this.undertoneModifiers,e))return{...t};const i=this.undertoneModifiers[e],s={...t};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 t=i.amplificationFactor;s.glowIntensity*=t,s.breathRate*=t,s.particleRate=Math.round(s.particleRate*t),s.coreSize*=t}if(void 0!==i.dampeningFactor){const t=i.dampeningFactor;s.glowIntensity*=t,s.breathRate*=t,s.particleRate=Math.round(s.particleRate*t),s.coreSize*=t}return void 0!==i.jitterAmount&&(s.jitterAmount=i.jitterAmount),s}update(t){this.errorBoundary.wrap(()=>{this.transitions.emotional.isActive&&this.updateEmotionalTransition(t),this.transitions.intensity.isActive&&this.updateIntensityTransition(t),this.transitions.undertone.isActive&&this.updateUndertoneTransition(t)},"state-machine-update")()}updateUndertoneTransition(t){const e=this.transitions.undertone,i=performance.now()-e.startTime,s=Math.min(i/e.duration,1),n=js(s);e.current&&e.target?(e.currentWeight=1-n,e.targetWeight=n):e.current&&!e.target?(e.currentWeight=1-n,e.targetWeight=0):!e.current&&e.target&&(e.currentWeight=0,e.targetWeight=n),e.progress=s,s>=1&&(e.isActive=!1,e.current=e.target,e.currentWeight=e.target?1:0,e.targetWeight=0)}updateIntensityTransition(t){const e=this.transitions.intensity,i=performance.now()-e.startTime;e.progress=Math.min(1,i/e.duration),e.progress>=1&&(e.isActive=!1,e.from=e.to,e.progress=1)}getEffectiveIntensity(){const t=this.transitions.intensity;if(!t.isActive)return this.state.intensity;const e=js(t.progress);return t.from+(t.to-t.from)*e}updateEmotionalTransition(t){const e=this.transitions.emotional;let i;void 0!==this.q?(this.q+=t,i=this.q):i=performance.now()-e.startTime,e.progress=Math.min(1,i/e.duration),e.progress>=1&&(e.isActive=!1,e.current=e.target,e.target=null,e.progress=1)}getCurrentEmotionalProperties(){return this.errorBoundary.wrap(()=>{const t=performance.now();if(this.interpolationCache.cachedProperties&&t-this.interpolationCache.lastUpdate<this.interpolationCache.cacheInterval)return this.interpolationCache.cachedProperties;let e;if(this.slots.length>1)e=this.$();else{const t=this.transitions.emotional;e=t.isActive&&t.target?this.interpolateEmotionalProperties(t.current,t.target,t.progress):{...this.emotionalStates[this.state.emotion]||this.emotionalStates.neutral};const i=this.getEffectiveIntensity();i<1&&(e.glowIntensity=this.L(.7,e.glowIntensity,i),e.particleRate=Math.round(this.L(1,e.particleRate,i)),e.breathRate=this.L(1,e.breathRate,i),e.breathDepth=e.breathDepth*i,e.coreSize=this.L(1,e.coreSize,i))}return e=this.applyUndertone(e,this.state.undertone),this.interpolationCache.cachedProperties=e,this.interpolationCache.lastUpdate=t,e},"emotional-properties",()=>this.emotionalStates.neutral)()}$(){const t=this.getDominant(),e=this.getUndercurrents(),i=this.emotionalStates[t.emotion]||this.emotionalStates.neutral,s={...i},n=t.intensity;s.glowIntensity=.75*this.L(.7,i.glowIntensity,n),s.particleRate=i.particleRate*n*.75,s.breathRate=.75*this.L(1,i.breathRate,n),s.breathDepth=i.breathDepth*n*.75,s.coreSize=.75*this.L(1,i.coreSize,n);const r=e.length>0?.25/e.length:0;for(const t of e){const e=this.emotionalStates[t.emotion]||this.emotionalStates.neutral,i=t.intensity;s.glowIntensity+=this.L(.7,e.glowIntensity,i)*r,s.particleRate+=e.particleRate*i*r,s.breathRate+=this.L(1,e.breathRate,i)*r,s.breathDepth+=e.breathDepth*i*r,s.coreSize+=this.L(1,e.coreSize,i)*r}if(s.particleRate=Math.round(s.particleRate),e.length>0){const t=this.slots.reduce((t,e)=>t+e.intensity,0);let n=i.primaryColor;for(const i of e){const e=this.emotionalStates[i.emotion]||this.emotionalStates.neutral,s=i.intensity/t;n=Cs(n,e.primaryColor,s)}s.primaryColor=n}return s.particleBehavior=i.particleBehavior,s}L(t,e,i){return t+(e-t)*i}interpolateEmotionalProperties(t,e,i){const s=this.emotionalStates[t]||this.emotionalStates.neutral,n=this.emotionalStates[e]||this.emotionalStates.neutral,r=Hs(i,0,1,"easeOutCubic");return{primaryColor:Cs(s.primaryColor,n.primaryColor,r),glowIntensity:s.glowIntensity+(n.glowIntensity-s.glowIntensity)*r,particleRate:Math.round(s.particleRate+(n.particleRate-s.particleRate)*r),coreSize:s.coreSize+(n.coreSize-s.coreSize)*r,breathRate:s.breathRate+(n.breathRate-s.breathRate)*r,breathDepth:s.breathDepth+(n.breathDepth-s.breathDepth)*r,particleBehavior:r>.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(t){return this.errorBoundary.wrap(()=>{if(null!==t&&!{}.hasOwnProperty.call(this.undertoneModifiers,t))throw new Error(`Invalid undertone: ${t}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return this.state.undertone=t,!0},"undertone-application",!1)()}clearUndertone(){this.state.undertone=null}getUndertoneModifier(t){return this.errorBoundary.wrap(()=>{if(this.renderer&&this.renderer.undertoneModifiers&&this.renderer.undertoneModifiers[t])return{...this.renderer.undertoneModifiers[t]};if(!t||!{}.hasOwnProperty.call(this.undertoneModifiers,t))return null;const e={...this.undertoneModifiers[t]};return e.glowRadiusMult||(e.glowRadiusMult=1),e},"undertone-retrieval",null)()}getWeightedUndertoneModifiers(){const t=this.transitions.undertone;if(!t.isActive){if(this.state.undertone){const t=this.getUndertoneModifier(this.state.undertone);if(t)return{...t,weight:1,type:this.state.undertone}}return null}if(t.target){const e=this.getUndertoneModifier(t.target);if(e)return{...e,weight:t.targetWeight,type:t.target}}if(t.current&&t.currentWeight>0){const e=this.getUndertoneModifier(t.current);if(e)return{...e,weight:t.currentWeight,type:t.current}}return null}reset(t=500){this.slots=[],this.setEmotion("neutral",null,t)}isValidEmotion(t){return{}.hasOwnProperty.call(this.emotionalStates,t)}isValidUndertone(t){return null===t||{}.hasOwnProperty.call(this.undertoneModifiers,t)}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(t,e,i,s="easeOutCubic"){return t+(e-t)*Hs(i,0,1,s)}serialize(){return{version:1,emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,slots:this.slots.map(t=>({...t})),dampening:this.R,negativeEmotions:[...this.F]}}deserialize(t){t&&1===t.version&&(this.slots=(t.slots||[]).map(t=>({emotion:t.emotion,intensity:t.intensity})),this.R=t.dampening??0,t.negativeEmotions&&(this.F=new Set(t.negativeEmotions)),this.state.emotion=t.emotion||"neutral",this.state.undertone=t.undertone||null,this.state.intensity=t.intensity??1,this.D=t.emotion||null,this.transitions.emotional.isActive=!1,this.transitions.intensity.isActive=!1,this.transitions.undertone.isActive=!1,this.interpolationCache.cachedProperties=null)}enableSimulatedTime(t=!0){t?this.q=0:delete this.q}}const Ys=16.67,Xs=3e4;let Vs;"undefined"!=typeof window&&window.__emotiveRhythmEngine?Vs=window.__emotiveRhythmEngine:(Vs=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 t=(performance.now()-this.startTime)/this.beatDuration,e=Math.floor(t);this.beatProgress=t%1,e>this.currentBeat&&this.onBeat(e);const i=Math.floor(e/this.timeSignature[0]);i>this.currentBar&&this.onBar(i),this.currentBeat=e,this.currentBar=i,this.barProgress=e%this.timeSignature[0]/this.timeSignature[0],this.updateSubdivisions(),this.emit("update",this.getTimeInfo()),this.isPlaying&&requestAnimationFrame(()=>this.update())}onBeat(t){const e=t%this.timeSignature[0],i=this.getAccent(e),s=this.humanize*(Math.random()-.5)*this.beatDuration,n={beat:t,beatInBar:e,bar:this.currentBar,accent:i,intensity:this.intensity*i,humanTiming:s,timestamp:performance.now()};this.emit("beat",n),this.beatCallbacks.forEach(t=>t(n)),this.lastBeatTime=performance.now(),this.nextBeatTime=this.lastBeatTime+this.beatDuration}onBar(t){const e={bar:t,timeSignature:this.timeSignature,pattern:this.currentPattern,timestamp:performance.now()};this.emit("bar",e),this.barCallbacks.forEach(t=>t(e))}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 t=.5+.17*this.groove;this.subdivisions.eighth<.5?this.subdivisions.swing=this.subdivisions.eighth/t:this.subdivisions.swing=.5+(this.subdivisions.eighth-.5)/(1-t)}else this.subdivisions.swing=this.subdivisions.eighth}getAccent(t){if(this.currentPattern&&this.patterns.has(this.currentPattern)){const e=this.patterns.get(this.currentPattern);if(e.accents&&void 0!==e.accents[t])return e.accents[t]}return 0===t?1:2===t&&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(t){this.bpm=Math.max(20,Math.min(360,t)),this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.emit("tempoChange",{bpm:this.bpm})}setTimeSignature(t,e){this.timeSignature=[t,e],this.barDuration=this.beatDuration*t,this.emit("timeSignatureChange",{timeSignature:this.timeSignature})}setPattern(t){if(!this.patterns.has(t))return;const e=this.patterns.get(t);this.currentPattern=t,e.timeSignature&&this.setTimeSignature(...e.timeSignature),void 0!==e.groove&&(this.groove=e.groove),this.emit("patternChange",{pattern:t})}onBeatCallback(t){return this.beatCallbacks.add(t),()=>this.beatCallbacks.delete(t)}onBarCallback(t){return this.barCallbacks.add(t),()=>this.barCallbacks.delete(t)}emit(t,e){this.listeners.has(t)&&this.listeners.get(t).forEach(t=>t(e))}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{this.listeners.has(t)&&this.listeners.get(t).delete(e)}}syncToAudio(t,e){this.G||(this.G=!0),this.audioSync={context:t,source:e}}getAdapter(){return{getTimeInfo:()=>this.getTimeInfo(),isOnBeat:(t=.1)=>this.beatProgress<t||this.beatProgress>1-t,isOnSubdivision:(t,e=.1)=>{const i=this.subdivisions[t]||0;return i<e||i>1-e},getBeatSync:(t=0,e=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 t+(e-t)*s},getAccentedValue:(t,e=2)=>t*(1+(this.getAccent(this.currentBeat%this.timeSignature[0])-.5)*e),onBeat:t=>this.onBeatCallback(t),onBar:t=>this.onBarCallback(t),beatsToMs:t=>t*this.beatDuration,msToBeats:t=>t/this.beatDuration,isPlaying:()=>this.isPlaying,getBPM:()=>this.bpm,getPattern:()=>this.currentPattern}}},"undefined"!=typeof window&&(window.__emotiveRhythmEngine=Vs));class Ns{constructor(t,e={}){this._=t,this.H={perfect:e.windows?.perfect??30,great:e.windows?.great??60,good:e.windows?.good??100},this.U={perfect:{multiplier:2,label:"Perfect"},great:{multiplier:1.5,label:"Great"},good:{multiplier:1,label:"Good"},miss:{multiplier:0,label:"Miss"}},this.W={multiplier:1},this.Y=e.emotionSource??null,this.X=[],this.V=100,this.N=[],this.J=null,this.K=null,this.Z=null}evaluate(t=performance.now()){const e=this._.getTimeInfo(),{beatDuration:i}=e,s=performance.now()-e.elapsed,n=t-s,r=n-n%i,a=r+i,o=n-r<a-n?r:a,h=n-o;return this.tt(h,t,o+s)}evaluateAgainst(t,e){return this.tt(t-e,t,e)}evaluateSequence(t,e){const i=[],s=new Set;for(const n of t){let t=-1,r=1/0;for(let i=0;i<e.length;i++){if(s.has(i))continue;const a=Math.abs(n-e[i]);a<r&&(r=a,t=i)}t>=0?(s.add(t),i.push(this.evaluateAgainst(n,e[t]))):i.push({grade:"miss",offset:0,absOffset:0,multiplier:0,label:"Miss",timestamp:n,targetTime:null})}return i}tt(t,e,i){if(this.Z&&this.Z.autoRhythm)return this.et("good",t,e,i);const s=Math.abs(t),n=this.Y?.()??{windowMultiplier:1},r=this.Z?this.Z.getWindowMultiplier():1,a=this.W.multiplier*(n.windowMultiplier||1)*r;let o;return o=s<=this.H.perfect*a?"perfect":s<=this.H.great*a?"great":s<=this.H.good*a?"good":"miss",this.et(o,t,e,i)}et(t,e,i,s){const n={grade:t,offset:e,absOffset:Math.abs(e),multiplier:this.U[t].multiplier,label:this.U[t].label,timestamp:i,targetTime:s};this.X.push(n),this.X.length>this.V&&this.X.shift();for(const t of this.N)t(n);if(this.J&&this.K){const e=this.J[t];e&&this.K(e.emotion,e.delta)}return n}setWindowModifier(t){this.W.multiplier=Math.max(.3,Math.min(3,t))}setEmotionSource(t){this.Y=t}getAccuracy(){if(!this.X.length)return{perfect:0,great:0,good:0,miss:0,averageOffset:0,total:0};const t={perfect:0,great:0,good:0,miss:0};let e=0;for(const i of this.X)t[i.grade]++,e+=i.offset;return{...t,averageOffset:e/this.X.length,total:this.X.length}}getHistory(){return[...this.X]}clearHistory(){this.X.length=0}onEvaluate(t){return this.N.push(t),()=>{this.N=this.N.filter(e=>e!==t)}}setEmotionFeedback(t){this.J=t||null}setEmotionTarget(t){this.K=t||null}setDifficultyManager(t){this.Z=t||null}setWindows(t){Object.assign(this.H,t)}setGrades(t){Object.assign(this.U,t)}destroy(){this.X.length=0,this.N.length=0}}const Qs=new class{constructor(){this.enabled=!1,this.adapter=null,this.subsystemConfigs=new Map,this.activeModulations=new Map,this.it=null,this.st=null,this.nt=null}initialize(){this.adapter=Vs.getAdapter(),this.enabled=!0,this.st=this.adapter.onBeat(this.handleBeat.bind(this)),this.nt=this.adapter.onBar(this.handleBar.bind(this))}updateBPM(t){if(t>=60&&t<=220){if(window.rhythmManuallyStoppedForCurrentAudio)return;if(!Vs.isRunning)return this.start(t,"straight"),void(window.rhythmSyncVisualizer&&!window.rhythmSyncVisualizer.state.active&&window.rhythmSyncVisualizer.start());Vs.setBPM(t)}}registerConfig(t,e,i){if(!i.rhythm||!i.rhythm.enabled)return;const s=`${t}:${e}`;this.subsystemConfigs.set(s,{type:t,name:e,rhythmConfig:i.rhythm,originalConfig:i})}applyGestureRhythm(t,e,i,s){if(!this.enabled||!t.rhythm?.enabled)return{};const n=t.rhythm,r={};if(n.amplitudeSync){const t=n.amplitudeSync,e=this.adapter.getBeatSync(t.offBeat||.8,t.onBeat||1.5,t.curve||"linear");r.amplitudeMultiplier=e}if(n.wobbleSync){const t=n.wobbleSync;this.adapter.isOnSubdivision(t.subdivision,.1)?r.wobbleMultiplier=1+t.intensity:r.wobbleMultiplier=1}if(n.accentResponse?.enabled){const t=this.adapter.getAccentedValue(1,n.accentResponse.multiplier||1.5);r.accentMultiplier=t}const a=this.adapter.getPattern();return a&&n.patternOverrides?.[a]&&Object.assign(r,n.patternOverrides[a]),r}applyParticleRhythm(t,e){if(!this.enabled||!t.rhythm?.enabled)return{};const i=this.adapter.getTimeInfo(),s=t.rhythm,n={};if(s.particleEmission){const t=s.particleEmission;"beat"===t.syncMode&&this.adapter.isOnBeat(.1)?n.emitBurst=t.burstSize||3:void 0!==t.offBeatRate&&(n.emissionRate=t.offBeatRate)}if(s.glowSync){const t=s.glowSync,e=this.adapter.getBeatSync(t.intensityRange[0]||1,t.intensityRange[1]||2,"pulse");n.glowIntensity=e}if("bars"===s.breathSync?.mode){const t=s.breathSync,e=i.bar%t.barsPerBreath/t.barsPerBreath;n.breathPhase=e*Math.PI*2}return n}applyBehaviorRhythm(t,e,i){if(!this.enabled||!t.rhythm?.enabled)return{};const s=this.adapter.getTimeInfo(),n=t.rhythm,r={};if(n.glitchTiming){const t=n.glitchTiming;if(this.adapter.isOnSubdivision(t.subdivision,.05)&&Math.random()<t.probability){const e=this.adapter.isOnBeat()?t.intensityOnBeat:t.intensityOffBeat;r.triggerGlitch=!0,r.glitchIntensity=e}}if(n.orbitRhythm){const t=n.orbitRhythm;"tempo"===t.baseSpeed&&(r.speedMultiplier=this.adapter.getBPM()/120),t.beatAcceleration&&this.adapter.isOnBeat(.1)&&(r.speedBoost=t.beatAcceleration),t.barReset&&0===s.beatInBar&&(r.resetOrbit=!0)}if(n.stutterSync){const t=n.stutterSync,e=this.adapter.getPattern();if(e&&t.patterns?.[e]){const i=t.patterns[e];i.freezeOnDrop&&2===s.beatInBar?(r.freeze=!0,r.freezeDuration=i.dropDuration):i.randomFreeze&&Math.random()<i.randomFreeze&&(r.freeze=!0,r.freezeDuration=i.duration)}}return r}handleBeat(t){this.lastBeatInfo=t}handleBar(t){this.lastBarInfo=t}getMusicalDuration(t,e){if(!this.enabled||!t?.durationSync)return e;const i=t.durationSync;return"bars"===i.mode?this.adapter.beatsToMs(4*i.bars):"beats"===i.mode?this.adapter.beatsToMs(i.beats):e}isEnabled(){return this.enabled&&this.adapter.isPlaying()}start(t=120,e="straight"){t&&Vs.setBPM(t),e&&Vs.setPattern(e),Vs.start(),this.enabled=!0}stop(){Vs.stop(),this.enabled=!1,this.bpmLocked=!1,this.lockedBPM=null}destroy(){this.stop(),this.st&&(this.st(),this.st=null),this.nt&&(this.nt(),this.nt=null),this.enabled=!1,this.adapter=null,this.subsystemConfigs.clear(),this.activeModulations.clear(),this.lastBeatInfo=null,this.lastBarInfo=null,this.it=null}setPattern(t){Vs.setPattern(t)}setBPM(t){Vs.setBPM(t),this.bpmLocked&&(this.lockedBPM=t)}resampleBPM(){this.bpmLocked=!1,this.lockedBPM=null}setTimeSignature(t){this.timeSignature=t;const e=document.getElementById("time-sig-display");e&&(e.textContent=t),"3/4"===t&&Vs.getPattern()}getInputEvaluator(t){return this.it||(this.adapter||this.initialize(),this.it=new Ns(this.adapter,t)),this.it}getEffectiveBPM(t){if(!this.adapter)return 120;let e=this.adapter.getBPM();if(t&&"function"==typeof t.getCurrentRhythmModifiers){const i=t.getCurrentRhythmModifiers();i.tempoShift&&(e*=1+i.tempoShift)}return Math.round(100*e)/100}syncToAudio(t,e){Vs.syncToAudio(t,e)}};class Js{constructor(t,e,i="ambient",s=1,n=1,r=null){const a=Math.random();this.z=a<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,h=Math.random()*Math.PI*2;this.x=t+Math.cos(h)*o,this.y=e+Math.sin(h)*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=r,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:t,initialY:e},ps(this,i)}update(t,e,i,s=null,n=null,r=0,a=null){const o=Math.min(t,50)/Ys,h=n&&n.type&&r>0&&Ri(n.type),l=this.rainData||"falling"===this.gestureBehavior||this.fallingData||this.gestureData?.rain,c=h||l;if(c||(this.x+=this.vx*o,this.y+=this.vy*o),!c){let t,s;if(a)t=a.width,s=a.height;else{const n=document.getElementById("card-mascot")||document.getElementById("cherokee-guide-mascot")||document.querySelector("canvas");t=n?n.width:2*e,s=n?n.height:2*i}const n=20,r=e-t/2+n,o=e+t/2+n,h=i-s/2+n,l=i+s/2-n;this.x-this.size<r?(this.x=r+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<h?(this.y=h+this.size,this.vy=.5*Math.abs(this.vy)):this.y+this.size>l&&(this.y=l-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(t,e){}applyGestureMotion(t,e,i,s,n){!function(t,e,i,s,n,r){if(!i||!i.type||s>=1)return;t.gestureData||(t.gestureData={originalVx:t.vx,originalVy:t.vy,initialX:t.x,initialY:t.y,startAngle:Math.atan2(t.y-r,t.x-n),startRadius:Math.sqrt(Math.pow(t.x-n,2)+Math.pow(t.y-r,2))});const a=Pi(i.type);if(!a)return;let o=i;if(Qs.isEnabled()&&a.rhythm?.enabled){const n=Qs.applyGestureRhythm(a,t,s,e);o={...i,amplitude:(i.amplitude||1)*(n.amplitudeMultiplier||1)*(n.accentMultiplier||1),wobbleAmount:(i.wobbleAmount||0)*(n.wobbleMultiplier||1),rhythmModulation:n}}a.apply&&a.apply(t,s,o,e,n,r),s>=.99&&a.cleanup&&(a.cleanup(t),t.gestureData=null)}(this,i,t,e,s,n)}isOutOfBounds(t,e){return this.x<-50||this.x>t+50||this.y<-50||this.y>e+50}isAlive(){return this.life>0}setOutwardVelocity(t){if(this.behaviorData&&void 0!==this.behaviorData.outwardSpeed){const e=this.behaviorData.outwardSpeed;this.vx=Math.cos(t)*e,this.vy=Math.sin(t)*e+(this.behaviorData.upwardBias||0)}}getDepthAdjustedSize(){const t=1+.2*this.z;return this.size*t}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(t,e,i="ambient",s=1,n=1,r=null){const a=Math.random();this.z=a<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,h=Math.random()*Math.PI*2;if(this.x=t+Math.cos(h)*o,this.y=e+Math.sin(h)*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=r,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 t in this.behaviorData)delete this.behaviorData[t];else this.behaviorData={};ps(this,i)}getCachedColor(t,e){const i=Math.round(100*e)/100,s=`${t}_${i}`;if(this.cachedColors.has(s)){const t=this.colorAccessOrder.indexOf(s);-1!==t&&this.colorAccessOrder.splice(t,1),this.colorAccessOrder.push(s)}else{if(this.cachedColors.size>=this.maxCachedColors){const t=this.colorAccessOrder.shift();this.cachedColors.delete(t)}this.cachedColors.set(s,this.hexToRgba(t,i)),this.colorAccessOrder.push(s)}return this.cachedColors.get(s)}hexToRgba(t,e){const i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return i?`rgba(${parseInt(i[1],16)}, ${parseInt(i[2],16)}, ${parseInt(i[3],16)}, ${e})`:`rgba(255, 255, 255, ${e})`}easeInOutCubic(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}render(t,e="#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),r=this.tempColor||this.color||e;if(t.save(),this.isCellShaded){t.strokeStyle=this.getCachedColor(r,.9*this.opacity),t.lineWidth=2,t.beginPath(),t.arc(i,s,n,0,2*Math.PI),t.stroke();const e=Math.floor(3*this.opacity)/3;t.fillStyle=this.getCachedColor(r,e*(this.baseOpacity||.5)*.5),t.beginPath(),t.arc(i,s,Math.max(.1,n-1),0,2*Math.PI),t.fill(),e>.5&&(t.fillStyle=this.getCachedColor("#FFFFFF",.3),t.beginPath(),t.arc(i-.3*n,s-.3*n,.3*n,0,2*Math.PI),t.fill())}else{const e=t.createRadialGradient(i,s,0,i,s,n);if(e.addColorStop(0,this.getCachedColor(r,this.opacity*(this.baseOpacity||.5))),e.addColorStop(.5,this.getCachedColor(r,this.opacity*(this.baseOpacity||.5)*.5)),e.addColorStop(1,this.getCachedColor(r,0)),t.fillStyle=e,t.beginPath(),t.arc(i,s,n,0,2*Math.PI),t.fill(),this.hasGlow&&this.glowSizeMultiplier>0){const e=n*this.glowSizeMultiplier,a=t.createRadialGradient(i,s,.5*n,i,s,e),o=.3,h=Math.max(o,this.opacity),l=Math.min(1,this.glowSizeMultiplier/3);a.addColorStop(0,this.getCachedColor(r,Math.max(.5,.8*h)*l)),a.addColorStop(.25,this.getCachedColor(r,Math.max(.3,.6*h)*l)),a.addColorStop(.5,this.getCachedColor(r,Math.max(.2,.4*h)*l)),a.addColorStop(.75,this.getCachedColor(r,Math.max(.1,.2*h)*l)),a.addColorStop(1,this.getCachedColor(r,0)),t.save(),t.globalCompositeOperation="screen",t.fillStyle=a,t.beginPath(),t.arc(i,s,e,0,2*Math.PI),t.fill(),t.restore()}}t.restore()}}class Ks{constructor(t=50){this.poolSize=Math.min(t,50),this.pool=[],this.totalParticlesCreated=0,this.totalParticlesDestroyed=0,this.poolHits=0,this.poolMisses=0}getParticle(t,e,i,s,n,r,a,o=null){let h;return this.pool.length>0?(h=this.pool.pop(),h.reset(t,e,i,s,n,r),this.poolHits++):(h=new Js(t,e,i,s,n,r),this.poolMisses++,this.totalParticlesCreated++),h.emotion=a,o&&(h.gestureBehavior=o),h}returnParticle(t){if(this.pool.length<this.poolSize){if(t.cachedGradient=null,t.cachedGradientKey=null,t.behaviorData)for(const e in t.behaviorData)delete t.behaviorData[e];this.pool.push(t)}else this.totalParticlesDestroyed++}refreshPool(){const t=this.pool.length-this.poolSize;t>0&&(this.pool.splice(this.poolSize),this.totalParticlesDestroyed+=t)}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 Zs{constructor(){this.spawnAccumulator=0}getSpawnPosition(t,e,i,s,n,r=null){const a=Math.min(s,n)/12,o=2.5*a,h=1.1*o,l=Math.min(e-30,s-e-30),c=Math.min(i-30,n-i-30),u=Math.min(1.5*o,l,c);switch(t){case"ambient":case"resting":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"ascending":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"rising":{const t=Math.random()*Math.PI*2,s=h+Math.random()*(u-h);return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"falling":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"aggressive":{const t=Math.random()*Math.PI*2,s=o+Math.random()*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"scattering":default:return{x:e,y:i};case"burst":{const t=Math.random()*Math.PI*2;if("suspicion"===r){const s=1.5*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}if("surprise"===r){const s=1.2*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}return{x:e,y:i}}case"repelling":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"orbiting":{const t=Math.random()*Math.PI*2,s=1.2*o+Math.random()*o*.5;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"glitchy":{const t=Math.random()*Math.PI*2,s=3*o+Math.random()*o*4;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"spaz":{const t=Math.random()*Math.PI*2,s=2*o+Math.random()*o*3;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}}}clampToCanvas(t,e,i,s,n=30){return{x:Math.max(n,Math.min(i-n,t)),y:Math.max(n,Math.min(s-n,e))}}calculateSpawnRate(t,e){if(t<=0)return 0;const i=Math.min(e,50),s=t/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 tn{render(t,e,i="#ffffff",s=null){const n=[];for(const t of e)t.life<=0||n.push(t);this.rt(t,n,i,s)}renderLayer(t,e,i="#ffffff",s=!1,n=null){const r=[],a=t.canvas.width,o=t.canvas.height;for(const t of e)t.z>=0===s&&(t.x<-50||t.x>a+50||t.y<-50||t.y>o+50||t.life<=0||r.push(t));return r.sort((t,e)=>t.isCellShaded!==e.isCellShaded?t.isCellShaded?-1:1:t.hasGlow!==e.hasGlow?t.hasGlow?-1:1:0),this.rt(t,r,i,n),r}rt(t,e,i,s=null){t.save();let n=null;for(const r of e)if(r.isCellShaded)r.render(t,i),n=null;else{const e=r.color||i;if(e!==n&&(t.fillStyle=e,n=e),!isFinite(r.x)||!isFinite(r.y))continue;const a=r.getDepthAdjustedSize?r.getDepthAdjustedSize():r.size;let o=Math.max(.1,a),h=1;if(s&&s.fireflyEffect){const t=(.01*r.x+.01*r.y+.1*r.size)%(2*Math.PI),e=s.fireflyTime||.001*Date.now(),i=s.particleGlow||2;h=.3+Math.max(0,Math.sin(3*e+t))*i}if(s&&s.flickerEffect){const t=(.02*r.x+.02*r.y)%(2*Math.PI),e=s.flickerTime||.001*Date.now(),i=s.particleGlow||2;h=.5+Math.sin(12*e+t)*i*.5}if(s&&s.shimmerEffect){const e=r.x-t.canvas.width/2,i=r.y-t.canvas.height/2,n=Math.sqrt(e*e+i*i)/200,a=s.shimmerTime||.001*Date.now(),o=s.shimmerWave||0,l=s.particleGlow||1.2;h=1+.15*Math.sin(3*a-n+o)*l}if(s&&s.glowEffect){const e=s.glowProgress||0,i=s.particleGlow||2,n=r.x-t.canvas.width/2,a=r.y-t.canvas.height/2,h=Math.sqrt(n*n+a*a)/300,l=Math.min(.3*h,.5),c=Math.max(0,(e-l)/(1-l)),u=Math.sin(c*Math.PI);r.ot||(r.ot={hasGlow:r.hasGlow,glowSizeMultiplier:r.glowSizeMultiplier||0}),r.hasGlow=!0,r.glowSizeMultiplier=Math.max(3,r.ot.glowSizeMultiplier)+u*i*3,o*=1+.3*u,e>=.99&&r.ot&&(r.hasGlow=r.ot.hasGlow,r.glowSizeMultiplier=r.ot.glowSizeMultiplier,delete r.ot)}if(r.hasGlow||h>1){const e=Math.max(.1,o*(r.glowSizeMultiplier||1.5)*h),i=t.globalCompositeOperation;t.globalCompositeOperation="screen",t.globalAlpha=.15*r.opacity*h,t.beginPath(),t.arc(r.x,r.y,e,0,2*Math.PI),t.fill(),t.globalAlpha=.25*r.opacity*h,t.beginPath(),t.arc(r.x,r.y,.6*e,0,2*Math.PI),t.fill(),t.globalCompositeOperation=i}t.globalAlpha=r.opacity*(r.baseOpacity||.5)*.6*Math.min(2,h),t.beginPath(),t.arc(r.x,r.y,o,0,2*Math.PI),t.fill()}t.restore()}}class en{constructor(t=50,e=null){this.errorBoundary=e,this.maxParticles=t,this.absoluteMaxParticles=2*t,this.particles=[],this.particlePool=new Ks(t),this.particleSpawner=new Zs,this.particleRenderer=new tn,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(t){this.particleSpawner.spawnAccumulator=t}getParticleFromPool(t,e,i){return this.particlePool.getParticle(t,e,i,this.scaleFactor||1,this.particleSizeMultiplier||1,this.currentEmotionColors,this.currentEmotion,this.gestureBehavior)}returnParticleToPool(t){this.particlePool.returnParticle(t)}spawn(t,e,i,s,n,r,a=null,o=0,h=10,l=1,c=1,u=null,d=null){if(this.scaleFactor=l,this.particleSizeMultiplier=c,this.errorBoundary)return this.errorBoundary.wrap(()=>{this.ht(t,e,i,s,n,r,a,o,h,u,d)},"particle-spawn")();this.ht(t,e,i,s,n,r,a,o,h,u,d)}resetAccumulator(){this.particleSpawner.resetAccumulator()}ht(t,e,i,s,n,r,a,o=0,h=10,c=null,u=null){this.currentEmotion=e,this.baseEmotionColors=c,this.currentUndertone=u,this.currentEmotionColors=c&&u?function(t,e){return t&&Array.isArray(t)&&e&&"clear"!==e?t.map(t=>"string"==typeof t?Ps(t,e):t&&"object"==typeof t&&t.color?{...t,color:Ps(t.color,e)}:t):t}(c,u):c;let d=i;if(Qs.isEnabled()){const i=Us&&Us.isInitialized?Us.getEmotion(e):l(e);if(i){const e=Qs.applyParticleRhythm(i,this);if(e.emitBurst)for(let i=0;i<e.emitBurst&&this.particles.length<h;i++)this.spawnSingleParticle(t,s,n);void 0!==e.emissionRate&&(d*=e.emissionRate)}}if(null!==a){for(let e=0;e<a&&this.particles.length<this.maxParticles;e++)this.spawnSingleParticle(t,s,n);return}if(this.skipSpawnThisFrame)return;for(;this.particles.length<o&&this.particles.length<this.maxParticles;)this.spawnSingleParticle(t,s,n);if(this.particles.length>=h)return;if(d<=0)return;const p=this.particleSpawner.calculateSpawnRate(d,r);for(let e=0;e<p&&this.particles.length<h;e++)this.spawnSingleParticle(t,s,n)}getSpawnPosition(t,e,i,s,n){return this.lt||(this.lt=!0),this.particleSpawner.getSpawnPosition(t,e,i,s,n,this.currentEmotion)}clampToCanvas(t,e,i,s,n=30){return this.ct||(this.ct=!0),this.particleSpawner.clampToCanvas(t,e,i,s,n)}spawnSingleParticle(t,e,i){if(this.particles.length>=this.absoluteMaxParticles)return;const s=this.canvasWidth||2*e,n=this.canvasHeight||2*i,r=this.particleSpawner.getSpawnPosition(t,e,i,s,n,this.currentEmotion),a=this.particleSpawner.clampToCanvas(r.x,r.y,s,n);r.x=a.x,r.y=a.y;const o=this.getParticleFromPool(r.x,r.y,t);"meditation_swirl"===t&&r.palmCenter&&(o.palmCenter=r.palmCenter,o.swirlAngle=r.swirlAngle),this.particles.push(o),this.particleCount++}update(t,e,i,s=null,n=0,r=null){if(this.errorBoundary)return this.errorBoundary.wrap((t,e,i,s,n,r)=>this.ut(t,e,i,s,n,r),"particle-update")(t,e,i,s,n,r);this.ut(t,e,i,s,n,r)}ut(t,e,i,s=null,n=0,r=null){for(let a=this.particles.length-1;a>=0;a--)this.particles[a].update(t,e,i,r,s,n,this.containmentBounds),this.particles[a].isAlive()||this.removeParticle(a);for(;this.particles.length>this.maxParticles;)this.removeParticle(0)}setGestureBehavior(t,e){this.gestureBehavior=e?t:null,e?this.particles.forEach(e=>{e.gestureBehavior=t}):this.particles.forEach(t=>{t.gestureBehavior=null})}removeParticle(t){if(t>=0&&t<this.particles.length){const e=this.particles.splice(t,1)[0];e.cachedGradient=null,e.cachedGradientKey=null,this.returnParticleToPool(e),this.particleCount=Math.max(0,this.particleCount-1)}}render(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.dt(t,e,i)},"particle-render")();this.dt(t,e,i)}renderBackground(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.gt(t,e,!1,i)},"particle-render-bg")();this.gt(t,e,!1,i)}renderForeground(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.gt(t,e,!0,i)},"particle-render-fg")();this.gt(t,e,!0,i)}gt(t,e,i,s=null){this.particleRenderer.renderLayer(t,this.particles,e,i,s)}dt(t,e,i=null){this.particleRenderer.render(t,this.particles,e,i)}onVisibilityResume(t,e=null){if(this.resetAccumulator(),t>Xs)this.clear();else if(t>1e4){const t=this.particles.length,i=e??t,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 t=this.particles.pop();if(t.cachedColors&&t.cachedColors.clear(),t.behaviorData)for(const e in t.behaviorData)delete t.behaviorData[e];this.pool.length<this.poolSize&&!this.pool.includes(t)&&this.pool.push(t)}if(this.particles.length=0,this.particleCount=0,this.spawnAccumulator=0,this.pool.length>this.poolSize){const t=this.pool.length-this.poolSize;this.pool.splice(this.poolSize,t)}}burst(t,e,i,s){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.ft(t,e,i,s)},"particle-burst")();this.ft(t,e,i,s)}ft(t,e,i,s){const n=Math.min(t,this.maxParticles-this.particles.length);for(let t=0;t<n;t++)this.spawnSingleParticle(e,i,s)}performCleanup(){if(this.pool.length>this.poolSize){const t=this.pool.length-this.poolSize;for(let e=0;e<t;e++){const t=this.pool.pop();t&&(t.cachedGradient=null,t.cachedGradientKey=null,t.behaviorData=null)}}for(const t of this.particles)t.cachedGradient&&t.life<.5&&(t.cachedGradient=null,t.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(t){for(this.originalMaxParticles=this.originalMaxParticles||this.maxParticles,this.maxParticles=Math.max(1,t);this.particles.length>this.maxParticles;)this.removeParticle(0)}cleanupDeadParticles(){const t=this.particles.length;this.particles=this.particles.filter(t=>t.isAlive());const e=t-this.particles.length;return this.pool.length>20&&(this.pool.length=20),e}getParticlesByBehavior(t){return this.particles.filter(e=>e.behavior===t)}validateParticles(){for(const t of this.particles)if(!t.isAlive()||t.life<0||t.life>1)return!1;return!0}cleanup(){for(let t=this.particles.length-1;t>=0;t--)this.particles[t].isAlive()||this.removeParticle(t)}refreshPool(){this.particlePool.clear();for(const t of this.particles)t.life=0}setContainmentBounds(t){this.containmentBounds=t}destroy(){this.clear(),this.particlePool.clear()}}const sn=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}yt(){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(t){this.isInitialized=!1}}cacheCoreGestures(){Object.values(wi).forEach(t=>{t&&t.name&&this.gestureCache.set(t.name,{...t,cached:!0,cacheTime:performance.now()})})}cacheGestureProperties(){this.gestureCache.forEach((t,e)=>{const i={type:t.type,emoji:t.emoji,description:t.description,config:t.config,rhythm:t.rhythm,duration:this.calculateGestureDuration(t),easing:this.extractEasingFunction(t),physics:this.extractPhysicsProperties(t),timing:this.extractTimingProperties(t)};this.propertyCache.set(e,i)})}cacheCommonCombinations(){[["bounce","pulse"],["shake","vibrate"],["orbit","spin"],["morph","glow"],["breathe","fade"],["wave","drift"],["nod","sway"],["jump","stretch"]].forEach(([t,e])=>{const i=`${t}+${e}`,s=this.calculateGestureCombination(t,e);s&&this.compositionCache.set(i,s)})}cachePluginGestures(){try{const t=k.getAllPluginGestures();t&&Object.entries(t).forEach(([t,e])=>{this.pluginCache.set(t,{...e,cached:!0,cacheTime:performance.now(),isPlugin:!0})})}catch(t){}}getGesture(t){return this.yt(),this.gestureCache.has(t)?(this.stats.hits++,this.stats.gestureHits++,this.gestureCache.get(t)):this.pluginCache.has(t)?(this.stats.hits++,this.stats.gestureHits++,this.pluginCache.get(t)):(this.stats.misses++,null)}getGestureProperties(t){return this.yt(),this.propertyCache.has(t)?(this.stats.hits++,this.stats.propertyHits++,this.propertyCache.get(t)):(this.stats.misses++,null)}getGestureCombination(t,e){this.yt();const i=`${t}+${e}`;return this.compositionCache.has(i)?(this.stats.hits++,this.stats.compositionHits++,this.compositionCache.get(i)):(this.stats.misses++,null)}calculateGestureDuration(t){if(!t.config)return 1e3;const{musicalDuration:e,duration:i}=t.config;return e&&e.musical?500*(e.beats||2):i||1e3}extractEasingFunction(t){if(!t.config)return"sine";const{easing:e,particleMotion:i}=t.config;return e||i?.easing||"sine"}extractPhysicsProperties(t){if(!t.config)return{};const{amplitude:e,strength:i,size:s,rotation:n}=t.config;return{amplitude:e||20,strength:i||1,size:s||80,rotation:n||0}}extractTimingProperties(t){if(!t.config)return{};const{phases:e,timingSync:i}=t.config;return{phases:e||[],timingSync:i||{},hasPhases:!!(e&&e.length>0),hasTimingSync:!!(i&&Object.keys(i).length>0)}}calculateGestureCombination(t,e){const i=this.getGesture(t),s=this.getGesture(e);return i&&s?{gestures:[t,e],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(t,e){const i=this.extractPhysicsProperties(t),s=this.extractPhysicsProperties(e);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(t,e){return t.type===e.type?"high":"blending"===t.type&&"blending"===e.type?"medium":"override"===t.type||"override"===e.type?"low":"medium"}getStats(){const t=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(1):0;return{...this.stats,hitRate:`${t}%`,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(t){t.forEach(t=>{this.getGesture(t),this.getGestureProperties(t)})}};function nn(t){if(sn&&sn.isInitialized){const e=sn.getGesture(t);if(e)return e}return Pi(t)}const rn={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 an{constructor(){this.cache=new Map,this.easingCache=new Map,this.preCalculateEasingCurves()}preCalculateEasingCurves(){const t=["linear","ease-in","ease-out","ease-in-out","bounce"];for(const e of t){const t=new Float32Array(101);for(let i=0;i<=100;i++){const s=i/100;t[i]=this.calculateEasing(s,e)}this.easingCache.set(e,t)}}calculateEasing(t,e){switch(e){case"ease-in":return t*t;case"ease-out":return t*(2-t);case"ease-in-out":return t<.5?2*t*t:(4-2*t)*t-1;case"bounce":return t<.363636?7.5625*t*t:t<.727272?7.5625*(t-=.545454)*t+.75:t<.90909?7.5625*(t-=.818181)*t+.9375:7.5625*(t-=.954545)*t+.984375;default:return t}}getEasingValue(t,e){const i=this.easingCache.get(e);return i?i[Math.min(Math.floor(100*t),100)]:t}compose(t,e,i=null){const s=`${t}-${e}-${i||"none"}`;if(this.cache.has(s))return this.cache.get(s);const n=nn(t),r=n?n.config:{duration:500,amplitude:20,easing:"sine"},a=Us&&Us.isInitialized?Us.getModifiers(e):u(e),o=function(t){return t&&""!==t&&"clear"!==t&&rn[t]||rn.clear}(i),h=this.applyModifiers(r,a,o,t);return this.cache.size>100&&this.cache.clear(),this.cache.set(s,h),h}applyModifiers(t,e,i,s){const n={...t},r=e.speed*i.speed;if(n.duration=Math.round(t.duration/r),void 0!==n.amplitude&&(n.amplitude=t.amplitude*e.amplitude*i.amplitude),void 0!==n.scaleAmount&&(n.scaleAmount=t.scaleAmount*e.intensity*i.intensity),void 0!==n.scaleTarget){const s=e.amplitude*i.amplitude;n.scaleTarget=1+(t.scaleTarget-1)*s}void 0!==n.glowAmount&&(n.glowAmount=t.glowAmount*e.intensity*i.intensity),void 0!==n.glowPeak&&(n.glowPeak=1+(t.glowPeak-1)*e.intensity*i.intensity),void 0!==n.rotations&&(n.rotations=t.rotations*e.amplitude*i.amplitude),void 0!==n.angle&&(n.angle=t.angle*e.amplitude*i.amplitude),void 0!==n.distance&&(n.distance=t.distance*e.amplitude*i.amplitude);const a=e.smoothness*i.smoothness;return n.smoothness=a,n.easing=this.selectEasing(t.easing,a),n.regularity=e.regularity*i.regularity,n.effects=[],e.addBounce&&n.effects.push("bounce"),e.addGravity&&n.effects.push("gravity"),e.addShake&&n.effects.push("shake"),e.addJitter&&n.effects.push("shake"),e.addPop&&n.effects.push("pop"),e.addRecoil&&n.effects.push("recoil"),e.addWarmth&&n.effects.push("warmth"),e.addFlow&&n.effects.push("flow"),e.addWobble&&n.effects.push("wobble"),e.addVibration&&n.effects.push("vibration"),e.addDrag&&n.effects.push("drag"),e.addWeight&&n.effects.push("weight"),e.addTension&&n.effects.push("tension"),e.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,e,i),t.particleMotion&&(n.particleMotion={...t.particleMotion},void 0!==n.particleMotion.strength&&(n.particleMotion.strength*=e.intensity*i.intensity),void 0!==n.particleMotion.frequency&&(n.particleMotion.frequency*=r),void 0!==n.particleMotion.amplitude&&(n.particleMotion.amplitude*=e.amplitude*i.amplitude)),n}selectEasing(t,e){return e<.5?"linear":e<.8?"quad":e<1.2?t:e<1.5?"cubic":"sine"}applyGestureSpecificMods(t,e,i,s){switch(e){case"bounce":i.addShake&&(t.frequency=Math.floor(1.5*t.frequency)),i.addGravity&&(t.amplitude*=.6,t.frequency=1);break;case"pulse":i.addWarmth&&(t.frequency=2,t.glowAmount*=1.5),s.addFlutter&&(t.irregular=!0);break;case"shake":i.addJitter&&(t.frequency*=1.5,t.amplitude*=1.2),i.addShake&&(t.amplitude*=1.5,t.decay=!1);break;case"spin":i.addBounce&&(t.rotations*=1.5),i.addWobble&&(t.wobble=!0)}}clearCache(){this.cache.clear()}}const on=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 t=[{musical:!0,beats:1},{musical:!0,bars:1},{musical:!0,beats:.5},{musical:!0,beats:2}];[60,90,120,140,160,180].forEach(e=>{t.forEach(t=>{const i=`${e}_${JSON.stringify(t)}`,s=this.toMilliseconds(t,e);if(this.cache.size>=this.maxCacheSize){const t=this.cacheAccessOrder.shift();this.cache.delete(t)}this.cache.set(i,s),this.cacheAccessOrder.push(i)})})}toMilliseconds(t,e=null){const i=e||Vs.bpm||120;if("number"==typeof t)return t;if("object"==typeof t&&t.musical){const e=6e4/i;if(void 0!==t.beats)return t.beats*e;if(void 0!==t.bars){const i=Vs.timeSignature||[4,4];return t.bars*i[0]*e}if(void 0!==t.subdivision)return(this.noteDurations[t.subdivision]||1)*e}return 1e3}toMusical(t,e=null){const i=t/(6e4/(e||Vs.bpm||120));let s="quarter",n=Math.abs(i-1);for(const[t,e]of Object.entries(this.noteDurations)){const r=Math.abs(i-e);r<n&&(n=r,s=t)}return{musical:!0,beats:i,bars:i/4,closestSubdivision:s,exact:n<.01}}calculatePhases(t,e){if(!t||0===t.length)return[{name:"main",beats:e,start:0,end:1}];const i=t.reduce((t,e)=>t+(e.beats||1),0),s=e/i;let n=0;return t.map(t=>{const i=(t.beats||1)*s,r=n/e;n+=i;const a=n/e;return{name:t.name,beats:i,start:r,end:a,duration:this.toMilliseconds({musical:!0,beats:i})}})}getBeatProgress(){const t=Vs.getTimeInfo();return t?t.beatProgress:0}getBarProgress(){const t=Vs.getTimeInfo();return t?t.barProgress:0}timeToNextBoundary(t="beat"){const e=Vs.getTimeInfo();if(!e)return 100;switch(t){case"beat":default:return e.nextBeatIn;case"bar":return(e.timeSignature[0]-e.beatInBar)*e.beatDuration;case"phrase":{const t=4,i=e.timeSignature[0];return(t-(e.bar||0)%t)*i*e.beatDuration}}}quantize(t,e="eighth"){const i=6e4/(Vs.bpm||120),s=(this.noteDurations[e]||1)*i;return Math.round(t/s)*s}isOnBoundary(t="beat",e=50){const i=this.timeToNextBoundary(t),s=Vs.getTimeInfo();return!!s&&(i<e||s.beatDuration-i<e)}getTempoAdaptation(t=120){const e=(Vs.bpm||120)/t;return{speed:e,energy:Math.min(2,Math.max(.5,e)),smoothness:e<.8?1.2:e>1.5?.8:1,intensity:e>1.3?1.2:e<.7?.8:1}}};class hn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyBounce(t,e){return{offsetY:-Math.abs(Math.sin(e*Math.PI*t.params.frequency))*t.params.amplitude*this.scaleFactor*(t.params.effects&&t.params.effects.includes("gravity")?.6:1)}}applyShake(t,e){t.randomAngle||(t.randomAngle=Math.random()*Math.PI*2);const i=t.params.decay?1-e:1,s=Math.sin(e*Math.PI*t.params.frequency)*t.params.amplitude*i*this.scaleFactor;return{offsetX:s*Math.cos(t.randomAngle),offsetY:s*Math.sin(t.randomAngle)}}applyJump(t,e){let i,s,n=0,r=1;if(e<.2){const i=e/.2;r=1-(1-t.params.squashAmount)*i}else if(e<.7){const i=(e-.2)/.5,s=Math.sin(i*Math.PI);n=-t.params.jumpHeight*s*this.scaleFactor,r=t.params.squashAmount+(t.params.stretchAmount-t.params.squashAmount)*s}else{const i=(e-.7)/.3;r=t.params.stretchAmount-(t.params.stretchAmount-1)*i}if(t.params.effects&&t.params.effects.includes("gravity")){const t=e<.7?(e-.2)/.5:0,n=Math.sin(t*Math.PI);i=1+.2*n,s=1-.15*n}const a={offsetY:n,scale:r};return void 0!==i&&(a.scaleX=i),void 0!==s&&(a.scaleY=s),a}applyVibrate(t,e){if(!t.vibrateAngles){t.vibrateAngles={x:2*Math.random()-1,y:2*Math.random()-1};const e=Math.sqrt(t.vibrateAngles.x**2+t.vibrateAngles.y**2);t.vibrateAngles.x/=e,t.vibrateAngles.y/=e}const i=t.params.amplitude||5,s=t.params.frequency||20,n=Math.sin(e*Math.PI*2*s)*i*this.scaleFactor;return{offsetX:n*t.vibrateAngles.x,offsetY:n*t.vibrateAngles.y}}applyWiggle(t,e){const i=(t.params?.amplitude||15)*this.scaleFactor;void 0===t.wiggleDirection&&(t.wiggleDirection=Math.random()<.5?1:-1);const s=t.wiggleDirection;let n=0,r=0;if(e<.25){const t=e/.25;n=i*s*t,r=3*s*t}else if(e<.5){const t=(e-.25)/.25;n=i*s*(1-2*t),r=3*s*(1-2*t)}else if(e<.75){const t=(e-.5)/.25;n=i*-s*(1-2*t),r=3*-s*(1-2*t)}else{const t=(e-.75)/.25;n=i*s*(1-t),r=3*s*(1-t)}return{offsetX:n,offsetY:-Math.abs(Math.sin(e*Math.PI*4))*i*.15,rotation:r}}}class ln{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyFlash(t,e){const i=Math.sin(e*Math.PI);return{glow:1+((t.params.glowPeak||2)-1)*i,scale:1+((t.params.scalePeak||1.1)-1)*i}}applyGlow(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+i*(t.params.scaleAmount||.1),glow:1+i*(t.params.glowAmount||.8)}}applyFlicker(t,e){const i=t.params?.intensity||2,s=t.params?.speed||3,n=1+Math.sin(e*Math.PI*2*s)*i*.3,r=5*Math.sin(e*Math.PI*4)*this.scaleFactor,a=.001*Date.now();return{offsetX:r,glow:n,particleGlow:(.5*Math.sin(e*Math.PI*s*2)+.5)*i,flickerTime:a,flickerEffect:!0}}applySparkle(t,e){const i=t.params?.intensity||2,s=.001*Date.now();return{particleGlow:i,glow:.3*Math.sin(e*Math.PI*4)+.7,fireflyTime:s,fireflyEffect:!0}}applyShimmer(t,e){const i=.001*Date.now(),s=t.params?.intensity||.3,n=Math.sin(2*i+e*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 cn{constructor(t){this.renderer=t}applyBreathe(t,e){const{params:i}=t,s=i.particleMotion?.holdPercent||.1;let n;if(e<.4)n=Math.sin(e/.4*Math.PI/2);else if(e<.4+s)n=1;else if(e<.9){const t=(e-.4-s)/(.5-s);n=Math.cos(t*Math.PI/2)}else n=0;const r=1+n*(i.scaleAmount||.25),a=1+n*(i.glowAmount||.4);return t.breathPhase=n,{scale:r,glow:a,breathPhase:n}}applyBreathIn(t,e){return{scale:1+(t.params.scaleAmount-1)*Math.sin(e*Math.PI/2)}}applyBreathOut(t,e){return{scale:1-(1-t.params.scaleAmount)*Math.sin(e*Math.PI/2)}}applyBreathHold(t,e){return{scale:t.params.scaleAmount}}applyBreathHoldEmpty(t,e){return{scale:t.params.scaleAmount}}}class un{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applySpin(t,e){return{rotation:Math.min(1.05*e,1)*t.params.rotations*360,scale:1+Math.sin(e*Math.PI)*t.params.scaleAmount}}applyDrift(t,e){e<=.01&&!t.currentDriftAngle&&(t.currentDriftAngle=Math.random()*Math.PI*2);const i=t.params.distance*Math.sin(e*Math.PI)*this.scaleFactor,s=t.currentDriftAngle||0;return e>=.99&&(t.currentDriftAngle=null),{offsetX:Math.cos(s)*i,offsetY:Math.sin(s)*i}}applyWave(t,e){const i=(t.params.amplitude||40)*this.scaleFactor,s=e*Math.PI*2,n=Math.sin(s)*i,r=-Math.sin(e*Math.PI)*i*.3;return{offsetX:n,offsetY:Math.sin(2*s)*i*.2+r,rotation:5*Math.sin(s),scale:1+.05*Math.sin(e*Math.PI*2),glow:1+.2*Math.sin(e*Math.PI)}}applySway(t,e){const i=(t.params?.amplitude||30)*this.scaleFactor,s=t.params?.frequency||1;return{offsetX:Math.sin(e*Math.PI*2*s)*i,offsetY:Math.sin(e*Math.PI*4*s)*i*.1,rotation:5*Math.sin(e*Math.PI*2*s)}}applyFloat(t,e){const i=(t.params?.amplitude||20)*this.scaleFactor,s=t.params?.speed||1,n=Math.sin(e*Math.PI*2*s)*i;return{offsetX:Math.sin(e*Math.PI*3*s)*i*.3,offsetY:n,scale:1+.02*Math.sin(e*Math.PI*4*s)}}applyOrbital(t,e){return{offsetX:0,offsetY:0}}applyHula(t,e){const i=(t.params?.amplitude||40)*this.scaleFactor,s=e*Math.PI*2;return{offsetX:Math.sin(s)*i,offsetY:Math.sin(2*s)*i*.5}}applyOrbit(t,e){const i=(t.params?.radius||30)*this.scaleFactor,s=t.params?.speed||1,n=e*Math.PI*2*s;return{offsetX:Math.cos(n)*i,offsetY:Math.sin(n)*i}}}class dn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyPulse(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+i*t.params.scaleAmount,glow:1+i*t.params.glowAmount}}applyExpand(t,e){const i=Math.max(t.params.scaleAmount||t.params.scaleTarget||1.5,1),s=Math.sin(e*Math.PI/2);return{scale:1+(i-1)*s,glow:1+Math.abs(t.params.glowAmount||.2)*s}}applyContract(t,e){const i=t.params.scaleAmount||t.params.scaleTarget||.7,s=Math.sin(e*Math.PI/2);return{scale:1+(i-1)*s,glow:1+(t.params.glowAmount||-.2)*s}}applyStretch(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+((t.params.scaleX+t.params.scaleY)/2-1)*i}}applyMorph(t,e){const i=Math.sin(e*Math.PI*2);return{scale:1+.1*i,rotation:10*i}}}class pn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyNod(t,e){return{offsetY:Math.sin(e*Math.PI*t.params.frequency)*t.params.amplitude*this.scaleFactor}}applyTilt(t,e){t.tiltDirection||(t.tiltDirection=Math.random()<.5?-1:1);const i=t.params.frequency||2,s=(t.params.angle||15)*Math.PI/180,n=Math.sin(e*Math.PI*i)*t.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(t,e){let i=1;return i=e<.3?1-e/.3:e<.5?0:e<.8?(e-.5)/.3:1,{glow:i}}applyLook(t,e){if(!t.targetX){const e=t.params.lookDirection,i=50*t.params.lookDistance*this.scaleFactor;switch(e){case"left":t.targetX=-i,t.targetY=0;break;case"right":t.targetX=i,t.targetY=0;break;case"up":t.targetX=0,t.targetY=-i;break;case"down":t.targetX=0,t.targetY=i;break;default:{const e=Math.random()*Math.PI*2;t.targetX=Math.cos(e)*i,t.targetY=Math.sin(e)*i;break}}}let i=e;return i=e<.3?e/.3:e<.7?1:1-(e-.7)/.3,{offsetX:t.targetX*i,offsetY:t.targetY*i}}applySettle(t,e){const i=Math.sin(e*Math.PI*t.params.wobbleFreq)*Math.exp(3*-e)*20*this.scaleFactor;return{offsetY:i,scale:1+.01*i}}}class mn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyPoint(t,e){void 0===t.pointDirection&&(t.pointDirection=Math.random()<.5?-1:1);const i=void 0!==t.params?.direction?t.params.direction:t.pointDirection,s=(t.params?.distance||40)*this.scaleFactor;let n,r;return e<.4?(n=1-Math.pow(1-e/.4,3),r=n):e<.6?(n=1,r=1):(n=Math.pow(1-(e-.6)/.4,3),r=n),{offsetX:i*s*n,offsetY:-Math.abs(.15*s*n),scale:1+.15*r,rotation:5*i*r}}applyLean(t,e){const i=t.params?.angle||15,s=t.params?.side||1,n=Math.sin(e*Math.PI),r=i*s*n;return{offsetX:10*s*this.scaleFactor*n,rotation:r}}applyReach(t,e){const i=void 0!==t.params?.direction?t.params.direction:-Math.PI/2,s=(t.params?.distance||40)*this.scaleFactor;let n;return n=e<.4?e/.4:e<.6?1:1-(e-.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 gn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyFlashWave(t,e){t.flashWave||(t.flashWave={innerRadius:0,outerRadius:0,maxRadius:3}),t.flashWave.outerRadius=e*t.flashWave.maxRadius,t.flashWave.innerRadius=Math.max(0,(e-.1)*t.flashWave.maxRadius);const i=Math.max(0,1-.7*e);return t.flashWaveData={innerRadius:t.flashWave.innerRadius,outerRadius:t.flashWave.outerRadius,intensity:i},{glow:1+.3*i,flashWave:t.flashWaveData}}applyRain(t,e){return{offsetX:0,offsetY:0,particleEffect:"rain"}}applyGroove(t,e){const i=(t.params?.amplitude||25)*this.scaleFactor;return{offsetX:Math.sin(e*Math.PI*2)*i+Math.sin(e*Math.PI*3+.5)*i*.4,offsetY:Math.sin(e*Math.PI*4+.3)*i*.25,scale:1+.03*Math.sin(e*Math.PI*3+.7),rotation:8*Math.sin(e*Math.PI*2+.2)}}applyHeadBob(t,e){const i=(t.params?.amplitude||20)*this.scaleFactor,s=e*(t.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(t,e){const i=20*Math.sin(e*Math.PI*4)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(e*Math.PI*8))*this.scaleFactor,rotation:.3*i,scaleY:1-.05*Math.abs(Math.sin(e*Math.PI*8))}}applyCharleston(t,e){const i=25*Math.sin(e*Math.PI*8)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(e*Math.PI*8))*this.scaleFactor,rotation:.6*i,scaleY:1-.06*Math.abs(Math.sin(e*Math.PI*8))}}}class fn{constructor(t){this.renderer=t,this.activeGestures=new Map,this.scaleFactor=t.scaleFactor||1,this.physicalGestureAnimator=new hn(t),this.visualEffectAnimator=new ln(t),this.breathGestureAnimator=new cn(t),this.movementGestureAnimator=new un(t),this.shapeTransformAnimator=new dn(t),this.expressionGestureAnimator=new pn(t),this.directionalGestureAnimator=new mn(t),this.complexAnimationAnimator=new gn(t),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(t){const e=nn(t);if(["bounce","shake","pulse","flash","jump","slam","spin","flicker"].includes(t)&&this.renderer.specialEffects){const e={flash:1,jump:1,shake:.9,bounce:.8,pulse:.7,slam:1,spin:.8,flicker:1}[t]||.8;this.renderer.specialEffects.triggerChromaticAberration(e)}let i;i=this.renderer.gestureCompositor?this.renderer.gestureCompositor.compose(t,this.renderer.state.emotion,this.renderer.currentUndertone):e?.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(e&&e.config)if(e.config.musicalDuration)s=on.toMilliseconds(e.config.musicalDuration);else if(e.config.duration){const{duration:t}=e.config;s=t}const n=this.gestureAnimations[t];n&&(n.active=!0,n.startTime=performance.now(),n.progress=0,n.params=i,n.duration=s,"shake"===t?n.randomAngle=void 0:"drift"===t?(n.startX=void 0,n.startY=void 0,n.currentDriftAngle=void 0):"tilt"===t?n.tiltDirection=void 0:"vibrate"===t&&(n.vibrateAngles=void 0))}applyGestureAnimations(){const t=performance.now(),e={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=t-s.startTime,r=s.duration||(s.params?s.params.duration:1e3);s.progress=Math.min(n/r,1);const a=this.applyEasing(s.progress,s.params.easing);let o={};switch(i){case"bounce":o=this.applyBounce(s,a);break;case"pulse":o=this.applyPulse(s,a);break;case"shake":o=this.applyShake(s,a);break;case"spin":o=this.applySpin(s,a);break;case"nod":o=this.applyNod(s,a);break;case"tilt":o=this.applyTilt(s,a);break;case"expand":o=this.applyExpand(s,a);break;case"contract":o=this.applyContract(s,a);break;case"flash":o=this.applyFlash(s,a);break;case"drift":o=this.applyDrift(s,a);break;case"stretch":o=this.applyStretch(s,a);break;case"glow":o=this.applyGlow(s,a);break;case"flicker":o=this.applyFlicker(s,a);break;case"vibrate":o=this.applyVibrate(s,a);break;case"orbital":o=this.applyOrbital(s,a);break;case"hula":o=this.applyHula(s,a);break;case"wave":o=this.applyWave(s,a);break;case"breathe":o=this.applyBreathe(s,a);break;case"morph":o=this.applyMorph(s,a);break;case"slowBlink":o=this.applySlowBlink(s,a);break;case"look":o=this.applyLook(s,a);break;case"settle":o=this.applySettle(s,a);break;case"breathIn":o=this.applyBreathIn(s,a);break;case"breathOut":o=this.applyBreathOut(s,a);break;case"breathHold":o=this.applyBreathHold(s,a);break;case"breathHoldEmpty":o=this.applyBreathHoldEmpty(s,a);break;case"jump":o=this.applyJump(s,a);break;case"sway":o=this.applySway(s,a);break;case"float":o=this.applyFloat(s,a);break;case"rain":o=this.applyRain(s,a);break;case"runningman":o=this.applyRunningMan(s,a);break;case"charleston":o=this.applyCharleston(s,a);break;case"sparkle":o=this.applySparkle(s,a);break;case"shimmer":o=this.applyShimmer(s,a);break;case"wiggle":o=this.applyWiggle(s,a);break;case"groove":o=this.applyGroove(s,a);break;case"point":o=this.applyPoint(s,a);break;case"lean":o=this.applyLean(s,a);break;case"reach":o=this.applyReach(s,a);break;case"headBob":o=this.applyHeadBob(s,a);break;case"orbit":o=this.applyOrbit(s,a)}e.offsetX+=o.offsetX||0,e.offsetY+=o.offsetY||0,e.scale*=o.scale||1,e.rotation+=o.rotation||0,e.glow=Math.max(e.glow,o.glow||1),o.flashWave&&(e.flashWave=o.flashWave),o.fireflyEffect&&(e.fireflyEffect=o.fireflyEffect,e.particleGlow=o.particleGlow,e.fireflyTime=o.fireflyTime),o.flickerEffect&&(e.flickerEffect=o.flickerEffect,e.particleGlow=o.particleGlow,e.flickerTime=o.flickerTime),o.shimmerEffect&&(e.shimmerEffect=o.shimmerEffect,e.particleGlow=o.particleGlow,e.shimmerTime=o.shimmerTime,e.shimmerWave=o.shimmerWave),o.glowEffect&&(e.glowEffect=o.glowEffect,e.particleGlow=o.particleGlow,e.glowTime=o.glowTime,e.glowProgress=o.glowProgress,e.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 e}update(t){return this.applyGestureAnimations()}stopAllGestures(){Object.keys(this.gestureAnimations).forEach(t=>{const e=this.gestureAnimations[t];e.active=!1,e.startTime=0,e.progress=0,e.params=null,e.glowEffect&&(e.glowEffect=null,e.particleGlow=null,e.glowTime=null,e.glowProgress=null,e.glowEnvelope=null),e.fireflyEffect&&(e.fireflyEffect=null,e.particleGlow=null,e.fireflyTime=null),e.flickerEffect&&(e.flickerEffect=null,e.particleGlow=null,e.flickerTime=null),e.shimmerEffect&&(e.shimmerEffect=null,e.particleGlow=null,e.shimmerTime=null,e.shimmerWave=null),e.flashWave&&(e.flashWave=null,e.flashWaveData=null)}),this.activeGestures.clear()}getCurrentGesture(){const t=performance.now(),e=["orbital","hula","wave","spin"];for(const i of e){const e=this.gestureAnimations[i];if(e&&e.active){const s=nn(i),n=t-e.startTime,r=e.duration||(e.params?e.params.duration:1e3),a=Math.min(n/r,1);return{name:i,particleMotion:s?.config?.particleMotion||{type:i,strength:e.params?.strength||1},progress:a,params:e.params}}}for(const[e,i]of Object.entries(this.gestureAnimations))if(i.active){const s=nn(e),n=t-i.startTime,r=i.duration||(i.params?i.params.duration:1e3),a=Math.min(n/r,1),o={name:e,particleMotion:s?.config?.particleMotion||i.params?.particleMotion||{type:e,strength:i.params?.strength||1},progress:a,params:i.params};return"breathe"===e&&void 0!==i.breathPhase&&(o.breathPhase=i.breathPhase),o}return null}applyEasing(t,e){switch(e){case"linear":default:return t;case"quad":return t*t;case"cubic":return t*t*t;case"sine":return Math.sin(t*Math.PI/2);case"back":return t*t*(2.7*t-1.7)}}applyBounce(t,e){return this.physicalGestureAnimator.applyBounce(t,e)}applyPulse(t,e){return this.shapeTransformAnimator.applyPulse(t,e)}applyShake(t,e){return this.physicalGestureAnimator.applyShake(t,e)}applySpin(t,e){return this.movementGestureAnimator.applySpin(t,e)}applyNod(t,e){return this.expressionGestureAnimator.applyNod(t,e)}applyTilt(t,e){return this.expressionGestureAnimator.applyTilt(t,e)}applyExpand(t,e){return this.shapeTransformAnimator.applyExpand(t,e)}applyContract(t,e){return this.shapeTransformAnimator.applyContract(t,e)}applyFlash(t,e){return this.visualEffectAnimator.applyFlash(t,e)}applyDrift(t,e){return this.movementGestureAnimator.applyDrift(t,e)}applyStretch(t,e){return this.shapeTransformAnimator.applyStretch(t,e)}applyGlow(t,e){return this.visualEffectAnimator.applyGlow(t,e)}applyFlashWave(t,e){return this.complexAnimationAnimator.applyFlashWave(t,e)}applyFlicker(t,e){return this.visualEffectAnimator.applyFlicker(t,e)}applyVibrate(t,e){return this.physicalGestureAnimator.applyVibrate(t,e)}applyWave(t,e){return this.movementGestureAnimator.applyWave(t,e)}applyBreathe(t,e){return this.breathGestureAnimator.applyBreathe(t,e)}applyMorph(t,e){return this.shapeTransformAnimator.applyMorph(t,e)}applySlowBlink(t,e){return this.expressionGestureAnimator.applySlowBlink(t,e)}applyLook(t,e){return this.expressionGestureAnimator.applyLook(t,e)}applySettle(t,e){return this.expressionGestureAnimator.applySettle(t,e)}applyBreathIn(t,e){return this.breathGestureAnimator.applyBreathIn(t,e)}applyBreathOut(t,e){return this.breathGestureAnimator.applyBreathOut(t,e)}applyBreathHold(t,e){return this.breathGestureAnimator.applyBreathHold(t,e)}applyBreathHoldEmpty(t,e){return this.breathGestureAnimator.applyBreathHoldEmpty(t,e)}applyJump(t,e){return this.physicalGestureAnimator.applyJump(t,e)}applySway(t,e){return this.movementGestureAnimator.applySway(t,e)}applyRain(t,e){return this.complexAnimationAnimator.applyRain(t,e)}applyFloat(t,e){return this.movementGestureAnimator.applyFloat(t,e)}applyOrbital(t,e){return this.movementGestureAnimator.applyOrbital(t,e)}applyHula(t,e){return this.movementGestureAnimator.applyHula(t,e)}applySparkle(t,e){return this.visualEffectAnimator.applySparkle(t,e)}applyShimmer(t,e){return this.visualEffectAnimator.applyShimmer(t,e)}applyWiggle(t,e){return this.physicalGestureAnimator.applyWiggle(t,e)}applyGroove(t,e){return this.complexAnimationAnimator.applyGroove(t,e)}applyPoint(t,e){return this.directionalGestureAnimator.applyPoint(t,e)}applyLean(t,e){return this.directionalGestureAnimator.applyLean(t,e)}applyReach(t,e){return this.directionalGestureAnimator.applyReach(t,e)}applyHeadBob(t,e){return this.complexAnimationAnimator.applyHeadBob(t,e)}applyOrbit(t,e){return this.movementGestureAnimator.applyOrbit(t,e)}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(t,e){return this.complexAnimationAnimator.applyRunningMan(t,e)}applyCharleston(t,e){return this.complexAnimationAnimator.applyCharleston(t,e)}startRunningManGesture(){this.startGesture("runningman")}startCharlestonGesture(){this.startGesture("charleston")}pauseCurrentAnimation(){const t=performance.now();for(const[,e]of Object.entries(this.gestureAnimations))e.active&&(e.pausedAt=t,e.pausedProgress=e.progress);this.isPaused=!0}resumeAnimation(){if(!this.isPaused)return;const t=performance.now();for(const[,e]of Object.entries(this.gestureAnimations))if(e.active&&e.pausedAt){const i=t-e.pausedAt;e.startTime&&(e.startTime+=i),delete e.pausedAt,delete e.pausedProgress}this.isPaused=!1}reset(){for(const[,t]of Object.entries(this.gestureAnimations))t.active=!1,t.progress=0,t.params={},delete t.startTime,delete t.pausedAt,delete t.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 yn{constructor(){this.colorTransition=null}applyUndertoneModifiers(t,e){return e}applyUndertoneToColor(t,e){if(e&&"object"==typeof e&&void 0!==e.weight){const{weight:i}=e,s=e.type||"clear";if("clear"===s||0===i)return t;const n=this.applyUndertoneSaturation(t,s),r=this.hexToRgb(t),a=this.hexToRgb(n),o=Math.round(r.r+(a.r-r.r)*i),h=Math.round(r.g+(a.g-r.g)*i),l=Math.round(r.b+(a.b-r.b)*i);return this.rgbToHex(o,h,l)}return e&&"clear"!==e?this.applyUndertoneSaturation(t,e):t}hexToRgb(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null}rgbToHsl(t,e,i){t/=255,e/=255,i/=255;const s=Math.max(t,e,i),n=Math.min(t,e,i),r=(s+n)/2;let a,o;if(s===n)a=o=0;else{const h=s-n;switch(o=r>.5?h/(2-s-n):h/(s+n),s){case t:a=((e-i)/h+(e<i?6:0))/6;break;case e:a=((i-t)/h+2)/6;break;case i:a=((t-e)/h+4)/6}}return{h:360*a,s:100*o,l:100*r}}hslToHex(t,e,i){let s,n,r;if(t/=360,i/=100,0==(e/=100))s=n=r=i;else{const a=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),o=i<.5?i*(1+e):i+e-i*e,h=2*i-o;s=a(h,o,t+1/3),n=a(h,o,t),r=a(h,o,t-1/3)}const a=t=>{const e=Math.round(255*t).toString(16);return 1===e.length?`0${e}`:e};return`#${a(s)}${a(n)}${a(r)}`}applyUndertoneSaturation(t,e){const i=this.hexToRgb(t),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}[e]||1;return s.s=Math.min(100,s.s*n),this.hslToHex(s.h,s.s,s.l)}rgbToHex(t,e,i){const s=t=>{const e=Math.round(t).toString(16);return 1===e.length?`0${e}`:e};return`#${s(t)}${s(e)}${s(i)}`}startColorTransition(t,e,i=1500){this.currentColor===t&&this.currentIntensity===e||(this.colorTransition={active:!0,fromColor:this.currentColor||"#ffffff",toColor:t,fromIntensity:this.currentIntensity||1,toIntensity:e,progress:0,startTime:performance.now(),duration:i})}updateColorTransition(t){if(!this.colorTransition||!this.colorTransition.active)return null;const e=performance.now()-this.colorTransition.startTime,i=Math.min(e/this.colorTransition.duration,1),s=1-Math.pow(1-i,2),n=this.hexToRgb(this.colorTransition.fromColor),r=this.hexToRgb(this.colorTransition.toColor),a=Math.round(n.r+(r.r-n.r)*s),o=Math.round(n.g+(r.g-n.g)*s),h=Math.round(n.b+(r.b-n.b)*s),l=this.rgbToHex(a,o,h),c=this.colorTransition.fromIntensity+(this.colorTransition.toIntensity-this.colorTransition.fromIntensity)*s;return this.currentColor=l,this.currentIntensity=c,i>=1&&(this.colorTransition.active=!1),{color:l,intensity:c}}}class Mn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.canvasManager?.canvas||t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}renderRecordingGlow(t,e,i,s){const{ctx:n}=this,r=2.5*i,a=n.createRadialGradient(t,e,0,t,e,r);a.addColorStop(0,`rgba(255, 0, 0, ${.3*s})`),a.addColorStop(.5,`rgba(255, 0, 0, ${.15*s})`),a.addColorStop(1,"rgba(255, 0, 0, 0)"),n.save(),n.globalCompositeOperation="screen",n.fillStyle=a,n.fillRect(t-r,e-r,2*r,2*r),n.restore()}renderRecordingIndicator(t,e){const i=Date.now()/1e3,s=.8+.2*Math.sin(2*i);this.ctx.save(),this.ctx.translate(t,e),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(t,e,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:t+Math.random()*this.scaleValue(30)-this.scaleValue(15),y:e+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(t=>{if(t.lifetime+=i,t.y+=t.speed*i,t.x+=Math.sin(8e-4*t.lifetime)*t.drift*.008,t.rotation+=.01*i,t.lifetime<2e3?t.opacity=1:t.lifetime<4e3?t.opacity=1-(t.lifetime-2e3)/2e3:t.opacity=0,t.opacity>.01){this.ctx.save(),this.ctx.translate(t.x,t.y),this.ctx.rotate(t.rotation*Math.PI/180);const e=this.renderer.state.glowColor||"#4a90e2";this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=this.hexToRgba(e,.5*t.opacity);const i=this.ctx.createLinearGradient(-t.size/2,-t.size/2,t.size/2,t.size/2);return i.addColorStop(0,this.hexToRgba(e,t.opacity)),i.addColorStop(.5,this.hexToRgba("#ffffff",.9*t.opacity)),i.addColorStop(1,this.hexToRgba(e,.7*t.opacity)),this.ctx.font=`italic ${t.weight||"900"} ${t.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=i,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(t.text||"Z",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic ${t.weight||"900"} ${.9*t.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=this.hexToRgba("#ffffff",.3*t.opacity),this.ctx.fillText(t.text||"Z",-1,-1),this.ctx.restore(),!0}return!1})}renderSpeakingRings(t,e,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(t,e,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(t,e,i={}){this.sparkles.push({x:t,y:e,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:t}=this;this.sparkles.forEach(e=>{const i=1-e.lifetime/e.maxLifetime,s=1-i;t.save(),t.translate(e.x,e.y),t.rotate(e.rotation);const n=this.scaleValue(e.size*(1-.5*i));t.beginPath();const r=n,a=.38*n;for(let e=0;e<10;e++){const i=e*Math.PI/5-Math.PI/2,s=e%2==0?r:a;0===e?t.moveTo(Math.cos(i)*s,Math.sin(i)*s):t.lineTo(Math.cos(i)*s,Math.sin(i)*s)}t.closePath(),t.shadowBlur=this.scaleValue(10),t.shadowColor=e.color,t.fillStyle=e.color.replace("70%",70+30*i+"%").replace(")",`, ${s})`).replace("hsl","hsla"),t.fill(),t.restore()})}triggerChromaticAberration(t=.8){this.chromaticAberration.active=!0,this.chromaticAberration.targetIntensity=Math.min(1,t),this.chromaticAberration.intensity=this.chromaticAberration.targetIntensity;const e=document.getElementById("emotive-canvas")||document.querySelector("canvas")||this.canvas;if(e){if(e.style.animation="none",!document.getElementById("chromatic-styles")){const t=document.createElement("style");t.id="chromatic-styles",t.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(t)}e.style.animation=`chromaticGlitch ${300+200*t}ms ease-out`}}applyChromaticAberration(t,e){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return;const{intensity:i}=this.chromaticAberration,s=this.scaleValue(this.chromaticAberration.maxOffset*i),n=t.globalCompositeOperation;t.save(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.globalCompositeOperation="source-over",t.filter="url(#red-channel)",t.drawImage(e,-s,0),t.globalCompositeOperation="screen",t.filter="url(#green-channel)",t.drawImage(e,0,0),t.globalCompositeOperation="screen",t.filter="url(#blue-channel)",t.drawImage(e,s,0),t.filter="none",t.globalCompositeOperation=n,t.restore()}applyChromaticAberrationSimple(t,e,i,s,n){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return void n();const{intensity:r}=this.chromaticAberration,a=this.scaleValue(this.chromaticAberration.maxOffset*r);t.save(),t.globalCompositeOperation="source-over",t.translate(-a,0),t.globalAlpha=.33,t.fillStyle="#ff0000",t.filter="brightness(3)",n(),t.translate(a,0),t.globalCompositeOperation="screen",t.globalAlpha=.33,t.fillStyle="#00ff00",n(),t.translate(a,0),t.globalAlpha=.33,t.fillStyle="#0000ff",n(),t.restore()}update(t){this.sparkles=this.sparkles.filter(e=>(e.x+=e.vx,e.y+=e.vy,e.rotation+=e.rotationSpeed,e.lifetime-=t,e.vy+=.1,e.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 bn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}update(t){this.blinking&&(this.blinkTimer+=t,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 t=Math.min(this.blinkTimer/150,1);return 1-.7*Math.sin(t*Math.PI)}drawEyes(t,e,i,s,n={}){const{ctx:r}=this,a=n.eyeOpenness||1,o=n.eyeExpression||"neutral";if("neutral"===s||a<=0)return;r.save(),r.strokeStyle="rgba(0, 0, 0, 0.3)",r.lineWidth=this.scaleValue(2),r.lineCap="round";const h=.4*i,l=e-.1*i,c=.25*i;switch(o){case"happy":this.drawHappyEyes(r,t,l,h,c,a);break;case"sad":this.drawSadEyes(r,t,l,h,c,a);break;case"angry":this.drawAngryEyes(r,t,l,h,c,a);break;case"surprised":this.drawSurprisedEyes(r,t,l,h,c,a);break;case"focused":this.drawFocusedEyes(r,t,l,h,c,a);break;case"sleepy":this.drawSleepyEyes(r,t,l,h,c,a);break;case"suspicious":this.drawSuspiciousEyes(r,t,l,h,c,a)}r.restore()}drawHappyEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i,n,.2*Math.PI,.8*Math.PI,!1),t.stroke(),t.beginPath(),t.arc(e+s,i,n,.2*Math.PI,.8*Math.PI,!1),t.stroke()}drawSadEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),t.stroke(),t.beginPath(),t.arc(e+s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),t.stroke()}drawAngryEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i-.3*n),t.lineTo(e-s+.5*n,i+.3*n),t.stroke(),t.beginPath(),t.moveTo(e+s+n,i-.3*n),t.lineTo(e+s-.5*n,i+.3*n),t.stroke()}drawSurprisedEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i,1.2*n,0,2*Math.PI),t.stroke(),t.beginPath(),t.arc(e+s,i,1.2*n,0,2*Math.PI),t.stroke()}drawFocusedEyes(t,e,i,s,n,r){t.fillStyle="rgba(0, 0, 0, 0.4)",t.beginPath(),t.arc(e-s,i,.3*n,0,2*Math.PI),t.fill(),t.beginPath(),t.arc(e+s,i,.3*n,0,2*Math.PI),t.fill()}drawSleepyEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i),t.lineTo(e-s+n,i),t.stroke(),t.beginPath(),t.moveTo(e+s-n,i),t.lineTo(e+s+n,i),t.stroke()}drawSuspiciousEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i),t.lineTo(e-s+.7*n,i),t.stroke(),t.beginPath(),t.arc(e+s,i,.8*n,.1*Math.PI,.9*Math.PI,!1),t.stroke()}setBlinkingEnabled(t){this.blinkingEnabled=t,t||(this.blinking=!1,this.blinkTimer=0)}setSquintAmount(t){this.squintAmount=Math.max(0,Math.min(1,t))}forceBlink(){this.startBlink()}}class wn{constructor(t){this.renderer=t,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(t,e,i={}){i=i||{};const s=this.emotionBreathPatterns[e]||{rate:1,depth:1},n=i?.breathRateMult||1,r=i?.breathDepthMult||1;this.breathRate=s.rate*this.breathRateMult*n,this.breathDepth=this.breathingDepth*s.depth*this.breathDepthMult*r;let a=this.breathingSpeed*this.breathRate*(t/1e3);this.breathIrregular&&i?.breathIrregular&&(a*=.8+.4*Math.sin(3e-4*Date.now())),this.breathingPhase+=a,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(t){this.customScale=t}setBreathingSpeed(t){this.breathingSpeed=t}setBreathingDepth(t){this.breathingDepth=Math.max(0,Math.min(1,t))}setBreathRateMultiplier(t){this.breathRateMult=t}setBreathDepthMultiplier(t){this.breathDepthMult=t}setIrregularBreathing(t){this.breathIrregular=t}reset(){this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null}holdBreath(t=!1){this.customScale=t?.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}}}const vn=new class{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(t,e){if("radial"===t){const{x0:t,y0:i,r0:s,x1:n,y1:r,r1:a,stops:o}=e;return`radial:${t},${i},${s},${n},${r},${a}:${o.map(t=>`${t.offset}:${t.color}`).join("|")}`}if("linear"===t){const{x0:t,y0:i,x1:s,y1:n,stops:r}=e;return`linear:${t},${i},${s},${n}:${r.map(t=>`${t.offset}:${t.color}`).join("|")}`}return null}getRadialGradient(t,e,i,s,n,r,a,o){const h=this.generateKey("radial",{x0:e,y0:i,r0:s,x1:n,y1:r,r1:a,stops:o}),l=this.cache.get(h);if(l&&Date.now()-l.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(h),l.gradient;this.stats.misses++;const c=t.createRadialGradient(e,i,s,n,r,a);return o.forEach(t=>{c.addColorStop(t.offset,t.color)}),this.set(h,c),c}getLinearGradient(t,e,i,s,n,r){const a=this.generateKey("linear",{x0:e,y0:i,x1:s,y1:n,stops:r}),o=this.cache.get(a);if(o&&Date.now()-o.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(a),o.gradient;this.stats.misses++;const h=t.createLinearGradient(e,i,s,n);return r.forEach(t=>{h.addColorStop(t.offset,t.color)}),this.set(a,h),h}set(t,e){this.cache.size>=this.maxSize&&!this.cache.has(t)&&this.evictLRU(),this.cache.set(t,{gradient:e,timestamp:Date.now()}),this.updateAccessOrder(t)}updateAccessOrder(t){const e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length>0){const t=this.accessOrder.shift();this.cache.delete(t),this.stats.evictions++}}clear(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.cache.clear(),this.accessOrder=[]}clearExpired(){const t=Date.now(),e=[];for(const[i,s]of this.cache.entries())t-s.timestamp>=this.ttl&&e.push(i);e.forEach(t=>{this.cache.delete(t);const e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1)})}destroy(){this.clear()}getStats(){const t=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:`${t}%`}}createHelper(t){return{radial:(e,i,s,n,r,a,o)=>this.getRadialGradient(t,e,i,s,n,r,a,o),linear:(e,i,s,n,r)=>this.getLinearGradient(t,e,i,s,n,r)}}};class Sn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i),this.initOffscreenCanvas()}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d")}updateOffscreenSize(t){this.offscreenCanvas.width===t&&this.offscreenCanvas.height===t||(this.offscreenCanvas.width=t,this.offscreenCanvas.height=t,this.cachedGlowColor=null)}renderGlow(t,e,i,s={}){const{ctx:n}=this,r=s.color||this.glowColor,a=void 0!==s.intensity?s.intensity:this.glowIntensity;a<.01||this.renderGlowDirect(n,t,e,i,r,a)}cacheGlowGradient(t,e){const i=this.offscreenCtx,s=e;this.updateOffscreenSize(2*e),i.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height);const n=vn.getRadialGradient(i,s,s,0,s,s,e,[{offset:0,color:this.hexToRgba(t,.4)},{offset:.3,color:this.hexToRgba(t,.2)},{offset:.6,color:this.hexToRgba(t,.1)},{offset:1,color:this.hexToRgba(t,0)}]);i.fillStyle=n,i.fillRect(0,0,2*e,2*e),this.cachedGlowColor=t,this.cachedGlowRadius=e}renderGlowDirect(t,e,i,s,n,r){t.save(),t.globalCompositeOperation="screen";const a=[];for(let t=0;t<=20;t++){const e=t/20,i=.6*Math.pow(1-e,2.2),s=Math.max(0,Math.min(1,i*r));a.push({offset:e,color:this.hexToRgba(n,s)})}const o=vn.getRadialGradient(t,e,i,0,e,i,s,a);t.fillStyle=o,t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.fill(),t.restore()}renderRecordingGlow(t,e,i,s){const{ctx:n}=this,r=2.5*i,a=vn.getRadialGradient(n,t,e,0,t,e,r,[{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=a,n.fillRect(t-r,e-r,2*r,2*r),n.restore()}updateGlowColor(t,e){this.targetGlowColor!==t&&(this.targetGlowColor=t,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(t,e,i){const s=this.hexToRgb(t),n=this.hexToRgb(e);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(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:{r:0,g:0,b:0}}setGlowIntensity(t){this.glowIntensity=Math.max(0,Math.min(1,t))}setGlowColor(t){this.glowColor=t,this.targetGlowColor=t,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 kn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.canvas,this.coreColor="#FFFFFF",this.coreOpacity=1,this.coreBorderWidth=0,this.coreBorderColor=null,this.shapePoints=null,this.isMorphing=!1,this.scaleValue=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}renderCore(t,e,i,s={}){const{ctx:n}=this,r=s.scaleX||1,a=s.scaleY||1,o=s.rotation||0,h=void 0!==s.opacity?s.opacity:this.coreOpacity,l=s.color||this.coreColor,c=s.shapePoints||this.shapePoints;n.save(),n.translate(t,e),0!==o&&n.rotate(o),n.scale(r,a),n.fillStyle=this.hexToRgba(l,h),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(t,e,i){t.save();const s=this.scaleValue(2);if(t.translate(0,s),i&&i.length>32)t.fillStyle="rgba(0, 0, 0, 0.15)",t.beginPath(),t.arc(0,0,1.05*e,0,2*Math.PI),t.fill();else{const s=vn.getRadialGradient(t,0,0,.7*e,0,0,1.2*e,[{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(t.fillStyle=s,t.beginPath(),i){const e=1.1,s=i.length>20?2:1;t.moveTo(i[0].x*e,i[0].y*e);for(let n=s;n<i.length;n+=s)t.lineTo(i[n].x*e,i[n].y*e);t.closePath()}else t.arc(0,0,1.1*e,0,2*Math.PI);t.fill()}t.restore()}drawCircle(t,e){t.beginPath(),t.arc(0,0,e,0,2*Math.PI),t.fill()}drawMorphedShape(t,e,i){!e||e.length<3?this.drawCircle(t,i):(t.beginPath(),e.forEach((e,i)=>{0===i?t.moveTo(e.x,e.y):t.lineTo(e.x,e.y)}),t.closePath(),t.fill())}renderSleepyCore(t,e,i){const{ctx:s}=this;s.save(),s.translate(t,e),s.scale(1,.85),s.fillStyle="#FFFFFF",s.beginPath(),s.arc(0,0,i,0,2*Math.PI),s.fill(),s.restore()}renderGlitchedCore(t,e,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(r=>{n.fillStyle=this.hexToRgba("#FFFFFF",r.alpha*s),n.beginPath(),n.arc(t+r.x*s*this.scaleValue(5),e+r.y*s*this.scaleValue(5),i,0,2*Math.PI),n.fill()}),n.fillStyle="#FFFFFF",n.beginPath(),n.arc(t,e,i,0,2*Math.PI),n.fill(),n.restore()}setShapePoints(t){this.shapePoints=t,this.isMorphing=t&&t.length>0}clearShapePoints(){this.shapePoints=null,this.isMorphing=!1}setCoreColor(t){this.coreColor=t}setCoreOpacity(t){this.coreOpacity=Math.max(0,Math.min(1,t))}setCoreBorder(t,e){this.coreBorderWidth=t,this.coreBorderColor=e}getCoreInfo(){return{color:this.coreColor,opacity:this.coreOpacity,hasBorder:this.coreBorderWidth>0,isMorphing:this.isMorphing,shapePointCount:this.shapePoints?this.shapePoints.length:0}}}class xn{renderSunEffects(t,e,i,s,n){const r=Date.now()/100;if(t.save(),t.translate(e,i),n.texture&&(void 0===n.textureOpacity||n.textureOpacity>0)){t.save(),t.globalCompositeOperation="screen",t.globalAlpha=void 0!==n.textureOpacity?n.textureOpacity:1;const e=.05*r*(n.turbulence||.3)/.3,i=t.createRadialGradient(Math.sin(e)*s*.15,Math.cos(.7*e)*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)"),t.fillStyle=i,t.beginPath(),t.arc(0,0,s,0,2*Math.PI),t.fill(),t.restore()}const a=void 0!==n.coronaOpacity?n.coronaOpacity:1;if(a>0){t.save(),t.globalCompositeOperation="screen";const e=t.createRadialGradient(0,0,.5*s,0,0,1.1*s);e.addColorStop(0,`rgba(255, 255, 255, ${.8*a})`),e.addColorStop(.3,`rgba(255, 250, 200, ${.6*a})`),e.addColorStop(.5,`rgba(255, 200, 100, ${.4*a})`),e.addColorStop(.7,`rgba(255, 150, 50, ${.2*a})`),e.addColorStop(1,"rgba(255, 100, 20, 0)"),t.fillStyle=e,t.beginPath(),t.arc(0,0,1.1*s,0,2*Math.PI),t.fill();for(let e=0;e<2;e++){const i=1.3+.4*e,n=(.35-.15*e)*a,o=.05*Math.sin(.1*r+e),h=t.createRadialGradient(0,0,s*(.9+o),0,0,s*(i+o));h.addColorStop(0,"rgba(255, 255, 200, 0)"),h.addColorStop(.4,`rgba(255, 200, 100, ${.5*n})`),h.addColorStop(.7,`rgba(255, 150, 50, ${n})`),h.addColorStop(.9,`rgba(255, 100, 30, ${.5*n})`),h.addColorStop(1,"rgba(255, 50, 10, 0)"),t.fillStyle=h,t.beginPath(),t.arc(0,0,s*(i+o),0,2*Math.PI),t.fill()}t.restore()}if(n.flares){t.save();const e=Math.sin(.08*r),i=Math.sin(.12*r),n=Math.sin(.16*r),a=t.createLinearGradient(0,-s,0,3*-s);a.addColorStop(0,"rgba(255, 255, 230, 0.4)"),a.addColorStop(.2,"rgba(255, 220, 150, 0.25)"),a.addColorStop(.5,"rgba(255, 180, 80, 0.15)"),a.addColorStop(.8,"rgba(255, 120, 40, 0.08)"),a.addColorStop(1,"rgba(255, 60, 20, 0)"),t.fillStyle=a,t.globalCompositeOperation="screen",t.beginPath();const o=(e,i,n,r)=>{const a=Math.cos(e),o=Math.sin(e),h=a*s,l=o*s,c=a*(s+i),u=o*(s+i),d=-o*n*.5,p=a*n*.5,m=r*n*.3;t.moveTo(h-d,l-p),t.quadraticCurveTo(.5*(h+c)+d*m,.5*(l+u)+p*m,c,u),t.quadraticCurveTo(.5*(h+c)-d*m,.5*(l+u)-p*m,h+d,l+p)};for(let t=0;t<8;t++)o(t/8*Math.PI*2+.1*e,s*(1.8+.4*Math.sin(.1*r+.5*t)),.18*s,Math.sin(.15*r+t));for(let t=0;t<12;t++)o((t+.5)/12*Math.PI*2+.08*i,s*(1.2+.3*Math.sin(.13*r+.7*t)),.12*s,Math.sin(.18*r+1.2*t));for(let t=0;t<15;t++)o(t/15*Math.PI*2+.05*n,s*(.7+.25*Math.sin(.17*r+.9*t)),.08*s,Math.sin(.2*r+1.5*t));for(let e=0;e<15;e++){const i=(e+.25)/15*Math.PI*2,n=s*(.4+.2*Math.sin(.22*r+e)),a=.06*s,o=Math.cos(i),h=Math.sin(i),l=o*s,c=h*s,u=o*(s+n),d=h*(s+n),p=-h*a*.5,m=o*a*.5;t.moveTo(l-p,c-m),t.lineTo(u,d),t.lineTo(l+p,c+m)}t.fill(),t.restore()}const o=t.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)"),t.fillStyle=o,t.beginPath(),t.arc(0,0,1.05*s,0,2*Math.PI),t.fill(),t.restore()}renderBaileysBeads(t,e,i,s,n,r,a,o,h,l=t=>t){if(!h)return void(this.Mt=null);const c=Math.abs(n)<1&&Math.abs(r)<1,u=o?30:15;if(!(Math.abs(n)<u&&Math.abs(r)<u||c))return void(this.Mt=null);if(!this.Mt){const t=Math.floor(4*Math.random())+1;this.bt=[];const e=[];for(let i=0;i<t;i++)e.push(Math.random()*Math.PI*2);const i=Array.from({length:t},(t,e)=>e);for(let t=i.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[i[t],i[e]]=[i[e],i[t]]}for(let s=0;s<t;s++)this.bt.push({angle:e[s],size:3+5*Math.random(),order:i[s],delay:200*i[s]});this.Mt=Date.now()}const d=Date.now()-this.Mt;(this.bt||[]).forEach(n=>{if(d<n.delay)return;const r=d-n.delay,a=Math.min(1,r/300),o=e+Math.cos(n.angle)*s,h=i+Math.sin(n.angle)*s;t.save(),t.translate(o,h),t.globalAlpha=a;const c=l(n.size),u=[{color:`rgba(255, 100, 100, ${.6*a})`,offset:-2},{color:`rgba(100, 255, 100, ${.6*a})`,offset:0},{color:`rgba(100, 100, 255, ${.6*a})`,offset:2}];t.globalCompositeOperation="screen",u.forEach(({color:e,offset:i})=>{const s=t.createRadialGradient(i,i,0,i,i,2*c);s.addColorStop(0,e),s.addColorStop(.2,e.replace(""+.6*a,""+.4*a)),s.addColorStop(.5,e.replace(""+.6*a,""+.2*a)),s.addColorStop(1,"rgba(255, 255, 255, 0)"),t.fillStyle=s,t.beginPath(),t.arc(i,i,2*c,0,2*Math.PI),t.fill()}),t.globalCompositeOperation="lighter";const p=t.createRadialGradient(0,0,0,0,0,c);p.addColorStop(0,`rgba(255, 255, 255, ${a})`),p.addColorStop(.3,`rgba(255, 255, 255, ${.5*a})`),p.addColorStop(1,"rgba(255, 255, 255, 0)"),t.fillStyle=p,t.beginPath(),t.arc(0,0,c,0,2*Math.PI),t.fill(),t.restore()})}renderMoonShadow(t,e,i,s,n,r,a=!1,o=0,h=null){if(t.save(),t.globalAlpha=1,t.translate(e,i),"crescent"===n.type){let e=1,i=n.offset||.7;if(h){const t=h.getProgress(),{targetShape:s}=h;"moon"===s&&void 0!==t&&t<1&&!n.shadowX&&(e=t,i=2.7*e-2)}const a=(n.angle||-30)*Math.PI/180,o=Math.cos(a)*s*i,l=Math.sin(a)*s*i;if(t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.beginPath(),r&&r.length>0){t.moveTo(r[0].x,r[0].y);for(let e=1;e<r.length;e++)t.lineTo(r[e].x,r[e].y);t.closePath()}else t.arc(0,0,s,0,2*Math.PI);t.clip();const c=t.createRadialGradient(o,l,.9*s,o,l,1.1*s),u=void 0!==n.coverage?n.coverage:.85,d=Math.min(1,1.2*e)*(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)"),t.fillStyle=c,t.beginPath(),t.arc(o,l,1.1*s,0,2*Math.PI),t.fill()}else if("lunar"===n.type){const e=1-(void 0!==n.diffusion?n.diffusion:1);let i=0,r=0;if(h){const t=h.getProgress(),{currentShape:e,targetShape:n}=h;if(a&&"solar"===n&&void 0!==t&&t<1){const e=2.5*s;i=-e*(1-t),r=e*(1-t)}else if(a&&"solar"===e&&"solar"!==n&&null!==n&&void 0!==t&&t<1){const e=2.5*s;i=e*t,r=-e*t}}t.translate(i,r),a?(t.save(),t.beginPath(),t.arc(-i,-r,s,0,2*Math.PI),t.clip()):(t.beginPath(),t.arc(0,0,s,0,2*Math.PI),t.clip());const o=s*(1.8-.5*e),l=t.createRadialGradient(0,0,.2*s,0,0,o),c=n.coverage||.9;if(n.color&&n.color.includes("0, 0, 0")?(l.addColorStop(0,`rgba(0, 0, 0, ${c})`),l.addColorStop(.3+.2*e,`rgba(0, 0, 0, ${.95*c})`),l.addColorStop(.6+.2*e,`rgba(0, 0, 0, ${.8*c})`),l.addColorStop(.85,`rgba(0, 0, 0, ${.4*c})`),l.addColorStop(1,"rgba(0, 0, 0, 0)")):(l.addColorStop(0,`rgba(10, 2, 0, ${c})`),l.addColorStop(.3+.2*e,`rgba(20, 5, 0, ${.95*c})`),l.addColorStop(.6+.2*e,`rgba(40, 10, 5, ${.8*c})`),l.addColorStop(.85,`rgba(60, 15, 10, ${.4*c})`),l.addColorStop(1,"rgba(80, 20, 15, 0)")),t.fillStyle=l,t.beginPath(),t.arc(0,0,o,0,2*Math.PI),t.fill(),e>.3){const i=s*(.8+.3*e),r=t.createRadialGradient(0,0,0,0,0,i);n.color&&n.color.includes("0, 0, 0")?(r.addColorStop(0,`rgba(0, 0, 0, ${c})`),r.addColorStop(.5,`rgba(0, 0, 0, ${.9*c})`),r.addColorStop(.8,`rgba(0, 0, 0, ${.5*c})`),r.addColorStop(1,"rgba(0, 0, 0, 0)")):(r.addColorStop(0,`rgba(0, 0, 0, ${c})`),r.addColorStop(.5,`rgba(10, 2, 0, ${.9*c})`),r.addColorStop(.8,`rgba(20, 5, 0, ${.5*c})`),r.addColorStop(1,"rgba(30, 8, 5, 0)")),t.fillStyle=r,t.beginPath(),t.arc(0,0,i,0,2*Math.PI),t.fill()}}a&&t.restore(),t.restore()}}class En{constructor(t){this.renderer=t,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(t,e,i,s,n){if(!t||!this.episodicEffects[t])return{jitterX:e,jitterY:i,coreRadius:s,glowRadius:n};const r=this.episodicEffects[t],a=performance.now();if(!r.active&&a>=r.nextTrigger)switch(r.active=!0,r.startTime=a,t){case"nervous":r.duration=500+500*Math.random(),r.intensity=2+Math.random(),r.nextTrigger=a+3e3+2e3*Math.random();break;case"confident":r.duration=1e3+1e3*Math.random(),r.intensity=.15,r.nextTrigger=a+4e3+2e3*Math.random();break;case"tired":r.duration=1e3+2e3*Math.random(),r.intensity=.2,r.nextTrigger=a+5e3+2e3*Math.random();break;case"intense":r.duration=500+500*Math.random(),r.intensity=.5,r.nextTrigger=a+3e3+3e3*Math.random();break;case"subdued":r.duration=2e3+1e3*Math.random(),r.intensity=.3,r.nextTrigger=a+4e3+3e3*Math.random()}if(r.active){const o=a-r.startTime;if(o<r.duration){const a=o/r.duration;switch(t){case"nervous":{const t=1-a,s=15,n=Math.sin(a*Math.PI*s)*t;e=n*r.intensity,i=n*r.intensity*.7;break}case"confident":{const t=Math.sin(a*Math.PI);s*=1+r.intensity*t,n*=1+.5*r.intensity*t;break}case"tired":{const t=Math.sin(a*Math.PI*.5);s*=1-r.intensity*t,i+=5*t;break}case"intense":{const t=1-Math.cos(a*Math.PI);s*=1-.05*t,n*=1+r.intensity*t;break}case"subdued":{const t=Math.sin(a*Math.PI*.5);s*=1-.1*t,n*=1-r.intensity*t;break}}}else r.active=!1}return{jitterX:e,jitterY:i,coreRadius:s,glowRadius:n}}reset(){Object.keys(this.episodicEffects).forEach(t=>{this.episodicEffects[t].active=!1,this.episodicEffects[t].startTime=0,this.episodicEffects[t].duration=0,this.episodicEffects[t].intensity=0})}getEpisodeState(t){return this.episodicEffects[t]||null}isEpisodeActive(t){const e=this.episodicEffects[t];return!!e&&e.active}}class Bn{constructor(t){this.renderer=t,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(t={}){return this.brakeToTarget(0,t)}brakeToNearest(t,e={}){const i=this.renderer.state.manualRotation||0,s=Math.round(i/t)*t;return this.brakeToTarget(s,e)}brakeToTarget(t,e={}){return new Promise(i=>{const{onProgress:s=null,onComplete:n=null}=e;this.onProgress=s,this.onComplete=n;const r=this.renderer.state.rotationSpeed||0,a=this.renderer.state.manualRotation||0;if(0===r||this.brakeStartTime)return void i();if(this.brakeStartTime=performance.now(),this.brakeStartRotation=a,this.brakeStartVelocity=r,0===t)this.brakeTargetRotation=r>0?360*(Math.floor(a/360)+1):360*Math.floor(a/360);else{const e=t%360,i=Math.floor(a/360);this.brakeTargetRotation=r>0?e>a%360?360*i+e:360*(i+1)+e:e<a%360?360*i+e:360*(i-1)+e}const o=Math.abs(this.brakeTargetRotation-this.brakeStartRotation);this.brakeDuration=Math.max(500,o/Math.abs(r)*this.DURATION_FACTOR*5),this.renderer.setRotationSpeed(0),this.resolvePromise=i})}updateBrake(t){if(!this.brakeStartTime)return null;const e=t-this.brakeStartTime,i=Math.min(e/this.brakeDuration,1),s=1-Math.pow(1-i,4),n=this.brakeStartRotation+(this.brakeTargetRotation-this.brakeStartRotation)*s,r=this.brakeStartVelocity*Math.pow(1-s,2);return this.onProgress&&this.onProgress(s,r,n),i>=1?(this.brakeStartTime=null,this.complete(),{rotation:this.brakeTargetRotation,speed:0,complete:!0}):{rotation:n,speed:r,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 t=performance.now()-this.brakeStartTime;return Math.min(t/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 An{constructor(t){this.renderer=t,this.rotationBrake=new Bn(t)}setRotationSpeed(t){this.renderer.state.rotationSpeed=t}setRotationAngle(t){this.renderer.state.manualRotation=t}getRotationAngle(){return this.renderer.state.manualRotation}getRotationSpeed(){return this.renderer.state.rotationSpeed}isBraking(){return this.rotationBrake&&this.rotationBrake.isBraking()}updateRotation(t){if(this.rotationBrake&&this.rotationBrake.isBraking()){const e=this.rotationBrake.updateBrake(t);e&&(this.renderer.state.manualRotation=e.rotation,this.renderer.state.rotationSpeed=e.complete?0:e.speed)}else 0!==this.renderer.state.rotationSpeed&&(this.renderer.state.manualRotation+=this.renderer.state.rotationSpeed);this.renderer.state.lastRotationUpdate=t}calculateTotalRotation(t=0,e=0){return(t+e+this.renderer.state.manualRotation)*Math.PI/180}applyRotation(t,e){0!==e&&t.rotate(e)}applyRotationTransform(t,e,i,s){this.updateRotation(performance.now());const n=this.calculateTotalRotation(s);return 0!==n&&(t.save(),t.translate(e,i),this.applyRotation(t,n),t.translate(-e,-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 Cn=class{constructor(t){this.renderer=t,this.canvas=t.canvas,this.initialized=!1,this.handleMouseMove=null,this.handleTouchMove=null}setEnabled(t){this.renderer.state.gazeTrackingEnabled=t,t?this.initialized||this.initialize():this.renderer.state.gazeTarget={x:0,y:0}}initialize(){this.initialized||(this.handleMouseMove=t=>{if(!this.renderer.state.gazeTrackingEnabled)return;const e=this.canvas.getBoundingClientRect(),i=e.width/2,s=e.height/2,n=t.clientX-e.left-i,r=t.clientY-e.top-s;this.renderer.state.gazeTarget={x:n/i,y:r/s}},this.handleTouchMove=t=>{if(this.renderer.state.gazeTrackingEnabled&&t.touches.length>0){const e=t.touches[0],i=this.canvas.getBoundingClientRect(),s=i.width/2,n=i.height/2,r=e.clientX-i.left-s,a=e.clientY-i.top-n;this.renderer.state.gazeTarget={x:r/s,y:a/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 Tn{constructor(t){this.renderer=t}setupCanvas(){this.renderer.updateOffscreenSize();const t=this.renderer.canvasManager.width||this.renderer.canvas.width||400,e=this.renderer.canvasManager.height||this.renderer.canvas.height||400,i=this.renderer.ctx;return this.renderer.ctx=this.renderer.offscreenCtx,{logicalWidth:t,logicalHeight:e,originalCtx:i}}renderBackdrop(t,e,i,s){const n=Math.min(t,e),r=this.renderer.getEffectiveCenter(),a=r.x,o=r.y-this.renderer.config.topOffset,h=n/this.renderer.config.referenceSize*this.renderer.config.baseScale*(r.coreScale||r.scale),l=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*h;this.renderer.backdropRenderer.update(s),this.renderer.audioAnalyzer&&this.renderer.audioAnalyzer.currentAmplitude&&this.renderer.backdropRenderer.setAudioIntensity(this.renderer.audioAnalyzer.currentAmplitude),this.renderer.backdropRenderer.render(a,o,l,i)}applyCanvasDecay(t,e,i){const s=this.renderer.particleSystem?this.renderer.particleSystem.particles.length:0,n=.12+Math.min(.08,.003*s);t.save(),t.globalCompositeOperation="destination-out",t.fillStyle=`rgba(0, 0, 0, ${n})`,t.fillRect(0,0,e,i),t.restore()}clearOffscreenCanvas(t,e){this.renderer.ctx.clearRect(0,0,t,e)}performCanvasSetup(t,e,i,s){this.renderBackdrop(t,e,i,s),this.applyCanvasDecay(i,t,e),this.clearOffscreenCanvas(t,e)}}class Pn{constructor(t){this.renderer=t}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 t=this.markFrameStart();return this.handleCleanRender(),t}}class Dn{constructor(t){this.renderer=t}mergeTransforms(t,e){const i=this.renderer.ambientDanceAnimator.getTransform(e);return t?(t.x=(t.x||0)+(i.x||0),t.y=(t.y||0)+(i.y||0),t.rotation=(t.rotation||0)+(i.rotation||0),t.scale=(t.scale||1)*(i.scale||1),t):i}mergeAndStoreTransforms(t,e){const i=this.mergeTransforms(t,e);return this.renderer.gestureTransform=i,i}}class Rn{constructor(t){this.renderer=t}updateUndertoneModifiers(){if(this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers){const t=this.renderer.stateMachine.getWeightedUndertoneModifiers();t?this.renderer.applyUndertoneModifiers(t):this.renderer.applyUndertoneModifiers(null)}}updateColorTransition(t){this.renderer.colorTransition&&this.renderer.colorTransition.active&&this.renderer.updateColorTransition(t)}updateAnimationTimers(t){this.renderer.updateTimers(t)}updateGazeOffset(){if(this.renderer.state.gazeTrackingEnabled){const t=.15,e=50;this.renderer.state.gazeOffset.x+=(this.renderer.state.gazeTarget.x*e-this.renderer.state.gazeOffset.x)*t,this.renderer.state.gazeOffset.y+=(this.renderer.state.gazeTarget.y*e-this.renderer.state.gazeOffset.y)*t}else{const t=.1;this.renderer.state.gazeOffset.x+=(0-this.renderer.state.gazeOffset.x)*t,this.renderer.state.gazeOffset.y+=(0-this.renderer.state.gazeOffset.y)*t}}performFrameStateUpdates(t){this.updateUndertoneModifiers(),this.updateColorTransition(t),this.updateAnimationTimers(t),this.updateGazeOffset()}}class Fn{constructor(t){this.renderer=t}calculateBaseDimensions(t,e){const i=Math.min(t,e),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(t,e,i){const s=t.x;let n=t.y-this.renderer.config.topOffset;return e.properties&&e.properties.verticalOffset&&(n=t.y-this.renderer.config.topOffset+i*e.properties.verticalOffset),{centerX:s,centerY:n}}applyGestureTransform(t,e,i){let s=1,n=0,r=1;return i&&(t+=i.x||0,e+=i.y||0,s=i.scale||1,n=(i.rotation||0)*Math.PI/180,r=i.glowIntensity||1),{centerX:t,centerY:e,scaleMultiplier:s,rotationAngle:n,glowMultiplier:r}}applyGestureAnimations(t,e,i,s,n){const r=this.renderer.gestureAnimator.applyGestureAnimations();return r&&(t+=r.offsetX||0,e+=r.offsetY||0,i*=r.scale||1,s+=(r.rotation||0)*Math.PI/180,n=r.glow||1),{centerX:t,centerY:e,scaleMultiplier:i,rotationAngle:s,glowMultiplier:n,gestureTransforms:r}}calculateRenderDimensions(t,e,i,s){const{canvasSize:n,effectiveCenter:r}=this.calculateBaseDimensions(t,e);let a,o,h,{centerX:l,centerY:c}=this.calculateCenterPosition(r,i,e);({centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h}=this.applyGestureTransform(l,c,s));const u=this.applyGestureAnimations(l,c,a,o,h);({centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h}=u);const{gestureTransforms:d}=u;return{canvasSize:n,effectiveCenter:r,centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h,gestureTransforms:d}}}var zn={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:t=>!0===t.recording,apply(t,e){const{deltaTime:i=16.67}=e;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(t,e,i){t.save();const s=Math.min(e,i),n=Math.floor(.08*s),r=1.5*n,a=1.5*n,o=.3*n;t.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),t.beginPath(),t.arc(r-n,a,o,0,2*Math.PI),t.fill(),t.strokeStyle=this.hexToRgba("#FFFFFF",.8*this.state.intensity),t.lineWidth=3,t.font=`bold ${n}px 'Arial', sans-serif`,t.textAlign="left",t.textBaseline="middle",t.strokeText("REC",r,a),t.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),t.fillText("REC",r,a),t.restore()},hexToRgba:(t,e)=>`rgba(${parseInt(t.slice(1,3),16)}, ${parseInt(t.slice(3,5),16)}, ${parseInt(t.slice(5,7),16)}, ${e})`,reset(){this.state.pulsePhase=0,this.state.intensity=0}},qn={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:t=>!0===t.speaking,apply(t,e){const{x:i,y:s,radius:n,audioLevel:r=0,deltaTime:a=16.67}=e;this.state.smoothedLevel+=(r-this.state.smoothedLevel)*this.config.smoothing,r>.5&&this.state.audioLevel<=.5&&this.state.rings.push({radius:n,opacity:.5,speed:2}),this.config.ringEffect&&this.drawRings(t,i,s,a),this.state.audioLevel=r},drawRings(t,e,i,s){t.save(),t.strokeStyle="rgba(100, 200, 255, 0.5)",t.lineWidth=2;for(let n=this.state.rings.length-1;n>=0;n--){const r=this.state.rings[n];r.radius+=r.speed*(s/16.67),r.opacity-=s/16.67*.02,r.opacity<=0?this.state.rings.splice(n,1):(t.globalAlpha=r.opacity,t.beginPath(),t.arc(e,i,r.radius,0,2*Math.PI),t.stroke())}t.restore()},getScaleModifier(){return 1+this.state.smoothedLevel*this.config.scaleMultiplier}},On={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:t=>!0===t.sleeping||"resting"===t.emotion,apply(t,e){const{x:i,y:s,radius:n,deltaTime:r=16.67}=e,a=Date.now();if(a-this.state.lastZSpawn>this.config.zParticleInterval){const t=[100,200,300,400,500,600,700,800,900],e=t[Math.floor(Math.random()*t.length)];this.state.zParticles.push({x:i+n,y:s-n,opacity:1,size:12+8*Math.random(),drift:.5*Math.random()-.25,weight:e,rotation:30*Math.random()-15}),this.state.lastZSpawn=a}this.drawZParticles(t,r)},drawZParticles(t,e){t.save(),t.textAlign="center",t.textBaseline="middle";for(let i=this.state.zParticles.length-1;i>=0;i--){const s=this.state.zParticles[i];s.y-=this.config.zDriftSpeed*(e/16.67),s.x+=s.drift*(e/16.67),s.opacity-=this.config.zFadeSpeed*(e/16.67),s.rotation+=e/16.67*.5,s.opacity<=0?this.state.zParticles.splice(i,1):(t.save(),t.translate(s.x,s.y),t.rotate(s.rotation*Math.PI/180),t.globalAlpha=.7*s.opacity,t.fillStyle="rgba(255, 255, 255, 0.9)",t.font=`${s.weight} ${s.size}px 'Poppins', sans-serif`,t.fillText("Z",0,0),t.shadowBlur=3,t.shadowColor="rgba(147, 112, 219, 0.5)",t.fillText("Z",0,0),t.restore())}t.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}}},jn={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:t=>"suspicion"===t.emotion||!0===t.suspicious,apply(t,e){const{deltaTime:i=16.67}=e,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(t){this.state.targetSquint=this.config.squintAmount;const e=this.state.targetSquint-this.state.currentSquint;Math.abs(e)>.01?this.state.currentSquint+=e*this.config.squintSpeed*(t/16.67):this.state.currentSquint=this.state.targetSquint},startScan(){this.state.scanning=!0,this.state.scanStartTime=Date.now(),this.state.scanPhase=-1},updateScan(t,e){const i=(t-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(t,e,i,s){if(!this.state.scanning)return;t.save(),t.strokeStyle="rgba(255, 165, 0, 0.3)",t.lineWidth=1,t.setLineDash([5,5]);const n=this.state.scanPhase*(this.config.scanAngle*Math.PI/180),r=e+Math.cos(n)*s*2,a=i+Math.sin(n)*s*.5;t.beginPath(),t.moveTo(e,i),t.lineTo(r,a),t.stroke(),t.restore()}},In={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:t=>t.gazeIntensity>0||t.gazeLocked,apply(t,e){const{gazeIntensity:i=0,deltaTime:s=16.67}=e;if(i>this.config.focusThreshold){const t=(i-this.config.focusThreshold)/(1-this.config.focusThreshold);this.state.targetScaleX=1+(this.config.maxHorizontalScale-1)*t,this.state.targetScaleY=1-(1-this.config.maxVerticalScale)*t}else this.state.targetScaleX=1,this.state.targetScaleY=1;this.animateScales(s)},animateScales(t){const e=this.config.smoothing*(t/16.67),i=this.state.targetScaleX-this.state.currentScaleX;Math.abs(i)>.001&&(this.state.currentScaleX+=i*e);const s=this.state.targetScaleY-this.state.currentScaleY;Math.abs(s)>.001&&(this.state.currentScaleY+=s*e)},getEyeScales(){return{scaleX:this.state.currentScaleX,scaleY:this.state.currentScaleY}},drawFocusIndicator(t,e,i,s,n){if(n<this.config.focusThreshold)return;t.save();const r=.5*(n-this.config.focusThreshold);t.strokeStyle=`rgba(100, 200, 255, ${r})`,t.lineWidth=1,t.setLineDash([2,4]);const a=[0,60,120,180,240,300];for(const n of a){const r=n*Math.PI/180,a=2*s,o=1.2*s;t.beginPath(),t.moveTo(e+Math.cos(r)*a,i+Math.sin(r)*a),t.lineTo(e+Math.cos(r)*o,i+Math.sin(r)*o),t.stroke()}t.restore()}},$n={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:t=>!0===t.biometric||!0===t.fingerprint||!0===t.authenticating,initialize(){this.state.breaks=[];for(let t=0;t<this.config.rings;t++){const t=[];for(let e=0;e<this.config.breakPoints;e++)t.push(Math.random()*Math.PI*2);this.state.breaks.push(t)}this.state.whorls=[{x:.2,y:-.1,strength:.3},{x:-.15,y:.2,strength:.25},{x:0,y:0,strength:.5}]},apply(t,e){const{x:i,y:s,radius:n,deltaTime:r=16.67,scanning:a=!1,authResult:o=null}=e;0===this.state.breaks.length&&this.initialize(),this.state.rotation+=this.config.rotationSpeed*(r/16.67),this.state.pulsePhase+=this.config.pulseSpeed*(r/16.67),(a||this.state.isScanning)&&(this.state.isScanning=!0,this.state.scanPosition+=this.config.scanLineSpeed*this.state.scanDirection*(r/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)),t.save(),this.drawFingerprintPattern(t,i,s,n),this.state.isScanning&&this.drawScanLine(t,i,s,n),o&&this.showAuthResult(t,i,s,n,o),t.restore()},drawFingerprintPattern(t,e,i,s){const n=.1*Math.sin(this.state.pulsePhase)+1;for(let r=0;r<this.config.rings;r++){const a=(r+1)*this.config.ringSpacing*n;if(!(a>2*s)){t.beginPath(),t.strokeStyle=this.config.color,t.lineWidth=this.config.lineWidth,t.globalAlpha=this.config.opacity*(1-r/this.config.rings*.5);for(let n=0;n<2*Math.PI;n+=.05){let o=!1;for(const t of this.state.breaks[r]||[])if(Math.abs(n-t)<.1){o=!0;break}if(o){t.stroke(),t.beginPath();continue}let h=a,l=n+this.state.rotation;for(const t of this.state.whorls){const n=e+t.x*s,r=i+t.y*s,a=e+Math.cos(l)*h,o=i+Math.sin(l)*h,c=Math.sqrt(Math.pow(a-n,2)+Math.pow(o-r,2));l+=Math.exp(-c/(.5*s))*t.strength*.5}h+=Math.sin(n*this.config.waveFrequency)*this.config.waveAmplitude;const c=e+Math.cos(l)*h,u=i+Math.sin(l)*h;0===n?t.moveTo(c,u):t.lineTo(c,u)}t.stroke()}}},drawScanLine(t,e,i,s){const n=i+this.state.scanPosition*s,r=t.createLinearGradient(e-s,n,e+s,n);r.addColorStop(0,"rgba(0, 255, 255, 0)"),r.addColorStop(.5,this.config.glowColor),r.addColorStop(1,"rgba(0, 255, 255, 0)"),t.strokeStyle=r,t.lineWidth=this.config.scanLineWidth,t.globalAlpha=.8,t.shadowBlur=10,t.shadowColor=this.config.glowColor,t.beginPath(),t.moveTo(e-s,n),t.lineTo(e+s,n),t.stroke(),t.shadowBlur=0},showAuthResult(t,e,i,s,n){const r="success"===n?this.config.successColor:this.config.failColor,a="success"===n?"โ AUTHENTICATED":"โ ACCESS DENIED";t.fillStyle=r,t.font=`bold ${.15*s}px monospace`,t.textAlign="center",t.textBaseline="middle",t.globalAlpha=.9,t.fillText(a,e,i+1.3*s),t.strokeStyle=r,t.lineWidth=3,t.globalAlpha=.5,t.beginPath(),t.arc(e,i,1.1*s,0,2*Math.PI),t.stroke()},startScan(){this.state.isScanning=!0,this.state.scanPosition=-1,this.state.scanDirection=1,this.state.scanResult=null},completeScan(t=!0){this.state.isScanning=!1,this.state.scanResult=t?"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 Ln=new Map;function Gn(t){t.name&&Ln.set(t.name,t)}function _n(t){return Ln.get(t)||null}function Hn(t,e,i){const s=_n(t);return!!s&&!!s.apply&&(s.apply(e,i),!0)}function Un(t,e){const i=_n(t);return!(!i||!i.shouldActivate)&&i.shouldActivate(e)}Gn(zn),Gn(qn),Gn(On),Gn(jn),Gn(In),Gn($n);class Wn{constructor(t){this.renderer=t}calculateSleepModifiers(){let t=1,e=1,i=1;if(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||Un("sleeping",this.renderer.state)){const s=_n("sleeping");if(s){const n=s.getDimmingValues();t=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:n.orbDimming,i=n.glowDimming,e=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9}else t=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:.3,i=.2,e=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9;this.renderer.state.breathRate=.5,this.renderer.state.breathDepth=.15}return{sleepOpacityMod:t,sleepScaleMod:e,glowOpacityMod:i}}calculateBreathingFactors(){let t,e;if(null!==this.renderer.state.customScale)t=this.renderer.state.customScale,e=1+.5*(this.renderer.state.customScale-1);else{const i=this.renderer.breathingAnimator.getBreathingScale();t=i,e=1-.5*(i-1)}return"nervous"===this.renderer.state.undertone&&this.renderer.undertoneModifiers.nervous.glowPulse&&(e*=1+Math.sin(Date.now()/200)*this.renderer.undertoneModifiers.nervous.glowPulse),{coreBreathFactor:t,glowBreathFactor:e}}calculateRadii(t,e,i){const{sleepOpacityMod:s,sleepScaleMod:n,glowOpacityMod:r}=this.calculateSleepModifiers(),{coreBreathFactor:a,glowBreathFactor:o}=this.calculateBreathingFactors(),h=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*this.renderer.scaleFactor,l=t.properties&&t.properties.coreSize?t.properties.coreSize:1,c=this.renderer.state.sizeMultiplier||1;return{coreRadius:h*l*a*e*n*c,glowRadius:h*this.renderer.config.glowMultiplier*o*this.renderer.state.glowIntensity*e*n*c*i,effectiveGlowIntensity:this.renderer.state.glowIntensity*i,sleepOpacityMod:s,glowOpacityMod:r}}}class Yn{constructor(t){this.renderer=t}applyBlinkSquish(t){return this.renderer.state.sleeping||(t*=this.renderer.eyeRenderer.getBlinkScale()),t}calculateJitter(t,e){let i=0,s=0;const n=this.renderer.state.jitterAmount||0;if(this.renderer.currentUndertone)({jitterX:i,jitterY:s,coreRadius:t,glowRadius:e}=this.renderer.episodicEffectController.updateEpisodicEffects(this.renderer.currentUndertone,i,s,t,e));else if(this.renderer.state.coreJitter||n>0){const t=Math.max(n,this.renderer.state.coreJitter?this.renderer.scaleValue(2):0);i=(Math.random()-.5)*t,s=(Math.random()-.5)*t}return{jitterX:i,jitterY:s,coreRadius:t,glowRadius:e}}calculateFinalPosition(t,e,i,s){return{coreX:t+this.renderer.state.gazeOffset.x+i,coreY:e+this.renderer.state.gazeOffset.y+s}}applyAllModifications(t,e,i,s,n){let r,a;s=this.applyBlinkSquish(s),({jitterX:r,jitterY:a,coreRadius:s,glowRadius:n}=this.calculateJitter(s,n));const{coreX:o,coreY:h}=this.calculateFinalPosition(t,e,r,a);return{coreX:o,coreY:h,rotationAngle:i,coreRadius:s,glowRadius:n}}}class Xn{constructor(t){this.renderer=t}renderGlow(t,e,i,s,n,r){Un("recording-glow",this.renderer.state)?Hn("recording-glow",this.renderer.ctx,{x:t,y:e,radius:i,deltaTime:r}):this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||Un("sleeping",this.renderer.state)?(this.renderer.ctx.save(),this.renderer.ctx.globalAlpha=n,this.renderer.glowRenderer.renderGlow(t,e,i,{intensity:s}),this.renderer.ctx.restore()):this.renderer.glowRenderer.renderGlow(t,e,i,{intensity:s})}renderFlashWave(t,e,i,s){if(t&&t.flashWave){const n=t.flashWave,{ctx:r}=this.renderer;r.save(),r.globalCompositeOperation="lighter";const a=s*n.innerRadius,o=s*n.outerRadius;if(o>a){const t=vn.getRadialGradient(r,e,i,a,e,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)"}]);r.fillStyle=t,r.beginPath(),r.arc(e,i,o,0,2*Math.PI),r.arc(e,i,Math.max(0,a),0,2*Math.PI,!0),r.fill()}r.restore()}}renderSpeakingPulse(t,e,i,s){Un("speaking-pulse",this.renderer.state)&&Hn("speaking-pulse",this.renderer.ctx,{x:t,y:e,radius:i,audioLevel:this.renderer.state.audioLevel||0,deltaTime:s})}renderAllEffects(t){const{coreX:e,coreY:i,glowRadius:s,effectiveGlowIntensity:n,glowOpacityMod:r,gestureTransforms:a,coreRadius:o,deltaTime:h}=t;this.renderGlow(e,i,s,n,r,h),this.renderFlashWave(a,e,i,o),this.renderSpeakingPulse(e,i,o,h)}}class Vn{constructor(t){this.renderer=t}applySleepOpacity(t){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=t)}updateShapeMorpher(t){let e=null,i=null;return this.renderer.shapeMorpher&&(this.renderer.shapeMorpher.update(),e=this.renderer.shapeMorpher.getCanvasPoints(0,0,t),i=this.renderer.shapeMorpher.getCurrentShadow()),{shapePoints:e,currentShadow:i}}renderSunEffects(t,e,i,s){let n=!1;return!s||"sun"!==s.type&&"solar-hybrid"!==s.type||(this.renderer.renderSunEffects(t,e,i,s),n=!0),n}renderCore(t,e,i,s,n){this.renderer.coreRenderer.renderCore(t,e,i,{scaleX:1,scaleY:1,rotation:s,shapePoints:n})}renderSparkles(t){this.renderer.specialEffects&&(this.renderer.specialEffects.update(t),this.renderer.specialEffects.renderSparkles())}renderShadowEffects(t,e,i,s,n,r){const a=this.renderer.shapeMorpher?this.renderer.shapeMorpher.currentShape:null,o=this.renderer.shapeMorpher?this.renderer.shapeMorpher.targetShape:null,h=this.renderer.shapeMorpher&&"solar"===o&&this.renderer.shapeMorpher.isTransitioning,l=this.renderer.shapeMorpher&&"solar"===a&&this.renderer.shapeMorpher.isTransitioning,c=s&&"solar-hybrid"===s.type,u=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"solar"===a&&"moon"===o,d=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"moon"===a&&"solar"===o;if(!s||"crescent"!==s.type&&"lunar"!==s.type||d||this.renderer.renderMoonShadow(t,e,i,s,n,!1,0),(c&&s.lunarOverlay||h||l)&&!u){const a=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 t=2.5*i;h&&d<1?(o=-t*(1-d),u=t*(1-d)):l&&d<1&&(o=t*d,u=-t*d)}if(this.renderer.renderMoonShadow(t,e,i,a,n,!0),(h||l)&&(h||r)&&(this.renderer.renderBaileysBeads(t,e,i,o,u,d,h,!0),Math.abs(o)<30&&Math.abs(u)<30&&this.renderer.specialEffects)){const t=Math.sqrt(o*o+u*u),e=Math.max(.1,.5*(1-t/30));this.renderer.specialEffects.triggerChromaticAberration(e)}}}cleanup(t){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=1),0!==t&&this.renderer.ctx.restore()}renderCoreAndShapes(t){const{coreX:e,coreY:i,coreRadius:s,totalRotation:n,sleepOpacityMod:r,deltaTime:a}=t;this.applySleepOpacity(r);const{shapePoints:o,currentShadow:h}=this.updateShapeMorpher(s),l=this.renderSunEffects(e,i,s,h);this.renderCore(e,i,s,n,o),this.renderSparkles(a),this.renderShadowEffects(e,i,s,h,o,l),this.cleanup(n)}}class Nn{constructor(t){this.renderer=t}renderSleepIndicator(t,e,i,s){this.renderer.state.sleeping&&this.renderer.renderSleepIndicator(t,e-i-this.renderer.scaleValue(20),s)}finalizeCanvas(t,e,i){this.renderer.ctx=t,t.drawImage(this.renderer.offscreenCanvas,0,0,e,i)}drawRecordingIndicator(t){if(Un("recording-glow",this.renderer.state)){const e=_n("recording-glow");e&&e.drawRecordingIndicator&&e.drawRecordingIndicator(t,this.renderer.canvas.width,this.renderer.canvas.height)}}finalizePerformanceMetrics(t){const e=performance.now()-t;this.renderer.performanceMonitor&&(this.renderer.performanceMonitor.markFrameEnd(),this.renderer.performanceMonitor.recordFrameTime(e))}finalizeRender(t){const{centerX:e,centerY:i,glowRadius:s,deltaTime:n,originalCtx:r,logicalWidth:a,logicalHeight:o,frameStartTime:h}=t;this.renderSleepIndicator(e,i,s,n),this.finalizeCanvas(r,a,o),this.drawRecordingIndicator(r),this.finalizePerformanceMetrics(h)}}class Qn{constructor(t){this.renderer=t,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(t,e={}){this.activeAnimation&&this.activeAnimation!==t&&this.stopAmbientAnimation(this.activeAnimation),this.activeAnimation=t,this.animations[t]={startTime:Date.now(),intensity:e.intensity||1,frequency:e.frequency||1,options:e}}stopAmbientAnimation(t){this.animations[t]&&(this.animations[t]=null),this.activeAnimation===t&&(this.activeAnimation=null)}updateBlendState(t){if(!t)return;const e=.2;this.blendState.x=this.lerp(this.blendState.x,t.x||0,e),this.blendState.y=this.lerp(this.blendState.y,t.y||0,e),this.blendState.rotation=this.lerp(this.blendState.rotation,t.rotation||0,e),this.blendState.scale=this.lerp(this.blendState.scale,t.scale||1,e),this.blendState.opacity=this.lerp(this.blendState.opacity,t.opacity||1,e)}getTransform(t){const e={x:this.blendState.x,y:this.blendState.y,rotation:this.blendState.rotation,scale:this.blendState.scale,opacity:this.blendState.opacity};if(this.activeAnimation){const t=this.animations[this.activeAnimation];if(t){const i=Date.now()-t.startTime;switch(this.activeAnimation){case"grooveSway":e.x+=15*Math.sin(i/500*t.frequency)*t.intensity,e.rotation+=5*Math.sin(i/500*t.frequency+Math.PI/4)*t.intensity;break;case"grooveBob":e.y+=10*Math.sin(i/400*t.frequency)*t.intensity,e.scale*=1+.03*Math.sin(i/400*t.frequency)*t.intensity;break;case"grooveFlow":{const s=i/1e3*t.frequency;e.x+=Math.sin(s)*Math.cos(2*s)*20*t.intensity,e.y+=Math.cos(s)*Math.sin(2*s)*10*t.intensity,e.rotation+=8*Math.sin(2*s)*t.intensity;break}case"groovePulse":e.scale*=1+.05*Math.sin(i/250*t.frequency)*t.intensity,e.opacity*=.9+.1*Math.sin(i/250*t.frequency)*t.intensity;break;case"grooveStep":{const s=Math.floor(i/500*t.frequency)%4,n=i/500*t.frequency%1,r=this.smoothStep(n);0===s?e.x+=25*r*t.intensity:2===s&&(e.x-=25*r*t.intensity),e.y+=5*Math.abs(Math.sin(i/250*t.frequency))*t.intensity;break}}}}return e}lerp(t,e,i){return t+(e-t)*i}smoothStep(t){return t*t*(3-2*t)}}class Jn{constructor(t){this.renderer=t,this.ctx=t.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(t={}){this.config={...this.config,...t},void 0!==t.enabled&&(this.targetIntensity=t.enabled?this.config.intensity:0)}update(t){this.config.enabled?(this.currentIntensity+=.1*(this.targetIntensity-this.currentIntensity),this.config.responsive&&(this.pulsePhase+=.001*t)):this.currentIntensity*=.95}setAudioIntensity(t){if(!this.config.responsive)return;const e=.2*t;this.targetIntensity=Math.min(1,this.config.intensity+e)}render(t,e,i,s=null){if(this.currentIntensity<.01)return;const n=s||this.ctx;switch(n.save(),this.config.type){case"radial-gradient":this.renderRadialGradient(t,e,i,n);break;case"vignette":this.renderVignette(t,e,i,n);break;case"glow":this.renderGlow(t,e,i,n)}n.restore()}renderRadialGradient(t,e,i,s){s=s||this.ctx;const n=i*this.config.radius,r=t+(this.config.offset.x||0),a=e+(this.config.offset.y||0);let o=n;(this.config.pulse||this.config.responsive)&&(o*=1+.05*Math.sin(this.pulsePhase));const h=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 l=s.createRadialGradient(r,a,0,r,a,o),c=this.config.color,u=this.currentIntensity;this.addGradientStopsSimple(l,c,u),s.fillStyle=l,s.beginPath(),s.arc(r,a,o,0,2*Math.PI),s.fill(),this.config.blur>0&&(s.filter="none"),this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=h)}renderVignette(t,e,i,s){s=s||this.ctx;const{canvas:n}=s,r=Math.max(n.width,n.height),a=s.createRadialGradient(t,e,.5*i,t,e,r);a.addColorStop(0,"rgba(0, 0, 0, 0)"),a.addColorStop(1,this.adjustColorAlpha(this.config.color,this.currentIntensity)),s.fillStyle=a,s.fillRect(0,0,n.width,n.height)}renderGlow(t,e,i,s){s=s||this.ctx;const n=i*this.config.radius;for(let i=0;i<3;i++){const r=n*(1-.2*i),a=this.currentIntensity*(.3-.1*i),o=s.createRadialGradient(t,e,0,t,e,r);o.addColorStop(0,this.adjustColorAlpha(this.config.color,a)),o.addColorStop(1,"rgba(0, 0, 0, 0)"),s.fillStyle=o,s.beginPath(),s.arc(t,e,r,0,2*Math.PI),s.fill()}}addGradientStopsSimple(t,e,i){const{coreTransparency:s}=this.config;t.addColorStop(0,this.adjustColorAlpha(e,i)),t.addColorStop(s,this.adjustColorAlpha(e,i));for(let n=1;n<=25;n++){const r=s+n/25*(1-s),a=(r-s)/(1-s),o=1-this.easeInOutCubic(a);t.addColorStop(r,this.adjustColorAlpha(e,i*o))}t.addColorStop(1,"rgba(0, 0, 0, 0)")}addGradientStops(t,e,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})=>{t.addColorStop(s,this.adjustColorAlpha(e,i*n))});else switch(this.config.falloff){case"linear":t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n,"rgba(0, 0, 0, 0)"),t.addColorStop(1,this.adjustColorAlpha(e,i));break;case"exponential":t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n,"rgba(0, 0, 0, 0)"),t.addColorStop(n+.3*(1-n),this.adjustColorAlpha(e,.05*i)),t.addColorStop(n+.5*(1-n),this.adjustColorAlpha(e,.15*i)),t.addColorStop(n+.7*(1-n),this.adjustColorAlpha(e,.4*i)),t.addColorStop(n+.85*(1-n),this.adjustColorAlpha(e,.7*i)),t.addColorStop(1,this.adjustColorAlpha(e,i));break;default:{t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n*s,"rgba(0, 0, 0, 0)");const{edgeSoftness:r}=this.config,a=s,o=n*s+(a-n*s)*r,h=25;for(let r=1;r<=h;r++){const l=r/h;let c=0;if(l<=n*s)c=0;else if(l<=a)if(l<=o){const t=(l-n*s)/(o-n*s);c=this.easeInOutCubic(t)}else{const t=(l-o)/(a-o);c=1-.05*(1-this.easeInOutCubic(t))}else{const t=(l-a)/(1-a);c=1-this.easeInOutCubic(t)}t.addColorStop(l,this.adjustColorAlpha(e,i*c))}t.addColorStop(1,"rgba(0, 0, 0, 0)");break}}}easeInOutCubic(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}adjustColorAlpha(t,e){const i=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(i){const[,t,s,n,r=1]=i;return`rgba(${t}, ${s}, ${n}, ${parseFloat(r)*e})`}return`rgba(0, 0, 0, ${.6*e})`}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 Kn=2,Zn=3,tr=4,er=new class{constructor(){this.callbacks=new Map,this.callbackIdCounter=0,this.wt=new Map,this.vt=!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={[Kn]:0,[Zn]:0,[tr]:0},this.performanceMonitor=null,this.frameTimeHistory=new Array(60).fill(0),this.St=0,this.kt=0,this.maxHistorySize=60,this.loop=this.loop.bind(this)}register(t,e=2,i=null){if("function"!=typeof t)throw new Error("Callback must be a function");const s=++this.callbackIdCounter;return this.callbacks.set(s,{callback:t,priority:e,context:i,lastRun:0,runCount:0,totalTime:0,enabled:!0}),this.vt=!0,1!==this.callbacks.size||this.isRunning||this.start(),s}unregister(t){this.callbacks.delete(t),this.vt=!0,0===this.callbacks.size&&this.isRunning&&this.stop()}setEnabled(t,e){const i=this.callbacks.get(t);i&&(i.enabled=e)}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(t){if(!this.isRunning)return;this.deltaTime=t-this.lastFrameTime,this.lastFrameTime=t,this.frameCount++,this.frameCount%60==0&&(this.fps=Math.round(1e3/(this.deltaTime||16.67))),this.frameTimeHistory[this.St]=this.deltaTime,this.St=(this.St+1)%this.maxHistorySize,this.kt<this.maxHistorySize&&this.kt++,this.vt&&this.xt();const e=this.wt;let i=0;for(const s of[0,1,2,3,4]){if(s>0&&i>.8*this.frameBudget)break;if(this.shouldSkipPriority(s))continue;const n=e.get(s)||[];for(const e of n){if(!e.enabled)continue;const s=performance.now();try{e.context?e.callback.call(e.context,this.deltaTime,t):e.callback(this.deltaTime,t);const n=performance.now()-s;e.totalTime+=n,e.runCount++,e.lastRun=t,i+=n}catch(t){e.runCount>0&&e.totalTime/e.runCount>10&&(e.enabled=!1)}if(i>this.frameBudget)break}}this.frameId=requestAnimationFrame(this.loop)}xt(){this.wt.clear();for(const[,t]of this.callbacks){const{priority:e}=t;this.wt.has(e)||this.wt.set(e,[]),this.wt.get(e).push(t)}this.vt=!1}shouldSkipPriority(t){if(0===t)return!1;if(this.fps<30&&t>=3)return!0;if(this.fps<45&&4===t)return!0;if(2===t){if(this.fps<50&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%2!=0))return!0}else if(3===t){if(this.fps<50&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%3!=0))return!0}else if(4===t&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%5!=0))return!0;return!1}getStats(){const t={fps:this.fps,frameCount:this.frameCount,callbackCount:this.callbacks.size,averageFrameTime:0,maxFrameTime:0,minFrameTime:1/0};if(this.kt>0){let e=0;for(let i=0;i<this.kt;i++){const s=this.frameTimeHistory[i];e+=s,t.maxFrameTime=Math.max(t.maxFrameTime,s),t.minFrameTime=Math.min(t.minFrameTime,s)}t.averageFrameTime=e/this.kt}t.callbacksByPriority={};for(const[,e]of this.callbacks){const{priority:i}=e;t.callbacksByPriority[i]||(t.callbacksByPriority[i]={count:0,totalTime:0,enabled:0}),t.callbacksByPriority[i].count++,t.callbacksByPriority[i].totalTime+=e.totalTime,e.enabled&&t.callbacksByPriority[i].enabled++}return t}setTargetFPS(t){this.targetFPS=Math.max(15,Math.min(120,t)),this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=this.targetFrameTime}setPerformanceMonitor(t){this.performanceMonitor=t}destroy(){this.stop(),this.callbacks.clear(),this.wt.clear(),this.vt=!0,this.frameTimeHistory.fill(0),this.St=0,this.kt=0}};class ir{constructor(t){this.renderer=t,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&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null);const t=performance.now(),e=2e3;this.loopCallbackIds.eyeClose=er.register(()=>{if(!this.renderer.state.sleeping)return void(this.loopCallbackIds.eyeClose=null);const i=performance.now()-t;if(i<e){const t=i/e,s=1-Math.pow(t,2);this.renderer.state.eyeOpenness=.1+.9*s,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1}else if(i<3e3){const t=(i-e)/1e3,s=1-Math.pow(1-t,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},1,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&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.loopCallbackIds.eyeClose&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null);const t=performance.now();this.loopCallbackIds.eyeOpen=er.register(()=>{const e=performance.now()-t;if(e<500){const t=e/500,i=Math.sin(t*Math.PI/2);this.renderer.state.sleepDimness=.6+.4*i,this.renderer.state.sleepScale=.9+.1*i,this.renderer.state.eyeOpenness=.1}else if(e<1500){const t=(e-500)/1e3,i=Math.sin(t*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},1,this.renderer)}renderSleepIndicator(t,e,i){return this.renderer.specialEffects.renderSleepIndicator(t,e,i)}cleanup(){this.loopCallbackIds.eyeClose&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.wakeJitterTimeout&&(clearTimeout(this.wakeJitterTimeout),this.wakeJitterTimeout=null)}}class sr{constructor(t){this.renderer=t}applyUndertoneModifiers(t){if(t&&"object"==typeof t&&void 0!==t.weight){const{weight:e}=t;return this.renderer.state.sizeMultiplier=1+((t.sizeMultiplier||1)-1)*e,this.renderer.state.jitterAmount=(t.jitterAmount||0)*e,this.renderer.state.episodicFlutter=e>.5&&t.episodicFlutter||!1,this.renderer.state.glowRadiusMult=1+((t.glowRadiusMult||1)-1)*e,this.renderer.state.breathRateMult=1+((t.breathRateMult||1)-1)*e,this.renderer.state.breathDepthMult=1+((t.breathDepthMult||1)-1)*e,this.renderer.state.breathIrregular=e>.5&&t.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=(t.glowPulse||0)*e,this.renderer.state.brightnessFlicker=(t.brightnessFlicker||0)*e,this.renderer.state.brightnessMult=1+((t.brightnessMult||1)-1)*e,this.renderer.state.saturationMult=1+((t.saturationMult||1)-1)*e,void(this.renderer.state.hueShift=(t.hueShift||0)*e)}if(!t||!this.renderer.undertoneModifiers[t])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 e=this.renderer.undertoneModifiers[t];this.renderer.state.sizeMultiplier=e.sizeMultiplier,this.renderer.state.jitterAmount=e.jitterAmount||0,this.renderer.state.episodicFlutter=e.episodicFlutter||!1,this.renderer.state.glowRadiusMult=e.glowRadiusMult,this.renderer.state.breathRateMult=e.breathRateMult,this.renderer.state.breathDepthMult=e.breathDepthMult,this.renderer.state.breathIrregular=e.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=e.glowPulse||0,this.renderer.state.brightnessFlicker=e.brightnessFlicker||0,this.renderer.state.brightnessMult=e.brightnessMult||1,this.renderer.state.saturationMult=e.saturationMult||1,this.renderer.state.hueShift=e.hueShift||0}updateUndertone(t){this.renderer.state.undertone!==t&&this.renderer.glowCache&&this.renderer.glowCache.clear(),this.renderer.state.undertone=t,this.renderer.currentUndertone=t;const e=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;if(this.applyUndertoneModifiers(e||t),this.renderer.state.emotion){const i=Us&&Us.isInitialized?Us.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,e||t);this.renderer.startColorTransition(n,200)}}}setEmotionalState(t,e,i=null){this.renderer.state.emotion===t&&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=e.glowColor||this.renderer.config.defaultGlowColor;let r;r="suspicion"===t?e.glowColor||n:this.renderer.applyUndertoneToColor(n,s||i);const a=s||(i?this.renderer.undertoneModifiers[i]:null),o=e.glowIntensity||1;let h=1;if(a)if(s){const t=a.weight||0;h=void 0!==a.glowRadiusMult&&isFinite(a.glowRadiusMult)&&isFinite(t)?1+(a.glowRadiusMult-1)*t:1}else h=void 0!==a.glowRadiusMult?a.glowRadiusMult:1;const l=o*h;let c=1500;"anger"===t||"fear"===t?c=800:"sadness"!==t&&"resting"!==t||(c=2e3),this.renderer.state.emotion=t,"suspicion"===t?(this.renderer.state.isSuspicious=!0,this.renderer.state.targetSquintAmount=e&&e.coreSquint?e.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(r,l,c);const u=e.breathRate||1,d=e.breathDepth||this.renderer.config.breathingDepth;this.renderer.state.breathRate=a?u*a.breathRateMult:u,this.renderer.state.breathDepth=a?d*a.breathDepthMult:d,this.renderer.state.coreJitter=e.coreJitter||a&&a.jitterAmount>0,this.renderer.state.emotionEyeOpenness=e.eyeOpenness,this.renderer.state.emotionEyeArc=e.eyeArc}}class nr{constructor(t){this.renderer=t}resetCanvasContext(){if(!this.renderer.canvas||!this.renderer.ctx)return;const{width:t}=this.renderer.canvas,{height:e}=this.renderer.canvas;this.resetContext(this.renderer.ctx,t,e),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(t,e,i){t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.clearRect(0,0,e,i)}setQualityLevel(t){this.renderer.qualityLevel=Math.max(0,Math.min(1,t)),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(t){t?this.setQualityLevel(.5):this.setQualityLevel(1)}handleContextRecovery(t){this.renderer.ctx=t}}class rr{constructor(t){this.renderer=t}destroy(){this.cancelAnimationFrames(),this.unregisterLoopCallbacks(),this.cleanupManagers(),this.clearTimeouts(),this.clearAnimationStates(),this.clearOtherResources()}cancelAnimationFrames(){for(const t in this.renderer.animationFrameIds)this.renderer.animationFrameIds[t]&&(cancelAnimationFrame(this.renderer.animationFrameIds[t]),this.renderer.animationFrameIds[t]=null)}unregisterLoopCallbacks(){for(const t in this.renderer.loopCallbackIds)this.renderer.loopCallbackIds[t]&&(er.unregister(this.renderer.loopCallbackIds[t]),this.renderer.loopCallbackIds[t]=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 ar{constructor(t){this.renderer=t}updateTimers(t){this.updateBreathing(t),this.updateBlinking(t)}updateBreathing(t){this.renderer.breathingAnimator.update(t,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(t){const e=this.renderer.state.blinkingEnabled&&!this.renderer.state.sleeping;this.renderer.eyeRenderer.setBlinkingEnabled(e),this.renderer.eyeRenderer.update(t),this.renderer.state.blinking=this.renderer.eyeRenderer.blinking}}class or{constructor(t){this.renderer=t}setGazeOffset(t){this.processGazeData(t),this.handleGazeInteraction()}processGazeData(t){"object"==typeof t&&null!==t&&(this.isOldFormat(t)?this.renderer.state.gazeOffset=t:this.applyNewFormatData(t))}isOldFormat(t){return{}.hasOwnProperty.call(t,"x")&&{}.hasOwnProperty.call(t,"y")}applyNewFormatData(t){this.renderer.state.gazeOffset=t.offset||{x:0,y:0},this.renderer.state.gazeIntensity=t.proximity||0,this.renderer.state.gazeLocked=t.isLocked||!1}handleGazeInteraction(){this.renderer.idleTimer=0,this.renderer.isAsleep&&this.renderer.wakeUp()}getCurrentOrbPosition(){const t=this.renderer.canvasManager.width/2,e=this.renderer.canvasManager.height/2-this.renderer.config.topOffset;return{x:t+this.renderer.state.gazeOffset.x,y:e+this.renderer.state.gazeOffset.y}}}class hr{constructor(t,e={}){this.canvasManager=t,this.ctx=t.getContext(),this.ctx||(this.T=!0),this.gestureCompositor=new an,this.currentUndertone=null,this.gestureAnimator=new fn(this),this.colorUtilities=new yn,this.specialEffects=new Mn(this),this.eyeRenderer=new bn(this),this.breathingAnimator=new wn(this),this.glowRenderer=new Sn(this),this.coreRenderer=new kn(this),this.celestialRenderer=new xn,this.episodicEffectController=new En(this),this.rotationManager=new An(this),this.gazeTracker=new Cn(this),this.canvasSetupManager=new Tn(this),this.renderPerformanceManager=new Pn(this),this.transformMerger=new Dn(this),this.stateUpdateManager=new Rn(this),this.dimensionCalculator=new Fn(this),this.radiusCalculator=new Wn(this),this.positionJitterManager=new Yn(this),this.effectsRenderManager=new Xn(this),this.coreShapeRenderManager=new Vn(this),this.renderFinalizationManager=new Nn(this),this.ambientDanceAnimator=new Qn(this),this.backdropRenderer=new Jn(this),this.sleepManager=new ir(this),this.emotionalStateManager=new sr(this),this.canvasContextManager=new nr(this),this.resourceCleanupManager=new rr(this),this.timerCoordinator=new ar(this),this.gazeInputHandler=new or(this),this.config={coreColor:e.coreColor||"#FFFFFF",coreSizeDivisor:e.coreSizeDivisor||12,glowMultiplier:e.glowMultiplier||2.5,defaultGlowColor:e.defaultGlowColor||"#14B8A6",breathingSpeed:e.breathingSpeed||.42,breathingDepth:e.breathingDepth||.08,renderingStyle:e.renderingStyle||"classic",baseScale:e.baseScale||1,referenceSize:400,topOffset:e.topOffset||0,positionController:e.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=t.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.Et()}scaleValue(t){return t*this.scaleFactor}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),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:t}=this.canvasManager.canvas,{height:e}=this.canvasManager.canvas;if(this.offscreenCanvas.width!==t||this.offscreenCanvas.height!==e){this.offscreenCanvas.width=t,this.offscreenCanvas.height=e;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(t){this.state.effectiveCenter=t}getEffectiveCenter(){const t=this.canvasManager.getCenter();let e;return e=this.config.positionController?this.config.positionController.getEffectiveCenter(t.x,t.y):{x:t.x,y:t.y,scale:1},e.x+=this.state.gazeOffset.x,e.y+=this.state.gazeOffset.y,e}render(t,e,i=null){if(this.T)return;const s=this.renderPerformanceManager.initializeFrame();i=this.transformMerger.mergeAndStoreTransforms(i,e);const{logicalWidth:n,logicalHeight:r,originalCtx:a}=this.canvasSetupManager.setupCanvas();this.canvasSetupManager.performCanvasSetup(n,r,a,e),this.stateUpdateManager.performFrameStateUpdates(e);const o=this.dimensionCalculator.calculateRenderDimensions(n,r,t,i),{scaleMultiplier:h,glowMultiplier:l,gestureTransforms:c,centerX:u,centerY:d}=o;let{rotationAngle:p}=o;const m=this.radiusCalculator.calculateRadii(t,h,l);let{coreRadius:g,glowRadius:f}=m;const{effectiveGlowIntensity:y,sleepOpacityMod:M,glowOpacityMod:b}=m,w=this.positionJitterManager.applyAllModifications(u,d,p,g,f),{coreX:v,coreY:S}=w;({rotationAngle:p,coreRadius:g,glowRadius:f}=w);const k=this.rotationManager.applyRotationTransform(this.ctx,v,S,p);this.effectsRenderManager.renderAllEffects({coreX:v,coreY:S,glowRadius:f,effectiveGlowIntensity:y,glowOpacityMod:b,gestureTransforms:c,coreRadius:g,deltaTime:e}),this.coreShapeRenderManager.renderCoreAndShapes({coreX:v,coreY:S,coreRadius:g,totalRotation:k,sleepOpacityMod:M,deltaTime:e}),this.renderFinalizationManager.finalizeRender({centerX:u,centerY:d,glowRadius:f,deltaTime:e,originalCtx:a,logicalWidth:n,logicalHeight:r,frameStartTime:s})}renderRecordingGlow(t,e,i,s){const n=this.canvas?.width||600,r=this.canvas?.height||600,a=Math.min(i,t-10,e-10,n-t-10,r-e-10),o=Math.max(50,a),h=vn.getRadialGradient(this.ctx,t,e,0,t,e,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=h,this.ctx.beginPath(),this.ctx.arc(t,e,o,0,2*Math.PI),this.ctx.fill()}renderDropShadow(t,e,i,s){const{ctx:n}=this,r=this.shapeMorpher&&this.shapeMorpher.isTransitioning;if(!(this.shapeMorpher&&(this.shapeMorpher.audioDeformation>.1||this.shapeMorpher.vocalEnergy>.1)||r&&!(this.shapeMorpher.morphProgress>.8))){n.save(),n.translate(t,e);const r=this.scaleValue(2);if(n.translate(0,r),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 t=n.createRadialGradient(0,0,.7*i,0,0,1.2*i);if(t.addColorStop(0,"rgba(0, 0, 0, 0.2)"),t.addColorStop(.8,"rgba(0, 0, 0, 0.1)"),t.addColorStop(1,"rgba(0, 0, 0, 0)"),n.fillStyle=t,n.beginPath(),s){const t=1.1,e=s.length>20?2:1;n.moveTo(s[0].x*t,s[0].y*t);for(let i=e;i<s.length;i+=e)n.lineTo(s[i].x*t,s[i].y*t);n.closePath()}else n.arc(0,0,1.1*i,0,2*Math.PI);n.fill()}n.restore()}}renderSunEffects(t,e,i,s){return this.celestialRenderer.renderSunEffects(this.ctx,t,e,i,s)}renderBaileysBeads(t,e,i,s,n,r,a,o){return this.celestialRenderer.renderBaileysBeads(this.ctx,t,e,i,s,n,r,a,o,this.scaleValue.bind(this))}renderMoonShadow(t,e,i,s,n,r=!1,a=0){return this.celestialRenderer.renderMoonShadow(this.ctx,t,e,i,s,n,r,a,this.shapeMorpher)}renderSpeakingRings(t,e,i,s){return this.specialEffects.renderSpeakingRings(t,e,i,s)}renderRecordingIndicator(t,e){return this.specialEffects.renderRecordingIndicator(t,e)}renderSleepIndicator(t,e,i){return this.sleepManager.renderSleepIndicator(t,e,i)}updateTimers(t){this.timerCoordinator.updateTimers(t)}applyUndertoneModifiers(t){this.emotionalStateManager.applyUndertoneModifiers(t)}applyUndertoneToColor(t,e){return this.colorUtilities.applyUndertoneToColor(t,e)}hexToRgb(t){return this.colorUtilities.hexToRgb(t)}rgbToHsl(t,e,i){return this.colorUtilities.rgbToHsl(t,e,i)}hslToHex(t,e,i){return this.colorUtilities.hslToHex(t,e,i)}hexToRgba(t,e=1){const i=this.hexToRgb(t);return i?`rgba(${i.r}, ${i.g}, ${i.b}, ${e})`:`rgba(255, 255, 255, ${e})`}startColorTransition(t,e,i=1500){this.colorUtilities.currentColor=this.state.glowColor,this.colorUtilities.currentIntensity=this.state.glowIntensity,this.colorUtilities.startColorTransition(t,e,i),this.colorTransition=this.colorUtilities.colorTransition}updateColorTransition(t){const e=this.colorUtilities.updateColorTransition(t);e&&(this.state.glowColor=e.color,this.state.glowIntensity=e.intensity,this.colorTransition=this.colorUtilities.colorTransition)}updateUndertone(t){this.emotionalStateManager.updateUndertone(t)}setEmotionalState(t,e,i=null){this.emotionalStateManager.setEmotionalState(t,e,i)}setBPM(t){}setRotationSpeed(t){this.rotationManager.setRotationSpeed(t)}setRotationAngle(t){this.rotationManager.setRotationAngle(t)}setGazeOffset(t){this.gazeInputHandler.setGazeOffset(t)}getCurrentOrbPosition(){return this.gazeInputHandler.getCurrentOrbPosition()}setCustomScale(t){this.state.customScale=t}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(t){this.state.blinkingEnabled=t,t||(this.state.blinking=!1,this.eyeRenderer.blinking=!1,this.eyeRenderer.blinkTimer=0)}setGazeTracking(t){this.gazeTracker.setEnabled(t)}initGazeTracking(){this.Bt||(this.Bt=!0),this.gazeTracker.initialize()}cleanupGazeTracking(){this.At||(this.At=!0),this.gazeTracker.cleanup()}resetCanvasContext(){this.canvasContextManager.resetCanvasContext()}setQualityLevel(t){this.canvasContextManager.setQualityLevel(t)}setQualityReduction(t){this.canvasContextManager.setQualityReduction(t)}handleContextRecovery(t){this.canvasContextManager.handleContextRecovery(t)}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(t){return this.gestureAnimator.startGesture(t)}getCurrentGesture(){return this.gestureAnimator.getCurrentGesture()}Et(){["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(t=>{const e=`start${t}`;this[e]=()=>this.gestureAnimator[e]()})}startGrooveSway(t){this.ambientDanceAnimator.startAmbientAnimation("grooveSway",t)}startGrooveBob(t){this.ambientDanceAnimator.startAmbientAnimation("grooveBob",t)}startGrooveFlow(t){this.ambientDanceAnimator.startAmbientAnimation("grooveFlow",t)}startGroovePulse(t){this.ambientDanceAnimator.startAmbientAnimation("groovePulse",t)}startGrooveStep(t){this.ambientDanceAnimator.startAmbientAnimation("grooveStep",t)}stopAllGestures(){this.gestureAnimator.stopAllGestures(),this.currentGesture=null}isGestureActive(){return Object.values(this.gestureAnimator.gestureAnimations).some(t=>t.active)}destroy(){this.resourceCleanupManager.destroy()}}class lr{constructor(t,e={}){this.canvas=t,this.config={smoothing:e.smoothing||.1,maxOffset:e.maxOffset||.3,lockDistance:e.lockDistance||30,enabled:!1!==e.enabled,boundaryPadding:e.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(t){const e=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:t.clientX-e.left,y:t.clientY-e.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(t){for(const e of t.changedTouches)this.touches.set(e.identifier,{x:e.clientX,y:e.clientY}),this.primaryTouch||1!==this.touches.size||(this.primaryTouch=e.identifier);null!==this.primaryTouch&&this.updateTouchPosition(t.touches)}handleTouchMove(t){for(const e of t.changedTouches)this.touches.has(e.identifier)&&this.touches.set(e.identifier,{x:e.clientX,y:e.clientY});null!==this.primaryTouch&&(this.updateTouchPosition(t.touches),this.onInteraction&&this.onInteraction("touch"))}handleTouchEnd(t){for(const e of t.changedTouches)this.touches.delete(e.identifier),e.identifier===this.primaryTouch&&(this.primaryTouch=null,this.touches.size>0?this.primaryTouch=this.touches.keys().next().value:this.handleMouseLeave())}updateTouchPosition(t){for(const e of t)if(e.identifier===this.primaryTouch){const t=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:e.clientX-t.left,y:e.clientY-t.top},this.updateTargetGaze();break}}updateTargetGaze(){const t=this.mousePos.x-this.canvasCenter.x,e=this.mousePos.y-this.canvasCenter.y,i=Math.sqrt(t*t+e*e),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:t*this.config.maxOffset*2,y:e*this.config.maxOffset*2};else{const n=Math.min(this.canvasCenter.x,this.canvasCenter.y)*this.config.maxOffset;if(i>0){const r=Math.min(1,i/s);this.targetGaze={x:t/i*n*r*this.config.boundaryPadding,y:e/i*n*r*this.config.boundaryPadding}}else this.targetGaze={x:0,y:0}}}update(t){if(!this.config.enabled)return;const e=1-Math.pow(1-this.config.smoothing,t/16.67);if(this.currentGaze.x+=(this.targetGaze.x-this.currentGaze.x)*e,this.currentGaze.y+=(this.targetGaze.y-this.currentGaze.y)*e,this.isLocked){const t=.5;this.currentGaze.x+=(Math.random()-.5)*t,this.currentGaze.y+=(Math.random()-.5)*t}}getGazeOffset(t){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(t){this.onInteraction=t}destroy(){this.detachEventListeners(),this.resizeObserver&&this.resizeObserver.disconnect(),this.touches.clear()}}class cr{constructor(t={}){this.config={blinkInterval:t.blinkInterval||{min:3e3,max:7e3},blinkDuration:t.blinkDuration||150,swayInterval:t.swayInterval||{min:2e4,max:4e4},swayDuration:t.swayDuration||4e3,swayIntensity:t.swayIntensity||1.5,sleepTimeout:void 0!==t.sleepTimeout?t.sleepTimeout:1/0,breathingSpeed:t.breathingSpeed||.25,breathingDepth:t.breathingDepth||.1,enabled:!1!==t.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(t){this.config.enabled&&(this.updateBreathing(t),this.timers.idle+=t,!this.state.isAsleep&&this.timers.idle>=this.config.sleepTimeout&&this.enterSleep(),this.state.isAsleep||this.updateBlinking(t),this.state.isAsleep||this.updateSwaying(t))}updateBreathing(t){const e=this.config.breathingSpeed*this.state.breathRate;this.state.breathingPhase+=e*t/1e3,this.state.breathingPhase>2*Math.PI&&(this.state.breathingPhase-=2*Math.PI)}updateBlinking(t){this.isBlinkingEnabled()&&(this.state.isBlinking?(this.timers.blink+=t,this.timers.blink>=this.config.blinkDuration&&this.endBlink()):(this.timers.blink+=t,this.timers.blink>=this.timers.nextBlink&&this.startBlink()))}updateSwaying(t){if(this.state.isSwaying){this.timers.sway+=t;const e=Math.min(this.timers.sway/this.config.swayDuration,1),i=(Math.sin((e-.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,e>=1&&this.endSway()}else this.timers.sway+=t,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 t=Math.random()*Math.PI*2,e=this.config.swayIntensity*(.5+.5*Math.random());this.swayTarget={x:Math.cos(t)*e*1.5,y:Math.sin(t)*e*.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 t={x:.5*this.config.swayIntensity,y:-this.config.swayIntensity};this.swayStart={...this.swayOffset},this.swayTarget=t,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(t){this.config.blinkingEnabled=t,!t&&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(t){const e=this.config[`${t}Interval`];return e.min+Math.random()*(e.max-e.min)}setCallback(t,e){({}).hasOwnProperty.call(this.callbacks,t)&&(this.callbacks[t]=e)}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}}}class ur{constructor(t){this.positionController=t,this.watchedElements=new Map,this.updateCallbacks=new Map}moveToElement(t,e="right",i={x:20,y:0},s={}){const n=document.querySelector(t);if(!n)return;const r=n.getBoundingClientRect(),a=r.left+r.width/2,o=r.top+r.height/2;let h,l;switch(e){case"right":default:h=r.right+i.x,l=o+i.y;break;case"left":h=r.left-i.x,l=o+i.y;break;case"above":h=a+i.x,l=r.top-i.y;break;case"below":h=a+i.x,l=r.bottom+i.y;break;case"center":h=a+i.x,l=o+i.y}const c=h-window.innerWidth/2,u=l-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(t="button",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToForm(t="form",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToModal(t='[role="dialog"], .modal',e="center",i={x:0,y:0}){this.moveToElement(t,e,i)}moveToNavigation(t="nav, .navigation",e="below",i={x:0,y:20}){this.moveToElement(t,e,i)}moveToContent(t="main, .content",e="center",i={x:0,y:0}){this.moveToElement(t,e,i)}moveToSidebar(t=".sidebar, aside",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToHeader(t="header, .header",e="below",i={x:0,y:20}){this.moveToElement(t,e,i)}moveToFooter(t="footer, .footer",e="above",i={x:0,y:20}){this.moveToElement(t,e,i)}watchElement(t,e="right",i={x:20,y:0}){const s=()=>{this.moveToElement(t,e,i,{animate:!1})},n=`${t}-${e}-${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(t=>{window.removeEventListener("scroll",t),window.removeEventListener("resize",t)}),this.updateCallbacks.clear()}destroy(){this.stopWatchingAll(),this.positionController=null}}class dr extends ur{constructor(t){super(t),this.activeCallbacks=new Map,this.callbackStates=new Map}moveToElementWithCallback(t,e,i="right",s={x:20,y:0},n={}){const r=`callback-${Date.now()}-${Math.random()}`,a=document.querySelector(t);if(!a)return;this.callbackStates.set(r,{executed:!1,element:a,callback:e,options:n}),this.moveToElement(t,i,s,n);const o=()=>{if(this.isMascotNearElement(a,n.proximity||50)){const t=this.callbackStates.get(r);t&&!t.executed&&(t.executed=!0,e(),n.repeat||this.callbackStates.delete(r))}this.callbackStates.has(r)&&requestAnimationFrame(o)};return this.activeCallbacks.set(r,o),o(),()=>{this.activeCallbacks.delete(r),this.callbackStates.delete(r)}}moveToElementSequence(t=[],e={}){let i=0;const s=[],n=()=>{if(i>=t.length)return void(e.onComplete&&e.onComplete());const r=t[i],a=this.moveToElementWithCallback(r.selector,()=>{r.callback&&r.callback(),i++,setTimeout(n,r.delay||0)},r.position||"right",r.offset||{x:20,y:0},{...e,...r.options});a&&s.push(a)};return n(),()=>{s.forEach(t=>t())}}moveToElementWithDelay(t,e,i=1e3,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,()=>{setTimeout(e,i)},s,n)}moveToElementWithCondition(t,e,i,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,()=>{e()&&i()},s,n)}moveToElementWithRepeat(t,e,i=1e3,s="right",n={x:20,y:0}){let r=null;const a=this.moveToElementWithCallback(t,()=>{r=setInterval(e,i)},s,n,{repeat:!0});return()=>{null!==r&&(clearInterval(r),r=null),a&&a()}}moveToElementWithProximity(t,e,i=100,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,e,s,n,{proximity:i})}isMascotNearElement(t,e=50){if(!this.positionController||!t)return!1;const i=t.getBoundingClientRect(),s=i.left+i.width/2,n=i.top+i.height/2,r=this.positionController.getOffset(),a=r.x+window.innerWidth/2,o=r.y+window.innerHeight/2;return Math.sqrt(Math.pow(a-s,2)+Math.pow(o-n,2))<=e}stopAllCallbacks(){this.activeCallbacks.forEach((t,e)=>{this.activeCallbacks.delete(e)}),this.callbackStates.clear()}destroy(){this.stopAllCallbacks(),super.destroy()}}class pr extends ur{constructor(t){super(t),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(t,e=[],i="right",s={x:20,y:0},n={}){const r=`path-${Date.now()}-${Math.random()}`,a=document.querySelector(t);if(!a)return;const o=window.innerWidth||1,h=window.innerHeight||1,l=o/2,c=h/2,u=n.coordinateSystem||"auto",d=Array.isArray(e)?e.map((t={})=>{const e="number"==typeof t.x?t.x:0,i="number"==typeof t.y?t.y:0;return"relative"===u||"auto"===u&&e>=0&&e<=1&&i>=0&&i<=1?{x:e*o-l,y:i*h-c}:"offset"===u||"auto"===u&&Math.abs(e)<=l&&Math.abs(i)<=c?{x:e,y:i}:{x:e-l,y:i-c}}):[],p=a.getBoundingClientRect(),m={x:p.left+p.width/2+s.x-l,y:p.top+p.height/2+s.y-c},g=this.positionController.getOffset?this.positionController.getOffset():{x:0,y:0},f=[{x:"number"==typeof g.x?g.x:0,y:"number"==typeof g.y?g.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=[],M=[0];let b=0;for(let t=0;t<f.length-1;t++){const e=f[t+1].x-f[t].x,i=f[t+1].y-f[t].y,s=Math.hypot(e,i);y.push(s),b+=s,M.push(b)}if(0===b)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const w="number"==typeof n.speed&&n.speed>0?n.speed:250,v=!0===n.loop,S=n.easing||"linear",k={covered:0,lastTimestamp:null},x=t=>{if(v)t%=b;else{if(t<=0)return f[0];if(t>=b)return f[f.length-1]}for(let e=0;e<y.length;e++){const i=M[e];if(t<=M[e+1]){const s=y[e]||1,n=0===s?0:(t-i)/s,r=this.positionController&&"function"==typeof this.positionController.applyEasing?this.positionController.applyEasing(n,S):n,a=f[e],o=f[e+1];return{x:a.x+(o.x-a.x)*r,y:a.y+(o.y-a.y)*r}}}return f[f.length-1]},E={stop:()=>{E.frameId&&cancelAnimationFrame(E.frameId),this.activePaths.delete(r)},frameId:null};this.activePaths.set(r,E),this.positionController.setOffset(f[0].x,f[0].y,0);const B=t=>{if(!this.activePaths.has(r))return;null===k.lastTimestamp&&(k.lastTimestamp=t);const e=t-k.lastTimestamp;if(k.lastTimestamp=t,k.covered+=w*(e/1e3),!v&&k.covered>=b)return this.positionController.setOffset(m.x,m.y,0),E.stop(),void("function"==typeof n.onComplete&&n.onComplete());const i=x(k.covered);this.positionController.setOffset(i.x,i.y,0),E.frameId=requestAnimationFrame(B)};return E.frameId=requestAnimationFrame(B),()=>{E.stop()}}moveToElementWithEasing(t,e,i=1e3,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=r.getBoundingClientRect(),o=a.left+a.width/2+n.x-window.innerWidth/2,h=a.top+a.height/2+n.y-window.innerHeight/2,l=this.positionController.getOffset(),c=performance.now();let u=null;const d=t=>{const s=t-c,n=Math.min(s/i,1),r=e(n),a=l.x+(o-l.x)*r,p=l.y+(h-l.y)*r;this.positionController.setOffset(a,p,0),n<1?(u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)):null!==u&&this.activeSmoothAnimations.delete(u)};u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)}moveToElementWithCollision(t,e=[],i=100,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=r.getBoundingClientRect(),o=a.left+a.width/2+n.x-window.innerWidth/2,h=a.top+a.height/2+n.y-window.innerHeight/2,l=this.positionController.getOffset();(()=>{let t=l.x,s=l.y;for(let n=0;n<=100;n++){const r=.01*n,a=l.x+(o-l.x)*r,c=l.y+(h-l.y)*r;let u=!1;e.forEach(e=>{let n,r;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();n=e.left+e.width/2-window.innerWidth/2,r=e.top+e.height/2-window.innerHeight/2}}else n=e.x-window.innerWidth/2,r=e.y-window.innerHeight/2;if(Math.sqrt(Math.pow(a-n,2)+Math.pow(c-r,2))<i){u=!0;const e=Math.atan2(c-r,a-n),o=n+Math.cos(e)*i,h=r+Math.sin(e)*i;t=o,s=h}}),u||(t=a,s=c)}this.positionController.setOffset(t,s,0)})()}moveToElementWithAudio(t,e,i=50,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256),this.audioContext.createMediaStreamSource(e).connect(this.audioAnalyser);const a=new Uint8Array(this.audioAnalyser.frequencyBinCount),o=r.getBoundingClientRect(),h=o.left+o.width/2+n.x-window.innerWidth/2,l=o.top+o.height/2+n.y-window.innerHeight/2;let c=null;const u=()=>{this.audioAnalyser.getByteFrequencyData(a);let t=0;for(let e=0;e<a.length;e++)t+=a[e];const e=t/a.length/255*i,s=h+e,n=l+.5*e;this.positionController.setOffset(s,n,0),null!==c&&this.activeRAFIds.delete(c),c=requestAnimationFrame(u),this.activeRAFIds.add(c)};u()}moveToElementWithGaze(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;this.gazeTracker||(this.gazeTracker={x:window.innerWidth/2,y:window.innerHeight/2});const r=n.getBoundingClientRect(),a=r.left+r.width/2+s.x-window.innerWidth/2,o=r.top+r.height/2+s.y-window.innerHeight/2;let h=null;const l=()=>{const t=this.gazeTracker.x-window.innerWidth/2,i=this.gazeTracker.y-window.innerHeight/2,s=e.gazeWeight||.3,n=a+(t-a)*s,r=o+(i-o)*s;this.positionController.setOffset(n,r,0),null!==h&&this.activeRAFIds.delete(h),h=requestAnimationFrame(l),this.activeRAFIds.add(h)};l()}addObstacle(t){this.obstacles.add(t)}removeObstacle(t){this.obstacles.delete(t)}clearObstacles(){this.obstacles.clear()}destroy(){Array.from(this.activePaths.values()).forEach(t=>{t&&"function"==typeof t.stop?t.stop():t&&t.frameId&&cancelAnimationFrame(t.frameId)}),this.activePaths.clear(),this.activeRAFIds.forEach(t=>{cancelAnimationFrame(t)}),this.activeRAFIds.clear(),this.activeSmoothAnimations.forEach(t=>{cancelAnimationFrame(t)}),this.activeSmoothAnimations.clear(),this.obstacles.clear(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.audioAnalyser=null,this.gazeTracker=null,super.destroy()}}class mr extends ur{constructor(t){super(t),this.scrollCallbacks=new Map,this.physicsSimulations=new Map,this.responsiveBreakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.accessibilityEnabled=!1}moveToElementWithScroll(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`scroll-${Date.now()}-${Math.random()}`,{startScroll:a=50,endScroll:o=300,onProgress:h=null,onStart:l=null,onComplete:c=null}=e;let u=!1,d=!1;const p=()=>{const{scrollY:t}=window,e=Math.min(Math.max((t-a)/(o-a),0),1);e>0&&!u&&(u=!0,l&&l()),e>=1&&!d&&(d=!0,c&&c());const i=n.getBoundingClientRect(),r=i.left+i.width/2+s.x-window.innerWidth/2,p=i.top+i.height/2+s.y-window.innerHeight/2,m=window.innerWidth>1024,g=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=g+(r-g)*e,M=f+(p-f)*e;this.positionController.setOffset(y,M,0),h&&h(e,{scrollY:t,currentX:y,currentY:M})};return this.scrollCallbacks.set(r,p),window.addEventListener("scroll",p),p(),()=>{this.scrollCallbacks.delete(r),window.removeEventListener("scroll",p)}}moveToElementWithPhysics(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`physics-${Date.now()}-${Math.random()}`,{mass:a=1,damping:o=.98,springConstant:h=.1,maxVelocity:l=10,onUpdate:c=null}=e,u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x-window.innerWidth/2,p=u.top+u.height/2+s.y-window.innerHeight/2,m=this.positionController.getOffset();let g=m.x,f=m.y,y=0,M=0;const b=()=>{y+=(d-g)*h/a,M+=(p-f)*h/a,y*=o,M*=o;const t=Math.sqrt(y*y+M*M);t>l&&(y=y/t*l,M=M/t*l),g+=y,f+=M,this.positionController.setOffset(g,f,0),c&&c({positionX:g,positionY:f,velocityX:y,velocityY:M}),this.physicsSimulations.has(r)&&requestAnimationFrame(b)};return this.physicsSimulations.set(r,b),b(),()=>{this.physicsSimulations.delete(r)}}moveToElementWithGroup(t=[],e="center",i={x:0,y:0}){if(0===t.length)return;let s=0,n=0,r=0,a=0,o=0;if(t.forEach(t=>{const e=document.querySelector(t);if(e){const t=e.getBoundingClientRect();s+=t.left,n+=t.top,r=Math.max(r,t.left+t.width),a=Math.max(a,t.top+t.height),o++}}),0===o)return;const h=s/o,l=n/o;let c,u;switch(e){case"center":default:c=h+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"left":c=s+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"right":c=r+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"top":c=h+i.x-window.innerWidth/2,u=n+i.y-window.innerHeight/2;break;case"bottom":c=h+i.x-window.innerWidth/2,u=a+i.y-window.innerHeight/2}this.positionController.setOffset(c,u,0)}moveToElementWithResponsive(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=()=>{const t=this.getCurrentBreakpoint(),i=e[t]||e.default||{},r=n.getBoundingClientRect(),a=r.left+r.width/2+(i.offsetX||s.x)-window.innerWidth/2,o=r.top+r.height/2+(i.offsetY||s.y)-window.innerHeight/2;this.positionController.setOffset(a,o,0)},a=()=>{const t=this.getCurrentBreakpoint();t!==this.currentBreakpoint&&(this.currentBreakpoint=t,r())};return window.addEventListener("resize",a),r(),()=>{window.removeEventListener("resize",a)}}moveToElementWithAccessibility(t,e={},i="right",s={x:20,y:0}){if(!document.querySelector(t))return;const{announce:n=!0,announcements:r=[],screenReaderPosition:a="bottom-right"}=e;let o,h;switch(a){case"bottom-right":default:o=window.innerWidth-100-window.innerWidth/2,h=window.innerHeight-100-window.innerHeight/2;break;case"bottom-left":o=100-window.innerWidth/2,h=window.innerHeight-100-window.innerHeight/2;break;case"top-right":o=window.innerWidth-100-window.innerWidth/2,h=100-window.innerHeight/2;break;case"top-left":o=100-window.innerWidth/2,h=100-window.innerHeight/2}this.positionController.setOffset(o,h,0),n&&window.speechSynthesis&&r.forEach(t=>{if(t.condition&&t.condition()){const e=new SpeechSynthesisUtterance(t.text);e.volume=.5,e.rate=.8,window.speechSynthesis.speak(e)}})}getCurrentBreakpoint(){const t=window.innerWidth;return t<this.responsiveBreakpoints.mobile?"mobile":t<this.responsiveBreakpoints.tablet?"tablet":t<this.responsiveBreakpoints.desktop?"desktop":"large"}setBreakpoints(t){this.responsiveBreakpoints={...this.responsiveBreakpoints,...t},this.currentBreakpoint=this.getCurrentBreakpoint()}enableAccessibility(){this.accessibilityEnabled=!0}disableAccessibility(){this.accessibilityEnabled=!1}destroy(){this.scrollCallbacks.forEach((t,e)=>{window.removeEventListener("scroll",t)}),this.scrollCallbacks.clear(),this.physicsSimulations.clear(),super.destroy()}}class gr extends ur{constructor(t){super(t),this.activeInteractions=new Map,this.hoverStates=new Map,this.clickStates=new Map,this.touchStates=new Map}moveToElementWithHover(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`hover-${Date.now()}-${Math.random()}`,{onMouseEnter:a=null,onMouseLeave:o=null,onHover:h=null,followMouse:l=!1,hoverDistance:c=50}=e;let u=!1,d=0,p=0;const m=t=>{u=!0,a&&a(t)},g=t=>{u=!1,o&&o(t)},f=t=>{if(d=t.clientX,p=t.clientY,u&&h&&h(t),l&&u){const t=n.getBoundingClientRect(),e=t.left+t.width/2,i=t.top+t.height/2;if(Math.sqrt(Math.pow(d-e,2)+Math.pow(p-i,2))<=c){const t=d+s.x-window.innerWidth/2,e=p+s.y-window.innerHeight/2;this.positionController.setOffset(t,e,0)}}};return n.addEventListener("mouseenter",m),n.addEventListener("mouseleave",g),n.addEventListener("mousemove",f),this.activeInteractions.set(r,{element:n,events:[{event:"mouseenter",handler:m},{event:"mouseleave",handler:g},{event:"mousemove",handler:f}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithClick(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`click-${Date.now()}-${Math.random()}`,{onClick:a=null,onDoubleClick:o=null,maxClicks:h=3}=e;let l=0;const c=t=>{if(l++,a&&a(t,l),l>=h){const t=n.getBoundingClientRect(),e=t.left+t.width/2+s.x-window.innerWidth/2,i=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(e,i,0)}},u=t=>{o&&o(t)};return n.addEventListener("click",c),n.addEventListener("dblclick",u),this.activeInteractions.set(r,{element:n,events:[{event:"click",handler:c},{event:"dblclick",handler:u}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithTouch(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`touch-${Date.now()}-${Math.random()}`,{onTouchStart:a=null,onTouchMove:o=null,onTouchEnd:h=null,onSwipe:l=null,swipeThreshold:c=50}=e;let u=0,d=0,p=0,m=0;const g=t=>{t.touches.length>0&&(u=t.touches[0].clientX,d=t.touches[0].clientY,a&&a(t))},f=t=>{if(t.touches.length>0){const e=t.touches[0].clientX,i=t.touches[0].clientY;o&&o(t);const n=e+s.x-window.innerWidth/2,r=i+s.y-window.innerHeight/2;this.positionController.setOffset(n,r,0)}},y=t=>{if(t.changedTouches.length>0){p=t.changedTouches[0].clientX,m=t.changedTouches[0].clientY,h&&h(t);const e=p-u,i=m-d,s=Math.sqrt(e*e+i*i);if(s>c&&l){const t=Math.abs(e)>Math.abs(i)?e>0?"right":"left":i>0?"down":"up";l(t,s)}}};return n.addEventListener("touchstart",g),n.addEventListener("touchmove",f),n.addEventListener("touchend",y),this.activeInteractions.set(r,{element:n,events:[{event:"touchstart",handler:g},{event:"touchmove",handler:f},{event:"touchend",handler:y}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithFocus(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`focus-${Date.now()}-${Math.random()}`,{onFocus:a=null,onBlur:o=null,onFocusIn:h=null,onFocusOut:l=null}=e,c=t=>{a&&a(t);const e=n.getBoundingClientRect(),i=e.left+e.width/2+s.x-window.innerWidth/2,r=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(i,r,0)},u=t=>{o&&o(t)},d=t=>{h&&h(t)},p=t=>{l&&l(t)};return n.addEventListener("focus",c),n.addEventListener("blur",u),n.addEventListener("focusin",d),n.addEventListener("focusout",p),this.activeInteractions.set(r,{element:n,events:[{event:"focus",handler:c},{event:"blur",handler:u},{event:"focusin",handler:d},{event:"focusout",handler:p}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithKeyboard(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`keyboard-${Date.now()}-${Math.random()}`,{onKeyDown:a=null,onKeyUp:o=null,onKeyPress:h=null,targetKeys:l=["Enter","Space"]}=e,c=t=>{if(a&&a(t),l.includes(t.key)){const t=n.getBoundingClientRect(),e=t.left+t.width/2+s.x-window.innerWidth/2,i=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(e,i,0)}},u=t=>{o&&o(t)},d=t=>{h&&h(t)};return n.addEventListener("keydown",c),n.addEventListener("keyup",u),n.addEventListener("keypress",d),this.activeInteractions.set(r,{element:n,events:[{event:"keydown",handler:c},{event:"keyup",handler:u},{event:"keypress",handler:d}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}stopAllInteractions(){this.activeInteractions.forEach((t,e)=>{t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(e)}),this.hoverStates.clear(),this.clickStates.clear(),this.touchStates.clear()}destroy(){this.stopAllInteractions(),super.destroy()}}class fr extends ur{constructor(t){super(t),this.activeAnimations=new Map,this.animationQueue=[],this.isAnimating=!1,this.queueTimeouts=new Set,this.activeRAFIds=new Set,this.animationRAFIds=new Map}moveToElementWithBounce(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`bounce-${Date.now()}-${Math.random()}`,{duration:a=1e3,intensity:o=50,bounces:h=3,onComplete:l=null}=e,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,p=this.positionController.getOffset(),m=performance.now(),g=t=>{const e=t-m,i=Math.min(e/a,1),s=1-Math.pow(1-i,3),n=Math.sin(s*Math.PI*h)*o*(1-i),c=p.x+(u-p.x)*i,f=p.y+(d-p.y)*i+n;if(this.positionController.setOffset(c,f,0),i<1){this.activeAnimations.set(r,g);const t=requestAnimationFrame(g);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,g);const f=requestAnimationFrame(g);return this.activeRAFIds.add(f),this.animationRAFIds.set(r,f),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithShake(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`shake-${Date.now()}-${Math.random()}`,{duration:a=500,intensity:o=10,frequency:h=20,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=(Math.random()-.5)*o*(1-i),n=(Math.random()-.5)*o*(1-i),c=u+s,g=d+n;if(this.positionController.setOffset(c,g,0),i<1)this.activeAnimations.set(r,m),setTimeout(()=>{const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)},1e3/h);else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithPulse(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`pulse-${Date.now()}-${Math.random()}`,{duration:a=2e3,intensity:o=20,frequency:h=2,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=Math.sin(e*h*.01)*o*(1-i),n=u+s,c=d+s;if(this.positionController.setOffset(n,c,0),i<1){this.activeAnimations.set(r,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithWiggle(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`wiggle-${Date.now()}-${Math.random()}`,{duration:a=1e3,intensity:o=15,frequency:h=8,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=Math.sin(e*h*.01)*o*(1-i),n=Math.cos(e*h*.01)*o*(1-i),c=u+s,g=d+n;if(this.positionController.setOffset(c,g,0),i<1){this.activeAnimations.set(r,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithCustom(t,e,i={},s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=`custom-${Date.now()}-${Math.random()}`,{duration:o=1e3,onComplete:h=null}=i,l=r.getBoundingClientRect(),c=l.left+l.width/2+n.x-window.innerWidth/2,u=l.top+l.height/2+n.y-window.innerHeight/2,d=this.positionController.getOffset(),p=performance.now(),m=t=>{const i=t-p,s=Math.min(i/o,1),n=e(s,{elapsed:i,startOffset:d,targetX:c,targetY:u,currentTime:t});if(n&&"object"==typeof n){const t=void 0!==n.x?n.x:c,e=void 0!==n.y?n.y:u;this.positionController.setOffset(t,e,0)}if(s<1){this.activeAnimations.set(a,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(a,t)}else{this.activeAnimations.delete(a);const t=this.animationRAFIds.get(a);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(a,g),()=>{this.activeAnimations.delete(a);const t=this.animationRAFIds.get(a);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(a))}}queueAnimations(t=[]){this.animationQueue=[...this.animationQueue,...t],this.processAnimationQueue()}processAnimationQueue(){if(this.isAnimating||0===this.animationQueue.length)return;this.isAnimating=!0;const t=this.animationQueue.shift();if(t){const e=this.executeAnimation(t);if(e){const i=setTimeout(()=>{this.queueTimeouts.delete(i),e(),this.isAnimating=!1,this.processAnimationQueue()},t.duration||1e3);this.queueTimeouts.add(i)}}}executeAnimation(t){const{type:e,targetSelector:i,options:s={},position:n="right",offset:r={x:20,y:0}}=t;switch(e){case"bounce":return this.moveToElementWithBounce(i,s,n,r);case"shake":return this.moveToElementWithShake(i,s,n,r);case"pulse":return this.moveToElementWithPulse(i,s,n,r);case"wiggle":return this.moveToElementWithWiggle(i,s,n,r);case"custom":return this.moveToElementWithCustom(i,s.animationFunction,s,n,r);default:return this.moveToElement(i,n,r)}}stopAllAnimations(){this.activeAnimations.forEach((t,e)=>{this.activeAnimations.delete(e)}),this.activeRAFIds.forEach(t=>cancelAnimationFrame(t)),this.activeRAFIds.clear(),this.animationRAFIds.clear(),this.queueTimeouts.forEach(t=>clearTimeout(t)),this.queueTimeouts.clear(),this.animationQueue=[],this.isAnimating=!1}destroy(){this.stopAllAnimations(),super.destroy()}}class yr extends ur{constructor(t){super(t),this.activeEffects=new Map,this.trailPoints=[],this.particles=[],this.effectCanvas=null,this.effectContext=null,this.maxTrailPoints=50,this.maxParticles=100}moveToElementWithTrail(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`trail-${Date.now()}-${Math.random()}`,{color:a="#00ff88",width:o=3,opacity:h=.8,fadeSpeed:l=.95,onComplete:c=null}=e;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,p=u.top+u.height/2+s.y,m=this.positionController.getOffset(),g=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),M=t=>{const e=t-y,i=Math.min(e/1e3,1),s=g+(d-g)*i,n=f+(p-f)*i;this.trailPoints.push({x:s,y:n,opacity:h*(1-i),timestamp:t}),this.trailPoints.length>this.maxTrailPoints&&this.trailPoints.shift(),this.trailPoints.forEach(t=>{t.opacity*=l}),this.trailPoints=this.trailPoints.filter(t=>t.opacity>.01),this.drawTrail(a,o),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(r,M),requestAnimationFrame(M)):(this.activeEffects.delete(r),c&&c())};return this.activeEffects.set(r,M),requestAnimationFrame(M),()=>{this.activeEffects.delete(r)}}moveToElementWithParticles(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`particles-${Date.now()}-${Math.random()}`,{count:a=20,color:o="#00ff88",size:h=2,speed:l=2,life:c=1e3,onComplete:u=null}=e;this.initializeEffectCanvas();const d=n.getBoundingClientRect(),p=d.left+d.width/2+s.x,m=d.top+d.height/2+s.y,g=this.positionController.getOffset(),f=g.x+window.innerWidth/2,y=g.y+window.innerHeight/2,M=performance.now();for(let t=0;t<a;t++)this.particles.push({x:f,y:y,vx:(Math.random()-.5)*l,vy:(Math.random()-.5)*l,life:c,maxLife:c,color:o,size:h});const b=t=>{const e=t-M,i=Math.min(e/1e3,1);this.particles.forEach(t=>{t.x+=t.vx,t.y+=t.vy,t.life-=16,t.opacity=t.life/t.maxLife}),this.particles=this.particles.filter(t=>t.life>0),this.drawParticles();const s=f+(p-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(r,b),requestAnimationFrame(b)):(this.activeEffects.delete(r),u&&u())};return this.activeEffects.set(r,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(r)}}moveToElementWithGlow(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`glow-${Date.now()}-${Math.random()}`,{color:a="#00ff88",intensity:o=50,radius:h=100,duration:l=1e3,onComplete:c=null}=e;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,p=u.top+u.height/2+s.y,m=this.positionController.getOffset(),g=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),M=t=>{const e=t-y,i=Math.min(e/l,1),s=g+(d-g)*i,n=f+(p-f)*i;this.drawGlow(s,n,a,o,h,i),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(r,M),requestAnimationFrame(M)):(this.activeEffects.delete(r),c&&c())};return this.activeEffects.set(r,M),requestAnimationFrame(M),()=>{this.activeEffects.delete(r)}}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(t,e){if(this.effectContext&&!(this.trailPoints.length<2)){this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.effectContext.strokeStyle=t,this.effectContext.lineWidth=e,this.effectContext.lineCap="round",this.effectContext.lineJoin="round",this.effectContext.beginPath(),this.effectContext.moveTo(this.trailPoints[0].x,this.trailPoints[0].y);for(let t=1;t<this.trailPoints.length;t++){const e=this.trailPoints[t];this.effectContext.globalAlpha=e.opacity,this.effectContext.lineTo(e.x,e.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(t=>{this.effectContext.globalAlpha=t.opacity,this.effectContext.fillStyle=t.color,this.effectContext.beginPath(),this.effectContext.arc(t.x,t.y,t.size,0,2*Math.PI),this.effectContext.fill()}),this.effectContext.globalAlpha=1)}drawGlow(t,e,i,s,n,r){if(!this.effectContext)return;this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height);const a=this.effectContext.createRadialGradient(t,e,0,t,e,n),o=Math.floor(s*r).toString(16).padStart(2,"0"),h=i.startsWith("#")?i:`#${i}`;a.addColorStop(0,`${h}${o}`),a.addColorStop(1,`${h}00`),this.effectContext.fillStyle=a,this.effectContext.beginPath(),this.effectContext.arc(t,e,n,0,2*Math.PI),this.effectContext.fill()}stopAllEffects(){this.activeEffects.forEach((t,e)=>{this.activeEffects.delete(e)}),this.trailPoints=[],this.particles=[]}destroy(){this.stopAllEffects(),this.effectCanvas&&(document.body.removeChild(this.effectCanvas),this.effectCanvas=null,this.effectContext=null),super.destroy()}}class Mr extends ur{constructor(t){super(t),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(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{announce:r=!0,announcement:a="Mascot moved to element",role:o="button",label:h=n.textContent||n.alt||"Interactive element"}=e;this.moveToElement(t,i,s),r&&this.accessibilityOptions.screenReader&&this.announceToScreenReader(a),n&&(n.setAttribute("role",o),n.setAttribute("aria-label",h),n.setAttribute("aria-live","polite"))}moveToElementWithKeyboard(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{onKeyDown:r=null,onKeyUp:a=null,onEnter:o=null,onEscape:h=null,onArrowKeys:l=null}=e,c=`keyboard-${Date.now()}-${Math.random()}`,u=t=>{switch(r&&r(t),t.key){case"Enter":case" ":o&&o(t);break;case"Escape":h&&h(t);break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":l&&l(t)}},d=t=>{a&&a(t)};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(t,i,s),()=>{const t=this.keyboardListeners.get(c);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.keyboardListeners.delete(c))}}moveToElementWithHighContrast(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{backgroundColor:r="#000000",textColor:a="#ffffff",borderColor:o="#ffffff",borderWidth:h=2}=e;this.accessibilityOptions.highContrast&&(n.style.backgroundColor=r,n.style.color=a,n.style.border=`${h}px solid ${o}`,n.style.outline=`${h}px solid ${o}`),this.moveToElement(t,i,s)}moveToElementWithReducedMotion(t,e={},i="right",s={x:20,y:0}){if(!document.querySelector(t))return;const{duration:n=0,easing:r="linear"}=e;window.matchMedia("(prefers-reduced-motion: reduce)").matches||this.accessibilityOptions.reducedMotion?this.moveToElement(t,i,s):this.moveToElement(t,i,s,{duration:n,easing:r})}moveToElementWithFocus(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{autoFocus:r=!1,focusRing:a=!0,focusOrder:o=[]}=e;o.length>0?this.focusOrder=o:this.focusOrder.includes(t)||this.focusOrder.push(t),n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),a&&(n.style.outline="2px solid #0066cc",n.style.outlineOffset="2px"),r&&n.focus(),this.moveToElement(t,i,s)}navigateFocus(t="next"){if(0===this.focusOrder.length)return;this.currentFocusIndex="next"===t?(this.currentFocusIndex+1)%this.focusOrder.length:(this.currentFocusIndex-1+this.focusOrder.length)%this.focusOrder.length;const e=this.focusOrder[this.currentFocusIndex],i=document.querySelector(e);i&&(i.focus(),this.moveToElement(e,"right",{x:20,y:0}))}announceToScreenReader(t){if(!this.accessibilityOptions.announcements)return;let e=document.getElementById("mascot-live-region");e||(e=document.createElement("div"),e.id="mascot-live-region",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.position="absolute",e.style.left="-10000px",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",document.body.appendChild(e)),e.textContent=t,setTimeout(()=>{e.textContent=""},1e3)}enableAccessibility(t={}){this.accessibilityOptions={...this.accessibilityOptions,...t}}disableAccessibility(t={}){Object.keys(t).forEach(t=>{({}).hasOwnProperty.call(this.accessibilityOptions,t)&&(this.accessibilityOptions[t]=!1)})}isAccessibilityEnabled(t){return this.accessibilityOptions[t]||!1}getAccessibilityOptions(){return{...this.accessibilityOptions}}destroy(){this.keyboardListeners.forEach((t,e)=>{t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)})}),this.keyboardListeners.clear();const t=document.getElementById("mascot-live-region");t&&document.body.removeChild(t),this.focusOrder=[],this.currentFocusIndex=0,super.destroy()}}class br{constructor(t){this.positionController=t,this.callbacks=new dr(t),this.advanced=new pr(t),this.context=new mr(t),this.interactions=new gr(t),this.animations=new fr(t),this.effects=new yr(t),this.accessibility=new Mr(t)}moveToElementWithCallback(...t){return this.callbacks.moveToElementWithCallback(...t)}moveToElementSequence(...t){return this.callbacks.moveToElementSequence(...t)}moveToElementWithDelay(...t){return this.callbacks.moveToElementWithDelay(...t)}moveToElementWithCondition(...t){return this.callbacks.moveToElementWithCondition(...t)}moveToElementWithRepeat(...t){return this.callbacks.moveToElementWithRepeat(...t)}moveToElementWithProximity(...t){return this.callbacks.moveToElementWithProximity(...t)}moveToElementWithPath(...t){return this.advanced.moveToElementWithPath(...t)}moveToElementWithEasing(...t){return this.advanced.moveToElementWithEasing(...t)}moveToElementWithCollision(...t){return this.advanced.moveToElementWithCollision(...t)}moveToElementWithAudio(...t){return this.advanced.moveToElementWithAudio(...t)}moveToElementWithGaze(...t){return this.advanced.moveToElementWithGaze(...t)}moveToElementWithScroll(...t){return this.context.moveToElementWithScroll(...t)}moveToElementWithPhysics(...t){return this.context.moveToElementWithPhysics(...t)}moveToElementWithGroup(...t){return this.context.moveToElementWithGroup(...t)}moveToElementWithResponsive(...t){return this.context.moveToElementWithResponsive(...t)}moveToElementWithAccessibility(...t){return this.context.moveToElementWithAccessibility(...t)}moveToElementWithHover(...t){return this.interactions.moveToElementWithHover(...t)}moveToElementWithClick(...t){return this.interactions.moveToElementWithClick(...t)}moveToElementWithTouch(...t){return this.interactions.moveToElementWithTouch(...t)}moveToElementWithFocus(...t){return this.interactions.moveToElementWithFocus(...t)}moveToElementWithKeyboard(...t){return this.interactions.moveToElementWithKeyboard(...t)}moveToElementWithBounce(...t){return this.animations.moveToElementWithBounce(...t)}moveToElementWithShake(...t){return this.animations.moveToElementWithShake(...t)}moveToElementWithPulse(...t){return this.animations.moveToElementWithPulse(...t)}moveToElementWithWiggle(...t){return this.animations.moveToElementWithWiggle(...t)}moveToElementWithCustom(...t){return this.animations.moveToElementWithCustom(...t)}moveToElementWithTrail(...t){return this.effects.moveToElementWithTrail(...t)}moveToElementWithParticles(...t){return this.effects.moveToElementWithParticles(...t)}moveToElementWithGlow(...t){return this.effects.moveToElementWithGlow(...t)}moveToElementWithScreenReader(...t){return this.accessibility.moveToElementWithScreenReader(...t)}moveToElementWithKeyboardAccessible(...t){return this.accessibility.moveToElementWithKeyboard(...t)}moveToElementWithHighContrast(...t){return this.accessibility.moveToElementWithHighContrast(...t)}moveToElementWithReducedMotion(...t){return this.accessibility.moveToElementWithReducedMotion(...t)}moveToElementWithFocusAccessible(...t){return this.accessibility.moveToElementWithFocus(...t)}announceToScreenReader(...t){return this.accessibility.announceToScreenReader(...t)}navigateFocus(...t){return this.accessibility.navigateFocus(...t)}enableAccessibility(...t){return this.accessibility.enableAccessibility(...t)}disableAccessibility(...t){return this.accessibility.disableAccessibility(...t)}destroy(){this.callbacks.destroy(),this.advanced.destroy(),this.context.destroy(),this.interactions.destroy(),this.animations.destroy(),this.effects.destroy(),this.accessibility.destroy()}}class wr{constructor(t){this.positionController=t,this.isTracking=!1,this.trackingCallbacks=new Map,this.audioContext=null,this.audioAnalyser=null,this.audioData=null}moveToMouse(t={x:20,y:20},e={}){const i="mouse-tracking",s=i=>{const s=i.clientX+t.x,n=i.clientY+t.y,r=s-window.innerWidth/2,a=n-window.innerHeight/2;!1!==e.smooth?this.positionController.animateOffset(r,a,0,e.duration||200,"easeOutQuad"):this.positionController.setOffset(r,a,0)};return this.trackingCallbacks.set(i,s),window.addEventListener("mousemove",s),()=>{window.removeEventListener("mousemove",s),this.trackingCallbacks.delete(i)}}moveToTouch(t={x:20,y:20},e={}){const i="touch-tracking",s=i=>{if(i.touches.length>0){const s=i.touches[0],n=s.clientX+t.x,r=s.clientY+t.y,a=n-window.innerWidth/2,o=r-window.innerHeight/2;!1!==e.smooth?this.positionController.animateOffset(a,o,0,e.duration||200,"easeOutQuad"):this.positionController.setOffset(a,o,0)}};return this.trackingCallbacks.set(i,s),window.addEventListener("touchmove",s),()=>{window.removeEventListener("touchmove",s),this.trackingCallbacks.delete(i)}}moveToAudio(t=0,e=50,i={}){if(this.audioContext||this.initAudioContext(),!this.audioContext||!this.audioAnalyser)return;const s="audio-tracking",n=()=>{if(!this.isTracking)return;this.audioAnalyser.getByteFrequencyData(this.audioData);let t=0;for(let e=0;e<this.audioData.length;e++)t+=this.audioData[e];const s=t/this.audioData.length/255*e,r=(i.centerX||0)+s,a=(i.centerY||0)+.5*s,o=r-window.innerWidth/2,h=a-window.innerHeight/2;this.positionController.setOffset(o,h,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(t){}}connectAudioSource(t){this.audioContext&&this.audioAnalyser||this.initAudioContext(),this.audioContext&&this.audioAnalyser&&this.audioContext.createMediaStreamSource(t).connect(this.audioAnalyser)}moveToViewport(t="right",e={x:20,y:20}){let i,s;switch(t){case"top":i=window.innerWidth/2,s=e.y;break;case"bottom":i=window.innerWidth/2,s=window.innerHeight-e.y;break;case"left":i=e.x,s=window.innerHeight/2;break;case"right":default:i=window.innerWidth-e.x,s=window.innerHeight/2;break;case"top-left":i=e.x,s=e.y;break;case"top-right":i=window.innerWidth-e.x,s=e.y;break;case"bottom-left":i=e.x,s=window.innerHeight-e.y;break;case"bottom-right":i=window.innerWidth-e.x,s=window.innerHeight-e.y}const n=i-window.innerWidth/2,r=s-window.innerHeight/2;this.positionController.setOffset(n,r,0)}stopAllTracking(){this.trackingCallbacks.forEach((t,e)=>{"mouse-tracking"===e?window.removeEventListener("mousemove",t):"touch-tracking"===e&&window.removeEventListener("touchmove",t)}),this.trackingCallbacks.clear(),this.isTracking=!1}destroy(){this.stopAllTracking(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.positionController=null}}class vr{constructor(t){this.positionController=t,this.isRunning=!1,this.physicsCallbacks=new Map,this.velocity={x:0,y:0},this.acceleration={x:0,y:0},this.lastTime=0}moveToGrid(t,e,i={x:0,y:0},s={}){const n=s.gridSize||100,r=t*n+i.x,a=e*n+i.y,o=r-window.innerWidth/2,h=a-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(o,h,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(o,h,0)}moveToGravity(t={x:0,y:0},e=.1,i={}){const s="gravity",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y,o=t.x-n,h=t.y-a,l=Math.sqrt(o*o+h*h);if(l>0){const t=e/(l*l);this.acceleration.x=o/l*t,this.acceleration.y=h/l*t,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const s=i.damping||.98;this.velocity.x*=s,this.velocity.y*=s;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t=[],e=.05,i={}){const s="magnetic",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y;let o=0,h=0;t.forEach(t=>{let i,s;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();i=t.left+t.width/2-window.innerWidth/2,s=t.top+t.height/2-window.innerHeight/2}}else{if(void 0===t.x||void 0===t.y)return;i=t.x-window.innerWidth/2,s=t.y-window.innerHeight/2}const r=i-n,l=s-a,c=Math.sqrt(r*r+l*l);if(c>0){const t=e/(c*c);o+=r/c*t,h+=l/c*t}}),this.acceleration.x=o,this.acceleration.y=h,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const l=i.damping||.95;this.velocity.x*=l,this.velocity.y*=l;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t=[],e=100,i={}){const s="avoid",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y;let o=0,h=0;t.forEach(t=>{let i,s;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();i=t.left+t.width/2-window.innerWidth/2,s=t.top+t.height/2-window.innerHeight/2}}else{if(void 0===t.x||void 0===t.y)return;i=t.x-window.innerWidth/2,s=t.y-window.innerHeight/2}const r=n-i,l=a-s,c=Math.sqrt(r*r+l*l);if(c<e&&c>0){const t=(e-c)/e;o+=r/c*t,h+=l/c*t}}),this.acceleration.x=o,this.acceleration.y=h,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const l=i.damping||.9;this.velocity.x*=l,this.velocity.y*=l;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t={x:0,y:0,width:400,height:400},e=3e3,i={}){const s="random",n=()=>{if(!this.isRunning)return;const s=t.x+Math.random()*t.width,r=t.y+Math.random()*t.height,a=s-window.innerWidth/2,o=r-window.innerHeight/2;!1!==i.animate?this.positionController.animateOffset(a,o,0,i.duration||1e3,i.easing||"easeOutCubic"):this.positionController.setOffset(a,o,0),this.isRunning&&setTimeout(n,e)};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 Sr{constructor(t){this.positionController=t,this.isRunning=!1,this.animationCallbacks=new Map,this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}moveToPath(t=[],e=1,i={}){if(t.length<2)return;const s="path",n=!1!==i.loop,r=i.reverse||!1,a=o=>{if(!this.isRunning)return;const h=o-(this.lastTime||o);if(this.lastTime=o,h>0){this.pathProgress+=e*h/1e3,this.pathProgress=n?this.pathProgress%t.length:Math.min(this.pathProgress,t.length-1);const a=Math.floor(this.pathProgress),o=this.pathProgress-a;let l,c;r?(l=t[t.length-1-a],c=t[t.length-2-a]||t[0]):(l=t[a],c=t[a+1]||t[0]);const u=l.x+(c.x-l.x)*o,d=l.y+(c.y-l.y)*o,p=u-window.innerWidth/2,m=d-window.innerHeight/2;if(this.positionController.setOffset(p,m,0),!n&&this.pathProgress>=t.length-1)return this.isRunning=!1,this.animationCallbacks.delete(s),void(i.onComplete&&i.onComplete())}this.isRunning&&requestAnimationFrame(a)};return this.animationCallbacks.set(s,a),this.isRunning=!0,this.lastTime=performance.now(),a(this.lastTime),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToTime(t=2e3,e="easeInOutCubic",i={}){const s="time",n=performance.now(),r=this.positionController.getOffset(),a=i.target||{x:0,y:0},o=h=>{if(!this.isRunning)return;const l=h-n,c=Math.min(l/t,1),u=this.applyEasing(c,e),d=r.x+(a.x-r.x)*u,p=r.y+(a.y-r.y)*u;this.positionController.setOffset(d,p,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(t=0,e={x:0,y:0},i={}){const s="scroll",n=()=>{if(!this.isRunning)return;const s=window.innerWidth,n=window.innerHeight;let r,a;if("horizontal"===i.direction)r=t*s+e.x,a=n/2+e.y;else if("vertical"===i.direction)r=s/2+e.x,a=t*n+e.y;else{const o=t*Math.PI*2,h=i.radius||Math.min(s,n)/4;r=s/2+Math.cos(o)*h+e.x,a=n/2+Math.sin(o)*h+e.y}const o=r-s/2,h=a-n/2;this.positionController.setOffset(o,h,0)};return this.animationCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}animateTo(t,e,i=1e3,s="easeOutCubic"){this.positionController.animateOffset(t,e,0,i,s)}applyEasing(t,e){switch(e){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return 1-(1-t)*(1-t);case"easeInOutQuad":return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;case"easeInCubic":return t*t*t;case"easeOutCubic":return 1-Math.pow(1-t,3);case"easeInOutCubic":return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;case"easeInBack":{const e=1.70158;return(e+1)*t*t*t-e*t*t}case"easeOutBack":{const e=1.70158;return 1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}case"easeInElastic":return 0===t?0:1===t?1:-Math.pow(2,10*t-10)*Math.sin((10*t-10.75)*(2*Math.PI/3));case"easeOutElastic":return 0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((10*t-.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 kr{constructor(t){this.positionController=t,this.breakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.responsiveCallbacks=new Map}getCurrentBreakpoint(){const t=window.innerWidth;return t<this.breakpoints.mobile?"mobile":t<this.breakpoints.tablet?"tablet":t<this.breakpoints.desktop?"desktop":"large"}moveToResponsive(t={},e={}){const i="responsive",s=()=>{if(!this.isRunning)return;const i=this.getCurrentBreakpoint(),s=t[i]||t.default||{x:0,y:0},n=s.x-window.innerWidth/2,r=s.y-window.innerHeight/2;!1!==e.animate?this.positionController.animateOffset(n,r,0,e.duration||500,e.easing||"easeOutCubic"):this.positionController.setOffset(n,r,0)};this.responsiveCallbacks.set(i,s),this.isRunning=!0,s();const n=()=>{const t=this.getCurrentBreakpoint();t!==this.currentBreakpoint&&(this.currentBreakpoint=t,s())};return window.addEventListener("resize",n),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(i),window.removeEventListener("resize",n)}}moveToGroup(t=[],e="center",i={x:0,y:0}){if(0===t.length)return;let s=0,n=0,r=0,a=0,o=0;if(t.forEach(t=>{let e,i,h,l;if("string"==typeof t){const s=document.querySelector(t);if(!s)return;{const t=s.getBoundingClientRect();e=t.left,i=t.top,h=t.width,l=t.height}}else{if(void 0===t.x||void 0===t.y)return;e=t.x,i=t.y,h=t.width||0,l=t.height||0}s+=e,n+=i,r=Math.max(r,e+h),a=Math.max(a,i+l),o++}),0===o)return;const h=s/o,l=n/o;let c,u;switch(e){case"center":default:c=h+i.x,u=l+i.y;break;case"left":c=s+i.x,u=l+i.y;break;case"right":c=r+i.x,u=l+i.y;break;case"top":c=h+i.x,u=n+i.y;break;case"bottom":c=h+i.x,u=a+i.y}const d=c-window.innerWidth/2,p=u-window.innerHeight/2;this.positionController.setOffset(d,p,0)}moveToAccessibility(t=[],e="bottom-right",i={}){const s="accessibility",n=()=>{if(!this.isRunning)return;let s,n;switch((window.speechSynthesis||window.webkitSpeechSynthesis)&&i.announce&&t.forEach(t=>{t.condition&&t.condition()&&this.announceToScreenReader(t.text)}),e){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 r=s-window.innerWidth/2,a=n-window.innerHeight/2;this.positionController.setOffset(r,a,0)};return this.responsiveCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(s)}}announceToScreenReader(t){if(window.speechSynthesis){const e=new SpeechSynthesisUtterance(t);e.volume=.5,e.rate=.8,window.speechSynthesis.speak(e)}}setBreakpoints(t){this.breakpoints={...this.breakpoints,...t},this.currentBreakpoint=this.getCurrentBreakpoint()}getCurrentBreakpointName(){return this.currentBreakpoint}isBreakpoint(t){return this.currentBreakpoint===t}stopAllResponsive(){this.isRunning=!1,this.responsiveCallbacks.clear()}destroy(){this.stopAllResponsive(),this.positionController=null}}class xr{constructor(t){this.positionController=t,this.elementTargeting=new ur(t),this.inputTracking=new wr(t),this.physics=new vr(t),this.animation=new Sr(t),this.responsive=new kr(t),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(t,...e){const i=this.methods.get(t);return i?i(...e):null}getAvailableMethods(){return Array.from(this.methods.keys())}hasMethod(t){return this.methods.has(t)}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 Er{constructor(t={}){this.offsetX=t.offsetX||0,this.offsetY=t.offsetY||0,this.offsetZ=t.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=t.onUpdate||(()=>{}),this.onAnimationComplete=t.onAnimationComplete||(()=>{}),this.minScale=t.minScale||.5,this.maxScale=t.maxScale||2,this.zScaleRange=t.zScaleRange||1e3,this.globalScale=1,this.coreScaleOverride=1,this.particleScaleOverride=1,this.positioning=new xr(this),this.elementTargeting=new br(this)}setOffset(t,e,i=0){this.stopAnimation(),this.offsetX=t,this.offsetY=e,this.offsetZ=i,this.onUpdate(this.getEffectiveCenter())}getOffset(){return{x:this.offsetX,y:this.offsetY,z:this.offsetZ}}getPosition(t=window.innerWidth/2,e=window.innerHeight/2){return{x:t+this.offsetX,y:e+this.offsetY,z:this.offsetZ,scale:this.getZScale()}}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){this.stopAnimation(),this.startOffset={x:this.offsetX,y:this.offsetY,z:this.offsetZ},this.targetOffset={x:t,y:e,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 t=e=>{if(!this.isAnimating)return;const i=e-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(t)};this.animationId=requestAnimationFrame(t)}getEffectiveCenter(t=0,e=0){return{x:t+this.offsetX,y:e+this.offsetY,scale:this.getZScale(),coreScale:this.getCoreScale(),particleScale:this.getParticleScale()}}getZScale(){const t=-this.offsetZ/this.zScaleRange,e=Math.max(-1,Math.min(1,t));return this.lerp(this.minScale,this.maxScale,(e+1)/2)*this.globalScale}setGlobalScale(t){this.globalScale=Math.max(.1,t),this.onUpdate(this.getEffectiveCenter())}setScaleOverrides(t){"number"==typeof t?(this.globalScale=Math.max(.1,t),this.coreScaleOverride=1,this.particleScaleOverride=1):(void 0!==t.global&&(this.globalScale=Math.max(.1,t.global)),void 0!==t.core&&(this.coreScaleOverride=Math.max(.1,t.core)),void 0!==t.particles&&(this.particleScaleOverride=Math.max(.1,t.particles))),this.onUpdate(this.getEffectiveCenter())}getCoreScale(){return this.calculateBaseZScale()*this.globalScale*this.coreScaleOverride}getParticleScale(){return this.calculateBaseZScale()*this.globalScale*this.particleScaleOverride}calculateBaseZScale(){const t=-this.offsetZ/this.zScaleRange,e=Math.max(-1,Math.min(1,t));return this.lerp(this.minScale,this.maxScale,(e+1)/2)}lerp(t,e,i){return t+(e-t)*i}applyEasing(t,e){switch(e){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return 1-(1-t)*(1-t);case"easeInOutQuad":return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;case"easeInCubic":return t*t*t;case"easeOutCubic":return 1-Math.pow(1-t,3);case"easeInOutCubic":return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;case"easeInBack":{const e=1.70158;return(e+1)*t*t*t-e*t*t}case"easeOutBack":{const e=1.70158;return 1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}}}getPositioning(){return this.positioning}getElementTargeting(){return this.elementTargeting}callPositioning(t,...e){return this.positioning.call(t,...e)}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 Br{static Ct(){return Br.Tt||(Br.Tt=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}]}]])),Br.Tt}static getSoundConfig(t){return Br.Ct().get(t)||null}}class Ar{constructor(t){this.Pt=t,this.Dt=new Map,this.Rt=t.createGain(),this.Rt.connect(t.destination),this.Ft={},this.zt=0,this.qt=!1,this.Ot=0,this.jt=0,this.It=null,this.$t=null}async addLayer(t,e){let i;try{if(e.src instanceof ArrayBuffer)i=await this.Pt.decodeAudioData(e.src);else if(e.src instanceof Blob){const t=await e.src.arrayBuffer();i=await this.Pt.decodeAudioData(t)}else if("string"==typeof e.src){const t=await fetch(e.src);if(!t.ok)return;const s=await t.arrayBuffer();i=await this.Pt.decodeAudioData(s)}}catch(t){return}if(!i)return;const s=this.Pt.createGain(),n=e.gain??0;s.gain.setValueAtTime(n,this.Pt.currentTime),s.connect(this.Rt),this.Dt.set(t,{buffer:i,gainNode:s,sourceNode:null,loop:e.loop??!0,baseGain:n}),this.Ft[t]=n}removeLayer(t){const e=this.Dt.get(t);if(e){if(e.sourceNode)try{e.sourceNode.stop()}catch{}e.gainNode.disconnect(),this.Dt.delete(t),delete this.Ft[t]}}play(t=0){this.qt&&this.stop();const e=t/1e3;this.Ot=e,this.jt=this.Pt.currentTime,this.qt=!0;for(const[,t]of this.Dt){const i=this.Pt.createBufferSource();i.buffer=t.buffer,i.loop=t.loop,i.connect(t.gainNode),i.start(0,e),t.sourceNode=i}}pause(){this.qt&&(this.Ot+=this.Pt.currentTime-this.jt,this.Lt(),this.qt=!1)}stop(){this.Lt(),this.qt=!1,this.Ot=0}Lt(){for(const[,t]of this.Dt)if(t.sourceNode){try{t.sourceNode.stop()}catch{}t.sourceNode=null}}setMix(t){const e=this.Pt.currentTime;for(const[i,s]of Object.entries(t)){const t=this.Dt.get(i);t&&(t.gainNode.gain.setValueAtTime(Math.max(0,Math.min(1,s)),e),this.Ft[i]=s)}}crossfadeTo(t,e=1e3){++this.zt;const i=this.Pt.currentTime,s=e/1e3;for(const[e,n]of Object.entries(t)){const t=this.Dt.get(e);if(t){const r=Math.max(1e-4,Math.min(1,n));t.gainNode.gain.setValueAtTime(t.gainNode.gain.value||1e-4,i),t.gainNode.gain.linearRampToValueAtTime(r,i+s),this.Ft[e]=n}}return new Promise(t=>{setTimeout(()=>{this.zt,t()},e)})}setEmotionModulation(t){this.It=t}applyEmotionState(t){if(!this.It||!t?.dominant)return;const e={},i=this.It[t.dominant.emotion];if(i)for(const[s,n]of Object.entries(i))e[s]=(e[s]||0)+n*t.dominant.intensity;for(const i of t.undercurrents||[]){const t=this.It[i.emotion];if(t)for(const[s,n]of Object.entries(t))e[s]=(e[s]||0)+n*i.intensity*.25}const s={...this.Ft};for(const[t,i]of Object.entries(e))t in s&&(s[t]=Math.max(0,Math.min(1,s[t]+i)));this.setMix(s)}syncToBPM(t,e){if(e&&(this.$t=e),!this.$t)return;const i=t/this.$t;for(const[,t]of this.Dt)t.sourceNode&&(t.sourceNode.playbackRate.value=i)}setMasterVolume(t){this.Rt.gain.setValueAtTime(Math.max(0,Math.min(1,t)),this.Pt.currentTime)}getLayerNames(){return[...this.Dt.keys()]}getCurrentMix(){return{...this.Ft}}isPlaying(){return this.qt}destroy(){this.stop();for(const[,t]of this.Dt)t.gainNode.disconnect();this.Dt.clear(),this.Rt.disconnect()}}class Cr{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 t=window.AudioContext||window.webkitAudioContext;return!!t&&(this.context=new t,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(t,e=null){this.masterVolume=Math.max(0,Math.min(1,t)),this.isEnabled&&this.nodes.master&&(this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),e&&this.updateAmbientVolume(e))}getMasterVolume(){return this.masterVolume}isAvailable(){return this.isEnabled&&this.isInitialized}getAudioLayerManager(){return this.isAvailable()?(this.Gt||(this.Gt=new Ar(this.context)),this.Gt):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.Gt&&(this.Gt.destroy(),this.Gt=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(t){return this.emotionalTones.get(t)||null}setAmbientTone(t,e=500){if(!this.isAvailable())return;const i=this.getEmotionalTone(t);if(i)try{this.resumeContext();const{currentTime:t}=this.context,s=e/1e3;this.currentOscillator&&this.currentGain&&(this.currentGain.gain.exponentialRampToValueAtTime(.001,t+.5*s),this.currentOscillator.stop(t+.5*s));const n=this.context.createOscillator(),r=this.context.createGain();n.type=i.waveform,n.frequency.setValueAtTime(i.frequency,t);const a=i.volume*this.masterVolume;r.gain.setValueAtTime(.001,t),r.gain.exponentialRampToValueAtTime(a,t+s),n.connect(r),r.connect(this.nodes.master),n.start(t),this.currentOscillator=n,this.currentGain=r}catch{}}stopAmbientTone(t=500){if(this.isAvailable()&&this.currentOscillator)try{const{currentTime:e}=this.context,i=t/1e3;this.currentGain&&this.currentGain.gain.exponentialRampToValueAtTime(.001,e+i),this.currentOscillator.stop(e+i),this.currentOscillator=null,this.currentGain=null}catch{}}updateAmbientVolume(t){if(!this.isAvailable()||!this.currentGain||!t)return;const e=this.getEmotionalTone(t);if(e)try{const t=e.volume*this.masterVolume,{currentTime:i}=this.context;this.currentGain.gain.exponentialRampToValueAtTime(t,i+.1)}catch{}}playGestureSound(t,e="neutral"){if(!this.isAvailable())return;const i=this.getGestureSoundConfig(t);if(i)try{this.resumeContext();const{currentTime:t}=this.context,s=i.duration/1e3,n=this.getEmotionalModifiers(e),r=i.volume*this.masterVolume*n.intensity,a=this.context.createOscillator(),o=this.context.createGain();a.type=i.waveform,this.applyFrequencyEnvelope(a,i.frequencyEnvelope,t,s),this.applyVolumeEnvelope(o,i.volumeEnvelope,t,s,r),a.connect(o),o.connect(this.nodes.effects),a.start(t),a.stop(t+s)}catch{}else this.throttledWarn(`Unknown gesture "${t}", cannot play sound`,`gesture_${t}`)}getGestureSoundConfig(t){return Br.getSoundConfig(t)}applyFrequencyEnvelope(t,e,i,s){e.forEach(e=>{const n=i+e.time*s;t.frequency.linearRampToValueAtTime(e.frequency,n)})}applyVolumeEnvelope(t,e,i,s,n){e.forEach((e,r)=>{const a=i+e.time*s,o=e.volume*n;0===r?t.gain.setValueAtTime(o,a):t.gain.linearRampToValueAtTime(o,a)})}getEmotionalModifiers(t){return this.emotionalModifiers.get(t)||this.emotionalModifiers.get("neutral")}setQualityReduction(t){this.qualityReduction=t,t&&this.audioContext?this.maxOscillators=2:this.maxOscillators=4}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}throttledWarn(t,e){const i=Date.now();if(i-(this.warningTimestamps[e]||0)>this.warningThrottle){if(Object.keys(this.warningTimestamps).length>=this.maxWarningKeys){const t=this.warningAccessOrder.shift();delete this.warningTimestamps[t]}this.warningTimestamps[e]=i;const t=this.warningAccessOrder.indexOf(e);-1!==t&&this.warningAccessOrder.splice(t,1),this.warningAccessOrder.push(e)}}}class Tr{constructor(){this._t=120,this.Ht=new Float64Array(this._t),this.Ut=0,this.Wt=0,this.fps=0,this.smoothedFPS=0,this.smoothingFactor=.9,this.lastFrameTime=0,this.frameTime=0,this.maxFrameTimeSamples=10,this.Yt=new Float64Array(this.maxFrameTimeSamples),this.Xt=0,this.Vt=0,this.averageFrameTime=0}update(t){this.Ht[this.Ut]=t,this.Ut=(this.Ut+1)%this._t,this.Wt<this._t&&this.Wt++;const e=t-1e3;let i=0;for(let t=0;t<this.Wt;t++)this.Ht[t]>e&&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=t-this.lastFrameTime,this.Yt[this.Xt]=this.frameTime,this.Xt=(this.Xt+1)%this.maxFrameTimeSamples,this.Vt<this.maxFrameTimeSamples&&this.Vt++,this.Vt>0)){let t=0;for(let e=0;e<this.Vt;e++)t+=this.Yt[e];this.averageFrameTime=t/this.Vt}this.lastFrameTime=t}getFPS(){return Math.round(this.fps)}getSmoothedFPS(){return Math.round(this.smoothedFPS)}getFrameTime(){return this.frameTime}getAverageFrameTime(){return this.averageFrameTime}reset(){this.Ht.fill(0),this.Ut=0,this.Wt=0,this.fps=0,this.smoothedFPS=0,this.lastFrameTime=0,this.frameTime=0,this.Yt.fill(0),this.Xt=0,this.Vt=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 Pr{constructor(t,e={}){this.errorBoundary=t,this.config=e,this.config.targetFPS=e.targetFPS||60,this.loopManager=e.loopManager||er,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 Tr,this.subsystems={},this.eventCallback=null,this.parentMascot=null}setSubsystems(t){this.subsystems={stateMachine:t.stateMachine,particleSystem:t.particleSystem,renderer:t.renderer,soundSystem:t.soundSystem,canvasManager:t.canvasManager};const e=["stateMachine","particleSystem","renderer"];for(const t of e)if(!this.subsystems[t])throw new Error(`Required subsystem '${t}' not provided`);this.performanceMonitor&&this.performanceMonitor.setSubsystems(this.subsystems)}setEventCallback(t){if("function"!=typeof t)throw new Error("Event callback must be a function");this.eventCallback=t}setParentMascot(t){this.parentMascot=t}emit(t,e=null){this.eventCallback&&this.eventCallback(t,e)}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((t,e)=>this.animate(t,e),0,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 t=performance.now(),e=t-this.pauseTime;this.lastFrameTime=t,this.frameTimeAccumulator=0,this.fpsCounter&&this.fpsCounter.reset(),this.subsystems?.particleSystem&&this.subsystems.particleSystem.onVisibilityResume(e,this.pausedParticleCount),this.renderer&&(e>Xs&&this.renderer.resetCanvasContext(),this.renderer.gestureAnimator&&this.renderer.gestureAnimator.resumeAnimation?.(),e>Xs&&(this.renderer.forceCleanRender=!0)),this.subsystems?.stateMachine&&(this.subsystems.stateMachine.lastUpdateTime=t),this.parentMascot?.resume&&this.parentMascot.resume(),this.isPaused=!1}}animate(t,e){if(!this.isRunning||this.isPaused)return;const i=e||performance.now();this.deltaTime=t||i-this.lastFrameTime,this.deltaTime>20&&(this.deltaTime=20),this.deltaTime>Ys&&this.deltaTime<20&&(this.deltaTime=Ys),this.lastFrameTime=i,this.deltaTime*=this.speedMultiplier,this.update(this.deltaTime),this.render()}update(t){if(this.subsystems.stateMachine&&this.subsystems.stateMachine.update(t),this.parentMascot?.stateCoordinator?.Nt&&this.parentMascot.stateCoordinator.Nt.update(t),this.parentMascot&&"function"==typeof this.parentMascot.update&&this.parentMascot.update(t),"classic"!==this.parentMascot?.config?.renderingStyle&&this.subsystems.particleSystem&&this.subsystems.stateMachine&&this.subsystems.canvasManager){const e=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 t=this.subsystems.renderer.getCurrentGesture();t&&t.particleMotion&&(s=t.particleMotion,n=t.progress||0)}this.subsystems.particleSystem.spawn(e.particleBehavior,this.subsystems.stateMachine.getCurrentState().emotion,e.particleRate,i.x,i.y,t),this.subsystems.particleSystem.update(t,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 t=this.fpsCounter?this.fpsCounter.getMetrics():{};return{fps:t.fps||60,instantFps:t.smoothedFPS||60,frameTime:t.frameTime||16.67,averageFrameTime:t.averageFrameTime||16.67,isRunning:this.isRunning,deltaTime:this.deltaTime}}setTargetFPS(t){}get targetFPS(){return this.config.targetFPS||60}setSpeedMultiplier(t){this.speedMultiplier=Math.max(.1,Math.min(10,t))}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 Dr{constructor(t={}){this.config={spikeThreshold:t.spikeThreshold||1.5,minimumSpikeLevel:t.minimumSpikeLevel||.1,spikeMinInterval:t.spikeMinInterval||1e3,historySize:t.historySize||10,smoothingTimeConstant:t.smoothingTimeConstant||.8,fftSize:t.fftSize||256,levelUpdateThrottle:t.levelUpdateThrottle||100,...t},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(t){try{if(!t)throw new Error("AudioContext is required for audio level processing");if("function"!=typeof t.createAnalyser)throw new Error("Invalid AudioContext provided");return this.audioContext=t,this.analyser=t.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"===t.state&&t.resume().catch(t=>{this.emitError("Failed to resume AudioContext",t)}),!0}catch(t){return this.emitError("Failed to initialize AudioLevelProcessor",t),!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(t){this.emitError("Error during AudioLevelProcessor cleanup",t)}}updateAudioLevel(t=16){if(this.isActive&&this.analyser&&this.dataArray)try{this.analyser.getByteFrequencyData(this.dataArray);const t=this.calculateRMS();this.currentLevel=Math.min(1,2*t),this.updateLevelHistory(),this.detectVolumeSpikes(),this.emitLevelUpdate()}catch(t){this.emitError("Error updating audio level",t),this.currentLevel=0}}calculateRMS(){if(!this.dataArray||0===this.dataArray.length)return 0;let t=0;for(let e=0;e<this.dataArray.length;e++){const i=this.dataArray[e]/255;t+=i*i}return Math.sqrt(t/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 t=performance.now();if(t-this.lastVolumeSpike<this.config.spikeMinInterval)return;const e=this.levelHistory.slice(0,-1),i=e.reduce((t,e)=>t+e,0)/e.length;this.currentLevel>=i*this.config.spikeThreshold&&i>=this.config.minimumSpikeLevel&&this.currentLevel>=2*this.config.minimumSpikeLevel&&(this.lastVolumeSpike=t,this.emitVolumeSpike({level:this.currentLevel,previousAverage:i,spikeRatio:this.currentLevel/i,timestamp:t,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(t){if("function"!=typeof t)throw new Error("Level update callback must be a function");this.callbacks.levelUpdate=t}onVolumeSpike(t){if("function"!=typeof t)throw new Error("Volume spike callback must be a function");this.callbacks.volumeSpike=t}onError(t){if("function"!=typeof t)throw new Error("Error callback must be a function");this.callbacks.error=t}removeAllCallbacks(){this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}updateConfig(t){this.config={...this.config,...t},this.analyser&&(t.fftSize&&(this.analyser.fftSize=this.config.fftSize,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount)),void 0!==t.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((t,e)=>t+e,0)/this.levelHistory.length:0}}emitLevelUpdate(){const t=performance.now();if(!(t-this.lastLevelEmit<this.config.levelUpdateThrottle)&&(this.lastLevelEmit=t,this.callbacks.levelUpdate))try{this.callbacks.levelUpdate({level:this.currentLevel,rawData:this.getFrequencyData(),timestamp:t,history:this.getLevelHistory()})}catch{}}emitVolumeSpike(t){if(this.callbacks.volumeSpike)try{this.callbacks.volumeSpike(t)}catch{}}emitError(t,e){if(this.callbacks.error)try{this.callbacks.error({message:t,error:e,timestamp:performance.now()})}catch{}}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}}class Rr{constructor(t={}){this.config={enableReducedMotion:!1!==t.enableReducedMotion,enableHighContrast:!1!==t.enableHighContrast,enableScreenReaderSupport:!1!==t.enableScreenReaderSupport,enableKeyboardNavigation:!1!==t.enableKeyboardNavigation,enableFocusIndicators:!1!==t.enableFocusIndicators,announceStateChanges:!1!==t.announceStateChanges,colorBlindMode:t.colorBlindMode||"none",...t},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 t=window.matchMedia("(prefers-reduced-motion: reduce)");this.reducedMotionPreferred=t.matches}if(this.config.enableHighContrast&&window.matchMedia){const t=window.matchMedia("(prefers-contrast: high)");if(this.highContrastEnabled=t.matches,!this.highContrastEnabled){const t=window.matchMedia("(-ms-high-contrast: active)");this.highContrastEnabled=t.matches}}this.detectScreenReader()}detectScreenReader(){const t=document.querySelector("[aria-live]"),e=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=!!(t||e||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.Qt=window.matchMedia("(prefers-reduced-motion: reduce)"),this.Jt=t=>{this.reducedMotionPreferred=t.matches,this.onPreferenceChange("reducedMotion",t.matches)},this.Qt.addEventListener?this.Qt.addEventListener("change",this.Jt):this.Qt.addListener&&this.Qt.addListener(this.Jt),this.Kt=window.matchMedia("(prefers-contrast: high)"),this.Zt=t=>{this.highContrastEnabled=t.matches,this.onPreferenceChange("highContrast",t.matches)},this.Kt.addEventListener?this.Kt.addEventListener("change",this.Zt):this.Kt.addListener&&this.Kt.addListener(this.Zt))}handleKeyDown(t){if(this.config.enableKeyboardNavigation){switch(t.key){case"Tab":t.preventDefault(),this.navigateFocus(t.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(t.key)}this.keyboardNavigationActive=!0}}handleKeyUp(t){}navigateFocus(t){const e=Array.from(this.focusableElements.values());if(0===e.length)return;this.currentFocusIndex+=t,this.currentFocusIndex<0?this.currentFocusIndex=e.length-1:this.currentFocusIndex>=e.length&&(this.currentFocusIndex=0);const i=e[this.currentFocusIndex];this.setFocus(i),i.label&&this.announce(`Focused on ${i.label}`)}handleArrowNavigation(t){const e={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}}[t];e&&this.onArrowNavigation&&this.onArrowNavigation(e)}registerFocusableElement(t,e){this.focusableElements.set(t,{id:t,label:e.label||t,bounds:e.bounds||null,action:e.action||null,type:e.type||"button"})}unregisterFocusableElement(t){this.focusableElements.delete(t)}setFocus(t){this.onFocusChange&&this.onFocusChange(t),this.focusHistory.push(t.id),this.focusHistory.length>10&&this.focusHistory.shift()}clearFocus(){this.currentFocusIndex=-1,this.onFocusChange&&this.onFocusChange(null),this.announce("Focus cleared")}activateCurrentFocus(){const t=Array.from(this.focusableElements.values());if(this.currentFocusIndex>=0&&this.currentFocusIndex<t.length){const e=t[this.currentFocusIndex];e.action&&(e.action(),this.announce(`Activated ${e.label}`))}}announce(t,e="polite"){this.config.enableScreenReaderSupport&&this.liveRegion&&(this.announcementQueue.push({message:t,priority:e}),this.processAnnouncementQueue())}processAnnouncementQueue(){if(0===this.announcementQueue.length)return;const{message:t,priority:e}=this.announcementQueue.shift();this.liveRegion.setAttribute("aria-live",e),this.liveRegion.textContent=t,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent=""),this.announcementQueue.length>0&&this.processAnnouncementQueue()},100)}getAnimationSettings(t={}){return this.reducedMotionPreferred?{...t,duration:t.duration?.5*t.duration:0,iterations:1,easing:"linear",particlesEnabled:!1,complexAnimations:!1,autoPlay:!1}:t}getColorScheme(t={}){return this.colorSchemes.normal||(this.colorSchemes.normal={...t}),this.highContrastEnabled?this.colorSchemes.highContrast:"none"!==this.currentColorBlindMode&&this.colorSchemes[this.currentColorBlindMode]?this.colorSchemes[this.currentColorBlindMode]:t}getStatePattern(t){return"none"===this.currentColorBlindMode?this.patterns.solid:this.statePatterns[t]||this.patterns.solid}applyPatternOverlay(t,e,i){if(e===this.patterns.solid)return;t.save();const s=document.createElement("canvas"),n=s.getContext("2d");switch(e){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 r=t.createPattern(s,"repeat");t.fillStyle=r,t.globalAlpha=.3,t.fillRect(i.x,i.y,i.width,i.height),t.restore()}createDotPattern(t,e){e.width=10,e.height=10,t.fillStyle="white",t.beginPath(),t.arc(5,5,2,0,2*Math.PI),t.fill()}createStripePattern(t,e){e.width=10,e.height=10,t.strokeStyle="white",t.lineWidth=2,t.beginPath(),t.moveTo(0,10),t.lineTo(10,0),t.stroke()}createCrosshatchPattern(t,e){e.width=10,e.height=10,t.strokeStyle="white",t.lineWidth=1,t.beginPath(),t.moveTo(0,10),t.lineTo(10,0),t.stroke(),t.beginPath(),t.moveTo(0,0),t.lineTo(10,10),t.stroke()}setColorBlindMode(t){["none","protanopia","deuteranopia","tritanopia"].includes(t)&&(this.currentColorBlindMode=t,this.announce(`Color blind mode set to ${t}`),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(t,e){this.announce(`${t} is now ${e?"enabled":"disabled"}`),"reducedMotion"===t&&this.onReducedMotionChange&&this.onReducedMotionChange(e),"highContrast"===t&&this.onHighContrastChange&&this.onHighContrastChange(e)}createStateDescription(t){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"}[t.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.Qt&&this.Jt&&(this.Qt.removeEventListener?this.Qt.removeEventListener("change",this.Jt):this.Qt.removeListener&&this.Qt.removeListener(this.Jt),this.Qt=null,this.Jt=null),this.Kt&&this.Zt&&(this.Kt.removeEventListener?this.Kt.removeEventListener("change",this.Zt):this.Kt.removeListener&&this.Kt.removeListener(this.Zt),this.Kt=null,this.Zt=null),this.liveRegion&&this.liveRegion.parentNode&&this.liveRegion.parentNode.removeChild(this.liveRegion),this.focusableElements.clear(),this.announcementQueue=[],this.focusHistory=[]}}class Fr{constructor(t={}){this.config={enableTouchOptimization:!1!==t.enableTouchOptimization,enableViewportHandling:!1!==t.enableViewportHandling,enableBatteryOptimization:!1!==t.enableBatteryOptimization,enableOrientationSupport:!1!==t.enableOrientationSupport,enableResponsiveScaling:!1!==t.enableResponsiveScaling,touchSensitivity:t.touchSensitivity||1,doubleTapDelay:t.doubleTapDelay||300,swipeThreshold:t.swipeThreshold||50,pinchThreshold:t.pinchThreshold||.1,...t},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=t=>t.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 t=navigator.userAgent.toLowerCase(),e=["android","iphone","ipod","windows phone","blackberry"].some(e=>t.includes(e)),i=window.innerWidth<=768,s="ontouchstart"in window||navigator.maxTouchPoints>0;return e||i&&s}detectTablet(){const t=navigator.userAgent.toLowerCase(),e=/ipad/.test(t),i=/android/.test(t)&&!/mobile/.test(t),s=/windows/.test(t)&&/touch/.test(t),n=window.innerWidth>768&&window.innerWidth<=1024,r="ontouchstart"in window||navigator.maxTouchPoints>0;return e||i||s||n&&r}detectTouch(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0}supportsOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}setupTouchHandlers(){const t=this.getCanvas();t&&(t.style.touchAction="none",t.style.userSelect="none",t.style.webkitUserSelect="none",t.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),t.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),t.addEventListener("touchend",this.handleTouchEnd,{passive:!1}),t.addEventListener("touchcancel",this.handleTouchCancel,{passive:!1}),t.addEventListener("contextmenu",this.handleContextMenu))}setupViewportHandlers(){window.addEventListener("resize",this.handleViewportChange),window.addEventListener("orientationchange",this.handleOrientationChange),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.setupViewportMeta()}setupViewportMeta(){let t=document.querySelector('meta[name="viewport"]');t||(t=document.createElement("meta"),t.name="viewport",document.head.appendChild(t)),t.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"}async setupBatteryMonitoring(){if(navigator.getBattery)try{const t=await navigator.getBattery();this.batteryRef=t,this.batteryLevel=t.level,this.isCharging=t.charging,this.boundBatteryLevelChange=()=>{this.batteryLevel=t.level,this.onBatteryChange()},this.boundBatteryChargingChange=()=>{this.isCharging=t.charging,this.onBatteryChange()},t.addEventListener("levelchange",this.boundBatteryLevelChange),t.addEventListener("chargingchange",this.boundBatteryChargingChange),this.onBatteryChange()}catch{}}setupOrientationHandlers(){window.DeviceOrientationEvent&&(this.te=t=>{this.handleDeviceOrientation(t)},window.addEventListener("deviceorientation",this.te))}handleTouchStart(t){t.cancelable&&t.preventDefault();const e=Date.now();this.gestureStartTime=e;for(const i of t.touches)this.touches.set(i.identifier,{id:i.identifier,startX:i.clientX,startY:i.clientY,currentX:i.clientX,currentY:i.clientY,startTime:e});1===t.touches.length?this.handleSingleTouchStart(t.touches[0]):2===t.touches.length&&this.handleMultiTouchStart(t.touches),this.emitTouchEvent("touchStart",{touches:Array.from(this.touches.values()),timestamp:e})}handleSingleTouchStart(t){const e=Date.now();e-this.lastTapTime<this.config.doubleTapDelay?this.tapCount++:this.tapCount=1,this.lastTapTime=e,this.touchStartPosition={x:t.clientX,y:t.clientY}}handleMultiTouchStart(t){if(2===t.length){const e=t[0],i=t[1];this.lastPinchDistance=this.getDistance(e.clientX,e.clientY,i.clientX,i.clientY),this.lastRotation=this.getAngle(e.clientX,e.clientY,i.clientX,i.clientY),this.isPinching=!0}}handleTouchMove(t){t.cancelable&&t.preventDefault();for(const e of t.touches){const t=this.touches.get(e.identifier);t&&(t.currentX=e.clientX,t.currentY=e.clientY)}1===t.touches.length?this.handleSingleTouchMove(t.touches[0]):2===t.touches.length&&this.handleMultiTouchMove(t.touches),this.emitTouchEvent("touchMove",{touches:Array.from(this.touches.values()),gesture:this.currentGesture})}handleSingleTouchMove(t){const e=this.touches.get(t.identifier);if(!e)return;const i=t.clientX-e.startX,s=t.clientY-e.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(t){if(2!==t.length)return;const e=t[0],i=t[1],s=this.getDistance(e.clientX,e.clientY,i.clientX,i.clientY),n=s-this.lastPinchDistance,r=s/this.lastPinchDistance;Math.abs(n)>this.config.pinchThreshold&&(this.currentGesture=r>1?"pinchOut":"pinchIn",this.emitTouchEvent("pinch",{scale:r,delta:n}));const a=this.getAngle(e.clientX,e.clientY,i.clientX,i.clientY),o=a-this.lastRotation;Math.abs(o)>5&&(this.currentGesture="rotate",this.emitTouchEvent("rotate",{angle:a,delta:o})),this.lastPinchDistance=s,this.lastRotation=a}handleTouchEnd(t){t.cancelable&&t.preventDefault();const e=Date.now();for(const i of t.changedTouches){const t=this.touches.get(i.identifier);if(t){const s=e-t.startTime,n=t.currentX-t.startX,r=t.currentY-t.startY,a=Math.sqrt(n*n+r*r);s<300&&a<10&&(2===this.tapCount?(this.emitTouchEvent("doubleTap",{x:t.currentX,y:t.currentY}),this.tapCount=0):this.emitTouchEvent("tap",{x:t.currentX,y:t.currentY})),s>500&&a<10&&this.emitTouchEvent("longPress",{x:t.currentX,y:t.currentY}),this.touches.delete(i.identifier)}}0===t.touches.length&&(this.currentGesture=null,this.isPinching=!1,this.isRotating=!1),this.emitTouchEvent("touchEnd",{gesture:this.currentGesture,duration:e-this.gestureStartTime})}handleTouchCancel(t){this.touches.clear(),this.currentGesture=null,this.isPinching=!1,this.isRotating=!1,this.emitTouchEvent("touchCancel",{})}handleOrientationChange(t){this.orientation=this.getOrientation(),this.emitTouchEvent("orientationChange",{orientation:this.orientation,angle:window.orientation||0}),this.applyOrientationOptimizations()}handleDeviceOrientation(t){const{alpha:e,beta:i,gamma:s}=t;this.emitTouchEvent("deviceOrientation",{alpha:e,beta:i,gamma:s})}handleViewportChange(t){const e=Date.now();e-this.lastViewportChange<100||(this.lastViewportChange=e,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(t){const e=!document.hidden;this.emitTouchEvent("visibilityChange",{visible:e}),!e&&this.config.enableBatteryOptimization?this.applyBackgroundOptimizations():this.restorePerformance()}getOrientation(){return window.innerWidth>window.innerHeight?"landscape":"portrait"}getDistance(t,e,i,s){const n=i-t,r=s-e;return Math.sqrt(n*n+r*r)}getAngle(t,e,i,s){return 180*Math.atan2(s-e,i-t)/Math.PI}applyMobileOptimizations(){if(!this.isMobile&&!this.isTablet)return;const t={...this.mobilePerformanceSettings,canvasScale:this.calculateOptimalCanvasScale(),useWebGL:!1,useOffscreenCanvas:this.useOffscreenCanvas};return this.emitTouchEvent("mobileOptimizations",t),t}applyOrientationOptimizations(){const t="landscape"===this.orientation,e={layoutMode:t?"horizontal":"vertical",particleDirection:t?"horizontal":"vertical",uiScale:t?.8:1};return this.emitTouchEvent("orientationOptimizations",e),e}applyResponsiveScaling(){const t=Math.min(this.viewportSize.width/375,2);return this.canvasScale=t,this.emitTouchEvent("responsiveScale",{scale:this.canvasScale,viewport:this.viewportSize}),this.canvasScale}applyBackgroundOptimizations(){const t={targetFPS:5,particlesEnabled:!1,animationsEnabled:!1,audioEnabled:!1};return this.emitTouchEvent("backgroundOptimizations",t),t}restorePerformance(){const t=this.applyMobileOptimizations();return this.emitTouchEvent("performanceRestore",t),t}onBatteryChange(){if(this.lowPowerMode=this.batteryLevel<.2&&!this.isCharging,this.lowPowerMode){const t={targetFPS:15,maxParticles:5,reducedEffects:!0,audioEnabled:!1};this.emitTouchEvent("lowPowerMode",{batteryLevel:this.batteryLevel,isCharging:this.isCharging,optimizations:t})}}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(t){this.canvas=t,this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers()}emitTouchEvent(t,e){this.onTouchEvent&&this.onTouchEvent(t,e)}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 t=this.getCanvas();t&&(t.removeEventListener("touchstart",this.handleTouchStart),t.removeEventListener("touchmove",this.handleTouchMove),t.removeEventListener("touchend",this.handleTouchEnd),t.removeEventListener("touchcancel",this.handleTouchCancel),t.removeEventListener("contextmenu",this.handleContextMenu)),window.removeEventListener("resize",this.handleViewportChange),window.removeEventListener("orientationchange",this.handleOrientationChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.te&&(window.removeEventListener("deviceorientation",this.te),this.te=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 zr{constructor(t={}){this.config={enablePlugins:!1!==t.enablePlugins,validatePlugins:!1!==t.validatePlugins,sandboxPlugins:!1!==t.sandboxPlugins,maxPlugins:t.maxPlugins||50,pluginTimeout:t.pluginTimeout||5e3,allowOverrides:!1!==t.allowOverrides},this.mascot=t.mascot||null,this.plugins=new Map,this.pluginTypes=["emotion","gesture","particle","audio","renderer","animation"],this.pluginsByType=new Map(this.pluginTypes.map(t=>[t,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 t=new Map,e={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 t.set("emotion",{...e,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}}),t.set("gesture",{...e,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}}),t.set("particle",{...e,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}}),t.set("audio",{...e,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}}),t}createSandbox(){return{Math:Math,Date:Date,JSON:JSON,console:{log:(...t)=>null,warn:(...t)=>null,error:(...t)=>null},window:void 0,document:void 0,localStorage:void 0,sessionStorage:void 0,fetch:void 0,XMLHttpRequest:void 0,api:this.pluginAPI}}async registerPlugin(t){if(!this.config.enablePlugins)return!1;if(this.plugins.size>=this.config.maxPlugins)return!1;if(this.config.validatePlugins&&!this.validatePlugin(t).valid)return!1;if(this.checkConflicts(t).length>0&&!this.config.allowOverrides)return!1;if(!(await this.resolveDependencies(t)).resolved)return!1;try{this.loadingPlugins.add(t.name);const e=this.config.sandboxPlugins?this.sandbox:window;if(!await this.initializePlugin(t,e))throw new Error("Plugin initialization failed");return this.plugins.set(t.name,t),this.pluginsByType.get(t.type).add(t.name),this.pluginStates.set(t.name,"active"),this.activePlugins.add(t.name),t.dependencies&&(this.dependencies.set(t.name,t.dependencies),this.updateDependencyGraph(t.name,t.dependencies)),t.hooks&&Object.entries(t.hooks).forEach(([e,i])=>{this.registerHook(e,i,t.name)}),this.emitPluginEvent("pluginRegistered",{name:t.name,type:t.type,version:t.version}),!0}catch(t){return!1}finally{this.loadingPlugins.delete(t.name)}}validatePlugin(t){const e=[];if(t.name&&"string"==typeof t.name||e.push("Plugin must have a valid name"),t.type&&this.pluginTypes.includes(t.type)||e.push(`Plugin type must be one of: ${this.pluginTypes.join(", ")}`),t.version&&"string"==typeof t.version||e.push("Plugin must have a version"),"function"!=typeof t.init&&e.push("Plugin must have an init function"),"function"!=typeof t.destroy&&e.push("Plugin must have a destroy function"),t.type&&this.validationSchemas.has(t.type)){const i=this.validationSchemas.get(t.type),s=this.validateAgainstSchema(t,i);e.push(...s)}return{valid:0===e.length,errors:e}}validateAgainstSchema(t,e){const i=[];return Object.entries(e).forEach(([e,s])=>{if(s.required&&!(e in t)&&i.push(`Missing required property: ${e}`),e in t){const n=t[e];if(s.type&&typeof n!==s.type&&i.push(`Property ${e} must be of type ${s.type}`),s.enum&&!s.enum.includes(n)&&i.push(`Property ${e} must be one of: ${s.enum.join(", ")}`),s.properties&&"object"==typeof n){const t=this.validateAgainstSchema(n,s.properties);i.push(...t.map(t=>`${e}.${t}`))}}}),i}checkConflicts(t){const e=[];return t.conflicts&&t.conflicts.forEach(t=>{this.plugins.has(t)&&e.push(t)}),"emotion"!==t.type&&"gesture"!==t.type||this.plugins.forEach(i=>{if(i.type===t.type){const s=i[t.type]?.name,n=t[t.type]?.name;s===n&&e.push(`${t.type} name collision: ${n}`)}}),e}async resolveDependencies(t){if(!t.dependencies||0===t.dependencies.length)return{resolved:!0,missing:[]};const e=[];for(const i of t.dependencies)this.plugins.has(i)||await this.tryLoadDependency(i)||e.push(i);return{resolved:0===e.length,missing:e}}tryLoadDependency(t){return this.plugins.has(t)}updateDependencyGraph(t,e){this.dependencyGraph.set(t,new Set(e)),e.forEach(t=>{this.dependencyGraph.has(t)||this.dependencyGraph.set(t,new Set)})}async initializePlugin(t,e){try{const i=new Promise((t,e)=>{setTimeout(()=>e(new Error("Plugin initialization timeout")),this.config.pluginTimeout)}),s=t.init.bind(e);return!1!==await Promise.race([s(this.pluginAPI),i])}catch(t){return!1}}async unregisterPlugin(t){const e=this.plugins.get(t);if(!e)return!1;if(this.getDependentPlugins(t).length>0)return!1;try{return"function"==typeof e.destroy&&await e.destroy(),this.plugins.delete(t),this.pluginsByType.get(e.type).delete(t),this.pluginStates.delete(t),this.activePlugins.delete(t),this.dependencies.delete(t),this.dependencyGraph.delete(t),this.hooks.forEach(e=>{e.forEach(i=>{i.pluginName===t&&e.delete(i)})}),this.emitPluginEvent("pluginUnregistered",{name:t}),!0}catch(t){return!1}}getDependentPlugins(t){const e=[];return this.dependencies.forEach((i,s)=>{i.includes(t)&&e.push(s)}),e}registerHook(t,e,i){this.hooks.has(t)||this.hooks.set(t,new Set),this.hooks.get(t).add({handler:e,pluginName:i})}async executeHooks(t,e){const i=this.hooks.get(t);if(!i||0===i.size)return[];const s=[];for(const t of i)try{const i=await t.handler(e);s.push({pluginName:t.pluginName,result:i})}catch(t){}return s}getPlugin(t){return this.plugins.get(t)||null}hasPlugin(t){return this.plugins.has(t)}getPluginsByType(t){const e=this.pluginsByType.get(t);return e?Array.from(e).map(t=>this.plugins.get(t)):[]}enablePlugin(t){if(!this.plugins.has(t))return;this.pluginStates.set(t,"active"),this.activePlugins.add(t);const e=this.plugins.get(t);e.onEnable&&e.onEnable(),this.emitPluginEvent("pluginEnabled",{name:t})}disablePlugin(t){if(!this.plugins.has(t))return;this.getDependentPlugins(t),this.pluginStates.set(t,"disabled"),this.activePlugins.delete(t);const e=this.plugins.get(t);e.onDisable&&e.onDisable(),this.emitPluginEvent("pluginDisabled",{name:t})}emitPluginEvent(t,e){this.onPluginEvent&&this.onPluginEvent(t,e)}onPluginEvent(t,e){}logFromPlugin(t,...e){}errorFromPlugin(t,...e){}setPluginState(t,e,i){this.pluginStates.has(t)||this.pluginStates.set(t,{});const s=this.pluginStates.get(t);"object"==typeof s&&(s[e]=i)}getPluginState(t,e){const i=this.pluginStates.get(t);if("object"==typeof i)return i[e]}overrideConflict(t,e){return e}mergeConflict(t,e){return{...t,...e}}rejectConflict(t,e){return t}queueConflict(t,e){return[t,e]}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(([t,e])=>[t,e.size])),hooks:Object.fromEntries(Array.from(this.hooks.entries()).map(([t,e])=>[t,e.size]))}}update(t,e){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(t,e)}catch(t){this.errorFromPlugin(i,"Update error:",t)}}}render(t,e){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(t,e)}catch(t){this.errorFromPlugin(i,"Render error:",t)}}}async destroy(){const t=Array.from(this.plugins.keys());for(const e of t)await this.unregisterPlugin(e);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 qr{constructor(){if(qr.ee)return this.features=qr.ee,void(this.capabilities=qr.ie);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(),qr.ee=this.features,qr.ie=this.capabilities}detectWebAudio(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectCanvas2D(){try{const t=document.createElement("canvas");return!(!t.getContext||!t.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 t=Object.values(this.features).filter(Boolean).length,e=Object.keys(this.features).length,i=t/e*100;let s="basic";return i>=90?s="full":i>=70?s="good":i>=50&&(s="limited"),{score:t,total:e,percentage:i,level:s,recommendations:this.getRecommendations(s)}}getRecommendations(t){const e=[];return this.features.webAudio||e.push("Audio features will be disabled"),this.features.requestAnimationFrame||e.push("Animation will use setTimeout fallback"),this.features.performance||e.push("Performance monitoring will be limited"),"basic"===t&&e.push("Consider using minimal build for better performance"),e}getFeatures(){return{...this.features}}getCapabilities(){return{...this.capabilities}}}class Or{constructor(){this.polyfills=new Map,this.applied=new Set}register(t,e){this.polyfills.set(t,e)}apply(t){if(this.applied.has(t))return!0;const e=this.polyfills.get(t);if(!e)return!1;try{return e(),this.applied.add(t),!0}catch{return!1}}applyAll(){const t=[];for(const e of this.polyfills.keys())this.apply(e)&&t.push(e);return t}isApplied(t){return this.applied.has(t)}}function jr(){window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(()=>{t(Date.now())},1e3/60)},window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){window.clearTimeout(t)})}function Ir(){if(window.performance&&window.performance.now)return;window.performance||(window.performance={});const t=Date.now();window.performance.now=function(){return Date.now()-t}}function $r(){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(t){for(let e=0;e<t.length;e++)t[e]=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 Lr{constructor(t){this.canvas=t,this.context=null,this.isContextLost=!1,this.recoveryCallbacks=[],this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this),this.setupContextLossHandling()}handleContextLost(t){t.preventDefault(),this.isContextLost=!0}handleContextRestored(){this.isContextLost=!1,this.context=this.canvas.getContext("2d"),this.recoveryCallbacks.forEach(t=>{try{t(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(t){this.recoveryCallbacks.push(t)}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 Gr{constructor(){if(Gr.se)return this.browser=Gr.se,void(this.optimizations=Gr.ne);this.browser=this.detectBrowser(),this.optimizations=new Map,this.setupOptimizations(),Gr.se=this.browser,Gr.ne=this.optimizations}detectBrowser(){const{userAgent:t}=navigator;let e="unknown",i="unknown";if(t.includes("Chrome")){e="chrome";const s=t.match(/Chrome\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Firefox")){e="firefox";const s=t.match(/Firefox\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Safari")&&!t.includes("Chrome")){e="safari";const s=t.match(/Version\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Edge")){e="edge";const s=t.match(/Edge\/(\d+)/);i=s?s[1]:"unknown"}return{name:e,version:i,userAgent:t}}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(t,e){if(this.getOptimizations().canvasOptimizations.includes("willReadFrequently"))try{t.getContext("2d",{willReadFrequently:!0})}catch{}}getRecommendedParticleLimit(){return this.getOptimizations().particleLimit}getAudioContextOptions(){return this.getOptimizations().audioContextOptions}}let _r=null,Hr=null;const Ur=(Hr||(Hr=function(){if(_r)return _r;const t=new qr,e=new Or,i=new Gr;e.register("requestAnimationFrame",jr),e.register("performanceNow",Ir),e.register("webAudio",$r);const s=[];return t.features.requestAnimationFrame||e.apply("requestAnimationFrame")&&s.push("requestAnimationFrame"),t.features.performance||e.apply("performanceNow")&&s.push("performanceNow"),t.features.webAudio||e.apply("webAudio")&&s.push("webAudio"),_r={featureDetection:t,polyfillManager:e,browserOptimizations:i,appliedPolyfills:s,capabilities:t.getCapabilities(),browser:i.getBrowser()},_r}()),Hr);function Wr(t){const e=[];for(let i=0;i<t;i++){const s=i/t*Math.PI*2;e.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)})}return e}function Yr(t,e=12){return Wr(t)}const Xr={circle:{points:Wr(64),shadow:{type:"none"}},sphere:{points:Wr(64),shadow:{type:"none"}},heart:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/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));t.push({x:.5+s/32,y:.5+n/32})}return t}(),shadow:{type:"none"}},star:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/64,s=Math.floor(10*i),n=s%2==0,r=Math.floor(s/2);let a;a=n?(72*r-90)*Math.PI/180:(72*r+36-90)*Math.PI/180;const o=n?.5:.2;t.push({x:.5+Math.cos(a)*o,y:.5+Math.sin(a)*o})}return t}(),shadow:{type:"none"}},sun:{points:Yr(64,12),shadow:{type:"sun",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3}},moon:{points:Wr(64),shadow:{type:"crescent",coverage:.85,angle:-30,softness:.05,offset:.7}},lunar:{points:Wr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)",progression:"center"}},suspicion:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/64*Math.PI*2;let s,n;if(i<Math.PI)s=.45*Math.cos(i),n=.45*Math.sin(i);else{const t=2*Math.PI-i;s=.25*Math.cos(t)-.1,n=.35*Math.sin(t)}t.push({x:.5+s,y:.5+n})}return t}(),shadow:{type:"none"}},eclipse:{points:Wr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)"}},square:{points:function(){const t=[],e=Math.floor(16);for(let i=0;i<4;i++)for(let s=0;s<e;s++){const n=s/e;let r,a;switch(i){case 0:r=-.5+n,a=-.5;break;case 1:r=.5,a=-.5+n;break;case 2:r=.5-n,a=.5;break;case 3:r=-.5,a=.5-n}t.push({x:.5+.8*r,y:.5+.8*a})}return t}(),shadow:{type:"none"}},triangle:{points:function(){const t=[],e=[{x:0,y:-.5},{x:-.433,y:.25},{x:.433,y:.25}],i=[Math.sqrt(Math.pow(e[1].x-e[0].x,2)+Math.pow(e[1].y-e[0].y,2)),Math.sqrt(Math.pow(e[2].x-e[1].x,2)+Math.pow(e[2].y-e[1].y,2)),Math.sqrt(Math.pow(e[0].x-e[2].x,2)+Math.pow(e[0].y-e[2].y,2))],s=i[0]+i[1]+i[2],n=i.map(t=>Math.round(64*t/s)),r=n.reduce((t,e)=>t+e,0);r<64&&(n[0]+=64-r);for(let i=0;i<3;i++){const s=e[i],r=e[(i+1)%3],a=n[i];for(let e=0;e<a;e++){if(e===a-1&&i<2)continue;const n=e/a,o=s.x+(r.x-s.x)*n,h=s.y+(r.y-s.y)*n;t.push({x:.5+.9*o,y:.5+.9*h})}}for(;t.length<64;)t.push(t[t.length-1]);for(;t.length>64;)t.pop();return t}(),shadow:{type:"none"}},solar:{points:Yr(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"}}}},Vr=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 t=Object.keys(Xr);t.forEach(t=>{this.cacheShape(t)}),this.cacheCommonMorphs(t),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.shapeCache.size}catch(t){this.isInitialized=!1}}cacheShape(t){try{const e=Xr[t];if(e){this.shapeCache.set(t,e);const i={pointCount:e.points?.length||64,hasShadow:"none"!==e.shadow?.type,shadowType:e.shadow?.type||"none",isRadial:this.isRadialShape(t),bounds:this.calculateBounds(e.points)};this.propertyCache.set(t,i)}}catch(t){}}cacheCommonMorphs(t){[["circle","heart"],["circle","star"],["circle","square"],["heart","star"],["star","circle"],["square","circle"],["triangle","circle"],["moon","sun"],["lunar","eclipse"]].forEach(([e,i])=>{if(t.includes(e)&&t.includes(i))try{const t=this.calculateMorphSteps(e,i),s=`${e}->${i}`;this.morphCache.set(s,t)}catch(t){}})}calculateMorphSteps(t,e){const i=this.shapeCache.get(t),s=this.shapeCache.get(e);if(!i||!s)return null;const n=[];for(let t=0;t<5;t++){const e=t/4,r=this.interpolateShapePoints(i.points,s.points,e);n.push({progress:e,points:r})}return{from:t,to:e,steps:n,isRadial:this.isRadialShape(t)||this.isRadialShape(e)}}interpolateShapePoints(t,e,i){if(!t||!e)return t||e||[];const s=Math.max(t.length,e.length),n=[];for(let r=0;r<s;r++){const s=t[r]||t[0]||{x:.5,y:.5},a=e[r]||e[0]||{x:.5,y:.5};n.push({x:s.x+(a.x-s.x)*i,y:s.y+(a.y-s.y)*i})}return n}isRadialShape(t){return["circle","star","square","triangle","sun","moon"].includes(t)}calculateBounds(t){if(!t||0===t.length)return{minX:0,minY:0,maxX:1,maxY:1,width:1,height:1};let e=1/0,i=1/0,s=-1/0,n=-1/0;return t.forEach(t=>{e=Math.min(e,t.x),i=Math.min(i,t.y),s=Math.max(s,t.x),n=Math.max(n,t.y)}),{minX:e,minY:i,maxX:s,maxY:n,width:s-e,height:n-i}}getShape(t){if(!this.isInitialized)return Xr[t]||null;const e=this.shapeCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,Xr[t]||null)}getProperties(t){if(!this.isInitialized){const e=Xr[t];return e?{pointCount:e.points?.length||64,hasShadow:"none"!==e.shadow?.type,shadowType:e.shadow?.type||"none",isRadial:this.isRadialShape(t),bounds:this.calculateBounds(e.points)}:{}}const e=this.propertyCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,{})}getMorph(t,e){if(!this.isInitialized)return this.calculateMorphSteps(t,e);const i=`${t}->${e}`,s=this.morphCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,this.calculateMorphSteps(t,e))}hasShape(t){return this.shapeCache.has(t)}getStats(){const t=this.stats.hits+this.stats.misses;return{...this.stats,hitRate:t>0?`${(this.stats.hits/t*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}},Nr=new class{constructor(){this.pools=new Map,this.inUse=new Set}acquire(t,e="array"){const i=`${e}_${t}`;this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);if(s.length>0){const t=s.pop();return this.inUse.add(t),t}let n;switch(e){case"float32":n=new Float32Array(t);break;case"uint8":n=new Uint8Array(t);break;default:n=new Array(t).fill(0)}return this.inUse.add(n),n}release(t){if(!this.inUse.has(t))return;this.inUse.delete(t);let e="array";t instanceof Float32Array?e="float32":t instanceof Uint8Array&&(e="uint8");const i=`${e}_${t.length}`;t.fill(0),this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);s.length<10&&s.push(t)}clear(){this.pools.clear(),this.inUse.clear()}};class Qr{constructor(t){this.morpher=t,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(t){if(!t||0===t.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 t=0,e=0;for(let i=0;i<=2&&i<this.morpher.frequencyData.length;i++)t+=this.morpher.frequencyData[i],e++;e>0&&(t/=e),this.morpher.bassPeakHistory||(this.morpher.bassPeakHistory=[],this.morpher.bassThumpTimer=0),this.morpher.bassPeakHistory.push(t),this.morpher.bassPeakHistory.length>20&&this.morpher.bassPeakHistory.shift();const i=this.morpher.bassPeakHistory.reduce((t,e)=>t+e,0)/this.morpher.bassPeakHistory.length,s=this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.microphoneStream;if(t>1.08*i&&t>(s?.15:.25)){const e=s?8:6;this.bassEnergy=Math.min(1,(t-i)*e),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 r=0,a=0;if(this.morpher.spectralHistory.length>0){const t=this.morpher.spectralHistory[this.morpher.spectralHistory.length-1];for(let e=0;e<=2&&e<n.length;e++){const i=n[e]-t[e];i>0&&(a+=i)}for(let e=4;e<=15&&e<n.length;e++){const i=n[e]-t[e];i>0&&(r+=i*(e>=9&&e<=13?2:1))}a>.15&&(r*=.3)}if(this.morpher.spectralHistory.push(n),this.morpher.spectralHistory.length>30&&this.morpher.spectralHistory.shift(),this.morpher.spectralFluxHistory.push(r),this.morpher.spectralFluxHistory.length>30&&this.morpher.spectralFluxHistory.shift(),this.morpher.bassFluxHistory||(this.morpher.bassFluxHistory=[],this.morpher.bassOnsetThreshold=.05),this.morpher.bassFluxHistory.push(a),this.morpher.bassFluxHistory.length>30&&this.morpher.bassFluxHistory.shift(),this.morpher.spectralFluxHistory.length>=10){const t=[...this.morpher.spectralFluxHistory].sort((t,e)=>t-e),e=t[Math.floor(t.length/2)],i=t.reduce((t,e)=>t+e,0)/t.length;this.morpher.onsetThreshold=e+.5*(i-e)}if(this.morpher.bassFluxHistory.length>=10){const t=[...this.morpher.bassFluxHistory].sort((t,e)=>t-e),e=t[Math.floor(t.length/2)],i=t.reduce((t,e)=>t+e,0)/t.length;this.morpher.bassOnsetThreshold=e+.5*(i-e)}const o=r>1.2*this.morpher.onsetThreshold&&r>.02,h=a>1.5*this.morpher.bassOnsetThreshold&&a>.08;if(o&&(this.transientHoldTime=8,this.morpher.vocalGlowBoost=.3),h){const t=performance.now(),e={time:t,strength:a/(this.morpher.bassOnsetThreshold||1),bassWeight:a};this.morpher.onsetStrengths.push(e),this.morpher.onsetStrengths.length>40&&this.morpher.onsetStrengths.shift(),this.morpher.musicDetector.addOnset(t,a)}const l=performance.now();this.morpher.musicDetector.processFrequencyFrame&&this.morpher.musicDetector.processFrequencyFrame(this.morpher.frequencyData,l),this.morpher.musicDetector.update(l),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=r,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 e=this.morpher.frequencyData&&this.morpher.frequencyData.some(t=>t>.01);if(this.morpher.audioAnalyzer&&e||(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)),!e&&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 t;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 e=2+Math.floor(2*Math.random());for(let i=0;i<e;i++)this.glitchPoints.push({index:Math.floor(Math.random()*t.length),intensity:.02+.03*Math.random(),decay:.94+.02*Math.random()})}this.glitchPoints=this.glitchPoints.filter(t=>(t.intensity*=t.decay,t.intensity>.01));for(let e=0;e<t.length;e++){const s=t[e];if(!s||void 0===s.x||void 0===s.y){const s=e/t.length*Math.PI*2;i.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)});continue}const n=s.x-.5,r=s.y-.5,a=Math.sqrt(n*n+r*r),o=Math.atan2(r,n),h=.12*Math.abs(this.audioDeformation);let l=0,c=0;if(this.morpher.bassEffectActive){const t=2,e=.25*this.bassEnergy;l=Math.sin(o*t+this.morpher.undulationPhase)*e,c=Math.sin(.5*this.morpher.undulationPhase)*this.bassEnergy*.08}let u=0;const d=this.glitchPoints.find(t=>t.index===e);if(d){const t=.015*Date.now(),i=Math.sin(t+.5*e)*Math.cos(.7*t);u=d.intensity*i*.5}const p=1+h+l+c+u,m=a*Math.max(.8,p);i.push({x:.5+Math.cos(o)*m,y:.5+Math.sin(o)*m})}return i}setAudioDeformation(t){this.audioDeformation=Math.max(0,Math.min(1,t)),this.vocalEffectActive=t>.01}setVocalEnergy(t){this.vocalEnergy=Math.max(0,Math.min(1,t)),this.vocalEffectActive=t>.01}updateFrequencyBands(t){t&&(this.bassEnergy=t.bass||0,this.vocalPresence=t.vocal||0,this.highFreqEnergy=t.high||0)}processTransient(t,e){t>e?(this.transientActive=!0,this.transientStrength=t,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 Jr{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.re=[],this.ae=0,this.oe=0,this.he=!1,this.le=0,this.grooveConfidence=.15,this.ce=.15,this.ue=0,this.de=2e3,this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0,this.m=[],this.Me=20}processPeak(t,e=performance.now()){if(this.isActive=!0,this.peakCount++,t<.1)this.fe++;else{if(this.lastPeakTime>0){const t=e-this.lastPeakTime;t>=250&&t<=2e3?(this.intervals.push(t),this.pe.push(Math.round(t)),this.intervals.length>this.maxIntervals&&this.intervals.shift(),this.voteForInterval(t)):this.ye++}this.lastPeakTime=e,this.updateBPM(),this.be(e)}}voteForInterval(t){const e=6e4/t;this.me.push(Math.round(e));let i=e;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.ge.push(Math.round(i));const r=Math.round(i);for(let t=-2;t<=2;t++){const e=r+t;if(e>=this.minBPM&&e<=this.maxBPM){const i=Math.exp(-t*t/2),s=this.bpmVotes.get(e)||0;this.bpmVotes.set(e,s+i)}}for(const[t,e]of this.bpmVotes){const i=.95*e;i<.3?this.bpmVotes.delete(t):this.bpmVotes.set(t,i)}}updateBPM(){if(0===this.bpmVotes.size||this.intervals.length<3)return;const t=performance.now();let e=0,i=0,s=0;for(const[t,n]of this.bpmVotes)s+=n,n>i&&(i=n,e=t);if(0===e)return;let n=0;for(let t=-2;t<=2;t++){const i=e+t;n+=this.bpmVotes.get(i)||0}const r=n,a=Math.round(e/2);let o=0;if(a>=this.minBPM)for(let t=-2;t<=2;t++)o+=this.bpmVotes.get(a+t)||0;const h=2*e;let l=0;if(h<=this.maxBPM)for(let t=-2;t<=2;t++)l+=this.bpmVotes.get(h+t)||0;let c=0,u=0;const d=r>0?o/r:0;if(this.intervals.length>=6){const t=this.intervals.slice(-8),e=t.reduce((t,e)=>t+e,0)/t.length;let i=0;for(let s=0;s<t.length-1;s++)t[s]>e!=t[s+1]>e&&i++;c=i/(t.length-1);const s=[];for(let e=0;e<t.length-1;e+=2)s.push(t[e]+t[e+1]);if(s.length>=2){const t=s.reduce((t,e)=>t+e,0)/s.length;u=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}this.confidence=s>0?r/s:0;let p=0;if(this.intervals.length>=4){const t=6e4/e,i=t/2,s=this.intervals.slice(-8);let n=0;for(const e of s){const s=Math.abs(e-t)/t<.15,r=Math.abs(e-i)/i<.15,a=Math.abs(e-2*t)/(2*t)<.15;(s||r||a)&&n++}p=n/s.length}if(0===this.currentBPM)this.currentBPM=e;else{const t=this.intervals.length<6?.5:.3;this.currentBPM=this.currentBPM*(1-t)+e*t}if(0===this.lockStage){this.we={intervalCount:this.intervals.length,bestVotes:i.toFixed(1),clusterVotes:r.toFixed(1),confidence:`${(100*this.confidence).toFixed(0)}%`,consistency:`${(100*p).toFixed(0)}%`,bestBPM:e,adjustedBPM:e,isSubdivision:!1,stage:0,failReasons:[]};const s=e>120?12:8,n=.2,a=.45;this.intervals.length<s&&this.we.failReasons.push(`intervals<${s}`),r<=5&&this.we.failReasons.push("votes<=5"),this.confidence<=n&&this.we.failReasons.push(`conf<=${(100*n).toFixed(0)}%`),p<=a&&this.we.failReasons.push(`consistency<=${(100*a).toFixed(0)}%`),this.intervals.length>=s&&r>5&&this.confidence>n&&p>a&&(this.lockedBPM=Math.round(this.currentBPM),this.lockStage=1,this.stage1LockTime=t)}if(1===this.lockStage||2===this.lockStage){this.re.push({alternatingScore:c,pairVariance:u,halfVoteRatio:d,time:t}),this.re.length>15&&this.re.shift();const i=this.re.filter(t=>t.alternatingScore>.7&&t.pairVariance<.1).length,s=this.re.reduce((t,e)=>t+e.alternatingScore,0)/this.re.length,n=this.re.reduce((t,e)=>t+e.pairVariance,0)/this.re.length,o=this.re.reduce((t,e)=>t+e.halfVoteRatio,0)/this.re.length,p=this.intervals.length>0?this.intervals.reduce((t,e)=>t+e,0)/this.intervals.length:0,m=r>0?l/r:0;let g=0,f=0;if(this.intervals.length>=8){const t=this.intervals.slice(-12),e=[...t].sort((t,e)=>t-e),i=e[Math.floor(e.length/2)],s=t.filter(t=>Math.abs(t-i)/i<.5);if(f=s.length,s.length>=6){const t=s.reduce((t,e)=>t+e,0)/s.length;g=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}if(this.we={intervalCount:this.intervals.length,bestBPM:e,adjustedBPM:this.lockedBPM,halfBPM:a,stage:this.lockStage,subdivisionChecks:this.re.length,positiveChecks:i,avgAltScore:`${(100*s).toFixed(0)}%`,avgPairVar:`${(100*n).toFixed(1)}%`,avgHalfRatio:`${(100*o).toFixed(0)}%`,intervalVariance:`${(100*g).toFixed(1)}%`,filteredCount:f,correctionApplied:this.stage2CorrectionApplied,failReasons:[]},!this.stage2CorrectionApplied&&this.re.length>=10&&a>=this.minBPM){const t=i>=7&&s>.7&&n<.1&&this.lockedBPM>100,e=o>.4&&this.lockedBPM>150&&a>=65&&a<=85;let r=0,h=0;if(this.intervals.length>=8){const t=this.intervals.slice(-12),e=[...t].sort((t,e)=>t-e),i=e[Math.floor(e.length/2)],s=t.filter(t=>Math.abs(t-i)/i<.5);if(h=s.length,s.length>=6){const t=s.reduce((t,e)=>t+e,0)/s.length;r=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}const l=this.lockedBPM>140&&a>=65&&a<=85&&h>=8&&r<.05;(t||e||l)&&(this.lockedBPM=Math.round(this.lockedBPM/2),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="halved")}!this.stage2CorrectionApplied&&this.re.length>=10&&h<=this.maxBPM&&p>900&&m>.5&&this.lockedBPM<75&&(this.lockedBPM=Math.round(2*this.lockedBPM),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="doubled");const y=t-this.stage1LockTime;1===this.lockStage&&this.re.length>=6&&(this.lockStage=2);const M=this.re.length>=12&&i<3,b=y>1e4;2===this.lockStage&&(this.stage2CorrectionApplied||M||b)&&(this.lockStage=3,this.ae=t)}if(3===this.lockStage){const e=t-this.ae,i=this.intervals.slice(-8);if(i.length>=4){const t=6e4/(i.reduce((t,e)=>t+e,0)/i.length);if(Math.abs(t-this.lockedBPM)/this.lockedBPM<.05){0===this.le&&(this.le=this.lockedBPM),this.le=.9*this.le+.1*t;const e=Math.round(this.le);e!==this.lockedBPM&&(this.lockedBPM=e),this.oe+=100}else this.oe=0}const s=(e>5e3||this.oe>3e3)&&!this.he;s&&3===this.lockStage&&(this.ve(),this.he=!0),this.we={stage:3,lockedBPM:this.lockedBPM,correctionType:this.correctionType,timeSinceStage3:`${(e/1e3).toFixed(1)}s`,stableTime:`${(this.oe/1e3).toFixed(1)}s`,finalized:s,failReasons:[]}}this.Se()}Se(){this.he?this.ce=1:this.ce=[.15,.4,.65,.85][this.lockStage]||.15;const t=this.grooveConfidence+.08*(this.ce-this.grooveConfidence);t>this.grooveConfidence&&(this.grooveConfidence=t)}ve(){this.intervals.length>8&&(this.intervals=this.intervals.slice(-8)),this.bpmVotes.clear(),this.ke=[],this.re=[],this.pe=[],this.me=[],this.ge=[]}processFrame(t,e=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.re=[],this.ae=0,this.oe=0,this.he=!1,this.le=0,this.grooveConfidence=.15,this.ce=.15,this.ue=0,this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0,this.m=[],this.we=null,this.ke=[]}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.he,grooveConfidence:this.grooveConfidence,agentCount:this.bpmVotes.size,peakCount:this.peakCount,histogramSize:this.bpmVotes.size,topAgents:this.getTopCandidates(5),intervalCount:this.intervals.length}}getTopCandidates(t=5){return[...this.bpmVotes.entries()].sort((t,e)=>e[1]-t[1]).slice(0,t).map(([t,e])=>({bpm:t,score:e.toFixed(1),interval:Math.round(6e4/t)}))}getTopIntervals(t=5){return this.getTopCandidates(t).map(t=>({interval:t.interval,bpm:t.bpm,weight:t.score}))}be(t){if(t-this.ue<this.de)return;if(this.ue=t,0===this.pe.length&&0===this.fe)return;const e=[],i=["Detecting","Initial Lock","Refinement","Final Lock"][this.lockStage]||"Unknown";e.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"),e.push(`Status: Stage ${this.lockStage} (${i}) | Current: ${Math.round(this.currentBPM)} BPM | Locked: ${this.lockedBPM||"-"}`),e.push(`Peaks: ${this.peakCount} total | ${this.fe} skipped (weak) | ${this.ye} intervals out-of-range`),this.pe.length>0&&e.push(`Recent intervals (ms): [${this.pe.join(", ")}]`),this.me.length>0&&e.push(`Raw BPMs (before normalize): [${this.me.join(", ")}]`),this.ge.length>0&&e.push(`Normalized BPMs (60-180): [${this.ge.join(", ")}]`);const s=this.getTopCandidates(5);if(s.length>0){const t=s.map(t=>`${t.bpm}(${t.score})`).join(", ");e.push(`Top candidates: ${t}`)}if(this.we){const t=this.we;0===t.stage?t.failReasons&&t.failReasons.length>0?e.push(`Stage 0: NOT locking - ${t.failReasons.join(", ")}`):e.push(`Stage 0: Ready to lock at ${t.bestBPM} BPM`):1===t.stage||2===t.stage?(e.push(`Stage ${t.stage}: Locked=${t.adjustedBPM} BPM | checks=${t.subdivisionChecks} positive=${t.positiveChecks}`),e.push(` altScore=${t.avgAltScore} pairVar=${t.avgPairVar} halfRatio=${t.avgHalfRatio}`),t.correctionApplied&&e.push(` Correction applied: ${this.correctionType}`)):3===t.stage&&(e.push(`Stage 3: Final=${t.lockedBPM} BPM | correction=${t.correctionType} | time=${t.timeSinceStage3} stable=${t.stableTime}`),t.finalized&&e.push(" FINALIZED - memory cleaned"))}if(this.intervals.length>=6){const t=this.intervals.slice(-8),i=t.reduce((t,e)=>t+e,0)/t.length,s=(t.reduce((t,e)=>t+Math.abs(e-i),0)/t.length/i*100).toFixed(1);let n=0;for(let e=0;e<t.length-1;e++)t[e]>i!=t[e+1]>i&&n++;const r=(n/(t.length-1)*100).toFixed(0);e.push(`Interval pattern: variance=${s}% alternating=${r}% (>70% triggers subdivision)`)}const n=[...this.intervals].map(t=>Math.round(t));if(n.length>0){const t=Math.min(...n),i=Math.max(...n),s=Math.round(n.reduce((t,e)=>t+e,0)/n.length);e.push(`Interval buffer (${n.length}/${this.maxIntervals}): min=${t}ms max=${i}ms avg=${s}ms (=${Math.round(6e4/s)} BPM)`)}e.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ");const r=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});for(this.m.push({time:r,lines:e});this.m.length>this.Me;)this.m.shift();this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0}getDebugLog(){if(0===this.m.length)return"No BPM debug logs yet. Play audio to generate logs.";let t="=== BPM Debug Log ===\n\n";for(const e of this.m){t+=`[${e.time}]\n`;for(const i of e.lines)t+=`${i}\n`;t+="\n"}return t}clearDebugLog(){this.m=[]}}class Kr{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 Jr,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 t=this.agentDetector.getStatus();if(t.locked&&t.confidence>.6)return this.detectedBPM=t.bpm,this.bpmConfidence=t.confidence,this.tempoLocked=!0,this.fundamentalBPM=t.bpm,this.bpmHistory.push(this.detectedBPM),this.bpmHistory.length>10&&this.bpmHistory.shift(),this.detectedBPM;if(t.bpm>0&&t.confidence>.4)return this.detectedBPM=t.bpm,this.bpmConfidence=t.confidence,t.confidence>.6&&(this.tempoLocked=!0),this.detectedBPM}if(this.onsetIntervals.length<4)return this.detectedBPM;const t=this.onsetIntervals.slice(-15),e=this.findTempoCandidates(t);if(0===e.length)return this.detectedBPM;const i=e[0],s=Math.round(6e4/i.interval);if(!this.tempoLocked&&this.bpmHistory.length>3){const t=this.bpmHistory.slice(-3),e=t.reduce((t,e)=>t+e,0)/t.length;t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length<5&&(this.fundamentalBPM=Math.round(e),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 t=this.tempoLocked?1:2,e=n-this.detectedBPM;Math.abs(e)<=t?this.detectedBPM=n:this.detectedBPM+=Math.sign(e)*t}return window.rhythmIntegration&&window.rhythmIntegration.updateBPM&&(window.rhythmManuallyStoppedForCurrentAudio||window.rhythmIntegration.updateBPM(this.detectedBPM)),this.detectedBPM}findTempoCandidates(t){const e=[];for(const i of[1,2,4]){const s=t.map(t=>t*i),n=this.clusterIntervals(s);for(const s of n){const n=s.intervals.reduce((t,e)=>t+e,0)/s.intervals.length/i,r=s.intervals.length/t.length*s.consistency,a=6e4/n,o=a>=120&&a<=140?.2:0;a>=60&&a<=220&&e.push({interval:n,strength:r+o,multiplier:i})}}return e.sort((t,e)=>e.strength-t.strength)}clusterIntervals(t){const e=[...t].sort((t,e)=>t-e),i=[];let s=[e[0]];for(let t=1;t<e.length;t++){const n=.03*s[0];if(e[t]-s[0]<=n)s.push(e[t]);else{if(s.length>=2){const t=s.reduce((t,e)=>t+e,0)/s.length,e=1/(1+s.reduce((e,i)=>e+Math.pow(i-t,2),0)/s.length/(t*t));i.push({intervals:s,consistency:e})}s=[e[t]]}}if(s.length>=3){const t=s.reduce((t,e)=>t+e,0)/s.length,e=1/(1+s.reduce((e,i)=>e+Math.pow(i-t,2),0)/s.length/(t*t));i.push({intervals:s,consistency:e})}return i}checkHarmonicRelation(t,e){const i=Math.max(t,e)/Math.min(t,e);return[2,1.5,1.333,1.25].some(t=>Math.abs(i-t)<.03)}detectTimeSignature(){const t=this.forceFastDetection?6:12;if(0===this.detectedBPM||this.onsetStrengths.length<t)return this.timeSignature;if(this.timeSignatureLocked&&!this.forceFastDetection)return this.detectedTimeSignature||this.timeSignature;const e=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 t of s){const s=(t.time-n)/e%4,r=Math.round(s)%4;i[r].strength+=t.strength,i[r].bassWeight+=t.bassWeight||0,i[r].count++}for(const t of i)t.count>0&&(t.strength/=t.count,t.bassWeight/=t.count);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,e)>.8&&(r="3/4"),this.timeSignatureHistory.push(r),this.timeSignatureHistory.length>3&&this.timeSignatureHistory.shift();const a=this.forceFastDetection?2:3;if(this.timeSignatureHistory.length>=a){const t={};for(const e of this.timeSignatureHistory)t[e]=(t[e]||0)+1;let e="4/4",i=0;for(const[s,n]of Object.entries(t))n>i&&(i=n,e=s);if(i>=2){this.detectedTimeSignature=e,this.timeSignatureLocked=!0,this.timeSignatureConfidence=i/3,window.rhythmIntegration&&window.rhythmIntegration.setTimeSignature&&window.rhythmIntegration.setTimeSignature(this.detectedTimeSignature);const t=document.getElementById("time-sig-display");t&&(t.textContent=this.detectedTimeSignature)}}return this.detectedTimeSignature||this.timeSignature}testWaltzPattern(t,e){let i=0,s=0;for(let e=0;e<t.length-2;e+=3)if(e+2<t.length){s++;const n=t[e].strength+(t[e].bassWeight||0),r=t[e+1].strength+(t[e+1].bassWeight||0),a=t[e+2].strength+(t[e+2].bassWeight||0);n>1.5*r&&n>1.5*a&&i++}return s>0?i/s:0}processFrequencyFrame(t,e=performance.now()){this.useAgentDetection&&this.agentDetector.processFrame&&this.agentDetector.processFrame(t,e)}addOnset(t,e,i=0){if(this.useAgentDetection&&this.agentDetector.processPeak(e,t),this.lastOnsetTime>0){const e=t-this.lastOnsetTime;e>273&&e<1e3&&(this.onsetIntervals.push(e),this.onsetIntervals.length>20&&this.onsetIntervals.shift())}this.onsetStrengths.push({time:t,strength:e,bassWeight:i}),this.onsetStrengths.length>40&&this.onsetStrengths.shift(),this.lastOnsetTime=t}update(t){t-this.lastBPMCalculation>this.bpmCalculationInterval&&(this.calculateBPM(),this.detectTimeSignature(),this.lastBPMCalculation=t)}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 Zr{constructor(t){this.morpher=t,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(t,e={}){this.isTransitioning&&this.morphQueue.length<this.maxQueueSize?this.morphQueue.push({shape:t,options:e}):(this.previousShape=this.currentShape,this.targetShape=t,this.isTransitioning=!0,this.transitionStartTime=performance.now(),this.transitionDuration=e.duration||800,this.easingFunction=e.easing||"easeInOutQuad",this.transitionProgress=0,this.shadowConfig=this.getTransitionConfig(this.currentShape,t))}update(t){if(!this.isTransitioning)return;const e=performance.now()-this.transitionStartTime,i=Math.min(1,e/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 t=this.morphQueue.shift();this.startTransition(t.shape,t.options)}}getTransitionConfig(t,e){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}}[`${t}-${e}`]||null}calculateShadowProgress(t){if(!this.shadowConfig)return 0;switch(this.shadowConfig.type){case"bloom":return t<.5?2*t:2-2*t;case"burst":return Math.pow(1-t,2);case"contract":case"collapse":return Math.sin(t*Math.PI);default:return 0}}applyEasing(t){switch(this.easingFunction){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return t*(2-t);case"easeInOutQuad":return t<.5?2*t*t:(4-2*t)*t-1;case"easeInCubic":return t*t*t;case"easeOutCubic":return--t*t*t+1;case"easeInOutCubic":return t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-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 ta{constructor(t){this.xe=t}getCurrentShadow(){const t=this.xe(),e=t.currentShape||"circle",i=Vr&&Vr.isInitialized?Vr.getShape(e):Xr[e],s=t.targetShape?Vr&&Vr.isInitialized?Vr.getShape(t.targetShape):Xr[t.targetShape]:null,n=i?.shadow||{type:"none"},r=s?.shadow||null;if(!t.isTransitioning||!r)return n;const a=t.morphProgress;if(t.transitionConfig&&"from_moon"===t.transitionConfig.type&&t.transitionConfig.slideOutCrescent)return this.Ee(a,t.transitionConfig);if(t.transitionConfig&&"moon_to_lunar"===t.transitionConfig.type)return this.Be(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_enter_lunar"===t.transitionConfig.type)return this.Ae(a,t.transitionConfig);if(t.transitionConfig&&"lunar_to_moon"===t.transitionConfig.type)return this.Ce(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_exit_lunar"===t.transitionConfig.type)return this.Te(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_enter"===t.transitionConfig.type)return this.Pe(a,r);if("eclipse_exit"===t.transitionConfig.type)return this.De(a,n);if("sun_fade"===t.transitionConfig.type)return this.Re(a,n);if("sun_bloom"===t.transitionConfig.type)return this.Fe(a,r);if("none"!==n.type||"none"!==r.type){const t=(n.coverage||0)+((r.coverage||0)-(n.coverage||0))*a;return{type:"none"!==r.type?r.type:n.type,coverage:t,angle:r.angle||n.angle||0,softness:r.softness||n.softness||.2,progress:a}}return n}Ee(t,e){const i=e.shadowSlideRatio||.4;if(t<i){const e=t/i,s=-30*Math.PI/180,n=.7,r=n+(2.5-n)*e;return{type:"crescent",coverage:e>.8?.85*(1-5*(e-.8)):.85,angle:-30,offset:r,shadowX:Math.cos(s)*r,shadowY:Math.sin(s)*r}}return{type:"none"}}Be(t,e){const i=e.startAngle*Math.PI/180,s=1-t,n=.7*Math.cos(i)*s,r=.7*Math.sin(i)*s,a=Math.pow(t,2);if(t<.6)return{type:"crescent",coverage:.85*(1-.2*a),angle:e.startAngle,offset:.7*s,shadowX:n,shadowY:r};{const e=(t-.6)/.4,i=Math.sin(e*Math.PI/2);return{type:"lunar",coverage:.85+.1*i,color:`rgba(80, 20, 0, ${.7+.2*i})`,shadowX:n*(1-i),shadowY:r*(1-i),diffusion:i,shadowProgress:t}}}Ae(t,e){if(t<.3)return{type:"none"};const i=(t-.3)/.7,s=Math.sin(i*Math.PI/2),n=e.startAngle*Math.PI/180,r=1-s,a=.7*Math.cos(n)*r,o=.7*Math.sin(n)*r;if(i<.7)return{type:"crescent",coverage:.85*Math.pow(i/.7,.5),angle:e.startAngle,offset:.7*r,shadowX:a,shadowY:o};{const t=(i-.7)/.3,e=Math.sin(t*Math.PI/2);return{type:"lunar",coverage:.85+.1*e,color:`rgba(80, 20, 0, ${.6+.3*e})`,shadowX:a*(1-e),shadowY:o*(1-e),diffusion:e,shadowProgress:i}}}Ce(t,e){const i=e.exitAngle*Math.PI/180,s=Math.sin(t*Math.PI/2),n=.7*Math.cos(i)*s,r=.7*Math.sin(i)*s;if(t<.6){const e=t/.6,i=Math.pow(e,.7);return{type:"lunar",coverage:.95-.1*i,color:`rgba(80, 20, 0, ${.9-.3*i})`,shadowX:.7*n,shadowY:.7*r,diffusion:1-i}}{const i=(t-.6)/.4;return{type:"crescent",coverage:.85*Math.sin(i*Math.PI/2)+.1,angle:e.exitAngle,offset:.7,shadowX:n,shadowY:r}}}Te(t,e){if(t<.7){const i=t/.7,s=e.exitAngle*Math.PI/180;if(i<.4){const t=i/.4,e=1-t,n=.3*t;return{type:"lunar",coverage:.95-.1*t,color:`rgba(80, 20, 0, ${.9-.2*t})`,shadowX:.7*Math.cos(s)*n,shadowY:.7*Math.sin(s)*n,diffusion:e}}{const t=(i-.4)/.6,n=Math.pow(t,.8),r=.7*Math.cos(s)*n,a=.7*Math.sin(s)*n;return{type:"crescent",coverage:.85*(1-Math.pow(t,2)),angle:e.exitAngle,offset:.7*n,shadowX:r,shadowY:a}}}return{type:"none"}}Pe(t,e){return{...e,shadowX:1.5-1.5*t,shadowProgress:t}}De(t,e){const i=1.5*-t;return{...e,coverage:e.coverage*(1-t),shadowX:i,shadowProgress:1-t}}Re(t,e){const i=1-t;return{...e,intensity:(e.intensity||1)*Math.pow(i,.7),corona:e.corona,coronaOpacity:i,flares:e.flares,flaresOpacity:Math.pow(i,1.5),texture:e.texture,textureOpacity:Math.pow(i,2),turbulence:(e.turbulence||.3)*i}}Fe(t,e){const i=t;return{...e,intensity:(e.intensity||1)*Math.pow(i,1.5),corona:e.corona,coronaOpacity:Math.pow(i,.8),flares:e.flares,flaresOpacity:i>.3?Math.pow((i-.3)/.7,.7):0,texture:e.texture,textureOpacity:i>.5?Math.pow((i-.5)/.5,2):0,turbulence:(e.turbulence||.3)*i}}}class ea{constructor(t={}){this.numPoints=t.numPoints||64,this.morphDuration=t.morphDuration||1e3,this.easing=t.easing||"easeInOutCubic",this.transitionManager=new Zr(this),this.audioDeformer=new Qr(this),this.musicDetector=new Kr,this.shadowEffectManager=new ta(()=>({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=Nr.acquire(32,"float32"),this.glitchPoints=[],this.undulationPhase=0,this.undulationDirection=1,this.beatGlitchIntensity=0,this.bassEnergy=0,this.vocalPresence=0,this.bassHistory=Nr.acquire(60,"float32"),this.vocalHistory=Nr.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(t=>{(Vr&&Vr.isInitialized?Vr.hasShape(t):Xr[t])&&this.getShapePoints(t)}),[0,.25,.5,.75,1].forEach(t=>{this.applyEasing(t)})}getShapePoints(t){if(!this.shapeCache.has(t)){const e=Vr&&Vr.isInitialized?Vr.getShape(t):Xr[t];if(!e||!e.points){const e=Xr.circle.points;return this.shapeCache.set(t,e),e}const{points:i}=e;return this.shapeCache.set(t,i),i}return this.shapeCache.get(t)}morphTo(t,e={}){if(!this.shapesLoaded)return;if(t===this.currentShape&&!this.isTransitioning)return;if(this.isTransitioning&&!e.force)return this.queuedMorph={targetShape:t,options:e},"queued";this.isTransitioning&&e.force&&this.completeMorph(!0);const i=this.getTransitionConfig(this.currentShape,t);if(this.targetShape=t,this.targetPoints=this.getShapePoints(t),this.morphStartTime=Date.now(),this.isTransitioning=!0,this.morphProgress=0,this.visualProgress=0,"bar"===e.duration||"beat"===e.duration){const t=6e4/(Vs.bpm||120);"bar"===e.duration?this.morphDuration=4*t:this.morphDuration=t,this.musicalDuration=!0,this.onBeat=!1!==e.onBeat}else this.morphDuration=i?.duration||e.duration||1e3,this.musicalDuration=null,this.onBeat=!1;this.morphMode=e.mode||"smooth",this.transitionConfig=i,this.onComplete=e.onComplete,this.onProgress=e.onProgress}update(t){if(this.audioAnalyzer&&this.audioAnalyzer.isAnalyzing){const t=this.audioAnalyzer.getShapeMorpherData();if(t&&t.frequencies)for(let e=0;e<Math.min(t.frequencies.length,this.frequencyData.length);e++)this.frequencyData[e]=t.frequencies[e]}if(this.musicDetector&&this.musicDetector.update(performance.now()),!this.isTransitioning||!this.targetShape)return;const e=Date.now()-this.morphStartTime;if(this.musicalDuration){const t=6e4/(Vs.bpm||120),e=this.morphDuration>2*t;this.morphDuration=e?4*t:t}let i=Math.min(e/this.morphDuration,1);if(this.musicalDuration&&this.onBeat){const t=Vs.bpm||120;let e;e=t>140?2:t>100?4:8;const s=6e4/t,n=this.morphDuration/s,r=i*n,a=Math.round(r*e)/e,o=Math.min(1,a/n),h=(.3+.5*(t<90?Math.max(.3,(t-60)/30):Math.max(.4,Math.min(1,1-(t-90)/90))))*(.3+.7*Math.sin(i*Math.PI));i+=h*h*(3-2*h)*(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(t=!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),!t&&this.queuedMorph){const t=this.queuedMorph;this.queuedMorph=null,this.queuedMorphTimeout=setTimeout(()=>{this.morphTo(t.targetShape,t.options),this.queuedMorphTimeout=null},50)}}hasQueuedMorph(){return null!==this.queuedMorph}clearQueue(){this.queuedMorph=null,this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null)}getCanvasPoints(t,e,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 r=s/this.numPoints*Math.PI*2;n.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*i})}return n}const r=Array.isArray(s)?s:[];for(let s=0;s<r.length;s++){const a=r[s];if(a&&"number"==typeof a.x&&"number"==typeof a.y){const s=t+(a.x-.5)*i*2,r=e+(a.y-.5)*i*2;n.push({x:s,y:r})}else{const a=s/r.length*Math.PI*2;n.push({x:t+Math.cos(a)*i,y:e+Math.sin(a)*i})}}for(;n.length<this.numPoints;){const s=n.length/this.numPoints*Math.PI*2;n.push({x:t+Math.cos(s)*i,y:e+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 t=[];for(let e=0;e<this.numPoints;e++){const i=this.currentPoints[e],s=this.targetPoints[e];if(!i||!s){const i=e/this.numPoints*Math.PI*2;t.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)});continue}const n=this.visualProgress;let r,a;const o=["square","circle","star","triangle"],h=o.includes(this.currentShape),l=o.includes(this.targetShape);if(h||l){const t=.5,e=.5;if(l&&!h){const o=s.x-t,h=s.y-e;if(n<.3){const s=n/.3;r=i.x+(t-i.x)*s,a=i.y+(e-i.y)*s}else{const i=(n-.3)/.7;r=t+o*i,a=e+h*i}}else if(h&&!l){const o=i.x-t,h=i.y-e;if(n<.5){const t=n/.5;r=i.x-o*t,a=i.y-h*t}else{const i=(n-.5)/.5;r=t+(s.x-t)*i,a=e+(s.y-e)*i}}else{const o=i.x-t,h=i.y-e,l=s.x-t,c=s.y-e;if(n<.5){const t=n/.5;r=i.x-o*t,a=i.y-h*t}else{const i=(n-.5)/.5;r=t+l*i,a=e+c*i}}}else if("spiral"===this.morphMode){const t=n*Math.PI*2,o=.02*Math.sin(t+.2*e)*(1-2*Math.abs(n-.5));r=i.x+(s.x-i.x)*n+o,a=i.y+(s.y-i.y)*n+o}else if("wave"===this.morphMode){const t=.01*Math.sin(.3*e+n*Math.PI*4);r=i.x+(s.x-i.x)*n+t,a=i.y+(s.y-i.y)*n+t}else r=i.x+(s.x-i.x)*n,a=i.y+(s.y-i.y)*n;t.push({x:r,y:a})}return this.applyAudioDeformation(t)}applyAudioDeformation(t){return this.audioDeformer.applyAudioDeformation(t)}setAudioDeformation(t){const e=Date.now();e-this.lastAudioUpdate>this.audioUpdateInterval&&(this.audioDeformation=Math.max(-1,Math.min(1,t)),this.lastAudioUpdate=e,this.audioDeformer&&this.audioDeformer.setAudioDeformation(Math.abs(this.audioDeformation)))}setVocalEnergy(t){const e=Date.now();e-this.lastVocalUpdate>this.audioUpdateInterval&&(this.vocalEnergy=Math.max(0,Math.min(1,t)),this.lastVocalUpdate=e,this.audioDeformer&&this.audioDeformer.setVocalEnergy(this.vocalEnergy))}getTransitionConfig(t,e){const i=Vr&&Vr.isInitialized?Vr.getShape(t):Xr[t],s=Vr&&Vr.isInitialized?Vr.getShape(e):Xr[e];return"moon"===e?{type:"to_moon",easing:"easeInOutCubic",duration:1500,glowIntensity:1.5,fadeInCrescent:!0}:"moon"===t&&"lunar"===e?{type:"moon_to_lunar",easing:"easeInOutSine",duration:2e3,slideOutCrescent:!1,description:"Crescent shadow moves to center and becomes lunar eclipse"}:"moon"===t?{type:"from_moon",easing:"easeInOutCubic",duration:1e3,slideOutCrescent:!0,shadowSlideRatio:.4,description:"Moon shadow slides away THEN morphs to target"}:"lunar"===e?{type:"eclipse_enter_lunar",startAngle:-30}:"lunar"===t&&"moon"===e?{type:"lunar_to_moon",exitAngle:-30}:"lunar"===t?{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"===t&&"sun"!==e?{type:"sun_fade",fadeEffects:!0}:"sun"!==t&&"sun"===e?{type:"sun_bloom",bloomEffects:!0}:{type:"standard"}}getCurrentShadow(){return this.shadowEffectManager.getCurrentShadow()}getCurrentRenderer(){return null}applyEasing(t){switch(this.transitionConfig?.easing||this.easing||"linear"){case"linear":return t;case"easeInQuad":return t*t;case"easeOutQuad":return t*(2-t);case"easeInOutQuad":return t<.5?2*t*t:(4-2*t)*t-1;case"easeInOutSine":return-(Math.cos(Math.PI*t)-1)/2;default:return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}}calculateBPM(){return this.musicDetector.calculateBPM()}findTempoCandidates(t){return this.musicDetector.findTempoCandidates(t)}clusterIntervals(t){return this.musicDetector.clusterIntervals(t)}checkHarmonicRelation(t,e){return this.musicDetector.checkHarmonicRelation(t,e)}detectTimeSignature(){this.musicDetector.forceFastDetection=this.forceFastDetection;const t=this.musicDetector.detectTimeSignature();return this.detectedTimeSignature=this.musicDetector.detectedTimeSignature,this.timeSignatureConfidence=this.musicDetector.timeSignatureConfidence,this.timeSignatureLocked=this.musicDetector.timeSignatureLocked,t}testWaltzPattern(t,e){return this.musicDetector.testWaltzPattern(t,e)}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 t=document.getElementById("time-sig-display");t&&(t.textContent="โ")}getCurrentMusicInfo(){return{bpm:this.detectedBPM,timeSignature:this.detectedTimeSignature,bpmLocked:this.tempoLocked,timeSigLocked:this.timeSignatureLocked}}generateFallbackCircle(){const t=[];for(let e=0;e<this.numPoints;e++){const i=e/this.numPoints*Math.PI*2;t.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)})}return t}getState(){return{currentShape:this.currentShape,targetShape:this.targetShape,isTransitioning:this.isTransitioning,progress:this.morphProgress,audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy}}getProgress(t=!0){return t?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&&(Nr.release(this.frequencyData),this.frequencyData=null),this.bassHistory&&(Nr.release(this.bassHistory),this.bassHistory=null),this.vocalHistory&&(Nr.release(this.vocalHistory),this.vocalHistory=null),this.audioAnalyzer=null}}class ia{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.ze=null,this.qe=()=>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(t){return!1}}createAnalyser(){if(this.audioContext&&!this.analyser){this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,this.analyser.smoothingTimeConstant=.5;const t=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(t),this.ze=new Uint8Array(t)}}connectAudioElement(t){if(this.audioContext)try{this.elementSource&&this.connectedElement===t||(this.elementSource=this.audioContext.createMediaElementSource(t),this.elementSource.connect(this.analyser),this.elementSource.connect(this.audioContext.destination)),this.source=this.elementSource,this.connectedElement=t,this.isAnalyzing=!0,this.analyze()}catch(e){(e instanceof Error?e.message:String(e)).includes("already been used")&&(this.source=this.elementSource,this.connectedElement=t,this.isAnalyzing=!0,this.analyze())}}analyze(){if(!this.isAnalyzing)return;this.animationFrameId=requestAnimationFrame(this.qe),this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this.ze);let t=0,e=0,i=0;const s=this.audioContext.sampleRate/2/this.dataArray.length,n=Math.floor(this.vocalRange.min/s),r=Math.ceil(this.vocalRange.max/s);for(let s=0;s<this.dataArray.length;s++){const a=this.dataArray[s]/255;t+=a,s>=n&&s<=r&&(e+=a,i++)}this.currentAmplitude=t/this.dataArray.length;const a=i>0?e/i:0;return this.extractFrequencyBands(),this.detectBeat(this.currentAmplitude),{amplitude:this.currentAmplitude,vocalAmplitude:a,frequencies:this.currentFrequencies,rawData:this.dataArray}}extractFrequencyBands(){const t=Math.floor(this.dataArray.length/this.frequencyBands);for(let e=0;e<this.frequencyBands;e++){let i=0;const s=e*t,n=Math.min(s+t,this.dataArray.length);for(let t=s;t<n;t++)i+=this.dataArray[t]/255;const r=i/t;this.currentFrequencies[e]=this.currentFrequencies[e]*this.smoothingFactor+r*(1-this.smoothingFactor)}}detectBeat(t){const e=performance.now();t>this.beatThreshold&&e-this.lastBeatTime>60&&(this.lastBeatTime=e,this.beatCallbacks.forEach(e=>e(t)))}getVocalInstability(){let t=0;const e=this.currentFrequencies.reduce((t,e)=>t+e,0)/this.frequencyBands;for(let i=0;i<this.frequencyBands;i++)t+=Math.pow(this.currentFrequencies[i]-e,2);return t=Math.sqrt(t/this.frequencyBands),Math.min(1,2*t+.5*this.currentAmplitude)}getShapeMorpherData(){return{instability:this.getVocalInstability(),frequencies:[...this.currentFrequencies],amplitude:this.currentAmplitude}}onBeat(t){this.beatCallbacks.push(t)}stop(){if(this.isAnalyzing=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.gainNode){try{this.gainNode.disconnect()}catch(t){}this.gainNode=null}if(this.elementSource&&this.connectedElement){try{this.elementSource.connect(this.analyser)}catch(t){}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.ze=null,this.beatCallbacks=[]}}class sa{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(t,e){if(t===e)return!1;if(this.incompatiblePairs.some(i=>i.includes(t)&&i.includes(e)))return!1;const i=this.getGestureGroup(t),s=this.getGestureGroup(e);if(i===s){const t=this.groups[i];return t&&1!==t.maxSimultaneous}return!("movement"===i&&"movement"===s||"dance"===i&&"dance"===s)}getGestureGroup(t){for(const[e,i]of Object.entries(this.groups))if(i.gestures.includes(t))return e;return null}getGesturePriority(t){const e=this.getGestureGroup(t);return e?this.groups[e].priority:99}getCompatibleGestures(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=[],i=new Set,s=t=>"string"==typeof t?t:t.gestureName,n=[...t].sort((t,e)=>this.getGesturePriority(s(t))-this.getGesturePriority(s(e)));for(const t of n){if(i.has(t))continue;const n=s(t);let r=!0;for(const t of e){const e=s(t);if(!this.canExecuteSimultaneously(n,e)){r=!1;break}}if(r){const r=this.groups[this.getGestureGroup(n)];if(r&&r.maxSimultaneous>0&&e.filter(t=>this.getGestureGroup(s(t))===this.getGestureGroup(n)).length>=r.maxSimultaneous)continue;e.push(t),i.add(t)}}return e}parseChain(t){return t?(this.chains[t]&&(t=this.chains[t]),t.split(">").map(t=>t.trim()).map(t=>t.split("+").map(t=>t.trim()).filter(t=>t))):[]}isEnhancingCombination(t){const e=t.map(t=>"string"==typeof t?t:t.gestureName);return this.enhancingCombinations.some(t=>t.every(t=>e.includes(t)))}getChord(t){return this.chords[t]||null}createChord(t){const e=this.getCompatibleGestures(t),i=this.isEnhancingCombination(e);return{type:"chord",gestures:e.map(t=>"string"==typeof t?t:t.gestureName),isEnhancing:i,timestamp:Date.now()}}isValidGesture(t){return null!==this.getGestureGroup(t)}getAllGestures(){const t=[];for(const e of Object.values(this.groups))t.push(...e.gestures);return[...new Set(t)]}getGestureTiming(t){for(const[e,i]of Object.entries(this.timingClasses))if(i.gestures.includes(t))return{name:e,...i};return null}getNextBeatForGesture(t,e,i=1){const s=this.getGestureTiming(t);if(!s)return e+1;if(-1===s.timing)return e;const n=s.timing/i,r=Math.ceil(e/n)*n;return"offbeat"===s.name?r+.5:r}getFillGestures(t,e="moderate"){const i=this.densityProfiles[e]||this.densityProfiles.moderate;let s;return s=t<80?"energetic":t<120?"rhythmic":t<160?"smooth":"subtle",Math.random()<i.fillProbability&&this.fillPatterns[s]||[]}getNextBeatTiming(t,e,i){return this.getNextBeatForGesture(t,e)}getIntensityFromBPM(t){return t<60?"dense":t<100||t<140?"moderate":"sparse"}applySwingTiming(t,e=.67){return.5==t%1?Math.floor(t)+e:t}}const na=new sa;var ra=Object.freeze({__proto__:null,GestureCompatibility:sa,default:na});class aa{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(t){return this.templates[t.toLowerCase()]||this.templates.straight}getEmphasis(t,e,i){if(!t||!t.pattern)return 0;const s=t.pattern.subdivisions.findIndex(t=>Math.abs(t-i)<.01);return-1===s?0:t.pattern.emphasis[s]||0}getVelocity(t,e,i){if(!t||!t.pattern)return 1;const s=t.pattern.subdivisions.findIndex(t=>Math.abs(t-i)<.01);return-1===s?0:t.pattern.velocities[s]||0}getPreferredGesture(t,e,i,s=[]){if(!t||!t.preferredGestures)return null;let n;n=0===i?"downbeat":.5===i?"offbeat":.25===i||.75===i?"subdivision":"syncopation","Funk"===t.name&&e%4==0&&0===i&&(n="one");const r=t.preferredGestures[n]||t.preferredGestures.fills;if(!r||0===r.length)return null;if(s.length>0){const t=r.filter(t=>s.includes(t));if(t.length>0)return t[Math.floor(Math.random()*t.length)]}return r[Math.floor(Math.random()*r.length)]}humanizeTiming(t,e){if(!t||!t.humanization)return e;const i=t.humanization,s=(Math.random()-.5)*i;return Math.max(0,Math.min(1,e+s))}applySwing(t,e){return t&&t.swing&&0!==t.swing?Math.abs(e-.5)<.01?.5+.5*(t.swing-.5):Math.abs(e-.25)<.01?.25+.25*(t.swing-.5):Math.abs(e-.75)<.01?.75+.25*(t.swing-.5):e:e}setGroove(t,e=null){const i=this.getTemplate(t);return!!i&&("instant"!==(e||this.transitionMode)&&this.currentGroove?this.pendingGroove=i:(this.currentGroove=i,this.pendingGroove=null),!0)}onBeat(t){this.pendingGroove&&("nextBar"===this.transitionMode&&t%4==0||"nextPhrase"===this.transitionMode&&t%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(t){return!!this.currentGroove?.compositeMove&&t%("sparse"===this.currentGroove.intensity?32:16)==0}getLayeredGestures(t,e){if(!this.currentGroove)return null;const i={base:this.getBaseMovement(),accent:null,transition:null,composite:null,velocity:1};this.shouldTriggerComposite(t)&&0===e&&(i.composite=this.getCompositeMove());const s=this.getEmphasis(this.currentGroove,t,e),n=this.getVelocity(this.currentGroove,t,e);return s>.3&&n>.3&&(i.accent=this.getPreferredGesture(this.currentGroove,t,e),i.velocity=n),i.accent&&Math.random()<.3&&(i.transition=this.getTransitionStyle()),i}getGrooveNames(){return Object.keys(this.templates)}getGrooveInfo(t){const e=this.templates[t];return e?{name:e.name,timeSignature:e.timeSignature,description:e.description,intensity:e.intensity,swing:e.swing,baseMovement:e.baseMovement,compositeMove:e.compositeMove}:null}}const oa={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 ha{constructor(t={}){this.performances=new Map,this.contextManager=null,this.sequenceExecutor=null,this.eventManager=t.eventManager||null,this.defaultIntensity=t.defaultIntensity||.7,this.enableContextAdjustment=!1!==t.enableContextAdjustment,this.enableAnalytics=t.enableAnalytics||!1,this.performanceHistory=[],this.maxHistorySize=t.maxHistorySize||100,this.loadBuiltInPerformances()}loadBuiltInPerformances(){Object.entries(oa).forEach(([t,e])=>{this.definePerformance(t,e)})}definePerformance(t,e){this.performances.set(t,{...e,name:t}),this.eventManager&&this.eventManager.emit("performanceDefined",{name:t,definition:e})}getPerformance(t){return this.performances.get(t)||null}hasPerformance(t){return this.performances.has(t)}async perform(t,e={}){const i=this.getPerformance(t);if(!i)return;const s=this.calculateIntensity(i,e),n={performance:i,semanticAction:t,intensity:s,options:e,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,...e}):await this.executeSimplePerformance(i,s,e),this.eventManager&&this.eventManager.emit("performanceComplete",n)}catch(t){this.eventManager&&this.eventManager.emit("performanceError",{...n,error:t})}}async executeSimplePerformance(t,e,i){const{emotion:s,gesture:n,delay:r=0}=t,a=i.mascot||this.mascot;if(a){if(s&&"function"==typeof a.setEmotion){const e=void 0!==i.emotionDuration?i.emotionDuration:t.emotionDuration||500;a.setEmotion(s,e)}n&&"function"==typeof a.express&&(r>0&&await new Promise(t=>setTimeout(t,r)),a.express(n))}}calculateIntensity(t,e){if(void 0!==e.intensity)return Math.max(0,Math.min(1,e.intensity));let i=t.baseIntensity||this.defaultIntensity;if(this.enableContextAdjustment&&e.context){const{context:t}=e;void 0!==t.frustration&&(i+=t.frustration/100*.3),"high"===t.urgency?i+=.2:"medium"===t.urgency&&(i+=.1),"epic"===t.magnitude?i=1:"major"===t.magnitude&&(i=Math.max(i,.9))}return Math.max(0,Math.min(1,i))}recordPerformance(t){this.performanceHistory.push({action:t.semanticAction,intensity:t.intensity,context:t.options.context||{},timestamp:t.timestamp}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift()}getAnalytics(){if(!this.enableAnalytics)return{enabled:!1};const t=this.performanceHistory.length,e={},i={};return this.performanceHistory.forEach(t=>{e[t.action]||(e[t.action]=0,i[t.action]=[]),e[t.action]++,i[t.action].push(t.intensity)}),Object.keys(i).forEach(t=>{const e=i[t];i[t]=e.reduce((t,e)=>t+e,0)/e.length}),{enabled:!0,total:t,byAction:e,avgIntensity:i,history:this.performanceHistory.slice(-20)}}clearAnalytics(){this.performanceHistory=[]}setMascot(t){this.mascot=t}setContextManager(t){this.contextManager=t}setSequenceExecutor(t){this.sequenceExecutor=t}listPerformances(){return Array.from(this.performances.keys())}getPerformanceMetadata(t){const e=this.getPerformance(t);return e?{name:e.name,category:e.category||"custom",emotion:e.emotion,gesture:e.gesture,hasSequence:!!e.sequence,baseIntensity:e.baseIntensity||this.defaultIntensity,description:e.description||""}:null}}class la{constructor(t={}){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory=!1!==t.enableHistory,this.historyLimit=t.historyLimit||50,this.history=[],this.enableDecay=!1!==t.enableDecay,this.frustrationDecayRate=t.frustrationDecayRate||5,this.decayInterval=t.decayInterval||1e4,this.decayTimer=null,this.enableDecay&&this.startDecayTimer()}update(t={}){const e={...this.context};void 0!==t.frustration&&(this.context.frustration=Math.max(0,Math.min(100,t.frustration))),void 0!==t.urgency&&["low","medium","high"].includes(t.urgency)&&(this.context.urgency=t.urgency),void 0!==t.magnitude&&["small","moderate","major","epic"].includes(t.magnitude)&&(this.context.magnitude=t.magnitude),void 0!==t.custom&&(this.context.customValues={...this.context.customValues,...t.custom}),this.enableHistory&&this.addToHistory(e,this.context,t),this.enableDecay&&this.restartDecayTimer()}incrementFrustration(t=10){this.update({frustration:this.context.frustration+t})}decrementFrustration(t=10){this.update({frustration:this.context.frustration-t})}resetFrustration(){this.update({frustration:0})}setUrgency(t){this.update({urgency:t})}setMagnitude(t){this.update({magnitude:t})}setCustom(t,e){this.update({custom:{[t]:e}})}getContext(){return{...this.context}}get(t){return t in this.context?this.context[t]:this.context.customValues[t]}calculateIntensity(t=.5,e={}){let i=t;return!1!==e.useFrustration&&(i+=this.context.frustration/100*.3),!1!==e.useUrgency&&(i+={low:-.1,medium:0,high:.2}[this.context.urgency]||0),!1!==e.useMagnitude&&(i+={small:-.1,moderate:0,major:.15,epic:.3}[this.context.magnitude]||0),void 0!==e.intensityMultiplier&&(i*=e.intensityMultiplier),Math.max(0,Math.min(1,i))}addToHistory(t,e,i){const s={timestamp:Date.now(),previous:t,current:{...e},updates:i,delta:{frustration:e.frustration-t.frustration,urgency:e.urgency!==t.urgency?e.urgency:null,magnitude:e.magnitude!==t.magnitude?e.magnitude:null}};this.history.push(s),this.history.length>this.historyLimit&&this.history.shift()}getHistory(t){return t?this.history.slice(-t):[...this.history]}clearHistory(){this.history=[]}startDecayTimer(){this.decayTimer=setInterval(()=>{if(this.context.frustration>0){const t=Math.max(0,this.context.frustration-this.frustrationDecayRate);this.update({frustration:t})}},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 t=this.history.map(t=>t.current.frustration),e=t.reduce((t,e)=>t+e,0)/t.length,i=Math.max(...t),s=Math.min(...t),n=this.history.reduce((t,e)=>(t[e.current.urgency]=(t[e.current.urgency]||0)+1,t),{}),r=this.history.reduce((t,e)=>(t[e.current.magnitude]=(t[e.current.magnitude]||0)+1,t),{});return{current:{...this.context},frustration:{current:this.context.frustration,average:e,max:i,min:s},urgency:{current:this.context.urgency,distribution:n},magnitude:{current:this.context.magnitude,distribution:r},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 ca{constructor(t={}){this.mascot=t.mascot||null,this.eventManager=t.eventManager||null,this.activeSequences=new Map,this.nextSequenceId=1,this.defaultDelay=t.defaultDelay||0,this.allowConcurrent=!1!==t.allowConcurrent}async execute(t,e={}){if(!Array.isArray(t)||0===t.length)return;const i=e.mascot||this.mascot;if(!i)return;!this.allowConcurrent&&this.activeSequences.size>0&&this.cancelAll();const s=this.nextSequenceId++,n=[...t].sort((t,e)=>t.at-e.at),r={cancelled:!1};this.activeSequences.set(s,r);try{this.eventManager&&this.eventManager.emit("sequenceStart",{sequenceId:s,steps:n,timestamp:Date.now()}),await this.executeSteps(n,i,r,e),this.eventManager&&this.eventManager.emit("sequenceComplete",{sequenceId:s,timestamp:Date.now()})}catch(t){this.eventManager&&this.eventManager.emit("sequenceError",{sequenceId:s,error:t,timestamp:Date.now()})}finally{this.activeSequences.delete(s)}}async executeSteps(t,e,i,s){let n=0;for(const r of t){if(i.cancelled)break;const t=r.at-n;if(t>0&&await this.sleep(t,i),i.cancelled)break;await this.executeStep(r,e,s),n=r.at}}executeStep(t,e,i){const{action:s,value:n,intensity:r,options:a}=t;try{switch(s){case"emotion":if("function"==typeof e.setEmotion){const t=void 0!==r?r:i.intensity,s=a?.duration||i.emotionDuration||500;e.setEmotion(n,void 0!==t?t:s)}break;case"gesture":"function"==typeof e.express&&e.express(n,a);break;case"morph":"function"==typeof e.morphTo&&e.morphTo(n,a);break;case"chain":"function"==typeof e.chain&&e.chain(n,a);break;case"sound":"function"==typeof e.playSound&&e.playSound(n,a)}this.eventManager&&this.eventManager.emit("stepExecuted",{action:s,value:n,timestamp:Date.now()})}catch(t){this.eventManager&&this.eventManager.emit("stepError",{action:s,value:n,error:t,timestamp:Date.now()})}}sleep(t,e){return new Promise(i=>{const s=setTimeout(()=>{e&&(e.Oe=null),i()},t);e&&(e.Oe=s,e.je=i)})}cancel(t){const e=this.activeSequences.get(t);e&&(e.cancelled=!0,e.Oe&&(clearTimeout(e.Oe),e.Oe=null),e.je&&(e.je(),e.je=null),this.activeSequences.delete(t),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:t,timestamp:Date.now()}))}cancelAll(){this.activeSequences.forEach((t,e)=>{t.cancelled=!0,t.Oe&&(clearTimeout(t.Oe),t.Oe=null),t.je&&(t.je(),t.je=null),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:e,timestamp:Date.now()})}),this.activeSequences.clear()}getActiveCount(){return this.activeSequences.size}isActive(){return this.activeSequences.size>0}setMascot(t){this.mascot=t}}let ua=class{constructor(t){if(!t.errorBoundary)throw new Error("GestureController: errorBoundary required");if(!t.config)throw new Error("GestureController: config required");if(!t.state)throw new Error("GestureController: state required");if(!t.throttledWarn)throw new Error("GestureController: throttledWarn required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.performanceMonitor=t.performanceMonitor||null,this.soundSystem=t.soundSystem||null,this.config=t.config,this.Ie=t.state,this.$e=t.throttledWarn,this.Le=t.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 ra}).then(t=>{this.gestureCompatibility=t.default}).catch(t=>{})}express(t,e={}){return this.errorBoundary.wrap(()=>{if(!t)return this.Le;const i=performance.now(),s=Array.isArray(t)||"object"==typeof t&&"chord"===t.type?"chord":t;if(this.performanceMonitor&&this.performanceMonitor.markGestureStart(s),Array.isArray(t))return this.expressChord(t,e);if("object"==typeof t&&"chord"===t.type)return this.expressChord(t.gestures,e);const n=this.rendererMethods[t];if(n&&this.renderer&&this.renderer[n]){if(this.renderer[n](e),this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(t),this.performanceMonitor){const t=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,t-i)}return this.Le}const r=Pi(t);if(r){if(Qs.registerConfig("gesture",t,r),this.Ie.currentModularGesture={type:t,config:r,startTime:performance.now(),duration:r.defaultParams?.duration||1e3,progress:0},this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(t),this.performanceMonitor){const t=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,t-i)}return this.Le}return this.$e(`Unknown gesture: ${t}`,`gesture_${t}`),this.performanceMonitor&&this.performanceMonitor.markGestureEnd(s),this.Le},"gesture-express",this.Le)()}expressChord(t,e={}){return this.errorBoundary.wrap(()=>{if(!t||!Array.isArray(t)||0===t.length)return this.Le;this.gestureCompatibility||Promise.resolve().then(function(){return ra}).then(t=>{this.gestureCompatibility=t.default}).catch(t=>{});const i=this.gestureCompatibility?this.gestureCompatibility.getCompatibleGestures(t):t;return i.forEach(t=>{const i="string"==typeof t?t:t.gestureName;this.executeGestureDirectly(i,e)}),this.gestureCompatibility?.isEnhancingCombination?.(i)&&this.renderer?.specialEffects?.addSparkle?.(),this.Le},"gesture-chord",this.Le)()}executeGestureDirectly(t,e={}){const i=this.rendererMethods[t];i&&this.renderer&&"function"==typeof this.renderer[i]&&this.renderer[i](e)}chain(...t){if(this.gestureCompatibility){const e=t.join(">"),i=this.gestureCompatibility.parseChain(e);this.executeChainSequence(i)}else t.length>0&&this.express(t[0]);return this.Le}executeChainSequence(t){if(!t||0===t.length)return;let e=0;const i=()=>{if(e>=t.length)return;const s=t[e];1===s.length?this.express(s[0]):this.expressChord(s),e++,e<t.length&&setTimeout(i,800)};i()}destroy(){this.currentGesture=null,this.gestureCompatibility=null}};class da{constructor(t={}){const e=t.initialState||{};this.Ge=e.isRunning??!1,this._e=e.debugMode??!1,this.He=e.speaking??!1,this.Ue=e.recording??!1,this.We=e.audioLevel??0,this.Ye=e.sleeping??!1,this.Xe=e.rhythmEnabled??!1,this.Ve=e.currentModularGesture??null,this.Ne=e.breathePhase??"idle",this.Qe=e.breatheStartTime??0,this.Je=e.orbScale??1,this.Ke=e.warningTimestamps??{},this.Ze=e.warningThrottle??5e3,this.ti=t.emit||(()=>{})}get isRunning(){return this.Ge}set isRunning(t){const e=this.Ge!==t;this.Ge=t,e&&this.ti("stateChange",{property:"isRunning",value:t})}get debugMode(){return this._e}set debugMode(t){const e=this._e!==t;this._e=t,e&&this.ti("stateChange",{property:"debugMode",value:t})}get speaking(){return this.He}set speaking(t){const e=this.He!==t;this.He=t,e&&this.ti("stateChange",{property:"speaking",value:t})}get recording(){return this.Ue}set recording(t){const e=this.Ue!==t;this.Ue=t,e&&this.ti("stateChange",{property:"recording",value:t})}get audioLevel(){return this.We}set audioLevel(t){this.We=t}get sleeping(){return this.Ye}set sleeping(t){const e=this.Ye!==t;this.Ye=t,e&&this.ti("stateChange",{property:"sleeping",value:t})}get rhythmEnabled(){return this.Xe}set rhythmEnabled(t){this.Xe=t}get currentModularGesture(){return this.Ve}set currentModularGesture(t){this.Ve=t}get breathePhase(){return this.Ne}set breathePhase(t){this.Ne=t}get breatheStartTime(){return this.Qe}set breatheStartTime(t){this.Qe=t}get orbScale(){return this.Je}set orbScale(t){this.Je=t}get warningTimestamps(){return this.Ke}set warningTimestamps(t){this.Ke=t}get warningThrottle(){return this.Ze}set warningThrottle(t){this.Ze=t}getSnapshot(){return{isRunning:this.Ge,debugMode:this._e,speaking:this.He,recording:this.Ue,audioLevel:this.We,sleeping:this.Ye,rhythmEnabled:this.Xe,currentModularGesture:this.Ve,breathePhase:this.Ne,breatheStartTime:this.Qe,orbScale:this.Je}}reset(){this.Ge=!1,this._e=!1,this.He=!1,this.Ue=!1,this.We=0,this.Ye=!1,this.Xe=!1,this.Ve=null,this.Ne="idle",this.Qe=0,this.Je=1,this.Ke={}}}class pa{constructor(t){if(!t.config)throw new Error("AudioHandler: config required");if(!t.state)throw new Error("AudioHandler: state required");if(!t.emit)throw new Error("AudioHandler: emit required");this.audioAnalyzer=t.audioAnalyzer||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.shapeMorpher=t.shapeMorpher||null,this.renderer=t.renderer||null,this.soundSystem=t.soundSystem||null,this.stateMachine=t.stateMachine||null,this.config=t.config,this.Ie=t.state,this.ti=t.emit,this.Le=t.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.Le}async connectAudio(t){if(!this.audioAnalyzer)return this.Le;if(!this.audioAnalyzer.audioContext)try{await this.audioAnalyzer.init()}catch(t){return this.Le}if(this.audioAnalyzer.audioContext&&"suspended"===this.audioAnalyzer.audioContext.state)try{await this.audioAnalyzer.audioContext.resume()}catch(t){}return this.audioAnalyzer.connectAudioElement(t),this.shapeMorpher&&(this.shapeMorpher.audioAnalyzer=this.audioAnalyzer,this.audioAnalyzer.onBeat(t=>{if(this.shapeMorpher){if(this.shapeMorpher.musicDetector){const e=performance.now();this.shapeMorpher.musicDetector.addOnset(e,t)}this.shapeMorpher.vocalEffectActive&&(this.shapeMorpher.beatGlitchIntensity=.3*t)}})),this.vocalUpdateInterval&&clearInterval(this.vocalUpdateInterval),this.renderer&&this.renderer.startGrooveBob({intensity:.5,frequency:1}),this.vocalUpdateInterval=setInterval(()=>{if(this.audioAnalyzer.isAnalyzing&&this.shapeMorpher){const t=this.audioAnalyzer.currentAmplitude||0,e=this.audioAnalyzer.getVocalInstability()||0;this.shapeMorpher.setVocalEnergy(e),this.shapeMorpher.setAudioDeformation(2*t)}},50),this.renderer&&(this.renderer.audioAnalyzer=this.audioAnalyzer),this.Le}stopSpeaking(){if(!this.Ie.speaking)return this.Le;const t=this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0;return this.audioLevelProcessor&&this.audioLevelProcessor.cleanup(),this.Ie.speaking=!1,this.renderer&&this.renderer.onSpeechStop(),this.ti("speechStopped",{previousAudioLevel:t,returnToBaseTime:500}),this.Le}setVolume(t){const e=Math.max(0,Math.min(1,t));if(this.config.masterVolume=e,this.soundSystem&&this.soundSystem.isAvailable()){const t=this.stateMachine.getCurrentState().emotion;this.soundSystem.setMasterVolume(e,t)}return this.ti("volumeChanged",{volume:e}),this.Le}destroy(){this.disconnectAudio()}}class ma{constructor(t,e={}){this.ei=t,this.ii=e.decayRate??.02,this.si=e.decayFloor??0,this.ni=e.accumulationCap??1,this.ri=e.enabled??!1,this.ai=!1,this.oi=[],this.hi=[]}update(t){if(!this.ri||this.ai)return;const e=this.ei.getSlots(),i=this.ii*t;for(const t of e){if(t.intensity<=this.si)continue;const e=t.intensity;if(t.intensity=Math.max(this.si,t.intensity-i),t.intensity!==e){for(const i of this.oi)i(t.emotion,t.intensity,e);this.ei.O("emotionDecayed",{emotion:t.emotion,intensity:t.intensity,removed:!1}),this.ei.O("slotChanged",{emotion:t.emotion,intensity:t.intensity,action:"decay"})}}this.ei.pruneEmptySlots()}nudge(t,e){this.ei.nudgeEmotion(t,e,this.ni);for(const i of this.hi)i(t,e)}setDecayRate(t){this.ii=Math.max(0,t)}getDecayRate(){return this.ii}setAccumulationCap(t){this.ni=Math.max(0,Math.min(1,t))}enable(){this.ri=!0}disable(){this.ri=!1}isEnabled(){return this.ri}pause(){this.ai=!0}resume(){this.ai=!1}reset(){this.ei.clearEmotions()}onDecay(t){return this.oi.push(t),()=>{this.oi=this.oi.filter(e=>e!==t)}}onNudge(t){return this.hi.push(t),()=>{this.hi=this.hi.filter(e=>e!==t)}}serialize(){return{decayRate:this.ii,decayFloor:this.si,accumulationCap:this.ni,enabled:this.ri,paused:this.ai}}deserialize(t){t&&(this.ii=t.decayRate??this.ii,this.si=t.decayFloor??this.si,this.ni=t.accumulationCap??this.ni,this.ri=t.enabled??this.ri,this.ai=t.paused??this.ai)}destroy(){this.oi.length=0,this.hi.length=0}}class ga{constructor(t){this.li=new Map,this.ti=t||(()=>{})}applyModifier(t,e){this.li.set(t,{name:t,config:{...e},remaining:e.duration??null,startTime:Date.now()}),this.ti("modifierApplied",{name:t,config:e})}removeModifier(t){this.li.get(t)&&(this.li.delete(t),this.ti("modifierExpired",{name:t,manual:!0}))}update(t){const e=[];for(const[i,s]of this.li)null!==s.remaining&&(s.remaining-=t,s.remaining<=0)?(e.push(i),s.config.onExpire&&s.config.onExpire()):s.config.onTick&&s.config.onTick(s.remaining);for(const t of e)this.li.delete(t),this.ti("modifierExpired",{name:t,manual:!1})}getCompositeModifiers(){let t=1,e=0,i=0,s=0;for(const n of this.li.values()){const r=n.config;void 0!==r.rhythmWindowMult&&(t*=r.rhythmWindowMult),void 0!==r.tempoShift&&(e+=r.tempoShift),void 0!==r.visualNoise&&(i+=r.visualNoise),void 0!==r.inputDelay&&(s+=r.inputDelay)}return{rhythmWindowMult:t,tempoShift:e,visualNoise:i,inputDelay:s}}getActiveModifiers(){return[...this.li.values()].map(t=>({name:t.name,remaining:t.remaining,config:{...t.config}}))}hasModifier(t){return this.li.has(t)}clear(){this.li.clear()}serialize(){const t=[];for(const e of this.li.values()){const{onTick:i,onExpire:s,...n}=e.config;t.push({name:e.name,remaining:e.remaining,config:n})}return t}deserialize(t){if(Array.isArray(t)){this.li.clear();for(const e of t)this.li.set(e.name,{name:e.name,config:e.config||{},remaining:e.remaining,startTime:Date.now()})}}}class fa{constructor(t){if(!t.stateMachine)throw new Error("StateCoordinator: stateMachine required");if(!t.config)throw new Error("StateCoordinator: config required");if(!t.emit)throw new Error("StateCoordinator: emit required");this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem||null,this.canvasManager=t.canvasManager||null,this.renderer=t.renderer||null,this.config=t.config,this.soundSystem=t.soundSystem||null,this.ti=t.emit,this.Le=t.chainTarget||this,this.currentEmotion="neutral",this.emotionIntensity=1,this.stateMachine.setEventCallback&&this.stateMachine.setEventCallback((t,e)=>{this.ti(t,e)}),this.ci=null,this.Nt=new ga((t,e)=>this.ti(t,e))}init(){}setEmotion(t,e=null){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;let s=null,n=500,r=1;if("string"==typeof e?s=e:e&&"object"==typeof e&&(s=e.undertone||null,n=e.duration||500,r=e.intensity??1),this.emotionIntensity=r,this.stateMachine.setEmotion(i,{undertone:s,duration:n,intensity:r})){const t=l(i);if(t&&Qs.registerConfig("emotion",i,t),this.particleSystem){this.particleSystem.clear();const t=this.stateMachine.getCurrentEmotionalProperties();let e;if(e="neutral"===i?1:"resting"===i?4:Math.min(3,Math.floor(t.particleRate/4)),e>0){let i,s;if(this.renderer&&"function"==typeof this.renderer.getEffectiveCenter){const t=this.renderer.getEffectiveCenter();i=t.x,s=t.y}else i=this.canvasManager.width/2,s=this.canvasManager.height/2;this.particleSystem.burst(e,t.particleBehavior,i,s)}}if("classic"===this.config.renderingStyle&&this.renderer.setEmotionalState){const t=c(i);this.renderer.setEmotionalState(i,t,s)}this.ti("emotionChanged",{emotion:i,undertone:s,duration:n})}return this.currentEmotion=i,this.Le}pushEmotion(t,e=.5){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;this.stateMachine.pushEmotion(i,e);const s=this.stateMachine.getDominant();return s&&(this.currentEmotion=s.emotion),this.ti("emotionChanged",{emotion:this.currentEmotion,slots:this.stateMachine.getSlots()}),this.Le}nudgeEmotion(t,e,i=1){const s={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;this.stateMachine.nudgeEmotion(s,e,i);const n=this.stateMachine.getDominant();return n&&(this.currentEmotion=n.emotion),this.Le}clearEmotions(){return this.stateMachine.clearEmotions(),this.currentEmotion="neutral",this.ti("emotionChanged",{emotion:"neutral",slots:[]}),this.Le}getEmotionalState(){return this.stateMachine.getEmotionalState()}get dynamics(){return this.ci||(this.ci=new ma(this.stateMachine)),this.ci}setEmotionDampening(t){return this.stateMachine.setEmotionDampening(t),this.Le}getEmotionDampening(){return this.stateMachine.getEmotionDampening()}get modifiers(){return this.Nt}destroy(){this.ci&&this.ci.destroy(),this.Nt.clear(),this.currentEmotion="neutral"}}class ya{constructor(t){if(!t.animationController)throw new Error("VisualizationRunner: animationController required");if(!t.stateMachine)throw new Error("VisualizationRunner: stateMachine required");if(!t.config)throw new Error("VisualizationRunner: config required");if(!t.state)throw new Error("VisualizationRunner: state required");if(!t.emit)throw new Error("VisualizationRunner: emit required");this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem||null,this.canvasManager=t.canvasManager||null,this.renderer=t.renderer||null,this.audioHandler=t.audioHandler||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.gazeTracker=t.gazeTracker||null,this.idleBehavior=t.idleBehavior||null,this.degradationManager=t.degradationManager||null,this.pluginSystem=t.pluginSystem||null,this.config=t.config,this.canvas=t.canvas||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this,this.animationId=null,this.isRunning=!1,this.lastTime=0}init(){}start(){if(this.animationController.isAnimating())return this.Le;if(this.animationController.start()){if(this.Ie.isRunning=!0,this.isRunning=!0,"classic"===this.config.renderingStyle&&this.particleSystem){const t=this.stateMachine.getCurrentState(),{emotion:e}=t,i=c(e);let s,n;if(this.renderer&&this.renderer.getCurrentOrbPosition){const t=this.renderer.getCurrentOrbPosition();s=t.x,n=t.y}else s=this.canvasManager.width/2,n=this.canvasManager.height/2;if(this.particleSystem.clear(),i.particleRate>0){const t=Math.min(3,Math.floor(i.particleRate/4));t>0&&this.particleSystem.burst(t,i.particleBehavior,s,n)}}this.degradationManager&&this.degradationManager.startMonitoring(),this.ti("started")}return this.Le}stop(){return this.animationController.isAnimating()?(this.Ie.speaking&&this.audioHandler&&this.audioHandler.stopSpeaking(),this.animationController.stop()&&(this.Ie.isRunning=!1,this.isRunning=!1,this.degradationManager&&this.degradationManager.stopMonitoring(),this.ti("stopped")),this.Le):this.Le}update(t){if(this.Ie.speaking&&this.audioLevelProcessor&&this.audioLevelProcessor.isProcessingActive()&&this.audioLevelProcessor.updateAudioLevel(t),"classic"===this.config.renderingStyle){if(this.gazeTracker&&(this.gazeTracker.update(t),"suspicion"===this.stateMachine.getCurrentState().emotion)){const{mousePos:t}=this.gazeTracker,e=this.canvas.width/2,i=this.canvas.height/2,s=Math.sqrt(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)),n=l("suspicion");if(n&&n.visual){const t=Math.min(e,i),r=Math.max(0,Math.min(1,1-s/t));n.visual.threatLevel=r}}if(this.idleBehavior&&this.idleBehavior.update(t),this.gazeTracker&&this.idleBehavior){const t=this.gazeTracker.getGazeOffset(),e=this.idleBehavior.getSwayOffset(),i=this.gazeTracker.getState(),s={offset:{x:t.x+e.x,y:t.y+e.y},proximity:i.proximity,isFocused:i.isFocused};this.renderer&&this.renderer.setGazeData&&this.renderer.setGazeData(s)}}if(this.pluginSystem){const e=this.stateMachine.getCurrentState();this.pluginSystem.update(t,e)}}destroy(){this.stop()}}class Ma{constructor(t){if(!t.errorBoundary)throw new Error("ExecutionLifecycleManager: errorBoundary required");if(!t.animationController)throw new Error("ExecutionLifecycleManager: animationController required");if(!t.visualizationRunner)throw new Error("ExecutionLifecycleManager: visualizationRunner required");if(!t.state)throw new Error("ExecutionLifecycleManager: state required");if(!t.emit)throw new Error("ExecutionLifecycleManager: emit required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.visualizationRunner=t.visualizationRunner,this.soundSystem=t.soundSystem||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}start(){return this.errorBoundary.wrap(()=>this.visualizationRunner.start(),"start",this.Le)()}stop(){return this.errorBoundary.wrap(()=>this.visualizationRunner.stop(),"stop",this.Le)()}pause(){return this.errorBoundary.wrap(()=>this.animationController.isAnimating()?(this.animationController.stop(),this.Ie.isRunning=!1,this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.stopAmbientTone(200),this.ti("paused"),this.Le):this.Le,"pause",this.Le)()}resume(){return this.errorBoundary.wrap(()=>(this.animationController.isAnimating()||(this.animationController.start(),this.Ie.isRunning=!0,this.ti("resumed")),this.Le),"resume",this.Le)()}isActive(){return this.animationController.isAnimating()}}class ba{constructor(t){if(!t.errorBoundary)throw new Error("AnimationFrameController: errorBoundary required");if(!t.animationController)throw new Error("AnimationFrameController: animationController required");if(!t.config)throw new Error("AnimationFrameController: config required");if(!t.emit)throw new Error("AnimationFrameController: emit required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.positionController=t.positionController||null,this.config=t.config,this.ti=t.emit,this.Le=t.chainTarget||this}setTargetFPS(t){const e=Math.max(15,Math.min(120,t));return this.config.targetFPS=e,this.animationController.setTargetFPS(e),this.ti("targetFPSChanged",{targetFPS:e}),this.Le}getTargetFPS(){return this.animationController.targetFPS}setPosition(t,e,i=0){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.setOffset(t,e,i)),this.Le}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.animateOffset(t,e,i,s,n)),this.Le}getPosition(){return this.errorBoundary.wrap(()=>{if(!this.positionController||"function"!=typeof this.positionController.getPosition)return null;const t="undefined"!=typeof window,e=t?window.innerWidth/2:0,i=t?window.innerHeight/2:0;return this.positionController.getPosition(e,i)},"get-position",this.Le)()}}class wa{constructor(t){if(!t.errorBoundary)throw new Error("ShapeTransformManager: errorBoundary required");if(!t.emit)throw new Error("ShapeTransformManager: emit required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.shapeMorpher=t.shapeMorpher||null,this.ti=t.emit,this.Le=t.chainTarget||this}morphTo(t,e={}){return this.errorBoundary.wrap(()=>this.shapeMorpher?(this.shapeMorpher.morphTo(t,e),this.renderer&&(this.renderer.shapeMorpher=this.shapeMorpher),this.ti("shapeMorphStarted",{from:this.shapeMorpher.currentShape,to:t}),this.Le):this.Le,"morphTo",this.Le)()}setBackdrop(t={}){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.backdropRenderer&&this.renderer.backdropRenderer.setConfig(t),this.Le),"setBackdrop",this.Le)()}getBackdrop(){return this.errorBoundary.wrap(()=>this.renderer&&this.renderer.backdropRenderer?this.renderer.backdropRenderer.getConfig():null,"getBackdrop",this.Le)()}}class va{constructor(t){if(!t.errorBoundary)throw new Error("EventListenerManager: errorBoundary required");if(!t.eventManager)throw new Error("EventListenerManager: eventManager required");this.errorBoundary=t.errorBoundary,this.eventManager=t.eventManager,this.Le=t.chainTarget||this}on(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.on(t,e),this.Le),"event-listener-add",this.Le)()}off(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.off(t,e),this.Le),"event-listener-remove",this.Le)()}once(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.once(t,e),this.Le),"event-listener-once",this.Le)()}removeAllListeners(t=null){return this.errorBoundary.wrap(()=>(this.eventManager.removeAllListeners(t),this.Le),"event-listeners-clear",this.Le)()}listenerCount(t){return this.eventManager.listenerCount(t)}getEventNames(){return this.eventManager.getEventNames()}getEventStats(){return this.eventManager.getEventStats()}getEventDebugInfo(){return this.eventManager.getDebugInfo()}emit(t,e=null){this.eventManager.emit(t,e)}}class Sa{constructor(t){if(!t.tts)throw new Error("TTSManager: tts required");if(!t.state)throw new Error("TTSManager: state required");this.speechManager=t.speechManager||null,this.renderer=t.renderer||null,this.tts=t.tts,this.Ie=t.state,this.Le=t.chainTarget||this}getTTSVoices(){return this.tts.available?window.speechSynthesis.getVoices():[]}isTTSSpeaking(){return this.tts.speaking}speak(t,e={}){return this.speechManager?this.speechManager.speak(t,e):this.Le}setTTSSpeaking(t){this.Ie.ttsSpeaking=t,this.renderer&&this.renderer.startSpeaking&&(t?this.renderer.startSpeaking():this.renderer.stopSpeaking()),this.Ie.speaking=t}getVoices(){return window.speechSynthesis?window.speechSynthesis.getVoices():[]}stopTTS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),this.setTTSSpeaking(!1))}}class ka{constructor(t){if(!t.errorBoundary)throw new Error("SpeechReactivityManager: errorBoundary required");if(!t.audioLevelProcessor)throw new Error("SpeechReactivityManager: audioLevelProcessor required");if(!t.state)throw new Error("SpeechReactivityManager: state required");if(!t.emit)throw new Error("SpeechReactivityManager: emit required");this.errorBoundary=t.errorBoundary,this.audioLevelProcessor=t.audioLevelProcessor,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}connectAudioSource(t){return this.errorBoundary.wrap(()=>this.Ie.audioAnalyser&&t&&"function"==typeof t.connect?(t.connect(this.Ie.audioAnalyser),this.ti("audioSourceConnected",{audioSource:t}),this.Le):this.Le,"audio-source-connection",this.Le)()}getAudioLevel(){return this.Ie.speaking?this.Ie.audioLevel:0}isSpeaking(){return this.Ie.speaking}setAudioSmoothing(t){return this.errorBoundary.wrap(()=>{const e=Math.max(0,Math.min(1,t));return this.Ie.audioAnalyser&&(this.Ie.audioAnalyser.smoothingTimeConstant=e),this.Le},"audio-smoothing",this.Le)()}getAudioStats(){return this.audioLevelProcessor.getStats()}updateAudioConfig(t){this.audioLevelProcessor.updateConfig(t)}}class xa{constructor(t){if(!t.emit)throw new Error("CanvasResizeManager: emit required");this.renderer=t.renderer||null,this.stateMachine=t.stateMachine||null,this.particleSystem=t.particleSystem||null,this.ti=t.emit,this.Le=t.chainTarget||this}handleResize(t,e,i){if(this.renderer&&this.renderer.initOffscreenCanvas&&this.renderer.initOffscreenCanvas(),this.stateMachine){const{currentEmotion:t}=this.stateMachine,{currentUndertone:e}=this.stateMachine;t&&this.stateMachine.setEmotion(t),e&&"none"!==e&&this.stateMachine.setUndertone(e)}this.ti("resize",{width:t,height:e,dpr:i})}clearParticles(){return this.particleSystem&&this.particleSystem.clear(),this.Le}setParticleSystemCanvasDimensions(t,e){return this.particleSystem&&(this.particleSystem.canvasWidth=t,this.particleSystem.canvasHeight=e),this.Le}}class Ea{constructor(t){if(!t.errorBoundary)throw new Error("OffsetPositionManager: errorBoundary required");if(!t.positionController)throw new Error("OffsetPositionManager: positionController required");this.errorBoundary=t.errorBoundary,this.positionController=t.positionController,this.Le=t.chainTarget||this}setOffset(t,e,i=0){return this.errorBoundary.wrap(()=>(this.positionController.setOffset(t,e,i),this.Le),"offset-setting",this.Le)()}getOffset(){return this.errorBoundary.wrap(()=>this.positionController.getOffset(),"offset-getting",this.Le)()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.errorBoundary.wrap(()=>(this.positionController.animateOffset(t,e,i,s,n),this.Le),"offset-animation",this.Le)()}}class Ba{constructor(t){if(!t.canvasResizeManager)throw new Error("VisualTransformationManager: canvasResizeManager required");if(!t.offsetPositionManager)throw new Error("VisualTransformationManager: offsetPositionManager required");if(!t.shapeTransformManager)throw new Error("VisualTransformationManager: shapeTransformManager required");this.canvasResizeManager=t.canvasResizeManager,this.offsetPositionManager=t.offsetPositionManager,this.shapeTransformManager=t.shapeTransformManager,this.Le=t.chainTarget||this}setOffset(t,e,i=0){return this.offsetPositionManager.setOffset(t,e,i)}getOffset(){return this.offsetPositionManager.getOffset()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.offsetPositionManager.animateOffset(t,e,i,s,n)}morphTo(t,e={}){return this.shapeTransformManager.morphTo(t,e)}setBackdrop(t={}){return this.shapeTransformManager.setBackdrop(t)}getBackdrop(){return this.shapeTransformManager.getBackdrop()}handleResize(t,e,i){this.canvasResizeManager.handleResize(t,e,i)}clearParticles(){return this.canvasResizeManager.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.canvasResizeManager.setParticleSystemCanvasDimensions(t,e)}}class Aa{constructor(t){if(!t.errorBoundary)throw new Error("FrustrationContextManager: errorBoundary required");if(!t.contextManager)throw new Error("FrustrationContextManager: contextManager required");this.errorBoundary=t.errorBoundary,this.contextManager=t.contextManager,this.Le=t.chainTarget||this}updateContext(t){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.update(t),this.Le):this.Le,"context-update",this.Le)()}incrementFrustration(t=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.incrementFrustration(t),this.Le):this.Le,"frustration-increment",this.Le)()}decrementFrustration(t=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.decrementFrustration(t),this.Le):this.Le,"frustration-decrement",this.Le)()}resetFrustration(){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.resetFrustration(),this.Le):this.Le,"frustration-reset",this.Le)()}}class Ca{constructor(t,e={}){if(!t)throw new Error("LLMResponseHandler requires a mascot instance");this.mascot=t,this.config={autoMorphShapes:!0,morphDuration:1e3,autoExpressGestures:!0,gestureTiming:300,gestureIntensity:.7,useFallbackGestures:!0,useSemanticPerformances:!0,enableContextTracking:!0,emotionToShapeMap:{},actionToGestureMap:{},...e},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(t,e={}){try{e.skipValidation||this.validateResponse(t);const{emotion:i="neutral",sentiment:s="neutral",action:n="none",shape:r,gesture:a,frustrationLevel:o=0}=t,h=void 0!==e.intensity?e.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 t=this.semanticActionMap[n];try{return await this.mascot.perform(t,{context:{frustration:o,sentiment:s,urgency:o>60?"high":o>30?"medium":"low"},intensity:h}),r&&this.config.autoMorphShapes&&await this.morphToShape(r),this.mascot}catch(t){}}return await this.choreographResponse(i,n,r,a,h),this.mascot}catch(t){return this.mascot}}async choreographResponse(t,e,i,s,n){if(this.mascot.setEmotion(t,n),this.config.autoMorphShapes){const s=i||this.getShapeForEmotion(t,e);s&&await this.morphToShape(s)}if(this.config.autoExpressGestures){const t=s||this.getGestureForAction(e);t&&(await this.delay(this.config.gestureTiming),this.mascot.express(t,{intensity:this.config.gestureIntensity}))}}calculateIntensity(t,e){let i=.5;return i+=t/100*.3,"positive"===e?i+=.2:"negative"===e&&(i+=.3),Math.max(.3,Math.min(1,i))}getShapeForEmotion(t,e){return this.config.emotionToShapeMap[t]?this.config.emotionToShapeMap[t]:"celebrate"===e?"star":"greet"===e?"sun":this.defaultShapeMap[t]||null}getGestureForAction(t){return this.config.useFallbackGestures?this.config.actionToGestureMap[t]?this.config.actionToGestureMap[t]:this.defaultGestureMap[t]||null:null}morphToShape(t){t&&"circle"!==t&&this.mascot.morphTo&&this.mascot.morphTo(t,{duration:this.config.morphDuration})}validateResponse(t){if(!t||"object"!=typeof t)throw new Error("LLM response must be an object");if(t.emotion&&this.schema.emotion.includes(t.emotion),t.sentiment&&this.schema.sentiment.includes(t.sentiment),t.action&&this.schema.action.includes(t.action),t.shape&&this.schema.shape.includes(t.shape),t.gesture&&this.schema.gesture.includes(t.gesture),void 0!==t.frustrationLevel){const e=Number(t.frustrationLevel);isNaN(e)}}getSchema(){return{...this.schema}}configure(t){return Object.assign(this.config,t),this}delay(t){return new Promise(e=>setTimeout(e,t))}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 Ta{constructor(t){if(!t.errorBoundary)throw new Error("LLMIntegrationBridge: errorBoundary required");this.errorBoundary=t.errorBoundary,this.ui=t.mascotRef,this.Le=t.chainTarget||this,this.di=null}pi(t={}){return this.di||(this.di=new Ca(this.ui,t)),this.di}handleLLMResponse(t,e={}){return this.errorBoundary.wrap(async()=>{const i=this.pi(e);return await i.handle(t,e),this.Le},"handleLLMResponse",this.Le)()}configureLLMHandler(t){return this.errorBoundary.wrap(()=>(this.pi(t).configure(t),this.Le),"configureLLMHandler",this.Le)()}getLLMResponseSchema(){return this.pi().getSchema()}static getLLMPromptTemplate(t={}){return function(t={}){const{domain:e="general assistance",personality:i="friendly, empathetic, and helpful",brand:s="our service",customEmotions:n=[],customActions:r=[]}=t,a=["offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond",...r];return`You are a ${i} AI assistant for ${s}, providing ${e}. 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": "${a.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 ${e} 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.`}(t)}static getLLMEmotions(){return Ca.getAvailableEmotions()}static getLLMActions(){return Ca.getAvailableActions()}static getLLMShapes(){return Ca.getAvailableShapes()}static getLLMGestures(){return Ca.getAvailableGestures()}}class Pa{constructor(t){if(!t.errorBoundary)throw new Error("DiagnosticsManager: errorBoundary required");if(!t.animationController)throw new Error("DiagnosticsManager: animationController required");if(!t.stateMachine)throw new Error("DiagnosticsManager: stateMachine required");if(!t.config)throw new Error("DiagnosticsManager: config required");if(!t.state)throw new Error("DiagnosticsManager: state required");if(!t.getCurrentState)throw new Error("DiagnosticsManager: getCurrentState required");if(!t.getAudioStats)throw new Error("DiagnosticsManager: getAudioStats required");if(!t.getEventStats)throw new Error("DiagnosticsManager: getEventStats required");this.errorBoundary=t.errorBoundary,this.degradationManager=t.degradationManager||null,this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.performanceSystem=t.performanceSystem||null,this.config=t.config,this.Ie=t.state,this.mi=t.getCurrentState,this.gi=t.getAudioStats,this.fi=t.getEventStats,this.Le=t.chainTarget||this}getBrowserCompatibility(){return{browser:Ur.browser,features:Ur.featureDetection.getFeatures(),capabilities:Ur.capabilities,appliedPolyfills:Ur.appliedPolyfills,optimizations:Ur.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(t){return!!this.degradationManager&&this.degradationManager.setLevel(t)}getDebugReport(){const t={timestamp:Date.now(),mascot:{isRunning:this.Ie.isRunning,speaking:this.Ie.speaking,debugMode:this.Ie.debugMode,config:this.config},currentState:this.mi(),performanceMetrics:this.getPerformanceMetrics(),audioStats:this.gi(),eventStats:this.fi(),browserCompatibility:this.getBrowserCompatibility(),degradationStatus:this.getDegradationStatus(),runtimeCapabilities:Ss.generateReport(),debuggerReport:vs.getDebugReport()};return this.Ie.debugMode&&vs.log("DEBUG","Generated debug report",{reportSize:JSON.stringify(t).length,sections:Object.keys(t)}),t}exportDebugData(){const t={metadata:{exportTime:Date.now(),version:"1.0.0",userAgent:navigator.userAgent,url:window.location?.href},mascotState:{config:this.config,currentState:this.mi(),isRunning:this.Ie.isRunning,speaking:this.Ie.speaking},performance:{metrics:this.getPerformanceMetrics(),degradationStatus:this.getDegradationStatus(),frameTimings:vs.frameTimings},compatibility:{browser:this.getBrowserCompatibility(),runtimeCapabilities:Ss.generateReport()},debuggerData:vs.exportDebugData()};return this.Ie.debugMode&&vs.log("INFO","Exported debug data",{dataSize:JSON.stringify(t).length}),t}getPerformanceMetrics(){const t=this.animationController.getPerformanceMetrics(),e=this.stateMachine.getCurrentState();return{...t,currentEmotion:e.emotion,currentUndertone:e.undertone,isTransitioning:e.isTransitioning,errorStats:this.errorBoundary.getErrorStats()}}getPerformanceAnalytics(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAnalytics():null,"performance-analytics",this.Le)()}}class Da{constructor(t){if(!t.errorBoundary)throw new Error("EmotionalStateQueryManager: errorBoundary required");if(!t.stateMachine)throw new Error("EmotionalStateQueryManager: stateMachine required");this.errorBoundary=t.errorBoundary,this.stateMachine=t.stateMachine,this.contextManager=t.contextManager||null,this.performanceSystem=t.performanceSystem||null,this.Le=t.chainTarget||this}getEmotionalColor(){const t=this.stateMachine.getCurrentEmotionalProperties();return t?.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.Le)()}getAvailableShapes(){return ea.getAvailableShapes()}getContext(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getContext():null,"context-get",this.Le)()}getContextAnalytics(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getAnalytics():null,"context-analytics",this.Le)()}}class Ra{constructor(t){if(!t.diagnosticsManager)throw new Error("DebugProfilingManager: diagnosticsManager required");this.diagnosticsManager=t.diagnosticsManager,this.Ie=t.state||{debugMode:!1}}getDebugReport(){return this.diagnosticsManager.getDebugReport()}exportDebugData(){return this.diagnosticsManager.exportDebugData()}startProfiling(t,e={}){this.Ie.debugMode&&vs.startProfile(t,e)}endProfiling(t){return this.Ie.debugMode?vs.endProfile(t):null}takeMemorySnapshot(t){this.Ie.debugMode&&vs.takeMemorySnapshot(t)}clearDebugData(){vs.clear(),this.Ie.debugMode&&vs.log("INFO","Debug data cleared")}getRuntimeCapabilities(){return Ss.generateReport()}}class Fa{constructor(t){if(!t.errorBoundary)throw new Error("PerformanceBehaviorManager: errorBoundary required");if(!t.frustrationContextManager)throw new Error("PerformanceBehaviorManager: frustrationContextManager required");if(!t.emotionalStateQueryManager)throw new Error("PerformanceBehaviorManager: emotionalStateQueryManager required");if(!t.diagnosticsManager)throw new Error("PerformanceBehaviorManager: diagnosticsManager required");this.errorBoundary=t.errorBoundary,this.performanceSystem=t.performanceSystem||null,this.frustrationContextManager=t.frustrationContextManager,this.emotionalStateQueryManager=t.emotionalStateQueryManager,this.diagnosticsManager=t.diagnosticsManager,this.Le=t.chainTarget||this}perform(t,e={}){return this.errorBoundary.wrap(async()=>this.performanceSystem?(e.context&&this.frustrationContextManager.updateContext(e.context),await this.performanceSystem.perform(t,{...e,mascot:this.Le}),this.Le):this.Le,"semantic-performance",this.Le)()}registerPerformance(t,e){return this.errorBoundary.wrap(()=>this.performanceSystem?(this.performanceSystem.registerPerformance(t,e),this.Le):this.Le,"performance-register",this.Le)()}getAvailablePerformances(){return this.emotionalStateQueryManager.getAvailablePerformances()}getPerformanceAnalytics(){return this.diagnosticsManager.getPerformanceAnalytics()}getContextAnalytics(){return this.emotionalStateQueryManager.getContextAnalytics()}}class za{constructor(t){if(!t.diagnosticsManager)throw new Error("PerformanceMonitoringManager: diagnosticsManager required");if(!t.animationFrameController)throw new Error("PerformanceMonitoringManager: animationFrameController required");if(!t.animationController)throw new Error("PerformanceMonitoringManager: animationController required");if(!t.particleSystem)throw new Error("PerformanceMonitoringManager: particleSystem required");if(!t.config)throw new Error("PerformanceMonitoringManager: config required");this.diagnosticsManager=t.diagnosticsManager,this.degradationManager=t.degradationManager||null,this.animationFrameController=t.animationFrameController,this.animationController=t.animationController,this.particleSystem=t.particleSystem,this.healthCheckManager=t.healthCheckManager,this.config=t.config,this.Le=t.chainTarget||this}getDegradationStatus(){return this.diagnosticsManager.getDegradationStatus()}setDegradationLevel(t){return this.diagnosticsManager.setDegradationLevel(t)}isFeatureAvailable(t){return this.degradationManager?this.degradationManager.isFeatureAvailable(t):Ur.featureDetection.getFeatures()[t]||!1}setTargetFPS(t){return this.animationFrameController.setTargetFPS(t)}getTargetFPS(){return this.animationFrameController.getTargetFPS()}setPerformanceDegradation(t){const e=this.animationController.getPerformanceMetrics();if(t&&!e.performanceDegradation){const t=this.particleSystem.maxParticles,e=Math.max(5,Math.floor(.5*t));this.particleSystem.setMaxParticles(e)}else!t&&e.performanceDegradation&&this.particleSystem.setMaxParticles(this.config.maxParticles);return this.Le}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}}class qa{constructor(t){if(!t.errorBoundary)throw new Error("HealthCheckManager: errorBoundary required");if(!t.diagnosticsManager)throw new Error("HealthCheckManager: diagnosticsManager required");if(!t.mobileOptimization)throw new Error("HealthCheckManager: mobileOptimization required");if(!t.accessibilityManager)throw new Error("HealthCheckManager: accessibilityManager required");if(!t.config)throw new Error("HealthCheckManager: config required");this.errorBoundary=t.errorBoundary,this.systemStatusReporter=t.systemStatusReporter||null,this.diagnosticsManager=t.diagnosticsManager,this.mobileOptimization=t.mobileOptimization,this.accessibilityManager=t.accessibilityManager,this.config=t.config,this.Le=t.chainTarget||this}getSystemStatus(){return this.systemStatusReporter?this.systemStatusReporter.getSystemStatus():{}}setDebugMode(t){return this.config.showDebug=!!t,this.config.showFPS=!!t,this.Le}triggerTestError(t="manual-test"){return this.errorBoundary.wrap(()=>{throw new Error(`Test error triggered in context: ${t}`)},t,this.Le)()}getPerformanceMetrics(){return this.diagnosticsManager.getPerformanceMetrics()}getMobileStatus(){return this.mobileOptimization.getStatus()}getAccessibilityStatus(){return this.accessibilityManager.getStatus()}}class Oa{constructor(t){this.mascot=t}initialize(t){const e=this.mascot;this.yi(e,t),this.Mi(e,t),this.bi(e,t),e.audioHandler.init(),e.stateCoordinator.init(),e.visualizationRunner.init()}yi(t,e){t.audioHandler=new pa({audioAnalyzer:t.audioAnalyzer,audioLevelProcessor:t.audioLevelProcessor,shapeMorpher:t.shapeMorpher,soundSystem:t.soundSystem,renderer:t.renderer,errorBoundary:t.errorBoundary,config:t.config,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get audioLevel(){return t.audioLevel},set audioLevel(e){t.audioLevel=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.stateCoordinator=new fa({stateMachine:t.stateMachine,particleSystem:t.particleSystem,canvasManager:t.canvasManager,renderer:t.renderer,soundSystem:t.soundSystem,config:t.config,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.visualizationRunner=new ya({animationController:t.animationController,stateMachine:t.stateMachine,particleSystem:t.particleSystem,canvasManager:t.canvasManager,renderer:t.renderer,audioHandler:t.audioHandler,audioLevelProcessor:t.audioLevelProcessor,gazeTracker:t.gazeTracker,idleBehavior:t.idleBehavior,degradationManager:t.degradationManager,pluginSystem:t.pluginSystem,config:t.config,canvas:t.canvas,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get isRunning(){return t.isRunning},set isRunning(e){t.isRunning=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.executionLifecycleManager=new Ma({animationController:t.animationController,visualizationRunner:t.visualizationRunner,idleBehavior:t.idleBehavior,gazeTracker:t.gazeTracker,renderer:t.renderer,errorBoundary:t.errorBoundary,state:{get isRunning(){return t.isRunning},set isRunning(e){t.isRunning=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.animationFrameController=new ba({animationController:t.animationController,positionController:t.positionController,config:t.config,errorBoundary:t.errorBoundary,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.shapeTransformManager=new wa({shapeMorpher:t.shapeMorpher,renderer:t.renderer,errorBoundary:t.errorBoundary,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.eventListenerManager=new va({eventManager:t.eventManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.ttsManager=new Sa({soundSystem:t.soundSystem,errorBoundary:t.errorBoundary,config:t.config,tts:t.tts,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.speechReactivityManager=new ka({audioLevelProcessor:t.audioLevelProcessor,renderer:t.renderer,errorBoundary:t.errorBoundary,config:t.config,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get audioLevel(){return t.audioLevel},set audioLevel(e){t.audioLevel=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.canvasResizeManager=new xa({renderer:t.renderer,stateMachine:t.stateMachine,particleSystem:t.particleSystem,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.offsetPositionManager=new Ea({positionController:t.positionController,errorBoundary:t.errorBoundary,chainTarget:t}),t.visualTransformationManager=new Ba({canvasResizeManager:t.canvasResizeManager,offsetPositionManager:t.offsetPositionManager,shapeTransformManager:t.shapeTransformManager,chainTarget:t}),t.frustrationContextManager=new Aa({contextManager:t.contextManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.llmIntegrationBridge=new Ta({stateMachine:t.stateMachine,gestureController:t.gestureController,errorBoundary:t.errorBoundary,state:{get llmHandler(){return t.llmHandler},set llmHandler(e){t.llmHandler=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t})}Mi(t,e){t.diagnosticsManager=new Pa({errorBoundary:t.errorBoundary,degradationManager:t.degradationManager,animationController:t.animationController,stateMachine:t.stateMachine,performanceSystem:t.performanceSystem,config:t.config,state:{get isRunning(){return t.isRunning},get speaking(){return t.speaking},get debugMode(){return t.debugMode}},getCurrentState:()=>t.getCurrentState(),getAudioStats:()=>t.getAudioStats(),getEventStats:()=>t.getEventStats(),chainTarget:t}),t.emotionalStateQueryManager=new Da({stateMachine:t.stateMachine,performanceSystem:t.performanceSystem,contextManager:t.contextManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.debugProfilingManager=new Ra({diagnosticsManager:t.diagnosticsManager,errorBoundary:t.errorBoundary,state:{get debugMode(){return t.debugMode},set debugMode(e){t.debugMode=e}},chainTarget:t})}bi(t,e){t.performanceBehaviorManager=new Fa({errorBoundary:t.errorBoundary,performanceSystem:t.performanceSystem,frustrationContextManager:t.frustrationContextManager,emotionalStateQueryManager:t.emotionalStateQueryManager,diagnosticsManager:t.diagnosticsManager,chainTarget:t}),t.healthCheckManager=new qa({errorBoundary:t.errorBoundary,systemStatusReporter:t.systemStatusReporter,diagnosticsManager:t.diagnosticsManager,mobileOptimization:t.mobileOptimization,accessibilityManager:t.accessibilityManager,config:t.config,chainTarget:t}),t.performanceMonitoringManager=new za({diagnosticsManager:t.diagnosticsManager,degradationManager:t.degradationManager,animationFrameController:t.animationFrameController,animationController:t.animationController,particleSystem:t.particleSystem,healthCheckManager:t.healthCheckManager,config:t.config,chainTarget:t})}}class ja{constructor(t,e={}){this.mascot=t,this.userConfig=e}initialize(){this.initializeStateManager();const t=this.initializeConfiguration();return this.initializeCanvas(t),this.initializeCoreSystems(t),this.initializeAudioSystems(t),this.initializeInteractionSystems(t),this.initializeOptimizationSystems(t),this.initializeAnimationController(t),this.initializePerformanceSystems(t),this.initializeModularHandlers(t),this.finalizeInitialization(t),t}initializeStateManager(){this.mascot.stateManager=new da({initialState:{debugMode:this.userConfig.enableDebug||!1},emit:(t,e)=>this.mascot.emit(t,e)}),this.wi()}initializeConfiguration(){const t=Ur.browserOptimizations.getOptimizations(),e={canvasId:"emotive-mascot",targetFPS:60,enableAudio:Ur.featureDetection.features.webAudio,soundEnabled:!1,masterVolume:.5,maxParticles:t.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=e,e}initializeCanvas(t){if(this.mascot.canvas="string"==typeof t.canvasId?document.getElementById(t.canvasId):t.canvasId,!this.mascot.canvas)throw new Error(`Canvas with ID '${t.canvasId}' not found`);this.mascot.canvas.setAttribute("role","img"),this.mascot.canvas.setAttribute("aria-label","Animated emotional mascot visualization"),this.mascot.canvasManager=new ks(this.mascot.canvas),this.mascot.positionController=new Er({offsetX:t.offsetX,offsetY:t.offsetY,offsetZ:t.offsetZ,onUpdate:t=>{this.mascot.renderer&&this.mascot.renderer.updateEffectiveCenter(t)}}),t.renderSize&&t.renderSize.width&&t.renderSize.height&&this.mascot.canvasManager.setRenderSize(t.renderSize.width,t.renderSize.height),this.mascot.contextRecovery=new Lr(this.mascot.canvas),this.mascot.contextRecovery.onRecovery(t=>{this.mascot.renderer&&this.mascot.renderer.handleContextRecovery(t)}),Ur.browserOptimizations.applyCanvasOptimizations(this.mascot.canvas,this.mascot.canvasManager.getContext())}initializeCoreSystems(t){this.mascot.stateMachine=new Ws(this.mascot.errorBoundary),this.mascot.particleSystem=new en(t.maxParticles,this.mascot.errorBoundary),this.mascot.particleSystem.canvasWidth=this.mascot.canvasManager.width,this.mascot.particleSystem.canvasHeight=this.mascot.canvasManager.height,this.mascot.renderer=new hr(this.mascot.canvasManager,{...t.classicConfig,topOffset:t.topOffset||0,positionController:this.mascot.positionController}),this.mascot.renderer.stateMachine=this.mascot.stateMachine,this.mascot.stateMachine.renderer=this.mascot.renderer}initializeAudioSystems(t){this.mascot.shapeMorpher=new ea,this.mascot.audioAnalyzer=new ia,this.mascot.grooveTemplates=new aa,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 Cr,this.mascot.tts={available:"undefined"!=typeof window&&"speechSynthesis"in window,speaking:!1,currentUtterance:null};const e=this.mascot;this.mascot.gestureController=new ua({errorBoundary:e.errorBoundary,renderer:e.renderer,soundSystem:e.soundSystem,config:e.config,state:{get currentModularGesture(){return e.currentModularGesture},set currentModularGesture(t){e.currentModularGesture=t}},throttledWarn:e.throttledWarn,chainTarget:e}),this.mascot.gestureController.gestureCompatibility=na,this.mascot.gestureController.init(),this.mascot.audioLevelProcessor=new Dr({spikeThreshold:t.spikeThreshold||1.5,minimumSpikeLevel:t.minimumSpikeLevel||.1,spikeMinInterval:t.spikeMinInterval||1e3})}initializeInteractionSystems(t){t.enableGazeTracking&&(this.mascot.gazeTracker=new lr(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()})),t.enableIdleBehaviors&&(this.mascot.idleBehavior=new cr({enabled:!0,sleepTimeout:1/0}),this.mascot.idleBehavior.setCallback("onBlink",t=>{this.mascot.renderer&&this.mascot.renderer.state&&(this.mascot.renderer.state.blinking="start"===t.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(t){this.mascot.degradationManager=null,this.mascot.accessibilityManager=new Rr({enableReducedMotion:!1!==t.enableReducedMotion,enableHighContrast:!1!==t.enableHighContrast,enableScreenReaderSupport:!1!==t.enableScreenReaderSupport,enableKeyboardNavigation:!1!==t.enableKeyboardNavigation,colorBlindMode:t.colorBlindMode||"none"}),this.mascot.mobileOptimization=new Fr({enableTouchOptimization:!1!==t.enableTouchOptimization,enableViewportHandling:!1!==t.enableViewportHandling,enableBatteryOptimization:!1!==t.enableBatteryOptimization}),this.mascot.mobileOptimization.setCanvas(this.mascot.canvas),this.mascot.pluginSystem=new zr({mascot:this.mascot,enablePlugins:!1!==t.enablePlugins,validatePlugins:!1!==t.validatePlugins,sandboxPlugins:!1!==t.sandboxPlugins})}initializeAnimationController(t){try{this.mascot.animationController=new Pr(this.mascot.errorBoundary,{targetFPS:t.targetFPS})}catch(e){this.mascot.animationController=this.createFallbackAnimationController(t.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((t,e)=>{this.mascot.emit(t,e)}),this.mascot.animationController.setParentMascot(this.mascot),this.mascot.isRunning=!1}createFallbackAnimationController(t){return{isAnimating:()=>this.mascot.isRunning,start:()=>(this.mascot.isRunning=!0,!0),stop:()=>(this.mascot.isRunning=!1,!0),setTargetFPS:()=>{},targetFPS:t,getPerformanceMetrics:()=>({fps:0,isRunning:this.mascot.isRunning,performanceDegradation:!1,deltaTime:16,frameCount:0,targetFPS:t}),setSubsystems:()=>{},setEventCallback:()=>{},setParentMascot:()=>{},destroy:()=>{},deltaTime:16}}initializePerformanceSystems(t){this.mascot.contextManager=new la({enableHistory:!1!==t.enablePerformanceHistory,enableDecay:!1!==t.enableFrustrationDecay,historyLimit:t.performanceHistoryLimit||50,frustrationDecayRate:t.frustrationDecayRate||5,decayInterval:t.frustrationDecayInterval||1e4}),this.mascot.destructionManager&&(this.mascot.destructionManager.contextManager=this.mascot.contextManager),this.mascot.sequenceExecutor=new ca({mascot:this.mascot,eventManager:this.mascot.eventManager,allowConcurrent:!1!==t.allowConcurrentPerformances}),this.mascot.performanceSystem=new ha({mascot:this.mascot,contextManager:this.mascot.contextManager,sequenceExecutor:this.mascot.sequenceExecutor,eventManager:this.mascot.eventManager,enableAnalytics:!1!==t.enablePerformanceAnalytics})}initializeModularHandlers(t){new Oa(this.mascot).initialize(t);const e=this.mascot.destructionManager;e&&(e.gestureController=this.mascot.gestureController,e.stateCoordinator=this.mascot.stateCoordinator,e.visualizationRunner=this.mascot.visualizationRunner,e.audioHandler=this.mascot.audioHandler)}finalizeInitialization(t){t.enableAudio&&this.mascot.soundSystem.initialize().then(e=>{e&&this.mascot.soundSystem.setMasterVolume(t.masterVolume)}).catch(t=>{}),Qs.initialize(),this.mascot.rhythmIntegration=Qs,this.mascot.debugMode&&(vs.log("INFO","Debug mode enabled for EmotiveMascot",{config:t,runtimeCapabilities:Ss.generateReport()}),vs.startProfile("mascot-initialization",{canvasId:t.canvasId,maxParticles:t.maxParticles})),this.mascot.setupAudioLevelProcessorCallbacks(),this.mascot.stateMachine.setEmotion(t.defaultEmotion),this.mascot.canvasManager.onResize((t,e,i)=>{this.mascot.handleResize(t,e,i)}),this.mascot.stateManager.debugMode&&(vs.endProfile("mascot-initialization"),vs.takeMemorySnapshot("post-initialization"))}wi(){const t=this.mascot,e=t.stateManager;Object.defineProperties(t,{speaking:{get:()=>e.speaking,set(t){e.speaking=t},enumerable:!0,configurable:!0},recording:{get:()=>e.recording,set(t){e.recording=t},enumerable:!0,configurable:!0},sleeping:{get:()=>e.sleeping,set(t){e.sleeping=t},enumerable:!0,configurable:!0},isRunning:{get:()=>e.isRunning,set(t){e.isRunning=t},enumerable:!0,configurable:!0},debugMode:{get:()=>e.debugMode,set(t){e.debugMode=t},enumerable:!0,configurable:!0},audioLevel:{get:()=>e.audioLevel,set(t){e.audioLevel=t},enumerable:!0,configurable:!0},rhythmEnabled:{get:()=>e.rhythmEnabled,set(t){e.rhythmEnabled=t},enumerable:!0,configurable:!0},currentModularGesture:{get:()=>e.currentModularGesture,set(t){e.currentModularGesture=t},enumerable:!0,configurable:!0},breathePhase:{get:()=>e.breathePhase,set(t){e.breathePhase=t},enumerable:!0,configurable:!0},breatheStartTime:{get:()=>e.breatheStartTime,set(t){e.breatheStartTime=t},enumerable:!0,configurable:!0},orbScale:{get:()=>e.orbScale,set(t){e.orbScale=t},enumerable:!0,configurable:!0},warningTimestamps:{get:()=>e.warningTimestamps,set(t){e.warningTimestamps=t},enumerable:!0,configurable:!0},warningThrottle:{get:()=>e.warningThrottle,set(t){e.warningThrottle=t},enumerable:!0,configurable:!0}})}}class Ia{constructor(t){this.animationController=t.animationController||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.gazeTracker=t.gazeTracker||null,this.particleSystem=t.particleSystem,this.stateMachine=t.stateMachine,this.Ie=t.state||{debugMode:!1,speaking:!1}}buildRenderState(){return{renderStart:this.Ie.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.Ie.speaking,audioLevel:this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0,gazeOffset:this.getGazeOffset()}}getGazeOffset(){return this.gazeTracker?this.gazeTracker.currentGaze:{x:0,y:0}}}class $a{constructor(t){this.canvasManager=t.canvasManager,this.config=t.config,this.gazeTracker=t.gazeTracker||null}updateThreatLevel(t){if("suspicion"!==t.emotion||!this.gazeTracker)return;const e=l("suspicion");if(!e||!e.visual)return;const i=this.calculateThreatLevel();e.visual.threatLevel=i}calculateThreatLevel(){this.gazeTracker.getState();const{mousePos:t}=this.gazeTracker,e=this.canvasManager.width/2,i=this.canvasManager.height/2-this.config.topOffset,s=this.calculateDistance(t,{x:e,y:i}),n=Math.min(this.canvasManager.width,this.canvasManager.height)/2;return Math.max(0,Math.min(1,1-s/n))}calculateDistance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}}class La{constructor(t){this.renderer=t.renderer,this.stateMachine=t.stateMachine,this.canvasManager=t.canvasManager,this.config=t.config}calculateParticleConfig(t,e){const{orbX:i,orbY:s}=this.calculateOrbPosition(t),{particleBehavior:n,particleRate:r,minParticles:a,maxParticles:o}=this.calculateParticleBehavior(t,e);return{orbX:i,orbY:s,particleBehavior:n,particleRate:r,minParticles:a,maxParticles:o,emotionParams:e}}calculateOrbPosition(t){const e=this.renderer.getEffectiveCenter(),i=e.x;let s=e.y-this.config.topOffset;const n=this.stateMachine.getCurrentEmotionalProperties();return n.verticalOffset&&(s=e.y-this.config.topOffset+this.canvasManager.height*n.verticalOffset),{orbX:i,orbY:s}}calculateParticleBehavior(t,e){let i=e.particleBehavior||"ambient",s=e.particleRate||15;const n=this.stateMachine.getCurrentEmotionalProperties(),r=void 0!==e.minParticles?e.minParticles:n.minParticles||0;let a=void 0!==e.maxParticles?e.maxParticles:n.maxParticles||10;return({particleBehavior:i,particleRate:s,maxParticles:a}=this.applyRendererOverrides(i,s,a)),{particleBehavior:i,particleRate:s,minParticles:r,maxParticles:a}}applyRendererOverrides(t,e,i){return this.renderer.state&&this.renderer.state.particleBehaviorOverride&&(t=this.renderer.state.particleBehaviorOverride),this.renderer.state&&this.renderer.state.particleRateMult&&(e=Math.floor(e*this.renderer.state.particleRateMult),i=Math.floor(i*this.renderer.state.particleRateMult)),{particleBehavior:t,particleRate:e,maxParticles:i}}getParticleModifier(t){return this.renderer.getUndertoneModifier?this.renderer.getUndertoneModifier():null}}class Ga{constructor(t){this.renderer=t.renderer,this.Ie=t.state}getGestureMotion(){let t=null,e=0;const i=this.Ie.currentModularGesture;return i?({gestureMotion:t,gestureProgress:e}=this.processModularGesture(i)):this.renderer&&this.renderer.getCurrentGesture&&({gestureMotion:t,gestureProgress:e}=this.processRendererGesture()),{gestureMotion:t,gestureProgress:e}}processModularGesture(t){const e=performance.now()-t.startTime,i=Math.min(e/t.duration,1),s={type:t.type,amplitude:1,frequency:1,intensity:1};return i>=1&&this.handleGestureCleanup(t),{gestureMotion:s,gestureProgress:i}}handleGestureCleanup(t){t.cleanupPending?this.Ie.currentModularGesture=null:t.cleanupPending=!0}processRendererGesture(){const t=this.renderer.getCurrentGesture();return t&&t.particleMotion?{gestureMotion:t.particleMotion,gestureProgress:t.progress||0}:{gestureMotion:null,gestureProgress:0}}getGestureTransform(){return this.renderer?.gestureAnimator?.applyGestureAnimations()??null}}class _a{constructor(t){this.canvasManager=t.canvasManager,this.config=t.config,this.particleSystem=t.particleSystem,this.pluginSystem=t.pluginSystem||null,this.renderer=t.renderer,this.stateMachine=t.stateMachine,this.Ie=t.state||{debugMode:!1},this.Si=t.renderDebugInfo||(()=>{})}renderAllLayers(t){const{renderState:e,deltaTime:i,emotionParams:s,gestureTransform:n,renderStart:r}=t;this.renderBackgroundParticles(s.glowColor,n),this.renderOrb(e,i,n),this.renderForegroundParticles(s.glowColor,n),this.renderPlugins(),this.renderDebugIfEnabled(i),this.logPerformanceIfDebug(r,i)}renderBackgroundParticles(t,e){this.particleSystem.renderBackground(this.canvasManager.getContext(),t,e)}renderOrb(t,e,i){this.renderer.render(t,e,i)}renderForegroundParticles(t,e){this.particleSystem.renderForeground(this.canvasManager.getContext(),t,e)}renderPlugins(){if(this.pluginSystem){const t=this.stateMachine.getCurrentState();this.pluginSystem.render(this.canvasManager.getContext(),t)}}renderDebugIfEnabled(t){(this.config.showFPS||this.config.showDebug)&&this.Si(t)}logPerformanceIfDebug(t,e){if(!this.Ie.debugMode)return;const i=performance.now()-t;i>16.67&&vs.log("WARN","Slow render frame detected",{renderTime:i,deltaTime:e,particleCount:this.particleSystem.getStats().activeParticles})}}class Ha{constructor(t){this.animationController=t.animationController,this.canvasManager=t.canvasManager,this.config=t.config,this.particleSystem=t.particleSystem,this.stateMachine=t.stateMachine,this.Ie=t.state||{audioLevel:0,currentModularGesture:null,speaking:!1}}renderDebugInfo(t){const e=this.canvasManager.getContext();e.save(),this.setupTextStyle(e);let i=20;this.config.showFPS&&(i=this.renderFPSInfo(e,i,16)),this.config.showDebug&&this.renderDebugDetails(e,i,16),e.restore()}setupTextStyle(t){t.fillStyle="#ffffff",t.font="12px monospace",t.strokeStyle="#000000",t.lineWidth=2}renderFPSInfo(t,e,i){const s=this.animationController.getPerformanceMetrics(),n=s.instantFps||s.fps||0,r=[`FPS: ${n}`,`Frame: ${s.averageFrameTime?s.averageFrameTime.toFixed(1):"0.0"}ms`,`Particles: ${this.particleSystem.getStats().activeParticles}`],{x:a,maxWidth:o}=this.calculateFPSBoxPosition(t,r);return this.drawFPSBackground(t,a,e,o,r.length),this.drawFPSBorder(t,a,e,o,r.length,n),this.drawTextLines(t,r,a,e,i),e+i*r.length}calculateFPSBoxPosition(t,e){let i=0;return e.forEach(e=>{const{width:s}=t.measureText(e);s>i&&(i=s)}),{x:this.canvasManager.width-i-8-10,maxWidth:i}}drawFPSBackground(t,e,i,s,n){t.fillStyle="rgba(0, 0, 0, 0.7)",t.fillRect(e-8,i-14,s+16,18*n+4)}drawFPSBorder(t,e,i,s,n,r){const a=this.getFPSBorderColor(r);t.strokeStyle=a,t.lineWidth=2,t.strokeRect(e-8,i-14,s+16,18*n+4)}getFPSBorderColor(t){return t>=55?"#00ff00":t>=30?"#ffff00":"#ff0000"}drawTextLines(t,e,i,s,n){t.fillStyle="#ffffff",e.forEach((e,r)=>{const a=s+r*n;t.fillText(e,i,a)})}renderDebugDetails(t,e,i){const s=this.stateMachine.getCurrentState(),n=this.particleSystem.getStats(),r=[`Emotion: ${s.emotion}${s.undertone?` (${s.undertone})`:""}`,`Particles: ${n.activeParticles}/${n.maxParticles}`,`Gesture: ${this.Ie.currentModularGesture?this.Ie.currentModularGesture.type:"none"}`,"Speaking: "+(this.Ie.speaking?"yes":"no"),`Audio Level: ${(100*this.Ie.audioLevel).toFixed(1)}%`];t.fillStyle="rgba(0, 0, 0, 0.7)";const a=Math.max(...r.map(e=>t.measureText(e).width));t.fillRect(8,e-14,a+16,r.length*i+4),t.fillStyle="#ffffff";for(const s of r)t.fillText(s,10,e),e+=i}}const Ua=new class{constructor(t={}){this.enabled=!1!==t.enabled,this.maxErrors=t.maxErrors||100,this.maxStackFrames=t.maxStackFrames||10,this.reportingThreshold=t.reportingThreshold||10,this.reportingInterval=t.reportingInterval||6e4,this.errors=[],this.errorCounts=new Map,this.errorPatterns=new Map,this.suppressedErrors=new Set(t.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:t.onError||null,onReport:t.onReport||null,onCritical:t.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=(t,e,i,s,n)=>(this.captureError(n||new Error(t),{source:e,lineno:i,colno:s,uncaught:!0}),!this.originalOnError||this.originalOnError(t,e,i,s,n)),this.originalOnUnhandledRejection=window.onunhandledrejection,window.onunhandledrejection=t=>{const e=t.reason instanceof Error?t.reason:new Error(String(t.reason));if(this.captureError(e,{type:"unhandledRejection",promise:t.promise,uncaught:!0}),this.originalOnUnhandledRejection)return this.originalOnUnhandledRejection(t)})}detachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&(window.onunhandledrejection=this.originalOnUnhandledRejection))}captureError(t,e={}){if(!this.enabled)return;if(this.shouldSuppress(t))return;const i=this.processError(t,e);i.category=this.categorizeError(t,e),i.severity=this.determineSeverity(t,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(t,e){const i=Date.now(),s=this.parseStackTrace(t.stack);return{id:`${i}-${Math.random().toString(36).substr(2,9)}`,timestamp:i,name:t.name||"Error",message:t.message||String(t),stack:s.slice(0,this.maxStackFrames),fullStack:t.stack,context:{...e,url:"undefined"!=typeof window?window.location.href:"unknown",userAgent:this.metadata.userAgent,sessionId:this.metadata.sessionId},metadata:this.collectMetadata()}}parseStackTrace(t){if(!t)return[];const e=t.split("\n"),i=[];for(const t of e){const e=t.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);e&&i.push({function:e[1],file:e[2],line:parseInt(e[3],10),column:parseInt(e[4],10)})}return i}categorizeError(t,e){const i=t.message.toLowerCase(),s=t.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"===e.source?this.errorCategories.USER_INPUT:i.includes("performance")||i.includes("memory")?this.errorCategories.PERFORMANCE:this.errorCategories.UNKNOWN}determineSeverity(t,e){return"ReferenceError"===t.name||"TypeError"===t.name?this.severityLevels.CRITICAL:e===this.errorCategories.RENDERING||e===this.errorCategories.ANIMATION?this.severityLevels.HIGH:e===this.errorCategories.NETWORK?this.severityLevels.MEDIUM:this.severityLevels.LOW}shouldSuppress(t){const e=t.message||"";for(const t of this.suppressedErrors){if("string"==typeof t&&e.includes(t))return!0;if(t instanceof RegExp&&t.test(e))return!0}return!1}detectPatterns(t){const e=`${t.category}:${t.severity}`,i=this.errorPatterns.get(e)||{count:0,firstSeen:Date.now(),lastSeen:null};i.count++,i.lastSeen=Date.now(),this.errorPatterns.set(e,i);const s=this.errors.filter(t=>Date.now()-t.timestamp<5e3);s.length>10&&this.handleErrorStorm(s)}handleCriticalError(t){this.callbacks.onCritical&&this.callbacks.onCritical(t),this.sendReport([t],"critical")}handleErrorStorm(t){const e=new Map;for(const i of t){const t=`${i.name}:${i.message}`;e.has(t)||e.set(t,[]),e.get(t).push(i)}this.sendReport(t,"storm")}collectMetadata(){const t={};return"undefined"!=typeof window&&(t.viewport={width:window.innerWidth,height:window.innerHeight},t.screen={width:window.screen.width,height:window.screen.height,pixelRatio:window.devicePixelRatio},performance.memory&&(t.memory={used:Math.round(performance.memory.usedJSHeapSize/1048576),total:Math.round(performance.memory.totalJSHeapSize/1048576),limit:Math.round(performance.memory.jsHeapSizeLimit/1048576)})),t}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(t,e="batch"){const i={sessionId:this.metadata.sessionId,timestamp:Date.now(),type:e,errors:t,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(t={}){let e=[...this.errors];return t.category&&(e=e.filter(e=>e.category===t.category)),t.severity&&(e=e.filter(e=>e.severity===t.severity)),t.since&&(e=e.filter(e=>e.timestamp>=t.since)),e}getStats(){const t={total:this.errors.length,byCategory:{},bySeverity:{},patterns:this.errorPatterns.size,topErrors:[]};for(const e of Object.values(this.errorCategories))t.byCategory[e]=this.errors.filter(t=>t.category===e).length;for(const e of Object.values(this.severityLevels))t.bySeverity[e]=this.errors.filter(t=>t.severity===e).length;const e=Array.from(this.errorCounts.entries()).sort((t,e)=>e[1]-t[1]).slice(0,5);return t.topErrors=e.map(([t,e])=>({error:t,count:e})),t}clearErrors(){this.errors=[],this.errorCounts.clear(),this.errorPatterns.clear()}suppressError(t){this.suppressedErrors.add(t)}unsuppressError(t){this.suppressedErrors.delete(t)}enable(){this.enabled=!0,this.attachGlobalHandlers(),this.startReportingInterval()}disable(){this.enabled=!1,this.detachGlobalHandlers(),this.stopReportingInterval()}destroy(){this.disable(),this.clearErrors()}}({enabled:!0,maxErrors:100,reportingThreshold:10,reportingInterval:6e4,suppressedErrors:["ResizeObserver loop limit exceeded","Non-Error promise rejection captured"]}),Wa=new class{constructor(t={}){this.enabled=!1!==t.enabled,this.interval=t.interval||3e4,this.thresholds={memory:t.memoryThreshold||500,fps:t.fpsThreshold||30,errorRate:t.errorRateThreshold||.1,responseTime:t.responseTimeThreshold||1e3,...t.thresholds},this.checks=new Map,this.history=[],this.maxHistory=t.maxHistory||100,this.status="initializing",this.lastCheck=null,this.dependencies={animationLoop:null,stateStore:null,eventManager:null,performanceMonitor:null,errorTracker:null},this.callbacks={onHealthy:t.onHealthy||null,onWarning:t.onWarning||null,onCritical:t.onCritical||null,onStatusChange:t.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(t,e,i={}){this.checks.set(t,{fn:e,critical:i.critical||!1,weight:i.weight||1,timeout:i.timeout||5e3,lastResult:null,lastRun:null})}checkMemory(){const t={status:"healthy",details:{}};if(performance.memory){const e=performance.memory.usedJSHeapSize/1048576,i=performance.memory.totalJSHeapSize/1048576,s=performance.memory.jsHeapSizeLimit/1048576;t.details={used:Math.round(e),total:Math.round(i),limit:Math.round(s),percentage:Math.round(e/s*100)},e>this.thresholds.memory?(t.status="critical",t.message=`Memory usage too high: ${Math.round(e)}MB`):e>.8*this.thresholds.memory&&(t.status="warning",t.message=`Memory usage approaching limit: ${Math.round(e)}MB`)}else t.status="unknown",t.message="Memory API not available";return t}checkPerformance(){const t={status:"healthy",details:{}};if(this.dependencies.performanceMonitor){const e=this.dependencies.performanceMonitor.getStats();t.details={fps:e.fps.current,frameTime:e.frameTime.current,health:e.health,score:e.performance},e.fps.current<this.thresholds.fps&&(t.status="warning",t.message=`Low FPS: ${e.fps.current}`),"critical"!==e.health&&"poor"!==e.health||(t.status="critical",t.message="Performance is critically low")}return t}checkErrors(){const t={status:"healthy",details:{}};if(this.dependencies.errorTracker){const e=this.dependencies.errorTracker.getStats(),i=this.dependencies.errorTracker.getErrors({since:Date.now()-6e4});t.details={total:e.total,recent:i.length,critical:e.bySeverity.critical||0,patterns:e.patterns};const s=i.length/60;s>this.thresholds.errorRate?(t.status="critical",t.message=`High error rate: ${s.toFixed(2)}/s`):e.bySeverity.critical>0&&(t.status="warning",t.message=`${e.bySeverity.critical} critical errors`)}return t}checkDOM(){const t={status:"healthy",details:{}};if("undefined"!=typeof document){const e=document.querySelectorAll("*").length,i=document.querySelectorAll("canvas").length,s=this.countEventListeners();t.details={nodes:e,canvases:i,listeners:s},e>1e4&&(t.status="warning",t.message=`High DOM node count: ${e}`),s>1e3&&(t.status="warning",t.message=`High event listener count: ${s}`)}return t}checkAnimation(){const t={status:"healthy",details:{}};if(this.dependencies.animationLoop){const e=this.dependencies.animationLoop.getStats();t.details={callbacks:e.callbackCount,fps:e.fps,running:e.isRunning,dropped:e.droppedFrames},e.isRunning||(t.status="warning",t.message="Animation loop not running"),e.droppedFrames>100&&(t.status="warning",t.message=`Dropped frames: ${e.droppedFrames}`)}return t}checkState(){const t={status:"healthy",details:{}};if(this.dependencies.stateStore){const e=this.dependencies.stateStore.getState(),i=JSON.stringify(e).length;t.details={size:i,keys:Object.keys(e).length},i>1e6&&(t.status="warning",t.message=`Large state size: ${(i/1024).toFixed(2)}KB`)}return t}checkEvents(){const t={status:"healthy",details:{}};if(this.dependencies.eventManager){const e=this.dependencies.eventManager.getActiveListeners(),i=this.dependencies.eventManager.analyzeLeaks();t.details={active:e.length,potentialLeaks:i.potentialLeaks.length,byGroup:i.byGroup},i.potentialLeaks.length>10&&(t.status="warning",t.message=`Potential memory leaks: ${i.potentialLeaks.length}`),e.length>500&&(t.status="warning",t.message=`High listener count: ${e.length}`)}return t}async checkStorage(){const t={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.storage&&navigator.storage.estimate)try{const e=await navigator.storage.estimate(),i=e.usage||0,s=e.quota||0,n=s>0?i/s*100:0;t.details={used:Math.round(i/1048576),quota:Math.round(s/1048576),percentage:Math.round(n)},n>90?(t.status="critical",t.message=`Storage almost full: ${n.toFixed(1)}%`):n>70&&(t.status="warning",t.message=`Storage usage high: ${n.toFixed(1)}%`)}catch{t.status="unknown",t.message="Storage API error"}return t}async checkNetwork(){const t={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.connection){const{connection:e}=navigator;t.details={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData},"slow-2g"!==e.effectiveType&&"2g"!==e.effectiveType||(t.status="warning",t.message="Slow network connection detected"),e.saveData&&(t.status="warning",t.message="Data saver mode enabled")}try{const e=performance.now(),i=await fetch("/health",{method:"HEAD",cache:"no-cache"}),s=performance.now()-e;t.details.responseTime=Math.round(s),t.details.online=i.ok,s>this.thresholds.responseTime&&(t.status="warning",t.message=`Slow response time: ${s.toFixed(0)}ms`)}catch{t.details.online=navigator.onLine,navigator.onLine||(t.status="critical",t.message="No network connection")}return t}checkBrowser(){const t={status:"healthy",details:{}};t.details={userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,hardwareConcurrency:navigator.hardwareConcurrency,maxTouchPoints:navigator.maxTouchPoints};const e={webGL:!!document.createElement("canvas").getContext("webgl"),webAudio:"undefined"!=typeof AudioContext,localStorage:"undefined"!=typeof localStorage,serviceWorker:"serviceWorker"in navigator,webWorker:"undefined"!=typeof Worker};t.details.features=e;const i=Object.entries(e).filter(([t,e])=>!e).map(([t])=>t);return i.length>0&&(t.status="warning",t.message=`Missing features: ${i.join(", ")}`),t}countEventListeners(){let t=0;const e=document.querySelectorAll("*");for(const i of e){const e="undefined"!=typeof getEventListeners&&getEventListeners?getEventListeners(i):{};for(const i in e)t+=e[i].length}return t}async runCheck(t){const e=this.checks.get(t);if(!e)return{status:"unknown",message:`Check '${t}' not found`};try{const t=new Promise((t,i)=>{setTimeout(()=>i(new Error("Check timeout")),e.timeout)}),i=await Promise.race([e.fn(),t]);return e.lastResult=i,e.lastRun=Date.now(),i}catch(t){return{status:"error",message:t.message,error:t.stack}}}async runAllChecks(){const t={},e=[];for(const[i]of this.checks)e.push(this.runCheck(i).then(e=>{t[i]=e}));return await Promise.all(e),t}async performHealthCheck(){const t=performance.now(),e=await this.runAllChecks(),i=performance.now()-t,s=this.calculateOverallHealth(e),n={timestamp:Date.now(),status:s.status,score:s.score,duration:Math.round(i),checks:e,summary:s.summary};return this.lastCheck=n,this.addToHistory(n),this.updateStatus(s.status),n}calculateOverallHealth(t){let e=0,i=0,s=!1;const n=[];for(const[r,a]of Object.entries(t)){const t=this.checks.get(r),o=t?t.weight:1;let h=0;switch(a.status){case"healthy":h=100;break;case"warning":h=70,n.push({name:r,level:"warning",message:a.message});break;case"critical":h=30,n.push({name:r,level:"critical",message:a.message}),t&&t.critical&&(s=!0);break;case"error":h=0,n.push({name:r,level:"error",message:a.message});break;case"unknown":h=50}e+=h*o,i+=o}const r=i>0?Math.round(e/i):0;let a;return a=s||r<30?"critical":r<70?"degraded":r<90?"warning":"healthy",{status:a,score:r,summary:{total:Object.keys(t).length,healthy:Object.values(t).filter(t=>"healthy"===t.status).length,warning:Object.values(t).filter(t=>"warning"===t.status).length,critical:Object.values(t).filter(t=>"critical"===t.status).length,issues:n}}}updateStatus(t){if(this.status!==t){const e=this.status;switch(this.status=t,this.callbacks.onStatusChange&&this.callbacks.onStatusChange(t,e),t){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(t){this.history.push(t),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(t){Object.assign(this.dependencies,t)}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 t=this.history[0].timestamp;return Date.now()-t}async handleHealthRequest(t,e){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"})}}}({enabled:!1,interval:3e4});class Ya{constructor(t){if(!t.errorBoundary)throw new Error("DestructionManager: errorBoundary required");if(!t.animationController)throw new Error("DestructionManager: animationController required");if(!t.state)throw new Error("DestructionManager: state required");if(!t.stop)throw new Error("DestructionManager: stop required");if(!t.stopSpeaking)throw new Error("DestructionManager: stopSpeaking required");if(!t.disconnectAudio)throw new Error("DestructionManager: disconnectAudio required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.positionController=t.positionController||null,this.soundSystem=t.soundSystem||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.particleSystem=t.particleSystem||null,this.renderer=t.renderer||null,this.canvasManager=t.canvasManager||null,this.eventManager=t.eventManager||null,this.accessibilityManager=t.accessibilityManager||null,this.mobileOptimization=t.mobileOptimization||null,this.pluginSystem=t.pluginSystem||null,this.audioAnalyzer=t.audioAnalyzer||null,this.shapeMorpher=t.shapeMorpher||null,this.gestureController=t.gestureController||null,this.stateCoordinator=t.stateCoordinator||null,this.visualizationRunner=t.visualizationRunner||null,this.orbScaleAnimator=t.orbScaleAnimator||null,this.audioHandler=t.audioHandler||null,this.degradationManager=t.degradationManager||null,this.stateMachine=t.stateMachine||null,this.contextManager=t.contextManager||null,this.Ie=t.state,this.ki=t.stop,this.xi=t.stopSpeaking,this.Ei=t.disconnectAudio}destroy(){this.errorBoundary.wrap(()=>{this.stopAnimations(),this.destroyControllers(),this.cleanupSubsystems(),this.cleanupEvents(),this.cleanupPluginsAndExtensions(),this.clearErrorBoundary()},"destruction")()}stopAnimations(){this.ki(),this.Ie.speaking&&this.xi()}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(){Ua&&Ua.destroy(),vn&&vn.destroy(),Wa&&Wa.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.Ie.llmHandler&&(this.Ie.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.Ei(),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.Ie=null,this.ki=null,this.xi=null,this.Ei=null}}class Xa{constructor(t){this.renderer=t.renderer||null,this.Ie=t.state,this.ti=t.emit}startBreathingAnimation(){this.Ie.breathingAnimationId&&cancelAnimationFrame(this.Ie.breathingAnimationId);const t=()=>{if(!this.Ie.breathePattern||!this.Ie.isRunning)return;const e=this.Ie.breathePattern,i=Date.now(),s=(i-e.phaseStartTime)/1e3,{scale:n,nextPhase:r}=this.calculatePhaseState(e,s,i);r!==e.currentPhase&&(e.currentPhase=r),this.applyScale(n),this.Ie.breathingAnimationId=requestAnimationFrame(t)};this.Ie.breathePattern.currentPhase="inhale",this.Ie.breathePattern.phaseStartTime=Date.now(),this.ti("inhale-start"),t()}calculatePhaseState(t,e,i){let s=1,n=t.currentPhase;switch(t.currentPhase){case"inhale":({scale:s,nextPhase:n}=this.processInhalePhase(t,e,i));break;case"hold1":({scale:s,nextPhase:n}=this.processHold1Phase(t,e,i));break;case"exhale":({scale:s,nextPhase:n}=this.processExhalePhase(t,e,i));break;case"hold2":({scale:s,nextPhase:n}=this.processHold2Phase(t,e,i))}return{scale:s,nextPhase:n}}processInhalePhase(t,e,i){let s=1,n=t.currentPhase;return e>=t.inhale?(n="hold1",t.phaseStartTime=i,this.ti("hold-start",{type:"post-inhale"})):s=1+e/t.inhale*.3,{scale:s,nextPhase:n}}processHold1Phase(t,e,i){let s=t.currentPhase;return e>=t.hold1&&(s="exhale",t.phaseStartTime=i,this.ti("exhale-start")),{scale:1.3,nextPhase:s}}processExhalePhase(t,e,i){let s=1.3,n=t.currentPhase;return e>=t.exhale?(n="hold2",t.phaseStartTime=i,this.ti("hold-start",{type:"post-exhale"})):s=1.3-e/t.exhale*.4,{scale:s,nextPhase:n}}processHold2Phase(t,e,i){let s=t.currentPhase;return e>=t.hold2&&(s="inhale",t.phaseStartTime=i,this.ti("inhale-start")),{scale:.9,nextPhase:s}}applyScale(t){this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(t)}}class Va{constructor(t){this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem,this.soundSystem=t.soundSystem,this.renderer=t.renderer||null,this.config=t.config,this.Ie=t.state,this.Bi=t.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 t=this.animationController.getPerformanceMetrics();return{isRunning:t.isRunning,fps:t.fps,targetFPS:t.targetFPS,performanceDegradation:t.performanceDegradation}}getEmotionalStatus(){const t=this.stateMachine.getCurrentState();return{emotion:t.emotion,undertone:t.undertone,isTransitioning:t.isTransitioning,transitionProgress:t.transitionProgress}}getGestureStatus(){return{currentGesture:this.renderer?.currentGesture||null,gestureActive:this.renderer?.isGestureActive()||!1}}getParticleStatus(){const t=this.particleSystem.getStats();return{active:t.activeParticles,max:t.maxParticles,poolEfficiency:t.poolEfficiency}}getAudioStatus(){return{audioEnabled:this.config.enableAudio,soundSystemAvailable:this.soundSystem.isAvailable(),speaking:this.Ie.speaking,audioLevel:this.Ie.audioLevel,masterVolume:this.config.masterVolume}}getRendererStatus(){const t=this.renderer.getStats();return{gradientCacheSize:t.gradientCacheSize,breathingPhase:t.breathingPhase,layers:t.layers}}getEventListenerCount(){return this.Bi().length}getErrorStats(){return this.errorBoundary.getErrorStats()}}class Na{constructor(t){if(!t.errorBoundary)throw new Error("SleepWakeManager: errorBoundary required");if(!t.express)throw new Error("SleepWakeManager: express required");if(!t.state)throw new Error("SleepWakeManager: state required");if(!t.emit)throw new Error("SleepWakeManager: emit required");this.errorBoundary=t.errorBoundary,this.Ai=t.express,this.idleBehavior=t.idleBehavior||null,this.renderer=t.renderer||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}sleep(){return this.errorBoundary.wrap(async()=>(this.Ie.sleeping||(await this.performSleepSequence(),this.enterSleepState()),this.Le),"sleep",this.Le)()}async performSleepSequence(){this.Ai("yawn"),await this.delay(1e3),this.Ai("sway"),await this.delay(1e3)}enterSleepState(){this.Ie.sleeping=!0,this.renderer&&this.renderer.enterSleepMode&&this.renderer.enterSleepMode(),this.idleBehavior&&this.idleBehavior.enterSleep&&this.idleBehavior.enterSleep(),this.ti("sleep")}wake(){return this.errorBoundary.wrap(async()=>this.Ie.sleeping?(this.exitSleepState(),await this.performWakeSequence(),this.Le):this.Le,"wake",this.Le)()}exitSleepState(){this.Ie.sleeping=!1,this.renderer&&this.renderer.wakeUp&&this.renderer.wakeUp(),this.idleBehavior&&this.idleBehavior.wakeUp&&this.idleBehavior.wakeUp()}async performWakeSequence(){this.Ai("stretch"),await this.delay(1e3),this.Ai("slowBlink"),await this.delay(1e3),this.Ai("shake"),await this.delay(500),this.ti("wake")}delay(t){return new Promise(e=>setTimeout(e,t))}}class Qa{constructor(t){if(!t.errorBoundary)throw new Error("SpeechManager: errorBoundary required");if(!t.emit)throw new Error("SpeechManager: emit required");this.errorBoundary=t.errorBoundary,this.audioLevelProcessor=t.audioLevelProcessor||null,this.audioHandler=t.audioHandler||null,this.renderer=t.renderer||null,this.config=t.config||{},this.Ie=t.state||{speaking:!1},this.Ci=t.setTTSSpeaking||(()=>{}),this.ti=t.emit,this.Le=t.chainTarget||this}speak(t,e={}){if(!window.speechSynthesis)return null;const i=this.createUtterance(t,e);return this.setupUtteranceHandlers(i,t),window.speechSynthesis.speak(i),i}createUtterance(t,e){const i=new SpeechSynthesisUtterance(t);return e.voice&&(i.voice=e.voice),e.rate&&(i.rate=e.rate),e.pitch&&(i.pitch=e.pitch),e.volume&&(i.volume=e.volume),e.lang&&(i.lang=e.lang),i}setupUtteranceHandlers(t,e){t.onstart=()=>{this.Ci(!0),this.ti("tts:start",{text:e})},t.onend=()=>{this.Ci(!1),this.ti("tts:end")},t.onerror=t=>{this.Ci(!1),this.ti("tts:error",{error:t})},t.onboundary=t=>{this.ti("tts:boundary",{name:t.name,charIndex:t.charIndex,charLength:t.charLength})}}startSpeaking(t){return this.errorBoundary.wrap(()=>this.validateAudioContext(t)&&this.initializeAudioProcessor(t)?(this.activateSpeechMode(t),this.Le):this.Le,"speech-start",this.Le)()}validateAudioContext(t){if(!t)throw new Error("AudioContext is required for speech reactivity");return!!this.config.enableAudio&&!this.Ie.speaking}initializeAudioProcessor(t){return!!this.audioLevelProcessor.initialize(t)}activateSpeechMode(t){this.Ie.speaking=!0,this.renderer&&this.renderer.onSpeechStart(t),this.ti("speechStarted",{audioContext:t,analyser:this.audioLevelProcessor.getAnalyser(),chainTarget:this.Le})}stopSpeaking(){return this.errorBoundary.wrap(()=>this.audioHandler?this.audioHandler.stopSpeaking():this.Le,"speech-stop",this.Le)()}}class Ja{constructor(t){if(!t.emit)throw new Error("AudioLevelCallbackManager: emit required");this.audioLevelProcessor=t.audioLevelProcessor||null,this.renderer=t.renderer||null,this.particleSystem=t.particleSystem||null,this.Ai=t.express||(()=>{}),this.ti=t.emit}setupAudioLevelProcessorCallbacks(){this.setupLevelUpdateCallback(),this.setupVolumeSpikeCallback(),this.setupErrorCallback()}setupLevelUpdateCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onLevelUpdate(t=>{this.renderer&&this.renderer.updateAudioLevel(t.level),this.ti("audioLevelUpdate",{level:t.level,rawData:Array.from(t.rawData),timestamp:t.timestamp})})}setupVolumeSpikeCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onVolumeSpike(t=>{const e=this.handleVolumeSpike();this.ti("volumeSpike",{...t,gestureTriggered:e})})}handleVolumeSpike(){return!!this.particleSystem&&!this.particleSystem.particles.some(t=>t.gestureProgress<1)&&(this.Ai("pulse"),!0)}setupErrorCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onError(t=>{this.ti("audioProcessingError",t)})}}class Ka{constructor(t){this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state,this.Le=t.chainTarget||this,this.animationId=null}setOrbScale(t,e=1e3,i="easeInOut"){return this.errorBoundary.wrap(()=>(this.renderer&&this.startScaleAnimation(t,e,i),this.Le),"setOrbScale",this.Le)()}startScaleAnimation(t,e,i){const s=this.Ie.currentOrbScale||1,n=Date.now(),r=()=>{const a=Date.now()-n,o=Math.min(a/e,1),h=this.applyEasing(o,i);this.Ie.currentOrbScale=s+(t-s)*h,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(this.Ie.currentOrbScale),o<1&&this.Ie.isRunning&&(this.animationId=requestAnimationFrame(r))};r()}applyEasing(t,e){switch(e){case"easeIn":return this.easeIn(t);case"easeOut":return this.easeOut(t);case"easeInOut":return this.easeInOut(t);default:return t}}easeIn(t){return t*t}easeOut(t){return t*(2-t)}easeInOut(t){return t<.5?2*t*t:(4-2*t)*t-1}destroy(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.renderer=null,this.Ie=null}}class Za{constructor(t){if(!t.errorBoundary)throw new Error("RecordingStateManager: errorBoundary required");if(!t.emit)throw new Error("RecordingStateManager: emit required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state||{recording:!1},this.ti=t.emit,this.Le=t.chainTarget||this}startRecording(){return this.errorBoundary.wrap(()=>(this.Ie.recording||(this.Ie.recording=!0,this.renderer&&this.renderer.startRecording&&this.renderer.startRecording(),this.ti("recordingStarted")),this.Le),"recording-start",this.Le)()}stopRecording(){return this.errorBoundary.wrap(()=>this.Ie.recording?(this.Ie.recording=!1,this.renderer&&this.renderer.stopRecording&&this.renderer.stopRecording(),this.ti("recordingStopped"),this.Le):this.Le,"recording-stop",this.Le)()}}class to{constructor(t){this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state,this.Ti=t.startBreathingAnimation,this.Le=t.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(t,e,i,s){return this.errorBoundary.wrap(()=>{const n=t+e+i+s;return this.Ie.breathePattern={inhale:t,hold1:e,exhale:i,hold2:s,totalCycle:n,currentPhase:"inhale",phaseStartTime:Date.now(),phaseProgress:0},this.Ti(),this.Le},"setBreathePattern",this.Le)()}breathe(t="calm"){return this.errorBoundary.wrap(()=>{const e=to.getPresets(),i=e[t]||e.calm;return this.setBreathePattern(i.inhale,i.hold1,i.exhale,i.hold2)},"breathe",this.Le)()}stopBreathing(){return this.errorBoundary.wrap(()=>(this.Ie.breathingAnimationId&&(cancelAnimationFrame(this.Ie.breathingAnimationId),this.Ie.breathingAnimationId=null),this.Ie.breathePattern=null,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(1),this.Le),"stopBreathing",this.Le)()}}class eo{constructor(t,e){this.Pi=t,this.O=e}handleEvent(t,e){switch(t){case"degradationApplied":this.applySettings(e.settings),this.O("performanceDegradation",e);break;case"recoveryApplied":this.applySettings(e.settings),this.O("performanceRecovery",e);break;case"levelChanged":this.applySettings(e.settings),this.O("degradationLevelChanged",e)}}applySettings(t){const e=this.Pi();e.particleSystem&&void 0!==t.particleLimit&&e.particleSystem.setMaxParticles(t.particleLimit),e.soundSystem&&void 0!==t.audioEnabled&&!t.audioEnabled&&e.soundSystem.isAvailable()&&e.soundSystem.stopAmbientTone(200),e.renderer&&void 0!==t.qualityLevel&&e.renderer.setQualityLevel(t.qualityLevel)}}class io{constructor(t={}){this.errorBoundary=new e,this.eventManager=new Ms({maxListeners:t.maxEventListeners||100,enableDebugging:t.enableEventDebugging||!1,enableMonitoring:t.enableEventMonitoring||!0,memoryWarningThreshold:t.eventMemoryWarningThreshold||50}),this.eventManager.emit||(this.eventManager.u={},this.eventManager.emit=(t,e)=>{const i=this.eventManager.u[t];i&&i.forEach(t=>t(e))},this.eventManager.on=(t,e)=>{this.eventManager.u[t]||(this.eventManager.u[t]=[]),this.eventManager.u[t].push(e)},this.eventManager.off=(t,e)=>{const i=this.eventManager.u[t];if(i){const t=i.indexOf(e);t>-1&&i.splice(t,1)}}),this.errorBoundary.wrap(()=>{this.initialize(t)},"initialization")()}initialize(t){this.Emotions=v,this.Gestures=Ii,this.ParticleBehaviors=ys,this.speechManager=new Qa({errorBoundary:this.errorBoundary,emit:(t,e)=>this.emit(t,e)}),this.audioLevelCallbackManager=new Ja({emit:(t,e)=>this.emit(t,e)}),this.orbScaleAnimator=new Ka(this),this.recordingStateManager=new Za({errorBoundary:this.errorBoundary,emit:(t,e)=>this.emit(t,e)}),this.breathingPatternManager=new to(this),new ja(this,t).initialize(),this.renderStateBuilder=new Ia(this),this.threatLevelCalculator=new $a(this),this.particleConfigCalculator=new La(this);const e=this;this.gestureMotionProvider=new Ga({renderer:this.renderer,state:{get currentModularGesture(){return e.currentModularGesture},set currentModularGesture(t){e.currentModularGesture=t}}}),this.renderLayerOrchestrator=new _a(this),this.debugInfoRenderer=new Ha(this),this.destructionManager=new Ya({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 e.speaking},get llmHandler(){return e.llmHandler},set llmHandler(t){e.llmHandler=t}},stop:()=>this.stop(),stopSpeaking:()=>this.stopSpeaking(),disconnectAudio:()=>this.disconnectAudio()}),this.breathingAnimationController=new Xa(this),this.systemStatusReporter=new Va({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 e.speaking},get audioLevel(){return e.audioLevel}},getEventNames:()=>this.getEventNames()}),this.sleepWakeManager=new Na({errorBoundary:this.errorBoundary,express:(t,e)=>this.express(t,e),idleBehavior:this.idleBehavior,renderer:this.renderer,state:{get sleeping(){return e.sleeping},set sleeping(t){e.sleeping=t}},emit:(t,e)=>this.emit(t,e),chainTarget:this}),this.degradationEventHandler=new eo(()=>({particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer}),(t,e)=>this.emit(t,e))}handleDegradationEvent(t,e){return this.degradationEventHandler.handleEvent(t,e)}applyDegradationSettings(t){return this.degradationEventHandler.applySettings(t)}setupAudioLevelProcessorCallbacks(){this.audioLevelCallbackManager.setupAudioLevelProcessorCallbacks()}setEmotion(t,e=null){return this.errorBoundary.wrap(()=>this.stateCoordinator.setEmotion(t,e),"emotion-setting",this)()}updateUndertone(t){return this.errorBoundary.wrap(()=>(this.stateMachine.applyUndertoneModifier(t),this.renderer&&this.renderer.updateUndertone&&this.renderer.updateUndertone(t),this),"undertone-update",this)()}setBPM(t){return this.errorBoundary.wrap(()=>(this.renderer?.setBPM&&this.renderer.setBPM(t),this),"bpm-update",this)()}setRotationSpeed(t){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationSpeed&&this.renderer.setRotationSpeed(t),this),"rotation-speed-update",this)()}setRotationAngle(t){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationAngle&&this.renderer.setRotationAngle(t),this),"rotation-angle-update",this)()}getPosition(){return this.animationFrameController.getPosition()}setGazeTracking(t){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.setGazeTracking&&this.renderer.setGazeTracking(t),this),"gaze-tracking-update",this)()}express(t,e={}){return this.gestureController?this.gestureController.express(t,e):this}expressChord(t,e={}){return this.gestureController.expressChord(t,e)}executeGestureDirectly(t,e={}){this.gestureController.executeGestureDirectly(t,e),this.emit("gesture",{name:t,options:e})}chain(...t){return this.gestureController.chain(...t)}executeChainSequence(t){return this.gestureController.executeChainSequence(t)}perform(t,e={}){return this.performanceBehaviorManager.perform(t,e)}updateContext(t){return this.frustrationContextManager.updateContext(t)}getContext(){return this.emotionalStateQueryManager.getContext()}incrementFrustration(t=10){return this.frustrationContextManager.incrementFrustration(t)}decrementFrustration(t=10){return this.frustrationContextManager.decrementFrustration(t)}resetFrustration(){return this.frustrationContextManager.resetFrustration()}getAvailablePerformances(){return this.performanceBehaviorManager.getAvailablePerformances()}registerPerformance(t,e){return this.performanceBehaviorManager.registerPerformance(t,e)}getPerformanceAnalytics(){return this.performanceBehaviorManager.getPerformanceAnalytics()}getContextAnalytics(){return this.performanceBehaviorManager.getContextAnalytics()}startSpeaking(t){return this.speechManager?this.speechManager.startSpeaking(t):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(t,e,i,s){return this.breathingPatternManager?this.breathingPatternManager.setBreathePattern(t,e,i,s):this}setOrbScale(t,e=1e3,i="easeInOut"){return this.orbScaleAnimator?this.orbScaleAnimator.setOrbScale(t,e,i):this}breathe(t="calm"){return this.breathingPatternManager?this.breathingPatternManager.breathe(t):this}startBreathingAnimation(){this.breathingAnimationController.startBreathingAnimation()}stopBreathing(){return this.breathingPatternManager?this.breathingPatternManager.stopBreathing():this}on(t,e){return this.eventListenerManager.on(t,e)}off(t,e){return this.eventListenerManager.off(t,e)}once(t,e){return this.eventListenerManager.once(t,e)}removeAllListeners(t=null){return this.eventListenerManager.removeAllListeners(t)}listenerCount(t){return this.eventListenerManager.listenerCount(t)}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(t){return this.performanceMonitoringManager.setDegradationLevel(t)}isFeatureAvailable(t){return this.performanceMonitoringManager.isFeatureAvailable(t)}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(t,e={}){this.debugProfilingManager.startProfiling(t,e)}endProfiling(t){return this.debugProfilingManager.endProfiling(t)}takeMemorySnapshot(t){this.debugProfilingManager.takeMemorySnapshot(t)}clearDebugData(){this.debugProfilingManager.clearDebugData()}getRuntimeCapabilities(){return this.debugProfilingManager.getRuntimeCapabilities()}emit(t,e=null){this.eventListenerManager.emit(t,e)}update(t){this.errorBoundary.wrap(()=>{this.visualizationRunner.update(t)},"audio-update")()}render(){try{const{renderStart:t,deltaTime:e,renderState:i}=this.renderStateBuilder.buildRenderState();this.debugMode&&vs.trackFrameTiming(e),this.canvasManager.clear(),this.gazeTracker&&this.gazeTracker.update(e),this.threatLevelCalculator.updateThreatLevel(i);const s=c(i.emotion);this.renderer.setEmotionalState(i.emotion,s,i.undertone);const n=this.particleConfigCalculator.calculateParticleConfig(i,s),{orbX:r,orbY:a,particleBehavior:o,particleRate:h,minParticles:l,maxParticles:u}=n;this.particleSystem.spawn(o,i.emotion,h,r,a,e,null,l,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:p,gestureProgress:m}=this.gestureMotionProvider.getGestureMotion();this.particleSystem.update(e,r,a,p,m,d);const g=this.gestureMotionProvider.getGestureTransform();this.renderLayerOrchestrator.renderAllLayers({renderState:i,deltaTime:e,emotionParams:s,gestureTransform:g,renderStart:t})}catch(t){this.errorBoundary.logError(t,"main-render")}}renderDebugInfo(t){this.debugInfoRenderer.renderDebugInfo(t)}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(t){this.speechReactivityManager.updateAudioConfig(t)}getAvailableGestures(){return this.emotionalStateQueryManager.getAvailableGestures()}connectAudioSource(t){return this.speechReactivityManager.connectAudioSource(t)}setVolume(t){return this.errorBoundary.wrap(()=>this.audioHandler.setVolume(t),"volume-setting",this)()}getVolume(){return this.config.masterVolume}setSoundEnabled(t){return this.config.soundEnabled=t,this}isSoundEnabled(){return this.config.soundEnabled}pause(){return this.executionLifecycleManager.pause()}resume(){return this.executionLifecycleManager.resume()}isActive(){return this.executionLifecycleManager.isActive()}setTargetFPS(t){return this.performanceMonitoringManager.setTargetFPS(t)}getTargetFPS(){return this.performanceMonitoringManager.getTargetFPS()}setPosition(t,e,i=0){return this.animationFrameController.setPosition(t,e,i)}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){return this.animationFrameController.animateToPosition(t,e,i,s,n)}clearParticles(){return this.visualTransformationManager.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.visualTransformationManager.setParticleSystemCanvasDimensions(t,e)}setPerformanceDegradation(t){return this.performanceMonitoringManager.setPerformanceDegradation(t)}getAudioLevel(){return this.speechReactivityManager.getAudioLevel()}isSpeaking(){return this.speechReactivityManager.isSpeaking()}setAudioSmoothing(t){return this.speechReactivityManager.setAudioSmoothing(t)}getSystemStatus(){return this.healthCheckManager.getSystemStatus()}setDebugMode(t){return this.healthCheckManager.setDebugMode(t)}triggerTestError(t="manual-test"){return this.healthCheckManager.triggerTestError(t)}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}registerPlugin(t){return this.pluginSystem.registerPlugin(t)}setAccessibility(t){t.colorBlindMode&&this.accessibilityManager.setColorBlindMode(t.colorBlindMode),void 0!==t.reducedMotion&&(this.accessibilityManager.reducedMotionPreferred=t.reducedMotion),void 0!==t.highContrast&&(this.accessibilityManager.highContrastEnabled=t.highContrast)}getMobileStatus(){return this.healthCheckManager.getMobileStatus()}getAccessibilityStatus(){return this.healthCheckManager.getAccessibilityStatus()}setState(t){return this.setEmotion(t)}speak(t,e={}){return this.ttsManager.speak(t,e)}setTTSSpeaking(t){this.ttsManager.setTTSSpeaking(t)}getVoices(){return this.ttsManager.getVoices()}stopTTS(){this.ttsManager.stopTTS()}handleResize(t,e,i){this.visualTransformationManager.handleResize(t,e,i)}morphTo(t,e={}){return this.visualTransformationManager.morphTo(t,e)}connectAudio(t){return this.errorBoundary.wrap(()=>this.audioHandler.connectAudio(t),"connectAudio",this)()}disconnectAudio(){return this.errorBoundary.wrap(()=>this.audioHandler.disconnectAudio(),"disconnectAudio",this)()}setOffset(t,e,i=0){return this.visualTransformationManager.setOffset(t,e,i)}getOffset(){return this.visualTransformationManager.getOffset()}setBackdrop(t={}){return this.visualTransformationManager.setBackdrop(t)}getBackdrop(){return this.visualTransformationManager.getBackdrop()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.visualTransformationManager.animateOffset(t,e,i,s,n)}getAvailableShapes(){return this.emotionalStateQueryManager.getAvailableShapes()}async handleLLMResponse(t,e={}){return this.llmIntegrationBridge.handleLLMResponse(t,e)}configureLLMHandler(t){return this.llmIntegrationBridge.configureLLMHandler(t)}getLLMResponseSchema(){return this.llmIntegrationBridge.getLLMResponseSchema()}static getLLMPromptTemplate(t={}){return Ta.getLLMPromptTemplate(t)}static getLLMEmotions(){return Ta.getLLMEmotions()}static getLLMActions(){return Ta.getLLMActions()}static getLLMShapes(){return Ta.getLLMShapes()}static getLLMGestures(){return Ta.getLLMGestures()}destroy(){this.destructionManager.destroy()}throttledWarn(t,e){const i=Date.now();i-(this.warningTimestamps[e]||0)>this.warningThrottle&&(this.warningTimestamps[e]=i)}}const so={easy:{windowMultiplier:1.5,label:"Easy"},normal:{windowMultiplier:1,label:"Normal"},hard:{windowMultiplier:.7,label:"Hard"}};class no{constructor(){this.Di="normal",this.Ri={autoRhythm:!1,slowMode:!1,visualMetronome:!1},this.Fi=.75}setDifficulty(t){so[t]&&(this.Di=t)}getDifficulty(){return this.Di}getWindowMultiplier(){return so[this.Di].windowMultiplier}setAssist(t){void 0!==t.autoRhythm&&(this.Ri.autoRhythm=!!t.autoRhythm),void 0!==t.slowMode&&(this.Ri.slowMode=!!t.slowMode),void 0!==t.visualMetronome&&(this.Ri.visualMetronome=!!t.visualMetronome)}getAssist(){return{...this.Ri}}get autoRhythm(){return this.Ri.autoRhythm}getBPMMultiplier(){return this.Ri.slowMode?this.Fi:1}get visualMetronome(){return this.Ri.visualMetronome}serialize(){return{preset:this.Di,assist:{...this.Ri}}}deserialize(t){t&&(t.preset&&so[t.preset]&&(this.Di=t.preset),t.assist&&this.setAssist(t.assist))}}class ro{constructor(t){this.zi=t,this.qi=null,this.Oi=0,this.Z=null}getAudioBlob(){return this.qi}getAudioDuration(){return this.Oi}setAudioDuration(t){this.Oi=t||0}async loadAudio(t){if(t instanceof Blob){this.qi=t;const e=URL.createObjectURL(t);await this.ji(e),URL.revokeObjectURL(e)}else await this.ji(t)}async ji(t){const e=new Audio(t);await new Promise((t,i)=>{e.addEventListener("loadedmetadata",()=>{this.Oi=1e3*e.duration,t()},{once:!0}),e.addEventListener("error",i,{once:!0}),e.load()});const i=this.zi();i&&i.soundSystem&&await i.soundSystem.loadAudioFromURL(t)}getAudioAnalysis(){const t=this.zi();return t&&t.audioAnalyzer?{bpm:t.rhythmIntegration?.getBPM()||0,beats:t.rhythmIntegration?.getBeatMarkers()||[],energy:t.audioAnalyzer?.getEnergyLevel()||0,frequencies:t.audioAnalyzer?.getFrequencyData()||[]}:null}connectAudio(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.connectAudio&&e.connectAudio(t)}disconnectAudio(t){const e=this.zi();e&&e.disconnectAudio&&e.disconnectAudio(t)}getSpectrumData(){const t=this.zi();return t&&t.audioAnalyzer?t.audioAnalyzer.dataArray?Array.from(t.audioAnalyzer.dataArray).map(t=>t/255):t.shapeMorpher&&t.shapeMorpher.frequencyData?Array.from(t.shapeMorpher.frequencyData):[]:[]}startRhythmSync(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.rhythmIntegration&&(t&&e.rhythmIntegration.setBPM(t),e.rhythmIntegration.start())}stopRhythmSync(){const t=this.zi();t&&t.rhythmIntegration&&t.rhythmIntegration.stop()}getInputEvaluator(t){const e=this.zi();if(!e||!e.rhythmIntegration)return null;const i=e.rhythmIntegration.getInputEvaluator(t);return i&&!i.K&&e.stateCoordinator&&i.setEmotionTarget((t,i)=>{e.stateCoordinator.nudgeEmotion(t,i)}),i&&!i.Z&&i.setDifficultyManager(this.getDifficultyManager()),i}getDifficultyManager(){return this.Z||(this.Z=new no),this.Z}getLayers(){const t=this.zi();return t&&t.soundSystem?t.soundSystem.getAudioLayerManager():null}}class ao{constructor(t,e){this.zi=t,this.Ue=e,this.Ii={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(t,e){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");if(this.Ue.isRecording()){const i=e||Date.now()-this.Ue.startTime();this.Ue.timeline().push({type:"gesture",name:t,time:i})}i.express(t)}express(t,e){return this.triggerGesture(t,e)}chain(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");const i=this.Ii[t.toLowerCase()];i&&(i.includes(">")?i.split(">").map(t=>t.trim()).filter(t=>t.length>0).forEach((t,i)=>{setTimeout(()=>{t.split("+").map(t=>t.trim()).filter(t=>t.length>0).forEach(t=>{e.express(t)})},500*i)}):i.split("+").map(t=>t.trim()).filter(t=>t.length>0).forEach(t=>{e.express(t)}))}updateUndertone(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.updateUndertone&&"function"==typeof e.updateUndertone?e.updateUndertone(t):e.addUndertone&&"function"==typeof e.addUndertone&&e.addUndertone(t)}getAvailableChains(){return Object.keys(this.Ii)}getChainDefinition(t){return this.Ii[t.toLowerCase()]||null}}class oo{constructor(t,e,i){this.zi=t,this.$i=e,this.Ie=i,this.Li=new Set}startRecording(){this.Ie.timeline.length=0,this.Ie.isRecording=!0,this.Ie.recordingStartTime=Date.now()}stopRecording(){return this.Ie.isRecording=!1,[...this.Ie.timeline]}playTimeline(t){if(!t||!t.length)return void(this.Ie.isPlaying=!1);this.Ie.isPlaying=!0,this.Ie.playbackStartTime=Date.now(),t.forEach(t=>{const e=setTimeout(()=>{if(this.Li.delete(e),!this.Ie.isPlaying)return;const i=this.zi();if(i)switch(t.type){case"gesture":i.express(t.name);break;case"emotion":i.setEmotion(t.name);break;case"shape":i.morphTo(t.name)}},t.time);this.Li.add(e)});const e=Math.max(...t.map(t=>t.time)),i=setTimeout(()=>{this.Li.delete(i),this.Ie.isPlaying=!1},e);this.Li.add(i)}stopPlayback(){this.Ie.isPlaying=!1,this.Li.forEach(t=>clearTimeout(t)),this.Li.clear()}getTimeline(){return[...this.Ie.timeline]}loadTimeline(t){this.Ie.timeline.length=0,this.Ie.timeline.push(...t)}exportTimeline(){return JSON.stringify({version:"1.0",duration:this.$i.getAudioDuration()||0,events:this.Ie.timeline})}importTimeline(t){let e;try{e=JSON.parse(t)}catch{return}this.Ie.timeline.length=0,this.Ie.timeline.push(...e.events||[]),this.$i.setAudioDuration(e.duration||0)}getCurrentTime(){return this.Ie.isPlaying?Date.now()-this.Ie.playbackStartTime:0}seek(t){const e=this.Ie.timeline.filter(e=>e.time<=t),i={};e.forEach(t=>{i[t.type]=t});const s=this.zi();s&&(i.emotion&&s.setEmotion(i.emotion.name),i.shape&&s.morphTo(i.shape.name))}getAnimationData(){const t=this.zi();return{timeline:[...this.Ie.timeline],duration:this.$i.getAudioDuration()||0,currentTime:this.getCurrentTime(),emotion:t?.state?.emotion||"neutral",shape:t?.state?.currentShape||"circle"}}destroy(){this.stopPlayback(),this.zi=null,this.$i=null,this.Ie=null}}class ho{constructor(t,e,i){this.zi=t,this.Gi=e,this._i=i,this.Hi=null,this.Ui=null,this.Wi=!1,this.Yi=null}attachToElement(t,e={}){if(!this.zi())throw new Error("Engine not initialized. Call init() first.");const i="string"==typeof t?document.querySelector(t):t;if(!i)return this._i;this.Hi=i,this.Ui={offsetX:e.offsetX||0,offsetY:e.offsetY||0,animate:!1!==e.animate,duration:e.duration||1e3,scale:e.scale||1,containParticles:!1!==e.containParticles};const s=i.getBoundingClientRect();return this.Ui.containParticles?this._i.setContainment({width:s.width,height:s.height},this.Ui.scale):1!==this.Ui.scale&&this._i.setContainment(null,this.Ui.scale),this.Gi()&&this.Xi(),this.Vi(),this._i}Xi(){if(!this.Hi)return;if(!this.Gi())return;const t=this.Hi.getBoundingClientRect(),e=window.innerWidth/2,i=window.innerHeight/2,s=t.left+t.width/2,n=t.top+t.height/2,r=s-e+this.Ui.offsetX,a=n-i+this.Ui.offsetY,o=!this.Wi;this.Wi=!0,o&&this.Ui.animate?this._i.animateToPosition(r,a,0,this.Ui.duration):this._i.setPosition(r,a,0)}Vi(){this.Yi||(this.Yi={scroll:()=>this.Xi(),resize:()=>this.Xi()},window.addEventListener("scroll",this.Yi.scroll,{passive:!0}),window.addEventListener("resize",this.Yi.resize))}isAttachedToElement(){return!!this.Hi}detachFromElement(){return this.Hi=null,this.Yi&&(window.removeEventListener("scroll",this.Yi.scroll),window.removeEventListener("resize",this.Yi.resize),this.Yi=null),this._i.setContainment(null,1),this._i.setEmotion("neutral"),this._i.morphTo("sphere",{duration:800}),this._i}cleanup(){this.Yi&&(window.removeEventListener("scroll",this.Yi.scroll),window.removeEventListener("resize",this.Yi.resize),this.Yi=null),this.Hi=null}}class lo{constructor(t,e){this.zi=t,this.Gi=e}setContainment(t,e=1){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");i.particleSystem&&i.particleSystem.setContainmentBounds(t),i.positionController&&(i.positionController.coreScaleOverride=e,i.positionController.particleScaleOverride=e),i.particleSystem&&i.particleSystem.particles&&i.particleSystem.particles.forEach(t=>{t.scaleFactor=e,t.size=t.baseSize*e})}clearParticles(){const t=this.zi();if(!t)throw new Error("Engine not initialized. Call init() first.");t.particleSystem&&t.particleSystem.clear()}setParticleSystemCanvasDimensions(t,e){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");i.setParticleSystemCanvasDimensions&&i.setParticleSystemCanvasDimensions(t,e)}getFrameData(t="png"){const e=this.Gi();return e?e.toDataURL(`image/${t}`):null}getFrameBlob(t="png"){const e=this.Gi();return e?new Promise(i=>{e.toBlob(t=>i(t),`image/${t}`)}):Promise.resolve(null)}}class co{constructor(){this.Ni=new Map,this.Qi=null}registerStance(t,e){this.Ni.set(t,{...e})}hasStance(t){return this.Ni.has(t)}getStance(t){const e=this.Ni.get(t);return e?{...e}:null}activate(t){const e=this.Ni.get(t);return e?(this.Qi={name:t,config:{...e}},this.Qi.config):null}dismiss(){return!!this.Qi&&(this.Qi=null,!0)}getActiveStance(){return this.Qi?{name:this.Qi.name,config:{...this.Qi.config}}:null}getAvailableStances(){return[...this.Ni.keys()]}}const uo=["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(t=>{const e=t.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{normalized:e,regex:new RegExp(i,"g")}}),po=/[,;|/]+/,mo=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"]),go=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 fo(t){return["but","and","or","yet","while","although","with"].includes(t)}function yo(t){return["not","no","never","don't","dont","doesn't","doesnt","isn't","isnt"].includes(t)}const Mo={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 wo(t,e,i){const s=bo[`${i}Context`];if(!s)return!1;const n=Math.max(0,e-3),r=Math.min(t.length,e+4);for(let i=n;i<r;i++)if(i!==e&&s.includes(t[i]))return!0;return!1}function vo(t,e){switch(e){case"emotion":return null!==t.emotion;case"gesture":return t.gestures&&t.gestures.length>0;case"shape":return null!==t.shape;case"undertone":return null!==t.undertone;default:return!1}}function So(t,e,i,s){const n=Mo[t];if(!n)return null;const{candidates:r,rule:a}=n;if(1===r.length)return r[0];switch(a){case"standalone_is_emotion":if(vo(s,"emotion")){const t=r.find(t=>"emotion"!==t.category);if(t)return t}return wo(e,i,"emotion"),r.find(t=>"emotion"===t.category)||r[0];case"standalone_is_gesture":if(vo(s,"gesture")){const t=r.find(t=>"gesture"!==t.category);if(t)return t}return wo(e,i,"gesture"),r.find(t=>"gesture"===t.category)||r[0];case"prefer_undertone":return wo(e,i,"emotion")?r.find(t=>"emotion"===t.category)||r[0]:r.find(t=>"undertone"===t.category)||r[0];case"always_gesture":return r.find(t=>"gesture"===t.category)||r[0];case"always_emotion":return r.find(t=>"emotion"===t.category)||r[0];case"context_dependent":for(const t of["emotion","gesture","shape","undertone"])if(wo(e,i,t)){const e=r.find(e=>e.category===t);if(e)return e}return r.sort((t,e)=>t.priority-e.priority)[0];default:return r.sort((t,e)=>t.priority-e.priority)[0]}}function ko(t){return t in Mo}const xo={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"]},Eo={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"]},Bo={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"]},Ao={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"]},Co={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"]}},To={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}},Po={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 Do(t){const e=new Map;for(const[i,s]of Object.entries(t)){for(const t of s){const s=t.toLowerCase().trim();e.set(s,i)}e.set(i.toLowerCase(),i)}return e}class Ro{constructor(){this.emotionLookup=Do(xo),this.undertoneLookup=Do(Eo),this.gestureLookup=Do(Bo),this.shapeLookup=Do(Ao),this.modifierLookup=function(t){const e=new Map;for(const[i,s]of Object.entries(t))for(const[t,n]of Object.entries(s))for(const s of n){const n=s.toLowerCase().trim();e.set(n,{type:i,level:t})}return e}(Co)}parse(t){const e={emotion:null,undertone:"clear",gestures:[],shape:null,intensity:To.normal.default,duration:Po.normal.default,transition:"smooth",repetition:"once",unrecognized:[],raw:t};if(!t||"string"!=typeof t)return e;const{tokens:i}=function(t){if(!t||"string"!=typeof t)return{tokens:[],segments:[],phrases:new Map};const e=t.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),{processed:i,phrases:s}=function(t){const e=new Map;let i=t,s=0;for(const{normalized:t,regex:n}of uo)if(i.includes(t)){const r=`__PHRASE_${s}__`;n.lastIndex=0,i=i.replace(n,r),e.set(r,t),s++}return{processed:i,phrases:e}}(e),n=i.split(po).map(t=>t.trim()).filter(t=>t.length>0),r=[],a=[];for(const t of n){let e=t;for(const[t,i]of s)e=e.replace(t,i);a.push(e.trim());const i=t.split(/\s+/);for(const t of i){if(s.has(t)){r.push(s.get(t));continue}if(!t)continue;if(mo.has(t)&&!go.has(t))continue;const e=t.replace(/^[^\w]+|[^\w]+$/g,"");e&&r.push(e)}}return{tokens:r,segments:a,phrases:s}}(t);if(0===i.length)return e;let s=!1;for(let t=0;t<i.length;t++){const n=i[t];if(!fo(n))if(yo(n))s=!0;else if(s)s=!1;else{if(ko(n)){const s=So(n,i,t,e);if(s){this.Ji(e,s);continue}}this.Ki(n,e)||this.Zi(n,e)||this.ts(n,e)||this.es(n,e)||this.ss(n,e)||e.unrecognized.push(n)}}return e}Ji(t,e){const{category:i,target:s}=e;switch(i){case"emotion":t.emotion||(t.emotion=s);break;case"undertone":"clear"===t.undertone&&(t.undertone=s);break;case"gesture":t.gestures.includes(s)||t.gestures.push(s);break;case"shape":t.shape||(t.shape=s)}}Ki(t,e){const i=this.emotionLookup.get(t);return!(!i||e.emotion||(e.emotion=i,0))}Zi(t,e){const i=this.gestureLookup.get(t);return!(!i||e.gestures.includes(i)||(e.gestures.push(i),0))}ts(t,e){const i=this.shapeLookup.get(t);return!(!i||e.shape||(e.shape=i,0))}es(t,e){const i=this.undertoneLookup.get(t);return!(!i||"clear"!==e.undertone||(e.undertone=i,0))}ss(t,e){const i=this.modifierLookup.get(t);if(i){const{type:t,level:s}=i;switch(t){case"intensity":e.intensity=To[s]?.default||e.intensity;break;case"duration":e.duration=Po[s]?.default||e.duration;break;case"transition":e.transition=s;break;case"repetition":e.repetition=s}return!0}return!1}validate(t){const e=[];return t.emotion||0!==t.gestures.length||t.shape||e.push("No actionable intent found (need emotion, gesture, or shape)"),(t.intensity<0||t.intensity>1)&&e.push(`Intensity ${t.intensity} out of range [0, 1]`),t.duration<=0&&e.push(`Duration ${t.duration} must be positive`),{valid:0===e.length,errors:e}}static getAvailableEmotions(){return Object.keys(xo)}static getAvailableUndertones(){return Object.keys(Eo)}static getAvailableGestures(){return Object.keys(Bo)}static getAvailableShapes(){return Object.keys(Ao)}}class Fo{#t=null;constructor(t={}){this.ns=this.rs(t),this.hs=null,this.ls=[],this.cs=!1,this.us=0,this.ds=0,this.qt=!1,this.ps=!1,this.gs=new Ro,this.fs={calls:[],maxCallsPerSecond:10,windowMs:1e3},this.ys=new co,this.$i=new ro(()=>this.#e()),this.Ms=new ao(()=>this.#e(),{isRecording:()=>this.cs,startTime:()=>this.us,timeline:()=>this.ls});const e=this;this.bs=new oo(()=>this.#e(),this.$i,{get timeline(){return e.ls},set timeline(t){e.ls=t},get isRecording(){return e.cs},set isRecording(t){e.cs=t},get recordingStartTime(){return e.us},set recordingStartTime(t){e.us=t},get isPlaying(){return e.qt},set isPlaying(t){e.qt=t},get playbackStartTime(){return e.ds},set playbackStartTime(t){e.ds=t}}),this.ws=new ho(()=>this.#e(),()=>this.vs,this),this.Ss=new lo(()=>this.#e(),()=>this.vs),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)}#e(){return this.#t||this.hs}rs(t){const e={...t};return delete e.enableDebug,delete e.enableInternalAPIs,delete e.exposeInternals,e.mode="production",void 0===e.enableGazeTracking&&(e.enableGazeTracking=!0),e}init(t){if(this.ps)return Promise.resolve();this.vs="string"==typeof t?document.getElementById(t):t;const e={...this.ns,canvasId:t},i=new io(e);return this.#t=i,this.hs=new Proxy(i,{get(t,e){if(["soundSystem","stateMachine","emotionLibrary","audioLevelProcessor","particleSystem","errorBoundary","performanceMonitor","config","debugMode"].includes(e))return new Proxy({},{get(){},set:()=>!1,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor(){}});if("renderer"===e||"shapeMorpher"===e||"audioAnalyzer"===e||"gazeTracker"===e){const i=t[e];if(!i)return;return new Proxy(i,{get(t,i){if({renderer:["setBlinkingEnabled"],shapeMorpher:["resetMusicDetection","frequencyData"],audioAnalyzer:["microphoneStream","currentFrequencies"],gazeTracker:["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"]}[e]?.includes(i))return t[i]},set:()=>!1,has:()=>!1,ownKeys:()=>[]})}return t[e]},set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1,getPrototypeOf:()=>null,setPrototypeOf:()=>!1,has:(t,e)=>!["soundSystem","stateMachine","emotionLibrary"].includes(e)&&e in t,ownKeys:t=>["canvas","start","stop","pause","resume","setEmotion","morphTo","express"].filter(e=>e in t)}),this.canvas=this.hs.canvas,this.ps=!0,Promise.resolve()}start(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.start()}stop(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.stop()}pause(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.pause()}resume(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.resume()}loadAudio(t){return this.$i.loadAudio(t)}getAudioAnalysis(){return this.$i.getAudioAnalysis()}connectAudio(t){return this.$i.connectAudio(t)}disconnectAudio(t){return this.$i.disconnectAudio(t)}getSpectrumData(){return this.$i.getSpectrumData()}startRhythmSync(t){return this.$i.startRhythmSync(t)}stopRhythmSync(){return this.$i.stopRhythmSync()}getPerformanceMetrics(){const t=this.#e();return t?t.performanceMonitor?{fps:t.performanceMonitor.getCurrentFPS()||0,frameTime:t.performanceMonitor.getAverageFrameTime()||0,particleCount:t.particleSystem?.activeParticles||0}:t.animationController?{fps:t.animationController.currentFPS||0,frameTime:1e3/60,particleCount:0}:{fps:0,frameTime:0,particleCount:0}:{fps:0,frameTime:0}}triggerGesture(t,e){return this.Ms.triggerGesture(t,e)}express(t,e){return this.Ms.express(t,e)}chain(t){return this.Ms.chain(t)}morphTo(t,e){return this.setShape(t,e)}updateUndertone(t){return this.Ms.updateUndertone(t)}feel(t){if(!this.#e())throw new Error("Engine not initialized. Call init() first.");const e=Date.now(),i=this.fs;if(i.calls=i.calls.filter(t=>e-t<i.windowMs),i.calls.length>=i.maxCallsPerSecond)return{success:!1,error:"Rate limit exceeded",parsed:null};i.calls.push(e);const s=this.gs.parse(t),n=this.gs.validate(s);if(!n.valid)return{success:!1,error:n.errors.join("; "),parsed:s};try{if(s.emotion){const t={};s.undertone&&"clear"!==s.undertone&&(t.undertone=s.undertone);const e=Math.round(500+1e3*(1-s.intensity));this.setEmotion(s.emotion,t,e)}for(const t of s.gestures)this.express(t);return s.shape&&this.morphTo(s.shape),{success:!0,error:null,parsed:s}}catch(t){return{success:!1,error:t.message,parsed:s}}}static getFeelVocabulary(){return{emotions:Ro.getAvailableEmotions(),undertones:Ro.getAvailableUndertones(),gestures:Ro.getAvailableGestures(),shapes:Ro.getAvailableShapes()}}parseIntent(t){return this.gs.parse(t)}setEmotion(t,e,i){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");let n=null,r=500,a=i;if("string"==typeof e)n=e;else if("number"==typeof e)void 0!==i?r=e:a=e;else if(e&&"object"==typeof e){const{undertone:t,duration:i,intensity:s}=e;n=t,void 0!==i&&(r=i),void 0!==s&&(this.ks=s)}if(this.cs){const e=a||Date.now()-this.us;this.ls.push({type:"emotion",name:t,undertone:n,time:e})}const o={};return n&&(o.undertone=n),void 0!==this.ks&&(o.intensity=this.ks,this.ks=void 0),s.setEmotion(t,Object.keys(o).length?o:null,r),this}setSoundEnabled(t){const e=this.#e();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.soundSystem&&(e.soundSystem.enabled=t),this}pushEmotion(t,e=.5){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.pushEmotion(t,e),this}nudgeEmotion(t,e,i=1){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");return s.stateCoordinator.nudgeEmotion(t,e,i),this}setEmotionDampening(t){const e=this.#e();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.stateCoordinator.setEmotionDampening(t),this}getEmotionDampening(){const t=this.#e();return t?t.stateCoordinator.getEmotionDampening():0}clearEmotions(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.stateCoordinator.clearEmotions(),this}getEmotionalState(){const t=this.#e();return t?t.stateCoordinator.getEmotionalState():{dominant:null,undercurrents:[],slots:[]}}getSnapshot(){const t=this.#e();if(!t)return null;const e={version:1,timestamp:Date.now(),stateMachine:t.stateMachine.serialize()};return t.stateCoordinator.ci&&(e.dynamics=t.stateCoordinator.ci.serialize()),e}loadSnapshot(t){const e=this.#e();return e&&t&&1===t.version?(t.stateMachine&&e.stateMachine.deserialize(t.stateMachine),t.dynamics&&e.stateCoordinator.dynamics.deserialize(t.dynamics),e.stateCoordinator.ti("emotionChanged",{emotion:e.stateMachine.state.emotion,slots:e.stateMachine.getSlots(),restored:!0}),this):this}get dynamics(){const t=this.#e();return t?t.stateCoordinator.dynamics:null}getInputEvaluator(t){return this.$i.getInputEvaluator(t)}setEmotionFeedback(t){const e=this.getInputEvaluator();return e&&e.setEmotionFeedback(t),this}getAudioLayers(){const t=this.$i.getLayers();return t?Object.freeze({...t}):null}getEffectiveBPM(){const t=this.#e();if(!t||!t.rhythmIntegration)return 120;let e=t.rhythmIntegration.getEffectiveBPM(t.stateMachine);return e*=this.$i.getDifficultyManager().getBPMMultiplier(),Math.round(100*e)/100}setDifficulty(t){return this.$i.getDifficultyManager().setDifficulty(t),this}setAssist(t){return this.$i.getDifficultyManager().setAssist(t),this}applyModifier(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.modifiers.applyModifier(t,e),this}removeModifier(t){const e=this.#e();return e?(e.stateCoordinator.modifiers.removeModifier(t),this):this}getActiveModifiers(){const t=this.#e();return t?t.stateCoordinator.modifiers.getActiveModifiers():[]}setShape(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");let s=t;if(this.ys.hasStance(t)){const e=this.ys.activate(t);s=e.shape||t,i.stateCoordinator&&i.stateCoordinator.ti("stanceChanged",{name:t,config:e})}let n,r={};if("number"==typeof e)n=e;else if(e&&"object"==typeof e){const{timestamp:t,...i}=e;r=i,n=t}if(this.cs){const t=n||Date.now()-this.us;this.ls.push({type:"shape",name:s,time:t,config:r})}return i&&i.morphTo(s,r),this}registerStance(t,e){return this.ys.registerStance(t,e),this}getActiveStance(){return this.ys.getActiveStance()}getAvailableStances(){return this.ys.getAvailableStances()}dismissStance(){if(this.ys.dismiss()){const t=this.#e();t&&t.stateCoordinator&&t.stateCoordinator.ti("stanceChanged",{name:null,config:null})}return this}enableGazeTracking(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.gazeTracker&&t.gazeTracker.enable(),this}disableGazeTracking(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.gazeTracker&&t.gazeTracker.disable()}setGazeTarget(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");i.gazeTracker&&(i.gazeTracker.mousePos={x:t,y:e},i.gazeTracker.updateTargetGaze())}setContainment(t,e=1){return this.Ss.setContainment(t,e)}setPosition(t,e,i=0){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");if(s.positionController)s.positionController.onUpdate||(s.positionController.onUpdate=()=>{}),s.positionController.setOffset(t,e,i);else if(this.vs){const s=window.innerWidth/2+t,n=window.innerHeight/2+e,r=1+.001*i;this.vs.style.transform=`translate(${s}px, ${n}px) translate(-50%, -50%) scale(${r})`}}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){const r=this.#e();if(!r)throw new Error("Engine not initialized. Call init() first.");r.positionController?(r.positionController.onUpdate||(r.positionController.onUpdate=()=>{}),r.positionController.animateOffset(t,e,i,s,n)):this.setPosition(t,e,i)}clearParticles(){return this.Ss.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.Ss.setParticleSystemCanvasDimensions(t,e),this}attachToElement(t,e={}){return this.ws.attachToElement(t,e)}isAttachedToElement(){return this.ws.isAttachedToElement()}detachFromElement(){return this.ws.detachFromElement()}getGazeState(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.gazeTracker?t.gazeTracker.getState():null}setBPM(t){t=Math.max(0,Math.min(300,Number(t)||0));const e=this.#e();return e&&e.rhythmIntegration&&e.rhythmIntegration.setBPM(t),this}setQuality(t){const e={low:{particleCount:50,fps:30},medium:{particleCount:100,fps:60},high:{particleCount:200,fps:60}},i=e[t]||e.medium,s=this.#e();s&&s.performanceMonitor&&s.performanceMonitor.setTargetFPS(i.fps),s&&s.particleSystem&&s.particleSystem.setMaxParticles(i.particleCount)}setMaxParticles(t){t=Math.max(0,Math.min(1e3,Math.floor(Number(t)||0)));const e=this.#e();return e&&e.particleSystem&&e.particleSystem.setMaxParticles(t),this}getParticleCount(){const t=this.#e();return t&&t.particleSystem&&t.particleSystem.particles?t.particleSystem.particles.length:0}setOpacity(t){const e=this.#e();if(t=Math.max(0,Math.min(1,t)),e&&e.renderer){const i=e.canvasManager?.getContext();i&&(i.globalAlpha=t)}return this.xs=t,this}getOpacity(){return void 0!==this.xs?this.xs:1}fadeIn(t=1e3){const e=this.getOpacity(),i=performance.now(),s=n=>{const r=n-i,a=Math.min(r/t,1),o=e+(1-e)*a;this.setOpacity(o),a<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}fadeOut(t=1e3){const e=this.getOpacity(),i=performance.now(),s=n=>{const r=n-i,a=Math.min(r/t,1),o=e*(1-a);this.setOpacity(o),a<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}async transitionTo(t,e={}){const i=e.fadeOutMs??500,s=e.fadeInMs??500;await new Promise(t=>{const e=this.getOpacity(),s=performance.now(),n=r=>{const a=Math.min((r-s)/i,1);this.setOpacity(e*(1-a)),a<1?requestAnimationFrame(n):t()};requestAnimationFrame(n)}),t&&t(this),await new Promise(t=>{const e=performance.now(),i=n=>{const r=Math.min((n-e)/s,1);this.setOpacity(r),r<1?requestAnimationFrame(i):t()};requestAnimationFrame(i)})}setAmbientMood(t){let e;if("string"==typeof t){if(e=this.Es?.[t],!e)return this}else e=t;return this.Bs={...e},e.tint&&this.setColor(e.tint),this}registerAmbientPreset(t,e){if("__proto__"===t||"constructor"===t||"prototype"===t)return this;this.Es||(this.Es={});const i={};for(const t of Object.keys(e))"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(i[t]=e[t]);return this.Es[t]=i,this}getAmbientMood(){return this.Bs?{...this.Bs}:null}setColor(t){const e=this.#e();return e&&e.renderer&&e.renderer.config&&(e.renderer.config.coreColor=t),this}setGlowColor(t){const e=this.#e();return e&&e.renderer&&e.renderer.config&&(e.renderer.config.defaultGlowColor=t),this}setTheme(t){return t&&"object"==typeof t?(t.core&&this.setColor(t.core),t.glow&&this.setGlowColor(t.glow),this):this}setSpeed(t){const e=this.#e();return t=Math.max(.1,Math.min(10,t)),this.As=t,e&&e.animationController&&e.animationController.setSpeedMultiplier(t),this}getSpeed(){const t=this.#e();return t&&t.animationController?t.animationController.getSpeedMultiplier():this.As||1}setFPS(t){const e=this.#e();return t=Math.max(1,Math.min(120,t)),e&&e.animationController&&e.animationController.setTargetFPS(t),this}getFPS(){const t=this.#e();return t&&t.animationController&&t.animationController.targetFPS||60}isPaused(){const t=this.#e();return!(!t||!t.animationController)&&!0===t.animationController.isPaused}batch(t){const e=this.isPaused();return e||this.pause(),"function"==typeof t&&t(this),e||this.resume(),this}on(t,e){const i=this.#e();return i&&i.eventManager&&i.eventManager.on(t,e),this}off(t,e){const i=this.#e();return i&&i.eventManager&&i.eventManager.off(t,e),this}setScale(t){const e=this.#e();return e&&e.positionController&&(e.positionController.setScaleOverrides(t),"object"==typeof t&&void 0!==t.particles&&e.particleSystem&&"function"==typeof e.particleSystem.refreshPool&&e.particleSystem.refreshPool()),this}getScale(){const t=this.#e();return t&&t.positionController&&t.positionController.globalScale||1}setBackdrop(t={}){const e=this.#e();return e&&"function"==typeof e.setBackdrop&&e.setBackdrop(t),this}getBackdrop(){const t=this.#e();return t&&"function"==typeof t.getBackdrop?t.getBackdrop():null}startRecording(){return this.bs.startRecording()}stopRecording(){return this.bs.stopRecording()}playTimeline(t){return this.bs.playTimeline(t)}stopPlayback(){return this.bs.stopPlayback()}getTimeline(){return this.bs.getTimeline()}loadTimeline(t){return this.bs.loadTimeline(t)}exportTimeline(){return this.bs.exportTimeline()}importTimeline(t){return this.bs.importTimeline(t)}getCurrentTime(){return this.bs.getCurrentTime()}seek(t){return this.bs.seek(t)}getFrameData(t="png"){return this.Ss.getFrameData(t)}getFrameBlob(t="png"){return this.Ss.getFrameBlob(t)}getAnimationData(){return this.bs.getAnimationData()}getAvailableGestures(){return zi()}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 t=this.#e();return t&&t.renderer?new Proxy(t.renderer,{get:(t,e)=>["setBlinkingEnabled"].includes(e)?t[e]:void 0}):null}get shapeMorpher(){const t=this.#e();return t&&t.shapeMorpher?new Proxy(t.shapeMorpher,{get:(t,e)=>["resetMusicDetection","frequencyData"].includes(e)?t[e]:void 0}):null}get gazeTracker(){const t=this.#e();return t&&t.gazeTracker?new Proxy(t.gazeTracker,{get:(t,e)=>["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"].includes(e)?t[e]:void 0}):null}destroy(){this.stop(),this.ls=[],this.cs=!1,this.qt=!1,this.detachFromElement();const t=this.#e();t&&t.destroy&&t.destroy()}}class zo{constructor(t={}){this.Ie=this.deepClone(t),this.Cs=this.deepClone(t),this.Ts=new Map,this.X=[],this.Ps=50,this.Ds=[],this.Rs=new Map,this.Fs=new Map,this.zs=new Map,this.qs={updates:0,notifications:0,computedCacheHits:0,computedCacheMisses:0}}getState(t=null){return t?this.deepClone(this.getNestedValue(this.Ie,t)):this.deepClone(this.Ie)}setState(t,e=void 0){let i;i="string"==typeof t?{[t]:e}:t;for(const t of this.Ds)if(i=t(i,this.Ie),!i)return!1;const s=this.deepClone(this.Ie);for(const[t,e]of Object.entries(i)){if(this.Rs.has(t)&&!this.Rs.get(t)(e))return!1;this.setNestedValue(s,t,e)}return this.Cs=this.Ie,this.Ie=s,this.addToHistory(i),this.invalidateComputed(Object.keys(i)),this.notifySubscribers(i),this.qs.updates++,!0}subscribe(t,e=null){let i=null,s=t;"string"==typeof t&&(i=t,s=e);const n=Symbol("subscriber"),r={path:i,callback:s,id:n};return this.Ts.set(n,r),()=>{this.Ts.delete(n)}}computed(t,e,i){this.zs.set(t,e),Object.defineProperty(this,t,{get:()=>{if(this.Fs.has(t))return this.qs.computedCacheHits++,this.Fs.get(t);this.qs.computedCacheMisses++;const s=e.map(t=>this.getState(t)),n=i(...s);return this.Fs.set(t,n),n}})}addValidator(t,e){this.Rs.set(t,e)}addMiddleware(t){this.Ds.push(t)}reset(t={}){this.Ie=this.deepClone(t),this.Cs=this.deepClone(t),this.X=[],this.Fs.clear(),this.notifySubscribers({"*":"reset"})}getDiff(){return this.objectDiff(this.Cs,this.Ie)}undo(t=1){if(this.X.length<t)return!1;const e=Math.max(0,this.X.length-t-1),i=this.X[e];return!!i&&(this.Ie=this.deepClone(i.state),this.X=this.X.slice(0,e+1),this.notifySubscribers({"*":"undo"}),!0)}batch(t){const e={},i=this.setState.bind(this);return this.setState=(t,i)=>("string"==typeof t?e[t]=i:Object.assign(e,t),!0),t(),this.setState=i,this.setState(e)}createSelector(t){let e=null,i=null;return()=>{const s=this.Ie;return s===e||(e=s,i=t(s)),i}}static Os=new Set(["__proto__","constructor","prototype"]);notifySubscribers(t){for(const e of this.Ts.values())e.path&&!Object.keys(t).some(t=>t.startsWith(e.path)||e.path.startsWith(t))||(e.callback(this.Ie,t),this.qs.notifications++)}invalidateComputed(t){for(const[e,i]of this.zs.entries())i.some(e=>t.some(t=>e.startsWith(t)||t.startsWith(e)))&&this.Fs.delete(e)}addToHistory(t){this.X.push({timestamp:Date.now(),updates:t,state:this.deepClone(this.Ie)}),this.X.length>this.Ps&&this.X.shift()}deepClone(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map(t=>this.deepClone(t));if(t instanceof Object){const e={};for(const i in t)({}).hasOwnProperty.call(t,i)&&(e[i]=this.deepClone(t[i]));return e}}getNestedValue(t,e){const i=e.split(".");for(const t of i)if(zo.Os.has(t))return;return i.reduce((t,e)=>t&&void 0!==t[e]?t[e]:void 0,t)}setNestedValue(t,e,i){const s=e.split(".");for(const t of s)if(zo.Os.has(t))return;const n=s.pop();s.reduce((t,e)=>(t[e]||(t[e]={}),t[e]),t)[n]=i}js(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(typeof t!=typeof e)return!1;if("object"!=typeof t)return!1;const i=Array.isArray(t);if(i!==Array.isArray(e))return!1;if(i){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this.js(t[i],e[i]))return!1;return!0}const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s){if(!{}.hasOwnProperty.call(e,i))return!1;if(!this.js(t[i],e[i]))return!1}return!0}objectDiff(t,e){const i={};for(const s in e)s in t?this.js(t[s],e[s])||(i[s]={type:"changed",oldValue:t[s],newValue:e[s]}):i[s]={type:"added",value:e[s]};for(const s in t)s in e||(i[s]={type:"deleted",oldValue:t[s]});return i}getStats(){return{...this.qs,subscribers:this.Ts.size,historySize:this.X.length,computedValues:this.Fs.size,validators:this.Rs.size}}}const qo=new zo({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}});t.BUILD_TYPE="lean",t.CanvasManager=ks,t.ENGINE_NAME="Emotive Engine Lean",t.EmotiveMascot=io,t.EmotiveMascotPublic=Fo,t.EmotiveRenderer=hr,t.ErrorBoundary=e,t.EventManager=Ms,t.FEATURES={rhythmSync:!1,grooveTemplates:!1,undertones:!1,undertoneSaturation:!1,gestureBlending:!0,audioReactive:!1,particleSystem:!0,accessibility:!1,mobileOptimization:!0,performanceMonitoring:!1},t.GESTURE_TYPES=Bi,t.ParticleSystem=en,t.PositionController=Er,t.StateStore=zo,t.VERSION="3.4.0-lean",t.applyEasing=Hs,t.applyGesture=Fi,t.default=Fo,t.easeInOutQuad=zs,t.easeInOutSine=_s,t.easeOutCubic=qs,t.engineState=qo,t.eventManager=bs,t.getEmotion=l,t.getEmotionVisualParams=c,t.getGesture=Pi,t.hasEmotion=m,t.interpolateHsl=Cs,t.listEmotions=d,t.listGestures=zi,Object.defineProperty(t,"Is",{value:!0})});
|
|
1
|
+
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).EmotiveMascotLean={})}(this,function(t){"use strict";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(t,e,i=null){return(...s)=>{try{const n=t(...s);return n&&"function"==typeof n.then?n.catch(t=>(this.logError(t,e),null!==i?i:this.getDefault(e))):n}catch(t){return this.logError(t,e),null!==i?i:this.getDefault(e)}}}logError(t,e){const i={timestamp:(new Date).toISOString(),context:e,message:t.message,stack:t.stack};this.errors.push(i);const s=this.errorCounts.get(e)||0;this.errorCounts.set(e,s+1),this.errors.length>this.maxErrors&&this.errors.shift()}getDefault(t){const e={"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(e,t)?e[t]:null}validateInput(t,e,i){try{switch(e){case"emotion":return["neutral","joy","sadness","anger","fear","surprise","disgust","love","euphoria"].includes(t)?t:i;case"undertone":return null===t||["nervous","confident","tired","intense","subdued"].includes(t)?t:null;case"gesture":return["bounce","pulse","shake","spin","nod","tilt","expand","contract","flash","drift"].includes(t)?t:i;case"number":return"number"!=typeof t||isNaN(t)?i:t;case"string":return"string"==typeof t?t:i;case"boolean":return"boolean"==typeof t?t:i;default:return null!=t?t:i}}catch(t){return this.logError(t,"input-validation"),i}}hasExceededThreshold(t,e=5){return(this.errorCounts.get(t)||0)>=e}getErrorStats(){return{totalErrors:this.errors.length,errorsByContext:Object.fromEntries(this.errorCounts),recentErrors:this.errors.slice(-5)}}clearErrors(){this.errors=[],this.errorCounts.clear()}async attemptRecovery(t,e,i=3){let s=0;for(;s<i;)try{return await e()}catch(e){if(s++,this.logError(e,`recovery-${t}-attempt-${s}`),s>=i)throw new Error(`Recovery failed for ${t} after ${i} attempts`);await new Promise(t=>setTimeout(t,100*Math.pow(2,s)))}}}const i=new Map;var s={registerPluginEmotion:function(t,e){return!!e.color&&(e.name||(e.name=t),e.visual||(e.visual={primaryColor:e.color,particleCount:e.particleCount||15,particleSize:e.particleSize||{min:2,max:6}}),e.modifiers||(e.modifiers={speed:1,amplitude:1,intensity:1}),i.set(t,e),!0)},unregisterPluginEmotion:function(t){return!!i.has(t)&&(i.delete(t),!0)},getPluginEmotion:function(t){return i.get(t)||null},getAllPluginEmotions:function(){return Array.from(i.keys())},clearPluginEmotions:function(){i.clear()},createLegacyAdapter:function(t){return{name:t.name||"unknown",emoji:t.emoji||"๐",color:t.primaryColor||t.color||"#7B68EE",energy:t.energy||"medium",visual:{primaryColor:t.primaryColor||t.color||"#7B68EE",secondaryColor:t.secondaryColor,particleCount:t.particleCount||t.particleRate||15,particleSize:t.particleSize||{min:2,max:6},glowIntensity:t.glowIntensity||.5,trailLength:t.trailLength||5,pulseRate:t.pulseRate||t.breathRate||1},particles:{behavior:t.particleBehavior||"ambient",density:t.particleDensity||"medium",speed:t.particleSpeed||"normal"},modifiers:{speed:t.speedMultiplier||1,amplitude:t.amplitudeMultiplier||1,intensity:t.intensityMultiplier||1,smoothness:t.smoothnessMultiplier||1},gestures:t.gestures||[],transitions:t.transitions||{}}}},n={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 t=this.threatLevel||0,e=Math.round(107+113*t),i=Math.round(70+-32*t),s=Math.round(193+-66*t),n=t=>t.toString(16).padStart(2,"0");return`#${n(e)}${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}},r={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(t){const e=t.time||Date.now(),i=.5*Math.sin(6e-4*e)+.5;return{scaleX:1-.02*i,scaleY:1-.02*i,eyeOpenness:.85,eyeExpression:"serene",pupilOffset:{x:2*Math.sin(3e-4*e),y:1*Math.cos(4e-4*e)},glowPulse:.95+.05*i}},updateParticle(t,e){t.x+=.1*Math.sin(.001*t.life),t.y-=.02*e,t.opacity=.3*Math.sin(.002*t.life)+.2,t.size=t.baseSize*(1+.2*Math.sin(.001*t.life))},renderCore:(t,e,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,o={happy:"joy",peaceful:"calm",curious:"surprise",frustrated:"anger",sad:"sadness",excitement:"excited"};function h(t){t.name&&a.set(t.name,t)}function l(t){const e=o[t]||t,i=a.get(e);return i||(s.getPluginEmotion(e)||null)}function c(t){const e=l(t);if(!e)return l("neutral").visual;if(!e.visual)return{};const{visual:i}=e,s={};for(const t in i)"function"!=typeof i[t]&&(s[t]=i[t]);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 u(t){const e=l(t);return e?e.modifiers:l("neutral").modifiers}function d(){return[...Array.from(a.keys()),...s.getAllPluginEmotions()]}function p(){const t={};return a.forEach((e,i)=>{t[i]=e}),t}function m(t){const e=o[t]||t;return a.has(e)||null!==s.getPluginEmotion(e)}function g(t,e){o[t]=e}function f(t,e){const i=l(t),s=l(e);return i&&s?s.transitions&&s.transitions[t]?s.transitions[t]:{duration:1e3,easing:"ease-in-out",gesture:s.transitions?.defaultGesture||null}:{duration:1e3,easing:"ease-in-out"}}function y(t){const e=l(t);return e?.gestures||[]}function M(t){const e=l(t);return e?.rhythmModifiers??{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0}}function b(t){if(!t||0===t.length)return{windowMultiplier:1,visualNoise:0,inputDelay:0,tempoShift:0};if(1===t.length){const e=M(t[0].emotion),i=t[0].intensity;return{windowMultiplier:1+(e.windowMultiplier-1)*i,visualNoise:e.visualNoise*i,inputDelay:e.inputDelay*i,tempoShift:e.tempoShift*i}}let e=0;for(let i=1;i<t.length;i++)t[i].intensity>t[e].intensity&&(e=i);const i={windowMultiplier:0,visualNoise:0,inputDelay:0,tempoShift:0},s=t.filter((t,i)=>i!==e),n=s.length>0?.25/s.length:0,r=M(t[e].emotion),a=t[e].intensity;i.windowMultiplier+=.75*(1+(r.windowMultiplier-1)*a),i.visualNoise+=r.visualNoise*a*.75,i.inputDelay+=r.inputDelay*a*.75,i.tempoShift+=r.tempoShift*a*.75;for(const t of s){const e=M(t.emotion),s=t.intensity;i.windowMultiplier+=(1+(e.windowMultiplier-1)*s)*n,i.visualNoise+=e.visualNoise*s*n,i.inputDelay+=e.inputDelay*s*n,i.tempoShift+=e.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:t=>({scaleX:1,scaleY:1,eyeOpenness:1,eyeExpression:"neutral",pupilOffset:{x:0,y:0}}),renderCore:(t,e,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:t=>({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}},n,{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:t=>({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}},r].forEach(t=>{t&&t.name&&a.set(t.name,t)});var w={registerEmotion:h,getEmotion:l,getEmotionVisualParams:c,getEmotionParams:c,getEmotionModifiers:u,getEmotionRhythmModifiers:M,getBlendedRhythmModifiers:b,listEmotions:d,getAllEmotions:p,hasEmotion:m,addEmotionAlias:g,getTransitionParams:f,getEmotionGestures:y,pluginAdapter:s},v=Object.freeze({__proto__:null,addEmotionAlias:g,default:w,getAllEmotions:p,getBlendedRhythmModifiers:b,getEmotion:l,getEmotionGestures:y,getEmotionModifiers:u,getEmotionRhythmModifiers:M,getEmotionVisualParams:c,getTransitionParams:f,hasEmotion:m,listEmotions:d,pluginAdapter:s,registerEmotion:h});const S=new Map;var k={registerPluginGesture:function(t,e){return!(!e.apply&&!e.type||(e.name||(e.name=t),e.type||(e.type="blending"),S.set(t,e),0))},unregisterPluginGesture:function(t){return!!S.has(t)&&(S.delete(t),!0)},getPluginGesture:function(t){return S.get(t)||null},getAllPluginGestures:function(){return Array.from(S.keys())},clearPluginGestures:function(){S.clear()},createLegacyAdapter:function(t){return{name:t.name||"unknown",type:t.type||"blending",emoji:t.emoji||"๐",description:t.description||"Plugin gesture",config:t.config||{},apply(e,i,s,n,r,a){t.animate?t.animate(e,i,s,n,r,a):t.apply&&t.apply(e,i,s,n,r,a)},cleanup:t.cleanup||function(t){t.gestureData&&t.gestureData[this.name]&&delete t.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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.breathe={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),phaseOffset:.2*Math.random()-.1}},apply(t,e,i,s,n,r){t.gestureData?.breathe||this.initialize(t,i,n,r);const a={...this.config,...i},o=(Math.sin(e*Math.PI*2*a.breathRate)+1)/2,h=100*(t.scaleFactor||1),l=a.inhaleRadius*h,c=a.exhaleRadius*h,u=c+(l-c)*o,d=t.x-n,p=t.y-r,m=Math.sqrt(d*d+p*p),g=u-m,f=.05*(i.strength||.8)*s;if(m>0){const e=d/m*g*f,n=p/m*g*f;t.vx+=e,t.vy+=n;const r=a.spiralStrength*s*(i.strength||1),h=-p/m,l=d/m;t.vx+=h*r*o,t.vy+=l*r*o}t.vx*=.98,t.vy*=.98},cleanup(t){t.gestureData?.breathe&&delete t.gestureData.breathe},"3d":{evaluate(t,e){const i=(e.config||{}).breathRate||.3,s=Math.sin(t*Math.PI*2*i);let n=1;if(t>.8){const e=(t-.8)/(1-.8);n=1-e*e*e}const r=.2*s*n;return{position:[0,.05*s*n,0],rotation:[0,0,0],scale:1+.35*s*n,glowIntensity:1+r,glowBoost:Math.max(0,2*r)}}}},E={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.expand={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.expand?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.expand,o={...this.config,...i},h=o.strength||1,l=1+(o.scaleTarget-1)*e*h,c=a.baseRadius*l,u=n+Math.cos(a.angle)*c,d=r+Math.sin(a.angle)*c,p=u-t.x,m=d-t.y;t.vx+=.8*p*s,t.vy+=.8*m*s,t.vx*=.95,t.vy*=.95},cleanup(t){t.gestureData?.expand&&delete t.gestureData.expand},"3d":{evaluate(t,e){const i={...this.config,...e},s=i.strength||3;return{position:[0,0,0],rotation:[0,0,0],scale:1+t*(i.scaleAmount||3)*(s/3),glowIntensity:1+.25*t,glowBoost:.8*t}}}},B={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.contract={startX:t.x,startY:t.y,angle:Math.atan2(r,n),baseRadius:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.contract?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.contract,o={...this.config,...i},h=o.strength||1,l=1-(1-o.scaleTarget)*e*h,c=a.baseRadius*l,u=n+Math.cos(a.angle)*c,d=r+Math.sin(a.angle)*c,p=u-t.x,m=d-t.y;t.vx+=.5*p*s,t.vy+=.5*m*s,t.vx*=.95,t.vy*=.95},cleanup(t){t.gestureData?.contract&&delete t.gestureData.contract},"3d":{evaluate(t,e){const i={...this.config,...e},s=i.strength||2.5,n=i.scaleTarget||.2,r=1-t*(1-n)*(s/2.5),a=1-.15*t;return{position:[0,0,0],rotation:[0,0,0],scale:Math.max(n,r),glowIntensity:a}}}},A={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.atan2(r,n);t.gestureData.pulse={baseDistance:a,angle:o,startX:t.x,startY:t.y,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.pulse?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.pulse,o={...this.config,...i},h=i.strength||1,l=this.easeInOutSine(e);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 p=l*u*2%2;c=o.holdPeak>0&&p>1-o.holdPeak&&p<1+o.holdPeak?1:Math.sin(l*Math.PI*2*u);const m=c*d*h*t.scaleFactor,g=a.baseDistance+m,f=n+Math.cos(a.angle)*g,y=r+Math.sin(a.angle)*g,M=.15*s;if(t.vx+=(f-t.x)*M*.1,t.vy+=(y-t.y)*M*.1,e>.9){const i=1-10*(e-.9);t.vx*=.9+.1*i,t.vy*=.9+.1*i}},cleanup(t){t.gestureData?.pulse&&delete t.gestureData.pulse},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i=e||{},s=i.frequency||1,n=i.strength||.15,r=i.scaleAmount||.2,a=i.glowAmount||.3,o=-(Math.cos(Math.PI*t)-1)/2,h=Math.sin(o*Math.PI*2*s);return{position:[0,0,0],rotation:[0,0,0],scale:1+h*r*n,glowIntensity:1+Math.max(-.3,Math.min(.3,h*a*n*2)),glowBoost:Math.max(0,.8*h)}}}},C={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.amplitude||this.config.amplitude,h=a.frequency||this.config.frequency,l=a.strength||this.config.strength,c=Math.sin(e*Math.PI*2*h)*o;t.vx+=.01*c*s*l,t.vy+=.5*Math.cos(e*Math.PI*4)*s*l},cleanup(t){},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.amplitude||this.config.amplitude;const n=i.frequency||this.config.frequency,r=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const a=Math.sin(t*Math.PI*2*n),o=s*r*.3*.01,h=.15*a*r,l=.08*a*r;return{position:[a*o,.3*Math.cos(t*Math.PI*4)*o,Math.sin(t*Math.PI*n)*o*.5],rotation:[0,l,h],scale:1}}}},T={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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.float||(t.gestureData.float={originalSize:t.size,originalOpacity:t.opacity||1});const a={...this.config,...i};let o=a.amplitude||this.config.amplitude,h=a.wobbleAmount||this.config.wobbleAmount;const l=a.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1,h*=i.rhythmModulation.wobbleMultiplier||1);const c=Math.sin(e*Math.PI*4)*h;t.vy-=.01*o*s*l*(1-.5*e),t.vx+=.01*c*s*l,t.size=t.baseSize*(1+.1*e),t.opacity=1-.3*e},cleanup(t){t.gestureData?.float?(t.opacity=t.gestureData.float.originalOpacity,t.size=t.gestureData.float.originalSize,delete t.gestureData.float):(t.opacity=1,t.size=t.baseSize),t.vx*=.5,t.vy*=.5},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.amplitude||this.config.amplitude,n=i.wobbleAmount||this.config.wobbleAmount;const r=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1,n*=e.rhythmModulation.wobbleMultiplier||1);const a=Math.sin(t*Math.PI),o=s*a*r*.005,h=Math.sin(t*Math.PI*4)*n*.3*.005,l=Math.sin(t*Math.PI)*Math.PI*.5*r,c=Math.sin(t*Math.PI);return{position:[h,o,0],rotation:[c*Math.sin(t*Math.PI*2)*.1,l,c*Math.cos(t*Math.PI*3)*.08],scale:1+.1*a}}}};const P={left:{x:-1,y:0},right:{x:1,y:0},up:{x:0,y:1},down:{x:0,y:-1}};function D(t){return t.charAt(0).toUpperCase()+t.slice(1)}function R(t){const e=P[t];if(!e)throw new Error(`Invalid float direction: ${t}`);const i="up"===t||"down"===t;return{name:`float${D(t)}`,emoji:"up"===t?"๐":"down"===t?"๐":"left"===t?"๐ฌ๏ธ":"๐จ",type:"blending",description:`Gentle floating ${t}`,config:{duration:2e3,amplitude:80,wobbleAmount:20,strength:1,direction:t},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(t,s,n,r,a,o){t.gestureData||(t.gestureData={}),t.gestureData.float||(t.gestureData.float={originalSize:t.size,originalOpacity:t.opacity||1});const h={...this.config,...n};let l=h.amplitude||80,c=h.wobbleAmount||20;const u=h.strength||1;n.rhythmModulation&&(l*=n.rhythmModulation.amplitudeMultiplier||1,l*=n.rhythmModulation.accentMultiplier||1,c*=n.rhythmModulation.wobbleMultiplier||1);const d=Math.sin(s*Math.PI*4)*c,p=.01*l*r*u*(1-.5*s);i?(t.vy+=e.y*p,t.vx+=.01*d*r*u):(t.vx+=e.x*p,t.vy+=.01*d*r*u),t.size=t.baseSize*(1+.1*s),t.opacity=1-.3*s},cleanup(t){t.gestureData?.float?(t.opacity=t.gestureData.float.originalOpacity,t.size=t.gestureData.float.originalSize,delete t.gestureData.float):(t.opacity=1,t.size=t.baseSize),t.vx*=.5,t.vy*=.5},"3d":{evaluate(t,s){const n=s||{};let r=n.amplitude||80,a=n.wobbleAmount||20;const o=n.strength||1;s.rhythmModulation&&(r*=s.rhythmModulation.amplitudeMultiplier||1,r*=s.rhythmModulation.accentMultiplier||1,a*=s.rhythmModulation.wobbleMultiplier||1);const h=Math.sin(t*Math.PI),l=r*h*o*.005,c=Math.sin(t*Math.PI*4)*a*.3*.005,u=Math.sin(t*Math.PI)*Math.PI*.5*o,d=Math.sin(t*Math.PI),p=d*Math.sin(t*Math.PI*2)*.1,m=d*Math.cos(t*Math.PI*3)*.08,g=1+.1*h;let f=0,y=0;return i?(y=e.y*l,f=c):(f=e.x*l,y=c),{cameraRelativePosition:[f,y,0],rotation:[p,u,m],scale:g}}}}}var F=R("up"),z=R("down"),q=R("left"),O=R("right"),j={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.lean={startX:t.x,startY:t.y,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.lean?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e),l=a.frequency||this.config.frequency;let c=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(h*Math.PI*l),d="left"===a.direction?-1:1;if(t.vx+=u*c*.015*s*d,t.vy+=u*c*.01*s*d*.5,e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.lean&&delete t.gestureData.lean},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||10,n=i.frequency||1,r=i.strength||.7,a=i.direction||"right",o=.003*s*r,h=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,l=Math.sin(h*Math.PI*n),c="left"===a?-1:1;return{position:[l*o*c,0,0],rotation:[0,0,.35*l*c],scale:1}}}};function I(t){if("left"!==t&&"right"!==t)throw new Error(`Invalid lean direction: ${t}. Only 'left' and 'right' are supported.`);const e=P[t];return{name:`lean${D(t)}`,emoji:"left"===t?"โ๏ธ":"โ๏ธ",type:"blending",description:`Lean ${t} with smooth return`,config:{duration:800,amplitude:10,frequency:1,strength:.7,direction:t},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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.lean={startX:t.x,startY:t.y,initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.lean?.initialized||this.initialize(t,s);const o={...this.config,...s},h=o.strength||.7,l=this.easeInOutCubic(i);let c=o.amplitude*h*t.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI*o.frequency);if(t.vx+=u*c*.015*n*e.x,t.vy+=u*c*.01*n*e.x*.5,i>.9){const e=1-10*(i-.9);t.vx*=.95+.05*e,t.vy*=.95+.05*e}},cleanup(t){t.gestureData?.lean&&delete t.gestureData.lean},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||10,r=s.frequency||1,a=.003*n*(s.strength||.7),o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI*r),l=.35*h*e.x;return{cameraRelativePosition:[h*a*e.x,0,0],cameraRelativeRotation:[0,0,l],scale:1}}}}}var $=I("left"),L=I("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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.jitter||(t.gestureData.jitter={originalSize:t.size});const a={...this.config,...i};let o=a.intensity||this.config.intensity;const h=a.strength||this.config.strength;i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1,o*=i.rhythmModulation.accentMultiplier||1);const l=(Math.random()-.5)*o*h,c=(Math.random()-.5)*o*h,u=1-.5*e;t.vx+=.1*l*s*u,t.vy+=.1*c*s*u,t.size=t.baseSize*(1+.1*(Math.random()-.5))},cleanup(t){t.gestureData?.jitter?(t.size=t.gestureData.jitter.originalSize,delete t.gestureData.jitter):t.size=t.baseSize,t.vx*=.7,t.vy*=.7},"3d":{evaluate(t,e){const i={...this.config,...e};let s=i.intensity||this.config.intensity;const n=i.strength||this.config.strength;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const r=Math.sin(t*Math.PI),a=s*n*.002*r;return{position:[(Math.random()-.5)*a,(Math.random()-.5)*a,(Math.random()-.5)*a],rotation:[.005*(Math.random()-.5)*r,.005*(Math.random()-.5)*r,.005*(Math.random()-.5)*r],scale:1+.02*(Math.random()-.5)*r}}}},_={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(t,e,i,s,n,r){t.gestureData||(t.gestureData={}),t.gestureData.twitch||(t.gestureData.twitch={twitchOffset:{x:0,y:0},targetOffset:{x:0,y:0},isTwitching:!1,twitchTimer:0,cooldownTimer:0,lastTwitch:0});const a=t.gestureData.twitch,{config:o}=this;let h=i.intensity||o.intensity;i.rhythmModulation&&(h*=i.rhythmModulation.amplitudeMultiplier||1,h*=i.rhythmModulation.accentMultiplier||1);const l=Date.now();if(!a.isTwitching&&a.cooldownTimer<=0&&Math.random()<(i.frequency||o.frequency)){a.isTwitching=!0,a.twitchTimer=o.duration,a.cooldownTimer=o.recovery;const t=Math.random()*Math.PI*2,e=.5*o.maxOffset+Math.random()*(.5*o.maxOffset);a.targetOffset={x:Math.cos(t)*e*h/8,y:Math.sin(t)*e*h/8},a.lastTwitch=l}if(a.cooldownTimer>0&&(a.cooldownTimer-=16*s),a.isTwitching)if(a.twitchTimer-=16*s,a.twitchTimer>0){const{sharpness:t}=o;a.twitchOffset.x+=(a.targetOffset.x-a.twitchOffset.x)*t,a.twitchOffset.y+=(a.targetOffset.y-a.twitchOffset.y)*t}else a.isTwitching=!1;else a.twitchOffset.x*=.85,a.twitchOffset.y*=.85;t.vx+=a.twitchOffset.x*s*.5,t.vy+=a.twitchOffset.y*s*.5,Math.random()<.1&&(t.vx+=(Math.random()-.5)*h*.3,t.vy+=(Math.random()-.5)*h*.3)},cleanup(t){t.gestureData?.twitch&&delete t.gestureData.twitch},"3d":{evaluate(t,e){const i=e.config||{};let s=.6*(i.intensity||8);const n=i.maxOffset||15,r=i.frequency||.08;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const a=9999*Math.floor(10*t),o=t=>{const e=1e4*Math.sin(a+t);return e-Math.floor(e)};if(o(0)<3*r){const t=o(1)*Math.PI*2,e=n*s/8*.003;return{position:[Math.cos(t)*e*o(2),Math.sin(t)*e*o(3),(o(4)-.5)*e],rotation:[.12*(o(5)-.5),.12*(o(6)-.5),.12*(o(7)-.5)],scale:1+.06*(o(8)-.5)}}{const t=.3;return{position:[(o(10)-.5)*t,(o(11)-.5)*t,(o(12)-.5)*t],rotation:[.006*(o(13)-.5),.006*(o(14)-.5),.006*(o(15)-.5)],scale:1}}}}},H={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.vibrate={timer:0,seed:1e3*Math.random(),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.vibrate?.initialized||this.initialize(t,i);const a=t.gestureData.vibrate,o={...this.config,...i},h=o.strength||this.config.strength||1;let{amplitude:l}=o,{frequency:c}=o;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier)),a.timer+=s*c;const u=(Math.random()-.5)*l*h,d=(Math.random()-.5)*l*h;if(t.vx+=.5*u*s,t.vy+=.5*d*s,t.vx*=.9,t.vy*=.9,e>.8){const i=1-5*(e-.8);t.vx*=i,t.vy*=i}},cleanup(t){t.gestureData?.vibrate&&delete t.gestureData.vibrate},"3d":{evaluate(t,e){const i={...this.config,...e};let{amplitude:s}=i;const n=i.strength||this.config.strength||1;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);const r=Math.sin(t*Math.PI),a=s*n*.003*r;return{position:[(Math.random()-.5)*a,(Math.random()-.5)*a,(Math.random()-.5)*a],rotation:[.01*(Math.random()-.5)*r,.01*(Math.random()-.5)*r,.01*(Math.random()-.5)*r],scale:1+.01*(Math.random()-.5)*r}}}},U={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.shake={originalX:t.x,originalY:t.y,randomAngle:Math.random()*Math.PI*2,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.shake?.initialized||this.initialize(t,i);const a=t.gestureData.shake,o={...this.config,...i},h=o.strength||this.config.strength||1;let{amplitude:l}=o,{frequency:c}=o;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(c*=i.rhythmModulation.frequencyMultiplier));const u=o.decay?1-e:1,d=Math.sin(e*Math.PI*c)*l*u*h*t.scaleFactor,p=d*Math.cos(a.randomAngle),m=d*Math.sin(a.randomAngle);t.x=a.originalX+p,t.y=a.originalY+m},pseudoRandom(t){const e=1e4*Math.sin(t);return e-Math.floor(e)},cleanup(t){t.gestureData?.shake&&(t.x=t.gestureData.shake.originalX,t.y=t.gestureData.shake.originalY,delete t.gestureData.shake)},"3d":{evaluate(t,e){const i=e||{},s=.003*(i.amplitude||15),n=i.frequency||15,r=.5*(i.strength||1),a=i.decay?1-t:1,o=Math.sin(t*Math.PI*n)*s*a*r,h=Math.floor(t*n);return{position:[o*(1e4*Math.sin(h)%1-.5)*2,0,o*(1e4*Math.sin(1.3*h)%1-.5)*2],rotation:[0,0,o*(1e4*Math.sin(1.7*h)%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(t,e,i,s,n,r,a){const o=(i.amplitude||this.config.amplitude)*n,h=i.frequency||this.config.frequency,l=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*h)*o*l;t.vx+=.5*c;const u=Math.cos(s*Math.PI*h*2)*o*.1*l;t.vy+=.3*u},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.amplitude||15,r=Math.pow(1-t,.5),a=Math.sin(t*Math.PI*14)*r,o=Math.cos(t*Math.PI*14*.7)*r*.4,h=n/15*s,l=.15*a*s;return{cameraRelativePosition:[.08*a*h,.02*Math.abs(o)*h,0],cameraRelativeRotation:[0,0,l],scale:1+.05*Math.abs(a),glowIntensity:1+.2*Math.abs(a)}}}};function Y(t){const e=P[t];if(!e)throw new Error(`Invalid step direction: ${t}`);return{name:`step${D(t)}`,emoji:"left"===t?"๐":"right"===t?"๐":"up"===t?"๐":"๐",type:"blending",description:`Quick step ${t} and return`,config:{duration:400,amplitude:25,strength:.7,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h,l=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1),h=i<.3?this.easeOutQuad(i/.3):1-this.easeInOutCubic((i-.3)/.7);const c=e.x*l*h*.01*n,u=e.y*l*h*.01*n;t.vx+=c,t.vy+=u},cleanup(t){},easeOutQuad:t=>1-(1-t)*(1-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||25,r=s.strength||.7;let a,o=.008*n*r;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),t<.3)a=1-(1-t/.3)*(1-t/.3);else{const e=(t-.3)/.7;a=1-(e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2)}const h=e.x*o*a,l=e.y*o*a,c=.12*a*r,u=-e.x*c;return{cameraRelativePosition:[h,l,0],rotation:[e.y*c*.5,0,u],scale:1}}}}}function X(t){const e=P[t];if(!e)throw new Error(`Invalid slide direction: ${t}`);return{name:`slide${D(t)}`,emoji:"left"===t?"โฌ
๏ธ":"โก๏ธ",type:"blending",description:`Smooth slide ${t} and return`,config:{duration:800,amplitude:35,strength:.6,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(h*=s.rhythmModulation.amplitudeMultiplier||1,h*=s.rhythmModulation.accentMultiplier||1);const l=Math.sin(i*Math.PI),c=e.x*h*l*.008*n,u=e.y*h*l*.008*n;t.vx+=c,t.vy+=u},cleanup(t){},"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||35,r=s.strength||.6;let a=.008*n*r;i.rhythmModulation&&(a*=i.rhythmModulation.amplitudeMultiplier||1);const o=Math.sin(t*Math.PI),h=e.x*a*o,l=e.y*a*o,c=.08*o*r,u=-e.x*c,d=e.x*c*.5;return{cameraRelativePosition:[h,l,.02*Math.sin(t*Math.PI*2)*r],rotation:[0,d,u],scale:1+.03*o}}}}}var V=Y("left"),N=Y("right"),Q=Y("up"),J=Y("down"),K=X("left"),Z=X("right"),tt={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:(t,e,i,s,n,r)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i={...this.config,...e}.strength||.8;return{position:[.1*Math.sin(t*Math.PI*4)*i,.05*Math.abs(Math.sin(t*Math.PI*8))*i,0],rotation:[0,0,.035*Math.sin(t*Math.PI*4)*i],scale:1-.035*Math.abs(Math.sin(t*Math.PI*8))*i,glowIntensity:1+.25*Math.abs(Math.sin(t*Math.PI*8)),glowBoost:.35*Math.max(0,Math.abs(Math.sin(t*Math.PI*8)))}}}},et={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:(t,e,i,s,n,r)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i={...this.config,...e}.strength||.9;return{position:[.12*Math.sin(t*Math.PI*8)*i,.05*Math.abs(Math.sin(t*Math.PI*8))*i,0],rotation:[0,0,.05*Math.sin(t*Math.PI*8)*i],scale:1-.04*Math.abs(Math.sin(t*Math.PI*8))*i,glowIntensity:1+.3*Math.abs(Math.sin(t*Math.PI*8)),glowBoost:.4*Math.max(0,Math.abs(Math.sin(t*Math.PI*8)))}}}},it={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.random()<.5?1:-1,h=Math.max(a,100+180*Math.random()),l=a<5?Math.random()*Math.PI*2:Math.atan2(r,n);t.gestureData.hula={radius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,wobblePhase:Math.random()*Math.PI*2,direction:o}},apply(t,e,i,s,n,r){t.gestureData?.hula||this.initialize(t,i,n,r);const a=t.gestureData.hula,o=(i.speed||this.config.speed)*(i.strength||1);let h=1;e<.1?(h=e/.1,h=Math.sin(h*Math.PI*.5)):e>.9&&(h=(1-e)/.1,h=Math.sin(h*Math.PI*.5)),a.angle+=o*s*a.direction*h;const l=Math.sin(2*a.angle+a.wobblePhase)*(i.wobbleAmount||this.config.wobbleAmount)*h,c=a.radius*(1+l)*h,u=a.radius*(.7+l)*h,d=n+Math.cos(a.angle)*c,p=r+Math.sin(a.angle)*u;if(e<.1){const e=t.x-n,i=t.y-r;Math.sqrt(e*e+i*i)<50?(t.x=n+Math.cos(a.angle)*c,t.y=r+Math.sin(a.angle)*u):(t.x=t.x+(d-t.x)*h*.5,t.y=t.y+(p-t.y)*h*.5)}else t.x=d,t.y=p;const m=a.angle+a.zPhase+(i.zPhaseOffset||this.config.zPhaseOffset);t.z=.9*Math.sin(m)*h;const g=i.verticalOscillation||this.config.verticalOscillation,f=Math.cos(2*m)*g*a.radius*.2*h;t.y+=f;const y=t.z*a.radius*.1;t.y-=y;const M=-Math.sin(a.angle)*c*o,b=Math.cos(a.angle)*u*o;e<.1?(t.vx=a.originalVx+(M-a.originalVx)*h,t.vy=a.originalVy+(b-a.originalVy)*h):e>.9?(t.vx=M*h+a.originalVx*(1-h),t.vy=b*h+a.originalVy*(1-h),t.z=t.z*h+a.originalZ*(1-h)):(t.vx=M,t.vy=b)},cleanup(t){if(t.gestureData?.hula){const e=t.gestureData.hula;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.hula}},"3d":{evaluate(t,e){const{particle:i}=e;if(!i||!i.gestureData?.hula)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=i.gestureData.hula,n=e.config||{};let r=1;t<.15?(r=t/.15,r=Math.sin(r*Math.PI*.5)):t>.85&&(r=(1-t)/.15,r=Math.sin(r*Math.PI*.5));const a=s.initialAngle+t*Math.PI*2*s.direction,o=.25*Math.cos(a)*r,h=.25*Math.sin(a)*r,l=n.verticalOscillation||.3;return{position:[o,Math.sin(2*a+s.wobblePhase)*l*r,h],rotation:[0,(a-s.initialAngle)*r,0],scale:1+.15*Math.abs(Math.sin(a))*r}}}},st={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.twist={startX:t.x,startY:t.y,startAngle:Math.atan2(t.y-e.centerY,t.x-e.centerX),startDistance:Math.sqrt(Math.pow(t.x-e.centerX,2)+Math.pow(t.y-e.centerY,2)),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.twist?.initialized||this.initialize(t,{...i,centerX:n,centerY:r});const a={...this.config,...i},o=t.gestureData.twist,h=a.strength||this.config.strength||1,l=e*a.twistFrequency*Math.PI*2,c=Math.sin(l)*h;let{rotationAngle:u}=a,{contractionFactor:d}=a;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,d=1-(1-d)*(i.rhythmModulation.amplitudeMultiplier||1));const p=u*Math.PI/180*c,m=1-(1-d)*Math.abs(c),g=o.startAngle+p,f=o.startDistance*m,y=n+Math.cos(g)*f,M=r+Math.sin(g)*f,b=.15*h;t.x+=(y-t.x)*b,t.y+=(M-t.y)*b,t.vx=.05*(y-t.x),t.vy=.05*(M-t.y);const w=5*Math.sin(e*Math.PI*4)*h;if(t.y+=.1*w,e>.9){const i=1-10*(e-.9);t.vx*=i,t.vy*=i}},cleanup(t){t.gestureData?.twist&&delete t.gestureData.twist},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||.8,n=t>.85?(1-t)/.15:1,r=t*(i.twistFrequency||2)*Math.PI*2,a=Math.sin(r)*s*n,o=a*((i.rotationAngle||45)*Math.PI/180);return{position:[.05*Math.sin(r)*s*n,.02*Math.abs(Math.sin(2*r))*s*n,0],rotation:[.08*Math.cos(r)*s*n,o,.12*Math.sin(.5*r)*s*n],scale:1-(1-(i.contractionFactor||.8))*Math.abs(a),glowIntensity:1+.3*Math.abs(a)}}}},nt={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;return t<.15?(s=t/.15,s=1-Math.pow(1-s,3)):(s=1-(t-.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]}}}},rt={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.1){const e=t/.1;s=1-Math.pow(1-e,4)}else if(t<.3){const e=(t-.1)/.2;s=1-.1*Math.sin(e*Math.PI)}else s=1-(t-.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(t*Math.PI*4)*(1-t)*.02)*i,glowBoost:.8*s*i,positionBoost:[0,.04*s*i,0]}}}},at={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.6){const e=t/.6;s=e*e}else{const e=(t-.6)/.4;s=1-e*e}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(t*Math.PI)*i,0]}}}},ot={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1;let s;if(t<.3){const e=t/.3;s=1-Math.pow(1-e,2)}else if(t<.7)s=1;else{const e=(t-.7)/.3;s=1-e*e}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}}}},ht={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{isAccent:!0,evaluate(t,e){const i=e?.strength||1,s=Math.sin(t*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1,positionBoost:[0,.015*-s*i,0],scaleBoost:1-.015*s*i}}}},lt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.bounce={startY:t.y,startX:t.x,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.bounce?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e);let{frequency:l}=a;const c=i.phase||0;let u=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(u*=i.rhythmModulation.amplitudeMultiplier||1,u*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const d=Math.sin((h+c)*Math.PI*2*l);if(a.damping&&e>.7&&(u*=1-(e-.7)/.3*.8),"vertical"===a.axis?(t.vy+=d*u*.01*s,e>.9&&(t.vx*=.98)):"horizontal"===a.axis&&(t.vx+=d*u*.01*s,e>.9&&(t.vy*=.98)),e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.bounce&&delete t.gestureData.bounce},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||30,n=i.frequency||2,r=.003*s*(i.strength||.6),a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*Math.PI*n,o=Math.abs(Math.sin(a));let h=r;return t>.7&&(h*=1-(t-.7)/.3*.8),{position:[0,o*h,0],rotation:[0,0,0],scale:1+.08*o}}}},ct={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.sqrt(n*n+r*r),o=Math.random()<.5?1:-1,h=Math.max(a,100+180*Math.random()),l=a<5?Math.random()*Math.PI*2:Math.atan2(r,n);t.gestureData.orbit={radius:h,targetRadius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,direction:o}},apply(t,e,i,s,n,r){t.gestureData?.orbit||this.initialize(t,i,n,r);const a=t.gestureData.orbit,o=(i.speed||this.config.speed)*(i.strength||1);a.angle+=o*s*a.direction;let{radius:h}=a;if(i.maintainRadius||(h=a.radius*(1+.1*Math.sin(e*Math.PI*2))),t.x=n+Math.cos(a.angle)*h,t.y=r+Math.sin(a.angle)*h,!1!==i.use3D){const e=a.angle+a.zPhase+(i.zPhaseOffset||0);if(t.z=.8*Math.sin(e),i.verticalOscillation){const s=Math.cos(e)*i.verticalOscillation*h*.1;t.y+=s}}if(t.vx=-Math.sin(a.angle)*h*o,t.vy=Math.cos(a.angle)*h*o,e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.orbit){const e=t.gestureData.orbit;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.orbit}},"3d":{evaluate(t,e){const i=e?.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;t<.15?n=Math.sin(t/.15*Math.PI*.5):t>.85&&(n=Math.sin((1-t)/.15*Math.PI*.5));const r=s.initialAngle+t*Math.PI*2*s.direction,a=.3*Math.cos(r)*n,o=.3*Math.sin(r)*n,h=(r+Math.PI/2-(s.initialAngle+Math.PI/2))*n,l=i.z||0;return{position:[a,0,o+.1*l*n],rotation:[0,h,0],scale:1+.15*l*n}}}};function ut(t){const e=P[t];if(!e)throw new Error(`Invalid orbit direction: ${t}`);const i="up"===t||"down"===t,s="left"===t||"up"===t?1:-1;return{name:`orbit${D(t)}`,emoji:"left"===t?"๐":"right"===t?"๐":"up"===t?"๐":"๐ซ",type:"override",description:`Orbit ${"left"===t?"counter-clockwise":"right"===t?"clockwise":t}`,config:{duration:1500,musicalDuration:{musical:!0,beats:4},speed:.02,maintainRadius:!0,use3D:!0,rotations:1,strength:1,direction:t,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(t,e,i,n){t.gestureData||(t.gestureData={});const r=t.x-i,a=t.y-n,o=Math.sqrt(r*r+a*a),h=Math.max(o,80+100*Math.random()),l=o<5?Math.random()*Math.PI*2:Math.atan2(a,r);t.gestureData.orbit={radius:h,targetRadius:h,angle:l,initialAngle:l,originalVx:t.vx,originalVy:t.vy,originalZ:t.z||0,zPhase:Math.random()*Math.PI*2,direction:s,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.orbit?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.orbit,l={...this.config,...n},c=n.strength||1,u=(l.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)),h.angle+=u*r*h.direction*d;let{radius:p}=h;l.maintainRadius||(p=h.radius*(1+.1*Math.sin(s*Math.PI*2)));const m=p*d+(1-d)*h.radius*.5;if(t.x=a+Math.cos(h.angle)*m,t.y=o+Math.sin(h.angle)*m,!1!==l.use3D){const n=h.angle+h.zPhase;if(t.z=.8*Math.sin(n)*d,i&&l.verticalOscillation){const i=e.y*s*l.verticalOscillation*p*.5;t.y+=i}}if(t.vx=-Math.sin(h.angle)*m*u*d,t.vy=Math.cos(h.angle)*m*u*d,s>.9){const e=10*(1-s);t.vx=t.vx*e+h.originalVx*(1-e),t.vy=t.vy*e+h.originalVy*(1-e)}},cleanup(t){if(t.gestureData?.orbit){const e=t.gestureData.orbit;t.vx=e.originalVx,t.vy=e.originalVy,t.z=e.originalZ,delete t.gestureData.orbit}},"3d":{evaluate(t,n){const r=n.config||n||{},a=n.strength||1,o=r.rotations||1;let h=1;t<.15?h=Math.sin(t/.15*Math.PI*.5):t>.85&&(h=Math.sin((1-t)/.15*Math.PI*.5));const l=.25*a,c=t*Math.PI*2*o*s,u=Math.cos(c)*l*h,d=Math.sin(c)*l*h;let p=0;return i&&(p=e.y*t*.2*a*h),{cameraRelativePosition:[u,p,d],rotation:[0,c*h*.5,0],scale:1+.2*d}}}}}var dt=ut("left"),pt=ut("right"),mt=ut("up"),gt=ut("down"),ft={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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.jump={startX:t.x,startY:t.y,startSize:t.size,originalVx:t.vx,originalVy:t.vy,driftDirection:.1*(t.x-i),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.jump?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.jump,o={...this.config,...i},h=i.strength||1,l=o.jumpHeight*h*t.scaleFactor,c=o.squashAmount,u=o.stretchAmount,d=o.anticipation,p=1-.5*o.anticipation;if(e<d){const i=e/d,s=this.easeOutQuad(i);t.size=a.startSize*(1-(1-c)*s),t.y=a.startY+5*s*t.scaleFactor,t.vx=0,t.vy=0}else if(e<p){const i=(e-d)/(p-d);let s=Math.sin(i*Math.PI);if(o.hangTime>0&&i>.4&&i<.6){const t=(i-.4)/.2;s=.95+.05*this.easeInOutCubic(t)}if(t.y=a.startY-s*l,o.driftOutward&&(t.x=a.startX+s*a.driftDirection),i<.5){const e=2*i;t.size=a.startSize*(c+(u-c)*e)}else{const e=2*(i-.5);t.size=a.startSize*(u-(u-1)*e*.8)}t.vx=.5*a.driftDirection,t.vy=-Math.cos(i*Math.PI)*l*.1}else{const i=(e-p)/(1-p),s=this.easeOutBounce(i);if(t.y=a.startY,o.landingImpact)if(i<.3){const e=i/.3;t.size=a.startSize*(1-(1-.8*c)*(1-e))}else{const e=(i-.3)/.7;t.size=a.startSize*(.8*c+(1-.8*c)*e)}else t.size=a.startSize*(c+(1-c)*s);t.vx=a.originalVx*s,t.vy=a.originalVy*s}},cleanup(t){if(t.gestureData?.jump){const e=t.gestureData.jump;t.size=e.startSize,t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.jump}},easeOutQuad:t=>t*(2-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},"3d":{evaluate(t,e){const i=e.config||e||{},s=e.strength||1,n=.004*(i.jumpHeight||60)*s,r=i.squashAmount||.8,a=i.stretchAmount||1.2,o=i.anticipation||.2,h=1-.5*o;let l=0,c=1,u=0;if(t<o){const e=t/o,i=e*(2-e);c=1-(1-r)*i,l=.02*-i}else if(t<h){const e=(t-o)/(h-o);l=Math.sin(e*Math.PI)*n,c=e<.5?r+2*e*(a-r):a-2*(e-.5)*(a-1)*.8,u=.05*Math.sin(e*Math.PI)}else{const e=(t-h)/(1-h);if(e<.5){const t=2*e;l=-Math.sin(t*Math.PI)*n*.15}else l=0;c=!1!==i.landingImpact?e<.3?1-(1-.8*r)*(1-e/.3):.8*r+(e-.3)/.7*(1-.8*r):r+(1-r)*e}return{position:[0,l,0],rotation:[u,0,0],scale:c}}}};function yt(t){const e=P[t];if(!e)throw new Error(`Invalid jump direction: ${t}`);const i="up"===t||"down"===t;return{name:`jump${D(t)}`,emoji:"up"===t?"๐ฆ":"down"===t?"๐ฅ":"left"===t?"โฌ
๏ธ":"โก๏ธ",type:"override",description:`Jump ${t} 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:t,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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.jump={startX:t.x,startY:t.y,startSize:t.size,originalVx:t.vx,originalVy:t.vy,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.jump?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.jump,l={...this.config,...n},c=n.strength||1,u=l.jumpDistance*c*t.scaleFactor,d=l.squashAmount,p=l.stretchAmount,m=l.anticipation,g=1-.5*l.anticipation;if(s<m){const n=s/m,r=this.easeOutQuad(n);t.size=h.startSize*(1-(1-d)*r),i?t.y=h.startY-e.y*r*5*t.scaleFactor:t.x=h.startX-e.x*r*5*t.scaleFactor,t.vx=0,t.vy=0}else if(s<g){const n=(s-m)/(g-m);let r=Math.sin(n*Math.PI);if(l.hangTime>0&&n>.4&&n<.6){const t=(n-.4)/.2;r=.95+.05*this.easeInOutCubic(t)}if(i?(t.y=h.startY+e.y*r*u,t.x=h.startX+3*Math.sin(n*Math.PI*2)):(t.x=h.startX+e.x*r*u,t.y=h.startY-Math.sin(n*Math.PI)*u*.3),n<.5){const e=2*n;t.size=h.startSize*(d+(p-d)*e)}else{const e=2*(n-.5);t.size=h.startSize*(p-(p-1)*e*.8)}i?(t.vy=e.y*Math.cos(n*Math.PI)*u*.1,t.vx=0):(t.vx=e.x*Math.cos(n*Math.PI)*u*.1,t.vy=-Math.cos(n*Math.PI)*u*.05)}else{const e=(s-g)/(1-g),i=this.easeOutBounce(e);if(t.x=h.startX,t.y=h.startY,l.landingImpact)if(e<.3){const i=e/.3;t.size=h.startSize*(1-(1-.8*d)*(1-i))}else{const i=(e-.3)/.7;t.size=h.startSize*(.8*d+(1-.8*d)*i)}else t.size=h.startSize*(d+(1-d)*i);t.vx=h.originalVx*i,t.vy=h.originalVy*i}},cleanup(t){if(t.gestureData?.jump){const e=t.gestureData.jump;t.size=e.startSize,t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.jump}},easeOutQuad:t=>t*(2-t),easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},"3d":{evaluate(t,s){const n=s.config||s||{},r=s.strength||1,a=.004*(n.jumpDistance||60)*r,o=n.squashAmount||.8,h=n.stretchAmount||1.2,l=n.anticipation||.2,c=1-.5*l;let u=0,d=0,p=1,m=0,g=0,f=0;if(t<l){const s=t/l,n=s*(2-s);p=1-(1-o)*n,i?d=-e.y*n*.02:u=-e.x*n*.02}else if(t<c){const s=(t-l)/(c-l),n=Math.sin(s*Math.PI);i?d=e.y*n*a:(u=e.x*n*a,d=Math.sin(s*Math.PI)*a*.3),p=s<.5?o+2*s*(h-o):h-2*(s-.5)*(h-1)*.8,i?m=e.y*Math.sin(s*Math.PI)*.1:(g=e.x*Math.sin(s*Math.PI)*.15,f=-e.x*Math.sin(s*Math.PI)*.05)}else{const s=(t-c)/(1-c);if(s<.5){const t=2*s;i?d=-e.y*Math.sin(t*Math.PI)*a*.15:u=-e.x*Math.sin(t*Math.PI)*a*.1}p=!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,g,f],scale:p}}}}}var Mt=yt("down"),bt=yt("left"),wt=yt("right");function vt(t){if(!["forward","back","left","right","up","down"].includes(t))throw new Error(`Invalid rush direction: ${t}`);return{name:`rush${D(t)}`,emoji:{forward:"๐จ",back:"๐",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ"}[t],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"}[t],config:{duration:600,musicalDuration:{musical:!0,beats:1.5},strength:1,direction:t,particleMotion:{type:"rush",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.4}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"forward";let r=0,a=0,o=0,h=0,l=0,c=1,u=1,d=0;const p={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(t<.2){const e=t/.2,i=1-Math.pow(1-e,2);h=i*p.lean.x*s,l=i*p.lean.z*s,a="up"===n?.03*-i*s:.02*-i*s,u=1+.3*i}else if(t<.6){const e=(t-.2)/.4,i=1-Math.pow(1-e,3);r=p.x*i*m*s,a=p.y*i*m*s,o=p.z*i*m*s,"up"===n?a+=.05*i*s:"down"!==n&&(a+=(.04*i-.02)*s),h=p.lean.x*s,l=p.lean.z*s,c=1+.08*i,u=1.3+.5*i,d=.35*i,l+=Math.sin(e*Math.PI*12)*(1-e)*.015*s}else{const e=(t-.6)/.4,i=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;if(r=p.x*m*(1-i)*s,a=p.y*m*(1-i)*s,o=p.z*m*(1-i)*s,h=p.lean.x*(1-i)*s,l=p.lean.z*(1-i)*s,c=1.08-.08*i,e>.7){const t=(e-.7)/.3;a-=.02*Math.sin(t*Math.PI)*s}u=1.8-.8*i,d=.35*(1-i)}return{cameraRelativePosition:[r,a,o],cameraRelativeRotation:[h,0,l],scale:c,glowIntensity:u,glowBoost:d}}}}}var St={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.25,r=!1!==i.recover;let a;t<.3?(a=t/.3,a=1-Math.pow(1-a,3)):t<.6?a=1:r?(a=1-(t-.6)/.4,a=Math.pow(a,2)):a=1;const o=a*n*s;return{position:[0,.05*-Math.sin(a*Math.PI)*s,o],rotation:[.2*a*s,0,0],scale:1+.1*a*s,glowIntensity:1+.3*a,glowBoost:t<.4?.4*a:0}}}};function kt(t){if(!{...P,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[t])throw new Error(`Invalid lunge direction: ${t}`);return{name:`lunge${D(t)}`,emoji:{forward:"๐คบ",back:"๐",left:"๐",right:"๐",up:"โ๏ธ",down:"๐"}[t]||"๐คบ",type:"override",description:`Lunge thrust ${t}`,config:{duration:500,musicalDuration:{musical:!0,beats:1},distance:.25,recover:!0,strength:1,direction:t,particleMotion:{type:"lunge",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.25,r=!1!==i.recover,a=i.direction||"forward";let o;t<.3?(o=t/.3,o=1-Math.pow(1-o,3)):t<.6?o=1:r?(o=1-(t-.6)/.4,o=Math.pow(o,2)):o=1;let h=0,l=0,c=0,u=0,d=0;switch(a){case"forward":c=o*n*s,u=.2*o*s,l=.05*-Math.sin(o*Math.PI)*s;break;case"back":c=-o*n*s,u=.2*-o*s,l=.05*-Math.sin(o*Math.PI)*s;break;case"left":h=-o*n*s,d=.2*-o*s,l=.03*-Math.sin(o*Math.PI)*s;break;case"right":h=o*n*s,d=.2*o*s,l=.03*-Math.sin(o*Math.PI)*s;break;case"up":l=o*n*s,u=.15*-o*s;break;case"down":l=-o*n*s,u=.25*o*s}return{cameraRelativePosition:[h,l,c],cameraRelativeRotation:[u,0,d],scale:1+.1*o*s,glowIntensity:1+.3*o,glowBoost:t<.4?.4*o:0}}}}}var xt={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;let a=e.direction||this.config.direction;"random"===a&&(a=Math.random()<.5?"clockwise":"counter-clockwise"),t.gestureData.spin={startAngle:Math.atan2(r,n),startRadius:Math.sqrt(n*n+r*r)||30,originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,direction:a,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.spin?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.spin,o={...this.config,...i},h=i.strength||1;let{rotations:l}=o,{radiusMultiplier:c}=o;i.rhythmModulation&&(i.rhythmModulation.rotationMultiplier&&(l*=i.rhythmModulation.rotationMultiplier),i.rhythmModulation.radiusMultiplier&&(c*=i.rhythmModulation.radiusMultiplier));let u=e;o.accelerate&&(u=e<.5?.5*this.easeInQuad(2*e):.5+.5*this.easeOutQuad(2*(e-.5)));const d=l*Math.PI*2*h,p="counter-clockwise"===a.direction?-1:1,m=a.startAngle+d*u*p;let g=a.startRadius;o.spiralOut&&(g*=1+.5*e),1!==c&&(g*=1+(c-1)*Math.sin(e*Math.PI));const f=n+Math.cos(m)*g,y=r+Math.sin(m)*g;if(t.x+=.25*(f-t.x),t.y+=.25*(y-t.y),t.vx=.5*(f-t.x),t.vy=.5*(y-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.spin){const e=t.gestureData.spin;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.spin}},easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const i=e?.config||e||{},s=e?.strength||1,n=e?.particle;let r=1;n?.gestureData?.spin?r="counter-clockwise"===n.gestureData.spin.direction?-1:1:"counter-clockwise"!==i.direction&&"left"!==i.direction||(r=-1);let a=t;return!1!==i.accelerate&&(a=t<.5?t*t*4*.5:.5+(t-.5)*(2-(t-.5))*.5),{position:[0,0,0],rotation:[0,(i.rotations||1)*Math.PI*2*s*a*r,0],scale:1+(i.scaleAmount||.1)*Math.sin(t*Math.PI)*s}}}};const Et={left:"counter-clockwise",right:"clockwise"};function Bt(t){const e=Et[t];if(!e)throw new Error(`Invalid spin direction: ${t}`);const i="left"===t?-1:1;return{name:`spin${D(t)}`,emoji:"left"===t?"โบ":"โป",type:"override",description:`Spin ${e}`,config:{duration:600,rotations:1,direction:e,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(t,i,s,n){t.gestureData||(t.gestureData={});const r=t.x-s,a=t.y-n;t.gestureData.spin={startAngle:Math.atan2(a,r),startRadius:Math.sqrt(r*r+a*a)||30,originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,direction:e,initialized:!0}},apply(t,e,s,n,r,a){t.gestureData?.spin?.initialized||this.initialize(t,s,r,a);const o=t.gestureData.spin,h={...this.config,...s},l=s.strength||1;let{rotations:c,radiusMultiplier:u}=h;s.rhythmModulation&&(s.rhythmModulation.rotationMultiplier&&(c*=s.rhythmModulation.rotationMultiplier),s.rhythmModulation.radiusMultiplier&&(u*=s.rhythmModulation.radiusMultiplier));let d=e;h.accelerate&&(d=e<.5?.5*this.easeInQuad(2*e):.5+.5*this.easeOutQuad(2*(e-.5)));const p=c*Math.PI*2*l,m=o.startAngle+p*d*i;let g=o.startRadius;h.spiralOut&&(g*=1+.5*e),1!==u&&(g*=1+(u-1)*Math.sin(e*Math.PI));const f=r+Math.cos(m)*g,y=a+Math.sin(m)*g;if(t.x+=.25*(f-t.x),t.y+=.25*(y-t.y),t.vx=.5*(f-t.x),t.vy=.5*(y-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+o.originalVx*(1-i),t.vy=t.vy*i+o.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.spin){const e=t.gestureData.spin;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.spin}},easeInQuad:t=>t*t,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const s=e?.config||e||{},n=e?.strength||1;let r=t;return!1!==s.accelerate&&(r=t<.5?t*t*4*.5:.5+(t-.5)*(2-(t-.5))*.5),{position:[0,0,0],rotation:[0,(s.rotations||1)*Math.PI*2*n*r*i,0],scale:1+(s.scaleAmount||.1)*Math.sin(t*Math.PI)*n}}}}}var At=Bt("left"),Ct=Bt("right"),Tt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotations||1,r=i.height||.3,a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*(2*-Math.PI*n),o=Math.sin(t*Math.PI)*r*s;let h=1;if(t<.1)h=1-t/.1*.15;else if(t<.2)h=.85+(t-.1)/.1*.2;else if(t>.9){const e=(t-.9)/.1;h=1.05-.1*Math.sin(e*Math.PI)}else h=1.05;return t>=.99&&(h=1),{position:[0,o,0],rotation:[a,0,0],scale:h,glowIntensity:1+.4*Math.sin(t*Math.PI),glowBoost:t>.2&&t<.8?.3:0}}}},Pt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotations||1,r=i.height||.35,a=(t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2)*(2*Math.PI*n),o=Math.sin(t*Math.PI)*r*s,h=.1*Math.sin(t*Math.PI)*s;let l=1;if(t<.1)l=1-t/.1*.15;else if(t<.2)l=.85+(t-.1)/.1*.25;else if(t>.9){const e=(t-.9)/.1;l=1.1-.15*Math.sin(e*Math.PI)}else l=1.1;return t>=.99&&(l=1),{position:[0,o,h],rotation:[a,0,0],scale:l,glowIntensity:1+.5*Math.sin(t*Math.PI),glowBoost:.4*Math.sin(t*Math.PI)}}}},Dt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.point={startX:t.x,startY:t.y,startVx:t.vx,startVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.point?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=this.easeInOutCubic(e);let l=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1);const c=Math.sin(h*Math.PI);let u=0,d=0;switch(a.direction||"right"){case"right":u=1;break;case"left":u=-1;break;case"up":d=-1;break;case"down":d=1}if(t.vx+=c*l*.02*s*u,t.vy+=c*l*.02*s*d,e>.9){const i=1-10*(e-.9);t.vx=t.vx*(.95+.05*i),t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.point&&delete t.gestureData.point},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||15,n=i.strength||.8,r=i.direction||"right",a=.005*s*n,o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI);let l=0,c=0;switch(r){case"right":l=h*a,c=.25*h;break;case"left":l=-h*a,c=.25*-h;break;case"up":case"down":c=0}return{position:[l,0,0],rotation:[0,c,0],scale:1}}}};function Rt(t){const e=P[t];if(!e)throw new Error(`Invalid point direction: ${t}`);const i="up"===t||"down"===t;return{name:`point${D(t)}`,emoji:"up"===t?"โ๏ธ":"down"===t?"๐":"left"===t?"๐":"๐",type:"blending",description:`Point ${t} with extension and return`,config:{duration:500,amplitude:15,strength:.8,direction:t},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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.point={startX:t.x,startY:t.y,initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.point?.initialized||this.initialize(t,s);const o={...this.config,...s},h=o.strength||.8,l=this.easeInOutCubic(i);let c=o.amplitude*h*t.scaleFactor;s.rhythmModulation&&(c*=s.rhythmModulation.amplitudeMultiplier||1,c*=s.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI);if(t.vx+=u*c*.02*n*e.x,t.vy+=u*c*.02*n*-e.y,i>.9){const e=1-10*(i-.9);t.vx*=.95+.05*e,t.vy*=.95+.05*e}},cleanup(t){t.gestureData?.point&&delete t.gestureData.point},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,s){const n=s||{},r=.005*(n.amplitude||15)*(n.strength||.8),a=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,o=Math.sin(a*Math.PI),h=e.x*o*r,l=e.y*o*r;let c=0,u=0,d=0;return i?c=e.y*o*.2:(u=e.x*o*.25,d=-e.x*o*.1),{cameraRelativePosition:[h,l,0],rotation:[c,u,d],scale:1}}}}}var Ft=Rt("up"),zt=Rt("down"),qt=Rt("left"),Ot=Rt("right");function jt(t){if("left"!==t&&"right"!==t)throw new Error(`Invalid kick direction: ${t}. Only 'left' and 'right' are supported.`);const e=P[t];return{name:`kick${D(t)}`,emoji:"left"===t?"๐ฆต":"๐ฆถ",type:"blending",description:`Quick kick ${t} with snap return`,config:{duration:400,amplitude:30,strength:.8,direction:t},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(t,i,s,n,r,a){const o={...this.config,...s};let h,l=o.amplitude*o.strength*t.scaleFactor;s.rhythmModulation&&(l*=s.rhythmModulation.amplitudeMultiplier||1,l*=s.rhythmModulation.accentMultiplier||1),h=i<.25?this.easeOutQuad(i/.25):i<.5?1:1-this.easeInQuad((i-.5)/.5);const c=e.x*l*h*.012*n,u=e.y*l*h*.012*n;t.vx+=c,t.vy+=u},cleanup(t){},easeOutQuad:t=>1-(1-t)*(1-t),easeInQuad:t=>t*t,"3d":{evaluate(t,i){const s=i||{},n=s.amplitude||30,r=s.strength||.8;let a,o=.008*n*r;if(i.rhythmModulation&&(o*=i.rhythmModulation.amplitudeMultiplier||1),t<.25)a=1-(1-t/.25)*(1-t/.25);else if(t<.5)a=1;else{const e=(t-.5)/.5;a=1-e*e}const h=.15*a*r;return{cameraRelativePosition:[e.x*o*a,e.y*o*a*.3,0],rotation:[.08*a*r,0,e.x*h],scale:1+.05*a}}}}}var It=jt("left"),$t=jt("right"),Lt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.depth||.4,r=i.holdTime||.4;let a;const o=.4*(1-r),h=1-.6*(1-r);return t<o?(a=t/o,a=Math.sin(a*Math.PI/2)):t<h?a=1:(a=1-(t-h)/(1-h),a=Math.sin(a*Math.PI/2)),{cameraRelativePosition:[0,.1*-a*s,.05*-a*s],cameraRelativeRotation:[a*n*Math.PI*s,0,0],scale:1,glowIntensity:1-.2*a,glowBoost:0}}}},Gt={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.nod={startY:t.y,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.nod?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1;let{frequency:h}=a,{amplitude:l}=a;i.rhythmModulation&&(l*=i.rhythmModulation.amplitudeMultiplier||1,l*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(h*=i.rhythmModulation.frequencyMultiplier));const c=Math.sin(e*Math.PI*2*h);l=l*o*t.scaleFactor,t.vy+=c*l*.01*s,e>.9&&(t.vy*=.95)},cleanup(t){t.gestureData?.nod&&delete t.gestureData.nod},"3d":{evaluate(t,e){const i={...this.config,...e};let{amplitude:s}=i;e.rhythmModulation&&(s*=e.rhythmModulation.amplitudeMultiplier||1,s*=e.rhythmModulation.accentMultiplier||1);let n=0;if(t<.4){const e=t/.4;n=.12*Math.sin(e*Math.PI)}else if(t<.8){const e=(t-.4)/.4;n=.07*Math.sin(e*Math.PI)}return n*=s/15,{cameraRelativePosition:[0,0,n],scale:1-.3*Math.abs(n),glowIntensity:1+.5*Math.abs(n)}}}},_t={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.reach={startY:t.y,startVy:t.vy,originalSize:t.size,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.reach?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||this.config.strength||1,h=a.scaleMax||this.config.scaleMax||1.05,l=this.easeInOutCubic(e);let c=a.amplitude*o*t.scaleFactor;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1);const u=Math.sin(l*Math.PI);t.vy-=u*c*.015*s;const d=1+u*(h-1);if(t.size=t.baseSize*d,e>.9){const i=1-10*(e-.9);t.vy=t.vy*(.95+.05*i)}},cleanup(t){t.gestureData?.reach&&(t.gestureData.reach.originalSize?t.size=t.gestureData.reach.originalSize:t.size=t.baseSize,delete t.gestureData.reach)},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e||{},s=i.amplitude||25,n=i.strength||.9,r=i.scaleMax||1.05,a=.004*s*n,o=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,h=Math.sin(o*Math.PI);return{position:[0,h*a,0],rotation:[.1*h,0,0],scale:1+h*(r-1)}}}},Ht={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(t,e,i,s,n,r,a){const o=(i.amplitude||this.config.amplitude)*n,h=i.frequency||this.config.frequency,l=1-s*(i.damping||this.config.damping),c=Math.sin(s*Math.PI*2*h)*o*l;t.vy+=.5*c;const u=Math.cos(s*Math.PI*2*h*1.5)*o*.05*l;t.vx+=.2*u},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.amplitude||12,r=t<.15?t/.15:Math.pow(1-(t-.15)/.85,2),a=n/12*s;return{cameraRelativePosition:[0,0,.08*r*a],position:[0,.015*-r*a,0],scale:1-.05*r,glowIntensity:1+.15*r}}}},Ut={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.depth||.3,r=i.widen||.2;let a;const o=(1-(i.holdTime||.5))/2,h=1-o;return a=t<o?t/o:t<h?1:1-(t-h)/o,a=Math.sin(a*Math.PI/2),{position:[0,-a*n*s,0],rotation:[.15*a*s,0,0],scale:(1+a*r*s+(1-.25*a*s))/2,glowIntensity:1-.3*a,glowBoost:0}}}},Wt={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=Math.random(),l=({...this.config,...e}.homeRadius+20*Math.random())*t.scaleFactor;t.gestureData.tilt={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,angle:a,distance:o,homeRadius:l,homeX:i+Math.cos(a)*l,homeY:s+Math.sin(a)*l,role:h,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.tilt?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.tilt,o={...this.config,...i},h=i.strength||1;let l,c;if(e<o.gatherPhase){const i=e/o.gatherPhase,s=this.easeInOutCubic(i);l=a.startX+(a.homeX-a.startX)*s,c=a.startY+(a.homeY-a.startY)*s;const n=.6;t.x+=(l-t.x)*n,t.y+=(c-t.y)*n}else{const i=(e-o.gatherPhase)/(1-o.gatherPhase)*Math.PI*o.frequency,s=Math.sin(i),u=o.tiltAngle*Math.PI/180*h,d=a.angle+s*u,p=Math.abs(s)*o.liftAmount*t.scaleFactor,m=a.homeRadius+p;l=n+Math.cos(d)*m,c=r+Math.sin(d)*m-.3*p;const g=o.smoothness+.1*a.role;t.x+=(l-t.x)*g,t.y+=(c-t.y)*g;const f=-Math.sin(d),y=Math.cos(d);t.vx=f*s*2,t.vy=y*s*2}if(e<o.gatherPhase&&(t.vx=.25*(l-t.x),t.vy=.25*(c-t.y)),e>.9){const i=10*(1-e),s=a.startX+(t.x-a.startX)*i,n=a.startY+(t.y-a.startY)*i;t.x=s,t.y=n,t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.tilt){const e=t.gestureData.tilt;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.tilt}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||1,n=i.gatherPhase||.2,r=i.frequency||3,a=i.tiltAngle||45;let o=0;if(t>=n){const e=(t-n)/(1-n)*Math.PI*r;o=Math.sin(e)*(a*Math.PI/180*s*.4)}return{position:[0,0,0],rotation:[0,0,o],scale:1}}}};function Yt(t){const e=P[t];if(!e)throw new Error(`Invalid tilt direction: ${t}`);const i="up"===t||"down"===t;return{name:`tilt${D(t)}`,emoji:"up"===t?"๐ญ":"down"===t?"๐":"left"===t?"๐ค":"๐ง",type:"override",description:`Tilt ${t} 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:t,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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=({...this.config,...e}.homeRadius+20*Math.random())*t.scaleFactor;t.gestureData.tilt={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,angle:a,distance:o,homeRadius:h,homeX:i+Math.cos(a)*h,homeY:s+Math.sin(a)*h,role:Math.random(),initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.tilt?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.tilt,l={...this.config,...n},c=n.strength||1;let u,d;if(s<l.gatherPhase){const e=s/l.gatherPhase,i=this.easeInOutCubic(e);u=h.startX+(h.homeX-h.startX)*i,d=h.startY+(h.homeY-h.startY)*i;const n=.6;t.x+=(u-t.x)*n,t.y+=(d-t.y)*n}else if(s<l.gatherPhase+l.holdPhase){const n=(s-l.gatherPhase)/l.holdPhase,r=this.easeOutCubic(Math.min(2*n,1)),a=l.tiltAmount*c*t.scaleFactor*r;i?(u=h.homeX,d=h.homeY+e.y*a):(u=h.homeX+e.x*a,d=h.homeY-Math.abs(e.x)*a*.2);const o=l.smoothness+.1*h.role;t.x+=(u-t.x)*o,t.y+=(d-t.y)*o,t.vx=.5*(u-t.x),t.vy=.5*(d-t.y)}else{const e=(s-l.gatherPhase-l.holdPhase)/(1-l.gatherPhase-l.holdPhase),i=this.easeInOutCubic(e);u=t.x+(h.startX-t.x)*i,d=t.y+(h.startY-t.y)*i,t.x=u,t.y=d,t.vx=h.originalVx*i,t.vy=h.originalVy*i}s<l.gatherPhase&&(t.vx=.25*(u-t.x),t.vy=.25*(d-t.y))},cleanup(t){if(t.gestureData?.tilt){const e=t.gestureData.tilt;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.tilt}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutCubic:t=>1-Math.pow(1-t,3),"3d":{evaluate(t,s){const n=s.config||s||{},r=s.strength||1,a=n.gatherPhase||.2,o=n.holdPhase||.4,h=n.tiltAngle||45,l=n.tiltAmount||40;let c=0,u=0,d=0,p=0,m=0;if(t<a);else if(t<a+o){const s=(t-a)/o,n=1-Math.pow(1-Math.min(2*s,1),3),g=h*Math.PI/180*r*.4*n,f=.004*l*r*n;i?(d=e.y*g,u=e.y*f):(m=-e.x*g,c=e.x*f*.5,p=e.x*g*.3)}else{const s=(t-a-o)/(1-a-o),n=s<.5?4*s*s*s:1-Math.pow(-2*s+2,3)/2,g=h*Math.PI/180*r*.4*(1-n),f=.004*l*r*(1-n);i?(d=e.y*g,u=e.y*f):(m=-e.x*g,c=e.x*f*.5,p=e.x*g*.3)}return{cameraRelativePosition:[c,u,0],rotation:[d,p,m],scale:1}}}}}var Xt=Yt("up"),Vt=Yt("down"),Nt=Yt("left"),Qt=Yt("right");function Jt(t){if(!["left","right","front","back","up","down"].includes(t))throw new Error(`Invalid oof direction: ${t}`);return{name:`oof${D(t)}`,emoji:{left:"๐ค",right:"๐ค",front:"๐",back:"๐ซ",up:"๐ฅ",down:"๐ฅ"}[t],type:"override",description:{left:"Punched from left",right:"Punched from right",front:"Gut punch",back:"Kidney shot",up:"Uppercut",down:"Hammer fist"}[t],config:{duration:500,musicalDuration:{musical:!0,beats:1},intensity:1,strength:1,direction:t,particleMotion:{type:"oof",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.5}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1;let n,r;if(t<.25){const e=t/.25;n=e*(2-e)}else{const e=(t-.25)/.75;n=1-e*e}r=t<.1?t/.1:t<.4?1:1-(t-.4)/.6;const a=.2*s,o=.35*s;let h=0,l=0,c=0,u=0,d=0,p=[0,0,.4];switch(i.direction||"front"){case"left":h=-n*a,d=n*o,p=[.4,0,0];break;case"right":h=n*a,d=-n*o,p=[-.4,0,0];break;case"front":c=-n*a,l=.03*-n,u=n*o*.7,p=[0,0,.4];break;case"back":c=n*a,u=-n*o*.6,p=[0,0,-.4];break;case"up":l=n*a,u=-n*o*.4,p=[0,.8,0];break;case"down":l=-n*a,u=n*o*.3,p=[0,-.8,0]}let m=1,g=0;if(t<.15){const e=t/.15;m=1+.6*(1-e),g=.4*(1-e)}return{cameraRelativePosition:[h,l,c],cameraRelativeRotation:[u,0,d],scale:1,glowIntensity:m,glowBoost:g,deformation:{enabled:!0,strength:r*s*2,impactPoint:p,falloffRadius:.5}}}}}}var Kt={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.2,r=i.intensity||1,a=!1!==i.recover;let o;return t<.15?(o=t/.15,o=1-Math.pow(1-o,4)):t<.4?o=1:a?(o=1-(t-.4)/.6,o=Math.pow(o,.5)):o=1,{position:[0,.05*o*s,-o*n*s*r],rotation:[.25*-o*s*r,0,0],scale:1-.1*o*r,glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.5:0}}}};function Zt(t){if(!{...P,forward:{x:0,y:0,z:-1},back:{x:0,y:0,z:1}}[t])throw new Error(`Invalid recoil direction: ${t}`);return{name:`recoil${D(t)}`,emoji:{back:"๐ฑ",forward:"๐ต",left:"๐ฐ",right:"๐ฐ",up:"๐ฒ",down:"๐จ"}[t]||"๐ฑ",type:"override",description:`Recoil ${t} in shock`,config:{duration:600,musicalDuration:{musical:!0,beats:1.5},distance:.2,intensity:1,recover:!0,strength:1,direction:t,particleMotion:{type:"recoil",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:1.5},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.6}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.distance||.2,r=i.intensity||1,a=!1!==i.recover,o=i.direction||"back";let h;t<.15?(h=t/.15,h=1-Math.pow(1-h,4)):t<.4?h=1:a?(h=1-(t-.4)/.6,h=Math.pow(h,.5)):h=1;let l=0,c=0,u=0,d=0,p=0;switch(o){case"back":u=-h*n*s*r,d=.25*-h*s*r,c=.05*h*s;break;case"forward":u=h*n*s*r,d=.25*h*s*r,c=.05*-h*s;break;case"left":l=-h*n*s*r,p=.2*h*s*r;break;case"right":l=h*n*s*r,p=.2*-h*s*r;break;case"up":c=h*n*s*r,d=.1*-h*s*r;break;case"down":c=-h*n*s*r,d=.3*h*s*r}return{cameraRelativePosition:[l,c,u],cameraRelativeRotation:[d,0,p],scale:1-.1*h*r,glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.5:0}}}}}var te={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.15){const e=t/.15,s=1-Math.pow(1-e,2);n=.1*s*i,r=.2*-s*i,h=1+.6*s,l=.5*s}else if(t<.4){const e=(t-.15)/.25,n=e*e;s=.2*-n*i,r=(.6*n-.2)*i,a=.3*n*i,e>.7&&(o=1-(e-.7)/.3*.1),h=1.6-.5*e,l=.5-.4*e}else if(t<.6){const e=(t-.4)/.2;s=-.2*i,r=.4*i,a=.3*i,a+=.02*Math.sin(e*Math.PI*2),o=.9,h=.8}else{const e=(t-.6)/.4,n=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;if(s=(.2*n-.2)*i,r=(.4-.4*n)*i,a=(.3-.3*n)*i,o=.9+.1*n,e>.7){const t=(e-.7)/.3;a+=.03*Math.sin(t*Math.PI*4)*(1-t)}h=.8+.2*n,e>.9&&(l=(e-.9)/.1*.2)}return{position:[0,s,n],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},ee={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=0,h=1,l=1,c=0;if(t<.1){const e=t/.1,s=1-Math.pow(1-e,3);n=.15*s*i,r=.3*-s*i,l=1+.8*s,c=.6*s,o=.1*Math.sin(e*Math.PI*4)*s}else if(t<.25){const e=(t-.1)/.15,n=e*e;s=.25*-n*i,r=(.8*n-.3)*i,o=.4*n*i,e>.8&&(h=1-(e-.8)/.2*.15),l=1.8-.6*e,c=.6-.4*e}else if(t<.35){const e=(t-.25)/.1;s=-.25*i,r=.5*i,o=.4*i,o+=.03*Math.sin(e*Math.PI*6)*(1-e),h=.85,l=1-.3*e}else if(t<.45){const e=(t-.35)/.1,n=1-Math.pow(1-e,2);s=(.15*n-.25)*i,r=(.5-.3*n)*i,o=(.4-.2*n)*i,h=.85+.1*n,l=.7+.4*n}else if(t<.55){const e=(t-.45)/.1,n=e*e;s=(-.1-.15*n)*i,r=(.2+.35*n)*i,o=(.2+.25*n)*i,h=.95-.12*n,e>.7&&(c=(e-.7)/.3*.3),l=1.1-.4*e}else if(t<.75){const e=(t-.55)/.2;s=-.25*i,r=.55*i,o=.45*i,h=.83;const n=.02*Math.sin(e*Math.PI*4)*Math.sin(e*Math.PI);o+=n,l=.6+2*n}else if(t<.9){const e=(t-.75)/.15,n=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;s=(.25*n-.25)*i,r=(.55-.55*n)*i,o=(.45-.45*n)*i,h=.83+.17*n,l=.6+.5*n}else{const e=(t-.9)/.1;s=0,r=0,o=Math.sin(e*Math.PI*6)*(1-e)*.08*i,a=Math.sin(e*Math.PI*8)*(1-e)*.1*i,h=1,l=1+.2*Math.sin(e*Math.PI*3)*(1-e),c=.2*Math.sin(e*Math.PI)}return{position:[0,s,n],rotation:[r,a,o],scale:h,glowIntensity:l,glowBoost:c}}}},ie={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.maxScale||1.4,r=i.holdTime||.3,a=!1!==i.deflate;let o;const h=.5*(1-r),l=1-h;t<h?(o=t/h,o=1-Math.pow(1-o,2)):t<l||!a?o=1:(o=1-(t-l)/h,o=Math.pow(o,2));const c=1+(n-1)*o*s,u=.08*o*s,d=1+.4*o*s,p=.3*o,m=o>.8?.02*Math.sin(t*Math.PI*8):0;return{position:[m,u,0],rotation:[0,0,2*m],scale:c,glowIntensity:d,glowBoost:p}}}},se={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.minScale||.6,r=i.droop||.15,a=!1!==i.reinflate;let o;return t<.5?(o=t/.5,o=Math.pow(o,.7)):t<.7||!a?o=1:(o=1-(t-.7)/.3,o=Math.pow(o,1.5)),{position:[0,-o*r*s,0],rotation:[.15*o*s,0,.1*o*s],scale:1-(1-n)*o*s,glowIntensity:1-.4*o,glowBoost:0}}}},ne={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.squashAmount||.5,r=i.stretchAmount||1.5,a=!1!==i.bounce;let o;if(t<.15)o=t/.15,o=1-Math.pow(1-o,3);else if(a){const e=(t-.15)/.85,i=Math.exp(4*-e);o=Math.cos(e*Math.PI*3)*i,o=Math.max(0,o)}else o=0;const h=1+o*(r-1)*s;return{position:[0,.15*-o*s,0],rotation:[0,0,0],scale:[h,1-o*(1-n)*s,h],glowIntensity:1+(t<.2?3*(.2-t):0),glowBoost:t<.15?.6:0}}}},re={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;t.gestureData.stretch={offsetX:n,offsetY:r,startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.stretch?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.stretch,o={...this.config,...i},h=i.strength||1;let l,c,{scaleX:u}=o,{scaleY:d}=o;if(o.preserveArea&&1!==u&&1!==d){const t=u*d,e=Math.sqrt(1/t);u*=e,d*=e}if(o.alternate)if(e<.5){const t=2*e;u=1+(u-1)*this.getElasticProgress(t,o),d=1+(1/u-1)*(o.preserveArea?1:0)}else{const t=2*(e-.5);u+=(1-u)*this.getElasticProgress(t,o),d=1+(d-1)*this.getElasticProgress(t,o)}else{const t=this.getElasticProgress(e,o);u=1+(u-1)*t*h,d=1+(d-1)*t*h}if(o.centerBased?(l=n+a.offsetX*u,c=r+a.offsetY*d):(l=a.startX*u,c=a.startY*d),t.x=l,t.y=c,t.vx=a.offsetX*(u-1)*h*.1,t.vy=a.offsetY*(d-1)*h*.1,e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},getElasticProgress(t,e){if(!e.elastic)return this.easeInOutCubic(t);if(0===t)return 0;if(1===t)return 1;const i=e.overshoot||.1;if(t<.5){const e=2*t;return.5*this.easeInElastic(e,i)}{const e=2*(t-.5);return.5+.5*this.easeOutElastic(e,i)}},cleanup(t){if(t.gestureData?.stretch){const e=t.gestureData.stretch;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.stretch}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeInElastic:(t,e)=>0===t?0:1===t?1:-Math.pow(2,10*(t-1))*Math.sin((t-1-.075)*(2*Math.PI)/.3)*(1+e),easeOutElastic:(t,e)=>0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((t-.075)*(2*Math.PI)/.3)*(1+e)+1,"3d":{evaluate(t,e){const{particle:i}=e;if(!i||!i.gestureData?.stretch)return{position:[0,0,0],rotation:[0,0,0],scale:1};const s=e.config||{},n=e.strength||1;let r;if(s.elastic){const e=s.overshoot||.1;if(t<.5){const i=2*t,s=.3,n=s/4;r=-Math.pow(2,10*(i-1))*Math.sin((i-1-n)*(2*Math.PI)/s)*(1+e)*.5}else{const i=2*(t-.5),s=.3,n=s/4;r=.5+.5*(Math.pow(2,-10*i)*Math.sin((i-n)*(2*Math.PI)/s)*(1+e)+1)}}else r=t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;let a,o=1;if(t>.8){const e=(t-.8)/(1-.8);o=1-e*e*e}a=s.alternate?t<.5?2*t*.8:.8-2*(t-.5)*1.4:1*r*n;const h=1+a*o;return{position:[0,0,0],rotation:[0,0,.1*Math.sin(t*Math.PI*4)*r*o],scale:h}}}},ae={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.squashAmount||.2,r=i.stretchAmount||2,a=.1+.6*(i.holdRatio||.5);let o=0,h=0;if(t<.1){const e=t/.1;o=1-Math.pow(1-e,2)}else if(t<a){o=1;const e=(t-.1)/(a-.1);h=Math.sin(e*Math.PI*4)*(1-e)*.02}else{const e=(t-a)/(1-a);if(o=1-(e<.3?e/.3*.3:.3+(e-.3)/.7*.7),e>.8){const t=(e-.8)/.2,i=.15*Math.sin(t*Math.PI);o=Math.max(0,o-i)}}const l=1+o*(r-1)*s;let c=1,u=0;return t<.15?(c=1+.8*(1-t/.15),u=.6*(1-t/.15)):t<a?(c=1.3,u=.2):c=1.3-(t-a)/(1-a)*.3,{position:[h*s,.2*-o*s,0],rotation:[0,0,2*h*s],scale:[l,1-o*(1-n)*s,l],glowIntensity:c,glowBoost:u}}}},oe={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.2){const e=t/.2,o=e*e;n=.05*-o*i,r=.15*o*i;const l=Math.sin(80*t)*o*.02;a=l*i,s=.02*l*i,h=1+.3*o}else if(t<.6){const e=(t-.2)/.4,c=e*e;n=(-.05-.03*c)*i,r=(.15+.1*c)*i;const u=.02+.04*c,d=100+50*e,p=Math.sin(t*d)*u;a=p*i,s=.03*p*i,o=1+.1*c,h=1.3+.7*c,l=.5*c}else if(t<.8){const e=(t-.6)/.2;n=(.15*e-.08)*i,r=(.25-.4*e)*i,a=Math.sin(150*t)*(1-.5*e)*.05*i,o=1.1+.08*Math.sin(e*Math.PI),h=2-.3*e,l=.5+.3*Math.sin(e*Math.PI)}else{const e=(t-.8)/.2,s=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;n=(.07-.07*s)*i,r=(.15*s-.15)*i,a=Math.sin(50*t)*(1-s)*.02*i,o=1.1-.1*s,h=1.7-.7*s,l=.5*(1-s)}return{position:[s,n,0],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},he={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=1,o=1,h=0;if(t<.2){const e=t/.2,n=1-Math.pow(1-e,3);a=1+.15*n*i;const l=Math.sin(120*t)*n*.04;r=l*i,s=.02*l*i,o=1+1.2*n,h=.7*n}else if(t<.5){const e=(t-.2)/.3;a=1.15+.03*Math.sin(e*Math.PI*3);const l=.05*Math.sin(150*t)*(1-.3*e);r=l*i,s=.025*l*i,n=.1*Math.sin(e*Math.PI)*i,o=2.2-.3*e,h=.7-.2*e}else{const e=(t-.5)/.5,s=e*e;a=1.15-.15*s,r=Math.sin(80*t)*(1-s)*.03*i,n=.1*(1-s)*i,o=1.9-.9*s,h=.5*(1-s)}return{position:[s,0,0],rotation:[n,0,r],scale:a,glowIntensity:o,glowBoost:h}}}},le={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=1,h=1,l=0;if(t<.25){const e=t/.25,a=e*e;n=.08*a*i,r=.15*-a*i,s=.03*-a*i,o=1+.05*a,h=1+.4*a}else if(t<.4){const e=(t-.25)/.15;n=(.08+.02*e)*i,r=(-.15-.1*e)*i,s=(.05*e-.03)*i,o=1.05+.08*e,h=1.4+.5*e,l=.4*e}else if(t<.6){const e=(t-.4)/.2,c=1-Math.pow(1-e,3);n=(.1-.2*c)*i,r=(.4*c-.25)*i,s=(.02+.08*c)*i,o=1.13+.12*c,h=1.9+.6*c,l=.4+.4*c,a=Math.sin(e*Math.PI*20)*(1-e)*.02*i}else{const e=(t-.6)/.4,c=e<.5?2*e*e:1-Math.pow(-2*e+2,2)/2;n=-.1*(1-c)*i,r=.15*(1-c)*i,s=.1*(1-c)*i,o=1.25-.25*c,a=Math.sin(e*Math.PI*8)*(1-c)*.015*i,h=2.5-1.5*c,l=.8-.8*c}return{position:[0,s,n],rotation:[r,0,a],scale:o,glowIntensity:h,glowBoost:l}}}},ce={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(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=0,r=0,a=0,o=0,h=1,l=1,c=0;if(t<.2){const e=t/.2,s=e*e;n=.08*-s*i,r=.1*s*i,a=.25*s*i,h=1-.05*s,l=1+.4*s}else if(t<.6){const e=(t-.2)/.4,s=1-Math.pow(1-e,2);r=(.1-.35*s)*i,a=(.25+.1*s)*i,n=(.06*s-.08)*i,h=.95+.15*s,l=1.4+.6*s,c=.4*s,o=Math.sin(e*Math.PI*10)*s*.02*i}else if(t<.85){const e=(t-.6)/.25;r=-.25*i,a=(.35-.1*e)*i;const n=Math.sin(e*Math.PI*15)*(1-e)*.04;o=n*i,s=.02*n*i,h=1.1+.05*Math.sin(e*Math.PI),l=2-.3*e,c=.4*(1-.5*e)}else{const e=(t-.85)/.15,s=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2;r=-.25*(1-s)*i,a=.25*(1-s)*i,n=-.02*(1-s)*i,h=1.1-.1*s,l=1.7-.7*s,c=.2*(1-s)}return{cameraRelativePosition:[s,n,r],rotation:[a,0,o],scale:h,glowIntensity:l,glowBoost:c}}}},ue={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.wobbleRadius||.08,r=i.wobbleAngle||.2,a=i.rotations||2,o=i.decay||.5,h=t*a*Math.PI*2,l=1-o*t,c=Math.sin(h)*n*l*s,u=Math.cos(h)*n*l*s,d=Math.cos(h)*r*l*s,p=Math.sin(h)*r*l*s;return{position:[c,.02*Math.sin(2*h)*l*s,u],rotation:[d,0,p],scale:1+.05*Math.sin(2*h)*l,glowIntensity:1+.2*Math.sin(h)*l,glowBoost:0}}}},de={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.tiltAngle||.25,r=i.frequency||3,a=i.irregularity||.3,o=(Math.sin(t*r*Math.PI*2)+Math.sin(t*(r+1.7)*Math.PI*2)*a+Math.sin(t*(.5*r)*Math.PI*2)*a*.5)/(1+1.5*a),h=o*n*s*.7,l=Math.sin(t*r*Math.PI*2+.5)*n*s*.5;return{position:[.15*l,0,.1*h],rotation:[h,0,l],scale:1+.05*Math.abs(o),glowIntensity:1+.2*Math.abs(o),glowBoost:0}}}},pe={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rockAngle||.15,r=t*(i.rockCycles||2)*Math.PI*2,a=Math.sin(r),o=a*n*s,h=.05*a*s;return{position:[0,.02*Math.abs(a)*s,h],rotation:[o,0,0],scale:1+.02*Math.sin(.5*r),glowIntensity:1+.1*a,glowBoost:0}}}},me={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(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.swingAngle||.4,r=i.swings||2,a=i.damping||.3,o=t*r*Math.PI*2,h=1-a*t,l=Math.sin(o)*h,c=l*n*s;return{position:[.1*l*s,.03*-Math.abs(l)*s,0],rotation:[0,0,c],scale:1,glowIntensity:1+.15*Math.abs(l),glowBoost:0}}}};function ge(t){const e={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=e[t]||e.front;return{name:`crack${t.charAt(0).toUpperCase()+t.slice(1)}`,emoji:"๐",type:"override",category:"reactions",description:`Surface cracks spreading from ${t} impact`,config:{duration:2e3,strength:1,glowStrength:.3,holdTime:500},rhythm:{enabled:!0,syncMode:"accent",strengthSync:{onBeat:1.2,offBeat:.8}},"3d":{evaluate(t,e){const s={strength:1,glowStrength:.3,...e},{strength:n,glowStrength:r}=s,a=.03*Math.max(0,1-4*t)*n,{recoilDir:o}=i,h=t<.05;return{cameraRelativePosition:[o[0]*a,o[1]*a,o[2]*a],crack:{enabled:!0,trigger:h,amount:n,propagation:.8,screenOffset:i.screenOffset,screenDirection:i.screenDirection,glowStrength:r}}}}}}const fe=ge("front"),ye=ge("back"),Me=ge("left"),be=ge("right"),we=ge("up"),ve=ge("down"),Se={name:"crackHeal",emoji:"โจ",type:"override",category:"reactions",description:"Heal and fade existing cracks",config:{duration:1500,glowStrength:.5},"3d":{evaluate(t,e){const i={duration:1500,...e},s=t<.05;return{cameraRelativePosition:[0,.02*Math.sin(t*Math.PI),0],crack:{enabled:!1,heal:!0,healTrigger:s,healDuration:i.duration},glowBoost:.1*Math.sin(t*Math.PI)}}}};var ke={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=Math.random()*Math.PI*2,r=.5+.5*Math.random();t.gestureData.shatter={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,velocityX:Math.cos(n)*r,velocityY:Math.sin(n)*r,tumbleAngle:0,tumbleSpeed:4*(Math.random()-.5),frozenX:null,frozenY:null,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.shatter?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=a.distance||100,l=t.gestureData.shatter,c=a.explosionPhase||.3,u=a.freezePhase||.7;if(e<c){const i=e/c,s=1-Math.pow(1-i,3),n=l.velocityX*h*s*o,r=l.velocityY*h*s*o;t.x=l.originalX+n,t.y=l.originalY+r,l.tumbleAngle+=l.tumbleSpeed*(1-i)}else if(e<u){const i=(e-c)/(u-c),s=l.originalX+l.velocityX*h*o,n=l.originalY+l.velocityY*h*o,r=l.velocityX*h*.2*i*o,a=l.velocityY*h*.2*i*o;t.x=s+r,t.y=n+a,l.tumbleAngle+=.3*l.tumbleSpeed*(1-i),i>.95&&null===l.frozenX&&(l.frozenX=t.x,l.frozenY=t.y)}else if(null!==l.frozenX&&(t.x=l.frozenX,t.y=l.frozenY),e>.9){const i=(e-.9)/.1;t.opacity=l.originalOpacity*(1-.5*i)}},cleanup(t){if(t.gestureData?.shatter){const e=t.gestureData.shatter;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.shatter}},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1;let s=1,n=1,r=1,a=0,o=0,h=0,l=0,c=0,u=0,d=1,p=0;if(t<.1){const e=t/.1,a=1-Math.pow(1-e,2);n=1-.4*a*i,s=1+.2*a*i,r=1+.2*a*i,c=.1*-a*i,d=1+1*a,p=.8*a}else if(t<.4){const e=(t-.1)/.3,m=1-.6*e,g=40,f=Math.sin(t*g*Math.PI)*m,y=Math.cos(t*g*1.3*Math.PI)*m,M=Math.sin(t*g*.7*Math.PI)*m,b=1+.3*(1-Math.pow(1-e,2))*i;s=b+.15*f*i,n=b+.15*y*i,r=b+.15*M*i,a=.4*f*i,o=.5*y*i,h=.3*M*i,l=.15*f*i,c=.12*y*i+.1*e,u=.1*M*i,d=1.5+.5*Math.abs(f),p=.5*m}else if(t<.7){const e=(t-.4)/.3,a=e*e,o=1-a,l=20*o,u=Math.sin(t*l*Math.PI)*o,m=1.3-.4*a;s=m+.05*u*i,n=m+.05*u*i,r=m+.05*u*i,h=.15*u*i,c=.1*o,d=1.5-.3*a,p=.3*o}else{const e=(t-.7)/.3,i=e<.5?4*e*e*e:1-Math.pow(-2*e+2,3)/2,a=Math.sin(e*Math.PI*2)*(1-e)*.05;if(s=.9+.1*i+a,n=.9+.1*i+a,r=.9+.1*i+a,d=1.2-.2*i,t>.95){const e=(t-.95)/.05;p=.3*Math.sin(e*Math.PI)}}return{position:[l,c,u],rotation:[a,o,h],scale:[s,n,r],glowIntensity:d,glowBoost:p}}}};const xe={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 Ee(t="default"){const e=xe[t]||xe.default;return{name:e.name,emoji:e.emoji,type:"override",description:e.description,config:{duration:e.duration,musicalDuration:{musical:!0,beats:e.beats},intensity:e.intensity,variant:t},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:e.beats},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.3}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.intensity||1,n=i.variant||"default",r=xe[n]||xe.default,a=r.useDeformation||!1,o=r.direction||"front";let h=!1,l=!1,c=1,u=0,d=1,p=null,m=null,g=null;const f=r.reassemble,y=r.reassembleAt||.5;if(a){let e;if(t<.3){const i=t/.3;e=i*(2-i)}else e=0;let i=0;t<.25?i=t/.25:t<.3&&(i=1);const n=.15*s,a=.25*s;let l=0,d=0;const f=0;let y=0,M=0;switch(o){case"left":l=e*n,M=-e*a;break;case"right":l=-e*n,M=e*a;break;case"front":d=-e*n,y=e*a*.7}if(e>0&&(m=[l,f,d],g=[y,0,M]),i>0&&(p={enabled:!0,strength:i*s*2.5,impactPoint:r.impactPoint,falloffRadius:.5}),t>=.28&&t<.32&&(h=!0),t<.35){const e=t/.35;c=1+.8*(1-e),u=.5*(1-e)}}else{const e=void 0!==r.shatterTriggerAt?r.shatterTriggerAt:.1,i=e+.02;if(t<e){if(e>0){const i=t/e,s=i*i;c=1+.6*s,u=.3*s,d=1+.05*s,"explosive"===n&&(d+=.01*Math.sin(200*t)*i)}}else if(t<i)h=t>=e&&t<e+.005,c=1.6,u=.4,d=1.05;else{if(f&&t>=y&&t<y+.02&&(l=!0),f&&t>=y){const e=(t-y)/(1-y),i=e*e;c=1+.8*i,u=.5*i,t>.95&&(c=2,u=.8)}else{const e=(t-i)/(f?y-i:1-i),s=Math.min(1,e),n=1-(1-s)*(1-s);c=1.6-.6*n,u=.4-.4*n}d=1}}const M={scale:d,glowIntensity:c,glowBoost:u,shatter:{enabled:h,impactPoint:r.impactPoint,impactDirection:r.impactDirection||[0,0,-1],intensity:s*r.intensity,variant:n,reassemble:l,reassembleDuration:r.reassembleDuration||1e3,revealSoul:!1!==r.revealSoul,isSuspendMode:r.isSuspendMode||!1,suspendAt:r.suspendAt||.25,suspendDuration:r.suspendDuration||.35,isFreezeMode:r.isFreezeMode||!1,gravity:r.gravity,explosionForce:r.explosionForce,rotationForce:r.rotationForce,gestureDuration:r.duration,isDualMode:r.isDualMode||!1,dualModeType:r.dualModeType,dualModeConfig:{duration:r.dualModeDuration||2e3,impactPoint:r.impactPoint,windDirection:r.windDirection,windForce:r.windForce,turbulence:r.turbulence,waveSpeed:r.waveSpeed,floorY:r.floorY,orbitSpeed:r.orbitSpeed,radiusMultiplier:r.radiusMultiplier,reassemble:r.reassemble,reassembleDuration:r.reassembleDuration}}};return p&&(M.deformation=p),m&&(M.cameraRelativePosition=m),g&&(M.cameraRelativeRotation=g),M}}}}const Be={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 Ae(t="away"){const e=Be[t]||Be.away;return{name:e.name,emoji:e.emoji,type:"override",description:e.description,config:{duration:3500,musicalDuration:{musical:!0,beats:6},intensity:.7,direction:t},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:6},timingSync:"onBeat",accentResponse:{enabled:!0,multiplier:1.2}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.intensity||.7,n=i.direction||"away",r=Be[n]||Be.away;let a=!1,o=1,h=0,l=1;const c=.06;if(t<c){const e=t/c;o=1+.4*e,h=.2*e,l=1+.03*e}else if(t<.08)a=t>=c&&t<.065,o=1.4,h=.3;else{const e=(t-c)/.94;o=1.4-.6*e,h=Math.max(0,.3-.3*e)}return{scale:l,glowIntensity:o,glowBoost:h,shatter:{enabled:a,impactPoint:[0,0,0],impactDirection:r.impactDir||r.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:r.windDirection,windForce:r.windForce*s,turbulence:r.turbulence}}}}}}}var Ce={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(t,e,i,s,n){t.gestureData||(t.gestureData={});const r={...this.config,...e},a=t.x,o=t.y,h=Math.atan2(t.y-s,t.x-i),l=Math.random()<.5?1:-1;let c,u;const d=r.size*t.scaleFactor,p=(r.rotation||0)*Math.PI/180*l;switch(r.pattern){case"star":c=i,u=s,this.calculateStarPosition(t,h,d,r.points,r.innerRadius,p,i,s);break;case"heart":this.calculateHeartPosition(t,h,d,p,i,s);break;case"square":this.calculateSquarePosition(t,h,d,p,i,s);break;case"triangle":this.calculateTrianglePosition(t,h,d,p,i,s);break;default:{const t=d;c=i+Math.cos(h+p)*t,u=s+Math.sin(h+p)*t;break}}t.gestureData.morph={startX:a,startY:o,targetX:t.gestureData.morphTargetX||c,targetY:t.gestureData.morphTargetY||u,originalVx:t.vx,originalVy:t.vy,rotationDirection:l,initialized:!0}},calculateStarPosition(t,e,i,s,n,r,a,o){const h=((e+Math.PI)%(2*Math.PI)+2*Math.PI)%(2*Math.PI),l=Math.floor(h/(2*Math.PI)*10),c=l%2==0,u=Math.floor(l/2);let d;d=c?72*u*Math.PI/180:(72*u+36)*Math.PI/180,d+=r;const p=c?i:i*n;t.gestureData.morphTargetX=a+Math.cos(d)*p,t.gestureData.morphTargetY=o+Math.sin(d)*p},calculateHeartPosition(t,e,i,s,n,r){const a=(e+Math.PI)/(2*Math.PI),o=.05*i,h=16*Math.pow(Math.sin(a*Math.PI*2),3),l=-(13*Math.cos(a*Math.PI*2)-5*Math.cos(2*a*Math.PI*2)-2*Math.cos(3*a*Math.PI*2)-Math.cos(4*a*Math.PI*2)),c=Math.cos(s),u=Math.sin(s),d=h*c-l*u,p=h*u+l*c;t.gestureData.morphTargetX=n+d*o,t.gestureData.morphTargetY=r+p*o},calculateSquarePosition(t,e,i,s,n,r){const a=((e+s)%(2*Math.PI)+2*Math.PI)%(2*Math.PI);let o,h;const l=i;a<Math.PI/4||a>=7*Math.PI/4?(o=l,h=l*Math.tan(a)):a<3*Math.PI/4?(o=l/Math.tan(a),h=l):a<5*Math.PI/4?(o=-l,h=-l*Math.tan(a)):(o=-l/Math.tan(a),h=-l);const c=Math.cos(s),u=Math.sin(s),d=o*c-h*u,p=o*u+h*c;t.gestureData.morphTargetX=n+d,t.gestureData.morphTargetY=r+p},calculateTrianglePosition(t,e,i,s,n,r){const a=[{x:0,y:-i},{x:.866*-i,y:.5*i},{x:.866*i,y:.5*i}],o=Math.floor((e+Math.PI)/(2*Math.PI)*3)%3,h=(o+1)%3,l=Math.random(),c=a[o].x+(a[h].x-a[o].x)*l,u=a[o].y+(a[h].y-a[o].y)*l,d=Math.cos(s),p=Math.sin(s),m=c*d-u*p,g=c*p+u*d;t.gestureData.morphTargetX=n+m,t.gestureData.morphTargetY=r+g},apply(t,e,i,s,n,r){t.gestureData?.morph?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.morph,o={...this.config,...i};let h,l,c=e;if(o.holdTime>0){const t=.5-o.holdTime/2,i=.5+o.holdTime/2;c=e<t?e/t*.5:e<i?.5:.5+(e-i)/(1-i)*.5}if(c<=.5){const t=2*c;h=a.startX+(a.targetX-a.startX)*this.easeOutQuad(t),l=a.startY+(a.targetY-a.startY)*this.easeOutQuad(t)}else{const t=2*(c-.5);h=a.targetX+(a.startX-a.targetX)*this.easeInQuad(t),l=a.targetY+(a.startY-a.targetY)*this.easeInQuad(t)}if(o.smooth){const e=.2;t.x+=(h-t.x)*e,t.y+=(l-t.y)*e}else t.x=h,t.y=l;if(t.vx=.5*(h-t.x),t.vy=.5*(l-t.y),e>.9){const i=10*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i)}},cleanup(t){if(t.gestureData?.morph){const e=t.gestureData.morph;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.morph,delete t.gestureData.morphTargetX,delete t.gestureData.morphTargetY}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutQuad:t=>t*(2-t),easeInQuad:t=>t*t,"3d":{evaluate(t,e){const i=e?.strength||1,s=Math.sin(t*Math.PI);let n;if(t<=.5){const e=2*t;n=1+e*(2-e)*.25*i}else{const e=2*(t-.5);n=1.25*i+e*e*(1-1.25*i),n=Math.max(1,n)}return{position:[0,0,0],rotation:[0,s*Math.PI*.3*i,.1*Math.sin(t*Math.PI*2)*i],scale:n,glowIntensity:1+.4*s*i,glowBoost:1.5*s*i}}}},Te={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.rain={originalX:t.x,originalY:t.y,originalVx:t.vx,originalVy:t.vy,originalOpacity:t.opacity??t.life??1,currentX:t.x,currentY:t.y,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(t,e,i,s){const n="number"==typeof s?s:1;t.gestureData?.rain?.initialized||this.initialize(t,i);const r=t.gestureData.rain,a={...this.config,...i},o=i?.strength||1,h=(a.fallSpeed||8)*o,l=(a.fallDistance||400)*e*o;r.wobblePhase+=r.wobbleSpeed*n*.1;const c=Math.sin(r.wobblePhase)*(a.wobbleAmount||1.5);if(t.x=r.originalX+c,t.y=r.originalY+l,t.vx=.3*c,t.vy=10*h,e>.6){const i=(e-.6)/.4;t.opacity=r.originalOpacity*(1-i),void 0!==t.life&&(t.life=r.originalOpacity*(1-i))}else t.opacity=r.originalOpacity,void 0!==t.life&&(t.life=r.originalOpacity)},cleanup(t){if(t.gestureData?.rain){const e=t.gestureData.rain;t.x=e.originalX,t.y=e.originalY,t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.originalOpacity,void 0!==t.life&&(t.life=e.originalOpacity),delete t.gestureData.rain}},"3d":{evaluate:(t,e)=>({position:[0,0,0],rotation:[0,0,0],scale:1})}},Pe={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s;let a=Math.atan2(r,n);const o={...this.config,...e}.angleSpread*Math.PI/180,h=(Math.random()-.5)*o;a+=h;const l=30+30*Math.random();t.gestureData.drift={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,driftAngle:a,angleOffset:h,homeRadius:l*t.scaleFactor,homeX:i+Math.cos(a)*l,homeY:s+Math.sin(a)*l,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.drift?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.drift,o={...this.config,...i},h=i.strength||1,l=this.easeInOutCubic(e),c=Math.max(0,l-.1*a.role);let u,d,p;if(o.returnToOrigin)if(c<.4){const t=c/.4,e=this.easeOutQuad(t);u=a.startX+(a.homeX-a.startX)*e,d=a.startY+(a.homeY-a.startY)*e}else if(c<.6+o.holdTime){const e=(c-.4)/(.2+o.holdTime);p=a.homeRadius+Math.sin(e*Math.PI*.5)*o.distance*h*t.scaleFactor}else{const e=(c-.6-o.holdTime)/(.4-o.holdTime);p=a.homeRadius+Math.cos(e*Math.PI*.5)*o.distance*h*t.scaleFactor}else{const e=c;p=a.homeRadius+e*o.distance*h*t.scaleFactor}if(void 0!==p){a.turbulencePhase+=o.turbulence*s;const t=Math.sin(a.turbulencePhase)*o.turbulence*10,e=Math.cos(1.3*a.turbulencePhase)*o.turbulence*10,i=a.driftAngle+a.angleOffset;u=n+Math.cos(i)*p+t,d=r+Math.sin(i)*p+e}const m=o.smoothness+.08*a.role;if(t.x+=(u-t.x)*m,t.y+=(d-t.y)*m,t.vx=.25*(u-t.x),t.vy=.25*(d-t.y),o.fadeOut){let i;i=e<.25?.3+e/.25*.7:e<.75?.7+.3*Math.sin((e-.25)*Math.PI/.5):4*(1-e),t.opacity=a.baseOpacity*i,void 0!==t.life&&(t.life=t.opacity)}e>=.99&&(t.vx=.1*a.originalVx,t.vy=.1*a.originalVy,o.fadeOut&&(t.opacity=a.baseOpacity,void 0!==t.life&&(t.life=a.baseOpacity)))},cleanup(t){if(t.gestureData?.drift){const e=t.gestureData.drift;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.drift}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,easeOutQuad:t=>t*(2-t),"3d":{evaluate(t,e){const i={...this.config,...e},s=e.strength||1,n=(i.angle||45)*Math.PI/180,r=i.returnToOrigin?t<.5?2*t:2*(1-t):t;return{position:[Math.cos(n)*r*.3*s,Math.sin(n)*r*.3*s,.15*Math.sin(t*Math.PI)*s],rotation:[0,10*r*s,0],scale:1+.03*Math.sin(t*Math.PI),glowIntensity:1-.1*r}}}};function De(t){const e=P[t];if(!e)throw new Error(`Invalid drift direction: ${t}`);const i="up"===t||"down"===t;return{name:`drift${D(t)}`,emoji:"up"===t?"โ๏ธ":"down"===t?"๐":"left"===t?"๐ซ๏ธ":"๐ญ",type:"override",description:`Gentle drifting ${t}`,config:{duration:800,musicalDuration:{musical:!0,beats:2},distance:50,returnToOrigin:!0,fadeOut:!1,holdTime:.2,turbulence:.1,smoothness:.08,strength:1,direction:t,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(t,e,i,s){t.gestureData||(t.gestureData={});const n=(30+30*Math.random())*t.scaleFactor;t.gestureData.drift={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,homeRadius:n,role:Math.random(),turbulencePhase:Math.random()*Math.PI*2,initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.drift?.initialized||this.initialize(t,n,a,o);const h=t.gestureData.drift,l={...this.config,...n},c=n.strength||1,u=this.easeInOutCubic(s),d=Math.max(0,u-.1*h.role);let p,m=h.startX,g=h.startY;p=l.returnToOrigin?d<.5?2*d:2*(1-d):d;const f=l.distance*c*t.scaleFactor*p;h.turbulencePhase+=l.turbulence*r;const y=Math.sin(h.turbulencePhase)*l.turbulence*10,M=Math.cos(1.3*h.turbulencePhase)*l.turbulence*10;i?(g=h.startY+e.y*f+y,m=h.startX+.5*M):(m=h.startX+e.x*f+M,g=h.startY+.5*y);const b=l.smoothness+.08*h.role;if(t.x+=(m-t.x)*b,t.y+=(g-t.y)*b,t.vx=.25*(m-t.x),t.vy=.25*(g-t.y),l.fadeOut){let e=1;e=s<.25?.3+s/.25*.7:s<.75?.7+.3*Math.sin((s-.25)*Math.PI/.5):4*(1-s),t.opacity=h.baseOpacity*e}s>=.99&&(t.vx=.1*h.originalVx,t.vy=.1*h.originalVy,l.fadeOut&&(t.opacity=h.baseOpacity))},cleanup(t){if(t.gestureData?.drift){const e=t.gestureData.drift;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,delete t.gestureData.drift}},easeInOutCubic:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,"3d":{evaluate(t,s){const n=s||{},r=n.strength||1,a=n.distance||50,o=!1!==n.returnToOrigin?Math.sin(t*Math.PI):t,h=.004*a*r*o,l=e.x*h,c=e.y*h;let u=0,d=0;return i?u=e.y*o*.1:d=e.x*o*.15,{cameraRelativePosition:[l,c,0],rotation:[u,d,0],scale:1+.03*o,glowIntensity:1-.1*o}}}}}var Re=De("up"),Fe=De("down"),ze=De("left"),qe=De("right"),Oe={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-(i||0),r=t.y-(s||0);t.gestureData.vortex={originalX:t.x,originalY:t.y,startAngle:Math.atan2(r,n),startDistance:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.vortex?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=t.gestureData.vortex,h="outward"!==a.direction,l=a.rotationSpeed||2,c=a.pullStrength||1,u=e*l*Math.PI*2,d=o.startAngle+u;let p;p=h?1-e*c*.8:1+e*c*.5;const m=o.startDistance*p;t.x=n+Math.cos(d)*m,t.y=r+Math.sin(d)*m,h&&e>.7&&(t.opacity=1-(e-.7)/.3)},cleanup(t){if(t.gestureData?.vortex){const e=t.gestureData.vortex;t.x=e.originalX,t.y=e.originalY,t.opacity=1,delete t.gestureData.vortex}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n="outward"!==i.direction,r=i.rotationSpeed||2,a=i.liftAmount||.5,o=t*r*Math.PI*2*s;let h;h=n?1-.3*t*s:1+.2*t*s;const l=t>.85?(1-t)/.15:1;return{position:[0,Math.sin(t*Math.PI)*a*.1*s*l,0],rotation:[.1*Math.sin(o)*s*l,o,.1*Math.cos(o)*s*l],scale:h,glowIntensity:1+.4*t,glowBoost:.3*t}}}};function je(t){if(!P[t])throw new Error(`Invalid cascade direction: ${t}`);const e="up"===t||"down"===t,i="down"===t||"right"===t;return{name:`cascade${D(t)}`,emoji:"down"===t?"๐":"up"===t?"โจ":"left"===t?"๐":"๐ฌ๏ธ",type:"override",description:`Sequential cascade ${t}`,config:{duration:2e3,musicalDuration:{musical:!0,bars:1},distance:200,waveCount:4,staggerDelay:.15,wobble:1,strength:1,direction:t,particleMotion:{type:"cascade",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat",distanceSync:{quiet:100,loud:300,crescendo:"expand",diminuendo:"contract"}},initialize(t,e){t.gestureData||(t.gestureData={});const i=e?.waveCount||4;let s;s=Math.floor(Math.random()*i),t.gestureData.cascade={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,waveGroup:s,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),initialized:!0}},apply(t,s,n,r,a,o){t.gestureData?.cascade?.initialized||this.initialize(t,n);const h={...this.config,...n},l=h.strength||1,c=t.gestureData.cascade,u="number"==typeof r?r:1,d=h.waveCount||4,p=h.staggerDelay||.15,m=c.waveGroup*p,g=Math.max(0,(s-m)/(1-m*(d-1)/d));if(g<=0)return;const f=(1-Math.pow(1-g,2))*((h.distance||200)*l)*(i?1:-1);c.wobblePhase+=c.wobbleSpeed*u*.1;const y=Math.sin(c.wobblePhase)*(h.wobble||1)*10;if(e?(t.y=c.originalY+f,t.x=c.originalX+y):(t.x=c.originalX+f,t.y=c.originalY+y),g>.6){const e=(g-.6)/.4;t.opacity=c.originalOpacity*(1-e)}},cleanup(t){if(t.gestureData?.cascade){const e=t.gestureData.cascade;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.cascade}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"down",r=1-Math.pow(1-t,2);let a=0,o=0;const h=.3*r*s;switch(n){case"down":o=-h;break;case"up":o=h;break;case"left":a=-h;break;case"right":a=h}const l=.03*Math.sin(t*Math.PI*4)*s;"down"===n||"up"===n?a+=l:o+=l;const c=t>.85?(1-t)/.15:1;return{cameraRelativePosition:[a*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*r,glowIntensity:1+.2*(1-r)}}}}}var Ie=je("up"),$e=je("down"),Le=je("left"),Ge=je("right"),_e={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.confetti={originalX:t.x,originalY:t.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(t,e,i,s,n,r){t.gestureData?.confetti?.initialized||this.initialize(t,i);const a={...this.config,...i},o=a.strength||1,h=t.gestureData.confetti,l=Math.min(e/.2,1),c=Math.max(0,(e-.2)/.8),u=-50*Math.sin(l*Math.PI)*(a.burstHeight||.3),d=c*c*200*(a.fallSpeed||1),p=20*Math.sin(e*Math.PI*8*h.tumbleSpeed)*h.flutterAmp,m=h.driftX*e*100*(a.spread||1);t.x=h.originalX+m+p*o,t.y=h.originalY+u+d*o,e>.7&&(t.opacity=1-(e-.7)/.3)},cleanup(t){t.gestureData?.confetti&&delete t.gestureData.confetti},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1,s=Math.min(t/.2,1),n=Math.max(0,(t-.2)/.8),r=.15*Math.sin(s*Math.PI)-n*n*.3,a=t*Math.PI*4,o=.3*Math.sin(1.3*a)*i,h=.4*Math.sin(.7*a)*i,l=.5*Math.sin(1.1*a)*i,c=t>.85?(1-t)/.15:1;return{position:[.08*Math.sin(t*Math.PI*6)*i*c,r*i*c,0],rotation:[o*c,h*c,l*c],scale:1+.1*Math.sin(2*a)*i,glowIntensity:1+.3*(1-n)}}}},He={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.fizz={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.4+.6*Math.random(),riseMultiplier:.7+.6*Math.random(),initialized:!0}},apply(t,e,i,s){t.gestureData?.fizz?.initialized||this.initialize(t,i);const n={...this.config,...i},r=n.strength||1,a=t.gestureData.fizz,o="number"==typeof s?s:1,h=(n.riseDistance||300)*e*r*a.riseMultiplier;a.wobblePhase+=a.wobbleSpeed*o*.1;const l=Math.sin(a.wobblePhase)*(n.wobbleAmount||2)*(1+e);if(t.x=a.originalX+l,t.y=a.originalY-h,t.vx=.3*l,t.vy=10*-(n.riseSpeed||6),e>.6){const i=(e-.6)/.4;t.opacity=a.originalOpacity*(1-i),void 0!==t.life&&(t.life=a.originalOpacity*(1-i))}},cleanup(t){if(t.gestureData?.fizz){const e=t.gestureData.fizz;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,void 0!==t.life&&(t.life=e.originalOpacity),delete t.gestureData.fizz}},"3d":{evaluate(t,e){const i=(e.config||this.config||{}).strength||1;let s=0,n=1,r=1;if(t<.15){const e=t/.15;s=.15*e,n=1+.02*e,r=1+.15*e}else if(t<.7){const e=(t-.15)/.55;s=.5-.15*e,n=1.02+.03*Math.sin(e*Math.PI*6),r=1.2+.15*Math.sin(e*Math.PI*8)}else{const e=(t-.7)/.3;s=.35*(1-e),n=1.02-.02*e,r=1.2-.2*e}const a=35*t;return{position:[.008*Math.sin(1.7*a)*s*i,.006*Math.sin(2.3*a)*s*i,.004*Math.sin(1.9*a)*s*i],rotation:[.03*Math.sin(1.3*a)*s*i,.02*Math.sin(1.1*a)*s*i,.04*Math.sin(1.5*a)*s*i],scale:[n+.015*Math.sin(2.1*a)*s,n+.02*Math.sin(1.8*a)*s,n+.015*Math.sin(2.4*a)*s],glowIntensity:r,glowBoost:.2*s}}}};function Ue(t){const e=P[t];if(!e)throw new Error(`Invalid swarm direction: ${t}`);return{name:`swarm${D(t)}`,emoji:"up"===t?"๐ฆ
":"down"===t?"๐ฆ":"๐",type:"override",description:`Flock movement ${t}`,config:{duration:1800,musicalDuration:{musical:!0,bars:1},clusterPhase:.3,moveDistance:120,clusterTightness:.5,wobble:1,strength:1,direction:t,particleMotion:{type:"swarm",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"bars",bars:1},timingSync:"onBeat"},initialize(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.swarm={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),timeOffset:.1*Math.random(),initialized:!0}},apply(t,i,s,n,r,a){t.gestureData?.swarm?.initialized||this.initialize(t,s,r,a);const o={...this.config,...s},h=o.strength||1,l=t.gestureData.swarm,c=o.clusterPhase||.3,u=o.moveDistance||120,d=o.clusterTightness||.5,p=Math.max(0,Math.min(1,i-l.timeOffset));let m,g;if(p<c){const t=p/c,e=1-Math.pow(1-t,2);m=l.originalX+(r-l.originalX)*d*e,g=l.originalY+(a-l.originalY)*d*e}else{const t=(p-c)/(1-c),i=1-Math.pow(1-t,2),s=l.originalX+(r-l.originalX)*d,n=l.originalY+(a-l.originalY)*d;m=s+e.x*u*i*h,g=n+e.y*u*i*h}const f="number"==typeof n?n:1;l.wobblePhase+=l.wobbleSpeed*f*.1;const y=Math.sin(3*l.wobblePhase)*o.wobble*5,M=Math.cos(2.5*l.wobblePhase)*o.wobble*5;t.x=m+y,t.y=g+M,p>.8&&(t.opacity=l.originalOpacity*(1-5*(p-.8)))},cleanup(t){if(t.gestureData?.swarm){const e=t.gestureData.swarm;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.swarm}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"up",r=i.clusterPhase||.3,[a,o]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];let h=0,l=0,c=1;if(t<r)c=1-t/r*.1*s;else{const e=(t-r)/(1-r),i=1-Math.pow(1-e,2);h=a*i*.25*s,l=o*i*.25*s,c=.9+.1*e}const u=t>r?.1:0,d=t>.85?(1-t)/.15:1;return{cameraRelativePosition:[(h+.02*Math.sin(t*Math.PI*6)*s)*d,l*d,0],rotation:[o*u*s,0,-a*u*s],scale:c,glowIntensity:1+(t>r?.2:0)}}}}}var We=Ue("up"),Ye=Ue("down"),Xe=Ue("left"),Ve=Ue("right"),Ne={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(t,e,i,s,n,r){const a=i.decay||this.config.decay,o=(i.strength||this.config.strength)*(1-e*a),h=t.x-n,l=t.y-r,c=Math.sqrt(h*h+l*l);c>1&&(t.vx+=h/c*o*2*s,t.vy+=l/c*o*2*s)},"3d":{evaluate(t,e){const i=e.strength||2;let s=0,n=1,r=1,a=0;if(t<.15){const e=t/.15,o=1-Math.pow(1-e,3);s=.15*o*i,n=1+.2*o*i,r=1+.5*o,a=.4*o}else if(t<.35){const e=(t-.15)/.2;s=.15*(1-1.5*e)*i,n=1+.2*(1-e)*i-.1*Math.sin(e*Math.PI),r=1+.4*(1-e),a=.2*(1-e)}else{const e=(t-.35)/.65,a=Math.pow(1-e,2),o=Math.sin(e*Math.PI*2)*a;s=.03*o*i,n=1+.05*o,r=1+.15*Math.abs(o)}return{cameraRelativePosition:[0,0,s],position:[0,0,0],rotation:[0,0,0],scale:n,glowIntensity:r,glowBoost:a}}}};function Qe(t){const e=P[t];if(!e)throw new Error(`Invalid burst direction: ${t}`);const i="up"===t||"down"===t;return{name:`burst${D(t)}`,emoji:"up"===t?"โฒ":"down"===t?"๐ฟ":"๐จ",type:"blending",description:`Explosive burst ${t}`,config:{duration:600,musicalDuration:{musical:!0,beats:1},decay:.5,strength:2,spread:.3,direction:t,particleMotion:{type:"burst",strength:2,direction:t}},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(t,s,n,r,a,o){const h={...this.config,...n},l=h.decay||.5,c=(h.strength||2)*(1-s*l),u=h.spread||.3;let d=e.x*c*2,p=e.y*c*2;const m=(Math.random()-.5)*u*c;i?d+=m:p+=m,t.vx+=d*r,t.vy+=p*r},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||2,n=i.direction||"up";let r=0,a=0,o=0,h=1,l=1,c=0;const[u,d]={up:[0,1],down:[0,-1],left:[-1,0],right:[1,0]}[n]||[0,1];if(t<.15){const e=t/.15,i=1-Math.pow(1-e,3);r=u*i*.2*s,a=d*i*.2*s,o=.1*i*s,h=1+.15*i*s,l=1+.5*i,c=.4*i}else if(t<.35){const e=(t-.15)/.2,i=1-1.5*e;r=.2*u*i*s,a=.2*d*i*s,o=.1*i*s,h=1+.15*(1-e)*s,l=1+.4*(1-e),c=.2*(1-e)}else{const e=(t-.35)/.65,i=Math.pow(1-e,2),n=Math.sin(e*Math.PI*2)*i;r=u*n*.05*s,a=d*n*.05*s,h=1+.05*n,l=1+.15*Math.abs(n)}return{cameraRelativePosition:[r,a,o],position:[0,0,0],rotation:[0,0,0],scale:h,glowIntensity:l,glowBoost:c}}}}}var Je=Qe("up"),Ke=Qe("down"),Ze=Qe("left"),ti=Qe("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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=a.waveCount||3,l=a.amplitude||15,c=a.damping||.7,u=t.x-n,d=t.y-r,p=Math.sqrt(u*u+d*d),m=(p/50-e*h*2)*Math.PI,g=Math.pow(1-e,c),f=Math.sin(m)*l*o*g;if(p>1){const e=.5*Math.cos(m)*o*g;t.x+=u/p*e,t.y+=d/p*e}t.opacity=Math.max(.3,1-.3*Math.abs(f/l))},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.waveCount||3,r=i.damping||.7,a=Math.pow(1-t,r),o=t*Math.PI*n*2,h=Math.sin(o),l=t*Math.PI*4,c=Math.sin(l)*s*a,u=.5*Math.sin(l+Math.PI/2)*s*a,d=.12,p=1-c*d+u*d*.3,m=1+c*d,g=1-c*d-u*d*.3,f=.08*(m-1);return{position:[.01*Math.sin(1.5*l)*a,f,0],rotation:[.04*h*s*a,0,.03*u*s*a],scale:[p,m,g],glowIntensity:1+.3*Math.abs(c),glowBoost:.25*Math.max(0,c)*a}}}},ii={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-i,r=t.y-s,a=Math.atan2(r,n),o=Math.sqrt(n*n+r*r),h=Math.random()<.5?1:-1;t.gestureData.wave={startX:t.x,startY:t.y,originalVx:t.vx,originalVy:t.vy,baseOpacity:t.opacity||t.life||1,angle:a,radius:o,offset:Math.random()*Math.PI*2,role:Math.random(),direction:h,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.wave?.initialized||this.initialize(t,i,n,r);const a=t.gestureData.wave,o={...this.config,...i},h=i.strength||1,l=this.easeInOutSine(e),c=a.role*o.phaseShift,u=Math.max(0,l-c),d=u*Math.PI*2*o.frequency*a.direction+a.offset,p=.5+a.radius/100*.5,m=o.amplitude*p*h*t.scaleFactor,g=n+Math.sin(d)*m,f=r+Math.sin(2*d)*m*.3+-Math.abs(Math.sin(l*Math.PI))*o.liftHeight*t.scaleFactor,y=o.smoothness+.12*a.role;if(t.x+=(g-t.x)*y,t.y+=(f-t.y)*y,t.vx=.3*(g-t.x),t.vy=.3*(f-t.y),o.fadeInOut){let e;e=u<.1?u/.1:u>.9?(1-u)/.1:.5+.5*Math.sin(u*Math.PI),t.opacity=a.baseOpacity*(.3+.7*e),void 0!==t.life&&(t.life=t.opacity)}if(e>=.95){const i=20*(1-e);t.vx=t.vx*i+a.originalVx*(1-i),t.vy=t.vy*i+a.originalVy*(1-i),o.fadeInOut&&(t.opacity=a.baseOpacity*i,void 0!==t.life&&(t.life=t.opacity))}},cleanup(t){if(t.gestureData?.wave){const e=t.gestureData.wave;t.vx=e.originalVx,t.vy=e.originalVy,t.opacity=e.baseOpacity,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.wave}},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i=e?.strength||1,s=e?.frequency||1,n=-(Math.cos(Math.PI*t)-1)/2,r=n*Math.PI*2*s,a=.12*Math.sin(r)*i,o=.06*Math.sin(2*r)*i,h=.03*Math.sin(r)*i,l=.08*Math.sin(2*r)*i,c=.05*Math.sin(r)*i,u=1+.08*Math.abs(Math.sin(n*Math.PI))*i,d=Math.abs(Math.sin(r));return{position:[a,o,h],rotation:[l,0,c],scale:u,glowIntensity:1+.3*d*i,glowBoost:.6*d*i}}}},si={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(t,e){t.gestureData||(t.gestureData={}),t.gestureData.flash={originalOpacity:t.opacity,originalSize:t.size,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.flash?.initialized||this.initialize(t,i);const a=t.gestureData.flash,o={...this.config,...i},h=o.strength||1;let l;if(l=e<.3?e/.3*o.glowPeak:o.glowPeak*(1-(e-.3)/.7),t.opacity=Math.min(1,a.originalOpacity*(1+l*h)),t.size=a.originalSize*(1+(o.scalePeak-1)*l*h*.1),e<.2){const i=(1-e/.2)*h,a=Math.atan2(t.y-r,t.x-n);t.vx+=Math.cos(a)*i*2*s,t.vy+=Math.sin(a)*i*2*s}t.vx*=1-.1*o.particleMotion.decay,t.vy*=1-.1*o.particleMotion.decay},cleanup(t){t.gestureData?.flash&&(t.opacity=t.gestureData.flash.originalOpacity,t.size=t.gestureData.flash.originalSize,delete t.gestureData.flash)},"3d":{evaluate(t,e){let i;i=t<.3?t/.3:1-(t-.3)/.7;const s=1+.4*i;return{position:[0,0,0],rotation:[0,0,0],scale:1+i*(({...this.config,...e}.scalePeak||1.1)-1),glowIntensity:s,glowBoost:2*i}}}},ni={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(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.glow={startOpacity:t.opacity,startGlow:t.glowSizeMultiplier||0,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.glow?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=this.easeInOutSine(e);let h,{frequency:l}=a,{glowAmount:c}=a;i.rhythmModulation&&(c*=i.rhythmModulation.amplitudeMultiplier||1,c*=i.rhythmModulation.accentMultiplier||1,i.rhythmModulation.frequencyMultiplier&&(l*=i.rhythmModulation.frequencyMultiplier));const u=o*l*2%2;h=a.holdPeak>0&&u>1-a.holdPeak&&u<1+a.holdPeak?1:Math.sin(o*Math.PI*2*l);let d=1;e>.9&&(d=.5+.5*(1-10*(e-.9))),t.glowIntensity=1+h*c*d},cleanup(t){t.gestureData?.glow&&(t.glowIntensity=1,delete t.gestureData.glow)},easeInOutSine:t=>-(Math.cos(Math.PI*t)-1)/2,"3d":{evaluate(t,e){const i={...this.config,...e},s=-(Math.cos(Math.PI*t)-1)/2,n=Math.sin(s*Math.PI);let r=i.glowAmount||.8;e.rhythmModulation&&(r*=e.rhythmModulation.amplitudeMultiplier||1,r*=e.rhythmModulation.accentMultiplier||1);const a=1+n*r;return{position:[0,0,0],rotation:[0,0,0],scale:1+n*(i.scaleAmount||.1)*.5,glowIntensity:a,glowBoost:1.5*n}}}},ri={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(t,e,i,s){t.gestureData||(t.gestureData={});const n=t.x-(i||0),r=t.y-(s||0);t.gestureData.bloom={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,startAngle:Math.atan2(r,n),startDistance:Math.sqrt(n*n+r*r),initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.bloom?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=t.gestureData.bloom,l=Math.pow(e,.7),c=(a.rotationAmount||.3)*Math.PI,u=Math.sin(l*Math.PI)*c,d=1+.5*l*o,p=h.startDistance*d,m=h.startAngle+u;t.x=n+Math.cos(m)*p,t.y=r+Math.sin(m)*p,t.opacity=Math.min(1,h.originalOpacity*(.7+.3*l))},cleanup(t){if(t.gestureData?.bloom){const e=t.gestureData.bloom;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.bloom}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.rotationAmount||.3,r=Math.pow(t,.7),a=1+.2*r*s,o=Math.sin(r*Math.PI)*n*s,h=.1*Math.sin(r*Math.PI*.5)*s,l=t>.85?1-(t-.85)/.15*.3:1;return{position:[0,.05*Math.sin(r*Math.PI)*s*l,0],rotation:[0,o*l,h*l],scale:a*(.7+.3*l),glowIntensity:1+.4*r,glowBoost:.3*r}}}},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(t,e){t.gestureData||(t.gestureData={});const i={...this.config,...e},s=Math.random()<i.groupFlicker;t.gestureData.flicker={baseOpacity:t.opacity||t.life||1,baseColor:t.color,baseX:t.x,baseY:t.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(t,e,i,s,n,r){t.gestureData?.flicker?.initialized||this.initialize(t,i);const a=t.gestureData.flicker,o={...this.config,...i},h=i.strength||1;let l;if(a.flickerTimer+=s*o.flickerRate,o.strobe)l=(a.flickerTimer+a.phase)%1<.5?1:o.minOpacity;else if(o.pulseMode){const t=a.flickerTimer+a.phase;l=o.minOpacity+(o.maxOpacity-o.minOpacity)*(.5*Math.sin(t)+.5)}else{if(a.flickerTimer-a.lastFlicker>1)if(a.lastFlicker=a.flickerTimer,a.isGrouped){const t=Math.floor(a.flickerTimer)%3;a.flickerState=t===a.groupId}else a.flickerState=Math.random()>.3;const e=a.flickerState?o.maxOpacity:o.minOpacity+.3*Math.random(),i=t.opacity/a.baseOpacity;l=i+.3*(e-i)}const c=a.baseOpacity*(1+(l-1)*h);if(t.opacity=Math.max(0,Math.min(1,c)),void 0!==t.life&&(t.life=t.opacity),o.jitterAmount>0&&l>o.minOpacity){const e=o.jitterAmount*h*t.scaleFactor,i=(Math.random()-.5)*e*l,n=(Math.random()-.5)*e*l;t.vx+=.1*i*s,t.vy+=.1*n*s}if(o.colorShift&&t.color){a.colorHue+=.01*s;const e=30*Math.sin(a.colorHue);t.color=this.shiftHue(a.baseColor,e*h)}let u=1;e<.1?u=e/.1:e>.9&&(u=(1-e)/.1),t.opacity*=u,void 0!==t.life&&(t.life=t.opacity),e>.8&&(t.vx*=.95,t.vy*=.95)},shiftHue(t,e){if(!t||!t.startsWith("#"))return t;const i=t.slice(1),s=parseInt(i.substr(0,2),16)/255,n=parseInt(i.substr(2,2),16)/255,r=parseInt(i.substr(4,2),16)/255,a=e*Math.PI/180,o=Math.cos(a),h=Math.sin(a),l=s*h+n*o,c=r,u=t=>Math.max(0,Math.min(255,Math.round(255*t))).toString(16).padStart(2,"0");return`#${u(s*o-n*h)}${u(l)}${u(c)}`},cleanup(t){if(t.gestureData?.flicker){const e=t.gestureData.flicker;t.opacity=e.baseOpacity,t.color=e.baseColor,void 0!==t.life&&(t.life=e.baseOpacity),delete t.gestureData.flicker}},"3d":{evaluate(t,e){const i=e.config||{},s=e.strength||.7,n=t*(i.flickerRate||15),r=Math.sin(n*Math.PI*2),a=Math.floor(10*n),o=.3*r+.5*(Math.sin(123.456*a)+1)*.7,h=.6+.8*o,l=i.jitterAmount||2,c=.003*s*h,u=(Math.random()-.5)*l*c,d=(Math.random()-.5)*l*c,p=.03*(Math.random()-.5)*s*h;return{position:[u,d,0],rotation:[.5*p,0,p],scale:1+.08*(h-1),glowIntensity:h,glowBoost:1.2*o}}}},oi={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=a.frequency||30,l=100*(a.amplitude||.02),c=e*h*Math.PI*2,u=(.6*Math.sin(c)+.3*Math.sin(1.7*c+1.3)+.1*Math.sin(2.3*c+2.7))*l*o,d=Math.sin(e*Math.PI);t.x+=u*d*(Math.random()-.5)*2,t.y+=u*d*(Math.random()-.5)*2},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.frequency||30,r=i.amplitude||.02,a=Math.sin(t*Math.PI),o=t*n*Math.PI*2,h=.6*Math.sin(o)+.3*Math.sin(1.7*o)+.1*Math.sin(2.3*o),l=.5*Math.cos(1.1*o)+.3*Math.cos(1.9*o)+.2*Math.cos(2.7*o);return{position:[h*r*s*a,l*r*s*a,(.4*Math.sin(.9*o+1)+.4*Math.sin(1.5*o+2))*r*.5*s*a],rotation:[.02*l*s*a,0,.02*h*s*a],scale:1+.01*Math.abs(h)*s*a,glowIntensity:1+.1*Math.abs(h)*a}}}},hi={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=this.t(e,a),l=t.x-n,c=t.y-r,u=Math.sqrt(l*l+c*c)||1,d=10*h*o;t.x+=l/u*d,t.y+=c/u*d},t(t,e){const i=e.lubDubGap||.15,s=e.lubStrength||.8,n=e.dubStrength||1;let r=0;const a=Math.abs(t-.1);a<.08&&(r=Math.cos(a/.08*Math.PI*.5)*s);const o=.1+i+.05,h=Math.abs(t-o);if(h<.1){const t=Math.cos(h/.1*Math.PI*.5)*n;r=Math.max(r,t)}return r},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.lubDubGap||.15,r=i.lubStrength||.8,a=i.dubStrength||1;let o=0;const h=Math.abs(t-.1);h<.08&&(o=Math.cos(h/.08*Math.PI*.5)*r);const l=.1+n+.05,c=Math.abs(t-l);if(c<.1){const t=Math.cos(c/.1*Math.PI*.5)*a;o=Math.max(o,t)}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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=100*(a.snapDistance||.1),l=a.overshoot||1.3,c=this.i(e,l,a.bounces||2),u=n-t.x,d=r-t.y,p=Math.sqrt(u*u+d*d)||1;t.x+=u/p*c*h*o*.1,t.y+=d/p*c*h*o*.1},i(t,e,i){if(t<.2){const i=t/.2;return(1-Math.pow(1-i,3))*e}{const s=(t-.2)/.8,n=Math.exp(4*-s);return 1+(e-1)*Math.cos(s*Math.PI*i*2)*n}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.snapDistance||.1,r=i.overshoot||1.3,a=i.bounces||2;let o;if(t<.2){const e=t/.2;o=(1-Math.pow(1-e,3))*r}else{const e=(t-.2)/.8,i=Math.exp(4*-e);o=1+(r-1)*Math.cos(e*Math.PI*a*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:t<.3?(.3-t)/.3*.4:0}}}},ci={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(t,e,i,s,n,r){const a={...this.config,...i},o=a.strength||1,h=200*(a.dropHeight||.15),l=a.bounceCount||3,c=a.elasticity||.6,u=this.o(e,h,l,c);t.y+=u*o;const d=.3*Math.max(0,-u/h);t.scaleY=1-d*o,t.scaleX=1+.5*d*o},o(t,e,i,s){let n=e,r=0,a=0,o=.3;for(;a<i&&r<1;){const e=o*Math.pow(s,.5*a);if(t<r+e){const i=(t-r)/e;return 4*i*(1-i)*-n}r+=e,n*=s,a++,o*=s}return 0},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.dropHeight||.15,r=i.bounceCount||3,a=i.elasticity||.6;let o=n,h=0,l=0,c=.3,u=0,d=!1;for(;l<r&&h<1;){const e=c*Math.pow(a,.5*l);if(t<h+e){const i=(t-h)/e;u=o*(4*i*(1-i))*s,d=i>.45&&i<.55;break}h+=e,o*=a,l++,c*=a}let p=1,m=1;if(d){const t=.15*s*Math.pow(a,l);p=1+t,m=1-t}return{position:[0,u,0],rotation:[0,0,0],scale:(p+m)/2,glowIntensity:1+(d?.3:0)}}}},ui={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(t){t.gestureData||(t.gestureData={}),t.gestureData.hold={holdX:t.x,holdY:t.y,originalVx:t.vx,originalVy:t.vy}},apply(t,e,i,s,n,r){t.gestureData?.hold||this.initialize(t);const a=t.gestureData.hold,o=i.holdStrength||this.config.holdStrength;if(i.allowDrift?(t.vx*=o,t.vy*=o):(t.x+=(a.holdX-t.x)*(1-o),t.y+=(a.holdY-t.y)*(1-o),t.vx=0,t.vy=0),e>.9){const i=10*(e-.9);t.vx=t.vx*(1-i)+a.originalVx*i,t.vy=t.vy*(1-i)+a.originalVy*i}},cleanup(t){if(t.gestureData?.hold){const e=t.gestureData.hold;t.vx=e.originalVx,t.vy=e.originalVy,delete t.gestureData.hold}},"3d":{evaluate(t,e){let i=0,s=1;if(t<.15){const e=t/.15;i=e*e*(3-2*e),s=1-.2*i}else if(t<.85)i=1,s=.8;else{const e=(t-.85)/.15;i=1-e*e*(3-2*e),s=.8+.2*e}return i*=(e.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}}}},di={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(t){t.gestureData||(t.gestureData={}),t.gestureData.fade={baseOpacity:t.opacity||t.life||1}},apply(t,e,i,s,n,r){t.gestureData?.fade||this.initialize(t);const a=t.gestureData.fade,o={...this.config,...i};let h;h=o.fadeIn&&!o.fadeOut?o.minOpacity+(o.maxOpacity-o.minOpacity)*e:o.fadeOut&&!o.fadeIn?o.maxOpacity-(o.maxOpacity-o.minOpacity)*e:e<.5?o.minOpacity+(o.maxOpacity-o.minOpacity)*(2*e):o.maxOpacity-(o.maxOpacity-o.minOpacity)*(2*(e-.5)),t.opacity=a.baseOpacity*h,void 0!==t.life&&(t.life=t.opacity)},cleanup(t){t.gestureData?.fade&&(t.opacity=t.gestureData.fade.baseOpacity,void 0!==t.life&&(t.life=t.opacity),delete t.gestureData.fade)},"3d":{evaluate(t,e){const i={...this?.config||{},...e},s=i.fadeIn??!0,n=i.fadeOut??!0;let r;r=s&&!n?t:n&&!s?1-t:t<.5?1-t/.5:(t-.5)/.5;const a=r*r*(3-2*r);return{position:[0,0,0],rotation:[0,0,0],scale:.01+.99*a,glowIntensity:a,glowBoost:0}}}},pi={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(t,e,i,s,n,r){const a=i.damping||this.config.damping,o=i.threshold||this.config.threshold;t.vx*=Math.max(0,1-a*s*60),t.vy*=Math.max(0,1-a*s*60),Math.abs(t.vx)<o&&(t.vx=0),Math.abs(t.vy)<o&&(t.vy=0)},"3d":{evaluate(t,e){const i=1-Math.pow(1-t,2),s=.01*(1-i);return{position:[Math.sin(t*Math.PI*2)*s,Math.cos(t*Math.PI*3)*s*.5,0],rotation:[0,0,0],scale:1-.03*i,glowIntensity:1-.15*i}}}},mi={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(t,e,i,s,n,r){if(t.gestureData||(t.gestureData={}),!t.gestureData.peek){const e=t.x-n,i=t.y-r,s=Math.atan2(i,e),a=Math.sqrt(e*e+i*i);t.gestureData.peek={originalX:t.x,originalY:t.y,peekAngle:s,originalDistance:a,staggerDelay:this.config.stagger?.3*Math.random():0,phase:"waiting",phaseTimer:0,peekOffset:{x:0,y:0}}}const a=t.gestureData.peek,{config:o}=this,h=Math.max(0,Math.min(1,(e-a.staggerDelay)/(1-a.staggerDelay)));0===h?a.phase="waiting":h<.3?a.phase="peeking":h<.6?a.phase="holding":h<1&&(a.phase="hiding");let l=0;switch(a.phase){case"peeking":{const t=h/.3;l=this.easeOutCubic(t)*o.peekDistance;break}case"holding":l=o.peekDistance,Math.random()<.1&&(a.peekOffset.x+=2*(Math.random()-.5),a.peekOffset.y+=2*(Math.random()-.5));break;case"hiding":{const t=(h-.6)/.4;l=(1-this.easeInCubic(t))*o.peekDistance;break}}if("waiting"!==a.phase){const e=Math.cos(a.peekAngle)*l,i=Math.sin(a.peekAngle)*l;a.peekOffset.x+=(e-a.peekOffset.x)*o.peekSpeed,a.peekOffset.y+=(i-a.peekOffset.y)*o.peekSpeed,t.x=a.originalX+a.peekOffset.x,t.y=a.originalY+a.peekOffset.y}void 0!==t.alpha&&("peeking"===a.phase||"holding"===a.phase?t.alpha=.7+.3*Math.random():t.alpha=1)},easeOutCubic:t=>1-Math.pow(1-t,3),easeInCubic:t=>t*t*t,cleanup(t){t.gestureData?.peek&&(t.x=t.gestureData.peek.originalX,t.y=t.gestureData.peek.originalY,void 0!==t.alpha&&(t.alpha=1),delete t.gestureData.peek)},"3d":{evaluate(t,e){const i=.01*({...this.config,...e}.peekDistance||40);let s=0,n=1;if(t<.3){const e=t/.3;s=(1-Math.pow(1-e,3))*i}else if(t<.6)s=i,n=.7+.3*Math.random();else{const e=(t-.6)/.4;s=(1-Math.pow(e,3))*i}return{position:[s,0,0],rotation:[0,0,0],scale:1,glowIntensity:n}}}},gi={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(t){t.gestureData||(t.gestureData={}),t.gestureData.directional={initialX:t.x,initialY:t.y}},apply(t,e,i,s,n,r){t.gestureData?.directional||this.initialize(t);const a=(i.angle||this.config.angle)*Math.PI/180,o=i.strength||this.config.strength;if(t.vx+=Math.cos(a)*o*.3*s,t.vy+=Math.sin(a)*o*.3*s,i.returnToOrigin&&e>.5){const i=2*(e-.5),n=t.gestureData.directional,r=n.initialX-t.x,a=n.initialY-t.y;t.vx+=r*i*.02*s,t.vy+=a*i*.02*s}},"3d":{evaluate(t,e){const i={...this.config,...e},s=(i.angle||0)*Math.PI/180,n=e.strength||1,r=i.returnToOrigin?t<.5?2*t:2*(1-t):t;return{position:[Math.cos(s)*r*.4*n,Math.sin(s)*r*.4*n,0],rotation:[0,0,0],scale:1,glowIntensity:1}}}};function fi(t){if(!["forward","back","left","right","up","down","attract","repel"].includes(t))throw new Error(`Invalid magnetic direction: ${t}`);return{name:`magnetic${D(t)}`,emoji:{forward:"๐งฒ",back:"๐งฒ",left:"โฌ
๏ธ",right:"โก๏ธ",up:"โฌ๏ธ",down:"โฌ๏ธ",attract:"๐งฒ",repel:"๐ฅ"}[t],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"}[t],config:{duration:1200,musicalDuration:{musical:!0,beats:3},direction:t,pullStrength:1,returnToOrigin:!0,strength:1,particleMotion:{type:"magnetic",strength:1,direction:t}},rhythm:{enabled:!0,syncMode:"beat",durationSync:{mode:"beats",beats:3},timingSync:"onBeat",strengthSync:{onBeat:1.5,offBeat:.7}},initialize(t,e,i,s){t.gestureData||(t.gestureData={}),t.gestureData.magnetic={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??1,initialized:!0}},apply(t,e,i,s,n,r){t.gestureData?.magnetic?.initialized||this.initialize(t,i,n,r);const a={...this.config,...i},o=a.strength||1,h=a.pullStrength||1,l=!1!==a.returnToOrigin,c=t.gestureData.magnetic,u=a.direction||"attract";let d,p,m;switch(d=l?Math.sin(e*Math.PI):Math.min(1,2*e),u){case"left":p=c.originalX-100,m=c.originalY;break;case"right":p=c.originalX+100,m=c.originalY;break;case"up":p=c.originalX,m=c.originalY-100;break;case"down":p=c.originalX,m=c.originalY+100;break;case"repel":{const t=c.originalX-n,e=c.originalY-r,i=Math.sqrt(t*t+e*e)||1;p=c.originalX+t/i*100,m=c.originalY+e/i*100;break}default:p=n,m=r}const g=(p-c.originalX)*d*h*o*.5,f=(m-c.originalY)*d*h*o*.5;t.x=c.originalX+g,t.y=c.originalY+f},cleanup(t){if(t.gestureData?.magnetic){const e=t.gestureData.magnetic;t.x=e.originalX,t.y=e.originalY,t.opacity=e.originalOpacity,delete t.gestureData.magnetic}},"3d":{evaluate(t,e){const i=e.config||this.config||{},s=i.strength||1,n=i.direction||"attract";let r;r=!1!==i.returnToOrigin?Math.sin(t*Math.PI):Math.min(1,2*t);let a=0,o=0,h=0,l=1;const c=.15*r*s;switch(n){case"forward":h=c,l=1+.1*r*s;break;case"back":h=-c,l=1-.08*r*s;break;case"left":a=-c;break;case"right":a=c;break;case"up":o=c;break;case"down":o=-c;break;case"attract":h=c,l=1-.1*r*s;break;case"repel":h=-c,l=1+.1*r*s}const u=1+.4*r,d=.3*r;return{cameraRelativePosition:[a+(r>.5?.01*Math.sin(t*Math.PI*20)*(r-.5)*2:0),o,h],rotation:[0,0,0],scale:l,glowIntensity:u,glowBoost:d}}}}}const yi={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:(t,e,i)=>!1,blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i=e?.strength||1,s=Math.pow(Math.max(0,Math.sin(t*Math.PI*6)),3),n=Math.pow(Math.max(0,Math.sin(t*Math.PI*8+1)),3),r=Math.pow(Math.max(0,Math.sin(t*Math.PI*10+2)),3),a=Math.max(s,n,r)*Math.sin(t*Math.PI);return{position:[0,0,0],rotation:[0,0,0],scale:1+.08*a*i,glowIntensity:1+.5*a*i,glowBoost:2*a*i}}}},Mi={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:(t,e,i)=>(t.shimmerEffect=!0,t.shimmerProgress=e,!0),blend:(t,e,i)=>!1,"3d":{evaluate(t,e){const i=e?.strength||1,s=(.4*Math.sin(t*Math.PI*4)+.35*Math.sin(t*Math.PI*6+.5)+.25*Math.sin(t*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=((t,e="โจ")=>({name:t,emoji:e,type:"blending",description:`${t} 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:(t,e,i)=>!1,blend:(t,e,i)=>!1}))("groove","๐ต"),wi={},vi=[],Si=[],ki=[];function xi(t,e){wi[t.name]=t,e.push(t.name)}function Ei(t,e,i){Object.defineProperty(wi,t,{configurable:!0,enumerable:!0,get(){const i=e();return Object.defineProperty(wi,t,{configurable:!0,enumerable:!0,writable:!0,value:i}),i}}),i.push(t)}[lt,A,U,Gt,H,_,C,T,G,yi,Mi,W,bi,Dt,j,_t,Ht,nt,at,ot,ht,rt,V,N,Q,J,K,Z,$,L,It,$t,F,z,q,O,Ft,zt,qt,Ot,x,E,B,pe,me,ue,de,it,ct,dt,pt,mt,gt,st,tt,et].forEach(t=>xi(t,vi)),[xt,At,Ct,ft,Mt,bt,wt,Ce,re,Wt,Xt,Vt,Nt,Qt,ke,Tt,Pt,Ut,St,Kt,Lt,ie,se,ne,ee,te,fe,ye,Me,be,we,ve,Se,oe,he,le,ce,ae].forEach(t=>xi(t,Si)),Ei("lungeForward",()=>kt("forward"),Si),Ei("lungeBack",()=>kt("back"),Si),Ei("lungeLeft",()=>kt("left"),Si),Ei("lungeRight",()=>kt("right"),Si),Ei("lungeUp",()=>kt("up"),Si),Ei("lungeDown",()=>kt("down"),Si),Ei("recoilBack",()=>Zt("back"),Si),Ei("recoilForward",()=>Zt("forward"),Si),Ei("recoilLeft",()=>Zt("left"),Si),Ei("recoilRight",()=>Zt("right"),Si),Ei("recoilUp",()=>Zt("up"),Si),Ei("recoilDown",()=>Zt("down"),Si),Ei("oofLeft",()=>Jt("left"),Si),Ei("oofRight",()=>Jt("right"),Si),Ei("oofFront",()=>Jt("front"),Si),Ei("oofBack",()=>Jt("back"),Si),Ei("oofUp",()=>Jt("up"),Si),Ei("oofDown",()=>Jt("down"),Si),Ei("shatter",()=>Ee("default"),Si),Ei("shatterExplosive",()=>Ee("explosive"),Si),Ei("shatterCrumble",()=>Ee("crumble"),Si),Ei("shatterReform",()=>Ee("reform"),Si),Ei("shatterPunchLeft",()=>Ee("punchLeft"),Si),Ei("shatterPunchRight",()=>Ee("punchRight"),Si),Ei("shatterPunchFront",()=>Ee("punchFront"),Si),Ei("shatterSuspend",()=>Ee("suspend"),Si),Ei("shatterImplode",()=>Ee("implode"),Si),Ei("shatterGravity",()=>Ee("gravity"),Si),Ei("shatterOrbit",()=>Ee("orbit"),Si),Ei("dissolveUp",()=>Ae("up"),Si),Ei("dissolveDown",()=>Ae("down"),Si),Ei("dissolveLeft",()=>Ae("left"),Si),Ei("dissolveRight",()=>Ae("right"),Si),Ei("dissolveAway",()=>Ae("away"),Si),Ei("dissolveToward",()=>Ae("toward"),Si),Ei("rushForward",()=>vt("forward"),Si),Ei("rushBack",()=>vt("back"),Si),Ei("rushLeft",()=>vt("left"),Si),Ei("rushRight",()=>vt("right"),Si),Ei("rushUp",()=>vt("up"),Si),Ei("rushDown",()=>vt("down"),Si),[ii,Pe,Re,Fe,ze,qe,ai,Ne,gi,pi,di,ui,si,ni,mi,Te,oi,hi,_e,He,Ie,$e,Le,Ge,Je,Ke,Ze,ti,ei,ci,We,Ye,Xe,Ve,ri,li,Oe].forEach(t=>xi(t,ki)),Ei("magneticForward",()=>fi("forward"),ki),Ei("magneticBack",()=>fi("back"),ki),Ei("magneticLeft",()=>fi("left"),ki),Ei("magneticRight",()=>fi("right"),ki),Ei("magneticUp",()=>fi("up"),ki),Ei("magneticDown",()=>fi("down"),ki),Ei("magneticAttract",()=>fi("attract"),ki),Ei("magneticRepel",()=>fi("repel"),ki);const Bi={blending:vi,override:Si,effect:ki},Ai={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"]},Ci={};function Ti(t){return Ci[t]||"atmosphere"}function Pi(t){return wi[t]?wi[t]:k.getPluginGesture(t)||null}function Di(t){const e=Pi(t);return!!e&&"blending"===e.type}function Ri(t){const e=Pi(t);return!!e&&"override"===e.type}function Fi(t,e,i,s,n,r,a){const o=Pi(e);return!!o&&(o.apply&&o.apply(t,i,s,n,r,a),i>=1&&o.cleanup&&o.cleanup(t),!0)}function zi(){const t=[];return Object.values(wi).forEach(e=>{t.push({name:e.name,emoji:e.emoji||"๐ญ",type:e.type,category:Ci[e.name]||"atmosphere",description:e.description||"No description",source:"core",usesShatter:e.usesShatter||!1})}),k.getAllPluginGestures().forEach(e=>{const i=k.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}function qi(t){return wi[t]||null}function Oi(){return Object.keys(wi).filter(t=>{const e=Object.getOwnPropertyDescriptor(wi,t);return e&&"function"==typeof e.get})}Object.entries(Ai).forEach(([t,e])=>{e.forEach(e=>{Ci[e]=t})});var ji={GESTURE_REGISTRY:wi,GESTURE_TYPES:Bi,GESTURE_CATEGORIES:Ai,GESTURE_TO_CATEGORY:Ci,getGesture:Pi,getGestureCategory:Ti,isBlendingGesture:Di,isOverrideGesture:Ri,applyGesture:Fi,listGestures:zi,pluginAdapter:k},Ii=Object.freeze({__proto__:null,GESTURE_CATEGORIES:Ai,GESTURE_REGISTRY:wi,GESTURE_TO_CATEGORY:Ci,GESTURE_TYPES:Bi,applyGesture:Fi,default:ji,getGesture:Pi,getGestureCategory:Ti,getLazyGestureNames:Oi,isBlendingGesture:Di,isOverrideGesture:Ri,listGestures:zi,pluginAdapter:k,resolveGesture:qi,warmUpGestures:function({onBatch:t,onComplete:e}={}){const i=Object.keys(wi);t&&t(i.map(t=>({name:t,category:Ci[t]||"atmosphere",source:"core"})));try{const e=[];k.getAllPluginGestures().forEach(t=>{const i=k.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.length&&t&&t(e)}catch{}return e&&e(),Oi().map(t=>()=>qi(t))}});function $i(t){if(!t||0===t.length)return"#FFFFFF";let e=0,i=0;const s=[];for(const n of t)"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?e+=n.weight:i++);const n=Math.max(0,100-e),r=i>0?n/i:0,a=[];let o=0;for(const t of s)o+=null!==t.weight?t.weight:r,a.push({color:t.color,threshold:o});const h=Math.random()*o;for(const t of a)if(h<=t.threshold)return t.color;return s[s.length-1].color}var Li={name:"ambient",emoji:"โ๏ธ",description:"Gentle upward drift like smoke",initialize:function(t){t.vx=0,t.vy=-.04-.02*Math.random(),t.lifeDecay=.002,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={upwardSpeed:5e-4,waviness:0,friction:.998}},update:function(t,e,i,s){const n=t.behaviorData;t.vy*=Math.pow(n.friction,e),t.vy-=n.upwardSpeed*e,t.vx=0}};const Gi=2*Math.PI;var _i={name:"orbiting",emoji:"๐",description:"Romantic firefly dance around the orb",initialize:function(t){t.lifeDecay=.001+.002*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.isSparkle="#FFE4E1"===t.color||"#FFCCCB"===t.color||"#FFC0CB"===t.color;const e=40*(t.scaleFactor||1)*(1.3+.9*Math.random());t.blinkPhase=Math.random()*Gi,t.blinkSpeed=.3+1.2*Math.random(),t.blinkIntensity=.6+.4*Math.random(),t.fadePhase=Math.random()*Gi,t.fadeSpeed=.1+.3*Math.random(),t.minOpacity=.2+.2*Math.random(),t.maxOpacity=.8+.2*Math.random(),t.isSparkle&&(t.blinkSpeed*=2,t.blinkIntensity=1,t.minOpacity=0,t.maxOpacity=1),t.behaviorData={angle:Math.random()*Gi,radius:e,baseRadius:e,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(t,e,i,s){const n=t.behaviorData;n.angle+=n.angularVelocity*e;const r=Math.sin(n.angle*n.swaySpeed)*n.swayAmount,a=6*Math.sin(1.5*n.angle),o=(n.radius||n.baseRadius)+a+.2*r,h=i+Math.cos(n.angle)*o,l=s+Math.sin(n.angle)*o;n.floatOffset+=n.floatSpeed*e*.001;const c=Math.sin(n.floatOffset)*n.floatAmount;t.vx=.1*(h-t.x),t.vy=.1*(l+c-t.y),t.fadePhase+=t.fadeSpeed*e*.001;const u=.5*Math.sin(t.fadePhase)+.5,d=t.minOpacity+(t.maxOpacity-t.minOpacity)*u;let p;t.blinkPhase+=t.blinkSpeed*e*.002,t.isSparkle?(n.twinklePhase+=n.twinkleSpeed*e*.001,p=.7*Math.pow(Math.sin(n.twinklePhase),16)+.2*Math.sin(5*t.blinkPhase)+.1):p=.4*Math.sin(t.blinkPhase)+.3*Math.sin(3*t.blinkPhase)+.2*Math.sin(7*t.blinkPhase)+.1*Math.sin(11*t.blinkPhase);const m=.5*(p+1),g=.2+m*t.blinkIntensity*.8;t.opacity=t.baseOpacity*d*g,t.isSparkle?t.size=t.baseSize*(.5+1*m):t.size=t.baseSize*(.8+.3*m),t.isSparkle&&(t.tempColor=m>.85?"#FFFFFF":t.color)}},Hi={name:"rising",emoji:"๐",description:"Buoyant upward movement like balloons",initialize:function(t){t.vx=.02*(Math.random()-.5),t.vy=-.05-.03*Math.random(),t.lifeDecay=.002,t.baseOpacity=.7+.3*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={buoyancy:.001,driftAmount:.005}},update:function(t,e,i,s){const n=t.behaviorData;t.vy-=n.buoyancy*e,t.vx+=(Math.random()-.5)*n.driftAmount*e,t.vx*=Math.pow(.995,e),t.vy*=Math.pow(.998,e)}};function Ui(t){t.fallingData||(t.fallingData={originalX:t.x,originalY:t.y,originalOpacity:t.opacity??t.life??1,wobblePhase:Math.random()*Math.PI*2,wobbleSpeed:.3+.4*Math.random(),fallProgress:0}),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors));const e=Math.random(),i=Math.random(),s=e*Math.PI*2,n=2*i-1,r=Math.sqrt(1-n*n);t.behaviorData={fallSpeed:8,fallDistance:400,wobbleAmount:1.5,fallingDir:{x:r*Math.cos(s),y:n,z:r*Math.sin(s)},orbitDistanceRatio:.7+.4*Math.random()}}var Wi={name:"falling",emoji:"๐ง",description:"Heavy downward drift like tears",initialize:Ui,update:function(t,e,i,s){const n=t.behaviorData;let r=t.fallingData;r||(Ui(t),r=t.fallingData),r.fallProgress+=.02*e;const a=Math.min(r.fallProgress,1),o=n.fallDistance*a;r.wobblePhase+=r.wobbleSpeed*e*.1;const h=Math.sin(r.wobblePhase)*n.wobbleAmount;if(t.x=r.originalX+h,t.y=r.originalY+o,t.vx=.3*h,t.vy=10*n.fallSpeed,a>.6){const e=(a-.6)/.4;t.opacity=r.originalOpacity*(1-e),void 0!==t.life&&(t.life=r.originalOpacity*(1-e))}}};var Yi={name:"popcorn",emoji:"๐ฟ",description:"Spontaneous popping with gravity and bounces",initialize:function(t){if(t.vx=.1*(Math.random()-.5),t.vy=.1*(Math.random()-.5),t.lifeDecay=.008+.012*Math.random(),t.emotionColors&&t.emotionColors.length>0)t.color=$i(t.emotionColors);else{const e=["#FFFFFF","#FFFACD","#FFF8DC","#FFFFE0","#FAFAD2"];t.color=$i(e)}t.size=Math.random()<.3?(8+4*Math.random())*t.scaleFactor*t.particleSizeMultiplier:(2+4*Math.random())*t.scaleFactor*t.particleSizeMultiplier,t.baseSize=t.size,t.hasGlow=Math.random()<.2,t.glowSizeMultiplier=t.hasGlow?1.2:0,t.behaviorData={popDelay:2e3*Math.random(),hasPopped:!1,popStrength:3+5*Math.random(),gravity:.098,bounceDamping:.7,bounceCount:0,maxBounces:2+Math.floor(2*Math.random()),spinRate:10*(Math.random()-.5),lifetime:0}},update:function(t,e,i,s){const n=t.behaviorData;if(n.lifetime+=16.67*e,!n.hasPopped&&n.lifetime>n.popDelay){n.hasPopped=!0;const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*n.popStrength*1.5,t.vy=Math.sin(e)*n.popStrength-.3,t.size=1.25*t.baseSize}if(n.hasPopped){t.vy+=n.gravity*e;const i=s+100*t.scaleFactor;t.y>i&&n.bounceCount<n.maxBounces&&(t.y=i,t.vy=-Math.abs(t.vy)*n.bounceDamping,t.vx*=.9,n.bounceCount++,t.size=t.baseSize*(1.5-.1*n.bounceCount)),n.bounceCount>=n.maxBounces&&(t.lifeDecay=.03+.02*Math.random(),t.size*=.95),Math.sqrt(t.vx*t.vx+t.vy*t.vy)<.5&&(t.lifeDecay*=1.5)}}},Xi={name:"burst",emoji:"๐ฅ",description:"Explosive expansion from center",initialize:function(t){const e="suspicion"===t.emotion,i="surprise"===t.emotion,s="glitch"===t.emotion,n=Math.random()*Gi,r=e?1+.8*Math.random():i?7+5*Math.random():s?2+1.5*Math.random():3.5+2.5*Math.random();t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r,t.lifeDecay=e?.01:i?.006+.008*Math.random():s?.012:.015,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),e&&(t.size=(6+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.opacity=1,t.baseOpacity=t.opacity),t.behaviorData={isSuspicion:e,isSurprise:i,isGlitch:s,age:0,fadeStart:e?.3:.2,glitchPhase:Math.random()*Math.PI*2,glitchIntensity:s?.3:0,glitchFrequency:s?.1:0}},update:function(t,e,i,s){const n=t.behaviorData;if(n.isSurprise)if(n.age+=.016*e,n.age<.15){const i=.98;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}else if(n.age<.25){const i=.85;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}else{const i=.99;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e),t.vx+=.01*(Math.random()-.5)*e,t.vy+=.01*(Math.random()-.5)*e}else{const i=n.isSuspicion?.99:n.isGlitch?.97:.95;t.vx*=Math.pow(i,e),t.vy*=Math.pow(i,e)}if(n.isSuspicion){const i=.001*Date.now();t.vx+=.01*Math.sin(2*i+t.id)*e}if(n.isGlitch){n.age+=.016*e,n.glitchPhase+=n.glitchFrequency*e;const i=Math.sin(n.glitchPhase)*n.glitchIntensity*e,s=Math.cos(1.3*n.glitchPhase)*n.glitchIntensity*e;if(t.vx+=i,t.vy+=s,Math.random()<.02){const e=Math.random()*Math.PI*2,i=.5+.5*Math.random();t.vx+=Math.cos(e)*i,t.vy+=Math.sin(e)*i}}}},Vi={name:"aggressive",emoji:"โก",description:"Sharp, chaotic movement with violent bursts",initialize:function(t){const e=Math.random()*Gi,i=1.5+2*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.015,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={acceleration:.05,jitter:.3,speedDecay:.95}},update:function(t,e,i,s){const n=t.behaviorData;if(t.vx+=(Math.random()-.5)*n.jitter*e,t.vy+=(Math.random()-.5)*n.jitter*e,t.vx*=Math.pow(n.speedDecay,e),t.vy*=Math.pow(n.speedDecay,e),Math.random()<Math.min(.05*e,.5)){const e=Math.random()*Gi;t.vx+=Math.cos(e)*n.acceleration,t.vy+=Math.sin(e)*n.acceleration}}},Ni={name:"scattering",emoji:"๐จ",description:"Particles flee from center in panic",initialize:function(t){t.vx=0,t.vy=0,t.lifeDecay=.008,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={fleeSpeed:2,panicFactor:1.2,initialized:!1}},update:function(t,e,i,s){const n=t.behaviorData;if(!n.initialized){const e=t.x-i,r=t.y-s,a=Math.sqrt(e*e+r*r);if(a>0)t.vx=e/a*n.fleeSpeed,t.vy=r/a*n.fleeSpeed;else{const e=Math.random()*Gi;t.vx=Math.cos(e)*n.fleeSpeed,t.vy=Math.sin(e)*n.fleeSpeed}n.initialized=!0}const r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);o>0&&(t.vx+=r/o*n.panicFactor*.01*e,t.vy+=a/o*n.panicFactor*.01*e),t.vx+=.1*(Math.random()-.5)*e,t.vy+=.1*(Math.random()-.5)*e,t.vx*=Math.pow(.98,e),t.vy*=Math.pow(.98,e)}},Qi={name:"repelling",emoji:"๐ซ",description:"Particles pushed away from center, maintaining distance",initialize:function(t){t.vx=0,t.vy=0,t.lifeDecay=.01,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={repelStrength:.8,minDistance:50,initialized:!1}},update:function(t,e,i,s){const n=t.behaviorData,r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(!n.initialized||o<n.minDistance){if(o>0){const i=n.repelStrength/Math.max(o,5);t.vx+=r/o*i*e,t.vy+=a/o*i*e}n.initialized=!0}t.vx*=Math.pow(.99,e),t.vy*=Math.pow(.99,e)}},Ji={name:"connecting",emoji:"๐",description:"Chaotic movement with center attraction for social states",initialize:function(t){const e=Math.random()*Gi,i=2+5*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.012,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={attractionForce:.008,chaosFactor:1,friction:.95}},update:function(t,e,i,s){const n=t.behaviorData;t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e);const r=(i-t.x)*n.attractionForce,a=(s-t.y)*n.attractionForce,o=(Math.random()-.5)*n.chaosFactor,h=(Math.random()-.5)*n.chaosFactor;t.vx+=r+o,t.vy+=a+h}},Ki={name:"resting",emoji:"๐ด",description:"Ultra-slow vertical drift for deep rest states",initialize:function(t){t.vx=0,t.vy=-.01,t.lifeDecay=.001,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={upwardSpeed:2e-5,friction:.999}},update:function(t,e,i,s){const n=t.behaviorData;t.vy*=Math.pow(n.friction,e),t.vy-=n.upwardSpeed*e,t.vx=0}},Zi={name:"radiant",emoji:"โ๏ธ",description:"Particles radiate outward like sunbeams",initialize:function(t){const e=Math.random()*Gi,i=.8+.4*Math.random();if(t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.006,t.emotionColors&&t.emotionColors.length>0)t.color=$i(t.emotionColors);else{const e=["#FFD700","#FFB347","#FFA500","#FF69B4"];t.color=$i(e)}t.hasGlow=Math.random()<.7,t.glowSizeMultiplier=t.hasGlow?1.5+.5*Math.random():0,t.behaviorData={radialSpeed:.02,shimmer:Math.random()*Gi,shimmerSpeed:.1,friction:.99}},update:function(t,e,i,s){const n=t.behaviorData,r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(o>0){const i=r/o,s=a/o;t.vx+=i*n.radialSpeed*e,t.vy+=s*n.radialSpeed*e}n.shimmer+=n.shimmerSpeed*e;const h=Math.sin(n.shimmer);t.size=t.baseSize*(1+.2*h),t.opacity=t.baseOpacity*(1+.3*h),t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e)}};function ts(t){t.vx=.02*(Math.random()-.5),t.vy=-.03-.02*Math.random(),t.lifeDecay=8e-4,t.size=(6+6*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1)*1.33,t.baseSize=t.size,t.baseOpacity=.2+.2*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={ascensionSpeed:3e-4,waveFactor:.5,waveFrequency:.001,friction:.998,fadeStartDistance:100}}var es={name:"ascending",emoji:"๐ง",description:"Slow steady upward float like incense smoke",initialize:ts,update:function(t,e,i,s){const n=t.behaviorData;if(!n)return void ts(t);t.vx*=Math.pow(n.friction,e),t.vy*=Math.pow(n.friction,e),t.vy-=n.ascensionSpeed*e;const r=Math.sin(t.age*n.waveFrequency*1e3)*n.waveFactor;t.vx+=.001*r*e,void 0===t.initialY&&(t.initialY=t.y);const a=t.initialY-t.y;if(a>n.fadeStartDistance){const e=(a-n.fadeStartDistance)/100,i=Math.max(0,1-e);t.baseOpacity*=.995,i<.5&&(t.lifeDecay*=1.02)}Math.abs(t.vx)>.05&&(t.vx*=Math.pow(.95,e)),t.vy<-.1&&(t.vy=-.1)}},is={name:"erratic",emoji:"๐ฐ",description:"Nervous jittery movement for anxious states",initialize:function(t){const e=Math.random()*Gi,i=.1+.15*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.004,t.size=(2+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.baseOpacity=.4+.3*Math.random(),t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={jitterStrength:.02,directionChangeRate:.1,speedVariation:.3,spinRate:.05+.1*Math.random()}},update:function(t,e){const i=t.behaviorData;if(t.vx+=(Math.random()-.5)*i.jitterStrength*e,t.vy+=(Math.random()-.5)*i.jitterStrength*e,Math.random()<Math.min(i.directionChangeRate*e,.5)){const e=Math.random()*Gi,i=Math.sqrt(t.vx*t.vx+t.vy*t.vy);t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i}const s=1+(Math.random()-.5)*i.speedVariation*e;t.vx*=s,t.vy*=s;const n=t.age*i.spinRate*1e3;t.size=t.baseSize*(1+.2*Math.sin(n)),t.opacity=t.baseOpacity*(.8+.4*Math.random()),t.vx*=Math.pow(.98,e),t.vy*=Math.pow(.98,e);const r=Math.sqrt(t.vx*t.vx+t.vy*t.vy);r>.5&&(t.vx=t.vx/r*.5,t.vy=t.vy/r*.5)}},ss={name:"cautious",emoji:"๐คจ",description:"Slow careful movement with watchful pauses",initialize:function(t){const e=Math.random()*Gi,i=.02+.03*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,t.lifeDecay=.001,t.life=1,t.size=(4+4*Math.random())*(t.scaleFactor||1)*(t.particleSizeMultiplier||1),t.baseSize=t.size,t.baseOpacity=.8+.2*Math.random(),t.opacity=t.baseOpacity,t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.behaviorData={pauseTimer:2*Math.random(),pauseDuration:.5+.5*Math.random(),moveDuration:1+.5*Math.random(),isMoving:Math.random()>.5,moveTimer:0,originalVx:t.vx,originalVy:t.vy,watchRadius:50+30*Math.random()}},update:function(t,e,i,s){const n=t.behaviorData;if(n.moveTimer+=e,n.isMoving)n.moveTimer>n.moveDuration?(n.isMoving=!1,n.moveTimer=0,t.vx=0,t.vy=0):(t.vx=n.originalVx,t.vy=n.originalVy);else if(n.moveTimer>n.pauseDuration){n.isMoving=!0,n.moveTimer=0;const e=Math.random()*Gi,i=.02+.03*Math.random();t.vx=Math.cos(e)*i,t.vy=Math.sin(e)*i,n.originalVx=t.vx,n.originalVy=t.vy}const r=t.x-i,a=t.y-s,o=Math.sqrt(r*r+a*a);if(o>n.watchRadius){const i=.02;t.vx-=r/o*i*e,t.vy-=a/o*i*e}t.vx*=Math.pow(.995,e),t.vy*=Math.pow(.995,e),n.isMoving?t.opacity=t.baseOpacity:t.opacity=t.baseOpacity*(.9+.1*Math.sin(5*t.age))}},ns={name:"surveillance",emoji:"๐๏ธ",description:"Searchlight scanning with paranoid watchfulness",initialize(t,e){t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.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:t.x,y:t.y}};const i=Math.random();i<.7?t.behaviorState.primaryRole="scanner":i<.9?(t.behaviorState.primaryRole="patroller",t.behaviorState.mode="patrolling"):(t.behaviorState.primaryRole="watcher",t.behaviorState.mode="frozen")},update(t,e,i){const s=t.behaviorState;if(s){switch(s.modeTimer+=16*e,s.modeTimer>s.nextModeChange&&(this.changeMode(t,s,i),s.modeTimer=0,s.nextModeChange=2e3+4e3*Math.random()),s.mode){case"scanning":this.updateScanning(t,e,s,i);break;case"darting":this.updateDarting(t,e,s,i);break;case"frozen":this.updateFrozen(t,e,s,i);break;case"patrolling":this.updatePatrolling(t,e,s,i)}t.vy+=.05*e,t.x+=t.vx*e,t.y+=t.vy*e,s.lastPosition.x=t.x,s.lastPosition.y=t.y}},updateScanning(t,e,i,s){i.pauseTimer>0?(i.pauseTimer-=16*e,t.vx*=.9,t.vy*=.9):(i.scanAngle+=i.scanDirection*i.scanSpeed*e*.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,r=.8+.5*i.alertLevel;t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r*.3},updateDarting(t,e,i,s){const n=i.dartTarget.x-t.x,r=i.dartTarget.y-t.y,a=Math.sqrt(n*n+r*r);a>5?(t.vx=n/a*i.dartSpeed,t.vy=r/a*i.dartSpeed):(i.mode="scanning",i.modeTimer=0)},updateFrozen(t,e,i,s){t.vx*=.95,t.vy*=.95,Math.random()<.01&&(t.vx+=.5*(Math.random()-.5),t.vy+=.5*(Math.random()-.5))},updatePatrolling(t,e,i,s){i.patrolAngle+=.01*e;const n=s.corePosition?.x??s.canvasWidth/2,r=s.corePosition?.y??s.canvasHeight/2,a=n+Math.cos(i.patrolAngle)*i.patrolRadius,o=r+Math.sin(i.patrolAngle)*i.patrolRadius,h=a-t.x,l=o-t.y;t.vx=.02*h,t.vy=.02*l},changeMode(t,e,i){const s=Math.random(),n=i?.corePosition?.x??(i?.canvasWidth/2||t.x),r=i?.corePosition?.y??(i?.canvasHeight/2||t.y);"scanner"===e.primaryRole?s<.1?(e.mode="darting",e.dartTarget={x:n+200*(Math.random()-.5),y:r+200*(Math.random()-.5)},e.dartSpeed=3+2*Math.random()):e.mode=s<.2?"frozen":"scanning":"patroller"===e.primaryRole?e.mode=s<.1?"frozen":"patrolling":e.mode=s<.3?"scanning":"frozen"}},rs={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(t,e,i,s){t.emotionColors&&t.emotionColors.length>0&&(t.color=$i(t.emotionColors)),t.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},t.lifeDecay=.0015,t.hasGlow=!0,t.glowSizeMultiplier=3+2*Math.random()},update(t,e,i,s){const n=t.behaviorState;if(!n)return;n.glitchTimer+=16*e,n.stutterTimer+=16*e,n.stutterTimer>n.nextStutter&&(n.isFrozen?(n.isFrozen=!1,n.stutterTimer=0,n.nextStutter=100+300*Math.random(),Math.random()<.3&&(t.x+=60*(Math.random()-.5),t.y+=60*(Math.random()-.5))):(n.isFrozen=!0,n.frozenPosition={x:t.x,y:t.y},n.frozenVelocity={x:t.vx,y:t.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&&t.emotionColors&&(t.color=$i(t.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*e;const r=.5*Math.sin(n.beatPhase)+.5;if(n.beatPhase%(4*Math.PI)<.5*Math.PI?n.dropIntensity=Math.min(1,n.dropIntensity+.1*e):n.dropIntensity=Math.max(0,n.dropIntensity-.05*e),n.isFrozen)t.vx=.5*(Math.random()-.5),t.vy=.5*(Math.random()-.5);else{n.orbitAngle+=n.orbitSpeed*e*(1+.5*r);const a=n.orbitRadius*(1+.3*n.dropIntensity*Math.sin(4*n.beatPhase));let o=i+Math.cos(n.orbitAngle)*a,h=s+Math.sin(n.orbitAngle)*a*.6;if(n.isGlitching&&(o+=n.glitchOffset.x*Math.random()*.8,h+=n.glitchOffset.y*Math.random()*.8),n.rgbSplit){const t=3*(1+n.dropIntensity);o+=Math.sin(n.rgbPhase)*t,h+=Math.cos(n.rgbPhase)*t,n.rgbPhase+=.1*e}n.dropIntensity>.8&&Math.random()<.1&&(o+=30*(Math.random()-.5),h+=30*(Math.random()-.5));const l=n.isGlitching?.02:.03;t.vx=(o-t.x)*l,t.vy=(h-t.y)*l,t.vx+=(Math.random()-.5)*r*2,t.vy+=(Math.random()-.5)*r*2}t.x+=t.vx*e,t.y+=t.vy*e,Math.random()<.02&&(t.opacity=.1+.9*Math.random()),t.size=t.baseSize*(1+.3*r+.5*n.dropIntensity)}},as={name:"spaz",description:"Ultra-aggressive particles with explosive spread and chaotic motion",initialize(t,e,i,s){t.x=i,t.y=s,t.life=1,t.size=3+4*Math.random();const n=Math.random()*Math.PI*2,r=200+300*Math.random();t.vx=Math.cos(n)*r,t.vy=Math.sin(n)*r,t.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()},t.lifeDecay=8e-4,t.hasGlow=!0,t.glowSizeMultiplier=4+3*Math.random(),t.glowIntensity=1.5+.5*Math.random()},update(t,e,i,s){const n=t.behaviorState;if(n.explosionTimer+=e,n.chaosTimer+=e,0===n.explosionPhase&&n.explosionTimer<500)t.vx*=.98,t.vy*=.98,Math.random()<.1&&(t.vx+=100*(Math.random()-.5),t.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 e=Math.cos(n.chaosAngle)*n.chaosSpeed,i=Math.sin(n.chaosAngle)*n.chaosSpeed;if(t.vx=.7*t.vx+.3*e,t.vy=.7*t.vy+.3*i,n.zigzagPattern){const e=.01*n.chaosTimer;t.vx+=20*Math.sin(e),t.vy+=20*Math.cos(e)}if(n.spiralPattern){const e=.005*n.chaosTimer,i=50+30*Math.sin(.003*n.chaosTimer);t.vx+=Math.cos(e)*i*.1,t.vy+=Math.sin(e)*i*.1}}if(Math.random()<n.teleportChance){const e=Math.random()*Math.PI*2,n=200+400*Math.random();t.x=i+Math.cos(e)*n,t.y=s+Math.sin(e)*n,t.vx=200*(Math.random()-.5),t.vy=200*(Math.random()-.5)}if(t.x+=t.vx*(e/1e3),t.y+=t.vy*(e/1e3),n.sizePulse){n.sizePulsePhase+=n.sizePulseSpeed*e;const i=1+.5*Math.sin(n.sizePulsePhase);t.size=(3+4*Math.random())*i}n.colorShift&&(n.colorShiftPhase=(n.colorShiftPhase||0)+n.colorShiftSpeed*e),t.vx*=.995,t.vy*=.995,t.life-=t.lifeDecay*e,(t.life<=0||Math.abs(t.x-i)>2e3||Math.abs(t.y-s)>2e3)&&(t.life=0)},getSpawnPosition(t,e){const i=Math.random()*Math.PI*2,s=100+200*Math.random();return{x:t+Math.cos(i)*s,y:e+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}]})},os={name:"directed",emoji:"๐ฏ",description:"Focused, straight-line movement toward target",config:{speed:3,acceleration:.15,focusStrength:.8,randomness:.1,edgeBuffer:50},initialize(t,e,i,s,n){const r=e-t.x,a=i-t.y,o=Math.sqrt(r*r+a*a);if(o>0)t.vx=r/o*this.config.speed,t.vy=a/o*this.config.speed;else{const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*this.config.speed,t.vy=Math.sin(e)*this.config.speed}t.targetX=e,t.targetY=i,t.directedPhase=0},update(t,e,i,s,n,r){t.directedPhase+=.05*e;const a=t.targetX-t.x,o=t.targetY-t.y,h=Math.sqrt(a*a+o*o);if(h>10){const i=a/h*this.config.speed,s=o/h*this.config.speed;t.vx+=(i-t.vx)*this.config.acceleration*e,t.vy+=(s-t.vy)*this.config.acceleration*e,t.vx+=(Math.random()-.5)*this.config.randomness,t.vy+=(Math.random()-.5)*this.config.randomness}else{const e=Math.random()*Math.PI*2,a=100+200*Math.random();t.targetX=i+Math.cos(e)*a,t.targetY=s+Math.sin(e)*a,t.targetX=Math.max(this.config.edgeBuffer,Math.min(n-this.config.edgeBuffer,t.targetX)),t.targetY=Math.max(this.config.edgeBuffer,Math.min(r-this.config.edgeBuffer,t.targetY))}t.x+=t.vx*e,t.y+=t.vy*e,(t.x<=0||t.x>=n)&&(t.vx*=-.8,t.x=Math.max(0,Math.min(n,t.x)),t.targetX=i+300*(Math.random()-.5)),(t.y<=0||t.y>=r)&&(t.vy*=-.8,t.y=Math.max(0,Math.min(r,t.y)),t.targetY=s+300*(Math.random()-.5))},visuals:{trailLength:"medium",opacity:.9,sizeMultiplier:1,blurAmount:.2}},hs={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(t,e,i,s,n){t.vx=2*(Math.random()-.5),t.vy=-this.config.baseRiseSpeed-2*Math.random(),t.wobblePhase=Math.random()*Math.PI*2,t.wobbleSpeed=this.config.wobbleFrequency*(.8+.4*Math.random()),t.bubbleSize=.5+.5*Math.random(),t.popTimer=0,t.isFizzing=!0},update(t,e,i,s,n,r){t.wobblePhase+=t.wobbleSpeed*e;const a=Math.sin(t.wobblePhase)*this.config.wobbleAmplitude;if(t.vx=.05*a+(Math.random()-.5)*this.config.fizziness,t.vy+=this.config.gravity*e,t.vy+=(Math.random()-.5)*this.config.fizziness,Math.random()<this.config.popChance){const e=Math.random()*Math.PI*2;t.vx=Math.cos(e)*this.config.popForce,t.vy=Math.sin(e)*this.config.popForce*.7,t.popTimer=1,t.bubbleSize=.3+.7*Math.random()}t.popTimer>0&&(t.popTimer-=.05*e,t.vx*=.95,t.vy*=.95),t.x+=t.vx*e,t.y+=t.vy*e,t.y<-50&&(t.y=r+50,t.x=i+300*(Math.random()-.5),t.vy=-this.config.baseRiseSpeed-2*Math.random(),t.bubbleSize=.5+.5*Math.random()),(t.x<=0||t.x>=n)&&(t.vx*=-.5,t.x=Math.max(0,Math.min(n,t.x))),t.y>r+50&&(t.y=r,t.vy=1.5*-this.config.baseRiseSpeed),t.size=t.baseSize*t.bubbleSize*(1+.1*Math.sin(2*t.wobblePhase))},visuals:{trailLength:"short",opacity:.6,sizeMultiplier:1.2,blurAmount:.5,sparkle:!0}};const ls=new Map;var cs={registerPluginBehavior:function(t,e){return ls.has(t),!(!e.initialize||"function"!=typeof e.initialize||!e.update||"function"!=typeof e.update||(ls.set(t,{name:t,emoji:e.emoji||"๐",description:e.description||`Plugin behavior: ${t}`,initialize:e.initialize,update:e.update,isPlugin:!0}),0))},unregisterPluginBehavior:function(t){return!!ls.has(t)&&(ls.delete(t),!0)},getPluginBehavior:function(t){return ls.get(t)||null},getAllPluginBehaviors:function(){return Array.from(ls.keys())},createLegacyAdapter:function(t){return{name:t.name||"legacy",emoji:"๐",description:t.description||"Legacy plugin behavior",initialize(e){if(t.size&&(e.size="object"==typeof t.size?t.size.min+Math.random()*(t.size.max-t.size.min):t.size,e.baseSize=e.size),t.speed){const i="object"==typeof t.speed?t.speed.min+Math.random()*(t.speed.max-t.speed.min):t.speed,s=Math.random()*Math.PI*2;e.vx=Math.cos(s)*i,e.vy=Math.sin(s)*i}if(t.lifespan){const i="object"==typeof t.lifespan?t.lifespan.min+Math.random()*(t.lifespan.max-t.lifespan.min):t.lifespan;e.lifeDecay=1e3/i}t.color&&(e.color=Array.isArray(t.color)?$i(t.color):t.color),t.opacity&&(e.life="object"==typeof t.opacity?t.opacity.min+Math.random()*(t.opacity.max-t.opacity.min):t.opacity),e.behaviorData={movementType:t.movementType||"linear",turbulence:t.turbulence||0,drift:t.drift||0,acceleration:t.acceleration||0,...t.customData}},update(e,i,s,n){const r=e.behaviorData;switch(r.movementType){case"wander":e.vx+=(Math.random()-.5)*r.turbulence*i,e.vy+=(Math.random()-.5)*r.turbulence*i;break;case"fall":e.vy+=.1*i,e.vx+=(Math.random()-.5)*r.drift*i;break;case"rain":e.vy+=r.acceleration*i;break;case"orbit":{const t=e.x-s,r=e.y-n,a=Math.sqrt(t*t+r*r);if(a>0){const o=Math.atan2(r,t)+.02*i;e.x=s+Math.cos(o)*a,e.y=n+Math.sin(o)*a}break}}t.customUpdate&&t.customUpdate(e,i,s,n)}}}};const us={};function ds(t){return us[t]?us[t]:cs.getPluginBehavior(t)||null}function ps(t,e){const i=ds(e);return i&&i.initialize?(i.initialize(t),!0):"ambient"!==e&&ps(t,"ambient")}function ms(t,e,i,s,n){const r=ds(e);return!(!r||!r.update||(r.update(t,i,s,n),0))}function gs(){return[...Object.values(us).map(t=>({name:t.name,emoji:t.emoji||"๐ฏ",description:t.description||"No description",type:"core"})),...cs.getAllPluginBehaviors().map(t=>{const e=cs.getPluginBehavior(t);return{name:e.name,emoji:e.emoji||"๐",description:e.description||"Plugin behavior",type:"plugin"}})]}[Li,os,hs,_i,Hi,Wi,Yi,Xi,Vi,Ni,Qi,Ji,Ki,Zi,es,is,ss,ns,rs,as].forEach(t=>{us[t.name]=t}),"undefined"!=typeof window&&window.DEBUG_PARTICLES&&(window.ParticleBehaviors={registry:us,list:gs,get:ds});var fs={BEHAVIOR_REGISTRY:us,getBehavior:ds,initializeBehavior:ps,updateBehavior:ms,listBehaviors:gs,pluginAdapter:cs},ys=Object.freeze({__proto__:null,BEHAVIOR_REGISTRY:us,default:fs,getBehavior:ds,initializeBehavior:ps,listBehaviors:gs,pluginAdapter:cs,updateBehavior:ms});class Ms{constructor(){this.listeners=new Map,this.groups=new Map,this.stats={registered:0,removed:0,active:0},this.u={},this.p=new Map}addEventListener(t,e,i,s={},n="default"){const r=this.generateId(),a={id:r,target:t,eventType:e,handler:i,options:s,group:n,active:!0};return this.listeners.set(r,a),this.groups.has(n)||this.groups.set(n,new Set),this.groups.get(n).add(r),t.addEventListener(e,i,s),this.stats.registered++,this.stats.active++,r}removeEventListener(t){const e=this.listeners.get(t);if(!e||!e.active)return!1;e.target.removeEventListener(e.eventType,e.handler,e.options),e.active=!1;const i=this.groups.get(e.group);return i&&(i.delete(t),0===i.size&&this.groups.delete(e.group)),this.listeners.delete(t),this.stats.removed++,this.stats.active--,!0}removeGroup(t){const e=this.groups.get(t);if(!e)return 0;let i=0;for(const t of e)this.removeEventListener(t)&&i++;return i}removeAllForTarget(t){let e=0;for(const[i,s]of this.listeners.entries())s.target===t&&s.active&&this.removeEventListener(i)&&e++;return e}removeAllOfType(t){let e=0;for(const[i,s]of this.listeners.entries())s.eventType===t&&s.active&&this.removeEventListener(i)&&e++;return e}removeAll(){let t=0;for(const[e,i]of this.listeners.entries())i.active&&this.removeEventListener(e)&&t++;return t}createAutoRemove(t,e,i,s={}){const n=this.addEventListener(t,e,i,s);return{id:n,remove:()=>this.removeEventListener(n)}}once(t,e,i,s={}){const n=this.addEventListener(t,e,t=>{i(t),this.removeEventListener(n)},s);return n}debounced(t,e,i,s=250,n={}){let r;return this.addEventListener(t,e,t=>{clearTimeout(r),r=setTimeout(()=>i(t),s)},n)}throttled(t,e,i,s=100,n={}){let r=!1;return this.addEventListener(t,e,t=>{r||(i(t),r=!0,setTimeout(()=>{r=!1},s))},n)}on(t,e){this.p.has(t)||this.p.set(t,[]),this.p.get(t).push(e)}off(t,e){const i=this.p.get(t);if(!i)return;const s=i.indexOf(e);-1!==s&&i.splice(s,1),0===i.length&&this.p.delete(t)}emit(t,e=null){const i=this.p.get(t);if(i)for(let t=0;t<i.length;t++)try{i[t](e)}catch(t){}}removeAllListeners(t=null){if(t){const e=this.p.get(t),i=e?e.length:0;return this.p.delete(t),i}let e=0;for(const t of this.p.values())e+=t.length;return this.p.clear(),e}listenerCount(t){const e=this.p.get(t);return e?e.length:0}getEventNames(){return Array.from(this.p.keys())}getEventStats(){let t=0;for(const e of this.p.values())t+=e.length;return{domListeners:this.stats.active,emitterEvents:this.p.size,emitterListeners:t}}getDebugInfo(){const t={};for(const[e,i]of this.p)t[e]=i.length;return{domStats:this.getStats(),emitterEvents:t,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 t=[];for(const[e,i]of this.listeners.entries())i.active&&t.push({id:e,eventType:i.eventType,group:i.group,target:i.target.constructor.name});return t}analyzeLeaks(){const t={totalListeners:this.listeners.size,activeListeners:this.stats.active,inactiveButNotRemoved:0,byTarget:new Map,byType:new Map,potentialLeaks:[]};for(const[e,i]of this.listeners.entries()){const s=i.target.constructor.name;t.byTarget.set(s,(t.byTarget.get(s)||0)+1),t.byType.set(i.eventType,(t.byType.get(i.eventType)||0)+1),i.active||(t.inactiveButNotRemoved++,t.potentialLeaks.push({id:e,eventType:i.eventType,target:s}))}return t.byTarget=Object.fromEntries(t.byTarget),t.byType=Object.fromEntries(t.byType),t}cleanup(){let t=0;for(const[e,i]of this.listeners.entries())i.active||(this.listeners.delete(e),t++);return t}destroy(){const t=this.removeAll();return this.listeners.clear(),this.groups.clear(),this.p.clear(),this.u=null,this.stats={registered:0,removed:0,active:0},t}}const bs=new Ms,ws={NONE:0,ERROR:1,WARN:2,INFO:3,DEBUG:4,TRACE:5},vs=new class{constructor(t={}){this.config={enabled:!1!==t.enabled,level:t.level||ws.INFO,enableProfiling:!1!==t.enableProfiling,enableErrorTracking:!1!==t.enableErrorTracking,enableMemoryTracking:!1!==t.enableMemoryTracking,maxLogEntries:t.maxLogEntries||1e3,maxProfileEntries:t.maxProfileEntries||500,...t},this.m=new Array(t.maxLogEntries||1e3),this.M=0,this.v=0,this.errors=[],this.profiles=new Map,this.memorySnapshots=[],this.maxFrameTimings=120,this.S=new Array(this.maxFrameTimings),this.k=0,this.B=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 e=(()=>{}).bind(console);this.A={ERROR:e,WARN:e,DEBUG:e,TRACE:e,DEFAULT:e},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",t=>{this.trackError("UNHANDLED_ERROR",t.error||new Error(t.message),{filename:t.filename,lineno:t.lineno,colno:t.colno})}),window.addEventListener("unhandledrejection",t=>{this.trackError("UNHANDLED_REJECTION",t.reason,{promise:t.promise})}))}log(t,e,i=null){if(!this.config.enabled)return;if((ws[t]||ws.INFO)>this.config.level)return;const s=this.now(),n={timestamp:s,level:t,message:e,data:i,stackTrace:this.getStackTrace()};if(this.m[this.M]=n,this.M=(this.M+1)%this.config.maxLogEntries,this.v<this.config.maxLogEntries&&this.v++,this.capabilities.console){const n=this.getConsoleMethod(t),r=`[${(s/1e3).toFixed(3)}s]`;i?n(`${r} [${t}] ${e}`,i):n(`${r} [${t}] ${e}`)}}getConsoleMethod(t){return this.A[t]||this.A.DEFAULT}getStackTrace(){if(!this.capabilities.stackTrace)return null;try{throw new Error}catch(t){return t.stack}}trackError(t,e,i={}){if(!this.config.enableErrorTracking)return;const s={timestamp:this.now(),type:t,message:e.message||String(e),stack:e.stack,context:i,count:1},n=`${t}:${e.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(t,s),this.log("ERROR",`${t}: ${e.message}`,{error:s,context:i})}startProfile(t,e={}){if(!this.config.enableProfiling)return;const i={name:t,startTime:this.now(),metadata:e,samples:[],isActive:!0};this.profiles.set(t,i),this.log("TRACE",`Started profiling: ${t}`,e)}profileSample(t,e,i=null){if(!this.config.enableProfiling)return;const s=this.profiles.get(t);if(!s||!s.isActive)return;const n={timestamp:this.now(),label:e,data:i,relativeTime:this.now()-s.startTime};s.samples.push(n)}endProfile(t){if(!this.config.enableProfiling)return null;const e=this.profiles.get(t);if(!e||!e.isActive)return null;if(e.endTime=this.now(),e.duration=e.endTime-e.startTime,e.isActive=!1,e.stats=this.calculateProfileStats(e),this.log("TRACE",`Ended profiling: ${t}`,{duration:e.duration,samples:e.samples.length,stats:e.stats}),this.profiles.size>this.config.maxProfileEntries){const t=this.profiles.keys().next().value;this.profiles.delete(t)}return{...e}}calculateProfileStats(t){if(0===t.samples.length)return{sampleCount:0};const e=[];for(let i=1;i<t.samples.length;i++)e.push(t.samples[i].relativeTime-t.samples[i-1].relativeTime);if(0===e.length)return{sampleCount:t.samples.length};const i=e.reduce((t,e)=>t+e,0)/e.length,s=Math.min(...e),n=Math.max(...e);return{sampleCount:t.samples.length,avgSampleDuration:i,minSampleDuration:s,maxSampleDuration:n,totalDuration:t.duration}}trackFrameTiming(t){this.config.enableProfiling&&(this.S[this.k]={timestamp:this.now(),frameTime:t,fps:1e3/t},this.k=(this.k+1)%this.maxFrameTimings,this.B<this.maxFrameTimings&&this.B++)}C(t,e,i,s,n=0){const r=n>0?Math.min(n,i):i,a=new Array(r),o=(e-r+s)%s;for(let e=0;e<r;e++)a[e]=t[(o+e)%s];return a}takeMemorySnapshot(t="snapshot"){if(!this.config.enableMemoryTracking||!this.capabilities.memory)return;const e={timestamp:this.now(),label:t,memory:{usedJSHeapSize:performance.memory.usedJSHeapSize,totalJSHeapSize:performance.memory.totalJSHeapSize,jsHeapSizeLimit:performance.memory.jsHeapSizeLimit}};this.memorySnapshots.push(e),this.memorySnapshots.length>100&&this.memorySnapshots.shift(),this.log("DEBUG",`Memory snapshot: ${t}`,e.memory)}getDebugReport(){return{timestamp:this.now(),uptime:this.now()-0,config:this.config,capabilities:this.capabilities,logCount:this.v,recentLogs:this.C(this.m,this.M,this.v,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(t=>t.isActive).length,completedProfiles:Array.from(this.profiles.values()).filter(t=>!t.isActive).length,frameTimings:this.getFrameTimingStats(),memorySnapshots:this.memorySnapshots.slice(-5)}}getFrameTimingStats(){if(0===this.B)return{sampleCount:0};const t=this.C(this.S,this.k,this.B,this.maxFrameTimings),e=t.map(t=>t.frameTime),i=t.map(t=>t.fps);return{sampleCount:this.B,avgFrameTime:e.reduce((t,e)=>t+e,0)/e.length,minFrameTime:Math.min(...e),maxFrameTime:Math.max(...e),avgFPS:i.reduce((t,e)=>t+e,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.C(this.m,this.M,this.v,this.config.maxLogEntries),errors:[...this.errors],profiles:Object.fromEntries(this.profiles),frameTimings:this.C(this.S,this.k,this.B,this.maxFrameTimings),memorySnapshots:[...this.memorySnapshots],errorCounts:Object.fromEntries(this.errorCounts)}}clear(){this.m.fill(void 0),this.M=0,this.v=0,this.errors=[],this.profiles.clear(),this.S.fill(void 0),this.k=0,this.B=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:ws.INFO}),Ss=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 t=document.createElement("canvas");return!(!t.getContext("webgl")&&!t.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 t={},e=performance.now();t.jsExecutionSpeed=performance.now()-e;try{const e=document.createElement("canvas");e.width=100,e.height=100;const i=e.getContext("2d"),s=performance.now();for(let t=0;t<1e3;t++)i.fillRect(100*Math.random(),100*Math.random(),10,10);t.canvasPerformance=performance.now()-s}catch{t.canvasPerformance=null}return t}getCapabilities(){return{...this.capabilities}}getPerformance(){return{...this.performance}}generateReport(){const t=Object.entries(this.capabilities).filter(([,t])=>t).map(([t])=>t),e=Object.entries(this.capabilities).filter(([,t])=>!t).map(([t])=>t),i=t.length/Object.keys(this.capabilities).length*100;return{timestamp:Date.now(),userAgent:navigator.userAgent,supportedFeatures:t,unsupportedFeatures:e,supportPercentage:Math.round(i),performance:this.performance,recommendations:this.generateRecommendations(i)}}generateRecommendations(t){const e=[];return t<50&&e.push("Consider using the minimal build for better compatibility"),this.capabilities.webGL||e.push("WebGL not supported - advanced graphics features unavailable"),this.capabilities.webWorkers||e.push("Web Workers not supported - background processing unavailable"),this.capabilities.fetch||e.push("Fetch API not supported - consider using XMLHttpRequest polyfill"),this.performance.jsExecutionSpeed>50&&e.push("Slow JavaScript execution detected - consider performance optimizations"),this.performance.canvasPerformance>100&&e.push("Slow canvas performance detected - consider reducing visual complexity"),e}};class ks{constructor(t){this.canvas=t,this.ctx=t.getContext("2d",{alpha:!0,desynchronized:!1,willReadFrequently:!1}),this.ctx||(this.T=!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.T){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 t=parseInt(this.canvas.getAttribute("width"),10),e=parseInt(this.canvas.getAttribute("height"),10),i=this.canvas.getBoundingClientRect(),s=i.width,n=i.height;t>1.5*s||e>1.5*n?(this.width=s,this.height=n,this.canvas.width=t,this.canvas.height=e,this.ctx.setTransform(1,0,0,1,0,0),this.ctx.scale(this.dpr,this.dpr)):(this.width=t,this.height=e,this.canvas.width=t,this.canvas.height=e)}else{const t=this.canvas.getBoundingClientRect();this.width=t.width,this.height=t.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(t=>{try{t(this.width,this.height,this.dpr)}catch{}})}}onResize(t){"function"==typeof t&&this.resizeCallbacks.push(t)}handleResize(){clearTimeout(this.resizeTimeout),this.resizeTimeout=setTimeout(()=>{this.renderSize&&this.renderSize.width&&this.renderSize.height||this.resize()},100)}setRenderSize(t,e){this.renderSize={width:t,height:e},this.resize()}clear(){this.T||this.ctx.clearRect(0,0,this.width,this.height)}getCenter(){return{x:this.centerX,y:this.centerY}}setTransform(t=0,e=0,i=1,s=0){this.T||(this.ctx.save(),this.ctx.translate(t,e),this.ctx.rotate(s),this.ctx.scale(i,i))}restoreTransform(){this.T||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 xs(t){return 3===(t=t.replace("#","")).length&&(t=t.split("").map(t=>t+t).join("")),{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16)}}function Es(t,e,i){const s=t=>{const e=Math.round(Math.max(0,Math.min(255,t))).toString(16);return 1===e.length?`0${e}`:e};return`#${s(t)}${s(e)}${s(i)}`}function Bs(t,e,i){t/=255,e/=255,i/=255;const s=Math.max(t,e,i),n=Math.min(t,e,i),r=(s+n)/2;let a,o;if(s===n)a=o=0;else{const h=s-n;switch(o=r>.5?h/(2-s-n):h/(s+n),s){case t:a=(e-i)/h+(e<i?6:0);break;case e:a=(i-t)/h+2;break;case i:a=(t-e)/h+4}a/=6}return{h:360*a,s:100*o,l:100*r}}function As(t,e,i){t/=360,i/=100;const s=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t);let n,r,a;if(0==(e/=100))n=r=a=i;else{const o=i<.5?i*(1+e):i+e-i*e,h=2*i-o;n=s(h,o,t+1/3),r=s(h,o,t),a=s(h,o,t-1/3)}return{r:Math.round(255*n),g:Math.round(255*r),b:Math.round(255*a)}}function Cs(t,e,i){const s=xs(t),n=xs(e),r=Bs(s.r,s.g,s.b),a=Bs(n.r,n.g,n.b),o=r.h;let h=a.h;const l=h-o;l>180?h-=360:l<-180&&(h+=360);const c=As(((o+(h-o)*i)%360+360)%360,r.s+(a.s-r.s)*i,r.l+(a.l-r.l)*i);return Es(c.r,c.g,c.b)}const Ts={intense:1.6,confident:1.3,nervous:1.15,clear:1,tired:.8,subdued:.5};function Ps(t,e){if(!e||"clear"===e)return t;const i=Ts[e.toLowerCase()];return i&&1!==i?function(t,e){const i=xs(t),s=Bs(i.r,i.g,i.b);s.s=Math.max(0,Math.min(100,s.s*e));const n=As(s.h,s.s,s.l);return Es(n.r,n.g,n.b)}(t,i):t}function Ds(t){return t}function Rs(t){return t*(2-t)}function Fs(t){return t*t}function zs(t){return t<.5?2*t*t:(4-2*t)*t-1}function qs(t){return 1-Math.pow(1-t,3)}function Os(t){return t*t*t}function js(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}function Is(t){const e=2*Math.PI/3;return 0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((10*t-.75)*e)+1}function $s(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375}function Ls(t){const e=2.5949095;return t<.5?Math.pow(2*t,2)*(7.189819*t-e)/2:(Math.pow(2*t-2,2)*((e+1)*(2*t-2)+e)+2)/2}function Gs(t){return Math.sin(t*Math.PI/2)}function _s(t){return-(Math.cos(Math.PI*t)-1)/2}function Hs(t,e,i,s="linear"){return e+(i-e)*("string"==typeof s?{linear:Ds,easeOutQuad:Rs,easeInQuad:Fs,easeInOutQuad:zs,easeOutCubic:qs,easeInCubic:Os,easeInOutCubic:js,easeOutElastic:Is,easeOutBounce:$s,easeInOutBack:Ls,easeOutSine:Gs,easeInOutSine:_s}[s]||Ds:s)(Math.max(0,Math.min(1,t)))}Object.fromEntries(Object.entries({neutral:"#B0B0B0",joy:"#FFD700",sadness:"#4169E1",anger:"#DC143C",fear:"#8B008B",surprise:"#FF8C00",disgust:"#9ACD32",love:"#FF69B4"}).map(([t,e])=>{const i=xs(e);return[t,`${i.r}, ${i.g}, ${i.b}`]}));const Us=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 t=d();t.forEach(t=>{this.cacheEmotion(t)}),this.cacheCommonTransitions(t),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.emotionCache.size}catch(t){this.isInitialized=!1}}cacheEmotion(t){try{const e=l(t);e&&this.emotionCache.set(t,e);const i=c(t);this.visualParamsCache.set(t,i);const s=u(t);this.modifiersCache.set(t,s)}catch(t){}}cacheCommonTransitions(t){[["neutral","joy"],["neutral","sadness"],["neutral","anger"],["joy","sadness"],["sadness","joy"],["anger","calm"],["calm","anger"]].forEach(([e,i])=>{if(t.includes(e)&&t.includes(i))try{const t=f(e,i),s=`${e}->${i}`;this.transitionCache.set(s,t)}catch(t){}})}getEmotion(t){if(!this.isInitialized)return l(t);const e=this.emotionCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,l(t))}getVisualParams(t){if(!this.isInitialized)return c(t);const e=this.visualParamsCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,c(t))}getModifiers(t){if(!this.isInitialized)return u(t);const e=this.modifiersCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,u(t))}getTransitionParams(t,e){if(!this.isInitialized)return f(t,e);const i=`${t}->${e}`,s=this.transitionCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,f(t,e))}hasEmotion(t){return this.emotionCache.has(t)}getStats(){const t=this.stats.hits+this.stats.misses,e=t>0?(this.stats.hits/t*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:`${e}%`,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 Ws{constructor(t){this.errorBoundary=t,this.state={emotion:"neutral",undertone:null,intensity:1,gesture:null,speaking:!1,audioLevel:0},this.slots=[],this.maxSlots=3,this.P=null,this.D=null,this.R=0,this.F=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 t={};return["neutral","joy","sadness","anger","fear","surprise","disgust","love","suspicion","excited","resting","euphoria","focused","glitch","calm"].forEach(e=>{const i=Us.getVisualParams(e);i&&(t[e]={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})}),t}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(t,e=null,i=500){return this.errorBoundary.wrap(()=>{let s=null,n=1;if("string"==typeof e?s=e:e&&"object"==typeof e&&(s=e.undertone??null,i=e.duration??i,n=e.intensity??1),this.interpolationCache.cachedProperties=null,this.interpolationCache.cachedRenderState=null,!m(t)&&!{}.hasOwnProperty.call(this.emotionalStates,t)){const e=[...Object.keys(this.emotionalStates),...d()],i=[...new Set(e)];throw new Error(`Invalid emotion: ${t}. 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:t,intensity:n}],this.D=t,this.state.emotion===t&&this.state.undertone===s&&this.state.intensity===n||(this.state.emotion!==t&&(i>0?(this.transitions.emotional={current:this.state.emotion,target:t,progress:0,duration:Math.max(100,i),startTime:performance.now(),isActive:!0},void 0!==this.q&&(this.q=0)):this.transitions.emotional={current:t,target:null,progress:1,duration:0,startTime:performance.now(),isActive:!1},this.state.emotion=t),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(t){this.P=t}O(t,e){this.P&&this.P(t,e)}j(){const t=this.getDominant(),e=t?t.emotion:null,i=this.D;e!==i&&(this.D=e,this.O("dominantChanged",{previous:i,current:e,intensity:t?t.intensity:0}))}setEmotionDampening(t){this.R=Math.max(0,Math.min(1,t))}getEmotionDampening(){return this.R}setNegativeEmotions(t){this.F=new Set(t)}pushEmotion(t,e=.5){return this.errorBoundary.wrap(()=>{if(!m(t)&&!{}.hasOwnProperty.call(this.emotionalStates,t))return!1;e=Math.max(0,Math.min(1,e)),this.interpolationCache.cachedProperties=null;const i=this.slots.find(e=>e.emotion===t);if(i){const s=i.intensity;i.intensity=Math.min(1,i.intensity+e),this.O("slotChanged",{emotion:t,intensity:i.intensity,action:"push"}),i.intensity>=1&&s<1&&this.O("emotionPeaked",{emotion:t,intensity:i.intensity})}else if(this.slots.length<this.maxSlots)this.slots.push({emotion:t,intensity:e}),this.O("slotChanged",{emotion:t,intensity:e,action:"push"}),e>=1&&this.O("emotionPeaked",{emotion:t,intensity:e});else{let i=0;for(let t=1;t<this.slots.length;t++)this.slots[t].intensity<this.slots[i].intensity&&(i=t);const s=this.slots[i];this.O("slotChanged",{emotion:s.emotion,intensity:0,action:"replaced"}),this.slots[i]={emotion:t,intensity:e},this.O("slotChanged",{emotion:t,intensity:e,action:"push"})}return this.I(),this.j(),!0},"push-emotion",!1)()}nudgeEmotion(t,e,i=1){e>0&&this.R>0&&this.F.has(t)&&(e*=1-this.R),this.interpolationCache.cachedProperties=null;const s=this.slots.find(e=>e.emotion===t);if(s){const n=s.intensity;s.intensity=Math.max(0,Math.min(i,s.intensity+e)),s.intensity<=0?(this.slots=this.slots.filter(t=>t!==s),this.O("slotChanged",{emotion:t,intensity:0,action:"removed"})):(this.O("slotChanged",{emotion:t,intensity:s.intensity,action:"nudge"}),s.intensity>=i&&n<i&&this.O("emotionPeaked",{emotion:t,intensity:s.intensity}))}else if(e>0)return void this.pushEmotion(t,Math.min(i,e));this.I(),this.j()}clearEmotions(){const t=this.slots.length>0;this.slots=[],this.interpolationCache.cachedProperties=null,this.state.emotion="neutral",this.state.intensity=1,t&&(this.O("slotChanged",{emotion:null,intensity:0,action:"cleared"}),this.D=null,this.O("dominantChanged",{previous:this.D,current:null,intensity:0}))}getSlots(){return this.slots}pruneEmptySlots(){const t=this.slots.length,e=this.slots.filter(t=>t.intensity<=0);if(this.slots=this.slots.filter(t=>t.intensity>0),this.slots.length!==t){this.interpolationCache.cachedProperties=null;for(const t of e)this.O("emotionDecayed",{emotion:t.emotion,intensity:0,removed:!0});this.I(),this.j()}}getDominant(){return this.slots.length?this.slots.reduce((t,e)=>e.intensity>t.intensity?e:t):null}getUndercurrents(){const t=this.getDominant();return t?this.slots.filter(e=>e!==t):[]}getEmotionalState(){const t=this.getDominant();return{dominant:t?{...t}:null,undercurrents:this.getUndercurrents().map(t=>({...t})),slots:this.slots.map(t=>({...t}))}}getCurrentRhythmModifiers(){return this.slots.length>0?b(this.slots):b([{emotion:this.state.emotion,intensity:this.state.intensity}])}I(){const t=this.getDominant();t?(this.state.emotion!==t.emotion&&(this.transitions.emotional={current:this.state.emotion,target:t.emotion,progress:0,duration:300,startTime:performance.now(),isActive:!0},this.state.emotion=t.emotion),this.state.intensity=t.intensity):(this.state.emotion="neutral",this.state.intensity=1)}applyUndertone(t,e){if(!e||!{}.hasOwnProperty.call(this.undertoneModifiers,e))return{...t};const i=this.undertoneModifiers[e],s={...t};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 t=i.amplificationFactor;s.glowIntensity*=t,s.breathRate*=t,s.particleRate=Math.round(s.particleRate*t),s.coreSize*=t}if(void 0!==i.dampeningFactor){const t=i.dampeningFactor;s.glowIntensity*=t,s.breathRate*=t,s.particleRate=Math.round(s.particleRate*t),s.coreSize*=t}return void 0!==i.jitterAmount&&(s.jitterAmount=i.jitterAmount),s}update(t){this.errorBoundary.wrap(()=>{this.transitions.emotional.isActive&&this.updateEmotionalTransition(t),this.transitions.intensity.isActive&&this.updateIntensityTransition(t),this.transitions.undertone.isActive&&this.updateUndertoneTransition(t)},"state-machine-update")()}updateUndertoneTransition(t){const e=this.transitions.undertone,i=performance.now()-e.startTime,s=Math.min(i/e.duration,1),n=js(s);e.current&&e.target?(e.currentWeight=1-n,e.targetWeight=n):e.current&&!e.target?(e.currentWeight=1-n,e.targetWeight=0):!e.current&&e.target&&(e.currentWeight=0,e.targetWeight=n),e.progress=s,s>=1&&(e.isActive=!1,e.current=e.target,e.currentWeight=e.target?1:0,e.targetWeight=0)}updateIntensityTransition(t){const e=this.transitions.intensity,i=performance.now()-e.startTime;e.progress=Math.min(1,i/e.duration),e.progress>=1&&(e.isActive=!1,e.from=e.to,e.progress=1)}getEffectiveIntensity(){const t=this.transitions.intensity;if(!t.isActive)return this.state.intensity;const e=js(t.progress);return t.from+(t.to-t.from)*e}updateEmotionalTransition(t){const e=this.transitions.emotional;let i;void 0!==this.q?(this.q+=t,i=this.q):i=performance.now()-e.startTime,e.progress=Math.min(1,i/e.duration),e.progress>=1&&(e.isActive=!1,e.current=e.target,e.target=null,e.progress=1)}getCurrentEmotionalProperties(){return this.errorBoundary.wrap(()=>{const t=performance.now();if(this.interpolationCache.cachedProperties&&t-this.interpolationCache.lastUpdate<this.interpolationCache.cacheInterval)return this.interpolationCache.cachedProperties;let e;if(this.slots.length>1)e=this.$();else{const t=this.transitions.emotional;e=t.isActive&&t.target?this.interpolateEmotionalProperties(t.current,t.target,t.progress):{...this.emotionalStates[this.state.emotion]||this.emotionalStates.neutral};const i=this.getEffectiveIntensity();i<1&&(e.glowIntensity=this.L(.7,e.glowIntensity,i),e.particleRate=Math.round(this.L(1,e.particleRate,i)),e.breathRate=this.L(1,e.breathRate,i),e.breathDepth=e.breathDepth*i,e.coreSize=this.L(1,e.coreSize,i))}return e=this.applyUndertone(e,this.state.undertone),this.interpolationCache.cachedProperties=e,this.interpolationCache.lastUpdate=t,e},"emotional-properties",()=>this.emotionalStates.neutral)()}$(){const t=this.getDominant(),e=this.getUndercurrents(),i=this.emotionalStates[t.emotion]||this.emotionalStates.neutral,s={...i},n=t.intensity;s.glowIntensity=.75*this.L(.7,i.glowIntensity,n),s.particleRate=i.particleRate*n*.75,s.breathRate=.75*this.L(1,i.breathRate,n),s.breathDepth=i.breathDepth*n*.75,s.coreSize=.75*this.L(1,i.coreSize,n);const r=e.length>0?.25/e.length:0;for(const t of e){const e=this.emotionalStates[t.emotion]||this.emotionalStates.neutral,i=t.intensity;s.glowIntensity+=this.L(.7,e.glowIntensity,i)*r,s.particleRate+=e.particleRate*i*r,s.breathRate+=this.L(1,e.breathRate,i)*r,s.breathDepth+=e.breathDepth*i*r,s.coreSize+=this.L(1,e.coreSize,i)*r}if(s.particleRate=Math.round(s.particleRate),e.length>0){const t=this.slots.reduce((t,e)=>t+e.intensity,0);let n=i.primaryColor;for(const i of e){const e=this.emotionalStates[i.emotion]||this.emotionalStates.neutral,s=i.intensity/t;n=Cs(n,e.primaryColor,s)}s.primaryColor=n}return s.particleBehavior=i.particleBehavior,s}L(t,e,i){return t+(e-t)*i}interpolateEmotionalProperties(t,e,i){const s=this.emotionalStates[t]||this.emotionalStates.neutral,n=this.emotionalStates[e]||this.emotionalStates.neutral,r=Hs(i,0,1,"easeOutCubic");return{primaryColor:Cs(s.primaryColor,n.primaryColor,r),glowIntensity:s.glowIntensity+(n.glowIntensity-s.glowIntensity)*r,particleRate:Math.round(s.particleRate+(n.particleRate-s.particleRate)*r),coreSize:s.coreSize+(n.coreSize-s.coreSize)*r,breathRate:s.breathRate+(n.breathRate-s.breathRate)*r,breathDepth:s.breathDepth+(n.breathDepth-s.breathDepth)*r,particleBehavior:r>.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(t){return this.errorBoundary.wrap(()=>{if(null!==t&&!{}.hasOwnProperty.call(this.undertoneModifiers,t))throw new Error(`Invalid undertone: ${t}. Valid undertones: ${Object.keys(this.undertoneModifiers).join(", ")}`);return this.state.undertone=t,!0},"undertone-application",!1)()}clearUndertone(){this.state.undertone=null}getUndertoneModifier(t){return this.errorBoundary.wrap(()=>{if(this.renderer&&this.renderer.undertoneModifiers&&this.renderer.undertoneModifiers[t])return{...this.renderer.undertoneModifiers[t]};if(!t||!{}.hasOwnProperty.call(this.undertoneModifiers,t))return null;const e={...this.undertoneModifiers[t]};return e.glowRadiusMult||(e.glowRadiusMult=1),e},"undertone-retrieval",null)()}getWeightedUndertoneModifiers(){const t=this.transitions.undertone;if(!t.isActive){if(this.state.undertone){const t=this.getUndertoneModifier(this.state.undertone);if(t)return{...t,weight:1,type:this.state.undertone}}return null}if(t.target){const e=this.getUndertoneModifier(t.target);if(e)return{...e,weight:t.targetWeight,type:t.target}}if(t.current&&t.currentWeight>0){const e=this.getUndertoneModifier(t.current);if(e)return{...e,weight:t.currentWeight,type:t.current}}return null}reset(t=500){this.slots=[],this.setEmotion("neutral",null,t)}isValidEmotion(t){return{}.hasOwnProperty.call(this.emotionalStates,t)}isValidUndertone(t){return null===t||{}.hasOwnProperty.call(this.undertoneModifiers,t)}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(t,e,i,s="easeOutCubic"){return t+(e-t)*Hs(i,0,1,s)}serialize(){return{version:1,emotion:this.state.emotion,undertone:this.state.undertone,intensity:this.state.intensity,slots:this.slots.map(t=>({...t})),dampening:this.R,negativeEmotions:[...this.F]}}deserialize(t){t&&1===t.version&&(this.slots=(t.slots||[]).map(t=>({emotion:t.emotion,intensity:t.intensity})),this.R=t.dampening??0,t.negativeEmotions&&(this.F=new Set(t.negativeEmotions)),this.state.emotion=t.emotion||"neutral",this.state.undertone=t.undertone||null,this.state.intensity=t.intensity??1,this.D=t.emotion||null,this.transitions.emotional.isActive=!1,this.transitions.intensity.isActive=!1,this.transitions.undertone.isActive=!1,this.interpolationCache.cachedProperties=null)}enableSimulatedTime(t=!0){t?this.q=0:delete this.q}}const Ys=16.67,Xs=3e4;let Vs;"undefined"!=typeof window&&window.__emotiveRhythmEngine?Vs=window.__emotiveRhythmEngine:(Vs=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 t=(performance.now()-this.startTime)/this.beatDuration,e=Math.floor(t);this.beatProgress=t%1,e>this.currentBeat&&this.onBeat(e);const i=Math.floor(e/this.timeSignature[0]);i>this.currentBar&&this.onBar(i),this.currentBeat=e,this.currentBar=i,this.barProgress=e%this.timeSignature[0]/this.timeSignature[0],this.updateSubdivisions(),this.emit("update",this.getTimeInfo()),this.isPlaying&&requestAnimationFrame(()=>this.update())}onBeat(t){const e=t%this.timeSignature[0],i=this.getAccent(e),s=this.humanize*(Math.random()-.5)*this.beatDuration,n={beat:t,beatInBar:e,bar:this.currentBar,accent:i,intensity:this.intensity*i,humanTiming:s,timestamp:performance.now()};this.emit("beat",n),this.beatCallbacks.forEach(t=>t(n)),this.lastBeatTime=performance.now(),this.nextBeatTime=this.lastBeatTime+this.beatDuration}onBar(t){const e={bar:t,timeSignature:this.timeSignature,pattern:this.currentPattern,timestamp:performance.now()};this.emit("bar",e),this.barCallbacks.forEach(t=>t(e))}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 t=.5+.17*this.groove;this.subdivisions.eighth<.5?this.subdivisions.swing=this.subdivisions.eighth/t:this.subdivisions.swing=.5+(this.subdivisions.eighth-.5)/(1-t)}else this.subdivisions.swing=this.subdivisions.eighth}getAccent(t){if(this.currentPattern&&this.patterns.has(this.currentPattern)){const e=this.patterns.get(this.currentPattern);if(e.accents&&void 0!==e.accents[t])return e.accents[t]}return 0===t?1:2===t&&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(t){this.bpm=Math.max(20,Math.min(360,t)),this.beatDuration=6e4/this.bpm,this.barDuration=this.beatDuration*this.timeSignature[0],this.emit("tempoChange",{bpm:this.bpm})}setTimeSignature(t,e){this.timeSignature=[t,e],this.barDuration=this.beatDuration*t,this.emit("timeSignatureChange",{timeSignature:this.timeSignature})}setPattern(t){if(!this.patterns.has(t))return;const e=this.patterns.get(t);this.currentPattern=t,e.timeSignature&&this.setTimeSignature(...e.timeSignature),void 0!==e.groove&&(this.groove=e.groove),this.emit("patternChange",{pattern:t})}onBeatCallback(t){return this.beatCallbacks.add(t),()=>this.beatCallbacks.delete(t)}onBarCallback(t){return this.barCallbacks.add(t),()=>this.barCallbacks.delete(t)}emit(t,e){this.listeners.has(t)&&this.listeners.get(t).forEach(t=>t(e))}on(t,e){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(e),()=>{this.listeners.has(t)&&this.listeners.get(t).delete(e)}}syncToAudio(t,e){this.G||(this.G=!0),this.audioSync={context:t,source:e}}getAdapter(){return{getTimeInfo:()=>this.getTimeInfo(),isOnBeat:(t=.1)=>this.beatProgress<t||this.beatProgress>1-t,isOnSubdivision:(t,e=.1)=>{const i=this.subdivisions[t]||0;return i<e||i>1-e},getBeatSync:(t=0,e=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 t+(e-t)*s},getAccentedValue:(t,e=2)=>t*(1+(this.getAccent(this.currentBeat%this.timeSignature[0])-.5)*e),onBeat:t=>this.onBeatCallback(t),onBar:t=>this.onBarCallback(t),beatsToMs:t=>t*this.beatDuration,msToBeats:t=>t/this.beatDuration,isPlaying:()=>this.isPlaying,getBPM:()=>this.bpm,getPattern:()=>this.currentPattern}}},"undefined"!=typeof window&&(window.__emotiveRhythmEngine=Vs));class Ns{constructor(t,e={}){this._=t,this.H={perfect:e.windows?.perfect??30,great:e.windows?.great??60,good:e.windows?.good??100},this.U={perfect:{multiplier:2,label:"Perfect"},great:{multiplier:1.5,label:"Great"},good:{multiplier:1,label:"Good"},miss:{multiplier:0,label:"Miss"}},this.W={multiplier:1},this.Y=e.emotionSource??null,this.X=[],this.V=100,this.N=[],this.J=null,this.K=null,this.Z=null}evaluate(t=performance.now()){const e=this._.getTimeInfo(),{beatDuration:i}=e,s=performance.now()-e.elapsed,n=t-s,r=n-n%i,a=r+i,o=n-r<a-n?r:a,h=n-o;return this.tt(h,t,o+s)}evaluateAgainst(t,e){return this.tt(t-e,t,e)}evaluateSequence(t,e){const i=[],s=new Set;for(const n of t){let t=-1,r=1/0;for(let i=0;i<e.length;i++){if(s.has(i))continue;const a=Math.abs(n-e[i]);a<r&&(r=a,t=i)}t>=0?(s.add(t),i.push(this.evaluateAgainst(n,e[t]))):i.push({grade:"miss",offset:0,absOffset:0,multiplier:0,label:"Miss",timestamp:n,targetTime:null})}return i}tt(t,e,i){if(this.Z&&this.Z.autoRhythm)return this.et("good",t,e,i);const s=Math.abs(t),n=this.Y?.()??{windowMultiplier:1},r=this.Z?this.Z.getWindowMultiplier():1,a=this.W.multiplier*(n.windowMultiplier||1)*r;let o;return o=s<=this.H.perfect*a?"perfect":s<=this.H.great*a?"great":s<=this.H.good*a?"good":"miss",this.et(o,t,e,i)}et(t,e,i,s){const n={grade:t,offset:e,absOffset:Math.abs(e),multiplier:this.U[t].multiplier,label:this.U[t].label,timestamp:i,targetTime:s};this.X.push(n),this.X.length>this.V&&this.X.shift();for(const t of this.N)t(n);if(this.J&&this.K){const e=this.J[t];e&&this.K(e.emotion,e.delta)}return n}setWindowModifier(t){this.W.multiplier=Math.max(.3,Math.min(3,t))}setEmotionSource(t){this.Y=t}getAccuracy(){if(!this.X.length)return{perfect:0,great:0,good:0,miss:0,averageOffset:0,total:0};const t={perfect:0,great:0,good:0,miss:0};let e=0;for(const i of this.X)t[i.grade]++,e+=i.offset;return{...t,averageOffset:e/this.X.length,total:this.X.length}}getHistory(){return[...this.X]}clearHistory(){this.X.length=0}onEvaluate(t){return this.N.push(t),()=>{this.N=this.N.filter(e=>e!==t)}}setEmotionFeedback(t){this.J=t||null}setEmotionTarget(t){this.K=t||null}setDifficultyManager(t){this.Z=t||null}setWindows(t){Object.assign(this.H,t)}setGrades(t){Object.assign(this.U,t)}destroy(){this.X.length=0,this.N.length=0}}const Qs=new class{constructor(){this.enabled=!1,this.adapter=null,this.subsystemConfigs=new Map,this.activeModulations=new Map,this.it=null,this.st=null,this.nt=null}initialize(){this.adapter=Vs.getAdapter(),this.enabled=!0,this.st=this.adapter.onBeat(this.handleBeat.bind(this)),this.nt=this.adapter.onBar(this.handleBar.bind(this))}updateBPM(t){if(t>=60&&t<=220){if(window.rhythmManuallyStoppedForCurrentAudio)return;if(!Vs.isRunning)return this.start(t,"straight"),void(window.rhythmSyncVisualizer&&!window.rhythmSyncVisualizer.state.active&&window.rhythmSyncVisualizer.start());Vs.setBPM(t)}}registerConfig(t,e,i){if(!i.rhythm||!i.rhythm.enabled)return;const s=`${t}:${e}`;this.subsystemConfigs.set(s,{type:t,name:e,rhythmConfig:i.rhythm,originalConfig:i})}applyGestureRhythm(t,e,i,s){if(!this.enabled||!t.rhythm?.enabled)return{};const n=t.rhythm,r={};if(n.amplitudeSync){const t=n.amplitudeSync,e=this.adapter.getBeatSync(t.offBeat||.8,t.onBeat||1.5,t.curve||"linear");r.amplitudeMultiplier=e}if(n.wobbleSync){const t=n.wobbleSync;this.adapter.isOnSubdivision(t.subdivision,.1)?r.wobbleMultiplier=1+t.intensity:r.wobbleMultiplier=1}if(n.accentResponse?.enabled){const t=this.adapter.getAccentedValue(1,n.accentResponse.multiplier||1.5);r.accentMultiplier=t}const a=this.adapter.getPattern();return a&&n.patternOverrides?.[a]&&Object.assign(r,n.patternOverrides[a]),r}applyParticleRhythm(t,e){if(!this.enabled||!t.rhythm?.enabled)return{};const i=this.adapter.getTimeInfo(),s=t.rhythm,n={};if(s.particleEmission){const t=s.particleEmission;"beat"===t.syncMode&&this.adapter.isOnBeat(.1)?n.emitBurst=t.burstSize||3:void 0!==t.offBeatRate&&(n.emissionRate=t.offBeatRate)}if(s.glowSync){const t=s.glowSync,e=this.adapter.getBeatSync(t.intensityRange[0]||1,t.intensityRange[1]||2,"pulse");n.glowIntensity=e}if("bars"===s.breathSync?.mode){const t=s.breathSync,e=i.bar%t.barsPerBreath/t.barsPerBreath;n.breathPhase=e*Math.PI*2}return n}applyBehaviorRhythm(t,e,i){if(!this.enabled||!t.rhythm?.enabled)return{};const s=this.adapter.getTimeInfo(),n=t.rhythm,r={};if(n.glitchTiming){const t=n.glitchTiming;if(this.adapter.isOnSubdivision(t.subdivision,.05)&&Math.random()<t.probability){const e=this.adapter.isOnBeat()?t.intensityOnBeat:t.intensityOffBeat;r.triggerGlitch=!0,r.glitchIntensity=e}}if(n.orbitRhythm){const t=n.orbitRhythm;"tempo"===t.baseSpeed&&(r.speedMultiplier=this.adapter.getBPM()/120),t.beatAcceleration&&this.adapter.isOnBeat(.1)&&(r.speedBoost=t.beatAcceleration),t.barReset&&0===s.beatInBar&&(r.resetOrbit=!0)}if(n.stutterSync){const t=n.stutterSync,e=this.adapter.getPattern();if(e&&t.patterns?.[e]){const i=t.patterns[e];i.freezeOnDrop&&2===s.beatInBar?(r.freeze=!0,r.freezeDuration=i.dropDuration):i.randomFreeze&&Math.random()<i.randomFreeze&&(r.freeze=!0,r.freezeDuration=i.duration)}}return r}handleBeat(t){this.lastBeatInfo=t}handleBar(t){this.lastBarInfo=t}getMusicalDuration(t,e){if(!this.enabled||!t?.durationSync)return e;const i=t.durationSync;return"bars"===i.mode?this.adapter.beatsToMs(4*i.bars):"beats"===i.mode?this.adapter.beatsToMs(i.beats):e}isEnabled(){return this.enabled&&this.adapter.isPlaying()}start(t=120,e="straight"){t&&Vs.setBPM(t),e&&Vs.setPattern(e),Vs.start(),this.enabled=!0}stop(){Vs.stop(),this.enabled=!1,this.bpmLocked=!1,this.lockedBPM=null}destroy(){this.stop(),this.st&&(this.st(),this.st=null),this.nt&&(this.nt(),this.nt=null),this.enabled=!1,this.adapter=null,this.subsystemConfigs.clear(),this.activeModulations.clear(),this.lastBeatInfo=null,this.lastBarInfo=null,this.it=null}setPattern(t){Vs.setPattern(t)}setBPM(t){Vs.setBPM(t),this.bpmLocked&&(this.lockedBPM=t)}resampleBPM(){this.bpmLocked=!1,this.lockedBPM=null}setTimeSignature(t){this.timeSignature=t;const e=document.getElementById("time-sig-display");e&&(e.textContent=t),"3/4"===t&&Vs.getPattern()}getInputEvaluator(t){return this.it||(this.adapter||this.initialize(),this.it=new Ns(this.adapter,t)),this.it}getEffectiveBPM(t){if(!this.adapter)return 120;let e=this.adapter.getBPM();if(t&&"function"==typeof t.getCurrentRhythmModifiers){const i=t.getCurrentRhythmModifiers();i.tempoShift&&(e*=1+i.tempoShift)}return Math.round(100*e)/100}syncToAudio(t,e){Vs.syncToAudio(t,e)}};class Js{constructor(t,e,i="ambient",s=1,n=1,r=null){const a=Math.random();this.z=a<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,h=Math.random()*Math.PI*2;this.x=t+Math.cos(h)*o,this.y=e+Math.sin(h)*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=r,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:t,initialY:e},ps(this,i)}update(t,e,i,s=null,n=null,r=0,a=null){const o=Math.min(t,50)/Ys,h=n&&n.type&&r>0&&Ri(n.type),l=this.rainData||"falling"===this.gestureBehavior||this.fallingData||this.gestureData?.rain,c=h||l;if(c||(this.x+=this.vx*o,this.y+=this.vy*o),!c){let t,s;if(a)t=a.width,s=a.height;else{const n=document.getElementById("card-mascot")||document.getElementById("cherokee-guide-mascot")||document.querySelector("canvas");t=n?n.width:2*e,s=n?n.height:2*i}const n=20,r=e-t/2+n,o=e+t/2+n,h=i-s/2+n,l=i+s/2-n;this.x-this.size<r?(this.x=r+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<h?(this.y=h+this.size,this.vy=.5*Math.abs(this.vy)):this.y+this.size>l&&(this.y=l-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(t,e){}applyGestureMotion(t,e,i,s,n){!function(t,e,i,s,n,r){if(!i||!i.type||s>=1)return;t.gestureData||(t.gestureData={originalVx:t.vx,originalVy:t.vy,initialX:t.x,initialY:t.y,startAngle:Math.atan2(t.y-r,t.x-n),startRadius:Math.sqrt(Math.pow(t.x-n,2)+Math.pow(t.y-r,2))});const a=Pi(i.type);if(!a)return;let o=i;if(Qs.isEnabled()&&a.rhythm?.enabled){const n=Qs.applyGestureRhythm(a,t,s,e);o={...i,amplitude:(i.amplitude||1)*(n.amplitudeMultiplier||1)*(n.accentMultiplier||1),wobbleAmount:(i.wobbleAmount||0)*(n.wobbleMultiplier||1),rhythmModulation:n}}a.apply&&a.apply(t,s,o,e,n,r),s>=.99&&a.cleanup&&(a.cleanup(t),t.gestureData=null)}(this,i,t,e,s,n)}isOutOfBounds(t,e){return this.x<-50||this.x>t+50||this.y<-50||this.y>e+50}isAlive(){return this.life>0}setOutwardVelocity(t){if(this.behaviorData&&void 0!==this.behaviorData.outwardSpeed){const e=this.behaviorData.outwardSpeed;this.vx=Math.cos(t)*e,this.vy=Math.sin(t)*e+(this.behaviorData.upwardBias||0)}}getDepthAdjustedSize(){const t=1+.2*this.z;return this.size*t}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(t,e,i="ambient",s=1,n=1,r=null){const a=Math.random();this.z=a<1/13?.5+.5*Math.random():.9*Math.random()-1;const o=this.z>0?(20+20*Math.random())*s:3*s,h=Math.random()*Math.PI*2;if(this.x=t+Math.cos(h)*o,this.y=e+Math.sin(h)*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=r,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 t in this.behaviorData)delete this.behaviorData[t];else this.behaviorData={};ps(this,i)}getCachedColor(t,e){const i=Math.round(100*e)/100,s=`${t}_${i}`;if(this.cachedColors.has(s)){const t=this.colorAccessOrder.indexOf(s);-1!==t&&this.colorAccessOrder.splice(t,1),this.colorAccessOrder.push(s)}else{if(this.cachedColors.size>=this.maxCachedColors){const t=this.colorAccessOrder.shift();this.cachedColors.delete(t)}this.cachedColors.set(s,this.hexToRgba(t,i)),this.colorAccessOrder.push(s)}return this.cachedColors.get(s)}hexToRgba(t,e){const i=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return i?`rgba(${parseInt(i[1],16)}, ${parseInt(i[2],16)}, ${parseInt(i[3],16)}, ${e})`:`rgba(255, 255, 255, ${e})`}easeInOutCubic(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}render(t,e="#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),r=this.tempColor||this.color||e;if(t.save(),this.isCellShaded){t.strokeStyle=this.getCachedColor(r,.9*this.opacity),t.lineWidth=2,t.beginPath(),t.arc(i,s,n,0,2*Math.PI),t.stroke();const e=Math.floor(3*this.opacity)/3;t.fillStyle=this.getCachedColor(r,e*(this.baseOpacity||.5)*.5),t.beginPath(),t.arc(i,s,Math.max(.1,n-1),0,2*Math.PI),t.fill(),e>.5&&(t.fillStyle=this.getCachedColor("#FFFFFF",.3),t.beginPath(),t.arc(i-.3*n,s-.3*n,.3*n,0,2*Math.PI),t.fill())}else{const e=t.createRadialGradient(i,s,0,i,s,n);if(e.addColorStop(0,this.getCachedColor(r,this.opacity*(this.baseOpacity||.5))),e.addColorStop(.5,this.getCachedColor(r,this.opacity*(this.baseOpacity||.5)*.5)),e.addColorStop(1,this.getCachedColor(r,0)),t.fillStyle=e,t.beginPath(),t.arc(i,s,n,0,2*Math.PI),t.fill(),this.hasGlow&&this.glowSizeMultiplier>0){const e=n*this.glowSizeMultiplier,a=t.createRadialGradient(i,s,.5*n,i,s,e),o=.3,h=Math.max(o,this.opacity),l=Math.min(1,this.glowSizeMultiplier/3);a.addColorStop(0,this.getCachedColor(r,Math.max(.5,.8*h)*l)),a.addColorStop(.25,this.getCachedColor(r,Math.max(.3,.6*h)*l)),a.addColorStop(.5,this.getCachedColor(r,Math.max(.2,.4*h)*l)),a.addColorStop(.75,this.getCachedColor(r,Math.max(.1,.2*h)*l)),a.addColorStop(1,this.getCachedColor(r,0)),t.save(),t.globalCompositeOperation="screen",t.fillStyle=a,t.beginPath(),t.arc(i,s,e,0,2*Math.PI),t.fill(),t.restore()}}t.restore()}}class Ks{constructor(t=50){this.poolSize=Math.min(t,50),this.pool=[],this.totalParticlesCreated=0,this.totalParticlesDestroyed=0,this.poolHits=0,this.poolMisses=0}getParticle(t,e,i,s,n,r,a,o=null){let h;return this.pool.length>0?(h=this.pool.pop(),h.reset(t,e,i,s,n,r),this.poolHits++):(h=new Js(t,e,i,s,n,r),this.poolMisses++,this.totalParticlesCreated++),h.emotion=a,o&&(h.gestureBehavior=o),h}returnParticle(t){if(this.pool.length<this.poolSize){if(t.cachedGradient=null,t.cachedGradientKey=null,t.behaviorData)for(const e in t.behaviorData)delete t.behaviorData[e];this.pool.push(t)}else this.totalParticlesDestroyed++}refreshPool(){const t=this.pool.length-this.poolSize;t>0&&(this.pool.splice(this.poolSize),this.totalParticlesDestroyed+=t)}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 Zs{constructor(){this.spawnAccumulator=0}getSpawnPosition(t,e,i,s,n,r=null){const a=Math.min(s,n)/12,o=2.5*a,h=1.1*o,l=Math.min(e-30,s-e-30),c=Math.min(i-30,n-i-30),u=Math.min(1.5*o,l,c);switch(t){case"ambient":case"resting":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"ascending":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"rising":{const t=Math.random()*Math.PI*2,s=h+Math.random()*(u-h);return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"falling":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s,angle:t}}case"aggressive":{const t=Math.random()*Math.PI*2,s=o+Math.random()*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"scattering":default:return{x:e,y:i};case"burst":{const t=Math.random()*Math.PI*2;if("suspicion"===r){const s=1.5*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}if("surprise"===r){const s=1.2*a;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}return{x:e,y:i}}case"repelling":{const t=Math.random()*Math.PI*2,s=.9*o;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"orbiting":{const t=Math.random()*Math.PI*2,s=1.2*o+Math.random()*o*.5;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"glitchy":{const t=Math.random()*Math.PI*2,s=3*o+Math.random()*o*4;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}case"spaz":{const t=Math.random()*Math.PI*2,s=2*o+Math.random()*o*3;return{x:e+Math.cos(t)*s,y:i+Math.sin(t)*s}}}}clampToCanvas(t,e,i,s,n=30){return{x:Math.max(n,Math.min(i-n,t)),y:Math.max(n,Math.min(s-n,e))}}calculateSpawnRate(t,e){if(t<=0)return 0;const i=Math.min(e,50),s=t/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 tn{render(t,e,i="#ffffff",s=null){const n=[];for(const t of e)t.life<=0||n.push(t);this.rt(t,n,i,s)}renderLayer(t,e,i="#ffffff",s=!1,n=null){const r=[],a=t.canvas.width,o=t.canvas.height;for(const t of e)t.z>=0===s&&(t.x<-50||t.x>a+50||t.y<-50||t.y>o+50||t.life<=0||r.push(t));return r.sort((t,e)=>t.isCellShaded!==e.isCellShaded?t.isCellShaded?-1:1:t.hasGlow!==e.hasGlow?t.hasGlow?-1:1:0),this.rt(t,r,i,n),r}rt(t,e,i,s=null){t.save();let n=null;for(const r of e)if(r.isCellShaded)r.render(t,i),n=null;else{const e=r.color||i;if(e!==n&&(t.fillStyle=e,n=e),!isFinite(r.x)||!isFinite(r.y))continue;const a=r.getDepthAdjustedSize?r.getDepthAdjustedSize():r.size;let o=Math.max(.1,a),h=1;if(s&&s.fireflyEffect){const t=(.01*r.x+.01*r.y+.1*r.size)%(2*Math.PI),e=s.fireflyTime||.001*Date.now(),i=s.particleGlow||2;h=.3+Math.max(0,Math.sin(3*e+t))*i}if(s&&s.flickerEffect){const t=(.02*r.x+.02*r.y)%(2*Math.PI),e=s.flickerTime||.001*Date.now(),i=s.particleGlow||2;h=.5+Math.sin(12*e+t)*i*.5}if(s&&s.shimmerEffect){const e=r.x-t.canvas.width/2,i=r.y-t.canvas.height/2,n=Math.sqrt(e*e+i*i)/200,a=s.shimmerTime||.001*Date.now(),o=s.shimmerWave||0,l=s.particleGlow||1.2;h=1+.15*Math.sin(3*a-n+o)*l}if(s&&s.glowEffect){const e=s.glowProgress||0,i=s.particleGlow||2,n=r.x-t.canvas.width/2,a=r.y-t.canvas.height/2,h=Math.sqrt(n*n+a*a)/300,l=Math.min(.3*h,.5),c=Math.max(0,(e-l)/(1-l)),u=Math.sin(c*Math.PI);r.ot||(r.ot={hasGlow:r.hasGlow,glowSizeMultiplier:r.glowSizeMultiplier||0}),r.hasGlow=!0,r.glowSizeMultiplier=Math.max(3,r.ot.glowSizeMultiplier)+u*i*3,o*=1+.3*u,e>=.99&&r.ot&&(r.hasGlow=r.ot.hasGlow,r.glowSizeMultiplier=r.ot.glowSizeMultiplier,delete r.ot)}if(r.hasGlow||h>1){const e=Math.max(.1,o*(r.glowSizeMultiplier||1.5)*h),i=t.globalCompositeOperation;t.globalCompositeOperation="screen",t.globalAlpha=.15*r.opacity*h,t.beginPath(),t.arc(r.x,r.y,e,0,2*Math.PI),t.fill(),t.globalAlpha=.25*r.opacity*h,t.beginPath(),t.arc(r.x,r.y,.6*e,0,2*Math.PI),t.fill(),t.globalCompositeOperation=i}t.globalAlpha=r.opacity*(r.baseOpacity||.5)*.6*Math.min(2,h),t.beginPath(),t.arc(r.x,r.y,o,0,2*Math.PI),t.fill()}t.restore()}}class en{constructor(t=50,e=null){this.errorBoundary=e,this.maxParticles=t,this.absoluteMaxParticles=2*t,this.particles=[],this.particlePool=new Ks(t),this.particleSpawner=new Zs,this.particleRenderer=new tn,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(t){this.particleSpawner.spawnAccumulator=t}getParticleFromPool(t,e,i){return this.particlePool.getParticle(t,e,i,this.scaleFactor||1,this.particleSizeMultiplier||1,this.currentEmotionColors,this.currentEmotion,this.gestureBehavior)}returnParticleToPool(t){this.particlePool.returnParticle(t)}spawn(t,e,i,s,n,r,a=null,o=0,h=10,l=1,c=1,u=null,d=null){if(this.scaleFactor=l,this.particleSizeMultiplier=c,this.errorBoundary)return this.errorBoundary.wrap(()=>{this.ht(t,e,i,s,n,r,a,o,h,u,d)},"particle-spawn")();this.ht(t,e,i,s,n,r,a,o,h,u,d)}resetAccumulator(){this.particleSpawner.resetAccumulator()}ht(t,e,i,s,n,r,a,o=0,h=10,c=null,u=null){this.currentEmotion=e,this.baseEmotionColors=c,this.currentUndertone=u,this.currentEmotionColors=c&&u?function(t,e){return t&&Array.isArray(t)&&e&&"clear"!==e?t.map(t=>"string"==typeof t?Ps(t,e):t&&"object"==typeof t&&t.color?{...t,color:Ps(t.color,e)}:t):t}(c,u):c;let d=i;if(Qs.isEnabled()){const i=Us&&Us.isInitialized?Us.getEmotion(e):l(e);if(i){const e=Qs.applyParticleRhythm(i,this);if(e.emitBurst)for(let i=0;i<e.emitBurst&&this.particles.length<h;i++)this.spawnSingleParticle(t,s,n);void 0!==e.emissionRate&&(d*=e.emissionRate)}}if(null!==a){for(let e=0;e<a&&this.particles.length<this.maxParticles;e++)this.spawnSingleParticle(t,s,n);return}if(this.skipSpawnThisFrame)return;for(;this.particles.length<o&&this.particles.length<this.maxParticles;)this.spawnSingleParticle(t,s,n);if(this.particles.length>=h)return;if(d<=0)return;const p=this.particleSpawner.calculateSpawnRate(d,r);for(let e=0;e<p&&this.particles.length<h;e++)this.spawnSingleParticle(t,s,n)}getSpawnPosition(t,e,i,s,n){return this.lt||(this.lt=!0),this.particleSpawner.getSpawnPosition(t,e,i,s,n,this.currentEmotion)}clampToCanvas(t,e,i,s,n=30){return this.ct||(this.ct=!0),this.particleSpawner.clampToCanvas(t,e,i,s,n)}spawnSingleParticle(t,e,i){if(this.particles.length>=this.absoluteMaxParticles)return;const s=this.canvasWidth||2*e,n=this.canvasHeight||2*i,r=this.particleSpawner.getSpawnPosition(t,e,i,s,n,this.currentEmotion),a=this.particleSpawner.clampToCanvas(r.x,r.y,s,n);r.x=a.x,r.y=a.y;const o=this.getParticleFromPool(r.x,r.y,t);"meditation_swirl"===t&&r.palmCenter&&(o.palmCenter=r.palmCenter,o.swirlAngle=r.swirlAngle),this.particles.push(o),this.particleCount++}update(t,e,i,s=null,n=0,r=null){if(this.errorBoundary)return this.errorBoundary.wrap((t,e,i,s,n,r)=>this.ut(t,e,i,s,n,r),"particle-update")(t,e,i,s,n,r);this.ut(t,e,i,s,n,r)}ut(t,e,i,s=null,n=0,r=null){for(let a=this.particles.length-1;a>=0;a--)this.particles[a].update(t,e,i,r,s,n,this.containmentBounds),this.particles[a].isAlive()||this.removeParticle(a);for(;this.particles.length>this.maxParticles;)this.removeParticle(0)}setGestureBehavior(t,e){this.gestureBehavior=e?t:null,e?this.particles.forEach(e=>{e.gestureBehavior=t}):this.particles.forEach(t=>{t.gestureBehavior=null})}removeParticle(t){if(t>=0&&t<this.particles.length){const e=this.particles.splice(t,1)[0];e.cachedGradient=null,e.cachedGradientKey=null,this.returnParticleToPool(e),this.particleCount=Math.max(0,this.particleCount-1)}}render(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.dt(t,e,i)},"particle-render")();this.dt(t,e,i)}renderBackground(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.gt(t,e,!1,i)},"particle-render-bg")();this.gt(t,e,!1,i)}renderForeground(t,e="#ffffff",i=null){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.gt(t,e,!0,i)},"particle-render-fg")();this.gt(t,e,!0,i)}gt(t,e,i,s=null){this.particleRenderer.renderLayer(t,this.particles,e,i,s)}dt(t,e,i=null){this.particleRenderer.render(t,this.particles,e,i)}onVisibilityResume(t,e=null){if(this.resetAccumulator(),t>Xs)this.clear();else if(t>1e4){const t=this.particles.length,i=e??t,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 t=this.particles.pop();if(t.cachedColors&&t.cachedColors.clear(),t.behaviorData)for(const e in t.behaviorData)delete t.behaviorData[e];this.pool.length<this.poolSize&&!this.pool.includes(t)&&this.pool.push(t)}if(this.particles.length=0,this.particleCount=0,this.spawnAccumulator=0,this.pool.length>this.poolSize){const t=this.pool.length-this.poolSize;this.pool.splice(this.poolSize,t)}}burst(t,e,i,s){if(this.errorBoundary)return this.errorBoundary.wrap(()=>{this.ft(t,e,i,s)},"particle-burst")();this.ft(t,e,i,s)}ft(t,e,i,s){const n=Math.min(t,this.maxParticles-this.particles.length);for(let t=0;t<n;t++)this.spawnSingleParticle(e,i,s)}performCleanup(){if(this.pool.length>this.poolSize){const t=this.pool.length-this.poolSize;for(let e=0;e<t;e++){const t=this.pool.pop();t&&(t.cachedGradient=null,t.cachedGradientKey=null,t.behaviorData=null)}}for(const t of this.particles)t.cachedGradient&&t.life<.5&&(t.cachedGradient=null,t.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(t){for(this.originalMaxParticles=this.originalMaxParticles||this.maxParticles,this.maxParticles=Math.max(1,t);this.particles.length>this.maxParticles;)this.removeParticle(0)}cleanupDeadParticles(){const t=this.particles.length;this.particles=this.particles.filter(t=>t.isAlive());const e=t-this.particles.length;return this.pool.length>20&&(this.pool.length=20),e}getParticlesByBehavior(t){return this.particles.filter(e=>e.behavior===t)}validateParticles(){for(const t of this.particles)if(!t.isAlive()||t.life<0||t.life>1)return!1;return!0}cleanup(){for(let t=this.particles.length-1;t>=0;t--)this.particles[t].isAlive()||this.removeParticle(t)}refreshPool(){this.particlePool.clear();for(const t of this.particles)t.life=0}setContainmentBounds(t){this.containmentBounds=t}destroy(){this.clear(),this.particlePool.clear()}}const sn=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}yt(){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(t){this.isInitialized=!1}}cacheCoreGestures(){Object.values(wi).forEach(t=>{t&&t.name&&this.gestureCache.set(t.name,{...t,cached:!0,cacheTime:performance.now()})})}cacheGestureProperties(){this.gestureCache.forEach((t,e)=>{const i={type:t.type,emoji:t.emoji,description:t.description,config:t.config,rhythm:t.rhythm,duration:this.calculateGestureDuration(t),easing:this.extractEasingFunction(t),physics:this.extractPhysicsProperties(t),timing:this.extractTimingProperties(t)};this.propertyCache.set(e,i)})}cacheCommonCombinations(){[["bounce","pulse"],["shake","vibrate"],["orbit","spin"],["morph","glow"],["breathe","fade"],["wave","drift"],["nod","sway"],["jump","stretch"]].forEach(([t,e])=>{const i=`${t}+${e}`,s=this.calculateGestureCombination(t,e);s&&this.compositionCache.set(i,s)})}cachePluginGestures(){try{const t=k.getAllPluginGestures();t&&Object.entries(t).forEach(([t,e])=>{this.pluginCache.set(t,{...e,cached:!0,cacheTime:performance.now(),isPlugin:!0})})}catch(t){}}getGesture(t){return this.yt(),this.gestureCache.has(t)?(this.stats.hits++,this.stats.gestureHits++,this.gestureCache.get(t)):this.pluginCache.has(t)?(this.stats.hits++,this.stats.gestureHits++,this.pluginCache.get(t)):(this.stats.misses++,null)}getGestureProperties(t){return this.yt(),this.propertyCache.has(t)?(this.stats.hits++,this.stats.propertyHits++,this.propertyCache.get(t)):(this.stats.misses++,null)}getGestureCombination(t,e){this.yt();const i=`${t}+${e}`;return this.compositionCache.has(i)?(this.stats.hits++,this.stats.compositionHits++,this.compositionCache.get(i)):(this.stats.misses++,null)}calculateGestureDuration(t){if(!t.config)return 1e3;const{musicalDuration:e,duration:i}=t.config;return e&&e.musical?500*(e.beats||2):i||1e3}extractEasingFunction(t){if(!t.config)return"sine";const{easing:e,particleMotion:i}=t.config;return e||i?.easing||"sine"}extractPhysicsProperties(t){if(!t.config)return{};const{amplitude:e,strength:i,size:s,rotation:n}=t.config;return{amplitude:e||20,strength:i||1,size:s||80,rotation:n||0}}extractTimingProperties(t){if(!t.config)return{};const{phases:e,timingSync:i}=t.config;return{phases:e||[],timingSync:i||{},hasPhases:!!(e&&e.length>0),hasTimingSync:!!(i&&Object.keys(i).length>0)}}calculateGestureCombination(t,e){const i=this.getGesture(t),s=this.getGesture(e);return i&&s?{gestures:[t,e],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(t,e){const i=this.extractPhysicsProperties(t),s=this.extractPhysicsProperties(e);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(t,e){return t.type===e.type?"high":"blending"===t.type&&"blending"===e.type?"medium":"override"===t.type||"override"===e.type?"low":"medium"}getStats(){const t=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(1):0;return{...this.stats,hitRate:`${t}%`,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(t){t.forEach(t=>{this.getGesture(t),this.getGestureProperties(t)})}};function nn(t){if(sn&&sn.isInitialized){const e=sn.getGesture(t);if(e)return e}return Pi(t)}const rn={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 an{constructor(){this.cache=new Map,this.easingCache=new Map,this.preCalculateEasingCurves()}preCalculateEasingCurves(){const t=["linear","ease-in","ease-out","ease-in-out","bounce"];for(const e of t){const t=new Float32Array(101);for(let i=0;i<=100;i++){const s=i/100;t[i]=this.calculateEasing(s,e)}this.easingCache.set(e,t)}}calculateEasing(t,e){switch(e){case"ease-in":return t*t;case"ease-out":return t*(2-t);case"ease-in-out":return t<.5?2*t*t:(4-2*t)*t-1;case"bounce":return t<.363636?7.5625*t*t:t<.727272?7.5625*(t-=.545454)*t+.75:t<.90909?7.5625*(t-=.818181)*t+.9375:7.5625*(t-=.954545)*t+.984375;default:return t}}getEasingValue(t,e){const i=this.easingCache.get(e);return i?i[Math.min(Math.floor(100*t),100)]:t}compose(t,e,i=null){const s=`${t}-${e}-${i||"none"}`;if(this.cache.has(s))return this.cache.get(s);const n=nn(t),r=n?n.config:{duration:500,amplitude:20,easing:"sine"},a=Us&&Us.isInitialized?Us.getModifiers(e):u(e),o=function(t){return t&&""!==t&&"clear"!==t&&rn[t]||rn.clear}(i),h=this.applyModifiers(r,a,o,t);return this.cache.size>100&&this.cache.clear(),this.cache.set(s,h),h}applyModifiers(t,e,i,s){const n={...t},r=e.speed*i.speed;if(n.duration=Math.round(t.duration/r),void 0!==n.amplitude&&(n.amplitude=t.amplitude*e.amplitude*i.amplitude),void 0!==n.scaleAmount&&(n.scaleAmount=t.scaleAmount*e.intensity*i.intensity),void 0!==n.scaleTarget){const s=e.amplitude*i.amplitude;n.scaleTarget=1+(t.scaleTarget-1)*s}void 0!==n.glowAmount&&(n.glowAmount=t.glowAmount*e.intensity*i.intensity),void 0!==n.glowPeak&&(n.glowPeak=1+(t.glowPeak-1)*e.intensity*i.intensity),void 0!==n.rotations&&(n.rotations=t.rotations*e.amplitude*i.amplitude),void 0!==n.angle&&(n.angle=t.angle*e.amplitude*i.amplitude),void 0!==n.distance&&(n.distance=t.distance*e.amplitude*i.amplitude);const a=e.smoothness*i.smoothness;return n.smoothness=a,n.easing=this.selectEasing(t.easing,a),n.regularity=e.regularity*i.regularity,n.effects=[],e.addBounce&&n.effects.push("bounce"),e.addGravity&&n.effects.push("gravity"),e.addShake&&n.effects.push("shake"),e.addJitter&&n.effects.push("shake"),e.addPop&&n.effects.push("pop"),e.addRecoil&&n.effects.push("recoil"),e.addWarmth&&n.effects.push("warmth"),e.addFlow&&n.effects.push("flow"),e.addWobble&&n.effects.push("wobble"),e.addVibration&&n.effects.push("vibration"),e.addDrag&&n.effects.push("drag"),e.addWeight&&n.effects.push("weight"),e.addTension&&n.effects.push("tension"),e.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,e,i),t.particleMotion&&(n.particleMotion={...t.particleMotion},void 0!==n.particleMotion.strength&&(n.particleMotion.strength*=e.intensity*i.intensity),void 0!==n.particleMotion.frequency&&(n.particleMotion.frequency*=r),void 0!==n.particleMotion.amplitude&&(n.particleMotion.amplitude*=e.amplitude*i.amplitude)),n}selectEasing(t,e){return e<.5?"linear":e<.8?"quad":e<1.2?t:e<1.5?"cubic":"sine"}applyGestureSpecificMods(t,e,i,s){switch(e){case"bounce":i.addShake&&(t.frequency=Math.floor(1.5*t.frequency)),i.addGravity&&(t.amplitude*=.6,t.frequency=1);break;case"pulse":i.addWarmth&&(t.frequency=2,t.glowAmount*=1.5),s.addFlutter&&(t.irregular=!0);break;case"shake":i.addJitter&&(t.frequency*=1.5,t.amplitude*=1.2),i.addShake&&(t.amplitude*=1.5,t.decay=!1);break;case"spin":i.addBounce&&(t.rotations*=1.5),i.addWobble&&(t.wobble=!0)}}clearCache(){this.cache.clear()}}const on=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 t=[{musical:!0,beats:1},{musical:!0,bars:1},{musical:!0,beats:.5},{musical:!0,beats:2}];[60,90,120,140,160,180].forEach(e=>{t.forEach(t=>{const i=`${e}_${JSON.stringify(t)}`,s=this.toMilliseconds(t,e);if(this.cache.size>=this.maxCacheSize){const t=this.cacheAccessOrder.shift();this.cache.delete(t)}this.cache.set(i,s),this.cacheAccessOrder.push(i)})})}toMilliseconds(t,e=null){const i=e||Vs.bpm||120;if("number"==typeof t)return t;if("object"==typeof t&&t.musical){const e=6e4/i;if(void 0!==t.beats)return t.beats*e;if(void 0!==t.bars){const i=Vs.timeSignature||[4,4];return t.bars*i[0]*e}if(void 0!==t.subdivision)return(this.noteDurations[t.subdivision]||1)*e}return 1e3}toMusical(t,e=null){const i=t/(6e4/(e||Vs.bpm||120));let s="quarter",n=Math.abs(i-1);for(const[t,e]of Object.entries(this.noteDurations)){const r=Math.abs(i-e);r<n&&(n=r,s=t)}return{musical:!0,beats:i,bars:i/4,closestSubdivision:s,exact:n<.01}}calculatePhases(t,e){if(!t||0===t.length)return[{name:"main",beats:e,start:0,end:1}];const i=t.reduce((t,e)=>t+(e.beats||1),0),s=e/i;let n=0;return t.map(t=>{const i=(t.beats||1)*s,r=n/e;n+=i;const a=n/e;return{name:t.name,beats:i,start:r,end:a,duration:this.toMilliseconds({musical:!0,beats:i})}})}getBeatProgress(){const t=Vs.getTimeInfo();return t?t.beatProgress:0}getBarProgress(){const t=Vs.getTimeInfo();return t?t.barProgress:0}timeToNextBoundary(t="beat"){const e=Vs.getTimeInfo();if(!e)return 100;switch(t){case"beat":default:return e.nextBeatIn;case"bar":return(e.timeSignature[0]-e.beatInBar)*e.beatDuration;case"phrase":{const t=4,i=e.timeSignature[0];return(t-(e.bar||0)%t)*i*e.beatDuration}}}quantize(t,e="eighth"){const i=6e4/(Vs.bpm||120),s=(this.noteDurations[e]||1)*i;return Math.round(t/s)*s}isOnBoundary(t="beat",e=50){const i=this.timeToNextBoundary(t),s=Vs.getTimeInfo();return!!s&&(i<e||s.beatDuration-i<e)}getTempoAdaptation(t=120){const e=(Vs.bpm||120)/t;return{speed:e,energy:Math.min(2,Math.max(.5,e)),smoothness:e<.8?1.2:e>1.5?.8:1,intensity:e>1.3?1.2:e<.7?.8:1}}};class hn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyBounce(t,e){return{offsetY:-Math.abs(Math.sin(e*Math.PI*t.params.frequency))*t.params.amplitude*this.scaleFactor*(t.params.effects&&t.params.effects.includes("gravity")?.6:1)}}applyShake(t,e){t.randomAngle||(t.randomAngle=Math.random()*Math.PI*2);const i=t.params.decay?1-e:1,s=Math.sin(e*Math.PI*t.params.frequency)*t.params.amplitude*i*this.scaleFactor;return{offsetX:s*Math.cos(t.randomAngle),offsetY:s*Math.sin(t.randomAngle)}}applyJump(t,e){let i,s,n=0,r=1;if(e<.2){const i=e/.2;r=1-(1-t.params.squashAmount)*i}else if(e<.7){const i=(e-.2)/.5,s=Math.sin(i*Math.PI);n=-t.params.jumpHeight*s*this.scaleFactor,r=t.params.squashAmount+(t.params.stretchAmount-t.params.squashAmount)*s}else{const i=(e-.7)/.3;r=t.params.stretchAmount-(t.params.stretchAmount-1)*i}if(t.params.effects&&t.params.effects.includes("gravity")){const t=e<.7?(e-.2)/.5:0,n=Math.sin(t*Math.PI);i=1+.2*n,s=1-.15*n}const a={offsetY:n,scale:r};return void 0!==i&&(a.scaleX=i),void 0!==s&&(a.scaleY=s),a}applyVibrate(t,e){if(!t.vibrateAngles){t.vibrateAngles={x:2*Math.random()-1,y:2*Math.random()-1};const e=Math.sqrt(t.vibrateAngles.x**2+t.vibrateAngles.y**2);t.vibrateAngles.x/=e,t.vibrateAngles.y/=e}const i=t.params.amplitude||5,s=t.params.frequency||20,n=Math.sin(e*Math.PI*2*s)*i*this.scaleFactor;return{offsetX:n*t.vibrateAngles.x,offsetY:n*t.vibrateAngles.y}}applyWiggle(t,e){const i=(t.params?.amplitude||15)*this.scaleFactor;void 0===t.wiggleDirection&&(t.wiggleDirection=Math.random()<.5?1:-1);const s=t.wiggleDirection;let n=0,r=0;if(e<.25){const t=e/.25;n=i*s*t,r=3*s*t}else if(e<.5){const t=(e-.25)/.25;n=i*s*(1-2*t),r=3*s*(1-2*t)}else if(e<.75){const t=(e-.5)/.25;n=i*-s*(1-2*t),r=3*-s*(1-2*t)}else{const t=(e-.75)/.25;n=i*s*(1-t),r=3*s*(1-t)}return{offsetX:n,offsetY:-Math.abs(Math.sin(e*Math.PI*4))*i*.15,rotation:r}}}class ln{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyFlash(t,e){const i=Math.sin(e*Math.PI);return{glow:1+((t.params.glowPeak||2)-1)*i,scale:1+((t.params.scalePeak||1.1)-1)*i}}applyGlow(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+i*(t.params.scaleAmount||.1),glow:1+i*(t.params.glowAmount||.8)}}applyFlicker(t,e){const i=t.params?.intensity||2,s=t.params?.speed||3,n=1+Math.sin(e*Math.PI*2*s)*i*.3,r=5*Math.sin(e*Math.PI*4)*this.scaleFactor,a=.001*Date.now();return{offsetX:r,glow:n,particleGlow:(.5*Math.sin(e*Math.PI*s*2)+.5)*i,flickerTime:a,flickerEffect:!0}}applySparkle(t,e){const i=t.params?.intensity||2,s=.001*Date.now();return{particleGlow:i,glow:.3*Math.sin(e*Math.PI*4)+.7,fireflyTime:s,fireflyEffect:!0}}applyShimmer(t,e){const i=.001*Date.now(),s=t.params?.intensity||.3,n=Math.sin(2*i+e*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 cn{constructor(t){this.renderer=t}applyBreathe(t,e){const{params:i}=t,s=i.particleMotion?.holdPercent||.1;let n;if(e<.4)n=Math.sin(e/.4*Math.PI/2);else if(e<.4+s)n=1;else if(e<.9){const t=(e-.4-s)/(.5-s);n=Math.cos(t*Math.PI/2)}else n=0;const r=1+n*(i.scaleAmount||.25),a=1+n*(i.glowAmount||.4);return t.breathPhase=n,{scale:r,glow:a,breathPhase:n}}applyBreathIn(t,e){return{scale:1+(t.params.scaleAmount-1)*Math.sin(e*Math.PI/2)}}applyBreathOut(t,e){return{scale:1-(1-t.params.scaleAmount)*Math.sin(e*Math.PI/2)}}applyBreathHold(t,e){return{scale:t.params.scaleAmount}}applyBreathHoldEmpty(t,e){return{scale:t.params.scaleAmount}}}class un{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applySpin(t,e){return{rotation:Math.min(1.05*e,1)*t.params.rotations*360,scale:1+Math.sin(e*Math.PI)*t.params.scaleAmount}}applyDrift(t,e){e<=.01&&!t.currentDriftAngle&&(t.currentDriftAngle=Math.random()*Math.PI*2);const i=t.params.distance*Math.sin(e*Math.PI)*this.scaleFactor,s=t.currentDriftAngle||0;return e>=.99&&(t.currentDriftAngle=null),{offsetX:Math.cos(s)*i,offsetY:Math.sin(s)*i}}applyWave(t,e){const i=(t.params.amplitude||40)*this.scaleFactor,s=e*Math.PI*2,n=Math.sin(s)*i,r=-Math.sin(e*Math.PI)*i*.3;return{offsetX:n,offsetY:Math.sin(2*s)*i*.2+r,rotation:5*Math.sin(s),scale:1+.05*Math.sin(e*Math.PI*2),glow:1+.2*Math.sin(e*Math.PI)}}applySway(t,e){const i=(t.params?.amplitude||30)*this.scaleFactor,s=t.params?.frequency||1;return{offsetX:Math.sin(e*Math.PI*2*s)*i,offsetY:Math.sin(e*Math.PI*4*s)*i*.1,rotation:5*Math.sin(e*Math.PI*2*s)}}applyFloat(t,e){const i=(t.params?.amplitude||20)*this.scaleFactor,s=t.params?.speed||1,n=Math.sin(e*Math.PI*2*s)*i;return{offsetX:Math.sin(e*Math.PI*3*s)*i*.3,offsetY:n,scale:1+.02*Math.sin(e*Math.PI*4*s)}}applyOrbital(t,e){return{offsetX:0,offsetY:0}}applyHula(t,e){const i=(t.params?.amplitude||40)*this.scaleFactor,s=e*Math.PI*2;return{offsetX:Math.sin(s)*i,offsetY:Math.sin(2*s)*i*.5}}applyOrbit(t,e){const i=(t.params?.radius||30)*this.scaleFactor,s=t.params?.speed||1,n=e*Math.PI*2*s;return{offsetX:Math.cos(n)*i,offsetY:Math.sin(n)*i}}}class dn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyPulse(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+i*t.params.scaleAmount,glow:1+i*t.params.glowAmount}}applyExpand(t,e){const i=Math.max(t.params.scaleAmount||t.params.scaleTarget||1.5,1),s=Math.sin(e*Math.PI/2);return{scale:1+(i-1)*s,glow:1+Math.abs(t.params.glowAmount||.2)*s}}applyContract(t,e){const i=t.params.scaleAmount||t.params.scaleTarget||.7,s=Math.sin(e*Math.PI/2);return{scale:1+(i-1)*s,glow:1+(t.params.glowAmount||-.2)*s}}applyStretch(t,e){const i=Math.sin(e*Math.PI*t.params.frequency);return{scale:1+((t.params.scaleX+t.params.scaleY)/2-1)*i}}applyMorph(t,e){const i=Math.sin(e*Math.PI*2);return{scale:1+.1*i,rotation:10*i}}}class pn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyNod(t,e){return{offsetY:Math.sin(e*Math.PI*t.params.frequency)*t.params.amplitude*this.scaleFactor}}applyTilt(t,e){t.tiltDirection||(t.tiltDirection=Math.random()<.5?-1:1);const i=t.params.frequency||2,s=(t.params.angle||15)*Math.PI/180,n=Math.sin(e*Math.PI*i)*t.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(t,e){let i=1;return i=e<.3?1-e/.3:e<.5?0:e<.8?(e-.5)/.3:1,{glow:i}}applyLook(t,e){if(!t.targetX){const e=t.params.lookDirection,i=50*t.params.lookDistance*this.scaleFactor;switch(e){case"left":t.targetX=-i,t.targetY=0;break;case"right":t.targetX=i,t.targetY=0;break;case"up":t.targetX=0,t.targetY=-i;break;case"down":t.targetX=0,t.targetY=i;break;default:{const e=Math.random()*Math.PI*2;t.targetX=Math.cos(e)*i,t.targetY=Math.sin(e)*i;break}}}let i=e;return i=e<.3?e/.3:e<.7?1:1-(e-.7)/.3,{offsetX:t.targetX*i,offsetY:t.targetY*i}}applySettle(t,e){const i=Math.sin(e*Math.PI*t.params.wobbleFreq)*Math.exp(3*-e)*20*this.scaleFactor;return{offsetY:i,scale:1+.01*i}}}class mn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyPoint(t,e){void 0===t.pointDirection&&(t.pointDirection=Math.random()<.5?-1:1);const i=void 0!==t.params?.direction?t.params.direction:t.pointDirection,s=(t.params?.distance||40)*this.scaleFactor;let n,r;return e<.4?(n=1-Math.pow(1-e/.4,3),r=n):e<.6?(n=1,r=1):(n=Math.pow(1-(e-.6)/.4,3),r=n),{offsetX:i*s*n,offsetY:-Math.abs(.15*s*n),scale:1+.15*r,rotation:5*i*r}}applyLean(t,e){const i=t.params?.angle||15,s=t.params?.side||1,n=Math.sin(e*Math.PI),r=i*s*n;return{offsetX:10*s*this.scaleFactor*n,rotation:r}}applyReach(t,e){const i=void 0!==t.params?.direction?t.params.direction:-Math.PI/2,s=(t.params?.distance||40)*this.scaleFactor;let n;return n=e<.4?e/.4:e<.6?1:1-(e-.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 gn{constructor(t){this.renderer=t,this.scaleFactor=t.scaleFactor||1}applyFlashWave(t,e){t.flashWave||(t.flashWave={innerRadius:0,outerRadius:0,maxRadius:3}),t.flashWave.outerRadius=e*t.flashWave.maxRadius,t.flashWave.innerRadius=Math.max(0,(e-.1)*t.flashWave.maxRadius);const i=Math.max(0,1-.7*e);return t.flashWaveData={innerRadius:t.flashWave.innerRadius,outerRadius:t.flashWave.outerRadius,intensity:i},{glow:1+.3*i,flashWave:t.flashWaveData}}applyRain(t,e){return{offsetX:0,offsetY:0,particleEffect:"rain"}}applyGroove(t,e){const i=(t.params?.amplitude||25)*this.scaleFactor;return{offsetX:Math.sin(e*Math.PI*2)*i+Math.sin(e*Math.PI*3+.5)*i*.4,offsetY:Math.sin(e*Math.PI*4+.3)*i*.25,scale:1+.03*Math.sin(e*Math.PI*3+.7),rotation:8*Math.sin(e*Math.PI*2+.2)}}applyHeadBob(t,e){const i=(t.params?.amplitude||20)*this.scaleFactor,s=e*(t.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(t,e){const i=20*Math.sin(e*Math.PI*4)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(e*Math.PI*8))*this.scaleFactor,rotation:.3*i,scaleY:1-.05*Math.abs(Math.sin(e*Math.PI*8))}}applyCharleston(t,e){const i=25*Math.sin(e*Math.PI*8)*this.scaleFactor;return{offsetX:i,offsetY:10*-Math.abs(Math.sin(e*Math.PI*8))*this.scaleFactor,rotation:.6*i,scaleY:1-.06*Math.abs(Math.sin(e*Math.PI*8))}}}class fn{constructor(t){this.renderer=t,this.activeGestures=new Map,this.scaleFactor=t.scaleFactor||1,this.physicalGestureAnimator=new hn(t),this.visualEffectAnimator=new ln(t),this.breathGestureAnimator=new cn(t),this.movementGestureAnimator=new un(t),this.shapeTransformAnimator=new dn(t),this.expressionGestureAnimator=new pn(t),this.directionalGestureAnimator=new mn(t),this.complexAnimationAnimator=new gn(t),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(t){const e=nn(t);if(["bounce","shake","pulse","flash","jump","slam","spin","flicker"].includes(t)&&this.renderer.specialEffects){const e={flash:1,jump:1,shake:.9,bounce:.8,pulse:.7,slam:1,spin:.8,flicker:1}[t]||.8;this.renderer.specialEffects.triggerChromaticAberration(e)}let i;i=this.renderer.gestureCompositor?this.renderer.gestureCompositor.compose(t,this.renderer.state.emotion,this.renderer.currentUndertone):e?.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(e&&e.config)if(e.config.musicalDuration)s=on.toMilliseconds(e.config.musicalDuration);else if(e.config.duration){const{duration:t}=e.config;s=t}const n=this.gestureAnimations[t];n&&(n.active=!0,n.startTime=performance.now(),n.progress=0,n.params=i,n.duration=s,"shake"===t?n.randomAngle=void 0:"drift"===t?(n.startX=void 0,n.startY=void 0,n.currentDriftAngle=void 0):"tilt"===t?n.tiltDirection=void 0:"vibrate"===t&&(n.vibrateAngles=void 0))}applyGestureAnimations(){const t=performance.now(),e={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=t-s.startTime,r=s.duration||(s.params?s.params.duration:1e3);s.progress=Math.min(n/r,1);const a=this.applyEasing(s.progress,s.params.easing);let o={};switch(i){case"bounce":o=this.applyBounce(s,a);break;case"pulse":o=this.applyPulse(s,a);break;case"shake":o=this.applyShake(s,a);break;case"spin":o=this.applySpin(s,a);break;case"nod":o=this.applyNod(s,a);break;case"tilt":o=this.applyTilt(s,a);break;case"expand":o=this.applyExpand(s,a);break;case"contract":o=this.applyContract(s,a);break;case"flash":o=this.applyFlash(s,a);break;case"drift":o=this.applyDrift(s,a);break;case"stretch":o=this.applyStretch(s,a);break;case"glow":o=this.applyGlow(s,a);break;case"flicker":o=this.applyFlicker(s,a);break;case"vibrate":o=this.applyVibrate(s,a);break;case"orbital":o=this.applyOrbital(s,a);break;case"hula":o=this.applyHula(s,a);break;case"wave":o=this.applyWave(s,a);break;case"breathe":o=this.applyBreathe(s,a);break;case"morph":o=this.applyMorph(s,a);break;case"slowBlink":o=this.applySlowBlink(s,a);break;case"look":o=this.applyLook(s,a);break;case"settle":o=this.applySettle(s,a);break;case"breathIn":o=this.applyBreathIn(s,a);break;case"breathOut":o=this.applyBreathOut(s,a);break;case"breathHold":o=this.applyBreathHold(s,a);break;case"breathHoldEmpty":o=this.applyBreathHoldEmpty(s,a);break;case"jump":o=this.applyJump(s,a);break;case"sway":o=this.applySway(s,a);break;case"float":o=this.applyFloat(s,a);break;case"rain":o=this.applyRain(s,a);break;case"runningman":o=this.applyRunningMan(s,a);break;case"charleston":o=this.applyCharleston(s,a);break;case"sparkle":o=this.applySparkle(s,a);break;case"shimmer":o=this.applyShimmer(s,a);break;case"wiggle":o=this.applyWiggle(s,a);break;case"groove":o=this.applyGroove(s,a);break;case"point":o=this.applyPoint(s,a);break;case"lean":o=this.applyLean(s,a);break;case"reach":o=this.applyReach(s,a);break;case"headBob":o=this.applyHeadBob(s,a);break;case"orbit":o=this.applyOrbit(s,a)}e.offsetX+=o.offsetX||0,e.offsetY+=o.offsetY||0,e.scale*=o.scale||1,e.rotation+=o.rotation||0,e.glow=Math.max(e.glow,o.glow||1),o.flashWave&&(e.flashWave=o.flashWave),o.fireflyEffect&&(e.fireflyEffect=o.fireflyEffect,e.particleGlow=o.particleGlow,e.fireflyTime=o.fireflyTime),o.flickerEffect&&(e.flickerEffect=o.flickerEffect,e.particleGlow=o.particleGlow,e.flickerTime=o.flickerTime),o.shimmerEffect&&(e.shimmerEffect=o.shimmerEffect,e.particleGlow=o.particleGlow,e.shimmerTime=o.shimmerTime,e.shimmerWave=o.shimmerWave),o.glowEffect&&(e.glowEffect=o.glowEffect,e.particleGlow=o.particleGlow,e.glowTime=o.glowTime,e.glowProgress=o.glowProgress,e.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 e}update(t){return this.applyGestureAnimations()}stopAllGestures(){Object.keys(this.gestureAnimations).forEach(t=>{const e=this.gestureAnimations[t];e.active=!1,e.startTime=0,e.progress=0,e.params=null,e.glowEffect&&(e.glowEffect=null,e.particleGlow=null,e.glowTime=null,e.glowProgress=null,e.glowEnvelope=null),e.fireflyEffect&&(e.fireflyEffect=null,e.particleGlow=null,e.fireflyTime=null),e.flickerEffect&&(e.flickerEffect=null,e.particleGlow=null,e.flickerTime=null),e.shimmerEffect&&(e.shimmerEffect=null,e.particleGlow=null,e.shimmerTime=null,e.shimmerWave=null),e.flashWave&&(e.flashWave=null,e.flashWaveData=null)}),this.activeGestures.clear()}getCurrentGesture(){const t=performance.now(),e=["orbital","hula","wave","spin"];for(const i of e){const e=this.gestureAnimations[i];if(e&&e.active){const s=nn(i),n=t-e.startTime,r=e.duration||(e.params?e.params.duration:1e3),a=Math.min(n/r,1);return{name:i,particleMotion:s?.config?.particleMotion||{type:i,strength:e.params?.strength||1},progress:a,params:e.params}}}for(const[e,i]of Object.entries(this.gestureAnimations))if(i.active){const s=nn(e),n=t-i.startTime,r=i.duration||(i.params?i.params.duration:1e3),a=Math.min(n/r,1),o={name:e,particleMotion:s?.config?.particleMotion||i.params?.particleMotion||{type:e,strength:i.params?.strength||1},progress:a,params:i.params};return"breathe"===e&&void 0!==i.breathPhase&&(o.breathPhase=i.breathPhase),o}return null}applyEasing(t,e){switch(e){case"linear":default:return t;case"quad":return t*t;case"cubic":return t*t*t;case"sine":return Math.sin(t*Math.PI/2);case"back":return t*t*(2.7*t-1.7)}}applyBounce(t,e){return this.physicalGestureAnimator.applyBounce(t,e)}applyPulse(t,e){return this.shapeTransformAnimator.applyPulse(t,e)}applyShake(t,e){return this.physicalGestureAnimator.applyShake(t,e)}applySpin(t,e){return this.movementGestureAnimator.applySpin(t,e)}applyNod(t,e){return this.expressionGestureAnimator.applyNod(t,e)}applyTilt(t,e){return this.expressionGestureAnimator.applyTilt(t,e)}applyExpand(t,e){return this.shapeTransformAnimator.applyExpand(t,e)}applyContract(t,e){return this.shapeTransformAnimator.applyContract(t,e)}applyFlash(t,e){return this.visualEffectAnimator.applyFlash(t,e)}applyDrift(t,e){return this.movementGestureAnimator.applyDrift(t,e)}applyStretch(t,e){return this.shapeTransformAnimator.applyStretch(t,e)}applyGlow(t,e){return this.visualEffectAnimator.applyGlow(t,e)}applyFlashWave(t,e){return this.complexAnimationAnimator.applyFlashWave(t,e)}applyFlicker(t,e){return this.visualEffectAnimator.applyFlicker(t,e)}applyVibrate(t,e){return this.physicalGestureAnimator.applyVibrate(t,e)}applyWave(t,e){return this.movementGestureAnimator.applyWave(t,e)}applyBreathe(t,e){return this.breathGestureAnimator.applyBreathe(t,e)}applyMorph(t,e){return this.shapeTransformAnimator.applyMorph(t,e)}applySlowBlink(t,e){return this.expressionGestureAnimator.applySlowBlink(t,e)}applyLook(t,e){return this.expressionGestureAnimator.applyLook(t,e)}applySettle(t,e){return this.expressionGestureAnimator.applySettle(t,e)}applyBreathIn(t,e){return this.breathGestureAnimator.applyBreathIn(t,e)}applyBreathOut(t,e){return this.breathGestureAnimator.applyBreathOut(t,e)}applyBreathHold(t,e){return this.breathGestureAnimator.applyBreathHold(t,e)}applyBreathHoldEmpty(t,e){return this.breathGestureAnimator.applyBreathHoldEmpty(t,e)}applyJump(t,e){return this.physicalGestureAnimator.applyJump(t,e)}applySway(t,e){return this.movementGestureAnimator.applySway(t,e)}applyRain(t,e){return this.complexAnimationAnimator.applyRain(t,e)}applyFloat(t,e){return this.movementGestureAnimator.applyFloat(t,e)}applyOrbital(t,e){return this.movementGestureAnimator.applyOrbital(t,e)}applyHula(t,e){return this.movementGestureAnimator.applyHula(t,e)}applySparkle(t,e){return this.visualEffectAnimator.applySparkle(t,e)}applyShimmer(t,e){return this.visualEffectAnimator.applyShimmer(t,e)}applyWiggle(t,e){return this.physicalGestureAnimator.applyWiggle(t,e)}applyGroove(t,e){return this.complexAnimationAnimator.applyGroove(t,e)}applyPoint(t,e){return this.directionalGestureAnimator.applyPoint(t,e)}applyLean(t,e){return this.directionalGestureAnimator.applyLean(t,e)}applyReach(t,e){return this.directionalGestureAnimator.applyReach(t,e)}applyHeadBob(t,e){return this.complexAnimationAnimator.applyHeadBob(t,e)}applyOrbit(t,e){return this.movementGestureAnimator.applyOrbit(t,e)}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(t,e){return this.complexAnimationAnimator.applyRunningMan(t,e)}applyCharleston(t,e){return this.complexAnimationAnimator.applyCharleston(t,e)}startRunningManGesture(){this.startGesture("runningman")}startCharlestonGesture(){this.startGesture("charleston")}pauseCurrentAnimation(){const t=performance.now();for(const[,e]of Object.entries(this.gestureAnimations))e.active&&(e.pausedAt=t,e.pausedProgress=e.progress);this.isPaused=!0}resumeAnimation(){if(!this.isPaused)return;const t=performance.now();for(const[,e]of Object.entries(this.gestureAnimations))if(e.active&&e.pausedAt){const i=t-e.pausedAt;e.startTime&&(e.startTime+=i),delete e.pausedAt,delete e.pausedProgress}this.isPaused=!1}reset(){for(const[,t]of Object.entries(this.gestureAnimations))t.active=!1,t.progress=0,t.params={},delete t.startTime,delete t.pausedAt,delete t.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 yn{constructor(){this.colorTransition=null}applyUndertoneModifiers(t,e){return e}applyUndertoneToColor(t,e){if(e&&"object"==typeof e&&void 0!==e.weight){const{weight:i}=e,s=e.type||"clear";if("clear"===s||0===i)return t;const n=this.applyUndertoneSaturation(t,s),r=this.hexToRgb(t),a=this.hexToRgb(n),o=Math.round(r.r+(a.r-r.r)*i),h=Math.round(r.g+(a.g-r.g)*i),l=Math.round(r.b+(a.b-r.b)*i);return this.rgbToHex(o,h,l)}return e&&"clear"!==e?this.applyUndertoneSaturation(t,e):t}hexToRgb(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:null}rgbToHsl(t,e,i){t/=255,e/=255,i/=255;const s=Math.max(t,e,i),n=Math.min(t,e,i),r=(s+n)/2;let a,o;if(s===n)a=o=0;else{const h=s-n;switch(o=r>.5?h/(2-s-n):h/(s+n),s){case t:a=((e-i)/h+(e<i?6:0))/6;break;case e:a=((i-t)/h+2)/6;break;case i:a=((t-e)/h+4)/6}}return{h:360*a,s:100*o,l:100*r}}hslToHex(t,e,i){let s,n,r;if(t/=360,i/=100,0==(e/=100))s=n=r=i;else{const a=(t,e,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t),o=i<.5?i*(1+e):i+e-i*e,h=2*i-o;s=a(h,o,t+1/3),n=a(h,o,t),r=a(h,o,t-1/3)}const a=t=>{const e=Math.round(255*t).toString(16);return 1===e.length?`0${e}`:e};return`#${a(s)}${a(n)}${a(r)}`}applyUndertoneSaturation(t,e){const i=this.hexToRgb(t),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}[e]||1;return s.s=Math.min(100,s.s*n),this.hslToHex(s.h,s.s,s.l)}rgbToHex(t,e,i){const s=t=>{const e=Math.round(t).toString(16);return 1===e.length?`0${e}`:e};return`#${s(t)}${s(e)}${s(i)}`}startColorTransition(t,e,i=1500){this.currentColor===t&&this.currentIntensity===e||(this.colorTransition={active:!0,fromColor:this.currentColor||"#ffffff",toColor:t,fromIntensity:this.currentIntensity||1,toIntensity:e,progress:0,startTime:performance.now(),duration:i})}updateColorTransition(t){if(!this.colorTransition||!this.colorTransition.active)return null;const e=performance.now()-this.colorTransition.startTime,i=Math.min(e/this.colorTransition.duration,1),s=1-Math.pow(1-i,2),n=this.hexToRgb(this.colorTransition.fromColor),r=this.hexToRgb(this.colorTransition.toColor),a=Math.round(n.r+(r.r-n.r)*s),o=Math.round(n.g+(r.g-n.g)*s),h=Math.round(n.b+(r.b-n.b)*s),l=this.rgbToHex(a,o,h),c=this.colorTransition.fromIntensity+(this.colorTransition.toIntensity-this.colorTransition.fromIntensity)*s;return this.currentColor=l,this.currentIntensity=c,i>=1&&(this.colorTransition.active=!1),{color:l,intensity:c}}}class Mn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.canvasManager?.canvas||t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}renderRecordingGlow(t,e,i,s){const{ctx:n}=this,r=2.5*i,a=n.createRadialGradient(t,e,0,t,e,r);a.addColorStop(0,`rgba(255, 0, 0, ${.3*s})`),a.addColorStop(.5,`rgba(255, 0, 0, ${.15*s})`),a.addColorStop(1,"rgba(255, 0, 0, 0)"),n.save(),n.globalCompositeOperation="screen",n.fillStyle=a,n.fillRect(t-r,e-r,2*r,2*r),n.restore()}renderRecordingIndicator(t,e){const i=Date.now()/1e3,s=.8+.2*Math.sin(2*i);this.ctx.save(),this.ctx.translate(t,e),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(t,e,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:t+Math.random()*this.scaleValue(30)-this.scaleValue(15),y:e+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(t=>{if(t.lifetime+=i,t.y+=t.speed*i,t.x+=Math.sin(8e-4*t.lifetime)*t.drift*.008,t.rotation+=.01*i,t.lifetime<2e3?t.opacity=1:t.lifetime<4e3?t.opacity=1-(t.lifetime-2e3)/2e3:t.opacity=0,t.opacity>.01){this.ctx.save(),this.ctx.translate(t.x,t.y),this.ctx.rotate(t.rotation*Math.PI/180);const e=this.renderer.state.glowColor||"#4a90e2";this.ctx.shadowBlur=this.scaleValue(15),this.ctx.shadowColor=this.hexToRgba(e,.5*t.opacity);const i=this.ctx.createLinearGradient(-t.size/2,-t.size/2,t.size/2,t.size/2);return i.addColorStop(0,this.hexToRgba(e,t.opacity)),i.addColorStop(.5,this.hexToRgba("#ffffff",.9*t.opacity)),i.addColorStop(1,this.hexToRgba(e,.7*t.opacity)),this.ctx.font=`italic ${t.weight||"900"} ${t.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=i,this.ctx.textAlign="center",this.ctx.textBaseline="middle",this.ctx.fillText(t.text||"Z",0,0),this.ctx.shadowBlur=0,this.ctx.font=`italic ${t.weight||"900"} ${.9*t.size}px 'Poppins', sans-serif`,this.ctx.fillStyle=this.hexToRgba("#ffffff",.3*t.opacity),this.ctx.fillText(t.text||"Z",-1,-1),this.ctx.restore(),!0}return!1})}renderSpeakingRings(t,e,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(t,e,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(t,e,i={}){this.sparkles.push({x:t,y:e,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:t}=this;this.sparkles.forEach(e=>{const i=1-e.lifetime/e.maxLifetime,s=1-i;t.save(),t.translate(e.x,e.y),t.rotate(e.rotation);const n=this.scaleValue(e.size*(1-.5*i));t.beginPath();const r=n,a=.38*n;for(let e=0;e<10;e++){const i=e*Math.PI/5-Math.PI/2,s=e%2==0?r:a;0===e?t.moveTo(Math.cos(i)*s,Math.sin(i)*s):t.lineTo(Math.cos(i)*s,Math.sin(i)*s)}t.closePath(),t.shadowBlur=this.scaleValue(10),t.shadowColor=e.color,t.fillStyle=e.color.replace("70%",70+30*i+"%").replace(")",`, ${s})`).replace("hsl","hsla"),t.fill(),t.restore()})}triggerChromaticAberration(t=.8){this.chromaticAberration.active=!0,this.chromaticAberration.targetIntensity=Math.min(1,t),this.chromaticAberration.intensity=this.chromaticAberration.targetIntensity;const e=document.getElementById("emotive-canvas")||document.querySelector("canvas")||this.canvas;if(e){if(e.style.animation="none",!document.getElementById("chromatic-styles")){const t=document.createElement("style");t.id="chromatic-styles",t.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(t)}e.style.animation=`chromaticGlitch ${300+200*t}ms ease-out`}}applyChromaticAberration(t,e){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return;const{intensity:i}=this.chromaticAberration,s=this.scaleValue(this.chromaticAberration.maxOffset*i),n=t.globalCompositeOperation;t.save(),t.clearRect(0,0,t.canvas.width,t.canvas.height),t.globalCompositeOperation="source-over",t.filter="url(#red-channel)",t.drawImage(e,-s,0),t.globalCompositeOperation="screen",t.filter="url(#green-channel)",t.drawImage(e,0,0),t.globalCompositeOperation="screen",t.filter="url(#blue-channel)",t.drawImage(e,s,0),t.filter="none",t.globalCompositeOperation=n,t.restore()}applyChromaticAberrationSimple(t,e,i,s,n){if(!this.chromaticAberration.active||this.chromaticAberration.intensity<=0)return void n();const{intensity:r}=this.chromaticAberration,a=this.scaleValue(this.chromaticAberration.maxOffset*r);t.save(),t.globalCompositeOperation="source-over",t.translate(-a,0),t.globalAlpha=.33,t.fillStyle="#ff0000",t.filter="brightness(3)",n(),t.translate(a,0),t.globalCompositeOperation="screen",t.globalAlpha=.33,t.fillStyle="#00ff00",n(),t.translate(a,0),t.globalAlpha=.33,t.fillStyle="#0000ff",n(),t.restore()}update(t){this.sparkles=this.sparkles.filter(e=>(e.x+=e.vx,e.y+=e.vy,e.rotation+=e.rotationSpeed,e.lifetime-=t,e.vy+=.1,e.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 bn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}update(t){this.blinking&&(this.blinkTimer+=t,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 t=Math.min(this.blinkTimer/150,1);return 1-.7*Math.sin(t*Math.PI)}drawEyes(t,e,i,s,n={}){const{ctx:r}=this,a=n.eyeOpenness||1,o=n.eyeExpression||"neutral";if("neutral"===s||a<=0)return;r.save(),r.strokeStyle="rgba(0, 0, 0, 0.3)",r.lineWidth=this.scaleValue(2),r.lineCap="round";const h=.4*i,l=e-.1*i,c=.25*i;switch(o){case"happy":this.drawHappyEyes(r,t,l,h,c,a);break;case"sad":this.drawSadEyes(r,t,l,h,c,a);break;case"angry":this.drawAngryEyes(r,t,l,h,c,a);break;case"surprised":this.drawSurprisedEyes(r,t,l,h,c,a);break;case"focused":this.drawFocusedEyes(r,t,l,h,c,a);break;case"sleepy":this.drawSleepyEyes(r,t,l,h,c,a);break;case"suspicious":this.drawSuspiciousEyes(r,t,l,h,c,a)}r.restore()}drawHappyEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i,n,.2*Math.PI,.8*Math.PI,!1),t.stroke(),t.beginPath(),t.arc(e+s,i,n,.2*Math.PI,.8*Math.PI,!1),t.stroke()}drawSadEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),t.stroke(),t.beginPath(),t.arc(e+s,i+.5*n,n,1.2*Math.PI,1.8*Math.PI,!1),t.stroke()}drawAngryEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i-.3*n),t.lineTo(e-s+.5*n,i+.3*n),t.stroke(),t.beginPath(),t.moveTo(e+s+n,i-.3*n),t.lineTo(e+s-.5*n,i+.3*n),t.stroke()}drawSurprisedEyes(t,e,i,s,n,r){t.beginPath(),t.arc(e-s,i,1.2*n,0,2*Math.PI),t.stroke(),t.beginPath(),t.arc(e+s,i,1.2*n,0,2*Math.PI),t.stroke()}drawFocusedEyes(t,e,i,s,n,r){t.fillStyle="rgba(0, 0, 0, 0.4)",t.beginPath(),t.arc(e-s,i,.3*n,0,2*Math.PI),t.fill(),t.beginPath(),t.arc(e+s,i,.3*n,0,2*Math.PI),t.fill()}drawSleepyEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i),t.lineTo(e-s+n,i),t.stroke(),t.beginPath(),t.moveTo(e+s-n,i),t.lineTo(e+s+n,i),t.stroke()}drawSuspiciousEyes(t,e,i,s,n,r){t.beginPath(),t.moveTo(e-s-n,i),t.lineTo(e-s+.7*n,i),t.stroke(),t.beginPath(),t.arc(e+s,i,.8*n,.1*Math.PI,.9*Math.PI,!1),t.stroke()}setBlinkingEnabled(t){this.blinkingEnabled=t,t||(this.blinking=!1,this.blinkTimer=0)}setSquintAmount(t){this.squintAmount=Math.max(0,Math.min(1,t))}forceBlink(){this.startBlink()}}class wn{constructor(t){this.renderer=t,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(t,e,i={}){i=i||{};const s=this.emotionBreathPatterns[e]||{rate:1,depth:1},n=i?.breathRateMult||1,r=i?.breathDepthMult||1;this.breathRate=s.rate*this.breathRateMult*n,this.breathDepth=this.breathingDepth*s.depth*this.breathDepthMult*r;let a=this.breathingSpeed*this.breathRate*(t/1e3);this.breathIrregular&&i?.breathIrregular&&(a*=.8+.4*Math.sin(3e-4*Date.now())),this.breathingPhase+=a,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(t){this.customScale=t}setBreathingSpeed(t){this.breathingSpeed=t}setBreathingDepth(t){this.breathingDepth=Math.max(0,Math.min(1,t))}setBreathRateMultiplier(t){this.breathRateMult=t}setBreathDepthMultiplier(t){this.breathDepthMult=t}setIrregularBreathing(t){this.breathIrregular=t}reset(){this.breathingPhase=0,this.breathRate=1,this.breathDepth=this.breathingDepth,this.breathRateMult=1,this.breathDepthMult=1,this.breathIrregular=!1,this.customScale=null}holdBreath(t=!1){this.customScale=t?.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}}}const vn=new class{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(t,e){if("radial"===t){const{x0:t,y0:i,r0:s,x1:n,y1:r,r1:a,stops:o}=e;return`radial:${t},${i},${s},${n},${r},${a}:${o.map(t=>`${t.offset}:${t.color}`).join("|")}`}if("linear"===t){const{x0:t,y0:i,x1:s,y1:n,stops:r}=e;return`linear:${t},${i},${s},${n}:${r.map(t=>`${t.offset}:${t.color}`).join("|")}`}return null}getRadialGradient(t,e,i,s,n,r,a,o){const h=this.generateKey("radial",{x0:e,y0:i,r0:s,x1:n,y1:r,r1:a,stops:o}),l=this.cache.get(h);if(l&&Date.now()-l.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(h),l.gradient;this.stats.misses++;const c=t.createRadialGradient(e,i,s,n,r,a);return o.forEach(t=>{c.addColorStop(t.offset,t.color)}),this.set(h,c),c}getLinearGradient(t,e,i,s,n,r){const a=this.generateKey("linear",{x0:e,y0:i,x1:s,y1:n,stops:r}),o=this.cache.get(a);if(o&&Date.now()-o.timestamp<this.ttl)return this.stats.hits++,this.updateAccessOrder(a),o.gradient;this.stats.misses++;const h=t.createLinearGradient(e,i,s,n);return r.forEach(t=>{h.addColorStop(t.offset,t.color)}),this.set(a,h),h}set(t,e){this.cache.size>=this.maxSize&&!this.cache.has(t)&&this.evictLRU(),this.cache.set(t,{gradient:e,timestamp:Date.now()}),this.updateAccessOrder(t)}updateAccessOrder(t){const e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1),this.accessOrder.push(t)}evictLRU(){if(this.accessOrder.length>0){const t=this.accessOrder.shift();this.cache.delete(t),this.stats.evictions++}}clear(){this.cleanupInterval&&(clearInterval(this.cleanupInterval),this.cleanupInterval=null),this.cache.clear(),this.accessOrder=[]}clearExpired(){const t=Date.now(),e=[];for(const[i,s]of this.cache.entries())t-s.timestamp>=this.ttl&&e.push(i);e.forEach(t=>{this.cache.delete(t);const e=this.accessOrder.indexOf(t);e>-1&&this.accessOrder.splice(e,1)})}destroy(){this.clear()}getStats(){const t=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:`${t}%`}}createHelper(t){return{radial:(e,i,s,n,r,a,o)=>this.getRadialGradient(t,e,i,s,n,r,a,o),linear:(e,i,s,n,r)=>this.getLinearGradient(t,e,i,s,n,r)}}};class Sn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.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=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i),this.initOffscreenCanvas()}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d")}updateOffscreenSize(t){this.offscreenCanvas.width===t&&this.offscreenCanvas.height===t||(this.offscreenCanvas.width=t,this.offscreenCanvas.height=t,this.cachedGlowColor=null)}renderGlow(t,e,i,s={}){const{ctx:n}=this,r=s.color||this.glowColor,a=void 0!==s.intensity?s.intensity:this.glowIntensity;a<.01||this.renderGlowDirect(n,t,e,i,r,a)}cacheGlowGradient(t,e){const i=this.offscreenCtx,s=e;this.updateOffscreenSize(2*e),i.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height);const n=vn.getRadialGradient(i,s,s,0,s,s,e,[{offset:0,color:this.hexToRgba(t,.4)},{offset:.3,color:this.hexToRgba(t,.2)},{offset:.6,color:this.hexToRgba(t,.1)},{offset:1,color:this.hexToRgba(t,0)}]);i.fillStyle=n,i.fillRect(0,0,2*e,2*e),this.cachedGlowColor=t,this.cachedGlowRadius=e}renderGlowDirect(t,e,i,s,n,r){t.save(),t.globalCompositeOperation="screen";const a=[];for(let t=0;t<=20;t++){const e=t/20,i=.6*Math.pow(1-e,2.2),s=Math.max(0,Math.min(1,i*r));a.push({offset:e,color:this.hexToRgba(n,s)})}const o=vn.getRadialGradient(t,e,i,0,e,i,s,a);t.fillStyle=o,t.beginPath(),t.arc(e,i,s,0,2*Math.PI),t.fill(),t.restore()}renderRecordingGlow(t,e,i,s){const{ctx:n}=this,r=2.5*i,a=vn.getRadialGradient(n,t,e,0,t,e,r,[{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=a,n.fillRect(t-r,e-r,2*r,2*r),n.restore()}updateGlowColor(t,e){this.targetGlowColor!==t&&(this.targetGlowColor=t,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(t,e,i){const s=this.hexToRgb(t),n=this.hexToRgb(e);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(t){const e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);return e?{r:parseInt(e[1],16),g:parseInt(e[2],16),b:parseInt(e[3],16)}:{r:0,g:0,b:0}}setGlowIntensity(t){this.glowIntensity=Math.max(0,Math.min(1,t))}setGlowColor(t){this.glowColor=t,this.targetGlowColor=t,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 kn{constructor(t){this.renderer=t,this.ctx=t.ctx,this.canvas=t.canvas,this.coreColor="#FFFFFF",this.coreOpacity=1,this.coreBorderWidth=0,this.coreBorderColor=null,this.shapePoints=null,this.isMorphing=!1,this.scaleValue=e=>t.scaleValue(e),this.hexToRgba=(e,i)=>t.hexToRgba(e,i)}renderCore(t,e,i,s={}){const{ctx:n}=this,r=s.scaleX||1,a=s.scaleY||1,o=s.rotation||0,h=void 0!==s.opacity?s.opacity:this.coreOpacity,l=s.color||this.coreColor,c=s.shapePoints||this.shapePoints;n.save(),n.translate(t,e),0!==o&&n.rotate(o),n.scale(r,a),n.fillStyle=this.hexToRgba(l,h),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(t,e,i){t.save();const s=this.scaleValue(2);if(t.translate(0,s),i&&i.length>32)t.fillStyle="rgba(0, 0, 0, 0.15)",t.beginPath(),t.arc(0,0,1.05*e,0,2*Math.PI),t.fill();else{const s=vn.getRadialGradient(t,0,0,.7*e,0,0,1.2*e,[{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(t.fillStyle=s,t.beginPath(),i){const e=1.1,s=i.length>20?2:1;t.moveTo(i[0].x*e,i[0].y*e);for(let n=s;n<i.length;n+=s)t.lineTo(i[n].x*e,i[n].y*e);t.closePath()}else t.arc(0,0,1.1*e,0,2*Math.PI);t.fill()}t.restore()}drawCircle(t,e){t.beginPath(),t.arc(0,0,e,0,2*Math.PI),t.fill()}drawMorphedShape(t,e,i){!e||e.length<3?this.drawCircle(t,i):(t.beginPath(),e.forEach((e,i)=>{0===i?t.moveTo(e.x,e.y):t.lineTo(e.x,e.y)}),t.closePath(),t.fill())}renderSleepyCore(t,e,i){const{ctx:s}=this;s.save(),s.translate(t,e),s.scale(1,.85),s.fillStyle="#FFFFFF",s.beginPath(),s.arc(0,0,i,0,2*Math.PI),s.fill(),s.restore()}renderGlitchedCore(t,e,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(r=>{n.fillStyle=this.hexToRgba("#FFFFFF",r.alpha*s),n.beginPath(),n.arc(t+r.x*s*this.scaleValue(5),e+r.y*s*this.scaleValue(5),i,0,2*Math.PI),n.fill()}),n.fillStyle="#FFFFFF",n.beginPath(),n.arc(t,e,i,0,2*Math.PI),n.fill(),n.restore()}setShapePoints(t){this.shapePoints=t,this.isMorphing=t&&t.length>0}clearShapePoints(){this.shapePoints=null,this.isMorphing=!1}setCoreColor(t){this.coreColor=t}setCoreOpacity(t){this.coreOpacity=Math.max(0,Math.min(1,t))}setCoreBorder(t,e){this.coreBorderWidth=t,this.coreBorderColor=e}getCoreInfo(){return{color:this.coreColor,opacity:this.coreOpacity,hasBorder:this.coreBorderWidth>0,isMorphing:this.isMorphing,shapePointCount:this.shapePoints?this.shapePoints.length:0}}}class xn{renderSunEffects(t,e,i,s,n){const r=Date.now()/100;if(t.save(),t.translate(e,i),n.texture&&(void 0===n.textureOpacity||n.textureOpacity>0)){t.save(),t.globalCompositeOperation="screen",t.globalAlpha=void 0!==n.textureOpacity?n.textureOpacity:1;const e=.05*r*(n.turbulence||.3)/.3,i=t.createRadialGradient(Math.sin(e)*s*.15,Math.cos(.7*e)*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)"),t.fillStyle=i,t.beginPath(),t.arc(0,0,s,0,2*Math.PI),t.fill(),t.restore()}const a=void 0!==n.coronaOpacity?n.coronaOpacity:1;if(a>0){t.save(),t.globalCompositeOperation="screen";const e=t.createRadialGradient(0,0,.5*s,0,0,1.1*s);e.addColorStop(0,`rgba(255, 255, 255, ${.8*a})`),e.addColorStop(.3,`rgba(255, 250, 200, ${.6*a})`),e.addColorStop(.5,`rgba(255, 200, 100, ${.4*a})`),e.addColorStop(.7,`rgba(255, 150, 50, ${.2*a})`),e.addColorStop(1,"rgba(255, 100, 20, 0)"),t.fillStyle=e,t.beginPath(),t.arc(0,0,1.1*s,0,2*Math.PI),t.fill();for(let e=0;e<2;e++){const i=1.3+.4*e,n=(.35-.15*e)*a,o=.05*Math.sin(.1*r+e),h=t.createRadialGradient(0,0,s*(.9+o),0,0,s*(i+o));h.addColorStop(0,"rgba(255, 255, 200, 0)"),h.addColorStop(.4,`rgba(255, 200, 100, ${.5*n})`),h.addColorStop(.7,`rgba(255, 150, 50, ${n})`),h.addColorStop(.9,`rgba(255, 100, 30, ${.5*n})`),h.addColorStop(1,"rgba(255, 50, 10, 0)"),t.fillStyle=h,t.beginPath(),t.arc(0,0,s*(i+o),0,2*Math.PI),t.fill()}t.restore()}if(n.flares){t.save();const e=Math.sin(.08*r),i=Math.sin(.12*r),n=Math.sin(.16*r),a=t.createLinearGradient(0,-s,0,3*-s);a.addColorStop(0,"rgba(255, 255, 230, 0.4)"),a.addColorStop(.2,"rgba(255, 220, 150, 0.25)"),a.addColorStop(.5,"rgba(255, 180, 80, 0.15)"),a.addColorStop(.8,"rgba(255, 120, 40, 0.08)"),a.addColorStop(1,"rgba(255, 60, 20, 0)"),t.fillStyle=a,t.globalCompositeOperation="screen",t.beginPath();const o=(e,i,n,r)=>{const a=Math.cos(e),o=Math.sin(e),h=a*s,l=o*s,c=a*(s+i),u=o*(s+i),d=-o*n*.5,p=a*n*.5,m=r*n*.3;t.moveTo(h-d,l-p),t.quadraticCurveTo(.5*(h+c)+d*m,.5*(l+u)+p*m,c,u),t.quadraticCurveTo(.5*(h+c)-d*m,.5*(l+u)-p*m,h+d,l+p)};for(let t=0;t<8;t++)o(t/8*Math.PI*2+.1*e,s*(1.8+.4*Math.sin(.1*r+.5*t)),.18*s,Math.sin(.15*r+t));for(let t=0;t<12;t++)o((t+.5)/12*Math.PI*2+.08*i,s*(1.2+.3*Math.sin(.13*r+.7*t)),.12*s,Math.sin(.18*r+1.2*t));for(let t=0;t<15;t++)o(t/15*Math.PI*2+.05*n,s*(.7+.25*Math.sin(.17*r+.9*t)),.08*s,Math.sin(.2*r+1.5*t));for(let e=0;e<15;e++){const i=(e+.25)/15*Math.PI*2,n=s*(.4+.2*Math.sin(.22*r+e)),a=.06*s,o=Math.cos(i),h=Math.sin(i),l=o*s,c=h*s,u=o*(s+n),d=h*(s+n),p=-h*a*.5,m=o*a*.5;t.moveTo(l-p,c-m),t.lineTo(u,d),t.lineTo(l+p,c+m)}t.fill(),t.restore()}const o=t.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)"),t.fillStyle=o,t.beginPath(),t.arc(0,0,1.05*s,0,2*Math.PI),t.fill(),t.restore()}renderBaileysBeads(t,e,i,s,n,r,a,o,h,l=t=>t){if(!h)return void(this.Mt=null);const c=Math.abs(n)<1&&Math.abs(r)<1,u=o?30:15;if(!(Math.abs(n)<u&&Math.abs(r)<u||c))return void(this.Mt=null);if(!this.Mt){const t=Math.floor(4*Math.random())+1;this.bt=[];const e=[];for(let i=0;i<t;i++)e.push(Math.random()*Math.PI*2);const i=Array.from({length:t},(t,e)=>e);for(let t=i.length-1;t>0;t--){const e=Math.floor(Math.random()*(t+1));[i[t],i[e]]=[i[e],i[t]]}for(let s=0;s<t;s++)this.bt.push({angle:e[s],size:3+5*Math.random(),order:i[s],delay:200*i[s]});this.Mt=Date.now()}const d=Date.now()-this.Mt;(this.bt||[]).forEach(n=>{if(d<n.delay)return;const r=d-n.delay,a=Math.min(1,r/300),o=e+Math.cos(n.angle)*s,h=i+Math.sin(n.angle)*s;t.save(),t.translate(o,h),t.globalAlpha=a;const c=l(n.size),u=[{color:`rgba(255, 100, 100, ${.6*a})`,offset:-2},{color:`rgba(100, 255, 100, ${.6*a})`,offset:0},{color:`rgba(100, 100, 255, ${.6*a})`,offset:2}];t.globalCompositeOperation="screen",u.forEach(({color:e,offset:i})=>{const s=t.createRadialGradient(i,i,0,i,i,2*c);s.addColorStop(0,e),s.addColorStop(.2,e.replace(""+.6*a,""+.4*a)),s.addColorStop(.5,e.replace(""+.6*a,""+.2*a)),s.addColorStop(1,"rgba(255, 255, 255, 0)"),t.fillStyle=s,t.beginPath(),t.arc(i,i,2*c,0,2*Math.PI),t.fill()}),t.globalCompositeOperation="lighter";const p=t.createRadialGradient(0,0,0,0,0,c);p.addColorStop(0,`rgba(255, 255, 255, ${a})`),p.addColorStop(.3,`rgba(255, 255, 255, ${.5*a})`),p.addColorStop(1,"rgba(255, 255, 255, 0)"),t.fillStyle=p,t.beginPath(),t.arc(0,0,c,0,2*Math.PI),t.fill(),t.restore()})}renderMoonShadow(t,e,i,s,n,r,a=!1,o=0,h=null){if(t.save(),t.globalAlpha=1,t.translate(e,i),"crescent"===n.type){let e=1,i=n.offset||.7;if(h){const t=h.getProgress(),{targetShape:s}=h;"moon"===s&&void 0!==t&&t<1&&!n.shadowX&&(e=t,i=2.7*e-2)}const a=(n.angle||-30)*Math.PI/180,o=Math.cos(a)*s*i,l=Math.sin(a)*s*i;if(t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.beginPath(),r&&r.length>0){t.moveTo(r[0].x,r[0].y);for(let e=1;e<r.length;e++)t.lineTo(r[e].x,r[e].y);t.closePath()}else t.arc(0,0,s,0,2*Math.PI);t.clip();const c=t.createRadialGradient(o,l,.9*s,o,l,1.1*s),u=void 0!==n.coverage?n.coverage:.85,d=Math.min(1,1.2*e)*(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)"),t.fillStyle=c,t.beginPath(),t.arc(o,l,1.1*s,0,2*Math.PI),t.fill()}else if("lunar"===n.type){const e=1-(void 0!==n.diffusion?n.diffusion:1);let i=0,r=0;if(h){const t=h.getProgress(),{currentShape:e,targetShape:n}=h;if(a&&"solar"===n&&void 0!==t&&t<1){const e=2.5*s;i=-e*(1-t),r=e*(1-t)}else if(a&&"solar"===e&&"solar"!==n&&null!==n&&void 0!==t&&t<1){const e=2.5*s;i=e*t,r=-e*t}}t.translate(i,r),a?(t.save(),t.beginPath(),t.arc(-i,-r,s,0,2*Math.PI),t.clip()):(t.beginPath(),t.arc(0,0,s,0,2*Math.PI),t.clip());const o=s*(1.8-.5*e),l=t.createRadialGradient(0,0,.2*s,0,0,o),c=n.coverage||.9;if(n.color&&n.color.includes("0, 0, 0")?(l.addColorStop(0,`rgba(0, 0, 0, ${c})`),l.addColorStop(.3+.2*e,`rgba(0, 0, 0, ${.95*c})`),l.addColorStop(.6+.2*e,`rgba(0, 0, 0, ${.8*c})`),l.addColorStop(.85,`rgba(0, 0, 0, ${.4*c})`),l.addColorStop(1,"rgba(0, 0, 0, 0)")):(l.addColorStop(0,`rgba(10, 2, 0, ${c})`),l.addColorStop(.3+.2*e,`rgba(20, 5, 0, ${.95*c})`),l.addColorStop(.6+.2*e,`rgba(40, 10, 5, ${.8*c})`),l.addColorStop(.85,`rgba(60, 15, 10, ${.4*c})`),l.addColorStop(1,"rgba(80, 20, 15, 0)")),t.fillStyle=l,t.beginPath(),t.arc(0,0,o,0,2*Math.PI),t.fill(),e>.3){const i=s*(.8+.3*e),r=t.createRadialGradient(0,0,0,0,0,i);n.color&&n.color.includes("0, 0, 0")?(r.addColorStop(0,`rgba(0, 0, 0, ${c})`),r.addColorStop(.5,`rgba(0, 0, 0, ${.9*c})`),r.addColorStop(.8,`rgba(0, 0, 0, ${.5*c})`),r.addColorStop(1,"rgba(0, 0, 0, 0)")):(r.addColorStop(0,`rgba(0, 0, 0, ${c})`),r.addColorStop(.5,`rgba(10, 2, 0, ${.9*c})`),r.addColorStop(.8,`rgba(20, 5, 0, ${.5*c})`),r.addColorStop(1,"rgba(30, 8, 5, 0)")),t.fillStyle=r,t.beginPath(),t.arc(0,0,i,0,2*Math.PI),t.fill()}}a&&t.restore(),t.restore()}}class En{constructor(t){this.renderer=t,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(t,e,i,s,n){if(!t||!this.episodicEffects[t])return{jitterX:e,jitterY:i,coreRadius:s,glowRadius:n};const r=this.episodicEffects[t],a=performance.now();if(!r.active&&a>=r.nextTrigger)switch(r.active=!0,r.startTime=a,t){case"nervous":r.duration=500+500*Math.random(),r.intensity=2+Math.random(),r.nextTrigger=a+3e3+2e3*Math.random();break;case"confident":r.duration=1e3+1e3*Math.random(),r.intensity=.15,r.nextTrigger=a+4e3+2e3*Math.random();break;case"tired":r.duration=1e3+2e3*Math.random(),r.intensity=.2,r.nextTrigger=a+5e3+2e3*Math.random();break;case"intense":r.duration=500+500*Math.random(),r.intensity=.5,r.nextTrigger=a+3e3+3e3*Math.random();break;case"subdued":r.duration=2e3+1e3*Math.random(),r.intensity=.3,r.nextTrigger=a+4e3+3e3*Math.random()}if(r.active){const o=a-r.startTime;if(o<r.duration){const a=o/r.duration;switch(t){case"nervous":{const t=1-a,s=15,n=Math.sin(a*Math.PI*s)*t;e=n*r.intensity,i=n*r.intensity*.7;break}case"confident":{const t=Math.sin(a*Math.PI);s*=1+r.intensity*t,n*=1+.5*r.intensity*t;break}case"tired":{const t=Math.sin(a*Math.PI*.5);s*=1-r.intensity*t,i+=5*t;break}case"intense":{const t=1-Math.cos(a*Math.PI);s*=1-.05*t,n*=1+r.intensity*t;break}case"subdued":{const t=Math.sin(a*Math.PI*.5);s*=1-.1*t,n*=1-r.intensity*t;break}}}else r.active=!1}return{jitterX:e,jitterY:i,coreRadius:s,glowRadius:n}}reset(){Object.keys(this.episodicEffects).forEach(t=>{this.episodicEffects[t].active=!1,this.episodicEffects[t].startTime=0,this.episodicEffects[t].duration=0,this.episodicEffects[t].intensity=0})}getEpisodeState(t){return this.episodicEffects[t]||null}isEpisodeActive(t){const e=this.episodicEffects[t];return!!e&&e.active}}class Bn{constructor(t){this.renderer=t,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(t={}){return this.brakeToTarget(0,t)}brakeToNearest(t,e={}){const i=this.renderer.state.manualRotation||0,s=Math.round(i/t)*t;return this.brakeToTarget(s,e)}brakeToTarget(t,e={}){return new Promise(i=>{const{onProgress:s=null,onComplete:n=null}=e;this.onProgress=s,this.onComplete=n;const r=this.renderer.state.rotationSpeed||0,a=this.renderer.state.manualRotation||0;if(0===r||this.brakeStartTime)return void i();if(this.brakeStartTime=performance.now(),this.brakeStartRotation=a,this.brakeStartVelocity=r,0===t)this.brakeTargetRotation=r>0?360*(Math.floor(a/360)+1):360*Math.floor(a/360);else{const e=t%360,i=Math.floor(a/360);this.brakeTargetRotation=r>0?e>a%360?360*i+e:360*(i+1)+e:e<a%360?360*i+e:360*(i-1)+e}const o=Math.abs(this.brakeTargetRotation-this.brakeStartRotation);this.brakeDuration=Math.max(500,o/Math.abs(r)*this.DURATION_FACTOR*5),this.renderer.setRotationSpeed(0),this.resolvePromise=i})}updateBrake(t){if(!this.brakeStartTime)return null;const e=t-this.brakeStartTime,i=Math.min(e/this.brakeDuration,1),s=1-Math.pow(1-i,4),n=this.brakeStartRotation+(this.brakeTargetRotation-this.brakeStartRotation)*s,r=this.brakeStartVelocity*Math.pow(1-s,2);return this.onProgress&&this.onProgress(s,r,n),i>=1?(this.brakeStartTime=null,this.complete(),{rotation:this.brakeTargetRotation,speed:0,complete:!0}):{rotation:n,speed:r,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 t=performance.now()-this.brakeStartTime;return Math.min(t/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 An{constructor(t){this.renderer=t,this.rotationBrake=new Bn(t)}setRotationSpeed(t){this.renderer.state.rotationSpeed=t}setRotationAngle(t){this.renderer.state.manualRotation=t}getRotationAngle(){return this.renderer.state.manualRotation}getRotationSpeed(){return this.renderer.state.rotationSpeed}isBraking(){return this.rotationBrake&&this.rotationBrake.isBraking()}updateRotation(t){if(this.rotationBrake&&this.rotationBrake.isBraking()){const e=this.rotationBrake.updateBrake(t);e&&(this.renderer.state.manualRotation=e.rotation,this.renderer.state.rotationSpeed=e.complete?0:e.speed)}else 0!==this.renderer.state.rotationSpeed&&(this.renderer.state.manualRotation+=this.renderer.state.rotationSpeed);this.renderer.state.lastRotationUpdate=t}calculateTotalRotation(t=0,e=0){return(t+e+this.renderer.state.manualRotation)*Math.PI/180}applyRotation(t,e){0!==e&&t.rotate(e)}applyRotationTransform(t,e,i,s){this.updateRotation(performance.now());const n=this.calculateTotalRotation(s);return 0!==n&&(t.save(),t.translate(e,i),this.applyRotation(t,n),t.translate(-e,-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 Cn=class{constructor(t){this.renderer=t,this.canvas=t.canvas,this.initialized=!1,this.handleMouseMove=null,this.handleTouchMove=null}setEnabled(t){this.renderer.state.gazeTrackingEnabled=t,t?this.initialized||this.initialize():this.renderer.state.gazeTarget={x:0,y:0}}initialize(){this.initialized||(this.handleMouseMove=t=>{if(!this.renderer.state.gazeTrackingEnabled)return;const e=this.canvas.getBoundingClientRect(),i=e.width/2,s=e.height/2,n=t.clientX-e.left-i,r=t.clientY-e.top-s;this.renderer.state.gazeTarget={x:n/i,y:r/s}},this.handleTouchMove=t=>{if(this.renderer.state.gazeTrackingEnabled&&t.touches.length>0){const e=t.touches[0],i=this.canvas.getBoundingClientRect(),s=i.width/2,n=i.height/2,r=e.clientX-i.left-s,a=e.clientY-i.top-n;this.renderer.state.gazeTarget={x:r/s,y:a/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 Tn{constructor(t){this.renderer=t}setupCanvas(){this.renderer.updateOffscreenSize();const t=this.renderer.canvasManager.width||this.renderer.canvas.width||400,e=this.renderer.canvasManager.height||this.renderer.canvas.height||400,i=this.renderer.ctx;return this.renderer.ctx=this.renderer.offscreenCtx,{logicalWidth:t,logicalHeight:e,originalCtx:i}}renderBackdrop(t,e,i,s){const n=Math.min(t,e),r=this.renderer.getEffectiveCenter(),a=r.x,o=r.y-this.renderer.config.topOffset,h=n/this.renderer.config.referenceSize*this.renderer.config.baseScale*(r.coreScale||r.scale),l=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*h;this.renderer.backdropRenderer.update(s),this.renderer.audioAnalyzer&&this.renderer.audioAnalyzer.currentAmplitude&&this.renderer.backdropRenderer.setAudioIntensity(this.renderer.audioAnalyzer.currentAmplitude),this.renderer.backdropRenderer.render(a,o,l,i)}applyCanvasDecay(t,e,i){const s=this.renderer.particleSystem?this.renderer.particleSystem.particles.length:0,n=.12+Math.min(.08,.003*s);t.save(),t.globalCompositeOperation="destination-out",t.fillStyle=`rgba(0, 0, 0, ${n})`,t.fillRect(0,0,e,i),t.restore()}clearOffscreenCanvas(t,e){this.renderer.ctx.clearRect(0,0,t,e)}performCanvasSetup(t,e,i,s){this.renderBackdrop(t,e,i,s),this.applyCanvasDecay(i,t,e),this.clearOffscreenCanvas(t,e)}}class Pn{constructor(t){this.renderer=t}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 t=this.markFrameStart();return this.handleCleanRender(),t}}class Dn{constructor(t){this.renderer=t}mergeTransforms(t,e){const i=this.renderer.ambientDanceAnimator.getTransform(e);return t?(t.x=(t.x||0)+(i.x||0),t.y=(t.y||0)+(i.y||0),t.rotation=(t.rotation||0)+(i.rotation||0),t.scale=(t.scale||1)*(i.scale||1),t):i}mergeAndStoreTransforms(t,e){const i=this.mergeTransforms(t,e);return this.renderer.gestureTransform=i,i}}class Rn{constructor(t){this.renderer=t}updateUndertoneModifiers(){if(this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers){const t=this.renderer.stateMachine.getWeightedUndertoneModifiers();t?this.renderer.applyUndertoneModifiers(t):this.renderer.applyUndertoneModifiers(null)}}updateColorTransition(t){this.renderer.colorTransition&&this.renderer.colorTransition.active&&this.renderer.updateColorTransition(t)}updateAnimationTimers(t){this.renderer.updateTimers(t)}updateGazeOffset(){if(this.renderer.state.gazeTrackingEnabled){const t=.15,e=50;this.renderer.state.gazeOffset.x+=(this.renderer.state.gazeTarget.x*e-this.renderer.state.gazeOffset.x)*t,this.renderer.state.gazeOffset.y+=(this.renderer.state.gazeTarget.y*e-this.renderer.state.gazeOffset.y)*t}else{const t=.1;this.renderer.state.gazeOffset.x+=(0-this.renderer.state.gazeOffset.x)*t,this.renderer.state.gazeOffset.y+=(0-this.renderer.state.gazeOffset.y)*t}}performFrameStateUpdates(t){this.updateUndertoneModifiers(),this.updateColorTransition(t),this.updateAnimationTimers(t),this.updateGazeOffset()}}class Fn{constructor(t){this.renderer=t}calculateBaseDimensions(t,e){const i=Math.min(t,e),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(t,e,i){const s=t.x;let n=t.y-this.renderer.config.topOffset;return e.properties&&e.properties.verticalOffset&&(n=t.y-this.renderer.config.topOffset+i*e.properties.verticalOffset),{centerX:s,centerY:n}}applyGestureTransform(t,e,i){let s=1,n=0,r=1;return i&&(t+=i.x||0,e+=i.y||0,s=i.scale||1,n=(i.rotation||0)*Math.PI/180,r=i.glowIntensity||1),{centerX:t,centerY:e,scaleMultiplier:s,rotationAngle:n,glowMultiplier:r}}applyGestureAnimations(t,e,i,s,n){const r=this.renderer.gestureAnimator.applyGestureAnimations();return r&&(t+=r.offsetX||0,e+=r.offsetY||0,i*=r.scale||1,s+=(r.rotation||0)*Math.PI/180,n=r.glow||1),{centerX:t,centerY:e,scaleMultiplier:i,rotationAngle:s,glowMultiplier:n,gestureTransforms:r}}calculateRenderDimensions(t,e,i,s){const{canvasSize:n,effectiveCenter:r}=this.calculateBaseDimensions(t,e);let a,o,h,{centerX:l,centerY:c}=this.calculateCenterPosition(r,i,e);({centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h}=this.applyGestureTransform(l,c,s));const u=this.applyGestureAnimations(l,c,a,o,h);({centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h}=u);const{gestureTransforms:d}=u;return{canvasSize:n,effectiveCenter:r,centerX:l,centerY:c,scaleMultiplier:a,rotationAngle:o,glowMultiplier:h,gestureTransforms:d}}}var zn={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:t=>!0===t.recording,apply(t,e){const{deltaTime:i=16.67}=e;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(t,e,i){t.save();const s=Math.min(e,i),n=Math.floor(.08*s),r=1.5*n,a=1.5*n,o=.3*n;t.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),t.beginPath(),t.arc(r-n,a,o,0,2*Math.PI),t.fill(),t.strokeStyle=this.hexToRgba("#FFFFFF",.8*this.state.intensity),t.lineWidth=3,t.font=`bold ${n}px 'Arial', sans-serif`,t.textAlign="left",t.textBaseline="middle",t.strokeText("REC",r,a),t.fillStyle=this.hexToRgba("#FF0000",this.state.intensity),t.fillText("REC",r,a),t.restore()},hexToRgba:(t,e)=>`rgba(${parseInt(t.slice(1,3),16)}, ${parseInt(t.slice(3,5),16)}, ${parseInt(t.slice(5,7),16)}, ${e})`,reset(){this.state.pulsePhase=0,this.state.intensity=0}},qn={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:t=>!0===t.speaking,apply(t,e){const{x:i,y:s,radius:n,audioLevel:r=0,deltaTime:a=16.67}=e;this.state.smoothedLevel+=(r-this.state.smoothedLevel)*this.config.smoothing,r>.5&&this.state.audioLevel<=.5&&this.state.rings.push({radius:n,opacity:.5,speed:2}),this.config.ringEffect&&this.drawRings(t,i,s,a),this.state.audioLevel=r},drawRings(t,e,i,s){t.save(),t.strokeStyle="rgba(100, 200, 255, 0.5)",t.lineWidth=2;for(let n=this.state.rings.length-1;n>=0;n--){const r=this.state.rings[n];r.radius+=r.speed*(s/16.67),r.opacity-=s/16.67*.02,r.opacity<=0?this.state.rings.splice(n,1):(t.globalAlpha=r.opacity,t.beginPath(),t.arc(e,i,r.radius,0,2*Math.PI),t.stroke())}t.restore()},getScaleModifier(){return 1+this.state.smoothedLevel*this.config.scaleMultiplier}},On={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:t=>!0===t.sleeping||"resting"===t.emotion,apply(t,e){const{x:i,y:s,radius:n,deltaTime:r=16.67}=e,a=Date.now();if(a-this.state.lastZSpawn>this.config.zParticleInterval){const t=[100,200,300,400,500,600,700,800,900],e=t[Math.floor(Math.random()*t.length)];this.state.zParticles.push({x:i+n,y:s-n,opacity:1,size:12+8*Math.random(),drift:.5*Math.random()-.25,weight:e,rotation:30*Math.random()-15}),this.state.lastZSpawn=a}this.drawZParticles(t,r)},drawZParticles(t,e){t.save(),t.textAlign="center",t.textBaseline="middle";for(let i=this.state.zParticles.length-1;i>=0;i--){const s=this.state.zParticles[i];s.y-=this.config.zDriftSpeed*(e/16.67),s.x+=s.drift*(e/16.67),s.opacity-=this.config.zFadeSpeed*(e/16.67),s.rotation+=e/16.67*.5,s.opacity<=0?this.state.zParticles.splice(i,1):(t.save(),t.translate(s.x,s.y),t.rotate(s.rotation*Math.PI/180),t.globalAlpha=.7*s.opacity,t.fillStyle="rgba(255, 255, 255, 0.9)",t.font=`${s.weight} ${s.size}px 'Poppins', sans-serif`,t.fillText("Z",0,0),t.shadowBlur=3,t.shadowColor="rgba(147, 112, 219, 0.5)",t.fillText("Z",0,0),t.restore())}t.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}}},jn={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:t=>"suspicion"===t.emotion||!0===t.suspicious,apply(t,e){const{deltaTime:i=16.67}=e,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(t){this.state.targetSquint=this.config.squintAmount;const e=this.state.targetSquint-this.state.currentSquint;Math.abs(e)>.01?this.state.currentSquint+=e*this.config.squintSpeed*(t/16.67):this.state.currentSquint=this.state.targetSquint},startScan(){this.state.scanning=!0,this.state.scanStartTime=Date.now(),this.state.scanPhase=-1},updateScan(t,e){const i=(t-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(t,e,i,s){if(!this.state.scanning)return;t.save(),t.strokeStyle="rgba(255, 165, 0, 0.3)",t.lineWidth=1,t.setLineDash([5,5]);const n=this.state.scanPhase*(this.config.scanAngle*Math.PI/180),r=e+Math.cos(n)*s*2,a=i+Math.sin(n)*s*.5;t.beginPath(),t.moveTo(e,i),t.lineTo(r,a),t.stroke(),t.restore()}},In={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:t=>t.gazeIntensity>0||t.gazeLocked,apply(t,e){const{gazeIntensity:i=0,deltaTime:s=16.67}=e;if(i>this.config.focusThreshold){const t=(i-this.config.focusThreshold)/(1-this.config.focusThreshold);this.state.targetScaleX=1+(this.config.maxHorizontalScale-1)*t,this.state.targetScaleY=1-(1-this.config.maxVerticalScale)*t}else this.state.targetScaleX=1,this.state.targetScaleY=1;this.animateScales(s)},animateScales(t){const e=this.config.smoothing*(t/16.67),i=this.state.targetScaleX-this.state.currentScaleX;Math.abs(i)>.001&&(this.state.currentScaleX+=i*e);const s=this.state.targetScaleY-this.state.currentScaleY;Math.abs(s)>.001&&(this.state.currentScaleY+=s*e)},getEyeScales(){return{scaleX:this.state.currentScaleX,scaleY:this.state.currentScaleY}},drawFocusIndicator(t,e,i,s,n){if(n<this.config.focusThreshold)return;t.save();const r=.5*(n-this.config.focusThreshold);t.strokeStyle=`rgba(100, 200, 255, ${r})`,t.lineWidth=1,t.setLineDash([2,4]);const a=[0,60,120,180,240,300];for(const n of a){const r=n*Math.PI/180,a=2*s,o=1.2*s;t.beginPath(),t.moveTo(e+Math.cos(r)*a,i+Math.sin(r)*a),t.lineTo(e+Math.cos(r)*o,i+Math.sin(r)*o),t.stroke()}t.restore()}},$n={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:t=>!0===t.biometric||!0===t.fingerprint||!0===t.authenticating,initialize(){this.state.breaks=[];for(let t=0;t<this.config.rings;t++){const t=[];for(let e=0;e<this.config.breakPoints;e++)t.push(Math.random()*Math.PI*2);this.state.breaks.push(t)}this.state.whorls=[{x:.2,y:-.1,strength:.3},{x:-.15,y:.2,strength:.25},{x:0,y:0,strength:.5}]},apply(t,e){const{x:i,y:s,radius:n,deltaTime:r=16.67,scanning:a=!1,authResult:o=null}=e;0===this.state.breaks.length&&this.initialize(),this.state.rotation+=this.config.rotationSpeed*(r/16.67),this.state.pulsePhase+=this.config.pulseSpeed*(r/16.67),(a||this.state.isScanning)&&(this.state.isScanning=!0,this.state.scanPosition+=this.config.scanLineSpeed*this.state.scanDirection*(r/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)),t.save(),this.drawFingerprintPattern(t,i,s,n),this.state.isScanning&&this.drawScanLine(t,i,s,n),o&&this.showAuthResult(t,i,s,n,o),t.restore()},drawFingerprintPattern(t,e,i,s){const n=.1*Math.sin(this.state.pulsePhase)+1;for(let r=0;r<this.config.rings;r++){const a=(r+1)*this.config.ringSpacing*n;if(!(a>2*s)){t.beginPath(),t.strokeStyle=this.config.color,t.lineWidth=this.config.lineWidth,t.globalAlpha=this.config.opacity*(1-r/this.config.rings*.5);for(let n=0;n<2*Math.PI;n+=.05){let o=!1;for(const t of this.state.breaks[r]||[])if(Math.abs(n-t)<.1){o=!0;break}if(o){t.stroke(),t.beginPath();continue}let h=a,l=n+this.state.rotation;for(const t of this.state.whorls){const n=e+t.x*s,r=i+t.y*s,a=e+Math.cos(l)*h,o=i+Math.sin(l)*h,c=Math.sqrt(Math.pow(a-n,2)+Math.pow(o-r,2));l+=Math.exp(-c/(.5*s))*t.strength*.5}h+=Math.sin(n*this.config.waveFrequency)*this.config.waveAmplitude;const c=e+Math.cos(l)*h,u=i+Math.sin(l)*h;0===n?t.moveTo(c,u):t.lineTo(c,u)}t.stroke()}}},drawScanLine(t,e,i,s){const n=i+this.state.scanPosition*s,r=t.createLinearGradient(e-s,n,e+s,n);r.addColorStop(0,"rgba(0, 255, 255, 0)"),r.addColorStop(.5,this.config.glowColor),r.addColorStop(1,"rgba(0, 255, 255, 0)"),t.strokeStyle=r,t.lineWidth=this.config.scanLineWidth,t.globalAlpha=.8,t.shadowBlur=10,t.shadowColor=this.config.glowColor,t.beginPath(),t.moveTo(e-s,n),t.lineTo(e+s,n),t.stroke(),t.shadowBlur=0},showAuthResult(t,e,i,s,n){const r="success"===n?this.config.successColor:this.config.failColor,a="success"===n?"โ AUTHENTICATED":"โ ACCESS DENIED";t.fillStyle=r,t.font=`bold ${.15*s}px monospace`,t.textAlign="center",t.textBaseline="middle",t.globalAlpha=.9,t.fillText(a,e,i+1.3*s),t.strokeStyle=r,t.lineWidth=3,t.globalAlpha=.5,t.beginPath(),t.arc(e,i,1.1*s,0,2*Math.PI),t.stroke()},startScan(){this.state.isScanning=!0,this.state.scanPosition=-1,this.state.scanDirection=1,this.state.scanResult=null},completeScan(t=!0){this.state.isScanning=!1,this.state.scanResult=t?"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 Ln=new Map;function Gn(t){t.name&&Ln.set(t.name,t)}function _n(t){return Ln.get(t)||null}function Hn(t,e,i){const s=_n(t);return!!s&&!!s.apply&&(s.apply(e,i),!0)}function Un(t,e){const i=_n(t);return!(!i||!i.shouldActivate)&&i.shouldActivate(e)}Gn(zn),Gn(qn),Gn(On),Gn(jn),Gn(In),Gn($n);class Wn{constructor(t){this.renderer=t}calculateSleepModifiers(){let t=1,e=1,i=1;if(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||Un("sleeping",this.renderer.state)){const s=_n("sleeping");if(s){const n=s.getDimmingValues();t=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:n.orbDimming,i=n.glowDimming,e=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9}else t=void 0!==this.renderer.state.sleepDimness?this.renderer.state.sleepDimness:.3,i=.2,e=void 0!==this.renderer.state.sleepScale?this.renderer.state.sleepScale:.9;this.renderer.state.breathRate=.5,this.renderer.state.breathDepth=.15}return{sleepOpacityMod:t,sleepScaleMod:e,glowOpacityMod:i}}calculateBreathingFactors(){let t,e;if(null!==this.renderer.state.customScale)t=this.renderer.state.customScale,e=1+.5*(this.renderer.state.customScale-1);else{const i=this.renderer.breathingAnimator.getBreathingScale();t=i,e=1-.5*(i-1)}return"nervous"===this.renderer.state.undertone&&this.renderer.undertoneModifiers.nervous.glowPulse&&(e*=1+Math.sin(Date.now()/200)*this.renderer.undertoneModifiers.nervous.glowPulse),{coreBreathFactor:t,glowBreathFactor:e}}calculateRadii(t,e,i){const{sleepOpacityMod:s,sleepScaleMod:n,glowOpacityMod:r}=this.calculateSleepModifiers(),{coreBreathFactor:a,glowBreathFactor:o}=this.calculateBreathingFactors(),h=this.renderer.config.referenceSize/this.renderer.config.coreSizeDivisor*this.renderer.scaleFactor,l=t.properties&&t.properties.coreSize?t.properties.coreSize:1,c=this.renderer.state.sizeMultiplier||1;return{coreRadius:h*l*a*e*n*c,glowRadius:h*this.renderer.config.glowMultiplier*o*this.renderer.state.glowIntensity*e*n*c*i,effectiveGlowIntensity:this.renderer.state.glowIntensity*i,sleepOpacityMod:s,glowOpacityMod:r}}}class Yn{constructor(t){this.renderer=t}applyBlinkSquish(t){return this.renderer.state.sleeping||(t*=this.renderer.eyeRenderer.getBlinkScale()),t}calculateJitter(t,e){let i=0,s=0;const n=this.renderer.state.jitterAmount||0;if(this.renderer.currentUndertone)({jitterX:i,jitterY:s,coreRadius:t,glowRadius:e}=this.renderer.episodicEffectController.updateEpisodicEffects(this.renderer.currentUndertone,i,s,t,e));else if(this.renderer.state.coreJitter||n>0){const t=Math.max(n,this.renderer.state.coreJitter?this.renderer.scaleValue(2):0);i=(Math.random()-.5)*t,s=(Math.random()-.5)*t}return{jitterX:i,jitterY:s,coreRadius:t,glowRadius:e}}calculateFinalPosition(t,e,i,s){return{coreX:t+this.renderer.state.gazeOffset.x+i,coreY:e+this.renderer.state.gazeOffset.y+s}}applyAllModifications(t,e,i,s,n){let r,a;s=this.applyBlinkSquish(s),({jitterX:r,jitterY:a,coreRadius:s,glowRadius:n}=this.calculateJitter(s,n));const{coreX:o,coreY:h}=this.calculateFinalPosition(t,e,r,a);return{coreX:o,coreY:h,rotationAngle:i,coreRadius:s,glowRadius:n}}}class Xn{constructor(t){this.renderer=t}renderGlow(t,e,i,s,n,r){Un("recording-glow",this.renderer.state)?Hn("recording-glow",this.renderer.ctx,{x:t,y:e,radius:i,deltaTime:r}):this.renderer.state.sleeping||"resting"===this.renderer.state.emotion||Un("sleeping",this.renderer.state)?(this.renderer.ctx.save(),this.renderer.ctx.globalAlpha=n,this.renderer.glowRenderer.renderGlow(t,e,i,{intensity:s}),this.renderer.ctx.restore()):this.renderer.glowRenderer.renderGlow(t,e,i,{intensity:s})}renderFlashWave(t,e,i,s){if(t&&t.flashWave){const n=t.flashWave,{ctx:r}=this.renderer;r.save(),r.globalCompositeOperation="lighter";const a=s*n.innerRadius,o=s*n.outerRadius;if(o>a){const t=vn.getRadialGradient(r,e,i,a,e,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)"}]);r.fillStyle=t,r.beginPath(),r.arc(e,i,o,0,2*Math.PI),r.arc(e,i,Math.max(0,a),0,2*Math.PI,!0),r.fill()}r.restore()}}renderSpeakingPulse(t,e,i,s){Un("speaking-pulse",this.renderer.state)&&Hn("speaking-pulse",this.renderer.ctx,{x:t,y:e,radius:i,audioLevel:this.renderer.state.audioLevel||0,deltaTime:s})}renderAllEffects(t){const{coreX:e,coreY:i,glowRadius:s,effectiveGlowIntensity:n,glowOpacityMod:r,gestureTransforms:a,coreRadius:o,deltaTime:h}=t;this.renderGlow(e,i,s,n,r,h),this.renderFlashWave(a,e,i,o),this.renderSpeakingPulse(e,i,o,h)}}class Vn{constructor(t){this.renderer=t}applySleepOpacity(t){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=t)}updateShapeMorpher(t){let e=null,i=null;return this.renderer.shapeMorpher&&(this.renderer.shapeMorpher.update(),e=this.renderer.shapeMorpher.getCanvasPoints(0,0,t),i=this.renderer.shapeMorpher.getCurrentShadow()),{shapePoints:e,currentShadow:i}}renderSunEffects(t,e,i,s){let n=!1;return!s||"sun"!==s.type&&"solar-hybrid"!==s.type||(this.renderer.renderSunEffects(t,e,i,s),n=!0),n}renderCore(t,e,i,s,n){this.renderer.coreRenderer.renderCore(t,e,i,{scaleX:1,scaleY:1,rotation:s,shapePoints:n})}renderSparkles(t){this.renderer.specialEffects&&(this.renderer.specialEffects.update(t),this.renderer.specialEffects.renderSparkles())}renderShadowEffects(t,e,i,s,n,r){const a=this.renderer.shapeMorpher?this.renderer.shapeMorpher.currentShape:null,o=this.renderer.shapeMorpher?this.renderer.shapeMorpher.targetShape:null,h=this.renderer.shapeMorpher&&"solar"===o&&this.renderer.shapeMorpher.isTransitioning,l=this.renderer.shapeMorpher&&"solar"===a&&this.renderer.shapeMorpher.isTransitioning,c=s&&"solar-hybrid"===s.type,u=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"solar"===a&&"moon"===o,d=this.renderer.shapeMorpher&&this.renderer.shapeMorpher.isTransitioning&&"moon"===a&&"solar"===o;if(!s||"crescent"!==s.type&&"lunar"!==s.type||d||this.renderer.renderMoonShadow(t,e,i,s,n,!1,0),(c&&s.lunarOverlay||h||l)&&!u){const a=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 t=2.5*i;h&&d<1?(o=-t*(1-d),u=t*(1-d)):l&&d<1&&(o=t*d,u=-t*d)}if(this.renderer.renderMoonShadow(t,e,i,a,n,!0),(h||l)&&(h||r)&&(this.renderer.renderBaileysBeads(t,e,i,o,u,d,h,!0),Math.abs(o)<30&&Math.abs(u)<30&&this.renderer.specialEffects)){const t=Math.sqrt(o*o+u*u),e=Math.max(.1,.5*(1-t/30));this.renderer.specialEffects.triggerChromaticAberration(e)}}}cleanup(t){(this.renderer.state.sleeping||"resting"===this.renderer.state.emotion)&&(this.renderer.ctx.globalAlpha=1),0!==t&&this.renderer.ctx.restore()}renderCoreAndShapes(t){const{coreX:e,coreY:i,coreRadius:s,totalRotation:n,sleepOpacityMod:r,deltaTime:a}=t;this.applySleepOpacity(r);const{shapePoints:o,currentShadow:h}=this.updateShapeMorpher(s),l=this.renderSunEffects(e,i,s,h);this.renderCore(e,i,s,n,o),this.renderSparkles(a),this.renderShadowEffects(e,i,s,h,o,l),this.cleanup(n)}}class Nn{constructor(t){this.renderer=t}renderSleepIndicator(t,e,i,s){this.renderer.state.sleeping&&this.renderer.renderSleepIndicator(t,e-i-this.renderer.scaleValue(20),s)}finalizeCanvas(t,e,i){this.renderer.ctx=t,t.drawImage(this.renderer.offscreenCanvas,0,0,e,i)}drawRecordingIndicator(t){if(Un("recording-glow",this.renderer.state)){const e=_n("recording-glow");e&&e.drawRecordingIndicator&&e.drawRecordingIndicator(t,this.renderer.canvas.width,this.renderer.canvas.height)}}finalizePerformanceMetrics(t){const e=performance.now()-t;this.renderer.performanceMonitor&&(this.renderer.performanceMonitor.markFrameEnd(),this.renderer.performanceMonitor.recordFrameTime(e))}finalizeRender(t){const{centerX:e,centerY:i,glowRadius:s,deltaTime:n,originalCtx:r,logicalWidth:a,logicalHeight:o,frameStartTime:h}=t;this.renderSleepIndicator(e,i,s,n),this.finalizeCanvas(r,a,o),this.drawRecordingIndicator(r),this.finalizePerformanceMetrics(h)}}class Qn{constructor(t){this.renderer=t,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(t,e={}){this.activeAnimation&&this.activeAnimation!==t&&this.stopAmbientAnimation(this.activeAnimation),this.activeAnimation=t,this.animations[t]={startTime:Date.now(),intensity:e.intensity||1,frequency:e.frequency||1,options:e}}stopAmbientAnimation(t){this.animations[t]&&(this.animations[t]=null),this.activeAnimation===t&&(this.activeAnimation=null)}updateBlendState(t){if(!t)return;const e=.2;this.blendState.x=this.lerp(this.blendState.x,t.x||0,e),this.blendState.y=this.lerp(this.blendState.y,t.y||0,e),this.blendState.rotation=this.lerp(this.blendState.rotation,t.rotation||0,e),this.blendState.scale=this.lerp(this.blendState.scale,t.scale||1,e),this.blendState.opacity=this.lerp(this.blendState.opacity,t.opacity||1,e)}getTransform(t){const e={x:this.blendState.x,y:this.blendState.y,rotation:this.blendState.rotation,scale:this.blendState.scale,opacity:this.blendState.opacity};if(this.activeAnimation){const t=this.animations[this.activeAnimation];if(t){const i=Date.now()-t.startTime;switch(this.activeAnimation){case"grooveSway":e.x+=15*Math.sin(i/500*t.frequency)*t.intensity,e.rotation+=5*Math.sin(i/500*t.frequency+Math.PI/4)*t.intensity;break;case"grooveBob":e.y+=10*Math.sin(i/400*t.frequency)*t.intensity,e.scale*=1+.03*Math.sin(i/400*t.frequency)*t.intensity;break;case"grooveFlow":{const s=i/1e3*t.frequency;e.x+=Math.sin(s)*Math.cos(2*s)*20*t.intensity,e.y+=Math.cos(s)*Math.sin(2*s)*10*t.intensity,e.rotation+=8*Math.sin(2*s)*t.intensity;break}case"groovePulse":e.scale*=1+.05*Math.sin(i/250*t.frequency)*t.intensity,e.opacity*=.9+.1*Math.sin(i/250*t.frequency)*t.intensity;break;case"grooveStep":{const s=Math.floor(i/500*t.frequency)%4,n=i/500*t.frequency%1,r=this.smoothStep(n);0===s?e.x+=25*r*t.intensity:2===s&&(e.x-=25*r*t.intensity),e.y+=5*Math.abs(Math.sin(i/250*t.frequency))*t.intensity;break}}}}return e}lerp(t,e,i){return t+(e-t)*i}smoothStep(t){return t*t*(3-2*t)}}class Jn{constructor(t){this.renderer=t,this.ctx=t.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(t={}){this.config={...this.config,...t},void 0!==t.enabled&&(this.targetIntensity=t.enabled?this.config.intensity:0)}update(t){this.config.enabled?(this.currentIntensity+=.1*(this.targetIntensity-this.currentIntensity),this.config.responsive&&(this.pulsePhase+=.001*t)):this.currentIntensity*=.95}setAudioIntensity(t){if(!this.config.responsive)return;const e=.2*t;this.targetIntensity=Math.min(1,this.config.intensity+e)}render(t,e,i,s=null){if(this.currentIntensity<.01)return;const n=s||this.ctx;switch(n.save(),this.config.type){case"radial-gradient":this.renderRadialGradient(t,e,i,n);break;case"vignette":this.renderVignette(t,e,i,n);break;case"glow":this.renderGlow(t,e,i,n)}n.restore()}renderRadialGradient(t,e,i,s){s=s||this.ctx;const n=i*this.config.radius,r=t+(this.config.offset.x||0),a=e+(this.config.offset.y||0);let o=n;(this.config.pulse||this.config.responsive)&&(o*=1+.05*Math.sin(this.pulsePhase));const h=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 l=s.createRadialGradient(r,a,0,r,a,o),c=this.config.color,u=this.currentIntensity;this.addGradientStopsSimple(l,c,u),s.fillStyle=l,s.beginPath(),s.arc(r,a,o,0,2*Math.PI),s.fill(),this.config.blur>0&&(s.filter="none"),this.config.blendMode&&"normal"!==this.config.blendMode&&(s.globalCompositeOperation=h)}renderVignette(t,e,i,s){s=s||this.ctx;const{canvas:n}=s,r=Math.max(n.width,n.height),a=s.createRadialGradient(t,e,.5*i,t,e,r);a.addColorStop(0,"rgba(0, 0, 0, 0)"),a.addColorStop(1,this.adjustColorAlpha(this.config.color,this.currentIntensity)),s.fillStyle=a,s.fillRect(0,0,n.width,n.height)}renderGlow(t,e,i,s){s=s||this.ctx;const n=i*this.config.radius;for(let i=0;i<3;i++){const r=n*(1-.2*i),a=this.currentIntensity*(.3-.1*i),o=s.createRadialGradient(t,e,0,t,e,r);o.addColorStop(0,this.adjustColorAlpha(this.config.color,a)),o.addColorStop(1,"rgba(0, 0, 0, 0)"),s.fillStyle=o,s.beginPath(),s.arc(t,e,r,0,2*Math.PI),s.fill()}}addGradientStopsSimple(t,e,i){const{coreTransparency:s}=this.config;t.addColorStop(0,this.adjustColorAlpha(e,i)),t.addColorStop(s,this.adjustColorAlpha(e,i));for(let n=1;n<=25;n++){const r=s+n/25*(1-s),a=(r-s)/(1-s),o=1-this.easeInOutCubic(a);t.addColorStop(r,this.adjustColorAlpha(e,i*o))}t.addColorStop(1,"rgba(0, 0, 0, 0)")}addGradientStops(t,e,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})=>{t.addColorStop(s,this.adjustColorAlpha(e,i*n))});else switch(this.config.falloff){case"linear":t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n,"rgba(0, 0, 0, 0)"),t.addColorStop(1,this.adjustColorAlpha(e,i));break;case"exponential":t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n,"rgba(0, 0, 0, 0)"),t.addColorStop(n+.3*(1-n),this.adjustColorAlpha(e,.05*i)),t.addColorStop(n+.5*(1-n),this.adjustColorAlpha(e,.15*i)),t.addColorStop(n+.7*(1-n),this.adjustColorAlpha(e,.4*i)),t.addColorStop(n+.85*(1-n),this.adjustColorAlpha(e,.7*i)),t.addColorStop(1,this.adjustColorAlpha(e,i));break;default:{t.addColorStop(0,"rgba(0, 0, 0, 0)"),t.addColorStop(n*s,"rgba(0, 0, 0, 0)");const{edgeSoftness:r}=this.config,a=s,o=n*s+(a-n*s)*r,h=25;for(let r=1;r<=h;r++){const l=r/h;let c=0;if(l<=n*s)c=0;else if(l<=a)if(l<=o){const t=(l-n*s)/(o-n*s);c=this.easeInOutCubic(t)}else{const t=(l-o)/(a-o);c=1-.05*(1-this.easeInOutCubic(t))}else{const t=(l-a)/(1-a);c=1-this.easeInOutCubic(t)}t.addColorStop(l,this.adjustColorAlpha(e,i*c))}t.addColorStop(1,"rgba(0, 0, 0, 0)");break}}}easeInOutCubic(t){return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}adjustColorAlpha(t,e){const i=t.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)/);if(i){const[,t,s,n,r=1]=i;return`rgba(${t}, ${s}, ${n}, ${parseFloat(r)*e})`}return`rgba(0, 0, 0, ${.6*e})`}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 Kn=2,Zn=3,tr=4,er=new class{constructor(){this.callbacks=new Map,this.callbackIdCounter=0,this.wt=new Map,this.vt=!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={[Kn]:0,[Zn]:0,[tr]:0},this.performanceMonitor=null,this.frameTimeHistory=new Array(60).fill(0),this.St=0,this.kt=0,this.maxHistorySize=60,this.loop=this.loop.bind(this)}register(t,e=2,i=null){if("function"!=typeof t)throw new Error("Callback must be a function");const s=++this.callbackIdCounter;return this.callbacks.set(s,{callback:t,priority:e,context:i,lastRun:0,runCount:0,totalTime:0,enabled:!0}),this.vt=!0,1!==this.callbacks.size||this.isRunning||this.start(),s}unregister(t){this.callbacks.delete(t),this.vt=!0,0===this.callbacks.size&&this.isRunning&&this.stop()}setEnabled(t,e){const i=this.callbacks.get(t);i&&(i.enabled=e)}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(t){if(!this.isRunning)return;this.deltaTime=t-this.lastFrameTime,this.lastFrameTime=t,this.frameCount++,this.frameCount%60==0&&(this.fps=Math.round(1e3/(this.deltaTime||16.67))),this.frameTimeHistory[this.St]=this.deltaTime,this.St=(this.St+1)%this.maxHistorySize,this.kt<this.maxHistorySize&&this.kt++,this.vt&&this.xt();const e=this.wt;let i=0;for(const s of[0,1,2,3,4]){if(s>0&&i>.8*this.frameBudget)break;if(this.shouldSkipPriority(s))continue;const n=e.get(s)||[];for(const e of n){if(!e.enabled)continue;const s=performance.now();try{e.context?e.callback.call(e.context,this.deltaTime,t):e.callback(this.deltaTime,t);const n=performance.now()-s;e.totalTime+=n,e.runCount++,e.lastRun=t,i+=n}catch(t){e.runCount>0&&e.totalTime/e.runCount>10&&(e.enabled=!1)}if(i>this.frameBudget)break}}this.frameId=requestAnimationFrame(this.loop)}xt(){this.wt.clear();for(const[,t]of this.callbacks){const{priority:e}=t;this.wt.has(e)||this.wt.set(e,[]),this.wt.get(e).push(t)}this.vt=!1}shouldSkipPriority(t){if(0===t)return!1;if(this.fps<30&&t>=3)return!0;if(this.fps<45&&4===t)return!0;if(2===t){if(this.fps<50&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%2!=0))return!0}else if(3===t){if(this.fps<50&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%3!=0))return!0}else if(4===t&&(this.prioritySkipCounters[t]++,this.prioritySkipCounters[t]%5!=0))return!0;return!1}getStats(){const t={fps:this.fps,frameCount:this.frameCount,callbackCount:this.callbacks.size,averageFrameTime:0,maxFrameTime:0,minFrameTime:1/0};if(this.kt>0){let e=0;for(let i=0;i<this.kt;i++){const s=this.frameTimeHistory[i];e+=s,t.maxFrameTime=Math.max(t.maxFrameTime,s),t.minFrameTime=Math.min(t.minFrameTime,s)}t.averageFrameTime=e/this.kt}t.callbacksByPriority={};for(const[,e]of this.callbacks){const{priority:i}=e;t.callbacksByPriority[i]||(t.callbacksByPriority[i]={count:0,totalTime:0,enabled:0}),t.callbacksByPriority[i].count++,t.callbacksByPriority[i].totalTime+=e.totalTime,e.enabled&&t.callbacksByPriority[i].enabled++}return t}setTargetFPS(t){this.targetFPS=Math.max(15,Math.min(120,t)),this.targetFrameTime=1e3/this.targetFPS,this.frameBudget=this.targetFrameTime}setPerformanceMonitor(t){this.performanceMonitor=t}destroy(){this.stop(),this.callbacks.clear(),this.wt.clear(),this.vt=!0,this.frameTimeHistory.fill(0),this.St=0,this.kt=0}};class ir{constructor(t){this.renderer=t,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&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null);const t=performance.now(),e=2e3;this.loopCallbackIds.eyeClose=er.register(()=>{if(!this.renderer.state.sleeping)return void(this.loopCallbackIds.eyeClose=null);const i=performance.now()-t;if(i<e){const t=i/e,s=1-Math.pow(t,2);this.renderer.state.eyeOpenness=.1+.9*s,this.renderer.state.sleepDimness=1,this.renderer.state.sleepScale=1}else if(i<3e3){const t=(i-e)/1e3,s=1-Math.pow(1-t,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},1,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&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.loopCallbackIds.eyeClose&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null);const t=performance.now();this.loopCallbackIds.eyeOpen=er.register(()=>{const e=performance.now()-t;if(e<500){const t=e/500,i=Math.sin(t*Math.PI/2);this.renderer.state.sleepDimness=.6+.4*i,this.renderer.state.sleepScale=.9+.1*i,this.renderer.state.eyeOpenness=.1}else if(e<1500){const t=(e-500)/1e3,i=Math.sin(t*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},1,this.renderer)}renderSleepIndicator(t,e,i){return this.renderer.specialEffects.renderSleepIndicator(t,e,i)}cleanup(){this.loopCallbackIds.eyeClose&&(er.unregister(this.loopCallbackIds.eyeClose),this.loopCallbackIds.eyeClose=null),this.loopCallbackIds.eyeOpen&&(er.unregister(this.loopCallbackIds.eyeOpen),this.loopCallbackIds.eyeOpen=null),this.wakeJitterTimeout&&(clearTimeout(this.wakeJitterTimeout),this.wakeJitterTimeout=null)}}class sr{constructor(t){this.renderer=t}applyUndertoneModifiers(t){if(t&&"object"==typeof t&&void 0!==t.weight){const{weight:e}=t;return this.renderer.state.sizeMultiplier=1+((t.sizeMultiplier||1)-1)*e,this.renderer.state.jitterAmount=(t.jitterAmount||0)*e,this.renderer.state.episodicFlutter=e>.5&&t.episodicFlutter||!1,this.renderer.state.glowRadiusMult=1+((t.glowRadiusMult||1)-1)*e,this.renderer.state.breathRateMult=1+((t.breathRateMult||1)-1)*e,this.renderer.state.breathDepthMult=1+((t.breathDepthMult||1)-1)*e,this.renderer.state.breathIrregular=e>.5&&t.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=(t.glowPulse||0)*e,this.renderer.state.brightnessFlicker=(t.brightnessFlicker||0)*e,this.renderer.state.brightnessMult=1+((t.brightnessMult||1)-1)*e,this.renderer.state.saturationMult=1+((t.saturationMult||1)-1)*e,void(this.renderer.state.hueShift=(t.hueShift||0)*e)}if(!t||!this.renderer.undertoneModifiers[t])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 e=this.renderer.undertoneModifiers[t];this.renderer.state.sizeMultiplier=e.sizeMultiplier,this.renderer.state.jitterAmount=e.jitterAmount||0,this.renderer.state.episodicFlutter=e.episodicFlutter||!1,this.renderer.state.glowRadiusMult=e.glowRadiusMult,this.renderer.state.breathRateMult=e.breathRateMult,this.renderer.state.breathDepthMult=e.breathDepthMult,this.renderer.state.breathIrregular=e.breathIrregular||!1,this.renderer.state.particleRateMult=1,this.renderer.state.glowPulse=e.glowPulse||0,this.renderer.state.brightnessFlicker=e.brightnessFlicker||0,this.renderer.state.brightnessMult=e.brightnessMult||1,this.renderer.state.saturationMult=e.saturationMult||1,this.renderer.state.hueShift=e.hueShift||0}updateUndertone(t){this.renderer.state.undertone!==t&&this.renderer.glowCache&&this.renderer.glowCache.clear(),this.renderer.state.undertone=t,this.renderer.currentUndertone=t;const e=this.renderer.stateMachine&&this.renderer.stateMachine.getWeightedUndertoneModifiers?this.renderer.stateMachine.getWeightedUndertoneModifiers():null;if(this.applyUndertoneModifiers(e||t),this.renderer.state.emotion){const i=Us&&Us.isInitialized?Us.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,e||t);this.renderer.startColorTransition(n,200)}}}setEmotionalState(t,e,i=null){this.renderer.state.emotion===t&&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=e.glowColor||this.renderer.config.defaultGlowColor;let r;r="suspicion"===t?e.glowColor||n:this.renderer.applyUndertoneToColor(n,s||i);const a=s||(i?this.renderer.undertoneModifiers[i]:null),o=e.glowIntensity||1;let h=1;if(a)if(s){const t=a.weight||0;h=void 0!==a.glowRadiusMult&&isFinite(a.glowRadiusMult)&&isFinite(t)?1+(a.glowRadiusMult-1)*t:1}else h=void 0!==a.glowRadiusMult?a.glowRadiusMult:1;const l=o*h;let c=1500;"anger"===t||"fear"===t?c=800:"sadness"!==t&&"resting"!==t||(c=2e3),this.renderer.state.emotion=t,"suspicion"===t?(this.renderer.state.isSuspicious=!0,this.renderer.state.targetSquintAmount=e&&e.coreSquint?e.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(r,l,c);const u=e.breathRate||1,d=e.breathDepth||this.renderer.config.breathingDepth;this.renderer.state.breathRate=a?u*a.breathRateMult:u,this.renderer.state.breathDepth=a?d*a.breathDepthMult:d,this.renderer.state.coreJitter=e.coreJitter||a&&a.jitterAmount>0,this.renderer.state.emotionEyeOpenness=e.eyeOpenness,this.renderer.state.emotionEyeArc=e.eyeArc}}class nr{constructor(t){this.renderer=t}resetCanvasContext(){if(!this.renderer.canvas||!this.renderer.ctx)return;const{width:t}=this.renderer.canvas,{height:e}=this.renderer.canvas;this.resetContext(this.renderer.ctx,t,e),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(t,e,i){t.setTransform(1,0,0,1,0,0),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.imageSmoothingEnabled=!0,t.imageSmoothingQuality="high",t.clearRect(0,0,e,i)}setQualityLevel(t){this.renderer.qualityLevel=Math.max(0,Math.min(1,t)),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(t){t?this.setQualityLevel(.5):this.setQualityLevel(1)}handleContextRecovery(t){this.renderer.ctx=t}}class rr{constructor(t){this.renderer=t}destroy(){this.cancelAnimationFrames(),this.unregisterLoopCallbacks(),this.cleanupManagers(),this.clearTimeouts(),this.clearAnimationStates(),this.clearOtherResources()}cancelAnimationFrames(){for(const t in this.renderer.animationFrameIds)this.renderer.animationFrameIds[t]&&(cancelAnimationFrame(this.renderer.animationFrameIds[t]),this.renderer.animationFrameIds[t]=null)}unregisterLoopCallbacks(){for(const t in this.renderer.loopCallbackIds)this.renderer.loopCallbackIds[t]&&(er.unregister(this.renderer.loopCallbackIds[t]),this.renderer.loopCallbackIds[t]=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 ar{constructor(t){this.renderer=t}updateTimers(t){this.updateBreathing(t),this.updateBlinking(t)}updateBreathing(t){this.renderer.breathingAnimator.update(t,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(t){const e=this.renderer.state.blinkingEnabled&&!this.renderer.state.sleeping;this.renderer.eyeRenderer.setBlinkingEnabled(e),this.renderer.eyeRenderer.update(t),this.renderer.state.blinking=this.renderer.eyeRenderer.blinking}}class or{constructor(t){this.renderer=t}setGazeOffset(t){this.processGazeData(t),this.handleGazeInteraction()}processGazeData(t){"object"==typeof t&&null!==t&&(this.isOldFormat(t)?this.renderer.state.gazeOffset=t:this.applyNewFormatData(t))}isOldFormat(t){return{}.hasOwnProperty.call(t,"x")&&{}.hasOwnProperty.call(t,"y")}applyNewFormatData(t){this.renderer.state.gazeOffset=t.offset||{x:0,y:0},this.renderer.state.gazeIntensity=t.proximity||0,this.renderer.state.gazeLocked=t.isLocked||!1}handleGazeInteraction(){this.renderer.idleTimer=0,this.renderer.isAsleep&&this.renderer.wakeUp()}getCurrentOrbPosition(){const t=this.renderer.canvasManager.width/2,e=this.renderer.canvasManager.height/2-this.renderer.config.topOffset;return{x:t+this.renderer.state.gazeOffset.x,y:e+this.renderer.state.gazeOffset.y}}}class hr{constructor(t,e={}){this.canvasManager=t,this.ctx=t.getContext(),this.ctx||(this.T=!0),this.gestureCompositor=new an,this.currentUndertone=null,this.gestureAnimator=new fn(this),this.colorUtilities=new yn,this.specialEffects=new Mn(this),this.eyeRenderer=new bn(this),this.breathingAnimator=new wn(this),this.glowRenderer=new Sn(this),this.coreRenderer=new kn(this),this.celestialRenderer=new xn,this.episodicEffectController=new En(this),this.rotationManager=new An(this),this.gazeTracker=new Cn(this),this.canvasSetupManager=new Tn(this),this.renderPerformanceManager=new Pn(this),this.transformMerger=new Dn(this),this.stateUpdateManager=new Rn(this),this.dimensionCalculator=new Fn(this),this.radiusCalculator=new Wn(this),this.positionJitterManager=new Yn(this),this.effectsRenderManager=new Xn(this),this.coreShapeRenderManager=new Vn(this),this.renderFinalizationManager=new Nn(this),this.ambientDanceAnimator=new Qn(this),this.backdropRenderer=new Jn(this),this.sleepManager=new ir(this),this.emotionalStateManager=new sr(this),this.canvasContextManager=new nr(this),this.resourceCleanupManager=new rr(this),this.timerCoordinator=new ar(this),this.gazeInputHandler=new or(this),this.config={coreColor:e.coreColor||"#FFFFFF",coreSizeDivisor:e.coreSizeDivisor||12,glowMultiplier:e.glowMultiplier||2.5,defaultGlowColor:e.defaultGlowColor||"#14B8A6",breathingSpeed:e.breathingSpeed||.42,breathingDepth:e.breathingDepth||.08,renderingStyle:e.renderingStyle||"classic",baseScale:e.baseScale||1,referenceSize:400,topOffset:e.topOffset||0,positionController:e.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=t.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.Et()}scaleValue(t){return t*this.scaleFactor}initOffscreenCanvas(){this.offscreenCanvas=document.createElement("canvas"),this.offscreenCtx=this.offscreenCanvas.getContext("2d",{alpha:!0,desynchronized:!0,willReadFrequently:!1}),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:t}=this.canvasManager.canvas,{height:e}=this.canvasManager.canvas;if(this.offscreenCanvas.width!==t||this.offscreenCanvas.height!==e){this.offscreenCanvas.width=t,this.offscreenCanvas.height=e;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(t){this.state.effectiveCenter=t}getEffectiveCenter(){const t=this.canvasManager.getCenter();let e;return e=this.config.positionController?this.config.positionController.getEffectiveCenter(t.x,t.y):{x:t.x,y:t.y,scale:1},e.x+=this.state.gazeOffset.x,e.y+=this.state.gazeOffset.y,e}render(t,e,i=null){if(this.T)return;const s=this.renderPerformanceManager.initializeFrame();i=this.transformMerger.mergeAndStoreTransforms(i,e);const{logicalWidth:n,logicalHeight:r,originalCtx:a}=this.canvasSetupManager.setupCanvas();this.canvasSetupManager.performCanvasSetup(n,r,a,e),this.stateUpdateManager.performFrameStateUpdates(e);const o=this.dimensionCalculator.calculateRenderDimensions(n,r,t,i),{scaleMultiplier:h,glowMultiplier:l,gestureTransforms:c,centerX:u,centerY:d}=o;let{rotationAngle:p}=o;const m=this.radiusCalculator.calculateRadii(t,h,l);let{coreRadius:g,glowRadius:f}=m;const{effectiveGlowIntensity:y,sleepOpacityMod:M,glowOpacityMod:b}=m,w=this.positionJitterManager.applyAllModifications(u,d,p,g,f),{coreX:v,coreY:S}=w;({rotationAngle:p,coreRadius:g,glowRadius:f}=w);const k=this.rotationManager.applyRotationTransform(this.ctx,v,S,p);this.effectsRenderManager.renderAllEffects({coreX:v,coreY:S,glowRadius:f,effectiveGlowIntensity:y,glowOpacityMod:b,gestureTransforms:c,coreRadius:g,deltaTime:e}),this.coreShapeRenderManager.renderCoreAndShapes({coreX:v,coreY:S,coreRadius:g,totalRotation:k,sleepOpacityMod:M,deltaTime:e}),this.renderFinalizationManager.finalizeRender({centerX:u,centerY:d,glowRadius:f,deltaTime:e,originalCtx:a,logicalWidth:n,logicalHeight:r,frameStartTime:s})}renderRecordingGlow(t,e,i,s){const n=this.canvas?.width||600,r=this.canvas?.height||600,a=Math.min(i,t-10,e-10,n-t-10,r-e-10),o=Math.max(50,a),h=vn.getRadialGradient(this.ctx,t,e,0,t,e,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=h,this.ctx.beginPath(),this.ctx.arc(t,e,o,0,2*Math.PI),this.ctx.fill()}renderDropShadow(t,e,i,s){const{ctx:n}=this,r=this.shapeMorpher&&this.shapeMorpher.isTransitioning;if(!(this.shapeMorpher&&(this.shapeMorpher.audioDeformation>.1||this.shapeMorpher.vocalEnergy>.1)||r&&!(this.shapeMorpher.morphProgress>.8))){n.save(),n.translate(t,e);const r=this.scaleValue(2);if(n.translate(0,r),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 t=n.createRadialGradient(0,0,.7*i,0,0,1.2*i);if(t.addColorStop(0,"rgba(0, 0, 0, 0.2)"),t.addColorStop(.8,"rgba(0, 0, 0, 0.1)"),t.addColorStop(1,"rgba(0, 0, 0, 0)"),n.fillStyle=t,n.beginPath(),s){const t=1.1,e=s.length>20?2:1;n.moveTo(s[0].x*t,s[0].y*t);for(let i=e;i<s.length;i+=e)n.lineTo(s[i].x*t,s[i].y*t);n.closePath()}else n.arc(0,0,1.1*i,0,2*Math.PI);n.fill()}n.restore()}}renderSunEffects(t,e,i,s){return this.celestialRenderer.renderSunEffects(this.ctx,t,e,i,s)}renderBaileysBeads(t,e,i,s,n,r,a,o){return this.celestialRenderer.renderBaileysBeads(this.ctx,t,e,i,s,n,r,a,o,this.scaleValue.bind(this))}renderMoonShadow(t,e,i,s,n,r=!1,a=0){return this.celestialRenderer.renderMoonShadow(this.ctx,t,e,i,s,n,r,a,this.shapeMorpher)}renderSpeakingRings(t,e,i,s){return this.specialEffects.renderSpeakingRings(t,e,i,s)}renderRecordingIndicator(t,e){return this.specialEffects.renderRecordingIndicator(t,e)}renderSleepIndicator(t,e,i){return this.sleepManager.renderSleepIndicator(t,e,i)}updateTimers(t){this.timerCoordinator.updateTimers(t)}applyUndertoneModifiers(t){this.emotionalStateManager.applyUndertoneModifiers(t)}applyUndertoneToColor(t,e){return this.colorUtilities.applyUndertoneToColor(t,e)}hexToRgb(t){return this.colorUtilities.hexToRgb(t)}rgbToHsl(t,e,i){return this.colorUtilities.rgbToHsl(t,e,i)}hslToHex(t,e,i){return this.colorUtilities.hslToHex(t,e,i)}hexToRgba(t,e=1){const i=this.hexToRgb(t);return i?`rgba(${i.r}, ${i.g}, ${i.b}, ${e})`:`rgba(255, 255, 255, ${e})`}startColorTransition(t,e,i=1500){this.colorUtilities.currentColor=this.state.glowColor,this.colorUtilities.currentIntensity=this.state.glowIntensity,this.colorUtilities.startColorTransition(t,e,i),this.colorTransition=this.colorUtilities.colorTransition}updateColorTransition(t){const e=this.colorUtilities.updateColorTransition(t);e&&(this.state.glowColor=e.color,this.state.glowIntensity=e.intensity,this.colorTransition=this.colorUtilities.colorTransition)}updateUndertone(t){this.emotionalStateManager.updateUndertone(t)}setEmotionalState(t,e,i=null){this.emotionalStateManager.setEmotionalState(t,e,i)}setBPM(t){}setRotationSpeed(t){this.rotationManager.setRotationSpeed(t)}setRotationAngle(t){this.rotationManager.setRotationAngle(t)}setGazeOffset(t){this.gazeInputHandler.setGazeOffset(t)}getCurrentOrbPosition(){return this.gazeInputHandler.getCurrentOrbPosition()}setCustomScale(t){this.state.customScale=t}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(t){this.state.blinkingEnabled=t,t||(this.state.blinking=!1,this.eyeRenderer.blinking=!1,this.eyeRenderer.blinkTimer=0)}setGazeTracking(t){this.gazeTracker.setEnabled(t)}initGazeTracking(){this.Bt||(this.Bt=!0),this.gazeTracker.initialize()}cleanupGazeTracking(){this.At||(this.At=!0),this.gazeTracker.cleanup()}resetCanvasContext(){this.canvasContextManager.resetCanvasContext()}setQualityLevel(t){this.canvasContextManager.setQualityLevel(t)}setQualityReduction(t){this.canvasContextManager.setQualityReduction(t)}handleContextRecovery(t){this.canvasContextManager.handleContextRecovery(t)}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(t){return this.gestureAnimator.startGesture(t)}getCurrentGesture(){return this.gestureAnimator.getCurrentGesture()}Et(){["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(t=>{const e=`start${t}`;this[e]=()=>this.gestureAnimator[e]()})}startGrooveSway(t){this.ambientDanceAnimator.startAmbientAnimation("grooveSway",t)}startGrooveBob(t){this.ambientDanceAnimator.startAmbientAnimation("grooveBob",t)}startGrooveFlow(t){this.ambientDanceAnimator.startAmbientAnimation("grooveFlow",t)}startGroovePulse(t){this.ambientDanceAnimator.startAmbientAnimation("groovePulse",t)}startGrooveStep(t){this.ambientDanceAnimator.startAmbientAnimation("grooveStep",t)}stopAllGestures(){this.gestureAnimator.stopAllGestures(),this.currentGesture=null}isGestureActive(){return Object.values(this.gestureAnimator.gestureAnimations).some(t=>t.active)}destroy(){this.resourceCleanupManager.destroy()}}class lr{constructor(t,e={}){this.canvas=t,this.config={smoothing:e.smoothing||.1,maxOffset:e.maxOffset||.3,lockDistance:e.lockDistance||30,enabled:!1!==e.enabled,boundaryPadding:e.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(t){const e=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:t.clientX-e.left,y:t.clientY-e.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(t){for(const e of t.changedTouches)this.touches.set(e.identifier,{x:e.clientX,y:e.clientY}),this.primaryTouch||1!==this.touches.size||(this.primaryTouch=e.identifier);null!==this.primaryTouch&&this.updateTouchPosition(t.touches)}handleTouchMove(t){for(const e of t.changedTouches)this.touches.has(e.identifier)&&this.touches.set(e.identifier,{x:e.clientX,y:e.clientY});null!==this.primaryTouch&&(this.updateTouchPosition(t.touches),this.onInteraction&&this.onInteraction("touch"))}handleTouchEnd(t){for(const e of t.changedTouches)this.touches.delete(e.identifier),e.identifier===this.primaryTouch&&(this.primaryTouch=null,this.touches.size>0?this.primaryTouch=this.touches.keys().next().value:this.handleMouseLeave())}updateTouchPosition(t){for(const e of t)if(e.identifier===this.primaryTouch){const t=this.cachedRect||this.canvas.getBoundingClientRect();this.mousePos={x:e.clientX-t.left,y:e.clientY-t.top},this.updateTargetGaze();break}}updateTargetGaze(){const t=this.mousePos.x-this.canvasCenter.x,e=this.mousePos.y-this.canvasCenter.y,i=Math.sqrt(t*t+e*e),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:t*this.config.maxOffset*2,y:e*this.config.maxOffset*2};else{const n=Math.min(this.canvasCenter.x,this.canvasCenter.y)*this.config.maxOffset;if(i>0){const r=Math.min(1,i/s);this.targetGaze={x:t/i*n*r*this.config.boundaryPadding,y:e/i*n*r*this.config.boundaryPadding}}else this.targetGaze={x:0,y:0}}}update(t){if(!this.config.enabled)return;const e=1-Math.pow(1-this.config.smoothing,t/16.67);if(this.currentGaze.x+=(this.targetGaze.x-this.currentGaze.x)*e,this.currentGaze.y+=(this.targetGaze.y-this.currentGaze.y)*e,this.isLocked){const t=.5;this.currentGaze.x+=(Math.random()-.5)*t,this.currentGaze.y+=(Math.random()-.5)*t}}getGazeOffset(t){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(t){this.onInteraction=t}destroy(){this.detachEventListeners(),this.resizeObserver&&this.resizeObserver.disconnect(),this.touches.clear()}}class cr{constructor(t={}){this.config={blinkInterval:t.blinkInterval||{min:3e3,max:7e3},blinkDuration:t.blinkDuration||150,swayInterval:t.swayInterval||{min:2e4,max:4e4},swayDuration:t.swayDuration||4e3,swayIntensity:t.swayIntensity||1.5,sleepTimeout:void 0!==t.sleepTimeout?t.sleepTimeout:1/0,breathingSpeed:t.breathingSpeed||.25,breathingDepth:t.breathingDepth||.1,enabled:!1!==t.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(t){this.config.enabled&&(this.updateBreathing(t),this.timers.idle+=t,!this.state.isAsleep&&this.timers.idle>=this.config.sleepTimeout&&this.enterSleep(),this.state.isAsleep||this.updateBlinking(t),this.state.isAsleep||this.updateSwaying(t))}updateBreathing(t){const e=this.config.breathingSpeed*this.state.breathRate;this.state.breathingPhase+=e*t/1e3,this.state.breathingPhase>2*Math.PI&&(this.state.breathingPhase-=2*Math.PI)}updateBlinking(t){this.isBlinkingEnabled()&&(this.state.isBlinking?(this.timers.blink+=t,this.timers.blink>=this.config.blinkDuration&&this.endBlink()):(this.timers.blink+=t,this.timers.blink>=this.timers.nextBlink&&this.startBlink()))}updateSwaying(t){if(this.state.isSwaying){this.timers.sway+=t;const e=Math.min(this.timers.sway/this.config.swayDuration,1),i=(Math.sin((e-.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,e>=1&&this.endSway()}else this.timers.sway+=t,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 t=Math.random()*Math.PI*2,e=this.config.swayIntensity*(.5+.5*Math.random());this.swayTarget={x:Math.cos(t)*e*1.5,y:Math.sin(t)*e*.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 t={x:.5*this.config.swayIntensity,y:-this.config.swayIntensity};this.swayStart={...this.swayOffset},this.swayTarget=t,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(t){this.config.blinkingEnabled=t,!t&&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(t){const e=this.config[`${t}Interval`];return e.min+Math.random()*(e.max-e.min)}setCallback(t,e){({}).hasOwnProperty.call(this.callbacks,t)&&(this.callbacks[t]=e)}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}}}class ur{constructor(t){this.positionController=t,this.watchedElements=new Map,this.updateCallbacks=new Map}moveToElement(t,e="right",i={x:20,y:0},s={}){const n=document.querySelector(t);if(!n)return;const r=n.getBoundingClientRect(),a=r.left+r.width/2,o=r.top+r.height/2;let h,l;switch(e){case"right":default:h=r.right+i.x,l=o+i.y;break;case"left":h=r.left-i.x,l=o+i.y;break;case"above":h=a+i.x,l=r.top-i.y;break;case"below":h=a+i.x,l=r.bottom+i.y;break;case"center":h=a+i.x,l=o+i.y}const c=h-window.innerWidth/2,u=l-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(t="button",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToForm(t="form",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToModal(t='[role="dialog"], .modal',e="center",i={x:0,y:0}){this.moveToElement(t,e,i)}moveToNavigation(t="nav, .navigation",e="below",i={x:0,y:20}){this.moveToElement(t,e,i)}moveToContent(t="main, .content",e="center",i={x:0,y:0}){this.moveToElement(t,e,i)}moveToSidebar(t=".sidebar, aside",e="right",i={x:20,y:0}){this.moveToElement(t,e,i)}moveToHeader(t="header, .header",e="below",i={x:0,y:20}){this.moveToElement(t,e,i)}moveToFooter(t="footer, .footer",e="above",i={x:0,y:20}){this.moveToElement(t,e,i)}watchElement(t,e="right",i={x:20,y:0}){const s=()=>{this.moveToElement(t,e,i,{animate:!1})},n=`${t}-${e}-${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(t=>{window.removeEventListener("scroll",t),window.removeEventListener("resize",t)}),this.updateCallbacks.clear()}destroy(){this.stopWatchingAll(),this.positionController=null}}class dr extends ur{constructor(t){super(t),this.activeCallbacks=new Map,this.callbackStates=new Map}moveToElementWithCallback(t,e,i="right",s={x:20,y:0},n={}){const r=`callback-${Date.now()}-${Math.random()}`,a=document.querySelector(t);if(!a)return;this.callbackStates.set(r,{executed:!1,element:a,callback:e,options:n}),this.moveToElement(t,i,s,n);const o=()=>{if(this.isMascotNearElement(a,n.proximity||50)){const t=this.callbackStates.get(r);t&&!t.executed&&(t.executed=!0,e(),n.repeat||this.callbackStates.delete(r))}this.callbackStates.has(r)&&requestAnimationFrame(o)};return this.activeCallbacks.set(r,o),o(),()=>{this.activeCallbacks.delete(r),this.callbackStates.delete(r)}}moveToElementSequence(t=[],e={}){let i=0;const s=[],n=()=>{if(i>=t.length)return void(e.onComplete&&e.onComplete());const r=t[i],a=this.moveToElementWithCallback(r.selector,()=>{r.callback&&r.callback(),i++,setTimeout(n,r.delay||0)},r.position||"right",r.offset||{x:20,y:0},{...e,...r.options});a&&s.push(a)};return n(),()=>{s.forEach(t=>t())}}moveToElementWithDelay(t,e,i=1e3,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,()=>{setTimeout(e,i)},s,n)}moveToElementWithCondition(t,e,i,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,()=>{e()&&i()},s,n)}moveToElementWithRepeat(t,e,i=1e3,s="right",n={x:20,y:0}){let r=null;const a=this.moveToElementWithCallback(t,()=>{r=setInterval(e,i)},s,n,{repeat:!0});return()=>{null!==r&&(clearInterval(r),r=null),a&&a()}}moveToElementWithProximity(t,e,i=100,s="right",n={x:20,y:0}){return this.moveToElementWithCallback(t,e,s,n,{proximity:i})}isMascotNearElement(t,e=50){if(!this.positionController||!t)return!1;const i=t.getBoundingClientRect(),s=i.left+i.width/2,n=i.top+i.height/2,r=this.positionController.getOffset(),a=r.x+window.innerWidth/2,o=r.y+window.innerHeight/2;return Math.sqrt(Math.pow(a-s,2)+Math.pow(o-n,2))<=e}stopAllCallbacks(){this.activeCallbacks.forEach((t,e)=>{this.activeCallbacks.delete(e)}),this.callbackStates.clear()}destroy(){this.stopAllCallbacks(),super.destroy()}}class pr extends ur{constructor(t){super(t),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(t,e=[],i="right",s={x:20,y:0},n={}){const r=`path-${Date.now()}-${Math.random()}`,a=document.querySelector(t);if(!a)return;const o=window.innerWidth||1,h=window.innerHeight||1,l=o/2,c=h/2,u=n.coordinateSystem||"auto",d=Array.isArray(e)?e.map((t={})=>{const e="number"==typeof t.x?t.x:0,i="number"==typeof t.y?t.y:0;return"relative"===u||"auto"===u&&e>=0&&e<=1&&i>=0&&i<=1?{x:e*o-l,y:i*h-c}:"offset"===u||"auto"===u&&Math.abs(e)<=l&&Math.abs(i)<=c?{x:e,y:i}:{x:e-l,y:i-c}}):[],p=a.getBoundingClientRect(),m={x:p.left+p.width/2+s.x-l,y:p.top+p.height/2+s.y-c},g=this.positionController.getOffset?this.positionController.getOffset():{x:0,y:0},f=[{x:"number"==typeof g.x?g.x:0,y:"number"==typeof g.y?g.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=[],M=[0];let b=0;for(let t=0;t<f.length-1;t++){const e=f[t+1].x-f[t].x,i=f[t+1].y-f[t].y,s=Math.hypot(e,i);y.push(s),b+=s,M.push(b)}if(0===b)return this.positionController.setOffset(m.x,m.y,0),void("function"==typeof n.onComplete&&n.onComplete());const w="number"==typeof n.speed&&n.speed>0?n.speed:250,v=!0===n.loop,S=n.easing||"linear",k={covered:0,lastTimestamp:null},x=t=>{if(v)t%=b;else{if(t<=0)return f[0];if(t>=b)return f[f.length-1]}for(let e=0;e<y.length;e++){const i=M[e];if(t<=M[e+1]){const s=y[e]||1,n=0===s?0:(t-i)/s,r=this.positionController&&"function"==typeof this.positionController.applyEasing?this.positionController.applyEasing(n,S):n,a=f[e],o=f[e+1];return{x:a.x+(o.x-a.x)*r,y:a.y+(o.y-a.y)*r}}}return f[f.length-1]},E={stop:()=>{E.frameId&&cancelAnimationFrame(E.frameId),this.activePaths.delete(r)},frameId:null};this.activePaths.set(r,E),this.positionController.setOffset(f[0].x,f[0].y,0);const B=t=>{if(!this.activePaths.has(r))return;null===k.lastTimestamp&&(k.lastTimestamp=t);const e=t-k.lastTimestamp;if(k.lastTimestamp=t,k.covered+=w*(e/1e3),!v&&k.covered>=b)return this.positionController.setOffset(m.x,m.y,0),E.stop(),void("function"==typeof n.onComplete&&n.onComplete());const i=x(k.covered);this.positionController.setOffset(i.x,i.y,0),E.frameId=requestAnimationFrame(B)};return E.frameId=requestAnimationFrame(B),()=>{E.stop()}}moveToElementWithEasing(t,e,i=1e3,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=r.getBoundingClientRect(),o=a.left+a.width/2+n.x-window.innerWidth/2,h=a.top+a.height/2+n.y-window.innerHeight/2,l=this.positionController.getOffset(),c=performance.now();let u=null;const d=t=>{const s=t-c,n=Math.min(s/i,1),r=e(n),a=l.x+(o-l.x)*r,p=l.y+(h-l.y)*r;this.positionController.setOffset(a,p,0),n<1?(u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)):null!==u&&this.activeSmoothAnimations.delete(u)};u=requestAnimationFrame(d),this.activeSmoothAnimations.add(u)}moveToElementWithCollision(t,e=[],i=100,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=r.getBoundingClientRect(),o=a.left+a.width/2+n.x-window.innerWidth/2,h=a.top+a.height/2+n.y-window.innerHeight/2,l=this.positionController.getOffset();(()=>{let t=l.x,s=l.y;for(let n=0;n<=100;n++){const r=.01*n,a=l.x+(o-l.x)*r,c=l.y+(h-l.y)*r;let u=!1;e.forEach(e=>{let n,r;if("string"==typeof e){const t=document.querySelector(e);if(!t)return;{const e=t.getBoundingClientRect();n=e.left+e.width/2-window.innerWidth/2,r=e.top+e.height/2-window.innerHeight/2}}else n=e.x-window.innerWidth/2,r=e.y-window.innerHeight/2;if(Math.sqrt(Math.pow(a-n,2)+Math.pow(c-r,2))<i){u=!0;const e=Math.atan2(c-r,a-n),o=n+Math.cos(e)*i,h=r+Math.sin(e)*i;t=o,s=h}}),u||(t=a,s=c)}this.positionController.setOffset(t,s,0)})()}moveToElementWithAudio(t,e,i=50,s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.audioAnalyser=this.audioContext.createAnalyser(),this.audioAnalyser.fftSize=256),this.audioContext.createMediaStreamSource(e).connect(this.audioAnalyser);const a=new Uint8Array(this.audioAnalyser.frequencyBinCount),o=r.getBoundingClientRect(),h=o.left+o.width/2+n.x-window.innerWidth/2,l=o.top+o.height/2+n.y-window.innerHeight/2;let c=null;const u=()=>{this.audioAnalyser.getByteFrequencyData(a);let t=0;for(let e=0;e<a.length;e++)t+=a[e];const e=t/a.length/255*i,s=h+e,n=l+.5*e;this.positionController.setOffset(s,n,0),null!==c&&this.activeRAFIds.delete(c),c=requestAnimationFrame(u),this.activeRAFIds.add(c)};u()}moveToElementWithGaze(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;this.gazeTracker||(this.gazeTracker={x:window.innerWidth/2,y:window.innerHeight/2});const r=n.getBoundingClientRect(),a=r.left+r.width/2+s.x-window.innerWidth/2,o=r.top+r.height/2+s.y-window.innerHeight/2;let h=null;const l=()=>{const t=this.gazeTracker.x-window.innerWidth/2,i=this.gazeTracker.y-window.innerHeight/2,s=e.gazeWeight||.3,n=a+(t-a)*s,r=o+(i-o)*s;this.positionController.setOffset(n,r,0),null!==h&&this.activeRAFIds.delete(h),h=requestAnimationFrame(l),this.activeRAFIds.add(h)};l()}addObstacle(t){this.obstacles.add(t)}removeObstacle(t){this.obstacles.delete(t)}clearObstacles(){this.obstacles.clear()}destroy(){Array.from(this.activePaths.values()).forEach(t=>{t&&"function"==typeof t.stop?t.stop():t&&t.frameId&&cancelAnimationFrame(t.frameId)}),this.activePaths.clear(),this.activeRAFIds.forEach(t=>{cancelAnimationFrame(t)}),this.activeRAFIds.clear(),this.activeSmoothAnimations.forEach(t=>{cancelAnimationFrame(t)}),this.activeSmoothAnimations.clear(),this.obstacles.clear(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.audioAnalyser=null,this.gazeTracker=null,super.destroy()}}class mr extends ur{constructor(t){super(t),this.scrollCallbacks=new Map,this.physicsSimulations=new Map,this.responsiveBreakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.accessibilityEnabled=!1}moveToElementWithScroll(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`scroll-${Date.now()}-${Math.random()}`,{startScroll:a=50,endScroll:o=300,onProgress:h=null,onStart:l=null,onComplete:c=null}=e;let u=!1,d=!1;const p=()=>{const{scrollY:t}=window,e=Math.min(Math.max((t-a)/(o-a),0),1);e>0&&!u&&(u=!0,l&&l()),e>=1&&!d&&(d=!0,c&&c());const i=n.getBoundingClientRect(),r=i.left+i.width/2+s.x-window.innerWidth/2,p=i.top+i.height/2+s.y-window.innerHeight/2,m=window.innerWidth>1024,g=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=g+(r-g)*e,M=f+(p-f)*e;this.positionController.setOffset(y,M,0),h&&h(e,{scrollY:t,currentX:y,currentY:M})};return this.scrollCallbacks.set(r,p),window.addEventListener("scroll",p),p(),()=>{this.scrollCallbacks.delete(r),window.removeEventListener("scroll",p)}}moveToElementWithPhysics(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`physics-${Date.now()}-${Math.random()}`,{mass:a=1,damping:o=.98,springConstant:h=.1,maxVelocity:l=10,onUpdate:c=null}=e,u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x-window.innerWidth/2,p=u.top+u.height/2+s.y-window.innerHeight/2,m=this.positionController.getOffset();let g=m.x,f=m.y,y=0,M=0;const b=()=>{y+=(d-g)*h/a,M+=(p-f)*h/a,y*=o,M*=o;const t=Math.sqrt(y*y+M*M);t>l&&(y=y/t*l,M=M/t*l),g+=y,f+=M,this.positionController.setOffset(g,f,0),c&&c({positionX:g,positionY:f,velocityX:y,velocityY:M}),this.physicsSimulations.has(r)&&requestAnimationFrame(b)};return this.physicsSimulations.set(r,b),b(),()=>{this.physicsSimulations.delete(r)}}moveToElementWithGroup(t=[],e="center",i={x:0,y:0}){if(0===t.length)return;let s=0,n=0,r=0,a=0,o=0;if(t.forEach(t=>{const e=document.querySelector(t);if(e){const t=e.getBoundingClientRect();s+=t.left,n+=t.top,r=Math.max(r,t.left+t.width),a=Math.max(a,t.top+t.height),o++}}),0===o)return;const h=s/o,l=n/o;let c,u;switch(e){case"center":default:c=h+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"left":c=s+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"right":c=r+i.x-window.innerWidth/2,u=l+i.y-window.innerHeight/2;break;case"top":c=h+i.x-window.innerWidth/2,u=n+i.y-window.innerHeight/2;break;case"bottom":c=h+i.x-window.innerWidth/2,u=a+i.y-window.innerHeight/2}this.positionController.setOffset(c,u,0)}moveToElementWithResponsive(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=()=>{const t=this.getCurrentBreakpoint(),i=e[t]||e.default||{},r=n.getBoundingClientRect(),a=r.left+r.width/2+(i.offsetX||s.x)-window.innerWidth/2,o=r.top+r.height/2+(i.offsetY||s.y)-window.innerHeight/2;this.positionController.setOffset(a,o,0)},a=()=>{const t=this.getCurrentBreakpoint();t!==this.currentBreakpoint&&(this.currentBreakpoint=t,r())};return window.addEventListener("resize",a),r(),()=>{window.removeEventListener("resize",a)}}moveToElementWithAccessibility(t,e={},i="right",s={x:20,y:0}){if(!document.querySelector(t))return;const{announce:n=!0,announcements:r=[],screenReaderPosition:a="bottom-right"}=e;let o,h;switch(a){case"bottom-right":default:o=window.innerWidth-100-window.innerWidth/2,h=window.innerHeight-100-window.innerHeight/2;break;case"bottom-left":o=100-window.innerWidth/2,h=window.innerHeight-100-window.innerHeight/2;break;case"top-right":o=window.innerWidth-100-window.innerWidth/2,h=100-window.innerHeight/2;break;case"top-left":o=100-window.innerWidth/2,h=100-window.innerHeight/2}this.positionController.setOffset(o,h,0),n&&window.speechSynthesis&&r.forEach(t=>{if(t.condition&&t.condition()){const e=new SpeechSynthesisUtterance(t.text);e.volume=.5,e.rate=.8,window.speechSynthesis.speak(e)}})}getCurrentBreakpoint(){const t=window.innerWidth;return t<this.responsiveBreakpoints.mobile?"mobile":t<this.responsiveBreakpoints.tablet?"tablet":t<this.responsiveBreakpoints.desktop?"desktop":"large"}setBreakpoints(t){this.responsiveBreakpoints={...this.responsiveBreakpoints,...t},this.currentBreakpoint=this.getCurrentBreakpoint()}enableAccessibility(){this.accessibilityEnabled=!0}disableAccessibility(){this.accessibilityEnabled=!1}destroy(){this.scrollCallbacks.forEach((t,e)=>{window.removeEventListener("scroll",t)}),this.scrollCallbacks.clear(),this.physicsSimulations.clear(),super.destroy()}}class gr extends ur{constructor(t){super(t),this.activeInteractions=new Map,this.hoverStates=new Map,this.clickStates=new Map,this.touchStates=new Map}moveToElementWithHover(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`hover-${Date.now()}-${Math.random()}`,{onMouseEnter:a=null,onMouseLeave:o=null,onHover:h=null,followMouse:l=!1,hoverDistance:c=50}=e;let u=!1,d=0,p=0;const m=t=>{u=!0,a&&a(t)},g=t=>{u=!1,o&&o(t)},f=t=>{if(d=t.clientX,p=t.clientY,u&&h&&h(t),l&&u){const t=n.getBoundingClientRect(),e=t.left+t.width/2,i=t.top+t.height/2;if(Math.sqrt(Math.pow(d-e,2)+Math.pow(p-i,2))<=c){const t=d+s.x-window.innerWidth/2,e=p+s.y-window.innerHeight/2;this.positionController.setOffset(t,e,0)}}};return n.addEventListener("mouseenter",m),n.addEventListener("mouseleave",g),n.addEventListener("mousemove",f),this.activeInteractions.set(r,{element:n,events:[{event:"mouseenter",handler:m},{event:"mouseleave",handler:g},{event:"mousemove",handler:f}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithClick(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`click-${Date.now()}-${Math.random()}`,{onClick:a=null,onDoubleClick:o=null,maxClicks:h=3}=e;let l=0;const c=t=>{if(l++,a&&a(t,l),l>=h){const t=n.getBoundingClientRect(),e=t.left+t.width/2+s.x-window.innerWidth/2,i=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(e,i,0)}},u=t=>{o&&o(t)};return n.addEventListener("click",c),n.addEventListener("dblclick",u),this.activeInteractions.set(r,{element:n,events:[{event:"click",handler:c},{event:"dblclick",handler:u}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithTouch(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`touch-${Date.now()}-${Math.random()}`,{onTouchStart:a=null,onTouchMove:o=null,onTouchEnd:h=null,onSwipe:l=null,swipeThreshold:c=50}=e;let u=0,d=0,p=0,m=0;const g=t=>{t.touches.length>0&&(u=t.touches[0].clientX,d=t.touches[0].clientY,a&&a(t))},f=t=>{if(t.touches.length>0){const e=t.touches[0].clientX,i=t.touches[0].clientY;o&&o(t);const n=e+s.x-window.innerWidth/2,r=i+s.y-window.innerHeight/2;this.positionController.setOffset(n,r,0)}},y=t=>{if(t.changedTouches.length>0){p=t.changedTouches[0].clientX,m=t.changedTouches[0].clientY,h&&h(t);const e=p-u,i=m-d,s=Math.sqrt(e*e+i*i);if(s>c&&l){const t=Math.abs(e)>Math.abs(i)?e>0?"right":"left":i>0?"down":"up";l(t,s)}}};return n.addEventListener("touchstart",g),n.addEventListener("touchmove",f),n.addEventListener("touchend",y),this.activeInteractions.set(r,{element:n,events:[{event:"touchstart",handler:g},{event:"touchmove",handler:f},{event:"touchend",handler:y}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithFocus(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`focus-${Date.now()}-${Math.random()}`,{onFocus:a=null,onBlur:o=null,onFocusIn:h=null,onFocusOut:l=null}=e,c=t=>{a&&a(t);const e=n.getBoundingClientRect(),i=e.left+e.width/2+s.x-window.innerWidth/2,r=e.top+e.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(i,r,0)},u=t=>{o&&o(t)},d=t=>{h&&h(t)},p=t=>{l&&l(t)};return n.addEventListener("focus",c),n.addEventListener("blur",u),n.addEventListener("focusin",d),n.addEventListener("focusout",p),this.activeInteractions.set(r,{element:n,events:[{event:"focus",handler:c},{event:"blur",handler:u},{event:"focusin",handler:d},{event:"focusout",handler:p}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}moveToElementWithKeyboard(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`keyboard-${Date.now()}-${Math.random()}`,{onKeyDown:a=null,onKeyUp:o=null,onKeyPress:h=null,targetKeys:l=["Enter","Space"]}=e,c=t=>{if(a&&a(t),l.includes(t.key)){const t=n.getBoundingClientRect(),e=t.left+t.width/2+s.x-window.innerWidth/2,i=t.top+t.height/2+s.y-window.innerHeight/2;this.positionController.setOffset(e,i,0)}},u=t=>{o&&o(t)},d=t=>{h&&h(t)};return n.addEventListener("keydown",c),n.addEventListener("keyup",u),n.addEventListener("keypress",d),this.activeInteractions.set(r,{element:n,events:[{event:"keydown",handler:c},{event:"keyup",handler:u},{event:"keypress",handler:d}]}),()=>{const t=this.activeInteractions.get(r);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(r))}}stopAllInteractions(){this.activeInteractions.forEach((t,e)=>{t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.activeInteractions.delete(e)}),this.hoverStates.clear(),this.clickStates.clear(),this.touchStates.clear()}destroy(){this.stopAllInteractions(),super.destroy()}}class fr extends ur{constructor(t){super(t),this.activeAnimations=new Map,this.animationQueue=[],this.isAnimating=!1,this.queueTimeouts=new Set,this.activeRAFIds=new Set,this.animationRAFIds=new Map}moveToElementWithBounce(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`bounce-${Date.now()}-${Math.random()}`,{duration:a=1e3,intensity:o=50,bounces:h=3,onComplete:l=null}=e,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,p=this.positionController.getOffset(),m=performance.now(),g=t=>{const e=t-m,i=Math.min(e/a,1),s=1-Math.pow(1-i,3),n=Math.sin(s*Math.PI*h)*o*(1-i),c=p.x+(u-p.x)*i,f=p.y+(d-p.y)*i+n;if(this.positionController.setOffset(c,f,0),i<1){this.activeAnimations.set(r,g);const t=requestAnimationFrame(g);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,g);const f=requestAnimationFrame(g);return this.activeRAFIds.add(f),this.animationRAFIds.set(r,f),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithShake(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`shake-${Date.now()}-${Math.random()}`,{duration:a=500,intensity:o=10,frequency:h=20,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=(Math.random()-.5)*o*(1-i),n=(Math.random()-.5)*o*(1-i),c=u+s,g=d+n;if(this.positionController.setOffset(c,g,0),i<1)this.activeAnimations.set(r,m),setTimeout(()=>{const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)},1e3/h);else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithPulse(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`pulse-${Date.now()}-${Math.random()}`,{duration:a=2e3,intensity:o=20,frequency:h=2,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=Math.sin(e*h*.01)*o*(1-i),n=u+s,c=d+s;if(this.positionController.setOffset(n,c,0),i<1){this.activeAnimations.set(r,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithWiggle(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`wiggle-${Date.now()}-${Math.random()}`,{duration:a=1e3,intensity:o=15,frequency:h=8,onComplete:l=null}=e,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,p=performance.now(),m=t=>{const e=t-p,i=Math.min(e/a,1),s=Math.sin(e*h*.01)*o*(1-i),n=Math.cos(e*h*.01)*o*(1-i),c=u+s,g=d+n;if(this.positionController.setOffset(c,g,0),i<1){this.activeAnimations.set(r,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(r,t)}else{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(r)),l&&l()}};this.activeAnimations.set(r,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(r,g),()=>{this.activeAnimations.delete(r);const t=this.animationRAFIds.get(r);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(r))}}moveToElementWithCustom(t,e,i={},s="right",n={x:20,y:0}){const r=document.querySelector(t);if(!r)return;const a=`custom-${Date.now()}-${Math.random()}`,{duration:o=1e3,onComplete:h=null}=i,l=r.getBoundingClientRect(),c=l.left+l.width/2+n.x-window.innerWidth/2,u=l.top+l.height/2+n.y-window.innerHeight/2,d=this.positionController.getOffset(),p=performance.now(),m=t=>{const i=t-p,s=Math.min(i/o,1),n=e(s,{elapsed:i,startOffset:d,targetX:c,targetY:u,currentTime:t});if(n&&"object"==typeof n){const t=void 0!==n.x?n.x:c,e=void 0!==n.y?n.y:u;this.positionController.setOffset(t,e,0)}if(s<1){this.activeAnimations.set(a,m);const t=requestAnimationFrame(m);this.activeRAFIds.add(t),this.animationRAFIds.set(a,t)}else{this.activeAnimations.delete(a);const t=this.animationRAFIds.get(a);void 0!==t&&(this.activeRAFIds.delete(t),this.animationRAFIds.delete(a)),h&&h()}};this.activeAnimations.set(a,m);const g=requestAnimationFrame(m);return this.activeRAFIds.add(g),this.animationRAFIds.set(a,g),()=>{this.activeAnimations.delete(a);const t=this.animationRAFIds.get(a);void 0!==t&&(cancelAnimationFrame(t),this.activeRAFIds.delete(t),this.animationRAFIds.delete(a))}}queueAnimations(t=[]){this.animationQueue=[...this.animationQueue,...t],this.processAnimationQueue()}processAnimationQueue(){if(this.isAnimating||0===this.animationQueue.length)return;this.isAnimating=!0;const t=this.animationQueue.shift();if(t){const e=this.executeAnimation(t);if(e){const i=setTimeout(()=>{this.queueTimeouts.delete(i),e(),this.isAnimating=!1,this.processAnimationQueue()},t.duration||1e3);this.queueTimeouts.add(i)}}}executeAnimation(t){const{type:e,targetSelector:i,options:s={},position:n="right",offset:r={x:20,y:0}}=t;switch(e){case"bounce":return this.moveToElementWithBounce(i,s,n,r);case"shake":return this.moveToElementWithShake(i,s,n,r);case"pulse":return this.moveToElementWithPulse(i,s,n,r);case"wiggle":return this.moveToElementWithWiggle(i,s,n,r);case"custom":return this.moveToElementWithCustom(i,s.animationFunction,s,n,r);default:return this.moveToElement(i,n,r)}}stopAllAnimations(){this.activeAnimations.forEach((t,e)=>{this.activeAnimations.delete(e)}),this.activeRAFIds.forEach(t=>cancelAnimationFrame(t)),this.activeRAFIds.clear(),this.animationRAFIds.clear(),this.queueTimeouts.forEach(t=>clearTimeout(t)),this.queueTimeouts.clear(),this.animationQueue=[],this.isAnimating=!1}destroy(){this.stopAllAnimations(),super.destroy()}}class yr extends ur{constructor(t){super(t),this.activeEffects=new Map,this.trailPoints=[],this.particles=[],this.effectCanvas=null,this.effectContext=null,this.maxTrailPoints=50,this.maxParticles=100}moveToElementWithTrail(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`trail-${Date.now()}-${Math.random()}`,{color:a="#00ff88",width:o=3,opacity:h=.8,fadeSpeed:l=.95,onComplete:c=null}=e;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,p=u.top+u.height/2+s.y,m=this.positionController.getOffset(),g=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),M=t=>{const e=t-y,i=Math.min(e/1e3,1),s=g+(d-g)*i,n=f+(p-f)*i;this.trailPoints.push({x:s,y:n,opacity:h*(1-i),timestamp:t}),this.trailPoints.length>this.maxTrailPoints&&this.trailPoints.shift(),this.trailPoints.forEach(t=>{t.opacity*=l}),this.trailPoints=this.trailPoints.filter(t=>t.opacity>.01),this.drawTrail(a,o),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(r,M),requestAnimationFrame(M)):(this.activeEffects.delete(r),c&&c())};return this.activeEffects.set(r,M),requestAnimationFrame(M),()=>{this.activeEffects.delete(r)}}moveToElementWithParticles(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`particles-${Date.now()}-${Math.random()}`,{count:a=20,color:o="#00ff88",size:h=2,speed:l=2,life:c=1e3,onComplete:u=null}=e;this.initializeEffectCanvas();const d=n.getBoundingClientRect(),p=d.left+d.width/2+s.x,m=d.top+d.height/2+s.y,g=this.positionController.getOffset(),f=g.x+window.innerWidth/2,y=g.y+window.innerHeight/2,M=performance.now();for(let t=0;t<a;t++)this.particles.push({x:f,y:y,vx:(Math.random()-.5)*l,vy:(Math.random()-.5)*l,life:c,maxLife:c,color:o,size:h});const b=t=>{const e=t-M,i=Math.min(e/1e3,1);this.particles.forEach(t=>{t.x+=t.vx,t.y+=t.vy,t.life-=16,t.opacity=t.life/t.maxLife}),this.particles=this.particles.filter(t=>t.life>0),this.drawParticles();const s=f+(p-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(r,b),requestAnimationFrame(b)):(this.activeEffects.delete(r),u&&u())};return this.activeEffects.set(r,b),requestAnimationFrame(b),()=>{this.activeEffects.delete(r)}}moveToElementWithGlow(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const r=`glow-${Date.now()}-${Math.random()}`,{color:a="#00ff88",intensity:o=50,radius:h=100,duration:l=1e3,onComplete:c=null}=e;this.initializeEffectCanvas();const u=n.getBoundingClientRect(),d=u.left+u.width/2+s.x,p=u.top+u.height/2+s.y,m=this.positionController.getOffset(),g=m.x+window.innerWidth/2,f=m.y+window.innerHeight/2,y=performance.now(),M=t=>{const e=t-y,i=Math.min(e/l,1),s=g+(d-g)*i,n=f+(p-f)*i;this.drawGlow(s,n,a,o,h,i),this.positionController.setOffset(s-window.innerWidth/2,n-window.innerHeight/2,0),i<1?(this.activeEffects.set(r,M),requestAnimationFrame(M)):(this.activeEffects.delete(r),c&&c())};return this.activeEffects.set(r,M),requestAnimationFrame(M),()=>{this.activeEffects.delete(r)}}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(t,e){if(this.effectContext&&!(this.trailPoints.length<2)){this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height),this.effectContext.strokeStyle=t,this.effectContext.lineWidth=e,this.effectContext.lineCap="round",this.effectContext.lineJoin="round",this.effectContext.beginPath(),this.effectContext.moveTo(this.trailPoints[0].x,this.trailPoints[0].y);for(let t=1;t<this.trailPoints.length;t++){const e=this.trailPoints[t];this.effectContext.globalAlpha=e.opacity,this.effectContext.lineTo(e.x,e.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(t=>{this.effectContext.globalAlpha=t.opacity,this.effectContext.fillStyle=t.color,this.effectContext.beginPath(),this.effectContext.arc(t.x,t.y,t.size,0,2*Math.PI),this.effectContext.fill()}),this.effectContext.globalAlpha=1)}drawGlow(t,e,i,s,n,r){if(!this.effectContext)return;this.effectContext.clearRect(0,0,this.effectCanvas.width,this.effectCanvas.height);const a=this.effectContext.createRadialGradient(t,e,0,t,e,n),o=Math.floor(s*r).toString(16).padStart(2,"0"),h=i.startsWith("#")?i:`#${i}`;a.addColorStop(0,`${h}${o}`),a.addColorStop(1,`${h}00`),this.effectContext.fillStyle=a,this.effectContext.beginPath(),this.effectContext.arc(t,e,n,0,2*Math.PI),this.effectContext.fill()}stopAllEffects(){this.activeEffects.forEach((t,e)=>{this.activeEffects.delete(e)}),this.trailPoints=[],this.particles=[]}destroy(){this.stopAllEffects(),this.effectCanvas&&(document.body.removeChild(this.effectCanvas),this.effectCanvas=null,this.effectContext=null),super.destroy()}}class Mr extends ur{constructor(t){super(t),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(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{announce:r=!0,announcement:a="Mascot moved to element",role:o="button",label:h=n.textContent||n.alt||"Interactive element"}=e;this.moveToElement(t,i,s),r&&this.accessibilityOptions.screenReader&&this.announceToScreenReader(a),n&&(n.setAttribute("role",o),n.setAttribute("aria-label",h),n.setAttribute("aria-live","polite"))}moveToElementWithKeyboard(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{onKeyDown:r=null,onKeyUp:a=null,onEnter:o=null,onEscape:h=null,onArrowKeys:l=null}=e,c=`keyboard-${Date.now()}-${Math.random()}`,u=t=>{switch(r&&r(t),t.key){case"Enter":case" ":o&&o(t);break;case"Escape":h&&h(t);break;case"ArrowUp":case"ArrowDown":case"ArrowLeft":case"ArrowRight":l&&l(t)}},d=t=>{a&&a(t)};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(t,i,s),()=>{const t=this.keyboardListeners.get(c);t&&(t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)}),this.keyboardListeners.delete(c))}}moveToElementWithHighContrast(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{backgroundColor:r="#000000",textColor:a="#ffffff",borderColor:o="#ffffff",borderWidth:h=2}=e;this.accessibilityOptions.highContrast&&(n.style.backgroundColor=r,n.style.color=a,n.style.border=`${h}px solid ${o}`,n.style.outline=`${h}px solid ${o}`),this.moveToElement(t,i,s)}moveToElementWithReducedMotion(t,e={},i="right",s={x:20,y:0}){if(!document.querySelector(t))return;const{duration:n=0,easing:r="linear"}=e;window.matchMedia("(prefers-reduced-motion: reduce)").matches||this.accessibilityOptions.reducedMotion?this.moveToElement(t,i,s):this.moveToElement(t,i,s,{duration:n,easing:r})}moveToElementWithFocus(t,e={},i="right",s={x:20,y:0}){const n=document.querySelector(t);if(!n)return;const{autoFocus:r=!1,focusRing:a=!0,focusOrder:o=[]}=e;o.length>0?this.focusOrder=o:this.focusOrder.includes(t)||this.focusOrder.push(t),n.hasAttribute("tabindex")||n.setAttribute("tabindex","0"),a&&(n.style.outline="2px solid #0066cc",n.style.outlineOffset="2px"),r&&n.focus(),this.moveToElement(t,i,s)}navigateFocus(t="next"){if(0===this.focusOrder.length)return;this.currentFocusIndex="next"===t?(this.currentFocusIndex+1)%this.focusOrder.length:(this.currentFocusIndex-1+this.focusOrder.length)%this.focusOrder.length;const e=this.focusOrder[this.currentFocusIndex],i=document.querySelector(e);i&&(i.focus(),this.moveToElement(e,"right",{x:20,y:0}))}announceToScreenReader(t){if(!this.accessibilityOptions.announcements)return;let e=document.getElementById("mascot-live-region");e||(e=document.createElement("div"),e.id="mascot-live-region",e.setAttribute("aria-live","polite"),e.setAttribute("aria-atomic","true"),e.style.position="absolute",e.style.left="-10000px",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",document.body.appendChild(e)),e.textContent=t,setTimeout(()=>{e.textContent=""},1e3)}enableAccessibility(t={}){this.accessibilityOptions={...this.accessibilityOptions,...t}}disableAccessibility(t={}){Object.keys(t).forEach(t=>{({}).hasOwnProperty.call(this.accessibilityOptions,t)&&(this.accessibilityOptions[t]=!1)})}isAccessibilityEnabled(t){return this.accessibilityOptions[t]||!1}getAccessibilityOptions(){return{...this.accessibilityOptions}}destroy(){this.keyboardListeners.forEach((t,e)=>{t.events.forEach(({event:e,handler:i})=>{t.element.removeEventListener(e,i)})}),this.keyboardListeners.clear();const t=document.getElementById("mascot-live-region");t&&document.body.removeChild(t),this.focusOrder=[],this.currentFocusIndex=0,super.destroy()}}class br{constructor(t){this.positionController=t,this.callbacks=new dr(t),this.advanced=new pr(t),this.context=new mr(t),this.interactions=new gr(t),this.animations=new fr(t),this.effects=new yr(t),this.accessibility=new Mr(t)}moveToElementWithCallback(...t){return this.callbacks.moveToElementWithCallback(...t)}moveToElementSequence(...t){return this.callbacks.moveToElementSequence(...t)}moveToElementWithDelay(...t){return this.callbacks.moveToElementWithDelay(...t)}moveToElementWithCondition(...t){return this.callbacks.moveToElementWithCondition(...t)}moveToElementWithRepeat(...t){return this.callbacks.moveToElementWithRepeat(...t)}moveToElementWithProximity(...t){return this.callbacks.moveToElementWithProximity(...t)}moveToElementWithPath(...t){return this.advanced.moveToElementWithPath(...t)}moveToElementWithEasing(...t){return this.advanced.moveToElementWithEasing(...t)}moveToElementWithCollision(...t){return this.advanced.moveToElementWithCollision(...t)}moveToElementWithAudio(...t){return this.advanced.moveToElementWithAudio(...t)}moveToElementWithGaze(...t){return this.advanced.moveToElementWithGaze(...t)}moveToElementWithScroll(...t){return this.context.moveToElementWithScroll(...t)}moveToElementWithPhysics(...t){return this.context.moveToElementWithPhysics(...t)}moveToElementWithGroup(...t){return this.context.moveToElementWithGroup(...t)}moveToElementWithResponsive(...t){return this.context.moveToElementWithResponsive(...t)}moveToElementWithAccessibility(...t){return this.context.moveToElementWithAccessibility(...t)}moveToElementWithHover(...t){return this.interactions.moveToElementWithHover(...t)}moveToElementWithClick(...t){return this.interactions.moveToElementWithClick(...t)}moveToElementWithTouch(...t){return this.interactions.moveToElementWithTouch(...t)}moveToElementWithFocus(...t){return this.interactions.moveToElementWithFocus(...t)}moveToElementWithKeyboard(...t){return this.interactions.moveToElementWithKeyboard(...t)}moveToElementWithBounce(...t){return this.animations.moveToElementWithBounce(...t)}moveToElementWithShake(...t){return this.animations.moveToElementWithShake(...t)}moveToElementWithPulse(...t){return this.animations.moveToElementWithPulse(...t)}moveToElementWithWiggle(...t){return this.animations.moveToElementWithWiggle(...t)}moveToElementWithCustom(...t){return this.animations.moveToElementWithCustom(...t)}moveToElementWithTrail(...t){return this.effects.moveToElementWithTrail(...t)}moveToElementWithParticles(...t){return this.effects.moveToElementWithParticles(...t)}moveToElementWithGlow(...t){return this.effects.moveToElementWithGlow(...t)}moveToElementWithScreenReader(...t){return this.accessibility.moveToElementWithScreenReader(...t)}moveToElementWithKeyboardAccessible(...t){return this.accessibility.moveToElementWithKeyboard(...t)}moveToElementWithHighContrast(...t){return this.accessibility.moveToElementWithHighContrast(...t)}moveToElementWithReducedMotion(...t){return this.accessibility.moveToElementWithReducedMotion(...t)}moveToElementWithFocusAccessible(...t){return this.accessibility.moveToElementWithFocus(...t)}announceToScreenReader(...t){return this.accessibility.announceToScreenReader(...t)}navigateFocus(...t){return this.accessibility.navigateFocus(...t)}enableAccessibility(...t){return this.accessibility.enableAccessibility(...t)}disableAccessibility(...t){return this.accessibility.disableAccessibility(...t)}destroy(){this.callbacks.destroy(),this.advanced.destroy(),this.context.destroy(),this.interactions.destroy(),this.animations.destroy(),this.effects.destroy(),this.accessibility.destroy()}}class wr{constructor(t){this.positionController=t,this.isTracking=!1,this.trackingCallbacks=new Map,this.audioContext=null,this.audioAnalyser=null,this.audioData=null}moveToMouse(t={x:20,y:20},e={}){const i="mouse-tracking",s=i=>{const s=i.clientX+t.x,n=i.clientY+t.y,r=s-window.innerWidth/2,a=n-window.innerHeight/2;!1!==e.smooth?this.positionController.animateOffset(r,a,0,e.duration||200,"easeOutQuad"):this.positionController.setOffset(r,a,0)};return this.trackingCallbacks.set(i,s),window.addEventListener("mousemove",s),()=>{window.removeEventListener("mousemove",s),this.trackingCallbacks.delete(i)}}moveToTouch(t={x:20,y:20},e={}){const i="touch-tracking",s=i=>{if(i.touches.length>0){const s=i.touches[0],n=s.clientX+t.x,r=s.clientY+t.y,a=n-window.innerWidth/2,o=r-window.innerHeight/2;!1!==e.smooth?this.positionController.animateOffset(a,o,0,e.duration||200,"easeOutQuad"):this.positionController.setOffset(a,o,0)}};return this.trackingCallbacks.set(i,s),window.addEventListener("touchmove",s),()=>{window.removeEventListener("touchmove",s),this.trackingCallbacks.delete(i)}}moveToAudio(t=0,e=50,i={}){if(this.audioContext||this.initAudioContext(),!this.audioContext||!this.audioAnalyser)return;const s="audio-tracking",n=()=>{if(!this.isTracking)return;this.audioAnalyser.getByteFrequencyData(this.audioData);let t=0;for(let e=0;e<this.audioData.length;e++)t+=this.audioData[e];const s=t/this.audioData.length/255*e,r=(i.centerX||0)+s,a=(i.centerY||0)+.5*s,o=r-window.innerWidth/2,h=a-window.innerHeight/2;this.positionController.setOffset(o,h,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(t){}}connectAudioSource(t){this.audioContext&&this.audioAnalyser||this.initAudioContext(),this.audioContext&&this.audioAnalyser&&this.audioContext.createMediaStreamSource(t).connect(this.audioAnalyser)}moveToViewport(t="right",e={x:20,y:20}){let i,s;switch(t){case"top":i=window.innerWidth/2,s=e.y;break;case"bottom":i=window.innerWidth/2,s=window.innerHeight-e.y;break;case"left":i=e.x,s=window.innerHeight/2;break;case"right":default:i=window.innerWidth-e.x,s=window.innerHeight/2;break;case"top-left":i=e.x,s=e.y;break;case"top-right":i=window.innerWidth-e.x,s=e.y;break;case"bottom-left":i=e.x,s=window.innerHeight-e.y;break;case"bottom-right":i=window.innerWidth-e.x,s=window.innerHeight-e.y}const n=i-window.innerWidth/2,r=s-window.innerHeight/2;this.positionController.setOffset(n,r,0)}stopAllTracking(){this.trackingCallbacks.forEach((t,e)=>{"mouse-tracking"===e?window.removeEventListener("mousemove",t):"touch-tracking"===e&&window.removeEventListener("touchmove",t)}),this.trackingCallbacks.clear(),this.isTracking=!1}destroy(){this.stopAllTracking(),this.audioContext&&(this.audioContext.close(),this.audioContext=null),this.positionController=null}}class vr{constructor(t){this.positionController=t,this.isRunning=!1,this.physicsCallbacks=new Map,this.velocity={x:0,y:0},this.acceleration={x:0,y:0},this.lastTime=0}moveToGrid(t,e,i={x:0,y:0},s={}){const n=s.gridSize||100,r=t*n+i.x,a=e*n+i.y,o=r-window.innerWidth/2,h=a-window.innerHeight/2;!1!==s.animate?this.positionController.animateOffset(o,h,0,s.duration||1e3,s.easing||"easeOutCubic"):this.positionController.setOffset(o,h,0)}moveToGravity(t={x:0,y:0},e=.1,i={}){const s="gravity",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y,o=t.x-n,h=t.y-a,l=Math.sqrt(o*o+h*h);if(l>0){const t=e/(l*l);this.acceleration.x=o/l*t,this.acceleration.y=h/l*t,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const s=i.damping||.98;this.velocity.x*=s,this.velocity.y*=s;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t=[],e=.05,i={}){const s="magnetic",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y;let o=0,h=0;t.forEach(t=>{let i,s;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();i=t.left+t.width/2-window.innerWidth/2,s=t.top+t.height/2-window.innerHeight/2}}else{if(void 0===t.x||void 0===t.y)return;i=t.x-window.innerWidth/2,s=t.y-window.innerHeight/2}const r=i-n,l=s-a,c=Math.sqrt(r*r+l*l);if(c>0){const t=e/(c*c);o+=r/c*t,h+=l/c*t}}),this.acceleration.x=o,this.acceleration.y=h,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const l=i.damping||.95;this.velocity.x*=l,this.velocity.y*=l;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t=[],e=100,i={}){const s="avoid",n=s=>{if(!this.isRunning)return;const r=s-this.lastTime;if(this.lastTime=s,r>0){const s=this.positionController.getOffset(),n=s.x,a=s.y;let o=0,h=0;t.forEach(t=>{let i,s;if("string"==typeof t){const e=document.querySelector(t);if(!e)return;{const t=e.getBoundingClientRect();i=t.left+t.width/2-window.innerWidth/2,s=t.top+t.height/2-window.innerHeight/2}}else{if(void 0===t.x||void 0===t.y)return;i=t.x-window.innerWidth/2,s=t.y-window.innerHeight/2}const r=n-i,l=a-s,c=Math.sqrt(r*r+l*l);if(c<e&&c>0){const t=(e-c)/e;o+=r/c*t,h+=l/c*t}}),this.acceleration.x=o,this.acceleration.y=h,this.velocity.x+=this.acceleration.x*r,this.velocity.y+=this.acceleration.y*r;const l=i.damping||.9;this.velocity.x*=l,this.velocity.y*=l;const c=n+this.velocity.x*r,u=a+this.velocity.y*r;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(t={x:0,y:0,width:400,height:400},e=3e3,i={}){const s="random",n=()=>{if(!this.isRunning)return;const s=t.x+Math.random()*t.width,r=t.y+Math.random()*t.height,a=s-window.innerWidth/2,o=r-window.innerHeight/2;!1!==i.animate?this.positionController.animateOffset(a,o,0,i.duration||1e3,i.easing||"easeOutCubic"):this.positionController.setOffset(a,o,0),this.isRunning&&setTimeout(n,e)};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 Sr{constructor(t){this.positionController=t,this.isRunning=!1,this.animationCallbacks=new Map,this.pathProgress=0,this.timeProgress=0,this.scrollProgress=0}moveToPath(t=[],e=1,i={}){if(t.length<2)return;const s="path",n=!1!==i.loop,r=i.reverse||!1,a=o=>{if(!this.isRunning)return;const h=o-(this.lastTime||o);if(this.lastTime=o,h>0){this.pathProgress+=e*h/1e3,this.pathProgress=n?this.pathProgress%t.length:Math.min(this.pathProgress,t.length-1);const a=Math.floor(this.pathProgress),o=this.pathProgress-a;let l,c;r?(l=t[t.length-1-a],c=t[t.length-2-a]||t[0]):(l=t[a],c=t[a+1]||t[0]);const u=l.x+(c.x-l.x)*o,d=l.y+(c.y-l.y)*o,p=u-window.innerWidth/2,m=d-window.innerHeight/2;if(this.positionController.setOffset(p,m,0),!n&&this.pathProgress>=t.length-1)return this.isRunning=!1,this.animationCallbacks.delete(s),void(i.onComplete&&i.onComplete())}this.isRunning&&requestAnimationFrame(a)};return this.animationCallbacks.set(s,a),this.isRunning=!0,this.lastTime=performance.now(),a(this.lastTime),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}moveToTime(t=2e3,e="easeInOutCubic",i={}){const s="time",n=performance.now(),r=this.positionController.getOffset(),a=i.target||{x:0,y:0},o=h=>{if(!this.isRunning)return;const l=h-n,c=Math.min(l/t,1),u=this.applyEasing(c,e),d=r.x+(a.x-r.x)*u,p=r.y+(a.y-r.y)*u;this.positionController.setOffset(d,p,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(t=0,e={x:0,y:0},i={}){const s="scroll",n=()=>{if(!this.isRunning)return;const s=window.innerWidth,n=window.innerHeight;let r,a;if("horizontal"===i.direction)r=t*s+e.x,a=n/2+e.y;else if("vertical"===i.direction)r=s/2+e.x,a=t*n+e.y;else{const o=t*Math.PI*2,h=i.radius||Math.min(s,n)/4;r=s/2+Math.cos(o)*h+e.x,a=n/2+Math.sin(o)*h+e.y}const o=r-s/2,h=a-n/2;this.positionController.setOffset(o,h,0)};return this.animationCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.animationCallbacks.delete(s)}}animateTo(t,e,i=1e3,s="easeOutCubic"){this.positionController.animateOffset(t,e,0,i,s)}applyEasing(t,e){switch(e){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return 1-(1-t)*(1-t);case"easeInOutQuad":return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;case"easeInCubic":return t*t*t;case"easeOutCubic":return 1-Math.pow(1-t,3);case"easeInOutCubic":return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;case"easeInBack":{const e=1.70158;return(e+1)*t*t*t-e*t*t}case"easeOutBack":{const e=1.70158;return 1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}case"easeInElastic":return 0===t?0:1===t?1:-Math.pow(2,10*t-10)*Math.sin((10*t-10.75)*(2*Math.PI/3));case"easeOutElastic":return 0===t?0:1===t?1:Math.pow(2,-10*t)*Math.sin((10*t-.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 kr{constructor(t){this.positionController=t,this.breakpoints={mobile:768,tablet:1024,desktop:1200},this.currentBreakpoint=this.getCurrentBreakpoint(),this.responsiveCallbacks=new Map}getCurrentBreakpoint(){const t=window.innerWidth;return t<this.breakpoints.mobile?"mobile":t<this.breakpoints.tablet?"tablet":t<this.breakpoints.desktop?"desktop":"large"}moveToResponsive(t={},e={}){const i="responsive",s=()=>{if(!this.isRunning)return;const i=this.getCurrentBreakpoint(),s=t[i]||t.default||{x:0,y:0},n=s.x-window.innerWidth/2,r=s.y-window.innerHeight/2;!1!==e.animate?this.positionController.animateOffset(n,r,0,e.duration||500,e.easing||"easeOutCubic"):this.positionController.setOffset(n,r,0)};this.responsiveCallbacks.set(i,s),this.isRunning=!0,s();const n=()=>{const t=this.getCurrentBreakpoint();t!==this.currentBreakpoint&&(this.currentBreakpoint=t,s())};return window.addEventListener("resize",n),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(i),window.removeEventListener("resize",n)}}moveToGroup(t=[],e="center",i={x:0,y:0}){if(0===t.length)return;let s=0,n=0,r=0,a=0,o=0;if(t.forEach(t=>{let e,i,h,l;if("string"==typeof t){const s=document.querySelector(t);if(!s)return;{const t=s.getBoundingClientRect();e=t.left,i=t.top,h=t.width,l=t.height}}else{if(void 0===t.x||void 0===t.y)return;e=t.x,i=t.y,h=t.width||0,l=t.height||0}s+=e,n+=i,r=Math.max(r,e+h),a=Math.max(a,i+l),o++}),0===o)return;const h=s/o,l=n/o;let c,u;switch(e){case"center":default:c=h+i.x,u=l+i.y;break;case"left":c=s+i.x,u=l+i.y;break;case"right":c=r+i.x,u=l+i.y;break;case"top":c=h+i.x,u=n+i.y;break;case"bottom":c=h+i.x,u=a+i.y}const d=c-window.innerWidth/2,p=u-window.innerHeight/2;this.positionController.setOffset(d,p,0)}moveToAccessibility(t=[],e="bottom-right",i={}){const s="accessibility",n=()=>{if(!this.isRunning)return;let s,n;switch((window.speechSynthesis||window.webkitSpeechSynthesis)&&i.announce&&t.forEach(t=>{t.condition&&t.condition()&&this.announceToScreenReader(t.text)}),e){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 r=s-window.innerWidth/2,a=n-window.innerHeight/2;this.positionController.setOffset(r,a,0)};return this.responsiveCallbacks.set(s,n),this.isRunning=!0,n(),()=>{this.isRunning=!1,this.responsiveCallbacks.delete(s)}}announceToScreenReader(t){if(window.speechSynthesis){const e=new SpeechSynthesisUtterance(t);e.volume=.5,e.rate=.8,window.speechSynthesis.speak(e)}}setBreakpoints(t){this.breakpoints={...this.breakpoints,...t},this.currentBreakpoint=this.getCurrentBreakpoint()}getCurrentBreakpointName(){return this.currentBreakpoint}isBreakpoint(t){return this.currentBreakpoint===t}stopAllResponsive(){this.isRunning=!1,this.responsiveCallbacks.clear()}destroy(){this.stopAllResponsive(),this.positionController=null}}class xr{constructor(t){this.positionController=t,this.elementTargeting=new ur(t),this.inputTracking=new wr(t),this.physics=new vr(t),this.animation=new Sr(t),this.responsive=new kr(t),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(t,...e){const i=this.methods.get(t);return i?i(...e):null}getAvailableMethods(){return Array.from(this.methods.keys())}hasMethod(t){return this.methods.has(t)}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 Er{constructor(t={}){this.offsetX=t.offsetX||0,this.offsetY=t.offsetY||0,this.offsetZ=t.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=t.onUpdate||(()=>{}),this.onAnimationComplete=t.onAnimationComplete||(()=>{}),this.minScale=t.minScale||.5,this.maxScale=t.maxScale||2,this.zScaleRange=t.zScaleRange||1e3,this.globalScale=1,this.coreScaleOverride=1,this.particleScaleOverride=1,this.positioning=new xr(this),this.elementTargeting=new br(this)}setOffset(t,e,i=0){this.stopAnimation(),this.offsetX=t,this.offsetY=e,this.offsetZ=i,this.onUpdate(this.getEffectiveCenter())}getOffset(){return{x:this.offsetX,y:this.offsetY,z:this.offsetZ}}getPosition(t=window.innerWidth/2,e=window.innerHeight/2){return{x:t+this.offsetX,y:e+this.offsetY,z:this.offsetZ,scale:this.getZScale()}}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){this.stopAnimation(),this.startOffset={x:this.offsetX,y:this.offsetY,z:this.offsetZ},this.targetOffset={x:t,y:e,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 t=e=>{if(!this.isAnimating)return;const i=e-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(t)};this.animationId=requestAnimationFrame(t)}getEffectiveCenter(t=0,e=0){return{x:t+this.offsetX,y:e+this.offsetY,scale:this.getZScale(),coreScale:this.getCoreScale(),particleScale:this.getParticleScale()}}getZScale(){const t=-this.offsetZ/this.zScaleRange,e=Math.max(-1,Math.min(1,t));return this.lerp(this.minScale,this.maxScale,(e+1)/2)*this.globalScale}setGlobalScale(t){this.globalScale=Math.max(.1,t),this.onUpdate(this.getEffectiveCenter())}setScaleOverrides(t){"number"==typeof t?(this.globalScale=Math.max(.1,t),this.coreScaleOverride=1,this.particleScaleOverride=1):(void 0!==t.global&&(this.globalScale=Math.max(.1,t.global)),void 0!==t.core&&(this.coreScaleOverride=Math.max(.1,t.core)),void 0!==t.particles&&(this.particleScaleOverride=Math.max(.1,t.particles))),this.onUpdate(this.getEffectiveCenter())}getCoreScale(){return this.calculateBaseZScale()*this.globalScale*this.coreScaleOverride}getParticleScale(){return this.calculateBaseZScale()*this.globalScale*this.particleScaleOverride}calculateBaseZScale(){const t=-this.offsetZ/this.zScaleRange,e=Math.max(-1,Math.min(1,t));return this.lerp(this.minScale,this.maxScale,(e+1)/2)}lerp(t,e,i){return t+(e-t)*i}applyEasing(t,e){switch(e){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return 1-(1-t)*(1-t);case"easeInOutQuad":return t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2;case"easeInCubic":return t*t*t;case"easeOutCubic":return 1-Math.pow(1-t,3);case"easeInOutCubic":return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;case"easeInBack":{const e=1.70158;return(e+1)*t*t*t-e*t*t}case"easeOutBack":{const e=1.70158;return 1+(e+1)*Math.pow(t-1,3)+e*Math.pow(t-1,2)}}}getPositioning(){return this.positioning}getElementTargeting(){return this.elementTargeting}callPositioning(t,...e){return this.positioning.call(t,...e)}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 Br{static Ct(){return Br.Tt||(Br.Tt=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}]}]])),Br.Tt}static getSoundConfig(t){return Br.Ct().get(t)||null}}class Ar{constructor(t){this.Pt=t,this.Dt=new Map,this.Rt=t.createGain(),this.Rt.connect(t.destination),this.Ft={},this.zt=0,this.qt=!1,this.Ot=0,this.jt=0,this.It=null,this.$t=null}async addLayer(t,e){let i;try{if(e.src instanceof ArrayBuffer)i=await this.Pt.decodeAudioData(e.src);else if(e.src instanceof Blob){const t=await e.src.arrayBuffer();i=await this.Pt.decodeAudioData(t)}else if("string"==typeof e.src){const t=await fetch(e.src);if(!t.ok)return;const s=await t.arrayBuffer();i=await this.Pt.decodeAudioData(s)}}catch(t){return}if(!i)return;const s=this.Pt.createGain(),n=e.gain??0;s.gain.setValueAtTime(n,this.Pt.currentTime),s.connect(this.Rt),this.Dt.set(t,{buffer:i,gainNode:s,sourceNode:null,loop:e.loop??!0,baseGain:n}),this.Ft[t]=n}removeLayer(t){const e=this.Dt.get(t);if(e){if(e.sourceNode)try{e.sourceNode.stop()}catch{}e.gainNode.disconnect(),this.Dt.delete(t),delete this.Ft[t]}}play(t=0){this.qt&&this.stop();const e=t/1e3;this.Ot=e,this.jt=this.Pt.currentTime,this.qt=!0;for(const[,t]of this.Dt){const i=this.Pt.createBufferSource();i.buffer=t.buffer,i.loop=t.loop,i.connect(t.gainNode),i.start(0,e),t.sourceNode=i}}pause(){this.qt&&(this.Ot+=this.Pt.currentTime-this.jt,this.Lt(),this.qt=!1)}stop(){this.Lt(),this.qt=!1,this.Ot=0}Lt(){for(const[,t]of this.Dt)if(t.sourceNode){try{t.sourceNode.stop()}catch{}t.sourceNode=null}}setMix(t){const e=this.Pt.currentTime;for(const[i,s]of Object.entries(t)){const t=this.Dt.get(i);t&&(t.gainNode.gain.setValueAtTime(Math.max(0,Math.min(1,s)),e),this.Ft[i]=s)}}crossfadeTo(t,e=1e3){++this.zt;const i=this.Pt.currentTime,s=e/1e3;for(const[e,n]of Object.entries(t)){const t=this.Dt.get(e);if(t){const r=Math.max(1e-4,Math.min(1,n));t.gainNode.gain.setValueAtTime(t.gainNode.gain.value||1e-4,i),t.gainNode.gain.linearRampToValueAtTime(r,i+s),this.Ft[e]=n}}return new Promise(t=>{setTimeout(()=>{this.zt,t()},e)})}setEmotionModulation(t){this.It=t}applyEmotionState(t){if(!this.It||!t?.dominant)return;const e={},i=this.It[t.dominant.emotion];if(i)for(const[s,n]of Object.entries(i))e[s]=(e[s]||0)+n*t.dominant.intensity;for(const i of t.undercurrents||[]){const t=this.It[i.emotion];if(t)for(const[s,n]of Object.entries(t))e[s]=(e[s]||0)+n*i.intensity*.25}const s={...this.Ft};for(const[t,i]of Object.entries(e))t in s&&(s[t]=Math.max(0,Math.min(1,s[t]+i)));this.setMix(s)}syncToBPM(t,e){if(e&&(this.$t=e),!this.$t)return;const i=t/this.$t;for(const[,t]of this.Dt)t.sourceNode&&(t.sourceNode.playbackRate.value=i)}setMasterVolume(t){this.Rt.gain.setValueAtTime(Math.max(0,Math.min(1,t)),this.Pt.currentTime)}getLayerNames(){return[...this.Dt.keys()]}getCurrentMix(){return{...this.Ft}}isPlaying(){return this.qt}destroy(){this.stop();for(const[,t]of this.Dt)t.gainNode.disconnect();this.Dt.clear(),this.Rt.disconnect()}}class Cr{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 t=window.AudioContext||window.webkitAudioContext;return!!t&&(this.context=new t,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(t,e=null){this.masterVolume=Math.max(0,Math.min(1,t)),this.isEnabled&&this.nodes.master&&(this.nodes.master.gain.setValueAtTime(this.masterVolume,this.context.currentTime),e&&this.updateAmbientVolume(e))}getMasterVolume(){return this.masterVolume}isAvailable(){return this.isEnabled&&this.isInitialized}getAudioLayerManager(){return this.isAvailable()?(this.Gt||(this.Gt=new Ar(this.context)),this.Gt):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.Gt&&(this.Gt.destroy(),this.Gt=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(t){return this.emotionalTones.get(t)||null}setAmbientTone(t,e=500){if(!this.isAvailable())return;const i=this.getEmotionalTone(t);if(i)try{this.resumeContext();const{currentTime:t}=this.context,s=e/1e3;this.currentOscillator&&this.currentGain&&(this.currentGain.gain.exponentialRampToValueAtTime(.001,t+.5*s),this.currentOscillator.stop(t+.5*s));const n=this.context.createOscillator(),r=this.context.createGain();n.type=i.waveform,n.frequency.setValueAtTime(i.frequency,t);const a=i.volume*this.masterVolume;r.gain.setValueAtTime(.001,t),r.gain.exponentialRampToValueAtTime(a,t+s),n.connect(r),r.connect(this.nodes.master),n.start(t),this.currentOscillator=n,this.currentGain=r}catch{}}stopAmbientTone(t=500){if(this.isAvailable()&&this.currentOscillator)try{const{currentTime:e}=this.context,i=t/1e3;this.currentGain&&this.currentGain.gain.exponentialRampToValueAtTime(.001,e+i),this.currentOscillator.stop(e+i),this.currentOscillator=null,this.currentGain=null}catch{}}updateAmbientVolume(t){if(!this.isAvailable()||!this.currentGain||!t)return;const e=this.getEmotionalTone(t);if(e)try{const t=e.volume*this.masterVolume,{currentTime:i}=this.context;this.currentGain.gain.exponentialRampToValueAtTime(t,i+.1)}catch{}}playGestureSound(t,e="neutral"){if(!this.isAvailable())return;const i=this.getGestureSoundConfig(t);if(i)try{this.resumeContext();const{currentTime:t}=this.context,s=i.duration/1e3,n=this.getEmotionalModifiers(e),r=i.volume*this.masterVolume*n.intensity,a=this.context.createOscillator(),o=this.context.createGain();a.type=i.waveform,this.applyFrequencyEnvelope(a,i.frequencyEnvelope,t,s),this.applyVolumeEnvelope(o,i.volumeEnvelope,t,s,r),a.connect(o),o.connect(this.nodes.effects),a.start(t),a.stop(t+s)}catch{}else this.throttledWarn(`Unknown gesture "${t}", cannot play sound`,`gesture_${t}`)}getGestureSoundConfig(t){return Br.getSoundConfig(t)}applyFrequencyEnvelope(t,e,i,s){e.forEach(e=>{const n=i+e.time*s;t.frequency.linearRampToValueAtTime(e.frequency,n)})}applyVolumeEnvelope(t,e,i,s,n){e.forEach((e,r)=>{const a=i+e.time*s,o=e.volume*n;0===r?t.gain.setValueAtTime(o,a):t.gain.linearRampToValueAtTime(o,a)})}getEmotionalModifiers(t){return this.emotionalModifiers.get(t)||this.emotionalModifiers.get("neutral")}setQualityReduction(t){this.qualityReduction=t,t&&this.audioContext?this.maxOscillators=2:this.maxOscillators=4}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}throttledWarn(t,e){const i=Date.now();if(i-(this.warningTimestamps[e]||0)>this.warningThrottle){if(Object.keys(this.warningTimestamps).length>=this.maxWarningKeys){const t=this.warningAccessOrder.shift();delete this.warningTimestamps[t]}this.warningTimestamps[e]=i;const t=this.warningAccessOrder.indexOf(e);-1!==t&&this.warningAccessOrder.splice(t,1),this.warningAccessOrder.push(e)}}}class Tr{constructor(){this._t=120,this.Ht=new Float64Array(this._t),this.Ut=0,this.Wt=0,this.fps=0,this.smoothedFPS=0,this.smoothingFactor=.9,this.lastFrameTime=0,this.frameTime=0,this.maxFrameTimeSamples=10,this.Yt=new Float64Array(this.maxFrameTimeSamples),this.Xt=0,this.Vt=0,this.averageFrameTime=0}update(t){this.Ht[this.Ut]=t,this.Ut=(this.Ut+1)%this._t,this.Wt<this._t&&this.Wt++;const e=t-1e3;let i=0;for(let t=0;t<this.Wt;t++)this.Ht[t]>e&&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=t-this.lastFrameTime,this.Yt[this.Xt]=this.frameTime,this.Xt=(this.Xt+1)%this.maxFrameTimeSamples,this.Vt<this.maxFrameTimeSamples&&this.Vt++,this.Vt>0)){let t=0;for(let e=0;e<this.Vt;e++)t+=this.Yt[e];this.averageFrameTime=t/this.Vt}this.lastFrameTime=t}getFPS(){return Math.round(this.fps)}getSmoothedFPS(){return Math.round(this.smoothedFPS)}getFrameTime(){return this.frameTime}getAverageFrameTime(){return this.averageFrameTime}reset(){this.Ht.fill(0),this.Ut=0,this.Wt=0,this.fps=0,this.smoothedFPS=0,this.lastFrameTime=0,this.frameTime=0,this.Yt.fill(0),this.Xt=0,this.Vt=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 Pr{constructor(t,e={}){this.errorBoundary=t,this.config=e,this.config.targetFPS=e.targetFPS||60,this.loopManager=e.loopManager||er,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 Tr,this.subsystems={},this.eventCallback=null,this.parentMascot=null}setSubsystems(t){this.subsystems={stateMachine:t.stateMachine,particleSystem:t.particleSystem,renderer:t.renderer,soundSystem:t.soundSystem,canvasManager:t.canvasManager};const e=["stateMachine","particleSystem","renderer"];for(const t of e)if(!this.subsystems[t])throw new Error(`Required subsystem '${t}' not provided`);this.performanceMonitor&&this.performanceMonitor.setSubsystems(this.subsystems)}setEventCallback(t){if("function"!=typeof t)throw new Error("Event callback must be a function");this.eventCallback=t}setParentMascot(t){this.parentMascot=t}emit(t,e=null){this.eventCallback&&this.eventCallback(t,e)}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((t,e)=>this.animate(t,e),0,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 t=performance.now(),e=t-this.pauseTime;this.lastFrameTime=t,this.frameTimeAccumulator=0,this.fpsCounter&&this.fpsCounter.reset(),this.subsystems?.particleSystem&&this.subsystems.particleSystem.onVisibilityResume(e,this.pausedParticleCount),this.renderer&&(e>Xs&&this.renderer.resetCanvasContext(),this.renderer.gestureAnimator&&this.renderer.gestureAnimator.resumeAnimation?.(),e>Xs&&(this.renderer.forceCleanRender=!0)),this.subsystems?.stateMachine&&(this.subsystems.stateMachine.lastUpdateTime=t),this.parentMascot?.resume&&this.parentMascot.resume(),this.isPaused=!1}}animate(t,e){if(!this.isRunning||this.isPaused)return;const i=e||performance.now();this.deltaTime=t||i-this.lastFrameTime,this.deltaTime>20&&(this.deltaTime=20),this.deltaTime>Ys&&this.deltaTime<20&&(this.deltaTime=Ys),this.lastFrameTime=i,this.deltaTime*=this.speedMultiplier,this.update(this.deltaTime),this.render()}update(t){if(this.subsystems.stateMachine&&this.subsystems.stateMachine.update(t),this.parentMascot?.stateCoordinator?.Nt&&this.parentMascot.stateCoordinator.Nt.update(t),this.parentMascot&&"function"==typeof this.parentMascot.update&&this.parentMascot.update(t),"classic"!==this.parentMascot?.config?.renderingStyle&&this.subsystems.particleSystem&&this.subsystems.stateMachine&&this.subsystems.canvasManager){const e=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 t=this.subsystems.renderer.getCurrentGesture();t&&t.particleMotion&&(s=t.particleMotion,n=t.progress||0)}this.subsystems.particleSystem.spawn(e.particleBehavior,this.subsystems.stateMachine.getCurrentState().emotion,e.particleRate,i.x,i.y,t),this.subsystems.particleSystem.update(t,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 t=this.fpsCounter?this.fpsCounter.getMetrics():{};return{fps:t.fps||60,instantFps:t.smoothedFPS||60,frameTime:t.frameTime||16.67,averageFrameTime:t.averageFrameTime||16.67,isRunning:this.isRunning,deltaTime:this.deltaTime}}setTargetFPS(t){}get targetFPS(){return this.config.targetFPS||60}setSpeedMultiplier(t){this.speedMultiplier=Math.max(.1,Math.min(10,t))}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 Dr{constructor(t={}){this.config={spikeThreshold:t.spikeThreshold||1.5,minimumSpikeLevel:t.minimumSpikeLevel||.1,spikeMinInterval:t.spikeMinInterval||1e3,historySize:t.historySize||10,smoothingTimeConstant:t.smoothingTimeConstant||.8,fftSize:t.fftSize||256,levelUpdateThrottle:t.levelUpdateThrottle||100,...t},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(t){try{if(!t)throw new Error("AudioContext is required for audio level processing");if("function"!=typeof t.createAnalyser)throw new Error("Invalid AudioContext provided");return this.audioContext=t,this.analyser=t.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"===t.state&&t.resume().catch(t=>{this.emitError("Failed to resume AudioContext",t)}),!0}catch(t){return this.emitError("Failed to initialize AudioLevelProcessor",t),!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(t){this.emitError("Error during AudioLevelProcessor cleanup",t)}}updateAudioLevel(t=16){if(this.isActive&&this.analyser&&this.dataArray)try{this.analyser.getByteFrequencyData(this.dataArray);const t=this.calculateRMS();this.currentLevel=Math.min(1,2*t),this.updateLevelHistory(),this.detectVolumeSpikes(),this.emitLevelUpdate()}catch(t){this.emitError("Error updating audio level",t),this.currentLevel=0}}calculateRMS(){if(!this.dataArray||0===this.dataArray.length)return 0;let t=0;for(let e=0;e<this.dataArray.length;e++){const i=this.dataArray[e]/255;t+=i*i}return Math.sqrt(t/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 t=performance.now();if(t-this.lastVolumeSpike<this.config.spikeMinInterval)return;const e=this.levelHistory.slice(0,-1),i=e.reduce((t,e)=>t+e,0)/e.length;this.currentLevel>=i*this.config.spikeThreshold&&i>=this.config.minimumSpikeLevel&&this.currentLevel>=2*this.config.minimumSpikeLevel&&(this.lastVolumeSpike=t,this.emitVolumeSpike({level:this.currentLevel,previousAverage:i,spikeRatio:this.currentLevel/i,timestamp:t,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(t){if("function"!=typeof t)throw new Error("Level update callback must be a function");this.callbacks.levelUpdate=t}onVolumeSpike(t){if("function"!=typeof t)throw new Error("Volume spike callback must be a function");this.callbacks.volumeSpike=t}onError(t){if("function"!=typeof t)throw new Error("Error callback must be a function");this.callbacks.error=t}removeAllCallbacks(){this.callbacks={levelUpdate:null,volumeSpike:null,error:null}}updateConfig(t){this.config={...this.config,...t},this.analyser&&(t.fftSize&&(this.analyser.fftSize=this.config.fftSize,this.dataArray=new Uint8Array(this.analyser.frequencyBinCount)),void 0!==t.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((t,e)=>t+e,0)/this.levelHistory.length:0}}emitLevelUpdate(){const t=performance.now();if(!(t-this.lastLevelEmit<this.config.levelUpdateThrottle)&&(this.lastLevelEmit=t,this.callbacks.levelUpdate))try{this.callbacks.levelUpdate({level:this.currentLevel,rawData:this.getFrequencyData(),timestamp:t,history:this.getLevelHistory()})}catch{}}emitVolumeSpike(t){if(this.callbacks.volumeSpike)try{this.callbacks.volumeSpike(t)}catch{}}emitError(t,e){if(this.callbacks.error)try{this.callbacks.error({message:t,error:e,timestamp:performance.now()})}catch{}}static isSupported(){return!(!window.AudioContext&&!window.webkitAudioContext)}}class Rr{constructor(t={}){this.config={enableReducedMotion:!1!==t.enableReducedMotion,enableHighContrast:!1!==t.enableHighContrast,enableScreenReaderSupport:!1!==t.enableScreenReaderSupport,enableKeyboardNavigation:!1!==t.enableKeyboardNavigation,enableFocusIndicators:!1!==t.enableFocusIndicators,announceStateChanges:!1!==t.announceStateChanges,colorBlindMode:t.colorBlindMode||"none",...t},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 t=window.matchMedia("(prefers-reduced-motion: reduce)");this.reducedMotionPreferred=t.matches}if(this.config.enableHighContrast&&window.matchMedia){const t=window.matchMedia("(prefers-contrast: high)");if(this.highContrastEnabled=t.matches,!this.highContrastEnabled){const t=window.matchMedia("(-ms-high-contrast: active)");this.highContrastEnabled=t.matches}}this.detectScreenReader()}detectScreenReader(){const t=document.querySelector("[aria-live]"),e=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=!!(t||e||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.Qt=window.matchMedia("(prefers-reduced-motion: reduce)"),this.Jt=t=>{this.reducedMotionPreferred=t.matches,this.onPreferenceChange("reducedMotion",t.matches)},this.Qt.addEventListener?this.Qt.addEventListener("change",this.Jt):this.Qt.addListener&&this.Qt.addListener(this.Jt),this.Kt=window.matchMedia("(prefers-contrast: high)"),this.Zt=t=>{this.highContrastEnabled=t.matches,this.onPreferenceChange("highContrast",t.matches)},this.Kt.addEventListener?this.Kt.addEventListener("change",this.Zt):this.Kt.addListener&&this.Kt.addListener(this.Zt))}handleKeyDown(t){if(this.config.enableKeyboardNavigation){switch(t.key){case"Tab":t.preventDefault(),this.navigateFocus(t.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(t.key)}this.keyboardNavigationActive=!0}}handleKeyUp(t){}navigateFocus(t){const e=Array.from(this.focusableElements.values());if(0===e.length)return;this.currentFocusIndex+=t,this.currentFocusIndex<0?this.currentFocusIndex=e.length-1:this.currentFocusIndex>=e.length&&(this.currentFocusIndex=0);const i=e[this.currentFocusIndex];this.setFocus(i),i.label&&this.announce(`Focused on ${i.label}`)}handleArrowNavigation(t){const e={ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0},ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1}}[t];e&&this.onArrowNavigation&&this.onArrowNavigation(e)}registerFocusableElement(t,e){this.focusableElements.set(t,{id:t,label:e.label||t,bounds:e.bounds||null,action:e.action||null,type:e.type||"button"})}unregisterFocusableElement(t){this.focusableElements.delete(t)}setFocus(t){this.onFocusChange&&this.onFocusChange(t),this.focusHistory.push(t.id),this.focusHistory.length>10&&this.focusHistory.shift()}clearFocus(){this.currentFocusIndex=-1,this.onFocusChange&&this.onFocusChange(null),this.announce("Focus cleared")}activateCurrentFocus(){const t=Array.from(this.focusableElements.values());if(this.currentFocusIndex>=0&&this.currentFocusIndex<t.length){const e=t[this.currentFocusIndex];e.action&&(e.action(),this.announce(`Activated ${e.label}`))}}announce(t,e="polite"){this.config.enableScreenReaderSupport&&this.liveRegion&&(this.announcementQueue.push({message:t,priority:e}),this.processAnnouncementQueue())}processAnnouncementQueue(){if(0===this.announcementQueue.length)return;const{message:t,priority:e}=this.announcementQueue.shift();this.liveRegion.setAttribute("aria-live",e),this.liveRegion.textContent=t,setTimeout(()=>{this.liveRegion&&(this.liveRegion.textContent=""),this.announcementQueue.length>0&&this.processAnnouncementQueue()},100)}getAnimationSettings(t={}){return this.reducedMotionPreferred?{...t,duration:t.duration?.5*t.duration:0,iterations:1,easing:"linear",particlesEnabled:!1,complexAnimations:!1,autoPlay:!1}:t}getColorScheme(t={}){return this.colorSchemes.normal||(this.colorSchemes.normal={...t}),this.highContrastEnabled?this.colorSchemes.highContrast:"none"!==this.currentColorBlindMode&&this.colorSchemes[this.currentColorBlindMode]?this.colorSchemes[this.currentColorBlindMode]:t}getStatePattern(t){return"none"===this.currentColorBlindMode?this.patterns.solid:this.statePatterns[t]||this.patterns.solid}applyPatternOverlay(t,e,i){if(e===this.patterns.solid)return;t.save();const s=document.createElement("canvas"),n=s.getContext("2d");switch(e){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 r=t.createPattern(s,"repeat");t.fillStyle=r,t.globalAlpha=.3,t.fillRect(i.x,i.y,i.width,i.height),t.restore()}createDotPattern(t,e){e.width=10,e.height=10,t.fillStyle="white",t.beginPath(),t.arc(5,5,2,0,2*Math.PI),t.fill()}createStripePattern(t,e){e.width=10,e.height=10,t.strokeStyle="white",t.lineWidth=2,t.beginPath(),t.moveTo(0,10),t.lineTo(10,0),t.stroke()}createCrosshatchPattern(t,e){e.width=10,e.height=10,t.strokeStyle="white",t.lineWidth=1,t.beginPath(),t.moveTo(0,10),t.lineTo(10,0),t.stroke(),t.beginPath(),t.moveTo(0,0),t.lineTo(10,10),t.stroke()}setColorBlindMode(t){["none","protanopia","deuteranopia","tritanopia"].includes(t)&&(this.currentColorBlindMode=t,this.announce(`Color blind mode set to ${t}`),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(t,e){this.announce(`${t} is now ${e?"enabled":"disabled"}`),"reducedMotion"===t&&this.onReducedMotionChange&&this.onReducedMotionChange(e),"highContrast"===t&&this.onHighContrastChange&&this.onHighContrastChange(e)}createStateDescription(t){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"}[t.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.Qt&&this.Jt&&(this.Qt.removeEventListener?this.Qt.removeEventListener("change",this.Jt):this.Qt.removeListener&&this.Qt.removeListener(this.Jt),this.Qt=null,this.Jt=null),this.Kt&&this.Zt&&(this.Kt.removeEventListener?this.Kt.removeEventListener("change",this.Zt):this.Kt.removeListener&&this.Kt.removeListener(this.Zt),this.Kt=null,this.Zt=null),this.liveRegion&&this.liveRegion.parentNode&&this.liveRegion.parentNode.removeChild(this.liveRegion),this.focusableElements.clear(),this.announcementQueue=[],this.focusHistory=[]}}class Fr{constructor(t={}){this.config={enableTouchOptimization:!1!==t.enableTouchOptimization,enableViewportHandling:!1!==t.enableViewportHandling,enableBatteryOptimization:!1!==t.enableBatteryOptimization,enableOrientationSupport:!1!==t.enableOrientationSupport,enableResponsiveScaling:!1!==t.enableResponsiveScaling,touchSensitivity:t.touchSensitivity||1,doubleTapDelay:t.doubleTapDelay||300,swipeThreshold:t.swipeThreshold||50,pinchThreshold:t.pinchThreshold||.1,...t},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=t=>t.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 t=navigator.userAgent.toLowerCase(),e=["android","iphone","ipod","windows phone","blackberry"].some(e=>t.includes(e)),i=window.innerWidth<=768,s="ontouchstart"in window||navigator.maxTouchPoints>0;return e||i&&s}detectTablet(){const t=navigator.userAgent.toLowerCase(),e=/ipad/.test(t),i=/android/.test(t)&&!/mobile/.test(t),s=/windows/.test(t)&&/touch/.test(t),n=window.innerWidth>768&&window.innerWidth<=1024,r="ontouchstart"in window||navigator.maxTouchPoints>0;return e||i||s||n&&r}detectTouch(){return"ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0}supportsOffscreenCanvas(){return"undefined"!=typeof OffscreenCanvas}setupTouchHandlers(){const t=this.getCanvas();t&&(t.style.touchAction="none",t.style.userSelect="none",t.style.webkitUserSelect="none",t.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),t.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),t.addEventListener("touchend",this.handleTouchEnd,{passive:!1}),t.addEventListener("touchcancel",this.handleTouchCancel,{passive:!1}),t.addEventListener("contextmenu",this.handleContextMenu))}setupViewportHandlers(){window.addEventListener("resize",this.handleViewportChange),window.addEventListener("orientationchange",this.handleOrientationChange),document.addEventListener("visibilitychange",this.handleVisibilityChange),this.setupViewportMeta()}setupViewportMeta(){let t=document.querySelector('meta[name="viewport"]');t||(t=document.createElement("meta"),t.name="viewport",document.head.appendChild(t)),t.content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"}async setupBatteryMonitoring(){if(navigator.getBattery)try{const t=await navigator.getBattery();this.batteryRef=t,this.batteryLevel=t.level,this.isCharging=t.charging,this.boundBatteryLevelChange=()=>{this.batteryLevel=t.level,this.onBatteryChange()},this.boundBatteryChargingChange=()=>{this.isCharging=t.charging,this.onBatteryChange()},t.addEventListener("levelchange",this.boundBatteryLevelChange),t.addEventListener("chargingchange",this.boundBatteryChargingChange),this.onBatteryChange()}catch{}}setupOrientationHandlers(){window.DeviceOrientationEvent&&(this.te=t=>{this.handleDeviceOrientation(t)},window.addEventListener("deviceorientation",this.te))}handleTouchStart(t){t.cancelable&&t.preventDefault();const e=Date.now();this.gestureStartTime=e;for(const i of t.touches)this.touches.set(i.identifier,{id:i.identifier,startX:i.clientX,startY:i.clientY,currentX:i.clientX,currentY:i.clientY,startTime:e});1===t.touches.length?this.handleSingleTouchStart(t.touches[0]):2===t.touches.length&&this.handleMultiTouchStart(t.touches),this.emitTouchEvent("touchStart",{touches:Array.from(this.touches.values()),timestamp:e})}handleSingleTouchStart(t){const e=Date.now();e-this.lastTapTime<this.config.doubleTapDelay?this.tapCount++:this.tapCount=1,this.lastTapTime=e,this.touchStartPosition={x:t.clientX,y:t.clientY}}handleMultiTouchStart(t){if(2===t.length){const e=t[0],i=t[1];this.lastPinchDistance=this.getDistance(e.clientX,e.clientY,i.clientX,i.clientY),this.lastRotation=this.getAngle(e.clientX,e.clientY,i.clientX,i.clientY),this.isPinching=!0}}handleTouchMove(t){t.cancelable&&t.preventDefault();for(const e of t.touches){const t=this.touches.get(e.identifier);t&&(t.currentX=e.clientX,t.currentY=e.clientY)}1===t.touches.length?this.handleSingleTouchMove(t.touches[0]):2===t.touches.length&&this.handleMultiTouchMove(t.touches),this.emitTouchEvent("touchMove",{touches:Array.from(this.touches.values()),gesture:this.currentGesture})}handleSingleTouchMove(t){const e=this.touches.get(t.identifier);if(!e)return;const i=t.clientX-e.startX,s=t.clientY-e.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(t){if(2!==t.length)return;const e=t[0],i=t[1],s=this.getDistance(e.clientX,e.clientY,i.clientX,i.clientY),n=s-this.lastPinchDistance,r=s/this.lastPinchDistance;Math.abs(n)>this.config.pinchThreshold&&(this.currentGesture=r>1?"pinchOut":"pinchIn",this.emitTouchEvent("pinch",{scale:r,delta:n}));const a=this.getAngle(e.clientX,e.clientY,i.clientX,i.clientY),o=a-this.lastRotation;Math.abs(o)>5&&(this.currentGesture="rotate",this.emitTouchEvent("rotate",{angle:a,delta:o})),this.lastPinchDistance=s,this.lastRotation=a}handleTouchEnd(t){t.cancelable&&t.preventDefault();const e=Date.now();for(const i of t.changedTouches){const t=this.touches.get(i.identifier);if(t){const s=e-t.startTime,n=t.currentX-t.startX,r=t.currentY-t.startY,a=Math.sqrt(n*n+r*r);s<300&&a<10&&(2===this.tapCount?(this.emitTouchEvent("doubleTap",{x:t.currentX,y:t.currentY}),this.tapCount=0):this.emitTouchEvent("tap",{x:t.currentX,y:t.currentY})),s>500&&a<10&&this.emitTouchEvent("longPress",{x:t.currentX,y:t.currentY}),this.touches.delete(i.identifier)}}0===t.touches.length&&(this.currentGesture=null,this.isPinching=!1,this.isRotating=!1),this.emitTouchEvent("touchEnd",{gesture:this.currentGesture,duration:e-this.gestureStartTime})}handleTouchCancel(t){this.touches.clear(),this.currentGesture=null,this.isPinching=!1,this.isRotating=!1,this.emitTouchEvent("touchCancel",{})}handleOrientationChange(t){this.orientation=this.getOrientation(),this.emitTouchEvent("orientationChange",{orientation:this.orientation,angle:window.orientation||0}),this.applyOrientationOptimizations()}handleDeviceOrientation(t){const{alpha:e,beta:i,gamma:s}=t;this.emitTouchEvent("deviceOrientation",{alpha:e,beta:i,gamma:s})}handleViewportChange(t){const e=Date.now();e-this.lastViewportChange<100||(this.lastViewportChange=e,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(t){const e=!document.hidden;this.emitTouchEvent("visibilityChange",{visible:e}),!e&&this.config.enableBatteryOptimization?this.applyBackgroundOptimizations():this.restorePerformance()}getOrientation(){return window.innerWidth>window.innerHeight?"landscape":"portrait"}getDistance(t,e,i,s){const n=i-t,r=s-e;return Math.sqrt(n*n+r*r)}getAngle(t,e,i,s){return 180*Math.atan2(s-e,i-t)/Math.PI}applyMobileOptimizations(){if(!this.isMobile&&!this.isTablet)return;const t={...this.mobilePerformanceSettings,canvasScale:this.calculateOptimalCanvasScale(),useWebGL:!1,useOffscreenCanvas:this.useOffscreenCanvas};return this.emitTouchEvent("mobileOptimizations",t),t}applyOrientationOptimizations(){const t="landscape"===this.orientation,e={layoutMode:t?"horizontal":"vertical",particleDirection:t?"horizontal":"vertical",uiScale:t?.8:1};return this.emitTouchEvent("orientationOptimizations",e),e}applyResponsiveScaling(){const t=Math.min(this.viewportSize.width/375,2);return this.canvasScale=t,this.emitTouchEvent("responsiveScale",{scale:this.canvasScale,viewport:this.viewportSize}),this.canvasScale}applyBackgroundOptimizations(){const t={targetFPS:5,particlesEnabled:!1,animationsEnabled:!1,audioEnabled:!1};return this.emitTouchEvent("backgroundOptimizations",t),t}restorePerformance(){const t=this.applyMobileOptimizations();return this.emitTouchEvent("performanceRestore",t),t}onBatteryChange(){if(this.lowPowerMode=this.batteryLevel<.2&&!this.isCharging,this.lowPowerMode){const t={targetFPS:15,maxParticles:5,reducedEffects:!0,audioEnabled:!1};this.emitTouchEvent("lowPowerMode",{batteryLevel:this.batteryLevel,isCharging:this.isCharging,optimizations:t})}}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(t){this.canvas=t,this.config.enableTouchOptimization&&this.isTouchDevice&&this.setupTouchHandlers()}emitTouchEvent(t,e){this.onTouchEvent&&this.onTouchEvent(t,e)}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 t=this.getCanvas();t&&(t.removeEventListener("touchstart",this.handleTouchStart),t.removeEventListener("touchmove",this.handleTouchMove),t.removeEventListener("touchend",this.handleTouchEnd),t.removeEventListener("touchcancel",this.handleTouchCancel),t.removeEventListener("contextmenu",this.handleContextMenu)),window.removeEventListener("resize",this.handleViewportChange),window.removeEventListener("orientationchange",this.handleOrientationChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange),this.te&&(window.removeEventListener("deviceorientation",this.te),this.te=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 zr{constructor(t={}){this.config={enablePlugins:!1!==t.enablePlugins,validatePlugins:!1!==t.validatePlugins,sandboxPlugins:!1!==t.sandboxPlugins,maxPlugins:t.maxPlugins||50,pluginTimeout:t.pluginTimeout||5e3,allowOverrides:!1!==t.allowOverrides},this.mascot=t.mascot||null,this.plugins=new Map,this.pluginTypes=["emotion","gesture","particle","audio","renderer","animation"],this.pluginsByType=new Map(this.pluginTypes.map(t=>[t,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 t=new Map,e={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 t.set("emotion",{...e,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}}),t.set("gesture",{...e,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}}),t.set("particle",{...e,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}}),t.set("audio",{...e,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}}),t}createSandbox(){return{Math:Math,Date:Date,JSON:JSON,console:{log:(...t)=>null,warn:(...t)=>null,error:(...t)=>null},window:void 0,document:void 0,localStorage:void 0,sessionStorage:void 0,fetch:void 0,XMLHttpRequest:void 0,api:this.pluginAPI}}async registerPlugin(t){if(!this.config.enablePlugins)return!1;if(this.plugins.size>=this.config.maxPlugins)return!1;if(this.config.validatePlugins&&!this.validatePlugin(t).valid)return!1;if(this.checkConflicts(t).length>0&&!this.config.allowOverrides)return!1;if(!(await this.resolveDependencies(t)).resolved)return!1;try{this.loadingPlugins.add(t.name);const e=this.config.sandboxPlugins?this.sandbox:window;if(!await this.initializePlugin(t,e))throw new Error("Plugin initialization failed");return this.plugins.set(t.name,t),this.pluginsByType.get(t.type).add(t.name),this.pluginStates.set(t.name,"active"),this.activePlugins.add(t.name),t.dependencies&&(this.dependencies.set(t.name,t.dependencies),this.updateDependencyGraph(t.name,t.dependencies)),t.hooks&&Object.entries(t.hooks).forEach(([e,i])=>{this.registerHook(e,i,t.name)}),this.emitPluginEvent("pluginRegistered",{name:t.name,type:t.type,version:t.version}),!0}catch(t){return!1}finally{this.loadingPlugins.delete(t.name)}}validatePlugin(t){const e=[];if(t.name&&"string"==typeof t.name||e.push("Plugin must have a valid name"),t.type&&this.pluginTypes.includes(t.type)||e.push(`Plugin type must be one of: ${this.pluginTypes.join(", ")}`),t.version&&"string"==typeof t.version||e.push("Plugin must have a version"),"function"!=typeof t.init&&e.push("Plugin must have an init function"),"function"!=typeof t.destroy&&e.push("Plugin must have a destroy function"),t.type&&this.validationSchemas.has(t.type)){const i=this.validationSchemas.get(t.type),s=this.validateAgainstSchema(t,i);e.push(...s)}return{valid:0===e.length,errors:e}}validateAgainstSchema(t,e){const i=[];return Object.entries(e).forEach(([e,s])=>{if(s.required&&!(e in t)&&i.push(`Missing required property: ${e}`),e in t){const n=t[e];if(s.type&&typeof n!==s.type&&i.push(`Property ${e} must be of type ${s.type}`),s.enum&&!s.enum.includes(n)&&i.push(`Property ${e} must be one of: ${s.enum.join(", ")}`),s.properties&&"object"==typeof n){const t=this.validateAgainstSchema(n,s.properties);i.push(...t.map(t=>`${e}.${t}`))}}}),i}checkConflicts(t){const e=[];return t.conflicts&&t.conflicts.forEach(t=>{this.plugins.has(t)&&e.push(t)}),"emotion"!==t.type&&"gesture"!==t.type||this.plugins.forEach(i=>{if(i.type===t.type){const s=i[t.type]?.name,n=t[t.type]?.name;s===n&&e.push(`${t.type} name collision: ${n}`)}}),e}async resolveDependencies(t){if(!t.dependencies||0===t.dependencies.length)return{resolved:!0,missing:[]};const e=[];for(const i of t.dependencies)this.plugins.has(i)||await this.tryLoadDependency(i)||e.push(i);return{resolved:0===e.length,missing:e}}tryLoadDependency(t){return this.plugins.has(t)}updateDependencyGraph(t,e){this.dependencyGraph.set(t,new Set(e)),e.forEach(t=>{this.dependencyGraph.has(t)||this.dependencyGraph.set(t,new Set)})}async initializePlugin(t,e){try{const i=new Promise((t,e)=>{setTimeout(()=>e(new Error("Plugin initialization timeout")),this.config.pluginTimeout)}),s=t.init.bind(e);return!1!==await Promise.race([s(this.pluginAPI),i])}catch(t){return!1}}async unregisterPlugin(t){const e=this.plugins.get(t);if(!e)return!1;if(this.getDependentPlugins(t).length>0)return!1;try{return"function"==typeof e.destroy&&await e.destroy(),this.plugins.delete(t),this.pluginsByType.get(e.type).delete(t),this.pluginStates.delete(t),this.activePlugins.delete(t),this.dependencies.delete(t),this.dependencyGraph.delete(t),this.hooks.forEach(e=>{e.forEach(i=>{i.pluginName===t&&e.delete(i)})}),this.emitPluginEvent("pluginUnregistered",{name:t}),!0}catch(t){return!1}}getDependentPlugins(t){const e=[];return this.dependencies.forEach((i,s)=>{i.includes(t)&&e.push(s)}),e}registerHook(t,e,i){this.hooks.has(t)||this.hooks.set(t,new Set),this.hooks.get(t).add({handler:e,pluginName:i})}async executeHooks(t,e){const i=this.hooks.get(t);if(!i||0===i.size)return[];const s=[];for(const t of i)try{const i=await t.handler(e);s.push({pluginName:t.pluginName,result:i})}catch(t){}return s}getPlugin(t){return this.plugins.get(t)||null}hasPlugin(t){return this.plugins.has(t)}getPluginsByType(t){const e=this.pluginsByType.get(t);return e?Array.from(e).map(t=>this.plugins.get(t)):[]}enablePlugin(t){if(!this.plugins.has(t))return;this.pluginStates.set(t,"active"),this.activePlugins.add(t);const e=this.plugins.get(t);e.onEnable&&e.onEnable(),this.emitPluginEvent("pluginEnabled",{name:t})}disablePlugin(t){if(!this.plugins.has(t))return;this.getDependentPlugins(t),this.pluginStates.set(t,"disabled"),this.activePlugins.delete(t);const e=this.plugins.get(t);e.onDisable&&e.onDisable(),this.emitPluginEvent("pluginDisabled",{name:t})}emitPluginEvent(t,e){this.onPluginEvent&&this.onPluginEvent(t,e)}onPluginEvent(t,e){}logFromPlugin(t,...e){}errorFromPlugin(t,...e){}setPluginState(t,e,i){this.pluginStates.has(t)||this.pluginStates.set(t,{});const s=this.pluginStates.get(t);"object"==typeof s&&(s[e]=i)}getPluginState(t,e){const i=this.pluginStates.get(t);if("object"==typeof i)return i[e]}overrideConflict(t,e){return e}mergeConflict(t,e){return{...t,...e}}rejectConflict(t,e){return t}queueConflict(t,e){return[t,e]}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(([t,e])=>[t,e.size])),hooks:Object.fromEntries(Array.from(this.hooks.entries()).map(([t,e])=>[t,e.size]))}}update(t,e){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(t,e)}catch(t){this.errorFromPlugin(i,"Update error:",t)}}}render(t,e){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(t,e)}catch(t){this.errorFromPlugin(i,"Render error:",t)}}}async destroy(){const t=Array.from(this.plugins.keys());for(const e of t)await this.unregisterPlugin(e);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 qr{constructor(){if(qr.ee)return this.features=qr.ee,void(this.capabilities=qr.ie);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(),qr.ee=this.features,qr.ie=this.capabilities}detectWebAudio(){try{return!(!window.AudioContext&&!window.webkitAudioContext)}catch{return!1}}detectCanvas2D(){try{const t=document.createElement("canvas");return!(!t.getContext||!t.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 t=Object.values(this.features).filter(Boolean).length,e=Object.keys(this.features).length,i=t/e*100;let s="basic";return i>=90?s="full":i>=70?s="good":i>=50&&(s="limited"),{score:t,total:e,percentage:i,level:s,recommendations:this.getRecommendations(s)}}getRecommendations(t){const e=[];return this.features.webAudio||e.push("Audio features will be disabled"),this.features.requestAnimationFrame||e.push("Animation will use setTimeout fallback"),this.features.performance||e.push("Performance monitoring will be limited"),"basic"===t&&e.push("Consider using minimal build for better performance"),e}getFeatures(){return{...this.features}}getCapabilities(){return{...this.capabilities}}}class Or{constructor(){this.polyfills=new Map,this.applied=new Set}register(t,e){this.polyfills.set(t,e)}apply(t){if(this.applied.has(t))return!0;const e=this.polyfills.get(t);if(!e)return!1;try{return e(),this.applied.add(t),!0}catch{return!1}}applyAll(){const t=[];for(const e of this.polyfills.keys())this.apply(e)&&t.push(e);return t}isApplied(t){return this.applied.has(t)}}function jr(){window.requestAnimationFrame||(window.requestAnimationFrame=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(t){return window.setTimeout(()=>{t(Date.now())},1e3/60)},window.cancelAnimationFrame=window.webkitCancelAnimationFrame||window.mozCancelAnimationFrame||window.oCancelAnimationFrame||window.msCancelAnimationFrame||function(t){window.clearTimeout(t)})}function Ir(){if(window.performance&&window.performance.now)return;window.performance||(window.performance={});const t=Date.now();window.performance.now=function(){return Date.now()-t}}function $r(){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(t){for(let e=0;e<t.length;e++)t[e]=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 Lr{constructor(t){this.canvas=t,this.context=null,this.isContextLost=!1,this.recoveryCallbacks=[],this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this),this.setupContextLossHandling()}handleContextLost(t){t.preventDefault(),this.isContextLost=!0}handleContextRestored(){this.isContextLost=!1,this.context=this.canvas.getContext("2d"),this.recoveryCallbacks.forEach(t=>{try{t(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(t){this.recoveryCallbacks.push(t)}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 Gr{constructor(){if(Gr.se)return this.browser=Gr.se,void(this.optimizations=Gr.ne);this.browser=this.detectBrowser(),this.optimizations=new Map,this.setupOptimizations(),Gr.se=this.browser,Gr.ne=this.optimizations}detectBrowser(){const{userAgent:t}=navigator;let e="unknown",i="unknown";if(t.includes("Chrome")){e="chrome";const s=t.match(/Chrome\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Firefox")){e="firefox";const s=t.match(/Firefox\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Safari")&&!t.includes("Chrome")){e="safari";const s=t.match(/Version\/(\d+)/);i=s?s[1]:"unknown"}else if(t.includes("Edge")){e="edge";const s=t.match(/Edge\/(\d+)/);i=s?s[1]:"unknown"}return{name:e,version:i,userAgent:t}}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(t,e){if(this.getOptimizations().canvasOptimizations.includes("willReadFrequently"))try{t.getContext("2d",{willReadFrequently:!0})}catch{}}getRecommendedParticleLimit(){return this.getOptimizations().particleLimit}getAudioContextOptions(){return this.getOptimizations().audioContextOptions}}let _r=null,Hr=null;const Ur=(Hr||(Hr=function(){if(_r)return _r;const t=new qr,e=new Or,i=new Gr;e.register("requestAnimationFrame",jr),e.register("performanceNow",Ir),e.register("webAudio",$r);const s=[];return t.features.requestAnimationFrame||e.apply("requestAnimationFrame")&&s.push("requestAnimationFrame"),t.features.performance||e.apply("performanceNow")&&s.push("performanceNow"),t.features.webAudio||e.apply("webAudio")&&s.push("webAudio"),_r={featureDetection:t,polyfillManager:e,browserOptimizations:i,appliedPolyfills:s,capabilities:t.getCapabilities(),browser:i.getBrowser()},_r}()),Hr);function Wr(t){const e=[];for(let i=0;i<t;i++){const s=i/t*Math.PI*2;e.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)})}return e}function Yr(t,e=12){return Wr(t)}const Xr={circle:{points:Wr(64),shadow:{type:"none"}},sphere:{points:Wr(64),shadow:{type:"none"}},heart:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/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));t.push({x:.5+s/32,y:.5+n/32})}return t}(),shadow:{type:"none"}},star:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/64,s=Math.floor(10*i),n=s%2==0,r=Math.floor(s/2);let a;a=n?(72*r-90)*Math.PI/180:(72*r+36-90)*Math.PI/180;const o=n?.5:.2;t.push({x:.5+Math.cos(a)*o,y:.5+Math.sin(a)*o})}return t}(),shadow:{type:"none"}},sun:{points:Yr(64,12),shadow:{type:"sun",corona:!0,intensity:1.5,flares:!0,texture:!0,turbulence:.3}},moon:{points:Wr(64),shadow:{type:"crescent",coverage:.85,angle:-30,softness:.05,offset:.7}},lunar:{points:Wr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)",progression:"center"}},suspicion:{points:function(){const t=[];for(let e=0;e<64;e++){const i=e/64*Math.PI*2;let s,n;if(i<Math.PI)s=.45*Math.cos(i),n=.45*Math.sin(i);else{const t=2*Math.PI-i;s=.25*Math.cos(t)-.1,n=.35*Math.sin(t)}t.push({x:.5+s,y:.5+n})}return t}(),shadow:{type:"none"}},eclipse:{points:Wr(64),shadow:{type:"lunar",coverage:.7,color:"rgba(80, 20, 0, 0.8)"}},square:{points:function(){const t=[],e=Math.floor(16);for(let i=0;i<4;i++)for(let s=0;s<e;s++){const n=s/e;let r,a;switch(i){case 0:r=-.5+n,a=-.5;break;case 1:r=.5,a=-.5+n;break;case 2:r=.5-n,a=.5;break;case 3:r=-.5,a=.5-n}t.push({x:.5+.8*r,y:.5+.8*a})}return t}(),shadow:{type:"none"}},triangle:{points:function(){const t=[],e=[{x:0,y:-.5},{x:-.433,y:.25},{x:.433,y:.25}],i=[Math.sqrt(Math.pow(e[1].x-e[0].x,2)+Math.pow(e[1].y-e[0].y,2)),Math.sqrt(Math.pow(e[2].x-e[1].x,2)+Math.pow(e[2].y-e[1].y,2)),Math.sqrt(Math.pow(e[0].x-e[2].x,2)+Math.pow(e[0].y-e[2].y,2))],s=i[0]+i[1]+i[2],n=i.map(t=>Math.round(64*t/s)),r=n.reduce((t,e)=>t+e,0);r<64&&(n[0]+=64-r);for(let i=0;i<3;i++){const s=e[i],r=e[(i+1)%3],a=n[i];for(let e=0;e<a;e++){if(e===a-1&&i<2)continue;const n=e/a,o=s.x+(r.x-s.x)*n,h=s.y+(r.y-s.y)*n;t.push({x:.5+.9*o,y:.5+.9*h})}}for(;t.length<64;)t.push(t[t.length-1]);for(;t.length>64;)t.pop();return t}(),shadow:{type:"none"}},solar:{points:Yr(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"}}}},Vr=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 t=Object.keys(Xr);t.forEach(t=>{this.cacheShape(t)}),this.cacheCommonMorphs(t),this.isInitialized=!0,this.stats.loadTime=performance.now()-this.loadStartTime,this.stats.cacheSize=this.shapeCache.size}catch(t){this.isInitialized=!1}}cacheShape(t){try{const e=Xr[t];if(e){this.shapeCache.set(t,e);const i={pointCount:e.points?.length||64,hasShadow:"none"!==e.shadow?.type,shadowType:e.shadow?.type||"none",isRadial:this.isRadialShape(t),bounds:this.calculateBounds(e.points)};this.propertyCache.set(t,i)}}catch(t){}}cacheCommonMorphs(t){[["circle","heart"],["circle","star"],["circle","square"],["heart","star"],["star","circle"],["square","circle"],["triangle","circle"],["moon","sun"],["lunar","eclipse"]].forEach(([e,i])=>{if(t.includes(e)&&t.includes(i))try{const t=this.calculateMorphSteps(e,i),s=`${e}->${i}`;this.morphCache.set(s,t)}catch(t){}})}calculateMorphSteps(t,e){const i=this.shapeCache.get(t),s=this.shapeCache.get(e);if(!i||!s)return null;const n=[];for(let t=0;t<5;t++){const e=t/4,r=this.interpolateShapePoints(i.points,s.points,e);n.push({progress:e,points:r})}return{from:t,to:e,steps:n,isRadial:this.isRadialShape(t)||this.isRadialShape(e)}}interpolateShapePoints(t,e,i){if(!t||!e)return t||e||[];const s=Math.max(t.length,e.length),n=[];for(let r=0;r<s;r++){const s=t[r]||t[0]||{x:.5,y:.5},a=e[r]||e[0]||{x:.5,y:.5};n.push({x:s.x+(a.x-s.x)*i,y:s.y+(a.y-s.y)*i})}return n}isRadialShape(t){return["circle","star","square","triangle","sun","moon"].includes(t)}calculateBounds(t){if(!t||0===t.length)return{minX:0,minY:0,maxX:1,maxY:1,width:1,height:1};let e=1/0,i=1/0,s=-1/0,n=-1/0;return t.forEach(t=>{e=Math.min(e,t.x),i=Math.min(i,t.y),s=Math.max(s,t.x),n=Math.max(n,t.y)}),{minX:e,minY:i,maxX:s,maxY:n,width:s-e,height:n-i}}getShape(t){if(!this.isInitialized)return Xr[t]||null;const e=this.shapeCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,Xr[t]||null)}getProperties(t){if(!this.isInitialized){const e=Xr[t];return e?{pointCount:e.points?.length||64,hasShadow:"none"!==e.shadow?.type,shadowType:e.shadow?.type||"none",isRadial:this.isRadialShape(t),bounds:this.calculateBounds(e.points)}:{}}const e=this.propertyCache.get(t);return e?(this.stats.hits++,e):(this.stats.misses++,{})}getMorph(t,e){if(!this.isInitialized)return this.calculateMorphSteps(t,e);const i=`${t}->${e}`,s=this.morphCache.get(i);return s?(this.stats.hits++,s):(this.stats.misses++,this.calculateMorphSteps(t,e))}hasShape(t){return this.shapeCache.has(t)}getStats(){const t=this.stats.hits+this.stats.misses;return{...this.stats,hitRate:t>0?`${(this.stats.hits/t*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}},Nr=new class{constructor(){this.pools=new Map,this.inUse=new Set}acquire(t,e="array"){const i=`${e}_${t}`;this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);if(s.length>0){const t=s.pop();return this.inUse.add(t),t}let n;switch(e){case"float32":n=new Float32Array(t);break;case"uint8":n=new Uint8Array(t);break;default:n=new Array(t).fill(0)}return this.inUse.add(n),n}release(t){if(!this.inUse.has(t))return;this.inUse.delete(t);let e="array";t instanceof Float32Array?e="float32":t instanceof Uint8Array&&(e="uint8");const i=`${e}_${t.length}`;t.fill(0),this.pools.has(i)||this.pools.set(i,[]);const s=this.pools.get(i);s.length<10&&s.push(t)}clear(){this.pools.clear(),this.inUse.clear()}};class Qr{constructor(t){this.morpher=t,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(t){if(!t||0===t.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 t=0,e=0;for(let i=0;i<=2&&i<this.morpher.frequencyData.length;i++)t+=this.morpher.frequencyData[i],e++;e>0&&(t/=e),this.morpher.bassPeakHistory||(this.morpher.bassPeakHistory=[],this.morpher.bassThumpTimer=0),this.morpher.bassPeakHistory.push(t),this.morpher.bassPeakHistory.length>20&&this.morpher.bassPeakHistory.shift();const i=this.morpher.bassPeakHistory.reduce((t,e)=>t+e,0)/this.morpher.bassPeakHistory.length,s=this.morpher.audioAnalyzer&&this.morpher.audioAnalyzer.microphoneStream;if(t>1.08*i&&t>(s?.15:.25)){const e=s?8:6;this.bassEnergy=Math.min(1,(t-i)*e),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 r=0,a=0;if(this.morpher.spectralHistory.length>0){const t=this.morpher.spectralHistory[this.morpher.spectralHistory.length-1];for(let e=0;e<=2&&e<n.length;e++){const i=n[e]-t[e];i>0&&(a+=i)}for(let e=4;e<=15&&e<n.length;e++){const i=n[e]-t[e];i>0&&(r+=i*(e>=9&&e<=13?2:1))}a>.15&&(r*=.3)}if(this.morpher.spectralHistory.push(n),this.morpher.spectralHistory.length>30&&this.morpher.spectralHistory.shift(),this.morpher.spectralFluxHistory.push(r),this.morpher.spectralFluxHistory.length>30&&this.morpher.spectralFluxHistory.shift(),this.morpher.bassFluxHistory||(this.morpher.bassFluxHistory=[],this.morpher.bassOnsetThreshold=.05),this.morpher.bassFluxHistory.push(a),this.morpher.bassFluxHistory.length>30&&this.morpher.bassFluxHistory.shift(),this.morpher.spectralFluxHistory.length>=10){const t=[...this.morpher.spectralFluxHistory].sort((t,e)=>t-e),e=t[Math.floor(t.length/2)],i=t.reduce((t,e)=>t+e,0)/t.length;this.morpher.onsetThreshold=e+.5*(i-e)}if(this.morpher.bassFluxHistory.length>=10){const t=[...this.morpher.bassFluxHistory].sort((t,e)=>t-e),e=t[Math.floor(t.length/2)],i=t.reduce((t,e)=>t+e,0)/t.length;this.morpher.bassOnsetThreshold=e+.5*(i-e)}const o=r>1.2*this.morpher.onsetThreshold&&r>.02,h=a>1.5*this.morpher.bassOnsetThreshold&&a>.08;if(o&&(this.transientHoldTime=8,this.morpher.vocalGlowBoost=.3),h){const t=performance.now(),e={time:t,strength:a/(this.morpher.bassOnsetThreshold||1),bassWeight:a};this.morpher.onsetStrengths.push(e),this.morpher.onsetStrengths.length>40&&this.morpher.onsetStrengths.shift(),this.morpher.musicDetector.addOnset(t,a)}const l=performance.now();this.morpher.musicDetector.processFrequencyFrame&&this.morpher.musicDetector.processFrequencyFrame(this.morpher.frequencyData,l),this.morpher.musicDetector.update(l),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=r,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 e=this.morpher.frequencyData&&this.morpher.frequencyData.some(t=>t>.01);if(this.morpher.audioAnalyzer&&e||(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)),!e&&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 t;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 e=2+Math.floor(2*Math.random());for(let i=0;i<e;i++)this.glitchPoints.push({index:Math.floor(Math.random()*t.length),intensity:.02+.03*Math.random(),decay:.94+.02*Math.random()})}this.glitchPoints=this.glitchPoints.filter(t=>(t.intensity*=t.decay,t.intensity>.01));for(let e=0;e<t.length;e++){const s=t[e];if(!s||void 0===s.x||void 0===s.y){const s=e/t.length*Math.PI*2;i.push({x:.5+.5*Math.cos(s),y:.5+.5*Math.sin(s)});continue}const n=s.x-.5,r=s.y-.5,a=Math.sqrt(n*n+r*r),o=Math.atan2(r,n),h=.12*Math.abs(this.audioDeformation);let l=0,c=0;if(this.morpher.bassEffectActive){const t=2,e=.25*this.bassEnergy;l=Math.sin(o*t+this.morpher.undulationPhase)*e,c=Math.sin(.5*this.morpher.undulationPhase)*this.bassEnergy*.08}let u=0;const d=this.glitchPoints.find(t=>t.index===e);if(d){const t=.015*Date.now(),i=Math.sin(t+.5*e)*Math.cos(.7*t);u=d.intensity*i*.5}const p=1+h+l+c+u,m=a*Math.max(.8,p);i.push({x:.5+Math.cos(o)*m,y:.5+Math.sin(o)*m})}return i}setAudioDeformation(t){this.audioDeformation=Math.max(0,Math.min(1,t)),this.vocalEffectActive=t>.01}setVocalEnergy(t){this.vocalEnergy=Math.max(0,Math.min(1,t)),this.vocalEffectActive=t>.01}updateFrequencyBands(t){t&&(this.bassEnergy=t.bass||0,this.vocalPresence=t.vocal||0,this.highFreqEnergy=t.high||0)}processTransient(t,e){t>e?(this.transientActive=!0,this.transientStrength=t,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 Jr{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.re=[],this.ae=0,this.oe=0,this.he=!1,this.le=0,this.grooveConfidence=.15,this.ce=.15,this.ue=0,this.de=2e3,this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0,this.m=[],this.Me=20}processPeak(t,e=performance.now()){if(this.isActive=!0,this.peakCount++,t<.1)this.fe++;else{if(this.lastPeakTime>0){const t=e-this.lastPeakTime;t>=250&&t<=2e3?(this.intervals.push(t),this.pe.push(Math.round(t)),this.intervals.length>this.maxIntervals&&this.intervals.shift(),this.voteForInterval(t)):this.ye++}this.lastPeakTime=e,this.updateBPM(),this.be(e)}}voteForInterval(t){const e=6e4/t;this.me.push(Math.round(e));let i=e;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.ge.push(Math.round(i));const r=Math.round(i);for(let t=-2;t<=2;t++){const e=r+t;if(e>=this.minBPM&&e<=this.maxBPM){const i=Math.exp(-t*t/2),s=this.bpmVotes.get(e)||0;this.bpmVotes.set(e,s+i)}}for(const[t,e]of this.bpmVotes){const i=.95*e;i<.3?this.bpmVotes.delete(t):this.bpmVotes.set(t,i)}}updateBPM(){if(0===this.bpmVotes.size||this.intervals.length<3)return;const t=performance.now();let e=0,i=0,s=0;for(const[t,n]of this.bpmVotes)s+=n,n>i&&(i=n,e=t);if(0===e)return;let n=0;for(let t=-2;t<=2;t++){const i=e+t;n+=this.bpmVotes.get(i)||0}const r=n,a=Math.round(e/2);let o=0;if(a>=this.minBPM)for(let t=-2;t<=2;t++)o+=this.bpmVotes.get(a+t)||0;const h=2*e;let l=0;if(h<=this.maxBPM)for(let t=-2;t<=2;t++)l+=this.bpmVotes.get(h+t)||0;let c=0,u=0;const d=r>0?o/r:0;if(this.intervals.length>=6){const t=this.intervals.slice(-8),e=t.reduce((t,e)=>t+e,0)/t.length;let i=0;for(let s=0;s<t.length-1;s++)t[s]>e!=t[s+1]>e&&i++;c=i/(t.length-1);const s=[];for(let e=0;e<t.length-1;e+=2)s.push(t[e]+t[e+1]);if(s.length>=2){const t=s.reduce((t,e)=>t+e,0)/s.length;u=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}this.confidence=s>0?r/s:0;let p=0;if(this.intervals.length>=4){const t=6e4/e,i=t/2,s=this.intervals.slice(-8);let n=0;for(const e of s){const s=Math.abs(e-t)/t<.15,r=Math.abs(e-i)/i<.15,a=Math.abs(e-2*t)/(2*t)<.15;(s||r||a)&&n++}p=n/s.length}if(0===this.currentBPM)this.currentBPM=e;else{const t=this.intervals.length<6?.5:.3;this.currentBPM=this.currentBPM*(1-t)+e*t}if(0===this.lockStage){this.we={intervalCount:this.intervals.length,bestVotes:i.toFixed(1),clusterVotes:r.toFixed(1),confidence:`${(100*this.confidence).toFixed(0)}%`,consistency:`${(100*p).toFixed(0)}%`,bestBPM:e,adjustedBPM:e,isSubdivision:!1,stage:0,failReasons:[]};const s=e>120?12:8,n=.2,a=.45;this.intervals.length<s&&this.we.failReasons.push(`intervals<${s}`),r<=5&&this.we.failReasons.push("votes<=5"),this.confidence<=n&&this.we.failReasons.push(`conf<=${(100*n).toFixed(0)}%`),p<=a&&this.we.failReasons.push(`consistency<=${(100*a).toFixed(0)}%`),this.intervals.length>=s&&r>5&&this.confidence>n&&p>a&&(this.lockedBPM=Math.round(this.currentBPM),this.lockStage=1,this.stage1LockTime=t)}if(1===this.lockStage||2===this.lockStage){this.re.push({alternatingScore:c,pairVariance:u,halfVoteRatio:d,time:t}),this.re.length>15&&this.re.shift();const i=this.re.filter(t=>t.alternatingScore>.7&&t.pairVariance<.1).length,s=this.re.reduce((t,e)=>t+e.alternatingScore,0)/this.re.length,n=this.re.reduce((t,e)=>t+e.pairVariance,0)/this.re.length,o=this.re.reduce((t,e)=>t+e.halfVoteRatio,0)/this.re.length,p=this.intervals.length>0?this.intervals.reduce((t,e)=>t+e,0)/this.intervals.length:0,m=r>0?l/r:0;let g=0,f=0;if(this.intervals.length>=8){const t=this.intervals.slice(-12),e=[...t].sort((t,e)=>t-e),i=e[Math.floor(e.length/2)],s=t.filter(t=>Math.abs(t-i)/i<.5);if(f=s.length,s.length>=6){const t=s.reduce((t,e)=>t+e,0)/s.length;g=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}if(this.we={intervalCount:this.intervals.length,bestBPM:e,adjustedBPM:this.lockedBPM,halfBPM:a,stage:this.lockStage,subdivisionChecks:this.re.length,positiveChecks:i,avgAltScore:`${(100*s).toFixed(0)}%`,avgPairVar:`${(100*n).toFixed(1)}%`,avgHalfRatio:`${(100*o).toFixed(0)}%`,intervalVariance:`${(100*g).toFixed(1)}%`,filteredCount:f,correctionApplied:this.stage2CorrectionApplied,failReasons:[]},!this.stage2CorrectionApplied&&this.re.length>=10&&a>=this.minBPM){const t=i>=7&&s>.7&&n<.1&&this.lockedBPM>100,e=o>.4&&this.lockedBPM>150&&a>=65&&a<=85;let r=0,h=0;if(this.intervals.length>=8){const t=this.intervals.slice(-12),e=[...t].sort((t,e)=>t-e),i=e[Math.floor(e.length/2)],s=t.filter(t=>Math.abs(t-i)/i<.5);if(h=s.length,s.length>=6){const t=s.reduce((t,e)=>t+e,0)/s.length;r=s.reduce((e,i)=>e+Math.abs(i-t),0)/s.length/t}}const l=this.lockedBPM>140&&a>=65&&a<=85&&h>=8&&r<.05;(t||e||l)&&(this.lockedBPM=Math.round(this.lockedBPM/2),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="halved")}!this.stage2CorrectionApplied&&this.re.length>=10&&h<=this.maxBPM&&p>900&&m>.5&&this.lockedBPM<75&&(this.lockedBPM=Math.round(2*this.lockedBPM),this.lockStage=2,this.stage2CorrectionApplied=!0,this.correctionType="doubled");const y=t-this.stage1LockTime;1===this.lockStage&&this.re.length>=6&&(this.lockStage=2);const M=this.re.length>=12&&i<3,b=y>1e4;2===this.lockStage&&(this.stage2CorrectionApplied||M||b)&&(this.lockStage=3,this.ae=t)}if(3===this.lockStage){const e=t-this.ae,i=this.intervals.slice(-8);if(i.length>=4){const t=6e4/(i.reduce((t,e)=>t+e,0)/i.length);if(Math.abs(t-this.lockedBPM)/this.lockedBPM<.05){0===this.le&&(this.le=this.lockedBPM),this.le=.9*this.le+.1*t;const e=Math.round(this.le);e!==this.lockedBPM&&(this.lockedBPM=e),this.oe+=100}else this.oe=0}const s=(e>5e3||this.oe>3e3)&&!this.he;s&&3===this.lockStage&&(this.ve(),this.he=!0),this.we={stage:3,lockedBPM:this.lockedBPM,correctionType:this.correctionType,timeSinceStage3:`${(e/1e3).toFixed(1)}s`,stableTime:`${(this.oe/1e3).toFixed(1)}s`,finalized:s,failReasons:[]}}this.Se()}Se(){this.he?this.ce=1:this.ce=[.15,.4,.65,.85][this.lockStage]||.15;const t=this.grooveConfidence+.08*(this.ce-this.grooveConfidence);t>this.grooveConfidence&&(this.grooveConfidence=t)}ve(){this.intervals.length>8&&(this.intervals=this.intervals.slice(-8)),this.bpmVotes.clear(),this.ke=[],this.re=[],this.pe=[],this.me=[],this.ge=[]}processFrame(t,e=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.re=[],this.ae=0,this.oe=0,this.he=!1,this.le=0,this.grooveConfidence=.15,this.ce=.15,this.ue=0,this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0,this.m=[],this.we=null,this.ke=[]}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.he,grooveConfidence:this.grooveConfidence,agentCount:this.bpmVotes.size,peakCount:this.peakCount,histogramSize:this.bpmVotes.size,topAgents:this.getTopCandidates(5),intervalCount:this.intervals.length}}getTopCandidates(t=5){return[...this.bpmVotes.entries()].sort((t,e)=>e[1]-t[1]).slice(0,t).map(([t,e])=>({bpm:t,score:e.toFixed(1),interval:Math.round(6e4/t)}))}getTopIntervals(t=5){return this.getTopCandidates(t).map(t=>({interval:t.interval,bpm:t.bpm,weight:t.score}))}be(t){if(t-this.ue<this.de)return;if(this.ue=t,0===this.pe.length&&0===this.fe)return;const e=[],i=["Detecting","Initial Lock","Refinement","Final Lock"][this.lockStage]||"Unknown";e.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"),e.push(`Status: Stage ${this.lockStage} (${i}) | Current: ${Math.round(this.currentBPM)} BPM | Locked: ${this.lockedBPM||"-"}`),e.push(`Peaks: ${this.peakCount} total | ${this.fe} skipped (weak) | ${this.ye} intervals out-of-range`),this.pe.length>0&&e.push(`Recent intervals (ms): [${this.pe.join(", ")}]`),this.me.length>0&&e.push(`Raw BPMs (before normalize): [${this.me.join(", ")}]`),this.ge.length>0&&e.push(`Normalized BPMs (60-180): [${this.ge.join(", ")}]`);const s=this.getTopCandidates(5);if(s.length>0){const t=s.map(t=>`${t.bpm}(${t.score})`).join(", ");e.push(`Top candidates: ${t}`)}if(this.we){const t=this.we;0===t.stage?t.failReasons&&t.failReasons.length>0?e.push(`Stage 0: NOT locking - ${t.failReasons.join(", ")}`):e.push(`Stage 0: Ready to lock at ${t.bestBPM} BPM`):1===t.stage||2===t.stage?(e.push(`Stage ${t.stage}: Locked=${t.adjustedBPM} BPM | checks=${t.subdivisionChecks} positive=${t.positiveChecks}`),e.push(` altScore=${t.avgAltScore} pairVar=${t.avgPairVar} halfRatio=${t.avgHalfRatio}`),t.correctionApplied&&e.push(` Correction applied: ${this.correctionType}`)):3===t.stage&&(e.push(`Stage 3: Final=${t.lockedBPM} BPM | correction=${t.correctionType} | time=${t.timeSinceStage3} stable=${t.stableTime}`),t.finalized&&e.push(" FINALIZED - memory cleaned"))}if(this.intervals.length>=6){const t=this.intervals.slice(-8),i=t.reduce((t,e)=>t+e,0)/t.length,s=(t.reduce((t,e)=>t+Math.abs(e-i),0)/t.length/i*100).toFixed(1);let n=0;for(let e=0;e<t.length-1;e++)t[e]>i!=t[e+1]>i&&n++;const r=(n/(t.length-1)*100).toFixed(0);e.push(`Interval pattern: variance=${s}% alternating=${r}% (>70% triggers subdivision)`)}const n=[...this.intervals].map(t=>Math.round(t));if(n.length>0){const t=Math.min(...n),i=Math.max(...n),s=Math.round(n.reduce((t,e)=>t+e,0)/n.length);e.push(`Interval buffer (${n.length}/${this.maxIntervals}): min=${t}ms max=${i}ms avg=${s}ms (=${Math.round(6e4/s)} BPM)`)}e.push("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ");const r=(new Date).toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});for(this.m.push({time:r,lines:e});this.m.length>this.Me;)this.m.shift();this.pe=[],this.me=[],this.ge=[],this.fe=0,this.ye=0}getDebugLog(){if(0===this.m.length)return"No BPM debug logs yet. Play audio to generate logs.";let t="=== BPM Debug Log ===\n\n";for(const e of this.m){t+=`[${e.time}]\n`;for(const i of e.lines)t+=`${i}\n`;t+="\n"}return t}clearDebugLog(){this.m=[]}}class Kr{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 Jr,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 t=this.agentDetector.getStatus();if(t.locked&&t.confidence>.6)return this.detectedBPM=t.bpm,this.bpmConfidence=t.confidence,this.tempoLocked=!0,this.fundamentalBPM=t.bpm,this.bpmHistory.push(this.detectedBPM),this.bpmHistory.length>10&&this.bpmHistory.shift(),this.detectedBPM;if(t.bpm>0&&t.confidence>.4)return this.detectedBPM=t.bpm,this.bpmConfidence=t.confidence,t.confidence>.6&&(this.tempoLocked=!0),this.detectedBPM}if(this.onsetIntervals.length<4)return this.detectedBPM;const t=this.onsetIntervals.slice(-15),e=this.findTempoCandidates(t);if(0===e.length)return this.detectedBPM;const i=e[0],s=Math.round(6e4/i.interval);if(!this.tempoLocked&&this.bpmHistory.length>3){const t=this.bpmHistory.slice(-3),e=t.reduce((t,e)=>t+e,0)/t.length;t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length<5&&(this.fundamentalBPM=Math.round(e),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 t=this.tempoLocked?1:2,e=n-this.detectedBPM;Math.abs(e)<=t?this.detectedBPM=n:this.detectedBPM+=Math.sign(e)*t}return window.rhythmIntegration&&window.rhythmIntegration.updateBPM&&(window.rhythmManuallyStoppedForCurrentAudio||window.rhythmIntegration.updateBPM(this.detectedBPM)),this.detectedBPM}findTempoCandidates(t){const e=[];for(const i of[1,2,4]){const s=t.map(t=>t*i),n=this.clusterIntervals(s);for(const s of n){const n=s.intervals.reduce((t,e)=>t+e,0)/s.intervals.length/i,r=s.intervals.length/t.length*s.consistency,a=6e4/n,o=a>=120&&a<=140?.2:0;a>=60&&a<=220&&e.push({interval:n,strength:r+o,multiplier:i})}}return e.sort((t,e)=>e.strength-t.strength)}clusterIntervals(t){const e=[...t].sort((t,e)=>t-e),i=[];let s=[e[0]];for(let t=1;t<e.length;t++){const n=.03*s[0];if(e[t]-s[0]<=n)s.push(e[t]);else{if(s.length>=2){const t=s.reduce((t,e)=>t+e,0)/s.length,e=1/(1+s.reduce((e,i)=>e+Math.pow(i-t,2),0)/s.length/(t*t));i.push({intervals:s,consistency:e})}s=[e[t]]}}if(s.length>=3){const t=s.reduce((t,e)=>t+e,0)/s.length,e=1/(1+s.reduce((e,i)=>e+Math.pow(i-t,2),0)/s.length/(t*t));i.push({intervals:s,consistency:e})}return i}checkHarmonicRelation(t,e){const i=Math.max(t,e)/Math.min(t,e);return[2,1.5,1.333,1.25].some(t=>Math.abs(i-t)<.03)}detectTimeSignature(){const t=this.forceFastDetection?6:12;if(0===this.detectedBPM||this.onsetStrengths.length<t)return this.timeSignature;if(this.timeSignatureLocked&&!this.forceFastDetection)return this.detectedTimeSignature||this.timeSignature;const e=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 t of s){const s=(t.time-n)/e%4,r=Math.round(s)%4;i[r].strength+=t.strength,i[r].bassWeight+=t.bassWeight||0,i[r].count++}for(const t of i)t.count>0&&(t.strength/=t.count,t.bassWeight/=t.count);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,e)>.8&&(r="3/4"),this.timeSignatureHistory.push(r),this.timeSignatureHistory.length>3&&this.timeSignatureHistory.shift();const a=this.forceFastDetection?2:3;if(this.timeSignatureHistory.length>=a){const t={};for(const e of this.timeSignatureHistory)t[e]=(t[e]||0)+1;let e="4/4",i=0;for(const[s,n]of Object.entries(t))n>i&&(i=n,e=s);if(i>=2){this.detectedTimeSignature=e,this.timeSignatureLocked=!0,this.timeSignatureConfidence=i/3,window.rhythmIntegration&&window.rhythmIntegration.setTimeSignature&&window.rhythmIntegration.setTimeSignature(this.detectedTimeSignature);const t=document.getElementById("time-sig-display");t&&(t.textContent=this.detectedTimeSignature)}}return this.detectedTimeSignature||this.timeSignature}testWaltzPattern(t,e){let i=0,s=0;for(let e=0;e<t.length-2;e+=3)if(e+2<t.length){s++;const n=t[e].strength+(t[e].bassWeight||0),r=t[e+1].strength+(t[e+1].bassWeight||0),a=t[e+2].strength+(t[e+2].bassWeight||0);n>1.5*r&&n>1.5*a&&i++}return s>0?i/s:0}processFrequencyFrame(t,e=performance.now()){this.useAgentDetection&&this.agentDetector.processFrame&&this.agentDetector.processFrame(t,e)}addOnset(t,e,i=0){if(this.useAgentDetection&&this.agentDetector.processPeak(e,t),this.lastOnsetTime>0){const e=t-this.lastOnsetTime;e>273&&e<1e3&&(this.onsetIntervals.push(e),this.onsetIntervals.length>20&&this.onsetIntervals.shift())}this.onsetStrengths.push({time:t,strength:e,bassWeight:i}),this.onsetStrengths.length>40&&this.onsetStrengths.shift(),this.lastOnsetTime=t}update(t){t-this.lastBPMCalculation>this.bpmCalculationInterval&&(this.calculateBPM(),this.detectTimeSignature(),this.lastBPMCalculation=t)}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 Zr{constructor(t){this.morpher=t,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(t,e={}){this.isTransitioning&&this.morphQueue.length<this.maxQueueSize?this.morphQueue.push({shape:t,options:e}):(this.previousShape=this.currentShape,this.targetShape=t,this.isTransitioning=!0,this.transitionStartTime=performance.now(),this.transitionDuration=e.duration||800,this.easingFunction=e.easing||"easeInOutQuad",this.transitionProgress=0,this.shadowConfig=this.getTransitionConfig(this.currentShape,t))}update(t){if(!this.isTransitioning)return;const e=performance.now()-this.transitionStartTime,i=Math.min(1,e/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 t=this.morphQueue.shift();this.startTransition(t.shape,t.options)}}getTransitionConfig(t,e){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}}[`${t}-${e}`]||null}calculateShadowProgress(t){if(!this.shadowConfig)return 0;switch(this.shadowConfig.type){case"bloom":return t<.5?2*t:2-2*t;case"burst":return Math.pow(1-t,2);case"contract":case"collapse":return Math.sin(t*Math.PI);default:return 0}}applyEasing(t){switch(this.easingFunction){case"linear":default:return t;case"easeInQuad":return t*t;case"easeOutQuad":return t*(2-t);case"easeInOutQuad":return t<.5?2*t*t:(4-2*t)*t-1;case"easeInCubic":return t*t*t;case"easeOutCubic":return--t*t*t+1;case"easeInOutCubic":return t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-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 ta{constructor(t){this.xe=t}getCurrentShadow(){const t=this.xe(),e=t.currentShape||"circle",i=Vr&&Vr.isInitialized?Vr.getShape(e):Xr[e],s=t.targetShape?Vr&&Vr.isInitialized?Vr.getShape(t.targetShape):Xr[t.targetShape]:null,n=i?.shadow||{type:"none"},r=s?.shadow||null;if(!t.isTransitioning||!r)return n;const a=t.morphProgress;if(t.transitionConfig&&"from_moon"===t.transitionConfig.type&&t.transitionConfig.slideOutCrescent)return this.Ee(a,t.transitionConfig);if(t.transitionConfig&&"moon_to_lunar"===t.transitionConfig.type)return this.Be(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_enter_lunar"===t.transitionConfig.type)return this.Ae(a,t.transitionConfig);if(t.transitionConfig&&"lunar_to_moon"===t.transitionConfig.type)return this.Ce(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_exit_lunar"===t.transitionConfig.type)return this.Te(a,t.transitionConfig);if(t.transitionConfig&&"eclipse_enter"===t.transitionConfig.type)return this.Pe(a,r);if("eclipse_exit"===t.transitionConfig.type)return this.De(a,n);if("sun_fade"===t.transitionConfig.type)return this.Re(a,n);if("sun_bloom"===t.transitionConfig.type)return this.Fe(a,r);if("none"!==n.type||"none"!==r.type){const t=(n.coverage||0)+((r.coverage||0)-(n.coverage||0))*a;return{type:"none"!==r.type?r.type:n.type,coverage:t,angle:r.angle||n.angle||0,softness:r.softness||n.softness||.2,progress:a}}return n}Ee(t,e){const i=e.shadowSlideRatio||.4;if(t<i){const e=t/i,s=-30*Math.PI/180,n=.7,r=n+(2.5-n)*e;return{type:"crescent",coverage:e>.8?.85*(1-5*(e-.8)):.85,angle:-30,offset:r,shadowX:Math.cos(s)*r,shadowY:Math.sin(s)*r}}return{type:"none"}}Be(t,e){const i=e.startAngle*Math.PI/180,s=1-t,n=.7*Math.cos(i)*s,r=.7*Math.sin(i)*s,a=Math.pow(t,2);if(t<.6)return{type:"crescent",coverage:.85*(1-.2*a),angle:e.startAngle,offset:.7*s,shadowX:n,shadowY:r};{const e=(t-.6)/.4,i=Math.sin(e*Math.PI/2);return{type:"lunar",coverage:.85+.1*i,color:`rgba(80, 20, 0, ${.7+.2*i})`,shadowX:n*(1-i),shadowY:r*(1-i),diffusion:i,shadowProgress:t}}}Ae(t,e){if(t<.3)return{type:"none"};const i=(t-.3)/.7,s=Math.sin(i*Math.PI/2),n=e.startAngle*Math.PI/180,r=1-s,a=.7*Math.cos(n)*r,o=.7*Math.sin(n)*r;if(i<.7)return{type:"crescent",coverage:.85*Math.pow(i/.7,.5),angle:e.startAngle,offset:.7*r,shadowX:a,shadowY:o};{const t=(i-.7)/.3,e=Math.sin(t*Math.PI/2);return{type:"lunar",coverage:.85+.1*e,color:`rgba(80, 20, 0, ${.6+.3*e})`,shadowX:a*(1-e),shadowY:o*(1-e),diffusion:e,shadowProgress:i}}}Ce(t,e){const i=e.exitAngle*Math.PI/180,s=Math.sin(t*Math.PI/2),n=.7*Math.cos(i)*s,r=.7*Math.sin(i)*s;if(t<.6){const e=t/.6,i=Math.pow(e,.7);return{type:"lunar",coverage:.95-.1*i,color:`rgba(80, 20, 0, ${.9-.3*i})`,shadowX:.7*n,shadowY:.7*r,diffusion:1-i}}{const i=(t-.6)/.4;return{type:"crescent",coverage:.85*Math.sin(i*Math.PI/2)+.1,angle:e.exitAngle,offset:.7,shadowX:n,shadowY:r}}}Te(t,e){if(t<.7){const i=t/.7,s=e.exitAngle*Math.PI/180;if(i<.4){const t=i/.4,e=1-t,n=.3*t;return{type:"lunar",coverage:.95-.1*t,color:`rgba(80, 20, 0, ${.9-.2*t})`,shadowX:.7*Math.cos(s)*n,shadowY:.7*Math.sin(s)*n,diffusion:e}}{const t=(i-.4)/.6,n=Math.pow(t,.8),r=.7*Math.cos(s)*n,a=.7*Math.sin(s)*n;return{type:"crescent",coverage:.85*(1-Math.pow(t,2)),angle:e.exitAngle,offset:.7*n,shadowX:r,shadowY:a}}}return{type:"none"}}Pe(t,e){return{...e,shadowX:1.5-1.5*t,shadowProgress:t}}De(t,e){const i=1.5*-t;return{...e,coverage:e.coverage*(1-t),shadowX:i,shadowProgress:1-t}}Re(t,e){const i=1-t;return{...e,intensity:(e.intensity||1)*Math.pow(i,.7),corona:e.corona,coronaOpacity:i,flares:e.flares,flaresOpacity:Math.pow(i,1.5),texture:e.texture,textureOpacity:Math.pow(i,2),turbulence:(e.turbulence||.3)*i}}Fe(t,e){const i=t;return{...e,intensity:(e.intensity||1)*Math.pow(i,1.5),corona:e.corona,coronaOpacity:Math.pow(i,.8),flares:e.flares,flaresOpacity:i>.3?Math.pow((i-.3)/.7,.7):0,texture:e.texture,textureOpacity:i>.5?Math.pow((i-.5)/.5,2):0,turbulence:(e.turbulence||.3)*i}}}class ea{constructor(t={}){this.numPoints=t.numPoints||64,this.morphDuration=t.morphDuration||1e3,this.easing=t.easing||"easeInOutCubic",this.transitionManager=new Zr(this),this.audioDeformer=new Qr(this),this.musicDetector=new Kr,this.shadowEffectManager=new ta(()=>({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=Nr.acquire(32,"float32"),this.glitchPoints=[],this.undulationPhase=0,this.undulationDirection=1,this.beatGlitchIntensity=0,this.bassEnergy=0,this.vocalPresence=0,this.bassHistory=Nr.acquire(60,"float32"),this.vocalHistory=Nr.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(t=>{(Vr&&Vr.isInitialized?Vr.hasShape(t):Xr[t])&&this.getShapePoints(t)}),[0,.25,.5,.75,1].forEach(t=>{this.applyEasing(t)})}getShapePoints(t){if(!this.shapeCache.has(t)){const e=Vr&&Vr.isInitialized?Vr.getShape(t):Xr[t];if(!e||!e.points){const e=Xr.circle.points;return this.shapeCache.set(t,e),e}const{points:i}=e;return this.shapeCache.set(t,i),i}return this.shapeCache.get(t)}morphTo(t,e={}){if(!this.shapesLoaded)return;if(t===this.currentShape&&!this.isTransitioning)return;if(this.isTransitioning&&!e.force)return this.queuedMorph={targetShape:t,options:e},"queued";this.isTransitioning&&e.force&&this.completeMorph(!0);const i=this.getTransitionConfig(this.currentShape,t);if(this.targetShape=t,this.targetPoints=this.getShapePoints(t),this.morphStartTime=Date.now(),this.isTransitioning=!0,this.morphProgress=0,this.visualProgress=0,"bar"===e.duration||"beat"===e.duration){const t=6e4/(Vs.bpm||120);"bar"===e.duration?this.morphDuration=4*t:this.morphDuration=t,this.musicalDuration=!0,this.onBeat=!1!==e.onBeat}else this.morphDuration=i?.duration||e.duration||1e3,this.musicalDuration=null,this.onBeat=!1;this.morphMode=e.mode||"smooth",this.transitionConfig=i,this.onComplete=e.onComplete,this.onProgress=e.onProgress}update(t){if(this.audioAnalyzer&&this.audioAnalyzer.isAnalyzing){const t=this.audioAnalyzer.getShapeMorpherData();if(t&&t.frequencies)for(let e=0;e<Math.min(t.frequencies.length,this.frequencyData.length);e++)this.frequencyData[e]=t.frequencies[e]}if(this.musicDetector&&this.musicDetector.update(performance.now()),!this.isTransitioning||!this.targetShape)return;const e=Date.now()-this.morphStartTime;if(this.musicalDuration){const t=6e4/(Vs.bpm||120),e=this.morphDuration>2*t;this.morphDuration=e?4*t:t}let i=Math.min(e/this.morphDuration,1);if(this.musicalDuration&&this.onBeat){const t=Vs.bpm||120;let e;e=t>140?2:t>100?4:8;const s=6e4/t,n=this.morphDuration/s,r=i*n,a=Math.round(r*e)/e,o=Math.min(1,a/n),h=(.3+.5*(t<90?Math.max(.3,(t-60)/30):Math.max(.4,Math.min(1,1-(t-90)/90))))*(.3+.7*Math.sin(i*Math.PI));i+=h*h*(3-2*h)*(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(t=!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),!t&&this.queuedMorph){const t=this.queuedMorph;this.queuedMorph=null,this.queuedMorphTimeout=setTimeout(()=>{this.morphTo(t.targetShape,t.options),this.queuedMorphTimeout=null},50)}}hasQueuedMorph(){return null!==this.queuedMorph}clearQueue(){this.queuedMorph=null,this.queuedMorphTimeout&&(clearTimeout(this.queuedMorphTimeout),this.queuedMorphTimeout=null)}getCanvasPoints(t,e,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 r=s/this.numPoints*Math.PI*2;n.push({x:t+Math.cos(r)*i,y:e+Math.sin(r)*i})}return n}const r=Array.isArray(s)?s:[];for(let s=0;s<r.length;s++){const a=r[s];if(a&&"number"==typeof a.x&&"number"==typeof a.y){const s=t+(a.x-.5)*i*2,r=e+(a.y-.5)*i*2;n.push({x:s,y:r})}else{const a=s/r.length*Math.PI*2;n.push({x:t+Math.cos(a)*i,y:e+Math.sin(a)*i})}}for(;n.length<this.numPoints;){const s=n.length/this.numPoints*Math.PI*2;n.push({x:t+Math.cos(s)*i,y:e+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 t=[];for(let e=0;e<this.numPoints;e++){const i=this.currentPoints[e],s=this.targetPoints[e];if(!i||!s){const i=e/this.numPoints*Math.PI*2;t.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)});continue}const n=this.visualProgress;let r,a;const o=["square","circle","star","triangle"],h=o.includes(this.currentShape),l=o.includes(this.targetShape);if(h||l){const t=.5,e=.5;if(l&&!h){const o=s.x-t,h=s.y-e;if(n<.3){const s=n/.3;r=i.x+(t-i.x)*s,a=i.y+(e-i.y)*s}else{const i=(n-.3)/.7;r=t+o*i,a=e+h*i}}else if(h&&!l){const o=i.x-t,h=i.y-e;if(n<.5){const t=n/.5;r=i.x-o*t,a=i.y-h*t}else{const i=(n-.5)/.5;r=t+(s.x-t)*i,a=e+(s.y-e)*i}}else{const o=i.x-t,h=i.y-e,l=s.x-t,c=s.y-e;if(n<.5){const t=n/.5;r=i.x-o*t,a=i.y-h*t}else{const i=(n-.5)/.5;r=t+l*i,a=e+c*i}}}else if("spiral"===this.morphMode){const t=n*Math.PI*2,o=.02*Math.sin(t+.2*e)*(1-2*Math.abs(n-.5));r=i.x+(s.x-i.x)*n+o,a=i.y+(s.y-i.y)*n+o}else if("wave"===this.morphMode){const t=.01*Math.sin(.3*e+n*Math.PI*4);r=i.x+(s.x-i.x)*n+t,a=i.y+(s.y-i.y)*n+t}else r=i.x+(s.x-i.x)*n,a=i.y+(s.y-i.y)*n;t.push({x:r,y:a})}return this.applyAudioDeformation(t)}applyAudioDeformation(t){return this.audioDeformer.applyAudioDeformation(t)}setAudioDeformation(t){const e=Date.now();e-this.lastAudioUpdate>this.audioUpdateInterval&&(this.audioDeformation=Math.max(-1,Math.min(1,t)),this.lastAudioUpdate=e,this.audioDeformer&&this.audioDeformer.setAudioDeformation(Math.abs(this.audioDeformation)))}setVocalEnergy(t){const e=Date.now();e-this.lastVocalUpdate>this.audioUpdateInterval&&(this.vocalEnergy=Math.max(0,Math.min(1,t)),this.lastVocalUpdate=e,this.audioDeformer&&this.audioDeformer.setVocalEnergy(this.vocalEnergy))}getTransitionConfig(t,e){const i=Vr&&Vr.isInitialized?Vr.getShape(t):Xr[t],s=Vr&&Vr.isInitialized?Vr.getShape(e):Xr[e];return"moon"===e?{type:"to_moon",easing:"easeInOutCubic",duration:1500,glowIntensity:1.5,fadeInCrescent:!0}:"moon"===t&&"lunar"===e?{type:"moon_to_lunar",easing:"easeInOutSine",duration:2e3,slideOutCrescent:!1,description:"Crescent shadow moves to center and becomes lunar eclipse"}:"moon"===t?{type:"from_moon",easing:"easeInOutCubic",duration:1e3,slideOutCrescent:!0,shadowSlideRatio:.4,description:"Moon shadow slides away THEN morphs to target"}:"lunar"===e?{type:"eclipse_enter_lunar",startAngle:-30}:"lunar"===t&&"moon"===e?{type:"lunar_to_moon",exitAngle:-30}:"lunar"===t?{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"===t&&"sun"!==e?{type:"sun_fade",fadeEffects:!0}:"sun"!==t&&"sun"===e?{type:"sun_bloom",bloomEffects:!0}:{type:"standard"}}getCurrentShadow(){return this.shadowEffectManager.getCurrentShadow()}getCurrentRenderer(){return null}applyEasing(t){switch(this.transitionConfig?.easing||this.easing||"linear"){case"linear":return t;case"easeInQuad":return t*t;case"easeOutQuad":return t*(2-t);case"easeInOutQuad":return t<.5?2*t*t:(4-2*t)*t-1;case"easeInOutSine":return-(Math.cos(Math.PI*t)-1)/2;default:return t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2}}calculateBPM(){return this.musicDetector.calculateBPM()}findTempoCandidates(t){return this.musicDetector.findTempoCandidates(t)}clusterIntervals(t){return this.musicDetector.clusterIntervals(t)}checkHarmonicRelation(t,e){return this.musicDetector.checkHarmonicRelation(t,e)}detectTimeSignature(){this.musicDetector.forceFastDetection=this.forceFastDetection;const t=this.musicDetector.detectTimeSignature();return this.detectedTimeSignature=this.musicDetector.detectedTimeSignature,this.timeSignatureConfidence=this.musicDetector.timeSignatureConfidence,this.timeSignatureLocked=this.musicDetector.timeSignatureLocked,t}testWaltzPattern(t,e){return this.musicDetector.testWaltzPattern(t,e)}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 t=document.getElementById("time-sig-display");t&&(t.textContent="โ")}getCurrentMusicInfo(){return{bpm:this.detectedBPM,timeSignature:this.detectedTimeSignature,bpmLocked:this.tempoLocked,timeSigLocked:this.timeSignatureLocked}}generateFallbackCircle(){const t=[];for(let e=0;e<this.numPoints;e++){const i=e/this.numPoints*Math.PI*2;t.push({x:.5+.5*Math.cos(i),y:.5+.5*Math.sin(i)})}return t}getState(){return{currentShape:this.currentShape,targetShape:this.targetShape,isTransitioning:this.isTransitioning,progress:this.morphProgress,audioDeformation:this.audioDeformation,vocalEnergy:this.vocalEnergy}}getProgress(t=!0){return t?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&&(Nr.release(this.frequencyData),this.frequencyData=null),this.bassHistory&&(Nr.release(this.bassHistory),this.bassHistory=null),this.vocalHistory&&(Nr.release(this.vocalHistory),this.vocalHistory=null),this.audioAnalyzer=null}}class ia{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.ze=null,this.qe=()=>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(t){return!1}}createAnalyser(){if(this.audioContext&&!this.analyser){this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2048,this.analyser.smoothingTimeConstant=.5;const t=this.analyser.frequencyBinCount;this.dataArray=new Uint8Array(t),this.ze=new Uint8Array(t)}}connectAudioElement(t){if(this.audioContext)try{this.elementSource&&this.connectedElement===t||(this.elementSource=this.audioContext.createMediaElementSource(t),this.elementSource.connect(this.analyser),this.elementSource.connect(this.audioContext.destination)),this.source=this.elementSource,this.connectedElement=t,this.isAnalyzing=!0,this.analyze()}catch(e){(e instanceof Error?e.message:String(e)).includes("already been used")&&(this.source=this.elementSource,this.connectedElement=t,this.isAnalyzing=!0,this.analyze())}}analyze(){if(!this.isAnalyzing)return;this.animationFrameId=requestAnimationFrame(this.qe),this.analyser.getByteFrequencyData(this.dataArray),this.analyser.getByteTimeDomainData(this.ze);let t=0,e=0,i=0;const s=this.audioContext.sampleRate/2/this.dataArray.length,n=Math.floor(this.vocalRange.min/s),r=Math.ceil(this.vocalRange.max/s);for(let s=0;s<this.dataArray.length;s++){const a=this.dataArray[s]/255;t+=a,s>=n&&s<=r&&(e+=a,i++)}this.currentAmplitude=t/this.dataArray.length;const a=i>0?e/i:0;return this.extractFrequencyBands(),this.detectBeat(this.currentAmplitude),{amplitude:this.currentAmplitude,vocalAmplitude:a,frequencies:this.currentFrequencies,rawData:this.dataArray}}extractFrequencyBands(){const t=Math.floor(this.dataArray.length/this.frequencyBands);for(let e=0;e<this.frequencyBands;e++){let i=0;const s=e*t,n=Math.min(s+t,this.dataArray.length);for(let t=s;t<n;t++)i+=this.dataArray[t]/255;const r=i/t;this.currentFrequencies[e]=this.currentFrequencies[e]*this.smoothingFactor+r*(1-this.smoothingFactor)}}detectBeat(t){const e=performance.now();t>this.beatThreshold&&e-this.lastBeatTime>60&&(this.lastBeatTime=e,this.beatCallbacks.forEach(e=>e(t)))}getVocalInstability(){let t=0;const e=this.currentFrequencies.reduce((t,e)=>t+e,0)/this.frequencyBands;for(let i=0;i<this.frequencyBands;i++)t+=Math.pow(this.currentFrequencies[i]-e,2);return t=Math.sqrt(t/this.frequencyBands),Math.min(1,2*t+.5*this.currentAmplitude)}getShapeMorpherData(){return{instability:this.getVocalInstability(),frequencies:[...this.currentFrequencies],amplitude:this.currentAmplitude}}onBeat(t){this.beatCallbacks.push(t)}stop(){if(this.isAnalyzing=!1,null!==this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.gainNode){try{this.gainNode.disconnect()}catch(t){}this.gainNode=null}if(this.elementSource&&this.connectedElement){try{this.elementSource.connect(this.analyser)}catch(t){}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.ze=null,this.beatCallbacks=[]}}class sa{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(t,e){if(t===e)return!1;if(this.incompatiblePairs.some(i=>i.includes(t)&&i.includes(e)))return!1;const i=this.getGestureGroup(t),s=this.getGestureGroup(e);if(i===s){const t=this.groups[i];return t&&1!==t.maxSimultaneous}return!("movement"===i&&"movement"===s||"dance"===i&&"dance"===s)}getGestureGroup(t){for(const[e,i]of Object.entries(this.groups))if(i.gestures.includes(t))return e;return null}getGesturePriority(t){const e=this.getGestureGroup(t);return e?this.groups[e].priority:99}getCompatibleGestures(t){if(!t||0===t.length)return[];if(1===t.length)return t;const e=[],i=new Set,s=t=>"string"==typeof t?t:t.gestureName,n=[...t].sort((t,e)=>this.getGesturePriority(s(t))-this.getGesturePriority(s(e)));for(const t of n){if(i.has(t))continue;const n=s(t);let r=!0;for(const t of e){const e=s(t);if(!this.canExecuteSimultaneously(n,e)){r=!1;break}}if(r){const r=this.groups[this.getGestureGroup(n)];if(r&&r.maxSimultaneous>0&&e.filter(t=>this.getGestureGroup(s(t))===this.getGestureGroup(n)).length>=r.maxSimultaneous)continue;e.push(t),i.add(t)}}return e}parseChain(t){return t?(this.chains[t]&&(t=this.chains[t]),t.split(">").map(t=>t.trim()).map(t=>t.split("+").map(t=>t.trim()).filter(t=>t))):[]}isEnhancingCombination(t){const e=t.map(t=>"string"==typeof t?t:t.gestureName);return this.enhancingCombinations.some(t=>t.every(t=>e.includes(t)))}getChord(t){return this.chords[t]||null}createChord(t){const e=this.getCompatibleGestures(t),i=this.isEnhancingCombination(e);return{type:"chord",gestures:e.map(t=>"string"==typeof t?t:t.gestureName),isEnhancing:i,timestamp:Date.now()}}isValidGesture(t){return null!==this.getGestureGroup(t)}getAllGestures(){const t=[];for(const e of Object.values(this.groups))t.push(...e.gestures);return[...new Set(t)]}getGestureTiming(t){for(const[e,i]of Object.entries(this.timingClasses))if(i.gestures.includes(t))return{name:e,...i};return null}getNextBeatForGesture(t,e,i=1){const s=this.getGestureTiming(t);if(!s)return e+1;if(-1===s.timing)return e;const n=s.timing/i,r=Math.ceil(e/n)*n;return"offbeat"===s.name?r+.5:r}getFillGestures(t,e="moderate"){const i=this.densityProfiles[e]||this.densityProfiles.moderate;let s;return s=t<80?"energetic":t<120?"rhythmic":t<160?"smooth":"subtle",Math.random()<i.fillProbability&&this.fillPatterns[s]||[]}getNextBeatTiming(t,e,i){return this.getNextBeatForGesture(t,e)}getIntensityFromBPM(t){return t<60?"dense":t<100||t<140?"moderate":"sparse"}applySwingTiming(t,e=.67){return.5==t%1?Math.floor(t)+e:t}}const na=new sa;var ra=Object.freeze({__proto__:null,GestureCompatibility:sa,default:na});class aa{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(t){return this.templates[t.toLowerCase()]||this.templates.straight}getEmphasis(t,e,i){if(!t||!t.pattern)return 0;const s=t.pattern.subdivisions.findIndex(t=>Math.abs(t-i)<.01);return-1===s?0:t.pattern.emphasis[s]||0}getVelocity(t,e,i){if(!t||!t.pattern)return 1;const s=t.pattern.subdivisions.findIndex(t=>Math.abs(t-i)<.01);return-1===s?0:t.pattern.velocities[s]||0}getPreferredGesture(t,e,i,s=[]){if(!t||!t.preferredGestures)return null;let n;n=0===i?"downbeat":.5===i?"offbeat":.25===i||.75===i?"subdivision":"syncopation","Funk"===t.name&&e%4==0&&0===i&&(n="one");const r=t.preferredGestures[n]||t.preferredGestures.fills;if(!r||0===r.length)return null;if(s.length>0){const t=r.filter(t=>s.includes(t));if(t.length>0)return t[Math.floor(Math.random()*t.length)]}return r[Math.floor(Math.random()*r.length)]}humanizeTiming(t,e){if(!t||!t.humanization)return e;const i=t.humanization,s=(Math.random()-.5)*i;return Math.max(0,Math.min(1,e+s))}applySwing(t,e){return t&&t.swing&&0!==t.swing?Math.abs(e-.5)<.01?.5+.5*(t.swing-.5):Math.abs(e-.25)<.01?.25+.25*(t.swing-.5):Math.abs(e-.75)<.01?.75+.25*(t.swing-.5):e:e}setGroove(t,e=null){const i=this.getTemplate(t);return!!i&&("instant"!==(e||this.transitionMode)&&this.currentGroove?this.pendingGroove=i:(this.currentGroove=i,this.pendingGroove=null),!0)}onBeat(t){this.pendingGroove&&("nextBar"===this.transitionMode&&t%4==0||"nextPhrase"===this.transitionMode&&t%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(t){return!!this.currentGroove?.compositeMove&&t%("sparse"===this.currentGroove.intensity?32:16)==0}getLayeredGestures(t,e){if(!this.currentGroove)return null;const i={base:this.getBaseMovement(),accent:null,transition:null,composite:null,velocity:1};this.shouldTriggerComposite(t)&&0===e&&(i.composite=this.getCompositeMove());const s=this.getEmphasis(this.currentGroove,t,e),n=this.getVelocity(this.currentGroove,t,e);return s>.3&&n>.3&&(i.accent=this.getPreferredGesture(this.currentGroove,t,e),i.velocity=n),i.accent&&Math.random()<.3&&(i.transition=this.getTransitionStyle()),i}getGrooveNames(){return Object.keys(this.templates)}getGrooveInfo(t){const e=this.templates[t];return e?{name:e.name,timeSignature:e.timeSignature,description:e.description,intensity:e.intensity,swing:e.swing,baseMovement:e.baseMovement,compositeMove:e.compositeMove}:null}}const oa={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 ha{constructor(t={}){this.performances=new Map,this.contextManager=null,this.sequenceExecutor=null,this.eventManager=t.eventManager||null,this.defaultIntensity=t.defaultIntensity||.7,this.enableContextAdjustment=!1!==t.enableContextAdjustment,this.enableAnalytics=t.enableAnalytics||!1,this.performanceHistory=[],this.maxHistorySize=t.maxHistorySize||100,this.loadBuiltInPerformances()}loadBuiltInPerformances(){Object.entries(oa).forEach(([t,e])=>{this.definePerformance(t,e)})}definePerformance(t,e){this.performances.set(t,{...e,name:t}),this.eventManager&&this.eventManager.emit("performanceDefined",{name:t,definition:e})}getPerformance(t){return this.performances.get(t)||null}hasPerformance(t){return this.performances.has(t)}async perform(t,e={}){const i=this.getPerformance(t);if(!i)return;const s=this.calculateIntensity(i,e),n={performance:i,semanticAction:t,intensity:s,options:e,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,...e}):await this.executeSimplePerformance(i,s,e),this.eventManager&&this.eventManager.emit("performanceComplete",n)}catch(t){this.eventManager&&this.eventManager.emit("performanceError",{...n,error:t})}}async executeSimplePerformance(t,e,i){const{emotion:s,gesture:n,delay:r=0}=t,a=i.mascot||this.mascot;if(a){if(s&&"function"==typeof a.setEmotion){const e=void 0!==i.emotionDuration?i.emotionDuration:t.emotionDuration||500;a.setEmotion(s,e)}n&&"function"==typeof a.express&&(r>0&&await new Promise(t=>setTimeout(t,r)),a.express(n))}}calculateIntensity(t,e){if(void 0!==e.intensity)return Math.max(0,Math.min(1,e.intensity));let i=t.baseIntensity||this.defaultIntensity;if(this.enableContextAdjustment&&e.context){const{context:t}=e;void 0!==t.frustration&&(i+=t.frustration/100*.3),"high"===t.urgency?i+=.2:"medium"===t.urgency&&(i+=.1),"epic"===t.magnitude?i=1:"major"===t.magnitude&&(i=Math.max(i,.9))}return Math.max(0,Math.min(1,i))}recordPerformance(t){this.performanceHistory.push({action:t.semanticAction,intensity:t.intensity,context:t.options.context||{},timestamp:t.timestamp}),this.performanceHistory.length>this.maxHistorySize&&this.performanceHistory.shift()}getAnalytics(){if(!this.enableAnalytics)return{enabled:!1};const t=this.performanceHistory.length,e={},i={};return this.performanceHistory.forEach(t=>{e[t.action]||(e[t.action]=0,i[t.action]=[]),e[t.action]++,i[t.action].push(t.intensity)}),Object.keys(i).forEach(t=>{const e=i[t];i[t]=e.reduce((t,e)=>t+e,0)/e.length}),{enabled:!0,total:t,byAction:e,avgIntensity:i,history:this.performanceHistory.slice(-20)}}clearAnalytics(){this.performanceHistory=[]}setMascot(t){this.mascot=t}setContextManager(t){this.contextManager=t}setSequenceExecutor(t){this.sequenceExecutor=t}listPerformances(){return Array.from(this.performances.keys())}getPerformanceMetadata(t){const e=this.getPerformance(t);return e?{name:e.name,category:e.category||"custom",emotion:e.emotion,gesture:e.gesture,hasSequence:!!e.sequence,baseIntensity:e.baseIntensity||this.defaultIntensity,description:e.description||""}:null}}class la{constructor(t={}){this.context={frustration:0,urgency:"medium",magnitude:"moderate",customValues:{}},this.enableHistory=!1!==t.enableHistory,this.historyLimit=t.historyLimit||50,this.history=[],this.enableDecay=!1!==t.enableDecay,this.frustrationDecayRate=t.frustrationDecayRate||5,this.decayInterval=t.decayInterval||1e4,this.decayTimer=null,this.enableDecay&&this.startDecayTimer()}update(t={}){const e={...this.context};void 0!==t.frustration&&(this.context.frustration=Math.max(0,Math.min(100,t.frustration))),void 0!==t.urgency&&["low","medium","high"].includes(t.urgency)&&(this.context.urgency=t.urgency),void 0!==t.magnitude&&["small","moderate","major","epic"].includes(t.magnitude)&&(this.context.magnitude=t.magnitude),void 0!==t.custom&&(this.context.customValues={...this.context.customValues,...t.custom}),this.enableHistory&&this.addToHistory(e,this.context,t),this.enableDecay&&this.restartDecayTimer()}incrementFrustration(t=10){this.update({frustration:this.context.frustration+t})}decrementFrustration(t=10){this.update({frustration:this.context.frustration-t})}resetFrustration(){this.update({frustration:0})}setUrgency(t){this.update({urgency:t})}setMagnitude(t){this.update({magnitude:t})}setCustom(t,e){this.update({custom:{[t]:e}})}getContext(){return{...this.context}}get(t){return t in this.context?this.context[t]:this.context.customValues[t]}calculateIntensity(t=.5,e={}){let i=t;return!1!==e.useFrustration&&(i+=this.context.frustration/100*.3),!1!==e.useUrgency&&(i+={low:-.1,medium:0,high:.2}[this.context.urgency]||0),!1!==e.useMagnitude&&(i+={small:-.1,moderate:0,major:.15,epic:.3}[this.context.magnitude]||0),void 0!==e.intensityMultiplier&&(i*=e.intensityMultiplier),Math.max(0,Math.min(1,i))}addToHistory(t,e,i){const s={timestamp:Date.now(),previous:t,current:{...e},updates:i,delta:{frustration:e.frustration-t.frustration,urgency:e.urgency!==t.urgency?e.urgency:null,magnitude:e.magnitude!==t.magnitude?e.magnitude:null}};this.history.push(s),this.history.length>this.historyLimit&&this.history.shift()}getHistory(t){return t?this.history.slice(-t):[...this.history]}clearHistory(){this.history=[]}startDecayTimer(){this.decayTimer=setInterval(()=>{if(this.context.frustration>0){const t=Math.max(0,this.context.frustration-this.frustrationDecayRate);this.update({frustration:t})}},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 t=this.history.map(t=>t.current.frustration),e=t.reduce((t,e)=>t+e,0)/t.length,i=Math.max(...t),s=Math.min(...t),n=this.history.reduce((t,e)=>(t[e.current.urgency]=(t[e.current.urgency]||0)+1,t),{}),r=this.history.reduce((t,e)=>(t[e.current.magnitude]=(t[e.current.magnitude]||0)+1,t),{});return{current:{...this.context},frustration:{current:this.context.frustration,average:e,max:i,min:s},urgency:{current:this.context.urgency,distribution:n},magnitude:{current:this.context.magnitude,distribution:r},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 ca{constructor(t={}){this.mascot=t.mascot||null,this.eventManager=t.eventManager||null,this.activeSequences=new Map,this.nextSequenceId=1,this.defaultDelay=t.defaultDelay||0,this.allowConcurrent=!1!==t.allowConcurrent}async execute(t,e={}){if(!Array.isArray(t)||0===t.length)return;const i=e.mascot||this.mascot;if(!i)return;!this.allowConcurrent&&this.activeSequences.size>0&&this.cancelAll();const s=this.nextSequenceId++,n=[...t].sort((t,e)=>t.at-e.at),r={cancelled:!1};this.activeSequences.set(s,r);try{this.eventManager&&this.eventManager.emit("sequenceStart",{sequenceId:s,steps:n,timestamp:Date.now()}),await this.executeSteps(n,i,r,e),this.eventManager&&this.eventManager.emit("sequenceComplete",{sequenceId:s,timestamp:Date.now()})}catch(t){this.eventManager&&this.eventManager.emit("sequenceError",{sequenceId:s,error:t,timestamp:Date.now()})}finally{this.activeSequences.delete(s)}}async executeSteps(t,e,i,s){let n=0;for(const r of t){if(i.cancelled)break;const t=r.at-n;if(t>0&&await this.sleep(t,i),i.cancelled)break;await this.executeStep(r,e,s),n=r.at}}executeStep(t,e,i){const{action:s,value:n,intensity:r,options:a}=t;try{switch(s){case"emotion":if("function"==typeof e.setEmotion){const t=void 0!==r?r:i.intensity,s=a?.duration||i.emotionDuration||500;e.setEmotion(n,void 0!==t?t:s)}break;case"gesture":"function"==typeof e.express&&e.express(n,a);break;case"morph":"function"==typeof e.morphTo&&e.morphTo(n,a);break;case"chain":"function"==typeof e.chain&&e.chain(n,a);break;case"sound":"function"==typeof e.playSound&&e.playSound(n,a)}this.eventManager&&this.eventManager.emit("stepExecuted",{action:s,value:n,timestamp:Date.now()})}catch(t){this.eventManager&&this.eventManager.emit("stepError",{action:s,value:n,error:t,timestamp:Date.now()})}}sleep(t,e){return new Promise(i=>{const s=setTimeout(()=>{e&&(e.Oe=null),i()},t);e&&(e.Oe=s,e.je=i)})}cancel(t){const e=this.activeSequences.get(t);e&&(e.cancelled=!0,e.Oe&&(clearTimeout(e.Oe),e.Oe=null),e.je&&(e.je(),e.je=null),this.activeSequences.delete(t),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:t,timestamp:Date.now()}))}cancelAll(){this.activeSequences.forEach((t,e)=>{t.cancelled=!0,t.Oe&&(clearTimeout(t.Oe),t.Oe=null),t.je&&(t.je(),t.je=null),this.eventManager&&this.eventManager.emit("sequenceCancelled",{sequenceId:e,timestamp:Date.now()})}),this.activeSequences.clear()}getActiveCount(){return this.activeSequences.size}isActive(){return this.activeSequences.size>0}setMascot(t){this.mascot=t}}let ua=class{constructor(t){if(!t.errorBoundary)throw new Error("GestureController: errorBoundary required");if(!t.config)throw new Error("GestureController: config required");if(!t.state)throw new Error("GestureController: state required");if(!t.throttledWarn)throw new Error("GestureController: throttledWarn required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.performanceMonitor=t.performanceMonitor||null,this.soundSystem=t.soundSystem||null,this.config=t.config,this.Ie=t.state,this.$e=t.throttledWarn,this.Le=t.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 ra}).then(t=>{this.gestureCompatibility=t.default}).catch(t=>{})}express(t,e={}){return this.errorBoundary.wrap(()=>{if(!t)return this.Le;const i=performance.now(),s=Array.isArray(t)||"object"==typeof t&&"chord"===t.type?"chord":t;if(this.performanceMonitor&&this.performanceMonitor.markGestureStart(s),Array.isArray(t))return this.expressChord(t,e);if("object"==typeof t&&"chord"===t.type)return this.expressChord(t.gestures,e);const n=this.rendererMethods[t];if(n&&this.renderer&&this.renderer[n]){if(this.renderer[n](e),this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(t),this.performanceMonitor){const t=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,t-i)}return this.Le}const r=Pi(t);if(r){if(Qs.registerConfig("gesture",t,r),this.Ie.currentModularGesture={type:t,config:r,startTime:performance.now(),duration:r.defaultParams?.duration||1e3,progress:0},this.config.soundEnabled&&this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.playGestureSound(t),this.performanceMonitor){const t=performance.now();this.performanceMonitor.markGestureEnd(s),this.performanceMonitor.recordGestureTime(s,t-i)}return this.Le}return this.$e(`Unknown gesture: ${t}`,`gesture_${t}`),this.performanceMonitor&&this.performanceMonitor.markGestureEnd(s),this.Le},"gesture-express",this.Le)()}expressChord(t,e={}){return this.errorBoundary.wrap(()=>{if(!t||!Array.isArray(t)||0===t.length)return this.Le;this.gestureCompatibility||Promise.resolve().then(function(){return ra}).then(t=>{this.gestureCompatibility=t.default}).catch(t=>{});const i=this.gestureCompatibility?this.gestureCompatibility.getCompatibleGestures(t):t;return i.forEach(t=>{const i="string"==typeof t?t:t.gestureName;this.executeGestureDirectly(i,e)}),this.gestureCompatibility?.isEnhancingCombination?.(i)&&this.renderer?.specialEffects?.addSparkle?.(),this.Le},"gesture-chord",this.Le)()}executeGestureDirectly(t,e={}){const i=this.rendererMethods[t];i&&this.renderer&&"function"==typeof this.renderer[i]&&this.renderer[i](e)}chain(...t){if(this.gestureCompatibility){const e=t.join(">"),i=this.gestureCompatibility.parseChain(e);this.executeChainSequence(i)}else t.length>0&&this.express(t[0]);return this.Le}executeChainSequence(t){if(!t||0===t.length)return;let e=0;const i=()=>{if(e>=t.length)return;const s=t[e];1===s.length?this.express(s[0]):this.expressChord(s),e++,e<t.length&&setTimeout(i,800)};i()}destroy(){this.currentGesture=null,this.gestureCompatibility=null}};class da{constructor(t={}){const e=t.initialState||{};this.Ge=e.isRunning??!1,this._e=e.debugMode??!1,this.He=e.speaking??!1,this.Ue=e.recording??!1,this.We=e.audioLevel??0,this.Ye=e.sleeping??!1,this.Xe=e.rhythmEnabled??!1,this.Ve=e.currentModularGesture??null,this.Ne=e.breathePhase??"idle",this.Qe=e.breatheStartTime??0,this.Je=e.orbScale??1,this.Ke=e.warningTimestamps??{},this.Ze=e.warningThrottle??5e3,this.ti=t.emit||(()=>{})}get isRunning(){return this.Ge}set isRunning(t){const e=this.Ge!==t;this.Ge=t,e&&this.ti("stateChange",{property:"isRunning",value:t})}get debugMode(){return this._e}set debugMode(t){const e=this._e!==t;this._e=t,e&&this.ti("stateChange",{property:"debugMode",value:t})}get speaking(){return this.He}set speaking(t){const e=this.He!==t;this.He=t,e&&this.ti("stateChange",{property:"speaking",value:t})}get recording(){return this.Ue}set recording(t){const e=this.Ue!==t;this.Ue=t,e&&this.ti("stateChange",{property:"recording",value:t})}get audioLevel(){return this.We}set audioLevel(t){this.We=t}get sleeping(){return this.Ye}set sleeping(t){const e=this.Ye!==t;this.Ye=t,e&&this.ti("stateChange",{property:"sleeping",value:t})}get rhythmEnabled(){return this.Xe}set rhythmEnabled(t){this.Xe=t}get currentModularGesture(){return this.Ve}set currentModularGesture(t){this.Ve=t}get breathePhase(){return this.Ne}set breathePhase(t){this.Ne=t}get breatheStartTime(){return this.Qe}set breatheStartTime(t){this.Qe=t}get orbScale(){return this.Je}set orbScale(t){this.Je=t}get warningTimestamps(){return this.Ke}set warningTimestamps(t){this.Ke=t}get warningThrottle(){return this.Ze}set warningThrottle(t){this.Ze=t}getSnapshot(){return{isRunning:this.Ge,debugMode:this._e,speaking:this.He,recording:this.Ue,audioLevel:this.We,sleeping:this.Ye,rhythmEnabled:this.Xe,currentModularGesture:this.Ve,breathePhase:this.Ne,breatheStartTime:this.Qe,orbScale:this.Je}}reset(){this.Ge=!1,this._e=!1,this.He=!1,this.Ue=!1,this.We=0,this.Ye=!1,this.Xe=!1,this.Ve=null,this.Ne="idle",this.Qe=0,this.Je=1,this.Ke={}}}class pa{constructor(t){if(!t.config)throw new Error("AudioHandler: config required");if(!t.state)throw new Error("AudioHandler: state required");if(!t.emit)throw new Error("AudioHandler: emit required");this.audioAnalyzer=t.audioAnalyzer||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.shapeMorpher=t.shapeMorpher||null,this.renderer=t.renderer||null,this.soundSystem=t.soundSystem||null,this.stateMachine=t.stateMachine||null,this.config=t.config,this.Ie=t.state,this.ti=t.emit,this.Le=t.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.Le}async connectAudio(t){if(!this.audioAnalyzer)return this.Le;if(!this.audioAnalyzer.audioContext)try{await this.audioAnalyzer.init()}catch(t){return this.Le}if(this.audioAnalyzer.audioContext&&"suspended"===this.audioAnalyzer.audioContext.state)try{await this.audioAnalyzer.audioContext.resume()}catch(t){}return this.audioAnalyzer.connectAudioElement(t),this.shapeMorpher&&(this.shapeMorpher.audioAnalyzer=this.audioAnalyzer,this.audioAnalyzer.onBeat(t=>{if(this.shapeMorpher){if(this.shapeMorpher.musicDetector){const e=performance.now();this.shapeMorpher.musicDetector.addOnset(e,t)}this.shapeMorpher.vocalEffectActive&&(this.shapeMorpher.beatGlitchIntensity=.3*t)}})),this.vocalUpdateInterval&&clearInterval(this.vocalUpdateInterval),this.renderer&&this.renderer.startGrooveBob({intensity:.5,frequency:1}),this.vocalUpdateInterval=setInterval(()=>{if(this.audioAnalyzer.isAnalyzing&&this.shapeMorpher){const t=this.audioAnalyzer.currentAmplitude||0,e=this.audioAnalyzer.getVocalInstability()||0;this.shapeMorpher.setVocalEnergy(e),this.shapeMorpher.setAudioDeformation(2*t)}},50),this.renderer&&(this.renderer.audioAnalyzer=this.audioAnalyzer),this.Le}stopSpeaking(){if(!this.Ie.speaking)return this.Le;const t=this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0;return this.audioLevelProcessor&&this.audioLevelProcessor.cleanup(),this.Ie.speaking=!1,this.renderer&&this.renderer.onSpeechStop(),this.ti("speechStopped",{previousAudioLevel:t,returnToBaseTime:500}),this.Le}setVolume(t){const e=Math.max(0,Math.min(1,t));if(this.config.masterVolume=e,this.soundSystem&&this.soundSystem.isAvailable()){const t=this.stateMachine.getCurrentState().emotion;this.soundSystem.setMasterVolume(e,t)}return this.ti("volumeChanged",{volume:e}),this.Le}destroy(){this.disconnectAudio()}}class ma{constructor(t,e={}){this.ei=t,this.ii=e.decayRate??.02,this.si=e.decayFloor??0,this.ni=e.accumulationCap??1,this.ri=e.enabled??!1,this.ai=!1,this.oi=[],this.hi=[]}update(t){if(!this.ri||this.ai)return;const e=this.ei.getSlots(),i=this.ii*t;for(const t of e){if(t.intensity<=this.si)continue;const e=t.intensity;if(t.intensity=Math.max(this.si,t.intensity-i),t.intensity!==e){for(const i of this.oi)i(t.emotion,t.intensity,e);this.ei.O("emotionDecayed",{emotion:t.emotion,intensity:t.intensity,removed:!1}),this.ei.O("slotChanged",{emotion:t.emotion,intensity:t.intensity,action:"decay"})}}this.ei.pruneEmptySlots()}nudge(t,e){this.ei.nudgeEmotion(t,e,this.ni);for(const i of this.hi)i(t,e)}setDecayRate(t){this.ii=Math.max(0,t)}getDecayRate(){return this.ii}setAccumulationCap(t){this.ni=Math.max(0,Math.min(1,t))}enable(){this.ri=!0}disable(){this.ri=!1}isEnabled(){return this.ri}pause(){this.ai=!0}resume(){this.ai=!1}reset(){this.ei.clearEmotions()}onDecay(t){return this.oi.push(t),()=>{this.oi=this.oi.filter(e=>e!==t)}}onNudge(t){return this.hi.push(t),()=>{this.hi=this.hi.filter(e=>e!==t)}}serialize(){return{decayRate:this.ii,decayFloor:this.si,accumulationCap:this.ni,enabled:this.ri,paused:this.ai}}deserialize(t){t&&(this.ii=t.decayRate??this.ii,this.si=t.decayFloor??this.si,this.ni=t.accumulationCap??this.ni,this.ri=t.enabled??this.ri,this.ai=t.paused??this.ai)}destroy(){this.oi.length=0,this.hi.length=0}}class ga{constructor(t){this.li=new Map,this.ti=t||(()=>{})}applyModifier(t,e){this.li.set(t,{name:t,config:{...e},remaining:e.duration??null,startTime:Date.now()}),this.ti("modifierApplied",{name:t,config:e})}removeModifier(t){this.li.get(t)&&(this.li.delete(t),this.ti("modifierExpired",{name:t,manual:!0}))}update(t){const e=[];for(const[i,s]of this.li)null!==s.remaining&&(s.remaining-=t,s.remaining<=0)?(e.push(i),s.config.onExpire&&s.config.onExpire()):s.config.onTick&&s.config.onTick(s.remaining);for(const t of e)this.li.delete(t),this.ti("modifierExpired",{name:t,manual:!1})}getCompositeModifiers(){let t=1,e=0,i=0,s=0;for(const n of this.li.values()){const r=n.config;void 0!==r.rhythmWindowMult&&(t*=r.rhythmWindowMult),void 0!==r.tempoShift&&(e+=r.tempoShift),void 0!==r.visualNoise&&(i+=r.visualNoise),void 0!==r.inputDelay&&(s+=r.inputDelay)}return{rhythmWindowMult:t,tempoShift:e,visualNoise:i,inputDelay:s}}getActiveModifiers(){return[...this.li.values()].map(t=>({name:t.name,remaining:t.remaining,config:{...t.config}}))}hasModifier(t){return this.li.has(t)}clear(){this.li.clear()}serialize(){const t=[];for(const e of this.li.values()){const{onTick:i,onExpire:s,...n}=e.config;t.push({name:e.name,remaining:e.remaining,config:n})}return t}deserialize(t){if(Array.isArray(t)){this.li.clear();for(const e of t)this.li.set(e.name,{name:e.name,config:e.config||{},remaining:e.remaining,startTime:Date.now()})}}}class fa{constructor(t){if(!t.stateMachine)throw new Error("StateCoordinator: stateMachine required");if(!t.config)throw new Error("StateCoordinator: config required");if(!t.emit)throw new Error("StateCoordinator: emit required");this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem||null,this.canvasManager=t.canvasManager||null,this.renderer=t.renderer||null,this.config=t.config,this.soundSystem=t.soundSystem||null,this.ti=t.emit,this.Le=t.chainTarget||this,this.currentEmotion="neutral",this.emotionIntensity=1,this.stateMachine.setEventCallback&&this.stateMachine.setEventCallback((t,e)=>{this.ti(t,e)}),this.ci=null,this.Nt=new ga((t,e)=>this.ti(t,e))}init(){}setEmotion(t,e=null){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;let s=null,n=500,r=1;if("string"==typeof e?s=e:e&&"object"==typeof e&&(s=e.undertone||null,n=e.duration||500,r=e.intensity??1),this.emotionIntensity=r,this.stateMachine.setEmotion(i,{undertone:s,duration:n,intensity:r})){const t=l(i);if(t&&Qs.registerConfig("emotion",i,t),this.particleSystem){this.particleSystem.clear();const t=this.stateMachine.getCurrentEmotionalProperties();let e;if(e="neutral"===i?1:"resting"===i?4:Math.min(3,Math.floor(t.particleRate/4)),e>0){let i,s;if(this.renderer&&"function"==typeof this.renderer.getEffectiveCenter){const t=this.renderer.getEffectiveCenter();i=t.x,s=t.y}else i=this.canvasManager.width/2,s=this.canvasManager.height/2;this.particleSystem.burst(e,t.particleBehavior,i,s)}}if("classic"===this.config.renderingStyle&&this.renderer.setEmotionalState){const t=c(i);this.renderer.setEmotionalState(i,t,s)}this.ti("emotionChanged",{emotion:i,undertone:s,duration:n})}return this.currentEmotion=i,this.Le}pushEmotion(t,e=.5){const i={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;this.stateMachine.pushEmotion(i,e);const s=this.stateMachine.getDominant();return s&&(this.currentEmotion=s.emotion),this.ti("emotionChanged",{emotion:this.currentEmotion,slots:this.stateMachine.getSlots()}),this.Le}nudgeEmotion(t,e,i=1){const s={happy:"joy",curious:"surprise",frustrated:"anger",sad:"sadness"}[t]||t;this.stateMachine.nudgeEmotion(s,e,i);const n=this.stateMachine.getDominant();return n&&(this.currentEmotion=n.emotion),this.Le}clearEmotions(){return this.stateMachine.clearEmotions(),this.currentEmotion="neutral",this.ti("emotionChanged",{emotion:"neutral",slots:[]}),this.Le}getEmotionalState(){return this.stateMachine.getEmotionalState()}get dynamics(){return this.ci||(this.ci=new ma(this.stateMachine)),this.ci}setEmotionDampening(t){return this.stateMachine.setEmotionDampening(t),this.Le}getEmotionDampening(){return this.stateMachine.getEmotionDampening()}get modifiers(){return this.Nt}destroy(){this.ci&&this.ci.destroy(),this.Nt.clear(),this.currentEmotion="neutral"}}class ya{constructor(t){if(!t.animationController)throw new Error("VisualizationRunner: animationController required");if(!t.stateMachine)throw new Error("VisualizationRunner: stateMachine required");if(!t.config)throw new Error("VisualizationRunner: config required");if(!t.state)throw new Error("VisualizationRunner: state required");if(!t.emit)throw new Error("VisualizationRunner: emit required");this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem||null,this.canvasManager=t.canvasManager||null,this.renderer=t.renderer||null,this.audioHandler=t.audioHandler||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.gazeTracker=t.gazeTracker||null,this.idleBehavior=t.idleBehavior||null,this.degradationManager=t.degradationManager||null,this.pluginSystem=t.pluginSystem||null,this.config=t.config,this.canvas=t.canvas||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this,this.animationId=null,this.isRunning=!1,this.lastTime=0}init(){}start(){if(this.animationController.isAnimating())return this.Le;if(this.animationController.start()){if(this.Ie.isRunning=!0,this.isRunning=!0,"classic"===this.config.renderingStyle&&this.particleSystem){const t=this.stateMachine.getCurrentState(),{emotion:e}=t,i=c(e);let s,n;if(this.renderer&&this.renderer.getCurrentOrbPosition){const t=this.renderer.getCurrentOrbPosition();s=t.x,n=t.y}else s=this.canvasManager.width/2,n=this.canvasManager.height/2;if(this.particleSystem.clear(),i.particleRate>0){const t=Math.min(3,Math.floor(i.particleRate/4));t>0&&this.particleSystem.burst(t,i.particleBehavior,s,n)}}this.degradationManager&&this.degradationManager.startMonitoring(),this.ti("started")}return this.Le}stop(){return this.animationController.isAnimating()?(this.Ie.speaking&&this.audioHandler&&this.audioHandler.stopSpeaking(),this.animationController.stop()&&(this.Ie.isRunning=!1,this.isRunning=!1,this.degradationManager&&this.degradationManager.stopMonitoring(),this.ti("stopped")),this.Le):this.Le}update(t){if(this.Ie.speaking&&this.audioLevelProcessor&&this.audioLevelProcessor.isProcessingActive()&&this.audioLevelProcessor.updateAudioLevel(t),"classic"===this.config.renderingStyle){if(this.gazeTracker&&(this.gazeTracker.update(t),"suspicion"===this.stateMachine.getCurrentState().emotion)){const{mousePos:t}=this.gazeTracker,e=this.canvas.width/2,i=this.canvas.height/2,s=Math.sqrt(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)),n=l("suspicion");if(n&&n.visual){const t=Math.min(e,i),r=Math.max(0,Math.min(1,1-s/t));n.visual.threatLevel=r}}if(this.idleBehavior&&this.idleBehavior.update(t),this.gazeTracker&&this.idleBehavior){const t=this.gazeTracker.getGazeOffset(),e=this.idleBehavior.getSwayOffset(),i=this.gazeTracker.getState(),s={offset:{x:t.x+e.x,y:t.y+e.y},proximity:i.proximity,isFocused:i.isFocused};this.renderer&&this.renderer.setGazeData&&this.renderer.setGazeData(s)}}if(this.pluginSystem){const e=this.stateMachine.getCurrentState();this.pluginSystem.update(t,e)}}destroy(){this.stop()}}class Ma{constructor(t){if(!t.errorBoundary)throw new Error("ExecutionLifecycleManager: errorBoundary required");if(!t.animationController)throw new Error("ExecutionLifecycleManager: animationController required");if(!t.visualizationRunner)throw new Error("ExecutionLifecycleManager: visualizationRunner required");if(!t.state)throw new Error("ExecutionLifecycleManager: state required");if(!t.emit)throw new Error("ExecutionLifecycleManager: emit required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.visualizationRunner=t.visualizationRunner,this.soundSystem=t.soundSystem||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}start(){return this.errorBoundary.wrap(()=>this.visualizationRunner.start(),"start",this.Le)()}stop(){return this.errorBoundary.wrap(()=>this.visualizationRunner.stop(),"stop",this.Le)()}pause(){return this.errorBoundary.wrap(()=>this.animationController.isAnimating()?(this.animationController.stop(),this.Ie.isRunning=!1,this.soundSystem&&this.soundSystem.isAvailable()&&this.soundSystem.stopAmbientTone(200),this.ti("paused"),this.Le):this.Le,"pause",this.Le)()}resume(){return this.errorBoundary.wrap(()=>(this.animationController.isAnimating()||(this.animationController.start(),this.Ie.isRunning=!0,this.ti("resumed")),this.Le),"resume",this.Le)()}isActive(){return this.animationController.isAnimating()}}class ba{constructor(t){if(!t.errorBoundary)throw new Error("AnimationFrameController: errorBoundary required");if(!t.animationController)throw new Error("AnimationFrameController: animationController required");if(!t.config)throw new Error("AnimationFrameController: config required");if(!t.emit)throw new Error("AnimationFrameController: emit required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.positionController=t.positionController||null,this.config=t.config,this.ti=t.emit,this.Le=t.chainTarget||this}setTargetFPS(t){const e=Math.max(15,Math.min(120,t));return this.config.targetFPS=e,this.animationController.setTargetFPS(e),this.ti("targetFPSChanged",{targetFPS:e}),this.Le}getTargetFPS(){return this.animationController.targetFPS}setPosition(t,e,i=0){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.setOffset(t,e,i)),this.Le}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){return this.positionController&&(this.positionController.onUpdate||(this.positionController.onUpdate=()=>{}),this.positionController.animateOffset(t,e,i,s,n)),this.Le}getPosition(){return this.errorBoundary.wrap(()=>{if(!this.positionController||"function"!=typeof this.positionController.getPosition)return null;const t="undefined"!=typeof window,e=t?window.innerWidth/2:0,i=t?window.innerHeight/2:0;return this.positionController.getPosition(e,i)},"get-position",this.Le)()}}class wa{constructor(t){if(!t.errorBoundary)throw new Error("ShapeTransformManager: errorBoundary required");if(!t.emit)throw new Error("ShapeTransformManager: emit required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.shapeMorpher=t.shapeMorpher||null,this.ti=t.emit,this.Le=t.chainTarget||this}morphTo(t,e={}){return this.errorBoundary.wrap(()=>this.shapeMorpher?(this.shapeMorpher.morphTo(t,e),this.renderer&&(this.renderer.shapeMorpher=this.shapeMorpher),this.ti("shapeMorphStarted",{from:this.shapeMorpher.currentShape,to:t}),this.Le):this.Le,"morphTo",this.Le)()}setBackdrop(t={}){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.backdropRenderer&&this.renderer.backdropRenderer.setConfig(t),this.Le),"setBackdrop",this.Le)()}getBackdrop(){return this.errorBoundary.wrap(()=>this.renderer&&this.renderer.backdropRenderer?this.renderer.backdropRenderer.getConfig():null,"getBackdrop",this.Le)()}}class va{constructor(t){if(!t.errorBoundary)throw new Error("EventListenerManager: errorBoundary required");if(!t.eventManager)throw new Error("EventListenerManager: eventManager required");this.errorBoundary=t.errorBoundary,this.eventManager=t.eventManager,this.Le=t.chainTarget||this}on(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.on(t,e),this.Le),"event-listener-add",this.Le)()}off(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.off(t,e),this.Le),"event-listener-remove",this.Le)()}once(t,e){return this.errorBoundary.wrap(()=>(this.eventManager.once(t,e),this.Le),"event-listener-once",this.Le)()}removeAllListeners(t=null){return this.errorBoundary.wrap(()=>(this.eventManager.removeAllListeners(t),this.Le),"event-listeners-clear",this.Le)()}listenerCount(t){return this.eventManager.listenerCount(t)}getEventNames(){return this.eventManager.getEventNames()}getEventStats(){return this.eventManager.getEventStats()}getEventDebugInfo(){return this.eventManager.getDebugInfo()}emit(t,e=null){this.eventManager.emit(t,e)}}class Sa{constructor(t){if(!t.tts)throw new Error("TTSManager: tts required");if(!t.state)throw new Error("TTSManager: state required");this.speechManager=t.speechManager||null,this.renderer=t.renderer||null,this.tts=t.tts,this.Ie=t.state,this.Le=t.chainTarget||this}getTTSVoices(){return this.tts.available?window.speechSynthesis.getVoices():[]}isTTSSpeaking(){return this.tts.speaking}speak(t,e={}){return this.speechManager?this.speechManager.speak(t,e):this.Le}setTTSSpeaking(t){this.Ie.ttsSpeaking=t,this.renderer&&this.renderer.startSpeaking&&(t?this.renderer.startSpeaking():this.renderer.stopSpeaking()),this.Ie.speaking=t}getVoices(){return window.speechSynthesis?window.speechSynthesis.getVoices():[]}stopTTS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),this.setTTSSpeaking(!1))}}class ka{constructor(t){if(!t.errorBoundary)throw new Error("SpeechReactivityManager: errorBoundary required");if(!t.audioLevelProcessor)throw new Error("SpeechReactivityManager: audioLevelProcessor required");if(!t.state)throw new Error("SpeechReactivityManager: state required");if(!t.emit)throw new Error("SpeechReactivityManager: emit required");this.errorBoundary=t.errorBoundary,this.audioLevelProcessor=t.audioLevelProcessor,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}connectAudioSource(t){return this.errorBoundary.wrap(()=>this.Ie.audioAnalyser&&t&&"function"==typeof t.connect?(t.connect(this.Ie.audioAnalyser),this.ti("audioSourceConnected",{audioSource:t}),this.Le):this.Le,"audio-source-connection",this.Le)()}getAudioLevel(){return this.Ie.speaking?this.Ie.audioLevel:0}isSpeaking(){return this.Ie.speaking}setAudioSmoothing(t){return this.errorBoundary.wrap(()=>{const e=Math.max(0,Math.min(1,t));return this.Ie.audioAnalyser&&(this.Ie.audioAnalyser.smoothingTimeConstant=e),this.Le},"audio-smoothing",this.Le)()}getAudioStats(){return this.audioLevelProcessor.getStats()}updateAudioConfig(t){this.audioLevelProcessor.updateConfig(t)}}class xa{constructor(t){if(!t.emit)throw new Error("CanvasResizeManager: emit required");this.renderer=t.renderer||null,this.stateMachine=t.stateMachine||null,this.particleSystem=t.particleSystem||null,this.ti=t.emit,this.Le=t.chainTarget||this}handleResize(t,e,i){if(this.renderer&&this.renderer.initOffscreenCanvas&&this.renderer.initOffscreenCanvas(),this.stateMachine){const{currentEmotion:t}=this.stateMachine,{currentUndertone:e}=this.stateMachine;t&&this.stateMachine.setEmotion(t),e&&"none"!==e&&this.stateMachine.setUndertone(e)}this.ti("resize",{width:t,height:e,dpr:i})}clearParticles(){return this.particleSystem&&this.particleSystem.clear(),this.Le}setParticleSystemCanvasDimensions(t,e){return this.particleSystem&&(this.particleSystem.canvasWidth=t,this.particleSystem.canvasHeight=e),this.Le}}class Ea{constructor(t){if(!t.errorBoundary)throw new Error("OffsetPositionManager: errorBoundary required");if(!t.positionController)throw new Error("OffsetPositionManager: positionController required");this.errorBoundary=t.errorBoundary,this.positionController=t.positionController,this.Le=t.chainTarget||this}setOffset(t,e,i=0){return this.errorBoundary.wrap(()=>(this.positionController.setOffset(t,e,i),this.Le),"offset-setting",this.Le)()}getOffset(){return this.errorBoundary.wrap(()=>this.positionController.getOffset(),"offset-getting",this.Le)()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.errorBoundary.wrap(()=>(this.positionController.animateOffset(t,e,i,s,n),this.Le),"offset-animation",this.Le)()}}class Ba{constructor(t){if(!t.canvasResizeManager)throw new Error("VisualTransformationManager: canvasResizeManager required");if(!t.offsetPositionManager)throw new Error("VisualTransformationManager: offsetPositionManager required");if(!t.shapeTransformManager)throw new Error("VisualTransformationManager: shapeTransformManager required");this.canvasResizeManager=t.canvasResizeManager,this.offsetPositionManager=t.offsetPositionManager,this.shapeTransformManager=t.shapeTransformManager,this.Le=t.chainTarget||this}setOffset(t,e,i=0){return this.offsetPositionManager.setOffset(t,e,i)}getOffset(){return this.offsetPositionManager.getOffset()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.offsetPositionManager.animateOffset(t,e,i,s,n)}morphTo(t,e={}){return this.shapeTransformManager.morphTo(t,e)}setBackdrop(t={}){return this.shapeTransformManager.setBackdrop(t)}getBackdrop(){return this.shapeTransformManager.getBackdrop()}handleResize(t,e,i){this.canvasResizeManager.handleResize(t,e,i)}clearParticles(){return this.canvasResizeManager.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.canvasResizeManager.setParticleSystemCanvasDimensions(t,e)}}class Aa{constructor(t){if(!t.errorBoundary)throw new Error("FrustrationContextManager: errorBoundary required");if(!t.contextManager)throw new Error("FrustrationContextManager: contextManager required");this.errorBoundary=t.errorBoundary,this.contextManager=t.contextManager,this.Le=t.chainTarget||this}updateContext(t){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.update(t),this.Le):this.Le,"context-update",this.Le)()}incrementFrustration(t=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.incrementFrustration(t),this.Le):this.Le,"frustration-increment",this.Le)()}decrementFrustration(t=10){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.decrementFrustration(t),this.Le):this.Le,"frustration-decrement",this.Le)()}resetFrustration(){return this.errorBoundary.wrap(()=>this.contextManager?(this.contextManager.resetFrustration(),this.Le):this.Le,"frustration-reset",this.Le)()}}class Ca{constructor(t,e={}){if(!t)throw new Error("LLMResponseHandler requires a mascot instance");this.mascot=t,this.config={autoMorphShapes:!0,morphDuration:1e3,autoExpressGestures:!0,gestureTiming:300,gestureIntensity:.7,useFallbackGestures:!0,useSemanticPerformances:!0,enableContextTracking:!0,emotionToShapeMap:{},actionToGestureMap:{},...e},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(t,e={}){try{e.skipValidation||this.validateResponse(t);const{emotion:i="neutral",sentiment:s="neutral",action:n="none",shape:r,gesture:a,frustrationLevel:o=0}=t,h=void 0!==e.intensity?e.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 t=this.semanticActionMap[n];try{return await this.mascot.perform(t,{context:{frustration:o,sentiment:s,urgency:o>60?"high":o>30?"medium":"low"},intensity:h}),r&&this.config.autoMorphShapes&&await this.morphToShape(r),this.mascot}catch(t){}}return await this.choreographResponse(i,n,r,a,h),this.mascot}catch(t){return this.mascot}}async choreographResponse(t,e,i,s,n){if(this.mascot.setEmotion(t,n),this.config.autoMorphShapes){const s=i||this.getShapeForEmotion(t,e);s&&await this.morphToShape(s)}if(this.config.autoExpressGestures){const t=s||this.getGestureForAction(e);t&&(await this.delay(this.config.gestureTiming),this.mascot.express(t,{intensity:this.config.gestureIntensity}))}}calculateIntensity(t,e){let i=.5;return i+=t/100*.3,"positive"===e?i+=.2:"negative"===e&&(i+=.3),Math.max(.3,Math.min(1,i))}getShapeForEmotion(t,e){return this.config.emotionToShapeMap[t]?this.config.emotionToShapeMap[t]:"celebrate"===e?"star":"greet"===e?"sun":this.defaultShapeMap[t]||null}getGestureForAction(t){return this.config.useFallbackGestures?this.config.actionToGestureMap[t]?this.config.actionToGestureMap[t]:this.defaultGestureMap[t]||null:null}morphToShape(t){t&&"circle"!==t&&this.mascot.morphTo&&this.mascot.morphTo(t,{duration:this.config.morphDuration})}validateResponse(t){if(!t||"object"!=typeof t)throw new Error("LLM response must be an object");if(t.emotion&&this.schema.emotion.includes(t.emotion),t.sentiment&&this.schema.sentiment.includes(t.sentiment),t.action&&this.schema.action.includes(t.action),t.shape&&this.schema.shape.includes(t.shape),t.gesture&&this.schema.gesture.includes(t.gesture),void 0!==t.frustrationLevel){const e=Number(t.frustrationLevel);isNaN(e)}}getSchema(){return{...this.schema}}configure(t){return Object.assign(this.config,t),this}delay(t){return new Promise(e=>setTimeout(e,t))}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 Ta{constructor(t){if(!t.errorBoundary)throw new Error("LLMIntegrationBridge: errorBoundary required");this.errorBoundary=t.errorBoundary,this.ui=t.mascotRef,this.Le=t.chainTarget||this,this.di=null}pi(t={}){return this.di||(this.di=new Ca(this.ui,t)),this.di}handleLLMResponse(t,e={}){return this.errorBoundary.wrap(async()=>{const i=this.pi(e);return await i.handle(t,e),this.Le},"handleLLMResponse",this.Le)()}configureLLMHandler(t){return this.errorBoundary.wrap(()=>(this.pi(t).configure(t),this.Le),"configureLLMHandler",this.Le)()}getLLMResponseSchema(){return this.pi().getSchema()}static getLLMPromptTemplate(t={}){return function(t={}){const{domain:e="general assistance",personality:i="friendly, empathetic, and helpful",brand:s="our service",customEmotions:n=[],customActions:r=[]}=t,a=["offer_help","celebrate","guide","reassure","greet","confirm","deny","emphasize","question","think","listen","respond",...r];return`You are a ${i} AI assistant for ${s}, providing ${e}. 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": "${a.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 ${e} 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.`}(t)}static getLLMEmotions(){return Ca.getAvailableEmotions()}static getLLMActions(){return Ca.getAvailableActions()}static getLLMShapes(){return Ca.getAvailableShapes()}static getLLMGestures(){return Ca.getAvailableGestures()}}class Pa{constructor(t){if(!t.errorBoundary)throw new Error("DiagnosticsManager: errorBoundary required");if(!t.animationController)throw new Error("DiagnosticsManager: animationController required");if(!t.stateMachine)throw new Error("DiagnosticsManager: stateMachine required");if(!t.config)throw new Error("DiagnosticsManager: config required");if(!t.state)throw new Error("DiagnosticsManager: state required");if(!t.getCurrentState)throw new Error("DiagnosticsManager: getCurrentState required");if(!t.getAudioStats)throw new Error("DiagnosticsManager: getAudioStats required");if(!t.getEventStats)throw new Error("DiagnosticsManager: getEventStats required");this.errorBoundary=t.errorBoundary,this.degradationManager=t.degradationManager||null,this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.performanceSystem=t.performanceSystem||null,this.config=t.config,this.Ie=t.state,this.mi=t.getCurrentState,this.gi=t.getAudioStats,this.fi=t.getEventStats,this.Le=t.chainTarget||this}getBrowserCompatibility(){return{browser:Ur.browser,features:Ur.featureDetection.getFeatures(),capabilities:Ur.capabilities,appliedPolyfills:Ur.appliedPolyfills,optimizations:Ur.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(t){return!!this.degradationManager&&this.degradationManager.setLevel(t)}getDebugReport(){const t={timestamp:Date.now(),mascot:{isRunning:this.Ie.isRunning,speaking:this.Ie.speaking,debugMode:this.Ie.debugMode,config:this.config},currentState:this.mi(),performanceMetrics:this.getPerformanceMetrics(),audioStats:this.gi(),eventStats:this.fi(),browserCompatibility:this.getBrowserCompatibility(),degradationStatus:this.getDegradationStatus(),runtimeCapabilities:Ss.generateReport(),debuggerReport:vs.getDebugReport()};return this.Ie.debugMode&&vs.log("DEBUG","Generated debug report",{reportSize:JSON.stringify(t).length,sections:Object.keys(t)}),t}exportDebugData(){const t={metadata:{exportTime:Date.now(),version:"1.0.0",userAgent:navigator.userAgent,url:window.location?.href},mascotState:{config:this.config,currentState:this.mi(),isRunning:this.Ie.isRunning,speaking:this.Ie.speaking},performance:{metrics:this.getPerformanceMetrics(),degradationStatus:this.getDegradationStatus(),frameTimings:vs.frameTimings},compatibility:{browser:this.getBrowserCompatibility(),runtimeCapabilities:Ss.generateReport()},debuggerData:vs.exportDebugData()};return this.Ie.debugMode&&vs.log("INFO","Exported debug data",{dataSize:JSON.stringify(t).length}),t}getPerformanceMetrics(){const t=this.animationController.getPerformanceMetrics(),e=this.stateMachine.getCurrentState();return{...t,currentEmotion:e.emotion,currentUndertone:e.undertone,isTransitioning:e.isTransitioning,errorStats:this.errorBoundary.getErrorStats()}}getPerformanceAnalytics(){return this.errorBoundary.wrap(()=>this.performanceSystem?this.performanceSystem.getAnalytics():null,"performance-analytics",this.Le)()}}class Da{constructor(t){if(!t.errorBoundary)throw new Error("EmotionalStateQueryManager: errorBoundary required");if(!t.stateMachine)throw new Error("EmotionalStateQueryManager: stateMachine required");this.errorBoundary=t.errorBoundary,this.stateMachine=t.stateMachine,this.contextManager=t.contextManager||null,this.performanceSystem=t.performanceSystem||null,this.Le=t.chainTarget||this}getEmotionalColor(){const t=this.stateMachine.getCurrentEmotionalProperties();return t?.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.Le)()}getAvailableShapes(){return ea.getAvailableShapes()}getContext(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getContext():null,"context-get",this.Le)()}getContextAnalytics(){return this.errorBoundary.wrap(()=>this.contextManager?this.contextManager.getAnalytics():null,"context-analytics",this.Le)()}}class Ra{constructor(t){if(!t.diagnosticsManager)throw new Error("DebugProfilingManager: diagnosticsManager required");this.diagnosticsManager=t.diagnosticsManager,this.Ie=t.state||{debugMode:!1}}getDebugReport(){return this.diagnosticsManager.getDebugReport()}exportDebugData(){return this.diagnosticsManager.exportDebugData()}startProfiling(t,e={}){this.Ie.debugMode&&vs.startProfile(t,e)}endProfiling(t){return this.Ie.debugMode?vs.endProfile(t):null}takeMemorySnapshot(t){this.Ie.debugMode&&vs.takeMemorySnapshot(t)}clearDebugData(){vs.clear(),this.Ie.debugMode&&vs.log("INFO","Debug data cleared")}getRuntimeCapabilities(){return Ss.generateReport()}}class Fa{constructor(t){if(!t.errorBoundary)throw new Error("PerformanceBehaviorManager: errorBoundary required");if(!t.frustrationContextManager)throw new Error("PerformanceBehaviorManager: frustrationContextManager required");if(!t.emotionalStateQueryManager)throw new Error("PerformanceBehaviorManager: emotionalStateQueryManager required");if(!t.diagnosticsManager)throw new Error("PerformanceBehaviorManager: diagnosticsManager required");this.errorBoundary=t.errorBoundary,this.performanceSystem=t.performanceSystem||null,this.frustrationContextManager=t.frustrationContextManager,this.emotionalStateQueryManager=t.emotionalStateQueryManager,this.diagnosticsManager=t.diagnosticsManager,this.Le=t.chainTarget||this}perform(t,e={}){return this.errorBoundary.wrap(async()=>this.performanceSystem?(e.context&&this.frustrationContextManager.updateContext(e.context),await this.performanceSystem.perform(t,{...e,mascot:this.Le}),this.Le):this.Le,"semantic-performance",this.Le)()}registerPerformance(t,e){return this.errorBoundary.wrap(()=>this.performanceSystem?(this.performanceSystem.registerPerformance(t,e),this.Le):this.Le,"performance-register",this.Le)()}getAvailablePerformances(){return this.emotionalStateQueryManager.getAvailablePerformances()}getPerformanceAnalytics(){return this.diagnosticsManager.getPerformanceAnalytics()}getContextAnalytics(){return this.emotionalStateQueryManager.getContextAnalytics()}}class za{constructor(t){if(!t.diagnosticsManager)throw new Error("PerformanceMonitoringManager: diagnosticsManager required");if(!t.animationFrameController)throw new Error("PerformanceMonitoringManager: animationFrameController required");if(!t.animationController)throw new Error("PerformanceMonitoringManager: animationController required");if(!t.particleSystem)throw new Error("PerformanceMonitoringManager: particleSystem required");if(!t.config)throw new Error("PerformanceMonitoringManager: config required");this.diagnosticsManager=t.diagnosticsManager,this.degradationManager=t.degradationManager||null,this.animationFrameController=t.animationFrameController,this.animationController=t.animationController,this.particleSystem=t.particleSystem,this.healthCheckManager=t.healthCheckManager,this.config=t.config,this.Le=t.chainTarget||this}getDegradationStatus(){return this.diagnosticsManager.getDegradationStatus()}setDegradationLevel(t){return this.diagnosticsManager.setDegradationLevel(t)}isFeatureAvailable(t){return this.degradationManager?this.degradationManager.isFeatureAvailable(t):Ur.featureDetection.getFeatures()[t]||!1}setTargetFPS(t){return this.animationFrameController.setTargetFPS(t)}getTargetFPS(){return this.animationFrameController.getTargetFPS()}setPerformanceDegradation(t){const e=this.animationController.getPerformanceMetrics();if(t&&!e.performanceDegradation){const t=this.particleSystem.maxParticles,e=Math.max(5,Math.floor(.5*t));this.particleSystem.setMaxParticles(e)}else!t&&e.performanceDegradation&&this.particleSystem.setMaxParticles(this.config.maxParticles);return this.Le}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}}class qa{constructor(t){if(!t.errorBoundary)throw new Error("HealthCheckManager: errorBoundary required");if(!t.diagnosticsManager)throw new Error("HealthCheckManager: diagnosticsManager required");if(!t.mobileOptimization)throw new Error("HealthCheckManager: mobileOptimization required");if(!t.accessibilityManager)throw new Error("HealthCheckManager: accessibilityManager required");if(!t.config)throw new Error("HealthCheckManager: config required");this.errorBoundary=t.errorBoundary,this.systemStatusReporter=t.systemStatusReporter||null,this.diagnosticsManager=t.diagnosticsManager,this.mobileOptimization=t.mobileOptimization,this.accessibilityManager=t.accessibilityManager,this.config=t.config,this.Le=t.chainTarget||this}getSystemStatus(){return this.systemStatusReporter?this.systemStatusReporter.getSystemStatus():{}}setDebugMode(t){return this.config.showDebug=!!t,this.config.showFPS=!!t,this.Le}triggerTestError(t="manual-test"){return this.errorBoundary.wrap(()=>{throw new Error(`Test error triggered in context: ${t}`)},t,this.Le)()}getPerformanceMetrics(){return this.diagnosticsManager.getPerformanceMetrics()}getMobileStatus(){return this.mobileOptimization.getStatus()}getAccessibilityStatus(){return this.accessibilityManager.getStatus()}}class Oa{constructor(t){this.mascot=t}initialize(t){const e=this.mascot;this.yi(e,t),this.Mi(e,t),this.bi(e,t),e.audioHandler.init(),e.stateCoordinator.init(),e.visualizationRunner.init()}yi(t,e){t.audioHandler=new pa({audioAnalyzer:t.audioAnalyzer,audioLevelProcessor:t.audioLevelProcessor,shapeMorpher:t.shapeMorpher,soundSystem:t.soundSystem,renderer:t.renderer,errorBoundary:t.errorBoundary,config:t.config,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get audioLevel(){return t.audioLevel},set audioLevel(e){t.audioLevel=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.stateCoordinator=new fa({stateMachine:t.stateMachine,particleSystem:t.particleSystem,canvasManager:t.canvasManager,renderer:t.renderer,soundSystem:t.soundSystem,config:t.config,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.visualizationRunner=new ya({animationController:t.animationController,stateMachine:t.stateMachine,particleSystem:t.particleSystem,canvasManager:t.canvasManager,renderer:t.renderer,audioHandler:t.audioHandler,audioLevelProcessor:t.audioLevelProcessor,gazeTracker:t.gazeTracker,idleBehavior:t.idleBehavior,degradationManager:t.degradationManager,pluginSystem:t.pluginSystem,config:t.config,canvas:t.canvas,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get isRunning(){return t.isRunning},set isRunning(e){t.isRunning=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.executionLifecycleManager=new Ma({animationController:t.animationController,visualizationRunner:t.visualizationRunner,idleBehavior:t.idleBehavior,gazeTracker:t.gazeTracker,renderer:t.renderer,errorBoundary:t.errorBoundary,state:{get isRunning(){return t.isRunning},set isRunning(e){t.isRunning=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.animationFrameController=new ba({animationController:t.animationController,positionController:t.positionController,config:t.config,errorBoundary:t.errorBoundary,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.shapeTransformManager=new wa({shapeMorpher:t.shapeMorpher,renderer:t.renderer,errorBoundary:t.errorBoundary,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.eventListenerManager=new va({eventManager:t.eventManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.ttsManager=new Sa({soundSystem:t.soundSystem,errorBoundary:t.errorBoundary,config:t.config,tts:t.tts,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.speechReactivityManager=new ka({audioLevelProcessor:t.audioLevelProcessor,renderer:t.renderer,errorBoundary:t.errorBoundary,config:t.config,state:{get speaking(){return t.speaking},set speaking(e){t.speaking=e},get audioLevel(){return t.audioLevel},set audioLevel(e){t.audioLevel=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.canvasResizeManager=new xa({renderer:t.renderer,stateMachine:t.stateMachine,particleSystem:t.particleSystem,emit:(e,i)=>t.emit(e,i),chainTarget:t}),t.offsetPositionManager=new Ea({positionController:t.positionController,errorBoundary:t.errorBoundary,chainTarget:t}),t.visualTransformationManager=new Ba({canvasResizeManager:t.canvasResizeManager,offsetPositionManager:t.offsetPositionManager,shapeTransformManager:t.shapeTransformManager,chainTarget:t}),t.frustrationContextManager=new Aa({contextManager:t.contextManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.llmIntegrationBridge=new Ta({stateMachine:t.stateMachine,gestureController:t.gestureController,errorBoundary:t.errorBoundary,state:{get llmHandler(){return t.llmHandler},set llmHandler(e){t.llmHandler=e}},emit:(e,i)=>t.emit(e,i),chainTarget:t})}Mi(t,e){t.diagnosticsManager=new Pa({errorBoundary:t.errorBoundary,degradationManager:t.degradationManager,animationController:t.animationController,stateMachine:t.stateMachine,performanceSystem:t.performanceSystem,config:t.config,state:{get isRunning(){return t.isRunning},get speaking(){return t.speaking},get debugMode(){return t.debugMode}},getCurrentState:()=>t.getCurrentState(),getAudioStats:()=>t.getAudioStats(),getEventStats:()=>t.getEventStats(),chainTarget:t}),t.emotionalStateQueryManager=new Da({stateMachine:t.stateMachine,performanceSystem:t.performanceSystem,contextManager:t.contextManager,errorBoundary:t.errorBoundary,chainTarget:t}),t.debugProfilingManager=new Ra({diagnosticsManager:t.diagnosticsManager,errorBoundary:t.errorBoundary,state:{get debugMode(){return t.debugMode},set debugMode(e){t.debugMode=e}},chainTarget:t})}bi(t,e){t.performanceBehaviorManager=new Fa({errorBoundary:t.errorBoundary,performanceSystem:t.performanceSystem,frustrationContextManager:t.frustrationContextManager,emotionalStateQueryManager:t.emotionalStateQueryManager,diagnosticsManager:t.diagnosticsManager,chainTarget:t}),t.healthCheckManager=new qa({errorBoundary:t.errorBoundary,systemStatusReporter:t.systemStatusReporter,diagnosticsManager:t.diagnosticsManager,mobileOptimization:t.mobileOptimization,accessibilityManager:t.accessibilityManager,config:t.config,chainTarget:t}),t.performanceMonitoringManager=new za({diagnosticsManager:t.diagnosticsManager,degradationManager:t.degradationManager,animationFrameController:t.animationFrameController,animationController:t.animationController,particleSystem:t.particleSystem,healthCheckManager:t.healthCheckManager,config:t.config,chainTarget:t})}}class ja{constructor(t,e={}){this.mascot=t,this.userConfig=e}initialize(){this.initializeStateManager();const t=this.initializeConfiguration();return this.initializeCanvas(t),this.initializeCoreSystems(t),this.initializeAudioSystems(t),this.initializeInteractionSystems(t),this.initializeOptimizationSystems(t),this.initializeAnimationController(t),this.initializePerformanceSystems(t),this.initializeModularHandlers(t),this.finalizeInitialization(t),t}initializeStateManager(){this.mascot.stateManager=new da({initialState:{debugMode:this.userConfig.enableDebug||!1},emit:(t,e)=>this.mascot.emit(t,e)}),this.wi()}initializeConfiguration(){const t=Ur.browserOptimizations.getOptimizations(),e={canvasId:"emotive-mascot",targetFPS:60,enableAudio:Ur.featureDetection.features.webAudio,soundEnabled:!1,masterVolume:.5,maxParticles:t.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=e,e}initializeCanvas(t){if(this.mascot.canvas="string"==typeof t.canvasId?document.getElementById(t.canvasId):t.canvasId,!this.mascot.canvas)throw new Error(`Canvas with ID '${t.canvasId}' not found`);this.mascot.canvas.setAttribute("role","img"),this.mascot.canvas.setAttribute("aria-label","Animated emotional mascot visualization"),this.mascot.canvasManager=new ks(this.mascot.canvas),this.mascot.positionController=new Er({offsetX:t.offsetX,offsetY:t.offsetY,offsetZ:t.offsetZ,onUpdate:t=>{this.mascot.renderer&&this.mascot.renderer.updateEffectiveCenter(t)}}),t.renderSize&&t.renderSize.width&&t.renderSize.height&&this.mascot.canvasManager.setRenderSize(t.renderSize.width,t.renderSize.height),this.mascot.contextRecovery=new Lr(this.mascot.canvas),this.mascot.contextRecovery.onRecovery(t=>{this.mascot.renderer&&this.mascot.renderer.handleContextRecovery(t)}),Ur.browserOptimizations.applyCanvasOptimizations(this.mascot.canvas,this.mascot.canvasManager.getContext())}initializeCoreSystems(t){this.mascot.stateMachine=new Ws(this.mascot.errorBoundary),this.mascot.particleSystem=new en(t.maxParticles,this.mascot.errorBoundary),this.mascot.particleSystem.canvasWidth=this.mascot.canvasManager.width,this.mascot.particleSystem.canvasHeight=this.mascot.canvasManager.height,this.mascot.renderer=new hr(this.mascot.canvasManager,{...t.classicConfig,topOffset:t.topOffset||0,positionController:this.mascot.positionController}),this.mascot.renderer.stateMachine=this.mascot.stateMachine,this.mascot.stateMachine.renderer=this.mascot.renderer}initializeAudioSystems(t){this.mascot.shapeMorpher=new ea,this.mascot.audioAnalyzer=new ia,this.mascot.grooveTemplates=new aa,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 Cr,this.mascot.tts={available:"undefined"!=typeof window&&"speechSynthesis"in window,speaking:!1,currentUtterance:null};const e=this.mascot;this.mascot.gestureController=new ua({errorBoundary:e.errorBoundary,renderer:e.renderer,soundSystem:e.soundSystem,config:e.config,state:{get currentModularGesture(){return e.currentModularGesture},set currentModularGesture(t){e.currentModularGesture=t}},throttledWarn:e.throttledWarn,chainTarget:e}),this.mascot.gestureController.gestureCompatibility=na,this.mascot.gestureController.init(),this.mascot.audioLevelProcessor=new Dr({spikeThreshold:t.spikeThreshold||1.5,minimumSpikeLevel:t.minimumSpikeLevel||.1,spikeMinInterval:t.spikeMinInterval||1e3})}initializeInteractionSystems(t){t.enableGazeTracking&&(this.mascot.gazeTracker=new lr(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()})),t.enableIdleBehaviors&&(this.mascot.idleBehavior=new cr({enabled:!0,sleepTimeout:1/0}),this.mascot.idleBehavior.setCallback("onBlink",t=>{this.mascot.renderer&&this.mascot.renderer.state&&(this.mascot.renderer.state.blinking="start"===t.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(t){this.mascot.degradationManager=null,this.mascot.accessibilityManager=new Rr({enableReducedMotion:!1!==t.enableReducedMotion,enableHighContrast:!1!==t.enableHighContrast,enableScreenReaderSupport:!1!==t.enableScreenReaderSupport,enableKeyboardNavigation:!1!==t.enableKeyboardNavigation,colorBlindMode:t.colorBlindMode||"none"}),this.mascot.mobileOptimization=new Fr({enableTouchOptimization:!1!==t.enableTouchOptimization,enableViewportHandling:!1!==t.enableViewportHandling,enableBatteryOptimization:!1!==t.enableBatteryOptimization}),this.mascot.mobileOptimization.setCanvas(this.mascot.canvas),this.mascot.pluginSystem=new zr({mascot:this.mascot,enablePlugins:!1!==t.enablePlugins,validatePlugins:!1!==t.validatePlugins,sandboxPlugins:!1!==t.sandboxPlugins})}initializeAnimationController(t){try{this.mascot.animationController=new Pr(this.mascot.errorBoundary,{targetFPS:t.targetFPS})}catch(e){this.mascot.animationController=this.createFallbackAnimationController(t.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((t,e)=>{this.mascot.emit(t,e)}),this.mascot.animationController.setParentMascot(this.mascot),this.mascot.isRunning=!1}createFallbackAnimationController(t){return{isAnimating:()=>this.mascot.isRunning,start:()=>(this.mascot.isRunning=!0,!0),stop:()=>(this.mascot.isRunning=!1,!0),setTargetFPS:()=>{},targetFPS:t,getPerformanceMetrics:()=>({fps:0,isRunning:this.mascot.isRunning,performanceDegradation:!1,deltaTime:16,frameCount:0,targetFPS:t}),setSubsystems:()=>{},setEventCallback:()=>{},setParentMascot:()=>{},destroy:()=>{},deltaTime:16}}initializePerformanceSystems(t){this.mascot.contextManager=new la({enableHistory:!1!==t.enablePerformanceHistory,enableDecay:!1!==t.enableFrustrationDecay,historyLimit:t.performanceHistoryLimit||50,frustrationDecayRate:t.frustrationDecayRate||5,decayInterval:t.frustrationDecayInterval||1e4}),this.mascot.destructionManager&&(this.mascot.destructionManager.contextManager=this.mascot.contextManager),this.mascot.sequenceExecutor=new ca({mascot:this.mascot,eventManager:this.mascot.eventManager,allowConcurrent:!1!==t.allowConcurrentPerformances}),this.mascot.performanceSystem=new ha({mascot:this.mascot,contextManager:this.mascot.contextManager,sequenceExecutor:this.mascot.sequenceExecutor,eventManager:this.mascot.eventManager,enableAnalytics:!1!==t.enablePerformanceAnalytics})}initializeModularHandlers(t){new Oa(this.mascot).initialize(t);const e=this.mascot.destructionManager;e&&(e.gestureController=this.mascot.gestureController,e.stateCoordinator=this.mascot.stateCoordinator,e.visualizationRunner=this.mascot.visualizationRunner,e.audioHandler=this.mascot.audioHandler)}finalizeInitialization(t){t.enableAudio&&this.mascot.soundSystem.initialize().then(e=>{e&&this.mascot.soundSystem.setMasterVolume(t.masterVolume)}).catch(t=>{}),Qs.initialize(),this.mascot.rhythmIntegration=Qs,this.mascot.debugMode&&(vs.log("INFO","Debug mode enabled for EmotiveMascot",{config:t,runtimeCapabilities:Ss.generateReport()}),vs.startProfile("mascot-initialization",{canvasId:t.canvasId,maxParticles:t.maxParticles})),this.mascot.setupAudioLevelProcessorCallbacks(),this.mascot.stateMachine.setEmotion(t.defaultEmotion),this.mascot.canvasManager.onResize((t,e,i)=>{this.mascot.handleResize(t,e,i)}),this.mascot.stateManager.debugMode&&(vs.endProfile("mascot-initialization"),vs.takeMemorySnapshot("post-initialization"))}wi(){const t=this.mascot,e=t.stateManager;Object.defineProperties(t,{speaking:{get:()=>e.speaking,set(t){e.speaking=t},enumerable:!0,configurable:!0},recording:{get:()=>e.recording,set(t){e.recording=t},enumerable:!0,configurable:!0},sleeping:{get:()=>e.sleeping,set(t){e.sleeping=t},enumerable:!0,configurable:!0},isRunning:{get:()=>e.isRunning,set(t){e.isRunning=t},enumerable:!0,configurable:!0},debugMode:{get:()=>e.debugMode,set(t){e.debugMode=t},enumerable:!0,configurable:!0},audioLevel:{get:()=>e.audioLevel,set(t){e.audioLevel=t},enumerable:!0,configurable:!0},rhythmEnabled:{get:()=>e.rhythmEnabled,set(t){e.rhythmEnabled=t},enumerable:!0,configurable:!0},currentModularGesture:{get:()=>e.currentModularGesture,set(t){e.currentModularGesture=t},enumerable:!0,configurable:!0},breathePhase:{get:()=>e.breathePhase,set(t){e.breathePhase=t},enumerable:!0,configurable:!0},breatheStartTime:{get:()=>e.breatheStartTime,set(t){e.breatheStartTime=t},enumerable:!0,configurable:!0},orbScale:{get:()=>e.orbScale,set(t){e.orbScale=t},enumerable:!0,configurable:!0},warningTimestamps:{get:()=>e.warningTimestamps,set(t){e.warningTimestamps=t},enumerable:!0,configurable:!0},warningThrottle:{get:()=>e.warningThrottle,set(t){e.warningThrottle=t},enumerable:!0,configurable:!0}})}}class Ia{constructor(t){this.animationController=t.animationController||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.gazeTracker=t.gazeTracker||null,this.particleSystem=t.particleSystem,this.stateMachine=t.stateMachine,this.Ie=t.state||{debugMode:!1,speaking:!1}}buildRenderState(){return{renderStart:this.Ie.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.Ie.speaking,audioLevel:this.audioLevelProcessor?this.audioLevelProcessor.getCurrentLevel():0,gazeOffset:this.getGazeOffset()}}getGazeOffset(){return this.gazeTracker?this.gazeTracker.currentGaze:{x:0,y:0}}}class $a{constructor(t){this.canvasManager=t.canvasManager,this.config=t.config,this.gazeTracker=t.gazeTracker||null}updateThreatLevel(t){if("suspicion"!==t.emotion||!this.gazeTracker)return;const e=l("suspicion");if(!e||!e.visual)return;const i=this.calculateThreatLevel();e.visual.threatLevel=i}calculateThreatLevel(){this.gazeTracker.getState();const{mousePos:t}=this.gazeTracker,e=this.canvasManager.width/2,i=this.canvasManager.height/2-this.config.topOffset,s=this.calculateDistance(t,{x:e,y:i}),n=Math.min(this.canvasManager.width,this.canvasManager.height)/2;return Math.max(0,Math.min(1,1-s/n))}calculateDistance(t,e){return Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2))}}class La{constructor(t){this.renderer=t.renderer,this.stateMachine=t.stateMachine,this.canvasManager=t.canvasManager,this.config=t.config}calculateParticleConfig(t,e){const{orbX:i,orbY:s}=this.calculateOrbPosition(t),{particleBehavior:n,particleRate:r,minParticles:a,maxParticles:o}=this.calculateParticleBehavior(t,e);return{orbX:i,orbY:s,particleBehavior:n,particleRate:r,minParticles:a,maxParticles:o,emotionParams:e}}calculateOrbPosition(t){const e=this.renderer.getEffectiveCenter(),i=e.x;let s=e.y-this.config.topOffset;const n=this.stateMachine.getCurrentEmotionalProperties();return n.verticalOffset&&(s=e.y-this.config.topOffset+this.canvasManager.height*n.verticalOffset),{orbX:i,orbY:s}}calculateParticleBehavior(t,e){let i=e.particleBehavior||"ambient",s=e.particleRate||15;const n=this.stateMachine.getCurrentEmotionalProperties(),r=void 0!==e.minParticles?e.minParticles:n.minParticles||0;let a=void 0!==e.maxParticles?e.maxParticles:n.maxParticles||10;return({particleBehavior:i,particleRate:s,maxParticles:a}=this.applyRendererOverrides(i,s,a)),{particleBehavior:i,particleRate:s,minParticles:r,maxParticles:a}}applyRendererOverrides(t,e,i){return this.renderer.state&&this.renderer.state.particleBehaviorOverride&&(t=this.renderer.state.particleBehaviorOverride),this.renderer.state&&this.renderer.state.particleRateMult&&(e=Math.floor(e*this.renderer.state.particleRateMult),i=Math.floor(i*this.renderer.state.particleRateMult)),{particleBehavior:t,particleRate:e,maxParticles:i}}getParticleModifier(t){return this.renderer.getUndertoneModifier?this.renderer.getUndertoneModifier():null}}class Ga{constructor(t){this.renderer=t.renderer,this.Ie=t.state}getGestureMotion(){let t=null,e=0;const i=this.Ie.currentModularGesture;return i?({gestureMotion:t,gestureProgress:e}=this.processModularGesture(i)):this.renderer&&this.renderer.getCurrentGesture&&({gestureMotion:t,gestureProgress:e}=this.processRendererGesture()),{gestureMotion:t,gestureProgress:e}}processModularGesture(t){const e=performance.now()-t.startTime,i=Math.min(e/t.duration,1),s={type:t.type,amplitude:1,frequency:1,intensity:1};return i>=1&&this.handleGestureCleanup(t),{gestureMotion:s,gestureProgress:i}}handleGestureCleanup(t){t.cleanupPending?this.Ie.currentModularGesture=null:t.cleanupPending=!0}processRendererGesture(){const t=this.renderer.getCurrentGesture();return t&&t.particleMotion?{gestureMotion:t.particleMotion,gestureProgress:t.progress||0}:{gestureMotion:null,gestureProgress:0}}getGestureTransform(){return this.renderer?.gestureAnimator?.applyGestureAnimations()??null}}class _a{constructor(t){this.canvasManager=t.canvasManager,this.config=t.config,this.particleSystem=t.particleSystem,this.pluginSystem=t.pluginSystem||null,this.renderer=t.renderer,this.stateMachine=t.stateMachine,this.Ie=t.state||{debugMode:!1},this.Si=t.renderDebugInfo||(()=>{})}renderAllLayers(t){const{renderState:e,deltaTime:i,emotionParams:s,gestureTransform:n,renderStart:r}=t;this.renderBackgroundParticles(s.glowColor,n),this.renderOrb(e,i,n),this.renderForegroundParticles(s.glowColor,n),this.renderPlugins(),this.renderDebugIfEnabled(i),this.logPerformanceIfDebug(r,i)}renderBackgroundParticles(t,e){this.particleSystem.renderBackground(this.canvasManager.getContext(),t,e)}renderOrb(t,e,i){this.renderer.render(t,e,i)}renderForegroundParticles(t,e){this.particleSystem.renderForeground(this.canvasManager.getContext(),t,e)}renderPlugins(){if(this.pluginSystem){const t=this.stateMachine.getCurrentState();this.pluginSystem.render(this.canvasManager.getContext(),t)}}renderDebugIfEnabled(t){(this.config.showFPS||this.config.showDebug)&&this.Si(t)}logPerformanceIfDebug(t,e){if(!this.Ie.debugMode)return;const i=performance.now()-t;i>16.67&&vs.log("WARN","Slow render frame detected",{renderTime:i,deltaTime:e,particleCount:this.particleSystem.getStats().activeParticles})}}class Ha{constructor(t){this.animationController=t.animationController,this.canvasManager=t.canvasManager,this.config=t.config,this.particleSystem=t.particleSystem,this.stateMachine=t.stateMachine,this.Ie=t.state||{audioLevel:0,currentModularGesture:null,speaking:!1}}renderDebugInfo(t){const e=this.canvasManager.getContext();e.save(),this.setupTextStyle(e);let i=20;this.config.showFPS&&(i=this.renderFPSInfo(e,i,16)),this.config.showDebug&&this.renderDebugDetails(e,i,16),e.restore()}setupTextStyle(t){t.fillStyle="#ffffff",t.font="12px monospace",t.strokeStyle="#000000",t.lineWidth=2}renderFPSInfo(t,e,i){const s=this.animationController.getPerformanceMetrics(),n=s.instantFps||s.fps||0,r=[`FPS: ${n}`,`Frame: ${s.averageFrameTime?s.averageFrameTime.toFixed(1):"0.0"}ms`,`Particles: ${this.particleSystem.getStats().activeParticles}`],{x:a,maxWidth:o}=this.calculateFPSBoxPosition(t,r);return this.drawFPSBackground(t,a,e,o,r.length),this.drawFPSBorder(t,a,e,o,r.length,n),this.drawTextLines(t,r,a,e,i),e+i*r.length}calculateFPSBoxPosition(t,e){let i=0;return e.forEach(e=>{const{width:s}=t.measureText(e);s>i&&(i=s)}),{x:this.canvasManager.width-i-8-10,maxWidth:i}}drawFPSBackground(t,e,i,s,n){t.fillStyle="rgba(0, 0, 0, 0.7)",t.fillRect(e-8,i-14,s+16,18*n+4)}drawFPSBorder(t,e,i,s,n,r){const a=this.getFPSBorderColor(r);t.strokeStyle=a,t.lineWidth=2,t.strokeRect(e-8,i-14,s+16,18*n+4)}getFPSBorderColor(t){return t>=55?"#00ff00":t>=30?"#ffff00":"#ff0000"}drawTextLines(t,e,i,s,n){t.fillStyle="#ffffff",e.forEach((e,r)=>{const a=s+r*n;t.fillText(e,i,a)})}renderDebugDetails(t,e,i){const s=this.stateMachine.getCurrentState(),n=this.particleSystem.getStats(),r=[`Emotion: ${s.emotion}${s.undertone?` (${s.undertone})`:""}`,`Particles: ${n.activeParticles}/${n.maxParticles}`,`Gesture: ${this.Ie.currentModularGesture?this.Ie.currentModularGesture.type:"none"}`,"Speaking: "+(this.Ie.speaking?"yes":"no"),`Audio Level: ${(100*this.Ie.audioLevel).toFixed(1)}%`];t.fillStyle="rgba(0, 0, 0, 0.7)";const a=Math.max(...r.map(e=>t.measureText(e).width));t.fillRect(8,e-14,a+16,r.length*i+4),t.fillStyle="#ffffff";for(const s of r)t.fillText(s,10,e),e+=i}}const Ua=new class{constructor(t={}){this.enabled=!1!==t.enabled,this.maxErrors=t.maxErrors||100,this.maxStackFrames=t.maxStackFrames||10,this.reportingThreshold=t.reportingThreshold||10,this.reportingInterval=t.reportingInterval||6e4,this.errors=[],this.errorCounts=new Map,this.errorPatterns=new Map,this.suppressedErrors=new Set(t.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:t.onError||null,onReport:t.onReport||null,onCritical:t.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=(t,e,i,s,n)=>(this.captureError(n||new Error(t),{source:e,lineno:i,colno:s,uncaught:!0}),!this.originalOnError||this.originalOnError(t,e,i,s,n)),this.originalOnUnhandledRejection=window.onunhandledrejection,window.onunhandledrejection=t=>{const e=t.reason instanceof Error?t.reason:new Error(String(t.reason));if(this.captureError(e,{type:"unhandledRejection",promise:t.promise,uncaught:!0}),this.originalOnUnhandledRejection)return this.originalOnUnhandledRejection(t)})}detachGlobalHandlers(){"undefined"!=typeof window&&(this.originalOnError&&(window.onerror=this.originalOnError),this.originalOnUnhandledRejection&&(window.onunhandledrejection=this.originalOnUnhandledRejection))}captureError(t,e={}){if(!this.enabled)return;if(this.shouldSuppress(t))return;const i=this.processError(t,e);i.category=this.categorizeError(t,e),i.severity=this.determineSeverity(t,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(t,e){const i=Date.now(),s=this.parseStackTrace(t.stack);return{id:`${i}-${Math.random().toString(36).substr(2,9)}`,timestamp:i,name:t.name||"Error",message:t.message||String(t),stack:s.slice(0,this.maxStackFrames),fullStack:t.stack,context:{...e,url:"undefined"!=typeof window?window.location.href:"unknown",userAgent:this.metadata.userAgent,sessionId:this.metadata.sessionId},metadata:this.collectMetadata()}}parseStackTrace(t){if(!t)return[];const e=t.split("\n"),i=[];for(const t of e){const e=t.match(/at\s+(.+?)\s+\((.+?):(\d+):(\d+)\)/);e&&i.push({function:e[1],file:e[2],line:parseInt(e[3],10),column:parseInt(e[4],10)})}return i}categorizeError(t,e){const i=t.message.toLowerCase(),s=t.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"===e.source?this.errorCategories.USER_INPUT:i.includes("performance")||i.includes("memory")?this.errorCategories.PERFORMANCE:this.errorCategories.UNKNOWN}determineSeverity(t,e){return"ReferenceError"===t.name||"TypeError"===t.name?this.severityLevels.CRITICAL:e===this.errorCategories.RENDERING||e===this.errorCategories.ANIMATION?this.severityLevels.HIGH:e===this.errorCategories.NETWORK?this.severityLevels.MEDIUM:this.severityLevels.LOW}shouldSuppress(t){const e=t.message||"";for(const t of this.suppressedErrors){if("string"==typeof t&&e.includes(t))return!0;if(t instanceof RegExp&&t.test(e))return!0}return!1}detectPatterns(t){const e=`${t.category}:${t.severity}`,i=this.errorPatterns.get(e)||{count:0,firstSeen:Date.now(),lastSeen:null};i.count++,i.lastSeen=Date.now(),this.errorPatterns.set(e,i);const s=this.errors.filter(t=>Date.now()-t.timestamp<5e3);s.length>10&&this.handleErrorStorm(s)}handleCriticalError(t){this.callbacks.onCritical&&this.callbacks.onCritical(t),this.sendReport([t],"critical")}handleErrorStorm(t){const e=new Map;for(const i of t){const t=`${i.name}:${i.message}`;e.has(t)||e.set(t,[]),e.get(t).push(i)}this.sendReport(t,"storm")}collectMetadata(){const t={};return"undefined"!=typeof window&&(t.viewport={width:window.innerWidth,height:window.innerHeight},t.screen={width:window.screen.width,height:window.screen.height,pixelRatio:window.devicePixelRatio},performance.memory&&(t.memory={used:Math.round(performance.memory.usedJSHeapSize/1048576),total:Math.round(performance.memory.totalJSHeapSize/1048576),limit:Math.round(performance.memory.jsHeapSizeLimit/1048576)})),t}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(t,e="batch"){const i={sessionId:this.metadata.sessionId,timestamp:Date.now(),type:e,errors:t,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(t={}){let e=[...this.errors];return t.category&&(e=e.filter(e=>e.category===t.category)),t.severity&&(e=e.filter(e=>e.severity===t.severity)),t.since&&(e=e.filter(e=>e.timestamp>=t.since)),e}getStats(){const t={total:this.errors.length,byCategory:{},bySeverity:{},patterns:this.errorPatterns.size,topErrors:[]};for(const e of Object.values(this.errorCategories))t.byCategory[e]=this.errors.filter(t=>t.category===e).length;for(const e of Object.values(this.severityLevels))t.bySeverity[e]=this.errors.filter(t=>t.severity===e).length;const e=Array.from(this.errorCounts.entries()).sort((t,e)=>e[1]-t[1]).slice(0,5);return t.topErrors=e.map(([t,e])=>({error:t,count:e})),t}clearErrors(){this.errors=[],this.errorCounts.clear(),this.errorPatterns.clear()}suppressError(t){this.suppressedErrors.add(t)}unsuppressError(t){this.suppressedErrors.delete(t)}enable(){this.enabled=!0,this.attachGlobalHandlers(),this.startReportingInterval()}disable(){this.enabled=!1,this.detachGlobalHandlers(),this.stopReportingInterval()}destroy(){this.disable(),this.clearErrors()}}({enabled:!0,maxErrors:100,reportingThreshold:10,reportingInterval:6e4,suppressedErrors:["ResizeObserver loop limit exceeded","Non-Error promise rejection captured"]}),Wa=new class{constructor(t={}){this.enabled=!1!==t.enabled,this.interval=t.interval||3e4,this.thresholds={memory:t.memoryThreshold||500,fps:t.fpsThreshold||30,errorRate:t.errorRateThreshold||.1,responseTime:t.responseTimeThreshold||1e3,...t.thresholds},this.checks=new Map,this.history=[],this.maxHistory=t.maxHistory||100,this.status="initializing",this.lastCheck=null,this.dependencies={animationLoop:null,stateStore:null,eventManager:null,performanceMonitor:null,errorTracker:null},this.callbacks={onHealthy:t.onHealthy||null,onWarning:t.onWarning||null,onCritical:t.onCritical||null,onStatusChange:t.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(t,e,i={}){this.checks.set(t,{fn:e,critical:i.critical||!1,weight:i.weight||1,timeout:i.timeout||5e3,lastResult:null,lastRun:null})}checkMemory(){const t={status:"healthy",details:{}};if(performance.memory){const e=performance.memory.usedJSHeapSize/1048576,i=performance.memory.totalJSHeapSize/1048576,s=performance.memory.jsHeapSizeLimit/1048576;t.details={used:Math.round(e),total:Math.round(i),limit:Math.round(s),percentage:Math.round(e/s*100)},e>this.thresholds.memory?(t.status="critical",t.message=`Memory usage too high: ${Math.round(e)}MB`):e>.8*this.thresholds.memory&&(t.status="warning",t.message=`Memory usage approaching limit: ${Math.round(e)}MB`)}else t.status="unknown",t.message="Memory API not available";return t}checkPerformance(){const t={status:"healthy",details:{}};if(this.dependencies.performanceMonitor){const e=this.dependencies.performanceMonitor.getStats();t.details={fps:e.fps.current,frameTime:e.frameTime.current,health:e.health,score:e.performance},e.fps.current<this.thresholds.fps&&(t.status="warning",t.message=`Low FPS: ${e.fps.current}`),"critical"!==e.health&&"poor"!==e.health||(t.status="critical",t.message="Performance is critically low")}return t}checkErrors(){const t={status:"healthy",details:{}};if(this.dependencies.errorTracker){const e=this.dependencies.errorTracker.getStats(),i=this.dependencies.errorTracker.getErrors({since:Date.now()-6e4});t.details={total:e.total,recent:i.length,critical:e.bySeverity.critical||0,patterns:e.patterns};const s=i.length/60;s>this.thresholds.errorRate?(t.status="critical",t.message=`High error rate: ${s.toFixed(2)}/s`):e.bySeverity.critical>0&&(t.status="warning",t.message=`${e.bySeverity.critical} critical errors`)}return t}checkDOM(){const t={status:"healthy",details:{}};if("undefined"!=typeof document){const e=document.querySelectorAll("*").length,i=document.querySelectorAll("canvas").length,s=this.countEventListeners();t.details={nodes:e,canvases:i,listeners:s},e>1e4&&(t.status="warning",t.message=`High DOM node count: ${e}`),s>1e3&&(t.status="warning",t.message=`High event listener count: ${s}`)}return t}checkAnimation(){const t={status:"healthy",details:{}};if(this.dependencies.animationLoop){const e=this.dependencies.animationLoop.getStats();t.details={callbacks:e.callbackCount,fps:e.fps,running:e.isRunning,dropped:e.droppedFrames},e.isRunning||(t.status="warning",t.message="Animation loop not running"),e.droppedFrames>100&&(t.status="warning",t.message=`Dropped frames: ${e.droppedFrames}`)}return t}checkState(){const t={status:"healthy",details:{}};if(this.dependencies.stateStore){const e=this.dependencies.stateStore.getState(),i=JSON.stringify(e).length;t.details={size:i,keys:Object.keys(e).length},i>1e6&&(t.status="warning",t.message=`Large state size: ${(i/1024).toFixed(2)}KB`)}return t}checkEvents(){const t={status:"healthy",details:{}};if(this.dependencies.eventManager){const e=this.dependencies.eventManager.getActiveListeners(),i=this.dependencies.eventManager.analyzeLeaks();t.details={active:e.length,potentialLeaks:i.potentialLeaks.length,byGroup:i.byGroup},i.potentialLeaks.length>10&&(t.status="warning",t.message=`Potential memory leaks: ${i.potentialLeaks.length}`),e.length>500&&(t.status="warning",t.message=`High listener count: ${e.length}`)}return t}async checkStorage(){const t={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.storage&&navigator.storage.estimate)try{const e=await navigator.storage.estimate(),i=e.usage||0,s=e.quota||0,n=s>0?i/s*100:0;t.details={used:Math.round(i/1048576),quota:Math.round(s/1048576),percentage:Math.round(n)},n>90?(t.status="critical",t.message=`Storage almost full: ${n.toFixed(1)}%`):n>70&&(t.status="warning",t.message=`Storage usage high: ${n.toFixed(1)}%`)}catch{t.status="unknown",t.message="Storage API error"}return t}async checkNetwork(){const t={status:"healthy",details:{}};if("undefined"!=typeof navigator&&navigator.connection){const{connection:e}=navigator;t.details={effectiveType:e.effectiveType,downlink:e.downlink,rtt:e.rtt,saveData:e.saveData},"slow-2g"!==e.effectiveType&&"2g"!==e.effectiveType||(t.status="warning",t.message="Slow network connection detected"),e.saveData&&(t.status="warning",t.message="Data saver mode enabled")}try{const e=performance.now(),i=await fetch("/health",{method:"HEAD",cache:"no-cache"}),s=performance.now()-e;t.details.responseTime=Math.round(s),t.details.online=i.ok,s>this.thresholds.responseTime&&(t.status="warning",t.message=`Slow response time: ${s.toFixed(0)}ms`)}catch{t.details.online=navigator.onLine,navigator.onLine||(t.status="critical",t.message="No network connection")}return t}checkBrowser(){const t={status:"healthy",details:{}};t.details={userAgent:navigator.userAgent,platform:navigator.platform,language:navigator.language,cookiesEnabled:navigator.cookieEnabled,doNotTrack:navigator.doNotTrack,hardwareConcurrency:navigator.hardwareConcurrency,maxTouchPoints:navigator.maxTouchPoints};const e={webGL:!!document.createElement("canvas").getContext("webgl"),webAudio:"undefined"!=typeof AudioContext,localStorage:"undefined"!=typeof localStorage,serviceWorker:"serviceWorker"in navigator,webWorker:"undefined"!=typeof Worker};t.details.features=e;const i=Object.entries(e).filter(([t,e])=>!e).map(([t])=>t);return i.length>0&&(t.status="warning",t.message=`Missing features: ${i.join(", ")}`),t}countEventListeners(){let t=0;const e=document.querySelectorAll("*");for(const i of e){const e="undefined"!=typeof getEventListeners&&getEventListeners?getEventListeners(i):{};for(const i in e)t+=e[i].length}return t}async runCheck(t){const e=this.checks.get(t);if(!e)return{status:"unknown",message:`Check '${t}' not found`};try{const t=new Promise((t,i)=>{setTimeout(()=>i(new Error("Check timeout")),e.timeout)}),i=await Promise.race([e.fn(),t]);return e.lastResult=i,e.lastRun=Date.now(),i}catch(t){return{status:"error",message:t.message,error:t.stack}}}async runAllChecks(){const t={},e=[];for(const[i]of this.checks)e.push(this.runCheck(i).then(e=>{t[i]=e}));return await Promise.all(e),t}async performHealthCheck(){const t=performance.now(),e=await this.runAllChecks(),i=performance.now()-t,s=this.calculateOverallHealth(e),n={timestamp:Date.now(),status:s.status,score:s.score,duration:Math.round(i),checks:e,summary:s.summary};return this.lastCheck=n,this.addToHistory(n),this.updateStatus(s.status),n}calculateOverallHealth(t){let e=0,i=0,s=!1;const n=[];for(const[r,a]of Object.entries(t)){const t=this.checks.get(r),o=t?t.weight:1;let h=0;switch(a.status){case"healthy":h=100;break;case"warning":h=70,n.push({name:r,level:"warning",message:a.message});break;case"critical":h=30,n.push({name:r,level:"critical",message:a.message}),t&&t.critical&&(s=!0);break;case"error":h=0,n.push({name:r,level:"error",message:a.message});break;case"unknown":h=50}e+=h*o,i+=o}const r=i>0?Math.round(e/i):0;let a;return a=s||r<30?"critical":r<70?"degraded":r<90?"warning":"healthy",{status:a,score:r,summary:{total:Object.keys(t).length,healthy:Object.values(t).filter(t=>"healthy"===t.status).length,warning:Object.values(t).filter(t=>"warning"===t.status).length,critical:Object.values(t).filter(t=>"critical"===t.status).length,issues:n}}}updateStatus(t){if(this.status!==t){const e=this.status;switch(this.status=t,this.callbacks.onStatusChange&&this.callbacks.onStatusChange(t,e),t){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(t){this.history.push(t),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(t){Object.assign(this.dependencies,t)}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 t=this.history[0].timestamp;return Date.now()-t}async handleHealthRequest(t,e){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"})}}}({enabled:!1,interval:3e4});class Ya{constructor(t){if(!t.errorBoundary)throw new Error("DestructionManager: errorBoundary required");if(!t.animationController)throw new Error("DestructionManager: animationController required");if(!t.state)throw new Error("DestructionManager: state required");if(!t.stop)throw new Error("DestructionManager: stop required");if(!t.stopSpeaking)throw new Error("DestructionManager: stopSpeaking required");if(!t.disconnectAudio)throw new Error("DestructionManager: disconnectAudio required");this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.positionController=t.positionController||null,this.soundSystem=t.soundSystem||null,this.audioLevelProcessor=t.audioLevelProcessor||null,this.particleSystem=t.particleSystem||null,this.renderer=t.renderer||null,this.canvasManager=t.canvasManager||null,this.eventManager=t.eventManager||null,this.accessibilityManager=t.accessibilityManager||null,this.mobileOptimization=t.mobileOptimization||null,this.pluginSystem=t.pluginSystem||null,this.audioAnalyzer=t.audioAnalyzer||null,this.shapeMorpher=t.shapeMorpher||null,this.gestureController=t.gestureController||null,this.stateCoordinator=t.stateCoordinator||null,this.visualizationRunner=t.visualizationRunner||null,this.orbScaleAnimator=t.orbScaleAnimator||null,this.audioHandler=t.audioHandler||null,this.degradationManager=t.degradationManager||null,this.stateMachine=t.stateMachine||null,this.contextManager=t.contextManager||null,this.Ie=t.state,this.ki=t.stop,this.xi=t.stopSpeaking,this.Ei=t.disconnectAudio}destroy(){this.errorBoundary.wrap(()=>{this.stopAnimations(),this.destroyControllers(),this.cleanupSubsystems(),this.cleanupEvents(),this.cleanupPluginsAndExtensions(),this.clearErrorBoundary()},"destruction")()}stopAnimations(){this.ki(),this.Ie.speaking&&this.xi()}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(){Ua&&Ua.destroy(),vn&&vn.destroy(),Wa&&Wa.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.Ie.llmHandler&&(this.Ie.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.Ei(),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.Ie=null,this.ki=null,this.xi=null,this.Ei=null}}class Xa{constructor(t){this.renderer=t.renderer||null,this.Ie=t.state,this.ti=t.emit}startBreathingAnimation(){this.Ie.breathingAnimationId&&cancelAnimationFrame(this.Ie.breathingAnimationId);const t=()=>{if(!this.Ie.breathePattern||!this.Ie.isRunning)return;const e=this.Ie.breathePattern,i=Date.now(),s=(i-e.phaseStartTime)/1e3,{scale:n,nextPhase:r}=this.calculatePhaseState(e,s,i);r!==e.currentPhase&&(e.currentPhase=r),this.applyScale(n),this.Ie.breathingAnimationId=requestAnimationFrame(t)};this.Ie.breathePattern.currentPhase="inhale",this.Ie.breathePattern.phaseStartTime=Date.now(),this.ti("inhale-start"),t()}calculatePhaseState(t,e,i){let s=1,n=t.currentPhase;switch(t.currentPhase){case"inhale":({scale:s,nextPhase:n}=this.processInhalePhase(t,e,i));break;case"hold1":({scale:s,nextPhase:n}=this.processHold1Phase(t,e,i));break;case"exhale":({scale:s,nextPhase:n}=this.processExhalePhase(t,e,i));break;case"hold2":({scale:s,nextPhase:n}=this.processHold2Phase(t,e,i))}return{scale:s,nextPhase:n}}processInhalePhase(t,e,i){let s=1,n=t.currentPhase;return e>=t.inhale?(n="hold1",t.phaseStartTime=i,this.ti("hold-start",{type:"post-inhale"})):s=1+e/t.inhale*.3,{scale:s,nextPhase:n}}processHold1Phase(t,e,i){let s=t.currentPhase;return e>=t.hold1&&(s="exhale",t.phaseStartTime=i,this.ti("exhale-start")),{scale:1.3,nextPhase:s}}processExhalePhase(t,e,i){let s=1.3,n=t.currentPhase;return e>=t.exhale?(n="hold2",t.phaseStartTime=i,this.ti("hold-start",{type:"post-exhale"})):s=1.3-e/t.exhale*.4,{scale:s,nextPhase:n}}processHold2Phase(t,e,i){let s=t.currentPhase;return e>=t.hold2&&(s="inhale",t.phaseStartTime=i,this.ti("inhale-start")),{scale:.9,nextPhase:s}}applyScale(t){this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(t)}}class Va{constructor(t){this.errorBoundary=t.errorBoundary,this.animationController=t.animationController,this.stateMachine=t.stateMachine,this.particleSystem=t.particleSystem,this.soundSystem=t.soundSystem,this.renderer=t.renderer||null,this.config=t.config,this.Ie=t.state,this.Bi=t.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 t=this.animationController.getPerformanceMetrics();return{isRunning:t.isRunning,fps:t.fps,targetFPS:t.targetFPS,performanceDegradation:t.performanceDegradation}}getEmotionalStatus(){const t=this.stateMachine.getCurrentState();return{emotion:t.emotion,undertone:t.undertone,isTransitioning:t.isTransitioning,transitionProgress:t.transitionProgress}}getGestureStatus(){return{currentGesture:this.renderer?.currentGesture||null,gestureActive:this.renderer?.isGestureActive()||!1}}getParticleStatus(){const t=this.particleSystem.getStats();return{active:t.activeParticles,max:t.maxParticles,poolEfficiency:t.poolEfficiency}}getAudioStatus(){return{audioEnabled:this.config.enableAudio,soundSystemAvailable:this.soundSystem.isAvailable(),speaking:this.Ie.speaking,audioLevel:this.Ie.audioLevel,masterVolume:this.config.masterVolume}}getRendererStatus(){const t=this.renderer.getStats();return{gradientCacheSize:t.gradientCacheSize,breathingPhase:t.breathingPhase,layers:t.layers}}getEventListenerCount(){return this.Bi().length}getErrorStats(){return this.errorBoundary.getErrorStats()}}class Na{constructor(t){if(!t.errorBoundary)throw new Error("SleepWakeManager: errorBoundary required");if(!t.express)throw new Error("SleepWakeManager: express required");if(!t.state)throw new Error("SleepWakeManager: state required");if(!t.emit)throw new Error("SleepWakeManager: emit required");this.errorBoundary=t.errorBoundary,this.Ai=t.express,this.idleBehavior=t.idleBehavior||null,this.renderer=t.renderer||null,this.Ie=t.state,this.ti=t.emit,this.Le=t.chainTarget||this}sleep(){return this.errorBoundary.wrap(async()=>(this.Ie.sleeping||(await this.performSleepSequence(),this.enterSleepState()),this.Le),"sleep",this.Le)()}async performSleepSequence(){this.Ai("yawn"),await this.delay(1e3),this.Ai("sway"),await this.delay(1e3)}enterSleepState(){this.Ie.sleeping=!0,this.renderer&&this.renderer.enterSleepMode&&this.renderer.enterSleepMode(),this.idleBehavior&&this.idleBehavior.enterSleep&&this.idleBehavior.enterSleep(),this.ti("sleep")}wake(){return this.errorBoundary.wrap(async()=>this.Ie.sleeping?(this.exitSleepState(),await this.performWakeSequence(),this.Le):this.Le,"wake",this.Le)()}exitSleepState(){this.Ie.sleeping=!1,this.renderer&&this.renderer.wakeUp&&this.renderer.wakeUp(),this.idleBehavior&&this.idleBehavior.wakeUp&&this.idleBehavior.wakeUp()}async performWakeSequence(){this.Ai("stretch"),await this.delay(1e3),this.Ai("slowBlink"),await this.delay(1e3),this.Ai("shake"),await this.delay(500),this.ti("wake")}delay(t){return new Promise(e=>setTimeout(e,t))}}class Qa{constructor(t){if(!t.errorBoundary)throw new Error("SpeechManager: errorBoundary required");if(!t.emit)throw new Error("SpeechManager: emit required");this.errorBoundary=t.errorBoundary,this.audioLevelProcessor=t.audioLevelProcessor||null,this.audioHandler=t.audioHandler||null,this.renderer=t.renderer||null,this.config=t.config||{},this.Ie=t.state||{speaking:!1},this.Ci=t.setTTSSpeaking||(()=>{}),this.ti=t.emit,this.Le=t.chainTarget||this}speak(t,e={}){if(!window.speechSynthesis)return null;const i=this.createUtterance(t,e);return this.setupUtteranceHandlers(i,t),window.speechSynthesis.speak(i),i}createUtterance(t,e){const i=new SpeechSynthesisUtterance(t);return e.voice&&(i.voice=e.voice),e.rate&&(i.rate=e.rate),e.pitch&&(i.pitch=e.pitch),e.volume&&(i.volume=e.volume),e.lang&&(i.lang=e.lang),i}setupUtteranceHandlers(t,e){t.onstart=()=>{this.Ci(!0),this.ti("tts:start",{text:e})},t.onend=()=>{this.Ci(!1),this.ti("tts:end")},t.onerror=t=>{this.Ci(!1),this.ti("tts:error",{error:t})},t.onboundary=t=>{this.ti("tts:boundary",{name:t.name,charIndex:t.charIndex,charLength:t.charLength})}}startSpeaking(t){return this.errorBoundary.wrap(()=>this.validateAudioContext(t)&&this.initializeAudioProcessor(t)?(this.activateSpeechMode(t),this.Le):this.Le,"speech-start",this.Le)()}validateAudioContext(t){if(!t)throw new Error("AudioContext is required for speech reactivity");return!!this.config.enableAudio&&!this.Ie.speaking}initializeAudioProcessor(t){return!!this.audioLevelProcessor.initialize(t)}activateSpeechMode(t){this.Ie.speaking=!0,this.renderer&&this.renderer.onSpeechStart(t),this.ti("speechStarted",{audioContext:t,analyser:this.audioLevelProcessor.getAnalyser(),chainTarget:this.Le})}stopSpeaking(){return this.errorBoundary.wrap(()=>this.audioHandler?this.audioHandler.stopSpeaking():this.Le,"speech-stop",this.Le)()}}class Ja{constructor(t){if(!t.emit)throw new Error("AudioLevelCallbackManager: emit required");this.audioLevelProcessor=t.audioLevelProcessor||null,this.renderer=t.renderer||null,this.particleSystem=t.particleSystem||null,this.Ai=t.express||(()=>{}),this.ti=t.emit}setupAudioLevelProcessorCallbacks(){this.setupLevelUpdateCallback(),this.setupVolumeSpikeCallback(),this.setupErrorCallback()}setupLevelUpdateCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onLevelUpdate(t=>{this.renderer&&this.renderer.updateAudioLevel(t.level),this.ti("audioLevelUpdate",{level:t.level,rawData:Array.from(t.rawData),timestamp:t.timestamp})})}setupVolumeSpikeCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onVolumeSpike(t=>{const e=this.handleVolumeSpike();this.ti("volumeSpike",{...t,gestureTriggered:e})})}handleVolumeSpike(){return!!this.particleSystem&&!this.particleSystem.particles.some(t=>t.gestureProgress<1)&&(this.Ai("pulse"),!0)}setupErrorCallback(){this.audioLevelProcessor&&this.audioLevelProcessor.onError(t=>{this.ti("audioProcessingError",t)})}}class Ka{constructor(t){this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state,this.Le=t.chainTarget||this,this.animationId=null}setOrbScale(t,e=1e3,i="easeInOut"){return this.errorBoundary.wrap(()=>(this.renderer&&this.startScaleAnimation(t,e,i),this.Le),"setOrbScale",this.Le)()}startScaleAnimation(t,e,i){const s=this.Ie.currentOrbScale||1,n=Date.now(),r=()=>{const a=Date.now()-n,o=Math.min(a/e,1),h=this.applyEasing(o,i);this.Ie.currentOrbScale=s+(t-s)*h,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(this.Ie.currentOrbScale),o<1&&this.Ie.isRunning&&(this.animationId=requestAnimationFrame(r))};r()}applyEasing(t,e){switch(e){case"easeIn":return this.easeIn(t);case"easeOut":return this.easeOut(t);case"easeInOut":return this.easeInOut(t);default:return t}}easeIn(t){return t*t}easeOut(t){return t*(2-t)}easeInOut(t){return t<.5?2*t*t:(4-2*t)*t-1}destroy(){this.animationId&&(cancelAnimationFrame(this.animationId),this.animationId=null),this.renderer=null,this.Ie=null}}class Za{constructor(t){if(!t.errorBoundary)throw new Error("RecordingStateManager: errorBoundary required");if(!t.emit)throw new Error("RecordingStateManager: emit required");this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state||{recording:!1},this.ti=t.emit,this.Le=t.chainTarget||this}startRecording(){return this.errorBoundary.wrap(()=>(this.Ie.recording||(this.Ie.recording=!0,this.renderer&&this.renderer.startRecording&&this.renderer.startRecording(),this.ti("recordingStarted")),this.Le),"recording-start",this.Le)()}stopRecording(){return this.errorBoundary.wrap(()=>this.Ie.recording?(this.Ie.recording=!1,this.renderer&&this.renderer.stopRecording&&this.renderer.stopRecording(),this.ti("recordingStopped"),this.Le):this.Le,"recording-stop",this.Le)()}}class to{constructor(t){this.errorBoundary=t.errorBoundary,this.renderer=t.renderer||null,this.Ie=t.state,this.Ti=t.startBreathingAnimation,this.Le=t.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(t,e,i,s){return this.errorBoundary.wrap(()=>{const n=t+e+i+s;return this.Ie.breathePattern={inhale:t,hold1:e,exhale:i,hold2:s,totalCycle:n,currentPhase:"inhale",phaseStartTime:Date.now(),phaseProgress:0},this.Ti(),this.Le},"setBreathePattern",this.Le)()}breathe(t="calm"){return this.errorBoundary.wrap(()=>{const e=to.getPresets(),i=e[t]||e.calm;return this.setBreathePattern(i.inhale,i.hold1,i.exhale,i.hold2)},"breathe",this.Le)()}stopBreathing(){return this.errorBoundary.wrap(()=>(this.Ie.breathingAnimationId&&(cancelAnimationFrame(this.Ie.breathingAnimationId),this.Ie.breathingAnimationId=null),this.Ie.breathePattern=null,this.renderer&&this.renderer.setCustomScale&&this.renderer.setCustomScale(1),this.Le),"stopBreathing",this.Le)()}}class eo{constructor(t,e){this.Pi=t,this.O=e}handleEvent(t,e){switch(t){case"degradationApplied":this.applySettings(e.settings),this.O("performanceDegradation",e);break;case"recoveryApplied":this.applySettings(e.settings),this.O("performanceRecovery",e);break;case"levelChanged":this.applySettings(e.settings),this.O("degradationLevelChanged",e)}}applySettings(t){const e=this.Pi();e.particleSystem&&void 0!==t.particleLimit&&e.particleSystem.setMaxParticles(t.particleLimit),e.soundSystem&&void 0!==t.audioEnabled&&!t.audioEnabled&&e.soundSystem.isAvailable()&&e.soundSystem.stopAmbientTone(200),e.renderer&&void 0!==t.qualityLevel&&e.renderer.setQualityLevel(t.qualityLevel)}}class io{constructor(t={}){this.errorBoundary=new e,this.eventManager=new Ms({maxListeners:t.maxEventListeners||100,enableDebugging:t.enableEventDebugging||!1,enableMonitoring:t.enableEventMonitoring||!0,memoryWarningThreshold:t.eventMemoryWarningThreshold||50}),this.eventManager.emit||(this.eventManager.u={},this.eventManager.emit=(t,e)=>{const i=this.eventManager.u[t];i&&i.forEach(t=>t(e))},this.eventManager.on=(t,e)=>{this.eventManager.u[t]||(this.eventManager.u[t]=[]),this.eventManager.u[t].push(e)},this.eventManager.off=(t,e)=>{const i=this.eventManager.u[t];if(i){const t=i.indexOf(e);t>-1&&i.splice(t,1)}}),this.errorBoundary.wrap(()=>{this.initialize(t)},"initialization")()}initialize(t){this.Emotions=v,this.Gestures=Ii,this.ParticleBehaviors=ys,this.speechManager=new Qa({errorBoundary:this.errorBoundary,emit:(t,e)=>this.emit(t,e)}),this.audioLevelCallbackManager=new Ja({emit:(t,e)=>this.emit(t,e)}),this.orbScaleAnimator=new Ka(this),this.recordingStateManager=new Za({errorBoundary:this.errorBoundary,emit:(t,e)=>this.emit(t,e)}),this.breathingPatternManager=new to(this),new ja(this,t).initialize(),this.renderStateBuilder=new Ia(this),this.threatLevelCalculator=new $a(this),this.particleConfigCalculator=new La(this);const e=this;this.gestureMotionProvider=new Ga({renderer:this.renderer,state:{get currentModularGesture(){return e.currentModularGesture},set currentModularGesture(t){e.currentModularGesture=t}}}),this.renderLayerOrchestrator=new _a(this),this.debugInfoRenderer=new Ha(this),this.destructionManager=new Ya({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 e.speaking},get llmHandler(){return e.llmHandler},set llmHandler(t){e.llmHandler=t}},stop:()=>this.stop(),stopSpeaking:()=>this.stopSpeaking(),disconnectAudio:()=>this.disconnectAudio()}),this.breathingAnimationController=new Xa(this),this.systemStatusReporter=new Va({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 e.speaking},get audioLevel(){return e.audioLevel}},getEventNames:()=>this.getEventNames()}),this.sleepWakeManager=new Na({errorBoundary:this.errorBoundary,express:(t,e)=>this.express(t,e),idleBehavior:this.idleBehavior,renderer:this.renderer,state:{get sleeping(){return e.sleeping},set sleeping(t){e.sleeping=t}},emit:(t,e)=>this.emit(t,e),chainTarget:this}),this.degradationEventHandler=new eo(()=>({particleSystem:this.particleSystem,soundSystem:this.soundSystem,renderer:this.renderer}),(t,e)=>this.emit(t,e))}handleDegradationEvent(t,e){return this.degradationEventHandler.handleEvent(t,e)}applyDegradationSettings(t){return this.degradationEventHandler.applySettings(t)}setupAudioLevelProcessorCallbacks(){this.audioLevelCallbackManager.setupAudioLevelProcessorCallbacks()}setEmotion(t,e=null){return this.errorBoundary.wrap(()=>this.stateCoordinator.setEmotion(t,e),"emotion-setting",this)()}updateUndertone(t){return this.errorBoundary.wrap(()=>(this.stateMachine.applyUndertoneModifier(t),this.renderer&&this.renderer.updateUndertone&&this.renderer.updateUndertone(t),this),"undertone-update",this)()}setBPM(t){return this.errorBoundary.wrap(()=>(this.renderer?.setBPM&&this.renderer.setBPM(t),this),"bpm-update",this)()}setRotationSpeed(t){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationSpeed&&this.renderer.setRotationSpeed(t),this),"rotation-speed-update",this)()}setRotationAngle(t){return this.errorBoundary.wrap(()=>(this.renderer?.setRotationAngle&&this.renderer.setRotationAngle(t),this),"rotation-angle-update",this)()}getPosition(){return this.animationFrameController.getPosition()}setGazeTracking(t){return this.errorBoundary.wrap(()=>(this.renderer&&this.renderer.setGazeTracking&&this.renderer.setGazeTracking(t),this),"gaze-tracking-update",this)()}express(t,e={}){return this.gestureController?this.gestureController.express(t,e):this}expressChord(t,e={}){return this.gestureController.expressChord(t,e)}executeGestureDirectly(t,e={}){this.gestureController.executeGestureDirectly(t,e),this.emit("gesture",{name:t,options:e})}chain(...t){return this.gestureController.chain(...t)}executeChainSequence(t){return this.gestureController.executeChainSequence(t)}perform(t,e={}){return this.performanceBehaviorManager.perform(t,e)}updateContext(t){return this.frustrationContextManager.updateContext(t)}getContext(){return this.emotionalStateQueryManager.getContext()}incrementFrustration(t=10){return this.frustrationContextManager.incrementFrustration(t)}decrementFrustration(t=10){return this.frustrationContextManager.decrementFrustration(t)}resetFrustration(){return this.frustrationContextManager.resetFrustration()}getAvailablePerformances(){return this.performanceBehaviorManager.getAvailablePerformances()}registerPerformance(t,e){return this.performanceBehaviorManager.registerPerformance(t,e)}getPerformanceAnalytics(){return this.performanceBehaviorManager.getPerformanceAnalytics()}getContextAnalytics(){return this.performanceBehaviorManager.getContextAnalytics()}startSpeaking(t){return this.speechManager?this.speechManager.startSpeaking(t):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(t,e,i,s){return this.breathingPatternManager?this.breathingPatternManager.setBreathePattern(t,e,i,s):this}setOrbScale(t,e=1e3,i="easeInOut"){return this.orbScaleAnimator?this.orbScaleAnimator.setOrbScale(t,e,i):this}breathe(t="calm"){return this.breathingPatternManager?this.breathingPatternManager.breathe(t):this}startBreathingAnimation(){this.breathingAnimationController.startBreathingAnimation()}stopBreathing(){return this.breathingPatternManager?this.breathingPatternManager.stopBreathing():this}on(t,e){return this.eventListenerManager.on(t,e)}off(t,e){return this.eventListenerManager.off(t,e)}once(t,e){return this.eventListenerManager.once(t,e)}removeAllListeners(t=null){return this.eventListenerManager.removeAllListeners(t)}listenerCount(t){return this.eventListenerManager.listenerCount(t)}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(t){return this.performanceMonitoringManager.setDegradationLevel(t)}isFeatureAvailable(t){return this.performanceMonitoringManager.isFeatureAvailable(t)}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(t,e={}){this.debugProfilingManager.startProfiling(t,e)}endProfiling(t){return this.debugProfilingManager.endProfiling(t)}takeMemorySnapshot(t){this.debugProfilingManager.takeMemorySnapshot(t)}clearDebugData(){this.debugProfilingManager.clearDebugData()}getRuntimeCapabilities(){return this.debugProfilingManager.getRuntimeCapabilities()}emit(t,e=null){this.eventListenerManager.emit(t,e)}update(t){this.errorBoundary.wrap(()=>{this.visualizationRunner.update(t)},"audio-update")()}render(){try{const{renderStart:t,deltaTime:e,renderState:i}=this.renderStateBuilder.buildRenderState();this.debugMode&&vs.trackFrameTiming(e),this.canvasManager.clear(),this.gazeTracker&&this.gazeTracker.update(e),this.threatLevelCalculator.updateThreatLevel(i);const s=c(i.emotion);this.renderer.setEmotionalState(i.emotion,s,i.undertone);const n=this.particleConfigCalculator.calculateParticleConfig(i,s),{orbX:r,orbY:a,particleBehavior:o,particleRate:h,minParticles:l,maxParticles:u}=n;this.particleSystem.spawn(o,i.emotion,h,r,a,e,null,l,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:p,gestureProgress:m}=this.gestureMotionProvider.getGestureMotion();this.particleSystem.update(e,r,a,p,m,d);const g=this.gestureMotionProvider.getGestureTransform();this.renderLayerOrchestrator.renderAllLayers({renderState:i,deltaTime:e,emotionParams:s,gestureTransform:g,renderStart:t})}catch(t){this.errorBoundary.logError(t,"main-render")}}renderDebugInfo(t){this.debugInfoRenderer.renderDebugInfo(t)}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(t){this.speechReactivityManager.updateAudioConfig(t)}getAvailableGestures(){return this.emotionalStateQueryManager.getAvailableGestures()}connectAudioSource(t){return this.speechReactivityManager.connectAudioSource(t)}setVolume(t){return this.errorBoundary.wrap(()=>this.audioHandler.setVolume(t),"volume-setting",this)()}getVolume(){return this.config.masterVolume}setSoundEnabled(t){return this.config.soundEnabled=t,this}isSoundEnabled(){return this.config.soundEnabled}pause(){return this.executionLifecycleManager.pause()}resume(){return this.executionLifecycleManager.resume()}isActive(){return this.executionLifecycleManager.isActive()}setTargetFPS(t){return this.performanceMonitoringManager.setTargetFPS(t)}getTargetFPS(){return this.performanceMonitoringManager.getTargetFPS()}setPosition(t,e,i=0){return this.animationFrameController.setPosition(t,e,i)}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){return this.animationFrameController.animateToPosition(t,e,i,s,n)}clearParticles(){return this.visualTransformationManager.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.visualTransformationManager.setParticleSystemCanvasDimensions(t,e)}setPerformanceDegradation(t){return this.performanceMonitoringManager.setPerformanceDegradation(t)}getAudioLevel(){return this.speechReactivityManager.getAudioLevel()}isSpeaking(){return this.speechReactivityManager.isSpeaking()}setAudioSmoothing(t){return this.speechReactivityManager.setAudioSmoothing(t)}getSystemStatus(){return this.healthCheckManager.getSystemStatus()}setDebugMode(t){return this.healthCheckManager.setDebugMode(t)}triggerTestError(t="manual-test"){return this.healthCheckManager.triggerTestError(t)}getPerformanceMetrics(){return this.healthCheckManager.getPerformanceMetrics()}registerPlugin(t){return this.pluginSystem.registerPlugin(t)}setAccessibility(t){t.colorBlindMode&&this.accessibilityManager.setColorBlindMode(t.colorBlindMode),void 0!==t.reducedMotion&&(this.accessibilityManager.reducedMotionPreferred=t.reducedMotion),void 0!==t.highContrast&&(this.accessibilityManager.highContrastEnabled=t.highContrast)}getMobileStatus(){return this.healthCheckManager.getMobileStatus()}getAccessibilityStatus(){return this.healthCheckManager.getAccessibilityStatus()}setState(t){return this.setEmotion(t)}speak(t,e={}){return this.ttsManager.speak(t,e)}setTTSSpeaking(t){this.ttsManager.setTTSSpeaking(t)}getVoices(){return this.ttsManager.getVoices()}stopTTS(){this.ttsManager.stopTTS()}handleResize(t,e,i){this.visualTransformationManager.handleResize(t,e,i)}morphTo(t,e={}){return this.visualTransformationManager.morphTo(t,e)}connectAudio(t){return this.errorBoundary.wrap(()=>this.audioHandler.connectAudio(t),"connectAudio",this)()}disconnectAudio(){return this.errorBoundary.wrap(()=>this.audioHandler.disconnectAudio(),"disconnectAudio",this)()}setOffset(t,e,i=0){return this.visualTransformationManager.setOffset(t,e,i)}getOffset(){return this.visualTransformationManager.getOffset()}setBackdrop(t={}){return this.visualTransformationManager.setBackdrop(t)}getBackdrop(){return this.visualTransformationManager.getBackdrop()}animateOffset(t,e,i=0,s=1e3,n="easeOutCubic"){return this.visualTransformationManager.animateOffset(t,e,i,s,n)}getAvailableShapes(){return this.emotionalStateQueryManager.getAvailableShapes()}async handleLLMResponse(t,e={}){return this.llmIntegrationBridge.handleLLMResponse(t,e)}configureLLMHandler(t){return this.llmIntegrationBridge.configureLLMHandler(t)}getLLMResponseSchema(){return this.llmIntegrationBridge.getLLMResponseSchema()}static getLLMPromptTemplate(t={}){return Ta.getLLMPromptTemplate(t)}static getLLMEmotions(){return Ta.getLLMEmotions()}static getLLMActions(){return Ta.getLLMActions()}static getLLMShapes(){return Ta.getLLMShapes()}static getLLMGestures(){return Ta.getLLMGestures()}destroy(){this.destructionManager.destroy()}throttledWarn(t,e){const i=Date.now();i-(this.warningTimestamps[e]||0)>this.warningThrottle&&(this.warningTimestamps[e]=i)}}const so={easy:{windowMultiplier:1.5,label:"Easy"},normal:{windowMultiplier:1,label:"Normal"},hard:{windowMultiplier:.7,label:"Hard"}};class no{constructor(){this.Di="normal",this.Ri={autoRhythm:!1,slowMode:!1,visualMetronome:!1},this.Fi=.75}setDifficulty(t){so[t]&&(this.Di=t)}getDifficulty(){return this.Di}getWindowMultiplier(){return so[this.Di].windowMultiplier}setAssist(t){void 0!==t.autoRhythm&&(this.Ri.autoRhythm=!!t.autoRhythm),void 0!==t.slowMode&&(this.Ri.slowMode=!!t.slowMode),void 0!==t.visualMetronome&&(this.Ri.visualMetronome=!!t.visualMetronome)}getAssist(){return{...this.Ri}}get autoRhythm(){return this.Ri.autoRhythm}getBPMMultiplier(){return this.Ri.slowMode?this.Fi:1}get visualMetronome(){return this.Ri.visualMetronome}serialize(){return{preset:this.Di,assist:{...this.Ri}}}deserialize(t){t&&(t.preset&&so[t.preset]&&(this.Di=t.preset),t.assist&&this.setAssist(t.assist))}}class ro{constructor(t){this.zi=t,this.qi=null,this.Oi=0,this.Z=null}getAudioBlob(){return this.qi}getAudioDuration(){return this.Oi}setAudioDuration(t){this.Oi=t||0}async loadAudio(t){if(t instanceof Blob){this.qi=t;const e=URL.createObjectURL(t);await this.ji(e),URL.revokeObjectURL(e)}else await this.ji(t)}async ji(t){const e=new Audio(t);await new Promise((t,i)=>{e.addEventListener("loadedmetadata",()=>{this.Oi=1e3*e.duration,t()},{once:!0}),e.addEventListener("error",i,{once:!0}),e.load()});const i=this.zi();i&&i.soundSystem&&await i.soundSystem.loadAudioFromURL(t)}getAudioAnalysis(){const t=this.zi();return t&&t.audioAnalyzer?{bpm:t.rhythmIntegration?.getBPM()||0,beats:t.rhythmIntegration?.getBeatMarkers()||[],energy:t.audioAnalyzer?.getEnergyLevel()||0,frequencies:t.audioAnalyzer?.getFrequencyData()||[]}:null}connectAudio(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.connectAudio&&e.connectAudio(t)}disconnectAudio(t){const e=this.zi();e&&e.disconnectAudio&&e.disconnectAudio(t)}getSpectrumData(){const t=this.zi();return t&&t.audioAnalyzer?t.audioAnalyzer.dataArray?Array.from(t.audioAnalyzer.dataArray).map(t=>t/255):t.shapeMorpher&&t.shapeMorpher.frequencyData?Array.from(t.shapeMorpher.frequencyData):[]:[]}startRhythmSync(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.rhythmIntegration&&(t&&e.rhythmIntegration.setBPM(t),e.rhythmIntegration.start())}stopRhythmSync(){const t=this.zi();t&&t.rhythmIntegration&&t.rhythmIntegration.stop()}getInputEvaluator(t){const e=this.zi();if(!e||!e.rhythmIntegration)return null;const i=e.rhythmIntegration.getInputEvaluator(t);return i&&!i.K&&e.stateCoordinator&&i.setEmotionTarget((t,i)=>{e.stateCoordinator.nudgeEmotion(t,i)}),i&&!i.Z&&i.setDifficultyManager(this.getDifficultyManager()),i}getDifficultyManager(){return this.Z||(this.Z=new no),this.Z}getLayers(){const t=this.zi();return t&&t.soundSystem?t.soundSystem.getAudioLayerManager():null}}class ao{constructor(t,e){this.zi=t,this.Ue=e,this.Ii={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(t,e){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");if(this.Ue.isRecording()){const i=e||Date.now()-this.Ue.startTime();this.Ue.timeline().push({type:"gesture",name:t,time:i})}i.express(t)}express(t,e){return this.triggerGesture(t,e)}chain(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");const i=this.Ii[t.toLowerCase()];i&&(i.includes(">")?i.split(">").map(t=>t.trim()).filter(t=>t.length>0).forEach((t,i)=>{setTimeout(()=>{t.split("+").map(t=>t.trim()).filter(t=>t.length>0).forEach(t=>{e.express(t)})},500*i)}):i.split("+").map(t=>t.trim()).filter(t=>t.length>0).forEach(t=>{e.express(t)}))}updateUndertone(t){const e=this.zi();if(!e)throw new Error("Engine not initialized. Call init() first.");e.updateUndertone&&"function"==typeof e.updateUndertone?e.updateUndertone(t):e.addUndertone&&"function"==typeof e.addUndertone&&e.addUndertone(t)}getAvailableChains(){return Object.keys(this.Ii)}getChainDefinition(t){return this.Ii[t.toLowerCase()]||null}}class oo{constructor(t,e,i){this.zi=t,this.$i=e,this.Ie=i,this.Li=new Set}startRecording(){this.Ie.timeline.length=0,this.Ie.isRecording=!0,this.Ie.recordingStartTime=Date.now()}stopRecording(){return this.Ie.isRecording=!1,[...this.Ie.timeline]}playTimeline(t){if(!t||!t.length)return void(this.Ie.isPlaying=!1);this.Ie.isPlaying=!0,this.Ie.playbackStartTime=Date.now(),t.forEach(t=>{const e=setTimeout(()=>{if(this.Li.delete(e),!this.Ie.isPlaying)return;const i=this.zi();if(i)switch(t.type){case"gesture":i.express(t.name);break;case"emotion":i.setEmotion(t.name);break;case"shape":i.morphTo(t.name)}},t.time);this.Li.add(e)});const e=Math.max(...t.map(t=>t.time)),i=setTimeout(()=>{this.Li.delete(i),this.Ie.isPlaying=!1},e);this.Li.add(i)}stopPlayback(){this.Ie.isPlaying=!1,this.Li.forEach(t=>clearTimeout(t)),this.Li.clear()}getTimeline(){return[...this.Ie.timeline]}loadTimeline(t){this.Ie.timeline.length=0,this.Ie.timeline.push(...t)}exportTimeline(){return JSON.stringify({version:"1.0",duration:this.$i.getAudioDuration()||0,events:this.Ie.timeline})}importTimeline(t){let e;try{e=JSON.parse(t)}catch{return}this.Ie.timeline.length=0,this.Ie.timeline.push(...e.events||[]),this.$i.setAudioDuration(e.duration||0)}getCurrentTime(){return this.Ie.isPlaying?Date.now()-this.Ie.playbackStartTime:0}seek(t){const e=this.Ie.timeline.filter(e=>e.time<=t),i={};e.forEach(t=>{i[t.type]=t});const s=this.zi();s&&(i.emotion&&s.setEmotion(i.emotion.name),i.shape&&s.morphTo(i.shape.name))}getAnimationData(){const t=this.zi();return{timeline:[...this.Ie.timeline],duration:this.$i.getAudioDuration()||0,currentTime:this.getCurrentTime(),emotion:t?.state?.emotion||"neutral",shape:t?.state?.currentShape||"circle"}}destroy(){this.stopPlayback(),this.zi=null,this.$i=null,this.Ie=null}}class ho{constructor(t,e,i){this.zi=t,this.Gi=e,this._i=i,this.Hi=null,this.Ui=null,this.Wi=!1,this.Yi=null}attachToElement(t,e={}){if(!this.zi())throw new Error("Engine not initialized. Call init() first.");const i="string"==typeof t?document.querySelector(t):t;if(!i)return this._i;this.Hi=i,this.Ui={offsetX:e.offsetX||0,offsetY:e.offsetY||0,animate:!1!==e.animate,duration:e.duration||1e3,scale:e.scale||1,containParticles:!1!==e.containParticles};const s=i.getBoundingClientRect();return this.Ui.containParticles?this._i.setContainment({width:s.width,height:s.height},this.Ui.scale):1!==this.Ui.scale&&this._i.setContainment(null,this.Ui.scale),this.Gi()&&this.Xi(),this.Vi(),this._i}Xi(){if(!this.Hi)return;if(!this.Gi())return;const t=this.Hi.getBoundingClientRect(),e=window.innerWidth/2,i=window.innerHeight/2,s=t.left+t.width/2,n=t.top+t.height/2,r=s-e+this.Ui.offsetX,a=n-i+this.Ui.offsetY,o=!this.Wi;this.Wi=!0,o&&this.Ui.animate?this._i.animateToPosition(r,a,0,this.Ui.duration):this._i.setPosition(r,a,0)}Vi(){this.Yi||(this.Yi={scroll:()=>this.Xi(),resize:()=>this.Xi()},window.addEventListener("scroll",this.Yi.scroll,{passive:!0}),window.addEventListener("resize",this.Yi.resize))}isAttachedToElement(){return!!this.Hi}detachFromElement(){return this.Hi=null,this.Yi&&(window.removeEventListener("scroll",this.Yi.scroll),window.removeEventListener("resize",this.Yi.resize),this.Yi=null),this._i.setContainment(null,1),this._i.setEmotion("neutral"),this._i.morphTo("sphere",{duration:800}),this._i}cleanup(){this.Yi&&(window.removeEventListener("scroll",this.Yi.scroll),window.removeEventListener("resize",this.Yi.resize),this.Yi=null),this.Hi=null}}class lo{constructor(t,e){this.zi=t,this.Gi=e}setContainment(t,e=1){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");i.particleSystem&&i.particleSystem.setContainmentBounds(t),i.positionController&&(i.positionController.coreScaleOverride=e,i.positionController.particleScaleOverride=e),i.particleSystem&&i.particleSystem.particles&&i.particleSystem.particles.forEach(t=>{t.scaleFactor=e,t.size=t.baseSize*e})}clearParticles(){const t=this.zi();if(!t)throw new Error("Engine not initialized. Call init() first.");t.particleSystem&&t.particleSystem.clear()}setParticleSystemCanvasDimensions(t,e){const i=this.zi();if(!i)throw new Error("Engine not initialized. Call init() first.");i.setParticleSystemCanvasDimensions&&i.setParticleSystemCanvasDimensions(t,e)}getFrameData(t="png"){const e=this.Gi();return e?e.toDataURL(`image/${t}`):null}getFrameBlob(t="png"){const e=this.Gi();return e?new Promise(i=>{e.toBlob(t=>i(t),`image/${t}`)}):Promise.resolve(null)}}class co{constructor(){this.Ni=new Map,this.Qi=null}registerStance(t,e){this.Ni.set(t,{...e})}hasStance(t){return this.Ni.has(t)}getStance(t){const e=this.Ni.get(t);return e?{...e}:null}activate(t){const e=this.Ni.get(t);return e?(this.Qi={name:t,config:{...e}},this.Qi.config):null}dismiss(){return!!this.Qi&&(this.Qi=null,!0)}getActiveStance(){return this.Qi?{name:this.Qi.name,config:{...this.Qi.config}}:null}getAvailableStances(){return[...this.Ni.keys()]}}const uo=["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(t=>{const e=t.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return{normalized:e,regex:new RegExp(i,"g")}}),po=/[,;|/]+/,mo=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"]),go=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 fo(t){return["but","and","or","yet","while","although","with"].includes(t)}function yo(t){return["not","no","never","don't","dont","doesn't","doesnt","isn't","isnt"].includes(t)}const Mo={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 wo(t,e,i){const s=bo[`${i}Context`];if(!s)return!1;const n=Math.max(0,e-3),r=Math.min(t.length,e+4);for(let i=n;i<r;i++)if(i!==e&&s.includes(t[i]))return!0;return!1}function vo(t,e){switch(e){case"emotion":return null!==t.emotion;case"gesture":return t.gestures&&t.gestures.length>0;case"shape":return null!==t.shape;case"undertone":return null!==t.undertone;default:return!1}}function So(t,e,i,s){const n=Mo[t];if(!n)return null;const{candidates:r,rule:a}=n;if(1===r.length)return r[0];switch(a){case"standalone_is_emotion":if(vo(s,"emotion")){const t=r.find(t=>"emotion"!==t.category);if(t)return t}return wo(e,i,"emotion"),r.find(t=>"emotion"===t.category)||r[0];case"standalone_is_gesture":if(vo(s,"gesture")){const t=r.find(t=>"gesture"!==t.category);if(t)return t}return wo(e,i,"gesture"),r.find(t=>"gesture"===t.category)||r[0];case"prefer_undertone":return wo(e,i,"emotion")?r.find(t=>"emotion"===t.category)||r[0]:r.find(t=>"undertone"===t.category)||r[0];case"always_gesture":return r.find(t=>"gesture"===t.category)||r[0];case"always_emotion":return r.find(t=>"emotion"===t.category)||r[0];case"context_dependent":for(const t of["emotion","gesture","shape","undertone"])if(wo(e,i,t)){const e=r.find(e=>e.category===t);if(e)return e}return r.sort((t,e)=>t.priority-e.priority)[0];default:return r.sort((t,e)=>t.priority-e.priority)[0]}}function ko(t){return t in Mo}const xo={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"]},Eo={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"]},Bo={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"]},Ao={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"]},Co={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"]}},To={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}},Po={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 Do(t){const e=new Map;for(const[i,s]of Object.entries(t)){for(const t of s){const s=t.toLowerCase().trim();e.set(s,i)}e.set(i.toLowerCase(),i)}return e}class Ro{constructor(){this.emotionLookup=Do(xo),this.undertoneLookup=Do(Eo),this.gestureLookup=Do(Bo),this.shapeLookup=Do(Ao),this.modifierLookup=function(t){const e=new Map;for(const[i,s]of Object.entries(t))for(const[t,n]of Object.entries(s))for(const s of n){const n=s.toLowerCase().trim();e.set(n,{type:i,level:t})}return e}(Co)}parse(t){const e={emotion:null,undertone:"clear",gestures:[],shape:null,intensity:To.normal.default,duration:Po.normal.default,transition:"smooth",repetition:"once",unrecognized:[],raw:t};if(!t||"string"!=typeof t)return e;const{tokens:i}=function(t){if(!t||"string"!=typeof t)return{tokens:[],segments:[],phrases:new Map};const e=t.toLowerCase().trim().replace(/['']/g,"'").replace(/[""]/g,'"').replace(/\s+/g," "),{processed:i,phrases:s}=function(t){const e=new Map;let i=t,s=0;for(const{normalized:t,regex:n}of uo)if(i.includes(t)){const r=`__PHRASE_${s}__`;n.lastIndex=0,i=i.replace(n,r),e.set(r,t),s++}return{processed:i,phrases:e}}(e),n=i.split(po).map(t=>t.trim()).filter(t=>t.length>0),r=[],a=[];for(const t of n){let e=t;for(const[t,i]of s)e=e.replace(t,i);a.push(e.trim());const i=t.split(/\s+/);for(const t of i){if(s.has(t)){r.push(s.get(t));continue}if(!t)continue;if(mo.has(t)&&!go.has(t))continue;const e=t.replace(/^[^\w]+|[^\w]+$/g,"");e&&r.push(e)}}return{tokens:r,segments:a,phrases:s}}(t);if(0===i.length)return e;let s=!1;for(let t=0;t<i.length;t++){const n=i[t];if(!fo(n))if(yo(n))s=!0;else if(s)s=!1;else{if(ko(n)){const s=So(n,i,t,e);if(s){this.Ji(e,s);continue}}this.Ki(n,e)||this.Zi(n,e)||this.ts(n,e)||this.es(n,e)||this.ss(n,e)||e.unrecognized.push(n)}}return e}Ji(t,e){const{category:i,target:s}=e;switch(i){case"emotion":t.emotion||(t.emotion=s);break;case"undertone":"clear"===t.undertone&&(t.undertone=s);break;case"gesture":t.gestures.includes(s)||t.gestures.push(s);break;case"shape":t.shape||(t.shape=s)}}Ki(t,e){const i=this.emotionLookup.get(t);return!(!i||e.emotion||(e.emotion=i,0))}Zi(t,e){const i=this.gestureLookup.get(t);return!(!i||e.gestures.includes(i)||(e.gestures.push(i),0))}ts(t,e){const i=this.shapeLookup.get(t);return!(!i||e.shape||(e.shape=i,0))}es(t,e){const i=this.undertoneLookup.get(t);return!(!i||"clear"!==e.undertone||(e.undertone=i,0))}ss(t,e){const i=this.modifierLookup.get(t);if(i){const{type:t,level:s}=i;switch(t){case"intensity":e.intensity=To[s]?.default||e.intensity;break;case"duration":e.duration=Po[s]?.default||e.duration;break;case"transition":e.transition=s;break;case"repetition":e.repetition=s}return!0}return!1}validate(t){const e=[];return t.emotion||0!==t.gestures.length||t.shape||e.push("No actionable intent found (need emotion, gesture, or shape)"),(t.intensity<0||t.intensity>1)&&e.push(`Intensity ${t.intensity} out of range [0, 1]`),t.duration<=0&&e.push(`Duration ${t.duration} must be positive`),{valid:0===e.length,errors:e}}static getAvailableEmotions(){return Object.keys(xo)}static getAvailableUndertones(){return Object.keys(Eo)}static getAvailableGestures(){return Object.keys(Bo)}static getAvailableShapes(){return Object.keys(Ao)}}class Fo{#t=null;constructor(t={}){this.ns=this.rs(t),this.hs=null,this.ls=[],this.cs=!1,this.us=0,this.ds=0,this.qt=!1,this.ps=!1,this.gs=new Ro,this.fs={calls:[],maxCallsPerSecond:10,windowMs:1e3},this.ys=new co,this.$i=new ro(()=>this.#e()),this.Ms=new ao(()=>this.#e(),{isRecording:()=>this.cs,startTime:()=>this.us,timeline:()=>this.ls});const e=this;this.bs=new oo(()=>this.#e(),this.$i,{get timeline(){return e.ls},set timeline(t){e.ls=t},get isRecording(){return e.cs},set isRecording(t){e.cs=t},get recordingStartTime(){return e.us},set recordingStartTime(t){e.us=t},get isPlaying(){return e.qt},set isPlaying(t){e.qt=t},get playbackStartTime(){return e.ds},set playbackStartTime(t){e.ds=t}}),this.ws=new ho(()=>this.#e(),()=>this.vs,this),this.Ss=new lo(()=>this.#e(),()=>this.vs),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)}#e(){return this.#t||this.hs}rs(t){const e={...t};return delete e.enableDebug,delete e.enableInternalAPIs,delete e.exposeInternals,e.mode="production",void 0===e.enableGazeTracking&&(e.enableGazeTracking=!0),e}init(t){if(this.ps)return Promise.resolve();this.vs="string"==typeof t?document.getElementById(t):t;const e={...this.ns,canvasId:t},i=new io(e);return this.#t=i,this.hs=new Proxy(i,{get(t,e){if(["soundSystem","stateMachine","emotionLibrary","audioLevelProcessor","particleSystem","errorBoundary","performanceMonitor","config","debugMode"].includes(e))return new Proxy({},{get(){},set:()=>!1,has:()=>!1,ownKeys:()=>[],getOwnPropertyDescriptor(){}});if("renderer"===e||"shapeMorpher"===e||"audioAnalyzer"===e||"gazeTracker"===e){const i=t[e];if(!i)return;return new Proxy(i,{get(t,i){if({renderer:["setBlinkingEnabled"],shapeMorpher:["resetMusicDetection","frequencyData"],audioAnalyzer:["microphoneStream","currentFrequencies"],gazeTracker:["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"]}[e]?.includes(i))return t[i]},set:()=>!1,has:()=>!1,ownKeys:()=>[]})}return t[e]},set:()=>!1,deleteProperty:()=>!1,defineProperty:()=>!1,getPrototypeOf:()=>null,setPrototypeOf:()=>!1,has:(t,e)=>!["soundSystem","stateMachine","emotionLibrary"].includes(e)&&e in t,ownKeys:t=>["canvas","start","stop","pause","resume","setEmotion","morphTo","express"].filter(e=>e in t)}),this.canvas=this.hs.canvas,this.ps=!0,Promise.resolve()}start(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.start()}stop(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.stop()}pause(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.pause()}resume(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.resume()}loadAudio(t){return this.$i.loadAudio(t)}getAudioAnalysis(){return this.$i.getAudioAnalysis()}connectAudio(t){return this.$i.connectAudio(t)}disconnectAudio(t){return this.$i.disconnectAudio(t)}getSpectrumData(){return this.$i.getSpectrumData()}startRhythmSync(t){return this.$i.startRhythmSync(t)}stopRhythmSync(){return this.$i.stopRhythmSync()}getPerformanceMetrics(){const t=this.#e();return t?t.performanceMonitor?{fps:t.performanceMonitor.getCurrentFPS()||0,frameTime:t.performanceMonitor.getAverageFrameTime()||0,particleCount:t.particleSystem?.activeParticles||0}:t.animationController?{fps:t.animationController.currentFPS||0,frameTime:1e3/60,particleCount:0}:{fps:0,frameTime:0,particleCount:0}:{fps:0,frameTime:0}}triggerGesture(t,e){return this.Ms.triggerGesture(t,e)}express(t,e){return this.Ms.express(t,e)}chain(t){return this.Ms.chain(t)}morphTo(t,e){return this.setShape(t,e)}updateUndertone(t){return this.Ms.updateUndertone(t)}feel(t){if(!this.#e())throw new Error("Engine not initialized. Call init() first.");const e=Date.now(),i=this.fs;if(i.calls=i.calls.filter(t=>e-t<i.windowMs),i.calls.length>=i.maxCallsPerSecond)return{success:!1,error:"Rate limit exceeded",parsed:null};i.calls.push(e);const s=this.gs.parse(t),n=this.gs.validate(s);if(!n.valid)return{success:!1,error:n.errors.join("; "),parsed:s};try{if(s.emotion){const t={};s.undertone&&"clear"!==s.undertone&&(t.undertone=s.undertone);const e=Math.round(500+1e3*(1-s.intensity));this.setEmotion(s.emotion,t,e)}for(const t of s.gestures)this.express(t);return s.shape&&this.morphTo(s.shape),{success:!0,error:null,parsed:s}}catch(t){return{success:!1,error:t.message,parsed:s}}}static getFeelVocabulary(){return{emotions:Ro.getAvailableEmotions(),undertones:Ro.getAvailableUndertones(),gestures:Ro.getAvailableGestures(),shapes:Ro.getAvailableShapes()}}parseIntent(t){return this.gs.parse(t)}setEmotion(t,e,i){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");let n=null,r=500,a=i;if("string"==typeof e)n=e;else if("number"==typeof e)void 0!==i?r=e:a=e;else if(e&&"object"==typeof e){const{undertone:t,duration:i,intensity:s}=e;n=t,void 0!==i&&(r=i),void 0!==s&&(this.ks=s)}if(this.cs){const e=a||Date.now()-this.us;this.ls.push({type:"emotion",name:t,undertone:n,time:e})}const o={};return n&&(o.undertone=n),void 0!==this.ks&&(o.intensity=this.ks,this.ks=void 0),s.setEmotion(t,Object.keys(o).length?o:null,r),this}setSoundEnabled(t){const e=this.#e();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.soundSystem&&(e.soundSystem.enabled=t),this}pushEmotion(t,e=.5){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.pushEmotion(t,e),this}nudgeEmotion(t,e,i=1){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");return s.stateCoordinator.nudgeEmotion(t,e,i),this}setEmotionDampening(t){const e=this.#e();if(!e)throw new Error("Engine not initialized. Call init() first.");return e.stateCoordinator.setEmotionDampening(t),this}getEmotionDampening(){const t=this.#e();return t?t.stateCoordinator.getEmotionDampening():0}clearEmotions(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.stateCoordinator.clearEmotions(),this}getEmotionalState(){const t=this.#e();return t?t.stateCoordinator.getEmotionalState():{dominant:null,undercurrents:[],slots:[]}}getSnapshot(){const t=this.#e();if(!t)return null;const e={version:1,timestamp:Date.now(),stateMachine:t.stateMachine.serialize()};return t.stateCoordinator.ci&&(e.dynamics=t.stateCoordinator.ci.serialize()),e}loadSnapshot(t){const e=this.#e();return e&&t&&1===t.version?(t.stateMachine&&e.stateMachine.deserialize(t.stateMachine),t.dynamics&&e.stateCoordinator.dynamics.deserialize(t.dynamics),e.stateCoordinator.ti("emotionChanged",{emotion:e.stateMachine.state.emotion,slots:e.stateMachine.getSlots(),restored:!0}),this):this}get dynamics(){const t=this.#e();return t?t.stateCoordinator.dynamics:null}getInputEvaluator(t){return this.$i.getInputEvaluator(t)}setEmotionFeedback(t){const e=this.getInputEvaluator();return e&&e.setEmotionFeedback(t),this}getAudioLayers(){const t=this.$i.getLayers();return t?Object.freeze({...t}):null}getEffectiveBPM(){const t=this.#e();if(!t||!t.rhythmIntegration)return 120;let e=t.rhythmIntegration.getEffectiveBPM(t.stateMachine);return e*=this.$i.getDifficultyManager().getBPMMultiplier(),Math.round(100*e)/100}setDifficulty(t){return this.$i.getDifficultyManager().setDifficulty(t),this}setAssist(t){return this.$i.getDifficultyManager().setAssist(t),this}applyModifier(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");return i.stateCoordinator.modifiers.applyModifier(t,e),this}removeModifier(t){const e=this.#e();return e?(e.stateCoordinator.modifiers.removeModifier(t),this):this}getActiveModifiers(){const t=this.#e();return t?t.stateCoordinator.modifiers.getActiveModifiers():[]}setShape(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");let s=t;if(this.ys.hasStance(t)){const e=this.ys.activate(t);s=e.shape||t,i.stateCoordinator&&i.stateCoordinator.ti("stanceChanged",{name:t,config:e})}let n,r={};if("number"==typeof e)n=e;else if(e&&"object"==typeof e){const{timestamp:t,...i}=e;r=i,n=t}if(this.cs){const t=n||Date.now()-this.us;this.ls.push({type:"shape",name:s,time:t,config:r})}return i&&i.morphTo(s,r),this}registerStance(t,e){return this.ys.registerStance(t,e),this}getActiveStance(){return this.ys.getActiveStance()}getAvailableStances(){return this.ys.getAvailableStances()}dismissStance(){if(this.ys.dismiss()){const t=this.#e();t&&t.stateCoordinator&&t.stateCoordinator.ti("stanceChanged",{name:null,config:null})}return this}enableGazeTracking(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.gazeTracker&&t.gazeTracker.enable(),this}disableGazeTracking(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");t.gazeTracker&&t.gazeTracker.disable()}setGazeTarget(t,e){const i=this.#e();if(!i)throw new Error("Engine not initialized. Call init() first.");i.gazeTracker&&(i.gazeTracker.mousePos={x:t,y:e},i.gazeTracker.updateTargetGaze())}setContainment(t,e=1){return this.Ss.setContainment(t,e)}setPosition(t,e,i=0){const s=this.#e();if(!s)throw new Error("Engine not initialized. Call init() first.");if(s.positionController)s.positionController.onUpdate||(s.positionController.onUpdate=()=>{}),s.positionController.setOffset(t,e,i);else if(this.vs){const s=window.innerWidth/2+t,n=window.innerHeight/2+e,r=1+.001*i;this.vs.style.transform=`translate(${s}px, ${n}px) translate(-50%, -50%) scale(${r})`}}animateToPosition(t,e,i=0,s=1e3,n="easeOutCubic"){const r=this.#e();if(!r)throw new Error("Engine not initialized. Call init() first.");r.positionController?(r.positionController.onUpdate||(r.positionController.onUpdate=()=>{}),r.positionController.animateOffset(t,e,i,s,n)):this.setPosition(t,e,i)}clearParticles(){return this.Ss.clearParticles()}setParticleSystemCanvasDimensions(t,e){return this.Ss.setParticleSystemCanvasDimensions(t,e),this}attachToElement(t,e={}){return this.ws.attachToElement(t,e)}isAttachedToElement(){return this.ws.isAttachedToElement()}detachFromElement(){return this.ws.detachFromElement()}getGazeState(){const t=this.#e();if(!t)throw new Error("Engine not initialized. Call init() first.");return t.gazeTracker?t.gazeTracker.getState():null}setBPM(t){t=Math.max(0,Math.min(300,Number(t)||0));const e=this.#e();return e&&e.rhythmIntegration&&e.rhythmIntegration.setBPM(t),this}setQuality(t){const e={low:{particleCount:50,fps:30},medium:{particleCount:100,fps:60},high:{particleCount:200,fps:60}},i=e[t]||e.medium,s=this.#e();s&&s.performanceMonitor&&s.performanceMonitor.setTargetFPS(i.fps),s&&s.particleSystem&&s.particleSystem.setMaxParticles(i.particleCount)}setMaxParticles(t){t=Math.max(0,Math.min(1e3,Math.floor(Number(t)||0)));const e=this.#e();return e&&e.particleSystem&&e.particleSystem.setMaxParticles(t),this}getParticleCount(){const t=this.#e();return t&&t.particleSystem&&t.particleSystem.particles?t.particleSystem.particles.length:0}setOpacity(t){const e=this.#e();if(t=Math.max(0,Math.min(1,t)),e&&e.renderer){const i=e.canvasManager?.getContext();i&&(i.globalAlpha=t)}return this.xs=t,this}getOpacity(){return void 0!==this.xs?this.xs:1}fadeIn(t=1e3){const e=this.getOpacity(),i=performance.now(),s=n=>{const r=n-i,a=Math.min(r/t,1),o=e+(1-e)*a;this.setOpacity(o),a<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}fadeOut(t=1e3){const e=this.getOpacity(),i=performance.now(),s=n=>{const r=n-i,a=Math.min(r/t,1),o=e*(1-a);this.setOpacity(o),a<1&&requestAnimationFrame(s)};return requestAnimationFrame(s),this}async transitionTo(t,e={}){const i=e.fadeOutMs??500,s=e.fadeInMs??500;await new Promise(t=>{const e=this.getOpacity(),s=performance.now(),n=r=>{const a=Math.min((r-s)/i,1);this.setOpacity(e*(1-a)),a<1?requestAnimationFrame(n):t()};requestAnimationFrame(n)}),t&&t(this),await new Promise(t=>{const e=performance.now(),i=n=>{const r=Math.min((n-e)/s,1);this.setOpacity(r),r<1?requestAnimationFrame(i):t()};requestAnimationFrame(i)})}setAmbientMood(t){let e;if("string"==typeof t){if(e=this.Es?.[t],!e)return this}else e=t;return this.Bs={...e},e.tint&&this.setColor(e.tint),this}registerAmbientPreset(t,e){if("__proto__"===t||"constructor"===t||"prototype"===t)return this;this.Es||(this.Es={});const i={};for(const t of Object.keys(e))"__proto__"!==t&&"constructor"!==t&&"prototype"!==t&&(i[t]=e[t]);return this.Es[t]=i,this}getAmbientMood(){return this.Bs?{...this.Bs}:null}setColor(t){const e=this.#e();return e&&e.renderer&&e.renderer.config&&(e.renderer.config.coreColor=t),this}setGlowColor(t){const e=this.#e();return e&&e.renderer&&e.renderer.config&&(e.renderer.config.defaultGlowColor=t),this}setTheme(t){return t&&"object"==typeof t?(t.core&&this.setColor(t.core),t.glow&&this.setGlowColor(t.glow),this):this}setSpeed(t){const e=this.#e();return t=Math.max(.1,Math.min(10,t)),this.As=t,e&&e.animationController&&e.animationController.setSpeedMultiplier(t),this}getSpeed(){const t=this.#e();return t&&t.animationController?t.animationController.getSpeedMultiplier():this.As||1}setFPS(t){const e=this.#e();return t=Math.max(1,Math.min(120,t)),e&&e.animationController&&e.animationController.setTargetFPS(t),this}getFPS(){const t=this.#e();return t&&t.animationController&&t.animationController.targetFPS||60}isPaused(){const t=this.#e();return!(!t||!t.animationController)&&!0===t.animationController.isPaused}batch(t){const e=this.isPaused();return e||this.pause(),"function"==typeof t&&t(this),e||this.resume(),this}on(t,e){const i=this.#e();return i&&i.eventManager&&i.eventManager.on(t,e),this}off(t,e){const i=this.#e();return i&&i.eventManager&&i.eventManager.off(t,e),this}setScale(t){const e=this.#e();return e&&e.positionController&&(e.positionController.setScaleOverrides(t),"object"==typeof t&&void 0!==t.particles&&e.particleSystem&&"function"==typeof e.particleSystem.refreshPool&&e.particleSystem.refreshPool()),this}getScale(){const t=this.#e();return t&&t.positionController&&t.positionController.globalScale||1}setBackdrop(t={}){const e=this.#e();return e&&"function"==typeof e.setBackdrop&&e.setBackdrop(t),this}getBackdrop(){const t=this.#e();return t&&"function"==typeof t.getBackdrop?t.getBackdrop():null}startRecording(){return this.bs.startRecording()}stopRecording(){return this.bs.stopRecording()}playTimeline(t){return this.bs.playTimeline(t)}stopPlayback(){return this.bs.stopPlayback()}getTimeline(){return this.bs.getTimeline()}loadTimeline(t){return this.bs.loadTimeline(t)}exportTimeline(){return this.bs.exportTimeline()}importTimeline(t){return this.bs.importTimeline(t)}getCurrentTime(){return this.bs.getCurrentTime()}seek(t){return this.bs.seek(t)}getFrameData(t="png"){return this.Ss.getFrameData(t)}getFrameBlob(t="png"){return this.Ss.getFrameBlob(t)}getAnimationData(){return this.bs.getAnimationData()}getAvailableGestures(){return zi()}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 t=this.#e();return t&&t.renderer?new Proxy(t.renderer,{get:(t,e)=>["setBlinkingEnabled"].includes(e)?t[e]:void 0}):null}get shapeMorpher(){const t=this.#e();return t&&t.shapeMorpher?new Proxy(t.shapeMorpher,{get:(t,e)=>["resetMusicDetection","frequencyData"].includes(e)?t[e]:void 0}):null}get gazeTracker(){const t=this.#e();return t&&t.gazeTracker?new Proxy(t.gazeTracker,{get:(t,e)=>["enable","disable","mousePos","updateTargetGaze","currentGaze","getState"].includes(e)?t[e]:void 0}):null}destroy(){this.stop(),this.ls=[],this.cs=!1,this.qt=!1,this.detachFromElement();const t=this.#e();t&&t.destroy&&t.destroy()}}class zo{constructor(t={}){this.Ie=this.deepClone(t),this.Cs=this.deepClone(t),this.Ts=new Map,this.X=[],this.Ps=50,this.Ds=[],this.Rs=new Map,this.Fs=new Map,this.zs=new Map,this.qs={updates:0,notifications:0,computedCacheHits:0,computedCacheMisses:0}}getState(t=null){return t?this.deepClone(this.getNestedValue(this.Ie,t)):this.deepClone(this.Ie)}setState(t,e=void 0){let i;i="string"==typeof t?{[t]:e}:t;for(const t of this.Ds)if(i=t(i,this.Ie),!i)return!1;const s=this.deepClone(this.Ie);for(const[t,e]of Object.entries(i)){if(this.Rs.has(t)&&!this.Rs.get(t)(e))return!1;this.setNestedValue(s,t,e)}return this.Cs=this.Ie,this.Ie=s,this.addToHistory(i),this.invalidateComputed(Object.keys(i)),this.notifySubscribers(i),this.qs.updates++,!0}subscribe(t,e=null){let i=null,s=t;"string"==typeof t&&(i=t,s=e);const n=Symbol("subscriber"),r={path:i,callback:s,id:n};return this.Ts.set(n,r),()=>{this.Ts.delete(n)}}computed(t,e,i){this.zs.set(t,e),Object.defineProperty(this,t,{get:()=>{if(this.Fs.has(t))return this.qs.computedCacheHits++,this.Fs.get(t);this.qs.computedCacheMisses++;const s=e.map(t=>this.getState(t)),n=i(...s);return this.Fs.set(t,n),n}})}addValidator(t,e){this.Rs.set(t,e)}addMiddleware(t){this.Ds.push(t)}reset(t={}){this.Ie=this.deepClone(t),this.Cs=this.deepClone(t),this.X=[],this.Fs.clear(),this.notifySubscribers({"*":"reset"})}getDiff(){return this.objectDiff(this.Cs,this.Ie)}undo(t=1){if(this.X.length<t)return!1;const e=Math.max(0,this.X.length-t-1),i=this.X[e];return!!i&&(this.Ie=this.deepClone(i.state),this.X=this.X.slice(0,e+1),this.notifySubscribers({"*":"undo"}),!0)}batch(t){const e={},i=this.setState.bind(this);return this.setState=(t,i)=>("string"==typeof t?e[t]=i:Object.assign(e,t),!0),t(),this.setState=i,this.setState(e)}createSelector(t){let e=null,i=null;return()=>{const s=this.Ie;return s===e||(e=s,i=t(s)),i}}static Os=new Set(["__proto__","constructor","prototype"]);notifySubscribers(t){for(const e of this.Ts.values())e.path&&!Object.keys(t).some(t=>t.startsWith(e.path)||e.path.startsWith(t))||(e.callback(this.Ie,t),this.qs.notifications++)}invalidateComputed(t){for(const[e,i]of this.zs.entries())i.some(e=>t.some(t=>e.startsWith(t)||t.startsWith(e)))&&this.Fs.delete(e)}addToHistory(t){this.X.push({timestamp:Date.now(),updates:t,state:this.deepClone(this.Ie)}),this.X.length>this.Ps&&this.X.shift()}deepClone(t){if(null===t||"object"!=typeof t)return t;if(t instanceof Date)return new Date(t.getTime());if(t instanceof Array)return t.map(t=>this.deepClone(t));if(t instanceof Object){const e={};for(const i in t)({}).hasOwnProperty.call(t,i)&&(e[i]=this.deepClone(t[i]));return e}}getNestedValue(t,e){const i=e.split(".");for(const t of i)if(zo.Os.has(t))return;return i.reduce((t,e)=>t&&void 0!==t[e]?t[e]:void 0,t)}setNestedValue(t,e,i){const s=e.split(".");for(const t of s)if(zo.Os.has(t))return;const n=s.pop();s.reduce((t,e)=>(t[e]||(t[e]={}),t[e]),t)[n]=i}js(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(typeof t!=typeof e)return!1;if("object"!=typeof t)return!1;const i=Array.isArray(t);if(i!==Array.isArray(e))return!1;if(i){if(t.length!==e.length)return!1;for(let i=0;i<t.length;i++)if(!this.js(t[i],e[i]))return!1;return!0}const s=Object.keys(t),n=Object.keys(e);if(s.length!==n.length)return!1;for(const i of s){if(!{}.hasOwnProperty.call(e,i))return!1;if(!this.js(t[i],e[i]))return!1}return!0}objectDiff(t,e){const i={};for(const s in e)s in t?this.js(t[s],e[s])||(i[s]={type:"changed",oldValue:t[s],newValue:e[s]}):i[s]={type:"added",value:e[s]};for(const s in t)s in e||(i[s]={type:"deleted",oldValue:t[s]});return i}getStats(){return{...this.qs,subscribers:this.Ts.size,historySize:this.X.length,computedValues:this.Fs.size,validators:this.Rs.size}}}const qo=new zo({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}});t.BUILD_TYPE="lean",t.CanvasManager=ks,t.ENGINE_NAME="Emotive Engine Lean",t.EmotiveMascot=io,t.EmotiveMascotPublic=Fo,t.EmotiveRenderer=hr,t.ErrorBoundary=e,t.EventManager=Ms,t.FEATURES={rhythmSync:!1,grooveTemplates:!1,undertones:!1,undertoneSaturation:!1,gestureBlending:!0,audioReactive:!1,particleSystem:!0,accessibility:!1,mobileOptimization:!0,performanceMonitoring:!1},t.GESTURE_TYPES=Bi,t.ParticleSystem=en,t.PositionController=Er,t.StateStore=zo,t.VERSION="3.4.0-lean",t.applyEasing=Hs,t.applyGesture=Fi,t.default=Fo,t.easeInOutQuad=zs,t.easeInOutSine=_s,t.easeOutCubic=qs,t.engineState=qo,t.eventManager=bs,t.getEmotion=l,t.getEmotionVisualParams=c,t.getGesture=Pi,t.hasEmotion=m,t.interpolateHsl=Cs,t.listEmotions=d,t.listGestures=zi,Object.defineProperty(t,"Is",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=emotive-mascot.lean.umd.js.map
|