@snf/access-qa-bot 3.7.1 → 3.7.2

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.
@@ -37,7 +37,7 @@
37
37
  }
38
38
  `),f.createElement("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:`qa-bot-login-button ${o?"qa-bot-header-login-button":""} ${r}`,style:Object.assign(Object.assign({},a),n),onClick:()=>{A({type:"chatbot_login_clicked",loginUrl:t})}},"Log In"))},$l=()=>f.createElement("div",{className:"user-login-icon",style:{alignItems:"center",justifyContent:"center",width:"30px",height:"30px",borderRadius:"50%",backgroundColor:"var(--primaryColor, #1a5b6e)",marginRight:"5px",display:"flex"},role:"img","aria-label":"User logged in",title:"User logged in"},f.createElement("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false"},f.createElement("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),f.createElement("circle",{cx:"12",cy:"7",r:"4"}))),Ie=[];for(let e=0;e<256;++e)Ie.push((e+256).toString(16).slice(1));let _r;const ec=new Uint8Array(16);var $A={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ei(e,t,r){var o;if($A.randomUUID&&!e)return $A.randomUUID();const n=(e=e||{}).random??((o=e.rng)==null?void 0:o.call(e))??function(){if(!_r){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");_r=crypto.getRandomValues.bind(crypto)}return _r(ec)}();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=15&n[6]|64,n[8]=63&n[8]|128,function(A,a=0){return(Ie[A[a+0]]+Ie[A[a+1]]+Ie[A[a+2]]+Ie[A[a+3]]+"-"+Ie[A[a+4]]+Ie[A[a+5]]+"-"+Ie[A[a+6]]+Ie[A[a+7]]+"-"+Ie[A[a+8]]+Ie[A[a+9]]+"-"+Ie[A[a+10]]+Ie[A[a+11]]+Ie[A[a+12]]+Ie[A[a+13]]+Ie[A[a+14]]+Ie[A[a+15]]).toLowerCase()}(n)}function xt(){return typeof localStorage<"u"&&localStorage.getItem("QA_BOT_DEBUG")==="true"}const tc="background: #1a5b6e; color: white; padding: 2px 6px; border-radius: 3px;",nc="background: #7c3aed; color: white; padding: 2px 6px; border-radius: 3px;",rc="background: #059669; color: white; padding: 2px 6px; border-radius: 3px;",oc="background: #f97316; color: white; padding: 2px 6px; border-radius: 3px;",Ac="background: #f59e0b; color: #000; padding: 2px 6px; border-radius: 3px 0 0 3px; font-weight: bold;",ic="background: #fbbf24; color: #000; padding: 2px 6px; border-radius: 0 3px 3px 0;",sc=()=>{xt()&&console.log("%c QA Bot Core %c v0.2.35 ",Ac,ic)},Qn=function(e){if(xt()){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];console.log(`%c[Session]%c ${e}`,tc,"",...r)}},it=function(e){if(xt()){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];console.log(`%c[History]%c ${e}`,nc,"",...r)}},ac=(e,t)=>{xt()&&console.log(`%c[Message]%c ${e}`,rc,"",t)},on=function(e){if(xt()){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];console.log(`%c[Turnstile]%c ${e}`,oc,"",...r)}},ti=function(){console.warn(...arguments)},Be=function(){console.error(...arguments)},ni="qa_bot_session_messages",ri=()=>`qa_bot_session_${ei()}`,An=()=>{try{const e=localStorage.getItem(ni);return e?JSON.parse(e):{}}catch{return{}}},lc=(e,t,r,n,o)=>{const A=An();if(!A[e]&&(A[e]={messages:[],startedAt:new Date().toISOString(),preview:""},it("NEW session created",{sessionId:e.slice(-12)})),A[e].messages.some(l=>l.id===t))return void it("DUPLICATE message skipped",{sessionId:e.slice(-12),messageId:t.slice(-8),sender:n});const a={id:t,content:r,sender:n,type:o,timestamp:Date.now()};A[e].messages.push(a),it("MESSAGE added",{sessionId:e.slice(-12),messageId:t.slice(-8),sender:n,totalInSession:A[e].messages.length});const s=A[e].messages,i=s.find(l=>{var c;return l.sender.toLowerCase()==="bot"&&((c=l.content)===null||c===void 0?void 0:c.trim())&&l.content.length>=100});if(i){const l=i.content;A[e].preview=l.slice(0,50)+(l.length>50?"...":"")}else{const l=s.find(c=>{var d;return c.sender.toLowerCase()==="user"&&((d=c.content)===null||d===void 0?void 0:d.trim())});if(l&&!A[e].preview){const c=l.content;A[e].preview=c.slice(0,50)+(c.length>50?"...":"")}}(l=>{var c;const d=()=>Object.values(l).reduce((u,p)=>u+p.messages.length,0);for(;d()>100&&Object.keys(l).length>1;){const u=(c=Object.entries(l).sort((p,g)=>{let[,v]=p,[,h]=g;return new Date(v.startedAt).getTime()-new Date(h.startedAt).getTime()})[0])===null||c===void 0?void 0:c[0];if(!u)break;delete l[u]}localStorage.setItem(ni,JSON.stringify(l))})(A),it("STORAGE state",{ourSessions:Object.keys(A).length,ourTotalMessages:Object.values(A).reduce((l,c)=>l+c.messages.length,0)})},oi=e=>{var t,r;return(r=(t=An()[e])===null||t===void 0?void 0:t.messages.length)!==null&&r!==void 0?r:0},cc=e=>{const t=An()[e];return t!=null&&t.startedAt?Date.now()-new Date(t.startedAt).getTime():0},Ai=f.createContext(void 0),uc=e=>{let{children:t,getSessionId:r,setSessionId:n,resetSession:o,clearResettingFlag:A}=e;return f.createElement(Ai.Provider,{value:{getSessionId:r,setSessionId:n,resetSession:o,clearResettingFlag:A}},t)},Or=()=>{const e=f.useContext(Ai);if(!e)throw new Error("useSession must be used within a SessionProvider");return e},dc=()=>{const[e,t]=f.useState(!1),[r,n]=f.useState([]),[o,A]=f.useState(null),[a,s]=f.useState(0),i=f.useRef(null),l=f.useRef(null),{replaceMessages:c}=Xt(),{toggleTextAreaDisabled:d}=So(),{setSessionId:u,getSessionId:p}=Or();f.useEffect(()=>{var v,h;const w=m=>{i.current&&!i.current.contains(m.target)&&l.current&&!l.current.contains(m.target)&&t(!1)},E=(h=(v=i.current)===null||v===void 0?void 0:v.getRootNode())!==null&&h!==void 0?h:document;return e&&E.addEventListener("mousedown",w),()=>{E.removeEventListener("mousedown",w)}},[e]);const g=v=>{var h;const w=p();if(it("RESTORE requested",{targetSession:v.slice(-12),currentSession:w==null?void 0:w.slice(-12)}),v===w)return it("RESTORE skipped - already on this session"),void t(!1);const E=(k=>{var S;return((S=An()[k])===null||S===void 0?void 0:S.messages)||[]})(v).filter(k=>{var S;return(S=k.content)===null||S===void 0?void 0:S.trim()});it("Stored messages from our localStorage",{count:E.length,ids:E.map(k=>k.id.slice(-8))});const m=E.map(k=>({id:k.id,content:k.content,sender:k.sender.toUpperCase(),type:k.type||"string",timestamp:new Date(k.timestamp).toISOString()}));var C;u(v),it("Session ID updated",{newSession:v.slice(-12)}),c(m),it("replaceMessages called",{count:m.length}),C=(h=l.current)===null||h===void 0?void 0:h.getRootNode(),setTimeout(()=>{const k=(C||document).querySelector(".rcb-chat-body-container");k&&k.querySelectorAll(".rcb-bot-message").forEach(S=>{var D;let I=S.innerHTML,Q=!1;I.includes("](")&&(I=I.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),Q=!0),I.includes("&lt;a href=")&&(I=I.replace(/&lt;a\s+href=["']([^"']+)["'][^&]*&gt;([^&]+)&lt;\/a&gt;/gi,'<a href="$1" target="_blank" rel="noopener noreferrer">$2</a>'),Q=!0),(I.includes("&lt;a ")||!((D=S.textContent)===null||D===void 0)&&D.includes("<a href="))&&(S.textContent||"").includes("<a href=")&&(I=I.replace(/&lt;a\s+href="([^"]+)"[^&]*&gt;([^&]+)&lt;\/a&gt;/gi,'<a href="$1" target="_blank" rel="noopener noreferrer">$2</a>'),Q=!0),Q&&(S.innerHTML=I)})},50),d(!1),it("Chat input enabled after restore"),t(!1)};return f.createElement("div",{style:{position:"relative"}},f.createElement("button",{ref:l,className:"history-button",onClick:()=>{if(!e&&(n((()=>{const v=An();return Object.entries(v).map(h=>{let[w,E]=h;return Object.assign({sessionId:w},E)}).sort((h,w)=>new Date(w.startedAt).getTime()-new Date(h.startedAt).getTime())})()),l.current)){const v=l.current.closest(".rcb-chat-window");if(v){const h=v.getBoundingClientRect(),w=l.current.getBoundingClientRect();A(h.width+3),s(h.right-w.right-18+4)}}t(!e)},style:{alignItems:"center",justifyContent:"center",width:"30px",height:"30px",borderRadius:"50%",backgroundColor:"var(--primaryColor, #1a5b6e)",marginRight:"18px",display:"flex",border:"none",cursor:"pointer",padding:0},"aria-label":"View chat history",title:"View chat history","aria-expanded":e,"aria-haspopup":"menu"},f.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false"},f.createElement("circle",{cx:"12",cy:"12",r:"10"}),f.createElement("polyline",{points:"12 6 12 12 16 14"}))),e&&f.createElement("div",{ref:i,role:"menu",style:{position:"absolute",right:a?`-${a}px`:"-18px",top:"100%",marginTop:"8px",width:o?`${o}px`:"550px",backgroundColor:"white",borderRadius:0,borderBottom:"3px solid var(--primaryColor, #1a5b6e)",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.1)",maxHeight:"250px",overflowY:"auto",zIndex:1e3}},r.length===0?f.createElement("div",{style:{padding:"12px 16px",color:"#666",fontSize:"14px",textAlign:"center"}},"No chat history"):r.map(v=>f.createElement("button",{key:v.sessionId,role:"menuitem",onClick:()=>g(v.sessionId),style:{width:"100%",padding:"10px 14px",border:"none",backgroundColor:"transparent",cursor:"pointer",textAlign:"left",display:"flex",flexDirection:"column",gap:"2px",borderBottom:"1px solid #eee"},onMouseEnter:h=>{h.currentTarget.style.backgroundColor="#f5f5f5"},onMouseLeave:h=>{h.currentTarget.style.backgroundColor="transparent"}},f.createElement("span",{style:{fontSize:"14px",color:"#333",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},v.preview||"New conversation"),f.createElement("span",{style:{fontSize:"12px",color:"#888"}},(h=>{const w=new Date(h),E=new Date().getTime()-w.getTime(),m=Math.floor(E/864e5);return m===0?w.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):m===1?"Yesterday":m<7?w.toLocaleDateString([],{weekday:"short"}):w.toLocaleDateString([],{month:"short",day:"numeric"})})(v.startedAt))))))},ii=e=>{var{width:t=24,height:r=24,color:n="currentColor",children:o}=e,A=Gr(e,["width","height","color","children"]);return f.createElement("svg",dn({xmlns:"http://www.w3.org/2000/svg",width:t,height:r,viewBox:"0 0 24 24",fill:"none",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false"},A),o)},fc=e=>f.createElement(ii,e,f.createElement("path",{d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})),pc=()=>{const{restartFlow:e}=bn(),{setTextAreaValue:t}=So(),{messages:r}=Xt(),{getSessionId:n,resetSession:o,clearResettingFlag:A}=Or(),{trackEvent:a}=JA();return f.createElement("button",{onClick:async()=>{const s=n(),i=s?oi(s):0;a({type:"chatbot_new_chat",previousMessageCount:i}),o(),await t(""),await e(),setTimeout(()=>{A()},100)},tabIndex:0,"aria-label":"New chat conversation",style:{backgroundColor:"var(--primaryColor, #107180)",border:"none",color:"#ffffff",fontSize:"14px",cursor:"pointer",padding:"8px 12px",borderRadius:"4px",transition:"all 0.2s ease",display:"flex",alignItems:"center",gap:"6px",fontWeight:"500"},onMouseEnter:s=>{s.target.style.backgroundColor="var(--secondaryColor, #0d5f6b)"},onMouseLeave:s=>{s.target.style.backgroundColor="var(--primaryColor, #107180)"}},f.createElement(fc,{width:16,height:16}),"New Chat")};function Nr(e){if(typeof e=="string")return e;if(typeof e=="number")return String(e);if(!e)return"";if(Array.isArray(e))return e.map(Nr).join("");if(typeof e=="object"&&e!==null&&"props"in e){const t=e.props;if(t&&"children"in t)return Nr(t.children)}return""}const gc=()=>{const{getSessionId:e}=Or(),t=f.useCallback(r=>{var n;const o=(n=r.data)===null||n===void 0?void 0:n.message;if(!(o!=null&&o.id))return;const A=o.sender,a=o.type||"string";let s;if(s=typeof o.content=="string"?o.content:Nr(o.content),ac("TRACKED",{id:o.id,sender:A,content:s.substring(0,50)+(s.length>50?"...":"")}),s.includes("rcb-options-container")||!s.trim())return;const i=e();lc(i,o.id,s,A,a)},[e]);return f.useEffect(()=>(window.addEventListener("rcb-pre-inject-message",t),()=>{window.removeEventListener("rcb-pre-inject-message",t)}),[t]),null},hc=()=>(f.useEffect(()=>{const e=A=>{if(!["ArrowDown","ArrowUp","ArrowLeft","ArrowRight","Enter"," ","Home","End"].includes(A.key))return;const a=document.activeElement;if(a&&(a.tagName==="INPUT"||a.tagName==="TEXTAREA"||a.contentEditable==="true"||a.classList.contains("rcb-chat-input-textarea")))return;const s=document.querySelector(".rcb-chat-window");if(!s)return;const i=Array.from(s.querySelectorAll(".rcb-message-container, .rcb-bot-message-container, .rcb-user-message-container")).filter(d=>d.offsetParent!==null);if(i.length>0){const d=i[i.length-1].querySelector(".rcb-checkbox-container");if(d&&d.offsetParent!==null){const u=Array.from(d.querySelectorAll(".rcb-checkbox-row-container")),p=d.querySelector(".rcb-checkbox-next-button");if(u.length>0){const g=[...u];return p&&g.push(p),void((v,h)=>{v.preventDefault();let w=-1;for(let m=0;m<h.length;m++)if(h[m]===document.activeElement||h[m].contains(document.activeElement)){w=m;break}w===-1&&(w=0);let E=w;switch(v.key){case"ArrowDown":case"ArrowRight":E=w<h.length-1?w+1:0;break;case"ArrowUp":case"ArrowLeft":E=w>0?w-1:h.length-1;break;case"Home":E=0;break;case"End":E=h.length-1;break;case"Enter":case" ":{const m=h[w],C=new MouseEvent("mousedown",{bubbles:!0,cancelable:!0,view:window});return void m.dispatchEvent(C)}default:return}h[E].focus(),h[E].setAttribute("tabindex","0"),h[E].classList.add("keyboard-focused"),h.forEach((m,C)=>{C!==E&&(m.setAttribute("tabindex","-1"),m.classList.remove("keyboard-focused"))})})(A,g)}}}let l=[];if(i.length>0){const d=i[i.length-1],u=Array.from(d.querySelectorAll(".rcb-options-container")).filter(p=>p.offsetParent!==null);if(u.length>0){const p=u[u.length-1];l=Array.from(p.querySelectorAll(".rcb-options"))}}if(l.length===0)return;const c=l.findIndex(d=>d===document.activeElement);switch(A.key){case"ArrowDown":case"ArrowRight":{let d;A.preventDefault(),d=c<l.length-1?c+1:0,l[d].setAttribute("tabindex","0"),l.forEach((u,p)=>{p!==d&&(u.setAttribute("tabindex","-1"),u.classList.remove("keyboard-focused"))}),l[d].classList.add("keyboard-focused"),l[d].focus();break}case"ArrowUp":case"ArrowLeft":{let d;A.preventDefault(),d=c>0?c-1:l.length-1,l[d].setAttribute("tabindex","0"),l.forEach((u,p)=>{p!==d&&(u.setAttribute("tabindex","-1"),u.classList.remove("keyboard-focused"))}),l[d].classList.add("keyboard-focused"),l[d].focus();break}case"Enter":case" ":if(A.preventDefault(),document.activeElement&&l.includes(document.activeElement)){const d=document.activeElement;if(d.classList.contains("rcb-checkbox-row-container")||d.closest(".rcb-checkbox-row-container")){const u=new MouseEvent("mousedown",{bubbles:!0,cancelable:!0,view:window});d.dispatchEvent(u);const p=d.querySelector(".rcb-checkbox-label"),g=p?p.textContent:d.textContent||"checkbox",v=d.querySelector(".rcb-checkbox-mark"),h=v&&v.style.backgroundColor?"checked":"unchecked";t(`${g} ${h}`)}else{const u=new MouseEvent("mousedown",{bubbles:!0,cancelable:!0,view:window});d.dispatchEvent(u);const p=d.textContent||d.innerText;t(`Selected: ${p}`)}}break;case"Home":A.preventDefault(),l.length>0&&(l[0].setAttribute("tabindex","0"),l.forEach((d,u)=>{u!==0&&(d.setAttribute("tabindex","-1"),d.classList.remove("keyboard-focused"))}),l[0].classList.add("keyboard-focused"),l[0].focus());break;case"End":if(A.preventDefault(),l.length>0){const d=l.length-1;l[d].setAttribute("tabindex","0"),l.forEach((u,p)=>{p!==d&&(u.setAttribute("tabindex","-1"),u.classList.remove("keyboard-focused"))}),l[d].classList.add("keyboard-focused"),l[d].focus()}}},t=A=>{const a=document.createElement("div");a.setAttribute("aria-live","assertive"),a.setAttribute("aria-atomic","true"),a.className="sr-only",a.textContent=A,document.body.appendChild(a),setTimeout(()=>{document.body.contains(a)&&document.body.removeChild(a)},1e3)},r=(A=null)=>{let a=A;if(a||(a=document.querySelector(".rcb-chat-window"),a||(a=document.querySelector('[class*="rcb-chat"]')),a||(a=document.querySelector(".qa-bot"))),!a)return;const s=a.closest(".embedded-qa-bot")!==null,i=Array.from(a.querySelectorAll(".rcb-message-container, .rcb-bot-message-container, .rcb-user-message-container")).filter(u=>u.offsetParent!==null);if(i.length===0)return;const l=i[i.length-1],c=Array.from(l.querySelectorAll(".rcb-options-container")).filter(u=>u.offsetParent!==null);let d=[];if(c.length>0){const u=c[c.length-1];d=Array.from(u.querySelectorAll(".rcb-options"))}if(d.length===0){let u=l.querySelector(".rcb-checkbox-container");if(!u&&a&&(u=a.querySelector(".rcb-checkbox-container")),u&&u.offsetParent!==null){const p=Array.from(u.querySelectorAll(".rcb-checkbox-row-container")).filter(g=>g.offsetParent!==null&&g.style.display!=="none");if(p.length>0){const g=u.querySelector(".rcb-checkbox-next-button"),v=[...p];if(g&&g.offsetParent!==null&&v.push(g),v.forEach((h,w)=>{h.setAttribute("tabindex",w===0?"0":"-1"),w===0?h.classList.add("keyboard-focused"):h.classList.remove("keyboard-focused")}),p.length>1){u.querySelectorAll(".keyboard-nav-hint").forEach(w=>w.remove());const h=document.createElement("div");h.className="keyboard-nav-hint",h.textContent="Use arrow keys ↕ to navigate, Enter to select/deselect, or click any option",h.style.cssText="font-size: 12px !important; color: #666 !important; margin-bottom: 8px !important; font-style: italic !important; display: block !important;",u.insertBefore(h,u.firstChild)}return void setTimeout(()=>{v[0]&&v[0].offsetParent!==null&&!s&&v[0].focus()},150)}}}if(d.length>0){if(d.forEach((u,p)=>{const g=p===0?"0":"-1";u.setAttribute("tabindex",g),u.setAttribute("role","option"),u.setAttribute("aria-posinset",p+1),u.setAttribute("aria-setsize",d.length),p===0?u.classList.add("keyboard-focused"):u.classList.remove("keyboard-focused")}),d.length>1){const u=c.length>0?c[c.length-1]:null;if(u){u.querySelectorAll(".keyboard-nav-hint").forEach(g=>g.remove());const p=document.createElement("div");p.className="keyboard-nav-hint",p.textContent="Use arrow keys ↕ to navigate, Enter to select, or click any option",p.style.cssText="font-size: 12px !important; color: #666 !important; margin-bottom: 8px !important; font-style: italic !important; display: block !important;",u.insertBefore(p,u.firstChild)}}else{const u=c.length>0?c[c.length-1]:null;u&&u.querySelectorAll(".keyboard-nav-hint").forEach(p=>p.remove())}setTimeout(()=>{d[0]&&d[0].offsetParent!==null&&!s&&(d[0].focus(),d.length>1&&t(`${d.length} options available. Use arrow keys to navigate.`))},200)}},n=new MutationObserver(A=>{A.forEach(a=>{var s,i;if(a.type==="childList"){const l=Array.from(a.addedNodes),c=l.some(u=>{var p,g,v,h;return u.nodeType===Node.ELEMENT_NODE&&(((p=u.classList)==null?void 0:p.contains("rcb-options-container"))||((g=u.classList)==null?void 0:g.contains("rcb-options"))||((v=u.querySelector)==null?void 0:v.call(u,".rcb-options-container"))||((h=u.querySelector)==null?void 0:h.call(u,".rcb-options")))}),d=l.some(u=>{var p,g;return u.nodeType===Node.ELEMENT_NODE&&(((p=u.classList)==null?void 0:p.contains("rcb-checkbox-container"))||((g=u.querySelector)==null?void 0:g.call(u,".rcb-checkbox-container")))});if(c||d){let u=a.target;for(;u&&!((s=u.classList)!=null&&s.contains("qa-bot"))&&!((i=u.classList)!=null&&i.contains("rcb-chat-window"));)u=u.parentElement;(u||document).querySelectorAll(".rcb-options[tabindex], .rcb-checkbox-row-container[tabindex], .rcb-checkbox-next-button[tabindex]").forEach(p=>{p.setAttribute("tabindex","-1"),p.classList.remove("keyboard-focused")}),setTimeout(()=>r(u),100)}}})});n.observe(document.body,{childList:!0,subtree:!0}),document.addEventListener("keydown",e),r();const o=setInterval(()=>{document.querySelectorAll(".qa-bot").forEach(A=>{const a=A.querySelectorAll(".rcb-options-container .rcb-options").length>0,s=A.querySelectorAll(".rcb-checkbox-row-container").length>0;if(a){const i=A.querySelectorAll(".rcb-options[tabindex]").length;A.querySelectorAll(".rcb-options").length>i&&r(A)}if(s){const i=A.querySelectorAll(".rcb-checkbox-row-container[tabindex]").length;A.querySelectorAll(".rcb-checkbox-row-container").length>i&&r(A)}})},1e3);return()=>{document.removeEventListener("keydown",e),n.disconnect(),clearInterval(o)}},[]),null);let si=!1,Mn=null;function ai(){return si?Promise.resolve():Mn||(Mn=new Promise((e,t)=>{const r=document.createElement("script");r.src="https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",r.async=!0,r.onload=()=>{si=!0,on("Script loaded"),e()},r.onerror=()=>{Mn=null,t(new Error("Failed to load Turnstile script"))},document.head.appendChild(r)}),Mn)}const sn=e=>{if(!e||typeof e!="string")return e;let t=e.replace(/\[(https?:\/\/[^\s]+?)\]/gi,"[$1]($1)");return t=t.replace(new RegExp(`(?<!\\]\\(|href=["']|\\[)https?:\\/\\/[^\\s[\\]()]+`,"gi"),r=>{let n=r,o="";const A=n.match(/([.,;:!?]+)$/);return A&&(o=A[1],n=n.slice(0,-o.length)),`[${n}](${n})${o}`}),t},mc=e=>{let{siteKey:t,onVerify:r,onError:n,loginUrl:o}=e;const A=f.useRef(null),a=f.useRef(null),s=f.useRef(!1),i=f.useRef(null),l=f.useRef(null),[c,d]=f.useState(!1),[u,p]=f.useState(0),g=f.useRef("widget_error"),v=f.useRef(null),h=o&&o!=="/login",w=f.useCallback(()=>{const C=window.turnstile;if(i.current&&(C!=null&&C.remove)){try{C.remove(i.current)}catch{}i.current=null}},[]),E=f.useCallback(()=>{var C;w(),c?n==null||n(g.current,(C=v.current)!==null&&C!==void 0?C:void 0):n==null||n("user_cancelled")},[n,w,c]);f.useEffect(()=>()=>{w()},[w]),f.useEffect(()=>{var C;return l.current=document.activeElement,(C=a.current)===null||C===void 0||C.focus(),()=>{l.current&&typeof l.current.focus=="function"&&l.current.focus()}},[]),f.useEffect(()=>{const C=k=>{if(k.key==="Escape")return k.preventDefault(),void E();if(k.key==="Tab"&&a.current){const S=a.current.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])');if(S.length===0)return;const D=S[0],I=S[S.length-1];k.shiftKey&&document.activeElement===D?(k.preventDefault(),I.focus()):k.shiftKey||document.activeElement!==I||(k.preventDefault(),D.focus())}};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[E]),f.useEffect(()=>{s.current||!A.current||c||(s.current=!0,ai().then(()=>{const C=window.turnstile;if(!C||!A.current)return Be("Turnstile API not available after script load"),g.current="api_unavailable",void d(!0);i.current=C.render(A.current,{sitekey:t,callback:k=>{on("Visible challenge completed"),r(k)},"error-callback":k=>(Be("Turnstile challenge failed:",k),v.current=k,g.current="widget_error",w(),d(!0),!0),"expired-callback":()=>{Be("Turnstile token expired"),g.current="token_expired",w(),d(!0)}})}).catch(C=>{Be("Failed to load Turnstile script:",C),g.current="script_load_failed",d(!0)}))},[t,r,c]);const m=f.createElement(f.Fragment,null,f.createElement("div",{"aria-hidden":"true",style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.5)",zIndex:999998}}),f.createElement("div",{ref:a,role:"dialog","aria-modal":"true","aria-labelledby":"qa-bot-turnstile-label",tabIndex:-1,style:{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)",zIndex:999999,background:"white",padding:"24px",borderRadius:"8px",boxShadow:"0 4px 20px rgba(0, 0, 0, 0.3)",maxWidth:"90vw",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif'}},f.createElement("span",{id:"qa-bot-turnstile-label",className:"sr-only",style:{position:"absolute",width:"1px",height:"1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap"}},"Verification challenge"),c?f.createElement("div",{style:{fontSize:"14px",lineHeight:"1.5",color:"#333"}},u===0?f.createElement("p",{style:{margin:"0 0 16px 0"}},"Verification failed. You can try again",h&&f.createElement(f.Fragment,null,", or"," ",f.createElement("a",{href:o,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--primaryColor, #107180)",fontWeight:"bold"}},"log in")," ","to skip verification"),"."):f.createElement(f.Fragment,null,f.createElement("p",{style:{margin:"0 0 8px 0"}},"Verification is still not working. This can be caused by browser extensions (ad blockers, privacy tools) or VPN connections."),f.createElement("p",{style:{margin:"0 0 16px 0"}},"Try disabling extensions, using a private/incognito window,",h&&f.createElement(f.Fragment,null," ",f.createElement("a",{href:o,target:"_blank",rel:"noopener noreferrer",style:{color:"var(--primaryColor, #107180)",fontWeight:"bold"}},"logging in"),",")," ","or using a different browser.")),f.createElement("div",{style:{display:"flex",gap:"8px"}},f.createElement("button",{type:"button",onClick:()=>{w(),s.current=!1,p(C=>C+1),d(!1)},style:{padding:"8px 16px",background:"var(--primaryColor, #107180)",color:"white",border:"none",borderRadius:"4px",cursor:"pointer",fontSize:"14px"}},"Try again"),f.createElement("button",{type:"button",onClick:E,style:{padding:"8px 16px",background:"#f0f0f0",color:"#333",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",fontSize:"14px"}},"Close"))):f.createElement(f.Fragment,null,f.createElement("div",{ref:A,style:{borderRadius:"8px",overflow:"hidden"}}),f.createElement("button",{type:"button",onClick:E,style:{marginTop:"16px",padding:"8px 16px",background:"#f0f0f0",color:"#333",border:"1px solid #ccc",borderRadius:"4px",cursor:"pointer",fontSize:"14px"}},"Cancel"))));return mi.createPortal(m,document.body)};function li(e){const{confidence:t,tools_used:r,metadata:n}=e;if(!(t||r&&r.length!==0))return"";const o=[];return t&&o.push(`• Confidence: ${t}`),r&&r.length>0&&o.push(`• Tools used: ${r.join(", ")}`),n!=null&&n.agent&&o.push(`• Agent: ${n.agent}`),`---
39
39
  ${o.join(`
40
- `)}`}function yc(e){let{getState:t,onResubmit:r,trackEvent:n,loginUrl:o}=e;var A,a;const[s,i]=f.useState(null),[l,c]=f.useState(0),d=t(),u=(A=vi)!==null&&A!==void 0?A:{},p=u.VITE_FORCE_TURNSTILE_WIDGET==="true",g=(a=d.siteKey)!==null&&a!==void 0?a:p?u.VITE_TURNSTILE_SITE_KEY:null;return g&&(p||s!==g)?f.createElement(mc,{key:l,siteKey:g,loginUrl:o,onVerify:async v=>{d.token=v,n==null||n({type:"chatbot_turnstile_completed"}),await r(v)==="needs_another_challenge"?c(h=>h+1):i(d.siteKey)},onError:(v,h)=>{var w;i(d.siteKey),n==null||n({type:"chatbot_turnstile_error",queryId:(w=d.pendingQuery)===null||w===void 0?void 0:w.queryId,failureReason:v,cloudflareErrorCode:h})}}):null}const vc="#1a5b6e",wc="#107180",bc="Arial, sans-serif",ci="Q&A Bot",Ec="/chat-icon.svg",Cc="Type your question here...",Pc="Select an option to continue",Sc=!1,kc="Ask me a question!",ui="/login",Dc={general:{showHeader:!0,showFooter:!0},tooltip:{mode:"CLOSE"},chatInput:{disabled:!1,characterLimit:5e3,showCharacterCount:!1,allowNewline:!0,blockSpam:!1},chatWindow:{defaultOpen:!1,showScrollbar:!1},botBubble:{simulateStream:!0,streamSpeed:10,showAvatar:!1},userBubble:{showAvatar:!1},notification:{disabled:!0,showCount:!1},audio:{disabled:!0},emoji:{disabled:!0},fileAttachment:{disabled:!0}},Lr=f.forwardRef((e,t)=>{var r,n,o;const{apiKey:A,qaEndpoint:a,ratingEndpoint:s,capabilitiesEndpoint:i,agentRatingEndpoint:l,welcomeMessage:c,open:d,onOpenChange:u,isLoggedIn:p,allowAnonAccess:g=!1,actingUser:v,primaryColor:h,secondaryColor:w,botName:E,logo:m,placeholder:C,errorMessage:k,embedded:S,footerText:D,footerLink:I,tooltipText:Q,loginUrl:x,turnstileSiteKey:N,backendId:B,resourceContext:_,customFlow:U,onAnalyticsEvent:O}=e,F=f.useRef(`bot_${Math.random().toString(36).substr(2,9)}`);f.useEffect(()=>{sc()},[]);const M=f.useRef(null);M.current===null&&(M.current=ri(),Qn("CREATED",M.current));const L=f.useRef(!1),y=f.useRef({getSessionId:()=>M.current,isResetting:()=>L.current}),Y=f.useRef(null),b=function(z,q){const[le,ne]=f.useState(null),[me,fe]=f.useState("idle"),ce=f.useRef(null),Me=f.useRef(null),De=f.useRef(!0),Ft=f.useCallback(()=>{const Ee=window.turnstile;if(Me.current&&(Ee!=null&&Ee.remove)){try{Ee.remove(Me.current)}catch{}Me.current=null}ce.current&&(ce.current.remove(),ce.current=null)},[]);return f.useEffect(()=>{if(De.current=!0,!z)return fe("idle"),void ne(null);fe("loading");const Ee=document.createElement("div");return Ee.style.position="fixed",Ee.style.left="-9999px",Ee.style.top="-9999px",Ee.style.width="0",Ee.style.height="0",Ee.style.overflow="hidden",Ee.setAttribute("aria-hidden","true"),document.body.appendChild(Ee),ce.current=Ee,ai().then(()=>{if(!De.current)return;const $e=window.turnstile;if(!$e||!ce.current)return Be("Turnstile API not available for silent verification"),fe("failed"),void(q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"api_unavailable"}));const be=$e.render(ce.current,{sitekey:z,execution:"render","refresh-expired":"auto",callback:ut=>{De.current&&(on("Silent verification succeeded"),ne(ut),fe("verified"))},"error-callback":ut=>!De.current||(Be("Turnstile silent verification failed:",ut),ne(null),fe("failed"),q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"widget_error",cloudflareErrorCode:ut}),!0),"expired-callback":()=>{De.current&&(on("Token expired, awaiting refresh"),ne(null),fe("loading"))}});Me.current=be}).catch($e=>{De.current&&(Be("Failed to load Turnstile script for silent verification:",$e),fe("failed"),q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"script_load_failed"}))}),()=>{De.current=!1,Ft()}},[z,Ft]),{token:le,status:me,reset:f.useCallback(()=>{const Ee=window.turnstile;Me.current&&(Ee!=null&&Ee.reset)&&(ne(null),fe("loading"),Ee.reset(Me.current),on("Token consumed, resetting widget for fresh token"))},[])}}(N,z=>{var q;(q=Y.current)===null||q===void 0||q.call(Y,z)}),J=f.useRef(null);J.current=b.token;const[j,K]=f.useState(p);f.useEffect(()=>{K(p)},[p]);const V=S!==void 0?S:Sc,ae=f.useCallback(z=>{var q;O&&O(Object.assign(Object.assign({},z),{timestamp:Date.now(),sessionId:(q=M.current)!==null&&q!==void 0?q:void 0,pageUrl:typeof window<"u"?window.location.href:void 0,isEmbedded:V}))},[O,V]);f.useEffect(()=>{Y.current=z=>ae(z)},[ae]);const re=f.useMemo(()=>{const z=Object.assign({},Dc);z.general=Object.assign(Object.assign({},z.general),{primaryColor:h||vc,secondaryColor:w||wc,fontFamily:bc,embedded:V});const q=j===!1?[f.createElement(ZA,{key:"login-button",loginUrl:x||ui,isHeaderButton:!0})]:[f.createElement(dc,{key:"history-button"}),f.createElement($l,{key:"user-icon"})];z.header={title:f.createElement("span",{style:{fontSize:14,fontWeight:500}},E||ci),showAvatar:!0,avatar:m||Ec,buttons:[...q,we.CLOSE_CHAT_BUTTON]},z.chatInput=Object.assign(Object.assign({},z.chatInput),{disabled:!1,enabledPlaceholderText:C||Cc,disabledPlaceholderText:k||Pc}),z.tooltip=Object.assign(Object.assign({},z.tooltip),{text:Q||kc});const le=D?I?f.createElement("a",{href:I,target:"_blank",rel:"noopener noreferrer",key:"footer-link"},D):f.createElement("span",{key:"footer-text"},D):null;return z.footer={text:le??void 0,buttons:[f.createElement(pc,{key:"new-chat-button"})]},z.chatWindow=Object.assign(Object.assign({},z.chatWindow),{defaultOpen:!!V}),z.event={rcbPreInjectMessage:!0,rcbPostInjectMessage:!0,rcbUserSubmitText:!0,rcbChangePath:!0,rcbToggleChatWindow:!0},z},[h,w,E,m,C,k,V,Q,j,x,D,I]),Ue=f.useRef(null),Se=function(z){let q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return f.useMemo(()=>{const le=(ne,me)=>{if(z.current){const fe=getComputedStyle(z.current).getPropertyValue(ne);if(fe&&fe.trim()!=="")return fe.trim();if(z.current.parentElement){const ce=getComputedStyle(z.current.parentElement).getPropertyValue(ne);if(ce&&ce.trim()!=="")return ce.trim()}}return me};return{primaryColor:le("--primaryColor",q.primaryColor),secondaryColor:le("--secondaryColor",q.secondaryColor),fontFamily:le("--fontFamily",q.fontFamily)}},[z,q])}(Ue,re.general);((z,q)=>{f.useEffect(()=>{q.current&&(z?q.current.classList.add("bot-logged-in"):q.current.classList.remove("bot-logged-in"))},[z,q])})(j!==!1,Ue),(z=>{let{settings:q,themeColors:le}=z;f.useEffect(()=>{le&&(Object.entries(le).forEach(ne=>{let[me,fe]=ne;fe&&document.documentElement.style.setProperty(`--${me}`,fe)}),le.primaryColor&&document.documentElement.style.setProperty("--rcb-header-background",le.primaryColor),le.secondaryColor&&document.documentElement.style.setProperty("--rcb-header-background-hover",le.secondaryColor))},[le]),f.useEffect(()=>{var ne,me;!((ne=q.header)===null||ne===void 0)&&ne.title&&typeof q.header.title=="string"&&(q.header.title=f.createElement("div",{key:"header-title"},f.createElement("h1",{className:"sr-only"},q.header.title),f.createElement("span",{"aria-hidden":"true"},q.header.title))),q.device={desktopEnabled:!0,mobileEnabled:!0,applyMobileOptimizations:!1},q.chatHistory={disabled:!0},q.chatButton=Object.assign(Object.assign({},q.chatButton),{icon:(me=q.header)===null||me===void 0?void 0:me.avatar}),q.event=Object.assign(Object.assign({},q.event),{rcbToggleChatWindow:!0})},[q])})({settings:re,themeColors:Se});const xe=f.useMemo(()=>{const z=(le=>{let{endpoint:ne,ratingEndpoint:me,agentRatingEndpoint:fe,apiKey:ce,sessionId:Me,isResetting:De=()=>!1,isLoggedIn:Ft,allowAnonAccess:Ee=!1,loginUrl:$e="/login",trackEvent:be,getTurnstileToken:ut,resetTurnstileToken:Rt,backendId:zt,resourceContext:wt}=le;if(Ft===!1&&!Ee)return be==null||be({type:"chatbot_login_prompt_shown"}),{qa_loop:{message:"To ask questions, please log in first.",component:f.createElement(ZA,{loginUrl:$e}),chatDisabled:!0,path:"qa_loop"}};let T=null,G=null,X=!1;const W={siteKey:null,token:null,pendingQuery:null,needsChallenge:!1};let oe=null;if(!ne)throw new Error("Q&A endpoint is required");return{qa_loop:{message:async Ae=>{var Ye;oe=Ae.injectMessage.bind(Ae);const{userInput:ye}=Ae;if((!De||!De())&&ye&&ye.trim()!==""){if(ye==="👍 Helpful"||ye==="👎 Not helpful"){if(T){const de=ye==="👍 Helpful",_e=G==="agent"?fe:me;if(_e)try{const ie={"Content-Type":"application/json"};ce&&(ie["X-API-KEY"]=ce);const he=Me();he&&(ie["X-Session-ID"]=he,ie["X-Query-ID"]=T),await fetch(_e,{method:"POST",headers:ie,credentials:"include",body:JSON.stringify(G==="agent"?{query_id:T,rating:de?"helpful":"not_helpful",session_id:he}:{sessionId:he,queryId:T,rating:de?1:0})}),be==null||be({type:"chatbot_rating_sent",queryId:T,rating:de?"helpful":"not_helpful"})}catch(ie){Be("Error sending feedback:",ie)}}return"Thanks for the feedback!"}try{const de=ei();T=de,be==null||be({type:"chatbot_question_sent",queryId:de,questionLength:ye.length});const _e={"Content-Type":"application/json"};ce&&(_e["X-API-KEY"]=ce);const ie=Me();ie&&(_e["X-Session-ID"]=ie,_e["X-Query-ID"]=de),_e["X-Origin"]=wt||"access";const he={query:ye,question_id:de};ie&&(he.session_id=ie),zt&&(he._backend=zt),wt&&(he.rp_name=wt);const Oe=ut==null?void 0:ut();Oe&&(he.turnstile_token=Oe),Qn("SENT to API",{session_id:ie,question_id:de});const cn=Date.now(),bt=await fetch(ne,{method:"POST",headers:_e,credentials:"include",body:JSON.stringify(he)});if(!bt.ok)throw new Error(`API returned ${bt.status}`);if((bt.headers.get("content-type")||"").includes("text/event-stream")){Rt==null||Rt();const Fn=(Ye=bt.body)===null||Ye===void 0?void 0:Ye.getReader();if(!Fn)throw new Error("Response body is not readable");const qr=new TextDecoder;let at="",ft="",Ct=!1;try{for(;;){const{done:Pt,value:lt}=await Fn.read();if(Pt)break;at+=qr.decode(lt,{stream:!0});let Gt=at.indexOf(`
40
+ `)}`}function yc(e){let{getState:t,onResubmit:r,trackEvent:n,loginUrl:o}=e;var A,a;const[s,i]=f.useState(null),[l,c]=f.useState(0),d=t(),u=(A=vi)!==null&&A!==void 0?A:{},p=u.VITE_FORCE_TURNSTILE_WIDGET==="true",g=(a=d.siteKey)!==null&&a!==void 0?a:p?u.VITE_TURNSTILE_SITE_KEY:null;return g&&(p||s!==g)?f.createElement(mc,{key:l,siteKey:g,loginUrl:o,onVerify:async v=>{const h=g;d.token=v,n==null||n({type:"chatbot_turnstile_completed"}),await r(v)==="needs_another_challenge"?c(w=>w+1):i(h)},onError:(v,h)=>{var w;const E=(w=d.pendingQuery)===null||w===void 0?void 0:w.queryId,m=g;d.token=null,d.pendingQuery=null,d.needsChallenge=!1,d.siteKey=null,i(m),n==null||n({type:"chatbot_turnstile_error",queryId:E,failureReason:v,cloudflareErrorCode:h})}}):null}const vc="#1a5b6e",wc="#107180",bc="Arial, sans-serif",ci="Q&A Bot",Ec="/chat-icon.svg",Cc="Type your question here...",Pc="Select an option to continue",Sc=!1,kc="Ask me a question!",ui="/login",Dc={general:{showHeader:!0,showFooter:!0},tooltip:{mode:"CLOSE"},chatInput:{disabled:!1,characterLimit:5e3,showCharacterCount:!1,allowNewline:!0,blockSpam:!1},chatWindow:{defaultOpen:!1,showScrollbar:!1},botBubble:{simulateStream:!0,streamSpeed:10,showAvatar:!1},userBubble:{showAvatar:!1},notification:{disabled:!0,showCount:!1},audio:{disabled:!0},emoji:{disabled:!0},fileAttachment:{disabled:!0}},Lr=f.forwardRef((e,t)=>{var r,n,o;const{apiKey:A,qaEndpoint:a,ratingEndpoint:s,capabilitiesEndpoint:i,agentRatingEndpoint:l,welcomeMessage:c,open:d,onOpenChange:u,isLoggedIn:p,allowAnonAccess:g=!1,actingUser:v,primaryColor:h,secondaryColor:w,botName:E,logo:m,placeholder:C,errorMessage:k,embedded:S,footerText:D,footerLink:I,tooltipText:Q,loginUrl:x,turnstileSiteKey:N,backendId:B,resourceContext:_,customFlow:U,onAnalyticsEvent:O}=e,F=f.useRef(`bot_${Math.random().toString(36).substr(2,9)}`);f.useEffect(()=>{sc()},[]);const M=f.useRef(null);M.current===null&&(M.current=ri(),Qn("CREATED",M.current));const L=f.useRef(!1),y=f.useRef({getSessionId:()=>M.current,isResetting:()=>L.current}),Y=f.useRef(null),b=function(z,q){const[le,ne]=f.useState(null),[me,fe]=f.useState("idle"),ce=f.useRef(null),Me=f.useRef(null),De=f.useRef(!0),Ft=f.useCallback(()=>{const Ee=window.turnstile;if(Me.current&&(Ee!=null&&Ee.remove)){try{Ee.remove(Me.current)}catch{}Me.current=null}ce.current&&(ce.current.remove(),ce.current=null)},[]);return f.useEffect(()=>{if(De.current=!0,!z)return fe("idle"),void ne(null);fe("loading");const Ee=document.createElement("div");return Ee.style.position="fixed",Ee.style.left="-9999px",Ee.style.top="-9999px",Ee.style.width="0",Ee.style.height="0",Ee.style.overflow="hidden",Ee.setAttribute("aria-hidden","true"),document.body.appendChild(Ee),ce.current=Ee,ai().then(()=>{if(!De.current)return;const $e=window.turnstile;if(!$e||!ce.current)return Be("Turnstile API not available for silent verification"),fe("failed"),void(q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"api_unavailable"}));const be=$e.render(ce.current,{sitekey:z,execution:"render","refresh-expired":"auto",callback:ut=>{De.current&&(on("Silent verification succeeded"),ne(ut),fe("verified"))},"error-callback":ut=>!De.current||(Be("Turnstile silent verification failed:",ut),ne(null),fe("failed"),q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"widget_error",cloudflareErrorCode:ut}),!0),"expired-callback":()=>{De.current&&(on("Token expired, awaiting refresh"),ne(null),fe("loading"))}});Me.current=be}).catch($e=>{De.current&&(Be("Failed to load Turnstile script for silent verification:",$e),fe("failed"),q==null||q({type:"chatbot_turnstile_silent_failed",failureReason:"script_load_failed"}))}),()=>{De.current=!1,Ft()}},[z,Ft]),{token:le,status:me,reset:f.useCallback(()=>{const Ee=window.turnstile;Me.current&&(Ee!=null&&Ee.reset)&&(ne(null),fe("loading"),Ee.reset(Me.current),on("Token consumed, resetting widget for fresh token"))},[])}}(N,z=>{var q;(q=Y.current)===null||q===void 0||q.call(Y,z)}),J=f.useRef(null);J.current=b.token;const[j,K]=f.useState(p);f.useEffect(()=>{K(p)},[p]);const V=S!==void 0?S:Sc,ae=f.useCallback(z=>{var q;O&&O(Object.assign(Object.assign({},z),{timestamp:Date.now(),sessionId:(q=M.current)!==null&&q!==void 0?q:void 0,pageUrl:typeof window<"u"?window.location.href:void 0,isEmbedded:V}))},[O,V]);f.useEffect(()=>{Y.current=z=>ae(z)},[ae]);const re=f.useMemo(()=>{const z=Object.assign({},Dc);z.general=Object.assign(Object.assign({},z.general),{primaryColor:h||vc,secondaryColor:w||wc,fontFamily:bc,embedded:V});const q=j===!1?[f.createElement(ZA,{key:"login-button",loginUrl:x||ui,isHeaderButton:!0})]:[f.createElement(dc,{key:"history-button"}),f.createElement($l,{key:"user-icon"})];z.header={title:f.createElement("span",{style:{fontSize:14,fontWeight:500}},E||ci),showAvatar:!0,avatar:m||Ec,buttons:[...q,we.CLOSE_CHAT_BUTTON]},z.chatInput=Object.assign(Object.assign({},z.chatInput),{disabled:!1,enabledPlaceholderText:C||Cc,disabledPlaceholderText:k||Pc}),z.tooltip=Object.assign(Object.assign({},z.tooltip),{text:Q||kc});const le=D?I?f.createElement("a",{href:I,target:"_blank",rel:"noopener noreferrer",key:"footer-link"},D):f.createElement("span",{key:"footer-text"},D):null;return z.footer={text:le??void 0,buttons:[f.createElement(pc,{key:"new-chat-button"})]},z.chatWindow=Object.assign(Object.assign({},z.chatWindow),{defaultOpen:!!V}),z.event={rcbPreInjectMessage:!0,rcbPostInjectMessage:!0,rcbUserSubmitText:!0,rcbChangePath:!0,rcbToggleChatWindow:!0},z},[h,w,E,m,C,k,V,Q,j,x,D,I]),Ue=f.useRef(null),Se=function(z){let q=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return f.useMemo(()=>{const le=(ne,me)=>{if(z.current){const fe=getComputedStyle(z.current).getPropertyValue(ne);if(fe&&fe.trim()!=="")return fe.trim();if(z.current.parentElement){const ce=getComputedStyle(z.current.parentElement).getPropertyValue(ne);if(ce&&ce.trim()!=="")return ce.trim()}}return me};return{primaryColor:le("--primaryColor",q.primaryColor),secondaryColor:le("--secondaryColor",q.secondaryColor),fontFamily:le("--fontFamily",q.fontFamily)}},[z,q])}(Ue,re.general);((z,q)=>{f.useEffect(()=>{q.current&&(z?q.current.classList.add("bot-logged-in"):q.current.classList.remove("bot-logged-in"))},[z,q])})(j!==!1,Ue),(z=>{let{settings:q,themeColors:le}=z;f.useEffect(()=>{le&&(Object.entries(le).forEach(ne=>{let[me,fe]=ne;fe&&document.documentElement.style.setProperty(`--${me}`,fe)}),le.primaryColor&&document.documentElement.style.setProperty("--rcb-header-background",le.primaryColor),le.secondaryColor&&document.documentElement.style.setProperty("--rcb-header-background-hover",le.secondaryColor))},[le]),f.useEffect(()=>{var ne,me;!((ne=q.header)===null||ne===void 0)&&ne.title&&typeof q.header.title=="string"&&(q.header.title=f.createElement("div",{key:"header-title"},f.createElement("h1",{className:"sr-only"},q.header.title),f.createElement("span",{"aria-hidden":"true"},q.header.title))),q.device={desktopEnabled:!0,mobileEnabled:!0,applyMobileOptimizations:!1},q.chatHistory={disabled:!0},q.chatButton=Object.assign(Object.assign({},q.chatButton),{icon:(me=q.header)===null||me===void 0?void 0:me.avatar}),q.event=Object.assign(Object.assign({},q.event),{rcbToggleChatWindow:!0})},[q])})({settings:re,themeColors:Se});const xe=f.useMemo(()=>{const z=(le=>{let{endpoint:ne,ratingEndpoint:me,agentRatingEndpoint:fe,apiKey:ce,sessionId:Me,isResetting:De=()=>!1,isLoggedIn:Ft,allowAnonAccess:Ee=!1,loginUrl:$e="/login",trackEvent:be,getTurnstileToken:ut,resetTurnstileToken:Rt,backendId:zt,resourceContext:wt}=le;if(Ft===!1&&!Ee)return be==null||be({type:"chatbot_login_prompt_shown"}),{qa_loop:{message:"To ask questions, please log in first.",component:f.createElement(ZA,{loginUrl:$e}),chatDisabled:!0,path:"qa_loop"}};let T=null,G=null,X=!1;const W={siteKey:null,token:null,pendingQuery:null,needsChallenge:!1};let oe=null;if(!ne)throw new Error("Q&A endpoint is required");return{qa_loop:{message:async Ae=>{var Ye;oe=Ae.injectMessage.bind(Ae);const{userInput:ye}=Ae;if((!De||!De())&&ye&&ye.trim()!==""){if(ye==="👍 Helpful"||ye==="👎 Not helpful"){if(T){const de=ye==="👍 Helpful",_e=G==="agent"?fe:me;if(_e)try{const ie={"Content-Type":"application/json"};ce&&(ie["X-API-KEY"]=ce);const he=Me();he&&(ie["X-Session-ID"]=he,ie["X-Query-ID"]=T),await fetch(_e,{method:"POST",headers:ie,credentials:"include",body:JSON.stringify(G==="agent"?{query_id:T,rating:de?"helpful":"not_helpful",session_id:he}:{sessionId:he,queryId:T,rating:de?1:0})}),be==null||be({type:"chatbot_rating_sent",queryId:T,rating:de?"helpful":"not_helpful"})}catch(ie){Be("Error sending feedback:",ie)}}return"Thanks for the feedback!"}try{const de=ei();T=de,be==null||be({type:"chatbot_question_sent",queryId:de,questionLength:ye.length});const _e={"Content-Type":"application/json"};ce&&(_e["X-API-KEY"]=ce);const ie=Me();ie&&(_e["X-Session-ID"]=ie,_e["X-Query-ID"]=de),_e["X-Origin"]=wt||"access";const he={query:ye,question_id:de};ie&&(he.session_id=ie),zt&&(he._backend=zt),wt&&(he.rp_name=wt);const Oe=ut==null?void 0:ut();Oe&&(he.turnstile_token=Oe),Qn("SENT to API",{session_id:ie,question_id:de});const cn=Date.now(),bt=await fetch(ne,{method:"POST",headers:_e,credentials:"include",body:JSON.stringify(he)});if(!bt.ok)throw new Error(`API returned ${bt.status}`);if((bt.headers.get("content-type")||"").includes("text/event-stream")){Rt==null||Rt();const Fn=(Ye=bt.body)===null||Ye===void 0?void 0:Ye.getReader();if(!Fn)throw new Error("Response body is not readable");const qr=new TextDecoder;let at="",ft="",Ct=!1;try{for(;;){const{done:Pt,value:lt}=await Fn.read();if(Pt)break;at+=qr.decode(lt,{stream:!0});let Gt=at.indexOf(`
41
41
 
42
42
  `);for(;Gt!==-1;){const tu=at.slice(0,Gt);at=at.slice(Gt+2);let Wt,Yt="",Rn="";for(const Le of tu.split(`
43
43
  `))Le.startsWith("event: ")?Yt=Le.slice(7):Le.startsWith("data: ")&&(Rn=Le.slice(6));if(Yt&&Rn){try{Wt=JSON.parse(Rn)}catch{ti("Failed to parse SSE data:",Rn),Gt=at.indexOf(`