var chatbox=document.getElementById("chatbox"),botchat=document.getElementById("botchat"),chatheader=document.getElementById("chatheader"),expandButton=chatheader.querySelector(".expand"),chatHeaderName=document.getElementById("chatheader-name"),chatHeaderPhoto=document.getElementById("chatheader-photo"),newChatButton=document.getElementById("newChatButton"),chatMessagesHydrated=!1,pendingNewChat=!1;function resetMessages(){const e=document.getElementById("messages");e&&(e.innerHTML="")}function normaliseMessageContent(e){if("string"==typeof e)return e;if(null==e)return"";if("object"==typeof e&&"Buffer"===e.type&&Array.isArray(e.data))try{return(new TextDecoder).decode(new Uint8Array(e.data))}catch(e){return""}return String(e)}function updateChatHeader(e,t){chatHeaderName&&e&&(chatHeaderName.textContent=e),chatHeaderPhoto&&t&&(chatHeaderPhoto.src=t)}function closeAlertOverlay(){document.body.classList.remove("overlay"),parent.document?.body.classList.remove("overlay");const e=document.querySelector(".modalo");e&&(e.innerHTML="")}function aichat_init(){chatMessagesHydrated||resetMessages(),connectWebSocket(),sessionStorage.setItem("chatOpened","true"),document.getElementById("botchat").classList.add("hide"),document.getElementById("chatbox").classList.remove("hide")}async function aichat_open_from_bubble(){try{await fetch("/ws-aichat-v2",{method:"GET",credentials:"same-origin"})}catch(e){console.log("Chat preflight request failed:",e)}aichat_init()}function aichat_minimize(){document.body.classList.contains("fullscreenchat")&&document.body.classList.remove("fullscreenchat"),document.getElementById("chatbox").classList.add("hide"),document.getElementById("botchat").classList.remove("hide"),sessionStorage.removeItem("chatOpened")}function chatTyping(){const e=(chatHeaderName?.textContent||"Agent").trim();var t=document.createElement("div");t.id="typingDiv",t.className="message-cont assistant",t.innerHTML=`${e} is typing`,document.getElementById("messages").appendChild(t),t.scrollIntoView()}function sendMessage(){var e=document.getElementById("userInput").value;if(e.length<=0)return;const t={role:"user",content:e};addMessage(t.role,JSON.stringify(t)),ws.send(e),chatTyping()}function addMessage(e,t){const n=JSON.parse(t);if("chat-reset"===n.type)return resetMessages(),chatMessagesHydrated=!1,void(document.getElementById("userInput").value="");if("agent-meta"===n.type)return void updateChatHeader(n.agentName,n.agentPhoto);const{role:a,buttons:s,choices:o}=n;let c=normaliseMessageContent(n.content);const d=document.getElementById("messages"),r=document.getElementById("typingDiv");chatMessagesHydrated=!0,r&&d.removeChild(r),c=c.replace(/\n/g,"
"),c=c.replace(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/g,'$1'),c=c.replace(/【\d+:\d+†source】/g,"");const i=document.createElement("div");if(""!==c&&(i.innerHTML=""+c+"",i.classList.add(a.toLowerCase()),i.classList.add("message-cont"),d.appendChild(i),document.querySelector("#chatbox #input")?.classList.remove("hide")),document.getElementById("userInput").value="",s&&s.length>0){const e=document.createElement("div");e.style.display="flex",e.style.gap="10px",e.style.alignItems="center",e.innerHTML=s.map((e=>`
${e}
`)).join(""),d.appendChild(e)}if(o&&o.length>0){const e=document.createElement("div");e.classList.add("multiple-choice"),o.forEach((t=>{const n=document.createElement("div");n.classList.add("choice"),n.textContent=t,n.addEventListener("click",(()=>choiceClick(t))),e.appendChild(n)})),d.appendChild(e)}i.scrollIntoView()}function choiceClick(e){if(String(e||"").toLowerCase().includes("learn more about your products"))return void modalOpen(document.getElementById("request-a-webchat"));const t=document.getElementById("messages").getElementsByClassName("multiple-choice");for(;t.length>0;)t[0].remove();const n={role:"user",content:e};addMessage(n.role,JSON.stringify(n)),ws.send(e),chatTyping()}function confirmNewChat(){showAlert("fa-question-circle","Are you sure?",' ',"#FFFFFF",!1)}function startNewChat(){if(closeAlertOverlay(),!ws||ws.readyState!==WebSocket.OPEN)return pendingNewChat=!0,void connectWebSocket();pendingNewChat=!1,ws.send(JSON.stringify({type:"new-chat"}))}let ws;function connectWebSocket(){if(ws&&(ws.readyState===WebSocket.OPEN||ws.readyState===WebSocket.CONNECTING))return;const e=`${"https:"===window.location.protocol?"wss":"ws"}://${window.location.host}/ws-aichat-v2`;ws=new WebSocket(e),ws.onopen=function(){console.log("Connected to WebSocket!"),chatMessagesHydrated=!1,resetMessages(),void 0!==pendingNewChat&&pendingNewChat&&(pendingNewChat=!1,ws.send(JSON.stringify({type:"new-chat"})))},ws.onmessage=function(e){addMessage("Agent",e.data)},ws.onerror=function(e){console.log("WebSocket error:",e)},ws.onclose=function(e){const t=e.wasClean?`Closed cleanly, code=${e.code}, reason=${e.reason}`:"Connection died";console.log(t),ws=null,setTimeout(connectWebSocket,5e3)}}document.getElementById("userInput").addEventListener("keypress",(function(e){13===(e.which||e.keyCode)&&(e.preventDefault(),sendMessage())})),expandButton.addEventListener("click",(function(){document.body.classList.contains("fullscreenchat")?document.body.classList.remove("fullscreenchat"):document.body.classList.add("fullscreenchat")})),newChatButton?.addEventListener("click",(function(){confirmNewChat()})),"true"===sessionStorage.getItem("chatOpened")&&aichat_init();