@botzki/react 0.1.1 → 0.1.3

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/dist/index.mjs CHANGED
@@ -1,4 +1,139 @@
1
- import {createContext,forwardRef,useState,useEffect,useCallback,useImperativeHandle,useContext,useMemo,useRef}from'react';import {Botzki}from'@botzki/js';import {jsxs,jsx}from'react/jsx-runtime';import {createPortal}from'react-dom';var ie=createContext(null);function ae(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"sess_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function Te({botId:t,publishableKey:e,baseUrl:l,apiHost:p,user:b,defaultSessionId:a,client:m,children:y}){let g=p||l||"https://api.botzki.com",[u,c]=useState(()=>{if(a)return a;if(typeof window<"u")try{let h=localStorage.getItem(`botzki_session_${t}`);if(h)return h;let M=ae();return localStorage.setItem(`botzki_session_${t}`,M),M}catch{return ae()}return a||ae()}),n=useMemo(()=>m||new Botzki({botId:t,publishableKey:e,apiHost:g}),[m,t,e,g]);useEffect(()=>{b&&n&&typeof n.setUser=="function"&&n.setUser(b);},[n,b]);let w=useMemo(()=>({client:n,botId:t,publishableKey:e,baseUrl:g,apiHost:g,user:b,sessionId:u,setSessionId:c}),[n,t,e,g,b,u]);return jsx(ie.Provider,{value:w,children:y})}function O(){let t=useContext(ie);if(!t)throw new Error("useBotzki must be used within a <BotzkiProvider>. Wrap your application or component with <BotzkiProvider botId='...' publishableKey='...'>.");return t}function te(){return useContext(ie)}function le(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"msg_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function oe(t={}){let e=te(),l=t.botId||e?.botId,p=t.publishableKey||e?.publishableKey,b=t.baseUrl||e?.baseUrl||"https://api.botzki.com",a=useMemo(()=>e?.client&&(!t.botId||t.botId===e.botId)?e.client:l&&p?new Botzki({botId:l,publishableKey:p,apiHost:b}):null,[e?.client,e?.botId,t.botId,l,p,b]),m=t.storageKey||(l?`botzki_chat_history_${l}`:"botzki_chat_history"),y=t.persistSession??true,[g,u]=useState(()=>t.sessionId?t.sessionId:e?.sessionId?e.sessionId:"sess_"+Math.random().toString(36).substring(2,9)),[c,n]=useState(t.initialMessages||[]),[w,h]=useState(""),[M,S]=useState(false),[P,B]=useState(false),[Q,U]=useState(null),R=useRef(null),$=useRef(c);$.current=c,useEffect(()=>{if(!(!y||typeof window>"u"||t.initialMessages?.length))try{let o=localStorage.getItem(m);if(o){let f=JSON.parse(o);Array.isArray(f)&&n(f.map(x=>({...x,createdAt:new Date(x.createdAt)})));}}catch{}},[y,m,t.initialMessages?.length]),useEffect(()=>{if(!(!y||typeof window>"u"))try{c.length>0&&localStorage.setItem(m,JSON.stringify(c));}catch{}},[c,y,m]);let z=useCallback(()=>{R.current&&(R.current.abort(),R.current=null),S(false),B(false);},[]),T=useCallback(async(o,f)=>{let x=o.trim();if(!x&&!f?.imageBase64)return;if(!l){let d=new Error("botId is required. Provide botId in options or wrap your component tree in <BotzkiProvider botId='...'>");U(d),t.onError?.(d);return}U(null),S(true),B(t.stream!==false);let j={id:le(),role:"user",content:x,createdAt:new Date},k=le(),L={id:k,role:"assistant",content:"",createdAt:new Date,isStreaming:t.stream!==false};n(d=>[...d,j,L]);let I=new AbortController;R.current=I;try{if(t.stream!==!1){let d="";if(a&&typeof a.chatStream=="function")await a.chatStream({message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType,onDelta:i=>{I.signal.aborted||(d+=i,n(s=>s.map(r=>r.id===k?{...r,content:d}:r)));},onDone:i=>{if(I.signal.aborted)return;let s={id:k,role:"assistant",content:i.reply||d,createdAt:new Date,citations:i.citations,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onResponse?.(i),t.onFinish?.(s);},onError:i=>{I.signal.aborted||(U(i),S(!1),B(!1),n(s=>s.map(r=>r.id===k?{...r,isStreaming:!1,error:i.message}:r)),t.onError?.(i));}});else if(a&&typeof a.stream=="function")await a.stream({message:x,sessionId:g,language:t.language,onToken:i=>{I.signal.aborted||(d+=i,n(s=>s.map(r=>r.id===k?{...r,content:d}:r)));},onDone:i=>{if(I.signal.aborted)return;let s={id:k,role:"assistant",content:i||d,createdAt:new Date,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onFinish?.(s);},onError:i=>{I.signal.aborted||(U(i),S(!1),B(!1),n(s=>s.map(r=>r.id===k?{...r,isStreaming:!1,error:i.message}:r)),t.onError?.(i));}});else {let i=b?b.replace(/\/+$/,""):"https://api.botzki.com",s={"Content-Type":"application/json"};p&&(s.Authorization=`Bearer ${p}`);let r=await fetch(`${i}/api/v1/public/chat/${l}/stream`,{method:"POST",headers:s,body:JSON.stringify({query:x,message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType}),signal:I.signal});if(!r.ok){let G=`Chat request failed with status ${r.status}`;try{let N=await r.json();N?.message&&(G=N.message);}catch{}throw new Error(G)}let C=r.body?.getReader();if(!C)throw new Error("Response body is not readable.");let A=new TextDecoder("utf-8"),_="",V=[];for(;;){let{done:G,value:N}=await C.read();if(G||I.signal.aborted)break;_+=A.decode(N,{stream:!0});let me=_.split(`
2
- `);_=me.pop()||"";for(let re of me)if(re=re.trim(),re.startsWith("data: ")){let Se=re.slice(6);try{let X=JSON.parse(Se);X.delta&&(d+=X.delta,n(ze=>ze.map(se=>se.id===k?{...se,content:d}:se))),X.answer&&(d=X.answer),X.citations&&(V=X.citations);}catch{}}}let ee={id:k,role:"assistant",content:d,createdAt:new Date,citations:V.length>0?V:void 0,isStreaming:!1};n(G=>G.map(N=>N.id===k?ee:N)),S(!1),B(!1),t.onResponse?.({reply:d,answer:d,citations:V,insufficientEvidence:!1,sessionId:g}),t.onFinish?.(ee);}}else {let d="",i=[];if(a&&typeof a.chat=="function"){let r=await a.chat({message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType});d=r.reply||r.answer,i=r.citations||[];}else {let r=b?b.replace(/\/+$/,""):"https://api.botzki.com",C={"Content-Type":"application/json"};p&&(C.Authorization=`Bearer ${p}`);let A=await fetch(`${r}/api/v1/public/chat/${l}`,{method:"POST",headers:C,body:JSON.stringify({query:x,message:x,sessionId:g,language:t.language,imageBase64:f?.imageBase64,imageMimeType:f?.imageMimeType}),signal:I.signal});if(!A.ok){let V=`Chat request failed with status ${A.status}`;try{let ee=await A.json();ee?.message&&(V=ee.message);}catch{}throw new Error(V)}let _=await A.json();d=_.reply||_.answer||"",i=_.citations||[];}let s={id:k,role:"assistant",content:d,createdAt:new Date,citations:i.length>0?i:void 0,isStreaming:!1};n(r=>r.map(C=>C.id===k?s:C)),S(!1),B(!1),t.onResponse?.({reply:d,answer:d,citations:i,insufficientEvidence:!1,sessionId:g}),t.onFinish?.(s);}}catch(d){if(!I.signal.aborted){let i=d instanceof Error?d:new Error(String(d));U(i),S(false),B(false),n(s=>s.map(r=>r.id===k?{...r,isStreaming:false,error:i.message}:r)),t.onError?.(i);}}finally{R.current===I&&(R.current=null);}},[a,t,g]),F=useCallback(o=>{h(o.target.value);},[]),W=useCallback(async(o,f)=>{o&&typeof o.preventDefault=="function"&&o.preventDefault();let x=w;h(""),await T(x,f);},[w,T]),D=useCallback(o=>{let f={id:o.id||le(),role:o.role||"user",content:o.content,createdAt:o.createdAt||new Date,citations:o.citations,isStreaming:o.isStreaming,error:o.error};n(x=>[...x,f]);},[]),H=useCallback(async()=>{let o=$.current;if(o.length===0)return;let f=o.map(j=>j.role).lastIndexOf("user");if(f===-1)return;let x=o[f];n(o.slice(0,f)),await T(x.content);},[T]),Y=useCallback(()=>{if(z(),n([]),y&&typeof window<"u")try{localStorage.removeItem(m);}catch{}},[z,y,m]);return {messages:c,input:w,setInput:h,handleInputChange:F,handleSubmit:W,sendMessage:T,append:D,reload:H,stop:z,clearMessages:Y,setMessages:n,isLoading:M,isStreaming:P,error:Q,sessionId:g,setSessionId:u}}function de(){let{client:t,botId:e,baseUrl:l}=O(),[p,b]=useState(null),[a,m]=useState(true),[y,g]=useState(null),u=useCallback(async()=>{m(true),g(null);try{let c;if(typeof t.getBotInfo=="function")c=await t.getBotInfo();else {let n=l?l.replace(/\/+$/,""):"https://api.botzki.com";c=await(await fetch(`${n}/api/v1/public/chat/${e}`)).json();}b(c);}catch(c){g(c instanceof Error?c:new Error(String(c)));}finally{m(false);}},[t,e,l]);return useEffect(()=>{u();},[u,e]),{data:p,isLoading:a,error:y,refetch:u}}function ue({title:t,subtitle:e="Online",greeting:l="Hello! How can I help you today?",starterQuestions:p,theme:b="auto",primaryColor:a="#0ea5e9",className:m="",style:y,placeholder:g="Ask a question...",onClose:u,showCloseButton:c=false,showClearButton:n=true,chat:w,...h}){let M=oe(h),S=w||M,{messages:P,input:B,handleInputChange:Q,handleSubmit:U,sendMessage:R,clearMessages:$,isLoading:z,isStreaming:T,error:F}=S,{data:W}=de(),D=useRef(null);useEffect(()=>{D.current&&(D.current.scrollTop=D.current.scrollHeight);},[P,T]);let H=t||W?.name||"AI Assistant",Y=p||W?.starterQuestions||[],o=b==="dark"||b==="auto"&&typeof window<"u"&&window.matchMedia("(prefers-color-scheme: dark)").matches,f=o?"#0f172a":"#ffffff",x=o?"#1e293b":"#f8fafc",j=o?"#f8fafc":"#0f172a",k=o?"#94a3b8":"#64748b",L=o?"#334155":"#e2e8f0",I=a,d=o?"#1e293b":"#f1f5f9",i=o?"#f1f5f9":"#1e293b";return jsxs("div",{className:m,style:{display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:"450px",backgroundColor:f,color:j,borderRadius:"16px",border:`1px solid ${L}`,overflow:"hidden",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',boxSizing:"border-box",...y},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",backgroundColor:x,borderBottom:`1px solid ${L}`},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[jsx("div",{style:{width:"36px",height:"36px",borderRadius:"50%",backgroundColor:a,display:"flex",alignItems:"center",justifyContent:"center",color:"#ffffff",fontWeight:"bold",fontSize:"15px"},children:H.charAt(0).toUpperCase()}),jsxs("div",{children:[jsx("div",{style:{fontWeight:600,fontSize:"14px",lineHeight:1.2},children:H}),jsxs("div",{style:{fontSize:"12px",color:k,display:"flex",alignItems:"center",gap:"5px",marginTop:"2px"},children:[jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",backgroundColor:"#22c55e",display:"inline-block"}}),e]})]})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[P.length>0&&n&&jsx("button",{onClick:$,title:"Clear Chat",type:"button",style:{background:"transparent",border:"none",color:k,cursor:"pointer",fontSize:"12px",padding:"4px 8px",borderRadius:"6px"},children:"Clear"}),c&&u&&jsx("button",{onClick:u,title:"Close Chat",type:"button",style:{background:"transparent",border:"none",color:k,cursor:"pointer",fontSize:"16px",padding:"4px 8px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center"},children:"\u2715"})]})]}),jsxs("div",{ref:D,style:{flex:1,overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"12px"},children:[l&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{maxWidth:"80%",padding:"10px 14px",borderRadius:"14px",backgroundColor:d,color:i,fontSize:"14px",lineHeight:1.45},children:l})}),P.length===0&&Y.length>0&&jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"8px"},children:[jsx("span",{style:{fontSize:"11px",color:k,fontWeight:500},children:"SUGGESTED QUESTIONS"}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:Y.map((s,r)=>jsx("button",{onClick:()=>R(s),style:{backgroundColor:o?"#1e293b":"#f1f5f9",color:j,border:`1px solid ${L}`,padding:"6px 12px",borderRadius:"20px",fontSize:"12px",cursor:"pointer",textAlign:"left",transition:"all 0.15s ease"},children:s},r))})]}),P.map(s=>{let r=s.role==="user";return jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"flex-start"},children:jsxs("div",{style:{maxWidth:"85%",padding:"10px 14px",borderRadius:"14px",backgroundColor:r?I:d,color:r?"#ffffff":i,fontSize:"14px",lineHeight:1.45,whiteSpace:"pre-wrap",wordBreak:"break-word"},children:[s.content,s.citations&&s.citations.length>0&&jsxs("div",{style:{marginTop:"8px",paddingTop:"6px",borderTop:`1px solid ${r?"rgba(255,255,255,0.2)":L}`,fontSize:"11px",display:"flex",flexWrap:"wrap",gap:"4px"},children:[jsx("span",{style:{opacity:.8},children:"Sources:"}),s.citations.map((C,A)=>jsxs("span",{style:{backgroundColor:r?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.06)",padding:"2px 6px",borderRadius:"4px",fontWeight:500},children:[C.source," ",C.page_number?`p.${C.page_number}`:""]},A))]}),s.error&&jsxs("div",{style:{marginTop:"6px",fontSize:"12px",color:"#ef4444"},children:["Error: ",s.error]})]})},s.id)}),z&&!T&&jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:jsx("div",{style:{padding:"8px 14px",borderRadius:"14px",backgroundColor:d,color:k,fontSize:"13px"},children:"Thinking..."})}),F&&jsx("div",{style:{padding:"8px 12px",borderRadius:"8px",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444",fontSize:"12px"},children:F.message})]}),jsxs("form",{onSubmit:U,style:{display:"flex",alignItems:"center",gap:"8px",padding:"12px 16px",borderTop:`1px solid ${L}`,backgroundColor:x},children:[jsx("input",{type:"text",value:B,onChange:Q,placeholder:g,disabled:z,style:{flex:1,padding:"10px 14px",borderRadius:"22px",border:`1px solid ${L}`,backgroundColor:f,color:j,fontSize:"14px",outline:"none"}}),jsx("button",{type:"submit",disabled:z||!B.trim(),style:{backgroundColor:a,color:"#ffffff",border:"none",borderRadius:"20px",padding:"10px 18px",fontWeight:600,fontSize:"13px",cursor:z||!B.trim()?"not-allowed":"pointer",opacity:z||!B.trim()?.5:1,transition:"opacity 0.2s ease"},children:"Send"})]})]})}var je=forwardRef(function(e,l){let p=te(),b=e.botId||p?.botId,a=e.publishableKey||p?.publishableKey,m=e.baseUrl||p?.baseUrl||"https://api.botzki.com",[y,g]=useState(false),[u,c]=useState(false),[n,w]=useState(true),[h,M]=useState(e.theme||"dark"),[S,P]=useState(e.primaryColor||"#0ea5e9"),[,B]=useState(e.user||p?.user),[Q,U]=useState(false);useEffect(()=>{e.theme&&M(e.theme);},[e.theme]),useEffect(()=>{e.primaryColor&&P(e.primaryColor);},[e.primaryColor]),useEffect(()=>{e.user&&B(e.user);},[e.user]),useEffect(()=>{g(true);},[]);let R=oe({botId:b,publishableKey:a,baseUrl:m,persistSession:e.persistSession??true,onResponse:e.onMessage?o=>e.onMessage?.({role:"assistant",content:o.reply}):void 0,onError:e.onError}),$=useCallback(()=>{c(true),e.onOpen?.();},[e.onOpen]),z=useCallback(()=>{c(false),e.onClose?.();},[e.onClose]),T=useCallback(()=>{c(o=>{let f=!o;return f?e.onOpen?.():e.onClose?.(),f});},[e.onOpen,e.onClose]);if(useImperativeHandle(l,()=>({open:$,close:z,toggle:T,isOpen:()=>u,show:()=>w(true),hide:()=>{w(false),z();},sendMessage:async(o,f)=>{$(),await R.sendMessage(o,f?{imageBase64:f}:void 0);},clearMessages:()=>R.clearMessages(),setTheme:o=>M(o),setPrimaryColor:o=>P(o),setUser:o=>B(o)}),[$,z,T,u,R]),!y||typeof document>"u")return null;let F=e.position==="bottom-left",W=e.offset?.x??24,D=e.offset?.y??24,H=e.zIndex??2147483647,Y=jsxs("div",{id:"botzki-react-widget-container",style:{display:n?"block":"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[jsx("div",{role:"dialog","aria-label":"Botzki AI Chat",style:{position:"fixed",bottom:D+68,[F?"left":"right"]:W,width:"380px",maxWidth:"calc(100vw - 32px)",height:"580px",maxHeight:"calc(100vh - 110px)",zIndex:H,boxShadow:"0 20px 40px -10px rgba(0, 0, 0, 0.4), 0 0 1px 1px rgba(255, 255, 255, 0.1)",borderRadius:"16px",overflow:"hidden",transition:"opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1), visibility 0.25s",opacity:u?1:0,transform:u?"translateY(0) scale(1)":"translateY(16px) scale(0.95)",visibility:u?"visible":"hidden",pointerEvents:u?"auto":"none"},children:jsx(ue,{chat:R,title:e.widgetTitle,subtitle:e.widgetSubtitle||"Online",greeting:e.greeting,starterQuestions:e.starterPrompts,theme:h,primaryColor:S,showCloseButton:e.showCloseButton!==false,showClearButton:e.showClearButton!==false,onClose:z,style:{height:"100%",borderRadius:"16px"}})}),jsx("button",{type:"button",onClick:T,onMouseEnter:()=>U(true),onMouseLeave:()=>U(false),"aria-label":u?"Close AI Support Chat":"Open AI Support Chat",style:{position:"fixed",bottom:D,[F?"left":"right"]:W,width:"56px",height:"56px",borderRadius:"50%",backgroundColor:S,color:"#ffffff",border:"none",outline:"none",cursor:"pointer",boxShadow:Q?"0 10px 24px rgba(0, 0, 0, 0.35), 0 4px 8px rgba(0, 0, 0, 0.2)":"0 6px 16px rgba(0, 0, 0, 0.24), 0 3px 6px rgba(0, 0, 0, 0.12)",zIndex:H,display:"flex",alignItems:"center",justifyContent:"center",transform:Q?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), box-shadow 0.2s ease"},children:u?jsxs("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):jsx("svg",{viewBox:"0 0 24 24",width:"26",height:"26",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})})]});return createPortal(Y,document.body)});function _e(){let{client:t,botId:e,baseUrl:l,sessionId:p}=O(),[b,a]=useState(false),[m,y]=useState(false),[g,u]=useState(null),c=useCallback(async w=>{a(true),u(null),y(false);try{if(typeof t.submitFeedback=="function")await t.submitFeedback({...w,sessionId:p});else {let h=l?l.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${h}/api/v1/public/chat/${e}/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...w,sessionId:p})});}return y(!0),!0}catch(h){let M=h instanceof Error?h:new Error(String(h));return u(M),false}finally{a(false);}},[t,e,l,p]),n=useCallback(()=>{a(false),y(false),u(null);},[]);return {submitFeedback:c,isSubmitting:b,isSuccess:m,error:g,reset:n}}function Ve(){let{client:t,botId:e,baseUrl:l,sessionId:p}=O(),[b,a]=useState(false),[m,y]=useState(false),[g,u]=useState(null),c=useCallback(async w=>{a(true),u(null),y(false);try{if(typeof t.captureLead=="function")await t.captureLead({...w,sessionId:p});else {let h=l?l.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${h}/api/v1/public/chat/${e}/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...w,sessionId:p})});}return y(!0),!0}catch(h){let M=h instanceof Error?h:new Error(String(h));return u(M),false}finally{a(false);}},[t,e,l,p]),n=useCallback(()=>{a(false),y(false),u(null);},[]);return {captureLead:c,isSubmitting:b,isSuccess:m,error:g,reset:n}}function Ne(){let{client:t}=O(),[e,l]=useState(false),[p,b]=useState(null),[a,m]=useState(null),y=useCallback(async u=>{l(true),m(null);try{let n=(await t.transcribeAudio(u)).text||"";return b(n),n}catch(c){let n=c instanceof Error?c:new Error(String(c));return m(n),null}finally{l(false);}},[t]),g=useCallback(()=>{l(false),b(null),m(null);},[]);return {transcribe:y,isTranscribing:e,transcript:p,error:a,reset:g}}
3
- export{ue as BotzkiChat,Te as BotzkiProvider,je as BotzkiWidget,de as useBotInfo,O as useBotzki,oe as useChat,_e as useFeedback,Ve as useLeadCapture,te as useOptionalBotzki,Ne as useVoiceTranscription};//# sourceMappingURL=index.mjs.map
1
+ import gn,{createContext,forwardRef,useState,useEffect,useRef,useCallback,useImperativeHandle,useMemo,useContext,useId}from'react';import {Botzki}from'@botzki/js';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {createPortal}from'react-dom';var tn=createContext(null);function en(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"sess_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function zi({botId:t,publishableKey:e,baseUrl:i,apiHost:o,user:a,defaultSessionId:s,client:c,children:g}){let m=o||i||"https://api.botzki.com",[u,S]=useState(()=>{if(s)return s;if(typeof window<"u")try{let y=localStorage.getItem(`botzki_session_${t}`);if(y)return y;let L=en();return localStorage.setItem(`botzki_session_${t}`,L),L}catch{return en()}return s||en()}),f=useMemo(()=>c||new Botzki({botId:t,publishableKey:e,apiHost:m}),[c,t,e,m]);useEffect(()=>{a&&f&&typeof f.setUser=="function"&&f.setUser(a);},[f,a]);let C=useMemo(()=>({client:f,botId:t,publishableKey:e,baseUrl:m,apiHost:m,user:a,sessionId:u,setSessionId:S}),[f,t,e,m,a,u]);return jsx(tn.Provider,{value:C,children:g})}function Mt(){let t=useContext(tn);if(!t)throw new Error("useBotzki must be used within a <BotzkiProvider>. Wrap your application or component with <BotzkiProvider botId='...' publishableKey='...'>.");return t}function Dt(){return useContext(tn)}function on(t={}){let{maskInputs:e=true,maxHtmlBytes:i=1.5*1024*1024}=t;if(typeof window>"u"||typeof document>"u")return {url:"",pathname:"",title:"",viewportWidth:1280,viewportHeight:800,scrollX:0,scrollY:0,htmlSnapshot:"<html><body>Co-browsing not supported in this environment</body></html>",timestamp:Date.now()};let o=document.documentElement.cloneNode(true);o.querySelectorAll("script, noscript, iframe, object, embed, audio, video").forEach(f=>f.remove()),o.querySelectorAll("*").forEach(f=>{let C=Array.from(f.attributes);for(let y of C)y.name.toLowerCase().startsWith("on")&&f.removeAttribute(y.name);}),e&&(o.querySelectorAll("input").forEach(L=>{let N=(L.getAttribute("type")||"text").toLowerCase(),Q=(L.getAttribute("autocomplete")||"").toLowerCase();N==="password"||Q.includes("cc-")||Q.includes("cvv")||L.classList.contains("botzki-mask")||L.hasAttribute("data-private")||N==="password"?L.setAttribute("value","\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022"):L.value&&L.setAttribute("value",L.value);}),o.querySelectorAll("textarea").forEach(L=>{(L.classList.contains("botzki-mask")||L.hasAttribute("data-private"))&&(L.textContent="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022");}),o.querySelectorAll("[data-private], .botzki-mask").forEach(L=>{L.textContent="\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";}));let c=window.location.href;o.querySelectorAll("link[rel='stylesheet'], link[rel='preload']").forEach(f=>{let C=f.getAttribute("href");if(C&&!C.startsWith("http://")&&!C.startsWith("https://")&&!C.startsWith("//")&&!C.startsWith("data:"))try{f.setAttribute("href",new URL(C,c).href);}catch{}}),o.querySelectorAll("img").forEach(f=>{let C=f.getAttribute("src");if(C&&!C.startsWith("http://")&&!C.startsWith("https://")&&!C.startsWith("//")&&!C.startsWith("data:"))try{f.setAttribute("src",new URL(C,c).href);}catch{}});let u=o.querySelector("head");if(u&&!u.querySelector("base")){let f=document.createElement("base");f.setAttribute("href",c),u.insertBefore(f,u.firstChild);}let S=`<!DOCTYPE html>
2
+ `+o.outerHTML;return S.length>i&&(S=S.slice(0,i)),{url:window.location.href,pathname:window.location.pathname+window.location.search,title:document.title||"Visitor Page",viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollX:window.scrollX||window.pageXOffset||0,scrollY:window.scrollY||window.pageYOffset||0,htmlSnapshot:S,timestamp:Date.now()}}function rn({botId:t,baseUrl:e="",sessionId:i,isHumanHandoffActive:o=false}){let[a,s]=useState(true),[c,g]=useState(false),[m,u]=useState(false),[S,f]=useState(null),[C,y]=useState(null),[L,N]=useState(null),Q=useRef(0),U=useRef(false);U.current=m;let X=e.replace(/\/$/,"");useEffect(()=>{if(!t||!i)return;let _=true,q=null,Z=async()=>{try{let oe=await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/status?sessionId=${encodeURIComponent(i)}`);if(!oe.ok)return;let J=await oe.json();if(!_)return;if(s(J.enabled!==!1),J.requested&&!U.current?(g(!0),f(J.operatorName||"Support Specialist")):!J.requested&&!J.active&&(g(!1),U.current&&(u(!1),y(null),N(null))),J.active&&!U.current&&(u(!0),g(!1)),J.active&&J.latestPointer&&(y(J.latestPointer),J.latestPointer.selector&&N(J.latestPointer.selector)),J.active&&J.allowRemoteScroll&&J.latestScroll){let he=J.latestScroll.scrollY;typeof he=="number"&&Math.abs(window.scrollY-he)>20&&window.scrollTo({top:he,behavior:"smooth"});}}catch{}finally{_&&(q=setTimeout(Z,U.current?1e3:2500));}};return Z(),()=>{_=false,q&&clearTimeout(q);}},[t,i,X,o]),useEffect(()=>{if(!m||!t||!i)return;let _=async()=>{let q=Date.now();if(!(q-Q.current<150)){Q.current=q;try{await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/viewport?sessionId=${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:window.location.href,title:document.title||"Visitor Page",viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,scrollX:window.scrollX||window.pageXOffset||0,scrollY:window.scrollY||window.pageYOffset||0,timestamp:q})});}catch{}}};return window.addEventListener("scroll",_,{passive:true}),window.addEventListener("resize",_,{passive:true}),()=>{window.removeEventListener("scroll",_),window.removeEventListener("resize",_);}},[m,t,i,X]);let H=useCallback(async()=>{if(!(!t||!i))try{await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/respond`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:i,accept:!0})}),u(!0),g(!1);let _=on({maskInputs:!0});await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/snapshot?sessionId=${encodeURIComponent(i)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(_)});}catch(_){console.error("Failed to accept co-browsing:",_);}},[t,i,X]),le=useCallback(async _=>{if(!(!t||!i))try{await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/respond`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:i,accept:!1,reason:_||"Visitor declined"})});}catch(q){console.error("Failed to decline co-browsing:",q);}finally{g(false);}},[t,i,X]),Y=useCallback(async _=>{if(!(!t||!i))try{await fetch(`${X}/api/v1/public/chat/${t}/cobrowse/stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:i,reason:_||"Visitor ended session"})});}catch(q){console.error("Failed to stop co-browsing:",q);}finally{u(false),g(false),y(null),N(null);}},[t,i,X]);return {enabled:a,isRequested:c,isActive:m,operatorName:S,pointer:C,highlightedSelector:L,accept:H,decline:le,stop:Y}}var go=null,Eo="";function Ln(){if(!(typeof window>"u"))try{let t=window.AudioContext||window.webkitAudioContext;if(!t)return;let e=new t;e.state==="suspended"&&e.resume().catch(()=>{});let i=e.currentTime,o=e.createGain();o.gain.setValueAtTime(.001,i),o.gain.linearRampToValueAtTime(.12,i+.02),o.gain.exponentialRampToValueAtTime(.001,i+.4),o.connect(e.destination);let a=e.createOscillator();a.type="sine",a.frequency.setValueAtTime(587.33,i),a.connect(o),a.start(i),a.stop(i+.15);let s=e.createOscillator();s.type="sine",s.frequency.setValueAtTime(880,i+.1),s.connect(o),s.start(i+.1),s.stop(i+.4),setTimeout(()=>{e.close().catch(()=>{});},500);}catch{}}function Hn(t="\u{1F514} (1) New message from Support"){if(!(typeof document>"u"||!document.hidden)&&!go){Eo=document.title;let e=true;document.title=t,go=setInterval(()=>{document.title=e?t:Eo,e=!e;},1e3);let i=()=>{go&&(clearInterval(go),go=null,Eo&&(document.title=Eo)),window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i);};window.addEventListener("focus",i),document.addEventListener("visibilitychange",i);}}function Ft(t,e){typeof document<"u"&&document.hidden&&(e?.enableSound!==false&&Ln(),e?.enableTabTitle!==false&&Hn(t));}function ft(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"msg_"+Math.random().toString(36).substring(2,11)+"_"+Date.now()}function mo(t={}){let e=Dt(),i=t.botId||e?.botId,o=t.publishableKey||e?.publishableKey,a=t.baseUrl||e?.baseUrl||"https://api.botzki.com",s=useMemo(()=>e?.client&&(!t.botId||t.botId===e.botId)?e.client:i&&o?new Botzki({botId:i,publishableKey:o,apiHost:a}):null,[e?.client,e?.botId,t.botId,i,o,a]),c=t.storageKey||(i?`botzki_chat_history_${i}`:"botzki_chat_history"),g=t.persistSession??false,[m,u]=useState(()=>t.sessionId?t.sessionId:e?.sessionId?e.sessionId:"sess_"+Math.random().toString(36).substring(2,9)),[S,f]=useState(t.initialMessages||[]),[C,y]=useState(""),[L,N]=useState(false),[Q,U]=useState(false),[X,H]=useState(null),[le,Y]=useState(false),[_,q]=useState(false),[Z,oe]=useState(null),[J,he]=useState(false),[ze,R]=useState(null),T=useRef(new Set),[j,F]=useState(()=>typeof window<"u"?[window.location.pathname+(window.location.search||"")]:[]);useEffect(()=>{if(typeof window>"u")return;let E=window.location.pathname+(window.location.search||"");F(d=>d.length>0&&d[d.length-1]===E?d:[...d.slice(-9),E]);},[]);let G=useRef(le);G.current=le;let ee=useRef(_);ee.current=_;let ce=useRef(null),He=useRef(S);He.current=S,useEffect(()=>{if(!(!g||typeof window>"u"||t.initialMessages?.length))try{let E=localStorage.getItem(c);if(E){let d=JSON.parse(E);Array.isArray(d)&&f(d.map(W=>({...W,createdAt:new Date(W.createdAt)})));}}catch{}},[g,c,t.initialMessages?.length]),useEffect(()=>{if(!(!g||typeof window>"u"))try{S.length>0&&localStorage.setItem(c,JSON.stringify(S));}catch{}},[S,g,c]);let ke=useCallback(()=>{ce.current&&(ce.current.abort(),ce.current=null),N(false),U(false);},[]),pe=useCallback(async(E,d)=>{let W=E.trim();if(!W&&!d?.imageBase64&&!d?.audioUrl)return;if(!i){let A=new Error("botId is required. Provide botId in options or wrap your component tree in <BotzkiProvider botId='...'>");H(A),t.onError?.(A);return}if(H(null),G.current||ee.current){let A={id:ft(),role:"user",content:W,createdAt:new Date,imageBase64:d?.imageBase64,imageUrl:d?.imageUrl,audioUrl:d?.audioUrl,audioDuration:d?.audioDuration,fileUrl:d?.fileUrl,fileName:d?.fileName,fileSize:d?.fileSize};f(l=>[...l,A]),t.onSendMessage?.(A),N(false),U(false);try{let l=a?a.replace(/\/+$/,""):"https://api.botzki.com",v={"Content-Type":"application/json"};o&&(v.Authorization=`Bearer ${o}`),await fetch(`${l}/api/v1/public/chat/${i}/handoff/message`,{method:"POST",headers:v,body:JSON.stringify({sessionId:m,content:W||(d?.audioUrl?"\u{1F3A4} Voice message":d?.imageUrl||d?.imageBase64?"\u{1F4F7} Image attachment":d?.fileName?`\u{1F4CE} File: ${d.fileName}`:""),audioUrl:d?.audioUrl,audioDurationSeconds:d?.audioDuration,imageUrl:d?.imageUrl||d?.imageBase64,fileUrl:d?.fileUrl,fileName:d?.fileName,fileSize:d?.fileSize})});}catch(l){console.warn("Failed to deliver handoff message:",l);}return}N(true),U(t.stream!==false);let ie={id:ft(),role:"user",content:W,createdAt:new Date,imageBase64:d?.imageBase64,audioUrl:d?.audioUrl,audioDuration:d?.audioDuration},O=ft(),de={id:O,role:"assistant",content:"",createdAt:new Date,isStreaming:t.stream!==false};f(A=>[...A,ie,de]),t.onSendMessage?.(ie);let P=new AbortController;ce.current=P;try{if(t.stream!==!1){let A="";if(s&&typeof s.chatStream=="function")await s.chatStream({message:W,sessionId:m,language:t.language,imageBase64:d?.imageBase64,imageMimeType:d?.imageMimeType,onDelta:l=>{P.signal.aborted||(A+=l,f(v=>v.map(h=>h.id===O?{...h,content:A}:h)));},onDone:l=>{if(P.signal.aborted)return;let v={id:O,role:"assistant",content:l.reply||A,createdAt:new Date,citations:l.citations,isStreaming:!1};f(h=>h.map(x=>x.id===O?v:x)),N(!1),U(!1),t.onResponse?.(l),t.onFinish?.(v);},onError:l=>{P.signal.aborted||(H(l),N(!1),U(!1),f(v=>v.map(h=>h.id===O?{...h,isStreaming:!1,error:l.message}:h)),t.onError?.(l));}});else {let l=a?a.replace(/\/+$/,""):"https://api.botzki.com",v={"Content-Type":"application/json"};o&&(v.Authorization=`Bearer ${o}`);let h=await fetch(`${l}/api/v1/public/chat/${i}/stream`,{method:"POST",headers:v,body:JSON.stringify({query:W,message:W,sessionId:m,language:t.language,imageBase64:d?.imageBase64,imageMimeType:d?.imageMimeType}),signal:P.signal});if(!h.ok){let fe=`Chat request failed with status ${h.status}`;try{let xe=await h.json();xe?.message&&(fe=xe.message);}catch{}throw new Error(fe)}let x=h.body?.getReader();if(!x)throw new Error("Response body is not readable.");let M=new TextDecoder("utf-8"),B="",z=[],ue,re,w=null;for(;;){let{done:fe,value:xe}=await x.read();if(fe||P.signal.aborted)break;B+=M.decode(xe,{stream:!0});let Ne=B.split(`
3
+ `);B=Ne.pop()||"";for(let Pe of Ne)if(Pe=Pe.trim(),Pe.startsWith("data: ")){let qe=Pe.slice(6).trim();if(qe==="[DONE]")continue;try{let ae=JSON.parse(qe),Ye=ae.delta??ae.token??ae.text??ae.content??"";Ye&&(A+=Ye,f(Oe=>Oe.map(Ie=>Ie.id===O?{...Ie,content:A}:Ie))),ae.answer&&(A=ae.answer,f(Oe=>Oe.map(Ie=>Ie.id===O?{...Ie,content:A}:Ie))),ae.citations&&(z=ae.citations),ae.escalation&&(ue=ae.escalation),(ae.modelUsed||ae.model_used||ae.piiRedacted||ae.pii_redacted)&&(w=ae);let te=ae.proposedAction??ae.proposed_action??ae.action;te&&(te.actionId||te.action_id||te.actionName||te.action_name)&&(re={actionId:te.actionId??te.action_id??"",actionName:te.actionName??te.action_name??"",displayName:te.displayName??te.display_name??te.actionName??te.action_name??"",description:te.description,executionType:te.executionType??te.execution_type??"ServerWebhook",parameters:te.parameters,requiresConfirmation:te.requiresConfirmation??te.requires_confirmation??!0,confirmationPrompt:te.confirmationPrompt??te.confirmation_prompt,successMessage:te.successMessage??te.success_message,token:te.token??te.actionToken??"",status:"pending"});}catch{qe&&(A+=qe,f(ae=>ae.map(Ye=>Ye.id===O?{...Ye,content:A}:Ye)));}}}let me={id:O,role:"assistant",content:A,createdAt:new Date,citations:z.length>0?z:void 0,isStreaming:!1,escalation:ue,proposedAction:re,modelUsed:w?.modelUsed??w?.model_used,fallbackTriggered:w?.fallbackTriggered??w?.fallback_triggered,piiRedacted:w?.piiRedacted??w?.pii_redacted,redactionsCount:w?.redactionsCount??w?.redactions_count,localPrivacyMode:w?.localPrivacyMode??w?.local_privacy_mode};f(fe=>fe.map(xe=>xe.id===O?me:xe)),N(!1),U(!1),Ft("\u{1F514} (1) New message from Support",{enableSound:t.enableSoundAlert,enableTabTitle:t.enableTabTitleNotification}),re&&t.onActionProposed?.(re),t.onResponse?.({reply:A,answer:A,citations:z,insufficientEvidence:!1,sessionId:m}),t.onFinish?.(me);}}else {let A="",l=[],v,h,x=null;if(s&&typeof s.chat=="function"){let B=await s.chat({message:W,sessionId:m,language:t.language,imageBase64:d?.imageBase64,imageMimeType:d?.imageMimeType});x=B,A=B.reply||B.answer,l=B.citations||[],B.escalation&&(v=B.escalation);let z=B.proposedAction??B.proposed_action??B.action;z&&(z.actionId||z.action_id||z.actionName||z.action_name)&&(h={actionId:z.actionId??z.action_id??"",actionName:z.actionName??z.action_name??"",displayName:z.displayName??z.display_name??z.actionName??z.action_name??"",description:z.description,executionType:z.executionType??z.execution_type??"ServerWebhook",parameters:z.parameters,requiresConfirmation:z.requiresConfirmation??z.requires_confirmation??!0,confirmationPrompt:z.confirmationPrompt??z.confirmation_prompt,successMessage:z.successMessage??z.success_message,token:z.token??z.actionToken??"",status:"pending"});}else {let B=a?a.replace(/\/+$/,""):"https://api.botzki.com",z={"Content-Type":"application/json"};o&&(z.Authorization=`Bearer ${o}`);let ue=await fetch(`${B}/api/v1/public/chat/${i}`,{method:"POST",headers:z,body:JSON.stringify({query:W,message:W,sessionId:m,language:t.language,imageBase64:d?.imageBase64,imageMimeType:d?.imageMimeType}),signal:P.signal});if(!ue.ok){let me=`Chat request failed with status ${ue.status}`;try{let fe=await ue.json();fe?.message&&(me=fe.message);}catch{}throw new Error(me)}let re=await ue.json();x=re,A=re.reply||re.answer||"",l=re.citations||[],re.escalation&&(v=re.escalation);let w=re.proposedAction??re.proposed_action??re.action;w&&(w.actionId||w.action_id||w.actionName||w.action_name)&&(h={actionId:w.actionId??w.action_id??"",actionName:w.actionName??w.action_name??"",displayName:w.displayName??w.display_name??w.actionName??w.action_name??"",description:w.description,executionType:w.executionType??w.execution_type??"ServerWebhook",parameters:w.parameters,requiresConfirmation:w.requiresConfirmation??w.requires_confirmation??!0,confirmationPrompt:w.confirmationPrompt??w.confirmation_prompt,successMessage:w.successMessage??w.success_message,token:w.token??w.actionToken??"",status:"pending"});}let M={id:O,role:"assistant",content:A,createdAt:new Date,citations:l.length>0?l:void 0,isStreaming:!1,escalation:v,proposedAction:h,modelUsed:x?.modelUsed??x?.model_used,fallbackTriggered:x?.fallbackTriggered??x?.fallback_triggered,piiRedacted:x?.piiRedacted??x?.pii_redacted,redactionsCount:x?.redactionsCount??x?.redactions_count,localPrivacyMode:x?.localPrivacyMode??x?.local_privacy_mode};f(B=>B.map(z=>z.id===O?M:z)),N(!1),U(!1),Ft("\u{1F514} (1) New message from Support",{enableSound:t.enableSoundAlert,enableTabTitle:t.enableTabTitleNotification}),h&&t.onActionProposed?.(h),t.onResponse?.({reply:A,answer:A,citations:l,insufficientEvidence:!1,sessionId:m}),t.onFinish?.(M);}}catch(A){if(!P.signal.aborted){let l=A instanceof Error?A:new Error(String(A));H(l),N(false),U(false),f(v=>v.map(h=>h.id===O?{...h,isStreaming:false,error:l.message}:h)),t.onError?.(l);}}finally{ce.current===P&&(ce.current=null);}},[s,t,m]),ye=useCallback(E=>{y(E.target.value);},[]),Ee=useCallback(async(E,d)=>{E&&typeof E.preventDefault=="function"&&E.preventDefault();let W=C;y(""),await pe(W,d);},[C,pe]),We=useCallback(E=>{let d={id:E.id||ft(),role:E.role||"user",content:E.content,createdAt:E.createdAt||new Date,citations:E.citations,isStreaming:E.isStreaming,error:E.error};f(W=>[...W,d]);},[]),Ue=useCallback(async()=>{let E=He.current;if(E.length===0)return;let d=E.map(ie=>ie.role).lastIndexOf("user");if(d===-1)return;let W=E[d];f(E.slice(0,d)),await pe(W.content);},[pe]),wt=useCallback(async(E,d)=>{if(!i){let h=new Error("botId is required. Provide botId in options or wrap your component tree in <BotzkiProvider botId='...'>");H(h),t.onError?.(h);return}let W=d?.audioUrl||URL.createObjectURL(E),ie=ft();H(null),N(true);let O={id:ie,role:"user",content:"",audioUrl:W,audioDuration:d?.audioDuration,isTranscribing:true,createdAt:new Date};f(h=>[...h,O]);let de="";try{if(s&&typeof s.transcribeAudio=="function")de=(await s.transcribeAudio(E))?.text||"";else {let h=a?a.replace(/\/+$/,""):"https://api.botzki.com",x=new FormData;x.append("file",E,"voice_recording.webm");let M={};o&&(M.Authorization=`Bearer ${o}`);let B=await fetch(`${h}/api/v1/public/chat/${i}/transcribe`,{method:"POST",headers:M,body:x});B.ok&&(de=(await B.json()).text||"");}}catch(h){console.warn("Audio transcription error:",h);}f(h=>h.map(x=>x.id===ie?{...x,content:de||"(Voice message)",isTranscribing:false}:x));let P=de||"Voice message recorded",A=ft(),l=new AbortController;ce.current=l,U(t.stream!==false);let v={id:A,role:"assistant",content:"",createdAt:new Date,isStreaming:t.stream!==false};f(h=>[...h,v]);try{if(t.stream!==!1){let h="";if(s&&typeof s.chatStream=="function")await s.chatStream({message:P,sessionId:m,language:t.language,onDelta:x=>{l.signal.aborted||(h+=x,f(M=>M.map(B=>B.id===A?{...B,content:h}:B)));},onDone:x=>{if(l.signal.aborted)return;let M={id:A,role:"assistant",content:x.reply||h,createdAt:new Date,citations:x.citations,isStreaming:!1};f(B=>B.map(z=>z.id===A?M:z)),N(!1),U(!1),t.onResponse?.(x),t.onFinish?.(M);},onError:x=>{l.signal.aborted||(H(x),N(!1),U(!1),t.onError?.(x));}});else {let x=a?a.replace(/\/+$/,""):"https://api.botzki.com",M={"Content-Type":"application/json"};o&&(M.Authorization=`Bearer ${o}`);let B=await fetch(`${x}/api/v1/public/chat/${i}/stream`,{method:"POST",headers:M,body:JSON.stringify({query:P,message:P,sessionId:m,language:t.language}),signal:l.signal});if(!B.ok)throw new Error(`Chat stream failed with status ${B.status}`);if(B.body){let ue=B.body.getReader(),re=new TextDecoder,w="";for(;;){let{done:me,value:fe}=await ue.read();if(me)break;w+=re.decode(fe,{stream:!0});let xe=w.split(`
4
+ `);w=xe.pop()||"";for(let Ne of xe){let Pe=Ne.trim();if(Pe.startsWith("data:")){let qe=Pe.slice(5).trim();if(!qe||qe==="[DONE]")continue;try{let ae=JSON.parse(qe);ae.delta&&(h+=ae.delta,f(Ye=>Ye.map(te=>te.id===A?{...te,content:h}:te)));}catch{}}}}}let z={id:A,role:"assistant",content:h,createdAt:new Date,isStreaming:!1};f(ue=>ue.map(re=>re.id===A?z:re)),N(!1),U(!1),Ft("\u{1F514} (1) New message from Support"),t.onFinish?.(z);}}else {let h="",x=null;if(s&&typeof s.chat=="function"){let B=await s.chat({message:P,sessionId:m,language:t.language});x=B,h=B.reply||B.answer;}else {let B=a?a.replace(/\/+$/,""):"https://api.botzki.com",z={"Content-Type":"application/json"};o&&(z.Authorization=`Bearer ${o}`);let re=await(await fetch(`${B}/api/v1/public/chat/${i}`,{method:"POST",headers:z,body:JSON.stringify({query:P,message:P,sessionId:m,language:t.language}),signal:l.signal})).json();x=re,h=re.reply||re.answer||"";}let M={id:A,role:"assistant",content:h,createdAt:new Date,isStreaming:!1,modelUsed:x?.modelUsed??x?.model_used,fallbackTriggered:x?.fallbackTriggered??x?.fallback_triggered,piiRedacted:x?.piiRedacted??x?.pii_redacted,redactionsCount:x?.redactionsCount??x?.redactions_count,localPrivacyMode:x?.localPrivacyMode??x?.local_privacy_mode};f(B=>B.map(z=>z.id===A?M:z)),N(!1),U(!1),t.onFinish?.(M);}}catch(h){if(h?.name==="AbortError")return;H(h),N(false),U(false),t.onError?.(h);}},[i,a,o,s,m,t]);useEffect(()=>{if(!_&&!le||!i)return;let E=true,d=a.replace(/\/+$/,""),W=async()=>{try{let O={};o&&(O.Authorization=`Bearer ${o}`);let de=await fetch(`${d}/api/v1/public/chat/${i}/handoff/status?sessionId=${m}`,{headers:O});if(!de.ok||!E)return;let P=await de.json();if(!E)return;P.status==="OperatorActive"?(Y(!0),q(!1),P.assignedOperator&&oe(A=>{if(!A||A.name!==P.assignedOperator.name){let l=P.assignedOperator.name||"Support Specialist";t.onOperatorJoined?.(P.assignedOperator),f(v=>v.some(x=>x.content&&x.content.includes(`${l} from Customer Support has joined`))?v:[...v,{id:ft(),role:"system",content:`${l} from Customer Support has joined the conversation.`,createdAt:new Date}]);}return P.assignedOperator})):P.status==="WaitingHuman"?(q(!0),Y(!1)):(P.status==="BotHandling"||P.status==="Closed"||P.status==="Resolved")&&(q(!1),Y(!1),oe(null),he(!1),P.status==="Resolved"&&P.ticketId&&!T.current.has(P.ticketId)&&R(A=>(A!==P.ticketId&&t.onTicketResolved?.(P.ticketId),P.ticketId))),Array.isArray(P.messages)&&f(A=>{let l=new Set(A.map(M=>M.id)),v=new Set(A.map(M=>M.content)),h=[...A],x=!1;for(let M of P.messages)if(M.senderType==="System"){if(M.content&&M.content.startsWith("Visitor requested"))continue;if(!l.has(M.id)&&!v.has(M.content)){let B=String(M.createdAtUtc||""),z=B?new Date(B.endsWith("Z")?B:B+"Z"):new Date;h.push({id:M.id,role:"system",content:M.content,createdAt:z}),l.add(M.id),v.add(M.content),x=!0,Ft("\u{1F514} (1) New message from Support Specialist",{enableSound:t.enableSoundAlert,enableTabTitle:t.enableTabTitleNotification});}}else if(M.senderType==="Operator"){if(l.has(M.id))continue;let B=h.findIndex(z=>z.senderType==="operator"&&z.content===M.content&&z.id.startsWith("msg_"));if(B!==-1){h[B]={...h[B],id:M.id},l.add(M.id),x=!0;continue}if(!v.has(M.content)){let z=String(M.createdAtUtc||""),ue=z?new Date(z.endsWith("Z")?z:z+"Z"):new Date;h.push({id:M.id,role:"assistant",senderType:"operator",senderName:M.senderName||"Support Specialist",content:M.content,audioUrl:M.audioUrl,audioDuration:M.audioDurationSeconds,imageUrl:M.imageUrl,fileUrl:M.fileUrl,fileName:M.fileName,fileSize:M.fileSize,deliveryStatus:M.deliveryStatus,deliveryChannel:M.deliveryChannel,createdAt:ue}),l.add(M.id),v.add(M.content),x=!0,Ft("\u{1F514} (1) New message from Support Specialist",{enableSound:t.enableSoundAlert,enableTabTitle:t.enableTabTitleNotification});}}return x?h:A});}catch{}};W();let ie=setInterval(W,3e3);return ()=>{E=false,clearInterval(ie);}},[_,le,i,a,o,m]);let At=useCallback(async(E,d,W,ie)=>{let O=a.replace(/\/+$/,"");try{let de={"Content-Type":"application/json"};o&&(de.Authorization=`Bearer ${o}`);let P=typeof Intl<"u"?Intl.DateTimeFormat().resolvedOptions().timeZone:void 0,A={...t.visitorData||{},...ie?.customData||{}},l=Array.from(new Set([...t.tags||[],...ie?.tags||[]])),v=ie?.lastBrowsedPages||j,h=S.filter(B=>(B.role==="user"||B.role==="assistant")&&B.content&&B.content.trim().length>0).map(B=>({role:B.role,content:B.content.trim(),createdAt:B.createdAt instanceof Date?B.createdAt.toISOString():B.createdAt?new Date(B.createdAt).toISOString():new Date().toISOString()})),x=await fetch(`${O}/api/v1/public/chat/${i}/handoff/request`,{method:"POST",headers:de,body:JSON.stringify({sessionId:m,reason:E,visitorName:d,visitorEmail:W,timezone:P,lastBrowsedPages:v.length>0?v:void 0,customData:Object.keys(A).length>0?A:void 0,tags:l.length>0?l:void 0,transcript:h.length>0?h:void 0})}),M=await x.json().catch(()=>({}));if(!x.ok){if(M?.code==="EMAIL_REQUIRED"){let B=new Error(M.message||"Email is required before handoff.");throw B.code="EMAIL_REQUIRED",B}throw new Error(M?.message||`Handoff request failed with status ${x.status}`)}if(M.isOnline===!1){f(B=>[...B,{id:ft(),role:"system",content:M.offlineMessage||"Our support team is currently offline. We will reply as soon as possible!",createdAt:new Date}]),M.behavior==="aiOnly"?q(!1):q(!0);return}q(!0),t.onEscalationRequest?.({reason:E,visitorName:d,visitorEmail:W}),f(B=>{let z=[...B];return z.some(re=>re.role==="system"&&re.content.includes("Connecting you with our support team"))||z.push({id:ft(),role:"system",content:"Connecting you with our support team... You are in queue for a live specialist.",createdAt:new Date}),M.welcomeMessage&&(z.some(w=>w.senderType==="operator"&&w.content===M.welcomeMessage)||z.push({id:ft(),role:"assistant",senderType:"operator",senderName:"Support Specialist",content:M.welcomeMessage,createdAt:new Date})),z});}catch(de){if(de?.code==="EMAIL_REQUIRED")throw de;console.warn("Human handoff request failed:",de);}},[a,i,o,m,j,t.visitorData,t.tags]),Je=useCallback(async()=>{q(false),Y(false),oe(null),he(false);let E=a.replace(/\/+$/,"");try{let d={"Content-Type":"application/json"};o&&(d.Authorization=`Bearer ${o}`),await fetch(`${E}/api/v1/public/chat/${i}/handoff/cancel`,{method:"POST",headers:d,body:JSON.stringify({sessionId:m})});}catch{}f(d=>[...d,{id:ft(),role:"system",content:"Returned to autonomous AI assistant mode.",createdAt:new Date}]);},[a,i,o,m]),Ae=useCallback(()=>{ke(),f([]),R(null),q(false),Y(false),oe(null);let E="sess_"+Math.random().toString(36).substring(2,9);if(u(E),g&&typeof window<"u")try{localStorage.removeItem(c),localStorage.setItem(`${c}_session_id`,E);}catch{}},[ke,g,c]),be=useCallback(async(E,d)=>{if(!(!ze||!i))try{let W=a?a.replace(/\/+$/,""):"https://api.botzki.com",ie={"Content-Type":"application/json"};o&&(ie.Authorization=`Bearer ${o}`),await fetch(`${W}/api/v1/public/chat/${i}/handoff/feedback`,{method:"POST",headers:ie,body:JSON.stringify({ticketId:ze,rating:E,feedback:d||null})}),T.current.add(ze),R(null),t.onCsatSubmit?.(E,d);}catch(W){console.warn("Failed to submit handoff feedback:",W);}},[ze,i,a,o]),Qe=useCallback(async(E,d,W)=>{let ie=a.replace(/\/+$/,""),O={"Content-Type":"application/json"};o&&(O.Authorization=`Bearer ${o}`);let P=He.current.find(A=>A.id===E)?.proposedAction;f(A=>A.map(l=>l.id===E&&l.proposedAction?{...l,proposedAction:{...l.proposedAction,status:"executing"}}:l));try{let A=await fetch(`${ie}/api/v1/public/chat/${i}/actions/execute`,{method:"POST",headers:O,body:JSON.stringify({actionToken:d,confirmedParameters:W,visitorSessionId:m})});if(!A.ok){let v=`Execution failed with status ${A.status}`;try{let h=await A.json();h?.message&&(v=h.message);}catch{}throw new Error(v)}let l=await A.json();return f(v=>v.map(h=>h.id===E&&h.proposedAction?{...h,proposedAction:{...h.proposedAction,status:"completed",result:l}}:h)),P&&t.onActionExecuted?.({...P,status:"completed",result:l},l),{success:!0,result:l}}catch(A){return f(l=>l.map(v=>v.id===E&&v.proposedAction?{...v,proposedAction:{...v.proposedAction,status:"failed",error:A.message}}:v)),{success:false,error:A.message}}},[i,a,o,m]),Ke=useCallback(async(E,d)=>{let ie=He.current.find(de=>de.id===E)?.proposedAction,O=ie?.token;if(f(de=>de.map(P=>P.id===E&&P.proposedAction?{...P,proposedAction:{...P.proposedAction,status:"cancelled"}}:P)),ie&&t.onActionCancelled?.({...ie,status:"cancelled"},d),O&&i)try{let de=a?a.replace(/\/+$/,""):"https://api.botzki.com",P={"Content-Type":"application/json"};o&&(P.Authorization=`Bearer ${o}`),await fetch(`${de}/api/v1/public/chat/${i}/actions/cancel`,{method:"POST",headers:P,body:JSON.stringify({actionToken:O,reason:d||"Cancelled by visitor"})});}catch{}},[i,a,o]),Be=rn({botId:i||"",baseUrl:a,sessionId:m,isHumanHandoffActive:le&&t.enableCoBrowse!==false}),Ve=useRef(false);return useEffect(()=>{Be.isActive&&!Ve.current?t.onCoBrowseStart?.(Be.operatorName):!Be.isActive&&Ve.current&&t.onCoBrowseEnd?.(),Ve.current=Be.isActive;},[Be.isActive,Be.operatorName]),{messages:S,input:C,setInput:y,handleInputChange:ye,handleSubmit:Ee,sendMessage:pe,sendVoiceMessage:wt,append:We,reload:Ue,stop:ke,clearMessages:Ae,setMessages:f,isLoading:L,isStreaming:Q,error:X,sessionId:m,setSessionId:u,isHumanHandoffActive:le,isWaitingForHuman:_,assignedOperator:Z,isOperatorTyping:J,requestHumanHandoff:At,cancelHumanHandoff:Je,pendingCsatTicketId:ze,submitHandoffFeedback:be,executeProposedAction:Qe,cancelProposedAction:Ke,coBrowse:Be}}function bo(){let{client:t,botId:e,baseUrl:i}=Mt(),[o,a]=useState(null),[s,c]=useState(true),[g,m]=useState(null),u=useCallback(async()=>{c(true),m(null);try{let S;if(typeof t.getBotInfo=="function")S=await t.getBotInfo();else {let f=i?i.replace(/\/+$/,""):"https://api.botzki.com";S=await(await fetch(`${f}/api/v1/public/chat/${e}`)).json();}a(S);}catch(S){m(S instanceof Error?S:new Error(String(S)));}finally{c(false);}},[t,e,i]);return useEffect(()=>{u();},[u,e]),{data:o,isLoading:s,error:g,refetch:u}}var Ei=["broken","terrible","worst","hate","refund","stuck","bug","crash","error","horrible","awful","scam","useless","ridiculous","frustrated","fail","failed","failing","not working","doesn't work","does not work","charge","charged","cancel","disaster","slow","unacceptable","angry","mad","waste","trash","annoying","cheat","sucks","disappointed","garbage","bad service","poor","rip off","ripoff","never works"],Pi=["wow","amazing","unbelievable","omg","best bot","love you","solved","fixed","works now","working now","you saved","fantastic","brilliant","yay","hooray","bingo","perfect","genius","incredible","love it","awesome bot","superb","outstanding"],$i=["thanks","thank you","thx","appreciate","helpful","good","great","nice","awesome","sweet","cool","super","glad","kind of you","very clear","got it","clear now","understood"],Li=["how","what","why","where","when","can you","could you","tell me","is there","wondering","curious","possible to","explain"];function Un(t){if(!t||typeof t!="string")return {sentiment:"neutral",score:0};let e=t.toLowerCase();for(let i of Pi)if(e.includes(i))return {sentiment:"delighted",score:.95,triggerWord:i};for(let i of Ei)if(e.includes(i))return {sentiment:"frustrated",score:-0.9,triggerWord:i};for(let i of $i)if(e.includes(i))return {sentiment:"happy",score:.65,triggerWord:i};return e.includes("?")||Li.some(i=>e.includes(i))?{sentiment:"curious",score:.2}:{sentiment:"neutral",score:0}}function yo({messages:t=[],isLoading:e=false,isStreaming:i=false,isWaitingForHuman:o=false,isHumanHandoffActive:a=false,feedbackRating:s=null,manualEmotion:c,manualMotion:g,enabled:m=true,reactionCooldownMs:u=5500}={}){let[S,f]=useState("neutral"),[C,y]=useState(void 0),[L,N]=useState(0),[Q,U]=useState("neutral"),[X,H]=useState(0),[le,Y]=useState("Calm attentive baseline"),_=useRef(null),q=useRef(null),Z=()=>{_.current&&(clearTimeout(_.current),_.current=null);},oe=(R=u)=>{Z(),_.current=setTimeout(()=>{f("neutral"),y(void 0),U("neutral"),H(0),Y("Returned to calm baseline");},R);},J=()=>{Z(),f("love"),y("jump"),N(R=>R+1),U("delighted"),H(1),Y("Celebration triggered: Issue resolved!"),oe(6e3);},he=()=>{Z(),f("sad"),y("float"),N(R=>R+1),U("frustrated"),H(-0.85),Y("Attentive & sympathetic listening active"),oe(7e3);},ze=()=>{Z(),f("neutral"),y(void 0),U("neutral"),H(0),Y("Reset to neutral");};return useEffect(()=>{c&&(f(c),Y(`Manual emotion override: ${c}`)),g&&(y(g),N(R=>R+1));},[c,g]),useEffect(()=>{m&&(s==="up"?J():s==="down"&&he());},[s,m]),useEffect(()=>{m&&(o?(Z(),f("sad"),y("float"),N(R=>R+1),U("frustrated"),H(-0.7),Y("Visitor requested human agent: Sympathetic attentive stance")):a&&(Z(),f("happy"),y("bounce"),N(R=>R+1),U("happy"),H(.8),Y("Live human operator connected: Reassuring welcome"),oe(6e3)));},[o,a,m]),useEffect(()=>{m&&(o||(e||i?(Z(),f("thinking"),y(void 0),U("thinking"),H(.1),Y("Synthesizing answer & reasoning...")):Q==="thinking"&&(f("happy"),y(void 0),U("happy"),H(.5),Y("Answer delivered with friendly attentive smile"),oe(4e3))));},[e,i,o,m]),useEffect(()=>{if(!m||t.length===0)return;let R=[...t].reverse().find(j=>j.role==="user");if(!R||R.id===q.current)return;q.current=R.id;let T=Un(R.content);T.sentiment==="frustrated"?(Z(),f("sad"),y("float"),N(j=>j+1),U("frustrated"),H(T.score),Y(`Detected distress trigger '${T.triggerWord}': Avatar shifts to apologetic listening posture`),oe(8e3)):T.sentiment==="delighted"?(Z(),f("love"),y("jump"),N(j=>j+1),U("delighted"),H(T.score),Y(`Detected delight trigger '${T.triggerWord}': Avatar celebrates`),oe(7e3)):T.sentiment==="happy"?(Z(),f("happy"),y("bounce"),N(j=>j+1),U("happy"),H(T.score),Y(`Detected gratitude trigger '${T.triggerWord}': Avatar perks up happily`),oe(6e3)):T.sentiment==="curious"&&(Z(),f("surprised"),y(void 0),U("curious"),H(T.score),Y("Inquisitive customer question: Attentive focus"),oe(5e3));},[t,m]),useEffect(()=>()=>Z(),[]),{emotion:c??S,motion:g??C,motionKey:L,sentiment:Q,sentimentScore:X,empathyReason:le,triggerCelebration:J,triggerSympathy:he,resetToNeutral:ze}}var $o=[-3.2,3.2],Lo=-2.6,Hi=2.4,Wi=5.4,Dn=4.4,Ui=380,Ni=13.4+.5,Po=4,xo=2800,Oi=2200,Di="M0 1C-0.6 0.55-1.3 0.1-1.3-0.45C-1.3-0.95-0.9-1.2-0.55-1.2C-0.25-1.2-0.05-1 0-0.8C0.05-1 0.25-1.2 0.55-1.2C0.9-1.2 1.3-0.95 1.3-0.45C1.3 0.1 0.6 0.55 0 1Z",Me=t=>t*t*(3-2*t),at=t=>Math.min(1,Math.max(0,t)),Fi=t=>t<.5?4*t*t*t:1-(-2*t+2)**3/2,Fn=t=>1-(1-t)**3,Fe=(t,e,i)=>t<=e||t>=i?0:Math.sin(Math.PI*(t-e)/(i-e)),je=(t,e,i,o,a)=>t<=e||t>=a?0:t<i?Me((t-e)/(i-e)):t<=o?1:1-Me((t-o)/(a-o)),cn=t=>{let e=Math.sin(t*127.1+311.7)*43758.5453;return e-Math.floor(e)};function ji(t,e,i,o){let a=Math.cos;switch(t){case "circle":return .97+(.012+o*.03)*a(3*e+i*.5)+.008*a(5*e-i*.6);case "squircle":{let s=Math.abs(a(e)),c=Math.abs(Math.sin(e));return .9/(s**4+c**4)**.25+(.008+o*.02)*a(4*e+i*.6)}case "flower":return .95+(.075+o*.03)*a(8*e)+.012*a(3*e+i*.6);case "blob":return .97+(.05+o*.025)*a(3*e+1.5*Math.PI+.75*Math.sin(i*.3)+.25*Math.sin(i*.71))+(.022+o*.012)*a(2*e-i*.36)+.01*a(5*e+i*.5);default:return 1+(.038+o*.03)*a(5*e+.5*Math.PI+.75*Math.sin(i*.27)+.25*Math.sin(i*.63))+(.02+o*.02)*a(3*e+i*.45)+.01*a(7*e-i*.6)}}function jn(t){let e="";for(let i=0;i<96;i++){let o=i/96*Math.PI*2,a=t[i]*13.4;e+=`${i?"L":"M"}${(a*Math.cos(o)).toFixed(2)} ${(a*Math.sin(o)).toFixed(2)}`;}return `${e}Z`}var _i=jn(new Float32Array(96).fill(1));function _n(t,e,i,o,a,s,c){let g=Hi/2*a,m=Math.max(.35,Wi/2*i*a)*(4/3),u=[t-g,e,t-g,e-m*(1-s),t+g,e-m*(1-c),t+g,e,t+g,e+m,t-g,e+m],S=e+.4,f=[t-1.7,S+1,t-1.5,S-1.6,t+1.5,S-1.6,t+1.7,S+1,t+1.1,S-.3,t-1.1,S-.3],C=u.map((y,L)=>(y+(f[L]-y)*o).toFixed(2));return `M${C[0]} ${C[1]}C${C[2]} ${C[3]} ${C[4]} ${C[5]} ${C[6]} ${C[7]}C${C[8]} ${C[9]} ${C[10]} ${C[11]} ${C[0]} ${C[1]}Z`}function Vn(t,e,i,o,a,s,c=0){let g=(2+o*.8-i*.3)*a,m=e-o*.4,u=e+.4+o*(o<0?2.4:1.6),S=u+i*1.8+c,f=u-i*2.4-c,C=N=>N.toFixed(2),y=m+s,L=m-s;return `M${C(t-g)} ${C(y)}Q${C(t)} ${C(S)} ${C(t+g)} ${C(L)}Q${C(t)} ${C(f)} ${C(t-g)} ${C(y)}Z`}var gt={openL:1,openR:1,laughL:0,laughR:0,eyeScale:1,eyeY:0,heavy:0,droop:0,smile:.4,mouth:0,mouthW:1,mouthX:0,skew:0,taper:0,blush:0,gazeX:Number.NaN,gazeY:Number.NaN,wobble:0,bob:0,tilt:0,spin:1},Nn={neutral:gt,happy:{...gt,openL:.9,openR:.9,laughL:.45,laughR:.45,smile:1,wobble:.15,bob:-0.3},love:{...gt,openL:.88,openR:.88,laughL:.55,laughR:.55,eyeScale:1.03,smile:1,mouthW:.9,blush:1,gazeX:-0.6,gazeY:-0.7,wobble:.12,bob:-0.2,tilt:-3,spin:.7},laugh:{...gt,openL:.9,openR:.9,laughL:.5,laughR:.5,smile:1,mouth:.1,wobble:.3,spin:1.4},surprised:{...gt,openL:1.03,openR:1.03,eyeScale:1.07,eyeY:-0.5,smile:0,mouth:1,mouthW:.95,wobble:.12,bob:-0.6},wow:{...gt,openL:.98,openR:.98,eyeScale:1.15,eyeY:-0.5,smile:.15,mouth:.75,mouthW:1.35,wobble:.15,bob:-0.5},sad:{...gt,openL:.75,openR:.75,eyeScale:.92,droop:.85,eyeY:.5,smile:-1,mouthW:1.75,gazeX:0,gazeY:.75,bob:.8,tilt:-4,spin:.35},thinking:{...gt,openL:.95,openR:.8,heavy:.2,smile:.1,mouthW:.6,mouthX:.9,skew:.5,tilt:5,spin:.6},sleepy:{...gt,openL:.6,openR:.6,heavy:.65,eyeY:.5,smile:-0.04,mouthW:.8,taper:.3,gazeX:0,gazeY:.6,bob:.5,spin:.3},wink:{...gt,smile:.9,skew:.1,tilt:2,wobble:.1}},Vi={surprised:16,wow:18,sad:3.5,sleepy:2.5},qi=Object.keys(gt),qn=()=>({dy:0,sy:0,tilt:0,faceY:0,scale:0,openL:1,openR:1,laughL:0,laughR:0,mouth:0,smile:0,width:1,skew:0,mouthX:0,yawn:0,blink:0,steady:false,gaze:null}),sn=[[.75,-0.85],[.4,-1],[-0.35,-0.85]];function Yi(t,e,i){let o=qn();switch(t){case "happy":{e<520&&(o.dy=-1.6*Math.abs(Math.sin(Math.PI*2*e/520))),o.tilt=3*Math.sin(Math.PI*2*e/3600);let a=je(e%3600,1600,1900,2500,2900);o.laughL=o.laughR=.3*a,o.mouth=.22*a,o.dy-=.6*a;break}case "love":{e<600&&(o.dy=-1.4*Fe(e,0,600)),o.tilt=5*Math.sin(Math.PI*2*e/4e3);let a=je(e%4e3,1400,1900,2500,3200);o.laughL=o.laughR=.3*a,o.scale+=.05*a,o.sy+=.03*a,o.dy-=.8*a,o.mouth+=.1*a;break}case "laugh":{let s=Math.floor(e/5600),c=e%5600,g=cn(s)<.5?-1:1,m=Fe(c,0,340);o.dy-=1.2*m,o.sy+=.04*m,o.scale+=.1*m,o.laughL=o.laughR=-0.5*m,o.mouth+=.25*m;let u=je(c,220,380,3e3,3700);if(o.laughL+=.5*u,o.laughR+=.5*u,o.mouth+=.25*je(c,220,400,3400,4400),c>260&&c<2900){let S=(c-260)/2640,f=15*S-3*S*S,C=Math.abs(Math.sin(Math.PI*f))**.8,y=(1-.7*S)*(.6+.4*cn(s*17+Math.floor(f)))*Me(Math.min(1,(c-260)/120));o.mouth+=.6*C*y,o.dy-=1.4*C*y,o.sy-=.035*C*y,o.scale-=.1*C*y,o.tilt+=2.5*C*y*g;}else if(c>=2900&&c<4300){let S=(c-2900)/1400,f=Math.abs(Math.sin(Math.PI*S*4.2)),C=.4*(1-S);o.mouth+=.4*f*C,o.dy-=.8*f*C;}o.tilt-=7*g*je(c,260,600,1800,2900),o.sy-=.02*Fe(c,4300,5300),c>4300&&(o.gaze=[0,0]),o.steady=c<3600;break}case "surprised":{let a=e<900?e<120?Me(e/120):1-Me((e-120)/780):0;o.scale+=.12*a,o.dy-=3*Fe(e,0,420),o.sy+=.06*Fe(e,0,380),o.mouth+=.3*a,o.steady=e<1800;let s=e<600?-1:(e-600)%4200,c=je(s,300,380,640,720),g=je(s,700,780,1090,1170);o.gaze=s>=300&&s<700?[-0.85,-0.1]:s>=700&&s<1150?[.85,-0.1]:[0,0],o.tilt+=-3*c+3*g,o.blink=Math.max(Fe(s,1700,1850),Fe(s,1950,2100));let m=Me(at((e-2600)/900));o.mouth-=.45*m,o.width*=1-.2*m;break}case "wow":{let a=.08*Math.sin(Math.PI*2*e/2800);o.scale+=.04+a*.3,o.mouth+=.05+a*.3,o.openL+=a*.15,o.openR+=a*.15,o.dy-=.8+a*3,o.tilt=1.5*Math.sin(Math.PI*2*e/3400),o.steady=true;break}case "sad":{let a=e%7e3;o.sy-=.045*Fe(a,0,1400),o.dy+=.5*je(a,700,1100,1800,2400);let s=je(a,3e3,3200,3800,4100);o.gaze=[0,.75-.9*s],o.openL=o.openR=1+.15*s,o.dy-=.4*s;let c=je(a,4400,4600,5300,5600);o.skew+=.12*Math.sin(i/40)*c,o.mouth+=.05*c,o.smile-=.15*c,o.tilt+=1.5*Math.sin(i/2200);break}case "thinking":{let a=e%6400;o.gaze=a<1200?sn[0]:a<2400?sn[1]:sn[2];let s=je(a,1200,1500,2100,2400);o.mouthX-=1.8*s,o.skew-=s,o.tilt-=9*s;let c=je(a,4100,4250,5600,6200);c>.3&&(o.gaze=[0,0]),o.openL*=1+.2*c,o.openR*=1+.4*c,o.scale+=.08*c,o.smile+=.8*c,o.mouthX-=.9*c,o.skew-=.5*c,o.width*=1+.5*c,o.mouth+=.15*c,o.tilt-=5*c,o.dy-=1.6*Fe(a,4100,4500),o.tilt+=1.5*Math.sin(i/900);break}case "sleepy":{let a=e%9200,s=a<3e3?Me(a/3e3):a<3200?1-Me((a-3e3)/200):0;o.openL=o.openR=1-.8*s,o.dy+=1.6*s,o.tilt+=6*s,o.gaze=[0,.6+.4*s];let c=Fe(a,3e3,3350);o.openL*=1+.9*c,o.openR*=1+.9*c,o.dy-=1.4*c,o.scale+=.1*c,a>=3e3&&a<4200&&(o.gaze=[0,0]),o.blink=Math.max(Fe(a,3550,3780),Fe(a,3900,4130)),o.yawn=je(a,5400,6200,6800,7600),o.tilt+=2*Math.sin(i/1700),o.steady=a<3e3;break}case "wink":{let a=e%3200,s=0;if(a>150&&a<950){let c=(a-150)/800;s=c<.2?Me(c/.2):c<.75?1:1-Me((c-.75)/.25);}o.laughR+=s,o.laughL+=.25*s,o.openL*=1-.12*s,o.skew+=.45*s,o.smile+=.1*s,o.tilt+=5*s,o.dy-=.9*Fe(a,150,450),s>0&&(o.gaze=[0,0]),o.steady=s>0;break}}return o}var Yn={jump:950,spin:600,bounce:1200,wiggle:800,float:2200},et={dy:0,rot:0,sx:1,sy:1,yaw:0,joy:0,gaze:null};function Gi(t,e){let i=at(e/Yn[t]);switch(t){case "jump":{if(e<160){let s=Me(e/160);return {...et,sx:1+.1*s,sy:1-.14*s,joy:s*.6}}if(e<560){let s=(e-160)/400,c=.09*Math.abs(Math.cos(Math.PI*s));return {...et,dy:-44*s*(1-s),sx:1-c*.6,sy:1+c,joy:1}}let o=(e-560)/390,a=.16*Math.exp(-5*o)*Math.cos(10*o);return {...et,sx:1+a*.7,sy:1-a,joy:1-Me(o)}}case "spin":{if(e<90){let s=Me(e/90);return {...et,yaw:-30*s,sx:1+.06*s,sy:1-.08*s,joy:.3*s,gaze:[-0.6*s,0]}}if(e<440){let s=(e-90)/350,c=Math.sin(Math.PI*s)**2,g=1-Me(Math.min(1,s*4));return {...et,yaw:-30+390*Fi(s),dy:-2.6*c,sx:1+.06*g,sy:1-.08*g+.04*c,joy:.8,gaze:[.8*c,0]}}let o=(e-440)/160,a=.025*Math.sin(Math.PI*o)*(1-o);return {...et,yaw:360,sx:1+a*.7,sy:1-a,joy:.8*(1-o)}}case "bounce":{let o=Math.abs(Math.sin(Math.PI*3*i)),a=.08*(1-o)**6;return {...et,dy:-5*o,sx:1+a*.8,sy:1-a,joy:Math.sin(Math.PI*i)}}case "wiggle":return {...et,rot:14*Math.sin(Math.PI*8*i)*(1-i),joy:.6*Math.sin(Math.PI*i)};case "float":{let o=[0,.9];if(e<520){let c=e/520,g=.05*Math.sin(Math.PI*c);return {...et,dy:-4.5*Fn(c),sx:1-g*.6,sy:1+g,joy:.5*c,gaze:c>.4?o:null}}if(e<1500){let c=(e-520)/980;return {...et,dy:-4.5+.8*Math.sin(Math.PI*3*c),rot:4*Math.sin(Math.PI*2*c),joy:.5,gaze:o}}if(e<1820){let c=(e-1500)/320;return {...et,dy:-4.5*(1-c*c),sx:1-.02*c,sy:1+.04*c,joy:.5,gaze:o}}let a=(e-1820)/380,s=.12*Math.exp(-5*a)*Math.cos(10*a)*(1-a);return {...et,sx:1+s*.7,sy:1-s,joy:.5*(1-a)}}}}var bt={viewBox:"-24 -24 48 48",body:_i,eyes:$o.map(t=>_n(t,Lo,1,0,1,0,0)),blush:$o.map(t=>({cx:t*1.6,cy:Lo+4.6})),mouth:Vn(0,Dn,0,.4,1,0),groundY:Ni,heart:Di,hearts:Po},On=t=>({emotion:t.emotion??"neutral",activity:t.activity??"idle",shape:t.shape??"pebble",lookAround:t.lookAround??true,followCursor:t.followCursor??false,hoverGiggle:t.hoverGiggle??true});function Gn(t,e={}){let i={config:On(e),playing:e.motion?{name:e.motion,start:performance.now()}:null,morph:null,onMotionEnd:e.onMotionEnd,onTickle:e.onTickle,tickledAt:-1/0,chuckledAt:-1/0},o=new Float32Array(96).fill(1),a=i.config.shape,s=e.motion??null,c=e.motionKey??0,g=e.chuckleKey??0,m=()=>{let d=performance.now();i.config.hoverGiggle&&d-i.tickledAt>1300&&(i.tickledAt=d,i.onTickle?.());};t.mover.addEventListener("pointerenter",m);let u=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(prefers-reduced-motion: reduce)").matches:false,S=null,f=d=>{S=d.pointerType==="mouse"?{x:d.clientX,y:d.clientY}:null;},C=()=>{S=null;};window.addEventListener("pointermove",f,{passive:true}),document.documentElement.addEventListener("pointerleave",C);let y={...Nn[i.config.emotion]},L=Math.random()*1e3,N=0,Q=performance.now(),U=0,X=0,H=0,le=0,Y=Q+600+Math.random()*1800,_=Q+800+Math.random()*2600,q=-1,Z=false,oe=-1/0,J=0,he=0,ze=Q+4e3+Math.random()*4e3,R=Math.random()*360,T=13.4,j=0,F=7,G=0,ee=0,ce=0,He=5.5,ke=1,pe=1,ye=0,Ee=0,We=6,Ue=false,wt=-1/0,At=Q+900,Je=-1/0,Ae=0,be=null,Qe=Q,Ke=-1/0,Be=-1/0,Ve=d=>{let W=Math.min(.064,(d-Q)/1e3);Q=d;let ie=u?0:d/1e3+L,O=i.config;O.emotion!==be&&(be==="love"&&(Be=d),be=O.emotion,Qe=d,be==="love"&&(Ke=d,Be=1/0));let de=d-Qe,P=Nn[be],A=Math.min(1,W*(Vi[be]??8));for(let $ of qi){let D=P[$];Number.isNaN(D)?y[$]=Number.NaN:Number.isNaN(y[$])?y[$]=D:y[$]+=(D-y[$])*A;}let l=u?qn():Yi(be,de,d),v=0,h=0;if(O.activity==="speaking"){d>Ee&&d>ye&&(ye=d+160+Math.random()*260,We-=1,Ue=We<=0,Ee=ye+(Ue?520+Math.random()*420:60+Math.random()*120),Ue&&(We=4+Math.floor(Math.random()*5)),Math.random()<.3&&(wt=d));let $=d<ye;v=$?.55+.35*Math.abs(Math.sin(d/70)):0,$?(ce+=W*He*Math.PI*2,ce>=Math.PI*2&&(ce-=Math.PI*2,He=4.6+Math.random()*2,ke=Math.random()<.18?.12:.55+Math.random()*.45,pe=Math.random()<.4?.62+Math.random()*.12:1+Math.random()*.2),h=Math.min(1,(.35+G)*ke*(.5-.5*Math.cos(ce)))):ce=0;let D=Fe(d-wt,0,280);l.dy-=.7*D,l.scale+=.06*D;}else O.activity==="listening"&&(v=.18+.14*Math.sin(d/240)*Math.sin(d/610));G+=(v-G)*Math.min(1,W*12),ee+=(h-ee)*Math.min(1,W*(h>ee?30:20));let x=et,M=i.playing;if(M&&!u){let $=d-M.start;$>=Yn[M.name]?(i.playing=null,i.onMotionEnd?.(M.name)):x=Gi(M.name,$);}let B=O.activity==="listening"?1:0;if(B&&!M&&d>At&&(Je=d,Ae+=1,At=d+2400+Math.random()*1800),B&&!u){let $=d-Je;if(Ae%3===0){let D=je($,0,160,700,1e3);l.scale+=.08*D,l.faceY-=.6*D,l.mouth+=.18*D,l.smile-=.3*D,l.dy-=.5*D;}else {let D=Fe($,0,300)+.7*Fe($,340,640);l.dy+=1.6*D,l.faceY+=1.2*D,l.sy-=.02*D,l.openL*=1-.15*D,l.openR*=1-.15*D,l.smile+=.1*D;}l.tilt+=4+1.5*Math.sin(d/2600);}let z=false,ue=O.followCursor&&S?t.svg.getBoundingClientRect():void 0;if(S&&ue&&ue.width>0){let $=S.x-(ue.left+ue.width/2),D=S.y-(ue.top+ue.height/2),Se=ue.width*.9;z=true,H=$/(Math.abs($)+Se),le=D/(Math.abs(D)+Se),Y=d+700;}let re=x.gaze??l.gaze;z||(re?(H=re[0],le=re[1]):Number.isNaN(y.gazeX)?d>Y&&(O.activity==="listening"?(H=(Math.random()-.5)*.3,le=-0.05+(Math.random()-.5)*.15):O.activity==="speaking"?(H=Ue?Math.random()<.5?-0.7:.7:(Math.random()-.5)*.5,le=Ue?-0.5:(Math.random()-.5)*.3):O.lookAround?(H=[-1,-0.6,0,0,.6,1][Math.floor(Math.random()*6)],le=(Math.random()-.5)*1.2):(H=0,le=0),Y=d+(O.activity==="speaking"?500+Math.random()*900:900+Math.random()*2300)):(H=y.gazeX,le=y.gazeY));let w=Math.min(1,W*(z?14:16));U+=(H-U)*w,X+=(le-X)*w;let me=Math.min(1,W*5);J+=(U-J)*me,he+=(X-he)*me,l.steady&&q<0&&(_=Math.max(_,d+400)),q<0&&d>_&&(q=d);let fe=1;if(q>=0){let $=(d-q)/(be==="sleepy"?460:be==="sad"?280:170);$>=1?(q=-1,!Z&&Math.random()<.22?(Z=true,_=d+90):(Z=false,_=d+2e3+Math.random()*3200)):fe=1-Math.sin($*Math.PI)*.88;}fe*=1-l.blink*.9;let xe=d-i.tickledAt,Ne=0,Pe=0;O.hoverGiggle&&xe<1300&&(Ne=xe<180?Me(xe/180):xe<800?1:1-Me((xe-800)/500),Pe=Math.sin(xe/42)*Math.max(0,1-xe/520));let qe=d-i.chuckledAt,ae=qe>0&&qe<1700?.45*je(qe,0,260,1e3,1700):0;Ne=Math.max(Ne,ae),be==="neutral"&&O.activity==="idle"&&d>ze&&(oe=d,ze=d+5e3+Math.random()*6e3);let Ye=be==="neutral"?je(d-oe,0,380,1100,1600):0,te=be==="sleepy"?1:0,Oe=l.yawn,Ie=O.shape,Ut=y.wobble+G*.6+Ne*.25,Ge=Ie==="squircle"?90:Ie==="blob"?120:Ie==="pebble"?72:0,lt=Ge?0:3.5+G*18;R=u?R:(R+W*lt*y.spin)%360,Ge&&(R+=(Math.round(R/Ge)*Ge-R)*Math.min(1,W*4));let It=i.morph,ct=It?Me(at((d-It.start)/Ui)):1,Co=R*Math.PI/180,_t=o;for(let $=0;$<96;$++){let D=ji(Ie,$/96*Math.PI*2-Co,ie,Ut);_t[$]=It&&ct<1?It.from[$]+(D-It.from[$])*ct:D;}It&&ct>=1&&(i.morph=null);let ro=1+(u?0:te?.03*Math.sin(ie/1.1):.015*Math.sin(ie/.9))+G*.04;t.body.setAttribute("d",jn(_t)),t.bodyGroup.setAttribute("transform",`scale(${ro.toFixed(4)})`);let Vt=x.yaw*Math.PI/180,Nt=y.bob+te*.4*Math.sin(d/1100)-Ne*.5+ee*.25-Oe*.5,ht=y.tilt+l.tilt+Pe*4+x.rot,ao=x.dy+Nt+l.dy,mt=Math.min(0,ao),Tt=.7*Math.max(0,ao)/(2*13.4),No=x.sy*(1+l.sy+Oe*.03)*(1-Tt),so=x.sx*(1-(l.sy+Oe*.03)*.5)*(1-.04*Math.abs(Math.sin(Vt)))*(1+Tt*.5),Et=ht*Math.PI/180,dt=0;for(let $=0;$<96;$++)dt=Math.max(dt,_t[$]*Math.sin($/96*Math.PI*2+Et));dt*=13.4*ro;let $e=1/0,ut=-1/0;for(let $=0;$<96;$++){let D=$/96*Math.PI*2+Et,Se=_t[$]*13.4*ro;Se*Math.sin(D)<dt-2.2||($e=Math.min($e,Se*Math.cos(D)),ut=Math.max(ut,Se*Math.cos(D)));}T+=(dt-T)*Math.min(1,W*12),t.mover.setAttribute("transform",`translate(0 ${mt.toFixed(2)}) translate(0 ${13.4}) scale(${so.toFixed(4)} ${No.toFixed(4)}) translate(0 ${(-T).toFixed(2)}) rotate(${ht.toFixed(2)})`);let we=at(-mt/10),qt=(ut-$e)/2*so,Oo=($e+ut)/2*so;j+=(Oo-j)*Math.min(1,W*12),F+=(qt-F)*Math.min(1,W*12);let Pt=t.ground;Pt&&(Pt.setAttribute("cx",(j*(1-we)).toFixed(2)),Pt.setAttribute("rx",((F+3.2)*(1+.25*we)).toFixed(2)),Pt.setAttribute("ry",(2*(1+.2*we)).toFixed(2)),Pt.setAttribute("opacity",((1-.65*we)*(.9+2*Tt)).toFixed(3)));let $t=t.core;$t&&($t.setAttribute("cx",j.toFixed(2)),$t.setAttribute("rx",(F*.95*(1-.4*we)).toFixed(2)),$t.setAttribute("ry",(.85*(1-.3*we)).toFixed(2)),$t.setAttribute("opacity",((1-we)**2*(.9+3*Tt)).toFixed(3)));let pt=t.face;if(pt){let $=Math.cos(Vt);pt.setAttribute("transform",`translate(${(Math.sin(Vt)*13.4*.72).toFixed(2)} 0) scale(${Math.max(.001,Math.abs($)).toFixed(3)} 1)`),pt.setAttribute("opacity",Me(at(($+.1)/.35)).toFixed(3));}let vt=1-Me(at((d-Be)/200));t.hearts.forEach(($,D)=>{if(!$)return;let Se=d-Ke-250-D*(xo/Po),ot=Math.floor(Se/xo),Ce=(Se-ot*xo)/Oi,Xt=Ke+250+D*(xo/Po)+ot*xo;if(u||!(Se>=0&&Se<1/0)||Ce>=1||Xt>Be||vt<=0){$.setAttribute("opacity","0");return}let Ht=(D+ot)%2?1:-1,nt=cn(ot*Po+D),St=Ht*(12+1.5*nt+2*Ce)+.9*Math.sin(Math.PI*2*(1.1*Ce+nt)),co=mt-4-nt*2-14*Fn(Ce),Ot=(.75+.35*nt)*(.5+.5*Me(at(Ce/.18))),Jt=Ht*10+14*Math.sin(Math.PI*2*(.9*Ce+nt));$.setAttribute("transform",`translate(${St.toFixed(2)} ${co.toFixed(2)}) rotate(${Jt.toFixed(1)}) scale(${Ot.toFixed(3)})`),$.setAttribute("opacity",(vt*Me(at(Ce/.12))*(1-Me(at((Ce-.55)/.45)))).toFixed(3));});let Mo=Math.max(x.joy,Ye),kt=1-Ne,lo=Math.min(1,y.smile+l.smile+(1-y.smile)*Mo+B*.15),Yt=Math.max(-1,(lo+(1-lo)*Ne)*(1-Oe)),zo=1-.18*Math.max(0,(Yt-.6)/.4),Bo=[y.openL*l.openL,y.openR*l.openR],Ro=[y.laughL+l.laughL,y.laughR+l.laughR];t.eyes.forEach(($,D)=>{if(!$)return;let Se=$o[D]+U*1.8*kt,ot=Lo+y.eyeY+l.faceY+X*1.1*kt,Ce=at(Math.max(Ro[D],Ne,x.joy*.8)),Xt=Math.min(.9,y.heavy+y.droop),Ht=Math.min(.9,y.heavy),nt=Bo[D]*fe*zo*(1-Oe*.85);$.setAttribute("d",_n(Se,ot,nt,Ce,y.eyeScale+l.scale+B*.04,D===0?Xt:Ht,D===0?Ht:Xt)),$.setAttribute("stroke-width",(Ce*.7).toFixed(2));let St=t.blush[D];St&&(St.setAttribute("cx",($o[D]*1.6+U*1.2*kt).toFixed(2)),St.setAttribute("cy",(Lo+4.6+l.faceY+X*.7*kt).toFixed(2)),St.setAttribute("opacity",at(y.blush).toFixed(3)));});let Ao=Ne*(.3+.25*Math.abs(Math.sin(d/85))),Gt=y.mouthW*l.width*(1+(pe-1)*ee)*(1-Oe*.1),Kt=at(-Yt+y.taper*(1-Oe)),Lt=t.mouth;if(Lt){Lt.setAttribute("d",Vn((y.mouthX+l.mouthX)*(1-Oe)+J*1.2*kt,Dn+y.eyeY*.5+l.faceY+he*.6*kt,Math.max(0,y.mouth+l.mouth,ee,Ao,x.joy*.35,Oe*2.1),Yt,Gt,(y.skew+l.skew)*(1-Oe),.9*Kt));let $=Math.min(1,.55+.45*Gt);Lt.setAttribute("stroke-width",(1.4*$*(1-.6*Kt)).toFixed(2));}N=requestAnimationFrame(Ve);};N=requestAnimationFrame(Ve);let E=()=>{cancelAnimationFrame(N),window.removeEventListener("pointermove",f),document.documentElement.removeEventListener("pointerleave",C);};return {update(d){i.config=On(d),i.onMotionEnd=d.onMotionEnd,i.onTickle=d.onTickle,i.config.shape!==a&&(a=i.config.shape,i.morph={from:o.slice(),start:performance.now()});let W=d.motion??null,ie=d.motionKey??0;(W!==s||ie!==c)&&(s=W,c=ie,i.playing=W?{name:W,start:performance.now()}:null);let O=d.chuckleKey??0;O!==g&&(g=O,i.chuckledAt=performance.now()+140+Math.random()*160);},destroy(){E(),t.mover.removeEventListener("pointerenter",m);}}}function zt({colors:t=["#66a6ff","#0059d4"],faceColor:e="#ffffff",eyeColor:i,mouthColor:o,outlineColor:a,outlineWidth:s=0,size:c=36,label:g="Botzki AI",className:m,style:u,shape:S="pebble",followCursor:f=true,...C}){let y=`bot-${useId().replace(/:/g,"")}`,L=useRef(null),N=useRef(null),Q=useRef(null),U=useRef(null),X=useRef(null),H=useRef(null),le=useRef(null),Y=useRef(null),_=useRef([]),q=useRef([]),Z=useRef([]),oe=useRef(null),J={shape:S,followCursor:f,...C},he=useRef(J);useEffect(()=>{he.current=J,oe.current?.update(J);}),useEffect(()=>{if(typeof window>"u")return;let F=L.current,G=N.current,ee=Q.current,ce=U.current,He=X.current,ke=H.current,pe=le.current,ye=Y.current;if(!(!F||!G||!ee||!ce||!He||!ke||!pe||!ye))return oe.current=Gn({svg:F,mover:G,bodyGroup:ee,body:ce,face:He,mouth:ke,ground:pe,core:ye,eyes:_.current,blush:q.current,hearts:Z.current},he.current),()=>{oe.current?.destroy(),oe.current=null;}},[]);let ze=i??e,R=o??e,T=a||"none",j=s?Number(s):0;return jsx("span",{className:m,style:{position:"relative",display:"inline-block",flex:"none",width:`${c}px`,height:`${c}px`,verticalAlign:"middle",...u},role:"img","aria-label":g,children:jsxs("svg",{ref:L,style:{position:"absolute",inset:"-25%",display:"block",width:"150%",height:"150%",overflow:"visible"},viewBox:bt.viewBox,"aria-hidden":true,children:[jsxs("defs",{children:[jsxs("radialGradient",{id:y,gradientUnits:"userSpaceOnUse",cx:"-4.8",cy:"-6.4",r:"24",children:[jsx("stop",{offset:"0",stopColor:t[0]}),jsx("stop",{offset:"1",stopColor:t[1]})]}),jsx("filter",{id:`${y}-soft`,x:"-50%",y:"-300%",width:"200%",height:"700%",children:jsx("feGaussianBlur",{stdDeviation:"1.3"})}),jsx("filter",{id:`${y}-core`,x:"-50%",y:"-300%",width:"200%",height:"700%",children:jsx("feGaussianBlur",{stdDeviation:"0.8"})}),jsx("filter",{id:`${y}-blush`,x:"-100%",y:"-100%",width:"300%",height:"300%",children:jsx("feGaussianBlur",{stdDeviation:"0.55"})})]}),jsx("ellipse",{ref:le,cx:"0",cy:bt.groundY,rx:"10",ry:"2.1",fill:"rgba(0, 0, 0, 0.08)",filter:`url(#${y}-soft)`}),jsx("ellipse",{ref:Y,cx:"0",cy:bt.groundY,rx:"6.5",ry:"0.9",fill:"rgba(0, 0, 0, 0.12)",filter:`url(#${y}-core)`}),jsxs("g",{ref:N,children:[jsx("g",{ref:Q,children:jsx("path",{ref:U,d:bt.body,fill:`url(#${y})`,stroke:T,strokeWidth:j,strokeLinejoin:"round",vectorEffect:"non-scaling-stroke"})}),jsxs("g",{ref:X,children:[bt.blush.map((F,G)=>jsx("ellipse",{ref:ee=>{q.current[G]=ee;},cx:F.cx,cy:F.cy,rx:"1.9",ry:"1.1",opacity:"0",fill:"rgba(255, 110, 150, 0.55)",filter:`url(#${y}-blush)`},`blush${G}`)),bt.eyes.map((F,G)=>jsx("path",{ref:ee=>{_.current[G]=ee;},d:F,strokeWidth:0,strokeLinejoin:"round",fill:ze,stroke:ze},`eye${G}`)),jsx("path",{ref:H,d:bt.mouth,strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round",fill:R,stroke:R})]})]}),Array.from({length:bt.hearts},(F,G)=>jsx("path",{ref:ee=>{Z.current[G]=ee;},d:bt.heart,opacity:"0",fill:"#ff4f7e"},G))]})})}var Xi=zt;function Wo({content:t,isUser:e=false,primaryColor:i="#0ea5e9",isDark:o=false}){if(!t)return null;let a=Qi(t);return jsx("div",{className:"botzki-markdown",style:{lineHeight:1.5,wordBreak:"break-word",fontSize:"inherit"},children:a.map((s,c)=>s.type==="code"?jsx(Zi,{code:s.code,lang:s.lang,isDark:o},c):jsx(er,{lines:s.lines,isUser:e,primaryColor:i,isDark:o},c))})}function Qi(t){let e=t.split(/\r?\n/),i=[],o=false,a="",s=[],c=[];for(let g=0;g<e.length;g++){let m=e[g],u=m.trim();u.startsWith("```")?o?(o=false,i.push({type:"code",code:s.join(`
5
+ `),lang:a||void 0}),s=[],a=""):(c.length>0&&(i.push({type:"text",lines:c}),c=[]),o=true,a=u.slice(3).trim(),s=[]):o?s.push(m):c.push(m);}return o?i.push({type:"code",code:s.join(`
6
+ `),lang:a||void 0}):c.length>0&&i.push({type:"text",lines:c}),i}function Zi({code:t,lang:e,isDark:i}){let[o,a]=useState(false);return jsxs("div",{style:{margin:"10px 0",borderRadius:"8px",overflow:"hidden",backgroundColor:i?"#0f172a":"#1e293b",border:"1px solid rgba(255, 255, 255, 0.1)",fontSize:"12px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 12px",backgroundColor:"rgba(0, 0, 0, 0.25)",color:"#94a3b8",fontSize:"11px",fontFamily:"monospace",borderBottom:"1px solid rgba(255, 255, 255, 0.08)"},children:[jsx("span",{children:e||"code"}),jsx("button",{type:"button",onClick:()=>{typeof navigator<"u"&&navigator.clipboard&&(navigator.clipboard.writeText(t),a(true),setTimeout(()=>a(false),2e3));},style:{background:"transparent",border:"none",color:o?"#34d399":"#cbd5e1",cursor:"pointer",fontSize:"11px",padding:"2px 6px",borderRadius:"4px"},children:o?"\u2713 Copied":"Copy"})]}),jsx("pre",{style:{margin:0,padding:"12px",overflowX:"auto",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',color:"#f8fafc",lineHeight:1.45},children:jsx("code",{children:t})})]})}function er({lines:t,isUser:e,primaryColor:i,isDark:o}){let a=[],s=null,c=[],g=u=>{if(c.length>0){let S=c.join(`
7
+ `);a.push(jsx("p",{style:{margin:"0 0 8px 0",whiteSpace:"pre-line"},children:Ho(S,e,i,o)},u)),c=[];}},m=u=>{if(s){let S=s.type;a.push(jsx(S,{style:{margin:"4px 0 10px 0",paddingLeft:"20px",display:"flex",flexDirection:"column",gap:"4px"},children:s.items.map((f,C)=>jsx("li",{style:{lineHeight:1.5},children:Ho(f,e,i,o)},C))},u)),s=null;}};for(let u=0;u<t.length;u++){let S=t[u],f=S.trim();if(!f){g(`p-${u}`),m(`list-${u}`);continue}let C=S.match(/^(#{1,6})\s+(.*)$/);if(C){g(`p-${u}`),m(`list-${u}`);let N=C[1].length,Q=C[2],U=N===1?"18px":N===2?"16px":N===3?"15px":"14px";a.push(jsx("div",{style:{fontWeight:700,fontSize:U,margin:"12px 0 6px 0",lineHeight:1.3},children:Ho(Q,e,i,o)},`h-${u}`));continue}if(f.startsWith("> ")){g(`p-${u}`),m(`list-${u}`),a.push(jsx("blockquote",{style:{margin:"8px 0",paddingLeft:"10px",borderLeft:`3px solid ${e?"rgba(255,255,255,0.4)":i}`,fontStyle:"italic",opacity:.9},children:Ho(f.slice(2),e,i,o)},`quote-${u}`));continue}let y=S.match(/^(\s*)[-*+]\s+(.*)$/);if(y){g(`p-${u}`),(!s||s.type!=="ul")&&(m(`list-prev-${u}`),s={type:"ul",items:[]}),s.items.push(y[2]);continue}let L=S.match(/^(\s*)\d+\.\s+(.*)$/);if(L){g(`p-${u}`),(!s||s.type!=="ol")&&(m(`list-prev-${u}`),s={type:"ol",items:[]}),s.items.push(L[2]);continue}s&&m(`list-${u}`),c.push(S);}return g("p-final"),m("list-final"),jsx(Fragment,{children:a})}function Ho(t,e,i,o){if(!t)return null;let a=/(`[^`]+`)|(\[([^\]]+)\]\(([^)]+)\))|(\*\*\*([^*]+)\*\*\*)|(\*\*([^*]+)\*\*|__([^_]+)__)|(\*([^*]+)\*|_([^_]+)_)|(~~([^~]+)~~)/g,s=[],c=0,g;for(;(g=a.exec(t))!==null;){g.index>c&&s.push(t.slice(c,g.index));let m=g[0];if(m.startsWith("`")&&m.endsWith("`")){let u=m.slice(1,-1);s.push(jsx("code",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:"0.88em",padding:"2px 5px",borderRadius:"4px",backgroundColor:e?"rgba(255, 255, 255, 0.25)":o?"rgba(255, 255, 255, 0.1)":"rgba(0, 0, 0, 0.06)",color:e?"#ffffff":o?"#38bdf8":"#0284c7"},children:u},g.index));}else if(g[2]){let u=g[3],S=g[4];s.push(jsx("a",{href:S,target:"_blank",rel:"noopener noreferrer",style:{color:e?"#ffffff":i,textDecoration:"underline",textUnderlineOffset:"2px",fontWeight:500},children:u},g.index));}else if(g[5])s.push(jsx("strong",{style:{fontWeight:700},children:jsx("em",{children:g[6]})},g.index));else if(g[7]){let u=g[8]||g[9];s.push(jsx("strong",{style:{fontWeight:700},children:u},g.index));}else if(g[10]){let u=g[11]||g[12];s.push(jsx("em",{children:u},g.index));}else g[13]&&s.push(jsx("del",{children:g[14]},g.index));c=g.index+m.length;}return c<t.length&&s.push(t.slice(c)),s.length===1?s[0]:jsx(Fragment,{children:s})}var Zn=[35,65,40,85,100,70,45,90,60,40,80,95,75,50,65,85,40,70,90,55,35,60,30,20];function un(t){if(typeof t!="number"||isNaN(t)||!isFinite(t)||t<=0)return "0:00";let e=Math.floor(t/60),i=Math.floor(t%60);return `${e}:${i.toString().padStart(2,"0")}`}function pn({audioUrl:t,duration:e,isUser:i=false,primaryColor:o="#0ea5e9",isDark:a=false,className:s,style:c}){let g=useRef(null),m=useRef(null),[u,S]=useState(false),[f,C]=useState(0),y=e&&isFinite(e)&&e>0?e:0,[L,N]=useState(y),[Q,U]=useState(1),[X,H]=useState(false);useEffect(()=>{e&&isFinite(e)&&e>0&&N(e);},[e]);let le=()=>{let j=g.current;if(!j)return;let F=j.duration;F&&isFinite(F)&&!isNaN(F)&&F>0?N(F):F===1/0&&(j.currentTime=1e101,j.ontimeupdate=()=>{j.ontimeupdate=null,isFinite(j.duration)&&j.duration>0&&N(j.duration),j.currentTime=0;});},Y=useCallback(()=>{let j=g.current;j&&(u?j.pause():j.play().catch(()=>{}));},[u]),_=useCallback(j=>{j.stopPropagation();let F=[1,1.5,2],G=(F.indexOf(Q)+1)%F.length,ee=F[G];U(ee),g.current&&(g.current.playbackRate=ee);},[Q]),q=useCallback(j=>{let F=m.current,G=g.current;if(!F||!G||L<=0)return;let ee=F.getBoundingClientRect(),ke=Math.max(0,Math.min(j-ee.left,ee.width))/ee.width*L;G.currentTime=ke,C(ke);},[L]),Z=j=>{j.stopPropagation(),H(true),q(j.clientX);let F=ee=>{q(ee.clientX);},G=()=>{H(false),window.removeEventListener("mousemove",F),window.removeEventListener("mouseup",G);};window.addEventListener("mousemove",F),window.addEventListener("mouseup",G);},oe=useMemo(()=>L<=0?0:Math.min(1,Math.max(0,f/L)),[f,L]),J=i?"rgba(255, 255, 255, 0.25)":a?"rgba(255, 255, 255, 0.12)":o,he="#ffffff",ze=i?"#ffffff":o,R=i?"rgba(255, 255, 255, 0.35)":a?"rgba(255, 255, 255, 0.22)":"rgba(100, 116, 139, 0.35)",T=i?"rgba(255, 255, 255, 0.85)":a?"#94a3b8":"#64748b";return jsxs("div",{className:s,style:{display:"flex",alignItems:"center",gap:"10px",minWidth:"210px",maxWidth:"280px",padding:"6px 2px",userSelect:"none",...c},children:[jsx("audio",{ref:g,src:t,preload:"metadata",onPlay:()=>S(true),onPause:()=>S(false),onEnded:()=>{S(false),C(0);},onLoadedMetadata:le,onDurationChange:le,onTimeUpdate:()=>{!X&&g.current&&C(g.current.currentTime);}}),jsx("button",{type:"button",onClick:Y,"aria-label":u?"Pause voice message":"Play voice message",title:u?"Pause":"Play",style:{width:"34px",height:"34px",borderRadius:"50%",backgroundColor:J,color:he,border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"transform 0.12s ease, opacity 0.15s ease",boxShadow:i?"none":"0 2px 6px rgba(0,0,0,0.1)"},children:u?jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:[jsx("rect",{x:"6",y:"4",width:"4",height:"16",rx:"1"}),jsx("rect",{x:"14",y:"4",width:"4",height:"16",rx:"1"})]}):jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",style:{marginLeft:"2px"},children:jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}),jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"4px"},children:[jsx("div",{ref:m,onMouseDown:Z,role:"slider","aria-valuemin":0,"aria-valuemax":L,"aria-valuenow":f,tabIndex:0,style:{display:"flex",alignItems:"center",gap:"2px",height:"24px",cursor:"pointer",padding:"2px 0"},children:Zn.map((j,F)=>{let G=(F+1)/Zn.length,ee=oe>=G;return jsx("div",{style:{flex:1,height:`${Math.max(15,j)}%`,backgroundColor:ee?ze:R,borderRadius:"2px",transition:X?"none":"background-color 0.1s ease"}},F)})}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:"11px",color:T,fontVariantNumeric:"tabular-nums"},children:[jsx("span",{children:u||f>0?`${un(f)} / ${un(L)}`:un(L)}),jsxs("button",{type:"button",onClick:_,title:"Playback speed","aria-label":`Playback speed: ${Q}x`,style:{background:i?"rgba(255,255,255,0.2)":a?"rgba(255,255,255,0.08)":"rgba(0,0,0,0.06)",border:"none",color:i?"#ffffff":a?"#cbd5e1":"#475569",padding:"1px 5px",borderRadius:"4px",fontSize:"10px",fontWeight:600,cursor:"pointer",lineHeight:1.2},children:[Q,"x"]})]})]})]})}var fn=({coBrowse:t})=>{let{isActive:e,operatorName:i,pointer:o,highlightedSelector:a,stop:s}=t,[c,g]=useState(null);return useEffect(()=>{if(!e||!a){g(null);return}let m;try{let u=document.querySelector(a);if(u){let S=()=>{let f=u.getBoundingClientRect();g({top:f.top+window.scrollY,left:f.left+window.scrollX,width:f.width,height:f.height});};S(),window.addEventListener("scroll",S,{passive:!0}),window.addEventListener("resize",S,{passive:!0}),m=()=>{window.removeEventListener("scroll",S),window.removeEventListener("resize",S);};}else g(null);}catch{g(null);}return ()=>{m&&m();}},[e,a]),e?jsxs(Fragment,{children:[jsx("style",{children:`
8
+ @keyframes cobrowse-pulse-ring {
9
+ 0% {
10
+ transform: scale(0.6);
11
+ opacity: 1;
12
+ }
13
+ 100% {
14
+ transform: scale(2.4);
15
+ opacity: 0;
16
+ }
17
+ }
18
+ @keyframes cobrowse-spotlight-pulse {
19
+ 0%, 100% {
20
+ box-shadow: 0 0 0 4px rgba(147, 51, 234, 0.4), 0 0 20px rgba(147, 51, 234, 0.3);
21
+ border-color: #a855f7;
22
+ }
23
+ 50% {
24
+ box-shadow: 0 0 0 8px rgba(147, 51, 234, 0.7), 0 0 30px rgba(147, 51, 234, 0.5);
25
+ border-color: #c084fc;
26
+ }
27
+ }
28
+ `}),jsxs("div",{style:{position:"fixed",top:"16px",left:"50%",transform:"translateX(-50%)",zIndex:999999,display:"flex",alignItems:"center",gap:"12px",padding:"8px 16px",borderRadius:"9999px",background:"rgba(15, 23, 42, 0.95)",color:"#ffffff",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.3), 0 8px 10px -6px rgba(0, 0, 0, 0.2)",backdropFilter:"blur(12px)",border:"1px solid rgba(255, 255, 255, 0.15)",fontFamily:"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",fontSize:"13px",pointerEvents:"auto"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{display:"inline-block",width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"#10b981",boxShadow:"0 0 8px #10b981"}}),jsx("span",{style:{fontWeight:600},children:"Screen Assist Active"}),jsxs("span",{style:{color:"#94a3b8"},children:["with ",i||"Support Specialist"]})]}),jsx("span",{style:{fontSize:"11px",padding:"2px 8px",borderRadius:"6px",background:"rgba(255, 255, 255, 0.1)",color:"#cbd5e1"},children:"\u{1F512} Inputs Masked"}),jsx("button",{type:"button",onClick:()=>s("User clicked Stop button"),style:{background:"#ef4444",color:"#ffffff",border:"none",borderRadius:"9999px",padding:"4px 12px",fontSize:"12px",fontWeight:600,cursor:"pointer",transition:"background 0.15s ease"},onMouseEnter:m=>m.target.style.background="#dc2626",onMouseLeave:m=>m.target.style.background="#ef4444",children:"End Assist"})]}),c&&jsx("div",{style:{position:"absolute",top:`${c.top-6}px`,left:`${c.left-6}px`,width:`${c.width+12}px`,height:`${c.height+12}px`,borderRadius:"8px",border:"2px solid #a855f7",pointerEvents:"none",zIndex:999990,animation:"cobrowse-spotlight-pulse 1.8s infinite ease-in-out",transition:"all 0.2s cubic-bezier(0.16, 1, 0.3, 1)"},children:jsxs("div",{style:{position:"absolute",bottom:"100%",left:"50%",transform:"translateX(-50%) translateY(-6px)",background:"#9333ea",color:"#ffffff",padding:"3px 10px",borderRadius:"6px",fontSize:"11px",fontWeight:600,whiteSpace:"nowrap",boxShadow:"0 4px 12px rgba(147, 51, 234, 0.4)"},children:[i||"Agent"," points here \u{1F446}"]})}),o&&jsxs("div",{style:{position:"fixed",left:`${o.xPercent*100}%`,top:`${o.yPercent*100}%`,pointerEvents:"none",zIndex:999998,transform:"translate(-50%, -50%)",transition:"left 0.08s linear, top 0.08s linear"},children:[jsx("div",{style:{width:"16px",height:"16px",borderRadius:"50%",backgroundColor:"#ef4444",boxShadow:"0 0 12px 3px rgba(239, 68, 68, 0.9), 0 0 24px 6px rgba(249, 115, 22, 0.6)",position:"relative"},children:jsx("div",{style:{position:"absolute",top:"-8px",left:"-8px",width:"32px",height:"32px",borderRadius:"50%",border:"2px solid #ef4444",animation:"cobrowse-pulse-ring 1.2s cubic-bezier(0.215, 0.61, 0.355, 1) infinite"}})}),o.label&&jsx("div",{style:{position:"absolute",top:"20px",left:"14px",background:"rgba(15, 23, 42, 0.9)",color:"#f8fafc",fontSize:"11px",fontWeight:500,padding:"3px 8px",borderRadius:"6px",whiteSpace:"nowrap",border:"1px solid rgba(255, 255, 255, 0.15)",boxShadow:"0 4px 10px rgba(0, 0, 0, 0.25)"},children:o.label})]})]}):null};var ar=["\u{1F60A}","\u{1F44B}","\u{1F44D}","\u2764\uFE0F","\u{1F389}","\u{1F525}","\u{1F680}","\u{1F4A1}","\u2728","\u{1F64C}","\u{1F91D}","\u{1F60D}","\u{1F64F}","\u{1F60E}","\u{1F4AF}"];function ti(t){return !t||t<=0?"":t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function oi(t){let e=(t||"").split(".").pop()?.toLowerCase();return e==="zip"||e==="tar"||e==="gz"||e==="rar"||e==="7z"?jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M21 8v13H3V8"}),jsx("path",{d:"M1 3h22v5H1z"}),jsx("path",{d:"M10 12h4"})]}):e==="pdf"?jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"#ef4444",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsx("polyline",{points:"14 2 14 8 20 8"}),jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]}):e==="csv"||e==="xlsx"||e==="xls"?jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"#10b981",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsx("polyline",{points:"14 2 14 8 20 8"}),jsx("path",{d:"M8 13h8"}),jsx("path",{d:"M8 17h8"})]}):jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),jsx("polyline",{points:"14 2 14 8 20 8"}),jsx("line",{x1:"16",y1:"13",x2:"8",y2:"13"}),jsx("line",{x1:"16",y1:"17",x2:"8",y2:"17"})]})}function hn({title:t,avatar:e,botAvatar:i,userAvatar:o,showAvatars:a=true,enableImageUpload:s=true,enableVoiceInput:c=true,enableVoiceOutput:g=true,enableVoiceNotes:m=true,enableHumanHandoff:u=true,enableActionEngine:S=true,showFeedback:f=true,showCitations:C=true,showBranding:y=true,showCopyButton:L=true,showExportButton:N=true,avatarColors:Q,avatarFaceColor:U,avatarEyeColor:X,avatarMouthColor:H,avatarShape:le,avatarSize:Y,headerAvatarBackground:_,avatarFollowCursor:q,avatarProps:Z,enableEmpathyEngine:oe=true,subtitle:J="Online",greeting:he="Hello! How can I help you today?",starterQuestions:ze,theme:R="auto",primaryColor:T="#0ea5e9",className:j="",style:F,placeholder:G="Compose your message...",onClose:ee,showCloseButton:ce=false,showClearButton:He=false,showNewChatButton:ke=false,showHistoryButton:pe=false,allowExpand:ye=false,isExpanded:Ee=false,onToggleExpand:We,onNewChat:Ue,isHistoryOpen:wt,onHistoryOpenChange:At,onFeedbackSubmit:Je,onCitationClick:Ae,renderHeader:be,customHeader:Qe,renderMessage:Ke,renderComposer:Be,renderWelcome:Ve,unreadCount:E,unreadFromIndex:d,inputStyle:W,composerStyle:ie,userBubbleColor:O,userTextColor:de,assistantBubbleColor:P,assistantTextColor:A,fontFamily:l,fontSize:v,headerStyle:h,messagesContainerStyle:x,sendButtonStyle:M,chat:B,...z}){let ue=Dt(),re=mo(z),w=B||re,{messages:me,input:fe,setInput:xe,handleInputChange:Ne,sendMessage:Pe,clearMessages:qe,isLoading:ae,isStreaming:Ye,error:te}=w,Oe=z.botId||ue?.botId||"default",Ie=z.persistSession??false,Ut=`botzki_sessions_${Oe}`,{data:Ge}=bo(),lt=useRef(null),[It,ct]=useState(false),[Co,_t]=useState(""),[Uo,ro]=useState(""),[Vt,Nt]=useState(null),[ht,ao]=useState(false),[mt,Tt]=useState(()=>{if(!Ie||typeof window>"u"||!window.localStorage)return [];try{let r=localStorage.getItem(Ut);return r?JSON.parse(r):[]}catch{return []}}),[No,so]=useState(false),Et=wt!==void 0?wt:No,dt=r=>{let k=typeof r=="function"?r(Et):r;so(k),At?.(k);},[$e,ut]=useState(null),[we,qt]=useState(null),Oo=useMemo(()=>!fe||fe.length<8?false:/(?:\d[ -]*?){13,19}|\b\d{3}[- ]\d{2}[- ]\d{4}\b|sk-[A-Za-z0-9]{15,}|Bearer\s+[A-Za-z0-9_\-\.]{15,}/i.test(fe),[fe]),[Pt,$t]=useState(false),pt=useRef(null),[vt,Mo]=useState(0),[kt,lo]=useState(""),[Yt,zo]=useState(false),[Bo,Ro]=useState(false),[Ao,Gt]=useState(false),[Kt,Lt]=useState(0),$=useRef(0),D=useRef(null),Se=useRef(null),ot=useRef([]),Ce=useRef(null),Xt=r=>{let k=Math.floor(r/60),I=Math.floor(r%60);return `${k}:${I.toString().padStart(2,"0")}`},Ht=async()=>{if(typeof window>"u"||!navigator.mediaDevices?.getUserMedia){alert("Microphone recording is not supported in this browser environment.");return}try{let r=await navigator.mediaDevices.getUserMedia({audio:!0});Se.current=r,ot.current=[];let k="";typeof MediaRecorder<"u"&&(MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?k="audio/webm;codecs=opus":MediaRecorder.isTypeSupported("audio/webm")?k="audio/webm":MediaRecorder.isTypeSupported("audio/mp4")&&(k="audio/mp4"));let I=k?new MediaRecorder(r,{mimeType:k}):new MediaRecorder(r);I.ondataavailable=K=>{K.data&&K.data.size>0&&ot.current.push(K.data);},D.current=I,I.start(250),$.current=Date.now(),Gt(!0),Lt(0),Ce.current&&clearInterval(Ce.current),Ce.current=setInterval(()=>{Lt(K=>K+1);},1e3);}catch(r){console.warn("Failed to start voice recording:",r),alert("Could not access microphone. Please grant microphone permissions to send voice messages.");}},nt=()=>{if(Ce.current&&(clearInterval(Ce.current),Ce.current=null),D.current&&D.current.state!=="inactive"){D.current.onstop=null;try{D.current.stop();}catch{}}Se.current&&(Se.current.getTracks().forEach(r=>r.stop()),Se.current=null),ot.current=[],Gt(false),Lt(0);},St=()=>{Ce.current&&(clearInterval(Ce.current),Ce.current=null);let r=$.current?(Date.now()-$.current)/1e3:Kt,k=Math.max(1,Math.round(r)),I=D.current;if(I&&I.state!=="inactive"){I.onstop=()=>{let K=I.mimeType||"audio/webm",ge=new Blob(ot.current,{type:K});if(Se.current&&(Se.current.getTracks().forEach(V=>V.stop()),Se.current=null),ot.current=[],Gt(false),Lt(0),ge.size>0)if(typeof w.sendVoiceMessage=="function")w.sendVoiceMessage(ge,{audioDuration:k});else {let V=URL.createObjectURL(ge);w.sendMessage("",{audioUrl:V,audioDuration:k});}};try{I.stop();}catch{nt();}}else nt();};useEffect(()=>()=>{Ce.current&&clearInterval(Ce.current),Se.current&&Se.current.getTracks().forEach(r=>r.stop());},[]);let[co,Ot]=useState(false),Jt=useRef(null),[uo,Qt]=useState(null),[Do,li]=useState({}),[ci,wn]=useState(null),[Io,Fo]=useState(false),jo=useRef(null),di=r=>{xe(fe+r),Fo(false),Zt.current?.focus();};useEffect(()=>{if(!Io)return;let r=k=>{jo.current&&!jo.current.contains(k.target)&&Fo(false);};return document.addEventListener("mousedown",r),()=>document.removeEventListener("mousedown",r)},[Io]);let Zt=useRef(null),[vn,kn]=useState(false);useEffect(()=>{if(Zt.current){Zt.current.style.height="auto";let r=Zt.current.scrollHeight,k=Math.min(Math.max(r,38),120);Zt.current.style.height=`${k}px`;}},[fe]);let ui=r=>{r.key==="Enter"&&!r.shiftKey&&(r.preventDefault(),!ae&&(fe.trim()||$e)&&Bn(r));},Ct=yo({messages:w.messages,isLoading:w.isLoading,isStreaming:w.isStreaming,isWaitingForHuman:w.isWaitingForHuman,isHumanHandoffActive:w.isHumanHandoffActive,feedbackRating:Bo?vt>=4?"up":"down":null,manualEmotion:e?.emotion,manualMotion:e?.motion??void 0,enabled:oe}),se=useMemo(()=>({colors:e?.colors??Q??["#66a6ff","#0059d4"],faceColor:e?.faceColor??U??"#ffffff",eyeColor:e?.eyeColor??X,mouthColor:e?.mouthColor??H,shape:e?.shape??le??"pebble",size:e?.size??Y,followCursor:e?.followCursor??q??true,motion:e?.motion??(oe?Ct.motion:void 0),emotion:e?.emotion??(oe?Ct.emotion:"neutral"),outlineColor:e?.outlineColor,outlineWidth:e?.outlineWidth,background:e?.background??_,props:{...Z,...e?.props,motionKey:Ct.motionKey}}),[e,Q,U,X,H,le,Y,q,Z,_,oe,Ct.emotion,Ct.motion,Ct.motionKey]);useEffect(()=>{if(me.length===0)return;let r=w.sessionId,k=me.find(K=>K.role==="user"),I=k?k.content.slice(0,36)+(k.content.length>36?"...":""):"Conversation";Tt(K=>{let ge=new Date().toISOString(),V=K.findIndex(fo=>fo.id===r),De;V>=0?(De=[...K],De[V]={...De[V],title:De[V].title==="Conversation"||!De[V].title?I:De[V].title,updatedAt:ge,messages:me}):De=[{id:r,title:I,createdAt:ge,updatedAt:ge,messages:me},...K];try{Ie&&typeof window<"u"&&window.localStorage&&localStorage.setItem(Ut,JSON.stringify(De));}catch{}return De});},[me,w.sessionId,Ut,Ie]);let[_o,Sn]=useState(true),[Vo,qo]=useState(0),Yo=useRef(me.length),Go=useRef(null),Wt=d!==void 0?d:E&&E>0&&me.length>=E?me.length-E:void 0;useEffect(()=>{Wt!==void 0&&Go.current&&Go.current.scrollIntoView({behavior:"smooth",block:"start"});},[Wt]);let pi=()=>{if(!lt.current)return;let{scrollTop:r,scrollHeight:k,clientHeight:I}=lt.current,K=k-r-I<60;Sn(K),K&&qo(0);},fi=()=>{lt.current&&(lt.current.scrollTo({top:lt.current.scrollHeight,behavior:"smooth"}),Sn(true),qo(0));};useEffect(()=>{lt.current&&(Wt!==void 0&&Wt<me.length||(_o?lt.current.scrollTop=lt.current.scrollHeight:me.length>Yo.current&&qo(r=>r+(me.length-Yo.current)),Yo.current=me.length));},[me,Ye,$e,_o,Wt]),useEffect(()=>()=>{if(typeof window<"u"&&window.speechSynthesis&&window.speechSynthesis.cancel(),Jt.current)try{Jt.current.stop();}catch{}},[]);let po=()=>{typeof window<"u"&&window.speechSynthesis&&(window.speechSynthesis.cancel(),Qt(null));let r=`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;w.clearMessages(),w.setSessionId(r),ut(null),dt(false),Ue?.();},gi=r=>{typeof window<"u"&&window.speechSynthesis&&(window.speechSynthesis.cancel(),Qt(null)),w.setSessionId(r.id),w.setMessages(r.messages),dt(false);},hi=(r,k)=>{k.stopPropagation(),Tt(I=>{let K=I.filter(ge=>ge.id!==r);try{Ie&&typeof window<"u"&&window.localStorage&&localStorage.setItem(Ut,JSON.stringify(K));}catch{}return K}),w.sessionId===r&&po();},mi=()=>{Tt([]);try{Ie&&typeof window<"u"&&window.localStorage&&localStorage.removeItem(Ut);}catch{}po();},Cn=(r="markdown")=>{let k=t||Ge?.name||"Botzki AI Assistant",I="";if(r==="json"?I=JSON.stringify({sessionId:w.sessionId,botTitle:k,exportedAt:new Date().toISOString(),messages:w.messages},null,2):(I=`# Conversation with ${k}
29
+
30
+ `,I+=`- **Date:** ${new Date().toLocaleString()}
31
+ `,I+=`- **Session ID:** \`${w.sessionId}\`
32
+
33
+ ---
34
+
35
+ `,w.messages.forEach(K=>{let ge=K.role==="user"?"User":k;I+=`### ${ge} (${new Date(K.createdAt).toLocaleTimeString()}):
36
+ ${K.content}
37
+
38
+ `;})),typeof window<"u"&&typeof document<"u"){let K=new Blob([I],{type:r==="json"?"application/json":"text/markdown;charset=utf-8"}),ge=URL.createObjectURL(K),V=document.createElement("a");V.href=ge,V.download=`botzki-chat-${Date.now()}.${r==="json"?"json":"md"}`,document.body.appendChild(V),V.click(),document.body.removeChild(V),URL.revokeObjectURL(ge);}return I},bi=r=>{let k=r.target.files?.[0];if(k){if(k.size>25*1024*1024){alert("Attachment size must be less than 25MB."),pt.current&&(pt.current.value="");return}if(k.type.startsWith("image/")){let I=new FileReader;I.onload=()=>{ut({dataUrl:I.result,name:k.name}),qt(null);},I.readAsDataURL(k);}else qt({file:k,name:k.name,size:k.size}),ut(null);pt.current&&(pt.current.value="");}},yi=()=>{if(co){Jt.current?.stop(),Ot(false);return}let r=window.SpeechRecognition||window.webkitSpeechRecognition;if(!r){alert("Voice input is not supported in this browser. Please use Chrome, Edge, or Safari.");return}try{let k=new r;k.continuous=!1,k.interimResults=!0,k.lang="en-US",k.onstart=()=>Ot(!0),k.onresult=I=>{let K="";for(let ge=I.resultIndex;ge<I.results.length;ge++)K+=I.results[ge][0].transcript;xe(K);},k.onerror=()=>Ot(!1),k.onend=()=>Ot(!1),Jt.current=k,k.start();}catch{Ot(false);}},Mn=(r,k)=>{if(typeof window>"u"||!window.speechSynthesis)return;if(uo===r){window.speechSynthesis.cancel(),Qt(null);return}window.speechSynthesis.cancel();let I=k.replace(/[*_#`\[\]\(\)]/g," "),K=new SpeechSynthesisUtterance(I);K.onend=()=>Qt(null),K.onerror=()=>Qt(null),window.speechSynthesis.speak(K),Qt(r);},Ko=async(r,k)=>{li(V=>({...V,[r]:k})),Je?.(r,k);let I=z.botId||ue?.botId,K=z.baseUrl||ue?.baseUrl||"https://api.botzki.com",ge=z.publishableKey||ue?.publishableKey;if(I)try{await fetch(`${K.replace(/\/+$/,"")}/api/v1/public/chat/${I}/messages/${r}/reaction`,{method:"POST",headers:{"Content-Type":"application/json",...ge?{Authorization:`Bearer ${ge}`}:{}},body:JSON.stringify({rating:k,reaction:k,sessionId:w.sessionId})});}catch{}},zn=(r,k)=>{navigator.clipboard&&(navigator.clipboard.writeText(k),wn(r),setTimeout(()=>wn(null),2e3));},Bn=async r=>{r.preventDefault();let k=fe.trim();if(!(!k&&!$e&&!we)){if(we){$t(true);try{let I=z.botId||ue?.botId,K=z.baseUrl||ue?.baseUrl||"https://api.botzki.com",ge=z.publishableKey||ue?.publishableKey,V=new FormData;V.append("file",we.file);let De=K?K.replace(/\/+$/,""):"https://api.botzki.com",fo={};ge&&(fo.Authorization=`Bearer ${ge}`);let In=await fetch(`${De}/api/v1/public/bots/${I}/handoff/upload`,{method:"POST",headers:fo,body:V});if(In.ok){let Zo=await In.json(),vi=Zo.mediaUrl.startsWith("http")?Zo.mediaUrl:`${De}${Zo.mediaUrl}`;await Pe(k||`\u{1F4CE} ${we.name}`,{fileUrl:vi,fileName:we.name,fileSize:we.size});}else await Pe(k||`\u{1F4CE} ${we.name}`);}catch(I){console.warn("Failed to upload document attachment:",I),await Pe(k||`\u{1F4CE} ${we.name}`);}finally{$t(false),qt(null),xe("");}return}Pe(k||"Please analyze this image.",{imageBase64:$e?.dataUrl}),xe(""),ut(null);}},Xo=t||Ge?.name||"AI Assistant",Rn=ze||Ge?.starterQuestions||[],b=R==="dark"||R==="auto"&&typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches,To=b?"#0f172a":"#ffffff",Jo=b?"#1e293b":"#f8fafc",it=b?"#f8fafc":"#0f172a",ne=b?"#94a3b8":"#64748b",Te=b?"#334155":"#e2e8f0",xi=O||T,wi=de||"#ffffff",Qo=P||(b?"#1e293b":"#f1f5f9"),An=A||(b?"#f1f5f9":"#1e293b");return jsxs("div",{className:j,style:{position:"relative",display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:"450px",backgroundColor:To,color:it,borderRadius:"16px",border:`1px solid ${Te}`,overflow:"hidden",boxSizing:"border-box",fontFamily:l||'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',fontSize:typeof v=="number"?`${v}px`:v||"14px",...F},children:[jsx("style",{children:`
39
+ .botzki-chat-scroll::-webkit-scrollbar {
40
+ width: 5px;
41
+ height: 5px;
42
+ }
43
+ .botzki-chat-scroll::-webkit-scrollbar-track {
44
+ background: transparent;
45
+ }
46
+ .botzki-chat-scroll::-webkit-scrollbar-thumb {
47
+ background: ${b?"rgba(255, 255, 255, 0.2)":"rgba(0, 0, 0, 0.2)"};
48
+ border-radius: 9999px;
49
+ }
50
+ .botzki-chat-scroll::-webkit-scrollbar-thumb:hover {
51
+ background: ${b?"rgba(255, 255, 255, 0.38)":"rgba(0, 0, 0, 0.38)"};
52
+ }
53
+ .botzki-composer-textarea::-webkit-scrollbar {
54
+ display: none !important;
55
+ width: 0 !important;
56
+ height: 0 !important;
57
+ }
58
+ .botzki-composer-textarea {
59
+ -ms-overflow-style: none !important;
60
+ scrollbar-width: none !important;
61
+ }
62
+ @keyframes botzki-pulse {
63
+ 0% { transform: scale(1); opacity: 1; }
64
+ 50% { transform: scale(1.15); opacity: 0.8; }
65
+ 100% { transform: scale(1); opacity: 1; }
66
+ }
67
+ @keyframes botzki-equalizer {
68
+ 0% { transform: scaleY(0.25); opacity: 0.55; }
69
+ 100% { transform: scaleY(1); opacity: 1; }
70
+ }
71
+ @keyframes botzki-fade-in {
72
+ from { opacity: 0; transform: translateY(-6px); }
73
+ to { opacity: 1; transform: translateY(0); }
74
+ }
75
+ @keyframes botzki-greeting-pop {
76
+ 0% {
77
+ opacity: 0;
78
+ transform: translateY(16px) scale(0.94);
79
+ }
80
+ 65% {
81
+ opacity: 1;
82
+ transform: translateY(-2px) scale(1.02);
83
+ }
84
+ 100% {
85
+ opacity: 1;
86
+ transform: translateY(0) scale(1);
87
+ }
88
+ }
89
+ @keyframes botzki-avatar-entrance {
90
+ 0% {
91
+ opacity: 0;
92
+ transform: scale(0.6) rotate(-15deg);
93
+ }
94
+ 60% {
95
+ transform: scale(1.15) rotate(5deg);
96
+ }
97
+ 100% {
98
+ opacity: 1;
99
+ transform: scale(1) rotate(0deg);
100
+ }
101
+ }
102
+ @keyframes botzki-wave {
103
+ 0%, 100% { transform: rotate(0deg); }
104
+ 20% { transform: rotate(18deg); }
105
+ 40% { transform: rotate(-10deg); }
106
+ 60% { transform: rotate(16deg); }
107
+ 80% { transform: rotate(-4deg); }
108
+ }
109
+ @keyframes botzki-starter-in {
110
+ 0% {
111
+ opacity: 0;
112
+ transform: translateY(12px) scale(0.96);
113
+ }
114
+ 100% {
115
+ opacity: 1;
116
+ transform: translateY(0) scale(1);
117
+ }
118
+ }
119
+ .botzki-starter-btn {
120
+ transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
121
+ }
122
+ .botzki-starter-btn:hover {
123
+ transform: translateY(-2px);
124
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
125
+ border-color: ${T} !important;
126
+ }
127
+ `}),Et&&jsxs("div",{style:{position:"absolute",top:0,left:0,right:0,bottom:0,backgroundColor:To,zIndex:20,display:"flex",flexDirection:"column",overflow:"hidden",animation:"botzki-fade-in 0.2s ease-out"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",backgroundColor:Jo,borderBottom:`1px solid ${Te}`},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("polyline",{points:"12 6 12 12 16 14"})]}),jsx("span",{style:{fontWeight:600,fontSize:"14px"},children:"Chat History"}),jsx("span",{style:{fontSize:"11px",color:ne,padding:"2px 6px",borderRadius:"10px",backgroundColor:b?"#334155":"#e2e8f0"},children:mt.length})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[jsx("button",{type:"button",onClick:po,style:{background:T,color:"#ffffff",border:"none",borderRadius:"6px",padding:"5px 10px",fontSize:"12px",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",gap:"4px"},children:"+ New Chat"}),jsx("button",{type:"button",onClick:()=>dt(false),title:"Close History",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"16px",padding:"4px 8px",borderRadius:"6px"},children:"\u2715"})]})]}),jsx("div",{className:"botzki-chat-scroll",style:{flex:1,overflowY:"auto",padding:"12px 14px",display:"flex",flexDirection:"column",gap:"8px"},children:mt.length===0?jsx("div",{style:{textAlign:"center",color:ne,fontSize:"13px",marginTop:"40px"},children:"No saved chat sessions yet."}):mt.map(r=>{let k=r.id===w.sessionId;return jsxs("div",{onClick:()=>gi(r),style:{padding:"10px 12px",borderRadius:"8px",backgroundColor:k?b?"rgba(14, 165, 233, 0.15)":"rgba(14, 165, 233, 0.1)":b?"#1e293b":"#f8fafc",border:`1px solid ${k?T:Te}`,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"space-between",transition:"border-color 0.15s ease"},children:[jsxs("div",{style:{flex:1,overflow:"hidden",marginRight:"8px"},children:[jsx("div",{style:{fontWeight:600,fontSize:"13px",color:it,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:r.title||"Conversation"}),jsxs("div",{style:{fontSize:"11px",color:ne,marginTop:"2px"},children:[new Date(r.updatedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})," ","\xB7 ",r.messages.length," messages"]})]}),jsx("button",{type:"button",onClick:I=>hi(r.id,I),title:"Delete session",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",padding:"4px 6px",borderRadius:"4px",fontSize:"13px"},children:"\u{1F5D1}"})]},r.id)})}),jsxs("div",{style:{padding:"10px 16px",borderTop:`1px solid ${Te}`,backgroundColor:Jo,display:"flex",alignItems:"center",justifyContent:"space-between"},children:[jsx("button",{type:"button",onClick:()=>Cn("markdown"),disabled:w.messages.length===0,style:{background:"transparent",border:`1px solid ${Te}`,color:it,borderRadius:"6px",padding:"5px 10px",fontSize:"12px",cursor:w.messages.length===0?"not-allowed":"pointer",opacity:w.messages.length===0?.5:1,display:"flex",alignItems:"center",gap:"4px"},children:"\u{1F4E5} Export Chat (.md)"}),mt.length>0&&jsx("button",{type:"button",onClick:mi,style:{background:"transparent",border:"none",color:"#ef4444",fontSize:"12px",cursor:"pointer",padding:"5px 8px"},children:"Clear All"})]})]}),be?be({title:Xo,subtitle:J,isDark:b,primaryColor:T,isOpen:true,isExpanded:Ee,isHistoryOpen:Et,botAvatar:i,onClose:ee,onClear:qe,onNewChat:po,toggleHistory:()=>dt(r=>!r),toggleExpand:We}):Qe||jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"14px 18px",backgroundColor:Jo,borderBottom:`1px solid ${Te}`,...h},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[i?typeof i=="string"?jsx("img",{src:i,alt:Xo,style:{width:"36px",height:"36px",borderRadius:"50%",objectFit:"cover",flexShrink:0}}):i:jsx("div",{style:{width:"36px",height:"36px",borderRadius:"50%",backgroundColor:se.background??(b?"rgba(255, 255, 255, 0.08)":"rgba(0, 0, 0, 0.05)"),display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",flexShrink:0},children:jsx(zt,{size:se.size??28,shape:se.shape??"pebble",followCursor:se.followCursor,colors:se.colors??["#66a6ff","#0059d4"],faceColor:se.faceColor??"#ffffff",eyeColor:se.eyeColor,mouthColor:se.mouthColor,motion:se.motion,emotion:se.emotion,outlineColor:se.outlineColor,outlineWidth:se.outlineWidth,...se.props})}),jsxs("div",{style:{minWidth:0,flex:1},children:[jsx("div",{style:{fontWeight:600,fontSize:"14px",lineHeight:1.2,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:Xo}),jsxs("div",{style:{fontSize:"12px",color:ne,display:"flex",alignItems:"center",gap:"5px",marginTop:"2px"},children:[jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",backgroundColor:"#22c55e",display:"inline-block"}}),J]})]})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"4px"},children:[ke&&jsxs("button",{onClick:po,title:"Start New Chat",type:"button",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"4px 7px",borderRadius:"6px",display:"flex",alignItems:"center",gap:"3px"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),jsx("span",{children:"New"})]}),pe&&jsxs("button",{onClick:()=>dt(r=>!r),title:Et?"Close History":"Chat History",type:"button",style:{background:Et?b?"#334155":"#e2e8f0":"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"4px 7px",borderRadius:"6px",display:"flex",alignItems:"center",gap:"3px"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("polyline",{points:"12 6 12 12 16 14"})]}),mt.length>0&&jsx("span",{style:{fontSize:"10px",opacity:.85},children:mt.length})]}),ye&&We&&jsx("button",{onClick:We,title:Ee?"Collapse Widget":"Expand Widget",type:"button",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"13px",padding:"4px 6px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center"},children:Ee?jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("polyline",{points:"4 14 10 14 10 20"}),jsx("polyline",{points:"20 10 14 10 14 4"}),jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("polyline",{points:"15 3 21 3 21 9"}),jsx("polyline",{points:"9 21 3 21 3 15"}),jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),me.length>0&&N&&jsx("button",{onClick:()=>Cn("markdown"),title:"Download Chat Transcript",type:"button",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"4px 6px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center"},children:jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsx("polyline",{points:"7 10 12 15 17 10"}),jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]})}),me.length>0&&He&&jsx("button",{onClick:qe,title:"Clear Chat",type:"button",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"4px 7px",borderRadius:"6px"},children:"Clear"}),(()=>{let r=u!==false&&Ge?.liveChatEnabled!==false&&Ge?.humanHandoffEnabled!==false,k=Ge?.liveChatIsOnline===false&&Ge?.liveChatOutOfHoursBehavior==="aiOnly",I=r&&!k&&!w.isHumanHandoffActive&&!w.isWaitingForHuman,K=Ge?.handoffButtonText||"Talk to Support";return I?jsxs("button",{onClick:async()=>{if(Ge?.liveChatRequireEmail){ct(true);return}try{await w.requestHumanHandoff?.("User requested from widget header");}catch(V){V?.code==="EMAIL_REQUIRED"&&ct(true);}},title:K,type:"button",style:{background:b?"rgba(255, 255, 255, 0.08)":"rgba(0, 0, 0, 0.05)",border:`1px solid ${b?"rgba(255, 255, 255, 0.12)":"rgba(0, 0, 0, 0.08)"}`,color:b?"#e2e8f0":"#334155",cursor:"pointer",fontSize:"11px",fontWeight:600,padding:"4px 9px",borderRadius:"9999px",display:"flex",alignItems:"center",gap:"4px",transition:"all 0.15s ease"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M3 18v-6a9 9 0 0 1 18 0v6"}),jsx("path",{d:"M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"})]}),jsx("span",{children:K})]}):null})(),ce&&ee&&jsx("button",{onClick:ee,title:"Close Chat",type:"button",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"16px",padding:"4px 8px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center"},children:"\u2715"})]})]}),w.coBrowse?.isRequested&&!w.coBrowse?.isActive&&jsxs("div",{style:{padding:"12px 14px",backgroundColor:b?"rgba(30, 41, 59, 0.95)":"rgba(240, 253, 250, 0.95)",borderBottom:`1px solid ${b?"rgba(16, 185, 129, 0.3)":"rgba(16, 185, 129, 0.2)"}`,display:"flex",flexDirection:"column",gap:"10px",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.05)"},children:[jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"10px"},children:[jsx("div",{style:{width:"32px",height:"32px",borderRadius:"8px",backgroundColor:b?"rgba(16, 185, 129, 0.2)":"#d1fae5",color:"#10b981",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,fontSize:"16px"},children:"\u{1F6E1}\uFE0F"}),jsxs("div",{style:{flex:1},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:it},children:"Live Screen Assist Request"}),jsxs("div",{style:{fontSize:"11px",color:ne,marginTop:"2px",lineHeight:"1.4"},children:[jsx("strong",{children:w.coBrowse.operatorName||"Support Specialist"})," requested permission to view your screen to guide you."]}),jsx("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginTop:"4px",fontSize:"10px",color:b?"#34d399":"#059669"},children:jsx("span",{children:"\u{1F512} Privacy Shield Active \u2022 Form inputs & passwords masked"})})]})]}),jsxs("div",{style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[jsx("button",{type:"button",onClick:()=>w.coBrowse?.decline("Visitor declined"),style:{padding:"5px 12px",borderRadius:"6px",border:`1px solid ${Te}`,background:"transparent",color:ne,fontSize:"11px",fontWeight:500,cursor:"pointer"},children:"Decline"}),jsx("button",{type:"button",onClick:()=>w.coBrowse?.accept(),style:{padding:"5px 14px",borderRadius:"6px",border:"none",background:"linear-gradient(135deg, #10b981 0%, #059669 100%)",color:"#ffffff",fontSize:"11px",fontWeight:600,cursor:"pointer",boxShadow:"0 2px 6px rgba(16, 185, 129, 0.3)"},children:"Allow Live Assist"})]})]}),It&&jsxs("form",{onSubmit:async r=>{r.preventDefault();let k=Co.trim();if(!k||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(k)){Nt("Please enter a valid email address.");return}ao(true),Nt(null);try{await w.requestHumanHandoff?.("User requested live support via email gate",Uo.trim()||void 0,k),ct(!1);}catch(I){Nt(I?.message||"Failed to join live support queue.");}finally{ao(false);}},style:{padding:"12px 14px",backgroundColor:b?"#1e293b":"#f8fafc",borderBottom:`1px solid ${Te}`,display:"flex",flexDirection:"column",gap:"9px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.04)"},children:[jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start"},children:[jsxs("div",{children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:it},children:"Connect with Live Specialist"}),jsx("div",{style:{fontSize:"11px",color:ne,marginTop:"1px"},children:"Enter your details to join the live support queue."})]}),jsx("button",{type:"button",onClick:()=>{ct(false),Nt(null);},style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"14px",padding:"2px 6px",borderRadius:"4px"},children:"\u2715"})]}),Vt&&jsx("div",{style:{fontSize:"11px",color:"#ef4444",fontWeight:500},children:Vt}),jsxs("div",{style:{display:"flex",gap:"8px"},children:[jsx("input",{type:"text",placeholder:"Name (optional)",value:Uo,onChange:r=>ro(r.target.value),disabled:ht,style:{flex:1,fontSize:"12px",padding:"6px 9px",borderRadius:"6px",border:`1px solid ${Te}`,backgroundColor:b?"#0f172a":"#ffffff",color:it,outline:"none"}}),jsx("input",{type:"email",placeholder:"Email address *",required:true,value:Co,onChange:r=>_t(r.target.value),disabled:ht,style:{flex:1.2,fontSize:"12px",padding:"6px 9px",borderRadius:"6px",border:`1px solid ${Te}`,backgroundColor:b?"#0f172a":"#ffffff",color:it,outline:"none"}})]}),jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:"8px"},children:[jsx("button",{type:"button",onClick:()=>{ct(false),Nt(null);},disabled:ht,style:{background:"transparent",border:"none",fontSize:"11px",color:ne,cursor:"pointer",padding:"4px 8px"},children:"Cancel"}),jsx("button",{type:"submit",disabled:ht,style:{backgroundColor:T,color:"#ffffff",border:"none",borderRadius:"6px",padding:"5px 12px",fontSize:"11px",fontWeight:600,cursor:ht?"wait":"pointer",opacity:ht?.7:1,display:"inline-flex",alignItems:"center",gap:"5px"},children:ht?"Connecting...":"Join Queue"})]})]}),w.isWaitingForHuman&&jsxs("div",{style:{padding:"9px 14px",backgroundColor:b?"rgba(245, 158, 11, 0.15)":"#fef3c7",borderBottom:"1px solid rgba(245, 158, 11, 0.3)",display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:"12px",color:b?"#fbbf24":"#b45309"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"#f59e0b",display:"inline-block"}}),jsx("span",{children:"Connecting you with support team..."})]}),jsx("button",{onClick:()=>w.cancelHumanHandoff?.(),type:"button",style:{background:"transparent",border:"none",fontSize:"11px",fontWeight:600,color:"inherit",cursor:"pointer",textDecoration:"underline"},children:"Cancel"})]}),w.isHumanHandoffActive&&jsxs("div",{style:{padding:"9px 14px",backgroundColor:b?"rgba(14, 165, 233, 0.15)":"#e0f2fe",borderBottom:"1px solid rgba(14, 165, 233, 0.3)",display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:"12px",color:b?"#38bdf8":"#0284c7"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{width:"8px",height:"8px",borderRadius:"50%",backgroundColor:"#0284c7",display:"inline-block"}}),jsxs("span",{children:[jsx("strong",{children:"Live Agent:"})," ",w.assignedOperator?.name||"Support Specialist"]})]}),jsx("button",{onClick:()=>w.cancelHumanHandoff?.(),type:"button",style:{background:"transparent",border:"none",fontSize:"11px",fontWeight:600,color:"inherit",cursor:"pointer",textDecoration:"underline"},children:"Back to Bot"})]}),jsxs("div",{ref:lt,onScroll:pi,className:"botzki-chat-scroll",style:{flex:1,overflowY:"auto",padding:"16px",display:"flex",flexDirection:"column",gap:"14px",scrollbarWidth:"thin",scrollbarColor:b?"rgba(255, 255, 255, 0.2) transparent":"rgba(0, 0, 0, 0.2) transparent",...x},children:[me.length===0?Ve?Ve():jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"14px",animation:"botzki-greeting-pop 0.45s cubic-bezier(0.16, 1, 0.3, 1) both"},children:[he&&jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"10px"},children:[a&&jsx("div",{style:{width:"32px",height:"32px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",flexShrink:0,marginTop:"2px",animation:"botzki-avatar-entrance 0.5s cubic-bezier(0.16, 1, 0.3, 1) both"},children:i?typeof i=="string"?jsx("img",{src:i,alt:"Bot",style:{width:"32px",height:"32px",borderRadius:"50%",objectFit:"cover"}}):i:jsx(zt,{size:28,shape:se.shape??"pebble",colors:se.colors??["#66a6ff","#0059d4"],faceColor:se.faceColor??"#ffffff",eyeColor:se.eyeColor,mouthColor:se.mouthColor,motion:se.motion??"jump",emotion:se.emotion??"laugh",followCursor:se.followCursor})}),jsxs("div",{style:{maxWidth:"84%",padding:"12px 16px",borderRadius:"16px",borderTopLeftRadius:a?"4px":"16px",backgroundColor:Qo,color:An,fontSize:"14px",lineHeight:1.5,boxShadow:b?"0 4px 14px rgba(0, 0, 0, 0.25)":"0 4px 14px rgba(0, 0, 0, 0.05)",border:`1px solid ${Te}`},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"4px"},children:[jsx("span",{style:{display:"inline-block",transformOrigin:"70% 70%",animation:"botzki-wave 1.6s ease-in-out infinite",fontSize:"16px"},children:"\u{1F44B}"}),jsx("span",{style:{fontWeight:600,fontSize:"11px",color:T,textTransform:"uppercase",letterSpacing:"0.5px"},children:"Welcome"})]}),jsx(Wo,{content:he,isUser:false,primaryColor:T,isDark:b})]})]}),Rn.length>0&&jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px",marginTop:"4px",marginLeft:a?"42px":0},children:[jsx("span",{style:{fontSize:"11px",color:ne,fontWeight:600,letterSpacing:"0.5px"},children:"SUGGESTED QUESTIONS"}),jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"8px"},children:Rn.map((r,k)=>jsx("button",{className:"botzki-starter-btn",onClick:()=>Pe(r),style:{backgroundColor:b?"#1e293b":"#f1f5f9",color:it,border:`1px solid ${Te}`,padding:"8px 14px",borderRadius:"20px",fontSize:"12px",fontWeight:500,cursor:"pointer",textAlign:"left",animation:`botzki-starter-in 0.4s cubic-bezier(0.16, 1, 0.3, 1) ${.12+k*.08}s both`},children:r},k))})]})]}):null,me.map((r,k)=>{let I=r.role==="user",ge=Wt!==void 0&&Wt>=0&&k===Wt?jsxs("div",{ref:Go,style:{display:"flex",alignItems:"center",gap:"12px",margin:"18px 0 14px",width:"100%",padding:"0 4px"},children:[jsx("div",{style:{flex:1,height:"1px",background:b?"rgba(239, 68, 68, 0.45)":"rgba(239, 68, 68, 0.35)"}}),jsxs("span",{style:{fontSize:"11px",fontWeight:700,textTransform:"uppercase",letterSpacing:"0.5px",color:"#ef4444",background:b?"rgba(239, 68, 68, 0.15)":"#fee2e2",padding:"3px 10px",borderRadius:"9999px",border:`1px solid ${b?"rgba(239, 68, 68, 0.4)":"rgba(239, 68, 68, 0.3)"}`,display:"inline-flex",alignItems:"center",gap:"6px",lineHeight:1.2,boxShadow:"0 1px 3px rgba(0, 0, 0, 0.08)"},children:[jsx("span",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#ef4444"}}),"New Messages"]}),jsx("div",{style:{flex:1,height:"1px",background:b?"rgba(239, 68, 68, 0.45)":"rgba(239, 68, 68, 0.35)"}})]},"botzki-unread-messages-separator"):null;return r.role==="system"?jsxs(gn.Fragment,{children:[ge,jsx("div",{style:{display:"flex",justifyContent:"center",margin:"8px 0",width:"100%"},children:jsx("div",{style:{fontSize:"11px",color:b?"#94a3b8":"#64748b",backgroundColor:b?"rgba(255, 255, 255, 0.05)":"rgba(0, 0, 0, 0.04)",padding:"4px 12px",borderRadius:"9999px",border:`1px solid ${b?"rgba(255, 255, 255, 0.08)":"rgba(0, 0, 0, 0.06)"}`,maxWidth:"85%",textAlign:"center",lineHeight:1.4},children:r.content})})]},r.id):Ke?jsxs(gn.Fragment,{children:[ge,Ke({message:r,index:k,isUser:I,isDark:b,primaryColor:T,onCopy:()=>zn(r.id,r.content),onSpeak:()=>Mn(r.id,r.content),onFeedback:V=>Ko(r.id,V)})]},r.id):jsxs(gn.Fragment,{children:[ge,jsxs("div",{style:{display:"flex",flexDirection:I?"row-reverse":"row",alignItems:"flex-start",gap:"8px",width:"100%"},children:[a&&jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",flexShrink:0,marginTop:"2px",backgroundColor:I?b?"#334155":"#e2e8f0":"transparent"},children:I?o?typeof o=="string"?jsx("img",{src:o,alt:"User",style:{width:"28px",height:"28px",borderRadius:"50%",objectFit:"cover"}}):o:jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:b?"#cbd5e1":"#475569",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),jsx("circle",{cx:"12",cy:"7",r:"4"})]}):i?typeof i=="string"?jsx("img",{src:i,alt:"Bot",style:{width:"28px",height:"28px",borderRadius:"50%",objectFit:"cover"}}):i:jsx(zt,{size:24,shape:se.shape??"pebble",colors:se.colors??["#66a6ff","#0059d4"],faceColor:se.faceColor??"#ffffff",eyeColor:se.eyeColor,mouthColor:se.mouthColor,followCursor:se.followCursor})}),jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:I?"flex-end":"flex-start",maxWidth:"80%"},children:[jsxs("div",{style:{padding:"10px 14px",borderRadius:"14px",backgroundColor:I?xi:Qo,color:I?wi:An,fontSize:"14px",lineHeight:1.5,wordBreak:"break-word"},children:[r.senderType==="operator"&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginBottom:"6px"},children:[jsx("span",{style:{fontSize:"11px",fontWeight:600,color:b?"#38bdf8":"#0284c7"},children:r.senderName||w.assignedOperator?.name||"Support Specialist"}),jsx("span",{style:{fontSize:"9px",fontWeight:700,letterSpacing:"0.5px",textTransform:"uppercase",padding:"1px 5px",borderRadius:"4px",backgroundColor:b?"rgba(14, 165, 233, 0.2)":"#e0f2fe",color:b?"#38bdf8":"#0284c7"},children:"Operator"})]}),(r.imageUrl||r.imageBase64)&&jsx("img",{src:r.imageUrl||r.imageBase64,alt:"Attachment",style:{maxWidth:"100%",maxHeight:"180px",borderRadius:"8px",marginBottom:"8px",display:"block",cursor:"pointer"},onClick:()=>{typeof window<"u"&&window.open(r.imageUrl||r.imageBase64,"_blank");}}),r.audioUrl&&jsx("div",{style:{marginBottom:r.content||r.isTranscribing?"6px":0},children:jsx(pn,{audioUrl:r.audioUrl,duration:r.audioDuration,isUser:I,primaryColor:T,isDark:b})}),r.fileUrl&&jsxs("div",{style:{margin:"8px 0",padding:"10px 12px",borderRadius:"12px",backgroundColor:b?"rgba(255, 255, 255, 0.08)":"#f8fafc",border:`1px solid ${b?"rgba(255, 255, 255, 0.15)":"#e2e8f0"}`,display:"flex",flexDirection:"column",gap:"8px",minWidth:"190px",maxWidth:"260px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[jsx("div",{style:{width:"36px",height:"36px",borderRadius:"8px",backgroundColor:b?"rgba(255, 255, 255, 0.12)":"#e0f2fe",color:b?"#ffffff":T,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:oi(r.fileName)}),jsxs("div",{style:{minWidth:0,flex:1},children:[jsx("div",{style:{fontSize:"12px",fontWeight:600,color:b?"#f1f5f9":"#0f172a",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:r.fileName||"File",children:r.fileName||"Attachment"}),r.fileSize&&jsx("div",{style:{fontSize:"10.5px",color:b?"#94a3b8":"#64748b",marginTop:"1px"},children:ti(r.fileSize)})]})]}),jsxs("a",{href:`${r.fileUrl}${r.fileUrl.includes("?")?"&":"?"}download=true&name=${encodeURIComponent(r.fileName||"download")}`,target:"_blank",rel:"noreferrer",download:r.fileName||true,style:{display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",padding:"6px 12px",borderRadius:"8px",backgroundColor:b?"#38bdf8":"#0f172a",color:b?"#0f172a":"#ffffff",fontSize:"11px",fontWeight:600,textDecoration:"none",cursor:"pointer",transition:"opacity 0.15s ease"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsx("polyline",{points:"7 10 12 15 17 10"}),jsx("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),jsx("span",{children:"Download file"})]})]}),r.isTranscribing&&jsxs("div",{style:{fontSize:"11px",opacity:.85,display:"flex",alignItems:"center",gap:"6px",paddingTop:"2px"},children:[jsx("span",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:I?"#ffffff":T,animation:"botzki-pulse 1s infinite"}}),jsx("span",{children:"Transcribing audio..."})]}),I?r.content?jsxs("div",{style:{whiteSpace:"pre-wrap"},children:[r.audioUrl&&jsx("span",{style:{display:"block",fontSize:"11px",opacity:.75,marginBottom:"2px",fontStyle:"italic"},children:"Transcription:"}),r.content]}):null:r.content?jsx(Wo,{content:r.content,isUser:false,primaryColor:T,isDark:b}):null,C&&r.citations&&r.citations.length>0&&jsxs("div",{style:{marginTop:"8px",paddingTop:"6px",borderTop:`1px solid ${I?"rgba(255,255,255,0.2)":Te}`,fontSize:"11px",display:"flex",flexWrap:"wrap",gap:"4px"},children:[jsx("span",{style:{opacity:.8},children:"Sources:"}),r.citations.map((V,De)=>jsxs("span",{style:{backgroundColor:I?"rgba(255,255,255,0.2)":"rgba(0,0,0,0.06)",padding:"2px 6px",borderRadius:"4px",fontWeight:500},children:[V.source," ",V.page_number?`p.${V.page_number}`:""]},De))]}),!I&&r.escalation&&jsxs("div",{style:{marginTop:"10px",padding:"10px 12px",borderRadius:"10px",backgroundColor:b?"rgba(14, 165, 233, 0.12)":"rgba(14, 165, 233, 0.08)",border:"1px solid rgba(14, 165, 233, 0.25)",display:"flex",flexDirection:"column",gap:"6px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontWeight:600,fontSize:"12px",color:b?"#38bdf8":"#0284c7"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsx("path",{d:"M3 18v-6a9 9 0 0 1 18 0v6"}),jsx("path",{d:"M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"})]}),jsx("span",{children:r.escalation.title||"Live Support Specialist"})]}),r.escalation.description&&jsx("p",{style:{margin:0,fontSize:"11px",opacity:.85,lineHeight:1.4},children:r.escalation.description}),jsxs("button",{type:"button",onClick:async()=>{if(Ge?.liveChatRequireEmail){ct(true);return}try{await w.requestHumanHandoff?.(r.escalation?.title||"Visitor accepted AI escalation offer");}catch(V){V?.code==="EMAIL_REQUIRED"&&ct(true);}},style:{marginTop:"4px",padding:"6px 12px",backgroundColor:T,color:"#ffffff",border:"none",borderRadius:"6px",fontSize:"12px",fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:"6px",transition:"opacity 0.15s ease"},onMouseEnter:V=>V.currentTarget.style.opacity="0.9",onMouseLeave:V=>V.currentTarget.style.opacity="1",children:[jsxs("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsx("path",{d:"M3 18v-6a9 9 0 0 1 18 0v6"}),jsx("path",{d:"M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"})]}),jsx("span",{children:r.escalation.buttonText||"Connect with Support Agent"})]})]}),!I&&S!==false&&r.proposedAction&&jsxs("div",{style:{marginTop:"10px",padding:"12px 14px",borderRadius:"12px",backgroundColor:b?"rgba(99, 102, 241, 0.12)":"rgba(99, 102, 241, 0.07)",border:b?"1px solid rgba(99, 102, 241, 0.35)":"1px solid rgba(99, 102, 241, 0.25)",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.04)",display:"flex",flexDirection:"column",gap:"8px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:b?"1px solid rgba(99, 102, 241, 0.2)":"1px solid rgba(99, 102, 241, 0.15)",paddingBottom:"6px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",fontWeight:700,fontSize:"12px",color:b?"#818cf8":"#4f46e5"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),jsx("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})]}),jsx("span",{children:"Autonomous Action Guardrail"})]}),jsx("span",{style:{fontSize:"10px",fontFamily:"monospace",textTransform:"uppercase",padding:"2px 6px",borderRadius:"4px",backgroundColor:b?"rgba(99, 102, 241, 0.2)":"rgba(99, 102, 241, 0.12)",color:b?"#a5b4fc":"#4338ca",fontWeight:600},children:r.proposedAction.status==="completed"?"\u2713 Executed":r.proposedAction.status==="executing"?"Executing...":r.proposedAction.status==="cancelled"?"Cancelled":r.proposedAction.status==="failed"?"Failed":"2-Step Confirmation"})]}),jsxs("div",{children:[jsx("div",{style:{fontWeight:600,fontSize:"13px",color:b?"#f8fafc":"#0f172a"},children:r.proposedAction.displayName||r.proposedAction.actionName}),r.proposedAction.description&&jsx("div",{style:{fontSize:"11px",color:b?"#94a3b8":"#64748b",marginTop:"2px"},children:r.proposedAction.description})]}),jsx("div",{style:{fontSize:"12px",lineHeight:1.45,padding:"8px 10px",borderRadius:"8px",backgroundColor:b?"rgba(0, 0, 0, 0.25)":"rgba(255, 255, 255, 0.7)",border:b?"1px solid rgba(255, 255, 255, 0.08)":"1px solid rgba(0, 0, 0, 0.06)",color:b?"#e2e8f0":"#1e293b"},children:r.proposedAction.confirmationPrompt||"Do you confirm executing this autonomous action?"}),r.proposedAction.parameters&&Object.keys(r.proposedAction.parameters).length>0&&jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px"},children:Object.entries(r.proposedAction.parameters).map(([V,De])=>jsxs("span",{style:{fontSize:"10px",fontFamily:"monospace",padding:"2px 6px",borderRadius:"4px",backgroundColor:b?"rgba(255, 255, 255, 0.06)":"rgba(0, 0, 0, 0.05)",color:b?"#cbd5e1":"#475569"},children:[jsxs("strong",{children:[V,":"]})," ",String(De)]},V))}),r.proposedAction.status==="completed"?jsxs("div",{style:{padding:"8px 10px",borderRadius:"8px",backgroundColor:b?"rgba(16, 185, 129, 0.15)":"rgba(16, 185, 129, 0.1)",border:"1px solid rgba(16, 185, 129, 0.3)",color:b?"#34d399":"#059669",fontSize:"12px",fontWeight:600,display:"flex",alignItems:"center",gap:"6px"},children:[jsx("svg",{viewBox:"0 0 24 24",width:"14",height:"14",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:jsx("polyline",{points:"20 6 9 17 4 12"})}),jsx("span",{children:r.proposedAction.successMessage||"Action executed successfully with zero operator intervention."})]}):r.proposedAction.status==="executing"?jsx("div",{style:{padding:"8px 10px",borderRadius:"8px",backgroundColor:b?"rgba(99, 102, 241, 0.15)":"rgba(99, 102, 241, 0.1)",color:b?"#a5b4fc":"#4f46e5",fontSize:"12px",fontWeight:500,display:"flex",alignItems:"center",gap:"8px"},children:jsx("span",{children:"\u23F3 Executing action safely via signed token..."})}):r.proposedAction.status==="cancelled"?jsx("div",{style:{padding:"6px 10px",borderRadius:"6px",backgroundColor:b?"rgba(255, 255, 255, 0.05)":"rgba(0, 0, 0, 0.04)",color:b?"#94a3b8":"#64748b",fontSize:"11px",fontStyle:"italic"},children:"Action cancelled by visitor. No changes were made."}):r.proposedAction.status==="failed"?jsxs("div",{style:{padding:"8px 10px",borderRadius:"8px",backgroundColor:b?"rgba(239, 68, 68, 0.15)":"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:b?"#f87171":"#dc2626",fontSize:"12px"},children:["Execution failed: ",r.proposedAction.error||"Unknown server error."]}):jsxs("div",{style:{display:"flex",gap:"8px",marginTop:"4px"},children:[jsxs("button",{type:"button",onClick:async()=>{(await w.executeProposedAction?.(r.id,r.proposedAction.token,r.proposedAction.parameters))?.success&&Ct.triggerCelebration();},style:{flex:1,padding:"7px 12px",backgroundColor:"#4f46e5",color:"#ffffff",border:"none",borderRadius:"8px",fontSize:"12px",fontWeight:600,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",gap:"6px",boxShadow:"0 2px 4px rgba(79, 70, 229, 0.25)",transition:"opacity 0.15s ease"},onMouseEnter:V=>V.currentTarget.style.opacity="0.9",onMouseLeave:V=>V.currentTarget.style.opacity="1",children:[jsx("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:jsx("polyline",{points:"20 6 9 17 4 12"})}),jsx("span",{children:"Confirm & Execute"})]}),jsx("button",{type:"button",onClick:()=>{w.cancelProposedAction?.(r.id,"Cancelled by user");},style:{padding:"7px 12px",backgroundColor:b?"rgba(255, 255, 255, 0.08)":"rgba(0, 0, 0, 0.05)",color:b?"#cbd5e1":"#475569",border:`1px solid ${b?"rgba(255, 255, 255, 0.12)":"rgba(0, 0, 0, 0.1)"}`,borderRadius:"8px",fontSize:"12px",fontWeight:500,cursor:"pointer",transition:"background-color 0.15s ease"},children:"Cancel"})]})]}),!I&&r.piiRedacted&&jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:"4px",marginTop:"6px",fontSize:"10px",fontWeight:500,color:b?"#34d399":"#059669",backgroundColor:b?"rgba(16, 185, 129, 0.1)":"rgba(16, 185, 129, 0.06)",padding:"2px 6px",borderRadius:"4px",border:"1px solid rgba(16, 185, 129, 0.2)"},title:"Sensitive personal identifiers were redacted before transmission",children:[jsx("span",{children:"\u{1F6E1}\uFE0F"}),jsx("span",{children:"PII Protected"})]}),r.error&&jsxs("div",{style:{marginTop:"6px",fontSize:"12px",color:"#ef4444"},children:["Error: ",r.error]})]}),!I&&r.content&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",marginTop:"4px",paddingLeft:"4px"},children:[L&&jsxs("button",{type:"button",onClick:()=>zn(r.id,r.content),title:"Copy message",style:{background:"transparent",border:"none",cursor:"pointer",color:ne,fontSize:"11px",display:"inline-flex",alignItems:"center",gap:"3px",padding:"2px 6px",borderRadius:"4px"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]}),jsx("span",{children:ci===r.id?"Copied":"Copy"})]}),g&&typeof window<"u"&&window.speechSynthesis&&jsxs("button",{type:"button",onClick:()=>Mn(r.id,r.content),title:uo===r.id?"Stop speaking":"Read aloud",style:{background:uo===r.id?"rgba(14, 165, 233, 0.15)":"transparent",border:"none",cursor:"pointer",color:uo===r.id?T:ne,fontSize:"11px",display:"inline-flex",alignItems:"center",gap:"3px",padding:"2px 6px",borderRadius:"4px"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]}),jsx("span",{children:uo===r.id?"Stop":"Read"})]}),f&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"2px"},children:[jsx("button",{type:"button",onClick:()=>Ko(r.id,"up"),title:"Helpful",style:{background:"transparent",border:"none",cursor:"pointer",color:Do[r.id]==="up"?"#10b981":ne,padding:"2px 4px",borderRadius:"4px",display:"flex",alignItems:"center"},children:jsx("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("path",{d:"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"})})}),jsx("button",{type:"button",onClick:()=>Ko(r.id,"down"),title:"Not helpful",style:{background:"transparent",border:"none",cursor:"pointer",color:Do[r.id]==="down"?"#ef4444":ne,padding:"2px 4px",borderRadius:"4px",display:"flex",alignItems:"center"},children:jsx("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"none",stroke:"currentColor",strokeWidth:"2",children:jsx("path",{d:"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h3a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-3"})})}),Do[r.id]&&jsx("span",{style:{fontSize:"10px",color:ne,marginLeft:"2px"},children:"Thanks!"})]})]}),!I&&jsxs("div",{style:{fontSize:"10px",color:ne,marginTop:"2px",paddingLeft:"6px",display:"flex",alignItems:"center",gap:"4px",opacity:.85},children:[jsx("svg",{viewBox:"0 0 24 24",width:"11",height:"11",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("polyline",{points:"20 6 9 17 4 12"})}),jsx("span",{children:r.deliveryStatus==="Read"?"Read in chat":r.deliveryChannel==="Email"?"Delivered to email":"Delivered"})]})]})]})]},r.id)}),w.pendingCsatTicketId&&jsxs("div",{style:{margin:"12px 0 16px 0",padding:"16px",borderRadius:"14px",backgroundColor:b?"rgba(14, 165, 233, 0.08)":"#f0f9ff",border:`1px solid ${b?"rgba(14, 165, 233, 0.25)":"#bae6fd"}`,textAlign:"center"},children:[jsx("div",{style:{fontSize:"13px",fontWeight:600,color:b?"#f0f9ff":"#0c4a6e",marginBottom:"4px"},children:"How was your support experience today?"}),jsx("p",{style:{fontSize:"11px",color:ne,margin:"0 0 12px 0"},children:"Your feedback helps us continuously improve our live support service."}),Bo?jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"6px",color:"#10b981",fontSize:"12px",fontWeight:600},children:[jsx("span",{children:"\u2713 Thank you for your feedback!"}),jsx("span",{style:{fontSize:"11px",fontWeight:400,color:ne},children:"Our support team appreciates your review."})]}):jsxs("div",{children:[jsx("div",{style:{display:"flex",justifyContent:"center",gap:"8px",marginBottom:"10px"},children:[1,2,3,4,5].map(r=>jsx("button",{type:"button",onClick:()=>Mo(r),style:{background:"transparent",border:"none",fontSize:"22px",cursor:"pointer",transform:vt>=r?"scale(1.15)":"scale(1)",transition:"transform 0.15s ease",color:vt>=r?"#f59e0b":b?"#475569":"#cbd5e1"},title:`${r} star${r>1?"s":""}`,children:"\u2605"},r))}),vt>0&&jsxs("div",{style:{marginTop:"8px",display:"flex",flexDirection:"column",gap:"8px"},children:[jsx("input",{type:"text",value:kt,onChange:r=>lo(r.target.value),placeholder:"Add an optional comment (e.g. fast, helpful)...",style:{width:"100%",padding:"8px 12px",fontSize:"12px",borderRadius:"8px",border:`1px solid ${b?"#334155":"#e2e8f0"}`,background:b?"#1e293b":"#ffffff",color:b?"#f8fafc":"#0f172a",boxSizing:"border-box"}}),jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:"6px"},children:jsx("button",{type:"button",onClick:async()=>{zo(true),await w.submitHandoffFeedback?.(vt,kt),zo(false),Ro(true),vt>=4?Ct.triggerCelebration():Ct.triggerSympathy();},disabled:Yt,style:{background:T,color:"#ffffff",border:"none",borderRadius:"6px",padding:"6px 14px",fontSize:"11px",fontWeight:600,cursor:"pointer"},children:Yt?"Submitting...":"Submit Rating"})})]})]}),jsx("div",{style:{marginTop:"12px",borderTop:`1px solid ${b?"rgba(14, 165, 233, 0.2)":"#e0f2fe"}`,paddingTop:"10px",display:"flex",justifyContent:"center"},children:jsx("button",{type:"button",onClick:()=>{w.clearMessages?.(),Ro(false),Mo(0),lo("");},style:{background:b?"rgba(255,255,255,0.06)":"#ffffff",color:b?"#e2e8f0":"#334155",border:`1px solid ${b?"#334155":"#cbd5e1"}`,borderRadius:"8px",padding:"6px 14px",fontSize:"11px",fontWeight:600,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:"6px"},children:jsx("span",{children:"\u{1F4AC} Start New Conversation"})})})]}),ae&&!Ye&&jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:"8px"},children:[a&&jsx("div",{style:{width:"28px",height:"28px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",overflow:"hidden",flexShrink:0},children:jsx(zt,{size:24,shape:se.shape??"pebble",colors:se.colors??["#66a6ff","#0059d4"],faceColor:se.faceColor??"#ffffff",eyeColor:se.eyeColor,mouthColor:se.mouthColor,motion:"bounce"})}),jsx("div",{style:{padding:"8px 14px",borderRadius:"14px",backgroundColor:Qo,color:ne,fontSize:"13px"},children:"Thinking..."})]}),te&&jsx("div",{style:{padding:"8px 12px",borderRadius:"8px",backgroundColor:"rgba(239, 68, 68, 0.1)",border:"1px solid rgba(239, 68, 68, 0.3)",color:"#ef4444",fontSize:"12px"},children:te.message})]}),Vo>0&&!_o&&jsxs("button",{type:"button",onClick:fi,style:{position:"absolute",bottom:"74px",left:"50%",transform:"translateX(-50%)",backgroundColor:T,color:"#ffffff",border:"none",borderRadius:"20px",padding:"6px 14px",fontSize:"12px",fontWeight:600,boxShadow:"0 4px 14px rgba(0, 0, 0, 0.35)",cursor:"pointer",display:"flex",alignItems:"center",gap:"6px",zIndex:15,animation:"botzki-fade-in 0.2s ease-out"},children:[jsxs("svg",{viewBox:"0 0 24 24",width:"13",height:"13",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),jsx("polyline",{points:"19 12 12 19 5 12"})]}),jsxs("span",{children:[Vo," new ",Vo===1?"message":"messages"]})]}),Be?Be({input:fe,setInput:xe,sendMessage:(r,k)=>Pe(r,k),isLoading:ae,isStreaming:Ye,primaryColor:T,isDark:b,attachImage:()=>pt.current?.click(),pendingImage:$e,removeImage:()=>ut(null),isListening:co,toggleListening:yi,isRecordingVoiceNote:Ao,startVoiceRecording:Ht,stopVoiceRecording:St,cancelVoiceRecording:nt,voiceRecordingDuration:Kt,sendVoiceMessage:(r,k)=>w.sendVoiceMessage?w.sendVoiceMessage(r,k):w.sendMessage("",{audioUrl:URL.createObjectURL(r),audioDuration:k?.audioDuration})}):jsxs("div",{style:{padding:"8px 14px 4px 14px",backgroundColor:To,position:"relative"},children:[Io&&jsx("div",{ref:jo,style:{position:"absolute",bottom:"calc(100% - 2px)",left:"14px",backgroundColor:b?"#1e293b":"#ffffff",border:`1px solid ${Te}`,borderRadius:"14px",padding:"8px 10px",boxShadow:b?"0 8px 24px rgba(0, 0, 0, 0.45)":"0 8px 24px rgba(0, 0, 0, 0.12)",display:"flex",flexWrap:"wrap",gap:"6px",maxWidth:"260px",zIndex:30,animation:"botzki-fade-in 0.15s ease-out"},children:ar.map(r=>jsx("button",{type:"button",onClick:()=>di(r),style:{background:"transparent",border:"none",fontSize:"18px",cursor:"pointer",padding:"4px",borderRadius:"6px",lineHeight:1,transition:"transform 0.1s ease"},onMouseEnter:k=>k.currentTarget.style.transform="scale(1.2)",onMouseLeave:k=>k.currentTarget.style.transform="scale(1)",children:r},r))}),jsx("form",{onSubmit:Bn,style:{display:"flex",flexDirection:"column",borderRadius:"16px",border:`1px solid ${vn?T:Te}`,boxShadow:vn?`0 0 0 2px ${T}20, 0 2px 8px rgba(0, 0, 0, 0.05)`:b?"0 2px 6px rgba(0, 0, 0, 0.2)":"0 2px 6px rgba(0, 0, 0, 0.04)",backgroundColor:b?"#1e293b":"#ffffff",padding:"10px 12px 8px 12px",transition:"border-color 0.15s ease, box-shadow 0.15s ease",...ie},children:Ao?jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"6px 4px",minHeight:"44px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("span",{style:{width:"10px",height:"10px",borderRadius:"50%",backgroundColor:"#ef4444",boxShadow:"0 0 8px rgba(239, 68, 68, 0.7)",animation:"botzki-pulse 1.2s infinite ease-in-out"}}),jsx("span",{style:{fontSize:"13px",fontWeight:600,color:b?"#f1f5f9":"#1e293b",fontVariantNumeric:"tabular-nums"},children:Xt(Kt)}),jsx("div",{style:{display:"flex",alignItems:"center",gap:"2.5px",marginLeft:"6px",height:"18px"},children:[6,12,18,10,15,8,16,14,9,17,11,7].map((r,k)=>jsx("div",{style:{width:"2.5px",height:`${r}px`,borderRadius:"2px",backgroundColor:T,animation:"botzki-equalizer 0.8s ease-in-out infinite alternate",animationDelay:`${(k*.08).toFixed(2)}s`}},k))})]}),jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[jsx("button",{type:"button",onClick:nt,title:"Discard recording","aria-label":"Discard recording",style:{background:"transparent",border:"none",color:b?"#94a3b8":"#64748b",cursor:"pointer",padding:"6px",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s ease, background 0.15s ease"},children:jsxs("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}),jsx("button",{type:"button",onClick:St,title:"Send voice message","aria-label":"Send voice message",style:{width:"32px",height:"32px",borderRadius:"50%",backgroundColor:T,color:"#ffffff",border:"none",cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:`0 2px 8px ${T}55`,transition:"transform 0.12s ease, opacity 0.15s ease"},children:jsx("svg",{viewBox:"0 0 24 24",width:"16",height:"16",fill:"currentColor",children:jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]})]}):jsxs(Fragment,{children:[$e&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"4px 6px 8px 6px",marginBottom:"4px",borderBottom:`1px solid ${Te}`,fontSize:"12px"},children:[jsx("img",{src:$e.dataUrl,alt:"Thumbnail",style:{width:"28px",height:"28px",objectFit:"cover",borderRadius:"6px",border:`1px solid ${Te}`}}),jsx("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:it,fontSize:"11px",fontWeight:500},children:$e.name}),jsx("button",{type:"button",onClick:()=>ut(null),title:"Remove attachment",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"2px 4px",borderRadius:"4px"},children:"\u2715"})]}),we&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",padding:"4px 6px 8px 6px",marginBottom:"4px",borderBottom:`1px solid ${Te}`,fontSize:"12px"},children:[jsx("div",{style:{width:"28px",height:"28px",borderRadius:"6px",backgroundColor:b?"rgba(255, 255, 255, 0.1)":"#f1f5f9",display:"flex",alignItems:"center",justifyContent:"center",color:b?"#ffffff":T,flexShrink:0},children:oi(we.name)}),jsxs("span",{style:{flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:it,fontSize:"11px",fontWeight:500},children:[we.name,jsxs("span",{style:{opacity:.7,marginLeft:"4px"},children:["(",ti(we.size),")"]})]}),jsx("button",{type:"button",onClick:()=>qt(null),title:"Remove attachment",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",fontSize:"12px",padding:"2px 4px",borderRadius:"4px"},children:"\u2715"})]}),Oo&&jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"5px 8px",marginBottom:"6px",borderRadius:"6px",backgroundColor:b?"rgba(16, 185, 129, 0.12)":"rgba(16, 185, 129, 0.08)",border:"1px solid rgba(16, 185, 129, 0.25)",color:b?"#34d399":"#059669",fontSize:"11px",fontWeight:500},children:[jsx("span",{children:"\u{1F6E1}\uFE0F"}),jsx("span",{children:"PII Firewall Active: Sensitive numbers & credentials are encrypted & redacted in transit."})]}),jsx("textarea",{ref:Zt,rows:1,className:"botzki-composer-textarea",value:fe,onChange:Ne,onKeyDown:ui,onFocus:()=>kn(true),onBlur:()=>kn(false),placeholder:co?"Listening... Speak now":G||"Compose your message...",disabled:ae,style:{width:"100%",background:"transparent",border:"none",outline:"none",padding:"2px 4px",color:it,fontSize:"14px",lineHeight:"20px",resize:"none",boxSizing:"border-box",minHeight:"36px",maxHeight:"120px",overflowY:"auto",scrollbarWidth:"none",msOverflowStyle:"none",fontFamily:"inherit",...W}}),jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginTop:"4px",paddingTop:"4px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[jsx("button",{type:"button",onClick:()=>Fo(r=>!r),title:"Insert emoji","aria-label":"Insert emoji",style:{background:"transparent",border:"none",color:Io?T:ne,cursor:"pointer",padding:"4px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s ease"},children:jsxs("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("path",{d:"M8 14s1.5 2 4 2 4-2 4-2"}),jsx("line",{x1:"9",y1:"9",x2:"9.01",y2:"9"}),jsx("line",{x1:"15",y1:"9",x2:"15.01",y2:"9"})]})}),s&&jsxs(Fragment,{children:[jsx("button",{type:"button",onClick:()=>pt.current?.click(),title:"Attach file, document, or image","aria-label":"Attach file, document, or image",style:{background:"transparent",border:"none",color:$e||we?T:ne,cursor:"pointer",padding:"4px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s ease"},children:jsx("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"})})}),jsx("input",{ref:pt,type:"file",accept:"image/*,.pdf,.zip,.csv,.docx,.xlsx,.txt,.tar,.gz,.json",onChange:bi,style:{display:"none"}})]}),c&&m!==false&&jsx("button",{type:"button",onClick:Ht,title:"Record voice message","aria-label":"Voice input / Record voice message",style:{background:"transparent",border:"none",color:ne,cursor:"pointer",padding:"4px",borderRadius:"6px",display:"flex",alignItems:"center",justifyContent:"center",transition:"color 0.15s ease"},onMouseEnter:r=>{r.currentTarget.style.color=T;},onMouseLeave:r=>{r.currentTarget.style.color=ne;},children:jsxs("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[jsx("line",{x1:"4",y1:"9",x2:"4",y2:"15"}),jsx("line",{x1:"8",y1:"5",x2:"8",y2:"19"}),jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),jsx("line",{x1:"16",y1:"7",x2:"16",y2:"17"}),jsx("line",{x1:"20",y1:"10",x2:"20",y2:"14"})]})})]}),Ye?jsx("button",{type:"button",onClick:()=>w.stop(),"aria-label":"Stop generating",title:"Stop generating",style:{width:"28px",height:"28px",backgroundColor:"#ef4444",color:"#ffffff",border:"none",borderRadius:"50%",padding:0,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"opacity 0.2s ease, transform 0.1s ease",...M},children:jsx("svg",{viewBox:"0 0 24 24",width:"12",height:"12",fill:"currentColor",children:jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}):jsx("button",{type:"submit",disabled:ae||Pt||!fe.trim()&&!$e&&!we,"aria-label":"Send message",title:"Send message",style:{background:"transparent",border:"none",color:!fe.trim()&&!$e&&!we?b?"#475569":"#cbd5e1":T,cursor:ae||Pt||!fe.trim()&&!$e&&!we?"not-allowed":"pointer",padding:"4px",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,transition:"color 0.15s ease, transform 0.1s ease",...M},children:jsx("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"currentColor",children:jsx("path",{d:"M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"})})})]})]})})]}),y&&jsxs("div",{style:{textAlign:"center",padding:"4px 12px 10px 12px",backgroundColor:To,fontSize:"11px",color:ne,display:"flex",alignItems:"center",justifyContent:"center",gap:"4px"},children:[jsx("span",{children:"Powered by "}),jsxs("a",{href:"https://botzki.com",target:"_blank",rel:"noopener noreferrer",style:{color:it,fontWeight:600,textDecoration:"none",display:"inline-flex",alignItems:"center",gap:"3px"},children:[jsx("span",{style:{color:T},children:"\u26A1"})," Botzki"]})]}),w.coBrowse&&jsx(fn,{coBrowse:w.coBrowse})]})}function dr(t){if(!t||t.trim()===""||t.trim()==="*")return true;if(typeof window>"u")return false;let e=window.location.href,i=window.location.pathname,o=t.trim();if(o.includes("*")){let a=o.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*"),s=new RegExp(`^${a}$`,"i");return s.test(e)||s.test(i)}return e.toLowerCase().includes(o.toLowerCase())||i.toLowerCase().includes(o.toLowerCase())}var ur=forwardRef(function(e,i){let o=Dt(),a=e.botId||o?.botId,s=e.publishableKey||o?.publishableKey,c=e.baseUrl||o?.baseUrl||"https://api.botzki.com",[g,m]=useState(false),[u,S]=useState(e.defaultOpen??false),[f,C]=useState(true),[y,L]=useState(e.defaultExpanded??false),[N,Q]=useState(false),[U,X]=useState(false),[H,le]=useState(e.theme||"dark"),[Y,_]=useState(e.primaryColor||"#0ea5e9"),[,q]=useState(e.user||o?.user),[Z,oe]=useState(false);useEffect(()=>{e.theme&&le(e.theme);},[e.theme]),useEffect(()=>{e.primaryColor&&_(e.primaryColor);},[e.primaryColor]),useEffect(()=>{e.user&&q(e.user);},[e.user]),useEffect(()=>{m(true);},[]);let{data:J}=bo(),[he,ze]=useState(null);useEffect(()=>{if(u){X(false);return}try{if(typeof window<"u"&&window.sessionStorage&&sessionStorage.getItem(`botzki_proactive_dismissed_${a||"default"}`)==="true")return}catch{}if(e.proactiveMessage){let h=e.proactiveDelay??3e3,x=setTimeout(()=>{X(true);},h);return ()=>clearTimeout(x)}if(e.enableTriggers===false||!J?.activeTriggers||J.activeTriggers.length===0)return;let l=J.activeTriggers.find(h=>dr(h.urlPattern));if(!l)return;let v=l.triggerType||"TimeOnPage";if(v==="TimeOnPage"){let h=(l.delaySeconds??5)*1e3,x=setTimeout(()=>{ze(l),X(true),e.onTriggerActivated?.(l);},h);return ()=>clearTimeout(x)}if(v==="ScrollPercentage"){let h=l.scrollPercentage??50,x=()=>{if(typeof window>"u")return;let M=document.documentElement.scrollHeight-window.innerHeight;if(M<=0)return;window.scrollY/M*100>=h&&(ze(l),X(true),e.onTriggerActivated?.(l),window.removeEventListener("scroll",x));};return window.addEventListener("scroll",x,{passive:true}),()=>window.removeEventListener("scroll",x)}if(v==="ExitIntent"){let h=x=>{!x.relatedTarget&&x.clientY<=10&&(ze(l),X(true),e.onTriggerActivated?.(l),document.removeEventListener("mouseout",h));};return document.addEventListener("mouseout",h),()=>document.removeEventListener("mouseout",h)}},[e.proactiveMessage,e.proactiveDelay,e.enableTriggers,J?.activeTriggers,u,a]);let R=mo({botId:a,publishableKey:s,baseUrl:c,persistSession:e.persistSession??false,visitorData:e.visitorData,tags:e.tags,enableSoundAlert:e.enableSoundAlert,enableTabTitleNotification:e.enableTabTitleNotification,enableCoBrowse:e.enableCoBrowse,onSendMessage:e.onSendMessage,onResponse:l=>{e.onResponse?.(l),e.onMessage?.({role:"assistant",content:l.reply});},onFinish:e.onFinish,onError:e.onError,onEscalationRequest:e.onEscalationRequest,onOperatorJoined:e.onOperatorJoined,onTicketResolved:e.onTicketResolved,onCsatSubmit:e.onCsatSubmit,onActionProposed:e.onActionProposed,onActionExecuted:e.onActionExecuted,onActionCancelled:e.onActionCancelled,onCoBrowseStart:e.onCoBrowseStart,onCoBrowseEnd:e.onCoBrowseEnd}),T=useRef(new Set),j=useRef(false),[F,G]=useState(0),[ee,ce]=useState(void 0),[He,ke]=useState(null),pe=useRef(""),ye=e.unreadCount!==void 0?e.unreadCount:F;useEffect(()=>{!j.current&&R.messages.length>0&&(j.current=true,R.messages.forEach(l=>{l.isStreaming||T.current.add(l.id);}));},[R.messages]),useEffect(()=>{u&&(R.messages.forEach(l=>{l.role==="assistant"&&!l.isStreaming&&T.current.add(l.id);}),F!==0&&(G(0),e.onUnreadCountChange?.(0)),ke(null));},[u,R.messages,F,e.onUnreadCountChange]),useEffect(()=>{if(u)return;let l=R.messages.filter(h=>h.role==="assistant"&&!T.current.has(h.id)&&(h.content.trim().length>0||!h.isStreaming)),v=l.length;if(v!==F&&(G(v),e.onUnreadCountChange?.(v),v>F&&v>0)){if(e.enableSoundAlert!==false)try{if(typeof window<"u"){let x=window.AudioContext||window.webkitAudioContext;if(x){let M=new x,B=M.createOscillator(),z=M.createGain();B.type="sine",B.frequency.setValueAtTime(587.33,M.currentTime),B.frequency.exponentialRampToValueAtTime(880,M.currentTime+.12),z.gain.setValueAtTime(.08,M.currentTime),z.gain.exponentialRampToValueAtTime(.001,M.currentTime+.35),B.connect(z),z.connect(M.destination),B.start(),B.stop(M.currentTime+.35);}}}catch{}let h=l[l.length-1];if(h&&h.content){let x=h.content.length>90?h.content.slice(0,87)+"...":h.content;ke(x);}}},[R.messages,u,F,e.onUnreadCountChange]),useEffect(()=>{if(typeof document>"u"||e.enableTabTitleNotification===false)return;pe.current||(pe.current=document.title),ye>0&&!u?document.title=`(${ye}) ${pe.current}`:pe.current&&(document.title=pe.current);let l=()=>{u&&pe.current&&(document.title=pe.current);};return window.addEventListener("focus",l),()=>{window.removeEventListener("focus",l),pe.current&&(document.title=pe.current);}},[ye,u,e.enableTabTitleNotification]);let Ee=useCallback(()=>{let l=R.messages.findIndex(v=>v.role==="assistant"&&!T.current.has(v.id)&&(v.content.trim().length>0||!v.isStreaming));if(l>=0)ce(l);else {let v=e.unreadCount!==void 0?e.unreadCount:F;v>0&&R.messages.length>0?ce(Math.max(0,R.messages.length-v)):ce(void 0);}R.messages.forEach(v=>{v.role==="assistant"&&T.current.add(v.id);}),S(true),X(false),ke(null),G(0),typeof document<"u"&&pe.current&&(document.title=pe.current),e.onUnreadCountChange?.(0),e.onOpen?.();},[e.onOpen,e.onUnreadCountChange,e.unreadCount,F,R.messages]),We=useCallback(()=>{S(false),ce(void 0),e.onClose?.();},[e.onClose]),Ue=useCallback(()=>{S(l=>{let v=!l;if(v){let h=R.messages.findIndex(x=>x.role==="assistant"&&!T.current.has(x.id)&&(x.content.trim().length>0||!x.isStreaming));if(h>=0)ce(h);else {let x=e.unreadCount!==void 0?e.unreadCount:F;x>0&&R.messages.length>0?ce(Math.max(0,R.messages.length-x)):ce(void 0);}R.messages.forEach(x=>{x.role==="assistant"&&T.current.add(x.id);}),X(false),ke(null),G(0),typeof document<"u"&&pe.current&&(document.title=pe.current),e.onUnreadCountChange?.(0),e.onOpen?.();}else ce(void 0),e.onClose?.();return v});},[e.onOpen,e.onClose,e.onUnreadCountChange,e.unreadCount,F,R.messages]),wt=useCallback(()=>{L(l=>{let v=!l;return e.onExpandChange?.(v),v});},[e.onExpandChange]),At=useCallback(l=>{l.stopPropagation(),X(false);try{typeof window<"u"&&window.sessionStorage&&sessionStorage.setItem(`botzki_proactive_dismissed_${a||"default"}`,"true");}catch{}},[a]);useEffect(()=>{if(e.enableHotkey===false||typeof window>"u")return;let l=v=>{(v.metaKey||v.ctrlKey)&&v.key.toLowerCase()==="k"?(v.preventDefault(),Ue()):v.key==="Escape"&&u&&We();};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[e.enableHotkey,u,Ue,We]),useImperativeHandle(i,()=>({open:Ee,close:We,toggle:Ue,isOpen:()=>u,show:()=>C(true),hide:()=>{C(false),We();},sendMessage:async(l,v)=>{Ee(),await R.sendMessage(l,v?{imageBase64:v}:void 0);},clearMessages:()=>{R.clearMessages(),T.current.clear(),G(0),ce(void 0),ke(null);},newChat:()=>{R.clearMessages(),T.current.clear(),G(0),ce(void 0),ke(null),R.setSessionId(`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`),e.onNewChat?.();},expand:()=>{L(true),e.onExpandChange?.(true);},collapse:()=>{L(false),e.onExpandChange?.(false);},isExpanded:()=>y,openHistory:()=>{Ee(),Q(true);},closeHistory:()=>{Q(false);},exportChat:(l="markdown")=>{let v="";return l==="json"?v=JSON.stringify(R.messages,null,2):(v=`# Conversation
128
+
129
+ `,R.messages.forEach(h=>{v+=`### ${h.role==="user"?"User":"Assistant"}:
130
+ ${h.content}
131
+
132
+ `;})),v},setTheme:l=>le(l),setPrimaryColor:l=>_(l),setUser:l=>q(l),getUnreadCount:()=>ye,markAsRead:()=>{G(0),ce(void 0),ke(null),R.messages.forEach(l=>{l.role==="assistant"&&T.current.add(l.id);}),typeof document<"u"&&pe.current&&(document.title=pe.current),e.onUnreadCountChange?.(0);},requestHumanHandoff:async(l,v,h)=>{Ee(),await R.requestHumanHandoff?.(l,v,h);},cancelHumanHandoff:async()=>{await R.cancelHumanHandoff?.();},getMessages:()=>R.messages,getSessionId:()=>R.sessionId,setSessionId:l=>R.setSessionId(l),stopStreaming:()=>R.stop(),reloadLastMessage:()=>R.reload()}),[Ee,We,Ue,u,y,R,e.onNewChat,e.onExpandChange,ye,e.onUnreadCountChange]);let Je=yo({messages:R.messages,isLoading:R.isLoading,isStreaming:R.isStreaming,isWaitingForHuman:R.isWaitingForHuman,isHumanHandoffActive:R.isHumanHandoffActive,manualEmotion:e.avatar?.emotion,manualMotion:e.avatar?.motion??void 0,enabled:e.enableEmpathyEngine??true}),Ae=useMemo(()=>({colors:e.avatar?.colors??e.avatarColors??["#66a6ff","#0059d4"],faceColor:e.avatar?.faceColor??e.avatarFaceColor??"#ffffff",eyeColor:e.avatar?.eyeColor??e.avatarEyeColor,mouthColor:e.avatar?.mouthColor??e.avatarMouthColor,shape:e.avatar?.shape??e.avatarShape??"pebble",size:e.avatar?.size??e.avatarSize??50,followCursor:e.avatar?.followCursor??e.avatarFollowCursor??true,motion:e.avatar?.motion??(e.enableEmpathyEngine??true?Je.motion:void 0),emotion:e.avatar?.emotion??(e.enableEmpathyEngine??true?Je.emotion:"neutral"),outlineColor:e.avatar?.outlineColor,outlineWidth:e.avatar?.outlineWidth,background:e.avatar?.background,props:{...e.avatarProps,...e.avatar?.props,motionKey:Je.motionKey}}),[e.avatar,e.avatarColors,e.avatarFaceColor,e.avatarEyeColor,e.avatarMouthColor,e.avatarShape,e.avatarSize,e.avatarFollowCursor,e.avatarProps,e.enableEmpathyEngine,Je.emotion,Je.motion,Je.motionKey]),be=useMemo(()=>({background:e.launcher?.background??e.launcherBackground??"transparent",icon:e.launcher?.icon??e.launcherIcon,style:{...e.launcherStyle,...e.launcher?.style},closeBackground:e.launcher?.closeBackground??e.closeButtonBackground??Y,closeColor:e.launcher?.closeColor??e.closeButtonColor??"#ffffff",size:e.launcher?.size??56}),[e.launcher,e.launcherBackground,e.launcherIcon,e.launcherStyle,e.closeButtonBackground,e.closeButtonColor,Y]);if(!g||typeof document>"u")return null;let Qe=e.position==="bottom-left",Ke=e.offset?.x??24,Be=e.offset?.y??24,Ve=e.zIndex??2147483647,E=!u&&be.background&&be.background!=="transparent",d=u?be.closeBackground||Y:be.background??"transparent",W=u||E?Z?"0 10px 24px rgba(0, 0, 0, 0.35), 0 4px 8px rgba(0, 0, 0, 0.2)":"0 6px 16px rgba(0, 0, 0, 0.24), 0 3px 6px rgba(0, 0, 0, 0.12)":"none",ie=!u&&!E?Z?"drop-shadow(0 8px 18px rgba(0, 0, 0, 0.3))":"drop-shadow(0 3px 8px rgba(0, 0, 0, 0.18))":void 0,O=be.size||56,de=y?e.expandedWidth||"720px":e.width||"380px",P=y?e.expandedHeight||"calc(100vh - 100px)":e.height||"580px",A=jsxs("div",{id:"botzki-react-widget-container",style:{display:f?"block":"none",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'},children:[jsx("style",{children:`
133
+ @keyframes botzki-teaser-in {
134
+ from { opacity: 0; transform: translateY(8px) scale(0.95); }
135
+ to { opacity: 1; transform: translateY(0) scale(1); }
136
+ }
137
+ `}),U&&!u&&(e.proactiveMessage||he)&&jsxs("div",{onClick:Ee,role:"alert",style:{position:"fixed",bottom:Be+O+12,[Qe?"left":"right"]:Ke,maxWidth:"320px",backgroundColor:H==="dark"?"#1e293b":"#ffffff",color:H==="dark"?"#f8fafc":"#0f172a",padding:"12px 14px",borderRadius:"16px",boxShadow:"0 20px 30px -10px rgba(0, 0, 0, 0.25), 0 8px 12px -4px rgba(0, 0, 0, 0.1)",border:`1px solid ${H==="dark"?"#334155":"#e2e8f0"}`,cursor:"pointer",zIndex:Ve,display:"flex",flexDirection:"column",gap:"6px",animation:"botzki-teaser-in 0.25s cubic-bezier(0.16, 1, 0.3, 1)"},children:[jsxs("div",{style:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",gap:"8px"},children:[jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px"},children:[jsx("span",{style:{fontSize:"14px"},children:"\u2728"}),jsx("span",{style:{fontSize:"12.5px",fontWeight:700,color:Y},children:he?.headline||"Need help?"})]}),jsx("button",{type:"button",onClick:At,title:"Dismiss teaser","aria-label":"Dismiss greeting",style:{background:"transparent",border:"none",color:H==="dark"?"#94a3b8":"#64748b",cursor:"pointer",padding:"0 2px",fontSize:"14px",lineHeight:1},children:"\u2715"})]}),jsx("div",{style:{fontSize:"12.5px",lineHeight:1.45,opacity:.9},children:he?.message||e.proactiveMessage}),he?.suggestedPrompts&&he.suggestedPrompts.length>0&&jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px",marginTop:"4px",paddingTop:"6px",borderTop:`1px solid ${H==="dark"?"rgba(255,255,255,0.08)":"rgba(0,0,0,0.06)"}`},children:he.suggestedPrompts.map((l,v)=>jsxs("button",{type:"button",onClick:h=>{h.stopPropagation(),Ee(),R.sendMessage(l);},style:{background:H==="dark"?"#334155":"#f1f5f9",border:`1px solid ${H==="dark"?"#475569":"#cbd5e1"}`,borderRadius:"8px",padding:"4px 8px",fontSize:"11px",fontWeight:500,cursor:"pointer",color:H==="dark"?"#e2e8f0":"#1e293b",transition:"transform 0.1s ease"},children:[l," \u2192"]},v))})]}),!u&&He&&jsxs("div",{onClick:Ee,role:"alert",style:{position:"fixed",bottom:Be+O+12,[Qe?"left":"right"]:Ke,maxWidth:"290px",backgroundColor:H==="dark"?"#1e293b":"#ffffff",color:H==="dark"?"#f8fafc":"#0f172a",padding:"10px 14px",borderRadius:"14px",boxShadow:"0 10px 25px -5px rgba(0, 0, 0, 0.35), 0 4px 8px rgba(0, 0, 0, 0.15)",border:`1px solid ${H==="dark"?"#334155":"#e2e8f0"}`,cursor:"pointer",zIndex:Ve,display:"flex",alignItems:"flex-start",gap:"8px",animation:"botzki-teaser-in 0.25s cubic-bezier(0.16, 1, 0.3, 1)"},children:[jsxs("div",{style:{flex:1},children:[jsxs("div",{style:{fontSize:"11px",fontWeight:700,color:Y,marginBottom:"2px",display:"flex",alignItems:"center",gap:"5px"},children:[jsx("span",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#ef4444"}}),e.widgetTitle||"Botzki AI"]}),jsx("div",{style:{fontSize:"13px",lineHeight:1.4},children:He})]}),jsx("button",{type:"button",onClick:l=>{l.stopPropagation(),ke(null);},title:"Dismiss preview","aria-label":"Dismiss preview",style:{background:"transparent",border:"none",color:H==="dark"?"#94a3b8":"#64748b",cursor:"pointer",padding:"0 2px",fontSize:"14px",lineHeight:1},children:"\u2715"})]}),jsx("div",{role:"dialog","aria-label":"Botzki AI Chat",style:{position:"fixed",bottom:Be+68,[Qe?"left":"right"]:Ke,width:typeof de=="number"?`${de}px`:de,maxWidth:"calc(100vw - 32px)",height:typeof P=="number"?`${P}px`:P,maxHeight:"calc(100vh - 110px)",zIndex:Ve,boxShadow:"0 20px 40px -10px rgba(0, 0, 0, 0.4), 0 0 1px 1px rgba(255, 255, 255, 0.1)",borderRadius:"16px",overflow:"hidden",transition:"width 0.25s ease, height 0.25s ease, opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1), transform 0.25s cubic-bezier(0.16, 1, 0.3, 1), visibility 0.25s",opacity:u?1:0,transform:u?"translateY(0) scale(1)":"translateY(16px) scale(0.95)",visibility:u?"visible":"hidden",pointerEvents:u?"auto":"none"},children:jsx(hn,{chat:R,title:e.widgetTitle,subtitle:e.widgetSubtitle||"Online",avatar:Ae,botAvatar:e.botAvatar,userAvatar:e.userAvatar,showAvatars:e.showAvatars,enableImageUpload:e.enableImageUpload,enableVoiceInput:e.enableVoiceInput,enableVoiceOutput:e.enableVoiceOutput,enableVoiceNotes:e.enableVoiceNotes,enableHumanHandoff:e.enableHumanHandoff,enableActionEngine:e.enableActionEngine,showFeedback:e.showFeedback,showCitations:e.showCitations,showBranding:e.showBranding,showCopyButton:e.showCopyButton,showExportButton:e.showExportButton!==false,greeting:e.greeting,starterQuestions:e.starterPrompts,theme:H,primaryColor:Y,showCloseButton:e.showCloseButton!==false,showClearButton:e.showClearButton===true,showNewChatButton:e.showNewChatButton!==false,showHistoryButton:e.showHistoryButton!==false,allowExpand:e.allowExpand!==false,isExpanded:y,onToggleExpand:wt,onNewChat:e.onNewChat,isHistoryOpen:N,onHistoryOpenChange:Q,onFeedbackSubmit:e.onFeedbackSubmit,onCitationClick:e.onCitationClick,renderHeader:e.renderHeader,customHeader:e.customHeader,renderMessage:e.renderMessage,renderComposer:e.renderComposer,renderWelcome:e.renderWelcome,unreadFromIndex:ee,placeholder:e.placeholder,inputStyle:e.inputStyle,composerStyle:e.composerStyle,sendButtonStyle:e.sendButtonStyle,userBubbleColor:e.userBubbleColor,userTextColor:e.userTextColor,assistantBubbleColor:e.assistantBubbleColor,assistantTextColor:e.assistantTextColor,fontFamily:e.fontFamily,fontSize:e.fontSize,headerStyle:e.headerStyle,messagesContainerStyle:e.messagesContainerStyle,onClose:We,style:{height:"100%",borderRadius:"16px",...e.chatStyle}})}),e.renderLauncher?jsx("div",{style:{position:"fixed",bottom:Be,[Qe?"left":"right"]:Ke,zIndex:Ve},children:e.renderLauncher({isOpen:u,unreadCount:ye,onClick:Ue,primaryColor:Y,isHovered:Z})}):jsxs("button",{type:"button",onClick:Ue,onMouseEnter:()=>oe(true),onMouseLeave:()=>oe(false),"aria-label":u?"Close AI Support Chat":"Open AI Support Chat","aria-expanded":u,style:{position:"fixed",bottom:Be,[Qe?"left":"right"]:Ke,width:`${O}px`,height:`${O}px`,borderRadius:"50%",backgroundColor:d,color:"#ffffff",border:"none",outline:"none",cursor:"pointer",boxShadow:W,filter:ie,zIndex:Ve,display:"flex",alignItems:"center",justifyContent:"center",transform:Z?"scale(1.08)":"scale(1)",transition:"transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), box-shadow 0.2s ease, filter 0.2s ease, background-color 0.2s ease",...be.style},children:[u?jsxs("svg",{viewBox:"0 0 24 24",width:"24",height:"24",fill:"none",stroke:be.closeColor||"#ffffff",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]}):be.icon?be.icon:jsx(zt,{size:Ae.size??50,shape:Ae.shape??"pebble",followCursor:Ae.followCursor??true,colors:Ae.colors??["#66a6ff","#0059d4"],faceColor:Ae.faceColor??"#ffffff",eyeColor:Ae.eyeColor,mouthColor:Ae.mouthColor,motion:Ae.motion,emotion:Ae.emotion,outlineColor:Ae.outlineColor,outlineWidth:Ae.outlineWidth,...Ae.props}),!u&&ye>0?jsx("div",{style:{position:"absolute",top:"-2px",right:"-2px",backgroundColor:"#ef4444",color:"#ffffff",fontSize:"11px",fontWeight:700,width:ye>9?"auto":"22px",minWidth:"22px",height:"22px",borderRadius:ye>9?"9999px":"50%",display:"flex",alignItems:"center",justifyContent:"center",padding:ye>9?"0 6px":"0",boxShadow:"0 2px 6px rgba(0, 0, 0, 0.35)",border:"2px solid #ffffff",pointerEvents:"none",boxSizing:"border-box",lineHeight:1,...e.badgeStyle},children:ye>9?"9+":ye}):null]})]});return createPortal(A,document.body)});function pr(){let{client:t,botId:e,baseUrl:i,sessionId:o}=Mt(),[a,s]=useState(false),[c,g]=useState(false),[m,u]=useState(null),S=useCallback(async C=>{s(true),u(null),g(false);try{if(typeof t.submitFeedback=="function")await t.submitFeedback({...C,sessionId:o});else {let y=i?i.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${y}/api/v1/public/chat/${e}/feedback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...C,sessionId:o})});}return g(!0),!0}catch(y){let L=y instanceof Error?y:new Error(String(y));return u(L),false}finally{s(false);}},[t,e,i,o]),f=useCallback(()=>{s(false),g(false),u(null);},[]);return {submitFeedback:S,isSubmitting:a,isSuccess:c,error:m,reset:f}}function fr(){let{client:t,botId:e,baseUrl:i,sessionId:o}=Mt(),[a,s]=useState(false),[c,g]=useState(false),[m,u]=useState(null),S=useCallback(async C=>{s(true),u(null),g(false);try{if(typeof t.captureLead=="function")await t.captureLead({...C,sessionId:o});else {let y=i?i.replace(/\/+$/,""):"https://api.botzki.com";await fetch(`${y}/api/v1/public/chat/${e}/leads`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...C,sessionId:o})});}return g(!0),!0}catch(y){let L=y instanceof Error?y:new Error(String(y));return u(L),false}finally{s(false);}},[t,e,i,o]),f=useCallback(()=>{s(false),g(false),u(null);},[]);return {captureLead:S,isSubmitting:a,isSuccess:c,error:m,reset:f}}function gr(){let{client:t}=Mt(),[e,i]=useState(false),[o,a]=useState(null),[s,c]=useState(null),g=useCallback(async u=>{i(true),c(null);try{let f=(await t.transcribeAudio(u)).text||"";return a(f),f}catch(S){let f=S instanceof Error?S:new Error(String(S));return c(f),null}finally{i(false);}},[t]),m=useCallback(()=>{i(false),a(null),c(null);},[]);return {transcribe:g,isTranscribing:e,transcript:o,error:s,reset:m}}
138
+ export{Xi as AiBotAvatar,zt as BotziAvatar,pn as BotzkiAudioPlayer,hn as BotzkiChat,Wo as BotzkiMarkdown,zi as BotzkiProvider,ur as BotzkiWidget,fn as CoBrowseLaserPointer,Un as analyzeVisitorSentiment,on as captureDomSnapshot,Ft as notifyVisitorIncomingMessage,Ln as playVisitorNotificationChime,Hn as startTabTitleAlert,bo as useBotInfo,Mt as useBotzki,mo as useChat,rn as useCoBrowse,yo as useEmpathyEngine,pr as useFeedback,fr as useLeadCapture,Dt as useOptionalBotzki,gr as useVoiceTranscription};//# sourceMappingURL=index.mjs.map
4
139
  //# sourceMappingURL=index.mjs.map