PageSourceSearch

https://chat.appliancepartspros.com/api/widget

js appliancepartspros.com collected 2026-10-03 19:17:50 UTC 266,316 bytes, 2 lines download raw bytes

1window.__MX_PROACTIVE_CONFIG__={"proactiveTriggers":[{"id":"diagram_dwell","enabled":true,"variants":[{"id":"a","message":"Need help finding a specific part on this diagram? Tell me what's broken and I'll point you to it.","weight":34},{"id":"b","message":"Can't find the right part? I can help.","weight":33},{"id":"c","message":"Tell me what's broken - I'll find it on this diagram in seconds.","weight":33}]},{"id":"model_dwell","enabled":true,"variants":[{"id":"a","message":"Looking for a part for your {label}? Tell me what's wrong and I'll find it - no need to search through all the diagrams.","weight":34},{"id":"b","message":"Need a part? Tell me what's wrong - I'll find it.","weight":33},{"id":"c","message":"Skip the diagram search - tell me the symptom and I'll find the part.","weight":33}]},{"id":"pdp_dwell","enabled":true,"variants":[{"id":"a","message":"Not sure this is the right part? Tell me your model number and I'll confirm it fits.","weight":34},{"id":"b","message":"Not sure the {partName} fits your model? I can verify in seconds.","weight":33},{"id":"c","message":"I can confirm this part fits your model - takes 10 seconds.","weight":33}]},{"id":"exit_pdp","enabled":true,"variants":[{"id":"a","message":"Not sure this part fits? Tell me your model number and I'll verify before you go.","weight":34},{"id":"b","message":"Not sure? 365-day returns on new parts - order with confidence.","weight":33},{"id":"c","message":"I can verify this fits your model in 10 seconds.","weight":33}]},{"id":"exit_diagram","enabled":true,"variants":[{"id":"a","message":"Couldn't find the right part? Tell me what's broken and I'll help.","weight":34},{"id":"b","message":"Couldn't find it? I can help - one question.","weight":33},{"id":"c","message":"Tell me the symptom - I'll find the exact part.","weight":33}]},{"id":"cart_dwell","enabled":true,"variants":[{"id":"a","message":"Have a question about the parts in your cart? I can verify they're compatible with your model.","weight":34},{"id":"b","message":"Want me to verify these parts fit your model before you order?","weight":33},{"id":"c","message":"Same-day shipping if you order by 4 PM ET. Need help with anything?","weight":33}]},{"id":"exit_cart","enabled":true,"variants":[{"id":"a","message":"Have a question before you go? I can check part compatibility or shipping.","weight":34},{"id":"b","message":"365-day returns on new parts. Need help before you order?","weight":33},{"id":"c","message":"Your parts ship same-day if ordered by 4 PM ET.","weight":33}]},{"id":"search_dwell","enabled":true,"variants":[{"id":"a","message":"Need help narrowing down the right part? Tell me your model and what's wrong.","weight":50},{"id":"b","message":"Can't find it? Tell me your model - I'll track it down.","weight":50}]},{"id":"repair_help_dwell","enabled":true,"variants":[{"id":"a","message":"Need the parts for this repair? Tell me your model number and I'll find them.","weight":50},{"id":"b","message":"Working on this repair? I can find the exact parts for your model.","weight":50}]},{"id":"forum_dwell","enabled":true,"variants":[{"id":"a","message":"Need help with your appliance? I can diagnose the issue and find the right parts - just tell me your model number.","weight":50},{"id":"b","message":"I see this is about a {brand} {symptom} issue - I can help diagnose the next steps.","weight":50}]},{"id":"multi_pdp","enabled":true,"variants":[{"id":"a","message":"Comparing parts? Tell me your model number and what you're fixing - I can confirm which one fits.","weight":50},{"id":"b","message":"Not sure which part is right? I can check compatibility.","weight":50}]},{"id":"blog_dwell","enabled":true,"variants":[{"id":"a","message":"Working on a repair? Tell me your model number and I can help you find the right parts.","weight":100}]}]};
2(function(){"use strict";(function(){var prev=window.maxchat;var stub=function(){stub.q.push(Array.prototype.slice.call(arguments))};stub.q=prev&&prev.q&&typeof prev.q.slice==="function"?prev.q.slice():[];window.maxchat=stub})();var _currentScript=document.currentScript;var API_BASE=function(){if(_currentScript&&_currentScript.src){try{return new URL(_currentScript.src).origin}catch(e){}}var scripts=document.getElementsByTagName("script");for(var i=0;i<scripts.length;i++){var src=scripts[i].src||"";if(src.indexOf("widget.js")!==-1||src.indexOf("/api/widget")!==-1){try{return new URL(src).origin}catch(e){}}}return window.location.origin}();
2var C={navy:"#1B3A5C",navyDark:"#142C47",orange:"#E87722",bg:"#FFFFFF",bgSub:"#F7F6F4",bgWarm:"#FAF9F7",border:"#ECEAE6",t1:"#111111",t2:"#6E6D69",t3:"#767573",green:"#1A8C3A",greenBg:"#E6F7EC",red:"#D1291E",redBg:"#FEF0EF",grayBadge:"#888888",grayBadgeBg:"#F0EFED"};var FONT="-apple-system, 'Helvetica Neue', Helvetica, Arial, sans-serif";var MOBILE_BP=768;var CONSENT_VERSION="2026-06-09";var CONSENT_TERMS_URL="https://www.appliancepartspros.com/customerservice/legal.aspx";var CONSENT_PRIVACY_URL="https://www.appliancepartspros.com/customerservice/privacy.aspx";var CONSENT_FLAG_KEY="mx_consent";var CONSENT_GATE_MESSAGE="I'm Max - I help people fix appliances and find the right parts. Over 2 million genuine OEM parts, same-day shipping, and 365-day returns. This chat uses AI and/or a person, is recorded to improve service, and isn't a substitute for professional advice. [Terms of Use]("+CONSENT_TERMS_URL+") \xb7 [Privacy Policy]("+CONSENT_PRIVACY_URL+")";var CONSENT_GATE_MESSAGE_FORUM="I'm Max - I help people fix appliances and find the right parts. Over 2 million genuine OEM parts, same-day shipping, and 365-day returns. This chat uses AI, is recorded to improve service, and isn't a substitute for professional advice. [Terms of Use]("+CONSENT_TERMS_URL+") \xb7 [Privacy Policy]("+CONSENT_PRIVACY_URL+")";var CONSENT_CHIP_LABEL="I Agree - Start Chat";var state={isOpen:false,isMinimized:false,sessionToken:null,conversationId:null,messages:[],quickReplies:[],isTyping:false,businessHours:true,pageContext:null,browsingHistory:[],entrySource:null,entrySourceStamped:false,entrySourcePingFailed:false,historyLoading:false,navTracker:false,modelNumber:null,brand:null,applianceType:null,lastBotText:"",hasConversation:false,hadPartCard:false,customerMsgCount:0,consentDisplayedAt:null,consentAcceptedAt:null,_consentRecordedFor:null,lastCustomerMsg:"",handoffCompleted:false,agentMode:false,agentName:null,agentAssigned:false,agentStream:null,agentStreamLastSeen:null,agentStreamBackoffMs:3e3,agentStreamFailCount:0,agentPolling:false,agentPollTimer:null,agentPollInFlight:false,seenAgentMessageIds:{},alcConversationId:null,alcStreamUrl:null,agentRestoring:false,pendingAgentMessages:[],pageTracker:null,surveyShownForEventId:null,surveySubmitted:false,bypassAgentSend:false,maxHelpDuringWait:false,waitingTimerId:null,queueStatusTimer:null,heartbeatTimer:null,heartbeatInFlight:false,waitHelpOffered:false,isSending:false,agentTypingTimer:null,customerTypingDebounce:null,customerTypingIdleTimer:null,customerTypingActive:false,draftPreviewDebounce:null,lastSentDraft:"",collectedName:null,collectedEmail:null,capturedName:null,transcriptOffered:false,seenCheckoutEventIds:{},seenReassuranceEventIds:{},handoffContactPromptOpen:false,handoffInFlight:false,idlePromptTimer:null,idleCloseTimer:null,disconnectBeaconSent:false,agentReadAt:null,lastAgentMsgId:null,readReceiptSentForId:null,readReceiptTimer:null,proactiveContext:null};var PROACTIVE_STORE_KEY="mx_proactive";var proactive={triggerCount:0,dismissCount:0,dismissed:false,lastTriggerTime:0,pdpUrls:[],cartSignal:false,variants:{},activeVariantId:"a",activeIntent:null,activeIntentContext:null,currentTimer:null,fadeTimer:null,shownOnPage:false,closedByUser:false,active:false,activeTriggerType:null,navPatched:false,pendingEvents:[],pageStartTime:0,exitFiredOnPage:false,exitBound:false};var IDLE_PROMPT_MS=10*60*1e3;var IDLE_CLOSE_MS=3*60*1e3;function isMobile(){return window.innerWidth<MOBILE_BP}var DEBUG_MODE=function(){try{if(/[?&]mxdebug=1(?=&|$)/.test(window.location.search))return true}catch(e){}try{if(window.localStorage&&window.localStorage.getItem("mx_debug")==="1")return true}catch(e){}return false}();function debugLog(msg){if(!DEBUG_MODE)return;console.log("[MAX] "+msg)}function logQualityEvent(eventType,eventData,messageId){if(!state.sessionToken||!state.conversationId)return;fetch(API_BASE+"/api/chat/quality-event",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,messageId:messageId||null,eventType:eventType,eventData:eventData||{},pageUrl:window.location.href})}).catch(function(){})}function pushDataLayer(eventName,params){try{var dl=window.dataLayer;if(!dl||typeof dl.push!=="function")return;var payload={event:eventName,conversation_id:state.conversationId||null};if(params){for(var k in params){if(Object.prototype.hasOwnProperty.call(params,k)&&params[k]!=null)payload[k]=params[k]}}dl.push(payload)}catch(e){}}function buildAttributionCookie(convId){return"apc_conv="+encodeURIComponent(convId)+"; Domain=.appliancepartspros.com; Path=/; Max-Age=2592000; SameSite=Lax; Secure"}function setAttributionCookie(){try{if(!state.conversationId)return;document.cookie=buildAttributionCookie(state.conversationId)}catch(e){}}function postFunnelEvent(eventType,partId,source){if(!state.sessionToken||!state.conversationId)return;try{fetch(API_BASE+"/api/chat/funnel-event",{method:"POST",credentials:"include",keepalive:true,headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,eventType:eventType,partId:partId||null,source:source||null,pageUrl:window.location.href})}).catch(function(){})}catch(e){}}var VISITOR_ID_KEY="mx_visitor_id";var PAGE_HISTORY_MAX=50;function generateUuid(){try{if(window.crypto&&typeof window.crypto.randomUUID==="function"){return window.crypto.randomUUID()}}catch(e){}var hex="0123456789abcdef";var out="";for(var i=0;i<36;i++){if(i===8||i===13||i===18||i===23){out+="-";continue}if(i===14){out+="4";continue}var r=Math.floor(Math.random()*16);if(i===19)r=r&3|8;out+=hex.charAt(r)}return out}function getVisitorId(){try{var id=localStorage.getItem(VISITOR_ID_KEY);if(id&&/^[A-Za-z0-9_-]{8,64}$/.test(id))return id;id=generateUuid();localStorage.setItem(VISITOR_ID_KEY,id);return id}catch(e){return null}}function getPageHistory(){try{var arr=state&&Array.isArray(state.browsingHistory)?state.browsingHistory:[];return arr.slice(-PAGE_HISTORY_MAX).map(function(p){return{url:String(p&&p.url||"").slice(0,2048),title:null,pageType:p&&p.pageType?Str
2ing(p.pageType).slice(0,80):null,visitedAt:p&&typeof p.ts==="number"?new Date(p.ts).toISOString():null}}).filter(function(p){return!!p.url})}catch(e){return[]}}function wordOverlap(a,b){var wa=a.toLowerCase().split(/\s+/).filter(function(w){return w.length>2});var wb=b.toLowerCase().split(/\s+/).filter(function(w){return w.length>2});if(wa.length===0||wb.length===0)return 0;var set={};wa.forEach(function(w){set[w]=true});var overlap=0;wb.forEach(function(w){if(set[w])overlap++});return overlap/Math.max(wa.length,wb.length)}function extractCartItems(){var items=[];try{var cartRows=document.querySelectorAll(".product-item.cart-item");if(cartRows.length>0){cartRows.forEach(function(row){var item={};var titleEl=row.querySelector(".product-item-title a, .product-item-title");if(titleEl){item.name=titleEl.textContent.trim();if(titleEl.href)item.url=titleEl.href}var numEl=row.querySelector(".product-item-num");if(numEl)item.partNumber=numEl.textContent.replace(/[^A-Z0-9]/gi,"");var priceEl=row.querySelector('.product-item-price-area .price, .product-item-price-wrap .price, [class*="price"]');if(priceEl)item.price=priceEl.textContent.trim();var qtyEl=row.querySelector('select[name*="qty"], input[name*="qty"], .product-quantity-details select, .product-quantity-details input');if(qtyEl)item.quantity=qtyEl.value||"1";if(!item.quantity)item.quantity="1";if(item.name)items.push(item)})}if(items.length===0){var tableRows=document.querySelectorAll(".regular-table-wrap table tbody tr");tableRows.forEach(function(row){var cells=row.querySelectorAll("td");if(cells.length<2)return;var item={};var linkEl=row.querySelector('a[href*=".htm"]');if(linkEl){item.name=linkEl.textContent.trim();item.url=linkEl.href;var apMatch=linkEl.href.match(/ap(\d+)/i);if(apMatch)item.partNumber="AP"+apMatch[1]}if(!item.name){for(var c=0;c<cells.length;c++){var text=cells[c].textContent.trim();if(text.length>5&&!/^\$/.test(text)&&!/^\d+$/.test(text)){item.name=text;break}}}for(var c2=0;c2<cells.length;c2++){var ct=cells[c2].textContent.trim();if(/^\$[\d,.]+$/.test(ct)&&!item.price)item.price=ct}var qtyInput=row.querySelector('select, input[type="number"], input[name*="qty"]');if(qtyInput)item.quantity=qtyInput.value||"1";if(!item.quantity)item.quantity="1";if(item.name)items.push(item)})}if(items.length===0){var miniItems=document.querySelectorAll("#cart-top-detail .cart-goods");miniItems.forEach(function(el){var item={};var nameEl=el.querySelector(".cart-goods-text .h6, .cart-goods-text a");if(nameEl){item.name=nameEl.textContent.trim();if(nameEl.href)item.url=nameEl.href}var priceEl2=el.querySelector(".cart-goods-price");if(priceEl2)item.price=priceEl2.textContent.trim();if(item.name)items.push(item)})}}catch(e){debugLog("extractCartItems error: "+e.message)}return items.length>0?items:null}var FORUM_BRANDS=[["ge profile","GE Profile"],["ge monogram","GE Monogram"],["fisher & paykel","Fisher & Paykel"],["fisher and paykel","Fisher & Paykel"],["white-westinghouse","White-Westinghouse"],["magic chef","Magic Chef"],["speed queen","Speed Queen"],["sub-zero","Sub-Zero"],["subzero","Sub-Zero"],["jenn-air","Jenn-Air"],["jennair","Jenn-Air"],["kitchenaid","KitchenAid"],["whirlpool","Whirlpool"],["samsung","Samsung"],["frigidaire","Frigidaire"],["maytag","Maytag"],["bosch","Bosch"],["electrolux","Electrolux"],["kenmore","Kenmore"],["amana","Amana"],["hotpoint","Hotpoint"],["thermador","Thermador"],["gaggenau","Gaggenau"],["bertazzoni","Bertazzoni"],["admiral","Admiral"],["roper","Roper"],["estate","Estate"],["crosley","Crosley"],["inglis","Inglis"],["tappan","Tappan"],["caloric","Caloric"],["haier","Haier"],["miele","Miele"],["asko","Asko"],["viking","Viking"],["wolf","Wolf"],["dacor","Dacor"],["smeg","Smeg"],["dcs","DCS"],["lg","LG"],["ge","GE"]];function findForumBrand(text){if(!text)return"";for(var i=0;i<FORUM_BRANDS.length;i++){var token=FORUM_BRANDS[i][0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&");var re=new RegExp("(^|[^a-z0-9])"+token+"([^a-z0-9]|$)","i");if(re.test(text))return FORUM_BRANDS[i][1]}return""}function findForumModel(text){if(!text)return"";var tokens=String(text).toUpperCase().match(/\b[A-Z0-9][A-Z0-9-]{4,19}\b/g)||[];var best="";for(var i=0;i<tokens.length;i++){var compact=tokens[i].replace(/-/g,"");if(compact.length<6||compact.length>20)continue;if(/^AP\d+$/.test(compact))continue;if(!/[A-Z]/.test(compact)||!/\d/.test(compact))continue;if(!/^[A-Z]/.test(compact))continue;if(compact.length>best.length)best=compact}if(best)return best;var ken=String(text).match(/\b\d{3}\.\d{5,}\b/);return ken?ken[0]:""}function findForumParts(text,modelNumber){var out=[];var seen={};if(!text)return out;var up=String(text).toUpperCase();var model=(modelNumber||"").toUpperCase();function add(tok){if(!tok||tok===model||seen[tok])return;seen[tok]=true;out.push(tok)}var aps=up.match(/\bAP\d{6,8}\b/g)||[];for(var i=0;i<aps.length;i++)add(aps[i]);var tokens=up.match(/\b[A-Z0-9][A-Z0-9-]{4,14}\b/g)||[];for(var j=0;j<tokens.length&&out.length<10;j++){var compact=tokens[j].replace(/-/g,"");if(compact.length<5||compact.length>15)continue;if(/^AP\d+$/.test(compact))continue;var hasLetter=/[A-Z]/.test(compact),hasDigit=/\d/.test(compact);if(hasLetter&&hasDigit)add(compact);else if(!hasLetter&&hasDigit&&compact.length>=6&&compact.length<=11)add(compact)}return out.slice(0,10)}function extractForumThread(){try{var titleEl=document.querySelector(".fancy-title, h1.topic-title, .topic-title, #topic-title");var title=titleEl?(titleEl.textContent||"").trim():"";if(!title){title=(document.title||"").replace(/\s*[-|]\s*[^-|]+$/,"").trim()}var firstPost=document.querySelector(".topic-post .cooked, article .cooked, .cooked");var postText=firstPost?(firstPost.innerText||firstPost.textContent||"").trim():"";var symptom="";var tagEl=document.querySelector("[data-tag-name], .discourse-tags .discourse-tag, a.discourse-tag");if(tagEl)symptom=(tagEl.getAttribute("data-tag-name")||tagEl.textContent||"").trim();if(!symptom){var catEl=document.querySelector(".topic-category .badge-category__name, .badge-category__name, .badge-category .category-name");if(catEl)symptom=(catEl.textContent||"").trim()}var haystack=title+" "+postText;var modelNumber=findForumModel(haystack);var brand=findForumBrand(haystack);var partsMentioned=findForumParts(postText,modelNumber);var firstPostPreview=postText?postText.slice(0,500):"";if(!title&&!modelNumber&&!brand&&!symptom&&!partsMentioned.length&&!firstPostPreview){return null}var ft={};if(title)ft.title=title.slice(0,200);if(modelNumber)ft.modelNumber=modelNumber;if(brand)ft.brand=brand;if(symptom)ft.symptom=symptom.slice(0,80);if(partsMentioned.length)ft.partsMentioned=partsMentioned;if(firstPostPreview)ft.firstPostPreview=firstPostPreview;return ft}catch(e){return null}}function normalizeBrandName(brand){if(!brand||!String(brand).trim())return brand;var b=String(brand).replace(/\s+/g," ").trim().replace(/^model\s+/i,"");b=b.toLowerCase().split(" ").map(function(w){return w.length<=2?w.toUpperCase():w.charAt(0).toUpperCase()+w.slice(1)}).join(" ");if(/^kitchen\s?aid$/i.test(b))b="KitchenAid";return b}var BRAND_SLUGS=["white-westinghouse","fisher-paykel","general-electric","frigidaire-gallery","frigidaire-professional","kenmore-elite","kenmore-pro","ge-profile","ge-monogram","ge-cafe","magic-chef","speed-queen","sub-zero","jenn-air","kitchenaid","whirlpool","samsung","frigidaire","maytag","bosch","electrolux","kenmore","amana","hotpoint","thermador","gaggenau","bertazzoni","admiral","roper","estate","crosley","inglis","ta
2ppan","caloric","haier","miele","asko","viking","wolf","dacor","smeg","dcs","lg","ge"];function splitBrandModelSlug(slug){if(!slug)return null;var s=String(slug).toLowerCase().replace(/^model-/,"");for(var i=0;i<BRAND_SLUGS.length;i++){var b=BRAND_SLUGS[i];if(s.length>b.length+1&&s.indexOf(b+"-")===0){return{brand:normalizeBrandName(b.replace(/-/g," ")),modelNumber:s.slice(b.length+1).toUpperCase()}}}var m=s.match(/^(.+)-([a-z0-9]+)$/i);if(!m)return null;return{brand:normalizeBrandName(m[1].replace(/-/g," ")),modelNumber:m[2].toUpperCase()}}function detectPageContext(){var url=window.location.href;var pathname=window.location.pathname.replace(/\/+$/,"")||"/";var ctx={url:url,pageType:"other"};var hostname=(window.location.hostname||"").toLowerCase();if(hostname==="forum.appliancepartspros.com"){ctx.pageType="forum";var forumThread=extractForumThread();if(forumThread)ctx.forumThread=forumThread;return ctx}var APPLIANCE_TYPES=["washer","dryer","refrigerator","dishwasher","microwave","oven","range","stove","freezer","cooktop","hood","disposal","ice-maker","compactor","dehumidifier","air-conditioner","garbage-disposal","trash-compactor","wine-cooler","water-heater"];if(pathname==="/"||pathname===""){ctx.pageType="homepage"}else if(/checkout/i.test(pathname)){ctx.pageType="checkout"}else if(/cart/i.test(pathname)){ctx.pageType="cart";ctx.cartItems=extractCartItems()}else if(/\/(account|my-account|login|order-status|order-tracking|signin|register)/i.test(pathname)){ctx.pageType="account"}else if(/search\.(aspx|htm)|search-alt\.aspx/i.test(pathname)){ctx.pageType="search";var params=new URLSearchParams(window.location.search);ctx.searchQuery=params.get("q")||params.get("model")||"";if(!ctx.searchQuery&&/search-alt\.aspx/i.test(pathname)){ctx.searchQuery=params.get("i")||params.get("pm")||""}}else if(/repair-help/i.test(pathname)){ctx.pageType="repair-help"}else if(/\/(blog|news)(\/|$)/i.test(pathname)){ctx.pageType="blog"}else if(/\/(diy|stories?)\//i.test(pathname)){ctx.pageType="story";var storyApMatch=pathname.match(/AP(\d+)/i);if(storyApMatch)ctx.partId="AP"+storyApMatch[1];var storyModelMatch=pathname.match(/([A-Z0-9]{4,}[A-Z]\d+)/i);if(storyModelMatch)ctx.modelNumber=storyModelMatch[1].toUpperCase()}else if(/\/(qa|questions?)\//i.test(pathname)){ctx.pageType="qa";var qaApMatch=pathname.match(/AP(\d+)/i);if(qaApMatch)ctx.partId="AP"+qaApMatch[1]}else if(/^\/[a-z0-9][a-z0-9-]*-parts-for-.+\.html$/i.test(pathname)){ctx.pageType="diagram";var dMatch=pathname.match(/^\/(.+)-parts-for-(.+)\.html$/i);if(dMatch){ctx.diagramSlug=dMatch[1];ctx.modelSlug=dMatch[2];ctx.section=dMatch[1].replace(/-/g," ");var dSplit=splitBrandModelSlug(dMatch[2]);if(dSplit){ctx.brand=dSplit.brand;ctx.modelNumber=dSplit.modelNumber}}}else if(/^\/parts-for-.+\.html$/i.test(pathname)){ctx.pageType="model";var mMatch=pathname.match(/parts-for-(.+)\.html$/i);var mSlug=mMatch?mMatch[1].replace(/^(model-.+)-p\d{1,3}$/i,"$1"):null;var mSplit=mSlug?splitBrandModelSlug(mSlug):null;if(mSplit){ctx.brand=mSplit.brand;ctx.modelNumber=mSplit.modelNumber}}else if(/\.html$/i.test(pathname)&&/AP\d+/i.test(pathname)){ctx.pageType="part";var pMatch=pathname.match(/AP(\d+)/i);if(pMatch)ctx.partId="AP"+pMatch[1];var slugMatch=pathname.match(/^\/(.+)-AP\d+/i);if(slugMatch){var segments=slugMatch[1].split("-");segments.shift();var mpnSegments=[];while(segments.length>1&&/\d/.test(segments[segments.length-1])){mpnSegments.unshift(segments.pop())}var slugMpn=mpnSegments.join("-").toUpperCase();if(segments.length>0){ctx.partName=segments.join(" ").replace(/\b\w/g,function(c){return c.toUpperCase()})}var isMpnShaped=function(s){if(!s)return false;var u=String(s).toUpperCase().trim();var compact=u.replace(/[^A-Z0-9]/g,"");if(compact.length<4||compact.length>30)return false;if(/^AP\d+$/.test(compact))return false;if(!/\d/.test(compact))return false;return/^[A-Z0-9][A-Z0-9\/-]*$/.test(u)};var domMpn="";try{var mpnSel=['[itemprop="mpn"]',"[data-mpn]",'meta[itemprop="mpn"]','meta[property="product:mfr_part_no"]'];for(var mi=0;mi<mpnSel.length;mi++){var mEl=document.querySelector(mpnSel[mi]);if(!mEl)continue;var mVal=(mEl.getAttribute("content")||mEl.getAttribute("data-mpn")||mEl.textContent||"").trim();if(isMpnShaped(mVal)){domMpn=mVal.toUpperCase();break}}}catch(e){}if(domMpn)ctx.partNumber=domMpn;else if(isMpnShaped(slugMpn))ctx.partNumber=slugMpn}ctx._slugPartName=ctx.partName}else if(/^\/(.+)-parts\.html$/i.test(pathname)){ctx.pageType="catalog";var catMatch=pathname.match(/^\/(.+)-parts\.html$/i);if(catMatch){var catSlug=catMatch[1];
2if(APPLIANCE_TYPES.indexOf(catSlug)!==-1){ctx.applianceType=catSlug.replace(/-/g," ")}else{var catParts=catSlug.split("-");var foundAppliance=false;for(var ci=1;ci<catParts.length;ci++){var possibleAppliance=catParts.slice(ci).join("-");if(APPLIANCE_TYPES.indexOf(possibleAppliance)!==-1){ctx.brand=normalizeBrandName(catParts.slice(0,ci).join(" "));ctx.applianceType=possibleAppliance.replace(/-/g," ");foundAppliance=true;break}}if(!foundAppliance){ctx.brand=normalizeBrandName(catSlug.replace(/-/g," "))}}}}if((ctx.pageType==="model"||ctx.pageType==="diagram")&&!ctx.searchQuery){try{var findParam=new URLSearchParams(window.location.search).get("find");if(findParam&&findParam.trim())ctx.searchQuery=findParam.trim().slice(0,120)}catch(e){}}return ctx}function esc(str){return String(str).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function renderBotMarkdown(text){var html=esc(text);html=html.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>");html=html.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)"'<>]+)\)/g,function(_m,label,url){try{var parsed=new URL(url);if(parsed.protocol!=="https:")return label}catch(e){return label}return'<a href="'+url+'" target="_blank" rel="noopener noreferrer" style="color:#1B3A5C;text-decoration:underline">'+label+"</a>"});html=html.replace(/\n/g,"<br>");return html}function linkifyAgentText(text){var html=esc(text);html=html.replace(/https?:\/\/[^\s<]+/g,function(match){var trailing="";var url=match;var tm=url.match(/[.,;:!?)\]}]+$/);if(tm){trailing=tm[0];url=url.slice(0,url.length-trailing.length)}if(!url)return match;try{var parsed=new URL(url.replace(/&amp;/g,"&"));if(parsed.protocol!=="https:"&&parsed.protocol!=="http:")return match}catch(e){return match}return'<a href="'+url+'" target="_blank" rel="noopener noreferrer" style="color:#1B3A5C;text-decoration:underline">'+url+"</a>"+trailing});return html}function makeAvatar(size){var el=document.createElement("div");var r=Math.round(size*.32);el.style.cssText="width:"+size+"px;
2height:"+size+"px;border-radius:"+r+"px;background:"+C.navy+";display:flex;align-items:center;justify-content:center;flex-shrink:0;color:#fff;";var iconSize=Math.round(size*.5);el.innerHTML='<svg width="'+iconSize+'" height="'+iconSize+'" viewBox="0 0 24 24" fill="none"><path d="M12 2L13.9 8.6L20 11L13.9 13.4L12 20L10.1 13.4L4 11L10.1 8.6L12 2Z" fill="currentColor"/><path d="M19 14L19.8 16.7L22.5 17.5L19.8 18.3L19 21L18.2 18.3L15.5 17.5L18.2 16.7L19 14Z" fill="currentColor" opacity="0.4"/></svg>';return el}function createStyles(){var mobile="@media(max-width:"+(MOBILE_BP-1)+"px)";var desktop="@media(min-width:"+MOBILE_BP+"px)";return"@keyframes mx-slideInRight{from{transform:translateX(100%)}to{transform:translateX(0)}}@keyframes mx-slideOutRight{from{transform:translateX(0)}to{transform:translateX(100%)}}@keyframes mx-slideUp{from{transform:translateY(100%)}to{transform:translateY(0)}}@keyframes mx-slideDown{from{transform:translateY(0)}to{transform:translateY(100%)}}@keyframes mx-fadeIn{from{opacity:0}to{opacity:1}}@keyframes mx-fadeOut{from{opacity:1}to{opacity:0}}@keyframes mx-bounce{0%,80%,100%{transform:scale(0)}40%{transform:scale(1)}}@keyframes mx-proactive-in{from{opacity:0;transform:translateY(8px) scale(0.96)}to{opacity:1;transform:translateY(0) scale(1)}}@keyframes mx-proactive-out{from{opacity:1;transform:translateY(0) scale(1)}to{opacity:0;transform:translateY(6px) scale(0.97)}}@keyframes mx-launcher-pulse{0%,100%{transform:scale(1)}50%{transform:scale(1.12)}}*{box-sizing:border-box;margin:0;padding:0;font-family:"+FONT+";color:"+C.t1+"}.mx-launcher{position:fixed;bottom:calc(108px + var(--mx-dodge,0px));right:24px;z-index:999999;display:flex;flex-direction:row;align-items:flex-end;gap:10px;transition:bottom .22s ease}"+mobile+"{.mx-launcher{bottom:calc(92px + env(safe-area-inset-bottom, 0px) + var(--mx-dodge,0px));right:14px}}.mx-launcher-btn{width:52px;height:52px;border-radius:16px;background:"+C.navy+";border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;color:#fff;box-shadow:0 4px 16px rgba(27,58,92,0.3);transition:transform 0.2s}.mx-launcher-btn:hover{transform:scale(1.05)}"+mobile+"{.mx-launcher-btn{width:46px;height:46px;border-radius:14px}}.mx-proactive{position:relative;display:none;max-width:252px;background:#fff;border-radius:16px;padding:12px 32px 12px 15px;box-shadow:0 6px 22px rgba(27,58,92,0.18),0 0 0 1px rgba(0,0,0,0.05);font-size:13px;font-weight:500;line-height:1.42;color:"+C.t1+";cursor:pointer;text-align:left;-webkit-tap-highlight-color:transparent}.mx-proactive.visible{display:block;animation:mx-proactive-in 0.42s cubic-bezier(.16,1,.3,1) both}.mx-proactive.closing{display:block;animation:mx-proactive-out 0.25s ease forwards}.mx-proactive:hover{box-shadow:0 8px 26px rgba(27,58,92,0.24),0 0 0 1px rgba(0,0,0,0.05)}.mx-proactive-close{position:absolute;top:5px;right:5px;width:22px;height:22px;border:none;background:transparent;color:"+C.t3+";font-size:17px;line-height:1;cursor:pointer;border-radius:50%;display:flex;align-items:center;justify-content:center;padding:0;font-family:"+FONT+"}.mx-proactive-close:hover{background:"+C.bgSub+";color:"+C.t1+"}"+mobile+"{.mx-proactive{display:none !important}}.mx-launcher-btn.mx-pulsing{animation:mx-launcher-pulse 1.7s ease-in-out infinite}@media(prefers-reduced-motion:reduce){.mx-proactive.visible{animation:none}.mx-proactive.closing{animation:none}.mx-launcher-btn.mx-pulsing{animation:none}}.mx-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,0.25);z-index:999997;animation:mx-fadeIn 0.2s ease}.mx-sidebar{position:fixed;top:0;right:0;bottom:0;width:380px;background:#F7F6F3;z-index:999998;display:flex;flex-direction:column;border-left:1px solid "+C.border+";animation:mx-slideInRight 0.35s cubic-bezier(0.4,0,0.2,1)}.mx-sidebar.closing{animation:mx-slideOutRight 0.3s cubic-bezier(0.4,0,0.2,1) forwards}.mx-sheet{position:fixed;bottom:0;left:0;right:0;height:82vh;background:#F7F6F3;z-index:999998;border-radius:16px 16px 0 0;box-shadow:0 -4px 20px rgba(0,0,0,0.08);display:flex;flex-direction:column;animation:mx-slideUp 0.35s cubic-bezier(0.4,0,0.2,1)}.mx-sheet.closing{animation:mx-slideDown 0.3s ease forwards}.mx-sheet.mx-dragging{animation:none;transition:none}.mx-sheet.mx-snap{transition:transform 0.3s cubic-bezier(0.2,0,0,1)}.mx-drag-handle{width:100%;padding:10px 0 6px;display:flex;justify-content:center;flex-shrink:0;cursor:grab;touch-action:none}.mx-drag-bar{width:36px;height:4px;border-radius:2px;background:"+C.border+"}.mx-minimized{position:fixed;bottom:0;left:0;right:0;z-index:999998;background:"+C.bg+";border-radius:14px 14px 0 0;box-shadow:0 -2px 12px rgba(0,0,0,0.05);padding:8px 16px calc(12px + env(safe-area-inset-bottom, 0px));cursor:pointer;display:flex;flex-direction:column;align-items:center;gap:6px;touch-action:none}.mx-minimized.mx-dragging{transition:none}.mx-minimized.mx-snap{transition:transform 0.3s cubic-bezier(0.2,0,0,1)}.mx-minimized-handle{width:32px;height:3px;border-radius:2px;background:"+C.border+"}.mx-minimized-row{display:flex;align-items:center;gap:10px;width:100%}.mx-minimized-label{font-size:13px;font-weight:700;color:"+C.t1+"}.mx-minimized-preview{flex:1;font-size:12px;color:"+C.t2+";overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.mx-minimized-chevron{color:"+C.t3+";flex-shrink:0}.mx-header{padding:14px 16px;display:flex;align-items:center;gap:10px;background:"+C.bg+";flex-shrink:0;border-bottom:1px solid "+C.border+"}.mx-header-title{flex:1}.mx-header-name{font-size:15px;font-weight:700;color:"+C.t1+";letter-spacing:-0.02em}.mx-header-sub{font-size:15px;font-weight:400;color:"+C.t3+";margin-left:6px}.mx-share-btn{width:30px;height:30px;border-radius:15px;border:none;background:"+C.bgSub+";cursor:pointer;display:none;align-items:center;justify-content:center;color:"+C.t3+";flex-shrink:0;transition:background 0.15s}.mx-share-btn:hover{background:"+C.border+"}.mx-share-btn:disabled{opacity:0.4;cursor:not-allowed}.mx-share-btn.visible{display:flex}.mx-sound-btn{width:30px;height:30px;border-radius:15px;border:none;background:"+C.bgSub+";cursor:pointer;display:flex;align-items:center;justify-content:center;color:"+C.t3+";flex-shrink:0;transition:background 0.15s}.mx-sound-btn:hover{background:"+C.border+"}.mx-close-btn{width:30px;height:30px;border-radius:15px;border:none;background:"+C.bgSub+";cursor:pointer;display:flex;align-items:center;justify-content:center;color:"+C.t3+";flex-shrink:0}.mx-close-btn:hover{background:"+C.border+"}.mx-messages{flex:1;overflow-y:auto;overscroll-behavior:contain;padding:16px 14px 6px;display:flex;flex-direction:column;scrollbar-width:none;-ms-overflow-style:none}.mx-messages::-webkit-scrollbar{display:none}.mx-welcome{flex:1;display:flex;flex-direction:column;justify-content:center;padding:0 28px}.mx-welcome-avatar{display:flex;justify-content:center;margin-bottom:16px}.mx-welcome-greeting{font-size:20px;font-weight:800;color:"+C.t1+";text-align:center;letter-spacing:-0.03em;line-height:1.3}.mx-welcome-sub{font-size:14px;color:"+C.t2+";text-align:center;line-height:1.5;margin-top:8px}
2.mx-welcome-chips{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;margin-top:22px}.mx-msg-row{margin-bottom:16px}.mx-msg-row.user{display:flex;justify-content:flex-end}.mx-msg-row.bot{display:flex;gap:10px;align-items:flex-start}.mx-msg-bubble{padding:12px 16px;font-size:14px;line-height:1.6;max-width:82%;word-wrap:break-word}.mx-msg-bubble.user{background:"+C.navy+";color:#fff;border-radius:18px 2px 18px 18px}.mx-msg-bubble.bot{background:#FFFFFF;color:"+C.t1+";border-radius:2px 18px 18px 18px;box-shadow:0 1px 3px rgba(0,0,0,0.04)}.mx-feedback{display:flex;gap:3px;margin-top:2px;margin-bottom:-8px;padding-left:40px}.mx-fb-btn{width:26px;height:26px;border-radius:8px;border:1px solid transparent;background:transparent;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;padding:0}.mx-fb-btn:hover{background:"+C.bgSub+"}.mx-fb-btn.active{border:1.5px solid "+C.navy+";background:#E8EDF3}.mx-fb-btn.dimmed{opacity:0.25}"+mobile+"{.mx-fb-btn{width:36px;height:36px;border-radius:10px}}
2.mx-inline-chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px;padding-left:38px}.mx-chip{padding:8px 16px;border-radius:24px;border:1px solid "+C.navy+";background:"+C.bg+";color:"+C.navy+";font-size:13px;font-weight:500;cursor:pointer;font-family:"+FONT+";line-height:1.3;transition:all 0.15s}.mx-chip:hover{background:"+C.navy+";color:#fff}.mx-vid{margin-top:10px;padding-left:38px}.mx-vid-card{border-radius:12px;overflow:hidden;border:1px solid "+C.border+";cursor:pointer;position:relative;background:#000}.mx-vid-thumb{width:100%;aspect-ratio:16/9;object-fit:cover;display:block}.mx-vid-play{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);width:52px;height:52px;background:rgba(0,0,0,0.7);border-radius:50%;display:flex;align-items:center;justify-content:center;pointer-events:none}.mx-vid-play svg{width:22px;height:22px;fill:#fff;margin-left:3px}.mx-vid-title{padding:10px 12px;background:"+C.bg+";font-size:13px;font-weight:500;color:"+C.t1+";line-height:1.3}.mx-vid-brand-note{margin-top:6px;font-size:12px;color:"+C.t3+";line-height:1.35}.mx-vid-iframe{width:100%;aspect-ratio:16/9;border:none;display:block}.mx-typing{display:flex;flex-wrap:wrap;gap:4px;padding:12px 16px;align-self:flex-start;margin-bottom:16px;align-items:center}.mx-typing span{width:8px;height:8px;border-radius:50%;background:"+C.border+";animation:mx-bounce 1.4s infinite ease-in-out both}.mx-typing span:nth-child(1){animation-delay:-0.32s}.mx-typing span:nth-child(2){animation-delay:-0.16s}.mx-typing-label{width:100%;font-size:12px;color:"+C.t2+";margin-top:2px;opacity:0;transition:opacity 0.3s ease}.mx-typing-label.visible{opacity:1}.mx-agent-typing{display:flex;gap:4px;align-items:center;padding:4px 16px 8px;color:"+C.t2+";font-size:12px;font-style:italic}.mx-agent-typing-dots{display:inline-flex;gap:3px;align-items:center}.mx-agent-typing-dots span{width:5px;height:5px;border-radius:50%;background:"+C.t2+";animation:mx-bounce 1.4s infinite ease-in-out both}.mx-agent-typing-dots span:nth-child(1){animation-delay:-0.32s}.mx-agent-typing-dots span:nth-child(2){animation-delay:-0.16s}.mx-attachment{display:flex;flex-direction:column;align-items:flex-end;padding:4px 16px;gap:4px}.mx-attachment img{max-width:250px;max-height:250px;border-radius:12px;cursor:pointer;display:block}.mx-attachment-card{display:flex;align-items:center;gap:10px;background:"+C.bg+";border:1px solid "+C.border+";border-radius:12px;padding:10px 12px;max-width:280px}.mx-attachment-card a{color:"+C.navy+";font-size:13px;text-decoration:none;font-weight:500}.mx-attachment-progress{width:200px;height:4px;border-radius:999px;background:#E5E7EB;overflow:hidden}.mx-attachment-progress > div{height:100%;background:"+C.navy+";width:30%;animation:mx-attach-pulse 1.2s ease-in-out infinite}@keyframes mx-attach-pulse{0%{transform:translateX(-100%)}100%{transform:translateX(400%)}}.mx-checkout-card{margin:8px 12px;padding:14px;border:1px solid #e0e0e0;border-radius:14px;background:#FFFFFF;font-family:"+FONT+";display:flex;flex-direction:column;gap:10px;box-shadow:0 1px 4px rgba(0,0,0,0.04)}.mx-checkout-title{font-size:13px;font-weight:600;color:"+C.t1+"}.mx-checkout-subtitle{font-size:11px;color:"+C.t2+";margin-top:-4px}.mx-checkout-items{display:flex;flex-direction:column;gap:8px;margin-top:2px}.mx-checkout-row{display:flex;justify-content:space-between;gap:10px;font-size:12px;align-items:flex-start}.mx-checkout-row .mx-co-name{color:"+C.t1+";flex:1;line-height:1.35}.mx-checkout-row .mx-co-ap{display:block;font-size:11px;color:"+C.t2+";margin-top:1px}.mx-checkout-row .mx-co-qty{color:"+C.t2+";font-variant-numeric:tabular-nums}.mx-checkout-row .mx-co-price{color:"+C.t1+";font-variant-numeric:tabular-nums;font-weight:500;min-width:64px;text-align:right}.mx-checkout-divider{height:1px;background:#e0e0e0;margin:4px 0}.mx-checkout-total{display:flex;justify-content:space-between;align-items:center;font-size:13px;font-weight:700;color:"+C.t1+"}.mx-checkout-btn{background:#0066CC;color:#FFF;border:none;border-radius:999px;padding:10px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";width:100%;margin-top:4px}.mx-checkout-btn:disabled{background:#9AA1AB;cursor:default}.mx-checkout-foot{font-size:11px;color:"+C.t2+";text-align:center;margin-top:2px}.mx-checkout-err{font-size:12px;color:"+C.red+";margin-top:4px;display:none}.mx-checkout-err.visible{display:block}.mx-checkout-err a{color:#0066CC;text-decoration:underline;display:block;margin-top:4px;font-size:12px}.mx-part-card{background:"+C.bg+";border-radius:14px;border:1px solid "+C.border+";box-shadow:0 1px 4px rgba(0,0,0,0.06);overflow:hidden;margin-top:10px;flex-shrink:0}.mx-pc-row1{display:flex;justify-content:space-between;align-items:center;padding:12px 14px 0}.mx-pc-oem{display:flex;align-items:center;gap:6px;font-size:12px;color:#333}.mx-pc-oem-icon{width:18px;height:18px;border-radius:50%;background:#2D8A4E;
2display:flex;align-items:center;justify-content:center;flex-shrink:0}.mx-pc-oem-icon svg{width:10px;height:10px;fill:#fff}.mx-pc-oem b{color:#2D8A4E;font-weight:700}.mx-pc-apnum{font-size:12px;color:"+C.t3+";flex-shrink:0}.mx-pc-img-wrap{width:100%;aspect-ratio:4/3;background:#F5F5F5;border-radius:8px;margin:10px 14px 0;display:flex;align-items:center;justify-content:center;overflow:hidden;box-sizing:border-box;padding:8px;width:calc(100% - 28px);position:relative}.mx-pc-img{max-width:100%;max-height:100%;object-fit:contain;cursor:zoom-in}.mx-pc-row3{padding:10px 14px 0}.mx-pc-name{font-size:16px;font-weight:700;color:"+C.navy+";line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-decoration:none;display:block}.mx-pc-name:hover{text-decoration:underline}.mx-pc-pdp{font-size:12px;color:"+C.navy+";text-decoration:underline;text-underline-offset:2px;margin-top:2px;display:inline-block}.mx-pc-pdp:hover{color:#E87722}.mx-pc-price-row{display:flex;align-items:baseline;gap:8px;margin-top:4px}.mx-pc-price{font-size:20px;font-weight:700;color:#111;letter-spacing:-0.03em}.mx-pc-list-price{font-size:14px;color:#999;text-decoration:line-through}.mx-pc-row4{padding:8px 14px 0;display:flex;align-items:center;gap:6px}.mx-pc-dot{width:8px;height:8px;border-radius:50%;background:#2D8A4E;flex-shrink:0}.mx-pc-stock{font-size:12px;font-weight:700;text-transform:uppercase;color:#2D8A4E}.mx-pc-save{font-size:12px;font-weight:700;color:#2D8A4E}.mx-pc-stock-out{font-size:12px;font-weight:700;text-transform:uppercase;color:"+C.red+"}.mx-pc-stock-disc{font-size:12px;font-weight:700;text-transform:uppercase;color:"+C.grayBadge+"}.mx-pc-backorder{font-size:11px;color:#666;margin-top:2px}.mx-pc-diag-overlay{position:absolute;bottom:6px;right:6px;background:rgba(0,0,0,0.6);color:#fff;font-size:11px;padding:2px 6px;border-radius:4px;pointer-events:none}.mx-pc-diag-loc{padding:6px 14px 0;font-size:12px;color:"+C.t3+"}.mx-pc-fit{margin:10px 14px 0;padding:10px 12px;background:#E8F5E9;border-radius:8px;display:flex;align-items:center;gap:8px;font-size:13px;color:#333}.mx-pc-fit-icon{width:18px;height:18px;border-radius:50%;background:#2D8A4E;display:flex;align-items:center;justify-content:center;flex-shrink:0}.mx-pc-fit-icon svg{width:10px;height:10px;fill:#fff}.mx-pc-fit b{font-weight:700}.mx-pc-delivery-box{margin:10px 14px 0;padding:10px 12px;border:1px solid #EAEAEA;border-radius:8px;font-size:13px;color:#333}.mx-pc-del-line{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.mx-pc-del-line+.mx-pc-del-line{margin-top:6px}.mx-pc-del-line svg{width:16px;height:16px;flex-shrink:0;fill:#666}.mx-pc-del-line b{font-weight:700}.mx-pc-del-line .green{color:#2D8A4E}.mx-pc-actions{padding:10px 14px 14px}.mx-pc-cart-btn{width:100%;padding:14px 0;border-radius:8px;border:none;background:#E87722;color:#fff;font-weight:700;font-size:16px;cursor:pointer;font-family:"+FONT+";display:flex;align-items:center;justify-content:center;gap:6px;transition:background 0.15s}.mx-pc-cart-btn:hover{background:#D06A1A}.mx-pc-cart-btn:disabled{opacity:0.6;cursor:not-allowed}.mx-pc-cart-btn.added{background:#2D8A4E}.mx-pc-cart-btn.sent{background:#5A6B7C}.mx-pc-cart-btn.error{background:"+C.red+"}.mx-pc-cart-link{display:block;text-align:center;color:"+C.navy+";font-size:13px;font-weight:500;text-decoration:none;margin-top:6px}.mx-pc-cart-link:hover{text-decoration:underline}.mx-pc-trust{text-align:center;padding:6px 14px 14px;font-size:12px;color:#666;display:flex;align-items:center;justify-content:center;gap:4px}.mx-pc-trust svg{width:12px;height:12px;fill:#2D8A4E}.mx-pc-disc-label{display:block;text-align:center;background:"+C.grayBadgeBg+";color:"+C.grayBadge+";font-size:12px;font-weight:600;padding:8px 10px;border-radius:8px;width:100%}.mx-lightbox{position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:999999;display:flex;align-items:center;justify-content:center;animation:mx-fadeIn 0.2s ease}.mx-lightbox img{max-width:90%;max-height:90%;object-fit:contain;border-radius:4px}.mx-lightbox-close{position:absolute;top:12px;right:12px;width:32px;height:32px;border-radius:50%;border:none;background:rgba(255,255,255,0.2);color:#fff;font-size:20px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1}.mx-lightbox-close:hover{background:rgba(255,255,255,0.4)}.mx-input-area{padding:10px 14px 104px;border-top:1px solid "+C.border+";background:"+C.bg+";flex-shrink:0}"+mobile+"{.mx-input-area{padding-bottom:calc(88px + env(safe-area-inset-bottom, 0px))}}.mx-input-pill{display:flex;align-items:center;background:"+C.bgSub+";border-radius:28px;padding:4px 4px 4px 12px;border:1px solid "+C.border+"}.mx-camera-btn{width:32px;height:32px;border-radius:16px;background:transparent;border:none;cursor:pointer;display:none;align-items:center;justify-content:center;flex-shrink:0;padding:0;color:"+C.t2+";transition:color 0.15s}.mx-camera-btn:hover{color:"+C.navy+"}
2.mx-camera-btn.mobile-show{display:flex}.mx-attach-btn{width:32px;height:32px;border-radius:16px;background:transparent;border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;padding:0;color:"+C.t2+";transition:color 0.15s}.mx-attach-btn:hover{color:"+C.navy+"}.mx-attach-btn.mobile-hide{display:none}.mx-img-preview{max-width:200px;max-height:150px;border-radius:10px;margin-top:4px}.mx-input-pill:focus-within{border-color:"+C.navy+"}.mx-input-pill.mx-locked{opacity:0.55}.mx-input-pill.mx-locked .mx-chat-input{cursor:not-allowed}.mx-input-pill.mx-locked button{cursor:not-allowed}.mx-chat-input{flex:1;border:none;background:transparent;padding:9px 0;font-size:14px;font-family:"+FONT+";outline:none;color:"+C.t1+";resize:none;max-height:80px;line-height:1.4;scrollbar-width:none;-ms-overflow-style:none}.mx-chat-input::-webkit-scrollbar{display:none}.mx-send-btn{width:36px;height:36px;border-radius:18px;background:"+C.orange+";border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;flex-shrink:0;transition:opacity 0.15s}.mx-send-btn:disabled{opacity:0.4;cursor:not-allowed}.mx-disclaimer{font-size:11px;color:"+C.t3+";text-align:center;margin-top:7px}.mx-consent{font-size:11px;color:"+C.t3+";text-align:center;margin-top:4px;line-height:1.35;padding:0 4px}.mx-consent a{color:"+C.t3+";text-decoration:underline}.mx-consent a:hover{color:"+C.t2+"}.mx-share-toast{position:absolute;top:56px;left:50%;transform:translateX(-50%);background:"+C.t1+";color:#fff;padding:6px 14px;border-radius:6px;font-size:13px;z-index:10;opacity:0;transition:opacity 0.2s;pointer-events:none}.mx-share-toast.show{opacity:1}"}var shadow,launcher,panel,overlay,minimizedBar;var launcherBtn,proactiveBubble,proactiveBubbleText;function buildUI(){var host=document.createElement("div");host.id="app-chat-widget";document.body.appendChild(host);shadow=host.attachShadow({mode:"closed"});["keydown","keypress","keyup"].forEach(function(type){shadow.addEventListener(type,function(e){e.stopPropagation()})});var style=document.createElement("style");style.textContent=createStyles();shadow.appendChild(style);launcher=document.createElement("div");launcher.className="mx-launcher";proactiveBubble=document.createElement("div");proactiveBubble.className="mx-proactive";proactiveBubble.id="mx-proactive";proactiveBubble.setAttribute("role","button");proactiveBubble.setAttribute("tabindex","0");proactiveBubble.setAttribute("aria-label","Open chat with Max");proactiveBubbleText=document.createElement("div");proactiveBubbleText.className="mx-proactive-text";proactiveBubbleText.id="mx-proactive-text";var proactiveClose=document.createElement("button");proactiveClose.type="button";proactiveClose.className="mx-proactive-close";proactiveClose.id="mx-proactive-close";proactiveClose.setAttribute("aria-label","Dismiss");proactiveClose.innerHTML="&times;";proactiveClose.onclick=function(e){if(e){e.preventDefault();e.stopPropagation()}proactiveDismiss("x_clicked")};proactiveBubble.appendChild(proactiveClose);proactiveBubble.appendChild(proactiveBubbleText);proactiveBubble.onclick=function(){proactiveEngage()};proactiveBubble.onkeydown=function(e){if(e&&(e.key==="Enter"||e.key===" "||e.keyCode===13||e.keyCode===32)){e.preventDefault();proactiveEngage()}};launcher.appendChild(proactiveBubble);var btn=document.createElement("button");btn.className="mx-launcher-btn";btn.innerHTML='<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M12 2L13.9 8.6L20 11L13.9 13.4L12 20L10.1 13.4L4 11L10.1 8.6L12 2Z" fill="#fff"/><path d="M19 14L19.8 16.7L22.5 17.5L19.8 18.3L19 21L18.2 18.3L15.5 17.5L18.2 16.7L19 14Z" fill="#fff" opacity="0.4"/></svg>';btn.onclick=function(){debugLog("launcher clicked, state.isOpen="+state.isOpen+", proactiveActive="+proactive.active);if(proactive.active)proactiveEngage();else openWidget()};launcherBtn=btn;launcher.appendChild(btn);shadow.appendChild(launcher);installOverlapDodge()}var DODGE_STEP=8;var DODGE_MARGIN=6;var DODGE_SETTLE_MS=120;var dodgeTimer=null;var dodgeInstalled=false;var DODGE_INTERACTIVE_SEL='a[href],button,input:not([type="hidden"]),select,textarea,[role="button"],[onclick]';function dodgeRectsOf(el){var r=el.getBoundingClientRect();return{left:r.left,right:r.right,top:r.top,bottom:r.bottom}}function dodgeOverlaps(a,b){return a.left<b.right-1&&a.right>b.left+1&&a.top<b.bottom-1&&a.bottom>b.top+1}function dodgeObstacles(column){var out=[];var nodes=document.querySelectorAll(DODGE_INTERACTIVE_SEL);for(var i=0;i<nodes.length;i++){var el=nodes[i];if(el.closest&&el.closest("#app-chat-widget"))continue;var r=el.getBoundingClientRect();if(r.width<8||r.height<8)continue;if(r.right<=column.left||r.left>=column.right)continue;if(r.bottom<=0||r.top>=window.innerHeight)continue;var cs=getComputedStyle(el);if(cs.visibility==="hidden"||cs.display==="none"||cs.pointerEvents==="none")continue;out.push({left:r.left,right:r.right,top:r.top,bottom:r.bottom})}return out}function dodgeOverlapArea(probe,obstacles){var area=0;for(var i=0;i<obstacles.length;i++){var o=obstacles[i];var l=Math.max(probe.left,o.left-DODGE_MARGIN),r=Math.min(probe.right,o.right+DODGE_MARGIN);var t=Math.max(probe.top,o.top-DODGE_MARGIN),b=Math.min(probe.bottom,o.bottom+DODGE_MARGIN);if(r>l&&b>t)area+=(r-l)*(b-t)}return area}function dodgeOffsetFor(base,obstacles){var best=0,bestArea=Infinity;for(var up=0;base.top-up>=DODGE_MARGIN;up+=DODGE_STEP){var probe={left:base.left,right:base.right,top:base.top-up,bottom:base.bottom-up};var area=dodgeOverlapArea(probe,obstacles);if(area===0)return up;if(area<bestArea){bestArea=area;best=up}}return best}function dodgeApply(el,up){var current=parseFloat(el.style.getPropertyValue("--mx-dodge"))||0;if(current===up)return;el.style.setProperty("--mx-dodge",up+"px")}function dodgeElement(el){if(!el||el.style.display==="none")return;var current=parseFloat(el.style.getPropertyValue("--mx-dodge"))||0;var rect=dodgeRectsOf(el);if(rect.right-rect.left<1)return;var base={left:rect.left,right:rect.right,top:rect.top+current,bottom:rect.bottom+current};var column={left:base.left,right:base.right};dodgeApply(el,dodgeOffsetFor(base,dodgeObstacles(column)))}function runOverlapDodge(){dodgeTimer=null;try{if(state.isOpen)return;if(launcher&&launcher.style.display!=="none")dodgeElement(launcher);applyMinimizedBarPadding()}catch(e){debugLog("overlap dodge skipped: "+(e&&e.message))}}var minimizedPaddingBefore=null;function applyMinimizedBarPadding(){if(!minimizedBar||minimizedBar.style.display==="none")return;try{var h=Math.ceil(minimizedBar.getBoundingClientRect().height);
2if(!h)return;if(minimizedPaddingBefore===null)minimizedPaddingBefore=document.body.style.paddingBottom||"";if(document.body.style.paddingBottom!==h+"px")document.body.style.paddingBottom=h+"px"}catch(e){}}function clearMinimizedBarPadding(){if(minimizedPaddingBefore===null)return;try{document.body.style.paddingBottom=minimizedPaddingBefore}catch(e){}minimizedPaddingBefore=null}function scheduleOverlapDodge(){if(dodgeTimer)clearTimeout(dodgeTimer);dodgeTimer=setTimeout(runOverlapDodge,DODGE_SETTLE_MS)}function installOverlapDodge(){if(dodgeInstalled)return;dodgeInstalled=true;try{window.addEventListener("scroll",scheduleOverlapDodge,{passive:true});window.addEventListener("resize",scheduleOverlapDodge,{passive:true});window.addEventListener("load",scheduleOverlapDodge,{passive:true})}catch(e){}scheduleOverlapDodge()}function openWidget(){debugLog("openWidget called, state.isOpen="+state.isOpen+", state.isMinimized="+state.isMinimized+", isMobile="+isMobile());if(state.isOpen){debugLog("openWidget BAILED: already open");return}try{proactiveNotifyOpened()}catch(e){}try{if(isForumContext())state.pageContext=detectPageContext()}catch(e){}ensureAudioUnlocked();clearTabNotificationIfVisible();var wasMinimized=state.isMinimized;state.isOpen=true;state.isMinimized=false;launcher.style.display="none";if(minimizedBar)minimizedBar.style.display="none";clearMinimizedBarPadding();if(!wasMinimized){logQualityEvent("widget_opened",{pageType:state.pageContext?state.pageContext.pageType:null});pushDataLayer("chat_open",{page_type:state.pageContext?state.pageContext.pageType:null})}if(panel&&panel.parentNode){panel.parentNode.removeChild(panel);panel=null}var stale=shadow.querySelectorAll(".mx-sheet.closing, .mx-sidebar.closing");for(var i=0;i<stale.length;i++){if(stale[i].parentNode)stale[i].parentNode.removeChild(stale[i])}if(isMobile()){debugLog("openWidget: building sheet, hasConversation="+state.hasConversation+", messages.length="+state.messages.length);buildMobileSheet()}else{debugLog("openWidget: building sidebar, hasConversation="+state.hasConversation+", messages.length="+state.messages.length);buildDesktopSidebar()}debugLog("openWidget: hasConversation="+state.hasConversation+", sessionToken="+!!state.sessionToken);if(state._agentRestorePending){var savedAgent=state._agentRestorePending;state._agentRestorePending=null;restoreAgentMode(savedAgent)}else if(state._blockedMessage){addBotMessage(state._blockedMessage)}else if(!state.hasConversation){if(state.sessionToken&&state._restoredFromStorage){state._restoredFromStorage=false;fetchHistory()}else if(state.sessionToken){showWelcomeIfReady()}else{initSession()}fetchPdpPartName(state.pageContext)}var inp=shadow.querySelector(".mx-chat-input");if(inp)setTimeout(function(){inp.focus()},100);maybeSendReadReceipt()}function closeWidget(){debugLog("closeWidget called, isOpen="+state.isOpen+", isMinimized="+state.isMinimized+", isMobile="+isMobile()+", destroyingPanel="+!!panel);if(!state.isOpen&&!state.isMinimized)return;proactive.closedByUser=true;proactiveClearTimers();proactive.active=false;proactiveHideBubble();if(consentPending()&&!state.hasConversation){clearEntryMessage("consent declined")}if(state.customerMsgCount>0&&!state.hadPartCard){var lastBot="";for(var i=state.messages.length-1;i>=0;i--){if(state.messages[i].role==="bot"){lastBot=state.messages[i].content;break}}logQualityEvent("abandon_midconv",{messageCount:state.customerMsgCount,lastBotMessage:lastBot.substring(0,300)})}if(isMobile()){minimizeToBar()}else{if(panel){panel.classList.add("closing");setTimeout(function(){if(panel&&panel.parentNode)panel.parentNode.removeChild(panel);panel=null;document.body.style.marginRight=""},300)}state.isOpen=false;launcher.style.display="flex";scheduleOverlapDodge()}}var MAX_ENTRY_MESSAGE_CHARS=500;var MAX_ENTRY_SOURCE_CHARS=40;var ENTRY_DEDUPE_MS=2e3;var MAX_ENTRY_FLUSH_TRIES=60;var ENTRY_FLUSH_INTERVAL_MS=250;var entryPendingMessage=null;var entryFlushTimer=null;var entryFlushTries=0;var entryLastCallKey=null;var entryLastCallAt=0;
2function sanitizeEntrySource(raw){if(typeof raw!=="string")return"";return raw.toLowerCase().replace(/[^a-z0-9-]/g,"").slice(0,MAX_ENTRY_SOURCE_CHARS)}function normalizeOpenOptions(arg){var out={message:"",source:""};if(arg==null)return out;if(typeof arg==="string"){out.message=arg}else if(typeof arg==="object"){if(typeof arg.message==="string")out.message=arg.message;if(typeof arg.source==="string")out.source=arg.source}else{return out}out.message=out.message.trim().slice(0,MAX_ENTRY_MESSAGE_CHARS);out.source=sanitizeEntrySource(out.source);return out}function isDuplicateEntryCall(entry){var key=entry.message+" "+entry.source;var now=Date.now();if(entryLastCallKey===key&&now-entryLastCallAt<ENTRY_DEDUPE_MS){debugLog("[ENTRY] duplicate open+message suppressed");return true}entryLastCallKey=key;entryLastCallAt=now;return false}function applyEntrySource(source){if(!source||state.entrySource)return;state.entrySource=source;debugLog("[ENTRY] source captured: "+source);flushEntrySource()}function flushEntrySource(){if(!state.entrySource||state.entrySourceStamped)return;if(!state.sessionToken||!state.conversationId)return;recordPageVisit(true)}function queueEntryMessage(text){if(!text)return;entryPendingMessage=text;entryFlushTries=0;flushEntryMessage()}function clearEntryMessage(reason){if(!entryPendingMessage)return;debugLog("[ENTRY] dropping held message: "+reason);entryPendingMessage=null;if(entryFlushTimer){clearTimeout(entryFlushTimer);entryFlushTimer=null}}function scheduleEntryFlushRetry(){if(entryFlushTimer||!entryPendingMessage)return;if(entryFlushTries>=MAX_ENTRY_FLUSH_TRIES){clearEntryMessage("widget never became ready");return}entryFlushTries++;entryFlushTimer=setTimeout(function(){entryFlushTimer=null;flushEntryMessage()},ENTRY_FLUSH_INTERVAL_MS)}function flushEntryMessage(){if(!entryPendingMessage)return;if(state._blockedMessage||state._sessionFailed){clearEntryMessage("session unavailable");return}if(!state.sessionToken||!state.conversationId){scheduleEntryFlushRetry();return}if(state.historyLoading){scheduleEntryFlushRetry();return}if(consentPending()&&!state.hasConversation){debugLog("[ENTRY] holding message behind consent gate");return}var inp=shadow.querySelector("#mx-chat-input");if(!inp||state.isSending){scheduleEntryFlushRetry();return}var text=entryPendingMessage;entryPendingMessage=null;if(entryFlushTimer){clearTimeout(entryFlushTimer);entryFlushTimer=null}debugLog("[ENTRY] sending host-supplied message ("+text.length+" chars)");inp.value=text;sendMessage()}function installMaxchatApi(available){var pending=window.maxchat&&window.maxchat.q&&typeof window.maxchat.q.slice==="function"?window.maxchat.q.slice():[];function api(command,options){var cmd=String(command==null?"":command).trim().toLowerCase();if(!available){console.warn("[Max] chat is not available on this page");return}if(cmd==="open"){var entry=normalizeOpenOptions(options);debugLog("maxchat(open) called, state.isOpen="+state.isOpen+", message="+entry.message.length+"ch, source="+(entry.source||"none"));if(entry.source)applyEntrySource(entry.source);openWidget();if(entry.message&&!isDuplicateEntryCall(entry))queueEntryMessage(entry.message)}else if(cmd==="close"){debugLog("maxchat(close) called, state.isOpen="+state.isOpen);closeWidget()}else if(cmd==="toggle"){debugLog("maxchat(toggle) called, state.isOpen="+state.isOpen);if(state.isOpen)closeWidget();else openWidget()}else{console.warn("[Max] unknown maxchat command: "+command)}}window.maxchat=api;for(var i=0;i<pending.length;i++){var call=pending[i];var args=Object.prototype.toString.call(call)==="[object Array]"?call:[call];try{api.apply(null,args)}catch(e){debugLog("maxchat queued call failed: "+e)}}}function minimizeToBar(opts){var fromDrag=!!(opts&&opts.fromDrag);debugLog("minimizeToBar called");state.isOpen=false;state.isMinimized=true;if(overlay){overlay.style.display="none"}if(panel){var closingPanel=panel;panel=null;if(fromDrag){setTimeout(function(){if(closingPanel.parentNode)closingPanel.parentNode.removeChild(closingPanel)},320)}else{closingPanel.classList.add("closing");setTimeout(function(){if(closingPanel.parentNode)closingPanel.parentNode.removeChild(closingPanel)},300)}}if(!minimizedBar){minimizedBar=document.createElement("div");minimizedBar.className="mx-minimized";minimizedBar.onclick=function(){if(minimizedBar._mxDragged){minimizedBar._mxDragged=false;return}debugLog("minimized bar tapped");openWidget()};var handle=document.createElement("div");handle.className="mx-minimized-handle";minimizedBar.appendChild(handle);var row=document.createElement("div");row.className="mx-minimized-row";row.appendChild(makeAvatar(26));var label=document.createElement("span");label.className="mx-minimized-label";label.textContent="Max";row.appendChild(label);var preview=document.createElement("span");preview.className="mx-minimized-preview";preview.id="mx-min-preview";preview.textContent=state.lastBotText||"Parts Assistant";row.appendChild(preview);var chevron=document.createElement("span");chevron.className="mx-minimized-chevron";chevron.innerHTML='<svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M4 10L8 6L12 10" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>';row.appendChild(chevron);minimizedBar.appendChild(row);shadow.appendChild(minimizedBar);attachBarDragUp(minimizedBar)}else{var prev=minimizedBar.querySelector("#mx-min-preview");if(prev)prev.textContent=state.lastBotText||"Parts Assistant";minimizedBar.style.display="flex"}try{requestAnimationFrame(applyMinimizedBarPadding)}catch(e){applyMinimizedBarPadding()}scheduleOverlapDodge();launcher.style.display="none"}function buildDesktopSidebar(){panel=document.createElement("div");panel.className="mx-sidebar";panel.appendChild(buildHeader());panel.appendChild(buildMessageArea());panel.appendChild(buildInputArea());shadow.appendChild(panel);document.body.style.marginRight="380px";if(state.hasConversation){replayMessages()}syncDisclaimer()}var DRAG_DISTANCE_RATIO=.3;var DRAG_VELOCITY=.5;function attachSheetDrag(panelEl,handleEl){var startY=0,lastY=0,lastT=0,currentY=0,velocity=0;var dragging=false,rafId=null;function flush(){rafId=null;panelEl.style.transform="translateY("+currentY+"px)"}function onStart(e){if(!e.touches||e.touches.length!==1)return;var t=e.touches[0];dragging=true;startY=lastY=t.clientY;lastT=e.timeStamp;currentY=0;velocity=0;panelEl.classList.remove("mx-snap");panelEl.classList.add("mx-dragging");panelEl.style.willChange="transform"}function onMove(e){if(!dragging||!e.touches||e.touches.length!==1)return;var y=e.touches[0].clientY;var dt=e.timeStamp-lastT;if(dt>0)velocity=(y-lastY)/dt;lastY=y;lastT=e.timeStamp;var delta=y-startY;if(delta<0)delta=0;currentY=delta;if(e.cancelable)e.preventDefault();if(rafId===null)rafId=requestAnimationFrame(flush)}function onEnd(){if(!dragging)return;dragging=false;if(rafId!==null){cancelAnimationFrame(rafId);rafId=null}panelEl.classList.remove("mx-dragging");panelEl.style.willChange="";var height=panelEl.offsetHeight||window.innerHeight;var passed=currentY>height*DRAG_DISTANCE_RATIO;var fast=velocity>DRAG_VELOCITY;if(!passed&&!fast){panelEl.classList.add("mx-snap");panelEl.style.transform="translateY(0)";setTimeout(function(){panelEl.classList.remove("mx-snap");panelEl.style.transform=""},320);return}panelEl.classList.add("mx-snap");panelEl.style.transform="translateY("+height+"px)";minimizeToBar({fromDrag:true})}handleEl.addEventListener("touchstart",onStart,{passive:false});handleEl.addEventListener("touchmove",onMove,{passive:false});handleEl.addEventListener("touchend",onEnd);handleEl.addEventListener("touchcancel",onEnd)}function attachBarDragUp(barEl){var startY=0,lastY=0,lastT=0,currentY=0,velocity=0;var dragging=false,moved=false,rafId=null;function flush(){rafId=null;barEl.style.transform="translateY("+currentY+"px)"}function onStart(e){if(!e.touches||e.touches.length!==1)return;var t=e.touches[0];dragging=true;moved=false;startY=lastY=t.clientY;lastT=e.timeStamp;currentY=0;velocity=0;barEl.classList.remove("mx-snap");barEl.classList.add("mx-dragging");barEl.style.willChange="transform"}function onMove(e){if(!dragging||!e.touches||e.touches.length!==1)return;var y=e.touches[0].clientY;var dt=e.timeStamp-lastT;if(dt>0)velocity=(y-lastY)/dt;lastY=y;lastT=e.timeStamp;var delta=y-startY;if(delta>0)delta=0;var maxUp=-window.innerHeight*.82;if(delta<maxUp)delta=maxUp;if(Math.abs(delta)>4)moved=true;currentY=delta;if(e.cancelable)e.preventDefault();if(rafId===null)rafId=requestAnimationFrame(flush)}function onEnd(){if(!dragging)return;dragging=false;if(rafId!==null){cancelAnimationFrame(rafId);rafId=null}barEl.classList.remove("mx-dragging");barEl.style.willChange="";if(moved){barEl._mxDragged=true;setTimeout(function(){barEl._mxDragged=false},400)}var target=window.innerHeight*.82;var passed=-currentY>target*DRAG_DISTANCE_RATIO;var fast=velocity<-DRAG_VELOCITY;if(passed||fast){barEl.classList.remove("mx-snap");barEl.style.transform="";openWidget();return}barEl.classList.add("mx-snap");barEl.style.transform="translateY(0)";setTimeout(function(){barEl.classList.remove("mx-snap");barEl.style.transform=""},320)}barEl.addEventListener("touchstart",onStart,{passive:false});barEl.addEventListener("touchmove",onMove,{passive:false});barEl.addEventListener("touchend",onEnd);barEl.addEventListener("touchcancel",onEnd)}function buildMobileSheet(){overlay=shadow.querySelector(".mx-overlay");if(!overlay){overlay=document.createElement("div");overlay.className="mx-overlay";overlay.onclick=function(){minimizeToBar()};shadow.appendChild(overlay)}overlay.style.display="block";panel=document.createElement("div");panel.className="mx-sheet";var dragHandle=document.createElement("div");dragHandle.className="mx-drag-handle";var dragBar=document.createElement("div");dragBar.className="mx-drag-bar";dragHandle.appendChild(dragBar);panel.appendChild(dragHandle);attachSheetDrag(panel,dragHandle);panel.appendChild(buildHeader());panel.appendChild(buildMessageArea());panel.appendChild(buildInputArea());shadow.appendChild(panel);if(state.hasConversation){replayMessages()}syncDisclaimer()}function buildHeader(){var header=document.createElement("div");header.className="mx-header";header.appendChild(makeAvatar(30));var titleDiv=document.createElement("div");titleDiv.className="mx-header-title";var name=document.createElement("span");name.className="mx-header-name";var sub=document.createElement("span");sub.className="mx-header-sub";if(state.agentName){name.textContent=agentFirstName(state.agentName);sub.textContent="Customer Service"}else{name.textContent="Max";sub.textContent="Parts Assistant"}titleDiv.appendChild(name);titleDiv.appendChild(sub);header.appendChild(titleDiv);var shareBtn=document.createElement("button");shareBtn.className="mx-share-btn";shareBtn.id="mx-share-btn";shareBtn.setAttribute("aria-label","Share conversation");var shareSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");shareSvg.setAttribute("width","14");shareSvg.setAttribute("height","14");shareSvg.setAttribute("viewBox","0 0 24 24");shareSvg.setAttribute("fill","none");shareSvg.setAttribute("stroke","currentColor");shareSvg.setAttribute("stroke-width","2");shareSvg.setAttribute("stroke-linecap","round");shareSvg.setAttribute("stroke-linejoin","round");var sharePath1=document.createElementNS("http://www.w3.org/2000/svg","path");sharePath1.setAttribute("d","M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71");
2var sharePath2=document.createElementNS("http://www.w3.org/2000/svg","path");sharePath2.setAttribute("d","M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71");shareSvg.appendChild(sharePath1);shareSvg.appendChild(sharePath2);shareBtn.appendChild(shareSvg);shareBtn.onclick=handleShare;header.appendChild(shareBtn);var soundBtn=document.createElement("button");soundBtn.className="mx-sound-btn";soundBtn.id="mx-sound-btn";updateSoundButton(soundBtn);soundBtn.onclick=function(){var muted=!soundMuted();setSoundMuted(muted);updateSoundButton(soundBtn);if(!muted){ensureAudioUnlocked();playNotifySound()}};header.appendChild(soundBtn);var closeBtn=document.createElement("button");closeBtn.className="mx-close-btn";closeBtn.innerHTML='<svg width="12" height="12" viewBox="0 0 12 12" fill="none"><path d="M2.5 2.5L9.5 9.5M9.5 2.5L2.5 9.5" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';closeBtn.onclick=closeWidget;header.appendChild(closeBtn);var toast=document.createElement("div");toast.className="mx-share-toast";toast.id="mx-share-toast";toast.textContent="Link copied!";header.appendChild(toast);return header}function agentFirstName(agentName){return String(agentName||"Agent").trim().split(/\s+/)[0]||"Agent"}function updateHeaderForAgent(agentName){if(!shadow)return;var nameEl=shadow.querySelector(".mx-header-name");var subEl=shadow.querySelector(".mx-header-sub");if(nameEl)nameEl.textContent=agentFirstName(agentName);if(subEl)subEl.textContent="Customer Service";syncDisclaimer()}function resetHeaderToMax(){if(!shadow)return;var nameEl=shadow.querySelector(".mx-header-name");var subEl=shadow.querySelector(".mx-header-sub");if(nameEl)nameEl.textContent="Max";if(subEl)subEl.textContent="Parts Assistant";syncDisclaimer()}function syncDisclaimer(){if(!shadow)return;var d=shadow.querySelector(".mx-disclaimer");if(d)d.style.display=state.agentName?"none":""}function buildMessageArea(){var area=document.createElement("div");area.className="mx-messages";area.id="mx-messages";return area}function buildInputArea(){var wrapper=document.createElement("div");wrapper.className="mx-input-area";if(!state.consentDisplayedAt){state.consentDisplayedAt=(new Date).toISOString()}var pill=document.createElement("div");pill.className="mx-input-pill";var fileInput=document.createElement("input");fileInput.type="file";fileInput.accept="image/*,application/pdf";fileInput.style.display="none";fileInput.id="mx-file-input";fileInput.addEventListener("change",function(){if(this.files&&this.files[0]){handleUpload(this.files[0]);this.value=""}});var cameraBtn=document.createElement("button");cameraBtn.className="mx-camera-btn";cameraBtn.id="mx-camera-btn";cameraBtn.setAttribute("aria-label","Take photo of model label");var camSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");camSvg.setAttribute("width","22");camSvg.setAttribute("height","22");camSvg.setAttribute("viewBox","0 0 24 24");camSvg.setAttribute("fill","none");camSvg.setAttribute("stroke","currentColor");camSvg.setAttribute("stroke-width","1.8");camSvg.setAttribute("stroke-linecap","round");camSvg.setAttribute("stroke-linejoin","round");var camPath=document.createElementNS("http://www.w3.org/2000/svg","path");camPath.setAttribute("d","M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z");var camCircle=document.createElementNS("http://www.w3.org/2000/svg","circle");camCircle.setAttribute("cx","12");camCircle.setAttribute("cy","13");camCircle.setAttribute("r","4");camSvg.appendChild(camPath);camSvg.appendChild(camCircle);cameraBtn.appendChild(camSvg);cameraBtn.onclick=function(){fileInput.click()};if(isMobile())cameraBtn.classList.add("mobile-show");pill.appendChild(cameraBtn);pill.appendChild(fileInput);var attachBtn=document.createElement("button");attachBtn.className="mx-attach-btn";attachBtn.id="mx-attach-btn";attachBtn.setAttribute("aria-label","Upload a photo");var clipSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");clipSvg.setAttribute("width","20");clipSvg.setAttribute("height","20");clipSvg.setAttribute("viewBox","0 0 24 24");clipSvg.setAttribute("fill","none");clipSvg.setAttribute("stroke","currentColor");clipSvg.setAttribute("stroke-width","1.8");clipSvg.setAttribute("stroke-linecap","round");clipSvg.setAttribute("stroke-linejoin","round");var clipPath=document.createElementNS("http://www.w3.org/2000/svg","path");clipPath.setAttribute("d","M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48");clipSvg.appendChild(clipPath);attachBtn.appendChild(clipSvg);attachBtn.onclick=function(){fileInput.click()};if(isMobile())attachBtn.classList.add("mobile-hide");pill.appendChild(attachBtn);var inp=document.createElement("textarea");inp.className="mx-chat-input";inp.id="mx-chat-input";inp.placeholder="Model #, part #, or describe your issue";inp.rows=1;inp.addEventListener("keydown",function(e){if(e.key==="Enter"&&!e.shiftKey){e.preventDefault();sendMessage()}});inp.addEventListener("input",function(){this.style.height="auto";this.style.height=Math.min(this.scrollHeight,80)+"px";if(this.value.length>0){scheduleCustomerTyping()}scheduleDraftPreview()});inp.addEventListener("paste",function(e){if(!e.clipboardData||!e.clipboardData.items)return;for(var i=0;i<e.clipboardData.items.length;i++){var item=e.clipboardData.items[i];if(item.kind==="file"){e.preventDefault();var f=item.getAsFile();if(f&&ATTACHMENT_TYPES[f.type])handleUpload(f);return}}});pill.appendChild(inp);var sendBtn=document.createElement("button");sendBtn.className="mx-send-btn";
2sendBtn.innerHTML='<svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M3 8H13M13 8L8.5 3.5M13 8L8.5 12.5" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';sendBtn.onclick=sendMessage;pill.appendChild(sendBtn);wrapper.appendChild(pill);if(consentPending()&&!state.hasConversation){pill.classList.add("mx-locked");inp.disabled=true;sendBtn.disabled=true;cameraBtn.disabled=true;attachBtn.disabled=true}var disclaimer=document.createElement("div");disclaimer.className="mx-disclaimer";disclaimer.textContent="AI-generated \xb7 May not be 100% accurate";wrapper.appendChild(disclaimer);var consent=document.createElement("div");consent.className="mx-consent";var termsLink=document.createElement("a");termsLink.href=CONSENT_TERMS_URL;termsLink.target="_blank";termsLink.rel="noopener noreferrer";termsLink.textContent="Terms";var privacyLink=document.createElement("a");privacyLink.href=CONSENT_PRIVACY_URL;privacyLink.target="_blank";privacyLink.rel="noopener noreferrer";privacyLink.textContent="Privacy";consent.appendChild(document.createTextNode(isForumContext()?"By chatting, you agree that this conversation will be recorded. You may be assisted by AI. ":"By chatting, you agree that this conversation will be recorded. You may be assisted by AI and/or a human team member. "));consent.appendChild(termsLink);consent.appendChild(document.createTextNode(" | "));consent.appendChild(privacyLink);wrapper.appendChild(consent);return wrapper}function isForumContext(){var ctx=state.pageContext;if(ctx&&ctx.pageType==="forum")return true;try{if((window.location.hostname||"").toLowerCase()==="forum.appliancepartspros.com")return true;if((document.referrer||"").toLowerCase().indexOf("forum.appliancepartspros.com")!==-1)return true}catch(e){}return false}function getWelcomeContent(){if(state.proactiveContext&&state.proactiveContext.welcome){return state.proactiveContext.welcome}var ctx=state.pageContext;var pt=ctx?ctx.pageType:"other";if(pt==="homepage"){return{greeting:"Hi, I'm Max",subtext:"I can help you find the right part.",chips:["I have a model or part number","Something's broken, help me fix it"],placeholder:"Model #, part #, or describe your issue"}}if(pt==="model"){var label=ctx.modelNumber||"your appliance";if(ctx.brand)label=ctx.brand+" "+(ctx.applianceType||label);return{greeting:"Need help with your "+label+"?",subtext:"I already have your model loaded.",chips:[],placeholder:"What part do you need, or what's going wrong?"}}if(pt==="part"){var pName=ctx.partName||"this part";return{greeting:"Got a question about this "+pName+"?",subtext:null,chips:["Will this fit my model?"],placeholder:"Ask about this part..."}}if(pt==="diagram"){var dLabel="your appliance";if(ctx.brand)dLabel=ctx.brand+" "+(ctx.applianceType||"appliance");return{greeting:"Looking at parts for your "+dLabel+"?",subtext:null,chips:["Help me find the right part"],placeholder:"Which part do you need?"}}if(pt==="search"){return{greeting:"Can't find what you need?",subtext:null,chips:["Help me find my part"],placeholder:"Describe what you're looking for"}}if(pt==="catalog"){var catLabel="";
2if(ctx.brand&&ctx.applianceType){catLabel=ctx.brand+" "+ctx.applianceType}else if(ctx.brand){catLabel=ctx.brand}else if(ctx.applianceType){catLabel=ctx.applianceType}return{greeting:catLabel?"Looking for a "+catLabel+" part?":"Looking for a specific part?",subtext:"Tell me your model number and I can narrow it down.",chips:["I have my model number","Help me find my model number"],placeholder:"Model # or describe what you need"}}if(pt==="repair-help"){return{greeting:"Need more help with this repair?",subtext:null,chips:["Help me find the right part","Something's not working"],placeholder:"Describe your issue or enter a model #"}}if(pt==="story"){return{greeting:"Working on a similar repair?",subtext:"I can help you find the parts you need.",chips:["Find parts for my model","I need help diagnosing"],placeholder:"Model # or describe your issue"}}if(pt==="qa"){return{greeting:"Have a question about this part?",subtext:null,chips:["Will this fit my model?","Help me find a different part"],placeholder:"Ask about this part..."}}if(pt==="forum"){var ft=ctx.forumThread;if(ft&&(ft.modelNumber||ft.brand||ft.symptom)){var applianceLabel="";if(ft.brand&&ft.modelNumber)applianceLabel=ft.brand+" "+ft.modelNumber;else if(ft.modelNumber)applianceLabel=ft.modelNumber;else if(ft.brand)applianceLabel=ft.brand+" appliance";var symptomText=ft.symptom?ft.symptom.replace(/[-_]+/g," ").trim():"";var fGreeting=applianceLabel?"Need help with your "+applianceLabel+"?":"Need help with this repair?";var fSub;if(symptomText&&applianceLabel){fSub="I can see this thread is about a "+symptomText+" issue. Tell me what's happening and I'll diagnose it and find the right parts."}else if(applianceLabel){fSub="I can see this thread is about your "+applianceLabel+". Tell me what's happening and I'll diagnose it and find the right parts."}else{fSub="Tell me what's going wrong and I'll diagnose it and find the right parts."}return{greeting:fGreeting,subtext:fSub,chips:["Help me diagnose this","Find the right part"],placeholder:symptomText?"Tell me more about the "+symptomText:"What's going wrong?"}}return{greeting:"Need help with your appliance?",subtext:"Tell me your model number and what's going wrong, and I'll diagnose it and find the right parts.",chips:["Help me find the right part","Something's not working"],placeholder:"Model # and what's wrong"}}if(pt==="cart"){var cartItems=state.pageContext&&state.pageContext.cartItems;if(cartItems&&cartItems.length>0){var firstName=cartItems[0].name||"your parts";var shortName=firstName.length>30?firstName.substring(0,30).replace(/\s\S*$/,"")+"...":firstName;return{greeting:"I see "+(cartItems.length===1?shortName:cartItems.length+" items")+" in your cart",subtext:"Need help with installation, compatibility, or finding additional parts?",chips:["Will this fit my model?","Do I need anything else?"],placeholder:"Ask about a part in your cart..."}}return{greeting:"Questions about your order?",subtext:null,chips:["Will this fit my model?"],placeholder:"Ask about a part in your cart..."}}if(pt==="account"){return{greeting:"Need help with your order?",subtext:null,chips:["I need to find a part","Help with an order"],placeholder:"How can I help?"}}return{greeting:"Hi, I'm Max",subtext:"I can help you find the right part.",chips:["I have a model or part number","Something's broken, help me fix it"],placeholder:"Model #, part #, or describe your issue"}}function showWelcome(welcome){var container=shadow.querySelector("#mx-messages");if(!container)return;var welcomeDiv=document.createElement("div");welcomeDiv.className="mx-welcome";welcomeDiv.id="mx-welcome";var avatarWrap=document.createElement("div");avatarWrap.className="mx-welcome-avatar";avatarWrap.appendChild(makeAvatar(44));welcomeDiv.appendChild(avatarWrap);var greeting=document.createElement("div");greeting.className="mx-welcome-greeting";greeting.textContent=welcome.greeting;welcomeDiv.appendChild(greeting);if(welcome.subtext){var sub=document.createElement("div");sub.className="mx-welcome-sub";sub.textContent=welcome.subtext;welcomeDiv.appendChild(sub)}if(welcome.chips&&welcome.chips.length>0){var chipsDiv=document.createElement("div");chipsDiv.className="mx-welcome-chips";welcome.chips.forEach(function(text){var chip=document.createElement("button");chip.className="mx-chip";chip.textContent=text;chip.onclick=function(){handleChipClick(text)};chipsDiv.appendChild(chip)});welcomeDiv.appendChild(chipsDiv)}container.appendChild(welcomeDiv);var inp=shadow.querySelector("#mx-chat-input");if(inp)inp.placeholder=welcome.placeholder;if(state.proactiveContext)state.proactiveContext=null}function clearWelcome(){var el=shadow.querySelector("#mx-welcome");if(el)el.remove()}function getStoredConsent(){try{var parsed=JSON.parse(localStorage.getItem(CONSENT_FLAG_KEY)||"null");if(parsed&&parsed.version===CONSENT_VERSION&&typeof parsed.acceptedAt==="string"){return parsed}}catch(e){}return null}function storeConsentFlag(acceptedAt){try{localStorage.setItem(CONSENT_FLAG_KEY,JSON.stringify({version:CONSENT_VERSION,acceptedAt:acceptedAt}))}catch(e){}}function getConsentAcceptedAt(){if(state.consentAcceptedAt)return state.consentAcceptedAt;var stored=getStoredConsent();return stored?stored.acceptedAt:null}function consentPending(){return!getConsentAcceptedAt()}function setComposerEnabled(enabled){if(!shadow)return;var pill=shadow.querySelector(".mx-input-pill");
2if(pill){if(enabled)pill.classList.remove("mx-locked");else pill.classList.add("mx-locked")}var inp=shadow.querySelector("#mx-chat-input");if(inp)inp.disabled=!enabled;var sendBtn=shadow.querySelector(".mx-send-btn");if(sendBtn)sendBtn.disabled=!enabled;var cameraBtn=shadow.querySelector("#mx-camera-btn");if(cameraBtn)cameraBtn.disabled=!enabled;var attachBtn=shadow.querySelector("#mx-attach-btn");if(attachBtn)attachBtn.disabled=!enabled}function recordConsent(){if(!state.sessionToken||!state.conversationId)return;var acceptedAt=getConsentAcceptedAt();if(!acceptedAt)return;if(state._consentRecordedFor===state.conversationId)return;state._consentRecordedFor=state.conversationId;fetch(API_BASE+"/api/chat/consent",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,acceptedAt:acceptedAt,displayedAt:state.consentDisplayedAt,version:CONSENT_VERSION})}).catch(function(){state._consentRecordedFor=null})}function showConsentGate(){var container=shadow.querySelector("#mx-messages");if(!container)return;setComposerEnabled(false);var inp=shadow.querySelector("#mx-chat-input");if(inp)inp.placeholder=getWelcomeContent().placeholder;if(shadow.querySelector("#mx-consent-gate"))return;var wrap=document.createElement("div");wrap.id="mx-consent-gate";var row=document.createElement("div");row.className="mx-msg-row bot";row.appendChild(makeAvatar(28));var bubble=document.createElement("div");bubble.className="mx-msg-bubble bot";bubble.innerHTML=renderBotMarkdown(isForumContext()?CONSENT_GATE_MESSAGE_FORUM:CONSENT_GATE_MESSAGE);row.appendChild(bubble);wrap.appendChild(row);var chipsDiv=document.createElement("div");chipsDiv.className="mx-inline-chips";chipsDiv.id="mx-consent-chip";var chip=document.createElement("button");chip.className="mx-chip";chip.textContent=CONSENT_CHIP_LABEL;chip.onclick=acceptConsent;chipsDiv.appendChild(chip);wrap.appendChild(chipsDiv);container.appendChild(wrap);container.scrollTop=container.scrollHeight}function acceptConsent(){if(state.consentAcceptedAt)return;state.consentAcceptedAt=(new Date).toISOString();storeConsentFlag(state.consentAcceptedAt);var chipEl=shadow.querySelector("#mx-consent-chip");if(chipEl)chipEl.remove();var noteEl=shadow.querySelector("#mx-consent-handoff-note");if(noteEl)noteEl.remove();setComposerEnabled(true);recordConsent();showWelcome(getWelcomeContent());var inp=shadow.querySelector("#mx-chat-input");if(inp)setTimeout(function(){inp.focus()},50);flushEntryMessage()}function showWelcomeOrConsentGate(){if(consentPending()){showConsentGate()}else{showWelcome(getWelcomeContent());recordConsent()}}function addBotMessage(text,messageId){state.hasConversation=true;clearWelcome();var container=shadow.querySelector("#mx-messages");if(!container)return;debugLog("message rendered: role=bot, contentLength="+text.length);state.lastBotText=text.substring(0,100);var row=document.createElement("div");row.className="mx-msg-row bot";row.appendChild(makeAvatar(28));var bubble=document.createElement("div");bubble.className="mx-msg-bubble bot";bubble.innerHTML=renderBotMarkdown(text);row.appendChild(bubble);container.appendChild(row);if(messageId){addFeedbackButtons(container,messageId)}state.messages.push({role:"bot",content:text,messageId:messageId});updateShareButton();container.scrollTop=container.scrollHeight;return row}function addFeedbackButtons(container,messageId){var fb=document.createElement("div");fb.className="mx-feedback";fb.setAttribute("data-mid",messageId);var sz=isMobile()?18:14;function upSvg(color){return'<svg width="'+sz+'" height="'+sz+'" viewBox="0 0 24 24" fill="none" stroke="'+color+'" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M7 10v11"/><path d="M14 3l-1 6h6.28a2 2 0 0 1 1.96 2.39l-1.4 7A2 2 0 0 1 16.88 20H7V10l4-7h2a2 2 0 0 1 1 1.85V3z"/></svg>'}function downSvg(color){return'<svg width="'+sz+'" height="'+sz+'" viewBox="0 0 24 24" fill="none" stroke="'+color+'" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M17 14V3"/>
2<path d="M10 21l1-6H4.72a2 2 0 0 1-1.96-2.39l1.4-7A2 2 0 0 1 6.12 4H17v10l-4 7h-2a2 2 0 0 1-1-1.85V21z"/></svg>'}var rated=null;var upBtn=document.createElement("button");upBtn.className="mx-fb-btn";upBtn.innerHTML=upSvg(C.t3);upBtn.onclick=function(){if(rated==="positive")return;rated="positive";fb.setAttribute("data-rated","positive");sendFeedback(messageId,"positive");upBtn.classList.add("active");upBtn.classList.remove("dimmed");upBtn.innerHTML=upSvg(C.navy);downBtn.classList.remove("active");downBtn.classList.add("dimmed");downBtn.innerHTML=downSvg(C.t3)};var downBtn=document.createElement("button");downBtn.className="mx-fb-btn";downBtn.innerHTML=downSvg(C.t3);downBtn.onclick=function(){if(rated==="negative")return;rated="negative";fb.setAttribute("data-rated","negative");sendFeedback(messageId,"negative");var botMsg="";var userQuery="";for(var i=state.messages.length-1;i>=0;i--){if(!botMsg&&state.messages[i].messageId===messageId)botMsg=state.messages[i].content;if(!userQuery&&state.messages[i].role==="customer")userQuery=state.messages[i].content;if(botMsg&&userQuery)break}logQualityEvent("thumbs_down",{messageText:botMsg.substring(0,300),userQuery:userQuery.substring(0,300)},messageId);downBtn.classList.add("active");downBtn.classList.remove("dimmed");downBtn.innerHTML=downSvg(C.navy);upBtn.classList.remove("active");upBtn.classList.add("dimmed");upBtn.innerHTML=upSvg(C.t3)};fb.appendChild(upBtn);fb.appendChild(downBtn);container.appendChild(fb)}function addInlineChips(replies){var container=shadow.querySelector("#mx-messages");if(!container)return;var chipsDiv=document.createElement("div");chipsDiv.className="mx-inline-chips";chipsDiv.id="mx-inline-chips";replies.forEach(function(text){var chip=document.createElement("button");chip.className="mx-chip";chip.textContent=text;chip.onclick=function(){handleChipClick(text)};chipsDiv.appendChild(chip)});container.appendChild(chipsDiv)}function removeInlineChips(){var el=shadow.querySelector("#mx-inline-chips");if(el)el.remove()}function addVideoCard(video){var container=shadow.querySelector("#mx-messages");if(!container)return;var wrap=document.createElement("div");wrap.className="mx-vid";var card=document.createElement("div");card.className="mx-vid-card";var thumbImg=document.createElement("img");thumbImg.className="mx-vid-thumb";thumbImg.src="https://img.youtube.com/vi/"+video.youtubeId+"/hqdefault.jpg";thumbImg.alt=video.title;card.appendChild(thumbImg);var playBtn=document.createElement("div");playBtn.className="mx-vid-play";var playSvg=document.createElementNS("http://www.w3.org/2000/svg","svg");playSvg.setAttribute("viewBox","0 0 24 24");var playPath=document.createElementNS("http://www.w3.org/2000/svg","path");playPath.setAttribute("d","M8 5v14l11-7z");playSvg.appendChild(playPath);playBtn.appendChild(playSvg);card.appendChild(playBtn);var title=document.createElement("div");title.className="mx-vid-title";title.textContent=video.title;card.appendChild(title);card.onclick=function(){var iframe=document.createElement("iframe");iframe.className="mx-vid-iframe";iframe.src="https://www.youtube.com/embed/"+video.youtubeId+"?autoplay=1";iframe.allow="autoplay; encrypted-media";iframe.allowFullscreen=true;thumbImg.remove();playBtn.remove();card.insertBefore(iframe,title);card.style.cursor="default"};wrap.appendChild(card);if(video.brandNote){var note=document.createElement("div");note.className="mx-vid-brand-note";note.textContent=video.brandNote;wrap.appendChild(note)}container.appendChild(wrap)}function addCustomerMessage(text){state.hasConversation=true;state.customerMsgCount++;state.lastCustomerMsg=text;startIdleTimer();debugLog("message rendered: role=customer, contentLength="+text.length);clearWelcome();var container=shadow.querySelector("#mx-messages");if(!container)return;var row=document.createElement("div");row.className="mx-msg-row user";row.setAttribute("data-mx-sent-at",String(Date.now()));var bubble=document.createElement("div");bubble.className="mx-msg-bubble user";bubble.textContent=text;row.appendChild(bubble);container.appendChild(row);state.agentReadAt=null;removeSeenIndicator();state.messages.push({role:"customer",content:text});container.scrollTop=container.scrollHeight}function removeSeenIndicator(){if(!shadow)return;var el=shadow.querySelector("#mx-seen-indicator");if(el&&el.parentNode)el.parentNode.removeChild(el)}function updateSeenIndicator(){if(!shadow||!state.agentMode)return;removeSeenIndicator();if(!state.agentReadAt)return;var container=shadow.querySelector("#mx-messages");if(!container)return;var rows=container.querySelectorAll(".mx-msg-row.user");if(!rows.length)return;var lastRow=rows[rows.length-1];var readAtMs=new Date(state.agentReadAt).getTime();if(!isFinite(readAtMs))return;var sentAtMs=Number(lastRow.getAttribute("data-mx-sent-at")||0);if(sentAtMs&&sentAtMs>readAtMs)return;var el=document.createElement("div");el.id="mx-seen-indicator";el.textContent="Seen";el.style.cssText="font-size:11px;color:"+C.t3+";text-align:right;margin:2px 14px 0;font-family:"+FONT+";";if(lastRow.nextSibling)container.insertBefore(el,lastRow.nextSibling);else container.appendChild(el)}function addAgentMessage(text,agentName){state.hasConversation=true;state.lastBotText=(text||"").substring(0,100);clearWelcome();var container=shadow.querySelector("#mx-messages");if(!container)return;var displayName=agentName||state.agentName||"Agent";var row=document.createElement("div");row.className="mx-msg-row bot";var avatar=document.createElement("div");avatar.style.width="28px";avatar.style.height="28px";avatar.style.borderRadius="50%";avatar.style.background="#0066CC";avatar.style.color="#fff";avatar.style.display="flex";avatar.style.alignItems="center";avatar.style.justifyContent="center";avatar.style.fontSize="11px";avatar.style.fontWeight="600";avatar.style.flex="0 0 28px";avatar.textContent=(displayName.match(/[A-Za-z]/g)||["A"]).slice(0,2).join("").toUpperCase();row.appendChild(avatar);var bubble=document.createElement("div");bubble.className="mx-msg-bubble bot";var label=document.createElement("div");label.style.fontSize="10px";label.style.fontWeight="600";label.style.letterSpacing="0.05em";label.style.textTransform="uppercase";label.style.color="#0066CC";label.style.marginBottom="4px";label.textContent=displayName;bubble.appendChild(label);var body=document.createElement("div");body.innerHTML=linkifyAgentText(text);body.style.whiteSpace="pre-wrap";bubble.appendChild(body);row.appendChild(bubble);container.appendChild(row);state.messages.push({role:"agent",content:text,agentName:displayName});container.scrollTop=container.scrollHeight}function addAgentSystemMessage(text){var container=shadow.querySelector("#mx-messages");if(!container)return;
2var note=document.createElement("div");note.style.fontSize="11px";note.style.color="#6B6F76";note.style.textAlign="center";note.style.margin="12px 0";note.style.fontStyle="italic";note.textContent=text;container.appendChild(note);state.messages.push({role:"system",content:text});container.scrollTop=container.scrollHeight}function addGenericAgentAssignedNotice(){if(state.agentAssigned||!shadow)return;var container=shadow.querySelector("#mx-messages");if(!container)return;state.agentAssigned=true;var note=document.createElement("div");note.id="mx-agent-assigned-generic";note.style.cssText="font-size:11px;color:#6B6F76;text-align:center;margin:12px 0;font-style:italic;";note.textContent="You're now connected with our team. They'll be right with you.";container.appendChild(note);state.messages.push({role:"system",content:note.textContent});container.scrollTop=container.scrollHeight}function removeGenericAgentAssignedNotice(){if(!shadow)return;var el=shadow.querySelector("#mx-agent-assigned-generic");if(el&&el.parentNode)el.parentNode.removeChild(el)}var AGENT_MODE_STORAGE_KEY="alc_agent_mode";var AGENT_MODE_MAX_AGE_MS=24*60*60*1e3;var RESOLVED_FLAG_KEY="mx_session_resolved";function persistAgentMode(){if(!state.agentMode||!state.conversationId)return;var payload=JSON.stringify({conversationId:state.conversationId,sessionToken:state.sessionToken,alcConversationId:state.alcConversationId,streamUrl:state.alcStreamUrl,agentName:state.agentName,lastSeen:state.agentStreamLastSeen,enteredAt:Date.now()});try{sessionStorage.setItem(AGENT_MODE_STORAGE_KEY,payload)}catch(e){}try{localStorage.setItem(AGENT_MODE_STORAGE_KEY,payload)}catch(e){}}function clearAgentModeStorage(){try{sessionStorage.removeItem(AGENT_MODE_STORAGE_KEY)}catch(e){}try{localStorage.removeItem(AGENT_MODE_STORAGE_KEY)}catch(e){}}function enterAgentMode(opts){if(state.agentMode){if(opts&&opts.alcConversationId&&!state.alcConversationId){state.alcConversationId=opts.alcConversationId}if(opts&&opts.streamUrl&&!state.alcStreamUrl){state.alcStreamUrl=opts.streamUrl}persistAgentMode();return}state.agentMode=true;state.handoffCompleted=true;try{localStorage.removeItem(RESOLVED_FLAG_KEY)}catch(e){}if(!consentPending())setComposerEnabled(true);clearIdleTimer();state.alcConversationId=opts&&opts.alcConversationId||null;state.alcStreamUrl=opts&&opts.streamUrl||null;state.surveySubmitted=false;state.surveyShownForEventId=null;state.bypassAgentSend=false;state.maxHelpDuringWait=false;state.waitHelpOffered=false;state.agentAssigned=false;if(!opts||!opts.suppressConnecting){addAgentSystemMessage("Connecting you with a team member...")}persistAgentMode();if(state.alcStreamUrl)startAgentStream(state.alcStreamUrl);startPageTracking();startHeartbeat();if(!opts||!opts.suppressConnecting){var initialWait=opts&&typeof opts.estimatedWaitSeconds==="number"?opts.estimatedWaitSeconds:null;var initialPos=opts&&typeof opts.queuePosition==="number"?opts.queuePosition:null;var initialText=formatQueueStatus(initialPos,initialWait);if(initialText)showOrUpdateQueueStatus(initialText);startQueueStatusPolling();startWaitingTimer()}}function startWaitingTimer(){clearWaitingTimer();state.waitingTimerId=setTimeout(function(){if(!state.agentMode||state.agentName||state.waitHelpOffered)return;offerMaxHelpWhileWaiting()},6e4)}function clearWaitingTimer(){if(state.waitingTimerId){try{clearTimeout(state.waitingTimerId)}catch(e){}state.waitingTimerId=null}}function offerMaxHelpWhileWaiting(){state.waitHelpOffered=true;addBotMessage("I'm sorry about the wait - all our agents are currently helping other customers. Would you like me to try to help while you wait? The agent will see our full conversation and pick up where we left off.");addInlineChips(["Yes, help me","No, I'll wait"])}function acceptMaxHelpDuringWait(){state.bypassAgentSend=true;state.maxHelpDuringWait=true;removeInlineChips();hideQueueStatus();addAgentSystemMessage("Okay! Chatting with Max while we wait. You'll switch back to the agent as soon as they pick up.")}function declineMaxHelpDuringWait(){removeInlineChips();addBotMessage("No problem, hang tight! You're in the queue.")}function showOrUpdateQueueStatus(text){if(!shadow)return;var container=shadow.querySelector("#mx-messages");if(!container)return;var el=shadow.querySelector("#mx-queue-status");
2if(!el){el=document.createElement("div");el.id="mx-queue-status";el.style.cssText="font-size:12px;color:#6B6F76;text-align:center;margin:4px 12px;font-style:italic;";container.appendChild(el)}el.textContent=text;container.scrollTop=container.scrollHeight}function hideQueueStatus(){if(!shadow)return;var el=shadow.querySelector("#mx-queue-status");if(el&&el.parentNode)el.parentNode.removeChild(el)}function formatQueueStatus(queuePosition,estimatedWaitSeconds){var waitText=null;if(typeof estimatedWaitSeconds==="number"&&estimatedWaitSeconds>0){var mins=Math.max(1,Math.round(estimatedWaitSeconds/60));waitText="about "+mins+" minute"+(mins===1?"":"s")}if(typeof queuePosition==="number"&&queuePosition>0){if(waitText)return"You're #"+queuePosition+" in line - estimated wait "+waitText;return"You're #"+queuePosition+" in line"}if(waitText)return"Estimated wait: "+waitText;return null}function startQueueStatusPolling(){stopQueueStatusPolling();state.queueStatusTimer=setInterval(function(){if(!state.agentMode||state.agentName||!state.conversationId||!state.sessionToken){stopQueueStatusPolling();return}fetch(API_BASE+"/api/chat/queue-status/"+encodeURIComponent(state.conversationId)+"?token="+encodeURIComponent(state.sessionToken),{method:"GET",credentials:"include"}).then(function(r){return r.ok?r.json():null}).then(function(data){if(!data||!state.agentMode||state.agentName)return;if(data.agent_assigned){hideQueueStatus();if(!state.agentAssigned){addGenericAgentAssignedNotice();clearWaitingTimer();stopQueueStatusPolling()}return}if(typeof data.reassurance==="string"&&data.reassurance){addBotMessage(data.reassurance)}var text=formatQueueStatus(typeof data.queue_position==="number"?data.queue_position:null,typeof data.estimated_wait_seconds==="number"?data.estimated_wait_seconds:null);if(text&&!state.maxHelpDuringWait){showOrUpdateQueueStatus(text)}else if(!text){hideQueueStatus()}}).catch(function(){})},3e4)}function stopQueueStatusPolling(){if(state.queueStatusTimer){try{clearInterval(state.queueStatusTimer)}catch(e){}state.queueStatusTimer=null}}function sendHeartbeat(){if(!state.agentMode)return;if(!state.sessionToken||!state.conversationId)return;if(state.heartbeatInFlight)return;state.heartbeatInFlight=true;fetch(API_BASE+"/api/chat/heartbeat",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId})}).catch(function(){}).then(function(){state.heartbeatInFlight=false})}function startHeartbeat(){stopHeartbeat();sendHeartbeat();state.heartbeatTimer=setInterval(sendHeartbeat,3e4)}function postCustomerTyping(isTyping,draftText){if(!state.sessionToken||!state.conversationId)return;var body={sessionToken:state.sessionToken,conversationId:state.conversationId,isTyping:!!isTyping};if(typeof draftText==="string")body.draftText=draftText;fetch(API_BASE+"/api/chat/typing",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}).catch(function(){})}function scheduleDraftPreview(){if(!state.agentMode)return;if(state.draftPreviewDebounce){try{clearTimeout(state.draftPreviewDebounce)}catch(e){}}state.draftPreviewDebounce=setTimeout(function(){state.draftPreviewDebounce=null;if(!state.agentMode)return;var inp=shadow.querySelector("#mx-chat-input");var draft=inp&&typeof inp.value==="string"?inp.value:"";if(draft.length>1e3)draft=draft.slice(0,1e3);if(draft===state.lastSentDraft)return;state.lastSentDraft=draft;if(draft.length>0){state.customerTypingActive=true;if(state.customerTypingIdleTimer){try{clearTimeout(state.customerTypingIdleTimer)}catch(e){}}state.customerTypingIdleTimer=setTimeout(function(){state.customerTypingActive=false;state.customerTypingIdleTimer=null;postCustomerTyping(false)},3e3)}postCustomerTyping(draft.length>0,draft)},300)}function notifyCustomerTyping(){if(!state.agentMode)return;if(!state.customerTypingActive){state.customerTypingActive=true;postCustomerTyping(true)}if(state.customerTypingIdleTimer){try{clearTimeout(state.customerTypingIdleTimer)}catch(e){}}state.customerTypingIdleTimer=setTimeout(function(){state.customerTypingActive=false;state.customerTypingIdleTimer=null;postCustomerTyping(false)},3e3)}function scheduleCustomerTyping(){if(!state.agentMode)return;if(state.customerTypingDebounce)return;state.customerTypingDebounce=setTimeout(function(){state.customerTypingDebounce=null;notifyCustomerTyping()},800)}function stopCustomerTyping(){if(state.customerTypingDebounce){try{clearTimeout(state.customerTypingDebounce)}catch(e){}state.customerTypingDebounce=null}if(state.customerTypingIdleTimer){try{clearTimeout(state.customerTypingIdleTimer)}catch(e){}state.customerTypingIdleTimer=null}if(state.draftPreviewDebounce){try{clearTimeout(state.draftPreviewDebounce)}catch(e){}state.draftPreviewDebounce=null}var hadDraft=state.lastSentDraft!=="";state.lastSentDraft="";if(state.customerTypingActive||hadDraft){state.customerTypingActive=false;postCustomerTyping(false,hadDraft?"":undefined)}}function stopHeartbeat(){if(state.heartbeatTimer){try{clearInterval(state.heartbeatTimer)}catch(e){}state.heartbeatTimer=null}state.heartbeatInFlight=false}function isChatVisible(){if(!state.isOpen)return false;try{if(document.visibilityState!=="visible")return false;if(typeof document.hasFocus==="function"&&!document.hasFocus())return false}catch(e){}return true}function clearReadReceiptTimer(){if(state.readReceiptTimer){try{clearTimeout(state.readReceiptTimer)}catch(e){}state.readReceiptTimer=null}}
2function maybeSendReadReceipt(){if(!state.agentMode||!state.lastAgentMsgId)return;if(!state.sessionToken||!state.conversationId)return;if(state.readReceiptSentForId===state.lastAgentMsgId)return;if(!isChatVisible())return;if(state.readReceiptTimer)return;state.readReceiptTimer=setTimeout(function(){state.readReceiptTimer=null;if(!state.agentMode||!state.lastAgentMsgId)return;if(state.readReceiptSentForId===state.lastAgentMsgId)return;if(!isChatVisible())return;state.readReceiptSentForId=state.lastAgentMsgId;fetch(API_BASE+"/api/chat/read-receipt",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,lastReadMessageId:state.lastAgentMsgId})}).catch(function(){})},800)}var SOUND_PREF_KEY="mx_sound_muted";function soundMuted(){try{return localStorage.getItem(SOUND_PREF_KEY)==="1"}catch(e){return false}}function setSoundMuted(muted){try{localStorage.setItem(SOUND_PREF_KEY,muted?"1":"0")}catch(e){}}function ensureAudioUnlocked(){try{var Ctx=window.AudioContext||window.webkitAudioContext;if(!Ctx)return;if(!state._audioCtx)state._audioCtx=new Ctx;if(state._audioCtx.state==="suspended"&&state._audioCtx.resume)state._audioCtx.resume()}catch(e){}}function playNotifySound(){if(soundMuted())return;try{var Ctx=window.AudioContext||window.webkitAudioContext;if(!Ctx)return;if(!state._audioCtx)state._audioCtx=new Ctx;var ctx=state._audioCtx;if(ctx.state==="suspended"&&ctx.resume)ctx.resume();var osc=ctx.createOscillator();var gain=ctx.createGain();osc.type="sine";osc.frequency.value=660;osc.connect(gain);gain.connect(ctx.destination);var now=ctx.currentTime;gain.gain.setValueAtTime(1e-4,now);gain.gain.exponentialRampToValueAtTime(.08,now+.02);gain.gain.exponentialRampToValueAtTime(1e-4,now+.25);osc.start(now);osc.stop(now+.26)}catch(e){}}function startTitleFlash(){if(state._titleFlashTimer)return;if(!state._originalTitle){try{state._originalTitle=document.title}catch(e){state._originalTitle=""}}var on=false;state._titleFlashTimer=setInterval(function(){on=!on;try{document.title=on?"New message - APP":state._originalTitle||"AppliancePartsPros"}catch(e){}},1e3)}function stopTitleFlash(){if(state._titleFlashTimer){try{clearInterval(state._titleFlashTimer)}catch(e){}state._titleFlashTimer=null;if(state._originalTitle){try{document.title=state._originalTitle}catch(e){}}}}function tabBackgrounded(){try{if(document.visibilityState!=="visible")return true;if(typeof document.hasFocus==="function"&&!document.hasFocus())return true}catch(e){}return false}function notifyIncomingAgentMessage(){if(isChatVisible())return;
2if(tabBackgrounded())startTitleFlash();playNotifySound()}function clearTabNotificationIfVisible(){try{var focused=typeof document.hasFocus!=="function"||document.hasFocus();if(document.visibilityState==="visible"&&focused)stopTitleFlash()}catch(e){stopTitleFlash()}}function updateSoundButton(btn){if(!btn)return;var muted=soundMuted();btn.setAttribute("aria-label",muted?"Unmute notification sound":"Mute notification sound");btn.setAttribute("aria-pressed",muted?"true":"false");btn.title=muted?"Notification sound off":"Notification sound on";if(muted){btn.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4z"/><line x1="23" y1="9" x2="17" y2="15"/><line x1="17" y1="9" x2="23" y2="15"/></svg>'}else{btn.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H2v6h4l5 4z"/><path d="M15.5 8.5a5 5 0 0 1 0 7"/><path d="M19.5 5a9 9 0 0 1 0 14"/></svg>'}}function clearIdleTimer(){if(state.idlePromptTimer){try{clearTimeout(state.idlePromptTimer)}catch(e){}state.idlePromptTimer=null}if(state.idleCloseTimer){try{clearTimeout(state.idleCloseTimer)}catch(e){}state.idleCloseTimer=null}}function startIdleTimer(){clearIdleTimer();if(state.agentMode)return;if(!state.sessionToken||!state.conversationId)return;state.idlePromptTimer=setTimeout(triggerIdlePrompt,IDLE_PROMPT_MS)}function triggerIdlePrompt(){state.idlePromptTimer=null;if(state.agentMode)return;if(!state.sessionToken||!state.conversationId)return;addBotMessage("Just checking in - I'm still here if you need anything! This chat will close automatically after a few more minutes of inactivity.");state.idleCloseTimer=setTimeout(triggerIdleClose,IDLE_CLOSE_MS)}function triggerIdleClose(){state.idleCloseTimer=null;if(state.agentMode)return;if(!state.sessionToken||!state.conversationId)return;addBotMessage("Looks like you stepped away, so I closed this chat. If anything else comes up, just open a new chat - happy to help anytime!");sendDisconnectBeacon({useFetch:true});try{localStorage.removeItem("max_session")}catch(e){}state.disconnectBeaconSent=true}function sendDisconnectBeacon(opts){if(state.disconnectBeaconSent)return;if(!state.sessionToken||!state.conversationId)return;state.disconnectBeaconSent=true;var url=API_BASE+"/api/chat/disconnect";var payload=JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId});var useFetch=!!(opts&&opts.useFetch);if(!useFetch&&typeof navigator!=="undefined"&&typeof navigator.sendBeacon==="function"){try{var blob=new Blob([payload],{type:"application/json"});var ok=navigator.sendBeacon(url,blob);if(ok)return}catch(e){}}try{fetch(url,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:payload,keepalive:true}).catch(function(){})}catch(e){}}function isReturnToMaxPhrase(text){if(!text)return false;var t=text.toLowerCase().trim();if(/\b(go\s+)?back\s+to\s+(the\s+)?(max|bot)\b/.test(t))return true;if(/\b(return|switch)\s+(back\s+)?to\s+(the\s+)?(max|bot)\b/.test(t))return true;if(/\btalk\s+to\s+(the\s+)?(max|bot)\b/.test(t))return true;if(/\buse\s+(the\s+)?(max|bot)\b/.test(t))return true;if(/\bmax\s+instead\b/.test(t))return true;if(/\bcancel\s+(the\s+)?(agent|handoff|transfer)\b/.test(t))return true;if(/\bnever\s*mind\b.*\b(bot|max)\b/.test(t))return true;return false}function triggerReturnToMax(){if(!state.sessionToken||!state.conversationId)return;var alcId=state.alcConversationId;exitAgentMode();addAgentSystemMessage("You've been reconnected with Max.");fetch(API_BASE+"/api/chat/return-to-max",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,alcConversationId:alcId})}).catch(function(){})}function showAgentTyping(agentName){if(!shadow||!state.agentMode)return;var container=shadow.querySelector("#mx-messages");if(!container)return;var existing=shadow.querySelector("#mx-agent-typing");
2if(!existing){existing=document.createElement("div");existing.id="mx-agent-typing";existing.className="mx-agent-typing";var label=document.createElement("span");label.id="mx-agent-typing-label";var dots=document.createElement("span");dots.className="mx-agent-typing-dots";for(var i=0;i<3;i++)dots.appendChild(document.createElement("span"));existing.appendChild(label);existing.appendChild(dots);container.appendChild(existing)}var labelEl=shadow.querySelector("#mx-agent-typing-label");if(labelEl)labelEl.textContent=(agentName||state.agentName||"Agent")+" is typing ";container.scrollTop=container.scrollHeight;if(state.agentTypingTimer){try{clearTimeout(state.agentTypingTimer)}catch(e){}}state.agentTypingTimer=setTimeout(hideAgentTyping,4e3)}function hideAgentTyping(){if(state.agentTypingTimer){try{clearTimeout(state.agentTypingTimer)}catch(e){}state.agentTypingTimer=null}if(!shadow)return;var el=shadow.querySelector("#mx-agent-typing");if(el&&el.parentNode)el.parentNode.removeChild(el)}function exitAgentMode(){state.agentMode=false;state.agentRestoring=false;state.pendingAgentMessages=[];state.alcConversationId=null;state.alcStreamUrl=null;state.agentName=null;resetHeaderToMax();state.agentAssigned=false;state.agentStreamLastSeen=null;state.seenAgentMessageIds={};state.bypassAgentSend=false;state.maxHelpDuringWait=false;state.waitHelpOffered=false;state.handoffCompleted=false;state.agentReadAt=null;state.lastAgentMsgId=null;state.readReceiptSentForId=null;clearReadReceiptTimer();removeSeenIndicator();try{if(state.agentStream)state.agentStream.close()}catch(e){}state.agentStream=null;stopAgentPolling();resetAgentStreamBackoff();clearWaitingTimer();stopQueueStatusPolling();stopHeartbeat();hideQueueStatus();removeGenericAgentAssignedNotice();hideAgentTyping();stopPageTracking();clearAgentModeStorage()}function handleResolvedEvent(data){if(!data)return;if(data.id&&state.surveyShownForEventId===data.id)return;state.surveyShownForEventId=data.id||"resolved";state.handoffCompleted=false;state.handoffInFlight=false;try{if(state.agentStream)state.agentStream.close()}catch(e){}state.agentStream=null;stopAgentPolling();resetAgentStreamBackoff();state.agentMode=false;state.agentRestoring=false;hideReconnectingIndicator();try{localStorage.removeItem("max_session")}catch(e){}state.agentAssigned=false;state.agentName=null;state.bypassAgentSend=false;state.maxHelpDuringWait=false;state.waitHelpOffered=false;state.agentReadAt=null;state.lastAgentMsgId=null;state.readReceiptSentForId=null;clearReadReceiptTimer();removeSeenIndicator();clearWaitingTimer();stopQueueStatusPolling();stopHeartbeat();hideQueueStatus();removeGenericAgentAssignedNotice();hideAgentTyping();stopPageTracking();clearAgentModeStorage();try{localStorage.setItem(RESOLVED_FLAG_KEY,"1")}catch(e){}addAgentSystemMessage("This conversation has ended. Thank you for chatting with us!");state.alcConversationId=data.alc_conversation_id||state.alcConversationId;if(data.survey_eligible&&data.survey_token&&!state.surveySubmitted){renderCsatSurvey({token:data.survey_token,alcConversationId:state.alcConversationId})}else{renderEmailTranscriptOffer()}}function handleAutoLeaveMessageEvent(data){if(!data)return;if(data.id&&state.autoLeaveShownForId===data.id)return;state.autoLeaveShownForId=data.id||"auto_leave";try{if(state.agentStream)state.agentStream.close()}catch(e){}state.agentStream=null;stopAgentPolling();resetAgentStreamBackoff();state.agentMode=false;state.agentRestoring=false;hideReconnectingIndicator();try{localStorage.removeItem("max_session")}catch(e){}state.agentAssigned=false;state.bypassAgentSend=false;state.maxHelpDuringWait=false;state.waitHelpOffered=false;state.agentReadAt=null;state.lastAgentMsgId=null;state.readReceiptSentForId=null;clearReadReceiptTimer();removeSeenIndicator();clearWaitingTimer();stopQueueStatusPolling();stopHeartbeat();hideQueueStatus();removeGenericAgentAssignedNotice();hideAgentTyping();stopPageTracking();clearAgentModeStorage();try{localStorage.setItem(RESOLVED_FLAG_KEY,"1")}catch(e){}state.alcConversationId=data.alc_conversation_id||state.alcConversationId;var dept=data&&typeof data.department_name==="string"?data.department_name.trim():"";var who=dept?"our "+dept+" team":"a team member";addAgentSystemMessage("Your message has been saved and "+who+" will follow up within one business day. Thank y
2ou for your patience.");setComposerEnabled(false);renderStartNewConversation()}function handleReopenEvent(data){if(!data)return;if(data.id&&state.seenReopenEventIds&&state.seenReopenEventIds[data.id])return;if(!state.seenReopenEventIds)state.seenReopenEventIds={};if(data.id)state.seenReopenEventIds[data.id]=true;try{localStorage.removeItem(RESOLVED_FLAG_KEY)}catch(e){}state.surveyShownForEventId=null;state.surveySubmitted=false;state.transcriptOffered=false;addAgentSystemMessage("This conversation has been reopened.");if(!state.agentMode){var alcId=data.alc_conversation_id||state.alcConversationId||null;enterAgentMode({alcConversationId:alcId,streamUrl:state.alcStreamUrl||"/api/chat/agent-stream/"+encodeURIComponent(state.conversationId),suppressConnecting:true})}}function isAgentForwardAnswer(contentType,data){return/application\/json/i.test(contentType||"")&&!!data&&data.mode==="agent"&&data.forwarded===true}function resumeStreamCursor(current,since){var s=since?Date.parse(since):NaN;if(!isFinite(s))return current||null;var c=current?Date.parse(current):NaN;return!isFinite(c)||s>c?since:current}function resumeAgentModeAfterForward(data){if(state.agentMode)return;state.agentStreamLastSeen=resumeStreamCursor(state.agentStreamLastSeen,data&&data.stream_since);try{localStorage.removeItem(RESOLVED_FLAG_KEY)}catch(e){}enterAgentMode({alcConversationId:state.alcConversationId||null,streamUrl:"/api/chat/agent-stream/"+encodeURIComponent(state.conversationId),suppressConnecting:true})}function startAgentStream(streamUrl){if(typeof EventSource==="undefined"){debugLog("[AGENT] EventSource unavailable, falling back to polling");return}if(!state.sessionToken)return;try{if(state.agentStream)state.agentStream.close()}catch(e){}var url=API_BASE+streamUrl+"?token="+encodeURIComponent(state.sessionToken);if(state.agentStreamLastSeen){url+="&since="+encodeURIComponent(state.agentStreamLastSeen)}var es=new EventSource(url,{withCredentials:true});state.agentStream=es;es.addEventListener("ready",function(){resetAgentStreamBackoff();if(state.agentPolling)stopAgentPolling();if(state.agentRestoring){state.agentRestoring=false;hideReconnectingIndicator();flushPendingAgentMessages()}});es.addEventListener("agent_message",function(evt){try{applyAgentMessage(JSON.parse(evt.data))}catch(e){debugLog("[AGENT] parse error: "+e.message)}});es.addEventListener("typing",function(evt){if(!state.agentMode)return;try{var data=JSON.parse(evt.data);showAgentTyping(data&&data.agent_name)}catch(e){}});es.addEventListener("event",function(evt){try{applyAgentEvent(JSON.parse(evt.data))}catch(e){}});es.addEventListener("reconnect",function(evt){try{var data=JSON.parse(evt.data);if(data&&data.last_seen_at){state.agentStreamLastSeen=data.last_seen_at;persistAgentMode()}}catch(e){}try{es.close()}catch(e){}state.agentStream=null;setTimeout(function(){if(state.agentMode)startAgentStream(streamUrl)},250)});es.onerror=function(){try{es.close()}catch(e){}state.agentStream=null;state.agentStreamFailCount=(state.agentStreamFailCount||0)+1;if(state.agentStreamFailCount>=3&&!state.agentPolling){startAgentPolling()}var delay=nextAgentStreamDelay();debugLog("[AGENT] SSE error #"+state.agentStreamFailCount+", retry in "+delay+"ms");setTimeout(function(){if(state.agentMode)startAgentStream(streamUrl)},delay)}}function nextAgentStreamDelay(){var base=state.agentStreamBackoffMs||3e3;var jittered=base*(.75+Math.random()*.5);state.agentStreamBackoffMs=Math.min(base*2,6e4);return Math.round(jittered)}function resetAgentStreamBackoff(){state.agentStreamBackoffMs=3e3;state.agentStreamFailCount=0}function applyAgentMessage(data){if(!data)return;if(data.id&&state.seenAgentMessageIds[data.id])return;hideAgentTyping();if(!state.agentName&&data.sender_name){state.agentName=data.sender_name;updateHeaderForAgent(state.agentName);removeGenericAgentAssignedNotice();addAgentSystemMessage("You're now chatting with "+state.agentName);if(!state.agentJoinedPushed){state.agentJoinedPushed=true;pushDataLayer("chat_agent_joined",{source:"agent"})}persistAgentMode();clearWaitingTimer();stopQueueStatusPolling();hideQueueStatus();if(state.bypassAgentSend){state.bypassAgentSend=false;state.maxHelpDuringWait=false}removeInlineChips()}if(data.id)state.seenAgentMessageIds[data.id]=true;if(data.sent_at){state.agentStreamLastSeen=data.sent_at;persistAgentMode()}if(data.content_type==="part_card"&&data.part){renderAgentPartCard(data.part)}else if(data.content_type==="diagram"&&getAgentDiagramUrl(data)){renderAgentDiagram(getAgentDiagramUrl(data),data.content||"")}else if(data.content_type==="attachment"&&getAgentAttachment(data)){renderAgentAttachment(getAgentAttachment(data),data.content||"")}else{addAgentMessage(data.content||"",data.sender_name||null)}if(data.id){state.lastAgentMsgId=data.id;
2maybeSendReadReceipt()}notifyIncomingAgentMessage()}function applyAgentEvent(data){if(!data)return;if(data.event==="resolved"){handleResolvedEvent(data)}else if(data.event==="checkout"){if(data.id&&state.seenCheckoutEventIds[data.id])return;if(data.id)state.seenCheckoutEventIds[data.id]=true;renderCheckoutCard(data.items,data.total,data.sent_by)}else if(data.event==="reassurance"){if(data.id&&state.seenReassuranceEventIds[data.id])return;if(data.id)state.seenReassuranceEventIds[data.id]=true;addAgentSystemMessage(data.message||"Thanks for your patience - the agent is still with you and will be back in just a moment.")}else if(data.event==="assigned"){var assignedName=data.agent_name||"Agent";if(state.agentName===assignedName)return;state.agentName=assignedName;updateHeaderForAgent(assignedName);removeGenericAgentAssignedNotice();addAgentSystemMessage("You're now chatting with "+assignedName);if(!state.agentJoinedPushed){state.agentJoinedPushed=true;pushDataLayer("chat_agent_joined",{source:"agent"})}persistAgentMode();clearWaitingTimer();stopQueueStatusPolling();hideQueueStatus();if(state.bypassAgentSend){state.bypassAgentSend=false;state.maxHelpDuringWait=false}removeInlineChips()}else if(data.event==="read"){if(data.read_at){state.agentReadAt=data.read_at;updateSeenIndicator()}}else if(data.event==="reopen"){handleReopenEvent(data)}else if(data.event==="auto_leave_message"){handleAutoLeaveMessageEvent(data)}}var AGENT_POLL_INTERVAL_MS=12e3;function startAgentPolling(){if(state.agentPolling)return;state.agentPolling=true;debugLog("[AGENT] SSE down, starting polling fallback");pollAgentMessagesOnce();state.agentPollTimer=setInterval(function(){pollAgentMessagesOnce()},Math.round(AGENT_POLL_INTERVAL_MS*(.9+Math.random()*.2)))}function stopAgentPolling(){state.agentPolling=false;if(state.agentPollTimer){try{clearInterval(state.agentPollTimer)}catch(e){}state.agentPollTimer=null}state.agentPollInFlight=false}function pollAgentMessagesOnce(){if(!state.agentMode||!state.conversationId||!state.sessionToken)return;if(state.agentPollInFlight)return;state.agentPollInFlight=true;var sessionId=state.conversationId;fetch(API_BASE+"/api/chat/agent-messages/"+encodeURIComponent(sessionId)+"?token="+encodeURIComponent(state.sessionToken),{method:"GET",credentials:"include"}).then(function(r){return r.ok?r.json():null}).then(function(d){if(d&&Array.isArray(d.messages)){d.messages.forEach(function(m){if(!m)return;if(m.kind==="agent_message")applyAgentMessage(m);else if(m.kind==="agent_event")applyAgentEvent(m)})}}).catch(function(){}).then(function(){state.agentPollInFlight=false})}function flushPendingAgentMessages(){if(!state.pendingAgentMessages||state.pendingAgentMessages.length===0)return;var queue=state.pendingAgentMessages.slice();state.pendingAgentMessages=[];queue.forEach(function(text){fetch(API_BASE+"/api/chat/message",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,message:text})}).catch(function(){})})}function showReconnectingIndicator(){if(!shadow)return;var container=shadow.querySelector("#mx-messages");if(!container)return;if(shadow.querySelector("#mx-agent-reconnecting"))return;var note=document.createElement("div");note.id="mx-agent-reconnecting";note.style.cssText="font-size:11px;color:"+C.t2+";text-align:center;margin:12px 0;font-style:italic;";note.textContent="Reconnecting...";container.appendChild(note);container.scrollTop=container.scrollHeight}function hideReconnectingIndicator(){if(!shadow)return;var el=shadow.querySelector("#mx-agent-reconnecting");if(el&&el.parentNode)el.parentNode.removeChild(el)}function sendPageView(){if(!state.agentMode||!state.alcConversationId||!state.sessionToken||!state.conversationId)return;var pageType=null;try{pageType=(detectPageContext()||{}).pageType||null}catch(e){}fetch(API_BASE+"/api/chat/page-view",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,alc_conversation_id:state.alcConversationId,url:window.location.href,page_title:document.title,page_type:pageType})}).catch(function(){})}function startPageTracking(){if(state.pageTracker)return;var origPush=history.pushState;var origReplace=history.replaceState;var onPop=function(){sendPageView()};history.pushState=function(){var rv=origPush.apply(this,arguments);sendPageView();return rv};history.replaceState=function(){var rv=origReplace.apply(this,arguments);sendPageView();return rv};window.addEventListener("popstate",onPop);state.pageTracker={origPush:origPush,origReplace:origReplace,onPop:onPop};sendPageView()}function stopPageTracking(){if(!state.pageTracker)return;try{history.pushState=state.pageTracker.origPush}catch(e){}try{history.replaceState=state.pageTracker.origReplace}catch(e){}try{window.removeEventListener("popstate",state.pageTracker.onPop)}catch(e){}state.pageTracker=null}function recordPageVisit(force){if(!state.sessionToken||!state.conversationId)return;var ctx;try{ctx=detectPageContext()}catch(e){return}if(!ctx||!ctx.url)return;state.pageContext=ctx;if(!state.browsingHistory)state.browsingHistory=[];var hist=state.browsingHistory;var last=hist.length?hist[hist.length-1]:null;var duplicate=!!(last&&last.url===ctx.url);if(duplicate&&!force)return;if(!duplicate){hist.push({url:ctx.url,pageType:ctx.pageType||"other",model:ctx.modelNumber||null,section:ctx.pageType==="diagram"?ctx.section||null:null,ts:Date.now()});if(hist.length>25)state.browsingHistory=hist.slice(-25)}var pendingSource=state.entrySource&&!state.entrySourceStamped?state.entrySource:undefined;var cid=state.conversationId;var pendingSearches=[];if(!state._siteSearchPingInFlight){try{pendingSearches=pendingSiteSearches(cid)}catch(e){pendingSearches=[]}}if(pendingSearches.length)state._siteSearchPingInFlight=true;
2fetch(API_BASE+"/api/chat/page-navigation",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:cid,pageContext:ctx,browsingHistory:state.browsingHistory.slice(-25),entrySource:pendingSource,recentSearches:pendingSearches.length?pendingSearches:undefined})}).then(function(r){if(pendingSearches.length){state._siteSearchPingInFlight=false;if(r&&r.ok)ackSiteSearches(cid,pendingSearches[pendingSearches.length-1].ts)}if(!pendingSource)return;if(r&&r.ok)state.entrySourceStamped=true;else state.entrySourcePingFailed=true}).catch(function(){if(pendingSearches.length)state._siteSearchPingInFlight=false;if(pendingSource)state.entrySourcePingFailed=true})}function ensureNavTracking(){if(!state.navTracker){var origPush=history.pushState;var origReplace=history.replaceState;var onNav=function(){try{recordPageVisit()}catch(e){}};try{history.pushState=function(){var rv=origPush.apply(this,arguments);onNav();return rv};history.replaceState=function(){var rv=origReplace.apply(this,arguments);onNav();return rv}}catch(e){}try{window.addEventListener("popstate",onNav)}catch(e){}state.navTracker=true}recordPageVisit()}var SITE_SEARCH_KEY="mx_searches";var SITE_SEARCH_ACK_KEY="mx_searches_ack";var SITE_SEARCH_MAX=10;var SITE_SEARCH_QUERY_MAX=200;var SITE_SEARCH_COMMIT_WINDOW_MS=750;var SITE_SEARCH_INPUT_RE=/(^|[$_])tbs?Srch\d*$/;var SITE_SEARCH_TRIGGER_RE=/(^|[$_])bs?Srch\d*$/;var SITE_SEARCH_CONTROL_RE=/[\x00-\x1f\x7f]+/g;function normalizeSiteSearchQuery(raw){if(typeof raw!=="string")return"";var q=raw.replace(SITE_SEARCH_CONTROL_RE," ").replace(/\s+/g," ").trim();if(q.length>SITE_SEARCH_QUERY_MAX)q=q.slice(0,SITE_SEARCH_QUERY_MAX).trim();return q}function readSiteSearches(){try{var arr=JSON.parse(sessionStorage.getItem(SITE_SEARCH_KEY)||"[]");if(!Array.isArray(arr))return[];var out=[];for(var i=0;i<arr.length;i++){var it=arr[i];if(it&&typeof it.q==="string"&&it.q&&typeof it.ts==="number"&&isFinite(it.ts)){out.push({q:it.q,ts:it.ts})}}return out.slice(-SITE_SEARCH_MAX)}catch(e){return[]}}function writeSiteSearches(list){try{sessionStorage.setItem(SITE_SEARCH_KEY,JSON.stringify(list.slice(-SITE_SEARCH_MAX)));return true}catch(e){return false}}function recordSiteSearch(raw){var q=normalizeSiteSearchQuery(raw);if(!q)return null;var list=readSiteSearches();var last=list.length?list[list.length-1]:null;var now=Date.now();if(last){if(last.q.toLowerCase()===q.toLowerCase())return null;if(now-last.ts<SITE_SEARCH_COMMIT_WINDOW_MS)return null}var ts=last&&now<=last.ts?last.ts+1:now;var entry={q:q,ts:ts};list.push(entry);if(!writeSiteSearches(list))return null;debugLog("[SEARCH] captured: "+q);return entry}function readSiteSearchAck(){try{var ack=JSON.parse(sessionStorage.getItem(SITE_SEARCH_ACK_KEY)||"null");return ack&&typeof ack.cid==="string"&&typeof ack.ts==="number"?ack:null}catch(e){return null}}function pendingSiteSearches(conversationId){if(!conversationId)return[];var list=readSiteSearches();if(!list.length)return[];var ack=readSiteSearchAck();var from=ack&&ack.cid===conversationId?ack.ts:0;var out=[];for(var i=0;i<list.length;i++){if(list[i].ts>from)out.push(list[i])}return out}function ackSiteSearches(conversationId,ts){try{sessionStorage.setItem(SITE_SEARCH_ACK_KEY,JSON.stringify({cid:conversationId,ts:ts}))}catch(e){}}function siteSearchControlMatches(el,re){if(!el||el.nodeType!==1)return false;var name=typeof el.getAttribute==="function"&&el.getAttribute("name")||"";var id=typeof el.getAttribute==="function"&&el.getAttribute("id")||el.id||"";return re.test(name)||re.test(id)}function isSiteSearchInput(el){if(!el||el.nodeType!==1||String(el.tagName||"").toUpperCase()!=="INPUT")return false;return siteSearchControlMatches(el,SITE_SEARCH_INPUT_RE)}function isSiteSearchTrigger(el){return siteSearchControlMatches(el,SITE_SEARCH_TRIGGER_RE)}function firstSiteSearchInputIn(container){if(!container||typeof container.querySelectorAll!=="function")return null;var inputs=container.querySelectorAll("input");for(var i=0;i<inputs.length;
2i++){if(isSiteSearchInput(inputs[i]))return inputs[i]}return null}function siteSearchInputFor(trigger,doc){if(!trigger)return null;var box=typeof trigger.closest==="function"?trigger.closest(".autocomplete-form")||trigger.closest(".form"):null;var input=firstSiteSearchInputIn(box);if(input)return input;var m=String(trigger.id||"").match(/^(.*_)b(s?Srch\d*)$/);if(m&&doc&&typeof doc.getElementById==="function"){var byId=doc.getElementById(m[1]+"tb"+m[2]);if(isSiteSearchInput(byId))return byId}return null}function siteSearchInputForSuggestion(node){if(!node||typeof node.closest!=="function")return null;var drop=node.closest(".ajax-drop");if(!drop)return null;return firstSiteSearchInputIn(drop.closest(".autocomplete-form"))}function findSiteSearchInputs(doc){var out=[];try{var inputs=doc.querySelectorAll('input[type="search"], input.ac-input');for(var i=0;i<inputs.length;i++){if(isSiteSearchInput(inputs[i]))out.push(inputs[i])}}catch(e){}return out}function installSiteSearchCapture(doc){doc=doc||document;if(!findSiteSearchInputs(doc).length)return false;var opts={capture:true,passive:true};var captureFrom=function(input){if(input&&isSiteSearchInput(input))recordSiteSearch(input.value)};doc.addEventListener("keydown",function(e){try{if(!e||e.isComposing)return;if(e.key!=="Enter"&&e.keyCode!==13)return;captureFrom(e.target)}catch(err){}},opts);doc.addEventListener("click",function(e){try{var node=e&&e.target;if(node&&node.nodeType!==1)node=node.parentNode;if(!node||typeof node.closest!=="function")return;var trigger=node.closest("a, button, input");if(trigger&&isSiteSearchTrigger(trigger)){captureFrom(siteSearchInputFor(trigger,doc));return}captureFrom(siteSearchInputForSuggestion(node))}catch(err){}},opts);doc.addEventListener("submit",function(e){try{var s=e&&e.submitter||doc.activeElement;if(!s)return;if(isSiteSearchInput(s)){captureFrom(s);return}if(isSiteSearchTrigger(s))captureFrom(siteSearchInputFor(s,doc))}catch(err){}},opts);return true}var BROWSE_HISTORY_KEY="max_browse_history";var BROWSE_HISTORY_MAX=50;var RETURN_VISIT_KEY="max_return_visit";var RETURN_VISIT_SNAPSHOT_KEY="max_return_visit_prev";var returnVisitSnapshot=null;function browsePathOf(){try{return(window.location.pathname||"")+(window.location.search||"")}catch(e){return""}}function readBrowseHistory(){try{var arr=JSON.parse(sessionStorage.getItem(BROWSE_HISTORY_KEY)||"[]");return Array.isArray(arr)?arr:[]}catch(e){return[]}}function recordBrowseHistory(ctx){try{if(!ctx)return;var path=browsePathOf();var arr=readBrowseHistory();var last=arr.length?arr[arr.length-1]:null;if(last&&last.url===path)return;arr.push({type:ctx.pageType||"other",brand:ctx.brand||null,applianceType:ctx.applianceType||null,modelNumber:ctx.modelNumber||null,partName:ctx.partName||null,partCategory:ctx.partCategory||null,symptoms:ctx.symptoms||null,searchQuery:ctx.searchQuery||null,url:path,timestamp:Date.now()});if(arr.length>BROWSE_HISTORY_MAX)arr=arr.slice(arr.length-BROWSE_HISTORY_MAX);sessionStorage.setItem(BROWSE_HISTORY_KEY,JSON.stringify(arr))}catch(e){}}function isMeaningfulPage(ctx){if(!ctx)return false;var t=ctx.pageType;return t==="model"||t==="diagram"||t==="part"}function recordReturnVisit(ctx){try{if(!isMeaningfulPage(ctx))return;localStorage.setItem(RETURN_VISIT_KEY,JSON.stringify({lastVisitTimestamp:Date.now(),lastContext:{brand:ctx.brand||null,applianceType:ctx.applianceType||null,modelNumber:ctx.modelNumber||null}}))}catch(e){}}function captureReturnVisitSnapshot(){try{var existing=sessionStorage.getItem(RETURN_VISIT_SNAPSHOT_KEY);if(existing!==null){var p=null;try{p=JSON.parse(existing)}catch(e){p=null}returnVisitSnapshot=p&&typeof p==="object"&&typeof p.lastVisitTimestamp==="number"?p:null;return}var snap=null;var raw=localStorage.getItem(RETURN_VISIT_KEY);if(raw){var parsed=JSON.parse(raw);if(parsed&&typeof parsed==="object"&&typeof parsed.lastVisitTimestamp==="number"){var days=(Date.now()-parsed.lastVisitTimestamp)/864e5;if(days>3&&days<=14){try{localStorage.removeItem(RETURN_VISIT_KEY)}catch(e){}}else{snap=parsed}}}sessionStorage.setItem(RETURN_VISIT_SNAPSHOT_KEY,JSON.stringify(snap||null));returnVisitSnapshot=snap}catch(e){}}function recordIntelligentPageState(ctx){captureReturnVisitSnapshot();recordBrowseHistory(ctx);recordReturnVisit(ctx)}function detectUserIntent(browseHistory,currentPage,returnVisitData){var hist=Array.isArray(browseHistory)?browseHistory:[];var cur=currentPage||{};var curType=cur.pageType||cur.type||null;var dwellMs=typeof cur.dwellMs==="number"?cur.dwellMs:0;var pdpEntries=hist.filter(function(e){return e&&e.type==="part"});function partsViewed(entries){var names=[];for(var i=0;i<entries.length;i++){var n=entries[i]&&entries[i].partName;if(n&&names.indexOf(n)===-1)names.push(n)}return names.slice(0,6)}if(pdpEntries.length>=2){var symCount={};var sharedSymptom=null;for(var si=0;si<pdpEntries.length;si++){var syms=pdpEntries[si].symptoms;if(!Array.isArray(syms))continue;var seenSym={};for(var sj=0;sj<syms.length;sj++){var sym=syms[sj];if(!sym||seenSym[sym])continue;seenSym[sym]=true;symCount[sym]=(symCount[sym]||0)+1;if(symCount[sym]>=2&&!sharedSymptom)sharedSymptom=sym}}if(sharedSymptom){return{intent:"symptom_match",confidence:"high",context:{symptom:sharedSymptom,brand:firstNonNull(pdpEntries,"brand")||cur.brand||null,applianceType:firstNonNull(pdpEntries,"applianceType")||null,modelNumber:firstNonNull(hist,"modelNumber")||null,partsViewed:partsViewed(pdpEntries)}}}}if(curType==="part"){var resolved=null;for(var ri=hist.length-1;ri>=0;ri--){var re=hist[ri];if(re&&(re.type==="model"||re.type==="diagram")&&re.modelNumber){resolved=re;break}}if(resolved){var pdpModel=cur.modelNumber||null;if(!pdpModel||pdpModel!==resolved.modelNumber){return{intent:"compatibility_check",confidence:"high",context:{brand:resolved.brand||cur.brand||null,applianceType:resolved.appli
2anceType||null,modelNumber:resolved.modelNumber,partName:cur.partName||null}}}}}if(pdpEntries.length>=2){var atCount={};var sharedAt=null;for(var ai=0;ai<pdpEntries.length;ai++){var at=pdpEntries[ai].applianceType;if(!at)continue;atCount[at]=(atCount[at]||0)+1;if(atCount[at]>=2&&!sharedAt)sharedAt=at}if(sharedAt){var sameAt=pdpEntries.filter(function(e){return e.applianceType===sharedAt});return{intent:"comparing_parts",confidence:"medium",context:{applianceType:sharedAt,brand:firstNonNull(sameAt,"brand")||null,partsViewed:partsViewed(sameAt)}}}}var searchEntries=hist.filter(function(e){return e&&e.type==="search"});if(searchEntries.length>=1){var queries=[];for(var qi=0;qi<searchEntries.length;qi++){var sq=searchEntries[qi].searchQuery;if(sq){sq=String(sq).trim().toLowerCase();if(sq&&queries.indexOf(sq)===-1)queries.push(sq)}}var refined=queries.length>=2;var bounceBack=!refined&&hasSearchPdpSearch(hist);if(refined||bounceBack){return{intent:"stuck_searching",confidence:"medium",context:{searchQuery:cur.searchQuery||(searchEntries[searchEntries.length-1]||{}).searchQuery||null,brand:cur.brand||null,applianceType:cur.applianceType||null}}}}if(curType==="diagram"&&dwellMs>45e3){return{intent:"diagram_exploring",confidence:"low",context:{brand:cur.brand||null,applianceType:cur.applianceType||null,modelNumber:cur.modelNumber||null,section:cur.section||null}}}if(curType==="part"){var readyCount=cartCountOf(cur);if(readyCount>=1){return{intent:"cart_ready",confidence:"medium",context:{brand:cur.brand||null,applianceType:cur.applianceType||null,partName:cur.partName||null,cartItemCount:readyCount}}}}if(curType==="cart"&&dwellMs>9e4){return{intent:"cart_hesitation",confidence:"low",context:{cartItemCount:cartCountOf(cur)}}}if(returnVisitData&&typeof returnVisitData.lastVisitTimestamp==="number"){var rdays=(Date.now()-returnVisitData.lastVisitTimestamp)/864e5;if(rdays<=3){return{intent:"return_visitor_active",confidence:"medium",context:{daysSinceLastVisit:Math.round(rdays),lastVisitContext:returnVisitData.lastContext||null}}}if(rdays>14){return{intent:"return_visitor_new",confidence:"low",context:{daysSinceLastVisit:Math.round(rdays),referencePreviousVisit:false}}}}return{intent:"general_browsing",confidence:"low",context:{brand:cur.brand||null,applianceType:cur.applianceType||null}}}function firstNonNull(entries,field){for(var i=0;i<entries.length;i++){if(entries[i]&&entries[i][field])return entries[i][field]}return null}function hasSearchPdpSearch(hist){var stage=0;for(var i=0;i<hist.length;i++){var t=hist[i]&&hist[i].type;if(stage===0&&t==="search")stage=1;else if(stage===1&&t==="part")stage=2;else if(stage===2&&t==="search")return true}return false}function cartCountOf(cur){if(cur&&typeof cur.cartItemCount==="number")return cur.cartItemCount;if(cur&&cur.cartItems&&typeof cur.cartItems.length==="number")return cur.cartItems.length;if(cur&&cur.cartSignal)return 1;return 0}function proactiveDetectIntentForCtx(ctx){var cur={};try{for(var k in ctx){if(Object.prototype.hasOwnProperty.call(ctx,k))cur[k]=ctx[k]}}catch(e){}cur.dwellMs=proactive.pageStartTime?Date.now()-proactive.pageStartTime:0;var domCart=0;try{domCart=proactiveDetectCartItems()}catch(e){domCart=0}cur.cartItemCount=ctx&&ctx.cartItems&&ctx.cartItems.length?ctx.cartItems.length:domCart>0?domCart:proactive.cartSignal?1:0;cur.cartSignal=!!proactive.cartSignal;try{return detectUserIntent(readBrowseHistory(),cur,returnVisitSnapshot)}catch(e){return{intent:"general_browsing",confidence:"low",context:{}}}}function proactiveIntentTelemetry(intentResult){var hist=readBrowseHistory();var pdps=0;for(var i=0;i<hist.length;i++){if(hist[i]&&hist[i].type==="part")pdps++}var out={pages_in_session:hist.length,pdps_viewed:pdps};var c=intentResult&&intentResult.context||{};if(c.brand)out.brand=c.brand;if(c.applianceType)out.applianceType=c.applianceType;return out}var PROACTIVE={FLOOR_MS:15e3,COOLDOWN_MS:5*60*1e3,MAX_PER_SESSION:2,AUTOFADE_MS:15e3,PDP_WINDOW_MS:10*60*1e3,PDP_THRESHOLD:3,EXIT_GRACE_MS:1e4,dwell:{diagram_dwell:45e3,repair_help_dwell:45e3,model_dwell:6e4,pdp_dwell:6e4,blog_dwell:6e4,forum_dwell:6e4,multi_pdp:15e3,cart_dwell:9e4,search_dwell:12e4}};
2function proactiveApplyTestOverrides(){try{var o=window.__MX_PROACTIVE_TEST__;if(!o||typeof o!=="object")return;["FLOOR_MS","COOLDOWN_MS","MAX_PER_SESSION","AUTOFADE_MS","PDP_WINDOW_MS","PDP_THRESHOLD","EXIT_GRACE_MS"].forEach(function(k){if(typeof o[k]==="number")PROACTIVE[k]=o[k]});if(o.dwell&&typeof o.dwell==="object"){for(var k in o.dwell){if(Object.prototype.hasOwnProperty.call(o.dwell,k)&&typeof o.dwell[k]==="number")PROACTIVE.dwell[k]=o.dwell[k]}}}catch(e){}}var proactiveConfig=null;function proactiveLoadConfig(){proactiveConfig=null;try{var raw=window.__MX_PROACTIVE_CONFIG__;if(!raw||typeof raw!=="object")return;var list=raw.proactiveTriggers;if(!Array.isArray(list))return;var byId={};for(var i=0;i<list.length;i++){var t=list[i];if(!t||typeof t!=="object"||typeof t.id!=="string")continue;var variants=[];if(Array.isArray(t.variants)){for(var j=0;j<t.variants.length;j++){var v=t.variants[j];if(v&&typeof v==="object"&&typeof v.id==="string"&&typeof v.message==="string"&&v.message){variants.push({id:v.id,message:v.message,weight:typeof v.weight==="number"&&v.weight>0?v.weight:0})}}}byId[t.id]={enabled:t.enabled!==false,dwell:typeof t.dwell==="number"&&t.dwell>0?t.dwell:null,variants:variants}}proactiveConfig={byId:byId}}catch(e){proactiveConfig=null}}function proactiveTriggerEnabled(triggerType){if(!proactiveConfig)return true;var cfg=proactiveConfig.byId[triggerType];if(!cfg)return true;return cfg.enabled!==false}function proactiveWeightedPick(variants){var total=0,i,w;for(i=0;i<variants.length;i++){w=variants[i].weight>0?variants[i].weight:0;total+=w}if(total<=0)return variants[0];var r=Math.random()*total;for(i=0;i<variants.length;i++){w=variants[i].weight>0?variants[i].weight:0;r-=w;if(r<0)return variants[i]}return variants[variants.length-1]}function proactivePickVariant(triggerType){var cfg=proactiveConfig&&proactiveConfig.byId[triggerType];var variants=cfg&&cfg.variants&&cfg.variants.length?cfg.variants:null;if(!variants)return null;var store=proactive.variants&&typeof proactive.variants==="object"?proactive.variants:{};var stickyId=store[triggerType];if(stickyId){for(var i=0;i<variants.length;i++){if(variants[i].id===stickyId)return variants[i]}}var chosen=proactiveWeightedPick(variants);if(!chosen)return null;store[triggerType]=chosen.id;proactive.variants=store;proactiveSave();return chosen}function proactiveSubstitutions(ctx){var subs={};if(!ctx)return subs;var label=proactiveLabel(ctx);if(label)subs.label=label;if(ctx.brand)subs.brand=ctx.brand;else if(ctx.forumThread&&ctx.forumThread.brand)subs.brand=ctx.forumThread.brand;if(ctx.applianceType)subs.applianceType=ctx.applianceType;if(ctx.partName)subs.partName=ctx.partName;if(ctx.forumThread&&ctx.forumThread.symptom)subs.symptom=String(ctx.forumThread.symptom).replace(/-/g," ").trim();return subs}function proactiveRenderMessage(message,subs){if(typeof message!=="string")return null;var ok=true;var out=message.replace(/\{(\w+)\}/g,function(m,key){if(subs&&subs[key])return subs[key];ok=false;return m});return ok?out:null}function proactiveFirstRenderable(triggerType,subs){var cfg=proactiveConfig&&proactiveConfig.byId[triggerType];if(!cfg||!cfg.variants)return null;for(var i=0;i<cfg.variants.length;i++){var r=proactiveRenderMessage(cfg.variants[i].message,subs);if(r)return{id:cfg.variants[i].id,message:r}}return null}function pageUrlNow(){try{return window.location.href}catch(e){return null}}function proactiveLoad(){try{var raw=sessionStorage.getItem(PROACTIVE_STORE_KEY);if(!raw)return;var s=JSON.parse(raw);if(!s||typeof s!=="object")return;proactive.triggerCount=s.triggerCount||0;proactive.dismissCount=s.dismissCount||0;proactive.dismissed=!!s.dismissed;proactive.lastTriggerTime=s.lastTriggerTime||0;proactive.pdpUrls=Array.isArray(s.pdpUrls)?s.pdpUrls:[];proactive.cartSignal=!!s.cartSignal;proactive.variants=s.variants&&typeof s.variants==="object"?s.variants:{}}catch(e){}}function proactiveSave(){try{sessionStorage.setItem(PROACTIVE_STORE_KEY,JSON.stringify({triggerCount:proactive.triggerCount,dismissCount:proactive.dismissCount,dismissed:proactive.dismissed,lastTriggerTime:proactive.lastTriggerTime,pdpUrls:proactive.pdpUrls,cartSignal:proactive.cartSignal,variants:proactive.variants}))}catch(e){}}function proactiveLabel(ctx){if(!ctx)return"";
2if(ctx.brand&&ctx.applianceType)return ctx.brand+" "+ctx.applianceType;if(ctx.brand)return ctx.brand;if(ctx.applianceType)return ctx.applianceType;return""}function proactiveDetectCartItems(){try{var goods=document.querySelectorAll("#cart-top-detail .cart-goods");if(goods&&goods.length>0)return goods.length}catch(e){}return 0}function proactiveDetectSearchZeroResults(){try{var body=document.body;if(!body)return null;var text=body.innerText||body.textContent||"";if(/did not match any|no results found|no products?\s+(were\s+)?found|0\s+results|returned no results|your search.{0,40}did not|we (could ?n.?t|did not|couldn.?t) find/i.test(text))return true}catch(e){}return null}function proactivePdpKey(ctx){if(ctx&&ctx.partId)return"p:"+ctx.partId;try{return"u:"+(window.location.pathname||"")}catch(e){return"u:"+(ctx&&ctx.url||"")}}function proactiveRecordPdpVisit(ctx){var now=Date.now();var key=proactivePdpKey(ctx);var arr=Array.isArray(proactive.pdpUrls)?proactive.pdpUrls:[];arr=arr.filter(function(e){return e&&typeof e.ts==="number"&&now-e.ts<PROACTIVE.PDP_WINDOW_MS});var found=false;for(var i=0;i<arr.length;i++){if(arr[i].key===key){arr[i].ts=now;found=true;break}}if(!found)arr.push({key:key,ts:now});proactive.pdpUrls=arr;proactiveSave()}function proactivePdpCount(){var now=Date.now();var arr=Array.isArray(proactive.pdpUrls)?proactive.pdpUrls:[];var keys={};for(var i=0;i<arr.length;i++){var e=arr[i];if(e&&now-e.ts<PROACTIVE.PDP_WINDOW_MS)keys[e.key]=true}return Object.keys(keys).length}function proactiveDetermineTrigger(ctx){if(!ctx)return null;var pt=ctx.pageType;if(pt==="diagram")return"diagram_dwell";if(pt==="repair-help")return"repair_help_dwell";if(pt==="model")return"model_dwell";if(pt==="part"){if(!proactive.cartSignal&&proactivePdpCount()>=PROACTIVE.PDP_THRESHOLD)return"multi_pdp";return"pdp_dwell"}if(pt==="blog")return"blog_dwell";if(pt==="forum")return"forum_dwell";if(pt==="cart")return"cart_dwell";if(pt==="search")return"search_dwell";return null}function proactiveDwellMs(triggerType){var d=PROACTIVE.dwell[triggerType];if(!(window.__MX_PROACTIVE_TEST__&&window.__MX_PROACTIVE_TEST__.dwell&&typeof window.__MX_PROACTIVE_TEST__.dwell[triggerType]==="number")){var cfg=proactiveConfig&&proactiveConfig.byId[triggerType];if(cfg&&typeof cfg.dwell==="number")d=cfg.dwell}if(typeof d!=="number")d=PROACTIVE.FLOOR_MS;return Math.max(d,PROACTIVE.FLOOR_MS)}function proactiveEligible(){if(isLikelyBot())return false;if(state.isOpen||state.isMinimized)return false;if(state.agentMode||state._agentRestorePending)return false;if(state.customerMsgCount>0||state.hasConversation)return false;if(proactive.closedByUser)return false;if(proactive.shownOnPage)return false;if(proactive.triggerCount+proactive.dismissCount>=PROACTIVE.MAX_PER_SESSION)return false;if(proactive.lastTriggerTime&&Date.now()-proactive.lastTriggerTime<PROACTIVE.COOLDOWN_MS)return false;return true}function proactiveContentFor(triggerType,ctx,variant){var label=proactiveLabel(ctx);if(triggerType==="diagram_dwell"){return{bubble:"Need help finding a specific part on this diagram? Tell me what's broken and I'll point you to it.",welcome:{greeting:label?"Find the right part for your "+label:"Let's find the right part",subtext:"Tell me what's broken or not working and I'll point you to the exact part on this diagram.",chips:["Help me find the right part"],placeholder:"What's broken or not working?"}}}if(triggerType==="model_dwell"){return{bubble:label?"Looking for a part for your "+label+"? Tell me what's wrong and I'll find it - no need to search through all the diagrams.":"Looking for a specific part? Tell me what's wrong and I'll find it.",welcome:{greeting:label?"Need a part for your "+label+"?":"Need a specific part?",subtext:"Tell me what's wrong and I'll find the exact part - no need to dig through the diagrams.",chips:["Help me find the right part","Something's not working"],placeholder:"What part do you need, or what's going wrong?"}}}if(triggerType==="pdp_dwell"){return{bubble:"Not sure this is the right part? Tell me your model number and I'll confirm it fits.",welcome:{greeting:"Not sure this part is the right one?",subtext:"Tell me your model number and I'll confirm whether this part fits before you buy it.",chips:["Will this fit my model?"],placeholder:"Enter your model number"}}}if(triggerType==="repair_help_dwell"){return{bubble:"Need the parts for this repair? Tell me your model number and I'll find them.",welcome:{greeting:"Need the parts for this repair?",subtext:"Tell me your model number and what you're fixing, and I'll find the exact parts.",chips:["Help me find the right part","Something's not working"],placeholder:"Model # and what's wrong"}}}if(triggerType==="blog_dwell"){return{bubble:"Working on a repair? Tell me your model number and I can help you find the right parts.",welcome:{greeting:"Working on a repair?",subtext:"Tell me your model number and what you're fixing, and I'll help you find the right parts.",chips:["Help me find the right part","Something's not working"],placeholder:"Model # and what's wrong"}}}if(triggerType==="forum_dwell"){return{bubble:"Need help with your appliance? I can diagnose the issue and find the right parts - just tell me your model number.",welcome:{greeting:"Need help with your appliance?",subtext:"Tell me your model number and what's going wrong, and I'll diagnose it and find the right parts.",chips:["Help me find the right part","Something's not working"],placeholder:"Model # and what's wrong"}}}if(triggerType==="multi_pdp"){return{bubble:"Comparing parts? Tell me your model number and what you're fixing - I can confirm which one fits.",welcome:{greeting:"Comparing parts?",subtext:"Tell me your model number and what you're fixing, and I'll confirm which one actually fits.",chips:["Will this fit my model?"],placeholder:"Model # and what you're fixing"}}}if(triggerType==="cart_dwell"){return{bubble:"Have a question about the parts in your cart? I can verify they're compatible with your model.",welcome:{greeting:"Questions about your cart?",subtext:"I can verify the parts in your cart are compatible with your model before you check out.",chips:["Will these fit my model?","Do I need anything else?"],placeholder:"Ask about a part in your cart..."}}}if(triggerType==="search_dwell"){if(variant==="zero"){return{bubble:"Couldn't find what you're looking for? Tell me your model number and what you need - I can track it down.",welcome:{greeting:"Couldn't find it?",subtext:"Tell me your model number and what you need, and I'll track it down.",chips:["Help me find my part"],placeholder:"Model # and what you need"}}}return{bubble:"Need help narrowing down the right part? Tell me your model and what's wrong.",welcome:{greeting:"Need help narrowing it down?",subtext:"Tell me your model and what's wrong, and I'll find the right part.",chips:["Help me find my part"],placeholder:"Model # and what's wrong"}}}if(triggerType==="exit_pdp"){return{bubble:"Not sure this part fits? Tell me your model number and I'll verify before you go.",welcome:{greeting:"Not sure this part fits?",subtext:"Tell me your model number and I'll verify this part fits before you go.",chips:["Will this fit my model?"],placeholder:"Enter your model number"}}}if(triggerType==="exit_cart"){return{bubble:"Have a question before you go? I can check part compatibility or shipping.",welcome:{greeting:"A question before you go?",subtext:"I can check part compatibility or answer a shipping question before you check out.",chips:["Will these fit my model?","Shipping question"],placeholder:"Ask about your cart..."}}}if(triggerType==="exit_diagram"){return{bubble:"Couldn't find the right part? Tell me what's broken and I'll help.",welcome:{greeting:"Couldn't find the right part?",subtext:"Tell me what's broken or not working and I'll point you to the exact part on this diagram.",chips:["Help me find the right part"],placeholder:"What's broken or not working?"}}}return null}function proactiveClearTimers(){if(proactive.currentTimer){clearTimeout(proactive.currentTimer);proactive.currentTimer=null}if(proactive.fadeTimer){clearTimeout(proactive.fadeTimer);proactive.fadeTimer=null}}function proactiveHideBubble(){if(launcherBtn)launcherBtn.classList.remove("mx-pulsing");if(!proactiveBubble)return;if(proactiveBubble.classList.contains("visible")){proactiveBubble.classList.remove("visible");proactiveBubble.classList.add("closing");var el=proactiveBubble;setTimeout(function(){if(el)el.classList.remove("closing")},280)}else{proactiveBubble.classList.remove("closing")}}function proactiveLogEvent(eventType,data){if(state.sessionToken&&state.conversationId){logQualityEvent(eventType,data)}
2else{proactive.pendingEvents.push({eventType:eventType,data:data})}}function proactiveFlushPending(){if(!state.sessionToken||!state.conversationId)return;if(!proactive.pendingEvents||!proactive.pendingEvents.length)return;var ev=proactive.pendingEvents;proactive.pendingEvents=[];for(var i=0;i<ev.length;i++)logQualityEvent(ev[i].eventType,ev[i].data)}function proactiveShow(triggerType,ctx){if(!proactiveTriggerEnabled(triggerType))return;var variant=null;if(triggerType==="search_dwell"){variant=proactiveDetectSearchZeroResults()===true?"zero":"browsing"}var content=proactiveContentFor(triggerType,ctx,variant);if(!content)return;var variantId="a";if(!(triggerType==="search_dwell"&&variant==="zero")){var picked=proactivePickVariant(triggerType);if(picked){var subs=proactiveSubstitutions(ctx);var rendered=proactiveRenderMessage(picked.message,subs);if(rendered){content.bubble=rendered;variantId=picked.id}else{var fb=proactiveFirstRenderable(triggerType,subs);if(fb){content.bubble=fb.message;variantId=fb.id}}}}proactive.activeVariantId=variantId;var intentResult=proactiveDetectIntentForCtx(ctx);proactive.activeIntent=intentResult;proactive.activeIntentContext=proactiveIntentTelemetry(intentResult);proactive.activeContent=content;proactive.activeTriggerType=triggerType;proactive.shownOnPage=true;proactive.active=true;proactive.triggerCount+=1;proactive.lastTriggerTime=Date.now();proactiveSave();if(isMobile()){if(launcherBtn)launcherBtn.classList.add("mx-pulsing")}else if(proactiveBubble&&proactiveBubbleText){proactiveBubbleText.textContent=content.bubble;proactiveBubble.classList.remove("closing");proactiveBubble.classList.add("visible")}scheduleOverlapDodge();if(proactive.fadeTimer)clearTimeout(proactive.fadeTimer);proactive.fadeTimer=setTimeout(function(){proactive.fadeTimer=null;if(proactive.active)proactiveDismiss("auto_fade")},PROACTIVE.AUTOFADE_MS);var data={trigger_type:triggerType,page_url:pageUrlNow(),variant_id:variantId,detected_intent:intentResult.intent,intent_confidence:intentResult.confidence,intent_context:proactive.activeIntentContext};if(variant)data.variant=variant;proactiveLogEvent("proactive_shown",data)}function proactiveEngage(){if(!proactive.active){openWidget();return}var triggerType=proactive.activeTriggerType;var content=proactive.activeContent;proactive.active=false;proactiveLogEvent("proactive_clicked",{trigger_type:triggerType,page_url:pageUrlNow(),variant_id:proactive.activeVariantId,detected_intent:proactive.activeIntent?proactive.activeIntent.intent:null,intent_confidence:proactive.activeIntent?proactive.activeIntent.confidence:null,intent_context:proactive.activeIntentContext||null});if(content&&content.welcome){state.proactiveContext={triggerType:triggerType,welcome:content.welcome}}proactiveHideBubble();openWidget()}function proactiveDismiss(reason){var wasActive=proactive.active;var triggerType=proactive.activeTriggerType;proactive.active=false;if(proactive.fadeTimer){clearTimeout(proactive.fadeTimer);proactive.fadeTimer=null}proactiveHideBubble();if(!wasActive)return;if(reason==="x_clicked"){proactive.dismissCount+=1;proactive.dismissed=true;proactiveSave()}proactiveLogEvent("proactive_dismissed",{trigger_type:triggerType,page_url:pageUrlNow(),dismiss_reason:reason,variant_id:proactive.activeVariantId,detected_intent:proactive.activeIntent?proactive.activeIntent.intent:null,intent_confidence:proactive.activeIntent?proactive.activeIntent.confidence:null,intent_context:proactive.activeIntentContext||null})}function proactiveNotifyOpened(){proactiveClearTimers();proactive.active=false;proactiveHideBubble()}function proactiveStartDwell(triggerType){proactiveClearTimers();proactive.currentTimer=setTimeout(function(){proactive.currentTimer=null;if(!proactiveEligible())return;var ctx;try{ctx=detectPageContext()}catch(e){return}if(!ctx)return;if(proactiveDetermineTrigger(ctx)!==triggerType)return;proactiveShow(triggerType,ctx)},proactiveDwellMs(triggerType))}function proactiveExitTriggerFor(ctx){if(!ctx)return null;if(ctx.pageType==="part")return"exit_pdp";if(ctx.pageType==="cart")return"exit_cart";if(ctx.pageType==="diagram")return"exit_diagram";return null}function proactiveOnMouseLeave(e){try{if(isMobile())return;if(!e||typeof e.clientY!=="number"||e.clientY>=0)return;if(proactive.exitFiredOnPage)return;if(proactive.shownOnPage)return;var since=proactive.pageStartTime?Date.now()-proactive.pageStartTime:0;
2if(since<Math.max(PROACTIVE.EXIT_GRACE_MS,PROACTIVE.FLOOR_MS))return;if(!proactiveEligible())return;var ctx;try{ctx=detectPageContext()}catch(e2){return}var triggerType=proactiveExitTriggerFor(ctx);if(!triggerType)return;proactive.exitFiredOnPage=true;proactiveClearTimers();proactiveShow(triggerType,ctx)}catch(e2){}}function proactiveOnPageChange(){proactiveClearTimers();proactiveHideBubble();proactive.shownOnPage=false;proactive.closedByUser=false;proactive.active=false;proactive.exitFiredOnPage=false;proactive.pageStartTime=Date.now();var ctx;try{ctx=detectPageContext()}catch(e){return}if(!ctx)return;recordIntelligentPageState(ctx);if(ctx.pageType==="cart"||proactiveDetectCartItems()>0){if(!proactive.cartSignal){proactive.cartSignal=true;proactiveSave()}}if(ctx.pageType==="part")proactiveRecordPdpVisit(ctx);if(!proactiveEligible())return;var triggerType=proactiveDetermineTrigger(ctx);if(!triggerType)return;proactiveStartDwell(triggerType)}function proactiveOnNav(){setTimeout(function(){try{proactiveOnPageChange()}catch(e){}},0)}function proactiveStart(){proactiveApplyTestOverrides();proactiveLoadConfig();proactiveLoad();if(!proactive.navPatched){proactive.navPatched=true;try{var origPush=history.pushState;var origReplace=history.replaceState;history.pushState=function(){var rv=origPush.apply(this,arguments);proactiveOnNav();return rv};history.replaceState=function(){var rv=origReplace.apply(this,arguments);proactiveOnNav();return rv}}catch(e){}try{window.addEventListener("popstate",proactiveOnNav)}catch(e){}}if(!proactive.exitBound){proactive.exitBound=true;try{document.addEventListener("mouseleave",proactiveOnMouseLeave)}catch(e){}}proactiveOnPageChange()}try{if(typeof window!=="undefined"&&window.__MX_PROACTIVE_TEST__){window.__mxProactiveState=function(){return{triggerCount:proactive.triggerCount,dismissCount:proactive.dismissCount,dismissed:proactive.dismissed,lastTriggerTime:proactive.lastTriggerTime,pdpCount:proactivePdpCount(),cartSignal:proactive.cartSignal,shownOnPage:proactive.shownOnPage,active:proactive.active,activeTriggerType:proactive.activeTriggerType,closedByUser:proactive.closedByUser,exitFiredOnPage:proactive.exitFiredOnPage,pen
2dingEvents:(proactive.pendingEvents||[]).length,activeVariantId:proactive.activeVariantId,variants:proactive.variants,configLoaded:!!proactiveConfig}}}}catch(e){}function renderCsatSurvey(opts){if(!shadow)return;var container=shadow.querySelector("#mx-messages");if(!container)return;if(shadow.querySelector("#mx-csat"))return;var token=opts&&opts.token;var alcConvId=opts&&opts.alcConversationId||state.alcConversationId;if(!token||!alcConvId){renderStartNewConversation();return}var rating=0;var resolvedAnswer=null;var wrap=document.createElement("div");wrap.id="mx-csat";wrap.style.cssText="margin:8px 12px 12px;padding:14px;border:1px solid "+C.border+";border-radius:12px;background:"+C.bgWarm+";font-family:"+FONT+";";var title=document.createElement("div");title.style.cssText="font-size:13px;font-weight:600;color:"+C.t1+";margin-bottom:8px;";title.textContent="How was your experience?";wrap.appendChild(title);var starsRow=document.createElement("div");starsRow.style.cssText="display:flex;gap:4px;margin-bottom:12px;";var starEls=[];function paintStars(){starEls.forEach(function(s,i){s.style.color=i<rating?"#F5A623":"#CCC"});submitBtn.disabled=rating===0;submitBtn.style.opacity=rating===0?"0.5":"1";submitBtn.style.cursor=rating===0?"default":"pointer"}for(var i=0;i<5;i++){(function(idx){var b=document.createElement("button");b.type="button";b.setAttribute("aria-label",idx+1+" star"+(idx===0?"":"s"));b.style.cssText="background:none;border:none;font-size:26px;line-height:1;cursor:pointer;color:#CCC;padding:0;font-family:inherit;";b.textContent="\u2605";b.onclick=function(){rating=idx+1;paintStars()};starEls.push(b);starsRow.appendChild(b)})(i)}wrap.appendChild(starsRow);var qLabel=document.createElement("div");qLabel.style.cssText="font-size:12px;color:"+C.t2+";margin-bottom:6px;";qLabel.textContent="Was your issue resolved?";wrap.appendChild(qLabel);var toggleRow=document.createElement("div");toggleRow.style.cssText="display:flex;gap:8px;margin-bottom:12px;";var yesBtn=document.createElement("button");var noBtn=document.createElement("button");function paintToggle(){[yesBtn,noBtn].forEach(function(b){var active=b===yesBtn&&resolvedAnswer===true||b===noBtn&&resolvedAnswer===false;b.style.cssText="flex:0 0 auto;padding:6px 16px;border-radius:999px;border:1px solid "+(active?C.navy:C.border)+";background:"+(active?C.navy:"#FFF")+";color:"+(active?"#FFF":C.t1)+";font-size:12px;cursor:pointer;font-family:"+FONT+";font-weight:500;"})}yesBtn.type="button";yesBtn.textContent="Yes";noBtn.type="button";noBtn.textContent="No";yesBtn.onclick=function(){resolvedAnswer=true;paintToggle()};noBtn.onclick=function(){resolvedAnswer=false;paintToggle()};paintToggle();toggleRow.appendChild(yesBtn);toggleRow.appendChild(noBtn);wrap.appendChild(toggleRow);var ta=document.createElement("textarea");ta.maxLength=500;ta.placeholder="Any additional feedback? (optional)";ta.style.cssText="width:100%;box-sizing:border-box;min-height:60px;max-height:120px;resize:vertical;border:1px solid "+C.border+";border-radius:8px;padding:8px;font-size:12px;font-family:"+FONT+";margin-bottom:10px;background:#FFF;color:"+C.t1+";";wrap.appendChild(ta);var btnRow=document.createElement("div");btnRow.style.cssText="display:flex;flex-direction:column;align-items:stretch;gap:6px;";var submitBtn=document.createElement("button");submitBtn.type="button";submitBtn.textContent="Send feedback";submitBtn.disabled=true;submitBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:9px 14px;font-size:13px;font-weight:600;cursor:default;opacity:0.5;font-family:"+FONT+";";var skipLink=document.createElement("button");skipLink.type="button";skipLink.textContent="Skip";skipLink.style.cssText="background:none;border:none;color:"+C.t2+";font-size:12px;cursor:pointer;text-decoration:underline;font-family:"+FONT+";align-self:center;padding:4px;";var errEl=document.createElement("div");errEl.style.cssText="font-size:12px;color:"+C.red+";margin-top:6px;display:none;";wrap.appendChild(errEl);function submit(){if(rating===0)return;submitBtn.disabled=true;submitBtn.style.opacity="0.5";submitBtn.textContent="Sending...";errEl.style.display="none";fetch(API_BASE+"/api/chat/survey",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,alc_conversation_id:alcConvId,token:token,csat_score:rating,csat_resolved:resolvedAnswer,csat_feedback:ta.value||null})}).then(function(r){if(!r.ok)throw new Error("survey http "+r.status);state.surveySubmitted=true;
2replaceSurveyWithMessage("Thank you for your feedback!")}).catch(function(){submitBtn.disabled=false;submitBtn.style.opacity="1";submitBtn.style.cursor="pointer";submitBtn.textContent="Send feedback";errEl.textContent="Could not submit feedback. Please try again.";errEl.style.display="block"})}submitBtn.onclick=submit;skipLink.onclick=function(){state.surveySubmitted=true;replaceSurveyWithMessage("Thank you for chatting with us!")};btnRow.appendChild(submitBtn);btnRow.appendChild(skipLink);wrap.appendChild(btnRow);paintStars();container.appendChild(wrap);container.scrollTop=container.scrollHeight}function replaceSurveyWithMessage(text){if(!shadow)return;var existing=shadow.querySelector("#mx-csat");if(existing&&existing.parentNode)existing.parentNode.removeChild(existing);addAgentSystemMessage(text);renderEmailTranscriptOffer()}function resetWidgetState(){exitAgentMode();hideAgentTyping();clearWaitingTimer();stopQueueStatusPolling();hideQueueStatus();try{if(state.agentStream)state.agentStream.close()}catch(e){}state.agentStream=null;state._agentRestorePending=null;state._restoredFromStorage=false;try{localStorage.removeItem("max_session")}catch(e){}try{localStorage.removeItem(RESOLVED_FLAG_KEY)}catch(e){}try{sessionStorage.removeItem(AGENT_MODE_STORAGE_KEY)}catch(e){}clearIdleTimer();state.disconnectBeaconSent=false;state.sessionToken=null;state.conversationId=null;state.hasConversation=false;state.messages=[];state.quickReplies=[];state.customerMsgCount=0;state.hadPartCard=false;state.lastBotText="";state.lastCustomerMsg="";state.modelNumber=null;state.brand=null;state.applianceType=null;state.handoffCompleted=false;state.handoffInFlight=false;state.surveySubmitted=false;state.surveyShownForEventId=null;state.autoLeaveShownForId=null;state.bypassAgentSend=false;state.maxHelpDuringWait=false;state.waitHelpOffered=false;state.isSending=false;state.agentMode=false;state.agentName=null;resetHeaderToMax();state.agentAssigned=false;state.alcConversationId=null;state.alcStreamUrl=null;state.agentStreamLastSeen=null;state.seenAgentMessageIds={};state.pendingAgentMessages=[];state.agentReadAt=null;state.lastAgentMsgId=null;state.readReceiptSentForId=null;clearReadReceiptTimer();state.collectedName=null;state.collectedEmail=null;state.transcriptOffered=false;state.seenCheckoutEventIds={};state.seenReassuranceEventIds={};state.proactiveContext=null;state.pageContext=detectPageContext()}
2function renderStartNewConversation(){if(!shadow)return;var container=shadow.querySelector("#mx-messages");if(!container)return;if(shadow.querySelector("#mx-agent-restart"))return;var wrap=document.createElement("div");wrap.id="mx-agent-restart";wrap.style.cssText="text-align:center;margin:8px 0 16px;";var btn=document.createElement("button");btn.type="button";btn.textContent="Start new conversation";btn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:9px 16px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";btn.onclick=function(){resetWidgetState();var msgs=shadow.querySelector("#mx-messages");if(msgs){while(msgs.firstChild)msgs.removeChild(msgs.firstChild)}setComposerEnabled(true);initSession()};wrap.appendChild(btn);container.appendChild(wrap);container.scrollTop=container.scrollHeight}function restoreAgentMode(saved){if(!saved||!saved.conversationId||!saved.sessionToken)return false;state.sessionToken=saved.sessionToken;state.conversationId=saved.conversationId;state.agentName=saved.agentName||null;syncDisclaimer();state.agentStreamLastSeen=saved.lastSeen||null;state.agentRestoring=true;state.pendingAgentMessages=[];var streamUrl=saved.streamUrl||"/api/chat/agent-stream/"+saved.conversationId;enterAgentMode({alcConversationId:saved.alcConversationId||null,streamUrl:streamUrl,suppressConnecting:true});showReconnectingIndicator();if(!state.agentName){startQueueStatusPolling()}restoreAgentTranscript(saved.conversationId);return true}function restoreAgentTranscript(sessionId){if(!sessionId||!state.sessionToken)return;var token=state.sessionToken;var historyReq=fetch(API_BASE+"/api/chat/history",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:token,conversationId:sessionId})}).then(function(r){return r.ok?r.json():[]}).then(function(d){return Array.isArray(d)?d:[]}).catch(function(){return[]});var agentReq=fetch(API_BASE+"/api/chat/agent-messages/"+encodeURIComponent(sessionId)+"?token="+encodeURIComponent(token),{method:"GET",credentials:"include"}).then(function(r){return r.ok?r.json():null}).then(function(d){return d&&Array.isArray(d.messages)?d.messages:[]}).catch(function(){return[]});Promise.all([historyReq,agentReq]).then(function(res){renderAgentRestore(res[0]||[],res[1]||[])}).catch(function(){})}function agentRestoreTs(value){var t=value?new Date(value).getTime():0;return isFinite(t)?t:0}function renderAgentRestore(history,agentRows){var container=shadow.querySelector("#mx-messages");if(!container)return;clearWelcome();var items=[];var seq=0;
2history.forEach(function(m){items.push({t:agentRestoreTs(m.created_at),seq:seq++,type:"history",m:m})});agentRows.forEach(function(m){items.push({t:agentRestoreTs(m.sent_at),seq:seq++,type:"agent",m:m})});items.sort(function(a,b){return a.t!==b.t?a.t-b.t:a.seq-b.seq});state.messages=[];state.customerMsgCount=0;var resolvedEvt=null;var reopenEvt=null;var autoLeaveEvt=null;items.forEach(function(it){if(it.type==="history"){renderRestoredHistoryMessage(it.m,container);return}var m=it.m;if(m.kind==="agent_message"){if(m.id&&state.seenAgentMessageIds[m.id])return;if(m.id)state.seenAgentMessageIds[m.id]=true;if(m.id)state.lastAgentMsgId=m.id;if(!state.agentName&&m.sender_name){state.agentName=m.sender_name;updateHeaderForAgent(state.agentName)}if(m.sent_at)state.agentStreamLastSeen=m.sent_at;if(m.content_type==="part_card"&&m.part){renderAgentPartCard(m.part)}else if(m.content_type==="diagram"&&getAgentDiagramUrl(m)){renderAgentDiagram(getAgentDiagramUrl(m),m.content||"")}else if(m.content_type==="attachment"&&getAgentAttachment(m)){renderAgentAttachment(getAgentAttachment(m),m.content||"")}else{addAgentMessage(m.content||"",m.sender_name||null)}}else if(m.kind==="agent_event"&&m.event==="resolved"){resolvedEvt=m}else if(m.kind==="agent_event"&&m.event==="reopen"){reopenEvt=m}else if(m.kind==="agent_event"&&m.event==="auto_leave_message"){autoLeaveEvt=m}else if(m.kind==="agent_event"&&m.event==="checkout"){if(m.id&&state.seenCheckoutEventIds[m.id])return;if(m.id)state.seenCheckoutEventIds[m.id]=true;renderCheckoutCard(m.items,m.total,m.sent_by)}else if(m.kind==="agent_event"&&m.event==="assigned"){if(!state.agentName&&m.agent_name){state.agentName=m.agent_name;updateHeaderForAgent(state.agentName);removeGenericAgentAssignedNotice();addAgentSystemMessage("You're now chatting with "+state.agentName);clearWaitingTimer();stopQueueStatusPolling();hideQueueStatus()}}});state.hasConversation=true;setComposerEnabled(true);persistAgentMode();maybeSendReadReceipt();updateShareButton();var resolvedAt=resolvedEvt&&resolvedEvt.sent_at?new Date(resolvedEvt.sent_at).getTime():0;var reopenAt=reopenEvt&&reopenEvt.sent_at?new Date(reopenEvt.sent_at).getTime():0;var autoLeaveAt=autoLeaveEvt&&autoLeaveEvt.sent_at?new Date(autoLeaveEvt.sent_at).getTime():0;if(reopenEvt&&reopenAt>=resolvedAt&&reopenAt>=autoLeaveAt){handleReopenEvent(reopenEvt)}else if(autoLeaveEvt&&autoLeaveAt>=resolvedAt){handleAutoLeaveMessageEvent(autoLeaveEvt)}else if(resolvedEvt){handleResolvedEvent(resolvedEvt)}container.scrollTop=container.scrollHeight}function renderRestoredHistoryMessage(m,container){if(m.role==="customer"){state.messages.push({role:"customer",content:m.content});state.customerMsgCount++;var urow=document.createElement("div");urow.className="mx-msg-row user";var ububble=document.createElement("div");ububble.className="mx-msg-bubble user";ububble.textContent=m.content;urow.appendChild(ububble);container.appendChild(urow);return}state.messages.push({role:"bot",content:m.content});state.lastBotText=(m.content||"").substring(0,100);var brow=document.createElement("div");brow.className="mx-msg-row bot";brow.appendChild(makeAvatar(28));var bbubble=document.createElement("div");bbubble.className="mx-msg-bubble bot";bbubble.innerHTML=renderBotMarkdown(m.content);brow.appendChild(bbubble);container.appendChild(brow);if(m.metadata){if(m.metadata.partCards&&m.metadata.partCards.length>0){state.messages.push({role:"parts",cards:m.metadata.partCards});state.hadPartCard=true;addPartCards(m.metadata.partCards)}if(m.metadata.video){state.messages.push({role:"video",video:m.metadata.video});addVideoCard(m.metadata.video)}}}var APP_AFD_HOST="t-esb6c0d2a5gwexgk.z03.azurefd.net";function isAllowedAppImageUrl(u){if(typeof u!=="string"||!u)return false;var parsed;try{parsed=new URL(u)}catch(e){return false}if(parsed.protocol!=="https:")return false;if(parsed.username||parsed.password)return false;if(parsed.port&&parsed.port!=="443")return false;var host=parsed.hostname.toLowerCase();return host==="appliancepartspros.com"||host.endsWith(".appliancepartspros.com")||host===APP_AFD_HOST}function getAgentDiagramUrl(obj){if(!obj)return"";var d=obj.diagram;var candidate="";if(d&&typeof d==="object"&&typeof d.url==="string"&&d.url)candidate=d.url;else if(typeof d==="string"&&d)candidate=d;else if(typeof obj.external_url==="string"&&obj.external_url)candidate=obj.external_url;else if(typeof obj.externalUrl==="string"&&obj.externalUrl)candidate=obj.externalUrl;return isAllowedAppImageUrl(candidate)?candidate:""}function renderAgentDiagram(url,caption){if(!shadow||!url)return;var container=shadow.querySelector("#mx-messages");if(!container)return;var row=document.createElement("div");row.className="mx-msg mx-agent-diagram";row.style.cssText="display:flex;flex-direction:column;align-items:flex-start;margin:8px 0;";var link=document.createElement("a");link.href=url;link.target="_blank";link.rel="noopener noreferrer";link.setAttribute("aria-label",caption?"Open full size: "+caption:"Open diagram full size");link.style.cssText="display:block;line-height:0;width:100%;max-width:320px;border:1px solid #e5e3df;border-radius:10px;overflow:hidden;background:#fff;";var img=document.createElement("img");img.src=url;img.alt=caption||"Parts diagram";img.loading="lazy";img.style.cssText="width:100%;height:auto;display:block;cursor:zoom-in;";link.appendChild(img);row.appendChild(link);if(caption){var cap=document.createElement("div");cap.textContent=caption;cap.style.cssText="font-size:12px;line-height:1.4;color:#767573;margin-top:6px;max-width:320px;";row.appendChild(cap)}container.appendChild(row);container.scrollTop=container.scrollHeight}function getAgentAttachment(obj){if(!obj||obj.content_type!=="attachment")return null;var att=obj.attachment;if(!att||typeof att!=="object"||typeof att.url!=="string"||!att.url)return null;var parsed;try{parsed=new URL(att.url)}catch(e){return null}if(parsed.protocol!=="https:")return null;if(parsed.username||parsed.password)return null;if(parsed.port&&parsed.port!=="443")return null;var host=parsed.hostname.toLowerCase();var ok=host==="appliancepartspros.com"||host.endsWith(".appliancepartspros.com")||host===APP_AFD_HOST||host.endsWith(".supabase.co");if(!ok)return null;return{url:att.url,name:typeof att.name==="string"&&att.name||"Attachment",type:typeof att.type==="string"&&att.type||""}}function buildAttachmentLink(url,name){var a=document.createElement("a");a.href=url;a.target="_blank";a.rel="noopener noreferrer";a.textContent=name||"Attachment";a.style.cssText="font-size:14px;color:#0066CC;text-decoration:underline;text-underline-offset:2px;word-break:break-all;";return a}function renderAgentAttachment(att,caption){if(!shadow||!att||!att.url)return;var container=shadow.querySelector("#mx-messages");if(!container)return;var name=att.name||"Attachment";var type=(att.type||"").toLowerCase();var looksImage=type.indexOf("image/")===0||/\.(png|jpe?g|gif|webp|bmp|svg)(?:[?#]|$)/i.test(att.url)||/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(name);var row=document.createElement("div");row.className="mx-msg mx-agent-attachment";row.style.cssText="display:flex;flex-direction:column;align-items:flex-start;margin:8px 0;";if(looksImage){var link=document.createElement("a");link.href=att.url;link.target="_blank";link.rel="noopener noreferrer";link.setAttribute("aria-label",caption?"Open full size: "+caption:"Open image: "+name);link.style.cssText="display:block;line-height:0;width:100%;max-width:320px;border:1px solid #e5e3df;border-radius:10px;overflow:hidden;background:#fff;";var img=document.createElement("img");img.src=att.url;img.alt=caption||name;img.loading="lazy";img.style.cssText="width:100%;height:auto;display:block;cursor:zoom-in;";img.onerror=function(){if(link.parentNode===row){row.replaceChild(buildAttachmentLink(att.url,name),link)}};link.appendChild(img);row.appendChild(link)}else{row.appendChild(buildAttachmentLink(att.url,name))}if(caption&&caption!==name){var cap=document.createElement("div");cap.textContent=caption;cap.style.cssText="font-size:12px;line-height:1.4;color:#767573;margin-top:6px;max-width:320px;";row.appendChild(cap)}container.appendChild(row);container.scrollTop=container.scrollHeight}function makeCheckSvg(){var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("viewBox","0 0 24 24");var path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d","M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z");svg.appendChild(path);return svg}function makeTruckSvg(){var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("viewBox","0 0 24 24");var path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d","M20 8h-3V4H3c-1.1 0-2 .9-2 2v11h2c0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h2v-5l-3-4zM6 18.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm13.5-9l1.96 2.5H17V9.5h2.5zM18 18.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z");svg.appendChild(path);return svg}function makePinSvg(){var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("viewBox","0 0 24 24");svg.setAttribute("width","14");svg.setAttribute("height","14");var path=document.createElementNS("http://www.w3.org/2000/svg","path");path.setAttribute("d","M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z");svg.appendChild(path);return svg}function getETCutoffInfo(){var now=new Date;
2var fmt=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour12:false,hour:"numeric",minute:"numeric",weekday:"short"});var p=fmt.formatToParts(now);var dayName="",etHour=0,etMin=0;for(var i=0;i<p.length;i++){if(p[i].type==="weekday")dayName=p[i].value;if(p[i].type==="hour")etHour=parseInt(p[i].value,10);if(p[i].type==="minute")etMin=parseInt(p[i].value,10)}var totalMinNow=etHour*60+etMin;var cutoff=16*60;var isWeekend=dayName==="Sat"||dayName==="Sun";var pastCutoff=totalMinNow>=cutoff;var minsLeft=cutoff-totalMinNow;return{isWeekend:isWeekend,pastCutoff:pastCutoff,minsLeft:minsLeft,dayName:dayName}}function formatCountdown(minsLeft){if(minsLeft<=0)return null;var h=Math.floor(minsLeft/60);var m=minsLeft%60;if(h>0)return h+"h "+m+"m";return m+"m"}function openLightbox(imgSrc){var existing=shadow.querySelector(".mx-lightbox");if(existing)existing.remove();var lb=document.createElement("div");lb.className="mx-lightbox";var closeBtn=document.createElement("button");closeBtn.className="mx-lightbox-close";closeBtn.textContent="\xd7";function closeLb(){lb.remove();document.removeEventListener("keydown",onKey);shadow.removeEventListener("keydown",onKey)}function onKey(e){if(e.key==="Escape")closeLb()}closeBtn.onclick=closeLb;lb.onclick=function(e){if(e.target===lb)closeLb()};document.addEventListener("keydown",onKey);shadow.addEventListener("keydown",onKey);var img=document.createElement("img");img.src=imgSrc.replace(/-m\.jpg$/,"-l.jpg");img.onerror=function(){this.src=imgSrc};lb.appendChild(img);lb.appendChild(closeBtn);shadow.appendChild(lb)}function makePlaceholderSvg(){var svg=document.createElementNS("http://www.w3.org/2000/svg","svg");svg.setAttribute("width","48");svg.setAttribute("height","48");svg.setAttribute("viewBox","0 0 24 24");svg.setAttribute("fill","none");svg.style.opacity="0.2";var r=document.createElementNS("http://www.w3.org/2000/svg","rect");r.setAttribute("x","3");r.setAttribute("y","3");r.setAttribute("width","18");r.setAttribute("height","18");r.setAttribute("rx","3");r.setAttribute("stroke","#999");r.setAttribute("stroke-width","1.5");var c=document.createElementNS("http://www.w3.org/2000/svg","circle");c.setAttribute("cx","12");c.setAttribute("cy","10");c.setAttribute("r","3");c.setAttribute("stroke","#999");c.setAttribute("stroke-width","1.5");var p=document.createElementNS("http://www.w3.org/2000/svg","path");p.setAttribute("d","M3 17l4-4 3 3 4-4 7 7");p.setAttribute("stroke","#999");p.setAttribute("stroke-width","1.5");p.setAttribute("stroke-linecap","round");p.setAttribute("stroke-linejoin","round");svg.appendChild(r);svg.appendChild(c);svg.appendChild(p);return svg}function buildDeliveryBox(card,delBox){delBox.textContent="";var partNumericId=(card.partId||card.apNumber||"").replace(/^AP/i,"");if(!partNumericId)return;var loadLine=document.createElement("div");loadLine.className="mx-pc-del-line";loadLine.appendChild(makeTruckSvg());var loadText=document.createElement("span");loadText.style.cssText="color:#999;font-style:italic";loadText.textContent="Checking delivery...";loadLine.appendChild(loadText);delBox.appendChild(loadLine);fetchDeliveryEstimate(partNumericId,delBox)}function extractShipsTxt(html){var tmp=document.createElement("div");tmp.innerHTML=html;var node=tmp.querySelector(".ships-txt");return node?(node.textContent||"").trim():""}function fetchDeliveryEstimate(partId,target){var url=window.location.origin+"/avail3.ashx?part="+encodeURIComponent(partId)+"&p=d&r="+(new Date).getTime();var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.timeout=5e3;xhr.setRequestHeader("Accept","text/html");xhr.onload=function(){if(xhr.status>=200&&xhr.status<300){renderDeliveryResult(target,xhr.responseText||"")}else{target.textContent="";target.style.display="none"}};xhr.ontimeout=function(){target.textContent="";target.style.display="none"};xhr.onerror=function(){target.textContent="";target.style.display="none"};xhr.send()}function renderDeliveryResult(target,html){if(!target)return;if(!html){target.textContent="";target.style.display="none";return}var shipsTxt=extractShipsTxt(html);target.textContent="";if(html.indexOf("Get it by")>0&&shipsTxt){var line=document.createElement("div");line.className="mx-pc-del-line";line.appendChild(makeTruckSvg());var b=document.createElement("b");b.className="green";b.textContent=shipsTxt;line.appendChild(b);target.appendChild(line)}else if(html.indexOf("IN STOCK")>0&&shipsTxt){var line2=document.createElement("div");line2.className="mx-pc-del-line";line2.appendChild(makeTruckSvg());var b2=document.createElement("b");b2.className="green";b2.textContent=shipsTxt;line2.appendChild(b2);target.appendChild(line2)}else{target.style.display="none"}}function cardPurchaseAction(card){if(!card)return"none";if(card.discontinued===true)return"nla";if(card.price==null||card.price===0)return"check";if(!card.partId)return"none";return"cart"}function addPartCards(cards,modelNumber,source){state.hadPartCard=true;var cardSource=source||"max";debugLog("addPartCards called with "+(cards?cards.length:0)+" cards");var container=shadow.querySelector("#mx-messages");if(!container){debugLog("addPartCards ABORT: no #mx-messages container");return}var cardModelNumber=modelNumber||state.modelNumber;cards.forEach(function(card){var hasAp=card.apNumber!=null&&String(card.apNumber).trim()!=="";var hasPrice=card.price!=null;if(!hasAp&&!hasPrice){debugLog("addPartCards: skipping card with no AP# and n
2o price: "+(card.name||""));return}var div=document.createElement("div");div.className="mx-part-card";var productHref=card.productUrl&&(/^\//.test(card.productUrl)||/^https:\/\//i.test(card.productUrl))?card.productUrl:null;var row1=document.createElement("div");row1.className="mx-pc-row1";var oemDiv=document.createElement("div");oemDiv.className="mx-pc-oem";var oemIcon=document.createElement("span");oemIcon.className="mx-pc-oem-icon";oemIcon.appendChild(makeCheckSvg());oemDiv.appendChild(oemIcon);var oemText=document.createElement("span");if(card.manufacturer){oemText.textContent="Genuine OEM ";var brandB=document.createElement("b");brandB.textContent=card.manufacturer.toLowerCase().replace(/\b\w/g,function(c){return c.toUpperCase()});oemText.appendChild(brandB);var partText=document.createTextNode(" Part");oemText.appendChild(partText)}else{oemText.textContent="Genuine OEM Part"}oemDiv.appendChild(oemText);row1.appendChild(oemDiv);var apNum=document.createElement("span");apNum.className="mx-pc-apnum";apNum.textContent=card.apNumber;row1.appendChild(apNum);div.appendChild(row1);var imgSrc=card.imageUrl;if(!imgSrc&&card.apNumber){var numericId=card.apNumber.replace(/^AP/i,"");var padded=("0000000000"+numericId).slice(-10);imgSrc="https://t-esb6c0d2a5gwexgk.z03.azurefd.net/images/part/"+padded+"-001-m.jpg"}var diagRef=card.diagramRef;if(imgSrc){var imgWrap=document.createElement("div");imgWrap.className="mx-pc-img-wrap";var imgEl=document.createElement("img");imgEl.className="mx-pc-img";imgEl.alt=card.name;imgEl.src=imgSrc;imgEl.onerror=function(wrap,dr,pHref){var legacyTried=false;return function(){if(!legacyTried&&pHref){legacyTried=true;var slug=pHref.replace(/^https?:\/\/[^/]+/,"").replace(/^\//,"").replace(/\.html$/,"");if(slug){this.src="https://cdn.appliancepartspros.com/images/product/cache/"+slug+"_01_l.
2jpg";return}}this.parentNode.removeChild(this);if(dr&&dr.thumb){var dImg=document.createElement("img");dImg.className="mx-pc-img";dImg.alt=card.name+" diagram";dImg.src=dr.thumb;dImg.onclick=function(){openLightbox(dr.full)};wrap.appendChild(dImg);var overlay=document.createElement("span");overlay.className="mx-pc-diag-overlay";overlay.textContent="#"+dr.location+" on diagram";wrap.appendChild(overlay)}else{wrap.remove()}}}(imgWrap,diagRef,productHref);imgEl.onclick=function(){openLightbox(this.src.replace(/-m\.jpg$/,"-l.jpg").replace(/_01_l\.jpg$/,"_01_x.jpg"))};imgWrap.appendChild(imgEl);div.appendChild(imgWrap)}else if(diagRef&&diagRef.thumb){var imgWrap=document.createElement("div");imgWrap.className="mx-pc-img-wrap";var dImg=document.createElement("img");dImg.className="mx-pc-img";dImg.alt=card.name+" diagram";dImg.src=diagRef.thumb;dImg.onclick=function(full){return function(){openLightbox(full)}}(diagRef.full);imgWrap.appendChild(dImg);var overlay=document.createElement("span");overlay.className="mx-pc-diag-overlay";overlay.textContent="#"+diagRef.location+" on diagram";imgWrap.appendChild(overlay);div.appendChild(imgWrap)}var pdpUrl=productHref?"https://www.appliancepartspros.com"+productHref:null;var row3=document.createElement("div");row3.className="mx-pc-row3";if(pdpUrl){var onCardClick=function(apNum){return function(){pushDataLayer("chat_card_click",{part_id:apNum,source:cardSource});postFunnelEvent("chat_card_click",apNum,cardSource)}}(card.apNumber);var nameLink=document.createElement("a");nameLink.className="mx-pc-name";nameLink.href=pdpUrl;nameLink.target="_blank";nameLink.rel="noopener noreferrer";nameLink.textContent=card.name;nameLink.addEventListener("click",onCardClick);row3.appendChild(nameLink);var pdpLink=document.createElement("a");pdpLink.className="mx-pc-pdp";pdpLink.href=pdpUrl;pdpLink.target="_blank";pdpLink.rel="noopener noreferrer";pdpLink.textContent="View full details >";pdpLink.addEventListener("click",onCardClick);row3.appendChild(pdpLink)}else{var nameDiv=document.createElement("div");nameDiv.className="mx-pc-name";nameDiv.textContent=card.name;row3.appendChild(nameDiv)}var explicitDisc=card.discontinued===true;var priceMissing=card.price==null||card.price===0;var checkAvail=priceMissing&&!card.inStock&&!explicitDisc;var backordered=!card.inStock&&!explicitDisc&&!checkAvail;if(explicitDisc){div.style.opacity="0.6"}if(card.price!=null&&card.price>0){var priceRow=document.createElement("div");priceRow.className="mx-pc-price-row";var priceEl=document.createElement("span");priceEl.className="mx-pc-price";priceEl.textContent="$"+card.price.toFixed(2);priceRow.appendChild(priceEl);if(card.listPrice&&card.listPrice>card.price){var listEl=document.createElement("span");listEl.className="mx-pc-list-price";listEl.textContent="$"+card.listPrice.toFixed(2);priceRow.appendChild(listEl)}row3.appendChild(priceRow)}div.appendChild(row3);var row4=document.createElement("div");row4.className="mx-pc-row4";if(explicitDisc){var nlaSpan=document.createElement("span");nlaSpan.className="mx-pc-stock-disc";nlaSpan.textContent="NO LONGER AVAILABLE";row4.appendChild(nlaSpan)}else if(checkAvail){var caSpan=document.createElement("span");caSpan.className="mx-pc-stock-disc";caSpan.textContent="CHECK AVAILABILITY";row4.appendChild(caSpan)}else if(card.inStock){var dot=document.createElement("span");dot.className="mx-pc-dot";row4.appendChild(dot);var stockSpan=document.createElement("span");stockSpan.className="mx-pc-stock";stockSpan.textContent="IN STOCK";row4.appendChild(stockSpan);if(card.listPrice&&card.listPrice>card.price){var saveAmt=(card.listPrice-card.price).toFixed(2);var saveSpan=document.createElement("span");saveSpan.className="mx-pc-save";saveSpan.textContent=" \xb7 SAVE $"+saveAmt;row4.appendChild(saveSpan)}}else{var outSpan=document.createElement("span");outSpan.className="mx-pc-stock-out";outSpan.textContent="OUT OF STOCK";row4.appendChild(outSpan);var boSpan=document.createElement("div");boSpan.className="mx-pc-backorder";boSpan.textContent="On backorder - usually ships in 7-14 business days";
2row4.appendChild(boSpan)}div.appendChild(row4);if(card.sectionName&&String(card.sectionName).trim()){var diagLoc=document.createElement("div");diagLoc.className="mx-pc-diag-loc";var diagText="Diagram: "+String(card.sectionName).trim();if(card.callout&&String(card.callout).trim()){diagText+=", #"+String(card.callout).trim()}diagLoc.textContent=diagText;div.appendChild(diagLoc)}if(cardModelNumber&&!explicitDisc&&!checkAvail){var fitBox=document.createElement("div");fitBox.className="mx-pc-fit";var fitIcon=document.createElement("span");fitIcon.className="mx-pc-fit-icon";fitIcon.appendChild(makeCheckSvg());fitBox.appendChild(fitIcon);var fitText=document.createElement("span");fitText.textContent="Confirmed fit for your ";var modelB=document.createElement("b");modelB.textContent=cardModelNumber;fitText.appendChild(modelB);fitBox.appendChild(fitText);div.appendChild(fitBox)}if(card.inStock&&!explicitDisc){var delBox=document.createElement("div");delBox.className="mx-pc-delivery-box";buildDeliveryBox(card,delBox);div.appendChild(delBox)}var actions=document.createElement("div");actions.className="mx-pc-actions";var purchaseAction=cardPurchaseAction(card);if(purchaseAction==="nla"){var nlaLabel=document.createElement("span");nlaLabel.className="mx-pc-disc-label";nlaLabel.textContent="No Longer Available";actions.appendChild(nlaLabel)}else if(purchaseAction==="check"){var caLink=document.createElement("a");caLink.className="mx-pc-cart-btn";caLink.href=pdpUrl||"https://www.appliancepartspros.com/search.aspx?q="+encodeURIComponent(card.apNumber||card.name||"");caLink.target="_blank";caLink.rel="noopener noreferrer";caLink.textContent="Check availability and pricing";actions.appendChild(caLink)}else if(purchaseAction==="cart"){var cartBtn=document.createElement("button");cartBtn.className="mx-pc-cart-btn";var btnPrice=card.price!=null?" - $"+card.price.toFixed(2):"";cartBtn.textContent="Add to Cart"+btnPrice;cartBtn.onclick=function(btn,partId,pUrl,priceStr,cardRef){return function(){btn.disabled=true;btn.textContent="Adding...";logQualityEvent("add_to_cart_clicked",{partId:cardRef.partId,apNumber:cardRef.apNumber,price:cardRef.price});try{localStorage.setItem("max_conversion",JSON.stringify({conversationId:state.conversationId,sessionToken:state.sessionToken,partId:cardRef.partId,apNumber:cardRef.apNumber,price:cardRef.price,timestamp:Date.now()}))}catch(e){}addToCart(partId,1,btn,actions,pUrl,priceStr,cardRef)}}(cartBtn,card.partId,productHref,btnPrice,card);actions.appendChild(cartBtn)}div.appendChild(actions);if((card.inStock||backordered)&&!explicitDisc){var trust=document.createElement("div");trust.className="mx-pc-trust";trust.appendChild(makeCheckSvg());var trustText=document.createTextNode("365-day returns");trust.appendChild(trustText);div.appendChild(trust)}container.appendChild(div);debugLog("part card appended: "+card.apNumber)})}function renderAgentPartCard(part){if(!part||typeof part!=="object"||!part.name)return;var apNum=typeof part.apNumber==="string"?part.apNumber:"";var partId=apNum?apNum.replace(/^AP/i,""):null;var rel=typeof part.productUrl==="string"?part.productUrl.replace(/^https?:\/\/[^/]+/i,""):null;var card={partId:partId,apNumber:apNum,name:part.name,imageUrl:typeof part.imageUrl==="string"?part.imageUrl:null,price:typeof part.price==="number"?part.price:null,inStock:!!part.inStock,productUrl:rel,manufacturer:typeof part.manufacturer==="string"?part.manufacturer:null,manufacturerPartNumber:typeof part.partNumber==="string"?part.partNumber:null};addPartCards([card],state.modelNumber,"agent");logQualityEvent("part_card_shown",{partId:card.partId,apNumber:card.apNumber});pushDataLayer("chat_card_shown",{part_id:card.apNumber,source:"agent"})}function addToCart(partId,qty,btn,actionsDiv,productUrl,priceStr,cardRef){var hostFnType=typeof window.addtocart;debugLog("addToCart: typeof addtocart="+hostFnType+", partId="+partId+", qty="+qty);var defaultText="Add to Cart"+(priceStr||"");function report(outcome,extra){var data={outcome:outcome,partId:partId!=null?String(partId):null,apNumber:cardRef&&cardRef.apNumber?String(cardRef.apNumber):null,pageType:state.pageContext?state.pageContext.pageType:null,hostFn:
2hostFnType};if(extra){for(var k in extra){if(Object.prototype.hasOwnProperty.call(extra,k)&&extra[k]!=null)data[k]=extra[k]}}try{logQualityEvent("add_to_cart_result",data)}catch(e){}}function errText(e){try{return String(e&&e.message?e.message:e).slice(0,160)}catch(err){return""}}function showPdpFallback(){if(productUrl){var link=document.createElement("a");link.className="mx-pc-cart-link";link.href=productUrl;link.target="_blank";link.rel="noopener";link.textContent="Add from product page";actionsDiv.insertBefore(link,btn.nextSibling)}}function resetBtn(){btn.textContent=defaultText;btn.className="mx-pc-cart-btn";btn.disabled=false}function showViewCart(){var cartLink=document.createElement("a");cartLink.className="mx-pc-cart-link";cartLink.href="/cart.aspx";cartLink.textContent="View Cart";actionsDiv.insertBefore(cartLink,btn.nextSibling)}function showAdded(){btn.className="mx-pc-cart-btn added";btn.textContent="\u2713 Added to Cart";btn.disabled=true;showViewCart()}function showSent(){btn.className="mx-pc-cart-btn sent";btn.textContent="Sent to cart";btn.disabled=true;showViewCart()}function showFailed(){btn.className="mx-pc-cart-btn error";btn.textContent="Unable to add to cart";showPdpFallback();setTimeout(resetBtn,3e3)}function showNotAdded(){btn.className="mx-pc-cart-btn error";btn.textContent="Not added";btn.disabled=true;showPdpFallback()}function readCartCount(){try{var jq=window.jQuery||window.$;if(typeof jq!=="function")return null;var holder=jq("#cart-top-detail .cart-holder");if(!holder||!holder.length)return null;var n=parseInt(holder.data("count"),10);return isNaN(n)?null:n}catch(e){return null}}var cartCountBefore=readCartCount();function waitForCartCount(cb){var tries=0;var last=null;(function poll(){var count=readCartCount();if(count!=null)last=count;if(count!=null&&count!==cartCountBefore||tries>=8)return cb(last);tries++;setTimeout(poll,250)})()}if(hostFnType==="function"){try{var result=window.addtocart(partId,qty);if(result&&typeof result.then==="function"){result.then(function(data){if(data===undefined){report("resolved",{resolvedValue:"undefined",treatedAs:"neutral"});showSent();return}var value=String(data).trim();var resolvedValue=value===""?"(empty)":value.slice(0,40);if(value==="0"){showAdded();waitForCartCount(function(count){report("resolved",{resolvedValue:resolvedValue,treatedAs:"success",cartCount:count})})}else if(value==="-1"){report("resolved",{resolvedValue:resolvedValue,treatedAs:"failure"});showNotAdded()}else{report("resolved",{resolvedValue:resolvedValue,treatedAs:"failure",unexpected:true});showNotAdded()}}).catch(function(err){report("rejected",{error:errText(err),treatedAs:"failure"});showFailed()})}else{var returnType=result===null?"null":typeof result;if(result===false){report("non_promise_return",{returnType:returnType,returnValue:false,treatedAs:"failure"});showFailed()}else if(result===true){report("non_promise_return",{returnType:returnType,returnValue:true,treatedAs:"success"});showAdded()}else{report("non_promise_return",{returnType:returnType,treatedAs:"neutral"});showSent()}}}catch(e){debugLog("addToCart threw: "+e.message);report("threw",{error:errText(e)}
2);showFailed()}}else{debugLog("addToCart: window.addtocart not found, showing PDP link");report("host_function_missing");showFailed()}}var CHIP_MESSAGE_MAP={"I have a model or part number":"I have a model number","Something's broken, help me fix it":"Something's broken"};function handleChipClick(text){if(text==="Yes, help me"){acceptMaxHelpDuringWait();return}if(text==="No, I'll wait"){declineMaxHelpDuringWait();return}removeInlineChips();if(text==="Talk to a person"){debugLog('[MAX-HANDOFF] chip "Talk to a person" clicked, opening contact form');requestHandoffWithContact();return}if(text==="Leave a message"){debugLog('[MAX-HANDOFF] chip "Leave a message" clicked, opening leave-message form');clearWelcome();state.hasConversation=true;renderLeaveMessageForm();return}var inp=shadow.querySelector("#mx-chat-input");if(inp){inp.value=CHIP_MESSAGE_MAP[text]||text;sendMessage()}}function showTyping(){state.isTyping=true;var container=shadow.querySelector("#mx-messages");if(!container)return;var row=document.createElement("div");row.className="mx-msg-row bot";row.id="mx-typing";row.appendChild(makeAvatar(28));var typing=document.createElement("div");typing.className="mx-typing";for(var i=0;i<3;i++){typing.appendChild(document.createElement("span"))}var label=document.createElement("div");label.className="mx-typing-label";label.id="mx-typing-label";label.textContent="Thinking...";typing.appendChild(label);row.appendChild(typing);container.appendChild(row);container.scrollTop=container.scrollHeight;state._typingLabelTimer=setTimeout(function(){var lbl=shadow.querySelector("#mx-typing-label");if(lbl)lbl.classList.add("visible")},3e3)}function hideTyping(){state.isTyping=false;if(state._typingLabelTimer){clearTimeout(state._typingLabelTimer);state._typingLabelTimer=null}var el=shadow.querySelector("#mx-typing");if(el)el.remove()}function replayMessages(){clearWelcome();setComposerEnabled(true);var container=shadow.querySelector("#mx-messages");if(!container)return;state.messages.forEach(function(msg){if(msg.role==="bot"){var row=document.createElement("div");row.className="mx-msg-row bot";row.appendChild(makeAvatar(28));var bubble=document.createElement("div");bubble.className="mx-msg-bubble bot";bubble.innerHTML=renderBotMarkdown(msg.content);row.appendChild(bubble);container.appendChild(row);if(msg.messageId){addFeedbackButtons(container,msg.messageId)}}else if(msg.role==="parts"){addPartCards(msg.cards)}else if(msg.role==="video"){addVideoCard(msg.video)}else if(msg.role==="customer"){var row2=document.createElement("div");row2.className="mx-msg-row user";var bubble2=document.createElement("div");bubble2.className="mx-msg-bubble user";bubble2.textContent=msg.content;row2.appendChild(bubble2);container.appendChild(row2)}else if(msg.role==="checkout"){renderCheckoutCard(msg.items,msg.total,msg.sentBy,true)}});if(state.quickReplies.length>0){addInlineChips(state.quickReplies)}container.scrollTop=container.scrollHeight;updateShareButton()}function saveSession(){try{localStorage.setItem("max_session",JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,pageContext:state.pageContext,model:state.modelNumber,brand:state.brand,applianceType:state.applianceType,lastActive:Date.now()}))}catch(e){}}function restoreQuickReplies(input){var stored=input&&input.lastBotQuickReplies;if(stored&&stored.length)return stored.slice();if(input&&input.hasPartsAfterLastBot)return["How do I replace this?","I need a different part","What else might I need?"];var text=input&&input.lastBotText||"";if(/\?\s*(?:\[[^\]]*\]\([^)]*\)\s*)?$/.test(text))return[];return["Help me find a part","Talk to a person"]}function fetchHistory(){var container=shadow.querySelector("#mx-messages");if(container){var loading=document.createElement("div");loading.className="mx-msg-row bot";loading.id="mx-history-loading";loading.appendChild(makeAvatar(28));var bubble=document.createElement("div");bubble.className="mx-msg-bubble bot";bubble.textContent="Restoring your conversation...";loading.appendChild(bubble);container.appendChild(loading)}state.historyLoading=true;fetch(API_BASE+"/api/chat/history",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId})}).then(function(r){if(!r.ok)throw new Error("history fetch failed: "+r.status);return r.json()}).then(function(messages){state.historyLoading=false;var loadEl=shadow.querySelector("#mx-history-loading");if(loadEl)loadEl.remove();if(!messages||messages.length===0){if(state.isOpen)showWelcomeOrConsentGate();flushEntryMessage();return}state.messages=[];var lastBotQuickReplies=null;var lastBotFullText="";
2messages.forEach(function(m){state.messages.push({role:m.role,content:m.content});if(m.role==="customer")state.customerMsgCount++;if(m.role==="bot"&&!(m.metadata&&m.metadata.statusMessage)){lastBotFullText=m.content||"";lastBotQuickReplies=m.metadata&&Array.isArray(m.metadata.quickReplies)?m.metadata.quickReplies:null}if(m.role==="bot"&&m.metadata){if(m.metadata.partCards&&m.metadata.partCards.length>0){state.messages.push({role:"parts",cards:m.metadata.partCards});state.hadPartCard=true}if(m.metadata.video){state.messages.push({role:"video",video:m.metadata.video})}}});state.hasConversation=true;var lastBot="";for(var i=state.messages.length-1;i>=0;i--){if(state.messages[i].role==="bot"){lastBot=state.messages[i].content;break}}state.lastBotText=lastBot.substring(0,100);var hasPartsAfterLastBot=false;for(var j=state.messages.length-1;j>=0;j--){if(state.messages[j].role==="parts"){hasPartsAfterLastBot=true;break}if(state.messages[j].role==="customer")break}state.quickReplies=restoreQuickReplies({lastBotQuickReplies:lastBotQuickReplies,hasPartsAfterLastBot:hasPartsAfterLastBot,lastBotText:lastBotFullText});if(state.isOpen)replayMessages();addNewConversationLink();flushEntryMessage()}).catch(function(err){debugLog("history restore failed: "+(err&&err.message||err));state.historyLoading=false;var loadEl=shadow.querySelector("#mx-history-loading");if(loadEl)loadEl.remove();try{localStorage.removeItem("max_session")}catch(e){}state.sessionToken=null;state.conversationId=null;state.hasConversation=false;state.messages=[];initSession()})}function addNewConversationLink(){var container=shadow.querySelector("#mx-messages");if(!container)return;var link=document.createElement("div");link.style.cssText="text-align:center;margin:8px 0 12px;";var btn=document.createElement("button");btn.style.cssText="background:none;border:none;color:"+C.t3+";font-size:12px;cursor:pointer;text-decoration:underline;text-underline-offset:2px;font-family:"+FONT+";";btn.textContent="Start new conversation";btn.onclick=function(){resetWidgetState();var msgs=shadow.querySelector("#mx-messages");if(msgs){while(msgs.firstChild)msgs.removeChild(msgs.firstChild)}initSession()};link.appendChild(btn);container.appendChild(link);container.scrollTop=container.scrollHeight}var BOT_UA_TOKENS=["amazonbot","applebot","googlebot","bingbot","yandexbot","baiduspider","duckduckbot","slurp","facebookexternalhit","twitterbot","linkedinbot","mj12bot","ahrefsbot","semrushbot","dotbot","petalbot","bytespider","meta-externalads","meta-externalagent","adsbot-google","mediapartners-google"];function isLikelyBot(){try{var ua=(navigator.userAgent||"").toLowerCase();if(!ua)return false;for(var i=0;i<BOT_UA_TOKENS.length;i++){if(ua.indexOf(BOT_UA_TOKENS[i])!==-1)return true}}catch(e){}return false}function getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||null}catch(e){return null}}function initSession(){if(state.sessionToken||state._sessionPending||state._blockedMessage)return;if(isLikelyBot())return;state._sessionPending=true;fetch(API_BASE+"/api/chat/start",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({pageContext:state.pageContext,device:isMobile()?"mobile":"desktop",referrer:document.referrer,user_agent:navigator.userAgent,screen_width:window.screen.width,screen_height:window.screen.height,language:navigator.language,page_url:window.location.href,timezone:getTimezone(),pixel_ratio:window.devicePixelRatio,touch_capable:(navigator.maxTouchPoints||0)>0})}).then(function(r){if(!r.ok){state._sessionFailed=true;state._sessionPending=false;if(r.status===429){return r.json().then(function(data){var msg=data&&data.error||"Too many conversations from this connection. Please try again later.";if(state.isOpen)addBotMessage(msg);return Promise.reject("start rate-limited")}).catch(function(){if(state.isOpen)addBotMessage("Too many conversations from this connection. Please try again later.");return Promise.reject("start rate-limited")})}if(state.isOpen){addBotMessage("Max is temporarily unavailable. Please try again later or call us at 1-877-477-7278.")}return Promise.reject("start failed: "+r.status)}return r.json()}).then(function(data){state._sessionPending=false;if(!data)return;if(!data.available){state._sessionFailed=true;if(data.blocked){state._blockedMessage=data.message||"Chat is currently unavailable. Please call 1-877-477-7278 for assistance.";if(state.isOpen)addBotMessage(state._blockedMessage);return}if(state.isOpen){addBotMessage("Max isn't available on this page. Visit a product or model page to chat, or call us at 1-877-477-7278.")}return}state.sessionToken=data.sessionToken;state.conversationId=data.conversationId;state.businessHours=data.businessHours;saveSession();ensureNavTracking();proactiveFlushPending();if(state.isOpen)fetchPdpPartName(state.pageContext);if(state.isOpen&&!state.hasConversation){showWelcomeOrConsentGate()}flushEntrySource();flushEntryMessage()}).catch(function(err){state._sessionPending=false;debugLog("chat start failed: "+(err&&err.message||err));if(state.isOpen&&!shadow.querySelector(".mx-msg-bubble")){addBotMessage("Could not connect to Max. Please check your connection and try again.")}})}
2function showWelcomeIfReady(){var welcome=getWelcomeContent();var inp=shadow.querySelector("#mx-chat-input");if(inp)inp.placeholder=welcome.placeholder;if(state.sessionToken){showWelcomeOrConsentGate()}else if(state._blockedMessage){addBotMessage(state._blockedMessage)}else if(state._sessionFailed){addBotMessage("Max is temporarily unavailable. Please try again later or call us at 1-877-477-7278.")}}var PHOTO_UPLOADED_MARKER="[Photo uploaded - please analyze]";function shouldHoldTextForUpload(st){return!!st&&(st.uploadTurnsOpen||0)>0&&!st.agentMode}function beginUploadTurn(st){st.uploadTurnsOpen=(st.uploadTurnsOpen||0)+1}function endUploadTurn(st){st.uploadTurnsOpen=Math.max(0,(st.uploadTurnsOpen||0)-1)}function queueTextDuringUpload(st,text){if(!st.pendingUploadText)st.pendingUploadText=[];st.pendingUploadText.push(text)}function takePendingUploadText(st){var queued=st.pendingUploadText||[];st.pendingUploadText=[];return queued.join(" ").replace(/\s+/g," ").trim()}function composeVisionMessage(pendingText){return pendingText?PHOTO_UPLOADED_MARKER+" "+pendingText:PHOTO_UPLOADED_MARKER}var VISION_SEND_GRACE_MS=3e3;function armVisionSend(st,fire,setTimer){var fired=false;var trigger=function(){if(fired)return false;fired=true;st.visionSendTrigger=null;fire();return true};st.visionSendTrigger=trigger;(setTimer||setTimeout)(trigger,VISION_SEND_GRACE_MS);return trigger}function fireVisionSendIfArmed(st){return typeof st.visionSendTrigger==="function"?st.visionSendTrigger():false}function applyDoneModel(st,data){if(!st||!data||data.modelNumber===undefined)return false;var seq=typeof data.stateSeq==="number"?data.stateSeq:null;if(seq!==null&&typeof st.modelStateSeq==="number"&&seq<st.modelStateSeq)return false;if(seq!==null)st.modelStateSeq=seq;st.modelNumber=data.modelNumber||null;return true}var DEFERRED_VISION_MAX_MS=2e4;function shouldDeferVisionForTextTurn(st){return!!st&&st.isSending===true}function deferVisionSend(st,fire,setTimer){var fired=false;var trigger=function(){if(fired)return false;fired=true;if(st.deferredVisionSend===trigger)st.deferredVisionSend=null;fire();return true};st.deferredVisionSend=trigger;(setTimer||setTimeout)(trigger,DEFERRED_VISION_MAX_MS);return trigger}function fireDeferredVisionSend(st){return!!st&&typeof st.deferredVisionSend==="function"?st.deferredVisionSend():false}var DUPLICATE_UPLOAD_WINDOW_MS=15e3;function uploadKey(file){return(file&&file.name||"")+"|"+(file&&file.size||0)}function shouldQueueUpload(st){return!!st&&(st.uploadTurnsOpen||0)>0&&!st.agentMode}function queueUpload(st,item){if(!st.uploadQueue)st.uploadQueue=[];st.uploadQueue.push(item)}function takeQueuedUpload(st){var q=st&&st.uploadQueue||[];return q.length?q.shift():null}function recordCompletedUpload(st,file,now){if(!st.completedUploads)st.completedUploads=[];st.completedUploads.push({key:uploadKey(file),at:now||Date.now()});if(st.completedUploads.length>20)st.completedUploads.shift()}function isDuplicateUpload(st,file,now){var k=uploadKey(file);var t=now||Date.now();return(st&&st.completedUploads||[]).some(function(u){return u.key===k&&t-u.at<DUPLICATE_UPLOAD_WINDOW_MS})}var PLATFORM_BODY_LIMIT_BYTES=4.5*1024*1024;var MAX_ATTACHMENT_BYTES=4*1024*1024;var MAX_VISION_BASE64_CHARS=44e5;var VISION_MAX_SIDE=2e3;var VISION_JPEG_QUALITY=.8;var VISION_RETRY_MAX_SIDE=1600;var VISION_RETRY_JPEG_QUALITY=.7;var DOWNSCALE_MIN_BYTES=1024*1024;var DOWNSCALABLE_TYPES={"image/jpeg":true,"image/png":true,"image/webp":true};function planImageDownscale(width,height,maxSide){var w=Math.max(1,Math.round(width||0));var h=Math.max(1,Math.round(height||0));var longest=Math.max(w,h);if(!maxSide||longest<=maxSide)return{width:w,height:h,scale:1};var scale=maxSide/longest;return{width:Math.max(1,Math.round(w*scale)),height:Math.max(1,Math.round(h*scale)),scale:scale}}function shouldDownscaleImage(fileType,fileBytes,width,height){if(!DOWNSCALABLE_TYPES[fileType])return false;return Math.max(width||0,height||0)>VISION_MAX_SIDE||(fileBytes||0)>DOWNSCALE_MIN_BYTES}function base64CharsForBytes(bytes){return Math.ceil((bytes||0)/3)*4}function photoFitsBothRequests(bytes){return(bytes||0)<=MAX_ATTACHMENT_BYTES&&base64CharsForBytes(bytes)<=MAX_VISION_BASE64_CHARS}function jpegFilename(name){var base=String(name||"photo").replace(/\.[A-Za-z0-9]{1,5}$/,"");return(base||"photo")+".jpg"}function recordPhotoTurnOutcome(st,landed){st.lastPhotoTurnLanded=landed===true}function takePhotoTurnLanded(st){var landed=!!(st&&st.lastPhotoTurnLanded===true);if(st)st.lastPhotoTurnLanded=false;return landed}function releaseSendLock(){state.isSending=false;fireDeferredVisionSend(state)}function flushHeldText(){if(shouldHoldTextForUpload(state))return;var landed=takePhotoTurnLanded(state);var held=takePendingUploadText(state);if(held)sendMessageText(held,{alreadyRendered:true,followsPhoto:landed})}function sendMessage(){var inp=shadow.querySelector("#mx-chat-input");if(!inp)return;var text=inp.value.trim();if(!text||!state.sessionToken)return;if(consentPending()&&!state.hasConversation){showConsentGate();return}if(shouldHoldTextForUpload(state)){inp.value="";inp.style.height="auto";stopCustomerTyping();removeInlineChips();addCustomerMessage(text);queueTextDuringUpload(state,text);if(fireVisionSendIfArmed(state))debugLog("[SEND] joined the photo turn");else debugLog("[SEND] held during photo upload");return}if(state.isSending){debugLog("[SEND] ignored - already sending");return}inp.value="";inp.style.height="auto";sendMessageText(text,{})}function sendMessageText(text,opts){opts=opts||{};if(!text||!state.sessionToken)return;if(state.isSending){debugLog("[SEND] ignored - already sending");return}state.isSending=true;ensureAudioUnlocked();stopCustomerTyping();removeInlineChips();if(state.lastCustomerMsg&&wordOverlap(text,state.lastCustomerMsg)>.6){logQualityEvent("rephrase_detected",{original:state.lastCustomerMsg,rephrased:text})}if(state.customerMsgCount===0){logQualityEvent("message_sent",{firstMessage:text.substring(0,100)});pushDataLayer("chat_engaged");setAttributionCookie()}if(!opts.alreadyRendered)addCustomerMessage(text);if(state.agentMode&&isReturnToMaxPhrase(text)){debugLog("[AGENT] return-to-max phrase detected: "+text);triggerReturnToMax();releaseSendLock();return}if(state.agentMode&&!state.bypassAgentSend){if(state.agentRestoring){state.pendingAgentMessages.push(text);debugLog("[AGENT] queued message during restore");releaseSendLock();return}fetch(API_BASE+"/api/chat/message",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,message:text})}).then(function(response){releaseSendLock();if(response.status===429){if(state.agentName){return response.json().catch(function(){return null}).then(function(){addAgentSystemMessage("Please wait a moment before sending another message.")})}return response.json().then(function(data){var msg=data&&data.error||"You're sending messages quickly. Please wait a moment.";addBotMessage(msg)}).catch(function(){addBotMessage("You're sending messages quickly. Please wait a moment.")})}}).catch(function(err){releaseSendLock();debugLog("[AGENT] forward failed: "+(err&&err.message))});return}showTyping();try{state.pageContext=detectPageContext()}catch(e){}fetch(API_BASE+"/api/chat/message",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,message:text,followsPhoto:opts.followsPhoto===true?true:undefined,modelNumber:state.modelNumber,brand:state.brand,applianceType:state.applianceType,pageContext:state.pageContext,browsingHistory:state.browsingHistory,entrySource:state.entrySource&&!state.entrySourceStamped&&state.entrySourcePingFailed?state.entrySource:undefined,routeToMax:state.bypassAgentSend===true&&state.maxHelpDuringWait===true?true:undefined,consent:state.customerMsgCount===1?{displayed_at:state.consentDisplayedAt,accepted_at:getConsentAcceptedAt()||undefined,version:CONSENT_VERSION}:undefined})}).then(function(response){if(!response.ok){hideTyping();if(response.status===429){return response.json().then(function(data){var msg=data&&data.error||"You're sending messages quickly. Please wait a moment and try again.";addBotMessage(msg);addInlineChips(["Talk to a person"]);releaseSendLock()}).catch(function(){addBotMessage("You're sending messages quickly. Please wait a moment and try again.");addInlineChips(["Talk to a person"]);releaseSendLock()})}addBotMessage("I'm having trouble right now. Could you try again, or I can connect you with our support team.");addInlineChips(["Try again","Talk to a person"]);releaseSendLock();return}if(state.entrySource&&state.entrySourcePingFailed)state.entrySourceStamped=true;var answerType=response.headers.get("content-type")||"";if(answerType.indexOf("application/json")!==-1){return response.json().catch(function(){return null}).then(function(data){hideTyping();releaseSendLock();if(isAgentForwardAnswer(answerType,data)){debugLog("[AGENT] message forwarded to a reopened agent chat; entering agent mode");resumeAgentModeAfterForward(data);return}addBotMessage("I'm having trouble right now. Could you try again, or I can connect you with our support team.");addInlineChips(["Try again","Talk to a person"])})}var reader=response.body.getReader();var decoder=new TextDecoder;var buffer="";var lastMsgId=null;var gotTextEvent=false;var botMsgRow=null;var partCardsRendered=false;var videoRendered=false;var quickRepliesRendered=false;function renderPartCardsOnce(cards,cardModelNumber){if(partCardsRendered)return;if(!cards||cards.length===0)return;partCardsRendered=true;addPartCards(cards,cardModelNumber);state.messages.push({role:"parts",cards:cards});cards.forEach(function(c){logQualityEvent("part_card_shown",{partId:c.partId,apNumber:c.apNumber});pushDataLayer("chat_card_shown",{part_id:c.apNumber,source:"max"})})}function renderVideoOnce(video){if(videoRendered)return;if(!video)return;videoRendered=true;
2if(!video.title){var lastParts=null;for(var mi=state.messages.length-1;mi>=0;mi--){if(state.messages[mi].role==="parts"&&state.messages[mi].cards&&state.messages[mi].cards.length>0){lastParts=state.messages[mi].cards[0];break}}if(lastParts){var brand=(lastParts.manufacturer||"").toLowerCase().replace(/\b\w/g,function(c){return c.toUpperCase()});video.title="How to Replace "+(brand?brand+" ":"")+(lastParts.apNumber||"")+" "+(lastParts.name||"");video.title=video.title.replace(/\s+/g," ").trim()}}addVideoCard(video);state.messages.push({role:"video",video:video})}function renderQuickRepliesOnce(replies){if(quickRepliesRendered)return;if(!replies||replies.length===0)return;quickRepliesRendered=true;state.quickReplies=replies;addInlineChips(replies)}function read(){return reader.read().then(function(result){if(result.done){if(buffer.length>0){var trailing=(buffer+"\n").split("\n");buffer="";processSseLines(trailing)}hideTyping();if(!gotTextEvent){addBotMessage("I'm having trouble right now. Could you try again, or I can connect you with our support team.");addInlineChips(["Try again","Talk to a person"])}releaseSendLock();return}var chunk=decoder.decode(result.value,{stream:true});debugLog("SSE chunk received, length="+chunk.length);buffer+=chunk;var lines=buffer.split("\n");buffer=lines.pop()||"";processSseLines(lines);return read()})}function processSseLines(lineList){lineList.forEach(function(line){if(!line.startsWith("data: "))return;try{var data=JSON.parse(line.slice(6));debugLog("SSE event: "+data.type+(data.type==="part_cards"?" ("+(data.cards?data.cards.length:0)+" cards)":""));if(data.type==="text"){gotTextEvent=true;hideTyping();botMsgRow=addBotMessage(data.content);if(data.statusMessage)showTyping()}else if(data.type==="part_cards"){renderPartCardsOnce(data.cards,data.modelNumber)}else if(data.type==="video"){renderVideoOnce(data.video)}else if(data.type==="quick_replies"){renderQuickRepliesOnce(data.replies)}else if(data.type==="status"){var statusLbl=shadow.querySelector("#mx-typing-label");if(statusLbl){statusLbl.textContent=data.message;statusLbl.classList.add("visible")}}else if(data.type==="action"&&data.action==="handoff"){if(data.force&&state.handoffCompleted&&!state.agentMode){debugLog("[MAX-HANDOFF] server forced handoff, clearing stale completed flag");state.handoffCompleted=false}if(state.handoffCompleted){debugLog("[MAX-HANDOFF] server sent handoff action but handoff already completed, skipping")}else{debugLog("[MAX-HANDOFF] server sent handoff action, calling handleHandoff()");handleHandoff()}}else if(data.type==="action"&&data.action==="collect_contact"){debugLog("[MAX-HANDOFF] server requested contact form");requestHandoffWithContact()}else if(data.type==="action"&&data.action==="offline_options"){debugLog("[MAX-HANDOFF] server says agents offline, rendering offline options");renderOfflineOptionButtons({support_phone:data.support_phone})}else if(data.type==="action"&&data.action==="offer_transcript"){debugLog("[MAX-CLOSURE] server requested transcript offer");if(state.alcConversationId){renderEmailTranscriptOffer()}}else if(data.type==="done"&&data.messageId){lastMsgId=data.messageId;applyDoneModel(state,data);if(data.brand)state.brand=data.brand;if(data.applianceType)state.applianceType=data.applianceType;if(data.customerName)state.capturedName=data.customerName;if(data.partCards)renderPartCardsOnce(data.partCards,data.cardModelNumber);if(data.video)renderVideoOnce(data.video);if(data.quickReplies)renderQuickRepliesOnce(data.quickReplies);saveSession();var msgContainer=shadow.querySelector("#mx-messages");if(msgContainer&&!msgContainer.querySelector('.mx-feedback[data-mid="'+lastMsgId+'"]')){addFeedbackButtons(msgContainer,lastMsgId)}var lastIdx=state.messages.length-1;while(lastIdx>=0){if(state.messages[lastIdx].role==="bot"){state.messages[lastIdx].messageId=lastMsgId;break}lastIdx--}if(state.customerMsgCount>3&&!state.hadPartCard){logQualityEvent("stuck_no_parts",{turnCount:state.customerMsgCount},lastMsgId)}if(botMsgRow){var msgScrollEl=shadow.querySelector("#mx-messages");
2if(msgScrollEl)msgScrollEl.scrollTop=msgScrollEl.scrollHeight}}else if(data.type==="error"){hideTyping();addBotMessage(data.message||"Something went wrong. Please try again.")}}catch(e){debugLog("SSE parse error: "+e.message+" line: "+line.substring(0,100))}})}return read()}).catch(function(err){hideTyping();addBotMessage("I'm having trouble right now. Could you try again, or I can connect you with our support team.");addInlineChips(["Try again","Talk to a person"]);debugLog("message send failed: "+(err&&err.message||err));releaseSendLock()})}function sendFeedback(messageId,rating){if(!state.sessionToken)return;fetch(API_BASE+"/api/chat/feedback",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,messageId:messageId,rating:rating})}).catch(function(){})}var ATTACHMENT_TYPES={"image/jpeg":true,"image/png":true,"image/gif":true,"image/webp":true,"application/pdf":true};function renderAttachmentInline(opts){var msgs=shadow.querySelector("#mx-messages");if(!msgs)return null;var wrap=document.createElement("div");wrap.className="mx-attachment";if(opts.isImage){var img=document.createElement("img");img.src=opts.url;img.alt=opts.filename||"Attached image";img.onclick=function(){try{window.open(opts.url,"_blank","noopener")}catch(e){}};wrap.appendChild(img)}else{var card=document.createElement("div");card.className="mx-attachment-card";var icon=document.createElement("div");icon.style.cssText="width:32px;height:32px;border-radius:8px;background:"+C.navy+";color:#FFF;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;flex:0 0 32px;";icon.textContent=(opts.ext||"PDF").toUpperCase().slice(0,3);var label=document.createElement("div");label.style.cssText="display:flex;flex-direction:column;gap:2px;min-width:0;";var name=document.createElement("div");name.style.cssText="font-size:13px;font-weight:500;color:"+C.t1+";white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:200px;";name.textContent=opts.filename||"Attachment";var link=document.createElement("a");link.href=opts.url;link.target="_blank";link.rel="noopener";link.textContent="View";label.appendChild(name);label.appendChild(link);card.appendChild(icon);card.appendChild(label);wrap.appendChild(card)}msgs.appendChild(wrap);msgs.scrollTop=msgs.scrollHeight;state.messages.push({role:"customer",content:"[Attachment: "+(opts.filename||"file")+"]",attachment:opts});return wrap}function showAttachmentProgress(){var msgs=shadow.querySelector("#mx-messages");if(!msgs)return null;var wrap=document.createElement("div");wrap.className="mx-attachment";wrap.id="mx-attachment-progress-wrap";var bar=document.createElement("div");bar.className="mx-attachment-progress";bar.appendChild(document.createElement("div"));wrap.appendChild(bar);msgs.appendChild(wrap);msgs.scrollTop=msgs.scrollHeight;return wrap}function hideAttachmentProgress(node){if(node&&node.parentNode)node.parentNode.removeChild(node)}function handleUpload(file){if(!state.sessionToken||!state.conversationId)return;if(!file||!ATTACHMENT_TYPES[file.type]){addBotMessage("That file type is not supported. Please send a JPEG, PNG, GIF, WebP, or PDF.");return}if(file.size>MAX_ATTACHMENT_BYTES&&!DOWNSCALABLE_TYPES[file.type]){addBotMessage("That file is too large. Max size is 4MB.");return}if(isDuplicateUpload(state,file)){debugLog("[UPLOAD] duplicate of a file sent within 15 s, ignored");return}if(shouldQueueUpload(state)){queueUpload(state,{file:file,inlineNode:renderUploadPreview(file)});debugLog("[UPLOAD] queued behind the open photo turn");return}startUpload(file,null)}function renderUploadPreview(file){var isImage=file.type.indexOf("image/")===0;var localUrl=null;try{localUrl=URL.createObjectURL(file)}catch(e){}return localUrl?renderAttachmentInline({url:localUrl,filename:file.name,isImage:isImage,ext:(file.type.split("/")[1]||"").slice(0,3)}):null}function startQueuedUpload(item){if(!item||!item.file)return;if(isDuplicateUpload(state,item.file)){debugLog("[UPLOAD] queued duplicate dropped");if(item.inlineNode)hideAttachmentProgress(item.inlineNode);startQueuedUpload(takeQueuedUpload(state));return}startUpload(item.file,item.inlineNode)}function startUpload(file,prerenderedNode){var dedupeKey=uploadKey(file);if(!state._uploadsInFlight)state._uploadsInFlight={};if(state._uploadsInFlight[dedupeKey])return;state._uploadsInFlight[dedupeKey]=true;var clearInFlight=function(){delete state._uploadsInFlight[dedupeKey]};beginUploadTurn(state);var uploadTurnOpen=true;var closeUploadTurn=function(landed){if(!uploadTurnOpen)return;uploadTurnOpen=false;recordPhotoTurnOutcome(state,landed===true);endUploadTurn(state);flushHeldText();startQueuedUpload(takeQueuedUpload(state))};var isImage=file.type.indexOf("image/")===0;var inlineNode=prerenderedNode||renderUploadPreview(file);var progressNode=!inlineNode?showAttachmentProgress():null;var toAgent=function(){return state.agentMode&&!state.bypassAgentSend};preparePhotoForUpload(file).then(function(prep){var sendFile=prep.file;var failure=function(stage,status){if(!toAgent())reportPhotoFailure(stage,status,file.size,sendFile.size,prep.downscaled)};var tooLarge=sendFile.size>MAX_ATTACHMENT_BYTES||isImage&&!toAgent()&&!photoFitsBothRequests(sendFile.size);if(tooLarge){if(progressNode)hideAttachmentProgress(progressNode);if(inlineNode)hideAttachmentProgress(inlineNode);
2addBotMessage(isImage?"That photo is too large for me to receive, and I couldn't shrink it on this device. Try a smaller or cropped photo, or type the model or part number printed on it.":"That file is too large. Max size is 4MB.");if(isImage)failure("too_large",null);closeUploadTurn(false);return null}var fd=new FormData;fd.append("sessionToken",state.sessionToken);fd.append("conversationId",state.conversationId);fd.append("file",sendFile,prep.filename);return fetch(API_BASE+"/api/chat/attachment",{method:"POST",credentials:"include",body:fd}).then(function(r){return r.json().then(function(data){return{ok:r.ok,status:r.status,data:data}},function(){return{ok:false,status:r.status,data:null}})}).then(function(res){if(progressNode)hideAttachmentProgress(progressNode);if(!res.ok||!res.data||!res.data.success){if(inlineNode)hideAttachmentProgress(inlineNode);addBotMessage(res.data&&res.data.error||"Upload failed. Please try again.");if(isImage)failure("upload",res.status);closeUploadTurn(false);return}recordCompletedUpload(state,file);var finalUrl=res.data.url;if(!inlineNode&&finalUrl){renderAttachmentInline({url:finalUrl,filename:res.data.filename,isImage:(res.data.mime_type||"").indexOf("image/")===0,ext:res.data.ext})}if(toAgent()){addAgentSystemMessage("Attachment sent to agent.");closeUploadTurn(false);return}if(isImage){var visionDone=function(landed,status){if(!landed)failure(status==="no_reply"?"no_reply":"vision",typeof status==="number"?status:null);closeUploadTurn(landed)};readFileAsBase64(sendFile).then(function(base64){if(shouldDeferVisionForTextTurn(state)){debugLog("[UPLOAD] photo waits for the text reply in flight");deferVisionSend(state,function(){sendImageForVision(base64,prep.mimeType,visionDone)});return}armVisionSend(state,function(){sendImageForVision(base64,prep.mimeType,visionDone)})}).catch(function(){addBotMessage("Got it, but I couldn't process the photo. Try describing what you see.");failure("vision",null);closeUploadTurn(false)})}else{addBotMessage("Got the file. I can't open PDFs directly, but tell me what you'd like me to help with.");closeUploadTurn(false)}})}).catch(function(){if(progressNode)hideAttachmentProgress(progressNode);addBotMessage("Upload failed. Please try again.");if(isImage&&!toAgent())reportPhotoFailure("upload",null,file.size,null,false);closeUploadTurn(false)}).then(clearInFlight)}function decodeImageForCanvas(file){if(typeof createImageBitmap==="function"){return createImageBitmap(file,{imageOrientation:"from-image"}).then(function(bmp){return{source:bmp,width:bmp.width,height:bmp.height,release:function(){try{bmp.close()}catch(e){}}}})}return new Promise(function(resolve,reject){var url;try{url=URL.createObjectURL(file)}catch(e){reject(e);return}var img=new Image;img.onload=function(){resolve({source:img,width:img.naturalWidth,height:img.naturalHeight,release:function(){try{URL.revokeObjectURL(url)}catch(e){}}})};img.onerror=function(){try{URL.revokeObjectURL(url)}catch(e){}reject(new Error("decode failed"))};img.src=url})}function encodeCanvasJpeg(decoded,maxSide,quality){return new Promise(function(resolve){try{var plan=planImageDownscale(decoded.width,decoded.height,maxSide);var canvas=document.createElement("canvas");canvas.width=plan.width;canvas.height=plan.height;var ctx=canvas.getContext("2d");if(!ctx||typeof canvas.toBlob!=="function"){resolve(null);return}ctx.fillStyle="#FFFFFF";ctx.fillRect(0,0,plan.width,plan.height);ctx.imageSmoothingEnabled=true;ctx.imageSmoothingQuality="high";ctx.drawImage(decoded.source,0,0,plan.width,plan.height);canvas.toBlob(function(blob){resolve(blob||null)},"image/jpeg",quality)}catch(e){resolve(null)}})}function preparePhotoForUpload(file){var original={file:file,filename:file.name,mimeType:file.type,downscaled:false};if(!DOWNSCALABLE_TYPES[file.type])return Promise.resolve(original);return decodeImageForCanvas(file).then(function(decoded){if(!shouldDownscaleImage(file.type,file.size,decoded.width,decoded.height)){decoded.release();return original}var asResult=function(blob){return{file:blob,filename:jpegFilename(file.name),mimeType:"image/jpeg",downscaled:true}};return encodeCanvasJpeg(decoded,VISION_MAX_SIDE,VISION_JPEG_QUALITY).then(function(blob){if(blob&&photoFitsBothRequests(blob.size)&&(blob.size<file.size||!photoFitsBothRequests(file.size))){decoded.release();debugLog("[UPLOAD] photo downscaled",file.size,"->",blob.size);return asResult(blob)}if(photoFitsBothRequests(file.size)){decoded.release();return original}
2return encodeCanvasJpeg(decoded,VISION_RETRY_MAX_SIDE,VISION_RETRY_JPEG_QUALITY).then(function(smaller){decoded.release();return smaller&&photoFitsBothRequests(smaller.size)?asResult(smaller):original})})}).catch(function(){return original})}function reportPhotoFailure(stage,status,originalBytes,sentBytes,downscaled){if(!state.sessionToken||!state.conversationId)return;try{fetch(API_BASE+"/api/chat/photo-failure",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,stage:stage,status:typeof status==="number"?status:null,originalBytes:originalBytes,sentBytes:sentBytes,downscaled:downscaled===true})}).catch(function(){})}catch(e){}}function readFileAsBase64(file){return new Promise(function(resolve,reject){var reader=new FileReader;reader.onload=function(e){var result=e.target.result||"";var idx=result.indexOf(",");resolve(idx>=0?result.slice(idx+1):result)};reader.onerror=function(){reject(new Error("read failed"))};reader.readAsDataURL(file)})}function sendImageForVision(base64,mimeType,onTurnEnd){var endTurn=function(landed,status){if(typeof onTurnEnd==="function"){var f=onTurnEnd;onTurnEnd=null;f(landed===true,status)}};var visionMessage=composeVisionMessage(takePendingUploadText(state));fetch(API_BASE+"/api/chat/message",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,message:visionMessage,imageBase64:base64,imageMimeType:mimeType,modelNumber:state.modelNumber,brand:state.brand,applianceType:state.applianceType,pageContext:state.pageContext})}).then(function(response){if(!response.ok){hideTyping();if(response.status===429){return response.json().then(function(data){var msg=data&&data.error||"You're sending messages quickly. Please wait a moment and try again.";addBotMessage(msg)}).catch(function(){addBotMessage("You're sending messages quickly. Please wait a moment and try again.")}).then(function(){endTurn(false,429)})}addBotMessage("I had trouble analyzing that photo. Could you describe what you see?");endTurn(false,response.status);return}var reader=response.body.getReader();var decoder=new TextDecoder;var buffer="";var gotTextEvent=false;function read(){return reader.read().then(function(result){if(result.done){hideTyping();if(!gotTextEvent){addBotMessage("I had trouble analyzing that photo. Could you describe what you see?")}endTurn(gotTextEvent,gotTextEvent?undefined:"no_reply");return}var chunk=decoder.decode(result.value,{stream:true});buffer+=chunk;var lines=buffer.split("\n");buffer=lines.pop()||"";lines.forEach(function(line){if(!line.startsWith("data: "))return;try{var data=JSON.parse(line.slice(6));if(data.type==="text"){gotTextEvent=true;hideTyping();addBotMessage(data.content)}else if(data.type==="quick_replies"){state.quickReplies=data.replies;addInlineChips(data.replies)}else if(data.type==="part_cards"){if(data.cards&&data.cards.length>0){addPartCards(data.cards,data.modelNumber);state.messages.push({role:"parts",cards:data.cards});data.cards.forEach(function(c){logQualityEvent("part_card_shown",{partId:c.partId,apNumber:c.apNumber});pushDataLayer("chat_card_shown",{part_id:c.apNumber,source:"max"})})}}else if(data.type==="status"){var statusLbl2=shadow.querySelector("#mx-typing-label");if(statusLbl2){statusLbl2.textContent=data.message;statusLbl2.classList.add("visible")}}else if(data.type==="action"&&data.action==="handoff"){if(data.force&&state.handoffCompleted&&!state.agentMode){debugLog("[MAX-HANDOFF] server forced handoff, clearing stale completed flag");state.handoffCompleted=false}if(state.handoffCompleted){debugLog("[MAX-HANDOFF] server sent handoff action but handoff already completed, skipping")}else{debugLog("[MAX-HANDOFF] server sent handoff action, calling handleHandoff()");handleHandoff()}}else if(data.type==="action"&&data.action==="collect_contact"){debugLog("[MAX-HANDOFF] server requested contact form");requestHandoffWithContact()}else if(data.type==="action"&&data.action==="offline_options"){debugLog("[MAX-HANDOFF] server says agents offline, rendering offline options");renderOfflineOptionButtons({support_phone:data.support_phone})}else if(data.type==="action"&&data.action==="offer_transcript"){debugLog("[MAX-CLOSURE] server requested transcript offer");if(state.alcConversationId){renderEmailTranscriptOffer()}}else if(data.type==="done"&&data.messageId){applyDoneModel(state,data);if(data.brand)state.brand=data.brand;
2if(data.applianceType)state.applianceType=data.applianceType;if(data.customerName)state.capturedName=data.customerName;saveSession();var msgContainer=shadow.querySelector("#mx-messages");if(msgContainer&&!msgContainer.querySelector('.mx-feedback[data-mid="'+data.messageId+'"]')){addFeedbackButtons(msgContainer,data.messageId)}}}catch(e){}});return read()})}read()}).catch(function(){hideTyping();addBotMessage("I had trouble analyzing that photo. Could you describe what you see?");endTurn()})}function updateShareButton(){var btn=shadow.querySelector("#mx-share-btn");if(!btn)return;var hasBotMsg=state.messages.some(function(m){return m.role==="bot"});if(hasBotMsg){btn.classList.add("visible")}else{btn.classList.remove("visible")}}function handleShare(){var btn=shadow.querySelector("#mx-share-btn");if(!btn||btn.disabled||!state.sessionToken||!state.conversationId)return;btn.disabled=true;fetch(API_BASE+"/api/chat/share",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId})}).then(function(r){return r.json()}).then(function(data){btn.disabled=false;if(!data.shareUrl){debugLog("Share failed: no URL returned");return}if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(data.shareUrl).then(function(){showShareToast()}).catch(function(){showShareFallback(data.shareUrl)})}else{showShareFallback(data.shareUrl)}}).catch(function(){btn.disabled=false;debugLog("Share request failed")})}function showShareToast(){var toast=shadow.querySelector("#mx-share-toast");if(!toast)return;toast.classList.add("show");setTimeout(function(){toast.classList.remove("show")},3e3)}function showShareFallback(url){var existing=shadow.querySelector("#mx-share-fallback");if(existing)existing.remove();var overlay=document.createElement("div");overlay.id="mx-share-fallback";overlay.style.cssText="position:absolute;inset:0;background:rgba(0,0,0,0.4);z-index:100;display:flex;align-items:center;justify-content:center";var box=document.createElement("div");box.style.cssText="background:#fff;border-radius:12px;padding:20px;max-width:280px;width:90%;text-align:center;font-family:inherit";var label=document.createElement("div");label.style.cssText="font-size:14px;font-weight:600;margin-bottom:10px;color:#1a1a1a";label.textContent="Share link";var inp=document.createElement("input");inp.type="text";inp.value=url;inp.readOnly=true;inp.style.cssText="width:100%;padding:8px 10px;border:1px solid #ddd;border-radius:6px;font-size:13px;margin-bottom:10px;box-sizing:border-box";inp.onclick=function(){this.select()};var closeBtn=document.createElement("button");closeBtn.textContent="Close";closeBtn.style.cssText="padding:6px 16px;border:none;border-radius:6px;background:#f0f0f0;cursor:pointer;font-size:13px";closeBtn.onclick=function(){overlay.remove()};box.appendChild(label);box.appendChild(inp);box.appendChild(closeBtn);overlay.appendChild(box);overlay.onclick=function(e){if(e.target===overlay)overlay.remove()};var panel=shadow.querySelector("#mx-panel");if(panel)panel.appendChild(overlay)}function renderOfflineOptions(info){state.handoffCompleted=true;var hoursLine=info&&info.hours_line;var msg=hoursLine?"Our team is currently offline. Business hours are "+hoursLine+". You can:":"Our team is currently offline. You can:";addBotMessage(msg);renderOfflineOptionButtons(info)}function renderOfflineOptionButtons(info){var phone=info&&info.support_phone||"1-877-477-7278";var container=shadow.querySelector("#mx-messages");if(!container)return;var existing=shadow.querySelector("#mx-offline-options");if(existing&&existing.parentNode)existing.parentNode.removeChild(existing);var wrap=document.createElement("div");wrap.id="mx-offline-options";wrap.style.cssText="display:flex;flex-direction:column;gap:8px;padding:0 16px 8px;";var leaveBtn=document.createElement("button");leaveBtn.type="button";leaveBtn.textContent="Leave a message";leaveBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:10px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";leaveBtn.onclick=function(){var existing=shadow.querySelector("#mx-offline-options");
2if(existing&&existing.parentNode)existing.parentNode.removeChild(existing);renderLeaveMessageForm()};var callBtn=document.createElement("button");callBtn.type="button";callBtn.textContent="Call us at "+phone;callBtn.style.cssText="background:#FFF;color:"+C.t1+";border:1px solid "+C.border+";border-radius:999px;padding:10px 14px;font-size:13px;font-weight:500;cursor:pointer;font-family:"+FONT+";";callBtn.onclick=function(){try{window.location.href="tel:"+phone.replace(/[^\d+]/g,"")}catch(e){}};wrap.appendChild(leaveBtn);wrap.appendChild(callBtn);container.appendChild(wrap);container.scrollTop=container.scrollHeight}function renderLeaveMessageForm(){var container=shadow.querySelector("#mx-messages");if(!container)return;if(shadow.querySelector("#mx-offline-form"))return;var wrap=document.createElement("div");wrap.id="mx-offline-form";wrap.style.cssText="margin:8px 12px 12px;padding:14px;border:1px solid "+C.border+";border-radius:12px;background:"+C.bgWarm+";font-family:"+FONT+";display:flex;flex-direction:column;gap:8px;";var title=document.createElement("div");title.style.cssText="font-size:13px;font-weight:600;color:"+C.t1+";";title.textContent="We'll get back to you when we're back online.";wrap.appendChild(title);function makeInput(placeholder,type){var i=document.createElement("input");i.type=type||"text";i.placeholder=placeholder;i.style.cssText="border:1px solid "+C.border+";border-radius:8px;padding:8px 10px;font-size:13px;font-family:"+FONT+";background:#FFF;color:"+C.t1+";";return i}var nameInput=makeInput("Your name");nameInput.value=state.collectedName||"";wrap.appendChild(nameInput);var emailInput=makeInput("Email address","email");emailInput.value=state.collectedEmail||extractEmailFromMessages()||"";wrap.appendChild(emailInput);var ta=document.createElement("textarea");ta.placeholder="How can we help?";ta.maxLength=2e3;ta.style.cssText="border:1px solid "+C.border+";border-radius:8px;padding:8px 10px;font-size:13px;font-family:"+FONT+";background:#FFF;color:"+C.t1+";min-height:80px;resize:vertical;";wrap.appendChild(ta);var errEl=document.createElement("div");errEl.style.cssText="font-size:12px;color:"+C.red+";display:none;";wrap.appendChild(errEl);var submitBtn=document.createElement("button");submitBtn.type="button";submitBtn.textContent="Send message";submitBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:9px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";submitBtn.onclick=function(){var name=nameInput.value.trim();var email=emailInput.value.trim();var message=ta.value.trim();if(!name||!email||!message){errEl.textContent="Name, email, and a short message are required.";errEl.style.display="block";return}submitBtn.disabled=true;submitBtn.style.opacity="0.5";submitBtn.textContent="Sending...";errEl.style.display="none";fetch(API_BASE+"/api/chat/offline-message",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,name:name,email:email,message:message})}).then(function(r){return r.ok?r.json():Promise.reject(r.status)}).then(function(){state.collectedName=name;state.collectedEmail=email;if(wrap.parentNode)wrap.parentNode.removeChild(wrap);addAgentSystemMessage("Got it! We'll get back to you when we're back online.")}).catch(function(){submitBtn.disabled=false;submitBtn.style.opacity="1";submitBtn.textContent="Send message";errEl.textContent="Could not send. Please try again or call us.";errEl.style.display="block"})};wrap.appendChild(submitBtn);container.appendChild(wrap);container.scrollTop=container.scrollHeight;setTimeout(function(){nameInput.focus()},50)}function extractEmailFromMessages(){var re=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/i;for(var i=state.messages.length-1;i>=0;i--){var m=state.messages[i];if(m&&m.role==="customer"&&typeof m.content==="string"){var match=m.content.match(re);if(match)return match[0]}}return null}function renderEmailTranscriptOffer(){if(state.transcriptOffered)return;state.transcriptOffered=true;
2if(!state.alcConversationId){renderStartNewConversation();return}var container=shadow.querySelector("#mx-messages");if(!container)return;addAgentSystemMessage("Would you like a copy of this conversation emailed to you?");var wrap=document.createElement("div");wrap.id="mx-transcript-offer";wrap.style.cssText="display:flex;gap:8px;justify-content:center;padding:0 16px 12px;flex-wrap:wrap;";var yesBtn=document.createElement("button");yesBtn.type="button";yesBtn.textContent="Yes, email it";yesBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";yesBtn.onclick=function(){if(wrap.parentNode)wrap.parentNode.removeChild(wrap);renderEmailTranscriptForm(state.alcConversationId)};var noBtn=document.createElement("button");noBtn.type="button";noBtn.textContent="No thanks";noBtn.style.cssText="background:#FFF;color:"+C.t1+";border:1px solid "+C.border+";border-radius:999px;padding:8px 14px;font-size:13px;font-weight:500;cursor:pointer;font-family:"+FONT+";";noBtn.onclick=function(){if(wrap.parentNode)wrap.parentNode.removeChild(wrap);renderStartNewConversation()};wrap.appendChild(yesBtn);wrap.appendChild(noBtn);container.appendChild(wrap);container.scrollTop=container.scrollHeight}function renderEmailTranscriptForm(){var container=shadow.querySelector("#mx-messages");if(!container)return;var wrap=document.createElement("div");wrap.id="mx-transcript-form";wrap.style.cssText="margin:8px 12px 12px;padding:14px;border:1px solid "+C.border+";border-radius:12px;background:"+C.bgWarm+";font-family:"+FONT+";display:flex;flex-direction:column;gap:8px;";var label=document.createElement("div");label.style.cssText="font-size:13px;font-weight:600;color:"+C.t1+";";label.textContent="Where should we send it?";wrap.appendChild(label);var emailInput=document.createElement("input");emailInput.type="email";emailInput.placeholder="[email protected]";emailInput.value=state.collectedEmail||extractEmailFromMessages()||"";emailInput.style.cssText="border:1px solid "+C.border+";border-radius:8px;padding:8px 10px;font-size:13px;font-family:"+FONT+";background:#FFF;color:"+C.t1+";";wrap.appendChild(emailInput);var errEl=document.createElement("div");errEl.style.cssText="font-size:12px;color:"+C.red+";display:none;";wrap.appendChild(errEl);var btnRow=document.createElement("div");btnRow.style.cssText="display:flex;gap:8px;";var sendBtn=document.createElement("button");sendBtn.type="button";sendBtn.textContent="Send";sendBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:8px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";var cancelBtn=document.createElement("button");cancelBtn.type="button";cancelBtn.textContent="Skip";cancelBtn.style.cssText="background:#FFF;color:"+C.t1+";border:1px solid "+C.border+";border-radius:999px;padding:8px 14px;font-size:13px;font-weight:500;cursor:pointer;font-family:"+FONT+";";btnRow.appendChild(sendBtn);btnRow.appendChild(cancelBtn);wrap.appendChild(btnRow);cancelBtn.onclick=function(){if(wrap.parentNode)wrap.parentNode.removeChild(wrap);renderStartNewConversation()};sendBtn.onclick=function(){var email=emailInput.value.trim();var re=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;if(!re.test(email)){errEl.textContent="Please enter a valid email address.";errEl.style.display="block";return}sendBtn.disabled=true;sendBtn.style.opacity="0.5";sendBtn.textContent="Sending...";errEl.style.display="none";fetch(API_BASE+"/api/chat/email-transcript",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,email:email})}).then(function(r){return r.ok?r.json():Promise.reject(r.status)}).then(function(){state.collectedEmail=email;if(wrap.parentNode)wrap.parentNode.removeChild(wrap);addAgentSystemMessage("Transcript sent to "+email+"!");renderStartNewConversation()}).catch(function(){sendBtn.disabled=false;sendBtn.style.opacity="1";sendBtn.textContent="Send";errEl.textContent="Could not send right now. Try again or skip.";errEl.style.display="block"})};container.appendChild(wrap);container.scrollTop=container.scrollHeight;setTimeout(function(){emailInput.focus()},50)}function formatMoney(n){if(typeof n!=="number"||!isFinite(n))return"";return"$"+n.toFixed(2)}function isOnAppDomain(){try{return/(^|\.)appliancepartspros\.com$/i.test(window.location.hostname)}catch(e){return false}}function renderCheckoutCard(items,total,sentBy,skipPersist){if(!shadow)return;if(!Array.isArray(items)||items.length===0)return;var container=shadow.querySelector("#mx-messages");if(!container)return;clearWelcome();var card=document.createElement("div");card.className="mx-checkout-card";var title=document.createElement("div");title.className="mx-checkout-title";
2title.textContent=sentBy?sentBy+" prepared your order":"Your order is ready";card.appendChild(title);var subtitle=document.createElement("div");subtitle.className="mx-checkout-subtitle";subtitle.textContent=items.length+" item"+(items.length===1?"":"s");card.appendChild(subtitle);var list=document.createElement("div");list.className="mx-checkout-items";var computedTotal=0;items.forEach(function(it){var row=document.createElement("div");row.className="mx-checkout-row";var nameWrap=document.createElement("div");nameWrap.className="mx-co-name";var nameText=document.createElement("span");nameText.textContent=it.name||"Part";nameWrap.appendChild(nameText);if(it.ap_number){var ap=document.createElement("span");ap.className="mx-co-ap";ap.textContent=it.ap_number;nameWrap.appendChild(ap)}var qty=it.qty&&it.qty>0?it.qty:1;var qtyEl=document.createElement("span");qtyEl.className="mx-co-qty";qtyEl.textContent="x"+qty;var priceEl=document.createElement("span");priceEl.className="mx-co-price";if(typeof it.price==="number"){computedTotal+=it.price*qty;priceEl.textContent=formatMoney(it.price*qty)}else{priceEl.textContent=""}row.appendChild(nameWrap);row.appendChild(qtyEl);row.appendChild(priceEl);list.appendChild(row)});card.appendChild(list);var divider=document.createElement("div");divider.className="mx-checkout-divider";card.appendChild(divider);var totalRow=document.createElement("div");totalRow.className="mx-checkout-total";var totalLabel=document.createElement("span");totalLabel.textContent="Total";var totalAmount=document.createElement("span");var totalValue=typeof total==="number"?total:computedTotal;totalAmount.textContent=formatMoney(totalValue);totalRow.appendChild(totalLabel);totalRow.appendChild(totalAmount);card.appendChild(totalRow);var btn=document.createElement("button");btn.type="button";btn.className="mx-checkout-btn";btn.textContent="Proceed to checkout";card.appendChild(btn);var foot=document.createElement("div");foot.className="mx-checkout-foot";foot.textContent="You'll complete payment on AppliancePartsPros.com";card.appendChild(foot);var err=document.createElement("div");err.className="mx-checkout-err";card.appendChild(err);function showError(msg,retryItems){err.textContent=msg;err.classList.add("visible");if(retryItems&&retryItems.length>0){retryItems.forEach(function(it){if(!it||!it.ap_number)return;var a=document.createElement("a");a.href="https://www.appliancepartspros.com/search.aspx?q="+encodeURIComponent(it.ap_number);a.target="_blank";a.rel="noopener";a.textContent="Open "+(it.name||it.ap_number);err.appendChild(a)})}}btn.onclick=function(){if(btn.disabled)return;if(!isOnAppDomain()){showError("Checkout is only available on appliancepartspros.com.");return}if(typeof window.addtocart!=="function"){showError("Could not add items to cart. Please try adding them manually.",items);return}btn.disabled=true;btn.textContent="Adding to cart...";err.classList.remove("visible");err.textContent="";var failed=[];var sequence=Promise.resolve();items.forEach(function(it){sequence=sequence.then(function(){var partId=it.part_id;var qty=it.qty&&it.qty>0?it.qty:1;try{var r=window.addtocart(partId,qty);if(r&&typeof r.then==="function"){return r.then(function(v){if(v!==undefined&&String(v).trim()!=="0")failed.push(it)}).catch(function(){failed.push(it)})}return null}catch(e){failed.push(it);return null}})});sequence.then(function(){if(failed.length===items.length){btn.textContent="Proceed to checkout";btn.disabled=false;showError("Could not add items to cart. Please try adding them manually.",failed);return}if(failed.length>0){showError("Some items could not be added to your cart. Please add them manually.",failed)}try{window.open("/checkout.aspx","_blank","noopener")}catch(e){}btn.textContent="Checkout opened in new tab";addAgentSystemMessage("Checkout opened - complete your order in the new tab.");logQualityEvent("checkout_opened",{itemCount:items.length,total:typeof total==="number"?total:computedTotal,failedCount:failed.length});setTimeout(function(){btn.disabled=false;btn.textContent="Open checkout again"},1e4)})};container.appendChild(card);container.scrollTop=container.scrollHeight;if(!skipPersist){state.messages.push({role:"checkout",items:items,total:total,sentBy:sentBy})}}function setTalkButtonLoading(loading){if(!shadow)return;var btn=shadow.querySelector(".mx-header-talk");if(!btn)return;if(loading){if(!btn.dataset.origText)btn.dataset.origText=btn.textContent;
2btn.disabled=true;btn.textContent="Connecting...";btn.style.opacity="0.6";btn.style.cursor="default";btn.style.pointerEvents="none"}else{btn.disabled=false;if(btn.dataset.origText)btn.textContent=btn.dataset.origText;btn.style.opacity="";btn.style.cursor="";btn.style.pointerEvents=""}}function requestHandoffWithContact(){if(state.handoffInFlight||state.handoffCompleted){debugLog("[MAX-HANDOFF] requestHandoffWithContact: already in flight or completed");return}if(state.handoffContactPromptOpen){debugLog("[MAX-HANDOFF] contact prompt already open");return}if(!state.sessionToken){debugLog("[MAX-HANDOFF] requestHandoffWithContact: no sessionToken");return}clearWelcome();state.hasConversation=true;state.handoffContactPromptOpen=true;setTalkButtonLoading(true);renderHandoffContactForm()}function renderHandoffContactForm(){var container=shadow.querySelector("#mx-messages");if(!container)return;var existing=shadow.querySelector("#mx-handoff-contact-form");if(existing&&existing.parentNode)existing.parentNode.removeChild(existing);var wrap=document.createElement("div");wrap.id="mx-handoff-contact-form";wrap.style.cssText="margin:8px 12px 12px;padding:14px;border:1px solid "+C.border+";border-radius:12px;background:"+C.bgWarm+";font-family:"+FONT+";display:flex;flex-direction:column;gap:8px;";var knownName=(state.capturedName||state.collectedName||"").trim();var title=document.createElement("div");title.style.cssText="font-size:14px;font-weight:600;color:"+C.t1+";";title.textContent=knownName?"Before I connect you, what's the best email to reach you?":"Before I connect you, could I get your name and email?";wrap.appendChild(title);var sub=document.createElement("div");sub.style.cssText="font-size:12px;color:"+C.t2+";margin-top:-2px;";sub.textContent="We'll send you a copy of the conversation when we're done.";wrap.appendChild(sub);function makeInput(placeholder,type){var i=document.createElement("input");i.type=type||"text";i.placeholder=placeholder;i.style.cssText="border:1px solid "+C.border+";border-radius:8px;padding:9px 10px;font-size:14px;font-family:"+FONT+";background:#FFF;color:"+C.t1+";";return i}var nameInput=makeInput("Your name");nameInput.autocomplete="name";nameInput.value=state.collectedName||"";if(!knownName)wrap.appendChild(nameInput);var emailInput=makeInput("Email address","email");emailInput.autocomplete="email";emailInput.value=state.collectedEmail||extractEmailFromMessages()||"";wrap.appendChild(emailInput);var errEl=document.createElement("div");errEl.style.cssText="font-size:12px;color:"+C.red+";display:none;";wrap.appendChild(errEl);var btnRow=document.createElement("div");btnRow.style.cssText="display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap;";var skipBtn=document.createElement("button");skipBtn.type="button";skipBtn.textContent="Cancel";skipBtn.style.cssText="background:#FFF;color:"+C.t1+";border:1px solid "+C.border+";border-radius:999px;padding:9px 14px;font-size:13px;font-weight:500;cursor:pointer;font-family:"+FONT+";";var submitBtn=document.createElement("button");submitBtn.type="button";submitBtn.textContent="Connect me";submitBtn.style.cssText="background:"+C.navy+";color:#FFF;border:none;border-radius:999px;padding:9px 14px;font-size:13px;font-weight:600;cursor:pointer;font-family:"+FONT+";";btnRow.appendChild(skipBtn);btnRow.appendChild(submitBtn);wrap.appendChild(btnRow);function closeForm(){if(wrap.parentNode)wrap.parentNode.removeChild(wrap);state.handoffContactPromptOpen=false}skipBtn.onclick=function(){closeForm();setTalkButtonLoading(false)};submitBtn.onclick=function(){var name=knownName||nameInput.value.trim();var email=emailInput.value.trim();if(!name){errEl.textContent="Please enter your name.";errEl.style.display="block";nameInput.focus();return}var emailRe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;if(!email||!emailRe.test(email)){errEl.textContent="Please enter a valid email address.";errEl.style.display="block";emailInput.focus();return}state.collectedName=name;state.collectedEmail=email;submitBtn.disabled=true;submitBtn.style.opacity="0.6";submitBtn.textContent="Connecting...";skipBtn.disabled=true;skipBtn.style.opacity="0.6";errEl.style.display="none";closeForm();handleHandoff()};container.appendChild(wrap);container.scrollTop=container.scrollHeight;setTimeout(function(){(knownName?emailInput:nameInput).focus()},50)}function handleHandoff(){debugLog("[MAX-HANDOFF] handleHandoff() entered, sessionToken="+!!state.sessionToken+", conversationId="+state.conversationId+", inFlight="+!!state.handoffInFlight+", completed="+!!state.handoffCompleted);if(!state.sessionToken){debugLog("[MAX-HANDOFF] ABORT: no sessionToken");return}if(state.handoffInFlight){debugLog("[MAX-HANDOFF] ABORT: handoff already in flight");return}if(state.handoffCompleted){debugLog("[MAX-HANDOFF] ABORT: handoff already completed");return}state.handoffInFlight=true;logQualityEvent("talk_to_person",{messageCount:state.customerMsgCount,hadPartCard:state.hadPartCard});pushDataLayer("chat_handoff_requested",{source:"agent"});setTalkButtonLoading(true);fetch(API_BASE+"/api/chat/check-hours",{method:"GET",credentials:"include"}).then(function(r){return r.ok?r.json():null}).then(function(data){if(data&&data.available===false){state.handoffInFlight=false;setTalkButtonLoading(false);renderOfflineOptions(data);return}proceedHandoff(data?data.available:null,data)}).catch(function(){proceedHandoff(null,null)})}function proceedHandoff(available,hoursInfo){var type=available===false?"email_followup":"live_agent";debugLog("[MAX-HANDOFF] handoff type="+type+", available="+available);if(type==="email_followup"){debugLog("[MAX-HANDOFF] calling /api/chat/handoff (email_followup)");fetch(API_BASE+"/api/chat/handoff",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,type:type,agentOnline:false,name:state.collectedName||undefined,email:state.collectedEmail||undefined})}).then(function(r){debugLog("[MAX-HANDOFF] email_followup response status="+r.status);return r.json()}).then(function(data){debugLog("[MAX-HANDOFF] email_followup data="+JSON.stringify(data));state.handoffCompleted=true;state.handoffInFlight=false;setTalkButtonLoading(false);var phone=data&&data.supportPhone||hoursInfo&&hoursInfo.support_phone||"1-877-477-7278";var offlineMsg=data&&data.message||hoursInfo&&hoursInfo.message||"Our team is offline right now. You can leave a message and we'll get back to you, or call us at "+phone+".";addBotMessage(offlineMsg);if(window.Tawk_API){try{debugLog("[MAX-HANDOFF] calling Tawk_API.showWidget() + maximize() (offline path)");window.Tawk_API.showWidget();window.Tawk_API.maximize()}catch(e){debugLog("[MAX-HANDOFF] tawk offline show/maximize error: "+e.message)}}else{debugLog("[MAX-HANDOFF] Tawk_API not available on offline path")}}).catch(function(err){debugLog("[MAX-HANDOFF] email_followup fetch error: "+(err&&err.message));state.handoffInFlight=false;setTalkButtonLoading(false);var fallbackPhone=hoursInfo&&hoursInfo.support_phone||"1-877-477-7278";var fallbackLead=hoursInfo&&hoursInfo.message||"Our team is offline right now.";addBotMessage(fallbackLead+" You can call us at "+fallbackPhone+".");if(window.Tawk_API){try{window.Tawk_API.showWidget();window.Tawk_API.maximize()}catch(e){}}})}else{debugLog("[MAX-HANDOFF] calling /api/chat/handoff (live_agent)");fetch(API_BASE+"/api/chat/handoff",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionToken:state.sessionToken,conversationId:state.conversationId,type:type,agentOnline:true,name:state.collectedName||undefined,email:state.collectedEmail||undefined,visitorId:getVisitorId()||undefined,pageHistory:getPageHistory()})}).then(function(r){debugLog("[MAX-HANDOFF] live_agent response status="+r.status);return r.json()}).then(function(data){debugLog("[MAX-HANDOFF] live_agent data: success="+(data&&data.success)+", summary="+!!(data&&data.summary)+", shareUrl="+!!(data&&data.shareUrl)+", alc="+!!(data&&data.alc));if(!data||!data.success){debugLog("[MAX-HANDOFF] live_agent response not successful, aborting");state.handoffInFlight=false;setTalkButtonLoading(false);
2if(data&&data.forumNoLiveAgent)state.handoffCompleted=true;if(data&&data.departmentUnavailable){addBotMessage(data.message||"That team is not available for live chat right now. I can keep helping you here, or you can leave a message.");addInlineChips(["Keep chatting with Max","Leave a message"]);return}addBotMessage(data&&data.message||"Sorry, something went wrong connecting you. Please try again.");return}if(data.alc&&data.alc.stream_url){debugLog("[MAX-HANDOFF] entering ALC agent mode, stream="+data.alc.stream_url);state.handoffInFlight=false;setTalkButtonLoading(false);enterAgentMode({streamUrl:data.alc.stream_url,alcConversationId:data.alc.conversation_id||null,estimatedWaitSeconds:typeof data.alc.estimated_wait_seconds==="number"?data.alc.estimated_wait_seconds:null,queuePosition:typeof data.alc.queue_position==="number"?data.alc.queue_position:null});return}var ctx=state.pageContext||{};if(window.Tawk_API){try{debugLog("[MAX-HANDOFF] setting tawk attributes and calling showWidget() + maximize()");window.Tawk_API.setAttributes({summary:(data.summary||"").slice(0,255),transcript:(data.shareUrl||"").slice(0,255),page:(ctx.url||window.location.href).slice(0,255),part:(ctx.partId||"N/A").slice(0,255),model:(state.modelNumber||ctx.modelNumber||"N/A").slice(0,255),messages:String(state.customerMsgCount||0)},function(){});window.Tawk_API.addTags(["bot-handoff",ctx.pageType||"unknown"],function(){});window.Tawk_API.showWidget();window.Tawk_API.maximize();debugLog("[MAX-HANDOFF] tawk showWidget() + maximize() called successfully")}catch(e){debugLog("[MAX-HANDOFF] tawk handoff error: "+e.message)}}else{debugLog("[MAX-HANDOFF] Tawk_API not available on live_agent path")}state.handoffCompleted=true;state.handoffInFlight=false;setTalkButtonLoading(false);addBotMessage("I've connected you with our team. They can see our conversation and will be right with you.");if(isMobile()){minimizeToBar()}else{if(panel){panel.classList.add("closing");setTimeout(function(){if(panel&&panel.parentNode)panel.parentNode.removeChild(panel);panel=null;document.body.style.marginRight=""},300)}state.isOpen=false;launcher.style.display="flex";scheduleOverlapDodge()}}).catch(function(){state.handoffInFlight=false;setTalkButtonLoading(false);addBotMessage("Sorry, something went wrong connecting you. Please try again.")})}}function fetchPdpPartName(ctx){if(state.pdpPartNameFetched)return;var eligibleTypes=["part","qa","story"];if(eligibleTypes.indexOf(ctx.pageType)===-1||!ctx.partId||!state.sessionToken)return;state.pdpPartNameFetched=true;var partIdNum=ctx.partId.replace(/^AP/i,"");fetch(API_BASE+"/api/chat/part-name?id="+encodeURIComponent(partIdNum)+"&sessionToken="+encodeURIComponent(state.sessionToken),{credentials:"include"}).then(function(r){return r.ok?r.json():null}).then(function(data){if(data&&data.name){ctx.partName=data.name;var welcomeEl=shadow?shadow.querySelector(".mx-welcome-greeting"):null;if(welcomeEl){var greetings={part:"Got a question about this "+data.name+"?",qa:"Have a question about this "+data.name+"?",story:"Working on a repair with this "+data.name+"?"};welcomeEl.textContent=greetings[ctx.pageType]||welcomeEl.textContent}}}).catch(function(){})}var CONFIRM_URL_PATTERN=/\/checkout-confirm\.aspx/i;function checkPurchaseCompletion(){try{var raw=localStorage.getItem("max_conversion");if(!raw)return;var data=JSON.parse(raw);if(Date.now()-data.timestamp>24*60*60*1e3){localStorage.removeItem("max_conversion");return}var path=window.location.pathname+window.location.search;if(CONFIRM_URL_PATTERN.test(path)&&data.conversationId&&data.sessionToken){state.sessionToken=data.sessionToken;state.conversationId=data.conversationId;logQualityEvent("purchase_completed",{partId:data.partId,apNumber:data.apNumber,price:data.price,msSinceAddToCart:Date.now()-data.timestamp});localStorage.removeItem("max_conversion")}}catch(e){}}function hideTawkBubble(){if(window.Tawk_API&&window.Tawk_API.hideWidget){try{window.Tawk_API.hideWidget()}catch(e){}}if(!window.Tawk_API)window.Tawk_API={};var existingOnLoad=window.Tawk_API.onLoad;window.Tawk_API.onLoad=function(){if(typeof existingOnLoad==="function"){try{existingOnLoad()}catch(e){}}try{window.Tawk_API.hideWidget()}catch(e){}};var existingOnChatEnded=window.Tawk_API.onChatEnded;window.Tawk_API.onChatEnded=function(){if(typeof existingOnChatEnded==="function"){try{existingOnChatEnded()}catch(e){}}try{window.Tawk_API.hideWidget()}catch(e){}}}
2function init(){hideTawkBubble();state.pageContext=detectPageContext();try{state._originalTitle=document.title}catch(e){}getVisitorId();recordPageVisit();checkPurchaseCompletion();if(state.pageContext.pageType==="checkout"){installMaxchatApi(false);return}buildUI();window.addEventListener("resize",function(){var cam=shadow.querySelector("#mx-camera-btn");if(cam){if(isMobile())cam.classList.add("mobile-show");else cam.classList.remove("mobile-show")}});try{proactiveStart()}catch(e){debugLog("proactiveStart error: "+e)}try{installSiteSearchCapture(document)}catch(e){debugLog("[SEARCH] install error: "+e)}var sameSiteNavAt=0;var SAME_SITE_NAV_WINDOW_MS=5e3;function markSameSiteNav(href){try{var dest=new URL(href,window.location.href);if(dest.origin===window.location.origin)sameSiteNavAt=Date.now()}catch(e){}}document.addEventListener("click",function(e){try{var node=e.target;var a=node&&node.closest?node.closest("a[href]"):null;if(!a)return;var tgt=a.getAttribute("target");if(tgt&&tgt!=="_self")return;markSameSiteNav(a.href)}catch(err){}},true);document.addEventListener("submit",function(e){try{var form=e.target;markSameSiteNav(form&&form.getAttribute("action")?form.action:window.location.href)}catch(err){}},true);window.addEventListener("pagehide",function(){if(!state.hasConversation)return;if(state.agentMode&&Date.now()-sameSiteNavAt<SAME_SITE_NAV_WINDOW_MS)return;sendDisconnectBeacon()});window.addEventListener("focus",maybeSendReadReceipt);document.addEventListener("visibilitychange",maybeSendReadReceipt);window.addEventListener("focus",clearTabNotificationIfVisible);document.addEventListener("visibilitychange",clearTabNotificationIfVisible);debugLog("init: isMobile()="+isMobile()+", viewport="+window.innerWidth+"x"+window.innerHeight+", pageType="+state.pageContext.pageType);var isCart=state.pageContext.pageType==="cart";var restored=false;var resolvedFlag=false;try{resolvedFlag=!!localStorage.getItem(RESOLVED_FLAG_KEY)}catch(e){}if(resolvedFlag&&!isCart){try{localStorage.removeItem(RESOLVED_FLAG_KEY)}catch(e){}try{localStorage.removeItem("max_session")}catch(e){}try{sessionStorage.removeItem(AGENT_MODE_STORAGE_KEY)}catch(e){}try{localStorage.removeItem(AGENT_MODE_STORAGE_KEY)}catch(e){}debugLog("init: resolved flag found, clearing session and starting fresh");initSession();installMaxchatApi(true);return}try{var savedAgent=JSON.parse(sessionStorage.getItem(AGENT_MODE_STORAGE_KEY)||localStorage.getItem(AGENT_MODE_STORAGE_KEY)||"null");if(savedAgent&&savedAgent.conversationId&&savedAgent.sessionToken&&Date.now()-(savedAgent.enteredAt||0)<AGENT_MODE_MAX_AGE_MS){state.sessionToken=savedAgent.sessionToken;state.conversationId=savedAgent.conversationId;state.agentName=savedAgent.agentName||null;state.agentStreamLastSeen=savedAgent.lastSeen||null;state._agentRestorePending=savedAgent;state._restoredFromStorage=false;restored=true;debugLog("init: deferring agent-mode restore until widget opens")}else if(savedAgent){clearAgentModeStorage()}}catch(e){clearAgentModeStorage()}if(!restored&&!isCart){try{var saved=JSON.parse(localStorage.getItem("max_session"));if(saved&&saved.sessionToken&&saved.conversationId){if(Date.now()-saved.lastActive<24*60*60*1e3){state.sessionToken=saved.sessionToken;state.conversationId=saved.conversationId;state.modelNumber=saved.model||null;state.brand=saved.brand||null;state.applianceType=saved.applianceType||null;if(saved.pageContext&&saved.pageContext.pageType===state.pageContext.pageType){if(saved.pageContext.partName&&!state.pageContext.partName){state.pageContext.partName=saved.pageContext.partName}if(saved.pageContext.partId&&!state.pageContext.partId){state.pageContext.partId=saved.pageContext.partId}}state._restoredFromStorage=true;restored=true;debugLog("init: restored session from localStorage")}else{localStorage.removeItem("max_session")}}}catch(e){}}if(restored){ensureNavTracking()}else if(!isCart){initSession()}installMaxchatApi(true)}if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",init)}else{init()}})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.