(()=>{const e=document.getElementById("advice-chat-cont"),t=document.getElementById("advice-chat-messages"),n=document.getElementById("advice-chat-input"),r=document.getElementById("advice-chat-submit");if(!(e&&t&&n&&r))return;let o=null,l=null,i=null,s=0,a=!1,c=!0;const d=2e4,p=1e3,u=15e3;function y(e){const t=String(null==e?"":e);let n=(r=t.replace(/\r\n/g,"\n"),String(null==r?"":r).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"));var r;n=n.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'$1'),n=n.replace(/(^|[\s(])(https?:\/\/[^\s)<>]+)/g,'$1$2'),n=n.replace(/\*\*([^*\n]+)\*\*/g,"$1"),n=n.replace(/__([^_\n]+)__/g,"$1"),n=n.replace(/`([^`\n]+)`/g,"$1");const o=n.split("\n"),l=[];let i=!1;for(const e of o){const t=e.match(/^\s*[-*]\s+(.+)$/);t?(i||(l.push(""),i=!1),l.push(e))}return i&&l.push(""),l.join("
")}function f(e,n,r){const o=document.createElement("div"),l="user"===String(e||"").toLowerCase();o.style.display="flex",o.style.justifyContent=l?"flex-end":"flex-start";const i=document.createElement("div");i.style.padding="10px 12px",i.style.margin="8px 0",i.style.borderRadius="10px",i.style.fontSize="14px",i.style.lineHeight="1.4",i.style.maxWidth="80%",i.style.wordBreak="break-word","update"===r?(o.style.justifyContent="center",i.style.background="#f8fafc",i.style.border="1px dashed #cbd5e1",i.style.color="#475569"):l?(i.style.background="#1c3867",i.style.color="#ffffff"):(i.style.background="#f1f5f9",i.style.color="#0f172a"),i.innerHTML=y(n),o.appendChild(i),t.appendChild(o),o.scrollIntoView({block:"end"})}function g(){const e=document.getElementById("advice-chat-typing");e&&e.remove()}function m(e){if(e.summaryText.trim()&&f("assistant",e.summaryText),!e.items.length)return;const n=document.createElement("div");n.style.display="flex",n.style.flexWrap="wrap",n.style.gap="8px",n.style.margin="8px 0",e.items.forEach((e=>n.appendChild(function(e){const t=document.createElement("div");t.style.width="160px",t.style.border="1px solid #e2e8f0",t.style.borderRadius="10px",t.style.overflow="hidden",t.style.background="#ffffff",t.style.display="flex",t.style.flexDirection="column";const n=String(e?.image||"").trim();if(n){const r=document.createElement("img");r.src=n,r.alt=String(e?.imageAlt||e?.productName||""),r.style.width="100%",r.style.height="110px",r.style.objectFit="cover",r.onerror=()=>r.remove(),t.appendChild(r)}const r=document.createElement("div");r.style.padding="8px 10px",r.style.display="flex",r.style.flexDirection="column",r.style.gap="4px",r.style.flex="1";const o=document.createElement("div");o.textContent=String(e?.productName||""),o.style.fontSize="13px",o.style.fontWeight="600",o.style.color="#0f172a",o.style.lineHeight="1.3",r.appendChild(o);const l=String(e?.price||"").trim();if(l){const e=document.createElement("div");e.textContent=l,e.style.fontSize="13px",e.style.fontWeight="700",e.style.color="#1c3867",r.appendChild(e)}const i=String(e?.productUrl||"").trim();if(i){const e=document.createElement("a");e.href=i,e.target="_blank",e.rel="noopener noreferrer",e.textContent="View product",e.style.marginTop="auto",e.style.padding="6px 8px",e.style.borderRadius="8px",e.style.background="#1c3867",e.style.color="#ffffff",e.style.fontSize="12px",e.style.fontWeight="600",e.style.textAlign="center",e.style.textDecoration="none",r.appendChild(e)}return t.appendChild(r),t}(e)))),t.appendChild(n),n.scrollIntoView({block:"end"})}function h(e){let o=null;try{o=JSON.parse(e)}catch(e){return}if("heartbeat"===o?.type||"heartbeat-ack"===o?.type)return;if("chat-reset"===o?.type)return void(t.innerHTML="");if("chat-input-state"===o?.type)return c=!1!==o.enabled,n.disabled=!c,void(r.disabled=!c);if("agent-typing"===o?.type||"ai-typing"===o?.type)return void function(e){let n=document.getElementById("advice-chat-typing");const r=String(e||"Agent").trim()||"Agent";if(!n){n=document.createElement("div"),n.id="advice-chat-typing",n.style.display="flex",n.style.justifyContent="flex-start";const e=document.createElement("div");e.style.padding="10px 12px",e.style.borderRadius="10px",e.style.fontSize="14px",e.style.lineHeight="1.4",e.style.background="#f1f5f9",e.style.color="#0f172a",e.className="advice-chat-typing-bubble",n.appendChild(e),t.appendChild(n)}const o=n.querySelector(".advice-chat-typing-bubble");o&&(o.textContent=`${r} is typing...`),n.scrollIntoView({block:"end"})}(o.agentName);if("agent-stop-typing"===o?.type||"ai-stop-typing"===o?.type)return void g();if("chat-ended"===o?.type)return g(),c=!1,n.disabled=!0,r.disabled=!0,void(o.agentName&&f("assistant",`${o.agentName} ended this chat.`,"update"));const l=o?.role;if(!l)return;g();const i=function(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)}(o.content);if(!i.trim())return;const s=function(e){let t=null;try{t=JSON.parse(e)}catch(e){return null}const n=t?.output_parsed||t;if(!n||!Array.isArray(n.rows))return null;const r=n.rows.flatMap((e=>Array.isArray(e?.items)?e.items:[]));return{summaryText:String(n.summaryText||""),items:r}}(i);s?m(s):f(l,i)}function x(){if(o&&(o.readyState===WebSocket.OPEN||o.readyState===WebSocket.CONNECTING))return;const e=function(){const e=String(window.CHAT_WS_HOST||"").trim();return e?e.replace(/^wss?:\/\//i,"").replace(/\/+$/,""):"dev.galatent.co.uk"===String(window.location.hostname||"").trim().toLowerCase()?"localhost:8484":"chat.ws.galatent.co.uk"}(),t=function(e){const t=String(e||"").toLowerCase();return t.startsWith("localhost")||t.startsWith("127.0.0.1")?"ws":"wss"}(e),n=function(e){const t=`; ${document.cookie||""}`.split(`; ${e}=`);return 2===t.length?decodeURIComponent(t.pop().split(";").shift()||""):""}("connect.tid");o=new WebSocket(`${t}://${e}/ws-aichat-v2`),o.onopen=function(){s=0,i&&(clearTimeout(i),i=null),l&&clearInterval(l),l=setInterval((()=>{o&&o.readyState===WebSocket.OPEN&&o.send(JSON.stringify({type:"heartbeat",ts:Date.now()}))}),d),o.send(JSON.stringify({type:"customer-mode-config",mode:"search-chat",bypassProfile:!0,bypassInitialChoice:!0,hideFromAgentDashboard:!0})),n&&o.send(JSON.stringify({type:"session-id",sessionId:n}))},o.onmessage=function(e){h(e.data)},o.onclose=function(){l&&(clearInterval(l),l=null),o=null;const e=Math.min(u,p*Math.pow(2,s)),t=Math.floor(500*Math.random());s+=1,i=setTimeout(x,e+t)}}function b(){a||(a=!0,x())}function v(){const e=String(n.value||"").trim();e&&c&&o&&o.readyState===WebSocket.OPEN&&(f("user",e),o.send(e),n.value="")}n.addEventListener("focus",b,{once:!0}),n.addEventListener("click",b,{once:!0}),n.addEventListener("keydown",(e=>{"Enter"===e.key&&(e.preventDefault(),v())})),r.addEventListener("click",(()=>{b(),v()}))})();