@streamoji/avatar-widget 0.5.6 → 0.5.8

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.
@@ -1,9 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),yt=require("@react-three/drei"),Ct=require("@react-three/fiber"),t=require("react"),wn=require("three"),yn=require("three/examples/jsm/loaders/GLTFLoader.js");function Sn(l){const m=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const S in l)if(S!=="default"){const g=Object.getOwnPropertyDescriptor(l,S);Object.defineProperty(m,S,g.get?g:{enumerable:!0,get:()=>l[S]})}}return m.default=l,Object.freeze(m)}const dt=Sn(wn),st="https://ai.streamoji.com",C=(...l)=>{},Rn=(...l)=>{},qt=({analyser:l})=>{const m=t.useRef(null),S=t.useRef(null);return t.useEffect(()=>{const g=m.current;if(!g)return;const $=g.getContext("2d",{alpha:!0});if(!$)return;let Y,X=null;l&&(l.fftSize=128,X=new Uint8Array(l.frequencyBinCount));const Ke=()=>{Y=requestAnimationFrame(Ke),(g.width!==g.offsetWidth||g.height!==g.offsetHeight)&&(g.width=g.offsetWidth,g.height=g.offsetHeight);const Pe=g.width,N=g.height;if(Pe===0||N===0)return;const ot=N/2;$.clearRect(0,0,Pe,N),$.fillStyle="#1e293b";const Se=2,V=Se+2,ke=Pe*.95,G=Math.floor(ke/V);(!S.current||S.current.length!==G)&&(S.current=new Float32Array(G).fill(2));const ie=G*V,I=(Pe-ie)/2;l&&X&&l.getByteFrequencyData(X);const fe=X?X.length:0,_=Math.floor(fe*.7)/G,ne=new Float32Array(G);for(let p=0;p<G;p++){let O=0;if(X&&_>0){const U=Math.floor(p*_),j=Math.floor((p+1)*_);for(let q=U;q<j;q++){const K=X[q]||0;K>O&&(O=K)}}O<10&&(O=0);const J=O/255,T=O>0?Math.max(2,Math.pow(J,1.4)*N*.25):2;ne[p]=T}for(let p=0;p<G;p++){const O=G-1-p,J=Math.max(ne[p],ne[O]),T=S.current[p]+(J-S.current[p])*.3;S.current[p]=T;const U=I+p*V,j=ot-T/2;$.beginPath(),$.roundRect?$.roundRect(U,j,Se,T,4):$.fillRect(U,j,Se,T),$.fill()}};return Ke(),()=>{cancelAnimationFrame(Y)}},[l]),c.jsx("canvas",{ref:m,style:{width:"100%",height:"100%",display:"block"}})},vn="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",zt="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";function xn(l){const[m,S]=t.useState(null);return t.useEffect(()=>{if(!l){S(null);return}let g=!1;const $=`${vn}/${l}.glb`;return fetch($,{method:"HEAD"}).then(Y=>{g||S(Y.ok?$:zt)}).catch(()=>{g||S(zt)}),()=>{g=!0}},[l]),m}const Ln=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],kn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],En=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],Tn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"],Mn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"],An={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},In=[-.45,1.9,.1],On=[-.45,1.75,.1],Dn={browInnerUp:.2},At=.18,Cn=1,Nn=.5,Yt=3,bt=.55,It=.12,Kt=2,Qt=2,_t=4,Xt=8,Un=1,Zt=.38,en=.32,tn="__branding__",wt={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},sn=[{key:"viseme_aa",mix:{jawOpen:.6},teethMix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2},teethMix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2},teethMix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1},teethMix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.8,mouthRollUpper:.8,mouthUpperUpLeft:.3,mouthUpperUpRight:.3},teethMix:{mouthRollLower:.8,mouthRollUpper:.8,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:1},teethMix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:1}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.6,jawOpen:.2,tongueOut:.4},teethMix:{mouthRollUpper:.6,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2},teethMix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2},teethMix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15},teethMix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2},teethMix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],Fn={aei:[{v:"E",w:.8},{v:"I",w:.2}],ee:[{v:"I",w:1}],oo:[{v:"O",w:1}],u:[{v:"U",w:1}],aa:[{v:"aa",w:1}],ah:[{v:"aa",w:.7},{v:"O",w:.3}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],th:[{v:"TH",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],chjsh:[{v:"CH",w:1}],cdgknstxyz:[{v:"DD",w:.6},{v:"SS",w:.4}],sil:[{v:"sil",w:1}]},Ot=new Set(sn.flatMap(l=>[...Object.keys(l.mix),...l.teethMix?Object.keys(l.teethMix):[]]));function nn(l){const m=Math.max(0,Math.min(1,l));return m*m*(3-2*m)}function jn(l,m,S){if(S<=0)return 0;const g=(l-m)/S;return g<0||g>1?0:g<.25?nn(g/.25):g>.75?nn((1-g)/.25):1}function Pn(l){if(!l)return[{v:"sil",w:1}];const m=l.toLowerCase();return Fn[m]??[{v:"sil",w:1}]}function Bn({target:l}){const{camera:m}=Ct.useThree();return t.useEffect(()=>{m.lookAt(...l)},[m,l]),null}function u(l,m,S){if(!l||!l.morphTargetDictionary)return;const g=l,$=g.morphTargetDictionary,Y=g.morphTargetInfluences;if(Y)for(const X in $)X.toLowerCase()===m.toLowerCase()&&(Y[$[X]]=S)}const Wn=t.memo(({avatarUrl:l,isPlayingRef:m,visemeQueueRef:S,audioContextRef:g,responseAudioStartTimeRef:$,adjustments:Y,mood:X,expression:Ke,agentResponse:Pe,isSpeaking:N,nextStartTimeRef:ot,stopPlayback:Se,setIsSpeaking:Qe,expressionUrl:V,onExpressionFinished:ke,isNudgeResponse:G,avatarGender:ie})=>{const{scene:I}=yt.useGLTF(l),fe=ie==="female"?kn:Ln,W=yt.useGLTF(fe),_=t.useMemo(()=>W.flatMap(w=>w.animations),[W]),ne=ie==="female"?Mn:Tn,p=yt.useGLTF(ne),O=t.useMemo(()=>p.flatMap(w=>w.animations),[p]),J=t.useRef(null),T=t.useRef(null),U=t.useRef(null),j=t.useRef(null),q=t.useRef(null),K=t.useRef(null),St=t.useRef([]),[Z]=t.useState(()=>new dt.AnimationMixer(I)),H=t.useRef({}),P=t.useRef(null),Ee=t.useRef(0),Xe=t.useRef(!1),Be=t.useRef(0),Te=t.useRef(!1),be=t.useRef(null),Me=t.useRef(Yt),ht=t.useRef(-1),Ae=t.useRef("left"),We=t.useRef(_t+Math.random()*(Xt-_t)),de=t.useRef(0),Ie=t.useRef("smile"),Oe=t.useRef({});t.useEffect(()=>{if(!(!_||!I)){if(_.forEach((w,b)=>{const o=`idle_${b}`;if(!H.current[o]){const f=Z.clipAction(w,I);f.name=o,f.setLoop(dt.LoopOnce,1),f.clampWhenFinished=!0,H.current[o]=f}}),O.forEach((w,b)=>{const o=`talk_${b}`;if(!H.current[o]){const f=Z.clipAction(w,I);f.name=o,f.setLoop(dt.LoopOnce,1),f.clampWhenFinished=!0,H.current[o]=f}}),_.length>0){const w=H.current.idle_0,b=P.current&&Z.existingAction(P.current.getClip());w&&!b&&(w.reset().fadeIn(.5).play(),P.current=w)}return()=>{Z.stopAllAction(),H.current={},P.current=null}}},[_,O,I,Z]);const Ze=t.useRef("");t.useEffect(()=>{if(!V||!I||V===Ze.current)return;Ze.current=V,be.current=V,new yn.GLTFLoader().load(V,b=>{if(b.animations&&b.animations.length>0){const o=b.animations[0],f=Z.clipAction(o,I);if(f.name=`EXPR_${V}`,f.setLoop(dt.LoopOnce,1),f.clampWhenFinished=!0,H.current[`EXPR_${V}`]=f,N&&be.current===V){const R=P.current;f.reset().fadeIn(.3).play(),R&&R!==f&&R.crossFadeTo(f,.3,!0),P.current=f,be.current=null}}},void 0,b=>{console.error(`[ANIMATION] Failed to load ${V}`,b)})},[V,I,Z,N]),t.useEffect(()=>{const w=b=>{const o=b.action,f=o.name||"";if(f.startsWith("idle_")){const ee=(parseInt(f.split("_")[1])+1)%_.length,te=H.current[`idle_${ee}`];te&&(te.reset().fadeIn(.5).play(),o.crossFadeTo(te,.5,!0),P.current=te)}else if(f.startsWith("EXPR_")){if(N){const R=Math.floor(Math.random()*O.length),ee=H.current[`talk_${R}`];ee&&(ee.reset().fadeIn(.5).play(),o.crossFadeTo(ee,.5,!0),P.current=ee)}else{const R=H.current.idle_0;R&&(R.reset().fadeIn(.5).play(),o.crossFadeTo(R,.5,!0),P.current=R)}ke&&ke()}else if(f.startsWith("talk_"))if(N&&!G){const ee=(parseInt(f.split("_")[1])+1)%O.length,te=H.current[`talk_${ee}`];te&&(te.reset().fadeIn(.3).play(),o.crossFadeTo(te,.3,!0),P.current=te)}else{const R=H.current.idle_0;R&&(R.reset().fadeIn(.5).play(),o.crossFadeTo(R,.5,!0),P.current=R)}};return Z.addEventListener("finished",w),()=>Z.removeEventListener("finished",w)},[Z,_,O,N,G,ke]),t.useEffect(()=>{if(N&&I){const w=P.current,b=w?.name||"";if(b.startsWith("idle_")||b.startsWith("talk_")||b===""){const o=be.current;if(o){const f=H.current[`EXPR_${o}`];if(f){f.reset().fadeIn(.3).play(),w&&w!==f&&w.crossFadeTo(f,.3,!0),P.current=f,be.current=null;return}}if(b.startsWith("idle_")||b===""){const f=Math.floor(Math.random()*O.length),R=H.current[`talk_${f}`];R&&(R.reset().fadeIn(.5).play(),w&&w.crossFadeTo(R,.5,!0),P.current=R)}}}else if(!N&&I){const w=P.current,b=w?.name||"";if(b.startsWith("talk_")||b.startsWith("EXPR_")){const o=H.current.idle_0;o&&(o.reset().fadeIn(.5).play(),w&&w.crossFadeTo(o,.5,!0),P.current=o)}}},[N,I,V]),t.useEffect(()=>{if(!I)return;I.traverse(o=>{if(o.isMesh&&o.morphTargetDictionary){const f=o.name.toLowerCase();(f.includes("head")||f.includes("avatar"))&&(T.current=o,C(`[ANIMATION] Found head mesh: ${o.name}`)),f.includes("teeth")&&(U.current=o,C(`[ANIMATION] Found teeth mesh: ${o.name}`)),f.includes("beard")&&(j.current=o,C(`[ANIMATION] Found beard mesh: ${o.name}`)),f.includes("eyeleft")&&(q.current=o,C(`[ANIMATION] Found eye left mesh: ${o.name}`)),f.includes("eyeright")&&(K.current=o,C(`[ANIMATION] Found eye right mesh: ${o.name}`))}});const w=T.current?.morphTargetDictionary;w&&Object.keys(w).filter(o=>o.toLowerCase().includes("brow"));const b=[];I.traverse(o=>{if(o.isMesh){const R=o.morphTargetDictionary;R&&Object.keys(R).some(ee=>ee.toLowerCase().includes("brow"))&&b.push(o)}}),St.current=b,b.length>0&&C("[ANIMATION] Meshes with brow morphs:",b.length)},[I]);const it=w=>{const b=wt[w]??wt.neutral;for(const o in b)u(T.current,o,b[o]),u(U.current,o,b[o]),u(j.current,o,b[o])};return Ct.useFrame((w,b)=>{it(X);const o=w.clock.elapsedTime;let f=0;if(Math.floor(o)%5===0&&Math.floor((o-b)%5)!==0){let h=null;I.traverse(E=>{E.name.toLowerCase().includes("hips")&&(h=E)});const A=h?`Hips Y: ${h.position.y.toFixed(4)}`:"Hips not found";C(`[ANIMATION] Mixer Time: ${Z.time.toFixed(2)}, ${A}`)}if(Z.update(b),o>Ee.current&&!Xe.current&&(Xe.current=!0,Be.current=o),Xe.current){const h=N?.2:.3,A=(o-Be.current)/h;if(A>=1)if(Xe.current=!1,Te.current){const E=N?1:2.5;Ee.current=o+E,Te.current=!1}else Ee.current=o+.12,Te.current=!0;else{const E=A<.5?A*2:(1-A)*2;u(T.current,"eyeBlinkLeft",E),u(T.current,"eyeBlinkRight",E),u(U.current,"eyeBlinkLeft",E),u(U.current,"eyeBlinkRight",E),u(j.current,"eyeBlinkLeft",E),u(j.current,"eyeBlinkRight",E),f=E*Dn.browInnerUp}}const R=wt[X]??wt.neutral,ee=R.browInnerUp??0,te=R.browOuterUpLeft??0,ae=R.browOuterUpRight??0,et=o*Cn,De=At*Math.sin(et),$e=At*.7*Math.sin(et+.7),tt=At*.7*Math.sin(et+1.3),k=h=>Math.max(0,Math.min(1,h)),at=k(ee+De),Ve=k(te+$e),He=k(ae+tt),Ge=k(at+f);u(T.current,"browInnerUp",Ge),u(U.current,"browInnerUp",Ge),u(j.current,"browInnerUp",Ge),u(T.current,"browOuterUpLeft",Ve),u(U.current,"browOuterUpLeft",Ve),u(j.current,"browOuterUpLeft",Ve),u(T.current,"browOuterUpRight",He),u(U.current,"browOuterUpRight",He),u(j.current,"browOuterUpRight",He);const Re=Me.current,re=Re+bt,Ce=re+It;o>Ce&&(Me.current+=bt+It+Yt);const Je=!N&&o>=Re&&o<re,Ne=!N&&o>=re&&o<Ce;(Je||Ne)&&ht.current!==Re&&(ht.current=Re,Ae.current=Math.random()<.7?"left":"up");const ce=Je?o-Re:Ne?bt:0,qe=Je||Ne?Math.min(1,ce/bt):0,ct=qe<=0?0:Math.sin(qe*Math.PI),Rt=Ne?1-(o-re)/It:1,ut=Je?ct:Ne?ct*Rt:0,z=Nn*ut,M=h=>R[h]??0;if(Ae.current==="up"?(u(q.current,"eyeLookUpLeft",k(M("eyeLookUpLeft")+z)),u(q.current,"eyeLookDownLeft",k(M("eyeLookDownLeft"))),u(q.current,"eyeLookOutLeft",k(M("eyeLookOutLeft"))),u(q.current,"eyeLookInLeft",k(M("eyeLookInLeft"))),u(K.current,"eyeLookUpRight",k(M("eyeLookUpRight")+z)),u(K.current,"eyeLookDownRight",k(M("eyeLookDownRight"))),u(K.current,"eyeLookOutRight",k(M("eyeLookOutRight"))),u(K.current,"eyeLookInRight",k(M("eyeLookInRight")))):(u(q.current,"eyeLookUpLeft",k(M("eyeLookUpLeft"))),u(q.current,"eyeLookDownLeft",k(M("eyeLookDownLeft"))),u(q.current,"eyeLookOutLeft",k(M("eyeLookOutLeft"))),u(q.current,"eyeLookInLeft",k(M("eyeLookInLeft")+z)),u(K.current,"eyeLookUpRight",k(M("eyeLookUpRight"))),u(K.current,"eyeLookDownRight",k(M("eyeLookDownRight"))),u(K.current,"eyeLookOutRight",k(M("eyeLookOutRight")+z)),u(K.current,"eyeLookInRight",k(M("eyeLookInRight")))),!N&&o>=We.current){de.current=o,Ie.current=Math.random()<.5?"pucker":"smile";const h=Ie.current==="pucker"?Qt:Kt;We.current=o+h+_t+Math.random()*(Xt-_t)}const ue=Ie.current==="pucker"?Qt:Kt,lt=!N&&o>=de.current&&o<de.current+ue,Ue=lt?(o-de.current)/ue:0,he=Ue<=0?0:Ue<.5?Ue*2:(()=>{const h=(Ue-.5)*2;return 1-h*h*(3-2*h)})(),ve=h=>R[h]??0;if(lt)if(Ie.current==="pucker"){const h=k(ve("mouthPucker")+Un*he);u(T.current,"mouthPucker",h),u(U.current,"mouthPucker",h),u(j.current,"mouthPucker",h)}else{const h=k(ve("mouthSmileLeft")+Zt*he),A=k(ve("mouthSmileRight")+Zt*he),E=k(ve("mouthDimpleLeft")+en*he),_e=k(ve("mouthDimpleRight")+en*he);u(T.current,"mouthSmileLeft",h),u(T.current,"mouthSmileRight",A),u(T.current,"mouthDimpleLeft",E),u(T.current,"mouthDimpleRight",_e),u(U.current,"mouthSmileLeft",h),u(U.current,"mouthSmileRight",A),u(U.current,"mouthDimpleLeft",E),u(U.current,"mouthDimpleRight",_e),u(j.current,"mouthSmileLeft",h),u(j.current,"mouthSmileRight",A),u(j.current,"mouthDimpleLeft",E),u(j.current,"mouthDimpleRight",_e)}if(J.current){const h=m.current?0:Y.rotation[1];J.current.rotation.y=dt.MathUtils.lerp(J.current.rotation.y,h,.1),J.current.position.set(...Y.position),J.current.scale.setScalar(Y.scale),J.current.rotation.x=Y.rotation[0],J.current.rotation.z=Y.rotation[2]}const le={};if(Ot.forEach(h=>{le[h]=0}),m.current&&g.current){const h=g.current.currentTime,_e=(h-$.current)*1e3- -150;for(let Fe=0;Fe<S.current.length;Fe++){const xe=S.current[Fe];if(_e<xe.vtime||_e>=xe.vtime+xe.vduration)continue;const mt=jn(_e,xe.vtime,xe.vduration),vt=`viseme_${xe.viseme}`.toLowerCase(),je=sn.find(se=>se.key.toLowerCase()===vt);if(!je)continue;const me=(xe.weight??1)*mt;for(const se in je.mix)le[se]=(le[se]??0)+je.mix[se]*me;if(je.teethMix)for(const se in je.teethMix)le[se]=(le[se]??0)+je.teethMix[se]*me}h>ot.current+.5&&(Se(),Qe(!1))}const nt=Oe.current;Ot.forEach(h=>{const A=le[h]??0,E=nt[h]??0;nt[h]=Math.max(0,Math.min(1,E+(A-E)*(1-Math.exp(-12*b))))}),Ot.forEach(h=>{const A=nt[h]??0;u(T.current,h,A),u(j.current,h,A),u(U.current,h,A)})}),c.jsx("group",{ref:J,children:c.jsx("primitive",{object:I})})});function $n(l){return l?l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():""}function rn(l){return l.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const Dt=new Map,Vn=({onNavigationRequested:l,agentId:m,presetUserDetails:S,onAvatarReady:g})=>{const[$,Y]=t.useState(""),[X,Ke]=t.useState("male"),[Pe,N]=t.useState(""),[ot,Se]=t.useState(!1),Qe=$,V=X;t.useEffect(()=>{if(!m){Se(!0);return}let e=!1;return(async()=>{console.log(">> fetchConfig RUNNING for",m);try{const s=`agent_config_${m}`,i=sessionStorage.getItem(s);if(i)try{const a=JSON.parse(i);e||(a.encryptedAgentToken&&Y(a.encryptedAgentToken),a.avatarGender&&Ke(a.avatarGender),a.agent_id&&N(a.agent_id),Se(!0));return}catch(a){console.error("Failed to parse cached avatar config:",a),sessionStorage.removeItem(s)}let r;if(Dt.has(m))console.log(">> REUSING in-flight fetch for",m),r=await Dt.get(m);else{const a=(async()=>{console.log(">> INITIATING visitedWebsite fetch for",m);const d={agentId:m},y=await fetch(`${st}/visitedWebsite`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)});if(!y.ok)throw new Error(`Fetch failed: ${y.status}`);const v=await y.json();return sessionStorage.setItem(s,JSON.stringify(v)),v})();Dt.set(m,a),r=await a}if(e)return;r&&(r.encryptedAgentToken&&Y(r.encryptedAgentToken),r.avatarGender&&Ke(r.avatarGender),r.agent_id&&N(r.agent_id))}catch(s){console.error("Failed to fetch avatar config:",s)}finally{e||Se(!0)}})(),()=>{e=!0}},[m]);const ke=xn(m??Pe),[G,ie]=t.useState(""),[I,fe]=t.useState(""),[W,_]=t.useState("Ready"),[ne,p]=t.useState(!1),[O,J]=t.useState(!1),[T,U]=t.useState([]),[j,q]=t.useState(""),K=t.useRef(null),[St,Z]=t.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);t.useEffect(()=>{const e=window.matchMedia("(max-width: 480px)"),n=()=>Z(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]);const H=St?80:600,P=t.useRef(!1),Ee=t.useRef([]),Xe=t.useRef(0),Be=t.useRef(!1),Te=t.useRef([]),be=t.useRef(null),Me=t.useRef([]);t.useRef([]);const ht=t.useRef([]),Ae=t.useRef(0),We=t.useRef(0),de=t.useRef(0),Ie=t.useRef(0),Oe=t.useRef(!1),[Ze,it]=t.useState(null),w=t.useRef(null),[b,o]=t.useState("neutral"),[f,R]=t.useState(""),[ee,te]=t.useState(""),[ae,et]=t.useState(()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem("leadCaptureAskFor");return e&&e!==""?e:null}catch{return null}}),[De,$e]=t.useState("hidden"),[tt,k]=t.useState(""),at=t.useRef(null),Ve=t.useRef(De);Ve.current=De;const[He,Ge]=t.useState(null),Re=t.useRef(null),re=t.useRef(null),[Ce,Je]=t.useState(!1),Ne=t.useRef(null),[ce,qe]=t.useState("hidden"),[ct,Rt]=t.useState(""),ut=t.useRef(ce);ut.current=ce;const z=t.useRef(""),M=t.useRef(!1),ue=t.useRef(""),lt=t.useRef(Date.now()),Ue=t.useRef([]),he=t.useRef(!1),[ve,le]=t.useState(!1),[nt,h]=t.useState(!1),A=t.useRef(null),E=t.useMemo(()=>Ce?"Try again":W==="Busy"?"Busy":W==="Thinking..."||W==="Processing Voice..."?W:ae!=null&&ae!==""&&ae!=="none"&&ae!=="<none>"?`Enter ${$n(ae)}`:ce!=="hidden"||!nt?null:tn,[W,ae,Ce,ce,nt]),_e=!Ce&&W!=="Busy"&&W!=="Thinking..."&&W!=="Processing Voice..."&&(ae==null||ae===""||ae==="none"||ae==="<none>");t.useEffect(()=>{if(ce!=="hidden"||!_e){h(!1),A.current!=null&&(clearTimeout(A.current),A.current=null);return}return A.current=setTimeout(()=>{A.current=null,h(!0)},400),()=>{A.current!=null&&(clearTimeout(A.current),A.current=null)}},[ce,_e]);const Fe=E!=null&&E!=="";t.useEffect(()=>{const e=Ve.current;if(!(e==="exiting"||e==="entering")){if(e==="hidden"){Fe&&(k(E??""),$e("entering"));return}e==="visible"&&(!Fe||E!==tt)&&(at.current=Fe?E:null,$e("exiting"))}},[Fe,E,De,tt]),t.useEffect(()=>{if(W!=="Busy"){re.current!=null&&(clearTimeout(re.current),re.current=null);return}return re.current=setTimeout(()=>{re.current=null,_("Ready"),Je(!0)},12e3),()=>{re.current!=null&&(clearTimeout(re.current),re.current=null)}},[W]),t.useEffect(()=>{if(!Ce)return;const e=setTimeout(()=>Je(!1),2500);return()=>clearTimeout(e)},[Ce]);const xe=t.useCallback(()=>{const e=Ve.current;if(e==="exiting"){$e("hidden");const n=at.current;at.current=null,n!=null&&n!==""&&(k(n),$e("entering"))}else e==="entering"&&$e("visible")},[]),mt=e=>{if(!e)return;if(e.mood!=null){const r=String(e.mood).toLowerCase();o(r)}if(e.expression!=null){const r=String(e.expression).trim();R(r);const a=En.find(d=>d.name.toLowerCase()===r.toLowerCase());C(`[STREAM] Animation match for "${r}": ${a?a.name:"NONE"}`),te(a?.url??"")}if(e.navigation!=null){const r=String(e.navigation).trim();if(r!==""){let a=!1;if(typeof window<"u")try{const d=new URL(window.location.href),y=new URL(r,window.location.href),v=d.hostname==="leads.streamoji.com"||d.hostname.includes("localhost");if(y.origin!==d.origin&&!v){C("[STREAM] Navigation rejected: different origin");return}const L=x=>x.replace(/\/+$/,"")||"/";a=L(d.pathname)===L(y.pathname)}catch{}if(a)return;l?l(r):Ge(r)}}const n=e.ask_for||e.lead_capture?.ask_for,s=n?String(n).trim().toLowerCase():"",i=s==="none"||s==="<none>";if(n&&!i){const r=s;if(S&&(r==="email"&&S.email||r==="name"&&S.name||r==="phone"&&S.phone))return;if(typeof window<"u")try{window.sessionStorage.setItem("leadCaptureAskFor",r)}catch{}et(r||null)}else if(i||e.ask_for===null||e.lead_capture&&e.lead_capture.ask_for===null||e.ask_for==="none"){if(typeof window<"u")try{window.sessionStorage.removeItem("leadCaptureAskFor")}catch{}et(null)}e.collected,e.valid},vt=e=>{const n=e.trim();if(!n)return null;if(n.startsWith("{"))try{return JSON.parse(n)}catch{return null}if(n.includes(":")){const s=n.split(":"),i=s[0].trim().toLowerCase(),r=s.slice(1).join(":").trim();return{[i]:r}}return null},je=t.useCallback(()=>{},[]),me="§",se=()=>{for(;z.current.includes(`
2
- `);){const e=z.current.indexOf(`
3
- `),n=z.current.slice(0,e).trim();z.current=z.current.slice(e+1);const s=vt(n);s&&mt(s)}},Nt=e=>{if(M.current)if(e.includes(me)){const n=e.indexOf(me),s=e.slice(0,n),i=e.slice(n+me.length);s&&(ue.current+=s,fe(r=>r+s)),M.current=!1,i&&(z.current+=i,se())}else e===me?M.current=!1:(ue.current+=e,fe(n=>n+e));else if(e.includes(me)){const n=e.indexOf(me),s=e.slice(0,n),i=e.slice(n+me.length);z.current+=s,se(),M.current=!0,i&&(ue.current+=i,fe(r=>r+i))}else if(e===me){M.current=!0;return}else z.current+=e,se()};t.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const r="secret",a=Math.floor(Date.now()/1e3).toString();try{const d=new TextEncoder,y=await globalThis.crypto.subtle.importKey("raw",d.encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),v=await globalThis.crypto.subtle.sign("HMAC",y,d.encode(a)),x=Array.from(new Uint8Array(v)).map(D=>D.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",x),C("[SESSION] New HMAC UID generated and saved:",x)}catch(d){console.error("[SESSION] HMAC generation failed:",d);const y=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",y)}}const s=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let i=[];if(s)try{i=JSON.parse(s)}catch{i=[]}i.length===0&&S&&(S.name||S.email)?(i=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${S.name||""}" , Email is "${S.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(i))):s||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[S]),t.useEffect(()=>{const e=()=>{lt.current=Date.now(),he.current&&(he.current=!1,le(!1),U([]),q(""),fe(""),J(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const n=setInterval(async()=>{if(Date.now()-lt.current>=3e4&&!O&&!ne&&W==="Ready"&&!he.current)if(he.current=!0,Ue.current.length>0)le(!0),U(Ue.current);else try{const r=`${st}/nudgeUser`,a={navigationUrl:window.location.href,agentId:m},d=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(d.ok){const v=(await d.json()).nudge_questions;v&&v.length>0&&(C("[NUDGE] Received nudge questions from API:",v),Ue.current=v,le(!0),U(v))}}catch(r){console.error("[NUDGE] Error calling /nudgeUser:",r),he.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(n)}},[Qe,O,ne,W]),t.useEffect(()=>{if(T.length===0)return;let e=0,n=0,s=!1,i=100;const r=()=>{const a=T[e];if(s){const d=a.substring(0,n-1);q(d),n--,i=50}else{const d=a.substring(0,n+1);q(d),n++,i=100}!s&&n===a.length?(s=!0,i=3e3):s&&n===0&&(s=!1,e=(e+1)%T.length,i=500),K.current=setTimeout(r,i)};return r(),()=>{K.current&&clearTimeout(K.current)}},[T]);const Ut=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},on=e=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(e))},[xt,Lt]=t.useState(!1),[Ft,kt]=t.useState(0),we=t.useRef(null),pt=t.useRef([]),jt=t.useRef(0),[Pt,an]=t.useState(null),[cn,Et]=t.useState(null),Le=t.useRef(null),ze=t.useRef(null),ft=t.useCallback((e=!1)=>{e&&(Oe.current=!0,p(!1),_("Ready")),Te.current=[],Ee.current=[],Be.current=!1,J(!1),Ae.current=0,We.current=0,de.current=0,Me.current.forEach(n=>{try{n.stop()}catch{}}),Re.current&&(clearTimeout(Re.current),Re.current=null),setTimeout(()=>{Ge(null),te("")},10),Me.current=[]},[]),un=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=window.AudioContext||window.webkitAudioContext,s=new n,i=s.createMediaStreamSource(e),r=s.createAnalyser();r.fftSize=64,i.connect(r),Le.current=s,ze.current=i,Et(r);const a=new MediaRecorder(e);we.current=a,pt.current=[],a.ondataavailable=d=>{d.data.size>0&&pt.current.push(d.data)},a.onstop=async()=>{const d=Date.now()-jt.current;if(Et(null),ze.current&&(ze.current.disconnect(),ze.current=null),Le.current&&Le.current.state!=="closed"&&(Le.current.close(),Le.current=null),d<1e3){_("Recording too short. Hold or click longer."),p(!1);return}const y=new Blob(pt.current,{type:"audio/wav"});await hn(y)},jt.current=Date.now(),a.start(100),Lt(!0),_("Listening...")}catch(e){console.error("Error accessing microphone:",e),_("Mic Access Error")}},ln=()=>{we.current&&we.current.state!=="inactive"&&(we.current.stop(),we.current.stream.getTracks().forEach(e=>e.stop()),Lt(!1))},fn=()=>{we.current&&we.current.state!=="inactive"&&(we.current.onstop=null,we.current.stop(),we.current.stream.getTracks().forEach(e=>e.stop()),Et(null),ze.current&&(ze.current.disconnect(),ze.current=null),Le.current&&Le.current.state!=="closed"&&(Le.current.close(),Le.current=null),Lt(!1),pt.current=[],_("Ready"))};t.useEffect(()=>{if(!O)return;const e=()=>{const n=de.current;if(n<=0)return;const s=be.current,i=Ae.current;if(!s)return;const r=s.currentTime-i,a=Math.min(Math.max(0,r),n),y=rn(I).trim().length;if(y<=0)return;const v=Math.min(Math.round(a/n*y),y);it(v)};return clearInterval(w.current??void 0),w.current=setInterval(e,90),()=>clearInterval(w.current??void 0)},[O,I,de.current]),t.useEffect(()=>{let e;return xt?(kt(0),e=window.setInterval(()=>{kt(n=>n+1)},1e3)):kt(0),()=>clearInterval(e)},[xt]);const dn=e=>{const n=e.numberOfChannels,s=e.length*n*2+44,i=new ArrayBuffer(s),r=new DataView(i);let a=0;const d=x=>{r.setUint16(a,x,!0),a+=2},y=x=>{r.setUint32(a,x,!0),a+=4};y(1179011410),y(s-8),y(1163280727),y(544501094),y(16),d(1),d(n),y(e.sampleRate),y(e.sampleRate*2*n),d(n*2),d(16),y(1635017060),y(s-a-4);const v=[];for(let x=0;x<n;x++)v.push(e.getChannelData(x));let L=0;for(;a<s;){for(let x=0;x<n;x++){let D=Math.max(-1,Math.min(1,v[x][L]));D=D<0?D*32768:D*32767,r.setInt16(a,D,!0),a+=2}L++}return new Blob([i],{type:"audio/wav"})},Tt=async(e,n,s=!1)=>{if(!Oe.current){if(P.current){Ee.current.push({audio:e,visemes:n,isNewSegment:s});return}P.current=!0;try{const i=window.AudioContext||window.webkitAudioContext,r=be.current??new i;r.state==="suspended"&&await r.resume(),be.current=r;const a=window.atob(e),d=new Uint8Array(a.length);for(let B=0;B<a.length;B++)d[B]=a.charCodeAt(B);const y=await r.decodeAudioData(d.buffer.slice(0));de.current+=y.duration;const v=r.currentTime;let L=We.current;const x=!Be.current;L<v&&(L=v+.1),We.current=L+y.duration;const D=r.createBufferSource();D.buffer=y;let Q=Pt;if((!Q||Q.context!==r)&&(Q=r.createAnalyser(),Q.fftSize=64,Q.connect(r.destination),an(Q)),D.connect(Q),Me.current.push(D),Oe.current){Me.current=Me.current.filter(B=>B!==D);return}if(x){Be.current=!0,J(!0),C(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${L.toFixed(3)}`),Ae.current=L;const B=(L-v)*1e3;Xe.current=performance.now()+B,C(`[AUDIO] Response started. Initial startTime: ${L.toFixed(3)}, CT: ${v.toFixed(3)}`)}D.start(L);const oe=(L-Ae.current)*1e3;s&&(Ie.current=oe,C(`[AUDIO] New segment detected at +${oe.toFixed(0)}ms. Resetting segment offset.`)),n.forEach((B,pe)=>{const F=B.symbol??"";if(F){const ge=Pn(F),ye=Math.round(B.start*1e3),Ye=Math.round((B.duration??0)*1e3),Gt=Ie.current+ye;pe<3&&C(`[AUDIO] Viseme "${F}": segment_relative=${ye}ms, segment_offset=${Ie.current.toFixed(0)}ms => vtime=${Gt}ms`),ge.forEach(Jt=>{Te.current.push({viseme:Jt.v,weight:Jt.w,vtime:Gt,vduration:Ye})})}}),_("Speaking...")}finally{if(P.current=!1,Ee.current.length>0){const i=Ee.current.shift();i&&Tt(i.audio,i.visemes,i.isNewSegment)}}}},hn=async e=>{try{p(!0),le(!1),ue.current="",fe(""),_("Processing Voice...");const n=await e.arrayBuffer(),i=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(n),r=dn(i),a=new FileReader;a.readAsDataURL(r),a.onloadend=async()=>{const d=a.result.split(",")[1];ft(),ie(""),z.current="",M.current=!1;const y=`${st}/stt?token=${encodeURIComponent(Qe)}`,v=await fetch(y,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:d,audio_format:"wav"})});if(v.status===429){try{const pe=await v.text(),F=JSON.parse(pe);C("[STT] 429 agent at capacity:",F?.detail)}catch{}ie(""),_("Busy"),p(!1);return}if(!v.ok){const pe=await v.text();let F="STT Failed";try{F=JSON.parse(pe).error||F}catch{pe&&(F=pe.slice(0,200))}throw new Error(F)}const L=v.body;if(C("this is body"+L),!L){_("STT Failed"),p(!1);return}const x=L.getReader();Oe.current=!1;const D=new TextDecoder;let Q="",oe=!1;const B=async(pe,F)=>{switch(pe){case"transcript":F.transcript!=null&&ie(String(F.transcript));break;case"text":{const ge=F.delta??F.text??"";ge&&Nt(ge);break}case"audio":{const ge=F.chunk,ye=F.visemes??[],Ye=!!F.is_new_segment;ge&&await Tt(ge,ye,Ye);break}case"done":{oe=!0,_("Ready"),p(!1);break}case"error":{oe=!0,_("STT Failed"),p(!1);break}default:break}};for(;;){const{done:pe,value:F}=await x.read();F&&(Q+=D.decode(F,{stream:!0}));const ge=Q.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),xt=require("@react-three/drei"),Ut=require("@react-three/fiber"),t=require("react"),Rn=require("three"),Sn=require("three/examples/jsm/loaders/GLTFLoader.js");function xn(d){const g=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(d){for(const w in d)if(w!=="default"){const b=Object.getOwnPropertyDescriptor(d,w);Object.defineProperty(g,w,b.get?b:{enumerable:!0,get:()=>d[w]})}}return g.default=d,Object.freeze(g)}const dt=xn(Rn),ot="https://ai.streamoji.com",C=(...d)=>{},Yt=({analyser:d})=>{const g=t.useRef(null),w=t.useRef(null);return t.useEffect(()=>{const b=g.current;if(!b)return;const $=b.getContext("2d",{alpha:!0});if(!$)return;let q,K=null;d&&(d.fftSize=128,K=new Uint8Array(d.frequencyBinCount));const qe=()=>{q=requestAnimationFrame(qe),(b.width!==b.offsetWidth||b.height!==b.offsetHeight)&&(b.width=b.offsetWidth,b.height=b.offsetHeight);const Ue=b.width,D=b.height;if(Ue===0||D===0)return;const it=D/2;$.clearRect(0,0,Ue,D),$.fillStyle="#1e293b";const Re=2,V=Re+2,Se=Ue*.95,ee=Math.floor(Se/V);(!w.current||w.current.length!==ee)&&(w.current=new Float32Array(ee).fill(2));const je=ee*V,T=(Ue-je)/2;d&&K&&d.getByteFrequencyData(K);const ue=K?K.length:0,W=Math.floor(ue*.7)/ee,N=new Float32Array(ee);for(let m=0;m<ee;m++){let I=0;if(K&&W>0){const A=Math.floor(m*W),O=Math.floor((m+1)*W);for(let G=A;G<O;G++){const te=K[G]||0;te>I&&(I=te)}}I<10&&(I=0);const R=I/255,k=I>0?Math.max(2,Math.pow(R,1.4)*D*.25):2;N[m]=k}for(let m=0;m<ee;m++){const I=ee-1-m,R=Math.max(N[m],N[I]),k=w.current[m]+(R-w.current[m])*.3;w.current[m]=k;const A=T+m*V,O=it-k/2;$.beginPath(),$.roundRect?$.roundRect(A,O,Re,k,4):$.fillRect(A,O,Re,k),$.fill()}};return qe(),()=>{cancelAnimationFrame(q)}},[d]),c.jsx("canvas",{ref:g,style:{width:"100%",height:"100%",display:"block"}})},vn="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",Kt="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";function Ln(d){const[g,w]=t.useState(null);return t.useEffect(()=>{if(!d){w(null);return}let b=!1;const $=`${vn}/${d}.glb`;return fetch($,{method:"HEAD"}).then(q=>{b||w(q.ok?$:Kt)}).catch(()=>{b||w(Kt)}),()=>{b=!0}},[d]),g}const kn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_002.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/M_Standing_Idle_Variations_005.glb"],En=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_001.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/idle/F_Standing_Idle_Variations_003.glb"],Tn=[{id:"m_expr_01",name:"Friendly Wave",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_001.glb"},{id:"m_expr_02",name:"You There",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_002.glb"},{id:"m_expr_04",name:"Awkward Agreement",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_004.glb"},{id:"m_expr_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_005.glb"},{id:"m_expr_06",name:"Tired Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_006.glb"},{id:"m_expr_07",name:"Conceilied Laughter",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_007.glb"},{id:"m_expr_08",name:"You Come Here",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_008.glb"},{id:"m_expr_09",name:"Come Here Kid",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_009.glb"},{id:"m_expr_10",name:"Come Here Everyone",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_010.glb"},{id:"m_expr_11",name:"No Freaking Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_011.glb"},{id:"m_expr_12",name:"Cheerful Approval",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_012.glb"},{id:"m_expr_13",name:"Waving Hello",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_013.glb"},{id:"m_expr_14",name:"Checking Surroundings",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_014.glb"},{id:"m_expr_15",name:"Referee Warning",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_015.glb"},{id:"m_expr_16",name:"You Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_016.glb"},{id:"m_expr_17",name:"Side Thumbs Down",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_017.glb"},{id:"m_expr_18",name:"You're Finished",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Standing_Expressions_018.glb"},{id:"m_talk_01",name:"Oh God, Why Me?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_001.glb"},{id:"m_talk_02",name:"What Are You Doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_002.glb"},{id:"m_talk_03",name:"What Am I doing?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_003.glb"},{id:"m_talk_04",name:"No Way",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_004.glb"},{id:"m_talk_05",name:"What's Going On?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb"},{id:"m_talk_06",name:"I have no idea",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"},{id:"m_talk_07",name:"What's going on here?",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb"},{id:"m_talk_08",name:"Let's stop",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_008.glb"},{id:"m_talk_09",name:"Fed Up Moment",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_009.glb"},{id:"m_talk_10",name:"What's This? Hold On",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_010.glb"},{id:"f_talk_01",name:"Great Job Clap",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_001.glb"},{id:"f_talk_02",name:"Chill Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"},{id:"f_talk_03",name:"This Is Me",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_003.glb"},{id:"f_talk_04",name:"Empathize",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb"},{id:"f_talk_05",name:"Loose Hands Stretch",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb"},{id:"f_talk_06",name:"Take It Easy",url:"https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb"}],Mn=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_007.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/M_Talking_Variations_006.glb"],In=["https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_004.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_005.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_006.glb","https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/masculine/expression/F_Talking_Variations_002.glb"],An={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},On=[-.45,1.9,.1],Dn=[-.45,1.75,.1],Cn={browInnerUp:.2},Dt=.18,Nn=1,Fn=.5,Qt=3,yt=.55,Ct=.12,Xt=2,Zt=2,Rt=4,en=8,Un=1,tn=.38,nn=.32,rn="__branding__",St={neutral:{eyeLookDownLeft:.1,eyeLookDownRight:.1},happy:{mouthSmileLeft:.2,mouthSmileRight:.2,eyeLookDownLeft:.1,eyeLookDownRight:.1},sad:{eyeLookDownLeft:.2,eyeLookDownRight:.2,browDownRight:.1,browInnerUp:.6,browOuterUpRight:.2,eyeSquintLeft:.7,eyeSquintRight:.7,mouthFrownLeft:.8,mouthFrownRight:.8,mouthLeft:.2,mouthPucker:.5,mouthRollLower:.2,mouthRollUpper:.2,mouthShrugLower:.2,mouthShrugUpper:.2,mouthStretchLeft:.4},angry:{eyeLookDownLeft:.1,eyeLookDownRight:.1,browDownLeft:.6,browDownRight:.6,jawForward:.3,mouthFrownLeft:.7,mouthFrownRight:.7,mouthRollLower:.2,mouthShrugLower:.3},fear:{browInnerUp:.7,eyeSquintLeft:.5,eyeSquintRight:.5,eyeWideLeft:.6,eyeWideRight:.6,mouthClose:.1,mouthFunnel:.3,mouthShrugLower:.5,mouthShrugUpper:.5},disgust:{browDownLeft:.7,browDownRight:.1,browInnerUp:.3,eyeSquintLeft:1,eyeSquintRight:1,eyeWideLeft:.5,eyeWideRight:.5,mouthLeft:.4,mouthPressLeft:.3,mouthRollLower:.3,mouthShrugLower:.3,mouthShrugUpper:.8,mouthUpperUpLeft:.3,noseSneerLeft:1,noseSneerRight:.7},love:{browInnerUp:.4,browOuterUpLeft:.2,browOuterUpRight:.2,mouthSmileLeft:.2,mouthSmileRight:.2,eyeBlinkLeft:.6,eyeBlinkRight:.6,eyeWideLeft:.7,eyeWideRight:.7,mouthDimpleLeft:.1,mouthDimpleRight:.1,mouthPressLeft:.2,mouthShrugUpper:.2,mouthUpperUpLeft:.1,mouthUpperUpRight:.1}},an=[{key:"viseme_aa",mix:{jawOpen:.6},teethMix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2},teethMix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2},teethMix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1},teethMix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.8,mouthRollUpper:.4,mouthUpperUpLeft:.3,mouthUpperUpRight:.3},teethMix:{mouthRollLower:.8,mouthRollUpper:.4,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:1},teethMix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:1}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.6,jawOpen:.2,tongueOut:.4},teethMix:{mouthRollUpper:.6,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2},teethMix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2},teethMix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15},teethMix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15}},{key:"viseme_nn",mix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2},teethMix:{mouthLowerDownLeft:.4,mouthLowerDownRight:.4,mouthDimpleLeft:.3,mouthDimpleRight:.3,mouthFunnel:.3,mouthPucker:.3,jawOpen:.15,tongueOut:.2}},{key:"viseme_sil",mix:{}}],jn={aei:[{v:"aa",w:.5},{v:"E",w:.3},{v:"I",w:.2}],o:[{v:"O",w:.7},{v:"U",w:.3}],ee:[{v:"I",w:1}],bmp:[{v:"PP",w:1}],fv:[{v:"FF",w:1}],l:[{v:"nn",w:1}],r:[{v:"RR",w:1}],th:[{v:"TH",w:1}],qw:[{v:"U",w:.6},{v:"O",w:.4}],cdgknstxyz:[{v:"DD",w:.4},{v:"SS",w:.3},{v:"kk",w:.2},{v:"CH",w:.1}]},Nt=new Set(an.flatMap(d=>[...Object.keys(d.mix),...d.teethMix?Object.keys(d.teethMix):[]]));function sn(d){const g=Math.max(0,Math.min(1,d));return g*g*(3-2*g)}function Pn(d,g,w){if(w<=0)return 0;const b=(d-g)/w;return b<0||b>1?0:b<.15?sn(b/.15):b>.85?sn((1-b)/.15):1}function Bn(d){if(!d)return[{v:"sil",w:1}];const g=d.toLowerCase();return jn[g]??[{v:"sil",w:1}]}function $n({target:d}){const{camera:g}=Ut.useThree();return t.useEffect(()=>{g.lookAt(...d)},[g,d]),null}function l(d,g,w){if(!d||!d.morphTargetDictionary)return;const b=d,$=b.morphTargetDictionary,q=b.morphTargetInfluences;if(q)for(const K in $)K.toLowerCase()===g.toLowerCase()&&(q[$[K]]=w)}const Vn=t.memo(({avatarUrl:d,isPlayingRef:g,visemeQueueRef:w,audioContextRef:b,responseAudioStartTimeRef:$,adjustments:q,mood:K,expression:qe,agentResponse:Ue,isSpeaking:D,nextStartTimeRef:it,stopPlayback:Re,setIsSpeaking:ze,expressionUrl:V,onExpressionFinished:Se,isNudgeResponse:ee,avatarGender:je})=>{const{scene:T}=xt.useGLTF(d),ue=je==="female"?En:kn,Te=xt.useGLTF(ue),W=t.useMemo(()=>Te.flatMap(_=>_.animations),[Te]),N=je==="female"?In:Mn,m=xt.useGLTF(N),I=t.useMemo(()=>m.flatMap(_=>_.animations),[m]),R=t.useRef(null),k=t.useRef(null),A=t.useRef(null),O=t.useRef(null),G=t.useRef(null),te=t.useRef(null),at=t.useRef([]),[z]=t.useState(()=>new dt.AnimationMixer(T)),J=t.useRef({}),H=t.useRef(null),Ye=t.useRef(0),Me=t.useRef(!1),Pe=t.useRef(0),ct=t.useRef(!1),pe=t.useRef(null),Be=t.useRef(Qt),$e=t.useRef(-1),Ie=t.useRef("left"),ft=t.useRef(Rt+Math.random()*(en-Rt)),ge=t.useRef(0),xe=t.useRef("smile"),Ae=t.useRef({});t.useEffect(()=>{if(!(!W||!T)){if(W.forEach((_,p)=>{const s=`idle_${p}`;if(!J.current[s]){const h=z.clipAction(_,T);h.name=s,h.setLoop(dt.LoopOnce,1),h.clampWhenFinished=!0,J.current[s]=h}}),I.forEach((_,p)=>{const s=`talk_${p}`;if(!J.current[s]){const h=z.clipAction(_,T);h.name=s,h.setLoop(dt.LoopOnce,1),h.clampWhenFinished=!0,J.current[s]=h}}),W.length>0){const _=J.current.idle_0,p=H.current&&z.existingAction(H.current.getClip());_&&!p&&(_.reset().fadeIn(.5).play(),H.current=_)}return()=>{z.stopAllAction(),J.current={},H.current=null}}},[W,I,T,z]);const Ke=t.useRef("");t.useEffect(()=>{if(!V||!T||V===Ke.current)return;Ke.current=V,pe.current=V,new Sn.GLTFLoader().load(V,p=>{if(p.animations&&p.animations.length>0){const s=p.animations[0],h=z.clipAction(s,T);if(h.name=`EXPR_${V}`,h.setLoop(dt.LoopOnce,1),h.clampWhenFinished=!0,J.current[`EXPR_${V}`]=h,D&&pe.current===V){const S=H.current;h.reset().fadeIn(.3).play(),S&&S!==h&&S.crossFadeTo(h,.3,!0),H.current=h,pe.current=null}}},void 0,p=>{console.error(`[ANIMATION] Failed to load ${V}`,p)})},[V,T,z,D]),t.useEffect(()=>{const _=p=>{const s=p.action,h=s.name||"";if(h.startsWith("idle_")){const ne=(parseInt(h.split("_")[1])+1)%W.length,re=J.current[`idle_${ne}`];re&&(re.reset().fadeIn(.5).play(),s.crossFadeTo(re,.5,!0),H.current=re)}else if(h.startsWith("EXPR_")){if(D){const S=Math.floor(Math.random()*I.length),ne=J.current[`talk_${S}`];ne&&(ne.reset().fadeIn(.5).play(),s.crossFadeTo(ne,.5,!0),H.current=ne)}else{const S=J.current.idle_0;S&&(S.reset().fadeIn(.5).play(),s.crossFadeTo(S,.5,!0),H.current=S)}Se&&Se()}else if(h.startsWith("talk_"))if(D&&!ee){const ne=(parseInt(h.split("_")[1])+1)%I.length,re=J.current[`talk_${ne}`];re&&(re.reset().fadeIn(.3).play(),s.crossFadeTo(re,.3,!0),H.current=re)}else{const S=J.current.idle_0;S&&(S.reset().fadeIn(.5).play(),s.crossFadeTo(S,.5,!0),H.current=S)}};return z.addEventListener("finished",_),()=>z.removeEventListener("finished",_)},[z,W,I,D,ee,Se]),t.useEffect(()=>{if(D&&T){const _=H.current,p=_?.name||"";if(p.startsWith("idle_")||p.startsWith("talk_")||p===""){const s=pe.current;if(s){const h=J.current[`EXPR_${s}`];if(h){h.reset().fadeIn(.3).play(),_&&_!==h&&_.crossFadeTo(h,.3,!0),H.current=h,pe.current=null;return}}if(p.startsWith("idle_")||p===""){const h=Math.floor(Math.random()*I.length),S=J.current[`talk_${h}`];S&&(S.reset().fadeIn(.5).play(),_&&_.crossFadeTo(S,.5,!0),H.current=S)}}}else if(!D&&T){const _=H.current,p=_?.name||"";if(p.startsWith("talk_")||p.startsWith("EXPR_")){const s=J.current.idle_0;s&&(s.reset().fadeIn(.5).play(),_&&_.crossFadeTo(s,.5,!0),H.current=s)}}},[D,T,V]),t.useEffect(()=>{if(!T)return;T.traverse(s=>{if(s.isMesh&&s.morphTargetDictionary){const h=s.name.toLowerCase();(h.includes("head")||h.includes("avatar"))&&(k.current=s,C(`[ANIMATION] Found head mesh: ${s.name}`)),h.includes("teeth")&&(A.current=s,C(`[ANIMATION] Found teeth mesh: ${s.name}`)),h.includes("beard")&&(O.current=s,C(`[ANIMATION] Found beard mesh: ${s.name}`)),h.includes("eyeleft")&&(G.current=s,C(`[ANIMATION] Found eye left mesh: ${s.name}`)),h.includes("eyeright")&&(te.current=s,C(`[ANIMATION] Found eye right mesh: ${s.name}`))}});const _=k.current?.morphTargetDictionary;_&&Object.keys(_).filter(s=>s.toLowerCase().includes("brow"));const p=[];T.traverse(s=>{if(s.isMesh){const S=s.morphTargetDictionary;S&&Object.keys(S).some(ne=>ne.toLowerCase().includes("brow"))&&p.push(s)}}),at.current=p,p.length>0&&C("[ANIMATION] Meshes with brow morphs:",p.length)},[T]);const Oe=_=>{const p=St[_]??St.neutral;for(const s in p)l(k.current,s,p[s]),l(A.current,s,p[s]),l(O.current,s,p[s])};return Ut.useFrame((_,p)=>{Oe(K);const s=_.clock.elapsedTime;let h=0;if(Math.floor(s)%5===0&&Math.floor((s-p)%5)!==0){let f=null;T.traverse(M=>{M.name.toLowerCase().includes("hips")&&(f=M)});const j=f?`Hips Y: ${f.position.y.toFixed(4)}`:"Hips not found";C(`[ANIMATION] Mixer Time: ${z.time.toFixed(2)}, ${j}`)}if(z.update(p),s>Ye.current&&!Me.current&&(Me.current=!0,Pe.current=s),Me.current){const f=D?.2:.3,j=(s-Pe.current)/f;if(j>=1)if(Me.current=!1,ct.current){const M=D?1:2.5;Ye.current=s+M,ct.current=!1}else Ye.current=s+.12,ct.current=!0;else{const M=j<.5?j*2:(1-j)*2;l(k.current,"eyeBlinkLeft",M),l(k.current,"eyeBlinkRight",M),l(A.current,"eyeBlinkLeft",M),l(A.current,"eyeBlinkRight",M),l(O.current,"eyeBlinkLeft",M),l(O.current,"eyeBlinkRight",M),h=M*Cn.browInnerUp}}const S=St[K]??St.neutral,ne=S.browInnerUp??0,re=S.browOuterUpLeft??0,vt=S.browOuterUpRight??0,Qe=s*Nn,ie=Dt*Math.sin(Qe),ht=Dt*.7*Math.sin(Qe+.7),De=Dt*.7*Math.sin(Qe+1.3),x=f=>Math.max(0,Math.min(1,f)),Xe=x(ne+ie),Ze=x(re+ht),Ve=x(vt+De),We=x(Xe+h);l(k.current,"browInnerUp",We),l(A.current,"browInnerUp",We),l(O.current,"browInnerUp",We),l(k.current,"browOuterUpLeft",Ze),l(A.current,"browOuterUpLeft",Ze),l(O.current,"browOuterUpLeft",Ze),l(k.current,"browOuterUpRight",Ve),l(A.current,"browOuterUpRight",Ve),l(O.current,"browOuterUpRight",Ve);const ve=Be.current,Ce=ve+yt,et=Ce+Ct;s>et&&(Be.current+=yt+Ct+Qt);const se=!D&&s>=ve&&s<Ce,le=!D&&s>=Ce&&s<et;(se||le)&&$e.current!==ve&&($e.current=ve,Ie.current=Math.random()<.7?"left":"up");const mt=se?s-ve:le?yt:0,ut=se||le?Math.min(1,mt/yt):0,oe=ut<=0?0:Math.sin(ut*Math.PI),tt=le?1-(s-Ce)/Ct:1,pt=se?oe:le?oe*tt:0,nt=Fn*pt,U=f=>S[f]??0;if(Ie.current==="up"?(l(G.current,"eyeLookUpLeft",x(U("eyeLookUpLeft")+nt)),l(G.current,"eyeLookDownLeft",x(U("eyeLookDownLeft"))),l(G.current,"eyeLookOutLeft",x(U("eyeLookOutLeft"))),l(G.current,"eyeLookInLeft",x(U("eyeLookInLeft"))),l(te.current,"eyeLookUpRight",x(U("eyeLookUpRight")+nt)),l(te.current,"eyeLookDownRight",x(U("eyeLookDownRight"))),l(te.current,"eyeLookOutRight",x(U("eyeLookOutRight"))),l(te.current,"eyeLookInRight",x(U("eyeLookInRight")))):(l(G.current,"eyeLookUpLeft",x(U("eyeLookUpLeft"))),l(G.current,"eyeLookDownLeft",x(U("eyeLookDownLeft"))),l(G.current,"eyeLookOutLeft",x(U("eyeLookOutLeft"))),l(G.current,"eyeLookInLeft",x(U("eyeLookInLeft")+nt)),l(te.current,"eyeLookUpRight",x(U("eyeLookUpRight"))),l(te.current,"eyeLookDownRight",x(U("eyeLookDownRight"))),l(te.current,"eyeLookOutRight",x(U("eyeLookOutRight")+nt)),l(te.current,"eyeLookInRight",x(U("eyeLookInRight")))),!D&&s>=ft.current){ge.current=s,xe.current=Math.random()<.5?"pucker":"smile";const f=xe.current==="pucker"?Zt:Xt;ft.current=s+f+Rt+Math.random()*(en-Rt)}const Q=xe.current==="pucker"?Zt:Xt,ae=!D&&s>=ge.current&&s<ge.current+Q,X=ae?(s-ge.current)/Q:0,Ne=X<=0?0:X<.5?X*2:(()=>{const f=(X-.5)*2;return 1-f*f*(3-2*f)})(),Le=f=>S[f]??0;if(ae)if(xe.current==="pucker"){const f=x(Le("mouthPucker")+Un*Ne);l(k.current,"mouthPucker",f),l(A.current,"mouthPucker",f),l(O.current,"mouthPucker",f)}else{const f=x(Le("mouthSmileLeft")+tn*Ne),j=x(Le("mouthSmileRight")+tn*Ne),M=x(Le("mouthDimpleLeft")+nn*Ne),Y=x(Le("mouthDimpleRight")+nn*Ne);l(k.current,"mouthSmileLeft",f),l(k.current,"mouthSmileRight",j),l(k.current,"mouthDimpleLeft",M),l(k.current,"mouthDimpleRight",Y),l(A.current,"mouthSmileLeft",f),l(A.current,"mouthSmileRight",j),l(A.current,"mouthDimpleLeft",M),l(A.current,"mouthDimpleRight",Y),l(O.current,"mouthSmileLeft",f),l(O.current,"mouthSmileRight",j),l(O.current,"mouthDimpleLeft",M),l(O.current,"mouthDimpleRight",Y)}if(R.current){const f=g.current?0:q.rotation[1];R.current.rotation.y=dt.MathUtils.lerp(R.current.rotation.y,f,.1),R.current.position.set(...q.position),R.current.scale.setScalar(q.scale),R.current.rotation.x=q.rotation[0],R.current.rotation.z=q.rotation[2]}const ce={};if(Nt.forEach(f=>{ce[f]=0}),g.current&&b.current){const f=b.current.currentTime,Y=(f-$.current)*1e3- -150;for(let be=0;be<w.current.length;be++){const _e=w.current[be];if(Y<_e.vtime||Y>=_e.vtime+_e.vduration)continue;const rt=Pn(Y,_e.vtime,_e.vduration),Lt=`viseme_${_e.viseme}`.toLowerCase(),ke=an.find(de=>de.key.toLowerCase()===Lt);if(!ke)continue;const gt=(_e.weight??1)*rt;for(const de in ke.mix)ce[de]=Math.max(ce[de]??0,ke.mix[de]*gt);if(ke.teethMix)for(const de in ke.teethMix)ce[de]=Math.max(ce[de]??0,ke.teethMix[de]*gt)}f>it.current+.5&&(Re(),ze(!1))}const He=Ae.current;Nt.forEach(f=>{const j=ce[f]??0,M=He[f]??0;He[f]=Math.max(0,Math.min(1,M+(j-M)*(1-Math.exp(-20*p))))}),Nt.forEach(f=>{const j=He[f]??0;l(k.current,f,j),l(O.current,f,j),l(A.current,f,j)})}),c.jsx("group",{ref:R,children:c.jsx("primitive",{object:T})})});function Wn(d){return d?d.charAt(0).toUpperCase()+d.slice(1).toLowerCase():""}function on(d){return d.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const Ft=new Map,Hn=({onNavigationRequested:d,agentId:g,presetUserDetails:w,onAvatarReady:b})=>{const[$,q]=t.useState(""),[K,qe]=t.useState("male"),[Ue,D]=t.useState(""),[it,Re]=t.useState(!1),[ze,V]=t.useState(()=>typeof window>"u"?null:sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")),Se=$,ee=K;t.useEffect(()=>{if(!g){Re(!0);return}let e=!1;return(async()=>{console.log(">> fetchConfig RUNNING for",g);try{const r=`agent_config_${g}`,a=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID"),o=sessionStorage.getItem(r);if(o)try{const u=JSON.parse(o);e||(u.encryptedAgentToken&&q(u.encryptedAgentToken),u.avatarGender&&qe(u.avatarGender),u.agent_id&&D(u.agent_id),u.lead_id&&(V(u.lead_id),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",u.lead_id)),Re(!0));return}catch(u){console.error("Failed to parse cached avatar config:",u),sessionStorage.removeItem(r)}let i;if(Ft.has(g))console.log(">> REUSING in-flight fetch for",g),i=await Ft.get(g);else{const u=(async()=>{console.log(">> INITIATING visitedWebsite fetch for",g);const v={agentId:g,lead_id:a},y=await fetch(`${ot}/visitedWebsite`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!y.ok)throw new Error(`Fetch failed: ${y.status}`);const L=await y.json();return sessionStorage.setItem(r,JSON.stringify(L)),L})();Ft.set(g,u),i=await u}if(e)return;i&&(i.encryptedAgentToken&&q(i.encryptedAgentToken),i.avatarGender&&qe(i.avatarGender),i.agent_id&&D(i.agent_id),i.lead_id&&(V(i.lead_id),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",i.lead_id)))}catch(r){console.error("Failed to fetch avatar config:",r)}finally{e||Re(!0)}})(),()=>{e=!0}},[g]);const je=Ln(g??Ue),[T,ue]=t.useState(""),[Te,W]=t.useState(""),[N,m]=t.useState("Ready"),[I,R]=t.useState(!1),[k,A]=t.useState(!1),[O,G]=t.useState([]),[te,at]=t.useState(""),z=t.useRef(null),[J,H]=t.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);t.useEffect(()=>{const e=window.matchMedia("(max-width: 480px)"),n=()=>H(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]);const Ye=J?80:600,Me=t.useRef(!1),Pe=t.useRef([]),ct=t.useRef(0),pe=t.useRef(!1),Be=t.useRef([]),$e=t.useRef(null),Ie=t.useRef([]);t.useRef([]);const ft=t.useRef([]),ge=t.useRef(0),xe=t.useRef(0),Ae=t.useRef(0),Ke=t.useRef(0),Oe=t.useRef(!1),[_,p]=t.useState(null),s=t.useRef(null),[h,S]=t.useState("neutral"),[ne,re]=t.useState(""),[vt,Qe]=t.useState(""),[ie,ht]=t.useState(()=>{if(typeof window>"u")return null;try{const e=window.sessionStorage.getItem("leadCaptureAskFor");return e&&e!==""?e:null}catch{return null}}),[De,x]=t.useState("hidden"),[Xe,Ze]=t.useState(""),Ve=t.useRef(null),We=t.useRef(De);We.current=De;const[ve,Ce]=t.useState(null),et=t.useRef(null),se=t.useRef(null),[le,mt]=t.useState(!1),ut=t.useRef(null),[oe,tt]=t.useState("hidden"),[pt,nt]=t.useState(""),U=t.useRef(oe);U.current=oe;const Q=t.useRef(""),ae=t.useRef(!1),X=t.useRef(""),Ne=t.useRef(Date.now()),Le=t.useRef([]),ce=t.useRef(!1),[He,f]=t.useState(!1),[j,M]=t.useState(!1),Y=t.useRef(null),be=t.useMemo(()=>le?"Try again":N==="Busy"?"Busy":N==="Thinking..."||N==="Processing Voice..."?N:ie!=null&&ie!==""&&ie!=="none"&&ie!=="<none>"?`Enter ${Wn(ie)}`:oe!=="hidden"||!j?null:rn,[N,ie,le,oe,j]),_e=!le&&N!=="Busy"&&N!=="Thinking..."&&N!=="Processing Voice..."&&(ie==null||ie===""||ie==="none"||ie==="<none>");t.useEffect(()=>{if(oe!=="hidden"||!_e){M(!1),Y.current!=null&&(clearTimeout(Y.current),Y.current=null);return}return Y.current=setTimeout(()=>{Y.current=null,M(!0)},400),()=>{Y.current!=null&&(clearTimeout(Y.current),Y.current=null)}},[oe,_e]);const rt=be!=null&&be!=="";t.useEffect(()=>{const e=We.current;if(!(e==="exiting"||e==="entering")){if(e==="hidden"){rt&&(Ze(be??""),x("entering"));return}e==="visible"&&(!rt||be!==Xe)&&(Ve.current=rt?be:null,x("exiting"))}},[rt,be,De,Xe]),t.useEffect(()=>{if(N!=="Busy"){se.current!=null&&(clearTimeout(se.current),se.current=null);return}return se.current=setTimeout(()=>{se.current=null,m("Ready"),mt(!0)},12e3),()=>{se.current!=null&&(clearTimeout(se.current),se.current=null)}},[N]),t.useEffect(()=>{if(!le)return;const e=setTimeout(()=>mt(!1),2500);return()=>clearTimeout(e)},[le]);const Lt=t.useCallback(()=>{const e=We.current;if(e==="exiting"){x("hidden");const n=Ve.current;Ve.current=null,n!=null&&n!==""&&(Ze(n),x("entering"))}else e==="entering"&&x("visible")},[]),ke=e=>{if(!e)return;if(e.mood!=null){const o=String(e.mood).toLowerCase();S(o)}if(e.expression!=null){const o=String(e.expression).trim();re(o);const i=Tn.find(u=>u.name.toLowerCase()===o.toLowerCase());C(`[STREAM] Animation match for "${o}": ${i?i.name:"NONE"}`),Qe(i?.url??"")}if(e.navigation!=null){const o=String(e.navigation).trim();if(o!==""){let i=!1;if(typeof window<"u")try{const u=new URL(window.location.href),v=new URL(o,window.location.href),y=u.hostname==="leads.streamoji.com"||u.hostname.includes("localhost");if(v.origin!==u.origin&&!y){C("[STREAM] Navigation rejected: different origin");return}const L=E=>E.replace(/\/+$/,"")||"/";i=L(u.pathname)===L(v.pathname)}catch{}if(i)return;d?d(o):Ce(o)}}const n=e.ask_for||e.lead_capture?.ask_for,r=n?String(n).trim().toLowerCase():"",a=r==="none"||r==="<none>";if(n&&!a){const o=r;if(w&&(o==="email"&&w.email||o==="name"&&w.name||o==="phone"&&w.phone))return;if(typeof window<"u")try{window.sessionStorage.setItem("leadCaptureAskFor",o)}catch{}ht(o||null)}else if(a||e.ask_for===null||e.lead_capture&&e.lead_capture.ask_for===null||e.ask_for==="none"){if(typeof window<"u")try{window.sessionStorage.removeItem("leadCaptureAskFor")}catch{}ht(null)}e.collected,e.valid},gt=e=>{const n=e.trim();if(!n)return null;if(n.startsWith("{"))try{return JSON.parse(n)}catch{return null}if(n.includes(":")){const r=n.split(":"),a=r[0].trim().toLowerCase(),o=r.slice(1).join(":").trim();return{[a]:o}}return null},de=t.useCallback(()=>{},[]),Fe="§",kt=()=>{for(;Q.current.includes(`
2
+ `);){const e=Q.current.indexOf(`
3
+ `),n=Q.current.slice(0,e).trim();Q.current=Q.current.slice(e+1);const r=gt(n);r&&ke(r)}},jt=e=>{if(ae.current)if(e.includes(Fe)){const n=e.indexOf(Fe),r=e.slice(0,n),a=e.slice(n+Fe.length);r&&(X.current+=r,W(o=>o+r)),ae.current=!1,a&&(Q.current+=a,kt())}else e===Fe?ae.current=!1:(X.current+=e,W(n=>n+e));else if(e.includes(Fe)){const n=e.indexOf(Fe),r=e.slice(0,n),a=e.slice(n+Fe.length);Q.current+=r,kt(),ae.current=!0,a&&(X.current+=a,W(o=>o+a))}else if(e===Fe){ae.current=!0;return}else Q.current+=e,kt()};t.useEffect(()=>{(async()=>{const n=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let r=[];if(n)try{r=JSON.parse(n)}catch{r=[]}r.length===0&&w&&(w.name||w.email)?(r=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${w.name||""}" , Email is "${w.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(r))):n||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[w]),t.useEffect(()=>{const e=()=>{Ne.current=Date.now(),ce.current&&(ce.current=!1,f(!1),G([]),at(""),W(""),A(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const n=setInterval(async()=>{if(Date.now()-Ne.current>=3e4&&!k&&!I&&N==="Ready"&&!ce.current)if(ce.current=!0,Le.current.length>0)f(!0),G(Le.current);else try{const o=`${ot}/nudgeUser`,i={navigationUrl:window.location.href,agentId:g,lead_id:ze},u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(u.ok){const y=(await u.json()).nudge_questions;y&&y.length>0&&(C("[NUDGE] Received nudge questions from API:",y),Le.current=y,f(!0),G(y))}}catch(o){console.error("[NUDGE] Error calling /nudgeUser:",o),ce.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(n)}},[Se,k,I,N]),t.useEffect(()=>{if(O.length===0)return;let e=0,n=0,r=!1,a=100;const o=()=>{const i=O[e];if(r){const u=i.substring(0,n-1);at(u),n--,a=50}else{const u=i.substring(0,n+1);at(u),n++,a=100}!r&&n===i.length?(r=!0,a=3e3):r&&n===0&&(r=!1,e=(e+1)%O.length,a=500),z.current=setTimeout(o,a)};return o(),()=>{z.current&&clearTimeout(z.current)}},[O]);const Pt=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},cn=e=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(e))},[Et,Tt]=t.useState(!1),[Bt,Mt]=t.useState(0),we=t.useRef(null),bt=t.useRef([]),$t=t.useRef(0),[Vt,un]=t.useState(null),[ln,It]=t.useState(null),Ee=t.useRef(null),Ge=t.useRef(null),lt=t.useCallback((e=!1)=>{e&&(Oe.current=!0,R(!1),m("Ready")),Be.current=[],Pe.current=[],pe.current=!1,A(!1),ge.current=0,xe.current=0,Ae.current=0,Ie.current.forEach(n=>{try{n.stop()}catch{}}),et.current&&(clearTimeout(et.current),et.current=null),setTimeout(()=>{Ce(null),Qe("")},10),Ie.current=[]},[]),dn=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=window.AudioContext||window.webkitAudioContext,r=new n,a=r.createMediaStreamSource(e),o=r.createAnalyser();o.fftSize=64,a.connect(o),Ee.current=r,Ge.current=a,It(o);const i=new MediaRecorder(e);we.current=i,bt.current=[],i.ondataavailable=u=>{u.data.size>0&&bt.current.push(u.data)},i.onstop=async()=>{const u=Date.now()-$t.current;if(It(null),Ge.current&&(Ge.current.disconnect(),Ge.current=null),Ee.current&&Ee.current.state!=="closed"&&(Ee.current.close(),Ee.current=null),u<1e3){m("Recording too short. Hold or click longer."),R(!1);return}const v=new Blob(bt.current,{type:"audio/wav"});await pn(v)},$t.current=Date.now(),i.start(100),Tt(!0),m("Listening...")}catch(e){console.error("Error accessing microphone:",e),m("Mic Access Error")}},fn=()=>{we.current&&we.current.state!=="inactive"&&(we.current.stop(),we.current.stream.getTracks().forEach(e=>e.stop()),Tt(!1))},hn=()=>{we.current&&we.current.state!=="inactive"&&(we.current.onstop=null,we.current.stop(),we.current.stream.getTracks().forEach(e=>e.stop()),It(null),Ge.current&&(Ge.current.disconnect(),Ge.current=null),Ee.current&&Ee.current.state!=="closed"&&(Ee.current.close(),Ee.current=null),Tt(!1),bt.current=[],m("Ready"))};t.useEffect(()=>{if(!k)return;const e=()=>{const n=Ae.current;if(n<=0)return;const r=$e.current,a=ge.current;if(!r)return;const o=r.currentTime-a,i=Math.min(Math.max(0,o),n),v=on(Te).trim().length;if(v<=0)return;const y=Math.min(Math.round(i/n*v),v);p(y)};return clearInterval(s.current??void 0),s.current=setInterval(e,90),()=>clearInterval(s.current??void 0)},[k,Te,Ae.current]),t.useEffect(()=>{let e;return Et?(Mt(0),e=window.setInterval(()=>{Mt(n=>n+1)},1e3)):Mt(0),()=>clearInterval(e)},[Et]);const mn=e=>{const n=e.numberOfChannels,r=e.length*n*2+44,a=new ArrayBuffer(r),o=new DataView(a);let i=0;const u=E=>{o.setUint16(i,E,!0),i+=2},v=E=>{o.setUint32(i,E,!0),i+=4};v(1179011410),v(r-8),v(1163280727),v(544501094),v(16),u(1),u(n),v(e.sampleRate),v(e.sampleRate*2*n),u(n*2),u(16),v(1635017060),v(r-i-4);const y=[];for(let E=0;E<n;E++)y.push(e.getChannelData(E));let L=0;for(;i<r;){for(let E=0;E<n;E++){let P=Math.max(-1,Math.min(1,y[E][L]));P=P<0?P*32768:P*32767,o.setInt16(i,P,!0),i+=2}L++}return new Blob([a],{type:"audio/wav"})},At=async(e,n,r=!1)=>{if(!Oe.current){if(Me.current){Pe.current.push({audio:e,visemes:n,isNewSegment:r});return}Me.current=!0;try{const a=window.AudioContext||window.webkitAudioContext,o=$e.current??new a;o.state==="suspended"&&await o.resume(),$e.current=o;const i=window.atob(e),u=new Uint8Array(i.length);for(let Z=0;Z<i.length;Z++)u[Z]=i.charCodeAt(Z);const v=await o.decodeAudioData(u.buffer.slice(0));Ae.current+=v.duration;const y=o.currentTime;let L=xe.current;const E=!pe.current;L<y&&(L=y+.1),xe.current=L+v.duration;const P=o.createBufferSource();P.buffer=v;let B=Vt;if((!B||B.context!==o)&&(B=o.createAnalyser(),B.fftSize=64,B.connect(o.destination),un(B)),P.connect(B),Ie.current.push(P),Oe.current){Ie.current=Ie.current.filter(Z=>Z!==P);return}if(E){pe.current=!0,A(!0),C(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${L.toFixed(3)}`),ge.current=L;const Z=(L-y)*1e3;ct.current=performance.now()+Z,C(`[AUDIO] Response started. Initial startTime: ${L.toFixed(3)}, CT: ${y.toFixed(3)}`)}P.start(L);const fe=(L-ge.current)*1e3;r&&(Ke.current=fe,C(`[AUDIO] New segment detected at +${fe.toFixed(0)}ms. Resetting segment offset.`)),n.forEach((Z,he)=>{const F=Z.symbol??"";if(F){const me=Bn(F),ye=Math.round(Z.start*1e3),Je=Math.round((Z.duration??0)*1e3),qt=Ke.current+ye;he<3&&C(`[AUDIO] Viseme "${F}": segment_relative=${ye}ms, segment_offset=${Ke.current.toFixed(0)}ms => vtime=${qt}ms`),me.forEach(zt=>{Be.current.push({viseme:zt.v,weight:zt.w,vtime:qt,vduration:Je})})}}),m("Speaking...")}finally{if(Me.current=!1,Pe.current.length>0){const a=Pe.current.shift();a&&At(a.audio,a.visemes,a.isNewSegment)}}}},pn=async e=>{try{R(!0),f(!1),X.current="",W(""),m("Processing Voice...");const n=await e.arrayBuffer(),a=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(n),o=mn(a),i=new FileReader;i.readAsDataURL(o),i.onloadend=async()=>{const u=i.result.split(",")[1];lt(),ue(""),Q.current="",ae.current=!1;const v=`${ot}/stt?token=${encodeURIComponent(Se)}`,y=await fetch(v,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:u,audio_format:"wav",lead_id:ze})});if(y.status===429){try{const he=await y.text(),F=JSON.parse(he);C("[STT] 429 agent at capacity:",F?.detail)}catch{}ue(""),m("Busy"),R(!1);return}if(!y.ok){const he=await y.text();let F="STT Failed";try{F=JSON.parse(he).error||F}catch{he&&(F=he.slice(0,200))}throw new Error(F)}const L=y.body;if(C("this is body"+L),!L){m("STT Failed"),R(!1);return}const E=L.getReader();Oe.current=!1;const P=new TextDecoder;let B="",fe=!1;const Z=async(he,F)=>{switch(he){case"transcript":F.transcript!=null&&ue(String(F.transcript));break;case"text":{const me=F.delta??F.text??"";me&&jt(me);break}case"audio":{const me=F.chunk,ye=F.visemes??[],Je=!!F.is_new_segment;me&&await At(me,ye,Je);break}case"done":{fe=!0,m("Ready"),R(!1);break}case"error":{fe=!0,m("STT Failed"),R(!1);break}default:break}};for(;;){const{done:he,value:F}=await E.read();F&&(B+=P.decode(F,{stream:!0}));const me=B.split(`
4
4
 
5
- `);Q=ge.pop()??"";for(const ye of ge){const Ye=rt(ye);Ye&&await B(Ye.event,Ye.data)}if(pe){if(Q.trim()){const ye=rt(Q.trim());ye&&await B(ye.event,ye.data)}oe||(_("Ready"),p(!1));break}}}}catch(n){console.error("Audio Submission Error:",n),_("STT Failed"),p(!1)}},mn=async e=>{e&&e.preventDefault(),le(!1),ue.current="",fe(""),!(!G||ne)&&await pn(G)},rt=e=>{const n=e.split(/\r?\n/);let s="",i="";for(const a of n)a.startsWith("event:")?s=a.slice(6).trim():a.startsWith("data:")&&(i=a.slice(5).trim());if(!s)return null;let r={};if(i)try{r=JSON.parse(i)}catch{r={raw:i}}return{event:s,data:r}},gt=(e,n)=>{switch(e){case"connected":z.current="",M.current=!1;break;case"text":{const s=n.delta??"";s&&Nt(s);break}case"metadata":{mt(n);break}case"audio":{const s=n.chunk,i=n.visemes??[],r=n.is_new_segment??!1;s&&Tt(s,i,r);break}case"done":{const s=Ut(),i=ue.current.trim(),r=[...s,{role:"user",content:G||"..."},{role:"assistant",content:i}];on(r),ht.current=[...Te.current],_("Ready"),p(!1),ie("");break}case"error":{const s=n.message??"Unknown error";ue.current=s,fe(s),_("Agent Failed"),p(!1);break}}},Bt=async(e,n)=>{p(!0),_("Thinking..."),ue.current="",z.current="",M.current=!1,ft(),de.current=0,it(0);try{const s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(s.status===429){_("Busy"),p(!1);return}if(!s.ok)throw new Error("Request failed");const i=s.body;if(!i){_("Failed"),p(!1);return}const r=i.getReader();Oe.current=!1;const a=new TextDecoder;let d="";for(;;){const{done:y,value:v}=await r.read();v&&(d+=a.decode(v,{stream:!0}));const L=d.split(`
5
+ `);B=me.pop()??"";for(const ye of me){const Je=st(ye);Je&&await Z(Je.event,Je.data)}if(he){if(B.trim()){const ye=st(B.trim());ye&&await Z(ye.event,ye.data)}fe||(m("Ready"),R(!1));break}}}}catch(n){console.error("Audio Submission Error:",n),m("STT Failed"),R(!1)}},gn=async e=>{e&&e.preventDefault(),f(!1),X.current="",W(""),!(!T||I)&&await bn(T)},st=e=>{const n=e.split(/\r?\n/);let r="",a="";for(const i of n)i.startsWith("event:")?r=i.slice(6).trim():i.startsWith("data:")&&(a=i.slice(5).trim());if(!r)return null;let o={};if(a)try{o=JSON.parse(a)}catch{o={raw:a}}return{event:r,data:o}},_t=(e,n)=>{switch(e){case"connected":Q.current="",ae.current=!1;break;case"text":{const r=n.delta??"";r&&jt(r);break}case"metadata":{ke(n);break}case"audio":{const r=n.chunk,a=n.visemes??[],o=n.is_new_segment??!1;r&&At(r,a,o);break}case"done":{const r=Pt(),a=X.current.trim(),o=[...r,{role:"user",content:T||"..."},{role:"assistant",content:a}];cn(o),ft.current=[...Be.current],m("Ready"),R(!1),ue("");break}case"error":{const r=n.message??"Unknown error";X.current=r,W(r),m("Agent Failed"),R(!1);break}}},wt=async(e,n)=>{R(!0),m("Thinking..."),X.current="",Q.current="",ae.current=!1,lt(),Ae.current=0,p(0);try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status===429)return m("Busy"),R(!1),"";if(!r.ok)throw new Error("Request failed");const a=r.body;if(!a)return m("Failed"),R(!1),"";const o=a.getReader();Oe.current=!1;const i=new TextDecoder;let u="";for(;;){const{done:v,value:y}=await o.read();y&&(u+=i.decode(y,{stream:!0}));const L=u.split(`
6
6
 
7
- `);d=L.pop()??"";for(const x of L){const D=rt(x);D&&gt(D.event,D.data)}if(y){if(d.trim()){const x=rt(d.trim());x&&gt(x.event,x.data)}_("Ready"),p(!1);break}}}catch(s){console.error("Streaming Error:",s),_("Failed"),p(!1)}},Wt=t.useCallback(async(e,n)=>{const s=`${st}/avatar_tts`;await Bt(s,{user_query:e,llm_prompt:n})},[]),$t=t.useCallback(async(e,n,s,i)=>{const r=`${st}/avatar_ttsWithKnowledge`;await Bt(r,{user_query:e,llm_prompt:n,knowledge:s,history:i})},[]),Vt=t.useRef(!1);t.useEffect(()=>{g&&!Vt.current&&(g({avatarSpeak:Wt,avatarRespond:$t}),Vt.current=!0)},[g,Wt,$t]);const pn=async e=>{p(!0),_("Thinking..."),ue.current="",z.current="",M.current=!1,ft(),de.current=0,it(0);const n=`${st}/agent/chat?token=${encodeURIComponent(Qe)}`;try{const s=Ut();let i=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");i||(Rn("[CHAT] Session UID missing at send time! Generating emergency backup."),i="emergency-"+Math.random().toString(36).substring(7),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",i));const r={history:s,question:e,lead_id:i};C("[CHAT] Sending payload:",r);const a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),cache:"default"});if(a.status===429){try{const x=await a.json();C("[CHAT] 429 agent at capacity:",x?.detail)}catch{}ie(""),_("Busy"),p(!1);return}if(!a.ok)throw new Error("Agent request failed");const d=a.body;if(!d){_("Agent Failed"),p(!1);return}const y=d.getReader();Oe.current=!1;const v=new TextDecoder;let L="";for(;;){const{done:x,value:D}=await y.read();C(`[SSE] Chunk received. done=${x}, length=${D?.length||0}`),D&&(L+=v.decode(D,{stream:!0}));const Q=L.split(`
7
+ `);u=L.pop()??"";for(const E of L){const P=st(E);P&&_t(P.event,P.data)}if(v){if(u.trim()){const E=st(u.trim());E&&_t(E.event,E.data)}return m("Ready"),R(!1),X.current}}}catch(r){return console.error("Streaming Error:",r),m("Failed"),R(!1),""}},Wt=t.useCallback(async e=>{const n=`${ot}/avatar_tts`;return await wt(n,{user_query:e})},[wt]),Ht=t.useCallback(async(e,n,r)=>{const a=`${ot}/avatar_ttsWithKnowledge`;return await wt(a,{user_query:e,knowledge:n,history:r})},[wt]),Gt=t.useRef(!1);t.useEffect(()=>{b&&!Gt.current&&(b({avatarSpeak:Wt,avatarRespond:Ht}),Gt.current=!0)},[b,Wt,Ht]);const bn=async e=>{R(!0),m("Thinking..."),X.current="",Q.current="",ae.current=!1,lt(),Ae.current=0,p(0);const n=`${ot}/agent/chat?token=${encodeURIComponent(Se)}`;try{const a={history:Pt(),question:e,lead_id:ze};C("[CHAT] Sending payload:",a);const o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),cache:"default"});if(o.status===429){try{const L=await o.json();C("[CHAT] 429 agent at capacity:",L?.detail)}catch{}ue(""),m("Busy"),R(!1);return}if(!o.ok)throw new Error("Agent request failed");const i=o.body;if(!i){m("Agent Failed"),R(!1);return}const u=i.getReader();Oe.current=!1;const v=new TextDecoder;let y="";for(;;){const{done:L,value:E}=await u.read();C(`[SSE] Chunk received. done=${L}, length=${E?.length||0}`),E&&(y+=v.decode(E,{stream:!0}));const P=y.split(`
8
8
 
9
- `);L=Q.pop()??"";for(const oe of Q){C(`[SSE] Processing block: ${oe.slice(0,50)}...`);const B=rt(oe);B&&(C(`[SSE] Event: ${B.event}`),gt(B.event,B.data))}if(x){if(C("[SSE] Stream finished"),L.trim()){const oe=rt(L.trim());oe&&gt(oe.event,oe.data)}_("Ready"),p(!1),ie("");break}}}catch(s){console.error("Chat Error:",s),_("Agent Failed"),p(!1)}},gn=I.trim(),Ht=rn(gn),Mt=Ht&&O?Ht.slice(0,Ze!=null&&Ze>0?Ze:0):"";t.useEffect(()=>{const e=ut.current;if(e!=="exiting"){if(Mt)Rt(Mt),e==="hidden"&&qe("entering");else if(e==="visible"||e==="entering"){if(!l&&He){const n=He;try{window.location.href=n}catch{window.location.assign(n)}Ge(null)}qe("exiting")}}},[Mt,ce,l,He]);const bn=t.useCallback(()=>{const e=ut.current;e==="entering"?qe("visible"):e==="exiting"&&qe("hidden")},[]);t.useLayoutEffect(()=>{const e=Ne.current;e&&(e.scrollTop=e.scrollHeight)},[ct]);const _n=V==="female"?On:In;return ot?c.jsxs("div",{className:"avatar-widget-container",children:[c.jsxs("div",{className:"avatar-input-area",children:[De!=="hidden"?c.jsx("div",{className:`avatar-thinking-tab${De==="exiting"?" avatar-thinking-tab--exiting":De==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:xe,children:tt===tn?c.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):tt}):null,c.jsx("div",{className:"avatar-input-container",children:c.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:xt?c.jsxs("div",{className:"avatar-input-recording",children:[c.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:fn,title:"Cancel",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),c.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[c.jsx("div",{style:{flex:1,height:"100%"},children:c.jsx(qt,{analyser:cn})}),c.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(Ft/60),":",String(Ft%60).padStart(2,"0")]})]}),c.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:ln,title:"Send",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):O&&!ve?c.jsxs("div",{className:"avatar-input-speaking",children:[c.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:c.jsx(qt,{analyser:Pt})}),c.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>ft(!0),title:"Stop",children:c.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):ne?c.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:c.jsx("div",{className:"avatar-input-loader"})}):c.jsxs("form",{onSubmit:mn,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[c.jsx("input",{id:"avatar-text-input",type:"text",value:G,onChange:e=>ie(e.target.value),placeholder:W==="Busy"?"Assisting another user":j||"Ask me anything",disabled:ne||W==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),W==="Busy"?c.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):G.trim()===""?c.jsx("button",{type:"button",className:"mic-button",onClick:un,disabled:ne,style:{backgroundColor:"#1e4a5e"},children:c.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[c.jsx("path",{d:"M12 14C13.66 14 15 12.66 15 11V5C15 3.34 13.66 2 12 2C10.34 2 9 3.34 9 5V11C9 12.66 10.34 14 12 14Z",fill:"white"}),c.jsx("path",{d:"M17 11C17 13.76 14.76 16 12 16C9.24 16 7 13.76 7 11H5C5 14.53 7.61 17.43 11 17.93V21H13V17.93C16.39 17.43 19 14.53 19 11H17Z",fill:"white"})]})}):c.jsx("button",{type:"submit",className:"mic-button",disabled:ne,style:{backgroundColor:"#1e4a5e"},title:"Send",children:c.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:c.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),c.jsx("div",{className:"avatar-wrapper",children:c.jsxs("div",{className:"avatar-scene-wrapper",children:[ce!=="hidden"&&c.jsx("div",{className:`avatar-bubble${ce==="entering"?" avatar-bubble--entering":ce==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:bn,children:c.jsx("div",{ref:Ne,className:`avatar-bubble__content${ve?" avatar-bubble__content--nudge":""}`,children:ct})}),c.jsx("div",{className:"avatar-canvas-layer",style:{width:H,height:H},children:c.jsxs(Ct.Canvas,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1.8,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[c.jsx(Bn,{target:_n}),c.jsx("ambientLight",{intensity:.7}),c.jsx("directionalLight",{position:[0,2,2],intensity:1}),c.jsx(yt.Environment,{preset:"city"}),c.jsx(t.Suspense,{fallback:null,children:ke!==null&&c.jsx(Wn,{avatarUrl:ke,isPlayingRef:Be,visemeQueueRef:Te,audioContextRef:be,responseAudioStartTimeRef:Ae,adjustments:An,mood:b,expression:f,agentResponse:I,isSpeaking:O,nextStartTimeRef:We,stopPlayback:ft,setIsSpeaking:J,expressionUrl:ee,onExpressionFinished:je,isNudgeResponse:ve,avatarGender:V})})]})})]})})]}):null},Hn=({agentId:l,onNavigationRequested:m,presetUserDetails:S,onAvatarReady:g})=>c.jsx(Vn,{agentId:l,onNavigationRequested:m,presetUserDetails:S,onAvatarReady:g});exports.AvatarWidget=Hn;
9
+ `);y=P.pop()??"";for(const B of P){C(`[SSE] Processing block: ${B.slice(0,50)}...`);const fe=st(B);fe&&(C(`[SSE] Event: ${fe.event}`),_t(fe.event,fe.data))}if(L){if(C("[SSE] Stream finished"),y.trim()){const B=st(y.trim());B&&_t(B.event,B.data)}m("Ready"),R(!1),ue("");break}}}catch(r){console.error("Chat Error:",r),m("Agent Failed"),R(!1)}},_n=Te.trim(),Jt=on(_n),Ot=Jt&&k?Jt.slice(0,_!=null&&_>0?_:0):"";t.useEffect(()=>{const e=U.current;if(e!=="exiting"){if(Ot)nt(Ot),e==="hidden"&&tt("entering");else if(e==="visible"||e==="entering"){if(!d&&ve){const n=ve;try{window.location.href=n}catch{window.location.assign(n)}Ce(null)}tt("exiting")}}},[Ot,oe,d,ve]);const wn=t.useCallback(()=>{const e=U.current;e==="entering"?tt("visible"):e==="exiting"&&tt("hidden")},[]);t.useLayoutEffect(()=>{const e=ut.current;e&&(e.scrollTop=e.scrollHeight)},[pt]);const yn=ee==="female"?Dn:On;return it?c.jsxs("div",{className:"avatar-widget-container",children:[c.jsxs("div",{className:"avatar-input-area",children:[De!=="hidden"?c.jsx("div",{className:`avatar-thinking-tab${De==="exiting"?" avatar-thinking-tab--exiting":De==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:Lt,children:Xe===rn?c.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):Xe}):null,c.jsx("div",{className:"avatar-input-container",children:c.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:Et?c.jsxs("div",{className:"avatar-input-recording",children:[c.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:hn,title:"Cancel",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),c.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[c.jsx("div",{style:{flex:1,height:"100%"},children:c.jsx(Yt,{analyser:ln})}),c.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(Bt/60),":",String(Bt%60).padStart(2,"0")]})]}),c.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:fn,title:"Send",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block"},children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):k&&!He?c.jsxs("div",{className:"avatar-input-speaking",children:[c.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:c.jsx(Yt,{analyser:Vt})}),c.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>lt(!0),title:"Stop",children:c.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):I?c.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:c.jsx("div",{className:"avatar-input-loader"})}):c.jsxs("form",{onSubmit:gn,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[c.jsx("input",{id:"avatar-text-input",type:"text",value:T,onChange:e=>ue(e.target.value),placeholder:N==="Busy"?"Assisting another user":te||"Ask me anything",disabled:I||N==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),N==="Busy"?c.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:c.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):T.trim()===""?c.jsx("button",{type:"button",className:"mic-button",onClick:dn,disabled:I,style:{backgroundColor:"#1e4a5e"},children:c.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[c.jsx("path",{d:"M12 14C13.66 14 15 12.66 15 11V5C15 3.34 13.66 2 12 2C10.34 2 9 3.34 9 5V11C9 12.66 10.34 14 12 14Z",fill:"white"}),c.jsx("path",{d:"M17 11C17 13.76 14.76 16 12 16C9.24 16 7 13.76 7 11H5C5 14.53 7.61 17.43 11 17.93V21H13V17.93C16.39 17.43 19 14.53 19 11H17Z",fill:"white"})]})}):c.jsx("button",{type:"submit",className:"mic-button",disabled:I,style:{backgroundColor:"#1e4a5e"},title:"Send",children:c.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:c.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),c.jsx("div",{className:"avatar-wrapper",children:c.jsxs("div",{className:"avatar-scene-wrapper",children:[oe!=="hidden"&&c.jsx("div",{className:`avatar-bubble${oe==="entering"?" avatar-bubble--entering":oe==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:wn,children:c.jsx("div",{ref:ut,className:`avatar-bubble__content${He?" avatar-bubble__content--nudge":""}`,children:pt})}),c.jsx("div",{className:"avatar-canvas-layer",style:{width:Ye,height:Ye},children:c.jsxs(Ut.Canvas,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[c.jsx($n,{target:yn}),c.jsx("ambientLight",{intensity:.7}),c.jsx("directionalLight",{position:[0,2,2],intensity:1}),c.jsx(xt.Environment,{preset:"city"}),c.jsx(t.Suspense,{fallback:null,children:je!==null&&c.jsx(Vn,{avatarUrl:je,isPlayingRef:pe,visemeQueueRef:Be,audioContextRef:$e,responseAudioStartTimeRef:ge,adjustments:An,mood:h,expression:ne,agentResponse:Te,isSpeaking:k,nextStartTimeRef:xe,stopPlayback:lt,setIsSpeaking:A,expressionUrl:vt,onExpressionFinished:de,isNudgeResponse:He,avatarGender:ee})})]})})]})})]}):null},Gn=({agentId:d,onNavigationRequested:g,presetUserDetails:w,onAvatarReady:b})=>c.jsx(Hn,{agentId:d,onNavigationRequested:g,presetUserDetails:w,onAvatarReady:b});exports.AvatarWidget=Gn;