import{e as c}from"./livewire.esm-CvVQJolS.js";import{R as u,f as p}from"./lib.modern-DJaFKjpz.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 e=await navigator.mediaDevices.getUserMedia({audio:!0,video:!1});this.audioStream=e,this.conversation=await p.startSession({agentId:this.agentId,onConnect:async()=>{this.updateUIByStatus("calling"),await this.audioRecorder?.start(e),this.startDotVisualizer()},onDisconnect:()=>{this.disconnectHandle(this.conversation?.connection),this.updateUIByStatus(),this.storeConversation(this.conversation.getId()),this.audioRecorder?.stop(),this.stopAudioStream()},onModeChange:o=>{this.chatbotStatus.textContent=o.mode==="speaking"?"speaking":"listening",this.checkVoiceBalance().then(s=>{if(s.shouldStop){console.log(s.shouldStop),this.updateUIByStatus(),this.audioRecorder?.stop(),this.stopAudioStream(),this.stopConversation(),alert(s.errorMsg);return}})},onError:o=>{console.error("Error:",o)}})}catch(e){this.updateUIByStatus(),alert("Something went wrong with voice agent"),console.error(e)}},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 e=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 o=await e.json();e.ok||console.error("Failed create conversation:",o.message)}catch(o){console.error("Failed parse JSON:",o)}},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 e=>{try{const o=await fetch("/chatbot-voice/checkVoiceBalance",{method:"POST",headers:{"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest","X-CSRF-TOKEN":document.querySelector('meta[name="csrf-token"]')?.content},body:JSON.stringify({onStart:t,uuId:this.uuId})});if(!o.ok){e({shouldStop:!0,errorMsg:"An error occurred."});return}const s=await o.json(),n=s.status==="error",i=s.message||"";e({shouldStop:n,errorMsg:i})}catch(o){console.error("checkBalance fetch failed:",o),e({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 e=t.frequencyBinCount,o=new Uint8Array(e);if(this.audioRecorder.getMediaStreamSource().connect(t),!this.audioVisEl)return;const s=()=>{t.getByteFrequencyData(o);let n=0;for(let a=0;a<e;a++)n+=o[a];const r=1+n/e/256*1.2,h=Math.max(.2,1-(r-1)/1.5);this.audioVisEl.style.transform=`scale(${r})`,this.audioVisEl.style.opacity=h.toFixed(2),requestAnimationFrame(s)};s()},disconnectHandle(t){t?.disconnectionDetails?.reason=="error"&&alert(t?.disconnectionDetails?.message||"Something went wrong on agent")}});window.Alpine=c;document.addEventListener("alpine:init",()=>{c.data("elevenLabsConversationalAI",v)});
