var Widget=(function(exports){'use strict';var v=Object.defineProperty;var _=(h,a,t)=>a in h?v(h,a,{enumerable:true,configurable:true,writable:true,value:t}):h[a]=t;var s=(h,a,t)=>_(h,typeof a!="symbol"?a+"":a,t);var x=document.createElement("template");x.innerHTML=`
  <style>
    * {
      font-family: system-ui, -apple-system, BlinkMacSystemFont, Arial, sans-serif;
      box-sizing: border-box;
      margin: 0;
      padding: 0;
    }

    :host {
      position: fixed;
      bottom: 40px;
      z-index: 2147483647;
    }

    :host(.position-bottom-left) { left: 16px; }
    :host(.position-bottom-right) { right: 16px; }
    :host(.position-bottom-middle) { left: 50%; transform: translateX(-50%); }

    .widget-container {
      position: relative;
      width: var(--panel-width, 360px);
      height: var(--panel-height, 135px);
      background: var(--secondary-color, #FFFFFF);
      border-radius: 16px;
      overflow: hidden;
      box-shadow: 0 8px 32px rgba(0,0,0,.15), 0 0 0 1px rgba(0,0,0,.05);
      transition: height 0.4s cubic-bezier(0.34, 1.56, 0.64, 1), width 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
    }

    .widget-container.expanded {
      height: 420px;
    }

    .widget-header {
      display: flex;
      flex-direction: column;
      gap: 12px;
      padding: 20px 20px 16px 20px;
    }

    .header-row {
      display: flex;
      width: 100%;
      align-items: end;
      gap: 12px;
    }

    .avatar {
      width: 36px;
      height: 36px;
      border-radius: 50%;
      background: rgba(0,0,0,.15);
      border: 1px solid rgba(0,0,0,.2);
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      animation: spin 3s linear infinite;
    }

    @keyframes spin {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }

    .avatar-inner {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: linear-gradient(135deg, rgba(0,0,0,.7), rgba(0,0,0,.15));
      animation: pulse 2s ease-in-out infinite;
    }

    @keyframes pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.6; }
    }

    .header-text {
      flex: 1;
      color: #000;
    }

    .header-title {
      font-size: 16px;
      font-weight: 400;
      line-height: 1.2;
    }

    .aide-text {
      font-weight: 600;
      background: linear-gradient(135deg, #000, #333);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    .header-subtitle {
      font-size: 12px;
      color: rgba(0,0,0,.6);
      margin-top: 2px;
    }

    .header-subtitle.listening {
      color: rgba(0,0,0,.7);
      font-weight: 500;
    }

    .cta-button {
      all: unset;
      box-sizing: border-box;
      width: 100%;
      padding: 12px 16px;
      background: var(--primary-color, #5B21B6);
      color: #fff;
      border-radius: 12px;
      text-align: center;
      font-size: 16px;
      font-weight: 600;
      cursor: pointer;
      box-shadow: 0 2px 8px rgba(0,0,0,.12);
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 12px;
      transition: transform 0.15s, box-shadow 0.15s;
    }

    .cta-button:hover {
      transform: scale(1.02);
      box-shadow: 0 4px 12px rgba(0,0,0,.18);
    }

    .cta-button:active {
      transform: scale(0.98);
    }

    .cta-button.hidden {
      display: none;
    }

    .mic-icon {
      width: 24px;
      height: 24px;
      fill: currentColor;
    }

    .transcript-container {
      padding: 0 20px 20px 20px;
      height: 320px;
      overflow-y: auto;
      opacity: 0;
      transition: opacity 0.3s;
    }

    .transcript-container.visible {
      opacity: 1;
    }

    .transcript-container::-webkit-scrollbar {
      width: 4px;
    }

    .transcript-container::-webkit-scrollbar-thumb {
      background: rgba(0,0,0,.2);
      border-radius: 2px;
    }

    .bubble {
      padding: 10px 14px;
      border-radius: 16px;
      line-height: 1.4;
      max-width: 80%;
      margin-bottom: 10px;
      font-size: 14px;
      animation: slideIn 0.3s ease-out;
    }

    @keyframes slideIn {
      from {
        opacity: 0;
        transform: translateY(10px) scale(0.95);
      }
      to {
        opacity: 1;
        transform: translateY(0) scale(1);
      }
    }

    .bubble.agent {
      background: var(--primary-color, #5B21B6);
      color: #fff;
      align-self: flex-start;
      border-top-left-radius: 4px;
      margin-right: auto;
    }

    .bubble.user {
      background: rgba(0,0,0,.08);
      color: #111827;
      border: 1px solid rgba(0,0,0,.1);
      align-self: flex-end;
      border-top-right-radius: 4px;
      margin-left: auto;
    }

    .call-controls {
      position: absolute;
      bottom: 12px;
      left: 12px;
      right: 12px;
      display: none;
      align-items: center;
      justify-content: space-between;
      pointer-events: none;
    }

    .call-controls.visible {
      display: flex;
    }

    .control-btn {
      all: unset;
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      pointer-events: auto;
      transition: transform 0.15s, background 0.15s;
      box-shadow: 0 2px 8px rgba(0,0,0,.15);
    }

    .control-btn:hover {
      transform: scale(1.05);
    }

    .control-btn:active {
      transform: scale(0.95);
    }

    .mute-btn {
      background: rgba(255,255,255,.9);
      color: #000;
    }

    .hangup-btn {
      background: #E02424;
      color: #fff;
    }

    .hangup-btn:hover {
      background: #C41E1E;
    }

    .control-icon {
      width: 20px;
      height: 20px;
      fill: currentColor;
    }

    .powered-by {
      position: absolute;
      bottom: -24px;
      left: 0;
      right: 0;
      text-align: center;
      font-size: 11px;
      color: rgba(0,0,0,.5);
    }

    .powered-by a {
      color: inherit;
      text-decoration: underline;
    }

    .powered-by a:hover {
      color: rgba(0,0,0,.7);
    }
  </style>

  <div class="widget-container">
    <div class="widget-header">
      <div class="header-row">
        <div class="avatar">
          <div class="avatar-inner"></div>
        </div>
        <div class="header-text">
          <div class="header-title">
            Talk to <span class="aide-text">aide</span>
          </div>
          <div class="header-subtitle">Our Voice-Powered AI</div>
        </div>
      </div>

      <button class="cta-button">
        <svg class="mic-icon" viewBox="0 0 24 24">
          <path d="M12 14a4 4 0 0 0 4-4V5a4 4 0 1 0-8 0v5a4 4 0 0 0 4 4Zm7-4a1 1 0 0 0-2 0 5 5 0 0 1-10 0 1 1 0 0 0-2 0 7 7 0 0 0 6 6.92V20H9a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2h-2v-3.08A7 7 0 0 0 19 10Z"/>
        </svg>
        Ask anything
      </button>
    </div>

    <div class="transcript-container"></div>

    <div class="call-controls">
      <button class="control-btn mute-btn" title="Mute/Unmute">
        <svg class="control-icon mic-on" viewBox="0 0 24 24">
          <path d="M12 14a4 4 0 0 0 4-4V5a4 4 0 1 0-8 0v5a4 4 0 0 0 4 4Zm7-4a1 1 0 0 0-2 0 5 5 0 0 1-10 0 1 1 0 0 0-2 0 7 7 0 0 0 6 6.92V20H9a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2h-2v-3.08A7 7 0 0 0 19 10Z"/>
        </svg>
        <svg class="control-icon mic-off" style="display:none;" viewBox="0 0 24 24">
          <path d="M15 10.6V5a3 3 0 0 0-6 0v.4l6 6ZM12 14a4.003 4.003 0 0 1-3.626-2.327l-1.33 1.33A6 6 0 0 0 11 16.92V20H9a1 1 0 1 0 0 2h6a1 1 0 1 0 0-2h-2v-3.08a6.003 6.003 0 0 0 3.955-3.918l-1.33-1.33A4 4 0 0 1 12 14Zm8.71-3.29a1 1 0 1 0-1.42 0l-16 16a1 1 0 0 0 1.42 1.42l16-16a1 1 0 0 0 0-1.42Z"/>
        </svg>
      </button>

      <button class="control-btn hangup-btn" title="End call">
        <svg class="control-icon" viewBox="0 0 24 24">
          <path d="M15.5 1h-8C6.12 1 5 2.12 5 3.5v17C5 21.88 6.12 23 7.5 23h8c1.38 0 2.5-1.12 2.5-2.5v-17C16 2.12 14.88 1 13.5 1zm-4 21c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm4.5-4H7V4h9v14z"/>
        </svg>
      </button>
    </div>
  </div>

  <div class="powered-by">
    <a href="https://replicaide.com" target="_blank">Powered by ReplicAIDE</a>
  </div>
`;var y=class extends HTMLElement{constructor(){super(...arguments);s(this,"_outputFormat","pcm_16000");s(this,"_conversationInitiated",false);s(this,"_container");s(this,"_ctaButton");s(this,"_transcriptContainer");s(this,"_subtitle");s(this,"_callControls");s(this,"_muteBtn");s(this,"_hangupBtn");s(this,"_ws");s(this,"_isMuted",false);s(this,"_audioStream");s(this,"_audioContext");s(this,"_audioProcessor");s(this,"_audioQueue",[]);s(this,"_isPlayingAudio",false);s(this,"_playbackAudioContext");}static get observedAttributes(){return ["primary_color","secondary_color","size","position"]}connectedCallback(){this.shadowRoot||this.attachShadow({mode:"open"}).appendChild(x.content.cloneNode(true)),this.applyStyles(),this._container=this.shadowRoot.querySelector(".widget-container"),this._ctaButton=this.shadowRoot.querySelector(".cta-button"),this._transcriptContainer=this.shadowRoot.querySelector(".transcript-container"),this._subtitle=this.shadowRoot.querySelector(".header-subtitle"),this._callControls=this.shadowRoot.querySelector(".call-controls"),this._muteBtn=this.shadowRoot.querySelector(".mute-btn"),this._hangupBtn=this.shadowRoot.querySelector(".hangup-btn"),this._ctaButton.addEventListener("click",()=>this.startConversation()),this._hangupBtn.addEventListener("click",()=>this.endCall()),this._muteBtn.addEventListener("click",()=>this.toggleMute());}attributeChangedCallback(){this.shadowRoot&&this.applyStyles();}applyStyles(){let t=this.getAttribute("primary_color")||"#5B21B6",i=this.getAttribute("secondary_color")||"#FFFFFF";this.style.setProperty("--primary-color",t),this.style.setProperty("--secondary-color",i);let e=parseInt(this.getAttribute("size")||"5",10),c=Math.min(Math.max(180+(e-4)*40,220),560),r=e<5?96:135;this.style.setProperty("--panel-width",`${c}px`),this.style.setProperty("--panel-height",`${r}px`);let l=this.getAttribute("position")||"bottom-right";this.className=`position-${l}`;}async startConversation(){let t=this.getAttribute("widgetid")||this.getAttribute("widgetId"),i="https://app.replicaide.com";if(!t){console.error("[replica-mic] missing widgetId");return}this._container.classList.add("expanded"),this._ctaButton.classList.add("hidden"),this._transcriptContainer.classList.add("visible"),this._subtitle.textContent="Connecting...";try{let e=await fetch(`${i}/api/eleven/session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({widgetId:t})});if(!e.ok){let l=await e.text();console.error("[replica-mic] backend failed",l),this._subtitle.textContent="Connection failed",this.showErrorAndClose();return}let{ws_url:c}=await e.json(),r=new WebSocket(c);this._ws=r,r.onopen=()=>{console.log("[replica-mic] WebSocket connected"),setTimeout(()=>{this._conversationInitiated||(this._conversationInitiated=!0,this.openMicStream(r),this._subtitle.textContent="Listening\u2026",this._subtitle.classList.add("listening"),this._callControls.classList.add("visible"));},2e3);},r.onclose=()=>{console.log("[replica-mic] WebSocket closed"),this.cleanupAudio(),this.resetUI();},r.onmessage=l=>{var p,d,u,g;try{let o=JSON.parse(l.data);if(console.log("[replica-mic] Received message:",o.type),o.type==="ping"){let n=(p=o.ping_event)!=null&&p.event_id?{type:"pong",event_id:o.ping_event.event_id}:{type:"pong"};r.send(JSON.stringify(n));return}if(o.type==="conversation_initiation_metadata"||o.type==="conversation_initiation_complete"){console.log("[replica-mic] Conversation initiated"),this._conversationInitiated=!0,this.openMicStream(r),this._subtitle.textContent="Listening\u2026",this._subtitle.classList.add("listening"),this._callControls.classList.add("visible");return}if(o.type==="user_transcript"){let n=(d=o.user_transcription_event)==null?void 0:d.user_transcript;n?(console.log("[replica-mic] User transcript:",n),this.showTranscript(n,"user")):console.warn("[replica-mic] User transcript received but no text found");return}if(o.type==="agent_response"){let n=o.agent_response||((u=o.agent_response_event)==null?void 0:u.agent_response);n&&(console.log("[replica-mic] Agent response:",n),this.showTranscript(n,"agent"));return}if(o.type==="audio"){let n=o.audio_base_64||((g=o.audio_event)==null?void 0:g.audio_base_64);n&&(console.log("[replica-mic] Audio chunk received, length:",n.length),this.queueAudio(n));return}if(o.type==="interruption"){console.log("[replica-mic] Interruption detected"),this.clearAudioQueue();return}}catch(o){console.error("[replica-mic] Error parsing message:",o);}},r.onerror=l=>{console.error("[replica-mic] WebSocket error",l),this._subtitle.textContent="Connection error",this.showErrorAndClose();};}catch(e){console.error("[replica-mic] Error starting conversation",e),this._subtitle.textContent="Connection error",this.showErrorAndClose();}}async openMicStream(t){try{let i=await navigator.mediaDevices.getUserMedia({audio:!0}),e=new(window.AudioContext||window.webkitAudioContext)({sampleRate:48e3}),c=e.createMediaStreamSource(i),r=e.createScriptProcessor(4096,1,1);this._audioStream=i,this._audioContext=e,this._audioProcessor=r,c.connect(r),r.connect(e.destination),t.send(JSON.stringify({type:"audio_start"})),r.onaudioprocess=l=>{if(t.readyState!==1||this._isMuted)return;let p=l.inputBuffer.getChannelData(0),d=this.downsampleBuffer(p,e.sampleRate,16e3),u=this.floatTo16BitPCM(d),g=btoa(String.fromCharCode(...new Uint8Array(u.buffer)));t.send(JSON.stringify({type:"user_audio_chunk",user_audio_chunk:g}));};}catch(i){console.error("[replica-mic] Microphone error",i),this._subtitle.textContent="Microphone access denied",this.showErrorAndClose();}}cleanupAudio(){this._audioStream&&(this._audioStream.getTracks().forEach(t=>{t.stop(),console.log("[replica-mic] Stopped audio track");}),this._audioStream=void 0),this._audioProcessor&&(this._audioProcessor.disconnect(),this._audioProcessor=void 0),this._audioContext&&this._audioContext.state!=="closed"&&(this._audioContext.close().catch(t=>console.error("[replica-mic] Error closing AudioContext",t)),this._audioContext=void 0),this.clearAudioQueue(),this._playbackAudioContext&&this._playbackAudioContext.state!=="closed"&&(this._playbackAudioContext.close().catch(t=>console.error("[replica-mic] Error closing playback AudioContext",t)),this._playbackAudioContext=void 0);}downsampleBuffer(t,i,e){if(e===i)return this.floatTo16BitPCM(t);let c=i/e,r=Math.round(t.length/c),l=new Int16Array(r),p=0,d=0;for(;p<l.length;){let u=Math.round((p+1)*c),g=0,o=0;for(let n=d;n<u&&n<t.length;n++)g+=t[n],o++;l[p]=Math.max(-32768,Math.min(32767,g/o*32767)),p++,d=u;}return l}floatTo16BitPCM(t){if(t instanceof Int16Array)return t;let i=new Int16Array(t.length);for(let e=0;e<t.length;e++)i[e]=Math.max(-32768,Math.min(32767,t[e]*32767));return i}showTranscript(t,i){let e=document.createElement("div");e.className=`bubble ${i}`,e.textContent=t,this._transcriptContainer.appendChild(e),this._transcriptContainer.scrollTop=this._transcriptContainer.scrollHeight;}queueAudio(t){this._audioQueue.push(t),console.log("[replica-mic] Audio queued, queue size:",this._audioQueue.length),this._isPlayingAudio||this.processAudioQueue();}clearAudioQueue(){console.log("[replica-mic] Clearing audio queue"),this._audioQueue=[],this._isPlayingAudio=false;}async processAudioQueue(){if(this._audioQueue.length===0){this._isPlayingAudio=false,console.log("[replica-mic] Audio queue empty, playback finished");return}this._isPlayingAudio=true;let t=this._audioQueue.shift();console.log("[replica-mic] Playing audio chunk, remaining in queue:",this._audioQueue.length);try{await this.playAudioChunk(t);}catch(i){console.error("[replica-mic] Error playing audio chunk:",i);}this.processAudioQueue();}playAudioChunk(t){return new Promise((i,e)=>{try{let c=Uint8Array.from(atob(t),d=>d.charCodeAt(0));if(this._outputFormat==="pcm_16000"){let d=c.length/2;this._playbackAudioContext||(this._playbackAudioContext=new(window.AudioContext||window.webkitAudioContext)({sampleRate:16e3}));let u=this._playbackAudioContext,g=new Int16Array(c.buffer),o=u.createBuffer(1,d,16e3),n=o.getChannelData(0);for(let m=0;m<d;m++)n[m]=g[m]/32768;let b=u.createBufferSource();b.buffer=o,b.connect(u.destination),b.onended=()=>{console.log("[replica-mic] Audio chunk finished playing"),i();},b.start();return}let r=new Blob([c],{type:"audio/mpeg"}),l=URL.createObjectURL(r),p=new Audio(l);p.onended=()=>{URL.revokeObjectURL(l),i();},p.onerror=d=>{URL.revokeObjectURL(l),e(d);},p.play().catch(e);}catch(c){e(c);}})}toggleMute(){this._isMuted=!this._isMuted;let t=this._muteBtn.querySelector(".mic-on"),i=this._muteBtn.querySelector(".mic-off");this._isMuted?(t.style.display="none",i.style.display="block"):(t.style.display="block",i.style.display="none");}endCall(){this._ws&&this._ws.readyState===1&&this._ws.close(1e3,"client-hangup"),this.cleanupAudio(),this.resetUI();}showErrorAndClose(){this.cleanupAudio(),setTimeout(()=>{this.resetUI();},3e3);}resetUI(){this._container.classList.remove("expanded"),this._ctaButton.classList.remove("hidden"),this._transcriptContainer.classList.remove("visible"),this._transcriptContainer.innerHTML="",this._subtitle.textContent="Our Voice-Powered AI",this._subtitle.classList.remove("listening"),this._callControls.classList.remove("visible"),this._conversationInitiated=false,this._isMuted=false;}};customElements.get("replica-mic")||customElements.define("replica-mic",y);var f=new Map;function w(h){let{widgetId:a}=h;if(f.has(a))return console.log(`[Widget] Widget ${a} already initialized, skipping`),f.get(a);let t=document.querySelector(`replica-mic[widgetid="${a}"]`);if(t)return console.log(`[Widget] Widget ${a} already in DOM, skipping`),f.set(a,t),t;let i=document.createElement("replica-mic");return i.setAttribute("widgetid",a),Object.entries(h).forEach(([e,c])=>{c!==void 0&&e!=="widgetId"&&i.setAttribute(e,String(c));}),f.set(a,i),document.body.appendChild(i),i}typeof window!="undefined"&&(window.Widget={init:w});
exports.init=w;return exports;})({});