@streamoji/avatar-widget 0.3.6 → 0.3.9

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,7 +1,9 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("react/jsx-runtime"),Qe=require("@react-three/drei"),lt=require("@react-three/fiber"),t=require("react"),Yt=require("three"),Qt=require("three/examples/jsm/loaders/GLTFLoader.js");function Kt(u){const _=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(u){for(const g in u)if(g!=="default"){const m=Object.getOwnPropertyDescriptor(u,g);Object.defineProperty(_,g,m.get?m:{enumerable:!0,get:()=>u[g]})}}return _.default=u,Object.freeze(_)}const We=Kt(Yt),ct="https://ai.streamoji.com",W=(...u)=>{},Xt=(...u)=>{},Et=({analyser:u})=>{const _=t.useRef(null),g=t.useRef(null);return t.useEffect(()=>{const m=_.current;if(!m)return;const w=m.getContext("2d",{alpha:!0});if(!w)return;let C,V=null;u&&(u.fftSize=128,V=new Uint8Array(u.frequencyBinCount));const de=()=>{C=requestAnimationFrame(de),(m.width!==m.offsetWidth||m.height!==m.offsetHeight)&&(m.width=m.offsetWidth,m.height=m.offsetHeight);const Y=m.width,D=m.height;if(Y===0||D===0)return;const te=D/2;w.clearRect(0,0,Y,D),w.fillStyle="#1e293b";const A=2,y=A+2,E=Y*.95,N=Math.floor(E/y);(!g.current||g.current.length!==N)&&(g.current=new Float32Array(N).fill(2));const fe=N*y,x=(Y-fe)/2;u&&V&&u.getByteFrequencyData(V);const Re=V?V.length:0,G=Math.floor(Re*.7)/N,he=new Float32Array(N);for(let j=0;j<N;j++){let $=0;if(V&&G>0){const U=Math.floor(j*G),pe=Math.floor((j+1)*G);for(let I=U;I<pe;I++){const R=V[I]||0;R>$&&($=R)}}$<10&&($=0);const J=$/255,L=$>0?Math.max(2,Math.pow(J,1.4)*D*.25):2;he[j]=L}for(let j=0;j<N;j++){const $=N-1-j,J=Math.max(he[j],he[$]),L=g.current[j]+(J-g.current[j])*.3;g.current[j]=L;const U=x+j*y,pe=te-L/2;w.beginPath(),w.roundRect?w.roundRect(U,pe,A,L,4):w.fillRect(U,pe,A,L),w.fill()}};return de(),()=>{cancelAnimationFrame(C)}},[u]),a.jsx("canvas",{ref:_,style:{width:"100%",height:"100%",display:"block"}})},Zt="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",At="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";async function en(u){const _=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u));return Array.from(new Uint8Array(_)).map(g=>g.toString(16).padStart(2,"0")).join("")}function tn(u){const[_,g]=t.useState(null);return t.useEffect(()=>{if(!u){g(null);return}let m=!1;return en(u).then(w=>{if(m)return;const C=`${Zt}/${w}.glb`;fetch(C,{method:"HEAD"}).then(V=>{m||g(V.ok?C:At)}).catch(()=>{m||g(At)})}),()=>{m=!0}},[u]),_}const nn=["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"],rn=["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"],sn=[{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"}],an=["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"],on=["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"],cn={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},un=[-.45,1.9,.1],ln={browInnerUp:.2},ut=.18,dn=1,Lt="__branding__",Ye={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}},fn=[{key:"viseme_aa",mix:{jawOpen:.6}},{key:"viseme_E",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.3}},{key:"viseme_I",mix:{mouthPressLeft:.6,mouthPressRight:.6,mouthDimpleLeft:.6,mouthDimpleRight:.6,jawOpen:.2}},{key:"viseme_O",mix:{mouthPucker:1,jawForward:.6,jawOpen:.2}},{key:"viseme_U",mix:{mouthFunnel:1}},{key:"viseme_PP",mix:{mouthRollLower:.3,mouthRollUpper:.3,mouthUpperUpLeft:.3,mouthUpperUpRight:.3}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthLowerDownLeft:.2,mouthLowerDownRight:.2,mouthDimpleLeft:1,mouthDimpleRight:1,mouthRollLower:.3}},{key:"viseme_DD",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthFunnel:.5,jawOpen:.2}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.5,mouthLowerDownRight:.5,jawOpen:.1}},{key:"viseme_TH",mix:{mouthRollUpper:.3,jawOpen:.2,tongueOut:.4}},{key:"viseme_CH",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.5,jawOpen:.2}},{key:"viseme_kk",mix:{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}},{key:"viseme_sil",mix:{}}],hn={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}]};function mn(u){if(!u)return[{v:"sil",w:1}];const _=u.toLowerCase();return hn[_]??[{v:"sil",w:1}]}function pn({target:u}){const{camera:_}=lt.useThree();return t.useEffect(()=>{_.lookAt(...u)},[_,u]),null}function z(u,_,g){if(!u||!u.morphTargetDictionary)return;const m=u,w=m.morphTargetDictionary,C=m.morphTargetInfluences;if(C)for(const V in w)V.toLowerCase()===_.toLowerCase()&&(C[w[V]]=g)}function It(u,_=.97){if(!u)return;const g=u;if(g.morphTargetInfluences)for(let m=0;m<g.morphTargetInfluences.length;m++)g.morphTargetInfluences[m]*=_}const gn=t.memo(({avatarUrl:u,isPlayingRef:_,visemeQueueRef:g,audioContextRef:m,responseAudioStartTimeRef:w,adjustments:C,mood:V,expression:de,agentResponse:Y,isSpeaking:D,nextStartTimeRef:te,stopPlayback:A,setIsSpeaking:v,expressionUrl:y,onExpressionFinished:E,isNudgeResponse:N,avatarGender:fe})=>{const{scene:x}=Qe.useGLTF(u),Re=fe==="female"?rn:nn,Fe=Qe.useGLTF(Re),G=t.useMemo(()=>Fe.flatMap(f=>f.animations),[Fe]),he=fe==="female"?on:an,j=Qe.useGLTF(he),$=t.useMemo(()=>j.flatMap(f=>f.animations),[j]),J=t.useRef(null),L=t.useRef(null),U=t.useRef(null),pe=t.useRef([]),[I]=t.useState(()=>new We.AnimationMixer(x)),R=t.useRef({}),M=t.useRef(null),ge=t.useRef(0),Me=t.useRef(!1),be=t.useRef(0),oe=t.useRef(null);t.useEffect(()=>{if(!(!G||!x)){if(G.forEach((f,d)=>{const o=`idle_${d}`;if(!R.current[o]){const c=I.clipAction(f,x);c.name=o,c.setLoop(We.LoopOnce,1),c.clampWhenFinished=!0,R.current[o]=c}}),$.forEach((f,d)=>{const o=`talk_${d}`;if(!R.current[o]){const c=I.clipAction(f,x);c.name=o,c.setLoop(We.LoopOnce,1),c.clampWhenFinished=!0,R.current[o]=c}}),G.length>0){const f=R.current.idle_0,d=M.current&&I.existingAction(M.current.getClip());f&&!d&&(f.reset().fadeIn(.5).play(),M.current=f)}return()=>{I.stopAllAction(),R.current={},M.current=null}}},[G,$,x,I]);const _e=t.useRef("");t.useEffect(()=>{if(!y||!x||y===_e.current)return;_e.current=y,oe.current=y,new Qt.GLTFLoader().load(y,d=>{if(d.animations&&d.animations.length>0){const o=d.animations[0],c=I.clipAction(o,x);if(c.name=`EXPR_${y}`,c.setLoop(We.LoopOnce,1),c.clampWhenFinished=!0,R.current[`EXPR_${y}`]=c,D&&oe.current===y){const h=M.current;c.reset().fadeIn(.3).play(),h&&h!==c&&h.crossFadeTo(c,.3,!0),M.current=c,oe.current=null}}},void 0,d=>{console.error(`[ANIMATION] Failed to load ${y}`,d)})},[y,x,I,D]),t.useEffect(()=>{const f=d=>{const o=d.action,c=o.name||"";if(c.startsWith("idle_")){const P=(parseInt(c.split("_")[1])+1)%G.length,Q=R.current[`idle_${P}`];Q&&(Q.reset().fadeIn(.5).play(),o.crossFadeTo(Q,.5,!0),M.current=Q)}else if(c.startsWith("EXPR_")){if(D){const h=Math.floor(Math.random()*$.length),P=R.current[`talk_${h}`];P&&(P.reset().fadeIn(.5).play(),o.crossFadeTo(P,.5,!0),M.current=P)}else{const h=R.current.idle_0;h&&(h.reset().fadeIn(.5).play(),o.crossFadeTo(h,.5,!0),M.current=h)}E&&E()}else if(c.startsWith("talk_"))if(D&&!N){const P=(parseInt(c.split("_")[1])+1)%$.length,Q=R.current[`talk_${P}`];Q&&(Q.reset().fadeIn(.3).play(),o.crossFadeTo(Q,.3,!0),M.current=Q)}else{const h=R.current.idle_0;h&&(h.reset().fadeIn(.5).play(),o.crossFadeTo(h,.5,!0),M.current=h)}};return I.addEventListener("finished",f),()=>I.removeEventListener("finished",f)},[I,G,$,D,N,E]),t.useEffect(()=>{if(D&&x){const f=M.current,d=f?.name||"";if(d.startsWith("idle_")||d.startsWith("talk_")||d===""){const o=oe.current;if(o){const c=R.current[`EXPR_${o}`];if(c){c.reset().fadeIn(.3).play(),f&&f!==c&&f.crossFadeTo(c,.3,!0),M.current=c,oe.current=null;return}}if(d.startsWith("idle_")||d===""){const c=Math.floor(Math.random()*$.length),h=R.current[`talk_${c}`];h&&(h.reset().fadeIn(.5).play(),f&&f.crossFadeTo(h,.5,!0),M.current=h)}}}else if(!D&&x){const f=M.current,d=f?.name||"";if(d.startsWith("talk_")||d.startsWith("EXPR_")){const o=R.current.idle_0;o&&(o.reset().fadeIn(.5).play(),f&&f.crossFadeTo(o,.5,!0),M.current=o)}}},[D,x,y]),t.useEffect(()=>{if(!x)return;x.traverse(o=>{if(o.isMesh&&o.morphTargetDictionary){const c=o.name.toLowerCase();(c.includes("head")||c.includes("avatar"))&&(L.current=o,W(`[ANIMATION] Found head mesh: ${o.name}`)),c.includes("teeth")&&(U.current=o,W(`[ANIMATION] Found teeth mesh: ${o.name}`))}});const f=L.current?.morphTargetDictionary;f&&Object.keys(f).filter(o=>o.toLowerCase().includes("brow"));const d=[];x.traverse(o=>{if(o.isMesh){const h=o.morphTargetDictionary;h&&Object.keys(h).some(P=>P.toLowerCase().includes("brow"))&&d.push(o)}}),pe.current=d,d.length>0&&W("[ANIMATION] Meshes with brow morphs:",d.length)},[x]);const Ne=(f,d=1)=>{const o=`viseme_${f}`.toLowerCase(),c=fn.find(h=>h.key.toLowerCase()===o);if(c)for(const h in c.mix){const P=c.mix[h]*d;z(L.current,h,P),z(U.current,h,P)}},ke=f=>{const d=Ye[f]??Ye.neutral;for(const o in d)z(L.current,o,d[o]),z(U.current,o,d[o])};return lt.useFrame((f,d)=>{const o=Math.pow(.88,60*d);It(L.current,o),It(U.current,o),ke(V);const c=f.clock.elapsedTime;let h=0;if(Math.floor(c)%5===0&&Math.floor((c-d)%5)!==0){let H=null;x.traverse(K=>{K.name.toLowerCase().includes("hips")&&(H=K)});const we=H?`Hips Y: ${H.position.y.toFixed(4)}`:"Hips not found";W(`[ANIMATION] Mixer Time: ${I.time.toFixed(2)}, ${we}`)}if(I.update(d),c>ge.current&&!Me.current&&(Me.current=!0,be.current=c),Me.current){const H=D?.2:.3,we=(c-be.current)/H;if(we>=1){Me.current=!1;const K=D?1:2.5;ge.current=c+K}else{const K=we<.5?we*2:(1-we)*2;z(L.current,"eyeBlinkLeft",K),z(L.current,"eyeBlinkRight",K),z(U.current,"eyeBlinkLeft",K),z(U.current,"eyeBlinkRight",K),h=K*ln.browInnerUp}}const P=Ye[V]??Ye.neutral,Q=P.browInnerUp??0,Ke=P.browOuterUpLeft??0,Ve=P.browOuterUpRight??0,je=c*dn,Te=ut*Math.sin(je),Z=ut*.7*Math.sin(je+.7),$e=ut*.7*Math.sin(je+1.3),ne=H=>Math.max(0,Math.min(1,H)),Ee=ne(Q+Te),Ae=ne(Ke+Z),Ue=ne(Ve+$e),Oe=ne(Ee+h);if(z(L.current,"browInnerUp",Oe),z(U.current,"browInnerUp",Oe),z(L.current,"browOuterUpLeft",Ae),z(U.current,"browOuterUpLeft",Ae),z(L.current,"browOuterUpRight",Ue),z(U.current,"browOuterUpRight",Ue),J.current){const H=_.current?0:C.rotation[1];J.current.rotation.y=We.MathUtils.lerp(J.current.rotation.y,H,.1),J.current.position.set(...C.position),J.current.scale.setScalar(C.scale),J.current.rotation.x=C.rotation[0],J.current.rotation.z=C.rotation[2]}if(_.current&&m.current){const H=m.current.currentTime,Ce=(H-w.current)*1e3- -150;for(let ee=0;ee<g.current.length;ee++){const re=g.current[ee];Ce>=re.vtime&&Ce<re.vtime+re.vduration&&Ne(re.viseme,re.weight??1)}H>te.current+.5&&(A(),v(!1))}}),a.jsx("group",{ref:J,children:a.jsx("primitive",{object:x})})});function bn(u){return u?u.charAt(0).toUpperCase()+u.slice(1).toLowerCase():""}function Mt(u){return u.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const _n=({token:u,agentToken:_,onNavigationRequested:g,avatarGender:m,presetUserDetails:w}={})=>{const C=u??_??"",V=tn(C||void 0),[de,Y]=t.useState(""),[D,te]=t.useState(""),[A,v]=t.useState("Ready"),[y,E]=t.useState(!1),[N,fe]=t.useState(!1),[x,Re]=t.useState([]),[Fe,G]=t.useState(""),he=t.useRef(null),[j,$]=t.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);t.useEffect(()=>{const e=window.matchMedia("(max-width: 480px)"),n=()=>$(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]);const J=j?80:600,L=t.useRef(!1),U=t.useRef([]),pe=t.useRef(0),I=t.useRef(!1),R=t.useRef([]),M=t.useRef(null),ge=t.useRef([]);t.useRef([]);const Me=t.useRef([]),be=t.useRef(0),oe=t.useRef(0),_e=t.useRef(0),Ne=t.useRef(0),ke=t.useRef(!1),[f,d]=t.useState(null),o=t.useRef(null),[c,h]=t.useState("neutral"),[P,Q]=t.useState(""),[Ke,Ve]=t.useState(""),[je,Te]=t.useState("Chat with us"),[Z,$e]=t.useState(null),[ne,Ee]=t.useState("hidden"),[Ae,Ue]=t.useState(""),Oe=t.useRef(null),H=t.useRef(ne);H.current=ne;const[we,K]=t.useState(null),Ce=t.useRef(null),ee=t.useRef(null),[re,dt]=t.useState(!1),ft=t.useRef(null),[ce,He]=t.useState("hidden"),[ht,Ot]=t.useState(""),Xe=t.useRef(ce);Xe.current=ce;const se=t.useRef(""),Se=t.useRef(!1),ve=t.useRef(""),mt=t.useRef(Date.now()),Ze=t.useRef([]),Pe=t.useRef(!1),[et,Be]=t.useState(!1),[pt,gt]=t.useState(!1),xe=t.useRef(null),De=t.useMemo(()=>re?"Try again":A==="Busy"?"Busy":A==="Thinking..."||A==="Processing Voice..."?A:Z!=null&&Z!==""&&Z!=="none"&&Z!=="<none>"?`Enter ${bn(Z)}`:ce!=="hidden"||!pt?null:Lt,[A,Z,re,ce,pt]),bt=!re&&A!=="Busy"&&A!=="Thinking..."&&A!=="Processing Voice..."&&(Z==null||Z===""||Z==="none"||Z==="<none>");t.useEffect(()=>{if(ce!=="hidden"||!bt){gt(!1),xe.current!=null&&(clearTimeout(xe.current),xe.current=null);return}return xe.current=setTimeout(()=>{xe.current=null,gt(!0)},400),()=>{xe.current!=null&&(clearTimeout(xe.current),xe.current=null)}},[ce,bt]);const qe=De!=null&&De!=="";t.useEffect(()=>{const e=H.current;if(!(e==="exiting"||e==="entering")){if(e==="hidden"){qe&&(Ue(De??""),Ee("entering"));return}e==="visible"&&(!qe||De!==Ae)&&(Oe.current=qe?De:null,Ee("exiting"))}},[qe,De,ne,Ae]),t.useEffect(()=>{if(A!=="Busy"){ee.current!=null&&(clearTimeout(ee.current),ee.current=null);return}return ee.current=setTimeout(()=>{ee.current=null,v("Ready"),dt(!0)},12e3),()=>{ee.current!=null&&(clearTimeout(ee.current),ee.current=null)}},[A]),t.useEffect(()=>{if(!re)return;const e=setTimeout(()=>dt(!1),2500);return()=>clearTimeout(e)},[re]);const Ct=t.useCallback(()=>{const e=H.current;if(e==="exiting"){Ee("hidden");const n=Oe.current;Oe.current=null,n!=null&&n!==""&&(Ue(n),Ee("entering"))}else e==="entering"&&Ee("visible")},[]),Dt=e=>{if(!e)return;if(e.mood!=null){const r=String(e.mood).toLowerCase();h(r)}if(e.expression!=null){const r=String(e.expression).trim();Q(r);const l=sn.find(p=>p.name.toLowerCase()===r.toLowerCase());W(`[STREAM] Animation match for "${r}": ${l?l.name:"NONE"}`),Ve(l?.url??"")}if(e.navigation!=null){const r=String(e.navigation).trim();r!==""&&(g?g(r):window.open(r,"_blank"))}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(w&&(r==="email"&&w.email||r==="name"&&w.name||r==="phone"&&w.phone))return;$e(r||null),Te(r==="email"?"Enter your email":r==="name"?"Enter your name":r==="phone"?"Enter your phone number":"Chat with us")}else(i||e.ask_for===null||e.lead_capture&&e.lead_capture.ask_for===null||e.ask_for==="none")&&($e(null),je!=="Chat with us"&&Te("Chat with us"));e.collected,e.valid},Ft=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},Nt=t.useCallback(()=>{},[]),ye="§",tt=()=>{for(;se.current.includes(`
2
- `);){const e=se.current.indexOf(`
3
- `),n=se.current.slice(0,e).trim();se.current=se.current.slice(e+1);const s=Ft(n);s&&Dt(s)}},_t=e=>{if(Se.current)if(e.includes(ye)){const n=e.indexOf(ye),s=e.slice(0,n),i=e.slice(n+ye.length);s&&(ve.current+=s,te(r=>r+s)),Se.current=!1,i&&(se.current+=i,tt())}else e===ye?Se.current=!1:(ve.current+=e,te(n=>n+e));else if(e.includes(ye)){const n=e.indexOf(ye),s=e.slice(0,n),i=e.slice(n+ye.length);se.current+=s,tt(),Se.current=!0,i&&(ve.current+=i,te(r=>r+i))}else if(e===ye){Se.current=!0;return}else se.current+=e,tt()};t.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const r="secret",l=Math.floor(Date.now()/1e3).toString();try{const p=new TextEncoder,b=await crypto.subtle.importKey("raw",p.encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),S=await crypto.subtle.sign("HMAC",b,p.encode(l)),T=Array.from(new Uint8Array(S)).map(B=>B.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",T),W("[SESSION] New HMAC UID generated and saved:",T)}catch(p){console.error("[SESSION] HMAC generation failed:",p);const b=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",b)}}const s=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let i=[];if(s)try{i=JSON.parse(s)}catch{i=[]}i.length===0&&w&&(w.name||w.email)?(i=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${w.name||""}" , Email is "${w.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(i))):s||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[w]),t.useEffect(()=>{const e=()=>{mt.current=Date.now(),Pe.current&&(Pe.current=!1,Be(!1),Re([]),G(""),te(""),fe(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const n=setInterval(async()=>{if(Date.now()-mt.current>=3e4&&!N&&!y&&A==="Ready"&&!Pe.current)if(Pe.current=!0,Ze.current.length>0)Be(!0),Re(Ze.current);else try{const r=`${ct}/nudgeUser`,l={navigationUrl:window.location.href,token:C},p=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(p.ok){const S=(await p.json()).nudge_questions;S&&S.length>0&&(W("[NUDGE] Received nudge questions from API:",S),Ze.current=S,Be(!0),Re(S))}}catch(r){console.error("[NUDGE] Error calling /nudgeUser:",r),Pe.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(n)}},[C,N,y,A]),t.useEffect(()=>{if(x.length===0)return;let e=0,n=0,s=!1,i=100;const r=()=>{const l=x[e];if(s){const p=l.substring(0,n-1);G(p),n--,i=50}else{const p=l.substring(0,n+1);G(p),n++,i=100}!s&&n===l.length?(s=!0,i=3e3):s&&n===0&&(s=!1,e=(e+1)%x.length,i=500),he.current=setTimeout(r,i)};return r(),()=>{he.current&&clearTimeout(he.current)}},[x]);const wt=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},jt=e=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(e))},[nt,rt]=t.useState(!1),[St,st]=t.useState(0),ue=t.useRef(null),Je=t.useRef([]),vt=t.useRef(0),[xt,Ut]=t.useState(null),[Pt,it]=t.useState(null),me=t.useRef(null),Le=t.useRef(null),Ge=t.useCallback((e=!1)=>{e&&(ke.current=!0,E(!1),v("Ready")),R.current=[],U.current=[],I.current=!1,fe(!1),be.current=0,oe.current=0,_e.current=0,ge.current.forEach(n=>{try{n.stop()}catch{}}),Ce.current&&(clearTimeout(Ce.current),Ce.current=null),K(null),Ve(""),ge.current=[]},[]),Bt=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),me.current=s,Le.current=i,it(r);const l=new MediaRecorder(e);ue.current=l,Je.current=[],l.ondataavailable=p=>{p.data.size>0&&Je.current.push(p.data)},l.onstop=async()=>{const p=Date.now()-vt.current;if(it(null),Le.current&&(Le.current.disconnect(),Le.current=null),me.current&&me.current.state!=="closed"&&(me.current.close(),me.current=null),p<1e3){v("Recording too short. Hold or click longer."),E(!1);return}const b=new Blob(Je.current,{type:"audio/wav"});await Ht(b)},vt.current=Date.now(),l.start(100),rt(!0),v("Listening...")}catch(e){console.error("Error accessing microphone:",e),v("Mic Access Error")}},Wt=()=>{ue.current&&ue.current.state!=="inactive"&&(ue.current.stop(),ue.current.stream.getTracks().forEach(e=>e.stop()),rt(!1))},Vt=()=>{ue.current&&ue.current.state!=="inactive"&&(ue.current.onstop=null,ue.current.stop(),ue.current.stream.getTracks().forEach(e=>e.stop()),it(null),Le.current&&(Le.current.disconnect(),Le.current=null),me.current&&me.current.state!=="closed"&&(me.current.close(),me.current=null),rt(!1),Je.current=[],v("Ready"))};t.useEffect(()=>{if(!N)return;const e=()=>{const n=_e.current;if(n<=0)return;const s=M.current,i=be.current;if(!s)return;const r=s.currentTime-i,l=Math.min(Math.max(0,r),n),b=Mt(D).trim().length;if(b<=0)return;const S=Math.min(Math.round(l/n*b),b);d(S)};return clearInterval(o.current??void 0),o.current=setInterval(e,90),()=>clearInterval(o.current??void 0)},[N,D,_e.current]),t.useEffect(()=>{let e;return nt?(st(0),e=window.setInterval(()=>{st(n=>n+1)},1e3)):st(0),()=>clearInterval(e)},[nt]);const $t=e=>{const n=e.numberOfChannels,s=e.length*n*2+44,i=new ArrayBuffer(s),r=new DataView(i);let l=0;const p=T=>{r.setUint16(l,T,!0),l+=2},b=T=>{r.setUint32(l,T,!0),l+=4};b(1179011410),b(s-8),b(1163280727),b(544501094),b(16),p(1),p(n),b(e.sampleRate),b(e.sampleRate*2*n),p(n*2),p(16),b(1635017060),b(s-l-4);const S=[];for(let T=0;T<n;T++)S.push(e.getChannelData(T));let k=0;for(;l<s;){for(let T=0;T<n;T++){let B=Math.max(-1,Math.min(1,S[T][k]));B=B<0?B*32768:B*32767,r.setInt16(l,B,!0),l+=2}k++}return new Blob([i],{type:"audio/wav"})},at=async(e,n,s=!1)=>{if(!ke.current){if(L.current){U.current.push({audio:e,visemes:n,isNewSegment:s});return}L.current=!0;try{const i=window.AudioContext||window.webkitAudioContext,r=M.current??new i;r.state==="suspended"&&await r.resume(),M.current=r;const l=window.atob(e),p=new Uint8Array(l.length);for(let F=0;F<l.length;F++)p[F]=l.charCodeAt(F);const b=await r.decodeAudioData(p.buffer.slice(0));_e.current+=b.duration;const S=r.currentTime;let k=oe.current;const T=!I.current;k<S&&(k=S+.1),oe.current=k+b.duration;const B=r.createBufferSource();B.buffer=b;let q=xt;if((!q||q.context!==r)&&(q=r.createAnalyser(),q.fftSize=64,q.connect(r.destination),Ut(q)),B.connect(q),ge.current.push(B),ke.current){ge.current=ge.current.filter(F=>F!==B);return}if(T){I.current=!0,fe(!0),W(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${k.toFixed(3)}`),be.current=k;const F=(k-S)*1e3;pe.current=performance.now()+F,W(`[AUDIO] Response started. Initial startTime: ${k.toFixed(3)}, CT: ${S.toFixed(3)}`)}B.start(k);const X=(k-be.current)*1e3;s&&(Ne.current=X,W(`[AUDIO] New segment detected at +${X.toFixed(0)}ms. Resetting segment offset.`)),n.forEach((F,ie)=>{const O=F.symbol??"";if(O){const ae=mn(O),le=Math.round(F.start*1e3),Ie=Math.round((F.duration??0)*1e3),kt=Ne.current+le;ie<3&&W(`[AUDIO] Viseme "${O}": segment_relative=${le}ms, segment_offset=${Ne.current.toFixed(0)}ms => vtime=${kt}ms`),ae.forEach(Tt=>{R.current.push({viseme:Tt.v,weight:Tt.w,vtime:kt,vduration:Ie})})}}),v("Speaking...")}finally{if(L.current=!1,U.current.length>0){const i=U.current.shift();i&&at(i.audio,i.visemes,i.isNewSegment)}}}},Ht=async e=>{try{E(!0),Be(!1),ve.current="",te(""),v("Processing Voice...");const n=await e.arrayBuffer(),i=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(n),r=$t(i),l=new FileReader;l.readAsDataURL(r),l.onloadend=async()=>{const p=l.result.split(",")[1];Ge(),Y(""),se.current="",Se.current=!1;const b=`${ct}/stt?token=${encodeURIComponent(C)}`,S=await fetch(b,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:p,audio_format:"wav"})});if(S.status===429){try{const ie=await S.text(),O=JSON.parse(ie);W("[STT] 429 agent at capacity:",O?.detail)}catch{}Y(""),v("Busy"),E(!1);return}if(!S.ok){const ie=await S.text();let O="STT Failed";try{O=JSON.parse(ie).error||O}catch{ie&&(O=ie.slice(0,200))}throw new Error(O)}const k=S.body;if(W("this is body"+k),!k){v("STT Failed"),E(!1);return}const T=k.getReader();ke.current=!1;const B=new TextDecoder;let q="",X=!1;const F=async(ie,O)=>{switch(ie){case"transcript":O.transcript!=null&&Y(String(O.transcript));break;case"text":{const ae=O.delta??O.text??"";ae&&_t(ae);break}case"audio":{const ae=O.chunk,le=O.visemes??[],Ie=!!O.is_new_segment;ae&&await at(ae,le,Ie);break}case"done":{X=!0,v("Ready"),E(!1);break}case"error":{X=!0,v("STT Failed"),E(!1);break}default:break}};for(;;){const{done:ie,value:O}=await T.read();O&&(q+=B.decode(O,{stream:!0}));const ae=q.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("react/jsx-runtime"),Ze=require("@react-three/drei"),ft=require("@react-three/fiber"),t=require("react"),tn=require("three"),nn=require("three/examples/jsm/loaders/GLTFLoader.js");function rn(l){const y=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(l){for(const _ in l)if(_!=="default"){const g=Object.getOwnPropertyDescriptor(l,_);Object.defineProperty(y,_,g.get?g:{enumerable:!0,get:()=>l[_]})}}return y.default=l,Object.freeze(y)}const He=rn(tn),qe="https://ai.streamoji.com",j=(...l)=>{},sn=(...l)=>{},Ot=({analyser:l})=>{const y=t.useRef(null),_=t.useRef(null);return t.useEffect(()=>{const g=y.current;if(!g)return;const x=g.getContext("2d",{alpha:!0});if(!x)return;let W,M=null;l&&(l.fftSize=128,M=new Uint8Array(l.frequencyBinCount));const Oe=()=>{W=requestAnimationFrame(Oe),(g.width!==g.offsetWidth||g.height!==g.offsetHeight)&&(g.width=g.offsetWidth,g.height=g.offsetHeight);const re=g.width,k=g.height;if(re===0||k===0)return;const be=k/2;x.clearRect(0,0,re,k),x.fillStyle="#1e293b";const z=2,h=z+2,Y=re*.95,b=Math.floor(Y/h);(!_.current||_.current.length!==b)&&(_.current=new Float32Array(b).fill(2));const X=b*h,L=(re-X)/2;l&&M&&l.getByteFrequencyData(M);const _e=M?M.length:0,Z=Math.floor(_e*.7)/b,he=new Float32Array(b);for(let I=0;I<b;I++){let $=0;if(M&&Z>0){const P=Math.floor(I*Z),B=Math.floor((I+1)*Z);for(let Ee=P;Ee<B;Ee++){const F=M[Ee]||0;F>$&&($=F)}}$<10&&($=0);const G=$/255,C=$>0?Math.max(2,Math.pow(G,1.4)*k*.25):2;he[I]=C}for(let I=0;I<b;I++){const $=b-1-I,G=Math.max(he[I],he[$]),C=_.current[I]+(G-_.current[I])*.3;_.current[I]=C;const P=L+I*h,B=be-C/2;x.beginPath(),x.roundRect?x.roundRect(P,B,z,C,4):x.fillRect(P,B,z,C),x.fill()}};return Oe(),()=>{cancelAnimationFrame(W)}},[l]),c.jsx("canvas",{ref:y,style:{width:"100%",height:"100%",display:"block"}})},on="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",Ct="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";async function an(l){const y=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(l));return Array.from(new Uint8Array(y)).map(_=>_.toString(16).padStart(2,"0")).join("")}function cn(l){const[y,_]=t.useState(null);return t.useEffect(()=>{if(!l){_(null);return}let g=!1;return an(l).then(x=>{if(g)return;const W=`${on}/${x}.glb`;fetch(W,{method:"HEAD"}).then(M=>{g||_(M.ok?W:Ct)}).catch(()=>{g||_(Ct)})}),()=>{g=!0}},[l]),y}const un=["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"],ln=["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"],dn=[{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"}],hn=["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"],fn=["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"],mn={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},pn=[-.45,1.9,.1],gn=[-.45,1.75,.1],bn={browInnerUp:.2},dt=.18,_n=1,Ft="__branding__",Xe={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}},wn=[{key:"viseme_aa",mix:{jawOpen:.4,mouthSmileLeft:.15,mouthSmileRight:.15},teethMix:{jawOpen:.2,mouthSmileLeft:.15,mouthSmileRight:.15}},{key:"viseme_E",mix:{mouthPressLeft:.65,mouthPressRight:.65,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.25,mouthFunnel:.1},teethMix:{jawOpen:.15,mouthPressLeft:.65,mouthPressRight:.65,mouthDimpleLeft:1,mouthDimpleRight:1,mouthFunnel:.1}},{key:"viseme_I",mix:{mouthPressLeft:.55,mouthPressRight:.55,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.15,mouthFunnel:.05},teethMix:{mouthPressLeft:.55,mouthPressRight:.55,mouthDimpleLeft:1,mouthDimpleRight:1,jawOpen:.15,mouthFunnel:.05}},{key:"viseme_O",mix:{mouthPucker:.7,jawOpen:.4,mouthFunnel:.25},teethMix:{jawForward:.6,jawOpen:.2,mouthPucker:.7,mouthFunnel:.25}},{key:"viseme_U",mix:{mouthFunnel:1,mouthClose:.2},teethMix:{mouthFunnel:1,mouthClose:.2}},{key:"viseme_PP",mix:{mouthDimpleLeft:.5,mouthDimpleRight:.5,mouthStretchLeft:.3,mouthStretchRight:.3,mouthRollLower:.3,mouthRollUpper:.3,mouthPressLeft:.5,mouthPressRight:.5},teethMix:{mouthDimpleLeft:.5,mouthDimpleRight:.5,mouthStretchLeft:.3,mouthStretchRight:.3,mouthRollLower:.3,mouthRollUpper:.3,mouthPressLeft:.5,mouthPressRight:.5}},{key:"viseme_FF",mix:{mouthPucker:1,mouthShrugUpper:1,mouthDimpleLeft:1,mouthDimpleRight:1,mouthStretchLeft:.5,mouthStretchRight:.5,mouthPressLeft:.3,mouthPressRight:.3,mouthRollLower:.1},teethMix:{mouthPucker:1,mouthShrugUpper:1,mouthDimpleLeft:1,mouthDimpleRight:1,mouthStretchLeft:.5,mouthStretchRight:.5,mouthPressLeft:.3,mouthPressRight:.3,mouthRollLower:.1}},{key:"viseme_DD",mix:{mouthShrugUpper:.25,mouthShrugLower:.25,mouthPressLeft:.4,mouthPressRight:.4,mouthFunnel:.7,jawOpen:.1},teethMix:{mouthShrugUpper:.25,mouthShrugLower:.25,mouthPressLeft:.4,mouthPressRight:.4,mouthFunnel:.7,jawOpen:.1}},{key:"viseme_SS",mix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.3,mouthLowerDownRight:.3,jawOpen:.1},teethMix:{mouthPressLeft:.8,mouthPressRight:.8,mouthLowerDownLeft:.3,mouthLowerDownRight:.3,jawOpen:.1}},{key:"viseme_TH",mix:{mouthStretchLeft:.4,mouthStretchRight:.4,mouthDimpleLeft:1,mouthDimpleRight:1,mouthFunnel:.4,jawOpen:.15,mouthShrugLower:.45,mouthShrugUpper:.45},teethMix:{mouthStretchLeft:.4,mouthStretchRight:.4,mouthDimpleLeft:1,mouthDimpleRight:1,mouthFunnel:.4,jawOpen:.15,mouthShrugLower:.45,mouthShrugUpper:.45}},{key:"viseme_CH",mix:{mouthPucker:.8,mouthShrugLower:.7,mouthShrugUpper:.2,mouthLowerDownLeft:.6,mouthLowerDownRight:.6,mouthDimpleLeft:.5,mouthDimpleRight:.5,mouthUpperUpLeft:.8,mouthUpperUpRight:.8,jawOpen:.2},teethMix:{mouthPucker:.8,mouthShrugLower:.7,mouthShrugUpper:.2,mouthLowerDownLeft:.6,mouthLowerDownRight:.6,mouthDimpleLeft:.5,mouthDimpleRight:.5,mouthUpperUpLeft:.8,mouthUpperUpRight:.8,jawOpen:.2}},{key:"viseme_RR",mix:{mouthPucker:.4,jawOpen:.2,mouthShrugUpper:.5,mouthFunnel:.15,mouthDimpleLeft:.5,mouthDimpleRight:.5},teethMix:{mouthPucker:.4,jawOpen:.2,mouthShrugUpper:.5,mouthFunnel:.15,mouthDimpleLeft:.5,mouthDimpleRight:.5}},{key:"viseme_kk",mix:{mouthPucker:.5,jawOpen:.2,mouthShrugUpper:.5,mouthFunnel:.2,mouthDimpleLeft:.5,mouthDimpleRight:.5},teethMix:{mouthPucker:.5,jawOpen:.2,mouthShrugUpper:.5,mouthFunnel:.2,mouthDimpleLeft:.5,mouthDimpleRight:.5}},{key:"viseme_nn",mix:{mouthPucker:.6,jawOpen:.2,mouthShrugUpper:.7,mouthShrugLower:.1,mouthFunnel:.1,mouthDimpleLeft:.8,mouthDimpleRight:.8},teethMix:{mouthPucker:.6,jawOpen:.2,mouthShrugUpper:.7,mouthShrugLower:.1,mouthFunnel:.1,mouthDimpleLeft:.8,mouthDimpleRight:.8}},{key:"viseme_sil",mix:{}}],Sn={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}]};function xn(l){if(!l)return[{v:"sil",w:1}];const y=l.toLowerCase();return Sn[y]??[{v:"sil",w:1}]}function vn({target:l}){const{camera:y}=ft.useThree();return t.useEffect(()=>{y.lookAt(...l)},[y,l]),null}function A(l,y,_){if(!l||!l.morphTargetDictionary)return;const g=l,x=g.morphTargetDictionary,W=g.morphTargetInfluences;if(W)for(const M in x)M.toLowerCase()===y.toLowerCase()&&(W[x[M]]=_)}function ht(l,y=.97){if(!l)return;const _=l;if(_.morphTargetInfluences)for(let g=0;g<_.morphTargetInfluences.length;g++)_.morphTargetInfluences[g]*=y}const yn=t.memo(({avatarUrl:l,isPlayingRef:y,visemeQueueRef:_,audioContextRef:g,responseAudioStartTimeRef:x,adjustments:W,mood:M,expression:Oe,agentResponse:re,isSpeaking:k,nextStartTimeRef:be,stopPlayback:z,setIsSpeaking:V,expressionUrl:h,onExpressionFinished:Y,isNudgeResponse:b,avatarGender:X})=>{const{scene:L}=Ze.useGLTF(l),_e=X==="female"?ln:un,ke=Ze.useGLTF(_e),Z=t.useMemo(()=>ke.flatMap(m=>m.animations),[ke]),he=X==="female"?fn:hn,I=Ze.useGLTF(he),$=t.useMemo(()=>I.flatMap(m=>m.animations),[I]),G=t.useRef(null),C=t.useRef(null),P=t.useRef(null),B=t.useRef(null),Ee=t.useRef([]),[F]=t.useState(()=>new He.AnimationMixer(L)),N=t.useRef({}),D=t.useRef(null),we=t.useRef(0),Ce=t.useRef(!1),Se=t.useRef(0),ce=t.useRef(null);t.useEffect(()=>{if(!(!Z||!L)){if(Z.forEach((m,d)=>{const o=`idle_${d}`;if(!N.current[o]){const a=F.clipAction(m,L);a.name=o,a.setLoop(He.LoopOnce,1),a.clampWhenFinished=!0,N.current[o]=a}}),$.forEach((m,d)=>{const o=`talk_${d}`;if(!N.current[o]){const a=F.clipAction(m,L);a.name=o,a.setLoop(He.LoopOnce,1),a.clampWhenFinished=!0,N.current[o]=a}}),Z.length>0){const m=N.current.idle_0,d=D.current&&F.existingAction(D.current.getClip());m&&!d&&(m.reset().fadeIn(.5).play(),D.current=m)}return()=>{F.stopAllAction(),N.current={},D.current=null}}},[Z,$,L,F]);const fe=t.useRef("");t.useEffect(()=>{if(!h||!L||h===fe.current)return;fe.current=h,ce.current=h,new nn.GLTFLoader().load(h,d=>{if(d.animations&&d.animations.length>0){const o=d.animations[0],a=F.clipAction(o,L);if(a.name=`EXPR_${h}`,a.setLoop(He.LoopOnce,1),a.clampWhenFinished=!0,N.current[`EXPR_${h}`]=a,k&&ce.current===h){const f=D.current;a.reset().fadeIn(.3).play(),f&&f!==a&&f.crossFadeTo(a,.3,!0),D.current=a,ce.current=null}}},void 0,d=>{console.error(`[ANIMATION] Failed to load ${h}`,d)})},[h,L,F,k]),t.useEffect(()=>{const m=d=>{const o=d.action,a=o.name||"";if(a.startsWith("idle_")){const T=(parseInt(a.split("_")[1])+1)%Z.length,K=N.current[`idle_${T}`];K&&(K.reset().fadeIn(.5).play(),o.crossFadeTo(K,.5,!0),D.current=K)}else if(a.startsWith("EXPR_")){if(k){const f=Math.floor(Math.random()*$.length),T=N.current[`talk_${f}`];T&&(T.reset().fadeIn(.5).play(),o.crossFadeTo(T,.5,!0),D.current=T)}else{const f=N.current.idle_0;f&&(f.reset().fadeIn(.5).play(),o.crossFadeTo(f,.5,!0),D.current=f)}Y&&Y()}else if(a.startsWith("talk_"))if(k&&!b){const T=(parseInt(a.split("_")[1])+1)%$.length,K=N.current[`talk_${T}`];K&&(K.reset().fadeIn(.3).play(),o.crossFadeTo(K,.3,!0),D.current=K)}else{const f=N.current.idle_0;f&&(f.reset().fadeIn(.5).play(),o.crossFadeTo(f,.5,!0),D.current=f)}};return F.addEventListener("finished",m),()=>F.removeEventListener("finished",m)},[F,Z,$,k,b,Y]),t.useEffect(()=>{if(k&&L){const m=D.current,d=m?.name||"";if(d.startsWith("idle_")||d.startsWith("talk_")||d===""){const o=ce.current;if(o){const a=N.current[`EXPR_${o}`];if(a){a.reset().fadeIn(.3).play(),m&&m!==a&&m.crossFadeTo(a,.3,!0),D.current=a,ce.current=null;return}}if(d.startsWith("idle_")||d===""){const a=Math.floor(Math.random()*$.length),f=N.current[`talk_${a}`];f&&(f.reset().fadeIn(.5).play(),m&&m.crossFadeTo(f,.5,!0),D.current=f)}}}else if(!k&&L){const m=D.current,d=m?.name||"";if(d.startsWith("talk_")||d.startsWith("EXPR_")){const o=N.current.idle_0;o&&(o.reset().fadeIn(.5).play(),m&&m.crossFadeTo(o,.5,!0),D.current=o)}}},[k,L,h]),t.useEffect(()=>{if(!L)return;L.traverse(o=>{if(o.isMesh&&o.morphTargetDictionary){const a=o.name.toLowerCase();(a.includes("head")||a.includes("avatar"))&&(C.current=o,j(`[ANIMATION] Found head mesh: ${o.name}`)),a.includes("teeth")&&(P.current=o,j(`[ANIMATION] Found teeth mesh: ${o.name}`)),a.includes("beard")&&(B.current=o,j(`[ANIMATION] Found beard mesh: ${o.name}`))}});const m=C.current?.morphTargetDictionary;m&&Object.keys(m).filter(o=>o.toLowerCase().includes("brow"));const d=[];L.traverse(o=>{if(o.isMesh){const f=o.morphTargetDictionary;f&&Object.keys(f).some(T=>T.toLowerCase().includes("brow"))&&d.push(o)}}),Ee.current=d,d.length>0&&j("[ANIMATION] Meshes with brow morphs:",d.length)},[L]);const Pe=(m,d=1)=>{const o=`viseme_${m}`.toLowerCase(),a=wn.find(f=>f.key.toLowerCase()===o);if(a){for(const f in a.mix){const T=a.mix[f]*d;A(C.current,f,T),A(B.current,f,T),(!a.teethMix||!(f in a.teethMix))&&A(P.current,f,T)}if(a.teethMix)for(const f in a.teethMix){const T=a.teethMix[f]*d;A(P.current,f,T)}}},xe=m=>{const d=Xe[m]??Xe.neutral;for(const o in d)A(C.current,o,d[o]),A(P.current,o,d[o]),A(B.current,o,d[o])};return ft.useFrame((m,d)=>{const o=Math.pow(.88,60*d);ht(C.current,o),ht(P.current,o),ht(B.current,o),xe(M);const a=m.clock.elapsedTime;let f=0;if(Math.floor(a)%5===0&&Math.floor((a-d)%5)!==0){let H=null;L.traverse(J=>{J.name.toLowerCase().includes("hips")&&(H=J)});const ye=H?`Hips Y: ${H.position.y.toFixed(4)}`:"Hips not found";j(`[ANIMATION] Mixer Time: ${F.time.toFixed(2)}, ${ye}`)}if(F.update(d),a>we.current&&!Ce.current&&(Ce.current=!0,Se.current=a),Ce.current){const H=k?.2:.3,ye=(a-Se.current)/H;if(ye>=1){Ce.current=!1;const J=k?1:2.5;we.current=a+J}else{const J=ye<.5?ye*2:(1-ye)*2;A(C.current,"eyeBlinkLeft",J),A(C.current,"eyeBlinkRight",J),A(P.current,"eyeBlinkLeft",J),A(P.current,"eyeBlinkRight",J),A(B.current,"eyeBlinkLeft",J),A(B.current,"eyeBlinkRight",J),f=J*bn.browInnerUp}}const T=Xe[M]??Xe.neutral,K=T.browInnerUp??0,et=T.browOuterUpLeft??0,Je=T.browOuterUpRight??0,Be=a*_n,Te=dt*Math.sin(Be),ee=dt*.7*Math.sin(Be+.7),Ge=dt*.7*Math.sin(Be+1.3),se=H=>Math.max(0,Math.min(1,H)),Ae=se(K+Te),ve=se(et+ee),Fe=se(Je+Ge),Me=se(Ae+f);if(A(C.current,"browInnerUp",Me),A(P.current,"browInnerUp",Me),A(B.current,"browInnerUp",Me),A(C.current,"browOuterUpLeft",ve),A(P.current,"browOuterUpLeft",ve),A(B.current,"browOuterUpLeft",ve),A(C.current,"browOuterUpRight",Fe),A(P.current,"browOuterUpRight",Fe),A(B.current,"browOuterUpRight",Fe),G.current){const H=y.current?0:W.rotation[1];G.current.rotation.y=He.MathUtils.lerp(G.current.rotation.y,H,.1),G.current.position.set(...W.position),G.current.scale.setScalar(W.scale),G.current.rotation.x=W.rotation[0],G.current.rotation.z=W.rotation[2]}if(y.current&&g.current){const H=g.current.currentTime,Ne=(H-x.current)*1e3- -150;for(let te=0;te<_.current.length;te++){const ie=_.current[te];Ne>=ie.vtime&&Ne<ie.vtime+ie.vduration&&Pe(ie.viseme,ie.weight??1)}H>be.current+.5&&(z(),V(!1))}}),c.jsx("group",{ref:G,children:c.jsx("primitive",{object:L})})});function Rn(l){return l?l.charAt(0).toUpperCase()+l.slice(1).toLowerCase():""}function Nt(l){return l.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const Ln=({token:l,agentToken:y,onNavigationRequested:_,avatarGender:g,presetUserDetails:x,onAvatarReady:W}={})=>{const M=l??y??"",Oe=cn(M||void 0),[re,k]=t.useState(""),[be,z]=t.useState(""),[V,h]=t.useState("Ready"),[Y,b]=t.useState(!1),[X,L]=t.useState(!1),[_e,ke]=t.useState([]),[Z,he]=t.useState(""),I=t.useRef(null),[$,G]=t.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);t.useEffect(()=>{const e=window.matchMedia("(max-width: 480px)"),n=()=>G(e.matches);return e.addEventListener("change",n),()=>e.removeEventListener("change",n)},[]);const C=$?80:600,P=t.useRef(!1),B=t.useRef([]),Ee=t.useRef(0),F=t.useRef(!1),N=t.useRef([]),D=t.useRef(null),we=t.useRef([]);t.useRef([]);const Ce=t.useRef([]),Se=t.useRef(0),ce=t.useRef(0),fe=t.useRef(0),Pe=t.useRef(0),xe=t.useRef(!1),[m,d]=t.useState(null),o=t.useRef(null),[a,f]=t.useState("neutral"),[T,K]=t.useState(""),[et,Je]=t.useState(""),[Be,Te]=t.useState("Chat with us"),[ee,Ge]=t.useState(null),[se,Ae]=t.useState("hidden"),[ve,Fe]=t.useState(""),Me=t.useRef(null),H=t.useRef(se);H.current=se;const[ye,J]=t.useState(null),Ne=t.useRef(null),te=t.useRef(null),[ie,mt]=t.useState(!1),pt=t.useRef(null),[ue,ze]=t.useState("hidden"),[gt,Ut]=t.useState(""),tt=t.useRef(ue);tt.current=ue;const ne=t.useRef(""),me=t.useRef(!1),pe=t.useRef(""),bt=t.useRef(Date.now()),nt=t.useRef([]),We=t.useRef(!1),[rt,Ve]=t.useState(!1),[_t,wt]=t.useState(!1),Re=t.useRef(null),Ue=t.useMemo(()=>ie?"Try again":V==="Busy"?"Busy":V==="Thinking..."||V==="Processing Voice..."?V:ee!=null&&ee!==""&&ee!=="none"&&ee!=="<none>"?`Enter ${Rn(ee)}`:ue!=="hidden"||!_t?null:Ft,[V,ee,ie,ue,_t]),St=!ie&&V!=="Busy"&&V!=="Thinking..."&&V!=="Processing Voice..."&&(ee==null||ee===""||ee==="none"||ee==="<none>");t.useEffect(()=>{if(ue!=="hidden"||!St){wt(!1),Re.current!=null&&(clearTimeout(Re.current),Re.current=null);return}return Re.current=setTimeout(()=>{Re.current=null,wt(!0)},400),()=>{Re.current!=null&&(clearTimeout(Re.current),Re.current=null)}},[ue,St]);const Ye=Ue!=null&&Ue!=="";t.useEffect(()=>{const e=H.current;if(!(e==="exiting"||e==="entering")){if(e==="hidden"){Ye&&(Fe(Ue??""),Ae("entering"));return}e==="visible"&&(!Ye||Ue!==ve)&&(Me.current=Ye?Ue:null,Ae("exiting"))}},[Ye,Ue,se,ve]),t.useEffect(()=>{if(V!=="Busy"){te.current!=null&&(clearTimeout(te.current),te.current=null);return}return te.current=setTimeout(()=>{te.current=null,h("Ready"),mt(!0)},12e3),()=>{te.current!=null&&(clearTimeout(te.current),te.current=null)}},[V]),t.useEffect(()=>{if(!ie)return;const e=setTimeout(()=>mt(!1),2500);return()=>clearTimeout(e)},[ie]);const jt=t.useCallback(()=>{const e=H.current;if(e==="exiting"){Ae("hidden");const n=Me.current;Me.current=null,n!=null&&n!==""&&(Fe(n),Ae("entering"))}else e==="entering"&&Ae("visible")},[]),Pt=e=>{if(!e)return;if(e.mood!=null){const s=String(e.mood).toLowerCase();f(s)}if(e.expression!=null){const s=String(e.expression).trim();K(s);const u=dn.find(p=>p.name.toLowerCase()===s.toLowerCase());j(`[STREAM] Animation match for "${s}": ${u?u.name:"NONE"}`),Je(u?.url??"")}if(e.navigation!=null){const s=String(e.navigation).trim();s!==""&&(_?_(s):window.open(s,"_blank"))}const n=e.ask_for||e.lead_capture?.ask_for,r=n?String(n).trim().toLowerCase():"",i=r==="none"||r==="<none>";if(n&&!i){const s=r;if(x&&(s==="email"&&x.email||s==="name"&&x.name||s==="phone"&&x.phone))return;Ge(s||null),Te(s==="email"?"Enter your email":s==="name"?"Enter your name":s==="phone"?"Enter your phone number":"Chat with us")}else(i||e.ask_for===null||e.lead_capture&&e.lead_capture.ask_for===null||e.ask_for==="none")&&(Ge(null),Be!=="Chat with us"&&Te("Chat with us"));e.collected,e.valid},Bt=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(":"),i=r[0].trim().toLowerCase(),s=r.slice(1).join(":").trim();return{[i]:s}}return null},Wt=t.useCallback(()=>{},[]),Le="§",st=()=>{for(;ne.current.includes(`
2
+ `);){const e=ne.current.indexOf(`
3
+ `),n=ne.current.slice(0,e).trim();ne.current=ne.current.slice(e+1);const r=Bt(n);r&&Pt(r)}},xt=e=>{if(me.current)if(e.includes(Le)){const n=e.indexOf(Le),r=e.slice(0,n),i=e.slice(n+Le.length);r&&(pe.current+=r,z(s=>s+r)),me.current=!1,i&&(ne.current+=i,st())}else e===Le?me.current=!1:(pe.current+=e,z(n=>n+e));else if(e.includes(Le)){const n=e.indexOf(Le),r=e.slice(0,n),i=e.slice(n+Le.length);ne.current+=r,st(),me.current=!0,i&&(pe.current+=i,z(s=>s+i))}else if(e===Le){me.current=!0;return}else ne.current+=e,st()};t.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const s="secret",u=Math.floor(Date.now()/1e3).toString();try{const p=new TextEncoder,w=await crypto.subtle.importKey("raw",p.encode(s),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),v=await crypto.subtle.sign("HMAC",w,p.encode(u)),S=Array.from(new Uint8Array(v)).map(E=>E.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",S),j("[SESSION] New HMAC UID generated and saved:",S)}catch(p){console.error("[SESSION] HMAC generation failed:",p);const w=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",w)}}const r=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let i=[];if(r)try{i=JSON.parse(r)}catch{i=[]}i.length===0&&x&&(x.name||x.email)?(i=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${x.name||""}" , Email is "${x.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(i))):r||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[x]),t.useEffect(()=>{const e=()=>{bt.current=Date.now(),We.current&&(We.current=!1,Ve(!1),ke([]),he(""),z(""),L(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const n=setInterval(async()=>{if(Date.now()-bt.current>=3e4&&!X&&!Y&&V==="Ready"&&!We.current)if(We.current=!0,nt.current.length>0)Ve(!0),ke(nt.current);else try{const s=`${qe}/nudgeUser`,u={navigationUrl:window.location.href,token:M},p=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});if(p.ok){const v=(await p.json()).nudge_questions;v&&v.length>0&&(j("[NUDGE] Received nudge questions from API:",v),nt.current=v,Ve(!0),ke(v))}}catch(s){console.error("[NUDGE] Error calling /nudgeUser:",s),We.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(n)}},[M,X,Y,V]),t.useEffect(()=>{if(_e.length===0)return;let e=0,n=0,r=!1,i=100;const s=()=>{const u=_e[e];if(r){const p=u.substring(0,n-1);he(p),n--,i=50}else{const p=u.substring(0,n+1);he(p),n++,i=100}!r&&n===u.length?(r=!0,i=3e3):r&&n===0&&(r=!1,e=(e+1)%_e.length,i=500),I.current=setTimeout(s,i)};return s(),()=>{I.current&&clearTimeout(I.current)}},[_e]);const vt=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},Vt=e=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(e))},[it,ot]=t.useState(!1),[yt,at]=t.useState(0),le=t.useRef(null),Ke=t.useRef([]),Rt=t.useRef(0),[Lt,$t]=t.useState(null),[Ht,ct]=t.useState(null),ge=t.useRef(null),Ie=t.useRef(null),$e=t.useCallback((e=!1)=>{e&&(xe.current=!0,b(!1),h("Ready")),N.current=[],B.current=[],F.current=!1,L(!1),Se.current=0,ce.current=0,fe.current=0,we.current.forEach(n=>{try{n.stop()}catch{}}),Ne.current&&(clearTimeout(Ne.current),Ne.current=null),J(null),Je(""),we.current=[]},[]),qt=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),n=window.AudioContext||window.webkitAudioContext,r=new n,i=r.createMediaStreamSource(e),s=r.createAnalyser();s.fftSize=64,i.connect(s),ge.current=r,Ie.current=i,ct(s);const u=new MediaRecorder(e);le.current=u,Ke.current=[],u.ondataavailable=p=>{p.data.size>0&&Ke.current.push(p.data)},u.onstop=async()=>{const p=Date.now()-Rt.current;if(ct(null),Ie.current&&(Ie.current.disconnect(),Ie.current=null),ge.current&&ge.current.state!=="closed"&&(ge.current.close(),ge.current=null),p<1e3){h("Recording too short. Hold or click longer."),b(!1);return}const w=new Blob(Ke.current,{type:"audio/wav"});await Yt(w)},Rt.current=Date.now(),u.start(100),ot(!0),h("Listening...")}catch(e){console.error("Error accessing microphone:",e),h("Mic Access Error")}},Jt=()=>{le.current&&le.current.state!=="inactive"&&(le.current.stop(),le.current.stream.getTracks().forEach(e=>e.stop()),ot(!1))},Gt=()=>{le.current&&le.current.state!=="inactive"&&(le.current.onstop=null,le.current.stop(),le.current.stream.getTracks().forEach(e=>e.stop()),ct(null),Ie.current&&(Ie.current.disconnect(),Ie.current=null),ge.current&&ge.current.state!=="closed"&&(ge.current.close(),ge.current=null),ot(!1),Ke.current=[],h("Ready"))};t.useEffect(()=>{if(!X)return;const e=()=>{const n=fe.current;if(n<=0)return;const r=D.current,i=Se.current;if(!r)return;const s=r.currentTime-i,u=Math.min(Math.max(0,s),n),w=Nt(be).trim().length;if(w<=0)return;const v=Math.min(Math.round(u/n*w),w);d(v)};return clearInterval(o.current??void 0),o.current=setInterval(e,90),()=>clearInterval(o.current??void 0)},[X,be,fe.current]),t.useEffect(()=>{let e;return it?(at(0),e=window.setInterval(()=>{at(n=>n+1)},1e3)):at(0),()=>clearInterval(e)},[it]);const zt=e=>{const n=e.numberOfChannels,r=e.length*n*2+44,i=new ArrayBuffer(r),s=new DataView(i);let u=0;const p=S=>{s.setUint16(u,S,!0),u+=2},w=S=>{s.setUint32(u,S,!0),u+=4};w(1179011410),w(r-8),w(1163280727),w(544501094),w(16),p(1),p(n),w(e.sampleRate),w(e.sampleRate*2*n),p(n*2),p(16),w(1635017060),w(r-u-4);const v=[];for(let S=0;S<n;S++)v.push(e.getChannelData(S));let R=0;for(;u<r;){for(let S=0;S<n;S++){let E=Math.max(-1,Math.min(1,v[S][R]));E=E<0?E*32768:E*32767,s.setInt16(u,E,!0),u+=2}R++}return new Blob([i],{type:"audio/wav"})},ut=async(e,n,r=!1)=>{if(!xe.current){if(P.current){B.current.push({audio:e,visemes:n,isNewSegment:r});return}P.current=!0;try{const i=window.AudioContext||window.webkitAudioContext,s=D.current??new i;s.state==="suspended"&&await s.resume(),D.current=s;const u=window.atob(e),p=new Uint8Array(u.length);for(let U=0;U<u.length;U++)p[U]=u.charCodeAt(U);const w=await s.decodeAudioData(p.buffer.slice(0));fe.current+=w.duration;const v=s.currentTime;let R=ce.current;const S=!F.current;R<v&&(R=v+.1),ce.current=R+w.duration;const E=s.createBufferSource();E.buffer=w;let q=Lt;if((!q||q.context!==s)&&(q=s.createAnalyser(),q.fftSize=64,q.connect(s.destination),$t(q)),E.connect(q),we.current.push(E),xe.current){we.current=we.current.filter(U=>U!==E);return}if(S){F.current=!0,L(!0),j(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${R.toFixed(3)}`),Se.current=R;const U=(R-v)*1e3;Ee.current=performance.now()+U,j(`[AUDIO] Response started. Initial startTime: ${R.toFixed(3)}, CT: ${v.toFixed(3)}`)}E.start(R);const Q=(R-Se.current)*1e3;r&&(Pe.current=Q,j(`[AUDIO] New segment detected at +${Q.toFixed(0)}ms. Resetting segment offset.`)),n.forEach((U,oe)=>{const O=U.symbol??"";if(O){const ae=xn(O),de=Math.round(U.start*1e3),De=Math.round((U.duration??0)*1e3),It=Pe.current+de;oe<3&&j(`[AUDIO] Viseme "${O}": segment_relative=${de}ms, segment_offset=${Pe.current.toFixed(0)}ms => vtime=${It}ms`),ae.forEach(Dt=>{N.current.push({viseme:Dt.v,weight:Dt.w,vtime:It,vduration:De})})}}),h("Speaking...")}finally{if(P.current=!1,B.current.length>0){const i=B.current.shift();i&&ut(i.audio,i.visemes,i.isNewSegment)}}}},Yt=async e=>{try{b(!0),Ve(!1),pe.current="",z(""),h("Processing Voice...");const n=await e.arrayBuffer(),i=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(n),s=zt(i),u=new FileReader;u.readAsDataURL(s),u.onloadend=async()=>{const p=u.result.split(",")[1];$e(),k(""),ne.current="",me.current=!1;const w=`${qe}/stt?token=${encodeURIComponent(M)}`,v=await fetch(w,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:p,audio_format:"wav"})});if(v.status===429){try{const oe=await v.text(),O=JSON.parse(oe);j("[STT] 429 agent at capacity:",O?.detail)}catch{}k(""),h("Busy"),b(!1);return}if(!v.ok){const oe=await v.text();let O="STT Failed";try{O=JSON.parse(oe).error||O}catch{oe&&(O=oe.slice(0,200))}throw new Error(O)}const R=v.body;if(j("this is body"+R),!R){h("STT Failed"),b(!1);return}const S=R.getReader();xe.current=!1;const E=new TextDecoder;let q="",Q=!1;const U=async(oe,O)=>{switch(oe){case"transcript":O.transcript!=null&&k(String(O.transcript));break;case"text":{const ae=O.delta??O.text??"";ae&&xt(ae);break}case"audio":{const ae=O.chunk,de=O.visemes??[],De=!!O.is_new_segment;ae&&await ut(ae,de,De);break}case"done":{Q=!0,h("Ready"),b(!1);break}case"error":{Q=!0,h("STT Failed"),b(!1);break}default:break}};for(;;){const{done:oe,value:O}=await S.read();O&&(q+=E.decode(O,{stream:!0}));const ae=q.split(`
4
4
 
5
- `);q=ae.pop()??"";for(const le of ae){const Ie=ze(le);Ie&&await F(Ie.event,Ie.data)}if(ie){if(q.trim()){const le=ze(q.trim());le&&await F(le.event,le.data)}X||(v("Ready"),E(!1));break}}}}catch(n){console.error("Audio Submission Error:",n),v("STT Failed"),E(!1)}},qt=async e=>{e&&e.preventDefault(),Be(!1),ve.current="",te(""),!(!de||y)&&await Jt(de)},ze=e=>{const n=e.split(/\r?\n/);let s="",i="";for(const l of n)l.startsWith("event:")?s=l.slice(6).trim():l.startsWith("data:")&&(i=l.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}},yt=(e,n)=>{switch(e){case"connected":se.current="",Se.current=!1;break;case"text":{const s=n.delta??"";s&&_t(s);break}case"audio":{const s=n.chunk,i=n.visemes??[];s&&at(s,i);break}case"done":{const s=wt(),i=ve.current.trim(),r=[...s,{role:"user",content:de||"..."},{role:"assistant",content:i}];jt(r),Me.current=[...R.current],v("Ready"),E(!1),Y("");break}case"error":{const s=n.message??"Unknown error";ve.current=s,te(s),v("Agent Failed"),E(!1);break}}},Jt=async e=>{E(!0),v("Thinking..."),ve.current="",se.current="",Se.current=!1,Ge(),_e.current=0,d(0);const n=`${ct}/agent/chat?token=${encodeURIComponent(C)}`;try{const s=wt();let i=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");i||(Xt("[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};W("[CHAT] Sending payload:",r);const l=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),cache:"default"});if(l.status===429){try{const T=await l.json();W("[CHAT] 429 agent at capacity:",T?.detail)}catch{}Y(""),v("Busy"),E(!1);return}if(!l.ok)throw new Error("Agent request failed");const p=l.body;if(!p){v("Agent Failed"),E(!1);return}const b=p.getReader();ke.current=!1;const S=new TextDecoder;let k="";for(;;){const{done:T,value:B}=await b.read();W(`[SSE] Chunk received. done=${T}, length=${B?.length||0}`),B&&(k+=S.decode(B,{stream:!0}));const q=k.split(`
5
+ `);q=ae.pop()??"";for(const de of ae){const De=je(de);De&&await U(De.event,De.data)}if(oe){if(q.trim()){const de=je(q.trim());de&&await U(de.event,de.data)}Q||(h("Ready"),b(!1));break}}}}catch(n){console.error("Audio Submission Error:",n),h("STT Failed"),b(!1)}},Kt=async e=>{e&&e.preventDefault(),Ve(!1),pe.current="",z(""),!(!re||Y)&&await Qt(re)},je=e=>{const n=e.split(/\r?\n/);let r="",i="";for(const u of n)u.startsWith("event:")?r=u.slice(6).trim():u.startsWith("data:")&&(i=u.slice(5).trim());if(!r)return null;let s={};if(i)try{s=JSON.parse(i)}catch{s={raw:i}}return{event:r,data:s}},Qe=(e,n)=>{switch(e){case"connected":ne.current="",me.current=!1;break;case"text":{const r=n.delta??"";r&&xt(r);break}case"audio":{const r=n.chunk,i=n.visemes??[];r&&ut(r,i);break}case"done":{const r=vt(),i=pe.current.trim(),s=[...r,{role:"user",content:re||"..."},{role:"assistant",content:i}];Vt(s),Ce.current=[...N.current],h("Ready"),b(!1),k("");break}case"error":{const r=n.message??"Unknown error";pe.current=r,z(r),h("Agent Failed"),b(!1);break}}},kt=async(e,n)=>{b(!0),h("Thinking..."),pe.current="",ne.current="",me.current=!1,$e(),fe.current=0,d(0);try{const r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(r.status===429){h("Busy"),b(!1);return}if(!r.ok)throw new Error("Request failed");const i=r.body;if(!i){h("Failed"),b(!1);return}const s=i.getReader();xe.current=!1;const u=new TextDecoder;let p="";for(;;){const{done:w,value:v}=await s.read();v&&(p+=u.decode(v,{stream:!0}));const R=p.split(`
6
6
 
7
- `);k=q.pop()??"";for(const X of q){W(`[SSE] Processing block: ${X.slice(0,50)}...`);const F=ze(X);F&&(W(`[SSE] Event: ${F.event}`),yt(F.event,F.data))}if(T){if(W("[SSE] Stream finished"),k.trim()){const X=ze(k.trim());X&&yt(X.event,X.data)}v("Ready"),E(!1),Y("");break}}}catch(s){console.error("Chat Error:",s),v("Agent Failed"),E(!1)}},Gt=D.trim(),Rt=Mt(Gt),ot=Rt&&N?Rt.slice(0,f!=null&&f>0?f:0):"";t.useEffect(()=>{const e=Xe.current;e!=="exiting"&&(ot?(Ot(ot),e==="hidden"&&He("entering")):(e==="visible"||e==="entering")&&He("exiting"))},[ot,ce]);const zt=t.useCallback(()=>{const e=Xe.current;e==="entering"?He("visible"):e==="exiting"&&He("hidden")},[]);return t.useLayoutEffect(()=>{const e=ft.current;e&&(e.scrollTop=e.scrollHeight)},[ht]),a.jsxs("div",{className:"avatar-widget-container",children:[a.jsxs("div",{className:"avatar-input-area",children:[ne!=="hidden"?a.jsx("div",{className:`avatar-thinking-tab${ne==="exiting"?" avatar-thinking-tab--exiting":ne==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:Ct,children:Ae===Lt?a.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):Ae}):null,a.jsx("div",{className:"avatar-input-container",children:a.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:nt?a.jsxs("div",{className:"avatar-input-recording",children:[a.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:Vt,title:"Cancel",children:a.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:[a.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),a.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),a.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[a.jsx("div",{style:{flex:1,height:"100%"},children:a.jsx(Et,{analyser:Pt})}),a.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(St/60),":",String(St%60).padStart(2,"0")]})]}),a.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:Wt,title:"Send",children:a.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:a.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):N&&!et?a.jsxs("div",{className:"avatar-input-speaking",children:[a.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:a.jsx(Et,{analyser:xt})}),a.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>Ge(!0),title:"Stop",children:a.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):y?a.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx("div",{className:"avatar-input-loader"})}):a.jsxs("form",{onSubmit:qt,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[a.jsx("input",{id:"avatar-text-input",type:"text",value:de,onChange:e=>Y(e.target.value),placeholder:A==="Busy"?"Assisting another user":Fe||"Ask me anything",disabled:y||A==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),A==="Busy"?a.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:a.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:a.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):de.trim()===""?a.jsx("button",{type:"button",className:"mic-button",onClick:Bt,disabled:y,style:{backgroundColor:"#1e4a5e"},children:a.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[a.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"}),a.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"})]})}):a.jsx("button",{type:"submit",className:"mic-button",disabled:y,style:{backgroundColor:"#1e4a5e"},title:"Send",children:a.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:a.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),a.jsx("div",{className:"avatar-wrapper",children:a.jsxs("div",{className:"avatar-scene-wrapper",children:[ce!=="hidden"&&a.jsx("div",{className:`avatar-bubble${ce==="entering"?" avatar-bubble--entering":ce==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:zt,children:a.jsx("div",{ref:ft,className:`avatar-bubble__content${et?" avatar-bubble__content--nudge":""}`,children:ht})}),a.jsx("div",{className:"avatar-canvas-layer",style:{width:J,height:J},children:a.jsxs(lt.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:[a.jsx(pn,{target:un}),a.jsx("ambientLight",{intensity:.7}),a.jsx("directionalLight",{position:[0,2,2],intensity:1}),a.jsx(Qe.Environment,{preset:"city"}),a.jsx(t.Suspense,{fallback:null,children:V!==null&&a.jsx(gn,{avatarUrl:V,isPlayingRef:I,visemeQueueRef:R,audioContextRef:M,responseAudioStartTimeRef:be,adjustments:cn,mood:c,expression:P,agentResponse:D,isSpeaking:N,nextStartTimeRef:oe,stopPlayback:Ge,setIsSpeaking:fe,expressionUrl:Ke,onExpressionFinished:Nt,isNudgeResponse:et,avatarGender:m})})]})})]})})]})},wn=({token:u,avatarGender:_,onNavigationRequested:g,presetUserDetails:m})=>a.jsx(_n,{token:u,onNavigationRequested:g,avatarGender:_,presetUserDetails:m});exports.AvatarWidget=wn;
7
+ `);p=R.pop()??"";for(const S of R){const E=je(S);E&&Qe(E.event,E.data)}if(w){if(p.trim()){const S=je(p.trim());S&&Qe(S.event,S.data)}h("Ready"),b(!1);break}}}catch(r){console.error("Streaming Error:",r),h("Failed"),b(!1)}},Et=t.useCallback(async(e,n,r)=>{const i=`${qe}/avatar_tts`;await kt(i,{text:e,userQuery:n,llmPrompt:r})},[]),Tt=t.useCallback(async(e,n,r,i)=>{const s=`${qe}/avatar_ttsWithKnowledge`;await kt(s,{userQuery:e,llmPrompt:n,knowledge:r,history:i})},[]),At=t.useRef(!1);t.useEffect(()=>{W&&!At.current&&(W({avatarSpeak:Et,avatarRespond:Tt}),At.current=!0)},[W,Et,Tt]);const Qt=async e=>{b(!0),h("Thinking..."),pe.current="",ne.current="",me.current=!1,$e(),fe.current=0,d(0);const n=`${qe}/agent/chat?token=${encodeURIComponent(M)}`;try{const r=vt();let i=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");i||(sn("[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 s={history:r,question:e,lead_id:i};j("[CHAT] Sending payload:",s);const u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s),cache:"default"});if(u.status===429){try{const S=await u.json();j("[CHAT] 429 agent at capacity:",S?.detail)}catch{}k(""),h("Busy"),b(!1);return}if(!u.ok)throw new Error("Agent request failed");const p=u.body;if(!p){h("Agent Failed"),b(!1);return}const w=p.getReader();xe.current=!1;const v=new TextDecoder;let R="";for(;;){const{done:S,value:E}=await w.read();j(`[SSE] Chunk received. done=${S}, length=${E?.length||0}`),E&&(R+=v.decode(E,{stream:!0}));const q=R.split(`
8
+
9
+ `);R=q.pop()??"";for(const Q of q){j(`[SSE] Processing block: ${Q.slice(0,50)}...`);const U=je(Q);U&&(j(`[SSE] Event: ${U.event}`),Qe(U.event,U.data))}if(S){if(j("[SSE] Stream finished"),R.trim()){const Q=je(R.trim());Q&&Qe(Q.event,Q.data)}h("Ready"),b(!1),k("");break}}}catch(r){console.error("Chat Error:",r),h("Agent Failed"),b(!1)}},Xt=be.trim(),Mt=Nt(Xt),lt=Mt&&X?Mt.slice(0,m!=null&&m>0?m:0):"";t.useEffect(()=>{const e=tt.current;e!=="exiting"&&(lt?(Ut(lt),e==="hidden"&&ze("entering")):(e==="visible"||e==="entering")&&ze("exiting"))},[lt,ue]);const Zt=t.useCallback(()=>{const e=tt.current;e==="entering"?ze("visible"):e==="exiting"&&ze("hidden")},[]);t.useLayoutEffect(()=>{const e=pt.current;e&&(e.scrollTop=e.scrollHeight)},[gt]);const en=g==="female"?gn:pn;return c.jsxs("div",{className:"avatar-widget-container",children:[c.jsxs("div",{className:"avatar-input-area",children:[se!=="hidden"?c.jsx("div",{className:`avatar-thinking-tab${se==="exiting"?" avatar-thinking-tab--exiting":se==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:jt,children:ve===Ft?c.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):ve}):null,c.jsx("div",{className:"avatar-input-container",children:c.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:it?c.jsxs("div",{className:"avatar-input-recording",children:[c.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:Gt,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(Ot,{analyser:Ht})}),c.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(yt/60),":",String(yt%60).padStart(2,"0")]})]}),c.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:Jt,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"})})})]}):X&&!rt?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(Ot,{analyser:Lt})}),c.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>$e(!0),title:"Stop",children:c.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):Y?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:Kt,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[c.jsx("input",{id:"avatar-text-input",type:"text",value:re,onChange:e=>k(e.target.value),placeholder:V==="Busy"?"Assisting another user":Z||"Ask me anything",disabled:Y||V==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),V==="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"})})}):re.trim()===""?c.jsx("button",{type:"button",className:"mic-button",onClick:qt,disabled:Y,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:Y,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:[ue!=="hidden"&&c.jsx("div",{className:`avatar-bubble${ue==="entering"?" avatar-bubble--entering":ue==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:Zt,children:c.jsx("div",{ref:pt,className:`avatar-bubble__content${rt?" avatar-bubble__content--nudge":""}`,children:gt})}),c.jsx("div",{className:"avatar-canvas-layer",style:{width:C,height:C},children:c.jsxs(ft.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(vn,{target:en}),c.jsx("ambientLight",{intensity:.7}),c.jsx("directionalLight",{position:[0,2,2],intensity:1}),c.jsx(Ze.Environment,{preset:"city"}),c.jsx(t.Suspense,{fallback:null,children:Oe!==null&&c.jsx(yn,{avatarUrl:Oe,isPlayingRef:F,visemeQueueRef:N,audioContextRef:D,responseAudioStartTimeRef:Se,adjustments:mn,mood:a,expression:T,agentResponse:be,isSpeaking:X,nextStartTimeRef:ce,stopPlayback:$e,setIsSpeaking:L,expressionUrl:et,onExpressionFinished:Wt,isNudgeResponse:rt,avatarGender:g})})]})})]})})]})},kn=({token:l,avatarGender:y,onNavigationRequested:_,presetUserDetails:g,onAvatarReady:x})=>c.jsx(Ln,{token:l,onNavigationRequested:_,avatarGender:y,presetUserDetails:g,onAvatarReady:x});exports.AvatarWidget=kn;