(function(){var currentScript=document.currentScript||function(){var scripts=document.getElementsByTagName("script");return scripts[scripts.length-1]}();var assistantId=currentScript.getAttribute("data-assistant-id")||"";var userId=currentScript.getAttribute("data-user-id");var origin=currentScript.getAttribute("data-origin");var type=currentScript.getAttribute("data-type");var iframe=document.createElement("iframe");iframe.id="chatbot-widget-iframe-prod";var currentPosition="Right";var isKioskFullScreen=false;var isMobile=window.innerWidth<768;var originalBodyOverflow=document.body&&document.body.style.overflow||"";var originalViewportContent="";var viewportMetaTag=null;var messageQueue=[];var isIframeReady=false;var maxQueueSize=50;function initializeViewportControl(){viewportMetaTag=document.querySelector('meta[name="viewport"]');if(viewportMetaTag){originalViewportContent=viewportMetaTag.getAttribute("content")||""}else{viewportMetaTag=document.createElement("meta");viewportMetaTag.name="viewport";viewportMetaTag.content="width=device-width, initial-scale=1.0";document.head.appendChild(viewportMetaTag);originalViewportContent=viewportMetaTag.content}console.log("[chat-widget] Viewport control initialized with original content:",originalViewportContent);setTimeout(sendUrlContextToIframe,5e3)}function updateViewportScale(isMinimized,isMobileMode){if(!viewportMetaTag)return;if(isMobileMode&&!isMinimized){viewportMetaTag.setAttribute("content","width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no");console.log("[chat-widget] Viewport scaling disabled for mobile widget expansion")}else{viewportMetaTag.setAttribute("content",originalViewportContent);console.log("[chat-widget] Viewport scaling restored to original settings")}}initializeViewportControl();function constructNavigationUrl(bbasePath){try{const rootUrl=window.location.origin;const navigationUrl=rootUrl+bbasePath;console.log("[chat-widget] Constructed navigation URL:",navigationUrl);return navigationUrl}catch(error){console.error("[chat-widget] Error constructing navigation URL:",error);return null}}function detectUrlContext(){var currentUrl=window.location.href;var pathname=window.location.pathname;var productMatch=pathname.match(/\/products\/([^\/\?#]+)/);if(productMatch){return{type:"product",fullPath:pathname,url:currentUrl,timestamp:Date.now()}}return{type:"none",timestamp:Date.now()}}function sendUrlContextToIframe(){if(!iframe.contentWindow){console.log("[chat-widget] Iframe not ready for URL context message");return}var context=detectUrlContext();iframe.contentWindow.postMessage({type:"URL_CONTEXT_UPDATE",context:context},origin);console.log("[chat-widget] Sending URL context to iframe:",{type:"URL_CONTEXT_UPDATE",context:context},origin)}function sendShopifyTrackEvent(eventData){try{iframe.contentWindow.postMessage({type:"SHOPIFY_TRACK_EVENT",data:eventData},origin);console.log("[chat-widget] SHOPIFY_TRACK_EVENT sent to iframe:",eventData)}catch(error){console.error("[chat-widget] Error sending SHOPIFY_TRACK_EVENT:",error)}}function processQueuedMessages(){if(messageQueue.length===0){return}console.log("[chat-widget] Processing",messageQueue.length,"queued SHOPIFY_TRACK_EVENT messages");while(messageQueue.length>0){var queuedMessage=messageQueue.shift();sendShopifyTrackEvent(queuedMessage.data)}console.log("[chat-widget] All queued messages processed")}function checkIframeReadiness(){if(!isIframeReady&&iframe.contentWindow&&messageQueue.length>0){console.log("[chat-widget] Iframe became ready via fallback check");isIframeReady=true;processQueuedMessages()}}var readinessCheckInterval=setInterval(function(){if(isIframeReady){clearInterval(readinessCheckInterval);return}checkIframeReadiness()},2e3);setTimeout(function(){clearInterval(readinessCheckInterval)},3e4);var currentSettings={width:420,height:830,isMobile:isMobile};var currentWidgetState={isMinimized:true,isSmallWidth:false,dimensions:{width:0,height:0}};function updateIframePosition(position,isMobile,isMinimized){if(position!=="Left"&&position!=="Right"){position="Right"}iframe.style.left="";iframe.style.right="";if(isMinimized){if(position==="Left"){iframe.style.left=isMobile?"20px":"50px"}else{iframe.style.right=isMobile?"20px":"50px"}}else{if(isMobile){if(position==="Left"){iframe.style.left="0px"}else{iframe.style.right="0px"}}else{if(position==="Left"){iframe.style.left="50px"}else{iframe.style.right="50px"}}}currentPosition=position;console.log("[chat-widget] Widget position updated to:",position,"minimized:",isMinimized)}function handleSizeUpdate(){const wasMobile=isMobile;isMobile=window.innerWidth<768;currentSettings.isMobile=isMobile;updateIframeResponsive();updateBodyOverflow(currentWidgetState.isMinimized,currentSettings.isMobile);console.log("[chat-widget] Size update completed - Mobile state:",isMobile)}function updateIframeResponsive(){updateWidgetVisibility(currentWidgetState.isMinimized,currentWidgetState.dimensions);if(isMobile){iframe.style.bottom=currentWidgetState.isMinimized?"20px":"0px";updateIframePosition(currentPosition,isMobile,currentWidgetState.isMinimized)}else{iframe.style.bottom="40px";updateIframePosition(currentPosition,isMobile,currentWidgetState.isMinimized)}iframe.contentWindow.postMessage({type:"IFRAME_SIZE_UPDATE",width:isMobile?window.innerWidth:400,height:isMobile?window.innerHeight:700,isMobile:isMobile,siteUrl:window.location.href},"*");console.log("[chat-widget] Iframe responsive update completed")}iframe.style.position="fixed";iframe.style.bottom=isMobile?currentWidgetState.isMinimized?"20px":"0px":"40px";updateIframePosition(currentPosition,isMobile,currentWidgetState.isMinimized);iframe.style.zIndex="2147483647";iframe.style.webkitOverflowScrolling="touch";iframe.style.overflow="hidden";iframe.scrolling="no";iframe.allow="microphone; camera; autoplay; fullscreen; display-capture";iframe.setAttribute("playsinline","");iframe.src=type==="chatbot"?`${origin}/?type=${type}&preview=false&assistantId=${assistantId}&userId=${userId}&platform=ios&t=${Date.now()}`:`${origin}/?type=${type}&preview=false&userId=${userId}&platform=ios&t=${Date.now()}`;iframe.frameBorder="0";var isIOS=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream;iframe.onload=function(){updateIframeResponsive();updateViewportScale(currentWidgetState.isMinimized,currentSettings.isMobile);isIframeReady=true;processQueuedMessages()};function appendIframeToDOM(){if(document.body){document.body.appendChild(iframe)}else{if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",function(){document.body.appendChild(iframe)})}else{setTimeout(appendIframeToDOM,100)}}}appendIframeToDOM();function protectIframeStyles(){if(!isKioskFullScreen)return;iframe.style.width="100vw";iframe.style.height="100vh";const styleObserver=new MutationObserver(function(mutations){if(!isKioskFullScreen){styleObserver.disconnect();return}mutations.forEach(function(mutation){if(mutation.type==="attributes"&&(mutation.attributeName==="style"||mutation.attributeName==="class")){if(iframe.style.width!=="100vw"||iframe.style.height!=="100vh"){iframe.style.width="100vw";iframe.style.height="100vh";console.log("[chat-widget] Kiosk mode: Re-enforced full screen")}}})});styleObserver.observe(iframe,{attributes:true,attributeFilter:["style","class"]});console.log("[chat-widget] Kiosk mode: Style protection activated")}window.addEventListener("resize",handleSizeUpdate);if(isMobile){setTimeout(updateIframeResponsive,500);setTimeout(updateIframeResponsive,1500);setTimeout(updateIframeResponsive,2500)}window.addEventListener("message",function(event){if(event.origin===origin){if(event.data&&event.data.type==="REQUEST_SIZE_UPDATE"){console.log("[chat-widget] Received size update request");handleSizeUpdate()}if(event.data&&event.data.type==="REQUEST_SITE_URL"){console.log("[chat-widget] Received site URL request, timestamp:",event.data.timestamp);iframe.contentWindow.postMessage({type:"SITE_URL_RESPONSE",siteUrl:window.location.href,timestamp:Date.now()},origin)}if(event.data&&typeof event.data.widgetPosition!=="undefined"){var widgetPosition=event.data.widgetPosition;console.log("[chat-widget] Widget position received:",widgetPosition);updateIframePosition(widgetPosition,isMobile,currentWidgetState.isMinimized)}if(event.data&&event.data.siteUrl){var siteUrl=event.data.siteUrl;console.log("[chat-widget] Received site URL:",siteUrl)}if(event.data&&event.data.type==="navigate"&&event.data.url){console.log("[chat-widget] Received navigation request:",event.data.url);if(typeof event.data.url==="string"&&event.data.url.length>0){window.location.href=event.data.url}}if(event.data&&event.data.type==="CHECKOUT_REDIRECT"){console.log("[chat-widget] Received checkOUT_REDIRECT:",event.data);const cartUrl=constructNavigationUrl("/cart");if(cartUrl){console.log("[chat-widget] Navigating to cart URL:",cartUrl);window.location.href=cartUrl}else{console.error("[chat-widget] Failed to construct cart URL");window.location.href=window.location.href+"/cart"}}if(event.data&&event.data.type==="WIDGET_STATE_CHANGE"){console.log("[chat-widget] Widget state changed:",event.data.isMinimized?"minimized":"maximized");currentWidgetState.dimensions=event.data.dimensions;currentWidgetState.isMinimized=event.data.isMinimized;currentWidgetState.isSmallWidth=event.data.isSmallWidth;updateWidgetVisibility(event.data.isMinimized,event.data.dimensions);updateIframePosition(currentPosition,isMobile,currentWidgetState.isMinimized);updateBodyOverflow(event.data.isMinimized,currentSettings.isMobile)}if(event.data&&event.data.action==="addToCart"&&event.data.formData){console.log("[chat-widget] Received add to cart data:",event.data.formData);fetch(window.Shopify.routes.root+"cart/add.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(event.data.formData)}).then(function(response){return response.json()}).then(function(data){console.log("[chat-widget] Item added to cart:",data);if(data&&data.items){const cart=document.querySelector("cart-notification")||document.querySelector("cart-drawer");if(data.sections&&data.sections["cart-icon-bubble"]){const cartBubble=document.getElementById("cart-icon-bubble");if(cartBubble){cartBubble.innerHTML=data.sections["cart-icon-bubble"]}}iframe.contentWindow.postMessage({action:"addToCartSuccess",product:data},origin)}else{iframe.contentWindow.postMessage({action:"addToCartError",error:error.message},origin)}}).catch(function(error){console.error("[chat-widget] Error adding to cart:",error);iframe.contentWindow.postMessage({action:"addToCartError",error:error.message},origin)})}}if(event.data&&event.data.type==="SHOPIFY_TRACK_EVENT"){if(!isIframeReady||!iframe.contentWindow){console.log("[chat-widget] Iframe not ready, queuing SHOPIFY_TRACK_EVENT message");if(messageQueue.length>=maxQueueSize){console.warn("[chat-widget] Message queue full, dropping oldest message");messageQueue.shift()}messageQueue.push({type:"SHOPIFY_TRACK_EVENT",data:event.data,timestamp:Date.now()})}else{sendShopifyTrackEvent(event.data)}}if(event.data&&event.data.type==="KIOSK_FULL_SCREEN"){console.log("[chat-widget] Received KIOSK_FULL_SCREEN message");isKioskFullScreen=true;iframe.style.width="100vw";iframe.style.height="100vh";protectIframeStyles();console.log("[chat-widget] Kiosk full screen mode activated")}if(event.data&&event.data.type==="VIRTUAL_USER_ID"){console.log("[chat-widget] Received VIRTUAL_USER_ID message");if(window.Shopify&&window.Shopify.analytics){var virtualUserId=event.data.virtualUserId;window.Shopify.analytics.publish("chatbot:virtualUserId",{message:virtualUserId})}}},false);function updateWidgetVisibility(isMinimized,dimensions){if(isKioskFullScreen){iframe.style.width="100vw";iframe.style.height="100vh";console.log("[chat-widget] Kiosk mode active: Enforcing full screen dimensions");return}if(isMinimized){console.log("[chat-widget] Widget minimized - Small width mode:",dimensions);{iframe.style.width=dimensions.width?dimensions.width+"px":"100px";iframe.style.height=dimensions.height?dimensions.height+"px":"120px"}}else{if(currentSettings.isMobile){iframe.style.width="100vw";iframe.style.height="100vh"}else{iframe.style.width=currentSettings.width+"px";iframe.style.height=currentSettings.height+"px"}iframe.style.borderRadius=currentSettings.isMobile?"0":"15px"}}function updateBodyOverflow(isMinimized,isMobileMode){if(isMobileMode&&!isMinimized){document.body.style.overflow="hidden";console.log("[chat-widget] Body scroll disabled for mobile widget expansion")}else{document.body.style.overflow=originalBodyOverflow;console.log("[chat-widget] Body scroll restored to original state")}updateViewportScale(isMinimized,isMobileMode)}})();