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}`;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=>`