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"),currentAgentName=(chatHeaderName?.textContent||"").trim(),newChatButton=document.getElementById("newChatButton"),chatUploadButton=document.getElementById("chatUploadButton"),chatFileInput=document.getElementById("chatFileInput"),chatEmojiButton=document.getElementById("chatEmojiButton"),chatEmojiPicker=document.getElementById("chatEmojiPicker"),chatMessagesHydrated=!1,pendingNewChat=!1,currentChatSessionId="",agentImageRenderDelayMs=450,chatEmojiList=["๐Ÿ˜Š","๐Ÿ˜„","๐Ÿ˜ƒ","๐Ÿ˜","๐Ÿ˜‚","๐Ÿคฃ","๐Ÿ™‚","๐Ÿ˜‰","๐Ÿ˜","๐Ÿคฉ","๐Ÿ˜Ž","๐Ÿค”","๐Ÿ˜ฎ","๐Ÿ˜ข","๐Ÿ™","๐Ÿ‘","๐Ÿ‘Ž","๐Ÿ‘","๐Ÿ‘‹","โค๏ธ","๐Ÿ’™","๐Ÿ’š","๐Ÿ’›","๐Ÿงก","๐Ÿ”ฅ","โœจ","โœ…","โŒ","โš ๏ธ","โ›บ","๐Ÿ•๏ธ","๐Ÿท๏ธ","๐Ÿ› ๏ธ","๐Ÿ”ง","๐Ÿงต","๐Ÿ“","๐ŸŽจ","๐Ÿ–จ๏ธ","๐ŸŽ‰","๐ŸŽˆ","๐ŸŽช","๐ŸŽŠ","๐Ÿป","๐Ÿฝ๏ธ","๐ŸŒง๏ธ","โ˜”","๐ŸŒฆ๏ธ","โ˜€๏ธ","๐ŸŒค๏ธ","๐Ÿ’จ","โ„๏ธ","๐Ÿ“ฆ","๐Ÿšš","๐Ÿ“","๐Ÿ—บ๏ธ","๐Ÿ“ธ","๐Ÿ’ฌ","๐Ÿ“ž","๐Ÿ“ง","๐Ÿงพ","๐Ÿ“…","โฑ๏ธ","๐Ÿ’ท","๐Ÿ’ณ"];function escapeHtml(e){return String(null==e?"":e).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}function getChatCookieValue(e){const t=`; ${document.cookie||""}`.split(`; ${e}=`);return 2===t.length?decodeURIComponent(t.pop().split(";").shift()||""):""}function setInputVisible(e){const t=document.querySelector("#chatbox #input");t&&(e?t.classList.remove("hide"):t.classList.add("hide"))}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 getAgentDisplayName(e){const t=String(e||"").trim().replace(/\s+/g," ");if(!t)return"";const n=t.toLowerCase();if(/\b(agent|ai|service)\b/.test(n))return t;const a=t.split(" ");return a.length<=1?t:a[0]}function updateChatHeader(e,t){const n=getAgentDisplayName(e);chatHeaderName&&n&&(chatHeaderName.textContent=n,currentAgentName=n),chatHeaderPhoto&&t&&(chatHeaderPhoto.src=t)}function addUpdateMessage(e){const t=document.getElementById("messages");if(!t)return;const n=String(e||"").trim();if(!n)return;const a=document.createElement("div");a.classList.add("message-cont","update"),a.innerHTML=`${escapeHtml(n)}`,t.appendChild(a),a.scrollIntoView()}function closeAlertOverlay(){document.body.classList.remove("overlay"),parent.document?.body.classList.remove("overlay");const e=document.querySelector(".modalo");e&&(e.innerHTML="")}function aichat_init(){if(chatMessagesHydrated){setInputVisible(!!!document.querySelector("#messages .customer-profile-prompt"))}else resetMessages(),setInputVisible(!1);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 showAgentTyping(e){const t=document.getElementById("messages");if(!t)return;const n=document.getElementById("typingDiv");if(n){const t=n.querySelector(".typing-indicator");if(t){const n=getAgentDisplayName(e||(chatHeaderName?.textContent||"Agent").trim());t.textContent=`${n||"Agent"} is typing...`}return}const a=document.createElement("div");a.id="typingDiv",a.className="message-cont assistant";const o=getAgentDisplayName(e||(chatHeaderName?.textContent||"Agent").trim());a.innerHTML=`${o||"Agent"} is typing...`,t.appendChild(a),a.scrollIntoView()}function hideAgentTyping(){const e=document.getElementById("messages"),t=document.getElementById("typingDiv");e&&t&&e.removeChild(t)}function removeCustomerProfilePrompt(){const e=document.getElementById("messages");if(!e)return;e.querySelectorAll(".customer-profile-prompt").forEach((e=>e.remove()))}function renderCustomerProfilePrompt(e){const t=document.getElementById("messages");if(!t)return;removeCustomerProfilePrompt();const n=document.createElement("div");n.classList.add("customer-profile-prompt"),n.style.display="flex",n.style.justifyContent="center",n.style.width="100%",n.style.margin="10px 0 14px";const a=e.form||{},o=Array.isArray(a.fields)?a.fields:[],s=String(a.submitType||"customer-profile-submit"),i=String(a.submitLabel||"Start Chat"),r=document.createElement("div");r.classList.add("message-cont","assistant"),r.style.display="block",r.style.width="100%",r.style.maxWidth="360px",r.style.padding="14px 14px 12px",r.style.borderRadius="12px",r.style.background="#f7fbff",r.style.border="1px solid #d7e7f6",r.style.boxShadow="0 1px 3px rgba(0,0,0,0.08)";const c=document.createElement("div");c.style.marginBottom="10px",c.style.fontWeight="600",c.style.lineHeight="1.3",c.style.color="#1b3f66",c.style.textAlign="center",c.textContent=e.content||"Before we start, please complete this quick form:",r.appendChild(c);const l=document.createElement("form");l.className="gt-chat-profile-form",l.style.margin="0 auto",l.style.maxWidth="300px",o.forEach((e=>{const t=String(e.key||"").trim();if(!t)return;const n=document.createElement("div");n.className="form-group",n.style.marginBottom="10px";const a=document.createElement("label");a.textContent=e.label||t,a.style.fontSize="13px",a.style.fontWeight="600",a.style.marginBottom="5px",a.style.color="#244d78",n.appendChild(a);const o=document.createElement("input");o.className="form-control",o.name=t,o.type=e.inputType||"text",o.placeholder=e.placeholder||"",o.required=!1!==e.required,n.appendChild(o),l.appendChild(n)}));const d=document.createElement("button");d.type="submit",d.className="btn btn-primary",d.textContent=i,d.style.display="block",d.style.width="100%",d.style.marginTop="4px",d.style.borderRadius="22px",d.style.fontWeight="700",d.style.padding="8px 12px",l.appendChild(d),l.addEventListener("submit",(function(e){if(e.preventDefault(),!ws||ws.readyState!==WebSocket.OPEN)return void alert("Connection is not ready. Please try again in a moment.");const t={type:s};o.forEach((e=>{const n=String(e.key||"").trim();if(!n)return;const a=l.elements[n]?String(l.elements[n].value||"").trim():"";t[n]=a})),t.name&&t.email&&t.phone?(ws.send(JSON.stringify(t)),d.disabled=!0,d.textContent="Submitting..."):alert("Please complete name, email, and phone.")})),r.appendChild(l),n.appendChild(r),t.appendChild(n),n.scrollIntoView(),setInputVisible(!1)}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),closeChatEmojiPicker()}function insertTextAtCursor(e,t){if(!e)return;const n=e.selectionStart||0,a=e.selectionEnd||0,o=e.value||"";e.value=o.slice(0,n)+t+o.slice(a);const s=n+t.length;e.setSelectionRange(s,s),e.focus()}function closeChatEmojiPicker(){chatEmojiPicker&&chatEmojiPicker.classList.remove("open")}function toggleChatEmojiPicker(){chatEmojiPicker&&chatEmojiPicker.classList.toggle("open")}function initChatEmojiPicker(){chatEmojiPicker&&(chatEmojiPicker.innerHTML="",chatEmojiList.forEach((function(e){const t=document.createElement("button");t.type="button",t.className="chat-emoji-option",t.textContent=e,t.addEventListener("click",(function(){insertTextAtCursor(document.getElementById("userInput"),e),closeChatEmojiPicker()})),chatEmojiPicker.appendChild(t)})))}async function uploadChatFile(e){if(!e)return null;const t=new FormData;t.append("chatFile",e);const n=(currentChatSessionId||"").trim()||getChatCookieValue("connect.tid");n&&(t.append("sessionId",n),t.append("chatSessionId",n));const a=await fetch("/chat-v2/upload-file",{method:"POST",credentials:"same-origin",headers:n?{"x-chat-session-id":n}:void 0,body:t});if(!a.ok)throw new Error("Upload failed");const o=await a.json();if(!o?.ok||!o?.file?.url||!o?.file?.name)throw new Error("Invalid upload response");return o.file}function renderFileMessage(e,t){const n=t?.file||{},a=String(n.url||"").trim(),o=escapeHtml(n.name||"File"),s=String(n.mimeType||"").toLowerCase(),i=String(t?.role||"").toLowerCase(),r=i&&"user"!==i;if(!a)return!1;const c=s.startsWith("image/");let l=`${o}`;if(c){const t=`${o}
${o}
`;if(r)return e.innerHTML=`${o}
Loading image...
`,setTimeout((()=>{e.isConnected&&(e.innerHTML=t)}),agentImageRenderDelayMs),!0;l=t}return e.innerHTML=l,!0}function addMessage(e,t){const n=JSON.parse(t);if("heartbeat"===n?.type||"heartbeat-ack"===n?.type)return;if("chat-reset"===n.type)return resetMessages(),chatMessagesHydrated=!1,document.getElementById("userInput").value="",void setInputVisible(!1);if("session-id"===n.type)return void(currentChatSessionId=String(n.sessionId||"").trim());if("session-id-required"===n.type)return n.error&&console.log(n.error),void setInputVisible(!1);if("customer-profile-request"===n.type)return renderCustomerProfilePrompt(n),void(chatMessagesHydrated=!0);if("customer-profile-ok"===n.type)return removeCustomerProfilePrompt(),void setInputVisible(!0);if("customer-profile-error"===n.type||"customer-profile-required"===n.type)return void(n.error&&alert(n.error));if("customer-profile"===n.type)return;if("agent-typing"===n.type)return void showAgentTyping(n.agentName);if("agent-stop-typing"===n.type)return void hideAgentTyping();if("ai-typing"===n.type)return void showAgentTyping(n.agentName);if("ai-stop-typing"===n.type)return void hideAgentTyping();if("agent-meta"===n.type){const e=getAgentDisplayName(n.agentName),t=getAgentDisplayName(currentAgentName||(chatHeaderName?.textContent||"").trim());return updateChatHeader(n.agentName,n.agentPhoto),void(e&&t&&e!==t&&chatMessagesHydrated&&addUpdateMessage(`${e} has taken over the chat.`))}const{role:a,buttons:o,choices:s}=n;if(!a)return;let i=normaliseMessageContent(n.content);const r=document.getElementById("messages");chatMessagesHydrated=!0,hideAgentTyping(),i=i.replace(/\n/g,"
"),i=i.replace(/\[([^\]]+)\]\((https?:\/\/[^\s]+)\)/g,'$1'),i=i.replace(/ใ€\d+:\d+โ€ sourceใ€‘/g,""),i=i.replace(/(^|[\s(])(https?:\/\/[^\s)<>]+)/g,'$1$2');const c=document.createElement("div");if(""!==i||"file-message"===n.type||"live-agent-file-message"===n.type){renderFileMessage(c,n)||(c.innerHTML=""+i+""),c.classList.add(a.toLowerCase()),c.classList.add("message-cont"),r.appendChild(c),setInputVisible(!0)}if(document.getElementById("userInput").value="",o&&o.length>0){const e=document.createElement("div");e.style.display="flex",e.style.gap="10px",e.style.alignItems="center",e.innerHTML=o.map((e=>`
${e}
`)).join(""),r.appendChild(e)}if(s&&s.length>0){const e=document.createElement("div");e.classList.add("multiple-choice"),s.forEach((t=>{const n=document.createElement("div");n.classList.add("choice"),n.textContent=t,n.addEventListener("click",(()=>choiceClick(t))),e.appendChild(n)})),r.appendChild(e)}c.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)}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;document.getElementById("userInput").addEventListener("keypress",(function(e){13===(e.which||e.keyCode)&&(e.preventDefault(),sendMessage())})),chatUploadButton?.addEventListener("click",(function(){chatFileInput&&(chatFileInput.value="",chatFileInput.click())})),chatEmojiButton?.addEventListener("click",(function(e){e.preventDefault(),e.stopPropagation(),toggleChatEmojiPicker()})),document.addEventListener("click",(function(e){chatEmojiPicker&&chatEmojiButton&&(chatEmojiPicker.contains(e.target)||chatEmojiButton.contains(e.target)||closeChatEmojiPicker())})),chatFileInput?.addEventListener("change",(async function(){const e=chatFileInput.files&&chatFileInput.files[0];if(!e)return;if(!ws||ws.readyState!==WebSocket.OPEN)return void alert("Connection is not ready. Please try again in a moment.");const t=chatUploadButton?chatUploadButton.textContent:"";chatUploadButton&&(chatUploadButton.disabled=!0,chatUploadButton.textContent="...");try{const t=await uploadChatFile(e);ws.send(JSON.stringify({type:"customer-file-message",file:t}))}catch(e){alert("File upload failed. Please try again.")}finally{chatUploadButton&&(chatUploadButton.disabled=!1,chatUploadButton.textContent=t||"+"),chatFileInput.value=""}})),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(),initChatEmojiPicker();let chatHeartbeatTimer=null;const HEARTBEAT_INTERVAL_MS=2e4;function getCookieValue(e){const t=`; ${document.cookie||""}`.split(`; ${e}=`);return 2===t.length?decodeURIComponent(t.pop().split(";").shift()||""):""}function resolveChatWsHost(){const e=String(window.CHAT_WS_HOST||"").trim();if(e)return e.replace(/^wss?:\/\//i,"").replace(/\/+$/,"");return"dev.galatent.co.uk"===String(window.location.hostname||"").trim().toLowerCase()?"localhost:8484":"chat.ws.galatent.co.uk"}function resolveChatWsProtocol(e){const t=String(e||"").toLowerCase();return t.startsWith("localhost")||t.startsWith("127.0.0.1")?"ws":"wss"}function connectWebSocket(){if(ws&&(ws.readyState===WebSocket.OPEN||ws.readyState===WebSocket.CONNECTING))return;const e=resolveChatWsHost(),t=`${resolveChatWsProtocol(e)}://${e}/ws-aichat-v2`;ws=new WebSocket(t),window.ws=ws,window.chatSocket=ws,ws.onopen=function(){console.log("Connected to WebSocket!"),chatHeartbeatTimer&&(clearInterval(chatHeartbeatTimer),chatHeartbeatTimer=null),chatHeartbeatTimer=setInterval((()=>{ws&&ws.readyState===WebSocket.OPEN&&ws.send(JSON.stringify({type:"heartbeat",ts:Date.now()}))}),HEARTBEAT_INTERVAL_MS),chatMessagesHydrated=!1,resetMessages();const e=getCookieValue("connect.tid");e&&ws.send(JSON.stringify({type:"session-id",sessionId:e})),void 0!==pendingNewChat&&pendingNewChat&&(pendingNewChat=!1,ws.send(JSON.stringify({type:"new-chat"})))},ws.onmessage=function(e){let t=null;try{t=JSON.parse(e.data)}catch(e){t=null}"heartbeat-ack"!==t?.type&&addMessage("Agent",e.data)},ws.onerror=function(e){console.log("WebSocket error:",{message:e?.message||"Unknown websocket error",readyState:ws?ws.readyState:null,url:t})},ws.onclose=function(e){console.log("WebSocket closed:",{code:e.code,reason:e.reason||"",wasClean:e.wasClean,url:t}),chatHeartbeatTimer&&(clearInterval(chatHeartbeatTimer),chatHeartbeatTimer=null),ws=null,window.ws&&window.ws.readyState===WebSocket.CLOSED&&(window.ws=null),window.chatSocket&&window.chatSocket.readyState===WebSocket.CLOSED&&(window.chatSocket=null),setTimeout(connectWebSocket,5e3)}}