import{e as c}from"./livewire.esm-C819BCfU.js";import{R as u,f as p}from"./lib.modern-DHFPEOLP.js";const v=(d,l)=>({agentId:d,uuId:l,bubbleMessage:"Need help?",conversation:null,audioRecorder:null,chatbotStatus:null,startConversationBtn:null,stopConversationBtn:null,audioVisEl:null,audioStream:null,init(){this.chatbotStatus=document.getElementById("lqd-ext-chatbot-voice-bot-status"),this.bubbleMessage=this.chatbotStatus.textContent,this.startConversationBtn=document.getElementById("lqd-ext-chatbot-voice-start-btn"),this.stopConversationBtn=document.getElementById("lqd-ext-chatbot-voice-end-btn"),this.audioVisEl=document.getElementById("lqd-ext-chatbot-voice-vis-img"),this.initRecorder(),this.addEventListeners()},addEventListeners(){this.startConversationBtn.addEventListener("click",()=>{this.startConversation()}),this.stopConversationBtn.addEventListener("click",()=>this.stopConversation())},async startConversation(){this.startConversationBtn.setAttribute("disabled",!0),this.startConversationBtn.querySelector("span").textContent="starting...";const t=await this.checkVoiceBalance(!0);if(t.shouldStop){this.startConversationBtn.removeAttribute("disabled"),this.startConversationBtn.querySelector("span").textContent="Voice Chat",alert(t.errorMsg);return}try{const o=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});this.audioStream=o,this.conversation=await p.startSession({agentId:this.agentId,onConnect:async()=>{var e;this.updateUIByStatus("calling"),await((e=this.audioRecorder)==null?void 0:e.start(o)),this.startDotVisualizer()},onDisconnect:()=>{var e,s;this.disconnectHandle((e=this.conversation)==null?void 0:e.connection),this.updateUIByStatus(),this.storeConversation(this.conversation.getId()),(s=this.audioRecorder)==null||s.stop(),this.stopAudioStream()},onModeChange:e=>{this.chatbotStatus.textContent=e.mode==="speaking"?"speaking":"listening",this.checkVoiceBalance().then(s=>{var a;if(s.shouldStop){console.log(s.shouldStop),this.updateUIByStatus(),(a=this.audioRecorder)==null||a.stop(),this.stopAudioStream(),this.stopConversation(),alert(s.errorMsg);return}})},onError:e=>{console.error("Error:",e)}})}catch(o){this.updateUIByStatus(),alert("Something went wrong with voice agent"),console.error(o)}},async stopConversation(){this.conversation&&(await this.conversation.endSession(),this.conversation=null)},async initRecorder(){try{this.audioRecorder=new u(this.handleAudioRecordingBuffer)}catch(t){console.error("Error starting audio recorder:",t)}},async storeConversation(t){const o=await fetch(`/api/v2/chatbot-voice/${this.uuId}/store-conversation`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({conversation_id:t})});try{const e=await o.json();o.ok||console.error("Failed create conversation:",e.message)}catch(e){console.error("Failed parse JSON:",e)}},updateUIByStatus(t="default"){t=="default"?(this.startConversationBtn.style.display="flex",this.stopConversationBtn.style.display="none",this.chatbotStatus.textContent=this.bubbleMessage,this.audioVisEl&&(this.audioVisEl.style.transform="scale(1)",this.audioVisEl.style.opacity=1),this.startConversationBtn.removeAttribute("disabled"),this.startConversationBtn.querySelector("span").textContent="Voice Chat"):t=="calling"&&(this.startConversationBtn.style.display="none",this.stopConversationBtn.style.display="flex")},stopAudioStream(){this.audioStream&&(this.audioStream.getTracks().forEach(t=>t.stop()),this.audioStream=null)},checkVoiceBalance(t=!1){return new Promise(async o=>{var e;try{const s=await fetch("/chatbot-voice/checkVoiceBalance",{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","X-CSRF-TOKEN":(e=document.querySelector('meta[name="csrf-token"]'))==null?void 0:e.content},body:JSON.stringify({onStart:t,uuId:this.uuId})});if(!s.ok){o({shouldStop:!0,errorMsg:"An error occurred."});return}const a=await s.json(),r=a.status==="error",i=a.message||"";o({shouldStop:r,errorMsg:i})}catch(s){console.error("checkBalance fetch failed:",s),o({shouldStop:!0,errorMsg:"An error occurred."})}})},handleAudioRecordingBuffer(t){},startDotVisualizer(){if(!this.audioRecorder||!this.audioVisEl)return;const t=this.audioRecorder.audioContext.createAnalyser();t.fftSize=256;const o=t.frequencyBinCount,e=new Uint8Array(o);if(this.audioRecorder.getMediaStreamSource().connect(t),!this.audioVisEl)return;const s=()=>{t.getByteFrequencyData(e);let a=0;for(let n=0;n<o;n++)a+=e[n];const i=1+a/o/256*1.2,h=Math.max(.2,1-(i-1)/1.5);this.audioVisEl.style.transform=`scale(${i})`,this.audioVisEl.style.opacity=h.toFixed(2),requestAnimationFrame(s)};s()},disconnectHandle(t){var o,e;((o=t==null?void 0:t.disconnectionDetails)==null?void 0:o.reason)=="error"&&alert(((e=t==null?void 0:t.disconnectionDetails)==null?void 0:e.message)||"Something went wrong on agent")}});window.Alpine=c;document.addEventListener("alpine:init",()=>{c.data("elevenLabsConversationalAI",v)});
