@streamoji/avatar-widget 0.5.0 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -23,7 +23,7 @@ import "@streamoji/avatar-widget/styles.css";
|
|
|
23
23
|
function App() {
|
|
24
24
|
return (
|
|
25
25
|
<AvatarWidget
|
|
26
|
-
|
|
26
|
+
agentId="YOUR_AGENT_ID"
|
|
27
27
|
onNavigationRequested={(url) => window.open(url, "_blank")}
|
|
28
28
|
/>
|
|
29
29
|
);
|
|
@@ -41,8 +41,7 @@ function App() {
|
|
|
41
41
|
|
|
42
42
|
return (
|
|
43
43
|
<AvatarWidget
|
|
44
|
-
|
|
45
|
-
avatarGender="female"
|
|
44
|
+
agentId="YOUR_AGENT_ID"
|
|
46
45
|
presetUserDetails={
|
|
47
46
|
user
|
|
48
47
|
? { name: user.displayName, email: user.email, phone: user.phone }
|
|
@@ -77,7 +76,7 @@ For npm installs, the files are in `node_modules/@streamoji/avatar-widget/dist/`
|
|
|
77
76
|
|
|
78
77
|
```html
|
|
79
78
|
<script>
|
|
80
|
-
StreamojiLeadsAvatarWidget.init({
|
|
79
|
+
StreamojiLeadsAvatarWidget.init({ agentId: "YOUR_AGENT_ID" });
|
|
81
80
|
</script>
|
|
82
81
|
```
|
|
83
82
|
|
|
@@ -86,21 +85,23 @@ If you don’t add a container, the widget creates one fixed at the bottom-right
|
|
|
86
85
|
```html
|
|
87
86
|
<div id="streamoji-leads-avatar-widget-root"></div>
|
|
88
87
|
<script>
|
|
89
|
-
StreamojiLeadsAvatarWidget.init({
|
|
88
|
+
StreamojiLeadsAvatarWidget.init({ agentId: "YOUR_AGENT_ID" });
|
|
90
89
|
</script>
|
|
91
90
|
```
|
|
92
91
|
|
|
92
|
+
Session UID generation uses the Web Crypto API and requires a [secure context](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API#secure_contexts) (HTTPS or localhost). On plain HTTP, HMAC-based session IDs will not be available.
|
|
93
|
+
|
|
93
94
|
### Web init options
|
|
94
95
|
|
|
95
96
|
| Option | Type | Description |
|
|
96
97
|
|--------|------|-------------|
|
|
97
|
-
| `
|
|
98
|
+
| `agentId` | `string` | Agent ID; widget fetches config (and records visit) and uses it for chat/STT. |
|
|
98
99
|
|
|
99
100
|
## Props (React)
|
|
100
101
|
|
|
101
102
|
| Prop | Type | Description |
|
|
102
103
|
|------|------|-------------|
|
|
103
|
-
| `
|
|
104
|
+
| `agentId` | `string` | Agent ID to fetch config and for chat/STT. |
|
|
104
105
|
| `onNavigationRequested` | `(url: string) => void` | Called when the agent requests a link; if not provided, links open in a new tab. |
|
|
105
106
|
| `avatarGender` | `"male" \| "female"` | Gender of the avatar for idle animations. Defaults to `"male"`. |
|
|
106
107
|
| `presetUserDetails` | `UserDetails \| undefined` | Optional user details (name, email, phone) to identify logged-in users and skip lead capture. |
|
package/dist/avatar-widget.cjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const l=require("react/jsx-runtime"),gt=require("@react-three/drei"),It=require("@react-three/fiber"),t=require("react"),wn=require("three"),Sn=require("three/examples/jsm/loaders/GLTFLoader.js");function yn(f){const w=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(f){for(const b in f)if(b!=="default"){const S=Object.getOwnPropertyDescriptor(f,b);Object.defineProperty(w,b,S.get?S:{enumerable:!0,get:()=>f[b]})}}return w.default=f,Object.freeze(w)}const rt=yn(wn),Xe="https://ai.streamoji.com",U=(...f)=>{},Rn=(...f)=>{},Jt=({analyser:f})=>{const w=t.useRef(null),b=t.useRef(null);return t.useEffect(()=>{const S=w.current;if(!S)return;const V=S.getContext("2d",{alpha:!0});if(!V)return;let Y,X=null;f&&(f.fftSize=128,X=new Uint8Array(f.frequencyBinCount));const ze=()=>{Y=requestAnimationFrame(ze),(S.width!==S.offsetWidth||S.height!==S.offsetHeight)&&(S.width=S.offsetWidth,S.height=S.offsetHeight);const Fe=S.width,C=S.height;if(Fe===0||C===0)return;const Ze=C/2;V.clearRect(0,0,Fe,C),V.fillStyle="#1e293b";const Se=2,$=Se+2,xe=Fe*.95,G=Math.floor(xe/$);(!b.current||b.current.length!==G)&&(b.current=new Float32Array(G).fill(2));const oe=G*$,M=(Fe-oe)/2;f&&X&&f.getByteFrequencyData(X);const le=X?X.length:0,_=Math.floor(le*.7)/G,ne=new Float32Array(G);for(let p=0;p<G;p++){let D=0;if(X&&_>0){const A=Math.floor(p*_),F=Math.floor((p+1)*_);for(let q=A;q<F;q++){const K=X[q]||0;K>D&&(D=K)}}D<10&&(D=0);const J=D/255,E=D>0?Math.max(2,Math.pow(J,1.4)*C*.25):2;ne[p]=E}for(let p=0;p<G;p++){const D=G-1-p,J=Math.max(ne[p],ne[D]),E=b.current[p]+(J-b.current[p])*.3;b.current[p]=E;const A=M+p*$,F=Ze-E/2;V.beginPath(),V.roundRect?V.roundRect(A,F,Se,E,4):V.fillRect(A,F,Se,E),V.fill()}};return ze(),()=>{cancelAnimationFrame(Y)}},[f]),l.jsx("canvas",{ref:w,style:{width:"100%",height:"100%",display:"block"}})},Ln="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",qt="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";function vn(f){const[w,b]=t.useState(null);return t.useEffect(()=>{if(!f){b(null);return}let S=!1;const V=`${Ln}/${f}.glb`;return fetch(V,{method:"HEAD"}).then(Y=>{S||b(Y.ok?V:qt)}).catch(()=>{S||b(qt)}),()=>{S=!0}},[f]),w}const xn=["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],Dn=[-.45,1.75,.1],On={browInnerUp:.2},Et=.18,Cn=1,Un=.5,zt=3,dt=.55,Tt=.12,Yt=2,Kt=2,mt=4,Qt=8,Fn=1,Xt=.38,Zt=.32,en="__branding__",pt={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}},Nn=[{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:{}}],Pn={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 jn(f){if(!f)return[{v:"sil",w:1}];const w=f.toLowerCase();return Pn[w]??[{v:"sil",w:1}]}function Bn({target:f}){const{camera:w}=It.useThree();return t.useEffect(()=>{w.lookAt(...f)},[w,f]),null}function u(f,w,b){if(!f||!f.morphTargetDictionary)return;const S=f,V=S.morphTargetDictionary,Y=S.morphTargetInfluences;if(Y)for(const X in V)X.toLowerCase()===w.toLowerCase()&&(Y[V[X]]=b)}function Mt(f,w=.97){if(!f)return;const b=f;if(b.morphTargetInfluences)for(let S=0;S<b.morphTargetInfluences.length;S++)b.morphTargetInfluences[S]*=w}const Wn=t.memo(({avatarUrl:f,isPlayingRef:w,visemeQueueRef:b,audioContextRef:S,responseAudioStartTimeRef:V,adjustments:Y,mood:X,expression:ze,agentResponse:Fe,isSpeaking:C,nextStartTimeRef:Ze,stopPlayback:Se,setIsSpeaking:Ye,expressionUrl:$,onExpressionFinished:xe,isNudgeResponse:G,avatarGender:oe})=>{const{scene:M}=gt.useGLTF(f),le=oe==="female"?kn:xn,W=gt.useGLTF(le),_=t.useMemo(()=>W.flatMap(g=>g.animations),[W]),ne=oe==="female"?Mn:Tn,p=gt.useGLTF(ne),D=t.useMemo(()=>p.flatMap(g=>g.animations),[p]),J=t.useRef(null),E=t.useRef(null),A=t.useRef(null),F=t.useRef(null),q=t.useRef(null),K=t.useRef(null),bt=t.useRef([]),[Z]=t.useState(()=>new rt.AnimationMixer(M)),H=t.useRef({}),j=t.useRef(null),ke=t.useRef(0),Ke=t.useRef(!1),Ne=t.useRef(0),Ee=t.useRef(!1),ge=t.useRef(null),Te=t.useRef(zt),st=t.useRef(-1),Me=t.useRef("left"),Pe=t.useRef(mt+Math.random()*(Qt-mt)),fe=t.useRef(0),Ae=t.useRef("smile");t.useEffect(()=>{if(!(!_||!M)){if(_.forEach((g,h)=>{const c=`idle_${h}`;if(!H.current[c]){const o=Z.clipAction(g,M);o.name=c,o.setLoop(rt.LoopOnce,1),o.clampWhenFinished=!0,H.current[c]=o}}),D.forEach((g,h)=>{const c=`talk_${h}`;if(!H.current[c]){const o=Z.clipAction(g,M);o.name=c,o.setLoop(rt.LoopOnce,1),o.clampWhenFinished=!0,H.current[c]=o}}),_.length>0){const g=H.current.idle_0,h=j.current&&Z.existingAction(j.current.getClip());g&&!h&&(g.reset().fadeIn(.5).play(),j.current=g)}return()=>{Z.stopAllAction(),H.current={},j.current=null}}},[_,D,M,Z]);const ye=t.useRef("");t.useEffect(()=>{if(!$||!M||$===ye.current)return;ye.current=$,ge.current=$,new Sn.GLTFLoader().load($,h=>{if(h.animations&&h.animations.length>0){const c=h.animations[0],o=Z.clipAction(c,M);if(o.name=`EXPR_${$}`,o.setLoop(rt.LoopOnce,1),o.clampWhenFinished=!0,H.current[`EXPR_${$}`]=o,C&&ge.current===$){const d=j.current;o.reset().fadeIn(.3).play(),d&&d!==o&&d.crossFadeTo(o,.3,!0),j.current=o,ge.current=null}}},void 0,h=>{console.error(`[ANIMATION] Failed to load ${$}`,h)})},[$,M,Z,C]),t.useEffect(()=>{const g=h=>{const c=h.action,o=c.name||"";if(o.startsWith("idle_")){const I=(parseInt(o.split("_")[1])+1)%_.length,ee=H.current[`idle_${I}`];ee&&(ee.reset().fadeIn(.5).play(),c.crossFadeTo(ee,.5,!0),j.current=ee)}else if(o.startsWith("EXPR_")){if(C){const d=Math.floor(Math.random()*D.length),I=H.current[`talk_${d}`];I&&(I.reset().fadeIn(.5).play(),c.crossFadeTo(I,.5,!0),j.current=I)}else{const d=H.current.idle_0;d&&(d.reset().fadeIn(.5).play(),c.crossFadeTo(d,.5,!0),j.current=d)}xe&&xe()}else if(o.startsWith("talk_"))if(C&&!G){const I=(parseInt(o.split("_")[1])+1)%D.length,ee=H.current[`talk_${I}`];ee&&(ee.reset().fadeIn(.3).play(),c.crossFadeTo(ee,.3,!0),j.current=ee)}else{const d=H.current.idle_0;d&&(d.reset().fadeIn(.5).play(),c.crossFadeTo(d,.5,!0),j.current=d)}};return Z.addEventListener("finished",g),()=>Z.removeEventListener("finished",g)},[Z,_,D,C,G,xe]),t.useEffect(()=>{if(C&&M){const g=j.current,h=g?.name||"";if(h.startsWith("idle_")||h.startsWith("talk_")||h===""){const c=ge.current;if(c){const o=H.current[`EXPR_${c}`];if(o){o.reset().fadeIn(.3).play(),g&&g!==o&&g.crossFadeTo(o,.3,!0),j.current=o,ge.current=null;return}}if(h.startsWith("idle_")||h===""){const o=Math.floor(Math.random()*D.length),d=H.current[`talk_${o}`];d&&(d.reset().fadeIn(.5).play(),g&&g.crossFadeTo(d,.5,!0),j.current=d)}}}else if(!C&&M){const g=j.current,h=g?.name||"";if(h.startsWith("talk_")||h.startsWith("EXPR_")){const c=H.current.idle_0;c&&(c.reset().fadeIn(.5).play(),g&&g.crossFadeTo(c,.5,!0),j.current=c)}}},[C,M,$]),t.useEffect(()=>{if(!M)return;M.traverse(c=>{if(c.isMesh&&c.morphTargetDictionary){const o=c.name.toLowerCase();(o.includes("head")||o.includes("avatar"))&&(E.current=c,U(`[ANIMATION] Found head mesh: ${c.name}`)),o.includes("teeth")&&(A.current=c,U(`[ANIMATION] Found teeth mesh: ${c.name}`)),o.includes("beard")&&(F.current=c,U(`[ANIMATION] Found beard mesh: ${c.name}`)),o.includes("eyeleft")&&(q.current=c,U(`[ANIMATION] Found eye left mesh: ${c.name}`)),o.includes("eyeright")&&(K.current=c,U(`[ANIMATION] Found eye right mesh: ${c.name}`))}});const g=E.current?.morphTargetDictionary;g&&Object.keys(g).filter(c=>c.toLowerCase().includes("brow"));const h=[];M.traverse(c=>{if(c.isMesh){const d=c.morphTargetDictionary;d&&Object.keys(d).some(I=>I.toLowerCase().includes("brow"))&&h.push(c)}}),bt.current=h,h.length>0&&U("[ANIMATION] Meshes with brow morphs:",h.length)},[M]);const et=(g,h=1)=>{const c=`viseme_${g}`.toLowerCase(),o=Nn.find(d=>d.key.toLowerCase()===c);if(o){for(const d in o.mix){const I=o.mix[d]*h;u(E.current,d,I),u(F.current,d,I),(!o.teethMix||!(d in o.teethMix))&&u(A.current,d,I)}if(o.teethMix)for(const d in o.teethMix){const I=o.teethMix[d]*h;u(A.current,d,I)}}},tt=g=>{const h=pt[g]??pt.neutral;for(const c in h)u(E.current,c,h[c]),u(A.current,c,h[c]),u(F.current,c,h[c])};return It.useFrame((g,h)=>{const c=Math.pow(.88,60*h);Mt(E.current,c),Mt(A.current,c),Mt(F.current,c),tt(X);const o=g.clock.elapsedTime;let d=0;if(Math.floor(o)%5===0&&Math.floor((o-h)%5)!==0){let y=null;M.traverse(N=>{N.name.toLowerCase().includes("hips")&&(y=N)});const z=y?`Hips Y: ${y.position.y.toFixed(4)}`:"Hips not found";U(`[ANIMATION] Mixer Time: ${Z.time.toFixed(2)}, ${z}`)}if(Z.update(h),o>ke.current&&!Ke.current&&(Ke.current=!0,Ne.current=o),Ke.current){const y=C?.2:.3,z=(o-Ne.current)/y;if(z>=1)if(Ke.current=!1,Ee.current){const N=C?1:2.5;ke.current=o+N,Ee.current=!1}else ke.current=o+.12,Ee.current=!0;else{const N=z<.5?z*2:(1-z)*2;u(E.current,"eyeBlinkLeft",N),u(E.current,"eyeBlinkRight",N),u(A.current,"eyeBlinkLeft",N),u(A.current,"eyeBlinkRight",N),u(F.current,"eyeBlinkLeft",N),u(F.current,"eyeBlinkRight",N),d=N*On.browInnerUp}}const I=pt[X]??pt.neutral,ee=I.browInnerUp??0,_t=I.browOuterUpLeft??0,je=I.browOuterUpRight??0,te=o*Cn,ot=Et*Math.sin(te),Ie=Et*.7*Math.sin(te+.7),Be=Et*.7*Math.sin(te+1.3),v=y=>Math.max(0,Math.min(1,y)),it=v(ee+ot),We=v(_t+Ie),Ve=v(je+Be),at=v(it+d);u(E.current,"browInnerUp",at),u(A.current,"browInnerUp",at),u(F.current,"browInnerUp",at),u(E.current,"browOuterUpLeft",We),u(A.current,"browOuterUpLeft",We),u(F.current,"browOuterUpLeft",We),u(E.current,"browOuterUpRight",Ve),u(A.current,"browOuterUpRight",Ve),u(F.current,"browOuterUpRight",Ve);const $e=Te.current,De=$e+dt,he=De+Tt;o>he&&(Te.current+=dt+Tt+zt);const be=!C&&o>=$e&&o<De,Oe=!C&&o>=De&&o<he;(be||Oe)&&st.current!==$e&&(st.current=$e,Me.current=Math.random()<.7?"left":"up");const ct=be?o-$e:Oe?dt:0,re=be||Oe?Math.min(1,ct/dt):0,He=re<=0?0:Math.sin(re*Math.PI),ut=Oe?1-(o-De)/Tt:1,wt=be?He:Oe?He*ut:0,Ce=Un*wt,x=y=>I[y]??0;if(Me.current==="up"?(u(q.current,"eyeLookUpLeft",v(x("eyeLookUpLeft")+Ce)),u(q.current,"eyeLookDownLeft",v(x("eyeLookDownLeft"))),u(q.current,"eyeLookOutLeft",v(x("eyeLookOutLeft"))),u(q.current,"eyeLookInLeft",v(x("eyeLookInLeft"))),u(K.current,"eyeLookUpRight",v(x("eyeLookUpRight")+Ce)),u(K.current,"eyeLookDownRight",v(x("eyeLookDownRight"))),u(K.current,"eyeLookOutRight",v(x("eyeLookOutRight"))),u(K.current,"eyeLookInRight",v(x("eyeLookInRight")))):(u(q.current,"eyeLookUpLeft",v(x("eyeLookUpLeft"))),u(q.current,"eyeLookDownLeft",v(x("eyeLookDownLeft"))),u(q.current,"eyeLookOutLeft",v(x("eyeLookOutLeft"))),u(q.current,"eyeLookInLeft",v(x("eyeLookInLeft")+Ce)),u(K.current,"eyeLookUpRight",v(x("eyeLookUpRight"))),u(K.current,"eyeLookDownRight",v(x("eyeLookDownRight"))),u(K.current,"eyeLookOutRight",v(x("eyeLookOutRight")+Ce)),u(K.current,"eyeLookInRight",v(x("eyeLookInRight")))),!C&&o>=Pe.current){fe.current=o,Ae.current=Math.random()<.5?"pucker":"smile";const y=Ae.current==="pucker"?Kt:Yt;Pe.current=o+y+mt+Math.random()*(Qt-mt)}const ie=Ae.current==="pucker"?Kt:Yt,ae=!C&&o>=fe.current&&o<fe.current+ie,Ge=ae?(o-fe.current)/ie:0,Re=Ge<=0?0:Ge<.5?Ge*2:(()=>{const y=(Ge-.5)*2;return 1-y*y*(3-2*y)})(),de=y=>I[y]??0;if(ae)if(Ae.current==="pucker"){const y=v(de("mouthPucker")+Fn*Re);u(E.current,"mouthPucker",y),u(A.current,"mouthPucker",y),u(F.current,"mouthPucker",y)}else{const y=v(de("mouthSmileLeft")+Xt*Re),z=v(de("mouthSmileRight")+Xt*Re),N=v(de("mouthDimpleLeft")+Zt*Re),Le=v(de("mouthDimpleRight")+Zt*Re);u(E.current,"mouthSmileLeft",y),u(E.current,"mouthSmileRight",z),u(E.current,"mouthDimpleLeft",N),u(E.current,"mouthDimpleRight",Le),u(A.current,"mouthSmileLeft",y),u(A.current,"mouthSmileRight",z),u(A.current,"mouthDimpleLeft",N),u(A.current,"mouthDimpleRight",Le),u(F.current,"mouthSmileLeft",y),u(F.current,"mouthSmileRight",z),u(F.current,"mouthDimpleLeft",N),u(F.current,"mouthDimpleRight",Le)}if(J.current){const y=w.current?0:Y.rotation[1];J.current.rotation.y=rt.MathUtils.lerp(J.current.rotation.y,y,.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]}if(w.current&&S.current){const y=S.current.currentTime,Le=(y-V.current)*1e3- -150;for(let ce=0;ce<b.current.length;ce++){const ue=b.current[ce];Le>=ue.vtime&&Le<ue.vtime+ue.vduration&&et(ue.viseme,ue.weight??1)}y>Ze.current+.5&&(Se(),Ye(!1))}}),l.jsx("group",{ref:J,children:l.jsx("primitive",{object:M})})});function Vn(f){return f?f.charAt(0).toUpperCase()+f.slice(1).toLowerCase():""}function tn(f){return f.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const At=new Map,$n=({onNavigationRequested:f,agentId:w,presetUserDetails:b,onAvatarReady:S})=>{const[V,Y]=t.useState(""),[X,ze]=t.useState("male"),[Fe,C]=t.useState(""),[Ze,Se]=t.useState(!1),Ye=V,$=X;t.useEffect(()=>{if(!w){Se(!0);return}let e=!1;return(async()=>{console.log(">> fetchConfig RUNNING for",w);try{const s=`agent_config_${w}`,i=sessionStorage.getItem(s);if(i)try{const a=JSON.parse(i);e||(a.encryptedAgentToken&&Y(a.encryptedAgentToken),a.avatarGender&&ze(a.avatarGender),a.agent_id&&C(a.agent_id),Se(!0));return}catch(a){console.error("Failed to parse cached avatar config:",a),sessionStorage.removeItem(s)}let n;if(At.has(w))console.log(">> REUSING in-flight fetch for",w),n=await At.get(w);else{const a=(async()=>{console.log(">> INITIATING visitedWebsite fetch for",w);const m={agentId:w},R=await fetch(`${Xe}/visitedWebsite`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m)});if(!R.ok)throw new Error(`Fetch failed: ${R.status}`);const L=await R.json();return sessionStorage.setItem(s,JSON.stringify(L)),L})();At.set(w,a),n=await a}if(e)return;n&&(n.encryptedAgentToken&&Y(n.encryptedAgentToken),n.avatarGender&&ze(n.avatarGender),n.agent_id&&C(n.agent_id))}catch(s){console.error("Failed to fetch avatar config:",s)}finally{e||Se(!0)}})(),()=>{e=!0}},[w]);const xe=vn(w??Fe),[G,oe]=t.useState(""),[M,le]=t.useState(""),[W,_]=t.useState("Ready"),[ne,p]=t.useState(!1),[D,J]=t.useState(!1),[E,A]=t.useState([]),[F,q]=t.useState(""),K=t.useRef(null),[bt,Z]=t.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);t.useEffect(()=>{const e=window.matchMedia("(max-width: 480px)"),r=()=>Z(e.matches);return e.addEventListener("change",r),()=>e.removeEventListener("change",r)},[]);const H=bt?80:600,j=t.useRef(!1),ke=t.useRef([]),Ke=t.useRef(0),Ne=t.useRef(!1),Ee=t.useRef([]),ge=t.useRef(null),Te=t.useRef([]);t.useRef([]);const st=t.useRef([]),Me=t.useRef(0),Pe=t.useRef(0),fe=t.useRef(0),Ae=t.useRef(0),ye=t.useRef(!1),[et,tt]=t.useState(null),g=t.useRef(null),[h,c]=t.useState("neutral"),[o,d]=t.useState(""),[I,ee]=t.useState(""),[_t,je]=t.useState("Chat with us"),[te,ot]=t.useState(null),[Ie,Be]=t.useState("hidden"),[v,it]=t.useState(""),We=t.useRef(null),Ve=t.useRef(Ie);Ve.current=Ie;const[at,$e]=t.useState(null),De=t.useRef(null),he=t.useRef(null),[be,Oe]=t.useState(!1),ct=t.useRef(null),[re,He]=t.useState("hidden"),[ut,wt]=t.useState(""),Ce=t.useRef(re);Ce.current=re;const x=t.useRef(""),ie=t.useRef(!1),ae=t.useRef(""),Ge=t.useRef(Date.now()),Re=t.useRef([]),de=t.useRef(!1),[y,z]=t.useState(!1),[N,Le]=t.useState(!1),ce=t.useRef(null),ue=t.useMemo(()=>be?"Try again":W==="Busy"?"Busy":W==="Thinking..."||W==="Processing Voice..."?W:te!=null&&te!==""&&te!=="none"&&te!=="<none>"?`Enter ${Vn(te)}`:re!=="hidden"||!N?null:en,[W,te,be,re,N]),Dt=!be&&W!=="Busy"&&W!=="Thinking..."&&W!=="Processing Voice..."&&(te==null||te===""||te==="none"||te==="<none>");t.useEffect(()=>{if(re!=="hidden"||!Dt){Le(!1),ce.current!=null&&(clearTimeout(ce.current),ce.current=null);return}return ce.current=setTimeout(()=>{ce.current=null,Le(!0)},400),()=>{ce.current!=null&&(clearTimeout(ce.current),ce.current=null)}},[re,Dt]);const lt=ue!=null&&ue!=="";t.useEffect(()=>{const e=Ve.current;if(!(e==="exiting"||e==="entering")){if(e==="hidden"){lt&&(it(ue??""),Be("entering"));return}e==="visible"&&(!lt||ue!==v)&&(We.current=lt?ue:null,Be("exiting"))}},[lt,ue,Ie,v]),t.useEffect(()=>{if(W!=="Busy"){he.current!=null&&(clearTimeout(he.current),he.current=null);return}return he.current=setTimeout(()=>{he.current=null,_("Ready"),Oe(!0)},12e3),()=>{he.current!=null&&(clearTimeout(he.current),he.current=null)}},[W]),t.useEffect(()=>{if(!be)return;const e=setTimeout(()=>Oe(!1),2500);return()=>clearTimeout(e)},[be]);const nn=t.useCallback(()=>{const e=Ve.current;if(e==="exiting"){Be("hidden");const r=We.current;We.current=null,r!=null&&r!==""&&(it(r),Be("entering"))}else e==="entering"&&Be("visible")},[]),Ot=e=>{if(!e)return;if(e.mood!=null){const n=String(e.mood).toLowerCase();c(n)}if(e.expression!=null){const n=String(e.expression).trim();d(n);const a=En.find(m=>m.name.toLowerCase()===n.toLowerCase());U(`[STREAM] Animation match for "${n}": ${a?a.name:"NONE"}`),ee(a?.url??"")}if(e.navigation!=null){const n=String(e.navigation).trim();n!==""&&(f?f(n):window.open(n,"_blank"))}const r=e.ask_for||e.lead_capture?.ask_for,s=r?String(r).trim().toLowerCase():"",i=s==="none"||s==="<none>";if(r&&!i){const n=s;if(b&&(n==="email"&&b.email||n==="name"&&b.name||n==="phone"&&b.phone))return;ot(n||null),je(n==="email"?"Enter your email":n==="name"?"Enter your name":n==="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")&&(ot(null),_t!=="Chat with us"&&je("Chat with us"));e.collected,e.valid},rn=e=>{const r=e.trim();if(!r)return null;if(r.startsWith("{"))try{return JSON.parse(r)}catch{return null}if(r.includes(":")){const s=r.split(":"),i=s[0].trim().toLowerCase(),n=s.slice(1).join(":").trim();return{[i]:n}}return null},sn=t.useCallback(()=>{},[]),Ue="§",St=()=>{for(;x.current.includes(`
|
|
2
2
|
`);){const e=x.current.indexOf(`
|
|
3
|
-
`),r=x.current.slice(0,e).trim();x.current=x.current.slice(e+1);const s=rn(r);s&&Ot(s)}},Ct=e=>{if(ie.current)if(e.includes(Ue)){const r=e.indexOf(Ue),s=e.slice(0,r),i=e.slice(r+Ue.length);s&&(ae.current+=s,le(n=>n+s)),ie.current=!1,i&&(x.current+=i,St())}else e===Ue?ie.current=!1:(ae.current+=e,le(r=>r+e));else if(e.includes(Ue)){const r=e.indexOf(Ue),s=e.slice(0,r),i=e.slice(r+Ue.length);x.current+=s,St(),ie.current=!0,i&&(ae.current+=i,le(n=>n+i))}else if(e===Ue){ie.current=!0;return}else x.current+=e,St()};t.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const n="secret",a=Math.floor(Date.now()/1e3).toString();try{const m=new TextEncoder,R=await crypto.subtle.importKey("raw",m.encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),L=await crypto.subtle.sign("HMAC",R,m.encode(a)),k=Array.from(new Uint8Array(L)).map(O=>O.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",k),U("[SESSION] New HMAC UID generated and saved:",k)}catch(m){console.error("[SESSION] HMAC generation failed:",m);const R=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",R)}}const s=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let i=[];if(s)try{i=JSON.parse(s)}catch{i=[]}i.length===0&&b&&(b.name||b.email)?(i=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${b.name||""}" , Email is "${b.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(i))):s||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[b]),t.useEffect(()=>{const e=()=>{Ge.current=Date.now(),de.current&&(de.current=!1,z(!1),A([]),q(""),le(""),J(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const r=setInterval(async()=>{if(Date.now()-Ge.current>=3e4&&!D&&!ne&&W==="Ready"&&!de.current)if(de.current=!0,Re.current.length>0)z(!0),A(Re.current);else try{const n=`${Xe}/nudgeUser`,a={navigationUrl:window.location.href,agentId:w},m=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(m.ok){const L=(await m.json()).nudge_questions;L&&L.length>0&&(U("[NUDGE] Received nudge questions from API:",L),Re.current=L,z(!0),A(L))}}catch(n){console.error("[NUDGE] Error calling /nudgeUser:",n),de.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(r)}},[Ye,D,ne,W]),t.useEffect(()=>{if(E.length===0)return;let e=0,r=0,s=!1,i=100;const n=()=>{const a=E[e];if(s){const m=a.substring(0,r-1);q(m),r--,i=50}else{const m=a.substring(0,r+1);q(m),r++,i=100}!s&&r===a.length?(s=!0,i=3e3):s&&r===0&&(s=!1,e=(e+1)%E.length,i=500),K.current=setTimeout(n,i)};return n(),()=>{K.current&&clearTimeout(K.current)}},[E]);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))},[yt,Rt]=t.useState(!1),[Ft,Lt]=t.useState(0),_e=t.useRef(null),ft=t.useRef([]),Nt=t.useRef(0),[Pt,an]=t.useState(null),[cn,vt]=t.useState(null),ve=t.useRef(null),Je=t.useRef(null),nt=t.useCallback((e=!1)=>{e&&(ye.current=!0,p(!1),_("Ready")),Ee.current=[],ke.current=[],Ne.current=!1,J(!1),Me.current=0,Pe.current=0,fe.current=0,Te.current.forEach(r=>{try{r.stop()}catch{}}),De.current&&(clearTimeout(De.current),De.current=null),$e(null),ee(""),Te.current=[]},[]),un=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),r=window.AudioContext||window.webkitAudioContext,s=new r,i=s.createMediaStreamSource(e),n=s.createAnalyser();n.fftSize=64,i.connect(n),ve.current=s,Je.current=i,vt(n);const a=new MediaRecorder(e);_e.current=a,ft.current=[],a.ondataavailable=m=>{m.data.size>0&&ft.current.push(m.data)},a.onstop=async()=>{const m=Date.now()-Nt.current;if(vt(null),Je.current&&(Je.current.disconnect(),Je.current=null),ve.current&&ve.current.state!=="closed"&&(ve.current.close(),ve.current=null),m<1e3){_("Recording too short. Hold or click longer."),p(!1);return}const R=new Blob(ft.current,{type:"audio/wav"});await dn(R)},Nt.current=Date.now(),a.start(100),Rt(!0),_("Listening...")}catch(e){console.error("Error accessing microphone:",e),_("Mic Access Error")}},ln=()=>{_e.current&&_e.current.state!=="inactive"&&(_e.current.stop(),_e.current.stream.getTracks().forEach(e=>e.stop()),Rt(!1))},fn=()=>{_e.current&&_e.current.state!=="inactive"&&(_e.current.onstop=null,_e.current.stop(),_e.current.stream.getTracks().forEach(e=>e.stop()),vt(null),Je.current&&(Je.current.disconnect(),Je.current=null),ve.current&&ve.current.state!=="closed"&&(ve.current.close(),ve.current=null),Rt(!1),ft.current=[],_("Ready"))};t.useEffect(()=>{if(!D)return;const e=()=>{const r=fe.current;if(r<=0)return;const s=ge.current,i=Me.current;if(!s)return;const n=s.currentTime-i,a=Math.min(Math.max(0,n),r),R=tn(M).trim().length;if(R<=0)return;const L=Math.min(Math.round(a/r*R),R);tt(L)};return clearInterval(g.current??void 0),g.current=setInterval(e,90),()=>clearInterval(g.current??void 0)},[D,M,fe.current]),t.useEffect(()=>{let e;return yt?(Lt(0),e=window.setInterval(()=>{Lt(r=>r+1)},1e3)):Lt(0),()=>clearInterval(e)},[yt]);const hn=e=>{const r=e.numberOfChannels,s=e.length*r*2+44,i=new ArrayBuffer(s),n=new DataView(i);let a=0;const m=k=>{n.setUint16(a,k,!0),a+=2},R=k=>{n.setUint32(a,k,!0),a+=4};R(1179011410),R(s-8),R(1163280727),R(544501094),R(16),m(1),m(r),R(e.sampleRate),R(e.sampleRate*2*r),m(r*2),m(16),R(1635017060),R(s-a-4);const L=[];for(let k=0;k<r;k++)L.push(e.getChannelData(k));let T=0;for(;a<s;){for(let k=0;k<r;k++){let O=Math.max(-1,Math.min(1,L[k][T]));O=O<0?O*32768:O*32767,n.setInt16(a,O,!0),a+=2}T++}return new Blob([i],{type:"audio/wav"})},xt=async(e,r,s=!1)=>{if(!ye.current){if(j.current){ke.current.push({audio:e,visemes:r,isNewSegment:s});return}j.current=!0;try{const i=window.AudioContext||window.webkitAudioContext,n=ge.current??new i;n.state==="suspended"&&await n.resume(),ge.current=n;const a=window.atob(e),m=new Uint8Array(a.length);for(let B=0;B<a.length;B++)m[B]=a.charCodeAt(B);const R=await n.decodeAudioData(m.buffer.slice(0));fe.current+=R.duration;const L=n.currentTime;let T=Pe.current;const k=!Ne.current;T<L&&(T=L+.1),Pe.current=T+R.duration;const O=n.createBufferSource();O.buffer=R;let Q=Pt;if((!Q||Q.context!==n)&&(Q=n.createAnalyser(),Q.fftSize=64,Q.connect(n.destination),an(Q)),O.connect(Q),Te.current.push(O),ye.current){Te.current=Te.current.filter(B=>B!==O);return}if(k){Ne.current=!0,J(!0),U(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${T.toFixed(3)}`),Me.current=T;const B=(T-L)*1e3;Ke.current=performance.now()+B,U(`[AUDIO] Response started. Initial startTime: ${T.toFixed(3)}, CT: ${L.toFixed(3)}`)}O.start(T);const se=(T-Me.current)*1e3;s&&(Ae.current=se,U(`[AUDIO] New segment detected at +${se.toFixed(0)}ms. Resetting segment offset.`)),r.forEach((B,me)=>{const P=B.symbol??"";if(P){const pe=jn(P),we=Math.round(B.start*1e3),qe=Math.round((B.duration??0)*1e3),Ht=Ae.current+we;me<3&&U(`[AUDIO] Viseme "${P}": segment_relative=${we}ms, segment_offset=${Ae.current.toFixed(0)}ms => vtime=${Ht}ms`),pe.forEach(Gt=>{Ee.current.push({viseme:Gt.v,weight:Gt.w,vtime:Ht,vduration:qe})})}}),_("Speaking...")}finally{if(j.current=!1,ke.current.length>0){const i=ke.current.shift();i&&xt(i.audio,i.visemes,i.isNewSegment)}}}},dn=async e=>{try{p(!0),z(!1),ae.current="",le(""),_("Processing Voice...");const r=await e.arrayBuffer(),i=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(r),n=hn(i),a=new FileReader;a.readAsDataURL(n),a.onloadend=async()=>{const m=a.result.split(",")[1];nt(),oe(""),x.current="",ie.current=!1;const R=`${Xe}/stt?token=${encodeURIComponent(Ye)}`,L=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:m,audio_format:"wav"})});if(L.status===429){try{const me=await L.text(),P=JSON.parse(me);U("[STT] 429 agent at capacity:",P?.detail)}catch{}oe(""),_("Busy"),p(!1);return}if(!L.ok){const me=await L.text();let P="STT Failed";try{P=JSON.parse(me).error||P}catch{me&&(P=me.slice(0,200))}throw new Error(P)}const T=L.body;if(U("this is body"+T),!T){_("STT Failed"),p(!1);return}const k=T.getReader();ye.current=!1;const O=new TextDecoder;let Q="",se=!1;const B=async(me,P)=>{switch(me){case"transcript":P.transcript!=null&&oe(String(P.transcript));break;case"text":{const pe=P.delta??P.text??"";pe&&Ct(pe);break}case"audio":{const pe=P.chunk,we=P.visemes??[],qe=!!P.is_new_segment;pe&&await xt(pe,we,qe);break}case"done":{se=!0,_("Ready"),p(!1);break}case"error":{se=!0,_("STT Failed"),p(!1);break}default:break}};for(;;){const{done:me,value:P}=await k.read();P&&(Q+=O.decode(P,{stream:!0}));const pe=Q.split(`
|
|
3
|
+
`),r=x.current.slice(0,e).trim();x.current=x.current.slice(e+1);const s=rn(r);s&&Ot(s)}},Ct=e=>{if(ie.current)if(e.includes(Ue)){const r=e.indexOf(Ue),s=e.slice(0,r),i=e.slice(r+Ue.length);s&&(ae.current+=s,le(n=>n+s)),ie.current=!1,i&&(x.current+=i,St())}else e===Ue?ie.current=!1:(ae.current+=e,le(r=>r+e));else if(e.includes(Ue)){const r=e.indexOf(Ue),s=e.slice(0,r),i=e.slice(r+Ue.length);x.current+=s,St(),ie.current=!0,i&&(ae.current+=i,le(n=>n+i))}else if(e===Ue){ie.current=!0;return}else x.current+=e,St()};t.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const n="secret",a=Math.floor(Date.now()/1e3).toString();try{const m=new TextEncoder,R=await globalThis.crypto.subtle.importKey("raw",m.encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),L=await globalThis.crypto.subtle.sign("HMAC",R,m.encode(a)),k=Array.from(new Uint8Array(L)).map(O=>O.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",k),U("[SESSION] New HMAC UID generated and saved:",k)}catch(m){console.error("[SESSION] HMAC generation failed:",m);const R=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",R)}}const s=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let i=[];if(s)try{i=JSON.parse(s)}catch{i=[]}i.length===0&&b&&(b.name||b.email)?(i=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${b.name||""}" , Email is "${b.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(i))):s||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[b]),t.useEffect(()=>{const e=()=>{Ge.current=Date.now(),de.current&&(de.current=!1,z(!1),A([]),q(""),le(""),J(!1))};window.addEventListener("mousemove",e),window.addEventListener("keydown",e),window.addEventListener("mousedown",e),window.addEventListener("touchstart",e);const r=setInterval(async()=>{if(Date.now()-Ge.current>=3e4&&!D&&!ne&&W==="Ready"&&!de.current)if(de.current=!0,Re.current.length>0)z(!0),A(Re.current);else try{const n=`${Xe}/nudgeUser`,a={navigationUrl:window.location.href,agentId:w},m=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(m.ok){const L=(await m.json()).nudge_questions;L&&L.length>0&&(U("[NUDGE] Received nudge questions from API:",L),Re.current=L,z(!0),A(L))}}catch(n){console.error("[NUDGE] Error calling /nudgeUser:",n),de.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",e),window.removeEventListener("keydown",e),window.removeEventListener("mousedown",e),window.removeEventListener("touchstart",e),clearInterval(r)}},[Ye,D,ne,W]),t.useEffect(()=>{if(E.length===0)return;let e=0,r=0,s=!1,i=100;const n=()=>{const a=E[e];if(s){const m=a.substring(0,r-1);q(m),r--,i=50}else{const m=a.substring(0,r+1);q(m),r++,i=100}!s&&r===a.length?(s=!0,i=3e3):s&&r===0&&(s=!1,e=(e+1)%E.length,i=500),K.current=setTimeout(n,i)};return n(),()=>{K.current&&clearTimeout(K.current)}},[E]);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))},[yt,Rt]=t.useState(!1),[Ft,Lt]=t.useState(0),_e=t.useRef(null),ft=t.useRef([]),Nt=t.useRef(0),[Pt,an]=t.useState(null),[cn,vt]=t.useState(null),ve=t.useRef(null),Je=t.useRef(null),nt=t.useCallback((e=!1)=>{e&&(ye.current=!0,p(!1),_("Ready")),Ee.current=[],ke.current=[],Ne.current=!1,J(!1),Me.current=0,Pe.current=0,fe.current=0,Te.current.forEach(r=>{try{r.stop()}catch{}}),De.current&&(clearTimeout(De.current),De.current=null),$e(null),ee(""),Te.current=[]},[]),un=async()=>{try{const e=await navigator.mediaDevices.getUserMedia({audio:!0}),r=window.AudioContext||window.webkitAudioContext,s=new r,i=s.createMediaStreamSource(e),n=s.createAnalyser();n.fftSize=64,i.connect(n),ve.current=s,Je.current=i,vt(n);const a=new MediaRecorder(e);_e.current=a,ft.current=[],a.ondataavailable=m=>{m.data.size>0&&ft.current.push(m.data)},a.onstop=async()=>{const m=Date.now()-Nt.current;if(vt(null),Je.current&&(Je.current.disconnect(),Je.current=null),ve.current&&ve.current.state!=="closed"&&(ve.current.close(),ve.current=null),m<1e3){_("Recording too short. Hold or click longer."),p(!1);return}const R=new Blob(ft.current,{type:"audio/wav"});await dn(R)},Nt.current=Date.now(),a.start(100),Rt(!0),_("Listening...")}catch(e){console.error("Error accessing microphone:",e),_("Mic Access Error")}},ln=()=>{_e.current&&_e.current.state!=="inactive"&&(_e.current.stop(),_e.current.stream.getTracks().forEach(e=>e.stop()),Rt(!1))},fn=()=>{_e.current&&_e.current.state!=="inactive"&&(_e.current.onstop=null,_e.current.stop(),_e.current.stream.getTracks().forEach(e=>e.stop()),vt(null),Je.current&&(Je.current.disconnect(),Je.current=null),ve.current&&ve.current.state!=="closed"&&(ve.current.close(),ve.current=null),Rt(!1),ft.current=[],_("Ready"))};t.useEffect(()=>{if(!D)return;const e=()=>{const r=fe.current;if(r<=0)return;const s=ge.current,i=Me.current;if(!s)return;const n=s.currentTime-i,a=Math.min(Math.max(0,n),r),R=tn(M).trim().length;if(R<=0)return;const L=Math.min(Math.round(a/r*R),R);tt(L)};return clearInterval(g.current??void 0),g.current=setInterval(e,90),()=>clearInterval(g.current??void 0)},[D,M,fe.current]),t.useEffect(()=>{let e;return yt?(Lt(0),e=window.setInterval(()=>{Lt(r=>r+1)},1e3)):Lt(0),()=>clearInterval(e)},[yt]);const hn=e=>{const r=e.numberOfChannels,s=e.length*r*2+44,i=new ArrayBuffer(s),n=new DataView(i);let a=0;const m=k=>{n.setUint16(a,k,!0),a+=2},R=k=>{n.setUint32(a,k,!0),a+=4};R(1179011410),R(s-8),R(1163280727),R(544501094),R(16),m(1),m(r),R(e.sampleRate),R(e.sampleRate*2*r),m(r*2),m(16),R(1635017060),R(s-a-4);const L=[];for(let k=0;k<r;k++)L.push(e.getChannelData(k));let T=0;for(;a<s;){for(let k=0;k<r;k++){let O=Math.max(-1,Math.min(1,L[k][T]));O=O<0?O*32768:O*32767,n.setInt16(a,O,!0),a+=2}T++}return new Blob([i],{type:"audio/wav"})},xt=async(e,r,s=!1)=>{if(!ye.current){if(j.current){ke.current.push({audio:e,visemes:r,isNewSegment:s});return}j.current=!0;try{const i=window.AudioContext||window.webkitAudioContext,n=ge.current??new i;n.state==="suspended"&&await n.resume(),ge.current=n;const a=window.atob(e),m=new Uint8Array(a.length);for(let B=0;B<a.length;B++)m[B]=a.charCodeAt(B);const R=await n.decodeAudioData(m.buffer.slice(0));fe.current+=R.duration;const L=n.currentTime;let T=Pe.current;const k=!Ne.current;T<L&&(T=L+.1),Pe.current=T+R.duration;const O=n.createBufferSource();O.buffer=R;let Q=Pt;if((!Q||Q.context!==n)&&(Q=n.createAnalyser(),Q.fftSize=64,Q.connect(n.destination),an(Q)),O.connect(Q),Te.current.push(O),ye.current){Te.current=Te.current.filter(B=>B!==O);return}if(k){Ne.current=!0,J(!0),U(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${T.toFixed(3)}`),Me.current=T;const B=(T-L)*1e3;Ke.current=performance.now()+B,U(`[AUDIO] Response started. Initial startTime: ${T.toFixed(3)}, CT: ${L.toFixed(3)}`)}O.start(T);const se=(T-Me.current)*1e3;s&&(Ae.current=se,U(`[AUDIO] New segment detected at +${se.toFixed(0)}ms. Resetting segment offset.`)),r.forEach((B,me)=>{const P=B.symbol??"";if(P){const pe=jn(P),we=Math.round(B.start*1e3),qe=Math.round((B.duration??0)*1e3),Ht=Ae.current+we;me<3&&U(`[AUDIO] Viseme "${P}": segment_relative=${we}ms, segment_offset=${Ae.current.toFixed(0)}ms => vtime=${Ht}ms`),pe.forEach(Gt=>{Ee.current.push({viseme:Gt.v,weight:Gt.w,vtime:Ht,vduration:qe})})}}),_("Speaking...")}finally{if(j.current=!1,ke.current.length>0){const i=ke.current.shift();i&&xt(i.audio,i.visemes,i.isNewSegment)}}}},dn=async e=>{try{p(!0),z(!1),ae.current="",le(""),_("Processing Voice...");const r=await e.arrayBuffer(),i=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(r),n=hn(i),a=new FileReader;a.readAsDataURL(n),a.onloadend=async()=>{const m=a.result.split(",")[1];nt(),oe(""),x.current="",ie.current=!1;const R=`${Xe}/stt?token=${encodeURIComponent(Ye)}`,L=await fetch(R,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:m,audio_format:"wav"})});if(L.status===429){try{const me=await L.text(),P=JSON.parse(me);U("[STT] 429 agent at capacity:",P?.detail)}catch{}oe(""),_("Busy"),p(!1);return}if(!L.ok){const me=await L.text();let P="STT Failed";try{P=JSON.parse(me).error||P}catch{me&&(P=me.slice(0,200))}throw new Error(P)}const T=L.body;if(U("this is body"+T),!T){_("STT Failed"),p(!1);return}const k=T.getReader();ye.current=!1;const O=new TextDecoder;let Q="",se=!1;const B=async(me,P)=>{switch(me){case"transcript":P.transcript!=null&&oe(String(P.transcript));break;case"text":{const pe=P.delta??P.text??"";pe&&Ct(pe);break}case"audio":{const pe=P.chunk,we=P.visemes??[],qe=!!P.is_new_segment;pe&&await xt(pe,we,qe);break}case"done":{se=!0,_("Ready"),p(!1);break}case"error":{se=!0,_("STT Failed"),p(!1);break}default:break}};for(;;){const{done:me,value:P}=await k.read();P&&(Q+=O.decode(P,{stream:!0}));const pe=Q.split(`
|
|
4
4
|
|
|
5
5
|
`);Q=pe.pop()??"";for(const we of pe){const qe=Qe(we);qe&&await B(qe.event,qe.data)}if(me){if(Q.trim()){const we=Qe(Q.trim());we&&await B(we.event,we.data)}se||(_("Ready"),p(!1));break}}}}catch(r){console.error("Audio Submission Error:",r),_("STT Failed"),p(!1)}},mn=async e=>{e&&e.preventDefault(),z(!1),ae.current="",le(""),!(!G||ne)&&await pn(G)},Qe=e=>{const r=e.split(/\r?\n/);let s="",i="";for(const a of r)a.startsWith("event:")?s=a.slice(6).trim():a.startsWith("data:")&&(i=a.slice(5).trim());if(!s)return null;let n={};if(i)try{n=JSON.parse(i)}catch{n={raw:i}}return{event:s,data:n}},ht=(e,r)=>{switch(e){case"connected":x.current="",ie.current=!1;break;case"text":{const s=r.delta??"";s&&Ct(s);break}case"metadata":{Ot(r);break}case"audio":{const s=r.chunk,i=r.visemes??[],n=r.is_new_segment??!1;s&&xt(s,i,n);break}case"done":{const s=Ut(),i=ae.current.trim(),n=[...s,{role:"user",content:G||"..."},{role:"assistant",content:i}];on(n),st.current=[...Ee.current],_("Ready"),p(!1),oe("");break}case"error":{const s=r.message??"Unknown error";ae.current=s,le(s),_("Agent Failed"),p(!1);break}}},jt=async(e,r)=>{p(!0),_("Thinking..."),ae.current="",x.current="",ie.current=!1,nt(),fe.current=0,tt(0);try{const s=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});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 n=i.getReader();ye.current=!1;const a=new TextDecoder;let m="";for(;;){const{done:R,value:L}=await n.read();L&&(m+=a.decode(L,{stream:!0}));const T=m.split(`
|
|
6
6
|
|
package/dist/avatar-widget.js
CHANGED
|
@@ -1073,13 +1073,13 @@ const Ct = /* @__PURE__ */ new Map(), Xn = ({
|
|
|
1073
1073
|
)) {
|
|
1074
1074
|
const t = "secret", s = Math.floor(Date.now() / 1e3).toString();
|
|
1075
1075
|
try {
|
|
1076
|
-
const f = new TextEncoder(), w = await crypto.subtle.importKey(
|
|
1076
|
+
const f = new TextEncoder(), w = await globalThis.crypto.subtle.importKey(
|
|
1077
1077
|
"raw",
|
|
1078
1078
|
f.encode(t),
|
|
1079
1079
|
{ name: "HMAC", hash: "SHA-256" },
|
|
1080
1080
|
!1,
|
|
1081
1081
|
["sign"]
|
|
1082
|
-
), k = await crypto.subtle.sign(
|
|
1082
|
+
), k = await globalThis.crypto.subtle.sign(
|
|
1083
1083
|
"HMAC",
|
|
1084
1084
|
w,
|
|
1085
1085
|
f.encode(s)
|
|
@@ -4148,11 +4148,10 @@ void main() {
|
|
|
4148
4148
|
}
|
|
4149
4149
|
`;class WI extends Us{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:i,gainMapMax:o,maxDisplayBoost:l,hdrCapacityMin:h,hdrCapacityMax:d,sdr:p,gainMap:_}){super({name:"GainMapDecoderMaterial",vertexShader:qI,fragmentShader:KI,uniforms:{sdr:{value:p},gainMap:{value:_},gamma:{value:new Z(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new Z().fromArray(t)},offsetSdr:{value:new Z().fromArray(n)},gainMapMin:{value:new Z().fromArray(i)},gainMapMax:{value:new Z().fromArray(o)},weightFactor:{value:(Math.log2(l)-h)/(d-h)}},blending:so,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=l,this._hdrCapacityMin=h,this._hdrCapacityMax=d,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){const e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){const t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){const e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}}class rC extends JI{constructor(e,t){super({renderer:e,createMaterial:n=>new WI(n),createQuadRenderer:n=>new BS(n)},t)}async render(e,t,n,i){const{sdrImage:o,gainMapImage:l,needsFlip:h}=await this.processImages(n,i,"flipY"),{gainMap:d,sdr:p}=this.createTextures(o,l,h);this.updateQuadRenderer(e,o,d,p,t),e.render()}}class jI extends rC{load([e,t,n],i,o,l){const h=this.prepareQuadRenderer();let d,p,_;const v=async()=>{if(d&&p&&_){try{await this.render(h,_,d,p)}catch(U){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof l=="function"&&l(U),h.disposeOnDemandRenderer();return}typeof i=="function"&&i(h),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),h.disposeOnDemandRenderer()}};let y=!0,x=0,b=0,R=!0,T=0,M=0,w=!0,B=0,L=0;const H=()=>{if(typeof o=="function"){const U=x+T+B,I=b+M+L,W=y&&R&&w;o(new ProgressEvent("progress",{lengthComputable:W,loaded:I,total:U}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);const O=new La(this._internalLoadingManager);O.setResponseType("arraybuffer"),O.setRequestHeader(this.requestHeader),O.setPath(this.path),O.setWithCredentials(this.withCredentials),O.load(e,async U=>{if(typeof U=="string")throw new Error("Invalid sdr buffer");d=U,await v()},U=>{y=U.lengthComputable,b=U.loaded,x=U.total,H()},U=>{this.manager.itemError(e),typeof l=="function"&&l(U)});const z=new La(this._internalLoadingManager);z.setResponseType("arraybuffer"),z.setRequestHeader(this.requestHeader),z.setPath(this.path),z.setWithCredentials(this.withCredentials),z.load(t,async U=>{if(typeof U=="string")throw new Error("Invalid gainmap buffer");p=U,await v()},U=>{R=U.lengthComputable,M=U.loaded,T=U.total,H()},U=>{this.manager.itemError(t),typeof l=="function"&&l(U)});const V=new La(this._internalLoadingManager);return V.setRequestHeader(this.requestHeader),V.setPath(this.path),V.setWithCredentials(this.withCredentials),V.load(n,async U=>{if(typeof U!="string")throw new Error("Invalid metadata string");_=JSON.parse(U),await v()},U=>{w=U.lengthComputable,L=U.loaded,B=U.total,H()},U=>{this.manager.itemError(n),typeof l=="function"&&l(U)}),h}}class ZI extends rC{load(e,t,n,i){const o=this.prepareQuadRenderer(),l=new La(this._internalLoadingManager);return l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setPath(this.path),l.setWithCredentials(this.withCredentials),this.manager.itemStart(e),l.load(e,async h=>{if(typeof h=="string")throw new Error("Invalid buffer, received [string], was expecting [ArrayBuffer]");const d=new Uint8Array(h);let p,_,v;try{const y=await YI(d);p=y.sdr,_=y.gainMap,v=y.metadata}catch(y){if(y instanceof aC||y instanceof iC)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),v={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},p=d;else throw y}try{await this.render(o,v,p.buffer,_?.buffer)}catch(y){this.manager.itemError(e),typeof i=="function"&&i(y),o.disposeOnDemandRenderer();return}typeof t=="function"&&t(o),this.manager.itemEnd(e),o.disposeOnDemandRenderer()},n,h=>{this.manager.itemError(e),typeof i=="function"&&i(h)}),o}}const om={apartment:"lebombo_1k.hdr",city:"potsdamer_platz_1k.hdr",dawn:"kiara_1_dawn_1k.hdr",forest:"forest_slope_1k.hdr",lobby:"st_fagans_interior_1k.hdr",night:"dikhololo_night_1k.hdr",park:"rooitou_park_1k.hdr",studio:"studio_small_03_1k.hdr",sunset:"venice_sunset_1k.hdr",warehouse:"empty_warehouse_01_1k.hdr"},oC="https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/",Wh=s=>Array.isArray(s),DS=["/px.png","/nx.png","/py.png","/ny.png","/pz.png","/nz.png"];function v_({files:s=DS,path:e="",preset:t=void 0,colorSpace:n=void 0,extensions:i}={}){t&&(LS(t),s=om[t],e=oC);const o=Wh(s),{extension:l,isCubemap:h}=US(s),d=NS(l);if(!d)throw new Error("useEnvironment: Unrecognized file extension: "+s);const p=kh(x=>x.gl);me.useLayoutEffect(()=>{if(l!=="webp"&&l!=="jpg"&&l!=="jpeg")return;function x(){Gl.clear(d,o?[s]:s)}p.domElement.addEventListener("webglcontextlost",x,{once:!0})},[s,p.domElement]);const _=Gl(d,o?[s]:s,x=>{(l==="webp"||l==="jpg"||l==="jpeg")&&x.setRenderer(p),x.setPath==null||x.setPath(e),i&&i(x)});let v=o?_[0]:_;if(l==="jpg"||l==="jpeg"||l==="webp"){var y;v=(y=v.renderTarget)==null?void 0:y.texture}return v.mapping=h?ro:nh,v.colorSpace=n??(h?"srgb":"srgb-linear"),v}const QI={files:DS,path:"",preset:void 0,extensions:void 0};v_.preload=s=>{const e={...QI,...s};let{files:t,path:n=""}=e;const{preset:i,extensions:o}=e;i&&(LS(i),t=om[i],n=oC);const{extension:l}=US(t);if(l==="webp"||l==="jpg"||l==="jpeg")throw new Error("useEnvironment: Preloading gainmaps is not supported");const h=NS(l);if(!h)throw new Error("useEnvironment: Unrecognized file extension: "+t);Gl.preload(h,Wh(t)?[t]:t,d=>{d.setPath==null||d.setPath(n),o&&o(d)})};const $I={files:DS,preset:void 0};v_.clear=s=>{const e={...$I,...s};let{files:t}=e;const{preset:n}=e;n&&(LS(n),t=om[n]);const{extension:i}=US(t),o=NS(i);if(!o)throw new Error("useEnvironment: Unrecognized file extension: "+t);Gl.clear(o,Wh(t)?[t]:t)};function LS(s){if(!(s in om))throw new Error("Preset must be one of: "+Object.keys(om).join(", "))}function US(s){var e;const t=Wh(s)&&s.length===6,n=Wh(s)&&s.length===3&&s.some(l=>l.endsWith("json")),i=Wh(s)?s[0]:s;return{extension:t?"cube":n?"webp":i.startsWith("data:application/exr")?"exr":i.startsWith("data:application/hdr")?"hdr":i.startsWith("data:image/jpeg")?"jpg":(e=i.split(".").pop())==null||(e=e.split("?"))==null||(e=e.shift())==null?void 0:e.toLowerCase(),isCubemap:t,isGainmap:n}}function NS(s){return s==="cube"?X1:s==="hdr"?HI:s==="exr"?PI:s==="jpg"||s==="jpeg"?ZI:s==="webp"?jI:null}const eF=s=>s.current&&s.current.isScene,tF=s=>eF(s)?s.current:s;function OS(s,e,t,n,i={}){var o,l,h,d;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};const p=tF(e||t),_=p.background,v=p.environment,y={backgroundBlurriness:p.backgroundBlurriness,backgroundIntensity:p.backgroundIntensity,backgroundRotation:(o=(l=p.backgroundRotation)==null||l.clone==null?void 0:l.clone())!==null&&o!==void 0?o:[0,0,0],environmentIntensity:p.environmentIntensity,environmentRotation:(h=(d=p.environmentRotation)==null||d.clone==null?void 0:d.clone())!==null&&h!==void 0?h:[0,0,0]};return s!=="only"&&(p.environment=n),s&&(p.background=n),Yo(p,i),()=>{s!=="only"&&(p.environment=v),s&&(p.background=_),Yo(p,y)}}function IS({scene:s,background:e=!1,map:t,...n}){const i=kh(o=>o.scene);return me.useLayoutEffect(()=>{if(t)return OS(e,s,i,t,n)}),null}function lC({background:s=!1,scene:e,blur:t,backgroundBlurriness:n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h,...d}){const p=v_(d),_=kh(v=>v.scene);return me.useLayoutEffect(()=>OS(s,e,_,p,{backgroundBlurriness:t??n,backgroundIntensity:i,backgroundRotation:o,environmentIntensity:l,environmentRotation:h})),me.useEffect(()=>()=>{p.dispose()},[p]),null}function nF({children:s,near:e=.1,far:t=1e3,resolution:n=256,frames:i=1,map:o,background:l=!1,blur:h,backgroundBlurriness:d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y,scene:x,files:b,path:R,preset:T=void 0,extensions:M}){const w=kh(V=>V.gl),B=kh(V=>V.scene),L=me.useRef(null),[H]=me.useState(()=>new Rp),O=me.useMemo(()=>{const V=new K0(n);return V.texture.type=aa,V},[n]);me.useEffect(()=>()=>{O.dispose()},[O]),me.useLayoutEffect(()=>{if(i===1){const V=w.autoClear;w.autoClear=!0,L.current.update(w,H),w.autoClear=V}return OS(l,x,B,O.texture,{backgroundBlurriness:h??d,backgroundIntensity:p,backgroundRotation:_,environmentIntensity:v,environmentRotation:y})},[s,H,O.texture,x,B,l,i,w]);let z=1;return bT(()=>{if(i===1/0||z<i){const V=w.autoClear;w.autoClear=!0,L.current.update(w,H),w.autoClear=V,z++}}),me.createElement(me.Fragment,null,wO(me.createElement(me.Fragment,null,s,me.createElement("cubeCamera",{ref:L,args:[e,t,O]}),b||T?me.createElement(lC,{background:!0,files:b,preset:T,path:R,extensions:M}):o?me.createElement(IS,{background:!0,map:o,extensions:M}):null),H))}function iF(s){var e,t,n,i;const o=v_(s),l=s.map||o;me.useMemo(()=>RT({GroundProjectedEnvImpl:nI}),[]),me.useEffect(()=>()=>{o.dispose()},[o]);const h=me.useMemo(()=>[l],[l]),d=(e=s.ground)==null?void 0:e.height,p=(t=s.ground)==null?void 0:t.radius,_=(n=(i=s.ground)==null?void 0:i.scale)!==null&&n!==void 0?n:1e3;return me.createElement(me.Fragment,null,me.createElement(IS,Jy({},s,{map:l})),me.createElement("groundProjectedEnvImpl",{args:h,scale:_,height:d,radius:p}))}function aF(s){return s.ground?me.createElement(iF,s):s.map?me.createElement(IS,s):s.children?me.createElement(nF,s):me.createElement(lC,s)}function cC(s,e){if(e===ux)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),s;if(e===Nu||e===gp){let t=s.getIndex();if(t===null){const l=[],h=s.getAttribute("position");if(h!==void 0){for(let d=0;d<h.count;d++)l.push(d);s.setIndex(l),t=s.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),s}const n=t.count-2,i=[];if(e===Nu)for(let l=1;l<=n;l++)i.push(t.getX(0)),i.push(t.getX(l)),i.push(t.getX(l+1));else for(let l=0;l<n;l++)l%2===0?(i.push(t.getX(l)),i.push(t.getX(l+1)),i.push(t.getX(l+2))):(i.push(t.getX(l+2)),i.push(t.getX(l+1)),i.push(t.getX(l)));i.length/3!==n&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");const o=s.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),s}class sF extends Ja{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new uF(t)}),this.register(function(t){return new fF(t)}),this.register(function(t){return new xF(t)}),this.register(function(t){return new AF(t)}),this.register(function(t){return new SF(t)}),this.register(function(t){return new dF(t)}),this.register(function(t){return new pF(t)}),this.register(function(t){return new mF(t)}),this.register(function(t){return new gF(t)}),this.register(function(t){return new cF(t)}),this.register(function(t){return new vF(t)}),this.register(function(t){return new hF(t)}),this.register(function(t){return new yF(t)}),this.register(function(t){return new _F(t)}),this.register(function(t){return new oF(t)}),this.register(function(t){return new MF(t)}),this.register(function(t){return new bF(t)})}load(e,t,n,i){const o=this;let l;if(this.resourcePath!=="")l=this.resourcePath;else if(this.path!==""){const p=yr.extractUrlBase(e);l=yr.resolveURL(p,this.path)}else l=yr.extractUrlBase(e);this.manager.itemStart(e);const h=function(p){i?i(p):console.error(p),o.manager.itemError(e),o.manager.itemEnd(e)},d=new La(this.manager);d.setPath(this.path),d.setResponseType("arraybuffer"),d.setRequestHeader(this.requestHeader),d.setWithCredentials(this.withCredentials),d.load(e,function(p){try{o.parse(p,l,function(_){t(_),o.manager.itemEnd(e)},h)}catch(_){h(_)}},n,h)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,n,i){let o;const l={},h={},d=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(d.decode(new Uint8Array(e,0,4))===uC){try{l[Yn.KHR_BINARY_GLTF]=new EF(e)}catch(v){i&&i(v);return}o=JSON.parse(l[Yn.KHR_BINARY_GLTF].content)}else o=JSON.parse(d.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}const p=new HF(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});p.fileLoader.setRequestHeader(this.requestHeader);for(let _=0;_<this.pluginCallbacks.length;_++){const v=this.pluginCallbacks[_](p);v.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),h[v.name]=v,l[v.name]=!0}if(o.extensionsUsed)for(let _=0;_<o.extensionsUsed.length;++_){const v=o.extensionsUsed[_],y=o.extensionsRequired||[];switch(v){case Yn.KHR_MATERIALS_UNLIT:l[v]=new lF;break;case Yn.KHR_DRACO_MESH_COMPRESSION:l[v]=new TF(o,this.dracoLoader);break;case Yn.KHR_TEXTURE_TRANSFORM:l[v]=new CF;break;case Yn.KHR_MESH_QUANTIZATION:l[v]=new RF;break;default:y.indexOf(v)>=0&&h[v]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+v+'".')}}p.setExtensions(l),p.setPlugins(h),p.parse(n,i)}parseAsync(e,t){const n=this;return new Promise(function(i,o){n.parse(e,t,i,o)})}}function rF(){let s={};return{get:function(e){return s[e]},add:function(e,t){s[e]=t},remove:function(e){delete s[e]},removeAll:function(){s={}}}}const Yn={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"};class oF{constructor(e){this.parser=e,this.name=Yn.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){const e=this.parser,t=this.parser.json.nodes||[];for(let n=0,i=t.length;n<i;n++){const o=t[n];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){const t=this.parser,n="light:"+e;let i=t.cache.get(n);if(i)return i;const o=t.json,d=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e];let p;const _=new wt(16777215);d.color!==void 0&&_.setRGB(d.color[0],d.color[1],d.color[2],Sa);const v=d.range!==void 0?d.range:0;switch(d.type){case"directional":p=new Vv(_),p.target.position.set(0,0,-1),p.add(p.target);break;case"point":p=new zv(_),p.distance=v;break;case"spot":p=new Gv(_),p.distance=v,d.spot=d.spot||{},d.spot.innerConeAngle=d.spot.innerConeAngle!==void 0?d.spot.innerConeAngle:0,d.spot.outerConeAngle=d.spot.outerConeAngle!==void 0?d.spot.outerConeAngle:Math.PI/4,p.angle=d.spot.outerConeAngle,p.penumbra=1-d.spot.innerConeAngle/d.spot.outerConeAngle,p.target.position.set(0,0,-1),p.add(p.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+d.type)}return p.position.set(0,0,0),Jo(p,d),d.intensity!==void 0&&(p.intensity=d.intensity),p.name=t.createUniqueName(d.name||"light_"+e),i=Promise.resolve(p),t.cache.add(n,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){const t=this,n=this.parser,o=n.json.nodes[e],h=(o.extensions&&o.extensions[this.name]||{}).light;return h===void 0?null:this._loadLight(h).then(function(d){return n._getNodeRef(t.cache,h,d)})}}class lF{constructor(){this.name=Yn.KHR_MATERIALS_UNLIT}getMaterialType(){return Da}extendParams(e,t,n){const i=[];e.color=new wt(1,1,1),e.opacity=1;const o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){const l=o.baseColorFactor;e.color.setRGB(l[0],l[1],l[2],Sa),e.opacity=l[3]}o.baseColorTexture!==void 0&&i.push(n.assignTexture(e,"map",o.baseColorTexture,sa))}return Promise.all(i)}}class cF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name].emissiveStrength;return o!==void 0&&(t.emissiveIntensity=o),Promise.resolve()}}class uF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];if(l.clearcoatFactor!==void 0&&(t.clearcoat=l.clearcoatFactor),l.clearcoatTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatMap",l.clearcoatTexture)),l.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=l.clearcoatRoughnessFactor),l.clearcoatRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"clearcoatRoughnessMap",l.clearcoatRoughnessTexture)),l.clearcoatNormalTexture!==void 0&&(o.push(n.assignTexture(t,"clearcoatNormalMap",l.clearcoatNormalTexture)),l.clearcoatNormalTexture.scale!==void 0)){const h=l.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new et(h,h)}return Promise.all(o)}}class fF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_DISPERSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.dispersion=o.dispersion!==void 0?o.dispersion:0,Promise.resolve()}}class hF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.iridescenceFactor!==void 0&&(t.iridescence=l.iridescenceFactor),l.iridescenceTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceMap",l.iridescenceTexture)),l.iridescenceIor!==void 0&&(t.iridescenceIOR=l.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),l.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=l.iridescenceThicknessMinimum),l.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=l.iridescenceThicknessMaximum),l.iridescenceThicknessTexture!==void 0&&o.push(n.assignTexture(t,"iridescenceThicknessMap",l.iridescenceThicknessTexture)),Promise.all(o)}}class dF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_SHEEN}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[];t.sheenColor=new wt(0,0,0),t.sheenRoughness=0,t.sheen=1;const l=i.extensions[this.name];if(l.sheenColorFactor!==void 0){const h=l.sheenColorFactor;t.sheenColor.setRGB(h[0],h[1],h[2],Sa)}return l.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=l.sheenRoughnessFactor),l.sheenColorTexture!==void 0&&o.push(n.assignTexture(t,"sheenColorMap",l.sheenColorTexture,sa)),l.sheenRoughnessTexture!==void 0&&o.push(n.assignTexture(t,"sheenRoughnessMap",l.sheenRoughnessTexture)),Promise.all(o)}}class pF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.transmissionFactor!==void 0&&(t.transmission=l.transmissionFactor),l.transmissionTexture!==void 0&&o.push(n.assignTexture(t,"transmissionMap",l.transmissionTexture)),Promise.all(o)}}class mF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_VOLUME}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.thickness=l.thicknessFactor!==void 0?l.thicknessFactor:0,l.thicknessTexture!==void 0&&o.push(n.assignTexture(t,"thicknessMap",l.thicknessTexture)),t.attenuationDistance=l.attenuationDistance||1/0;const h=l.attenuationColor||[1,1,1];return t.attenuationColor=new wt().setRGB(h[0],h[1],h[2],Sa),Promise.all(o)}}class gF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_IOR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const i=this.parser.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=i.extensions[this.name];return t.ior=o.ior!==void 0?o.ior:1.5,Promise.resolve()}}class vF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_SPECULAR}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];t.specularIntensity=l.specularFactor!==void 0?l.specularFactor:1,l.specularTexture!==void 0&&o.push(n.assignTexture(t,"specularIntensityMap",l.specularTexture));const h=l.specularColorFactor||[1,1,1];return t.specularColor=new wt().setRGB(h[0],h[1],h[2],Sa),l.specularColorTexture!==void 0&&o.push(n.assignTexture(t,"specularColorMap",l.specularColorTexture,sa)),Promise.all(o)}}class _F{constructor(e){this.parser=e,this.name=Yn.EXT_MATERIALS_BUMP}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return t.bumpScale=l.bumpFactor!==void 0?l.bumpFactor:1,l.bumpTexture!==void 0&&o.push(n.assignTexture(t,"bumpMap",l.bumpTexture)),Promise.all(o)}}class yF{constructor(e){this.parser=e,this.name=Yn.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){const n=this.parser.json.materials[e];return!n.extensions||!n.extensions[this.name]?null:oa}extendMaterialParams(e,t){const n=this.parser,i=n.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();const o=[],l=i.extensions[this.name];return l.anisotropyStrength!==void 0&&(t.anisotropy=l.anisotropyStrength),l.anisotropyRotation!==void 0&&(t.anisotropyRotation=l.anisotropyRotation),l.anisotropyTexture!==void 0&&o.push(n.assignTexture(t,"anisotropyMap",l.anisotropyTexture)),Promise.all(o)}}class xF{constructor(e){this.parser=e,this.name=Yn.KHR_TEXTURE_BASISU}loadTexture(e){const t=this.parser,n=t.json,i=n.textures[e];if(!i.extensions||!i.extensions[this.name])return null;const o=i.extensions[this.name],l=t.options.ktx2Loader;if(!l){if(n.extensionsRequired&&n.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,l)}}class AF{constructor(e){this.parser=e,this.name=Yn.EXT_TEXTURE_WEBP}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class SF{constructor(e){this.parser=e,this.name=Yn.EXT_TEXTURE_AVIF}loadTexture(e){const t=this.name,n=this.parser,i=n.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;const l=o.extensions[t],h=i.images[l.source];let d=n.textureLoader;if(h.uri){const p=n.options.manager.getHandler(h.uri);p!==null&&(d=p)}return n.loadTextureImage(e,l.source,d)}}class MF{constructor(e){this.name=Yn.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){const t=this.parser.json,n=t.bufferViews[e];if(n.extensions&&n.extensions[this.name]){const i=n.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),l=this.parser.options.meshoptDecoder;if(!l||!l.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(h){const d=i.byteOffset||0,p=i.byteLength||0,_=i.count,v=i.byteStride,y=new Uint8Array(h,d,p);return l.decodeGltfBufferAsync?l.decodeGltfBufferAsync(_,v,y,i.mode,i.filter).then(function(x){return x.buffer}):l.ready.then(function(){const x=new ArrayBuffer(_*v);return l.decodeGltfBuffer(new Uint8Array(x),_,v,y,i.mode,i.filter),x})})}else return null}}class bF{constructor(e){this.name=Yn.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){const t=this.parser.json,n=t.nodes[e];if(!n.extensions||!n.extensions[this.name]||n.mesh===void 0)return null;const i=t.meshes[n.mesh];for(const p of i.primitives)if(p.mode!==Gr.TRIANGLES&&p.mode!==Gr.TRIANGLE_STRIP&&p.mode!==Gr.TRIANGLE_FAN&&p.mode!==void 0)return null;const l=n.extensions[this.name].attributes,h=[],d={};for(const p in l)h.push(this.parser.getDependency("accessor",l[p]).then(_=>(d[p]=_,d[p])));return h.length<1?null:(h.push(this.parser.createNodeMesh(e)),Promise.all(h).then(p=>{const _=p.pop(),v=_.isGroup?_.children:[_],y=p[0].count,x=[];for(const b of v){const R=new ln,T=new Z,M=new ka,w=new Z(1,1,1),B=new sv(b.geometry,b.material,y);for(let L=0;L<y;L++)d.TRANSLATION&&T.fromBufferAttribute(d.TRANSLATION,L),d.ROTATION&&M.fromBufferAttribute(d.ROTATION,L),d.SCALE&&w.fromBufferAttribute(d.SCALE,L),B.setMatrixAt(L,R.compose(T,M,w));for(const L in d)if(L==="_COLOR_0"){const H=d[L];B.instanceColor=new Bc(H.array,H.itemSize,H.normalized)}else L!=="TRANSLATION"&&L!=="ROTATION"&&L!=="SCALE"&&b.geometry.setAttribute(L,d[L]);kn.prototype.copy.call(B,b),this.parser.assignFinalMaterial(B),x.push(B)}return _.isGroup?(_.clear(),_.add(...x),_):x[0]}))}}const uC="glTF",lm=12,fC={JSON:1313821514,BIN:5130562};class EF{constructor(e){this.name=Yn.KHR_BINARY_GLTF,this.content=null,this.body=null;const t=new DataView(e,0,lm),n=new TextDecoder;if(this.header={magic:n.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==uC)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");const i=this.header.length-lm,o=new DataView(e,lm);let l=0;for(;l<i;){const h=o.getUint32(l,!0);l+=4;const d=o.getUint32(l,!0);if(l+=4,d===fC.JSON){const p=new Uint8Array(e,lm+l,h);this.content=n.decode(p)}else if(d===fC.BIN){const p=lm+l;this.body=e.slice(p,p+h)}l+=h}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}}class TF{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Yn.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){const n=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,l=e.extensions[this.name].attributes,h={},d={},p={};for(const _ in l){const v=HS[_]||_.toLowerCase();h[v]=l[_]}for(const _ in e.attributes){const v=HS[_]||_.toLowerCase();if(l[_]!==void 0){const y=n.accessors[e.attributes[_]],x=jh[y.componentType];p[v]=x.name,d[v]=y.normalized===!0}}return t.getDependency("bufferView",o).then(function(_){return new Promise(function(v,y){i.decodeDracoFile(_,function(x){for(const b in x.attributes){const R=x.attributes[b],T=d[b];T!==void 0&&(R.normalized=T)}v(x)},h,p,Sa,y)})})}}class CF{constructor(){this.name=Yn.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}}class RF{constructor(){this.name=Yn.KHR_MESH_QUANTIZATION}}class hC extends Wu{constructor(e,t,n,i){super(e,t,n,i)}copySampleValue_(e){const t=this.resultBuffer,n=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let l=0;l!==i;l++)t[l]=n[o+l];return t}interpolate_(e,t,n,i){const o=this.resultBuffer,l=this.sampleValues,h=this.valueSize,d=h*2,p=h*3,_=i-t,v=(n-t)/_,y=v*v,x=y*v,b=e*p,R=b-p,T=-2*x+3*y,M=x-y,w=1-T,B=M-y+v;for(let L=0;L!==h;L++){const H=l[R+L+h],O=l[R+L+d]*_,z=l[b+L+h],V=l[b+L]*_;o[L]=w*H+B*O+T*z+M*V}return o}}const wF=new ka;class BF extends hC{interpolate_(e,t,n,i){const o=super.interpolate_(e,t,n,i);return wF.fromArray(o).normalize().toArray(o),o}}const Gr={POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6},jh={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},dC={9728:Hi,9729:Un,9984:rp,9985:wu,9986:_c,9987:$s},pC={33071:Fi,33648:Ru,10497:oo},FS={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},HS={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Gc={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},DF={CUBICSPLINE:void 0,LINEAR:xc,STEP:Du},PS={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function LF(s){return s.DefaultMaterial===void 0&&(s.DefaultMaterial=new qu({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:ao})),s.DefaultMaterial}function df(s,e,t){for(const n in t.extensions)s[n]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[n]=t.extensions[n])}function Jo(s,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(s.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function UF(s,e,t){let n=!1,i=!1,o=!1;for(let p=0,_=e.length;p<_;p++){const v=e[p];if(v.POSITION!==void 0&&(n=!0),v.NORMAL!==void 0&&(i=!0),v.COLOR_0!==void 0&&(o=!0),n&&i&&o)break}if(!n&&!i&&!o)return Promise.resolve(s);const l=[],h=[],d=[];for(let p=0,_=e.length;p<_;p++){const v=e[p];if(n){const y=v.POSITION!==void 0?t.getDependency("accessor",v.POSITION):s.attributes.position;l.push(y)}if(i){const y=v.NORMAL!==void 0?t.getDependency("accessor",v.NORMAL):s.attributes.normal;h.push(y)}if(o){const y=v.COLOR_0!==void 0?t.getDependency("accessor",v.COLOR_0):s.attributes.color;d.push(y)}}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d)]).then(function(p){const _=p[0],v=p[1],y=p[2];return n&&(s.morphAttributes.position=_),i&&(s.morphAttributes.normal=v),o&&(s.morphAttributes.color=y),s.morphTargetsRelative=!0,s})}function NF(s,e){if(s.updateMorphTargets(),e.weights!==void 0)for(let t=0,n=e.weights.length;t<n;t++)s.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){const t=e.extras.targetNames;if(s.morphTargetInfluences.length===t.length){s.morphTargetDictionary={};for(let n=0,i=t.length;n<i;n++)s.morphTargetDictionary[t[n]]=n}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function OF(s){let e;const t=s.extensions&&s.extensions[Yn.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+GS(t.attributes):e=s.indices+":"+GS(s.attributes)+":"+s.mode,s.targets!==void 0)for(let n=0,i=s.targets.length;n<i;n++)e+=":"+GS(s.targets[n]);return e}function GS(s){let e="";const t=Object.keys(s).sort();for(let n=0,i=t.length;n<i;n++)e+=t[n]+":"+s[t[n]]+";";return e}function zS(s){switch(s){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function IF(s){return s.search(/\.jpe?g($|\?)/i)>0||s.search(/^data\:image\/jpeg/)===0?"image/jpeg":s.search(/\.webp($|\?)/i)>0||s.search(/^data\:image\/webp/)===0?"image/webp":s.search(/\.ktx2($|\?)/i)>0||s.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}const FF=new ln;class HF{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new rF,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let n=!1,i=-1,o=!1,l=-1;if(typeof navigator<"u"){const h=navigator.userAgent;n=/^((?!chrome|android).)*safari/i.test(h)===!0;const d=h.match(/Version\/(\d+)/);i=n&&d?parseInt(d[1],10):-1,o=h.indexOf("Firefox")>-1,l=o?h.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||n&&i<17||o&&l<98?this.textureLoader=new dA(this.options.manager):this.textureLoader=new _A(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new La(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){const n=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(l){return l._markDefs&&l._markDefs()}),Promise.all(this._invokeAll(function(l){return l.beforeRoot&&l.beforeRoot()})).then(function(){return Promise.all([n.getDependencies("scene"),n.getDependencies("animation"),n.getDependencies("camera")])}).then(function(l){const h={scene:l[0][i.scene||0],scenes:l[0],animations:l[1],cameras:l[2],asset:i.asset,parser:n,userData:{}};return df(o,h,i),Jo(h,i),Promise.all(n._invokeAll(function(d){return d.afterRoot&&d.afterRoot(h)})).then(function(){for(const d of h.scenes)d.updateMatrixWorld();e(h)})}).catch(t)}_markDefs(){const e=this.json.nodes||[],t=this.json.skins||[],n=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){const l=t[i].joints;for(let h=0,d=l.length;h<d;h++)e[l[h]].isBone=!0}for(let i=0,o=e.length;i<o;i++){const l=e[i];l.mesh!==void 0&&(this._addNodeRef(this.meshCache,l.mesh),l.skin!==void 0&&(n[l.mesh].isSkinnedMesh=!0)),l.camera!==void 0&&this._addNodeRef(this.cameraCache,l.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,n){if(e.refs[t]<=1)return n;const i=n.clone(),o=(l,h)=>{const d=this.associations.get(l);d!=null&&this.associations.set(h,d);for(const[p,_]of l.children.entries())o(_,h.children[p])};return o(n,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){const t=Object.values(this.plugins);t.push(this);for(let n=0;n<t.length;n++){const i=e(t[n]);if(i)return i}return null}_invokeAll(e){const t=Object.values(this.plugins);t.unshift(this);const n=[];for(let i=0;i<t.length;i++){const o=e(t[i]);o&&n.push(o)}return n}getDependency(e,t){const n=e+":"+t;let i=this.cache.get(n);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(n,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){const n=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,l){return n.getDependency(e,l)})),this.cache.add(e,t)}return t}loadBuffer(e){const t=this.json.buffers[e],n=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[Yn.KHR_BINARY_GLTF].body);const i=this.options;return new Promise(function(o,l){n.load(yr.resolveURL(t.uri,i.path),o,void 0,function(){l(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){const t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(n){const i=t.byteLength||0,o=t.byteOffset||0;return n.slice(o,o+i)})}loadAccessor(e){const t=this,n=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){const l=FS[i.type],h=jh[i.componentType],d=i.normalized===!0,p=new h(i.count*l);return Promise.resolve(new Wn(p,l,d))}const o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(l){const h=l[0],d=FS[i.type],p=jh[i.componentType],_=p.BYTES_PER_ELEMENT,v=_*d,y=i.byteOffset||0,x=i.bufferView!==void 0?n.bufferViews[i.bufferView].byteStride:void 0,b=i.normalized===!0;let R,T;if(x&&x!==v){const M=Math.floor(y/x),w="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+M+":"+i.count;let B=t.cache.get(w);B||(R=new p(h,M*x,i.count*x/_),B=new Th(R,x/_),t.cache.add(w,B)),T=new Ul(B,d,y%x/_,b)}else h===null?R=new p(i.count*d):R=new p(h,y,i.count*d),T=new Wn(R,d,b);if(i.sparse!==void 0){const M=FS.SCALAR,w=jh[i.sparse.indices.componentType],B=i.sparse.indices.byteOffset||0,L=i.sparse.values.byteOffset||0,H=new w(l[1],B,i.sparse.count*M),O=new p(l[2],L,i.sparse.count*d);h!==null&&(T=new Wn(T.array.slice(),T.itemSize,T.normalized)),T.normalized=!1;for(let z=0,V=H.length;z<V;z++){const U=H[z];if(T.setX(U,O[z*d]),d>=2&&T.setY(U,O[z*d+1]),d>=3&&T.setZ(U,O[z*d+2]),d>=4&&T.setW(U,O[z*d+3]),d>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}T.normalized=b}return T})}loadTexture(e){const t=this.json,n=this.options,o=t.textures[e].source,l=t.images[o];let h=this.textureLoader;if(l.uri){const d=n.manager.getHandler(l.uri);d!==null&&(h=d)}return this.loadTextureImage(e,o,h)}loadTextureImage(e,t,n){const i=this,o=this.json,l=o.textures[e],h=o.images[t],d=(h.uri||h.bufferView)+":"+l.sampler;if(this.textureCache[d])return this.textureCache[d];const p=this.loadImageSource(t,n).then(function(_){_.flipY=!1,_.name=l.name||h.name||"",_.name===""&&typeof h.uri=="string"&&h.uri.startsWith("data:image/")===!1&&(_.name=h.uri);const y=(o.samplers||{})[l.sampler]||{};return _.magFilter=dC[y.magFilter]||Un,_.minFilter=dC[y.minFilter]||$s,_.wrapS=pC[y.wrapS]||oo,_.wrapT=pC[y.wrapT]||oo,_.generateMipmaps=!_.isCompressedTexture&&_.minFilter!==Hi&&_.minFilter!==Un,i.associations.set(_,{textures:e}),_}).catch(function(){return null});return this.textureCache[d]=p,p}loadImageSource(e,t){const n=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(v=>v.clone());const l=i.images[e],h=self.URL||self.webkitURL;let d=l.uri||"",p=!1;if(l.bufferView!==void 0)d=n.getDependency("bufferView",l.bufferView).then(function(v){p=!0;const y=new Blob([v],{type:l.mimeType});return d=h.createObjectURL(y),d});else if(l.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");const _=Promise.resolve(d).then(function(v){return new Promise(function(y,x){let b=y;t.isImageBitmapLoader===!0&&(b=function(R){const T=new oi(R);T.needsUpdate=!0,y(T)}),t.load(yr.resolveURL(v,o.path),b,void 0,x)})}).then(function(v){return p===!0&&h.revokeObjectURL(d),Jo(v,l),v.userData.mimeType=l.mimeType||IF(l.uri),v}).catch(function(v){throw console.error("THREE.GLTFLoader: Couldn't load texture",d),v});return this.sourceCache[e]=_,_}assignTexture(e,t,n,i){const o=this;return this.getDependency("texture",n.index).then(function(l){if(!l)return null;if(n.texCoord!==void 0&&n.texCoord>0&&(l=l.clone(),l.channel=n.texCoord),o.extensions[Yn.KHR_TEXTURE_TRANSFORM]){const h=n.extensions!==void 0?n.extensions[Yn.KHR_TEXTURE_TRANSFORM]:void 0;if(h){const d=o.associations.get(l);l=o.extensions[Yn.KHR_TEXTURE_TRANSFORM].extendTexture(l,h),o.associations.set(l,d)}}return i!==void 0&&(l.colorSpace=i),e[t]=l,l})}assignFinalMaterial(e){const t=e.geometry;let n=e.material;const i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,l=t.attributes.normal===void 0;if(e.isPoints){const h="PointsMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new Fp,ra.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,d.sizeAttenuation=!1,this.cache.add(h,d)),n=d}else if(e.isLine){const h="LineBasicMaterial:"+n.uuid;let d=this.cache.get(h);d||(d=new as,ra.prototype.copy.call(d,n),d.color.copy(n.color),d.map=n.map,this.cache.add(h,d)),n=d}if(i||o||l){let h="ClonedMaterial:"+n.uuid+":";i&&(h+="derivative-tangents:"),o&&(h+="vertex-colors:"),l&&(h+="flat-shading:");let d=this.cache.get(h);d||(d=n.clone(),o&&(d.vertexColors=!0),l&&(d.flatShading=!0),i&&(d.normalScale&&(d.normalScale.y*=-1),d.clearcoatNormalScale&&(d.clearcoatNormalScale.y*=-1)),this.cache.add(h,d),this.associations.set(d,this.associations.get(n))),n=d}e.material=n}getMaterialType(){return qu}loadMaterial(e){const t=this,n=this.json,i=this.extensions,o=n.materials[e];let l;const h={},d=o.extensions||{},p=[];if(d[Yn.KHR_MATERIALS_UNLIT]){const v=i[Yn.KHR_MATERIALS_UNLIT];l=v.getMaterialType(),p.push(v.extendParams(h,o,t))}else{const v=o.pbrMetallicRoughness||{};if(h.color=new wt(1,1,1),h.opacity=1,Array.isArray(v.baseColorFactor)){const y=v.baseColorFactor;h.color.setRGB(y[0],y[1],y[2],Sa),h.opacity=y[3]}v.baseColorTexture!==void 0&&p.push(t.assignTexture(h,"map",v.baseColorTexture,sa)),h.metalness=v.metallicFactor!==void 0?v.metallicFactor:1,h.roughness=v.roughnessFactor!==void 0?v.roughnessFactor:1,v.metallicRoughnessTexture!==void 0&&(p.push(t.assignTexture(h,"metalnessMap",v.metallicRoughnessTexture)),p.push(t.assignTexture(h,"roughnessMap",v.metallicRoughnessTexture))),l=this._invokeOne(function(y){return y.getMaterialType&&y.getMaterialType(e)}),p.push(Promise.all(this._invokeAll(function(y){return y.extendMaterialParams&&y.extendMaterialParams(e,h)})))}o.doubleSided===!0&&(h.side=hr);const _=o.alphaMode||PS.OPAQUE;if(_===PS.BLEND?(h.transparent=!0,h.depthWrite=!1):(h.transparent=!1,_===PS.MASK&&(h.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&l!==Da&&(p.push(t.assignTexture(h,"normalMap",o.normalTexture)),h.normalScale=new et(1,1),o.normalTexture.scale!==void 0)){const v=o.normalTexture.scale;h.normalScale.set(v,v)}if(o.occlusionTexture!==void 0&&l!==Da&&(p.push(t.assignTexture(h,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(h.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&l!==Da){const v=o.emissiveFactor;h.emissive=new wt().setRGB(v[0],v[1],v[2],Sa)}return o.emissiveTexture!==void 0&&l!==Da&&p.push(t.assignTexture(h,"emissiveMap",o.emissiveTexture,sa)),Promise.all(p).then(function(){const v=new l(h);return o.name&&(v.name=o.name),Jo(v,o),t.associations.set(v,{materials:e}),o.extensions&&df(i,v,o),v})}createUniqueName(e){const t=$n.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){const t=this,n=this.extensions,i=this.primitiveCache;function o(h){return n[Yn.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(h,t).then(function(d){return mC(d,h,t)})}const l=[];for(let h=0,d=e.length;h<d;h++){const p=e[h],_=OF(p),v=i[_];if(v)l.push(v.promise);else{let y;p.extensions&&p.extensions[Yn.KHR_DRACO_MESH_COMPRESSION]?y=o(p):y=mC(new yn,p,t),i[_]={primitive:p,promise:y},l.push(y)}}return Promise.all(l)}loadMesh(e){const t=this,n=this.json,i=this.extensions,o=n.meshes[e],l=o.primitives,h=[];for(let d=0,p=l.length;d<p;d++){const _=l[d].material===void 0?LF(this.cache):this.getDependency("material",l[d].material);h.push(_)}return h.push(t.loadGeometries(l)),Promise.all(h).then(function(d){const p=d.slice(0,d.length-1),_=d[d.length-1],v=[];for(let x=0,b=_.length;x<b;x++){const R=_[x],T=l[x];let M;const w=p[x];if(T.mode===Gr.TRIANGLES||T.mode===Gr.TRIANGLE_STRIP||T.mode===Gr.TRIANGLE_FAN||T.mode===void 0)M=o.isSkinnedMesh===!0?new iv(R,w):new Li(R,w),M.isSkinnedMesh===!0&&M.normalizeSkinWeights(),T.mode===Gr.TRIANGLE_STRIP?M.geometry=cC(M.geometry,gp):T.mode===Gr.TRIANGLE_FAN&&(M.geometry=cC(M.geometry,Nu));else if(T.mode===Gr.LINES)M=new Ir(R,w);else if(T.mode===Gr.LINE_STRIP)M=new Vo(R,w);else if(T.mode===Gr.LINE_LOOP)M=new pv(R,w);else if(T.mode===Gr.POINTS)M=new vv(R,w);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+T.mode);Object.keys(M.geometry.morphAttributes).length>0&&NF(M,o),M.name=t.createUniqueName(o.name||"mesh_"+e),Jo(M,o),T.extensions&&df(i,M,T),t.assignFinalMaterial(M),v.push(M)}for(let x=0,b=v.length;x<b;x++)t.associations.set(v[x],{meshes:e,primitives:x});if(v.length===1)return o.extensions&&df(i,v[0],o),v[0];const y=new Nr;o.extensions&&df(i,y,o),t.associations.set(y,{meshes:e});for(let x=0,b=v.length;x<b;x++)y.add(v[x]);return y})}loadCamera(e){let t;const n=this.json.cameras[e],i=n[n.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return n.type==="perspective"?t=new ba(R0.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):n.type==="orthographic"&&(t=new Hl(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),n.name&&(t.name=this.createUniqueName(n.name)),Jo(t,n),Promise.resolve(t)}loadSkin(e){const t=this.json.skins[e],n=[];for(let i=0,o=t.joints.length;i<o;i++)n.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?n.push(this.getDependency("accessor",t.inverseBindMatrices)):n.push(null),Promise.all(n).then(function(i){const o=i.pop(),l=i,h=[],d=[];for(let p=0,_=l.length;p<_;p++){const v=l[p];if(v){h.push(v);const y=new ln;o!==null&&y.fromArray(o.array,p*16),d.push(y)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[p])}return new Dh(h,d)})}loadAnimation(e){const t=this.json,n=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,l=[],h=[],d=[],p=[],_=[];for(let v=0,y=i.channels.length;v<y;v++){const x=i.channels[v],b=i.samplers[x.sampler],R=x.target,T=R.node,M=i.parameters!==void 0?i.parameters[b.input]:b.input,w=i.parameters!==void 0?i.parameters[b.output]:b.output;R.node!==void 0&&(l.push(this.getDependency("node",T)),h.push(this.getDependency("accessor",M)),d.push(this.getDependency("accessor",w)),p.push(b),_.push(R))}return Promise.all([Promise.all(l),Promise.all(h),Promise.all(d),Promise.all(p),Promise.all(_)]).then(function(v){const y=v[0],x=v[1],b=v[2],R=v[3],T=v[4],M=[];for(let B=0,L=y.length;B<L;B++){const H=y[B],O=x[B],z=b[B],V=R[B],U=T[B];if(H===void 0)continue;H.updateMatrix&&H.updateMatrix();const I=n._createAnimationTracks(H,O,z,V,U);if(I)for(let W=0;W<I.length;W++)M.push(I[W])}const w=new Qu(o,void 0,M);return Jo(w,i),w})}createNodeMesh(e){const t=this.json,n=this,i=t.nodes[e];return i.mesh===void 0?null:n.getDependency("mesh",i.mesh).then(function(o){const l=n._getNodeRef(n.meshCache,i.mesh,o);return i.weights!==void 0&&l.traverse(function(h){if(h.isMesh)for(let d=0,p=i.weights.length;d<p;d++)h.morphTargetInfluences[d]=i.weights[d]}),l})}loadNode(e){const t=this.json,n=this,i=t.nodes[e],o=n._loadNodeShallow(e),l=[],h=i.children||[];for(let p=0,_=h.length;p<_;p++)l.push(n.getDependency("node",h[p]));const d=i.skin===void 0?Promise.resolve(null):n.getDependency("skin",i.skin);return Promise.all([o,Promise.all(l),d]).then(function(p){const _=p[0],v=p[1],y=p[2];y!==null&&_.traverse(function(x){x.isSkinnedMesh&&x.bind(y,FF)});for(let x=0,b=v.length;x<b;x++)_.add(v[x]);return _})}_loadNodeShallow(e){const t=this.json,n=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];const o=t.nodes[e],l=o.name?i.createUniqueName(o.name):"",h=[],d=i._invokeOne(function(p){return p.createNodeMesh&&p.createNodeMesh(e)});return d&&h.push(d),o.camera!==void 0&&h.push(i.getDependency("camera",o.camera).then(function(p){return i._getNodeRef(i.cameraCache,o.camera,p)})),i._invokeAll(function(p){return p.createNodeAttachment&&p.createNodeAttachment(e)}).forEach(function(p){h.push(p)}),this.nodeCache[e]=Promise.all(h).then(function(p){let _;if(o.isBone===!0?_=new Lp:p.length>1?_=new Nr:p.length===1?_=p[0]:_=new kn,_!==p[0])for(let v=0,y=p.length;v<y;v++)_.add(p[v]);if(o.name&&(_.userData.name=o.name,_.name=l),Jo(_,o),o.extensions&&df(n,_,o),o.matrix!==void 0){const v=new ln;v.fromArray(o.matrix),_.applyMatrix4(v)}else o.translation!==void 0&&_.position.fromArray(o.translation),o.rotation!==void 0&&_.quaternion.fromArray(o.rotation),o.scale!==void 0&&_.scale.fromArray(o.scale);if(!i.associations.has(_))i.associations.set(_,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){const v=i.associations.get(_);i.associations.set(_,{...v})}return i.associations.get(_).nodes=e,_}),this.nodeCache[e]}loadScene(e){const t=this.extensions,n=this.json.scenes[e],i=this,o=new Nr;n.name&&(o.name=i.createUniqueName(n.name)),Jo(o,n),n.extensions&&df(t,o,n);const l=n.nodes||[],h=[];for(let d=0,p=l.length;d<p;d++)h.push(i.getDependency("node",l[d]));return Promise.all(h).then(function(d){for(let _=0,v=d.length;_<v;_++)o.add(d[_]);const p=_=>{const v=new Map;for(const[y,x]of i.associations)(y instanceof ra||y instanceof oi)&&v.set(y,x);return _.traverse(y=>{const x=i.associations.get(y);x!=null&&v.set(y,x)}),v};return i.associations=p(o),o})}_createAnimationTracks(e,t,n,i,o){const l=[],h=e.name?e.name:e.uuid,d=[];Gc[o.path]===Gc.weights?e.traverse(function(y){y.morphTargetInfluences&&d.push(y.name?y.name:y.uuid)}):d.push(h);let p;switch(Gc[o.path]){case Gc.weights:p=Nl;break;case Gc.rotation:p=Ol;break;case Gc.translation:case Gc.scale:p=Il;break;default:n.itemSize===1?p=Nl:p=Il;break}const _=i.interpolation!==void 0?DF[i.interpolation]:xc,v=this._getArrayFromAccessor(n);for(let y=0,x=d.length;y<x;y++){const b=new p(d[y]+"."+Gc[o.path],t.array,v,_);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(b),l.push(b)}return l}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){const n=zS(t.constructor),i=new Float32Array(t.length);for(let o=0,l=t.length;o<l;o++)i[o]=t[o]*n;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(n){const i=this instanceof Ol?BF:hC;return new i(this.times,this.values,this.getValueSize()/3,n)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}}function PF(s,e,t){const n=e.attributes,i=new Xa;if(n.POSITION!==void 0){const h=t.json.accessors[n.POSITION],d=h.min,p=h.max;if(d!==void 0&&p!==void 0){if(i.set(new Z(d[0],d[1],d[2]),new Z(p[0],p[1],p[2])),h.normalized){const _=zS(jh[h.componentType]);i.min.multiplyScalar(_),i.max.multiplyScalar(_)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;const o=e.targets;if(o!==void 0){const h=new Z,d=new Z;for(let p=0,_=o.length;p<_;p++){const v=o[p];if(v.POSITION!==void 0){const y=t.json.accessors[v.POSITION],x=y.min,b=y.max;if(x!==void 0&&b!==void 0){if(d.setX(Math.max(Math.abs(x[0]),Math.abs(b[0]))),d.setY(Math.max(Math.abs(x[1]),Math.abs(b[1]))),d.setZ(Math.max(Math.abs(x[2]),Math.abs(b[2]))),y.normalized){const R=zS(jh[y.componentType]);d.multiplyScalar(R)}h.max(d)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(h)}s.boundingBox=i;const l=new Ba;i.getCenter(l.center),l.radius=i.min.distanceTo(i.max)/2,s.boundingSphere=l}function mC(s,e,t){const n=e.attributes,i=[];function o(l,h){return t.getDependency("accessor",l).then(function(d){s.setAttribute(h,d)})}for(const l in n){const h=HS[l]||l.toLowerCase();h in s.attributes||i.push(o(n[l],h))}if(e.indices!==void 0&&!s.index){const l=t.getDependency("accessor",e.indices).then(function(h){s.setIndex(h)});i.push(l)}return Hn.workingColorSpace!==Sa&&"COLOR_0"in n&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Hn.workingColorSpace}" not supported.`),Jo(s,e),PF(s,e,t),Promise.all(i).then(function(){return e.targets!==void 0?UF(s,e.targets,t):s})}const Zh="https://ai.streamoji.com",ca=(...s)=>{},GF=(...s)=>{},gC=({analyser:s})=>{const e=me.useRef(null),t=me.useRef(null);return me.useEffect(()=>{const n=e.current;if(!n)return;const i=n.getContext("2d",{alpha:!0});if(!i)return;let o,l=null;s&&(s.fftSize=128,l=new Uint8Array(s.frequencyBinCount));const h=()=>{o=requestAnimationFrame(h),(n.width!==n.offsetWidth||n.height!==n.offsetHeight)&&(n.width=n.offsetWidth,n.height=n.offsetHeight);const d=n.width,p=n.height;if(d===0||p===0)return;const _=p/2;i.clearRect(0,0,d,p),i.fillStyle="#1e293b";const v=2,x=v+2,b=d*.95,R=Math.floor(b/x);(!t.current||t.current.length!==R)&&(t.current=new Float32Array(R).fill(2));const T=R*x,M=(d-T)/2;s&&l&&s.getByteFrequencyData(l);const w=l?l.length:0,L=Math.floor(w*.7)/R,H=new Float32Array(R);for(let O=0;O<R;O++){let z=0;if(l&&L>0){const I=Math.floor(O*L),W=Math.floor((O+1)*L);for(let ne=I;ne<W;ne++){const ee=l[ne]||0;ee>z&&(z=ee)}}z<10&&(z=0);const V=z/255,U=z>0?Math.max(2,Math.pow(V,1.4)*p*.25):2;H[O]=U}for(let O=0;O<R;O++){const z=R-1-O,V=Math.max(H[O],H[z]),U=t.current[O]+(V-t.current[O])*.3;t.current[O]=U;const I=M+O*x,W=_-U/2;i.beginPath(),i.roundRect?i.roundRect(I,W,v,U,4):i.fillRect(I,W,v,U),i.fill()}};return h(),()=>{cancelAnimationFrame(o)}},[s]),Yt.jsx("canvas",{ref:e,style:{width:"100%",height:"100%",display:"block"}})},zF="https://pub-48df6f7d60d6440bbd01676ea5d90e55.r2.dev",vC="https://pub-be53cae7bd99457a8c1f11b4d38f1672.r2.dev/default-models/avatar-blue-suit.glb";function VF(s){const[e,t]=me.useState(null);return me.useEffect(()=>{if(!s){t(null);return}let n=!1;const i=`${zF}/${s}.glb`;return fetch(i,{method:"HEAD"}).then(o=>{n||t(o.ok?i:vC)}).catch(()=>{n||t(vC)}),()=>{n=!0}},[s]),e}const kF=["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"],XF=["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"],YF=[{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"}],JF=["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"],qF=["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"],KF={zoom:.85,position:[.15,-.8,0],scale:1.5,rotation:[.15,.02,0]},WF=[-.45,1.9,.1],jF=[-.45,1.75,.1],ZF={browInnerUp:.2},VS=.18,QF=1,$F=.5,_C=3,__=.55,kS=.12,yC=2,xC=2,y_=4,AC=8,e4=1,SC=.38,MC=.32,bC="__branding__",x_={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}},t4=[{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:{}}],n4={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 i4(s){if(!s)return[{v:"sil",w:1}];const e=s.toLowerCase();return n4[e]??[{v:"sil",w:1}]}function a4({target:s}){const{camera:e}=kh();return me.useEffect(()=>{e.lookAt(...s)},[e,s]),null}function fn(s,e,t){if(!s||!s.morphTargetDictionary)return;const n=s,i=n.morphTargetDictionary,o=n.morphTargetInfluences;if(o)for(const l in i)l.toLowerCase()===e.toLowerCase()&&(o[i[l]]=t)}function XS(s,e=.97){if(!s)return;const t=s;if(t.morphTargetInfluences)for(let n=0;n<t.morphTargetInfluences.length;n++)t.morphTargetInfluences[n]*=e}const s4=me.memo(({avatarUrl:s,isPlayingRef:e,visemeQueueRef:t,audioContextRef:n,responseAudioStartTimeRef:i,adjustments:o,mood:l,expression:h,agentResponse:d,isSpeaking:p,nextStartTimeRef:_,stopPlayback:v,setIsSpeaking:y,expressionUrl:x,onExpressionFinished:b,isNudgeResponse:R,avatarGender:T})=>{const{scene:M}=Kh(s),B=Kh(T==="female"?XF:kF),L=me.useMemo(()=>B.flatMap(Lt=>Lt.animations),[B]),O=Kh(T==="female"?qF:JF),z=me.useMemo(()=>O.flatMap(Lt=>Lt.animations),[O]),V=me.useRef(null),U=me.useRef(null),I=me.useRef(null),W=me.useRef(null),ne=me.useRef(null),ee=me.useRef(null),ae=me.useRef([]),[he]=me.useState(()=>new lE(M)),F=me.useRef({}),Y=me.useRef(null),$=me.useRef(0),_e=me.useRef(!1),ve=me.useRef(0),K=me.useRef(!1),se=me.useRef(null),be=me.useRef(_C),Ie=me.useRef(-1),at=me.useRef("left"),ge=me.useRef(y_+Math.random()*(AC-y_)),Te=me.useRef(0),nt=me.useRef("smile");me.useEffect(()=>{if(!(!L||!M)){if(L.forEach((Lt,mt)=>{const ye=`idle_${mt}`;if(!F.current[ye]){const xe=he.clipAction(Lt,M);xe.name=ye,xe.setLoop(pp,1),xe.clampWhenFinished=!0,F.current[ye]=xe}}),z.forEach((Lt,mt)=>{const ye=`talk_${mt}`;if(!F.current[ye]){const xe=he.clipAction(Lt,M);xe.name=ye,xe.setLoop(pp,1),xe.clampWhenFinished=!0,F.current[ye]=xe}}),L.length>0){const Lt=F.current.idle_0,mt=Y.current&&he.existingAction(Y.current.getClip());Lt&&!mt&&(Lt.reset().fadeIn(.5).play(),Y.current=Lt)}return()=>{he.stopAllAction(),F.current={},Y.current=null}}},[L,z,M,he]);const Et=me.useRef("");me.useEffect(()=>{if(!x||!M||x===Et.current)return;Et.current=x,se.current=x,new sF().load(x,mt=>{if(mt.animations&&mt.animations.length>0){const ye=mt.animations[0],xe=he.clipAction(ye,M);if(xe.name=`EXPR_${x}`,xe.setLoop(pp,1),xe.clampWhenFinished=!0,F.current[`EXPR_${x}`]=xe,p&&se.current===x){const we=Y.current;xe.reset().fadeIn(.3).play(),we&&we!==xe&&we.crossFadeTo(xe,.3,!0),Y.current=xe,se.current=null}}},void 0,mt=>{console.error(`[ANIMATION] Failed to load ${x}`,mt)})},[x,M,he,p]),me.useEffect(()=>{const Lt=mt=>{const ye=mt.action,xe=ye.name||"";if(xe.startsWith("idle_")){const tt=(parseInt(xe.split("_")[1])+1)%L.length,Q=F.current[`idle_${tt}`];Q&&(Q.reset().fadeIn(.5).play(),ye.crossFadeTo(Q,.5,!0),Y.current=Q)}else if(xe.startsWith("EXPR_")){if(p){const we=Math.floor(Math.random()*z.length),tt=F.current[`talk_${we}`];tt&&(tt.reset().fadeIn(.5).play(),ye.crossFadeTo(tt,.5,!0),Y.current=tt)}else{const we=F.current.idle_0;we&&(we.reset().fadeIn(.5).play(),ye.crossFadeTo(we,.5,!0),Y.current=we)}b&&b()}else if(xe.startsWith("talk_"))if(p&&!R){const tt=(parseInt(xe.split("_")[1])+1)%z.length,Q=F.current[`talk_${tt}`];Q&&(Q.reset().fadeIn(.3).play(),ye.crossFadeTo(Q,.3,!0),Y.current=Q)}else{const we=F.current.idle_0;we&&(we.reset().fadeIn(.5).play(),ye.crossFadeTo(we,.5,!0),Y.current=we)}};return he.addEventListener("finished",Lt),()=>he.removeEventListener("finished",Lt)},[he,L,z,p,R,b]),me.useEffect(()=>{if(p&&M){const Lt=Y.current,mt=Lt?.name||"";if(mt.startsWith("idle_")||mt.startsWith("talk_")||mt===""){const ye=se.current;if(ye){const xe=F.current[`EXPR_${ye}`];if(xe){xe.reset().fadeIn(.3).play(),Lt&&Lt!==xe&&Lt.crossFadeTo(xe,.3,!0),Y.current=xe,se.current=null;return}}if(mt.startsWith("idle_")||mt===""){const xe=Math.floor(Math.random()*z.length),we=F.current[`talk_${xe}`];we&&(we.reset().fadeIn(.5).play(),Lt&&Lt.crossFadeTo(we,.5,!0),Y.current=we)}}}else if(!p&&M){const Lt=Y.current,mt=Lt?.name||"";if(mt.startsWith("talk_")||mt.startsWith("EXPR_")){const ye=F.current.idle_0;ye&&(ye.reset().fadeIn(.5).play(),Lt&&Lt.crossFadeTo(ye,.5,!0),Y.current=ye)}}},[p,M,x]),me.useEffect(()=>{if(!M)return;M.traverse(ye=>{if(ye.isMesh&&ye.morphTargetDictionary){const xe=ye.name.toLowerCase();(xe.includes("head")||xe.includes("avatar"))&&(U.current=ye,ca(`[ANIMATION] Found head mesh: ${ye.name}`)),xe.includes("teeth")&&(I.current=ye,ca(`[ANIMATION] Found teeth mesh: ${ye.name}`)),xe.includes("beard")&&(W.current=ye,ca(`[ANIMATION] Found beard mesh: ${ye.name}`)),xe.includes("eyeleft")&&(ne.current=ye,ca(`[ANIMATION] Found eye left mesh: ${ye.name}`)),xe.includes("eyeright")&&(ee.current=ye,ca(`[ANIMATION] Found eye right mesh: ${ye.name}`))}});const Lt=U.current?.morphTargetDictionary;Lt&&Object.keys(Lt).filter(ye=>ye.toLowerCase().includes("brow"));const mt=[];M.traverse(ye=>{if(ye.isMesh){const we=ye.morphTargetDictionary;we&&Object.keys(we).some(tt=>tt.toLowerCase().includes("brow"))&&mt.push(ye)}}),ae.current=mt,mt.length>0&&ca("[ANIMATION] Meshes with brow morphs:",mt.length)},[M]);const Bt=(Lt,mt=1)=>{const ye=`viseme_${Lt}`.toLowerCase(),xe=t4.find(we=>we.key.toLowerCase()===ye);if(xe){for(const we in xe.mix){const tt=xe.mix[we]*mt;fn(U.current,we,tt),fn(W.current,we,tt),(!xe.teethMix||!(we in xe.teethMix))&&fn(I.current,we,tt)}if(xe.teethMix)for(const we in xe.teethMix){const tt=xe.teethMix[we]*mt;fn(I.current,we,tt)}}},un=Lt=>{const mt=x_[Lt]??x_.neutral;for(const ye in mt)fn(U.current,ye,mt[ye]),fn(I.current,ye,mt[ye]),fn(W.current,ye,mt[ye])};return bT((Lt,mt)=>{const ye=Math.pow(.88,60*mt);XS(U.current,ye),XS(I.current,ye),XS(W.current,ye),un(l);const xe=Lt.clock.elapsedTime;let we=0;if(Math.floor(xe)%5===0&&Math.floor((xe-mt)%5)!==0){let kt=null;M.traverse(Tn=>{Tn.name.toLowerCase().includes("hips")&&(kt=Tn)});const an=kt?`Hips Y: ${kt.position.y.toFixed(4)}`:"Hips not found";ca(`[ANIMATION] Mixer Time: ${he.time.toFixed(2)}, ${an}`)}if(he.update(mt),xe>$.current&&!_e.current&&(_e.current=!0,ve.current=xe),_e.current){const kt=p?.2:.3,an=(xe-ve.current)/kt;if(an>=1)if(_e.current=!1,K.current){const Tn=p?1:2.5;$.current=xe+Tn,K.current=!1}else $.current=xe+.12,K.current=!0;else{const Tn=an<.5?an*2:(1-an)*2;fn(U.current,"eyeBlinkLeft",Tn),fn(U.current,"eyeBlinkRight",Tn),fn(I.current,"eyeBlinkLeft",Tn),fn(I.current,"eyeBlinkRight",Tn),fn(W.current,"eyeBlinkLeft",Tn),fn(W.current,"eyeBlinkRight",Tn),we=Tn*ZF.browInnerUp}}const tt=x_[l]??x_.neutral,Q=tt.browInnerUp??0,Kt=tt.browOuterUpLeft??0,vt=tt.browOuterUpRight??0,Nt=xe*QF,yt=VS*Math.sin(Nt),j=VS*.7*Math.sin(Nt+.7),P=VS*.7*Math.sin(Nt+1.3),ie=kt=>Math.max(0,Math.min(1,kt)),Fe=ie(Q+yt),Ye=ie(Kt+j),Ne=ie(vt+P),Ht=ie(Fe+we);fn(U.current,"browInnerUp",Ht),fn(I.current,"browInnerUp",Ht),fn(W.current,"browInnerUp",Ht),fn(U.current,"browOuterUpLeft",Ye),fn(I.current,"browOuterUpLeft",Ye),fn(W.current,"browOuterUpLeft",Ye),fn(U.current,"browOuterUpRight",Ne),fn(I.current,"browOuterUpRight",Ne),fn(W.current,"browOuterUpRight",Ne);const _t=be.current,Ot=_t+__,Jt=Ot+kS;xe>Jt&&(be.current+=__+kS+_C);const Ve=!p&&xe>=_t&&xe<Ot,Je=!p&&xe>=Ot&&xe<Jt;(Ve||Je)&&Ie.current!==_t&&(Ie.current=_t,at.current=Math.random()<.7?"left":"up");const Rt=Ve?xe-_t:Je?__:0,pt=Ve||Je?Math.min(1,Rt/__):0,st=pt<=0?0:Math.sin(pt*Math.PI),qt=Je?1-(xe-Ot)/kS:1,de=Ve?st:Je?st*qt:0,Be=$F*de,ze=kt=>tt[kt]??0;if(at.current==="up"?(fn(ne.current,"eyeLookUpLeft",ie(ze("eyeLookUpLeft")+Be)),fn(ne.current,"eyeLookDownLeft",ie(ze("eyeLookDownLeft"))),fn(ne.current,"eyeLookOutLeft",ie(ze("eyeLookOutLeft"))),fn(ne.current,"eyeLookInLeft",ie(ze("eyeLookInLeft"))),fn(ee.current,"eyeLookUpRight",ie(ze("eyeLookUpRight")+Be)),fn(ee.current,"eyeLookDownRight",ie(ze("eyeLookDownRight"))),fn(ee.current,"eyeLookOutRight",ie(ze("eyeLookOutRight"))),fn(ee.current,"eyeLookInRight",ie(ze("eyeLookInRight")))):(fn(ne.current,"eyeLookUpLeft",ie(ze("eyeLookUpLeft"))),fn(ne.current,"eyeLookDownLeft",ie(ze("eyeLookDownLeft"))),fn(ne.current,"eyeLookOutLeft",ie(ze("eyeLookOutLeft"))),fn(ne.current,"eyeLookInLeft",ie(ze("eyeLookInLeft")+Be)),fn(ee.current,"eyeLookUpRight",ie(ze("eyeLookUpRight"))),fn(ee.current,"eyeLookDownRight",ie(ze("eyeLookDownRight"))),fn(ee.current,"eyeLookOutRight",ie(ze("eyeLookOutRight")+Be)),fn(ee.current,"eyeLookInRight",ie(ze("eyeLookInRight")))),!p&&xe>=ge.current){Te.current=xe,nt.current=Math.random()<.5?"pucker":"smile";const kt=nt.current==="pucker"?xC:yC;ge.current=xe+kt+y_+Math.random()*(AC-y_)}const St=nt.current==="pucker"?xC:yC,Ke=!p&&xe>=Te.current&&xe<Te.current+St,ke=Ke?(xe-Te.current)/St:0,ft=ke<=0?0:ke<.5?ke*2:(()=>{const kt=(ke-.5)*2;return 1-kt*kt*(3-2*kt)})(),jt=kt=>tt[kt]??0;if(Ke)if(nt.current==="pucker"){const kt=ie(jt("mouthPucker")+e4*ft);fn(U.current,"mouthPucker",kt),fn(I.current,"mouthPucker",kt),fn(W.current,"mouthPucker",kt)}else{const kt=ie(jt("mouthSmileLeft")+SC*ft),an=ie(jt("mouthSmileRight")+SC*ft),Tn=ie(jt("mouthDimpleLeft")+MC*ft),wi=ie(jt("mouthDimpleRight")+MC*ft);fn(U.current,"mouthSmileLeft",kt),fn(U.current,"mouthSmileRight",an),fn(U.current,"mouthDimpleLeft",Tn),fn(U.current,"mouthDimpleRight",wi),fn(I.current,"mouthSmileLeft",kt),fn(I.current,"mouthSmileRight",an),fn(I.current,"mouthDimpleLeft",Tn),fn(I.current,"mouthDimpleRight",wi),fn(W.current,"mouthSmileLeft",kt),fn(W.current,"mouthSmileRight",an),fn(W.current,"mouthDimpleLeft",Tn),fn(W.current,"mouthDimpleRight",wi)}if(V.current){const kt=e.current?0:o.rotation[1];V.current.rotation.y=R0.lerp(V.current.rotation.y,kt,.1),V.current.position.set(...o.position),V.current.scale.setScalar(o.scale),V.current.rotation.x=o.rotation[0],V.current.rotation.z=o.rotation[2]}if(e.current&&n.current){const kt=n.current.currentTime,wi=(kt-i.current)*1e3- -150;for(let ua=0;ua<t.current.length;ua++){const zi=t.current[ua];wi>=zi.vtime&&wi<zi.vtime+zi.vduration&&Bt(zi.viseme,zi.weight??1)}kt>_.current+.5&&(v(),y(!1))}}),Yt.jsx("group",{ref:V,children:Yt.jsx("primitive",{object:M})})});function r4(s){return s?s.charAt(0).toUpperCase()+s.slice(1).toLowerCase():""}function EC(s){return s.replace(/\*(.*?)\*/g," $1 ").replace(/\[.*?\]/g," ").replace(/<.*?\/>/g," ").replace(/<.*?>.*?<\/.*?>/g," ").replace(/\s+/g," ").trim()}const YS=new Map,o4=({onNavigationRequested:s,agentId:e,presetUserDetails:t,onAvatarReady:n})=>{const[i,o]=me.useState(""),[l,h]=me.useState("male"),[d,p]=me.useState(""),[_,v]=me.useState(!1),y=i,x=l;me.useEffect(()=>{if(!e){v(!0);return}let Ue=!1;return(async()=>{console.log(">> fetchConfig RUNNING for",e);try{const ut=`agent_config_${e}`,Tt=sessionStorage.getItem(ut);if(Tt)try{const Pt=JSON.parse(Tt);Ue||(Pt.encryptedAgentToken&&o(Pt.encryptedAgentToken),Pt.avatarGender&&h(Pt.avatarGender),Pt.agent_id&&p(Pt.agent_id),v(!0));return}catch(Pt){console.error("Failed to parse cached avatar config:",Pt),sessionStorage.removeItem(ut)}let Mt;if(YS.has(e))console.log(">> REUSING in-flight fetch for",e),Mt=await YS.get(e);else{const Pt=(async()=>{console.log(">> INITIATING visitedWebsite fetch for",e);const Mn={agentId:e},On=await fetch(`${Zh}/visitedWebsite`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Mn)});if(!On.ok)throw new Error(`Fetch failed: ${On.status}`);const In=await On.json();return sessionStorage.setItem(ut,JSON.stringify(In)),In})();YS.set(e,Pt),Mt=await Pt}if(Ue)return;Mt&&(Mt.encryptedAgentToken&&o(Mt.encryptedAgentToken),Mt.avatarGender&&h(Mt.avatarGender),Mt.agent_id&&p(Mt.agent_id))}catch(ut){console.error("Failed to fetch avatar config:",ut)}finally{Ue||v(!0)}})(),()=>{Ue=!0}},[e]);const b=VF(e??d),[R,T]=me.useState(""),[M,w]=me.useState(""),[B,L]=me.useState("Ready"),[H,O]=me.useState(!1),[z,V]=me.useState(!1),[U,I]=me.useState([]),[W,ne]=me.useState(""),ee=me.useRef(null),[ae,he]=me.useState(()=>typeof window<"u"?window.matchMedia("(max-width: 480px)").matches:!1);me.useEffect(()=>{const Ue=window.matchMedia("(max-width: 480px)"),ct=()=>he(Ue.matches);return Ue.addEventListener("change",ct),()=>Ue.removeEventListener("change",ct)},[]);const F=ae?80:600,Y=me.useRef(!1),$=me.useRef([]),_e=me.useRef(0),ve=me.useRef(!1),K=me.useRef([]),se=me.useRef(null),be=me.useRef([]);me.useRef([]);const Ie=me.useRef([]),at=me.useRef(0),ge=me.useRef(0),Te=me.useRef(0),nt=me.useRef(0),Et=me.useRef(!1),[Bt,un]=me.useState(null),Lt=me.useRef(null),[mt,ye]=me.useState("neutral"),[xe,we]=me.useState(""),[tt,Q]=me.useState(""),[Kt,vt]=me.useState("Chat with us"),[Nt,yt]=me.useState(null),[j,P]=me.useState("hidden"),[ie,Fe]=me.useState(""),Ye=me.useRef(null),Ne=me.useRef(j);Ne.current=j;const[Ht,_t]=me.useState(null),Ot=me.useRef(null),Jt=me.useRef(null),[Ve,Je]=me.useState(!1),Rt=me.useRef(null),[pt,st]=me.useState("hidden"),[qt,de]=me.useState(""),Be=me.useRef(pt);Be.current=pt;const ze=me.useRef(""),St=me.useRef(!1),Ke=me.useRef(""),ke=me.useRef(Date.now()),ft=me.useRef([]),jt=me.useRef(!1),[kt,an]=me.useState(!1),[Tn,wi]=me.useState(!1),ua=me.useRef(null),zi=me.useMemo(()=>Ve?"Try again":B==="Busy"?"Busy":B==="Thinking..."||B==="Processing Voice..."?B:Nt!=null&&Nt!==""&&Nt!=="none"&&Nt!=="<none>"?`Enter ${r4(Nt)}`:pt!=="hidden"||!Tn?null:bC,[B,Nt,Ve,pt,Tn]),qa=!Ve&&B!=="Busy"&&B!=="Thinking..."&&B!=="Processing Voice..."&&(Nt==null||Nt===""||Nt==="none"||Nt==="<none>");me.useEffect(()=>{if(pt!=="hidden"||!qa){wi(!1),ua.current!=null&&(clearTimeout(ua.current),ua.current=null);return}return ua.current=setTimeout(()=>{ua.current=null,wi(!0)},400),()=>{ua.current!=null&&(clearTimeout(ua.current),ua.current=null)}},[pt,qa]);const va=zi!=null&&zi!=="";me.useEffect(()=>{const Ue=Ne.current;if(!(Ue==="exiting"||Ue==="entering")){if(Ue==="hidden"){va&&(Fe(zi??""),P("entering"));return}Ue==="visible"&&(!va||zi!==ie)&&(Ye.current=va?zi:null,P("exiting"))}},[va,zi,j,ie]),me.useEffect(()=>{if(B!=="Busy"){Jt.current!=null&&(clearTimeout(Jt.current),Jt.current=null);return}return Jt.current=setTimeout(()=>{Jt.current=null,L("Ready"),Je(!0)},12e3),()=>{Jt.current!=null&&(clearTimeout(Jt.current),Jt.current=null)}},[B]),me.useEffect(()=>{if(!Ve)return;const Ue=setTimeout(()=>Je(!1),2500);return()=>clearTimeout(Ue)},[Ve]);const ss=me.useCallback(()=>{const Ue=Ne.current;if(Ue==="exiting"){P("hidden");const ct=Ye.current;Ye.current=null,ct!=null&&ct!==""&&(Fe(ct),P("entering"))}else Ue==="entering"&&P("visible")},[]),ji=Ue=>{if(!Ue)return;if(Ue.mood!=null){const Mt=String(Ue.mood).toLowerCase();ye(Mt)}if(Ue.expression!=null){const Mt=String(Ue.expression).trim();we(Mt);const Pt=YF.find(Mn=>Mn.name.toLowerCase()===Mt.toLowerCase());ca(`[STREAM] Animation match for "${Mt}": ${Pt?Pt.name:"NONE"}`),Q(Pt?.url??"")}if(Ue.navigation!=null){const Mt=String(Ue.navigation).trim();Mt!==""&&(s?s(Mt):window.open(Mt,"_blank"))}const ct=Ue.ask_for||Ue.lead_capture?.ask_for,ut=ct?String(ct).trim().toLowerCase():"",Tt=ut==="none"||ut==="<none>";if(ct&&!Tt){const Mt=ut;if(t&&(Mt==="email"&&t.email||Mt==="name"&&t.name||Mt==="phone"&&t.phone))return;yt(Mt||null),vt(Mt==="email"?"Enter your email":Mt==="name"?"Enter your name":Mt==="phone"?"Enter your phone number":"Chat with us")}else(Tt||Ue.ask_for===null||Ue.lead_capture&&Ue.lead_capture.ask_for===null||Ue.ask_for==="none")&&(yt(null),Kt!=="Chat with us"&&vt("Chat with us"));Ue.collected,Ue.valid},sn=Ue=>{const ct=Ue.trim();if(!ct)return null;if(ct.startsWith("{"))try{return JSON.parse(ct)}catch{return null}if(ct.includes(":")){const ut=ct.split(":"),Tt=ut[0].trim().toLowerCase(),Mt=ut.slice(1).join(":").trim();return{[Tt]:Mt}}return null},fa=me.useCallback(()=>{},[]),hn="§",G=()=>{for(;ze.current.includes(`
|
|
4150
4150
|
`);){const Ue=ze.current.indexOf(`
|
|
4151
|
-
`),ct=ze.current.slice(0,Ue).trim();ze.current=ze.current.slice(Ue+1);const ut=sn(ct);ut&&ji(ut)}},J=Ue=>{if(St.current)if(Ue.includes(hn)){const ct=Ue.indexOf(hn),ut=Ue.slice(0,ct),Tt=Ue.slice(ct+hn.length);ut&&(Ke.current+=ut,w(Mt=>Mt+ut)),St.current=!1,Tt&&(ze.current+=Tt,G())}else Ue===hn?St.current=!1:(Ke.current+=Ue,w(ct=>ct+Ue));else if(Ue.includes(hn)){const ct=Ue.indexOf(hn),ut=Ue.slice(0,ct),Tt=Ue.slice(ct+hn.length);ze.current+=ut,G(),St.current=!0,Tt&&(Ke.current+=Tt,w(Mt=>Mt+Tt))}else if(Ue===hn){St.current=!0;return}else ze.current+=Ue,G()};me.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const Mt="secret",Pt=Math.floor(Date.now()/1e3).toString();try{const Mn=new TextEncoder,On=await crypto.subtle.importKey("raw",Mn.encode(Mt),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),In=await crypto.subtle.sign("HMAC",On,Mn.encode(Pt)),Jn=Array.from(new Uint8Array(In)).map(mi=>mi.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",Jn),ca("[SESSION] New HMAC UID generated and saved:",Jn)}catch(Mn){console.error("[SESSION] HMAC generation failed:",Mn);const On=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",On)}}const ut=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let Tt=[];if(ut)try{Tt=JSON.parse(ut)}catch{Tt=[]}Tt.length===0&&t&&(t.name||t.email)?(Tt=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${t.name||""}" , Email is "${t.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(Tt))):ut||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[t]),me.useEffect(()=>{const Ue=()=>{ke.current=Date.now(),jt.current&&(jt.current=!1,an(!1),I([]),ne(""),w(""),V(!1))};window.addEventListener("mousemove",Ue),window.addEventListener("keydown",Ue),window.addEventListener("mousedown",Ue),window.addEventListener("touchstart",Ue);const ct=setInterval(async()=>{if(Date.now()-ke.current>=3e4&&!z&&!H&&B==="Ready"&&!jt.current)if(jt.current=!0,ft.current.length>0)an(!0),I(ft.current);else try{const Mt=`${Zh}/nudgeUser`,Pt={navigationUrl:window.location.href,agentId:e},Mn=await fetch(Mt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pt)});if(Mn.ok){const In=(await Mn.json()).nudge_questions;In&&In.length>0&&(ca("[NUDGE] Received nudge questions from API:",In),ft.current=In,an(!0),I(In))}}catch(Mt){console.error("[NUDGE] Error calling /nudgeUser:",Mt),jt.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",Ue),window.removeEventListener("keydown",Ue),window.removeEventListener("mousedown",Ue),window.removeEventListener("touchstart",Ue),clearInterval(ct)}},[y,z,H,B]),me.useEffect(()=>{if(U.length===0)return;let Ue=0,ct=0,ut=!1,Tt=100;const Mt=()=>{const Pt=U[Ue];if(ut){const Mn=Pt.substring(0,ct-1);ne(Mn),ct--,Tt=50}else{const Mn=Pt.substring(0,ct+1);ne(Mn),ct++,Tt=100}!ut&&ct===Pt.length?(ut=!0,Tt=3e3):ut&&ct===0&&(ut=!1,Ue=(Ue+1)%U.length,Tt=500),ee.current=setTimeout(Mt,Tt)};return Mt(),()=>{ee.current&&clearTimeout(ee.current)}},[U]);const le=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},Re=Ue=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(Ue))},[Pe,He]=me.useState(!1),[rt,it]=me.useState(0),Ze=me.useRef(null),je=me.useRef([]),gt=me.useRef(0),[ht,k]=me.useState(null),[te,fe]=me.useState(null),ue=me.useRef(null),ce=me.useRef(null),Qe=me.useCallback((Ue=!1)=>{Ue&&(Et.current=!0,O(!1),L("Ready")),K.current=[],$.current=[],ve.current=!1,V(!1),at.current=0,ge.current=0,Te.current=0,be.current.forEach(ct=>{try{ct.stop()}catch{}}),Ot.current&&(clearTimeout(Ot.current),Ot.current=null),_t(null),Q(""),be.current=[]},[]),ot=async()=>{try{const Ue=await navigator.mediaDevices.getUserMedia({audio:!0}),ct=window.AudioContext||window.webkitAudioContext,ut=new ct,Tt=ut.createMediaStreamSource(Ue),Mt=ut.createAnalyser();Mt.fftSize=64,Tt.connect(Mt),ue.current=ut,ce.current=Tt,fe(Mt);const Pt=new MediaRecorder(Ue);Ze.current=Pt,je.current=[],Pt.ondataavailable=Mn=>{Mn.data.size>0&&je.current.push(Mn.data)},Pt.onstop=async()=>{const Mn=Date.now()-gt.current;if(fe(null),ce.current&&(ce.current.disconnect(),ce.current=null),ue.current&&ue.current.state!=="closed"&&(ue.current.close(),ue.current=null),Mn<1e3){L("Recording too short. Hold or click longer."),O(!1);return}const On=new Blob(je.current,{type:"audio/wav"});await At(On)},gt.current=Date.now(),Pt.start(100),He(!0),L("Listening...")}catch(Ue){console.error("Error accessing microphone:",Ue),L("Mic Access Error")}},lt=()=>{Ze.current&&Ze.current.state!=="inactive"&&(Ze.current.stop(),Ze.current.stream.getTracks().forEach(Ue=>Ue.stop()),He(!1))},Ct=()=>{Ze.current&&Ze.current.state!=="inactive"&&(Ze.current.onstop=null,Ze.current.stop(),Ze.current.stream.getTracks().forEach(Ue=>Ue.stop()),fe(null),ce.current&&(ce.current.disconnect(),ce.current=null),ue.current&&ue.current.state!=="closed"&&(ue.current.close(),ue.current=null),He(!1),je.current=[],L("Ready"))};me.useEffect(()=>{if(!z)return;const Ue=()=>{const ct=Te.current;if(ct<=0)return;const ut=se.current,Tt=at.current;if(!ut)return;const Mt=ut.currentTime-Tt,Pt=Math.min(Math.max(0,Mt),ct),On=EC(M).trim().length;if(On<=0)return;const In=Math.min(Math.round(Pt/ct*On),On);un(In)};return clearInterval(Lt.current??void 0),Lt.current=setInterval(Ue,90),()=>clearInterval(Lt.current??void 0)},[z,M,Te.current]),me.useEffect(()=>{let Ue;return Pe?(it(0),Ue=window.setInterval(()=>{it(ct=>ct+1)},1e3)):it(0),()=>clearInterval(Ue)},[Pe]);const xt=Ue=>{const ct=Ue.numberOfChannels,ut=Ue.length*ct*2+44,Tt=new ArrayBuffer(ut),Mt=new DataView(Tt);let Pt=0;const Mn=Jn=>{Mt.setUint16(Pt,Jn,!0),Pt+=2},On=Jn=>{Mt.setUint32(Pt,Jn,!0),Pt+=4};On(1179011410),On(ut-8),On(1163280727),On(544501094),On(16),Mn(1),Mn(ct),On(Ue.sampleRate),On(Ue.sampleRate*2*ct),Mn(ct*2),Mn(16),On(1635017060),On(ut-Pt-4);const In=[];for(let Jn=0;Jn<ct;Jn++)In.push(Ue.getChannelData(Jn));let Fn=0;for(;Pt<ut;){for(let Jn=0;Jn<ct;Jn++){let mi=Math.max(-1,Math.min(1,In[Jn][Fn]));mi=mi<0?mi*32768:mi*32767,Mt.setInt16(Pt,mi,!0),Pt+=2}Fn++}return new Blob([Tt],{type:"audio/wav"})},Xt=async(Ue,ct,ut=!1)=>{if(!Et.current){if(Y.current){$.current.push({audio:Ue,visemes:ct,isNewSegment:ut});return}Y.current=!0;try{const Tt=window.AudioContext||window.webkitAudioContext,Mt=se.current??new Tt;Mt.state==="suspended"&&await Mt.resume(),se.current=Mt;const Pt=window.atob(Ue),Mn=new Uint8Array(Pt.length);for(let Di=0;Di<Pt.length;Di++)Mn[Di]=Pt.charCodeAt(Di);const On=await Mt.decodeAudioData(Mn.buffer.slice(0));Te.current+=On.duration;const In=Mt.currentTime;let Fn=ge.current;const Jn=!ve.current;Fn<In&&(Fn=In+.1),ge.current=Fn+On.duration;const mi=Mt.createBufferSource();mi.buffer=On;let Bi=ht;if((!Bi||Bi.context!==Mt)&&(Bi=Mt.createAnalyser(),Bi.fftSize=64,Bi.connect(Mt.destination),k(Bi)),mi.connect(Bi),be.current.push(mi),Et.current){be.current=be.current.filter(Di=>Di!==mi);return}if(Jn){ve.current=!0,V(!0),ca(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${Fn.toFixed(3)}`),at.current=Fn;const Di=(Fn-In)*1e3;_e.current=performance.now()+Di,ca(`[AUDIO] Response started. Initial startTime: ${Fn.toFixed(3)}, CT: ${In.toFixed(3)}`)}mi.start(Fn);const Vi=(Fn-at.current)*1e3;ut&&(nt.current=Vi,ca(`[AUDIO] New segment detected at +${Vi.toFixed(0)}ms. Resetting segment offset.`)),ct.forEach((Di,Ka)=>{const bi=Di.symbol??"";if(bi){const _a=i4(bi),Qi=Math.round(Di.start*1e3),ir=Math.round((Di.duration??0)*1e3),qo=nt.current+Qi;Ka<3&&ca(`[AUDIO] Viseme "${bi}": segment_relative=${Qi}ms, segment_offset=${nt.current.toFixed(0)}ms => vtime=${qo}ms`),_a.forEach(xr=>{K.current.push({viseme:xr.v,weight:xr.w,vtime:qo,vduration:ir})})}}),L("Speaking...")}finally{if(Y.current=!1,$.current.length>0){const Tt=$.current.shift();Tt&&Xt(Tt.audio,Tt.visemes,Tt.isNewSegment)}}}},At=async Ue=>{try{O(!0),an(!1),Ke.current="",w(""),L("Processing Voice...");const ct=await Ue.arrayBuffer(),Tt=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(ct),Mt=xt(Tt),Pt=new FileReader;Pt.readAsDataURL(Mt),Pt.onloadend=async()=>{const Mn=Pt.result.split(",")[1];Qe(),T(""),ze.current="",St.current=!1;const On=`${Zh}/stt?token=${encodeURIComponent(y)}`,In=await fetch(On,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:Mn,audio_format:"wav"})});if(In.status===429){try{const Ka=await In.text(),bi=JSON.parse(Ka);ca("[STT] 429 agent at capacity:",bi?.detail)}catch{}T(""),L("Busy"),O(!1);return}if(!In.ok){const Ka=await In.text();let bi="STT Failed";try{bi=JSON.parse(Ka).error||bi}catch{Ka&&(bi=Ka.slice(0,200))}throw new Error(bi)}const Fn=In.body;if(ca("this is body"+Fn),!Fn){L("STT Failed"),O(!1);return}const Jn=Fn.getReader();Et.current=!1;const mi=new TextDecoder;let Bi="",Vi=!1;const Di=async(Ka,bi)=>{switch(Ka){case"transcript":bi.transcript!=null&&T(String(bi.transcript));break;case"text":{const _a=bi.delta??bi.text??"";_a&&J(_a);break}case"audio":{const _a=bi.chunk,Qi=bi.visemes??[],ir=!!bi.is_new_segment;_a&&await Xt(_a,Qi,ir);break}case"done":{Vi=!0,L("Ready"),O(!1);break}case"error":{Vi=!0,L("STT Failed"),O(!1);break}default:break}};for(;;){const{done:Ka,value:bi}=await Jn.read();bi&&(Bi+=mi.decode(bi,{stream:!0}));const _a=Bi.split(`
|
|
4151
|
+
`),ct=ze.current.slice(0,Ue).trim();ze.current=ze.current.slice(Ue+1);const ut=sn(ct);ut&&ji(ut)}},J=Ue=>{if(St.current)if(Ue.includes(hn)){const ct=Ue.indexOf(hn),ut=Ue.slice(0,ct),Tt=Ue.slice(ct+hn.length);ut&&(Ke.current+=ut,w(Mt=>Mt+ut)),St.current=!1,Tt&&(ze.current+=Tt,G())}else Ue===hn?St.current=!1:(Ke.current+=Ue,w(ct=>ct+Ue));else if(Ue.includes(hn)){const ct=Ue.indexOf(hn),ut=Ue.slice(0,ct),Tt=Ue.slice(ct+hn.length);ze.current+=ut,G(),St.current=!0,Tt&&(Ke.current+=Tt,w(Mt=>Mt+Tt))}else if(Ue===hn){St.current=!0;return}else ze.current+=Ue,G()};me.useEffect(()=>{(async()=>{if(!sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID")){const Mt="secret",Pt=Math.floor(Date.now()/1e3).toString();try{const Mn=new TextEncoder,On=await globalThis.crypto.subtle.importKey("raw",Mn.encode(Mt),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),In=await globalThis.crypto.subtle.sign("HMAC",On,Mn.encode(Pt)),Jn=Array.from(new Uint8Array(In)).map(mi=>mi.toString(16).padStart(2,"0")).join("");sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",Jn),ca("[SESSION] New HMAC UID generated and saved:",Jn)}catch(Mn){console.error("[SESSION] HMAC generation failed:",Mn);const On=Math.random().toString(36)+Date.now().toString();sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",On)}}const ut=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES");let Tt=[];if(ut)try{Tt=JSON.parse(ut)}catch{Tt=[]}Tt.length===0&&t&&(t.name||t.email)?(Tt=[{role:"user",content:`PRESET_USER_DETAILS: Name is "${t.name||""}" , Email is "${t.email||""}"`}],sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(Tt))):ut||sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify([]))})()},[t]),me.useEffect(()=>{const Ue=()=>{ke.current=Date.now(),jt.current&&(jt.current=!1,an(!1),I([]),ne(""),w(""),V(!1))};window.addEventListener("mousemove",Ue),window.addEventListener("keydown",Ue),window.addEventListener("mousedown",Ue),window.addEventListener("touchstart",Ue);const ct=setInterval(async()=>{if(Date.now()-ke.current>=3e4&&!z&&!H&&B==="Ready"&&!jt.current)if(jt.current=!0,ft.current.length>0)an(!0),I(ft.current);else try{const Mt=`${Zh}/nudgeUser`,Pt={navigationUrl:window.location.href,agentId:e},Mn=await fetch(Mt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Pt)});if(Mn.ok){const In=(await Mn.json()).nudge_questions;In&&In.length>0&&(ca("[NUDGE] Received nudge questions from API:",In),ft.current=In,an(!0),I(In))}}catch(Mt){console.error("[NUDGE] Error calling /nudgeUser:",Mt),jt.current=!1}},1e3);return()=>{window.removeEventListener("mousemove",Ue),window.removeEventListener("keydown",Ue),window.removeEventListener("mousedown",Ue),window.removeEventListener("touchstart",Ue),clearInterval(ct)}},[y,z,H,B]),me.useEffect(()=>{if(U.length===0)return;let Ue=0,ct=0,ut=!1,Tt=100;const Mt=()=>{const Pt=U[Ue];if(ut){const Mn=Pt.substring(0,ct-1);ne(Mn),ct--,Tt=50}else{const Mn=Pt.substring(0,ct+1);ne(Mn),ct++,Tt=100}!ut&&ct===Pt.length?(ut=!0,Tt=3e3):ut&&ct===0&&(ut=!1,Ue=(Ue+1)%U.length,Tt=500),ee.current=setTimeout(Mt,Tt)};return Mt(),()=>{ee.current&&clearTimeout(ee.current)}},[U]);const le=()=>{try{return JSON.parse(sessionStorage.getItem("STREAMOJI_LEADS_SESSION_MESSAGES")||"[]")}catch{return[]}},Re=Ue=>{sessionStorage.setItem("STREAMOJI_LEADS_SESSION_MESSAGES",JSON.stringify(Ue))},[Pe,He]=me.useState(!1),[rt,it]=me.useState(0),Ze=me.useRef(null),je=me.useRef([]),gt=me.useRef(0),[ht,k]=me.useState(null),[te,fe]=me.useState(null),ue=me.useRef(null),ce=me.useRef(null),Qe=me.useCallback((Ue=!1)=>{Ue&&(Et.current=!0,O(!1),L("Ready")),K.current=[],$.current=[],ve.current=!1,V(!1),at.current=0,ge.current=0,Te.current=0,be.current.forEach(ct=>{try{ct.stop()}catch{}}),Ot.current&&(clearTimeout(Ot.current),Ot.current=null),_t(null),Q(""),be.current=[]},[]),ot=async()=>{try{const Ue=await navigator.mediaDevices.getUserMedia({audio:!0}),ct=window.AudioContext||window.webkitAudioContext,ut=new ct,Tt=ut.createMediaStreamSource(Ue),Mt=ut.createAnalyser();Mt.fftSize=64,Tt.connect(Mt),ue.current=ut,ce.current=Tt,fe(Mt);const Pt=new MediaRecorder(Ue);Ze.current=Pt,je.current=[],Pt.ondataavailable=Mn=>{Mn.data.size>0&&je.current.push(Mn.data)},Pt.onstop=async()=>{const Mn=Date.now()-gt.current;if(fe(null),ce.current&&(ce.current.disconnect(),ce.current=null),ue.current&&ue.current.state!=="closed"&&(ue.current.close(),ue.current=null),Mn<1e3){L("Recording too short. Hold or click longer."),O(!1);return}const On=new Blob(je.current,{type:"audio/wav"});await At(On)},gt.current=Date.now(),Pt.start(100),He(!0),L("Listening...")}catch(Ue){console.error("Error accessing microphone:",Ue),L("Mic Access Error")}},lt=()=>{Ze.current&&Ze.current.state!=="inactive"&&(Ze.current.stop(),Ze.current.stream.getTracks().forEach(Ue=>Ue.stop()),He(!1))},Ct=()=>{Ze.current&&Ze.current.state!=="inactive"&&(Ze.current.onstop=null,Ze.current.stop(),Ze.current.stream.getTracks().forEach(Ue=>Ue.stop()),fe(null),ce.current&&(ce.current.disconnect(),ce.current=null),ue.current&&ue.current.state!=="closed"&&(ue.current.close(),ue.current=null),He(!1),je.current=[],L("Ready"))};me.useEffect(()=>{if(!z)return;const Ue=()=>{const ct=Te.current;if(ct<=0)return;const ut=se.current,Tt=at.current;if(!ut)return;const Mt=ut.currentTime-Tt,Pt=Math.min(Math.max(0,Mt),ct),On=EC(M).trim().length;if(On<=0)return;const In=Math.min(Math.round(Pt/ct*On),On);un(In)};return clearInterval(Lt.current??void 0),Lt.current=setInterval(Ue,90),()=>clearInterval(Lt.current??void 0)},[z,M,Te.current]),me.useEffect(()=>{let Ue;return Pe?(it(0),Ue=window.setInterval(()=>{it(ct=>ct+1)},1e3)):it(0),()=>clearInterval(Ue)},[Pe]);const xt=Ue=>{const ct=Ue.numberOfChannels,ut=Ue.length*ct*2+44,Tt=new ArrayBuffer(ut),Mt=new DataView(Tt);let Pt=0;const Mn=Jn=>{Mt.setUint16(Pt,Jn,!0),Pt+=2},On=Jn=>{Mt.setUint32(Pt,Jn,!0),Pt+=4};On(1179011410),On(ut-8),On(1163280727),On(544501094),On(16),Mn(1),Mn(ct),On(Ue.sampleRate),On(Ue.sampleRate*2*ct),Mn(ct*2),Mn(16),On(1635017060),On(ut-Pt-4);const In=[];for(let Jn=0;Jn<ct;Jn++)In.push(Ue.getChannelData(Jn));let Fn=0;for(;Pt<ut;){for(let Jn=0;Jn<ct;Jn++){let mi=Math.max(-1,Math.min(1,In[Jn][Fn]));mi=mi<0?mi*32768:mi*32767,Mt.setInt16(Pt,mi,!0),Pt+=2}Fn++}return new Blob([Tt],{type:"audio/wav"})},Xt=async(Ue,ct,ut=!1)=>{if(!Et.current){if(Y.current){$.current.push({audio:Ue,visemes:ct,isNewSegment:ut});return}Y.current=!0;try{const Tt=window.AudioContext||window.webkitAudioContext,Mt=se.current??new Tt;Mt.state==="suspended"&&await Mt.resume(),se.current=Mt;const Pt=window.atob(Ue),Mn=new Uint8Array(Pt.length);for(let Di=0;Di<Pt.length;Di++)Mn[Di]=Pt.charCodeAt(Di);const On=await Mt.decodeAudioData(Mn.buffer.slice(0));Te.current+=On.duration;const In=Mt.currentTime;let Fn=ge.current;const Jn=!ve.current;Fn<In&&(Fn=In+.1),ge.current=Fn+On.duration;const mi=Mt.createBufferSource();mi.buffer=On;let Bi=ht;if((!Bi||Bi.context!==Mt)&&(Bi=Mt.createAnalyser(),Bi.fftSize=64,Bi.connect(Mt.destination),k(Bi)),mi.connect(Bi),be.current.push(mi),Et.current){be.current=be.current.filter(Di=>Di!==mi);return}if(Jn){ve.current=!0,V(!0),ca(`[AUDIO] setIsSpeaking(true) - First chunk starting at ${Fn.toFixed(3)}`),at.current=Fn;const Di=(Fn-In)*1e3;_e.current=performance.now()+Di,ca(`[AUDIO] Response started. Initial startTime: ${Fn.toFixed(3)}, CT: ${In.toFixed(3)}`)}mi.start(Fn);const Vi=(Fn-at.current)*1e3;ut&&(nt.current=Vi,ca(`[AUDIO] New segment detected at +${Vi.toFixed(0)}ms. Resetting segment offset.`)),ct.forEach((Di,Ka)=>{const bi=Di.symbol??"";if(bi){const _a=i4(bi),Qi=Math.round(Di.start*1e3),ir=Math.round((Di.duration??0)*1e3),qo=nt.current+Qi;Ka<3&&ca(`[AUDIO] Viseme "${bi}": segment_relative=${Qi}ms, segment_offset=${nt.current.toFixed(0)}ms => vtime=${qo}ms`),_a.forEach(xr=>{K.current.push({viseme:xr.v,weight:xr.w,vtime:qo,vduration:ir})})}}),L("Speaking...")}finally{if(Y.current=!1,$.current.length>0){const Tt=$.current.shift();Tt&&Xt(Tt.audio,Tt.visemes,Tt.isNewSegment)}}}},At=async Ue=>{try{O(!0),an(!1),Ke.current="",w(""),L("Processing Voice...");const ct=await Ue.arrayBuffer(),Tt=await new(window.AudioContext||window.webkitAudioContext)().decodeAudioData(ct),Mt=xt(Tt),Pt=new FileReader;Pt.readAsDataURL(Mt),Pt.onloadend=async()=>{const Mn=Pt.result.split(",")[1];Qe(),T(""),ze.current="",St.current=!1;const On=`${Zh}/stt?token=${encodeURIComponent(y)}`,In=await fetch(On,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audio_base64:Mn,audio_format:"wav"})});if(In.status===429){try{const Ka=await In.text(),bi=JSON.parse(Ka);ca("[STT] 429 agent at capacity:",bi?.detail)}catch{}T(""),L("Busy"),O(!1);return}if(!In.ok){const Ka=await In.text();let bi="STT Failed";try{bi=JSON.parse(Ka).error||bi}catch{Ka&&(bi=Ka.slice(0,200))}throw new Error(bi)}const Fn=In.body;if(ca("this is body"+Fn),!Fn){L("STT Failed"),O(!1);return}const Jn=Fn.getReader();Et.current=!1;const mi=new TextDecoder;let Bi="",Vi=!1;const Di=async(Ka,bi)=>{switch(Ka){case"transcript":bi.transcript!=null&&T(String(bi.transcript));break;case"text":{const _a=bi.delta??bi.text??"";_a&&J(_a);break}case"audio":{const _a=bi.chunk,Qi=bi.visemes??[],ir=!!bi.is_new_segment;_a&&await Xt(_a,Qi,ir);break}case"done":{Vi=!0,L("Ready"),O(!1);break}case"error":{Vi=!0,L("STT Failed"),O(!1);break}default:break}};for(;;){const{done:Ka,value:bi}=await Jn.read();bi&&(Bi+=mi.decode(bi,{stream:!0}));const _a=Bi.split(`
|
|
4152
4152
|
|
|
4153
4153
|
`);Bi=_a.pop()??"";for(const Qi of _a){const ir=mn(Qi);ir&&await Di(ir.event,ir.data)}if(Ka){if(Bi.trim()){const Qi=mn(Bi.trim());Qi&&await Di(Qi.event,Qi.data)}Vi||(L("Ready"),O(!1));break}}}}catch(ct){console.error("Audio Submission Error:",ct),L("STT Failed"),O(!1)}},zt=async Ue=>{Ue&&Ue.preventDefault(),an(!1),Ke.current="",w(""),!(!R||H)&&await Ut(R)},mn=Ue=>{const ct=Ue.split(/\r?\n/);let ut="",Tt="";for(const Pt of ct)Pt.startsWith("event:")?ut=Pt.slice(6).trim():Pt.startsWith("data:")&&(Tt=Pt.slice(5).trim());if(!ut)return null;let Mt={};if(Tt)try{Mt=JSON.parse(Tt)}catch{Mt={raw:Tt}}return{event:ut,data:Mt}},Pn=(Ue,ct)=>{switch(Ue){case"connected":ze.current="",St.current=!1;break;case"text":{const ut=ct.delta??"";ut&&J(ut);break}case"metadata":{ji(ct);break}case"audio":{const ut=ct.chunk,Tt=ct.visemes??[],Mt=ct.is_new_segment??!1;ut&&Xt(ut,Tt,Mt);break}case"done":{const ut=le(),Tt=Ke.current.trim(),Mt=[...ut,{role:"user",content:R||"..."},{role:"assistant",content:Tt}];Re(Mt),Ie.current=[...K.current],L("Ready"),O(!1),T("");break}case"error":{const ut=ct.message??"Unknown error";Ke.current=ut,w(ut),L("Agent Failed"),O(!1);break}}},Sn=async(Ue,ct)=>{O(!0),L("Thinking..."),Ke.current="",ze.current="",St.current=!1,Qe(),Te.current=0,un(0);try{const ut=await fetch(Ue,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(ct)});if(ut.status===429){L("Busy"),O(!1);return}if(!ut.ok)throw new Error("Request failed");const Tt=ut.body;if(!Tt){L("Failed"),O(!1);return}const Mt=Tt.getReader();Et.current=!1;const Pt=new TextDecoder;let Mn="";for(;;){const{done:On,value:In}=await Mt.read();In&&(Mn+=Pt.decode(In,{stream:!0}));const Fn=Mn.split(`
|
|
4154
4154
|
|
|
4155
4155
|
`);Mn=Fn.pop()??"";for(const Jn of Fn){const mi=mn(Jn);mi&&Pn(mi.event,mi.data)}if(On){if(Mn.trim()){const Jn=mn(Mn.trim());Jn&&Pn(Jn.event,Jn.data)}L("Ready"),O(!1);break}}}catch(ut){console.error("Streaming Error:",ut),L("Failed"),O(!1)}},Qt=me.useCallback(async(Ue,ct)=>{const ut=`${Zh}/avatar_tts`;await Sn(ut,{user_query:Ue,llm_prompt:ct})},[]),Dt=me.useCallback(async(Ue,ct,ut,Tt)=>{const Mt=`${Zh}/avatar_ttsWithKnowledge`;await Sn(Mt,{user_query:Ue,llm_prompt:ct,knowledge:ut,history:Tt})},[]),$t=me.useRef(!1);me.useEffect(()=>{n&&!$t.current&&(n({avatarSpeak:Qt,avatarRespond:Dt}),$t.current=!0)},[n,Qt,Dt]);const Ut=async Ue=>{O(!0),L("Thinking..."),Ke.current="",ze.current="",St.current=!1,Qe(),Te.current=0,un(0);const ct=`${Zh}/agent/chat?token=${encodeURIComponent(y)}`;try{const ut=le();let Tt=sessionStorage.getItem("STREAMOJI_LEADS_SESSION_LEAD_ID");Tt||(GF("[CHAT] Session UID missing at send time! Generating emergency backup."),Tt="emergency-"+Math.random().toString(36).substring(7),sessionStorage.setItem("STREAMOJI_LEADS_SESSION_LEAD_ID",Tt));const Mt={history:ut,question:Ue,lead_id:Tt};ca("[CHAT] Sending payload:",Mt);const Pt=await fetch(ct,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Mt),cache:"default"});if(Pt.status===429){try{const Jn=await Pt.json();ca("[CHAT] 429 agent at capacity:",Jn?.detail)}catch{}T(""),L("Busy"),O(!1);return}if(!Pt.ok)throw new Error("Agent request failed");const Mn=Pt.body;if(!Mn){L("Agent Failed"),O(!1);return}const On=Mn.getReader();Et.current=!1;const In=new TextDecoder;let Fn="";for(;;){const{done:Jn,value:mi}=await On.read();ca(`[SSE] Chunk received. done=${Jn}, length=${mi?.length||0}`),mi&&(Fn+=In.decode(mi,{stream:!0}));const Bi=Fn.split(`
|
|
4156
4156
|
|
|
4157
|
-
`);Fn=Bi.pop()??"";for(const Vi of Bi){ca(`[SSE] Processing block: ${Vi.slice(0,50)}...`);const Di=mn(Vi);Di&&(ca(`[SSE] Event: ${Di.event}`),Pn(Di.event,Di.data))}if(Jn){if(ca("[SSE] Stream finished"),Fn.trim()){const Vi=mn(Fn.trim());Vi&&Pn(Vi.event,Vi.data)}L("Ready"),O(!1),T("");break}}}catch(ut){console.error("Chat Error:",ut),L("Agent Failed"),O(!1)}},ei=M.trim(),Zi=EC(ei),Gn=Zi&&z?Zi.slice(0,Bt!=null&&Bt>0?Bt:0):"";me.useEffect(()=>{const Ue=Be.current;Ue!=="exiting"&&(Gn?(de(Gn),Ue==="hidden"&&st("entering")):(Ue==="visible"||Ue==="entering")&&st("exiting"))},[Gn,pt]);const Ni=me.useCallback(()=>{const Ue=Be.current;Ue==="entering"?st("visible"):Ue==="exiting"&&st("hidden")},[]);me.useLayoutEffect(()=>{const Ue=Rt.current;Ue&&(Ue.scrollTop=Ue.scrollHeight)},[qt]);const si=x==="female"?jF:WF;return _?Yt.jsxs("div",{className:"avatar-widget-container",children:[Yt.jsxs("div",{className:"avatar-input-area",children:[j!=="hidden"?Yt.jsx("div",{className:`avatar-thinking-tab${j==="exiting"?" avatar-thinking-tab--exiting":j==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:ss,children:ie===bC?Yt.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):ie}):null,Yt.jsx("div",{className:"avatar-input-container",children:Yt.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:Pe?Yt.jsxs("div",{className:"avatar-input-recording",children:[Yt.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:Ct,title:"Cancel",children:Yt.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:[Yt.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Yt.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),Yt.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[Yt.jsx("div",{style:{flex:1,height:"100%"},children:Yt.jsx(gC,{analyser:te})}),Yt.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(rt/60),":",String(rt%60).padStart(2,"0")]})]}),Yt.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:lt,title:"Send",children:Yt.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:Yt.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):z&&!kt?Yt.jsxs("div",{className:"avatar-input-speaking",children:[Yt.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:Yt.jsx(gC,{analyser:ht})}),Yt.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>Qe(!0),title:"Stop",children:Yt.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):H?Yt.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:Yt.jsx("div",{className:"avatar-input-loader"})}):Yt.jsxs("form",{onSubmit:zt,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[Yt.jsx("input",{id:"avatar-text-input",type:"text",value:R,onChange:Ue=>T(Ue.target.value),placeholder:B==="Busy"?"Assisting another user":W||"Ask me anything",disabled:H||B==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),B==="Busy"?Yt.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:Yt.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:Yt.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):R.trim()===""?Yt.jsx("button",{type:"button",className:"mic-button",onClick:ot,disabled:H,style:{backgroundColor:"#1e4a5e"},children:Yt.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[Yt.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"}),Yt.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"})]})}):Yt.jsx("button",{type:"submit",className:"mic-button",disabled:H,style:{backgroundColor:"#1e4a5e"},title:"Send",children:Yt.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:Yt.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),Yt.jsx("div",{className:"avatar-wrapper",children:Yt.jsxs("div",{className:"avatar-scene-wrapper",children:[pt!=="hidden"&&Yt.jsx("div",{className:`avatar-bubble${pt==="entering"?" avatar-bubble--entering":pt==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:Ni,children:Yt.jsx("div",{ref:Rt,className:`avatar-bubble__content${kt?" avatar-bubble__content--nudge":""}`,children:qt})}),Yt.jsx("div",{className:"avatar-canvas-layer",style:{width:F,height:F},children:Yt.jsxs(zO,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1.8,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[Yt.jsx(a4,{target:si}),Yt.jsx("ambientLight",{intensity:.7}),Yt.jsx("directionalLight",{position:[0,2,2],intensity:1}),Yt.jsx(aF,{preset:"city"}),Yt.jsx(me.Suspense,{fallback:null,children:b!==null&&Yt.jsx(s4,{avatarUrl:b,isPlayingRef:ve,visemeQueueRef:K,audioContextRef:se,responseAudioStartTimeRef:at,adjustments:KF,mood:mt,expression:xe,agentResponse:M,isSpeaking:z,nextStartTimeRef:ge,stopPlayback:Qe,setIsSpeaking:V,expressionUrl:tt,onExpressionFinished:fa,isNudgeResponse:kt,avatarGender:x})})]})})]})})]}):null},l4=({agentId:s,onNavigationRequested:e,presetUserDetails:t,onAvatarReady:n})=>Yt.jsx(o4,{agentId:s,onNavigationRequested:e,presetUserDetails:t,onAvatarReady:n}),TC="streamoji-leads-avatar-widget-root";function CC(s){const{
|
|
4158
|
-
//# sourceMappingURL=avatar-widget.umd.js.map
|
|
4157
|
+
`);Fn=Bi.pop()??"";for(const Vi of Bi){ca(`[SSE] Processing block: ${Vi.slice(0,50)}...`);const Di=mn(Vi);Di&&(ca(`[SSE] Event: ${Di.event}`),Pn(Di.event,Di.data))}if(Jn){if(ca("[SSE] Stream finished"),Fn.trim()){const Vi=mn(Fn.trim());Vi&&Pn(Vi.event,Vi.data)}L("Ready"),O(!1),T("");break}}}catch(ut){console.error("Chat Error:",ut),L("Agent Failed"),O(!1)}},ei=M.trim(),Zi=EC(ei),Gn=Zi&&z?Zi.slice(0,Bt!=null&&Bt>0?Bt:0):"";me.useEffect(()=>{const Ue=Be.current;Ue!=="exiting"&&(Gn?(de(Gn),Ue==="hidden"&&st("entering")):(Ue==="visible"||Ue==="entering")&&st("exiting"))},[Gn,pt]);const Ni=me.useCallback(()=>{const Ue=Be.current;Ue==="entering"?st("visible"):Ue==="exiting"&&st("hidden")},[]);me.useLayoutEffect(()=>{const Ue=Rt.current;Ue&&(Ue.scrollTop=Ue.scrollHeight)},[qt]);const si=x==="female"?jF:WF;return _?Yt.jsxs("div",{className:"avatar-widget-container",children:[Yt.jsxs("div",{className:"avatar-input-area",children:[j!=="hidden"?Yt.jsx("div",{className:`avatar-thinking-tab${j==="exiting"?" avatar-thinking-tab--exiting":j==="entering"?" avatar-thinking-tab--entering":""}`,onAnimationEnd:ss,children:ie===bC?Yt.jsx("a",{href:"https://leads.streamoji.com",target:"_blank",rel:"noopener noreferrer",children:"Made by Streamoji Leads"}):ie}):null,Yt.jsx("div",{className:"avatar-input-container",children:Yt.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",height:"100%"},children:Pe?Yt.jsxs("div",{className:"avatar-input-recording",children:[Yt.jsx("button",{type:"button",className:"avatar-recording-cancel",onClick:Ct,title:"Cancel",children:Yt.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:[Yt.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Yt.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),Yt.jsxs("div",{style:{flex:1,height:"100%",position:"relative",display:"flex",alignItems:"center",minWidth:0},children:[Yt.jsx("div",{style:{flex:1,height:"100%"},children:Yt.jsx(gC,{analyser:te})}),Yt.jsxs("span",{style:{fontSize:"0.75rem",color:"#64748b",fontWeight:500,marginLeft:"4px",minWidth:"32px",textAlign:"right",fontVariantNumeric:"tabular-nums"},children:[Math.floor(rt/60),":",String(rt%60).padStart(2,"0")]})]}),Yt.jsx("button",{type:"button",className:"avatar-recording-confirm",onClick:lt,title:"Send",children:Yt.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:Yt.jsx("polyline",{points:"20 6 9 17 4 12"})})})]}):z&&!kt?Yt.jsxs("div",{className:"avatar-input-speaking",children:[Yt.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",paddingRight:"8px"},children:Yt.jsx(gC,{analyser:ht})}),Yt.jsx("button",{type:"button",className:"avatar-speaking-stop",onClick:()=>Qe(!0),title:"Stop",children:Yt.jsx("span",{className:"avatar-speaking-stop__icon","aria-hidden":!0})})]}):H?Yt.jsx("div",{style:{flex:1,height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:Yt.jsx("div",{className:"avatar-input-loader"})}):Yt.jsxs("form",{onSubmit:zt,style:{flex:1,display:"flex",height:"100%",alignItems:"center"},children:[Yt.jsx("input",{id:"avatar-text-input",type:"text",value:R,onChange:Ue=>T(Ue.target.value),placeholder:B==="Busy"?"Assisting another user":W||"Ask me anything",disabled:H||B==="Busy",autoComplete:"off",style:{width:"100%",height:"100%"}}),B==="Busy"?Yt.jsx("button",{type:"button",className:"mic-button",disabled:!0,style:{backgroundColor:"#1e4a5e"},title:"Agent at capacity",children:Yt.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":"true",children:Yt.jsx("path",{d:"M4 2L20 2L12 10L4 2z M12 14L4 22L20 22L12 14z",fill:"white"})})}):R.trim()===""?Yt.jsx("button",{type:"button",className:"mic-button",onClick:ot,disabled:H,style:{backgroundColor:"#1e4a5e"},children:Yt.jsxs("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[Yt.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"}),Yt.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"})]})}):Yt.jsx("button",{type:"submit",className:"mic-button",disabled:H,style:{backgroundColor:"#1e4a5e"},title:"Send",children:Yt.jsx("svg",{width:24,height:24,viewBox:"0 0 24 24",fill:"none","aria-hidden":"true",children:Yt.jsx("path",{d:"M19 12H5M19 12L14 17M19 12L14 7",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})})]})})})]}),Yt.jsx("div",{className:"avatar-wrapper",children:Yt.jsxs("div",{className:"avatar-scene-wrapper",children:[pt!=="hidden"&&Yt.jsx("div",{className:`avatar-bubble${pt==="entering"?" avatar-bubble--entering":pt==="exiting"?" avatar-bubble--exiting":""}`,onAnimationEnd:Ni,children:Yt.jsx("div",{ref:Rt,className:`avatar-bubble__content${kt?" avatar-bubble__content--nudge":""}`,children:qt})}),Yt.jsx("div",{className:"avatar-canvas-layer",style:{width:F,height:F},children:Yt.jsxs(zO,{shadows:!0,camera:{position:[.2,1.4,3],fov:42},gl:{alpha:!0},dpr:1.8,style:{pointerEvents:"none",width:"100%",height:"100%"},children:[Yt.jsx(a4,{target:si}),Yt.jsx("ambientLight",{intensity:.7}),Yt.jsx("directionalLight",{position:[0,2,2],intensity:1}),Yt.jsx(aF,{preset:"city"}),Yt.jsx(me.Suspense,{fallback:null,children:b!==null&&Yt.jsx(s4,{avatarUrl:b,isPlayingRef:ve,visemeQueueRef:K,audioContextRef:se,responseAudioStartTimeRef:at,adjustments:KF,mood:mt,expression:xe,agentResponse:M,isSpeaking:z,nextStartTimeRef:ge,stopPlayback:Qe,setIsSpeaking:V,expressionUrl:tt,onExpressionFinished:fa,isNudgeResponse:kt,avatarGender:x})})]})})]})})]}):null},l4=({agentId:s,onNavigationRequested:e,presetUserDetails:t,onAvatarReady:n})=>Yt.jsx(o4,{agentId:s,onNavigationRequested:e,presetUserDetails:t,onAvatarReady:n}),TC="streamoji-leads-avatar-widget-root";function CC(s){const{agentId:e}=s;let t=document.getElementById(TC);if(!t){t=document.createElement("div"),t.id=TC,t.style.cssText="position:fixed;bottom:0;right:0;z-index:9999;pointer-events:none;";const i=document.createElement("div");i.style.cssText="pointer-events:auto;",t.appendChild(i),document.body.appendChild(t),t=i}CR.createRoot(t).render(wM.createElement(l4,{agentId:e||""}))}return window.StreamojiLeadsAvatarWidget={init:CC},Hy.init=CC,Object.defineProperty(Hy,Symbol.toStringTag,{value:"Module"}),Hy})({});
|