import{a as s,j as R}from"./react-CYZQF_UV.js";import{S as k,d as p,e as c,A as T,f as v}from"./livekit-IBzVVcEu.js";import{b as g}from"./main-CEJ7cS7B.js";import"./BroadcasterLive-D6NMA-d_.js";import"./three-Cs75aIhT.js";import"./index-Ec65i0Q1.js";import"./web3-D0IbNXhH.js";c.BROADCASTER,c.EXCITED,c.SERIOUS,c.EXCITED,c.SERIOUS;async function x(){try{const r=await g.post("/api/broadcaster/heygen-token",{});return r!=null&&r.ok&&r.token?r.token:null}catch{return null}}const M=({pendingLine:r,onLineConsumed:i,expression:f,avatarName:S="default",voiceId:y})=>{const[o,n]=s.useState("idle"),[A,E]=s.useState(null),u=s.useRef(null),m=s.useRef(null),h=s.useRef(f);return h.current=f,s.useEffect(()=>{let e=!1,t=null;return(async()=>{n("connecting");const a=await x();if(!e){if(!a){n("error"),E("token endpoint failed");return}try{t=new k({token:a}),m.current=t,t.on(p.STREAM_READY,l=>{const d=l==null?void 0:l.detail;u.current&&d&&(u.current.srcObject=d,u.current.play().catch(()=>{})),e||n("ready")}),t.on(p.STREAM_DISCONNECTED,()=>{e||(n("error"),E("stream disconnected"))}),await t.createStartAvatar({quality:T.Medium,avatarName:S,voice:y?{voiceId:y,emotion:c.BROADCASTER}:void 0})}catch(l){e||(n("error"),E(l.message))}}})(),()=>{var a;e=!0;try{(a=t==null?void 0:t.stopAvatar)==null||a.call(t)}catch{}m.current=null}},[S,y]),s.useEffect(()=>{const e=r==null?void 0:r.trim();if(!e)return;const t=m.current;!t||o!=="ready"||(async()=>{try{await t.speak({text:e,task_type:v.REPEAT})}catch(a){console.warn("[HeygenAvatarHost] speak error",a)}finally{i==null||i()}})()},[r,o,i]),R.jsxs("div",{className:`avatar-host avatar-host--${f}`,children:[R.jsx("video",{ref:u,className:"avatar-host__video",playsInline:!0,autoPlay:!0,muted:!1}),o!=="ready"&&R.jsxs("div",{className:"avatar-host__status",children:[o==="connecting"&&"Connecting to host…",o==="error"&&`Error: ${A??"unknown"}`,o==="idle"&&"Initialising…"]})]})};export{M as HeygenAvatarHost,M as default};
