@gengage/assistant-fe 0.4.1 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,7 +46,7 @@
46
46
  }
47
47
  `,document.head.appendChild(e)}var ct=null;function Io(){if(ct!==null)return ct;try{ct=localStorage.getItem("gengage:debug")==="1"}catch{ct=!1}return ct}function Ne(e,t,a){if(!Io())return;const n=[`[gengage:${e}]`,t];a!==void 0&&n.push(a),console.debug(...n)}var kt=class{constructor(){this.isVisible=!1,this.isInitialised=!1,this._handlers=new Map,this._cleanups=[],this._ownsRoot=!1,this._destroying=!1}async init(e){if(this.isInitialised){console.warn("[gengage] Widget already initialised. Call update() instead.");return}const t=yo(e.theme);this.config={...e,theme:t,session:tn(e.session)},this.root=this._resolveMount(e.mountTarget),this._applyTheme(t),So();const a=wt("gengage:context:update",n=>this.update(n));this._cleanups.push(a),Ne("lifecycle",`${this.constructor.name}.init`,{accountId:e.accountId,sku:e.pageContext?.sku});try{await this.onInit(this.config)}catch(n){throw this.destroy(),n}this._destroying||(this.isInitialised=!0,Ne("lifecycle",`${this.constructor.name} ready`),this.emit("ready"))}update(e){this.isInitialised&&(this.config.pageContext?this.config={...this.config,pageContext:{...this.config.pageContext,...e}}:e.pageType!==void 0&&(this.config={...this.config,pageContext:e}),this.onUpdate(e),this.emit("context-update",this.config.pageContext))}show(){this.isVisible||(this.isVisible=!0,this.root.style.display="",this.onShow(),this.emit("show"))}hide(){this.isVisible&&(this.isVisible=!1,this.root.style.display="none",this.onHide(),this.emit("hide"))}destroy(){this._destroying||(this._destroying=!0,this.emit("destroy"),this._cleanups.forEach(e=>e()),this._cleanups.length=0,this._handlers.clear(),this.onDestroy(),this.config.analyticsClient?.destroy(),this._cleanupRoot(),this.isInitialised=!1)}_cleanupRoot(){this._ownsRoot?this.root.remove():this.root.innerHTML=""}on(e,t){return this._handlers.has(e)||this._handlers.set(e,new Set),this._handlers.get(e).add(t),()=>this._handlers.get(e)?.delete(t)}trackCheckout(e,t){const a=e==="start"?Gi:Wi;this.track(a(this.analyticsContext(),t))}flushMeteringSummary(e){this.track(Zi(this.analyticsContext(),e))}emit(e,...t){this._handlers.get(e)?.forEach(a=>a(...t))}addCleanup(e){this._cleanups.push(e)}track(e){this.config.analyticsClient?.track(e)}analyticsContext(){const e={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??""};return this.config.session?.viewId!==void 0&&(e.view_id=this.config.session.viewId),this.config.session?.userId!==void 0&&(e.user_id=this.config.session.userId),this.config.pageContext?.pageType!==void 0&&(e.page_type=this.config.pageContext.pageType),this.config.pageContext?.sku!==void 0&&(e.sku=this.config.pageContext.sku),this.config.session?.abTestVariant!==void 0&&(e.ab_test_variant=this.config.session.abTestVariant),this.config.session?.abTestExperimentId!==void 0&&(e.ab_test_experiment_id=this.config.session.abTestExperimentId),e}_resolveMount(e){if(e instanceof HTMLElement)return e;if(typeof e=="string"){const a=document.querySelector(e);if(!a)throw new Error(`[gengage] Mount target not found: "${e}"`);return a}const t=document.createElement("div");return t.dataset.gengageWidget=this.constructor.name.toLowerCase(),document.body.insertBefore(t,document.body.firstChild),this._ownsRoot=!0,t}_applyTheme(e){if(e){for(const[t,a]of Object.entries(e))if(a!==void 0){const n=t.startsWith("--")?t:`--gengage-${No(t)}`;this.root.style.setProperty(n,a)}}}};function No(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function ln(){const e=Date.now(),t=new Uint8Array(16);crypto.getRandomValues(t),t[0]=e/2**40&255,t[1]=e/2**32&255,t[2]=e/2**24&255,t[3]=e/2**16&255,t[4]=e/2**8&255,t[5]=e&255,t[6]=t[6]&15|112,t[8]=t[8]&63|128;const a=Array.from(t,n=>n.toString(16).padStart(2,"0")).join("");return`${a.slice(0,8)}-${a.slice(8,12)}-${a.slice(12,16)}-${a.slice(16,20)}-${a.slice(20)}`}var zo=class{constructor(e){this._handlers=new Map,this._destroyed=!1,this._namespace=e.namespace,this._allowedOrigins=e.allowedOrigins??[location.origin],this._onMessage=e.onMessage,this._allowedOrigins.includes("*")&&Bo()&&console.warn("[gengage] postMessage bridge using wildcard origin. Set allowedOrigins for production security."),this._messageListener=t=>this._handlePostMessage(t),window.addEventListener("message",this._messageListener)}send(e,t){if(this._destroyed)return;const a={namespace:this._namespace,type:e};t!==void 0&&(a.payload=t),window.dispatchEvent(new CustomEvent("gengage:bridge:message",{detail:a,bubbles:!1}))}on(e,t){this._handlers.has(e)||this._handlers.set(e,new Set);const a=this._handlers.get(e);return a.add(t),()=>{a.delete(t),a.size===0&&this._handlers.delete(e)}}destroy(){this._destroyed||(this._destroyed=!0,window.removeEventListener("message",this._messageListener),this._handlers.clear())}_handlePostMessage(e){if(this._destroyed||!this._isOriginAllowed(e.origin))return;const t=e.data;if(!Mo(t)||t.gengage!==this._namespace)return;const a={type:t.type};t.payload!==void 0&&(a.payload=t.payload),this._onMessage?.(a);const n=this._handlers.get(a.type);if(n)for(const r of n)r(a.payload)}_isOriginAllowed(e){return this._allowedOrigins.includes("*")?!0:this._allowedOrigins.includes(e)}};function Mo(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.gengage=="string"&&typeof t.type=="string"}function Bo(){try{return typeof process<"u"&&process.env.NODE_ENV!=="production"}catch{return!1}}function dn(e,t){if(typeof window>"u"||!fe(e))return!1;const a=new CustomEvent("gengage:navigate",{detail:t===void 0?{url:e}:{url:e,newTab:t},cancelable:!0});return window.dispatchEvent(a)?(t?window.open(e,"_blank","noopener,noreferrer"):window.location.href=e,!0):!1}var Ro=console;function Oo(e,t,a={}){const n=e.action,r=a.logger??Ro;switch(Ne("action",`routing action: ${n.kind}`,n),n.kind){case"open_chat":t.openChat?.(n.payload);return;case"navigate":{if(typeof n.url!="string"){Qe(n,t,a,r);return}if(!fe(n.url)){r.warn("[gengage] Blocked navigation to unsafe URL:",n.url);return}const i=typeof n.newTab=="boolean"?n.newTab:void 0;if(t.navigate){t.navigate({url:n.url,...i!==void 0&&{newTab:i}});return}(a.defaultNavigate??Do)(n.url,i);return}case"save_session":if(typeof n.sessionId!="string"||typeof n.sku!="string"){Qe(n,t,a,r);return}t.saveSession?.({sessionId:n.sessionId,sku:n.sku});return;case"add_to_cart":if(typeof n.sku!="string"||typeof n.quantity!="number"||typeof n.cartCode!="string"){Qe(n,t,a,r);return}t.addToCart?.({sku:n.sku,quantity:n.quantity,cartCode:n.cartCode});return;case"script_call":{if(a.allowScriptCall===!1){Qe(n,t,a,r);return}if(typeof n.name!="string"){Qe(n,t,a,r);return}const i=Fo(n.payload)?n.payload:void 0;t.scriptCall?.({name:n.name,...i!==void 0&&{payload:i}});return}default:Qe(n,t,a,r)}}function Qe(e,t,a,n){const r=a.unknownActionPolicy??"log-and-ignore";if(r==="delegate"){t.unknown?.(e),t.unknown||n.warn("[gengage] Unknown action received without delegate handler",e);return}if(r==="throw")throw new Error(`[gengage] Unknown action kind: ${e.kind}`);n.warn("[gengage] Unknown action ignored",e)}function Do(e,t){if(!(typeof window>"u")){if(!fe(e)){console.warn("[gengage] Blocked navigation to unsafe URL:",e);return}dn(e,t)}}function Fo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ue(e){const t=e?.trim();return t||"tr"}function ve(e){const t=globalThis.CSS?.escape;if(typeof t=="function")return t(e);const a=Array.from(e);return a.map((n,r)=>{const i=n.codePointAt(0);return i===void 0?"":i===0?"�":i>=1&&i<=31||i===127||r===0&&i>=48&&i<=57||r===1&&a[0]==="-"&&i>=48&&i<=57?`\\${i.toString(16)} `:r===0&&n==="-"&&a.length===1?"\\-":i>=128||/[A-Za-z0-9_-]/.test(n)?n:`\\${n}`}).join("")}var Uo=["image/jpeg","image/png","image/webp"],_f=5*1024*1024;function $o(e){return Uo.includes(e.type)?e.size>5242880?{ok:!1,reason:"too_large"}:{ok:!0}:{ok:!1,reason:"invalid_type"}}function gn(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Ho(e){const t=[];let a=0,n=!1,r=!1,i=0;for(let o=0;o<e.length;o++){const s=e[o];if(r){r=!1;continue}if(s==="\\"&&n){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"&&a++,s==="}"&&(a--,a===0&&(t.push(e.slice(i,o+1)),i=o+1)))}return t.length>0?t:[e]}function pn(e,t){const a=e.trim();if(!a||a.startsWith(":"))return!1;const n=a.startsWith("data: ")?a.slice(6):a;if(n==="[DONE]")return t.onDone?.(),!0;try{const r=JSON.parse(n);return gn(r)?(Ne("stream",`event: ${r.type}`,r),t.onEvent(r),r.type==="done"?(t.onDone?.(),!0):!1):!1}catch{const r=Ho(n);if(r.length>1){for(const i of r)try{const o=JSON.parse(i);if(!gn(o))continue;if(t.onEvent(o),o.type==="done")return t.onDone?.(),!0}catch{}return!1}return!1}}async function Ct(e,t){if(!e.ok){t.onError?.(new Error(`HTTP ${e.status}: ${e.statusText}`));return}if(!e.body){t.onError?.(new Error("Response body is null — streaming not supported"));return}const a=e.body.getReader(),n=new TextDecoder("utf-8");let r="";const i=t.idleTimeoutMs??6e4,o=Symbol("idle-timeout");let s=!1;try{for(;;){const c=a.read();let l;const g=await(i>0?Promise.race([c.then(b=>(clearTimeout(l),b)),new Promise(b=>{l=setTimeout(()=>b(o),i)})]):c);if(g===o){s=!0,await a.cancel();break}const{done:p,value:h}=g;if(p)break;r+=n.decode(h,{stream:!0});const d=r.split(`
48
48
  `);r=d.pop()??"";for(const b of d)if(pn(b,t))return}if(r.trim()&&pn(r,t))return}catch(c){if(c instanceof DOMException&&c.name==="AbortError")return;t.onError?.(c instanceof Error?c:new Error(String(c)))}finally{s||a.releaseLock()}t.onDone?.()}var hn=3,qo=(e,t)=>{const a=e.replace(/\s+/g," ").trim().replace(/^[,.;:!?•-]+|[,.;:!?•-]+$/g,"");if(!a)return"";const n=t?.stripLeadingStopWords?a.replace(/^(?:daha|için)\s+/i,"").trim():a;return n?n.split(/\s+/).slice(0,3).join(" ").trim():""},la=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>qo(a,t)).filter(Boolean):[];function jo(e){const t=(e.display_keywords??[]).flatMap(r=>la(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,hn);const n=[...la(e.chosen_attribute,{stripLeadingStopWords:!0}),...la(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,hn)}function Zo(e){return jo(e).join(" • ")}var Vo=["beauty_consulting","watch_expert"];function un(e){return typeof e=="string"&&Vo.includes(e)}function St(e){if(typeof e.type!="string")return null;if(Go(e))return e;const t=e;switch(t.type){case"outputText":return Wo(t);case"suggestedActions":return Ko(t);case"productList":return Yo(t);case"productDetails":return Jo(t);case"productDetailsSimilars":return Qo(t);case"comparisonTable":return Xo(t);case"context":return ns(t);case"chatStreamEnd":return rs();case"loading":return is(t);case"panelLoading":return os(t);case"similarLoading":return ss(t);case"redirect":return cs(t);case"error":return ls(t);case"dummy":return ds(t);case"launcherAction":return gs(t);case"text":return da(t);case"productItem":return ps(t);case"text_image":return mn(t);case"quick_qna":return fn(t);case"reviewHighlights":return hs(t);case"aiProductSuggestions":return fs(t);case"aiProductGroupings":return bs(t);case"aiSuggestedSearches":return vs(t);case"prosAndCons":return us(t);case"getGroundingReview":return ys(t);case"voice":return xs(t);case"visitorDataResponse":return ms(t);case"productListPreview":return _s();case"groupList":return ws(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return ks(t);case"launcherContent":return Ss(t);case"handoff":return Cs(t);case"uiSpec":return Bs(t);default:return null}}function Go(e){const t=e.type;if(typeof t!="string")return!1;switch(t){case"metadata":return typeof e.sessionId=="string"&&typeof e.model=="string";case"text_chunk":return typeof e.content=="string";case"ui_spec":{const a=e.widget;if(a!=="chat"&&a!=="qna"&&a!=="simrel")return!1;const n=Ce(e.spec);return n?typeof n.root=="string"&&Ce(n.elements)!==null:!1}case"action":{const a=Ce(e.action);return a!==null&&typeof a.kind=="string"}case"error":return typeof e.code=="string"&&typeof e.message=="string";case"done":return!0;default:return!1}}function Wo(e){const t=G(e.payload.text,e.payload.plain_text)??"",a=G(e.payload.plain_text,e.payload.text)??t;if(e.payload.is_error)return{type:"error",code:"BACKEND_ERROR",message:a||"Backend returned an error"};const n={type:"text_chunk",content:t,final:!0},r=e.payload.product_mentions;Array.isArray(r)&&r.length>0&&(n.productMentions=r.filter(c=>typeof c=="object"&&c!==null&&typeof c.sku=="string"&&typeof c.short_name=="string"));const i=e.payload.sku_to_product_item;i&&typeof i=="object"&&!Array.isArray(i)&&(n.skuToProductItem=i);const o=e.payload.conversation_mode;typeof o=="string"&&o&&(n.conversationMode=o);const s=e.payload.render_hint;return typeof s=="string"&&s&&(n.renderHint=s),e.payload.kvkk===!0&&(n.kvkk=!0),n}function Ko(e){return bn((e.payload.actions??[]).map(t=>{const a=G(t.title)??"",n=ze(t.requestDetails,a),r=n?{label:a,action:n}:null;return r?(typeof t.icon=="string"&&(r.icon=t.icon),typeof t.image=="string"&&(r.image=t.image),r):null}).filter(dt),"chat")}function Yo(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=G(o.style_label);if(!s)return null;const c=G(o.style_mood),l=G(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(h=>{const d=Ce(h);return d?ga(Ce(d.product_detail)??Ce(d.product)??d):null}).filter(dt),p=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(h=>({label:G(h.label)??"",reason:G(h.reason)??"",skus:Array.isArray(h.skus)?h.skus.filter(d=>typeof d=="string"&&d.trim().length>0):[]})):[];return{style_label:s,style_mood:c??"",...l?{image_url:l}:{},...typeof o.status=="string"?{status:o.status}:{},product_list:g,recommendation_groups:p}}).filter(dt),a=e.payload.product_list??[],n=un(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?Es(n,"chat"):vn(a,"chat");r.panelHint="panel";const i=r.spec.elements[r.spec.root];if(i){const o={};typeof e.payload.offset=="number"&&(o.offset=e.payload.offset),typeof e.payload.end_of_list=="boolean"&&(o.endOfList=e.payload.end_of_list),typeof e.payload.title=="string"&&(o.panelTitle=e.payload.title),typeof e.payload.source=="string"&&(o.source=e.payload.source),t.length>0&&(o.styleVariations=t),e.payload.replace_panel===!0&&(o.replacePanel=!0),(e.payload.ranking_state==="pending"||e.payload.ranking_state==="final")&&(o.rankingState=e.payload.ranking_state);const s=e.payload.sequence_id??e.payload.search_id;typeof s=="string"&&s.length>0&&(o.sequenceId=s),Object.keys(o).length>0&&(i.props={...i.props,...o})}return r}function Jo(e){const t=e.payload.productDetails;if(!t)return Ts("chat");const a=$e(t);return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:{...t,...a}}}}},panelHint:"panel"}}function Qo(e){const t=vn(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function Xo(e){const t=e.payload.multiple_product_details??[],a=e.payload,n={key_differences:a.key_differences,recommended_choice:a.recommended_choice,recommended_choice_sku:a.recommended_choice_sku,special_considerations:a.special_considerations,criteria_view:a.criteria_view,criteria_view_short:a.criteria_view_short,compared_field_names:a.compared_field_names,winner_product:a.winner_product,winner_hits:a.winner_hits,...e.payload.product_comparison_framework??{}},r=e.payload.table,i=e.payload.features_list,o=[];for(const f of t){const m=$e(f);o.push(m)}const s=es(r,o,n,i);let c;n?.recommended_choice_sku?c=n.recommended_choice_sku:n?.winner_product&&n.winner_product.length>0&&(c=n.winner_product[0]?.product_detail?.sku??n.winner_product[0]?.sku);const l=c?o.find(f=>f.sku===c)??o[0]:o[0],g=[];if(Array.isArray(n?.key_differences))for(const f of n.key_differences)typeof f=="string"&&g.push(f);const p=Is(n?.special_considerations),h=n?.recommended_choice,d=n?.winner_hits,b={};for(const f of o){const m=f.sku;m&&(b[m]={title:f.name??m,type:"launchSingleProduct",payload:{sku:m}})}const u={products:o,attributes:s,highlights:g,productActions:b};return l&&(u.recommended=l),p.length>0&&(u.specialCases=p),h&&(u.recommendedText=h),d&&(u.winnerHits=d),typeof n?.key_differences=="string"&&(u.keyDifferencesHtml=n.key_differences),n?.special_considerations&&(u.specialConsiderations=n.special_considerations),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:u}}},panelHint:"panel"}}function es(e,t,a,n){if(!e)return[];const r=Object.entries(e);if(r.length===0)return[];const i=r[0]?.[1];if(Array.isArray(i)){const p=a.criteria_view??a.criteria_view_short??{},h=a.compared_field_names??Object.keys(e),d=[];for(const b of h){const u=e[b];if(!u||!Array.isArray(u))continue;const f=p[b]??b;d.push({label:f,values:u.map(m=>typeof m=="string"?m:String(m??""))})}return d}const o=e,s=t.map(p=>String(p.sku??"")).filter(p=>p.length>0),c=a.criteria_view??a.criteria_view_short??{},l=(n&&n.length>0?n:a.compared_field_names&&a.compared_field_names.length>0?a.compared_field_names:ts(o)).filter(p=>p!=="name"&&p!=="name_short"&&!p.endsWith("_short")),g=[];for(const p of l){const h=s.map(b=>{const u=o[b];if(!u||typeof u!="object")return"";const f=u[`${p}_short`],m=u[p];return as(f??m)});if(h.every(b=>b.length===0))continue;const d=c[p]??p;g.push({label:d,values:h})}return g}function ts(e){const t=[],a=new Set;for(const n of Object.values(e))if(!(!n||typeof n!="object"))for(const r of Object.keys(n))a.has(r)||(a.add(r),t.push(r));return t}function as(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function ns(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function rs(){return{type:"done"}}function is(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,loadingText:e.payload.text,thinkingMessages:e.payload.thinking_messages,dynamicLoading:e.payload.is_dynamic===!0}}}function os(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function ss(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function cs(e){const t=G(e.payload.url);return t?{type:"action",action:{kind:"navigate",url:t,newTab:e.payload.new_tab===!0}}:{type:"metadata",sessionId:"",model:"",meta:{redirect:e.payload,redirectTarget:G(e.payload.to)}}}function ls(e){return{type:"error",code:"BACKEND_ERROR",message:G(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function ds(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function gs(e){const t=e.payload??{};if(Array.isArray(t.action_list)){const r={action_list:t.action_list},i=typeof t.type=="string"?t.type:void 0,o=typeof t.theme=="string"?t.theme:void 0;return i!==void 0&&(r.type=i),o!==void 0&&(r.theme=o),fn({type:"quick_qna",payload:r})}const a=Ce(t.action);if(a){const r={action:a},i=typeof t.text=="string"?t.text:void 0,o=typeof t.image_url=="string"?t.image_url:void 0,s=typeof t.theme=="string"?t.theme:void 0;return i!==void 0&&(r.text=i),o!==void 0&&(r.image_url=o),s!==void 0&&(r.theme=s),mn({type:"text_image",payload:r})}const n=typeof t.text=="string"?t.text:"";if(n){const r={text:n},i=typeof t.type=="string"?t.type:void 0,o=typeof t.theme=="string"?t.theme:void 0,s=Ce(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),da({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function da(e){const t={text:G(e.payload.text)??""};return typeof e.payload.theme=="string"&&(t.theme=e.payload.theme),e.payload.payload!==void 0&&(t.payload=e.payload.payload),{type:"ui_spec",widget:"qna",spec:{root:"root",elements:{root:{type:"QuestionHeading",props:t}}}}}function ps(e){return Ps(e.payload,"qna")}function mn(e){const t=G(e.payload.text)??"",a=ze(e.payload.action,t);if(a){const r={label:t||a.title,action:a};return typeof e.payload.image_url=="string"&&(r.image=e.payload.image_url),typeof e.payload.theme=="string"&&(r.theme=e.payload.theme),{type:"ui_spec",widget:"qna",spec:{root:"root",elements:{root:{type:"ActionButton",props:r}}}}}const n={text:t};return typeof e.payload.theme=="string"&&(n.theme=e.payload.theme),da({type:"text",payload:n})}function fn(e){return bn((e.payload.action_list??[]).map(t=>{const a=G(t.title)??"",n=ze(t.requestDetails,a),r=n?{label:a,action:n}:null;return r?(typeof t.icon=="string"&&(r.icon=t.icon),typeof t.image=="string"&&(r.image=t.image),r):null}).filter(dt),"qna")}function hs(e){const t={reviews:(e.payload.reviews??[]).map(a=>{const n={};return typeof a.review_class=="string"&&(n.review_class=a.review_class),typeof a.review_text=="string"&&(n.review_text=a.review_text),(typeof a.review_rating=="string"||typeof a.review_rating=="number")&&(n.review_rating=a.review_rating),typeof a.review_tag=="string"&&(n.review_tag=a.review_tag),n})};return typeof e.payload.sku=="string"&&(t.sku=e.payload.sku),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ReviewHighlights",props:t}}}}}function us(e){const t={};return Array.isArray(e.payload.pros)&&(t.pros=e.payload.pros),Array.isArray(e.payload.cons)&&(t.cons=e.payload.cons),typeof e.payload.product_name=="string"&&(t.productName=e.payload.product_name),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProsAndCons",props:t}}}}}function ms(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function fs(e){const t=e.payload.product_suggestions??[],a=[];for(let n=0;n<t.length;n++){const r=t[n];if(!r)continue;const i=As(r);if(!i)continue;const o={product:i},s=ze(r.requestDetails,i.name);s&&(o.action=s),typeof r.role=="string"&&(o.role=r.role),typeof r.reason=="string"&&(o.reason=r.reason),typeof r.review_highlight=="string"&&(o.reviewHighlight=r.review_highlight),Array.isArray(r.labels)&&(o.labels=r.labels),typeof r.expert_quality_score=="number"&&(o.expertQualityScore=r.expert_quality_score),a.push(o)}return a.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiProductSuggestions:e.payload.product_suggestions??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AITopPicks",props:{suggestions:a}}}}}}function bs(e){const t=e.payload.product_groupings??[],a=[],n=[];for(let r=0;r<t.length;r++){const i=t[r];if(!i)continue;const o=G(i.name)??"",s=G(i.sku,i.repr_sku),c=G(i.image,i.repr_image),l=s!==void 0?{type:"findSimilar",payload:{sku:s}}:void 0,g=ze(i.requestDetails??l,o),p=(Array.isArray(i.group_products)?i.group_products:[]).map(b=>{const u=Ce(b);return u?ga(u):null}).filter(dt),h=c??G(...p.map(b=>b.imageUrl));if(o&&p.length>0){const b={groupName:o,products:p};h&&(b.image=h),a.push(b)}if(!g)continue;const d={name:o,action:g};if(Array.isArray(i.labels)){const b=i.labels.filter(u=>typeof u=="string");b.length>0&&(d.labels=b)}c!==void 0&&(d.image=c),n.push(d)}return a.length>0?{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"CategoriesContainer",props:{groups:a}}}},panelHint:"panel"}:n.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiProductGroupings:e.payload.product_groupings??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AIGroupingCards",props:{entries:n}}}}}}function vs(e){const t=e.payload.suggested_searches??[],a=[];for(let n=0;n<t.length;n++){const r=t[n];if(!r)continue;const i=G(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=G(r.detailed_user_message);s&&(o.text=s);const c=Ce(Ce(r.requestDetails)?.payload),l=c?.group_skus;r.group_skus&&Array.isArray(r.group_skus)?o.group_skus=r.group_skus:Array.isArray(l)&&(o.group_skus=l.filter(m=>typeof m=="string"));const g=G(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const p={type:"inputText",payload:o},h=ze(r.requestDetails,i),d=h?.type==="findSimilar"&&typeof o.text=="string"?ze(p,i):h??ze(p,i);if(!d)continue;const b={shortName:i,action:d},u=G(r.detailed_user_message);u&&u!==i&&(b.detailedMessage=u);const f=Zo(r);f&&f!==i&&f!==(u??"")&&(b.whyDifferent=f),typeof r.image=="string"&&(b.image=r.image),a.push(b)}return a.length===0?{type:"metadata",sessionId:"",model:"",meta:{aiSuggestedSearches:e.payload.suggested_searches??[]}}:{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"AISuggestedSearchCards",props:{entries:a}}}}}}function ys(e){const t=e.payload,a=ze(t.requestDetails??t.request_details,G(t.review_count,t.reviewCount,t.text,t.title)??"Show product reviews");if(!a)return{type:"metadata",sessionId:"",model:"",meta:{groundingReview:t}};const n={action:a};return t.title&&(n.title=t.title),t.text&&(n.text=t.text),t.review_count?n.reviewCount=t.review_count:typeof t.reviewCount=="string"&&t.reviewCount.trim()&&(n.reviewCount=t.reviewCount),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"GroundingReviewCard",props:n}}}}}function _s(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function xs(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function ws(e){const t=e.payload.group_list??[],a=[];for(const r of t){const i=r.group_name??"",o=(r.product_list??[]).map($e);a.push({groupName:i,products:o})}const n=[];for(const r of e.payload.filter_tags??[]){const i=r.title??"";if(!i)continue;const o=ze(r.requestDetails,i),s={title:i};o&&(s.action=o),n.push(s)}return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"CategoriesContainer",props:{groups:a,filterTags:n}}}},panelHint:"panel"}}function ks(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function Cs(e){const t={};return typeof e.payload?.summary=="string"&&(t.summary=e.payload.summary),Array.isArray(e.payload?.products_discussed)&&(t.products_discussed=e.payload.products_discussed),typeof e.payload?.user_sentiment=="string"&&(t.user_sentiment=e.payload.user_sentiment),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"HandoffNotice",props:t}}}}}function Ss(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function bn(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=`action-${r}`;n.push(o);const s={label:i.label,action:i.action};i.icon!==void 0&&(s.icon=i.icon),i.image!==void 0&&(s.image=i.image),i.description!==void 0&&(s.description=i.description),a[o]={type:"ActionButton",props:s}}return a.root={type:"ActionButtons",props:{buttons:e.map(r=>{const i={label:r.label,action:r.action};return r.image!==void 0&&(i.image=r.image),r.description!==void 0&&(i.description=r.description),r.icon!==void 0&&(i.icon=r.icon),i})},children:n},{type:"ui_spec",widget:t,spec:{root:"root",elements:a}}}function vn(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=$e(i),s=`product-${r}`;n.push(s);const c={product:o,index:r};o.sku&&(c.action={title:o.name,type:"launchSingleProduct",payload:{sku:o.sku}}),a[s]={type:"ProductCard",props:c}}return a.root={type:"ProductGrid",props:{layout:"grid"},children:n},{type:"ui_spec",widget:t,spec:{root:"root",elements:a}}}function Es(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=`product-${r}`;n.push(o);const s={product:i,index:r},c=i.sku;c&&(s.action={title:i.name??"",type:"launchSingleProduct",payload:{sku:c}}),a[o]={type:"ProductCard",props:s}}return a.root={type:"ProductGrid",props:{layout:"grid"},children:n},{type:"ui_spec",widget:t,spec:{root:"root",elements:a}}}function Ps(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:$e(e),index:0}}}}}}function Ts(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function As(e){const t=G(e.sku),a=G(e.short_name),n={...Ce(e.product_item)??e},r=G(e.discount_reason,e.discountReason);return r&&!G(n.discount_reason,n.discountReason)&&(n.discount_reason=r),ga(n,t,a)}function ga(e,t,a){const n=G(e.sku,t),r=G(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=G(e.brand);o&&(i.brand=o);const s=G(e.url);s&&(i.url=s);const c=Ls(e.images);if(c.length>0)i.images=c;else{const u=G(e.image,e.image_url,e.imageUrl);u&&(i.images=[u])}const l=lt(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=lt(e.price);g!==void 0&&(i.price=g);const p=lt(e.rating);p!==void 0&&(i.rating=p);const h=lt(e.review_count)??lt(e.reviewCount);h!==void 0&&(i.review_count=h);const d=G(e.cart_code,e.cartCode);d&&(i.cart_code=d),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const b=G(e.discount_reason,e.discountReason);return b&&(i.discount_reason=b),$e(i)}function ze(e,t){const a=Ce(e);if(!a)return null;const n=a.type;if(typeof n!="string"||n.length===0)return null;const r={title:t||n,type:n};return a.payload!==void 0&&(r.payload=a.payload),r}function Ce(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function G(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function Ls(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Is(e){if(typeof e=="string"){const t=e.trim();return t?[t]:[]}return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(t=>t.length>0):[]}function lt(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){let t;e.includes(".")&&e.includes(",")?t=e.replace(/\./g,"").replace(",","."):t=e.replace(",",".");const a=Number(t);if(Number.isFinite(a))return a}}function dt(e){return e!=null}var Ns=new Set(["sku","name","brand","images","price","price_discounted","price_discount_rate","price_currency","discount_reason","url","rating","review_count","cart_code","in_stock","description","description_html","features","specifications","facet_tags","short_name","category_ids","category_names","variants","facet_hits","promotions"]);function $e(e){const t=e.price_discounted!=null&&e.price_discounted>0,a=t?e.price_discounted:e.price,n=t&&e.price!=null?e.price:void 0;let r;n!=null&&a!=null&&n>0?r=Math.round((n-a)/n*100):e.price_discount_rate!=null&&e.price_discount_rate>0&&(r=e.price_discount_rate);const i=G(e.brand),o=G(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:G(e.url)??""},l=e.images?.[0];l&&(c.imageUrl=l),e.images&&e.images.length>1&&(c.images=e.images),a!=null&&a>0&&(c.price=String(a)),n!=null&&n>0&&(c.originalPrice=String(n)),r!==void 0&&(c.discountPercent=r),i!==void 0&&(c.brand=i),e.rating!==void 0&&(c.rating=e.rating),e.review_count!==void 0&&(c.reviewCount=e.review_count),e.cart_code!==void 0&&(c.cartCode=e.cart_code),e.in_stock!==void 0&&(c.inStock=e.in_stock),e.variants&&e.variants.length>0&&(c.variants=e.variants),e.discount_reason!==void 0&&(c.discountReason=e.discount_reason),e.promotions&&e.promotions.length>0&&(c.promotions=e.promotions),e.description!==void 0&&(c.description=e.description),e.description_html!==void 0&&(c.descriptionHtml=e.description_html),e.features&&e.features.length>0&&(c.features=e.features),e.specifications!==void 0&&(c.specifications=e.specifications),e.facet_hits&&(c.facetHits=e.facet_hits),e.short_name!==void 0&&(c.shortName=e.short_name);const g=e,p={};let h=!1;for(const d of Object.keys(g))Ns.has(d)||(p[d]=g[d],h=!0);return h&&(c.extras=p),c}function zs(e){return e.results.map($e)}function Ms(e){return e.product_groupings.map(t=>{const a={name:t.name,products:(t.group_products??[]).map($e)};return t.highlight!==void 0&&(a.highlight=t.highlight),a})}function Bs(e){const t=e.payload.type,{type:a,...n}=e.payload;return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:t,props:n}}}}}var Rs={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function Os(e){if(e===void 0)throw new Error("[gengage] middlewareUrl is required. Pass your Gengage backend URL in widget config.");const t=e.trim();return t===""?"":t.replace(/\/+$/,"")}function Et(e,t){return`${Os(t?.middlewareUrl)}/chat${Rs[e]}`}function Ds(e,t){const a=e.type,n=e.payload!=null&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{},r=i=>{const o={...n};for(const[s,c]of Object.entries(i))s in o||(o[s]=c);return o};switch(a){case"inputText":{const i={is_launcher:0};return t.pageContext?.extra&&(i.page_details=t.pageContext.extra),"is_suggested_text"in n||(i.is_suggested_text=0),{...e,payload:r(i)}}case"findSimilar":{const i={is_launcher:0};return e.title&&(i.text=e.title,i.input=e.title),{...e,payload:r(i)}}case"getComparisonTable":{const i=e.payload;if(i&&typeof i=="object"&&!Array.isArray(i)&&"gengage_analytics_source"in i){const o={...i};return delete o.gengage_analytics_source,{...e,payload:o}}return e}case"launchProductList":return e;case"launchHomepage":return e;case"addToCart":{const i={};return"error_message"in n||(i.error_message=""),{...e,payload:r(i)}}case"reviewSummary":{const i={};return t.pageContext?.sku&&!("sku"in n)&&(i.sku=t.pageContext.sku),Object.keys(i).length===0?e:{...e,payload:r(i)}}default:return e}}var Fs={user_message:"inputText"};function Us(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=Fs[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function $s(e,t,a){const n=Et("process_action",a),r=new AbortController;return(async()=>{try{const o=Us(e),s=a.attachment!==void 0;let c;if(s){const h=new FormData;h.append("request",o),a.attachment!==void 0&&h.append("attachment",a.attachment),c={method:"POST",body:h,signal:r.signal}}else c={method:"POST",headers:{"Content-Type":"application/json"},body:o,signal:r.signal};const l=await fetch(n,c);if(!l.ok){let h=l.statusText;try{const d=await l.json(),b=d.detail??d.message??d.error;typeof b=="string"&&(h=b)}catch{}t.onError(new Error(`HTTP ${l.status}: ${h}`));return}let g=!1;const p=()=>{g||(g=!0,t.onDone())};await Ct(l,{onEvent:h=>{const d=St(h);if(d&&!(g&&d.type!=="error"))switch(d.type){case"text_chunk":t.onTextChunk(d.content,d.final===!0,{productMentions:d.productMentions,skuToProductItem:d.skuToProductItem,conversationMode:d.conversationMode,renderHint:d.renderHint,kvkk:d.kvkk});break;case"ui_spec":t.onUISpec(d.spec,d.widget,d.panelHint,d.clearPanel===!0);break;case"action":t.onAction(d);break;case"metadata":t.onMetadata(d);break;case"error":t.onError(new Error(d.message));break;case"done":p();break}},onError:t.onError,signal:r.signal}),p()}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;t.onError(o instanceof Error?o:new Error(String(o)))}})(),r}var Hs="gengage-chat-scroll",yn=null;function _n(e){yn=e}function qs(){yn=null}var Xe={headerTitle:"Ürün Uzmanı",inputPlaceholder:"Ürün ara, soru sor",sendButton:"Gönder",closeButton:"Kapat",openButton:"Sohbeti aç",newChatButton:"Yeni sohbet",poweredBy:"Gengage ile",errorMessage:"Bir hata oluştu. Lütfen tekrar deneyin.",retryButton:"Tekrar Dene",loadingMessage:"İsteğinizi inceliyorum...",loadingSequenceGeneric:["İsteğinizi inceliyorum...","Ürün ve yorumlara bakıyorum...","Detayları inceliyorum..."],loadingSequencePanel:["En ilgili detayları inceliyorum","En güçlü sinyalleri kontrol ediyorum","Bu görünümü sizin için hazırlıyorum"],loadingSequenceComparison:["Ürün farklarını inceliyorum","En güçlü farkları ve ödünleşimleri kontrol ediyorum","Karşılaştırmayı sizin için hazırlıyorum"],productCtaLabel:"Satın Al",viewOnSiteLabel:"Sitede Gör",attachImageButton:"Resim ekle",attachMenuSelectPhoto:"Fotoğraf Seç",attachMenuPaste:"Yapıştır",clipboardNoImageMessage:"Panoda görsel bulunamadı. Önce bir görsel kopyalayın veya dosya seçin.",removeAttachmentButton:"Resmi kaldır",invalidFileType:"Sadece JPEG, PNG ve WebP dosyaları destekleniyor.",fileTooLarge:"Dosya boyutu 5 MB'dan küçük olmalıdır.",aiTopPicksTitle:"Sizin İçin En İyiler",roleWinner:"Size Özel Seçimim",roleBestValue:"En Uygun Fiyatlı",roleBestAlternative:"En İyi Alternatif",viewDetails:"Detayları Gör",groundingReviewCta:"Yorumları Oku",groundingReviewSubtitle:"{count} yorum mevcut",variantsLabel:"Varyantlar",sortRelated:"Önerilen",sortPriceAsc:"Fiyat düşükten yükseğe",sortPriceDesc:"Fiyat yüksekten düşüğe",sortToolbarAriaLabel:"Ürünleri sırala",compareSelected:"Karşılaştır",compareMinHint:"En az 2 ürün seçin",compareMaxHint:"En fazla 5 ürün seçebilirsiniz",comparisonSelectLabel:"Karşılaştırmak için seç",comparisonSelectedLabel:"Seçildi",comparisonSelectCardHint:"Karşılaştırmaya eklemek veya çıkarmak için kartın herhangi bir yerine dokunun.",comparisonPreparingLabel:"Karşılaştırma tablosu hazırlanıyor…",panelTitleProductDetails:"Ürün Detayı",panelTitleSimilarProducts:"Benzer Ürünler",panelTitleComparisonResults:"Karşılaştırma Sonuçları",panelTitleCategories:"Kategoriler",panelTitleSearchResults:"Arama Sonuçları",inStockLabel:"Stokta",outOfStockLabel:"Tükendi",findSimilarLabel:"Benzerlerini Bul",galleryPrevAriaLabel:"Önceki görsel",galleryNextAriaLabel:"Sonraki görsel",beautyStylesPreparedTitle:"Sizin için {count} farklı stil hazırladım",watchStylesPreparedTitle:"Sizin için {count} farklı stil yönü hazırladım",consultingOtherCompatibleProductsLabel:"Diğer Uyumlu Ürünler",consultingFallbackGroupLabel:"Öneri",consultingFallbackStyleLabel:"Stil {index}",consultingStyleLoadingDescription:"Bu stil için ürünleri toplamaya devam ediyorum. Panel kısa süre içinde yenilenir.",consultingStyleUnavailableDescription:"Bu stil için şu anda yeterli ürün eşleşmesi çıkaramadım. Diğer stilleri inceleyebilirsiniz.",consultingStyleLoadingBadge:"Yükleniyor",consultingStyleUnavailableBadge:"Hazır değil",choicePrompterHeading:"Kararsız mı kaldın?",choicePrompterSuggestion:"Ürünleri seçip karşılaştırabilirsin",choicePrompterCta:"Seç ve Karşılaştır",viewMoreLabel:"Daha Fazla Göster",similarProductsLabel:"Benzer Ürünler",addToCartButton:"Sepete Ekle",addedToCartToast:"Sepete eklendi",shareButton:"Paylaş",productInfoTab:"Ürün Bilgileri",specificationsTab:"Teknik Özellikler",recommendedChoiceLabel:"Önerilen Seçim",highlightsLabel:"Öne Çıkan Özellikler",keyDifferencesLabel:"Temel Farklar",specialCasesLabel:"Özel Durumlar İçin",emptyReviewsMessage:"Yorum özeti bulunamadı.",closeAriaLabel:"Kapat",startChatLabel:"Sohbete Başla",voiceButton:"Sesli giriş",voiceListening:"Dinleniyor...",voiceNotSupported:"Sesli giriş bu tarayıcıda desteklenmiyor.",voicePermissionDenied:"Mikrofon erişimi reddedildi.",voiceError:"Sesli giriş hatası.",handoffHeading:"Destek temsilcisine aktarılıyor",productNotFoundMessage:"Bu ürün bilgisi şu an kullanılamıyor. Başka bir konuda yardımcı olabilirim.",stopGenerating:"Yanıtı Durdur",offlineMessage:"Çevrimdışısınız — bağlantı kurulduğunda mesajlar gönderilecek.",cartAriaLabel:"Sepetim",favoritesAriaLabel:"Favorilerim",showPanelAriaLabel:"Sonuçları Göster",addToFavoritesLabel:"Favorilere ekle",customerReviewsTitle:"Müşteri Yorumları",togglePanelAriaLabel:"Paneli aç/kapat",chatMessagesAriaLabel:"Sohbet mesajları",suggestionsAriaLabel:"Öneriler",moreSuggestionsAriaLabel:"Daha fazla öneri",rollbackAriaLabel:"Bu mesaja geri dön",backAriaLabel:"Geri",forwardAriaLabel:"İleri",closePanelAriaLabel:"Paneli kapat",dismissAriaLabel:"Kapat",cartAddErrorMessage:"Üzgünüm sepete ekleyemedim, bir sorunla karşılaştım.",favoriteToggleErrorMessage:"Favoriler güncellenemedi. Lütfen tekrar deneyin.",reviewFilterPositive:"Olumlu",reviewFilterNegative:"Olumsuz",decreaseLabel:"Azalt",increaseLabel:"Artır",reviewCustomersMentionSingular:"1 müşteri bahsediyor",reviewCustomersMentionPlural:"müşteri bahsediyor",reviewSubjectsHeading:"İncelemek için seçin",tryAgainButton:"Tekrar dene",askSomethingElseButton:"Başka bir şey sor",accountInactiveMessage:"Bu hesap şu an aktif değil. Lütfen daha sonra tekrar deneyin.",favoritesPageTitle:"Favorilerim",emptyFavoritesMessage:"Henüz favori ürün yok. Bir ürünü kalp ikonuna tıklayarak favorilere ekleyebilirsin.",showFormerMessagesButton:"↑ Önceki mesajları göster",aiAnalysisAnalyzingLabel:"Ürünler analiz ediliyor...",aiBrowseCategoriesTitle:"Kategorilere Göz At",photoAnalysisBadge:"Cilt Analizi",photoAnalysisStrengthsLabel:"Öne Çıkanlar",photoAnalysisFocusLabel:"Odak Noktaları",photoAnalysisCelebStyleLabel:"Celeb Vibe Eşleşmesi",beautyPhotoStepTitle:"Selfie ile kişiselleştir",beautyPhotoStepDescription:"İstersen net bir profil fotoğrafı yükle, sana özel önerilerde bulunayım.",beautyPhotoStepUpload:"Fotoğraf Yükle",beautyPhotoStepProcessing:"Fotoğraf işleniyor...",beautyPhotoStepSkip:"Geç",beautyPhotoStepSkipMessage:"Fotoğraf adımını geçiyorum"},js={headerTitle:"Product Expert",inputPlaceholder:"Search products, ask questions",sendButton:"Send",closeButton:"Close",openButton:"Open chat",newChatButton:"New chat",poweredBy:"Powered by Gengage",errorMessage:"Something went wrong. Please try again.",retryButton:"Retry",loadingMessage:"Reviewing your request...",loadingSequenceGeneric:["Reviewing your request...","Looking through products and reviews...","Reviewing the details..."],loadingSequencePanel:["Reviewing the most relevant details","Checking the strongest signals","Preparing this view for you"],loadingSequenceComparison:["Reviewing the product differences","Checking the strongest tradeoffs","Preparing your comparison"],productCtaLabel:"Buy",viewOnSiteLabel:"View on Site",attachImageButton:"Attach image",attachMenuSelectPhoto:"Choose photo",attachMenuPaste:"Paste",clipboardNoImageMessage:"No image found in clipboard. Copy an image first or choose a file.",removeAttachmentButton:"Remove image",invalidFileType:"Only JPEG, PNG and WebP files are supported.",fileTooLarge:"File must be smaller than 5 MB.",aiTopPicksTitle:"Top Picks for You",roleWinner:"Top Pick",roleBestValue:"Best Value",roleBestAlternative:"Best Alternative",viewDetails:"View Details",groundingReviewCta:"Read Reviews",groundingReviewSubtitle:"{count} reviews available",variantsLabel:"Variants",sortRelated:"Recommended",sortPriceAsc:"Price low to high",sortPriceDesc:"Price high to low",sortToolbarAriaLabel:"Sort products",compareSelected:"Compare",compareMinHint:"Select at least 2 products",compareMaxHint:"You can select up to 5 products",comparisonSelectLabel:"Select to compare",comparisonSelectedLabel:"Selected",comparisonSelectCardHint:"Tap anywhere on the card to add or remove it from comparison.",comparisonPreparingLabel:"Preparing your comparison…",panelTitleProductDetails:"Product Details",panelTitleSimilarProducts:"Similar Products",panelTitleComparisonResults:"Comparison Results",panelTitleCategories:"Categories",panelTitleSearchResults:"Search Results",inStockLabel:"In Stock",outOfStockLabel:"Out of Stock",findSimilarLabel:"Find Similar",galleryPrevAriaLabel:"Previous image",galleryNextAriaLabel:"Next image",beautyStylesPreparedTitle:"Prepared {count} beauty styles for you",watchStylesPreparedTitle:"Prepared {count} style directions for you",consultingOtherCompatibleProductsLabel:"Other compatible products",consultingFallbackGroupLabel:"Recommendation",consultingFallbackStyleLabel:"Style {index}",consultingStyleLoadingDescription:"I am still collecting products for this style. The panel will refresh shortly.",consultingStyleUnavailableDescription:"I could not find enough product matches for this style yet. You can review the other styles.",consultingStyleLoadingBadge:"Loading",consultingStyleUnavailableBadge:"Not ready",choicePrompterHeading:"Can't decide?",choicePrompterSuggestion:"Select products to compare them",choicePrompterCta:"Select & Compare",viewMoreLabel:"Show More",similarProductsLabel:"Similar Products",addToCartButton:"Add to Cart",addedToCartToast:"Added to cart",shareButton:"Share",productInfoTab:"Product Info",specificationsTab:"Specifications",recommendedChoiceLabel:"Recommended Choice",highlightsLabel:"Key Highlights",keyDifferencesLabel:"Key Differences",specialCasesLabel:"For Special Cases",emptyReviewsMessage:"No review summary found.",closeAriaLabel:"Close",startChatLabel:"Start Chat",voiceButton:"Voice input",voiceListening:"Listening...",voiceNotSupported:"Voice input is not supported in this browser.",voicePermissionDenied:"Microphone access denied.",voiceError:"Voice input error.",handoffHeading:"Transferring to a support agent",productNotFoundMessage:"Product information is currently unavailable. I can help with something else.",stopGenerating:"Stop generating",offlineMessage:"You're offline — messages will send when you reconnect.",cartAriaLabel:"My cart",favoritesAriaLabel:"My favorites",showPanelAriaLabel:"Show Results",addToFavoritesLabel:"Add to favorites",customerReviewsTitle:"Customer Reviews",togglePanelAriaLabel:"Toggle panel",chatMessagesAriaLabel:"Chat messages",suggestionsAriaLabel:"Suggestions",moreSuggestionsAriaLabel:"More suggestions",rollbackAriaLabel:"Rollback to this message",backAriaLabel:"Back",forwardAriaLabel:"Forward",closePanelAriaLabel:"Close panel",dismissAriaLabel:"Dismiss",cartAddErrorMessage:"Sorry, I couldn't add that to your cart. Something went wrong.",favoriteToggleErrorMessage:"We couldn't update favorites. Please try again.",reviewFilterPositive:"Positive",reviewFilterNegative:"Negative",decreaseLabel:"Decrease",increaseLabel:"Increase",reviewCustomersMentionSingular:"1 customer mentions",reviewCustomersMentionPlural:"customers mention",reviewSubjectsHeading:"Select to learn more",tryAgainButton:"Try again",askSomethingElseButton:"Ask something else",accountInactiveMessage:"This account is currently inactive. Please try again later.",favoritesPageTitle:"My Favorites",emptyFavoritesMessage:"No favorites yet. Heart a product to save it here.",showFormerMessagesButton:"↑ Show earlier messages",aiAnalysisAnalyzingLabel:"Analyzing products...",aiBrowseCategoriesTitle:"Browse categories",photoAnalysisBadge:"Skin Analysis",photoAnalysisStrengthsLabel:"Your strengths",photoAnalysisFocusLabel:"Focus points",photoAnalysisCelebStyleLabel:"Celeb style match",beautyPhotoStepTitle:"Personalize with a selfie",beautyPhotoStepDescription:"Upload a clear profile photo so I can give you personalized recommendations.",beautyPhotoStepUpload:"Upload Photo",beautyPhotoStepProcessing:"Processing photo...",beautyPhotoStepSkip:"Skip",beautyPhotoStepSkipMessage:"Skip the photo step"};function Zs(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Vs(e){return Zs(e)==="en"?js:Xe}function Gs(){return xn()!==null}function xn(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var Ws=class{constructor(e,t){this.recognition=null,this._state="idle",this.silenceTimer=null,this.accumulatedTranscript="",this.intentionalStop=!1,this._lastRestartAt=0,this.callbacks=e,this.lang=t?.lang??"tr-TR",this.silenceTimeoutMs=t?.silenceTimeoutMs??1500,this.autoSubmit=t?.autoSubmit??!0}get state(){return this._state}start(){if(this._state==="listening")return;const e=xn();if(!e){this.setState("error"),this.callbacks.onError?.("not-supported","Web Speech API is not supported in this browser.");return}if(typeof globalThis.isSecureContext<"u"&&!globalThis.isSecureContext){this.setState("error"),this.callbacks.onError?.("not-allowed","Voice input requires HTTPS.");return}this.accumulatedTranscript="",this.intentionalStop=!1;const t=new e;t.continuous=!0,t.interimResults=!0,t.lang=this.lang,t.maxAlternatives=1,t.onstart=()=>{this.setState("listening")},t.onresult=a=>{this.clearSilenceTimer();let n="",r="";for(let i=a.resultIndex;i<a.results.length;i++){const o=a.results[i];if(!o)continue;const s=o[0];s&&(o.isFinal?r+=s.transcript:n+=s.transcript)}r&&(this.accumulatedTranscript+=r,this.callbacks.onFinal?.(this.accumulatedTranscript)),n&&this.callbacks.onInterim?.(this.accumulatedTranscript+n),this.autoSubmit&&this.accumulatedTranscript&&this.startSilenceTimer()},t.onerror=a=>{const n=Ks(a.error);this.intentionalStop&&(a.error==="no-speech"||a.error==="aborted")||(this.setState("error"),this.callbacks.onError?.(n,a.message||a.error))},t.onend=()=>{if(this.clearSilenceTimer(),this._state==="listening"&&!this.intentionalStop){const a=Date.now();if(a-this._lastRestartAt<500){this.setState("idle");return}this._lastRestartAt=a;try{t.start()}catch{this.setState("idle")}return}this.setState("idle")},this.recognition=t;try{t.start()}catch{this.setState("error"),this.callbacks.onError?.("unknown","Failed to start speech recognition.")}}stop(){if(this.intentionalStop=!0,this.clearSilenceTimer(),this.recognition){try{this.recognition.stop()}catch{}this.recognition=null}return this.setState("idle"),this.accumulatedTranscript}abort(){if(this.intentionalStop=!0,this.clearSilenceTimer(),this.accumulatedTranscript="",this.recognition){try{this.recognition.abort()}catch{}this.recognition=null}this.setState("idle")}destroy(){this.abort()}setState(e){this._state!==e&&(this._state=e,this.callbacks.onStateChange?.(e))}startSilenceTimer(){this.clearSilenceTimer(),this.silenceTimer=setTimeout(()=>{const e=this.stop();e.trim()&&this.callbacks.onAutoSubmit?.(e.trim())},this.silenceTimeoutMs)}clearSilenceTimer(){this.silenceTimer!==null&&(clearTimeout(this.silenceTimer),this.silenceTimer=null)}};function Ks(e){switch(e){case"not-allowed":return"not-allowed";case"no-speech":return"no-speech";case"audio-capture":return"no-microphone";case"network":return"network";case"aborted":return"aborted";default:return"unknown"}}function Ys(e){const t=document.createElement("div");t.className="gengage-chat-kvkk-banner gds-evidence-card gds-evidence-card-warning",t.dataset.gengagePart="kvkk-banner",t.setAttribute("role","alert");const a=document.createElement("div");a.className="gengage-chat-kvkk-content",a.dataset.gengagePart="kvkk-content",a.innerHTML=ke(e.htmlContent),t.appendChild(a);const n=document.createElement("button");return n.className="gengage-chat-kvkk-dismiss",n.dataset.gengagePart="kvkk-dismiss",n.type="button",n.setAttribute("aria-label",e.closeAriaLabel??"Close privacy notice"),n.textContent="×",n.addEventListener("click",e.onDismiss),t.appendChild(n),t}var Js=class{constructor(e){this._el=document.createElement("div"),this._el.className="gengage-chat-panel-topbar gds-toolbar",this._el.dataset.gengagePart="panel-topbar",this._backBtn=document.createElement("button"),this._backBtn.className="gengage-chat-panel-topbar-back gds-btn gds-btn-ghost gds-icon-btn",this._backBtn.dataset.gengagePart="panel-topbar-back",this._backBtn.type="button",this._backBtn.disabled=!0,this._backBtn.setAttribute("aria-label",e.backAriaLabel??"Back"),this._backBtn.title=e.backAriaLabel??"Back",this._backBtn.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6"/><path d="M21 12H9"/></svg>',this._backBtn.addEventListener("click",()=>e.onBack());const t=document.createElement("div");t.className="gengage-chat-panel-topbar-title-wrap",this._titleEl=document.createElement("span"),this._titleEl.className="gengage-chat-panel-topbar-title",this._titleEl.dataset.gengagePart="panel-topbar-title",t.appendChild(this._titleEl),this._forwardBtn=document.createElement("button"),this._forwardBtn.className="gengage-chat-panel-topbar-forward gds-btn gds-btn-ghost gds-icon-btn",this._forwardBtn.dataset.gengagePart="panel-topbar-forward",this._forwardBtn.type="button",this._forwardBtn.disabled=!0,this._forwardBtn.setAttribute("aria-label",e.forwardAriaLabel??"Forward"),this._forwardBtn.title=e.forwardAriaLabel??"Forward",this._forwardBtn.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6"/><path d="M3 12h12"/></svg>',this._forwardBtn.addEventListener("click",()=>e.onForward()),this._actionsEl=document.createElement("div"),this._actionsEl.className="gengage-chat-panel-topbar-actions",this._actionsEl.dataset.gengagePart="panel-topbar-actions",this._closeBtn=document.createElement("button"),this._closeBtn.className="gengage-chat-panel-topbar-close gds-btn gds-btn-ghost gds-icon-btn",this._closeBtn.dataset.gengagePart="panel-topbar-close",this._closeBtn.type="button",this._closeBtn.setAttribute("aria-label",e.closePanelAriaLabel??"Close panel"),this._closeBtn.title=e.closePanelAriaLabel??"Close panel",this._closeBtn.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',this._closeBtn.addEventListener("click",()=>e.onClose?.()),this._el.appendChild(this._backBtn),this._el.appendChild(t),this._el.appendChild(this._actionsEl),this._el.appendChild(this._forwardBtn),this._el.appendChild(this._closeBtn)}update(e,t,a){this._backBtn.disabled=!e,this._forwardBtn.disabled=!t,this._backBtn.hidden=!e,this._forwardBtn.hidden=!t,this._titleEl.textContent=a,this._titleEl.title=a}getElement(){return this._el}setTitle(e){this._titleEl.textContent=e}setActions(e){this._actionsEl.replaceChildren(),e&&this._actionsEl.appendChild(e)}getTitle(){return this._titleEl.textContent??""}},Qs=class{constructor(e){this._onThumbnailClick=e.onThumbnailClick,this._el=document.createElement("div"),this._el.className="gengage-chat-thumbnails-column",this._el.style.display="none"}getElement(){return this._el}setEntries(e){const t=new Set,a=[];for(const n of e)t.has(n.sku)||(t.add(n.sku),a.push(n));this._el.innerHTML="";for(const n of a){const r=document.createElement("button");if(r.type="button",r.className="gengage-chat-thumbnail-btn",r.title=n.sku,we(n.imageUrl)){const i=document.createElement("img");i.className="gengage-chat-thumbnail-img",i.src=n.imageUrl,i.alt=n.sku,i.width=40,i.height=40,r.appendChild(i)}r.addEventListener("click",()=>{this._onThumbnailClick(n.threadId)}),this._el.appendChild(r)}}show(){this._el.style.display=""}hide(){this._el.style.display="none"}};function Xs(e){return{processing:e.processing===!0,title:typeof e.title=="string"?e.title:void 0,description:typeof e.description=="string"?e.description:void 0,uploadLabel:typeof e.upload_label=="string"?e.upload_label:void 0,skipLabel:typeof e.skip_label=="string"?e.skip_label:void 0}}function wn(e,t,a){const n=e.props??{},r=n.processing===!0,i={...Xe,...t.i18n??{}},o=document.createElement("div");o.className="gengage-chat-beauty-photo-step-card";const s=document.createElement("span");s.className="gengage-chat-beauty-photo-step-icon",s.setAttribute("aria-hidden","true"),s.textContent="✦";const c=document.createElement("div");c.className="gengage-chat-beauty-photo-step-content";const l=document.createElement("div");l.className="gengage-chat-beauty-photo-step-title",l.textContent=(typeof n.title=="string"?n.title:void 0)??i.beautyPhotoStepTitle;const g=document.createElement("p");g.className="gengage-chat-beauty-photo-step-desc",g.textContent=(typeof n.description=="string"?n.description:void 0)??i.beautyPhotoStepDescription;const p=document.createElement("div");p.className="gengage-chat-beauty-photo-step-actions";const h=document.createElement("button");h.type="button",h.className="gengage-chat-beauty-photo-step-upload gds-btn gds-btn-primary",h.textContent=r?i.beautyPhotoStepProcessing:(typeof n.upload_label=="string"?n.upload_label:void 0)??i.beautyPhotoStepUpload,h.disabled=r,a?.onUpload&&h.addEventListener("click",()=>a.onUpload());const d=document.createElement("button");return d.type="button",d.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",d.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??i.beautyPhotoStepSkip,a?.onSkip&&d.addEventListener("click",()=>a.onSkip()),p.appendChild(h),p.appendChild(d),c.appendChild(l),c.appendChild(g),c.appendChild(p),o.appendChild(s),o.appendChild(c),o}function ec(e,t){if(e)return e;const a=document.createElement("section");a.className="gengage-chat-beauty-photo-step",a.dataset.gengagePart="chat-beauty-photo-step",a.hidden=!0;const n=t?.querySelector(".gengage-chat-input-area");return n?n.parentElement?.insertBefore(a,n):t?.appendChild(a),a}function tc(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=ec(e,t);i.hidden=!1,i.innerHTML="";const o=wn({type:"BeautyPhotoStep",props:{processing:a.processing??!1,title:a.title,description:a.description,upload_label:a.uploadLabel,skip_label:a.skipLabel}},{i18n:n,onAction:()=>{}},{onUpload:r,onSkip:a.onSkip});return i.appendChild(o),i}function kn(e){const t=typeof e.summary=="string"?e.summary:"",a=Array.isArray(e.strengths)?e.strengths.filter(c=>typeof c=="string"):[],n=Array.isArray(e.focus_points)?e.focus_points.filter(c=>typeof c=="string"):[];if(!t&&a.length===0&&n.length===0)return null;const r={summary:t},i=typeof e.celeb_style=="string"?e.celeb_style:void 0,o=typeof e.celeb_style_reason=="string"?e.celeb_style_reason:void 0,s=typeof e.next_question=="string"?e.next_question:void 0;return a.length>0&&(r.strengths=a),n.length>0&&(r.focusPoints=n),i&&(r.celebStyle=i),o&&(r.celebStyleReason=o),s&&(r.nextQuestion=s),r}function Cn(e,t,a){if(t.length===0)return null;const n=document.createElement("section");n.className=`gengage-chat-photo-analysis-section ${a}`;const r=document.createElement("h4");r.className="gengage-chat-photo-analysis-section-title",r.textContent=e;const i=document.createElement("ul");i.className="gengage-chat-photo-analysis-section-list";for(const o of t){const s=document.createElement("li");s.className="gengage-chat-photo-analysis-section-item",s.textContent=o,i.appendChild(s)}return n.appendChild(r),n.appendChild(i),n}function Sn(e,t){const a=document.createElement("div");a.className="gengage-chat-photo-analysis-card";const n=document.createElement("div");n.className="gengage-chat-photo-analysis-badge",n.textContent=e.badge;const r=document.createElement("div");if(r.className="gengage-chat-photo-analysis-body",t.summary){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-summary",c.textContent=t.summary,r.appendChild(c)}const i=document.createElement("div");i.className="gengage-chat-photo-analysis-highlights";const o=Cn(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=Cn(e.focus,t.focusPoints??[],"gengage-chat-photo-analysis-section--focus");if(o&&i.appendChild(o),s&&i.appendChild(s),i.childElementCount>0&&r.appendChild(i),t.celebStyle){const c=document.createElement("section");c.className="gengage-chat-photo-analysis-section gengage-chat-photo-analysis-section--celeb";const l=document.createElement("h4");l.className="gengage-chat-photo-analysis-section-title",l.textContent=e.celebStyle;const g=document.createElement("p");if(g.className="gengage-chat-photo-analysis-celeb-name",g.textContent=t.celebStyle,c.appendChild(l),c.appendChild(g),t.celebStyleReason){const p=document.createElement("p");p.className="gengage-chat-photo-analysis-celeb-reason",p.textContent=t.celebStyleReason,c.appendChild(p)}r.appendChild(c)}if(t.nextQuestion){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-next",c.textContent=t.nextQuestion,r.appendChild(c)}return a.appendChild(n),a.appendChild(r),a}function ac(e){const t={...Xe,...e?.i18n??{}};return{badge:t.photoAnalysisBadge,strengths:t.photoAnalysisStrengthsLabel,focus:t.photoAnalysisFocusLabel,celebStyle:t.photoAnalysisCelebStyleLabel}}function nc(e,t){const a=kn(e.props??{})??{summary:""};return Sn(ac(t),a)}function rc(e,t,a){e.innerHTML="",a&&e.appendChild(Sn(t,a))}var xf='<svg viewBox="0 0 16 16" class="gengage-chat-icon"><path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',En={search:'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><circle cx="6.5" cy="6.5" r="5" fill="none" stroke="currentColor" stroke-width="1.5"/><line x1="10" y1="10" x2="15" y2="15" stroke="currentColor" stroke-width="1.5"/></svg>',review:'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><polygon points="8,1 10,6 15,6 11,9 12.5,14 8,11 3.5,14 5,9 1,6 6,6" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>',info:'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><circle cx="8" cy="8" r="7" fill="none" stroke="currentColor" stroke-width="1.5"/><line x1="8" y1="7" x2="8" y2="12" stroke="currentColor" stroke-width="1.5"/><circle cx="8" cy="4.5" r="0.8" fill="currentColor"/></svg>',similar:'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><rect x="1" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/><rect x="9" y="3" width="6" height="6" rx="1" fill="none" stroke="currentColor" stroke-width="1.5"/></svg>'},ic=Xe,oc=1400,Pn=1500,sc=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function cc(e){for(const t of e)for(const a of t.types)if(a.startsWith("image/"))try{const n=await t.getType(a);if(!n||n.size===0)continue;const r=a||n.type||"image/png",i=r==="image/png"?"png":r==="image/webp"?"webp":"jpg",o=`paste-${Date.now()}.${i}`;return new File([n],o,{type:r})}catch{continue}for(const t of e)if(t.types.includes("text/html"))try{const a=(await(await t.getType("text/html")).text()).match(sc)?.[0];if(!a||a.length>5e6)continue;const n=await(await fetch(a)).blob();if(!n||n.size===0)continue;const r=n.type||"image/png";if(!["image/jpeg","image/png","image/webp"].includes(r))continue;const i=r==="image/png"?"png":r==="image/webp"?"webp":"jpg";return new File([n],`paste-${Date.now()}.${i}`,{type:r})}catch{continue}return null}async function lc(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?cc(await t):null}catch{}return null}var dc=class{_renderPhotoAnalysisCard(e,t){rc(e,{badge:this.i18n.photoAnalysisBadge,strengths:this.i18n.photoAnalysisStrengthsLabel,focus:this.i18n.photoAnalysisFocusLabel,celebStyle:this.i18n.photoAnalysisCelebStyleLabel},t)}constructor(e,t){this._sendStopHandler=null,this._panelVisible=!1,this._panelCollapsed=!1,this._dividerPreviewEnabled=!1,this._onPanelToggle=void 0,this._onHostShellSync=void 0,this._pendingAttachment=null,this._onAttachment=void 0,this._onRollback=void 0,this._onLinkClick=void 0,this._userScrolledUp=!1,this._scrollLockedUntil=0,this._favBadgeEl=null,this._thinkingSteps=[],this._firstBotMessageIds=new Set,this._voiceInput=null,this._micBtn=null,this._voiceEnabled=!1,this._voiceLang="tr-TR",this._ignoreNextDividerClick=!1,this._cleanups=[],this._focusTrapHandler=null,this._previouslyFocusedElement=null,this._conversationEl=null,this._reopenPanelBtn=null,this._presentationFocusThreadId=null,this._formerMessagesBtn=null,this._programmaticScrollUntil=0,this._userInteractionUntil=0,this._touchStartY=null,this._presentationPinned=!0,this._presentationUserInteracting=!1,this._resizeRafId=null,this._cartBtn=null,this._attachWrapEl=null,this._attachMenuEl=null,this._attachBtn=null,this._attachMenuCleanup=null,this._attachMenuClickTimerId=null,this._typingLoadingBinding=null,this._panelLoadingBinding=null,this._panelAiZoneLoadingBinding=null,this._beautyPhotoStepEl=null,this._options=t,this.i18n={...ic,...t.i18n},this.onSend=t.onSend,t.onPanelToggle!==void 0&&(this._onPanelToggle=t.onPanelToggle),t.onHostShellSync!==void 0&&(this._onHostShellSync=t.onHostShellSync),t.onAttachment!==void 0&&(this._onAttachment=t.onAttachment),t.onRollback!==void 0&&(this._onRollback=t.onRollback),t.onLinkClick!==void 0&&(this._onLinkClick=t.onLinkClick),t.voiceEnabled&&(this._voiceEnabled=!0),t.voiceLang!==void 0&&(this._voiceLang=t.voiceLang),this.root=document.createElement("div"),this.root.className="gengage-chat-drawer gds-panel",this.root.dataset.gengagePart="chat-drawer",this.root.setAttribute("role","dialog"),this.root.setAttribute("aria-label",this.i18n.headerTitle??"Chat"),this.root.setAttribute("aria-modal","true");const a="gengage-chat-dialog-desc",n=document.createElement("span");n.id=a,n.className="gengage-sr-only",n.textContent=this.i18n.headerTitle??"AI shopping assistant",this.root.appendChild(n),this.root.setAttribute("aria-describedby",a);let r=null;{const S=document.createElement("div");S.className="gengage-chat-drawer-handle",S.dataset.gengagePart="chat-drawer-handle",S.setAttribute("aria-hidden","true"),S.style.pointerEvents="none",r=S}const i=document.createElement("div");i.className="gengage-chat-header gds-shell-header",i.dataset.gengagePart="chat-header";const o=document.createElement("div");o.className="gengage-chat-header-left",o.dataset.gengagePart="chat-header-left";const s=t.headerAvatarUrl??t.launcherImageUrl,c=typeof t.headerAvatarUrl=="string"&&t.headerAvatarUrl.length>0&&t.headerAvatarUrl!==t.launcherImageUrl;if(s){const S=document.createElement("img");S.className="gengage-chat-header-avatar",c&&S.classList.add("gengage-chat-header-avatar--logo"),S.dataset.gengagePart="chat-header-avatar",S.src=s,S.alt=t.headerTitle??"Assistant",o.appendChild(S)}const l=document.createElement("div");l.className="gengage-chat-header-info",l.dataset.gengagePart="chat-header-info";const g=document.createElement("div");g.className="gengage-chat-header-title-row",g.dataset.gengagePart="chat-header-title-row";const p=document.createElement("span");if(p.className="gengage-chat-header-title",p.dataset.gengagePart="chat-header-title",p.textContent=t.headerTitle??this.i18n.headerTitle??"Product Expert",g.appendChild(p),t.headerBadge){const S=document.createElement("span");S.className="gengage-chat-header-badge gds-badge gds-badge-brand",S.dataset.gengagePart="chat-header-badge",S.textContent=t.headerBadge,g.appendChild(S)}l.appendChild(g);const h=document.createElement("a");h.className="gengage-chat-header-powered",h.dataset.gengagePart="chat-header-powered-by",h.href="https://gengage.ai/",h.target="_blank",h.rel="noopener noreferrer",h.innerHTML=`<svg viewBox="0 0 15 15" fill="none" aria-hidden="true"><path d="M15 5.88941C12.2201 5.88941 9.72762 7.14107 8.05571 9.11059H0C2.77991 9.11059 5.27238 7.85893 6.94429 5.88941H15Z" fill="currentColor"/><path d="M9.10964 0C9.10964 2.24394 8.29524 4.30038 6.94429 5.88941C5.27238 7.85962 2.77922 9.11059 0 9.11059V5.88941C3.24802 5.88941 5.89036 3.2465 5.89036 0H9.10964Z" fill="currentColor" fill-opacity="0.68"/><path d="M15 5.88941V9.11059C11.752 9.11059 9.10964 11.7535 9.10964 15H5.89036C5.89036 12.7561 6.70476 10.6996 8.05571 9.11059C9.72762 7.14038 12.2208 5.88941 15 5.88941Z" fill="currentColor" fill-opacity="0.68"/></svg>${this.i18n.poweredBy}`,l.appendChild(h),o.appendChild(l),i.appendChild(o);const d=document.createElement("div");d.className="gengage-chat-header-right",d.dataset.gengagePart="chat-header-actions";{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-reopen-panel",S.setAttribute("aria-label",this.i18n.showPanelAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></svg>',S.addEventListener("click",()=>this._showMobilePanelFromBtn()),d.appendChild(S),this._reopenPanelBtn=S}{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-cart",S.setAttribute("aria-label",this.i18n.cartAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>',S.addEventListener("click",()=>t.onCartClick?.()),d.appendChild(S),this._cartBtn=S}if(t.onNewChat){const S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-new-chat",S.type="button",S.setAttribute("aria-label",this.i18n.newChatButton),S.title=this.i18n.newChatButton,S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>',S.addEventListener("click",()=>t.onNewChat?.()),d.appendChild(S)}const b=document.createElement("button");if(b.className="gengage-chat-close gds-btn gds-btn-ghost gds-icon-btn",b.dataset.gengagePart="chat-header-close",b.type="button",b.setAttribute("aria-label",this.i18n.closeButton),b.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>',b.addEventListener("click",t.onClose),t.showHeaderFavorites){const S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-favorites",S.type="button",S.setAttribute("aria-label",this.i18n.favoritesAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';const W=document.createElement("span");W.className="gengage-chat-header-fav-badge",W.dataset.gengagePart="chat-header-favorites-badge",W.setAttribute("aria-hidden","true"),W.style.display="none",S.appendChild(W),this._favBadgeEl=W,S.addEventListener("click",()=>{t.onFavoritesClick?.()}),d.appendChild(S)}d.appendChild(b),r&&i.insertBefore(r,i.firstChild),i.appendChild(d);{let W=0,de=0,he=!1;const Z=ae=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||ae.target.closest('button, a, input, [role="button"]'))return;const Le=ae.changedTouches?.[0];Le&&(W=Le.clientY,de=0,he=!0,this.root.style.transition="none")},J=ae=>{if(!he)return;const Le=ae.changedTouches?.[0];if(!Le)return;de=Le.clientY-W;const yf=(t.getMobileState?.()??"full")==="full"?Math.max(0,de):de;ae.preventDefault(),this.root.style.transform=`translateY(${yf}px)`},se=()=>{if(!he)return;he=!1;const ae=t.getMobileState?.()??"full";let Le;de>72?Le=ae==="full"?"half":"close":de<-72&&ae==="half"?Le="full":Le=ae,this.root.style.transition="",Le==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Le)),de=0},V=()=>{he&&(he=!1,de=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",Z,{passive:!0}),i.addEventListener("touchmove",J,{passive:!1}),i.addEventListener("touchend",se,{passive:!0}),i.addEventListener("touchcancel",V,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",Z),i.removeEventListener("touchmove",J),i.removeEventListener("touchend",se),i.removeEventListener("touchcancel",V)})}const u=document.createElement("div");u.className="gengage-chat-body",u.dataset.gengagePart="chat-body",this._panelEl=document.createElement("div"),this._panelEl.className="gengage-chat-panel gds-panel",this._panelEl.dataset.gengagePart="chat-panel",this._panelTopBar=new Js({onBack:()=>t.onPanelBack?.(),onForward:()=>t.onPanelForward?.(),onClose:()=>{t.getMobileViewport?.()??!1?this.hideMobilePanel():this.clearPanel(),t.onPanelClose?.()},backAriaLabel:this.i18n.backAriaLabel,forwardAriaLabel:this.i18n.forwardAriaLabel,closePanelAriaLabel:this.i18n.closePanelAriaLabel}),this._panelEl.appendChild(this._panelTopBar.getElement());const f=()=>this._updateScrollAffordance();this._panelEl.addEventListener("scroll",f,{passive:!0}),this._cleanups.push(()=>this._panelEl.removeEventListener("scroll",f)),u.appendChild(this._panelEl),this._dividerEl=document.createElement("div"),this._dividerEl.className="gengage-chat-panel-divider gengage-chat-panel-divider--hidden",this._dividerEl.dataset.gengagePart="chat-panel-divider",this._dividerEl.setAttribute("role","separator"),this._dividerEl.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),this._dividerEl.setAttribute("title",this.i18n.togglePanelAriaLabel),this._dividerPreviewEl=document.createElement("div"),this._dividerPreviewEl.className="gengage-chat-panel-divider-preview",this._dividerPreviewEl.dataset.gengagePart="chat-panel-divider-preview",this._dividerPreviewEl.setAttribute("aria-hidden","true"),this._dividerEl.appendChild(this._dividerPreviewEl);const m=document.createElement("button");m.className="gengage-chat-panel-divider-toggle gds-btn gds-btn-ghost",m.dataset.gengagePart="chat-panel-divider-toggle",m.type="button",m.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),m.setAttribute("title",this.i18n.togglePanelAriaLabel),m.textContent="»",m.addEventListener("click",()=>{if(this._ignoreNextDividerClick){this._ignoreNextDividerClick=!1;return}this.togglePanel(),this._onPanelToggle?.()});let y=null,k=null;const _=24,x=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const W=S.changedTouches?.[0];W&&(y=W.clientX,k=W.clientY)},T=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||y===null||k===null)return;const W=S.changedTouches?.[0];if(!W)return;const de=W.clientX-y,he=W.clientY-k;if(y=null,k=null,Math.abs(he)<_||Math.abs(he)<Math.abs(de))return;const Z=he<0;Z!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(Z),this._onPanelToggle?.())};this._dividerEl.addEventListener("touchstart",x,{passive:!0}),this._dividerEl.addEventListener("touchend",T,{passive:!0}),this._cleanups.push(()=>{this._dividerEl.removeEventListener("touchstart",x),this._dividerEl.removeEventListener("touchend",T)}),this._dividerEl.appendChild(m),u.appendChild(this._dividerEl);const P=document.createElement("div");P.className="gengage-chat-conversation",P.dataset.gengagePart="chat-conversation",this._conversationEl=P,P.appendChild(i);const I=document.createElement("div");I.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",I.dataset.gengagePart="chat-offline-bar",I.setAttribute("role","status"),I.setAttribute("aria-live","polite"),I.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&I.classList.add("gengage-chat-offline-bar--visible"),P.appendChild(I);const F=()=>I.classList.add("gengage-chat-offline-bar--visible"),X=()=>I.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",F),window.addEventListener("online",X),this._cleanups.push(()=>{window.removeEventListener("offline",F),window.removeEventListener("online",X)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",P.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=Hs,this.messagesEl.className="gengage-chat-messages",this.messagesEl.dataset.gengagePart="chat-messages",this.messagesEl.setAttribute("role","log"),this.messagesEl.setAttribute("aria-live","polite"),this.messagesEl.setAttribute("aria-atomic","false"),this.messagesEl.setAttribute("aria-label",this.i18n.chatMessagesAriaLabel),_n(this.messagesEl);const ne=document.createElement("button");ne.type="button",ne.className="gengage-chat-former-messages-btn gds-chip",ne.dataset.gengagePart="chat-former-messages-button",ne.textContent=this.i18n.showFormerMessagesButton,ne.setAttribute("aria-label",this.i18n.showFormerMessagesButton),ne.style.display="none",ne.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(ne),this._formerMessagesBtn=ne;const me=()=>{this._userInteractionUntil=Date.now()+2e3};let O=!1;const v=()=>this._options.presentation,L=()=>{O||(O=!0,requestAnimationFrame(()=>{O=!1;const{scrollTop:S,scrollHeight:W,clientHeight:de}=this.messagesEl,he=W-S-de;this._userScrolledUp=he>10;const Z=this._presentationPinned?he<96:he<32,J=Date.now(),se=J<this._programmaticScrollUntil,V=!Z&&J<this._userInteractionUntil,ae=se?!1:V;Z!==this._presentationPinned&&(this._presentationPinned=Z,v()?.onPinnedToBottomChange?.(Z)),ae!==this._presentationUserInteracting&&(this._presentationUserInteracting=ae,v()?.onUserInteractingChange?.(ae))}))};this.messagesEl.addEventListener("scroll",L,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",L)});const R=S=>{me(),S.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",R,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",R));const M=S=>{me(),this._touchStartY=S.touches[0]?.clientY??null},H=S=>{me();const W=S.touches[0]?.clientY,de=this._touchStartY;typeof W=="number"&&typeof de=="number"&&W-de>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",M,{passive:!0}),this.messagesEl.addEventListener("touchmove",H,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",M),this.messagesEl.removeEventListener("touchmove",H)}),P.appendChild(this.messagesEl),this._thumbnailsColumn=new Qs({onThumbnailClick:S=>t.onThumbnailClick?.(S)}),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelFloatingEl=document.createElement("div"),this._panelFloatingEl.className="gengage-chat-panel-float",this._panelFloatingEl.dataset.gengagePart="chat-panel-floating-layer",this._panelEl.appendChild(this._panelFloatingEl),this._resetPanelAiZoneElement(),this._pillsEl=document.createElement("div"),this._pillsEl.className="gengage-chat-pills",this._pillsEl.dataset.gengagePart="chat-suggestion-pills",this._pillsEl.setAttribute("role","toolbar"),this._pillsEl.setAttribute("aria-label",this.i18n.suggestionsAriaLabel),this._pillsEl.style.display="none";const q=document.createElement("div");q.className="gengage-chat-pills-scroll",q.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(q);const j=document.createElement("button");j.className="gengage-chat-pills-arrow gds-btn gds-btn-ghost",j.dataset.gengagePart="chat-suggestion-pills-more",j.type="button",j.setAttribute("aria-label",this.i18n.moreSuggestionsAriaLabel),j.textContent="›",j.addEventListener("click",()=>{q.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(j);let w=!1;const A=()=>{w||(w=!0,requestAnimationFrame(()=>{w=!1;const S=q.scrollLeft+q.clientWidth>=q.scrollWidth-4;j.style.display=S?"none":""}))};q.addEventListener("scroll",A,{passive:!0}),this._cleanups.push(()=>{q.removeEventListener("scroll",A)}),P.appendChild(this._pillsEl),this._inputChipsEl=document.createElement("div"),this._inputChipsEl.className="gengage-chat-input-chips",this._inputChipsEl.dataset.gengagePart="chat-input-chips",this._inputChipsEl.style.display="none",P.appendChild(this._inputChipsEl);const E=document.createElement("div");E.className="gengage-chat-input-area",E.dataset.gengagePart="chat-input-area",this.inputEl=document.createElement("textarea"),this.inputEl.className="gengage-chat-input",this.inputEl.dataset.gengagePart="chat-input",this.inputEl.rows=1,this.inputEl.placeholder=this.i18n.inputPlaceholder,this.inputEl.addEventListener("input",()=>{this._resizeRafId!==null&&cancelAnimationFrame(this._resizeRafId),this._resizeRafId=requestAnimationFrame(()=>{this._resizeRafId=null,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`}),this._updateSendEnabled()}),this.inputEl.addEventListener("keydown",S=>{S.key==="Enter"&&!S.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!S.shiftKey)&&(S.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",S=>{const W=S.clipboardData;if(!W)return;let de=null;const he=W.files?.[0];if(he&&he.type.startsWith("image/"))de=he;else if(W.items?.length)for(let Z=0;Z<W.items.length;Z++){const J=W.items[Z];if(J?.kind==="file"&&J.type.startsWith("image/")){const se=J.getAsFile();if(se){de=se;break}}}de&&(S.preventDefault(),this._routeAttachmentFile(de))}),this._fileInput=document.createElement("input"),this._fileInput.type="file",this._fileInput.accept="image/jpeg,image/png,image/webp",this._fileInput.style.display="none",this._fileInput.addEventListener("change",()=>{const S=this._fileInput.files?.[0];S&&this._routeAttachmentFile(S),this._fileInput.value=""});const N=document.createElement("div");N.className="gengage-chat-attach-wrap",N.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=N;const z=document.createElement("button");this._attachBtn=z,z.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",z.dataset.gengagePart="chat-attach-button",z.type="button",z.setAttribute("aria-label",this.i18n.attachImageButton),z.setAttribute("aria-haspopup","menu"),z.setAttribute("aria-expanded","false"),z.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>',z.addEventListener("click",S=>{S.stopPropagation(),this._toggleAttachMenu()});const B=document.createElement("div");this._attachMenuEl=B,B.className="gengage-chat-attach-menu gds-menu",B.dataset.gengagePart="chat-attach-menu",B.setAttribute("role","menu"),B.setAttribute("hidden","");const U=document.createElement("button");U.type="button",U.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",U.dataset.gengagePart="chat-attach-menu-select-photo",U.setAttribute("role","menuitem"),U.innerHTML=`<span class="gengage-chat-attach-menu-icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg></span><span class="gengage-chat-attach-menu-label">${this.i18n.attachMenuSelectPhoto}</span>`,U.addEventListener("click",S=>{S.stopPropagation(),this._closeAttachMenu(),this._fileInput.click()});const ee=document.createElement("div");ee.className="gengage-chat-attach-menu-sep",ee.dataset.gengagePart="chat-attach-menu-separator",ee.setAttribute("aria-hidden","true");const Q=document.createElement("button");Q.type="button",Q.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",Q.dataset.gengagePart="chat-attach-menu-paste",Q.setAttribute("role","menuitem"),Q.innerHTML=`<span class="gengage-chat-attach-menu-icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 2H9a1 1 0 0 0-1 1v1a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1Z"/><path d="M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"/><path d="M16 4h2a2 2 0 0 1 2 2v4"/><path d="M21 14H11"/><path d="m15 10-4 4 4 4"/></svg></span><span class="gengage-chat-attach-menu-label">${this.i18n.attachMenuPaste}</span>`,Q.addEventListener("click",S=>{S.stopPropagation();const W=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(W)}),B.appendChild(U),B.appendChild(ee),B.appendChild(Q),N.appendChild(z),N.appendChild(B),this._previewStrip=document.createElement("div"),this._previewStrip.className="gengage-chat-attachment-preview gengage-chat-attachment-preview--hidden gds-card-soft",this._previewStrip.dataset.gengagePart="chat-attachment-preview";const $=document.createElement("img");$.className="gengage-chat-attachment-preview-thumb",$.dataset.gengagePart="chat-attachment-preview-thumb",$.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const ie=document.createElement("button");ie.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",ie.dataset.gengagePart="chat-attachment-preview-remove",ie.type="button",ie.setAttribute("aria-label",this.i18n.removeAttachmentButton),ie.textContent="×",ie.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild($),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(ie),this.sendBtn=document.createElement("button"),this.sendBtn.className="gengage-chat-send gds-btn gds-btn-primary",this.sendBtn.dataset.gengagePart="chat-send",this.sendBtn.type="button",this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-label",this.i18n.sendButton),this.sendBtn.dataset.tooltip=this.i18n.sendButton,this._renderSendButtonIcon("send"),this.sendBtn.addEventListener("click",()=>{if(this._sendStopHandler){const S=this._sendStopHandler;this.hideStopButton(),S();return}this._submit()}),E.addEventListener("dragover",S=>{S.preventDefault(),E.classList.add("gengage-chat-input-area--dragover")}),E.addEventListener("dragleave",()=>{E.classList.remove("gengage-chat-input-area--dragover")}),E.addEventListener("drop",S=>{S.preventDefault(),E.classList.remove("gengage-chat-input-area--dragover");const W=S.dataTransfer?.files[0];W&&this._routeAttachmentFile(W)});const Y=document.createElement("div");Y.className="gengage-chat-input-pill gds-input-shell",Y.dataset.gengagePart="chat-input-shell",Y.appendChild(N),Y.appendChild(this.inputEl),this._voiceEnabled&&Gs()&&(this._micBtn=document.createElement("button"),this._micBtn.className="gengage-chat-mic-btn gds-btn gds-btn-ghost",this._micBtn.dataset.gengagePart="chat-mic-button",this._micBtn.type="button",this._micBtn.setAttribute("aria-label",this.i18n.voiceButton),this._micBtn.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>',this._micBtn.addEventListener("click",()=>this._toggleVoice()),Y.appendChild(this._micBtn),this._voiceInput=new Ws({onInterim:S=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=S,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:S=>{this.inputEl.value=S},onAutoSubmit:S=>{this.inputEl.value=S,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:S=>{S==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(S,W)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),Y.appendChild(this.sendBtn),E.appendChild(this._previewStrip),E.appendChild(this._fileInput),E.appendChild(Y),P.appendChild(E),u.appendChild(P),this._comparisonDockSlotEl=document.createElement("div"),this._comparisonDockSlotEl.className="gengage-chat-comparison-dock-slot",this._comparisonDockSlotEl.dataset.gengagePart="comparison-dock-slot",u.appendChild(this._comparisonDockSlotEl),this.root.appendChild(u),this._setupHorizontalSwipe(P),this._setupHorizontalSwipe(this._panelEl);const Be=document.createElement("div");Be.className="gengage-chat-footer",Be.dataset.gengagePart="chat-footer",Be.textContent=this.i18n.poweredBy,this.root.appendChild(Be);const vt=S=>{S.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",vt),this._cleanups.push(()=>this.root.removeEventListener("keydown",vt)),e.appendChild(this.root)}addMessage(e){const t=document.createElement("div");if(t.className=`gengage-chat-bubble gds-message ${e.role==="assistant"?"gds-message-assistant":"gds-message-user"} gengage-chat-bubble--${e.role}`,t.dataset.gengagePart=e.role==="assistant"?"chat-message-assistant":"chat-message-user",t.setAttribute("role","listitem"),t.dataset.messageId=e.id,e.threadId&&(t.dataset.threadId=e.threadId),this._firstBotMessageIds.has(e.id)&&t.classList.add("gengage-chat-bubble--first"),e.attachment){const a=document.createElement("img");a.className="gengage-chat-attachment-thumb";const n=URL.createObjectURL(e.attachment);a.src=n,a.alt=e.attachment.name,a.addEventListener("load",()=>URL.revokeObjectURL(n),{once:!0}),a.addEventListener("error",()=>URL.revokeObjectURL(n),{once:!0}),t.insertBefore(a,t.firstChild)}if(e.content){const a=document.createElement("div");if(a.className="gengage-chat-bubble-text",a.dataset.gengagePart="chat-message-text",e.role==="assistant"){if(e.renderHint==="photo_analysis"?(t.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(a,e.photoAnalysis)):a.innerHTML=ke(e.content),this._onLinkClick){const n=a.querySelectorAll("a[href]");for(const r of n)r.addEventListener("click",i=>{i.preventDefault();const o=r.getAttribute("href");o&&this._onLinkClick?.(o)})}}else a.textContent=e.content;t.appendChild(a)}if(e.role==="user"&&this._onRollback){const a=document.createElement("button");a.className="gengage-chat-rollback-btn gds-btn gds-btn-ghost",a.dataset.gengagePart="chat-message-rollback",a.type="button",a.setAttribute("aria-label",this.i18n.rollbackAriaLabel),a.title=this.i18n.rollbackAriaLabel,a.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"/></svg>',a.addEventListener("click",n=>{n.stopPropagation(),this._onRollback?.(e.id)}),t.appendChild(a)}this.messagesEl.appendChild(t),this._presentationFocusThreadId&&this._applyPresentationCollapsed(),this._scrollToBottom(e.role==="user")}removeMessageBubble(e){this._firstBotMessageIds.delete(e),this.messagesEl.querySelector(`[data-message-id="${ve(e)}"]`)?.remove(),this._presentationFocusThreadId&&this._applyPresentationCollapsed()}showTypingIndicator(e){this.removeTypingIndicator();const t=this._thinkingSteps.length>0?this._thinkingSteps.slice(-3):e?[e]:this.i18n.loadingSequenceGeneric,{root:a,binding:n}=this._createLoadingSequence("chat",t,"chat-typing-indicator","gengage-chat-typing");a.dataset.typing="true",this._typingLoadingBinding=n,this.messagesEl.appendChild(a),this._scrollToBottom(!0)}addThinkingStep(e){const t=e.trim();t&&this._thinkingSteps[this._thinkingSteps.length-1]!==t&&(this._thinkingSteps.push(t),this._thinkingSteps=this._thinkingSteps.slice(-3),this._typingLoadingBinding&&this._applyLoadingSteps(this._typingLoadingBinding,this._thinkingSteps,!0),this._panelLoadingBinding&&this._applyLoadingSteps(this._panelLoadingBinding,this._thinkingSteps,!0),this._panelAiZoneLoadingBinding&&this._applyLoadingSteps(this._panelAiZoneLoadingBinding,this._thinkingSteps,!0))}setThinkingSteps(e){const t=e.map(a=>a.trim()).filter(Boolean).slice(-3);t.length!==0&&(this._thinkingSteps=t,this._typingLoadingBinding&&this._applyLoadingSteps(this._typingLoadingBinding,this._thinkingSteps,!0),this._panelLoadingBinding&&this._applyLoadingSteps(this._panelLoadingBinding,this._thinkingSteps,!0),this._panelAiZoneLoadingBinding&&this._applyLoadingSteps(this._panelAiZoneLoadingBinding,this._thinkingSteps,!0))}removeTypingIndicator(){this._destroyLoadingBinding(this._typingLoadingBinding),this._typingLoadingBinding=null,this.messagesEl.querySelector(".gengage-chat-typing")?.remove(),this._thinkingSteps=[],this.hideStopButton()}showStopButton(e){this._sendStopHandler=e,this.sendBtn.disabled=!1,this.sendBtn.classList.add("gengage-chat-send--stop","gds-btn-secondary"),this.sendBtn.classList.remove("gds-btn-primary"),this.sendBtn.setAttribute("aria-label",this.i18n.stopGenerating),this.sendBtn.dataset.tooltip=this.i18n.stopGenerating,this._renderSendButtonIcon("stop")}hideStopButton(){this._sendStopHandler=null,this.sendBtn.classList.remove("gengage-chat-send--stop","gds-btn-secondary"),this.sendBtn.classList.add("gds-btn-primary"),this.sendBtn.setAttribute("aria-label",this.i18n.sendButton),this.sendBtn.dataset.tooltip=this.i18n.sendButton,this._renderSendButtonIcon("send"),this._updateSendEnabled()}showError(e,t){const a=document.createElement("div");a.className="gengage-chat-error",a.setAttribute("role","alert");const n=document.createElement("span");if(n.textContent=e??this.i18n.errorMessage,a.appendChild(n),t){const r=document.createElement("button");r.className="gengage-chat-error-retry",r.textContent=this.i18n.retryButton??"Retry",r.addEventListener("click",()=>{a.remove(),t()}),a.appendChild(r)}this.messagesEl.appendChild(a),this._scrollToBottom(!0)}showErrorWithRecovery(e,t){this.showError(e),this.setRecoveryPills(t)}showRecoveryPillsOnly(e){this.setRecoveryPills(e)}setRecoveryPills(e){this.setPills([{label:this.i18n.tryAgainButton,onAction:e.onRetry},{label:this.i18n.askSomethingElseButton,onAction:e.onNewQuestion}])}clearMessages(){const e=this._formerMessagesBtn;for(const t of[...this.messagesEl.children])t!==e&&t.remove()}setPills(e){const t=this._pillsEl.querySelector(".gengage-chat-pills-scroll");if(!t)return;for(;t.firstChild;)t.removeChild(t.firstChild);if(e.length===0){this._pillsEl.style.display="none";return}this._pillsEl.style.display="";for(const n of e){const r=document.createElement("button");if(r.className=n.image?"gengage-chat-pill gds-chip gds-chip-active gengage-chat-pill--rich":"gengage-chat-pill gds-chip gds-chip-active",r.type="button",n.icon){const o=En[n.icon]??'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',s=document.createElement("span");s.className="gengage-chat-pill-icon",s.innerHTML=o,r.appendChild(s)}if(n.image&&we(n.image)){const o=document.createElement("img");o.className="gengage-chat-pill-img",o.src=n.image,o.alt="",r.appendChild(o)}const i=document.createElement("span");if(i.className="gengage-chat-pill-text",i.textContent=n.label,r.appendChild(i),n.description){const o=document.createElement("span");o.className="gengage-chat-pill-desc";const s=`pill-desc-${Math.random().toString(36).slice(2,9)}`;o.id=s,o.textContent=n.description,r.appendChild(o),r.setAttribute("aria-describedby",s)}r.addEventListener("click",()=>n.onAction()),t.appendChild(r)}const a=this._pillsEl.querySelector(".gengage-chat-pills-arrow");a&&requestAnimationFrame(()=>{a.style.display=t.scrollWidth>t.clientWidth?"":"none"})}focusInput(){this.inputEl.focus()}showKvkkBanner(e,t){this._kvkkSlot.innerHTML="";const a=Ys({htmlContent:e,onDismiss:t,closeAriaLabel:this.i18n.closeAriaLabel});this._kvkkSlot.appendChild(a)}hideKvkkBanner(){this._kvkkSlot.innerHTML=""}isKvkkBannerVisible(){return this._kvkkSlot.childNodes.length>0}getElement(){return this.root}openAttachmentPicker(){this._fileInput.click()}setAttachmentControlsVisible(e){this._attachWrapEl&&(this._attachWrapEl.style.display=e?"":"none",e||this._closeAttachMenu())}setBeautyPhotoStepCard(e){this._beautyPhotoStepEl=tc(this._beautyPhotoStepEl,this._conversationEl??null,e,this.i18n,()=>this.openAttachmentPicker())}stageAttachment(e){this._pendingAttachment=e,this._previewName.textContent=e.name;const t=this._previewStrip.querySelector(".gengage-chat-attachment-preview-thumb");t&&(t.src&&t.src.startsWith("blob:")&&URL.revokeObjectURL(t.src),t.src=URL.createObjectURL(e)),this._previewStrip.classList.remove("gengage-chat-attachment-preview--hidden"),this._updateSendEnabled()}clearAttachment(){const e=this._previewStrip.querySelector(".gengage-chat-attachment-preview-thumb");e?.src&&(URL.revokeObjectURL(e.src),e.src=""),this._pendingAttachment=null,this._previewStrip.classList.add("gengage-chat-attachment-preview--hidden"),this._updateSendEnabled()}_routeAttachmentFile(e){if(this._onAttachment)try{this._onAttachment(e)}catch(t){console.error("[gengage:chat] Attachment callback error:",t)}else this.stageAttachment(e)}_closeAttachMenu(){this._attachMenuEl&&(this._attachMenuEl.setAttribute("hidden",""),this._attachBtn?.setAttribute("aria-expanded","false"),this._attachMenuClickTimerId!==null&&(clearTimeout(this._attachMenuClickTimerId),this._attachMenuClickTimerId=null),this._attachMenuCleanup&&(this._attachMenuCleanup(),this._attachMenuCleanup=null))}_openAttachMenu(){if(!this._attachMenuEl)return;this._attachMenuEl.removeAttribute("hidden"),this._attachBtn?.setAttribute("aria-expanded","true");const e=a=>{this._attachWrapEl?.contains(a.target)||this._closeAttachMenu()},t=a=>{a.key==="Escape"&&(a.stopPropagation(),this._closeAttachMenu())};this._attachMenuClickTimerId=window.setTimeout(()=>{this._attachMenuClickTimerId=null,document.addEventListener("click",e,!0)},0),document.addEventListener("keydown",t,!0),this._attachMenuCleanup=()=>{document.removeEventListener("click",e,!0),document.removeEventListener("keydown",t,!0)}}_toggleAttachMenu(){this._attachMenuEl&&(this._attachMenuEl.hasAttribute("hidden")?this._openAttachMenu():this._closeAttachMenu())}async _pasteImageFromClipboardMenu(e){const t=await lc(e);if(t){this._routeAttachmentFile(t),this._closeAttachMenu();return}pe("gengage:global:error",{message:this.i18n.clipboardNoImageMessage,source:"chat"}),this._closeAttachMenu()}getPendingAttachment(){return this._pendingAttachment}setPanelAiZoneState(e,t){if(this._panelAiZoneEl.isConnected&&(this._clearPanelAiZoneState(),e!=="hidden"))if(this._panelAiZoneEl.removeAttribute("hidden"),e==="analyzing"){this._panelAiZoneEl.innerHTML="";const a=[t?.analyzingLabel??this.i18n.aiAnalysisAnalyzingLabel,...this.i18n.loadingSequencePanel],{root:n,binding:r}=this._createLoadingSequence("panel",this._thinkingSteps.length>0?this._thinkingSteps.slice(-3):a,"panel-ai-zone-loading","gengage-chat-panel-ai-zone-inner");this._panelAiZoneLoadingBinding=r,this._panelAiZoneEl.appendChild(n)}else e==="results"&&t?.resultEl&&(this._panelAiZoneEl.innerHTML="",this._panelAiZoneEl.appendChild(t.resultEl))}_clearPanelAiZoneState(){this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelAiZoneEl.innerHTML="",this._panelAiZoneEl.setAttribute("hidden","")}_resetPanelAiZoneElement(){this._panelAiZoneEl=document.createElement("div"),this._panelAiZoneEl.className="gengage-chat-panel-ai-zone",this._panelAiZoneEl.setAttribute("hidden","")}_emitHostShellSync(){this._onHostShellSync?.()}_syncPanelTopBarFromContent(e){const t=e.querySelector(".gengage-chat-product-grid-head");if(t){const a=t.querySelector(".gengage-chat-product-grid-head-title"),n=t.querySelector(".gengage-chat-product-grid-head-actions");if(a?.textContent?.trim()){const r=a.textContent.trim();e.dataset.gengagePanelDerivedTitle=r,this._panelTopBar.setTitle(r)}n?(n.classList.add("gengage-chat-panel-topbar-toolbar-host"),this._panelTopBar.setActions(n)):this._panelTopBar.setActions(null),t.remove();return}this._syncPanelTopBarTitleFromContent(e)}_syncPanelTopBarTitleFromContent(e){const t=e.dataset.gengagePanelDerivedTitle;if(t?.trim()){this._panelTopBar.setTitle(t.trim());return}const a=e.querySelector(".gengage-chat-product-details-title, .gengage-chat-product-details-similars-heading, .gengage-chat-ai-top-picks-title")?.textContent?.trim();a&&this._panelTopBar.setTitle(a)}setPanelContent(e,t){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,t?.preserveAiZone!==!0&&this._clearPanelAiZoneState(),this._panelVisible?this._swapPanelContent(e):(this._panelEl.innerHTML="",this._resetPanelAiZoneElement(),this._panelEl.appendChild(this._panelTopBar.getElement()),this._panelEl.appendChild(this._panelAiZoneEl),this._panelTopBar.setActions(null),this._panelEl.appendChild(e),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl)),this._syncPanelTopBarFromContent(e),this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel"),this._panelCollapsed&&this._panelEl.classList.add("gengage-chat-panel--collapsed"),this._syncDividerPreview(),requestAnimationFrame(()=>{this._updateScrollAffordance(),this._smoothScrollPanelListToTop()}),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync()}_swapPanelContent(e){this._panelTopBar.setActions(null);const t=this._panelEl.querySelector(".gengage-chat-panel-skeleton");if(t){t.replaceWith(e);return}const a=this.getPanelContentElement();if(a){a.replaceWith(e);return}const n=this._thumbnailsColumn.getElement();n.parentElement===this._panelEl?this._panelEl.insertBefore(e,n):this._panelEl.appendChild(e)}appendPanelContent(e){const t=this._thumbnailsColumn.getElement(),a=t.parentElement===this._panelEl?t:this._panelFloatingEl;this._panelEl.insertBefore(e,a),this._syncPanelTopBarFromContent(this.getPanelContentElement()??e),this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel"),this._syncDividerPreview(),this._emitHostShellSync()}getPanelContentElement(){const e=this._panelEl.children;for(let t=0;t<e.length;t++){const a=e[t];if(!(a.classList.contains("gengage-chat-panel-topbar")||a.classList.contains("gengage-chat-panel-ai-zone")||a.classList.contains("gengage-chat-thumbnails-column")||a.classList.contains("gengage-chat-panel-float")))return a}return null}resyncPanelTopBarFromCurrentContent(){const e=this.getPanelContentElement();e&&this._syncPanelTopBarFromContent(e)}isPanelVisible(){return this._panelVisible}hasPanelContent(){return this._panelVisible&&this.getPanelContentElement()!==null}isPanelLoading(){return this._panelEl.querySelector(".gengage-chat-panel-skeleton")!==null}showPanelLoading(e){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._panelEl.innerHTML="",this._resetPanelAiZoneElement(),this._panelEl.appendChild(this._panelTopBar.getElement()),this._panelEl.appendChild(this._panelAiZoneEl);const t=document.createElement("div");t.className="gengage-chat-panel-skeleton";const a=e==="comparisonTable"?this.i18n.loadingSequenceComparison:this.i18n.loadingSequencePanel,{root:n,binding:r}=this._createLoadingSequence("panel",this._thinkingSteps.length>0?this._thinkingSteps.slice(-3):a,"panel-loading-status","gengage-chat-panel-loading-status");switch(this._panelLoadingBinding=r,e){case"productDetails":{t.appendChild(n);const i=document.createElement("div");i.className="gengage-chat-panel-skeleton-block gengage-chat-panel-skeleton-block--image",t.appendChild(i);for(let o=0;o<3;o++){const s=document.createElement("div");s.className="gengage-chat-panel-skeleton-block gengage-chat-panel-skeleton-block--text",t.appendChild(s)}break}case"productList":case"groupList":{t.appendChild(n);const i=document.createElement("div");i.className="gengage-chat-panel-skeleton-grid";for(let o=0;o<6;o++){const s=document.createElement("div");s.className="gengage-chat-panel-skeleton-block gengage-chat-panel-skeleton-block--card",i.appendChild(s)}t.appendChild(i);break}case"comparisonTable":{t.classList.add("gengage-chat-panel-skeleton--comparison"),t.appendChild(n);const i=document.createElement("div");i.className="gengage-chat-comparison gengage-chat-comparison--skeleton",i.setAttribute("aria-busy","true");const o=document.createElement("div");o.className="gengage-chat-comparison-recommended";const s=document.createElement("div");s.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-label",o.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-comparison-recommended-body";const l=document.createElement("div");l.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-img",l.setAttribute("aria-hidden","true");const g=document.createElement("div");g.className="gengage-chat-comparison-recommended-info";for(let P=0;P<2;P++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",P===1&&I.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(I)}const p=document.createElement("div");p.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-price",g.appendChild(p),c.appendChild(l),c.appendChild(g),o.appendChild(c);const h=document.createElement("div");h.className="gengage-chat-comparison-highlights";const d=document.createElement("div");d.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",h.appendChild(d);const b=document.createElement("ul");b.className="gengage-chat-comparison-skeleton-hl-list";for(let P=0;P<3;P++){const I=document.createElement("li"),F=document.createElement("div");F.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",P===1&&F.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),P===2&&F.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),I.appendChild(F),b.appendChild(I)}h.appendChild(b),o.appendChild(h),i.appendChild(o);const u=document.createElement("div");u.className="gengage-chat-comparison-key-differences";const f=document.createElement("div");f.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-heading",u.appendChild(f);const m=document.createElement("div");m.className="gengage-chat-comparison-key-differences-content";for(let P=0;P<4;P++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",m.appendChild(I)}u.appendChild(m),i.appendChild(u);const y=document.createElement("div");y.className="gengage-chat-comparison-special gengage-chat-comparison-special--skeleton";const k=document.createElement("div");k.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-special-line",y.appendChild(k),i.appendChild(y);const _=document.createElement("div");_.className="gengage-chat-comparison-skeleton-table-wrap";const x=document.createElement("div");x.className="gengage-chat-comparison-skeleton-table-head";const T=document.createElement("div");T.className="gengage-chat-comparison-skeleton-table-corner",x.appendChild(T);for(let P=0;P<3;P++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-col";const F=document.createElement("div");F.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const X=document.createElement("div");X.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const ne=document.createElement("div");ne.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",I.appendChild(F),I.appendChild(X),I.appendChild(ne),x.appendChild(I)}_.appendChild(x);for(let P=0;P<3;P++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-row";const F=document.createElement("div");F.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",I.appendChild(F);for(let X=0;X<3;X++){const ne=document.createElement("div");ne.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",I.appendChild(ne)}_.appendChild(I)}i.appendChild(_),t.appendChild(i);break}default:t.appendChild(n);for(let i=0;i<3;i++){const o=document.createElement("div");o.className="gengage-chat-panel-skeleton-block",t.appendChild(o)}break}this._panelEl.appendChild(t),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel"),this._syncDividerPreview(),this._emitHostShellSync()}updatePanelTopBar(e,t,a){const n=this._options.getMobileViewport?.()??!1;this._panelTopBar.update(n?!0:e,t,a);const r=this.getPanelContentElement();r&&this._syncPanelTopBarTitleFromContent(r)}getPanelTopBarTitle(){return this._panelTopBar.getTitle()}updateFavoritesBadge(e){this._favBadgeEl&&(e>0?(this._favBadgeEl.textContent=e>99?"99+":String(e),this._favBadgeEl.style.display=""):this._favBadgeEl.style.display="none")}clearPanel(){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelEl.innerHTML="",this._resetPanelAiZoneElement(),this._panelEl.appendChild(this._panelTopBar.getElement()),this._panelEl.appendChild(this._panelAiZoneEl),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelTopBar.setActions(null),this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible","gengage-chat-panel--collapsed"),this.root.classList.remove("gengage-chat-drawer--with-panel"),this._dividerEl.classList.add("gengage-chat-panel-divider--hidden"),this._dividerPreviewEnabled=!1,this._syncDividerPreview(),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this.setComparisonDockContent(null),this._emitHostShellSync()}setComparisonDockContent(e){this._comparisonDockSlotEl.replaceChildren(),e&&this._comparisonDockSlotEl.appendChild(e)}hideMobilePanel(){this._panelVisible&&(this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="flex"),this._emitHostShellSync())}_showMobilePanelFromBtn(){this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync())}expandPanel(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._syncDividerPreview(),this._emitHostShellSync()}setForceExpanded(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._syncDividerPreview(),this._emitHostShellSync()}_smoothScrollPanelListToTop(){this._panelEl.scrollTop=0}_updateScrollAffordance(){const e=this._panelEl,t=e.scrollTop+e.clientHeight>=e.scrollHeight-10;e.classList.toggle("gengage-chat-panel--has-scroll",!t&&e.scrollHeight>e.clientHeight),e.classList.toggle("gengage-chat-panel--scrolled",e.scrollTop>88)}_setupHorizontalSwipe(e){let t=0,a=0;const n=i=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const o=i.touches[0];o&&(t=o.clientX,a=o.clientY)},r=i=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const o=i.changedTouches[0];if(!o)return;const s=o.clientX-t,c=o.clientY-a;Math.abs(s)>50&&Math.abs(s)>Math.abs(c)*2&&(this.togglePanel(),this._onPanelToggle?.())};e.addEventListener("touchstart",n,{passive:!0}),e.addEventListener("touchend",r,{passive:!0}),this._cleanups.push(()=>{e.removeEventListener("touchstart",n),e.removeEventListener("touchend",r)})}togglePanel(){this.setPanelCollapsed(!this._panelCollapsed)}isPanelCollapsed(){return this._panelCollapsed}setPanelCollapsed(e){this._panelCollapsed=e,e?this._panelEl.classList.add("gengage-chat-panel--collapsed"):this._panelEl.classList.remove("gengage-chat-panel--collapsed");const t=this._dividerEl.querySelector(".gengage-chat-panel-divider-toggle");t&&(t.textContent=e?"«":"»"),this._syncDividerPreview(),this._emitHostShellSync()}setDividerPreviewEnabled(e){this._dividerPreviewEnabled=e,this._syncDividerPreview()}persistPanelState(e){try{const t=`gengage:panel:${e}`;this._panelCollapsed?sessionStorage.setItem(t,"collapsed"):sessionStorage.removeItem(t)}catch{}}restorePanelState(e){try{const t=`gengage:panel:${e}`;if(sessionStorage.getItem(t)==="collapsed")return this._panelCollapsed=!0,!0}catch{}return!1}_createLoadingSequence(e,t,a,n){const r=document.createElement("div");r.className=`${n} gds-progress-loader ${e==="chat"?"gds-progress-loader-chat":"gds-progress-loader-panel"}`,r.dataset.gengagePart=a,r.setAttribute("role","status"),r.setAttribute("aria-live","polite");const i=document.createElement("span");i.className=e==="chat"?"gengage-chat-typing-text gds-progress-label":"gengage-chat-panel-loading-label gds-progress-label",r.appendChild(i);const o=document.createElement("span");o.className=e==="chat"?"gengage-chat-typing-dots gds-progress-dots":"gds-progress-dots",o.setAttribute("aria-hidden","true");for(let c=0;c<3;c++){const l=document.createElement("span");l.className="gds-progress-dot",o.appendChild(l)}r.appendChild(o);const s={labelEl:i,steps:[],index:0,intervalId:null};return this._applyLoadingSteps(s,t),{root:r,binding:s}}_applyLoadingSteps(e,t,a=!1){const n=t.map(i=>i.trim()).filter(Boolean).slice(-3),r=[this.i18n.loadingMessage];e.steps=n.length>0?n:r,this._clearLoadingBindingInterval(e),e.index=a?e.steps.length-1:0,e.labelEl.textContent=e.steps[e.index],!a&&e.steps.length>1&&(e.intervalId=setInterval(()=>{if(e.index>=e.steps.length-1){this._clearLoadingBindingInterval(e);return}e.index+=1,e.labelEl.textContent=e.steps[e.index],e.index>=e.steps.length-1&&this._clearLoadingBindingInterval(e)},oc))}_clearLoadingBindingInterval(e){e?.intervalId&&(clearInterval(e.intervalId),e.intervalId=null)}_destroyLoadingBinding(e){this._clearLoadingBindingInterval(e)}_updateSendEnabled(){if(this._sendStopHandler){this.sendBtn.disabled=!1;return}const e=this.inputEl.value.trim().length>0||this._pendingAttachment!==null;this.sendBtn.disabled=!e}_renderSendButtonIcon(e){this.sendBtn.innerHTML=e==="stop"?'<span class="gengage-chat-send-stop-icon" aria-hidden="true"></span>':'<svg viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>'}_submit(){const e=this.inputEl.value.trim(),t=this._pendingAttachment;if(this._sendStopHandler){const a=this._sendStopHandler;if(this.hideStopButton(),a(),!e&&!t)return}else if(!e&&!t)return;this.onSend(e,t??void 0),this.inputEl.value="",this.inputEl.style.height="auto",this.clearAttachment(),this._updateSendEnabled()}_toggleVoice(){if(this._voiceInput)if(this._voiceInput.state==="listening"){const e=this._voiceInput.stop();e.trim()&&(this.inputEl.value=e,this._submit())}else this.inputEl.value="",this._voiceInput.start()}lockScrollForRestore(){this._scrollLockedUntil=Date.now()+500}_scrollToBottom(e=!1){!e&&this._userScrolledUp||!e&&this._options.presentation?.shouldBlockSoftAutoScroll?.()||!e&&Date.now()<this._scrollLockedUntil||requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight,this._userScrolledUp=!1})}scrollToBottomIfNeeded(){this._scrollToBottom(!1)}updateBotMessage(e,t,a,n){const r=this.messagesEl.querySelector(`[data-message-id="${ve(e)}"]`);if(!r)return;let i=r.querySelector(".gengage-chat-bubble-text");i||(i=document.createElement("div"),i.className="gengage-chat-bubble-text",r.appendChild(i)),a==="photo_analysis"?(r.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(i,n)):(r.classList.remove("gengage-chat-bubble--photo-analysis"),i.innerHTML=ke(t)),this._scrollToBottom(!1)}markFirstBotMessage(e){this._firstBotMessageIds.add(e);const t=this.messagesEl.querySelector(`[data-message-id="${ve(e)}"]`);t&&t.classList.add("gengage-chat-bubble--first")}scrollToLastThread(){const e=this.messagesEl.querySelectorAll("[data-thread-id]");if(e.length===0){this._scrollToBottom(!0);return}const t=e[e.length-1].getAttribute("data-thread-id");if(!t){this._scrollToBottom(!0);return}this._programmaticScrollUntil=Date.now()+700;const a=this.messagesEl.querySelector(`[data-thread-id="${ve(t)}"]`);a?requestAnimationFrame(()=>{a.scrollIntoView({block:"start",behavior:"auto"}),this._userScrolledUp=!1}):this._scrollToBottom(!0)}scrollThreadIntoView(e,t="smooth"){const a=this.messagesEl.querySelectorAll(`[data-thread-id="${ve(e)}"]`);let n=null,r=null;for(let s=0;s<a.length;s++){const c=a[s];if(c instanceof HTMLElement&&(r||(r=c),!c.classList.contains("gengage-chat-bubble--presentation-collapsed")&&!c.classList.contains("gengage-chat-bubble--hidden")&&c.offsetHeight!==0&&!(c.classList.contains("gengage-chat-bubble--assistant")&&(c.textContent?.trim().length??0)===0))){n=c;break}}if(n||(n=r),!n)return!1;const i=Date.now();this._programmaticScrollUntil=i+Pn,this._scrollLockedUntil=Math.max(this._scrollLockedUntil,i+Pn),this._userScrolledUp=!0;const o=()=>{this._scrollMessagesTo(Math.max(n.offsetTop-20,0),t)};return o(),requestAnimationFrame(o),!0}scrollToBottomPresentation(e="smooth"){this._programmaticScrollUntil=Date.now()+700,requestAnimationFrame(()=>{this._scrollMessagesTo(this.messagesEl.scrollHeight,e),this._userScrolledUp=!1})}_scrollMessagesTo(e,t){if(typeof this.messagesEl.scrollTo=="function"){this.messagesEl.scrollTo({top:e,behavior:t});return}this.messagesEl.scrollTop=e}setPresentationFocus(e){this._presentationFocusThreadId=e,this._applyPresentationCollapsed()}setFormerMessagesButtonVisible(e){this._formerMessagesBtn&&(this._formerMessagesBtn.style.display=e?"":"none")}setInputPlaceholder(e){this.inputEl.placeholder=e}_applyPresentationCollapsed(){const e=this._presentationFocusThreadId;this.messagesEl.querySelectorAll("[data-thread-id]").forEach(t=>{const a=t.dataset.threadId;a&&(e&&a!==e?t.classList.add("gengage-chat-bubble--presentation-collapsed"):t.classList.remove("gengage-chat-bubble--presentation-collapsed"))})}refreshPresentationCollapsed(){this._presentationFocusThreadId&&this._applyPresentationCollapsed()}setInputAreaChips(e){if(this._inputChipsEl.innerHTML="",e.length===0){this._inputChipsEl.style.display="none";return}this._inputChipsEl.style.display="";for(const t of e){const a=document.createElement("button");if(a.className="gengage-chat-input-chip gds-chip",a.type="button",t.icon){const r=En[t.icon]??'<svg viewBox="0 0 16 16" class="gengage-chat-icon"><path d="M3 8h10M9 4l4 4-4 4" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>',i=document.createElement("span");i.className="gengage-chat-input-chip-icon",i.innerHTML=r,a.appendChild(i)}const n=document.createElement("span");n.textContent=t.label,a.appendChild(n),a.addEventListener("click",()=>t.onAction()),this._inputChipsEl.appendChild(a)}}clearInputAreaChips(){this._inputChipsEl.innerHTML="",this._inputChipsEl.style.display="none"}setThumbnails(e){this._thumbnailsColumn.setEntries(e),e.length>0?this._thumbnailsColumn.show():this._thumbnailsColumn.hide(),this._renderDividerPreview(e),this._syncDividerPreview()}hideThumbnails(){this._thumbnailsColumn.hide(),this._renderDividerPreview([]),this._syncDividerPreview()}_renderDividerPreview(e){this._dividerPreviewEl.innerHTML="";const t=new Set,a=[];for(let n=e.length-1;n>=0;n--){const r=e[n];if(!(!r||t.has(r.sku)||!we(r.imageUrl))&&(t.add(r.sku),a.push(r),a.length>=3))break}a.reverse();for(const n of a){const r=document.createElement("span");r.className="gengage-chat-panel-divider-preview-thumb";const i=document.createElement("img");i.className="gengage-chat-panel-divider-preview-img",i.src=n.imageUrl,i.alt="",i.width=48,i.height=48,r.appendChild(i),this._dividerPreviewEl.appendChild(r)}}_syncDividerPreview(){const e=this._dividerPreviewEl.childElementCount>0,t=this._dividerPreviewEnabled&&e&&this._panelCollapsed&&!this._dividerEl.classList.contains("gengage-chat-panel-divider--hidden");this._dividerEl.classList.toggle("gengage-chat-panel-divider--preview-active",t)}trapFocus(){this._previouslyFocusedElement=document.activeElement,this.releaseFocus();const e=t=>{if(t.key!=="Tab")return;const a=Array.from(this.root.querySelectorAll('a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter(l=>{const g=getComputedStyle(l);return l.hidden||l.getAttribute("aria-hidden")==="true"||g.display==="none"||g.visibility==="hidden"?!1:l.getClientRects().length>0});if(a.length===0)return;const n=a[0],r=a[a.length-1],i=t.composedPath().find(l=>l instanceof HTMLElement&&this.root.contains(l))??null,o=this.root.getRootNode(),s=i??(o instanceof ShadowRoot&&o.activeElement instanceof HTMLElement?o.activeElement:document.activeElement instanceof HTMLElement?document.activeElement:null),c=s&&this.root.contains(s)?s:null;t.shiftKey?(c===n||!this.root.contains(c))&&(t.preventDefault(),r.focus()):(c===r||!this.root.contains(c))&&(t.preventDefault(),n.focus())};this._focusTrapHandler=e,this.root.addEventListener("keydown",e)}releaseFocus(){if(this._focusTrapHandler&&(this.root.removeEventListener("keydown",this._focusTrapHandler),this._focusTrapHandler=null),this._previouslyFocusedElement){try{this._previouslyFocusedElement.focus()}catch{}this._previouslyFocusedElement=null}}flashCartBadge(){this._cartBtn&&(this._cartBtn.classList.remove("gengage-chat-header-btn--cart-flash"),this._cartBtn.offsetWidth,this._cartBtn.classList.add("gengage-chat-header-btn--cart-flash"),this._cartBtn.addEventListener("animationend",()=>{this._cartBtn?.classList.remove("gengage-chat-header-btn--cart-flash")},{once:!0}))}showCartToast(e){this.root.querySelector(".gengage-chat-cart-toast")?.remove();const t=document.createElement("div");t.className="gengage-chat-cart-toast",t.setAttribute("role","status"),t.setAttribute("aria-live","polite"),t.textContent=e,this.root.appendChild(t),t.offsetWidth,t.classList.add("gengage-chat-cart-toast--visible"),setTimeout(()=>{t.classList.remove("gengage-chat-cart-toast--visible"),setTimeout(()=>t.remove(),300)},2500)}destroy(){_n(null),this.releaseFocus(),this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this._destroyLoadingBinding(this._typingLoadingBinding),this._typingLoadingBinding=null,this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._closeAttachMenu();for(const e of this._cleanups)e();this._cleanups.length=0,this._voiceInput?.destroy(),this._voiceInput=null}},Tn=["beauty_consulting","watch_expert","booking"],gc=["shopping",...Tn];function pc(e){return typeof e=="string"&&gc.includes(e)?e:null}function pa(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function hc(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function uc(e){const t=pa(e);if(!t)return null;const a=hc(t.assistant_mode,t.assistantMode);return!a||!Tn.includes(a)?null:a}var mc=class{constructor(){this._mode="shopping",this._uiHints=null}get mode(){return this._mode}set mode(e){this._mode=e}get uiHints(){return this._uiHints}set uiHints(e){this._uiHints=e}get isShopping(){return this._mode==="shopping"}get isBeautyConsulting(){return this._mode==="beauty_consulting"}get isChoicePrompterHidden(){return this._uiHints?.hide_choice_prompter===!0}applyUiHints(e,t,a){const n=i=>this._uiHints?.[i]===!0;e?.setAttachmentControlsVisible(!n("hide_attachment_controls")),n("hide_choice_prompter")&&a?.();const r=typeof this._uiHints?.input_placeholder=="string"?this._uiHints.input_placeholder:void 0;r?e?.setInputPlaceholder(r):e?.setInputPlaceholder(t)}handleRedirect(e){Ne("mode","redirect metadata received",e);const t=uc(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Ne("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=pc(t);a?this._mode=a:Ne("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=pa(e.ui_hints)??null}reset(){const e=this._mode!=="shopping";return this._mode="shopping",this._uiHints=null,e}resolveAttachmentActionType(){return this._mode==="beauty_consulting"?"user_message":"findSimilar"}shouldCondenseThinking(){return this._mode!=="shopping"}};function fc(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function bc(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=kn(t);return i?(r.photoAnalysis=i,r.renderHint="photo_analysis",n.ensureRendered(),n.cancelTypewriter(),n.drawer?.updateBotMessage(r.id,r.content??"","photo_analysis",r.photoAnalysis),!0):(Ne("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Xs(t);return n.drawer?.setBeautyPhotoStepCard({visible:!0,...i,onSkip:()=>{n.drawer?.setBeautyPhotoStepCard({visible:!1}),n.streamDone?n.sendSkipMessage():a.pendingPhotoStepSkip=!0}}),!0}return!1}function vc(e){return e.renderHint==="photo_analysis"}function yc(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function _c(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function ha(e){return Number.isFinite(e)?Math.max(0,Math.min(5,e)):0}function ua(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function ma(e){const t=ha(e),a=Math.floor(t),n=t-a>=.5,r=5-a-(n?1:0),i=document.createElement("span");if(i.className="gengage-star-rating",i.setAttribute("role","img"),i.setAttribute("aria-label",`${t.toFixed(1)} out of 5 stars`),a>0&&i.appendChild(document.createTextNode("★".repeat(a))),n){const o=document.createElement("span");o.className="gengage-star-half",o.textContent="☆";const s=document.createElement("span");s.textContent="★",o.appendChild(s),i.appendChild(o)}return r>0&&i.appendChild(document.createTextNode("☆".repeat(r))),i}function Se(e){e.addEventListener("error",()=>{e.style.display="none"},{once:!0})}var xc={currencyCode:"TRY",currencySymbol:"TL",currencyPosition:"suffix",thousandsSeparator:".",decimalSeparator:",",alwaysShowDecimals:!1};function K(e,t){const a=Number(e);if(!Number.isFinite(a)||a<0)return e;const n={...xc,...t},r=Math.abs(a%1)<Number.EPSILON,i=n.alwaysShowDecimals||!r?a.toFixed(2):a.toFixed(0),o=i.indexOf("."),s=o===-1?i:i.slice(0,o),c=o===-1?void 0:i.slice(o+1),l=s.replace(/\B(?=(\d{3})+(?!\d))/g,n.thousandsSeparator);let g;return c!==void 0?g=`${l}${n.decimalSeparator}${c}`:g=l,n.currencySymbol?n.currencyPosition==="prefix"?`${n.currencySymbol}${g}`:`${g} ${n.currencySymbol}`:g}var wc={screen_size:"Screen Size",weight:"Weight",battery_capacity:"Battery Capacity",battery_life:"Battery Life",storage:"Storage",memory:"Memory",ram:"RAM",processor:"Processor",camera:"Camera",resolution:"Resolution",display_type:"Display Type",refresh_rate:"Refresh Rate",color:"Color",material:"Material",dimensions:"Dimensions",warranty:"Warranty",connectivity:"Connectivity",water_resistance:"Water Resistance",operating_system:"Operating System",brand:"Brand",model:"Model",price:"Price",energy_class:"Energy Class",noise_level:"Noise Level",capacity:"Capacity",power:"Power",voltage:"Voltage",width:"Width",height:"Height",depth:"Depth"};function kc(e,t,a){return t?.[e]??wc[e]??e.replace(/_/g," ").replace(/^./u,n=>Cc(n,a))}function Cc(e,t){try{return e.toLocaleUpperCase(Ue(t))}catch{return e.toLocaleUpperCase("tr")}}function An(e){if(typeof e!="string")return!1;const t=Number(e);return Number.isFinite(t)&&t>0}function Sc(e){const t=typeof e=="number"?e:typeof e=="string"?Number(e):NaN;return Number.isFinite(t)&&t>0}function Ec(e){const t=typeof e=="number"?e:Number(e),a=document.createElement("div");a.className="gengage-chat-comparison-recommended-rating",a.innerHTML='<span class="gengage-chat-comparison-recommended-rating-icon" aria-hidden="true"><svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.6l2.58 5.23 5.77.84-4.17 4.07.98 5.75L12 16.78l-5.16 2.71.99-5.75L3.66 9.67l5.76-.84L12 3.6z"/></svg></span>';const n=document.createElement("span");return n.className="gengage-chat-comparison-recommended-rating-value",n.textContent=t.toFixed(1),a.appendChild(n),a}function Pc(e){const{recommended:t,products:a,attributes:n,highlights:r,specialCases:i,onProductClick:o,i18n:s}=e,c=document.createElement("div");if(c.className="gengage-chat-comparison",c.dataset.gengagePart="comparison-dialog",c.setAttribute("role","dialog"),c.setAttribute("aria-label",s?.comparisonHeading??"Comparison Results"),t){const l=document.createElement("article");l.className="gengage-chat-comparison-recommended gds-card",l.dataset.gengagePart="comparison-recommended-card";const g=document.createElement("div");g.className="gengage-chat-comparison-recommended-label",g.textContent=s?.recommendedChoiceLabel??"Recommended Choice",l.appendChild(g);const p=document.createElement("div");p.className="gengage-chat-comparison-recommended-body",p.classList.add("gds-clickable"),p.tabIndex=0,p.setAttribute("role","button"),p.setAttribute("aria-label",t.name);const h=document.createElement("div");if(h.className="gengage-chat-comparison-recommended-media",t.imageUrl&&we(t.imageUrl)){const m=document.createElement("img");m.src=t.imageUrl,m.alt=t.name,m.loading="lazy",m.addEventListener("error",()=>{m.style.display="none"},{once:!0}),h.appendChild(m)}else{const m=document.createElement("div");m.className="gengage-chat-comparison-recommended-placeholder",m.setAttribute("aria-hidden","true"),h.appendChild(m)}p.appendChild(h);const d=document.createElement("div");d.className="gengage-chat-comparison-recommended-info";const b=document.createElement("div");b.className="gengage-chat-comparison-recommended-title",b.textContent=t.name,d.appendChild(b);const u=document.createElement("div");if(u.className="gengage-chat-comparison-recommended-meta",Sc(t.rating)&&u.appendChild(Ec(t.rating)),An(t.price)){const m=document.createElement("div");m.className="gengage-chat-comparison-recommended-price",m.textContent=K(t.price,e.pricing),u.appendChild(m)}if(u.childElementCount>0&&d.appendChild(u),e.recommendedText){const m=document.createElement("p");m.className="gengage-chat-comparison-recommended-text",m.innerHTML=ke(e.recommendedText),d.appendChild(m)}p.appendChild(d);const f=()=>{o({sku:t.sku,name:t.name})};if(p.addEventListener("click",f),p.addEventListener("keydown",m=>{m.key!=="Enter"&&m.key!==" "||(m.preventDefault(),f())}),l.appendChild(p),r.length>0){const m=document.createElement("div");m.className="gengage-chat-comparison-highlights",m.dataset.gengagePart="comparison-highlights";const y=document.createElement("div");y.className="gengage-chat-comparison-highlights-label",y.textContent=s?.highlightsLabel??"Key Highlights",m.appendChild(y);const k=document.createElement("ul");for(const _ of r){const x=document.createElement("li");x.textContent=_,k.appendChild(x)}m.appendChild(k),l.appendChild(m)}c.appendChild(l)}if(e.keyDifferencesHtml){const l=document.createElement("details");l.className="gengage-chat-comparison-key-differences",l.dataset.gengagePart="comparison-key-differences";const g=document.createElement("summary");g.className="gengage-chat-comparison-key-differences-summary";const p=document.createElement("span");p.className="gengage-chat-comparison-key-differences-summary-label",p.textContent=s?.keyDifferencesLabel??"Key Differences";const h=document.createElement("span");h.className="gengage-chat-comparison-key-differences-summary-meta",h.textContent=s?.viewMoreLabel??"Show More",g.appendChild(p),g.appendChild(h),l.appendChild(g);const d=document.createElement("div");d.className="gengage-chat-comparison-key-differences-content",d.innerHTML=ke(Tc(e.keyDifferencesHtml)),l.appendChild(d),c.appendChild(l)}if(i&&i.length>0){const l=document.createElement("details");l.className="gengage-chat-comparison-special gds-evidence-card gds-evidence-card-warning",l.dataset.gengagePart="comparison-special-cases";const g=document.createElement("summary");g.textContent=s?.specialCasesLabel??"For Special Cases",l.appendChild(g);const p=document.createElement("ul");for(const h of i)Ac(p,h);p.childElementCount>0&&l.appendChild(p),c.appendChild(l)}if(a.length>0&&n.length>0){const l=document.createElement("table");l.className="gengage-chat-comparison-table gds-comparison-table";const g=document.createElement("thead"),p=document.createElement("tr"),h=document.createElement("th");p.appendChild(h);for(const u of a){const f=document.createElement("th");u.sku===t?.sku&&(f.className="gengage-chat-comparison-selected gds-comparison-table-winner-cell");const m=document.createElement("div");m.className="gengage-chat-comparison-table-header-cell gengage-chat-comparison-table-header-cell--clickable gds-clickable",m.tabIndex=0,m.setAttribute("role","button"),m.setAttribute("aria-label",u.name),m.title=u.name;const y=()=>{o({sku:u.sku,name:u.name})};if(m.addEventListener("click",y),m.addEventListener("keydown",_=>{_.key!=="Enter"&&_.key!==" "||(_.preventDefault(),y())}),u.imageUrl&&we(u.imageUrl)){const _=document.createElement("img");_.src=u.imageUrl,_.alt=u.name,_.loading="lazy",_.addEventListener("error",()=>{_.style.display="none"},{once:!0}),m.appendChild(_)}else{const _=document.createElement("div");_.className="gengage-chat-comparison-table-header-img-placeholder",_.setAttribute("aria-hidden","true"),m.appendChild(_)}const k=document.createElement("div");if(k.className="gengage-chat-comparison-table-product-name",k.textContent=u.name,m.appendChild(k),An(u.price)){const _=document.createElement("div");_.className="gengage-chat-comparison-table-price",_.textContent=K(u.price,e.pricing),m.appendChild(_)}f.appendChild(m),p.appendChild(f)}g.appendChild(p),l.appendChild(g);const d=document.createElement("tbody");for(const u of n){const f=document.createElement("tr"),m=document.createElement("td");m.className="gengage-chat-comparison-label",m.textContent=kc(u.label,s?.criteriaLabels,e.locale),f.appendChild(m);for(let y=0;y<u.values.length;y++){const k=document.createElement("td");a[y]?.sku===t?.sku&&(k.className="gengage-chat-comparison-selected gds-comparison-table-winner-cell");const _=u.values[y]??"";Ln(_)?k.innerHTML=ke(_):k.textContent=_,f.appendChild(k)}d.appendChild(f)}l.appendChild(d);const b=document.createElement("div");b.className="gengage-chat-comparison-table-wrapper",b.dataset.gengagePart="comparison-table-wrapper",b.appendChild(l),c.appendChild(b)}return c.addEventListener("keydown",l=>{if(l.key!=="Tab")return;const g=c.querySelectorAll('button, [href], input, [tabindex]:not([tabindex="-1"])');if(g.length===0)return;const p=g[0],h=g[g.length-1];l.shiftKey&&document.activeElement===p?(l.preventDefault(),h.focus()):!l.shiftKey&&document.activeElement===h&&(l.preventDefault(),p.focus())}),c}function Tc(e){if(/<[uo]l[\s>]/i.test(e)||/<li[\s>]/i.test(e))return e;const t=e.split(`
49
- `).filter(a=>a.trim());return t.length<=1?e:"<ul>"+t.map(a=>`<li>${a.trim()}</li>`).join("")+"</ul>"}function Ac(e,t){const a=ke(t);if(!a)return;const n=document.createElement("template");n.innerHTML=a;const r=Array.from(n.content.querySelectorAll("li"));if(r.length>0){for(const o of r){const s=document.createElement("li");s.innerHTML=ke(o.innerHTML),e.appendChild(s)}return}const i=document.createElement("li");Ln(t)?i.innerHTML=a:i.textContent=t,e.appendChild(i)}function Ln(e){return/<\/?[a-z][\s\S]*>/i.test(e)}function gt(e,t=18){const a="http://www.w3.org/2000/svg",n=document.createElementNS(a,"svg");n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true");for(const r of e){const i=document.createElementNS(a,"path");i.setAttribute("d",r),n.appendChild(i)}return n}var fa="General",In=220,Lc=6;function Ic(e){if(typeof e!="string")return[fa];const t=e.split(/[,;|/]+/).map(a=>a.trim().replace(/\s+/g," ")).filter(a=>a.length>0);return t.length===0?[fa]:Array.from(new Set(t.map(a=>a.toLocaleLowerCase()))).map(a=>t.find(n=>n.toLocaleLowerCase()===a)??fa)}function Nc(e){return e==="positive"||e==="negative"||e==="neutral"?e:"neutral"}function zc(e){if(typeof e!="string")return"";const t=e.trim().replace(/\s+/g," ");return t.length<=In?t:`${t.slice(0,In-3).trimEnd()}...`}function Mc(e){return e.positive>e.negative?"positive":e.negative>e.positive?"negative":"neutral"}function Bc(e){return gt(e==="positive"?["M7 17 17 7","M7 7h10v10"]:e==="negative"?["M7 7 17 17","M17 7v10H7"]:["M5 12h14"],14)}function Rc(e,t="1 customer mentions",a="customers mention"){return e===1?t:`${e} ${a}`}function Oc(e,t){const a=document.createElement("div");a.className="gengage-chat-review-highlights";const n=e.props?.reviews;if(!Array.isArray(n)||n.length===0){const u=document.createElement("div");return u.className="gengage-chat-review-empty",u.textContent=t?.emptyReviewsMessage??"No review summary found.",a.appendChild(u),a}const r=n.filter(u=>u!==null&&typeof u=="object"),i=new Map;for(const u of r){const f=Nc(u.review_class),m=zc(u.review_text),y=Ic(u.review_tag);for(const k of y){const _=k.toLocaleLowerCase();let x=i.get(_);if(x||(x={key:_,label:k,mentions:0,positive:0,negative:0,neutral:0,snippets:[]},i.set(_,x)),x.mentions+=1,f==="positive"?x.positive+=1:f==="negative"?x.negative+=1:x.neutral+=1,m.length>0&&x.snippets.length<Lc&&!x.snippets.some(T=>T.text===m)){const T={text:m,tone:f};u.review_rating!==void 0&&String(u.review_rating).length>0&&(T.rating=u.review_rating),x.snippets.push(T)}}}const o=Array.from(i.values()).sort((u,f)=>f.mentions!==u.mentions?f.mentions-u.mentions:u.label.localeCompare(f.label));if(o.length===0){const u=document.createElement("div");return u.className="gengage-chat-review-empty",u.textContent=t?.emptyReviewsMessage??"No review summary found.",a.appendChild(u),a}const s=(t?.reviewFilterPositive??"positive").toLowerCase(),c=(t?.reviewFilterNegative??"negative").toLowerCase(),l=document.createElement("div");l.className="gengage-chat-review-subjects-heading",l.textContent=t?.reviewSubjectsHeading??"Select to learn more",a.appendChild(l);let g=o[0]?.key??null;const p=document.createElement("div");p.className="gengage-chat-review-subjects gds-toolbar gds-toolbar-compact";const h=document.createElement("section");h.className="gengage-chat-review-detail gds-evidence-card";const d=()=>{for(;h.firstChild;)h.removeChild(h.firstChild);if(!g)return;const u=o.find(k=>k.key===g);if(!u)return;const f=document.createElement("div");f.className="gengage-chat-review-detail-meta";const m=document.createElement("span");if(m.className="gengage-chat-review-detail-mentions",m.textContent=`${Rc(u.mentions,t?.reviewCustomersMentionSingular,t?.reviewCustomersMentionPlural)} "${u.label}"`,f.appendChild(m),u.positive>0){const k=document.createElement("span");k.className="gengage-chat-review-detail-positive",k.textContent=`${u.positive} ${s}`,f.appendChild(k)}if(u.negative>0){const k=document.createElement("span");k.className="gengage-chat-review-detail-negative",k.textContent=`${u.negative} ${c}`,f.appendChild(k)}h.appendChild(f);const y=document.createElement("div");y.className="gengage-chat-review-snippets";for(const k of u.snippets){const _=document.createElement("article");_.className="gengage-chat-review-snippet",_.dataset.tone=k.tone;const x=document.createElement("div");if(x.className="gengage-chat-review-snippet-text",x.textContent=`"${k.text}"`,_.appendChild(x),k.rating!==void 0&&String(k.rating).length>0){const T=document.createElement("div");T.className="gengage-chat-review-snippet-rating",T.textContent=`★ ${String(k.rating)}`,_.appendChild(T)}y.appendChild(_)}h.appendChild(y)},b=()=>{for(const u of p.querySelectorAll(".gengage-chat-review-subject")){const f=u.dataset.subjectKey===g;u.classList.toggle("gengage-chat-review-subject--active",f),u.classList.toggle("gds-chip-active",f),u.setAttribute("aria-pressed",String(f))}};for(const u of o){const f=Mc(u),m=document.createElement("button");m.type="button",m.className="gengage-chat-review-subject gds-chip",m.dataset.subjectKey=u.key,m.dataset.tone=f;const y=document.createElement("span");y.className="gengage-chat-review-subject-icon",y.appendChild(Bc(f)),m.appendChild(y);const k=document.createElement("span");k.className="gengage-chat-review-subject-label",k.textContent=u.label,m.appendChild(k);const _=document.createElement("span");_.className="gengage-chat-review-subject-count",_.textContent=`(${u.mentions})`,m.appendChild(_),m.addEventListener("click",()=>{g=u.key,b(),d()}),p.appendChild(m)}return a.appendChild(p),b(),d(),a.appendChild(h),a}function Dc(e){if(!e)return;const t=e.discountReason??e.discount_reason??e.campaignReason??e.campaign_reason;if(typeof t!="string")return;const a=t.trim();return a.length>0?a:void 0}function et(e,t){if(e.productPriceUi?.showCampaignReason===!0)return Dc(t)}function pt(e,t){const a=t?.originalPriceStyle??t?.price_original_style;if(a==="inline"||a==="strikethrough")return a;const n=e.productPriceUi?.originalPriceStyle;return n==="inline"||n==="strikethrough"?n:"strikethrough"}function Pt(e){const t=document.createElement("div");return t.className="gengage-chat-campaign-reason",t.textContent=e,t}function Tt(e,t){for(const n of["campaignReasonLogoUrl","campaign_reason_logo_url","discountBadgeLogoUrl","discount_badge_logo_url"]){const r=t?.[n];if(typeof r=="string"&&r.trim()){const i=r.trim();if(we(i))return i}}const a=e.productPriceUi?.campaignBadgeLogoUrl;if(typeof a=="string"&&a.trim()){const n=a.trim();if(we(n))return n}}function At(e){const t=document.createElement("div");if(t.className="gengage-chat-campaign-price-badge",t.dataset.gengagePart="campaign-price-badge",e.logoUrl){const i=document.createElement("div");i.className="gengage-chat-campaign-price-badge__logo";const o=document.createElement("img");o.alt="",o.loading="lazy",o.src=e.logoUrl,Se(o),i.appendChild(o),t.appendChild(i)}const a=document.createElement("div");a.className="gengage-chat-campaign-price-badge__body";const n=document.createElement("div");n.className="gengage-chat-campaign-price-badge__reason",n.textContent=e.reasonText;const r=document.createElement("span");return r.className="gengage-chat-campaign-price-badge__sale",r.textContent=e.salePriceFormatted,a.appendChild(n),a.appendChild(r),t.appendChild(a),t}function Nn(e){const t=e.product.sku;if(typeof t=="string"&&t.length>0)return t;const a=e.action?.payload;return a&&typeof a=="object"&&"sku"in a&&typeof a.sku=="string"?a.sku:null}var Fc={winner:"roleWinner",best_value:"roleBestValue",best_alternative:"roleBestAlternative"};function zn(e,t){if(!e||!t)return null;const a=Fc[e];return a?t[a]??e:e}function Uc(e){const t=e.rating,a=typeof t=="number"?t:typeof t=="string"?parseFloat(t):NaN;if(Number.isNaN(a)||a<=0)return null;const n=document.createElement("div");n.className="gengage-chat-ai-toppick-rating",n.dataset.gengagePart="ai-top-pick-rating";const r=document.createElement("span");r.className="gengage-chat-ai-toppick-rating-icon",r.setAttribute("aria-hidden","true"),r.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.6l2.58 5.23 5.77.84-4.17 4.07.98 5.75L12 16.78l-5.16 2.71.99-5.75L3.66 9.67l5.76-.84L12 3.6z"/></svg>';const i=document.createElement("span");return i.className="gengage-chat-ai-toppick-rating-value",i.textContent=a.toFixed(1),n.appendChild(r),n.appendChild(i),n}function $c(e,t,a,n,r){const i=document.createElement("div");i.className="gengage-chat-ai-toppick-media",i.dataset.gengagePart="ai-top-pick-media";const o=e.product,s=o.imageUrl;if(s&&we(s)){const l=document.createElement("img");l.className="gengage-chat-ai-toppick-img",l.dataset.gengagePart="ai-top-pick-image",ue(l,"src",s),l.loading="lazy",l.alt=t,Se(l),i.appendChild(l)}const c=Nn(e);if(c&&!r?.skipOverlayActions){const l=document.createElement("div");if(l.className="gengage-chat-product-card-img-actions",n.onFavoriteToggle){const d=document.createElement("button");d.className="gengage-chat-favorite-btn",d.type="button",d.dataset.gengageFavoriteSku=c,d.setAttribute("aria-label",n.i18n?.addToFavoritesLabel??"Add to favorites");const b=n.favoritedSkus?.has(c)??!1;b&&d.classList.add("gengage-chat-favorite-btn--active"),d.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${b?"currentColor":"none"}" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>`,d.addEventListener("click",u=>{u.stopPropagation(),d.classList.toggle("gengage-chat-favorite-btn--active"),d.querySelector("svg")?.setAttribute("fill",d.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),n.onFavoriteToggle?.(c,o)}),l.appendChild(d)}const g=n.i18n?.findSimilarLabel??"Find Similar",p=document.createElement("button");p.className="gengage-chat-find-similar-pill",p.type="button",p.setAttribute("aria-label",g),p.dataset.tooltip=g,p.innerHTML='<span class="gengage-chat-find-similar-pill-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="6.5"/><path d="M16 16l5.5 5.5"/></svg></span>';const h=document.createElement("span");h.className="gengage-chat-find-similar-pill-text",h.textContent=g,p.appendChild(h),p.addEventListener("click",d=>{d.stopPropagation(),n.onAction({title:g,type:"findSimilar",payload:{sku:c,...s?{image_url:s}:{}}})}),l.appendChild(p),i.appendChild(l)}a.appendChild(i)}function Hc(e,t,a){const n=e.price,r=e.originalPrice;if(!n)return;const i=et(a,e),o=pt(a,e),s=!!(r&&r!==n),c=!!(i&&s),l=Tt(a,e),g=document.createElement("div");if(g.className="gengage-chat-ai-toppick-price",g.dataset.gengagePart="ai-top-pick-price",c){const p=At({reasonText:i,salePriceFormatted:K(n,a.pricing),...l!==void 0?{logoUrl:l}:{}});if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline"),g.appendChild(p);const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=K(r,a.pricing),g.appendChild(h),g.appendChild(d)}else{const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=K(r,a.pricing),g.appendChild(h),g.appendChild(document.createTextNode(" ")),g.appendChild(p)}t.appendChild(g);return}if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline");const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=K(n,a.pricing);const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=K(r,a.pricing),g.appendChild(p),g.appendChild(h),g.appendChild(d)}else if(s){const p=document.createElement("span");p.className="gengage-chat-ai-toppick-original-price",p.textContent=K(r,a.pricing),g.appendChild(p),g.appendChild(document.createTextNode(" "));const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-current",h.textContent=K(n,a.pricing),g.appendChild(h)}else{const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=K(n,a.pricing),g.appendChild(p)}if(i){const p=document.createElement("div");p.className="gengage-chat-ai-toppick-price-stack",p.appendChild(Pt(i)),p.appendChild(g),t.appendChild(p)}else t.appendChild(g)}function qc(e,t){const a=typeof e.reason=="string"?e.reason.trim():"",n=typeof e.reviewHighlight=="string"?e.reviewHighlight.trim():"";if(!(!a&&!n)){if(a){const r=document.createElement("p");r.className="gengage-chat-ai-toppick-reason",r.dataset.gengagePart="ai-top-pick-reason",r.textContent=a,t.appendChild(r)}if(n){const r=document.createElement("div");r.className="gengage-chat-ai-toppick-review",r.dataset.gengagePart="ai-top-pick-review",r.textContent=n,t.appendChild(r)}}}function Mn(e,t,a){const n=document.createElement("div");n.className=a?"gengage-chat-ai-toppick-card gengage-chat-ai-toppick-card--winner gds-card":"gengage-chat-ai-toppick-card gengage-chat-ai-toppick-card--compact gds-card",n.dataset.gengagePart=a?"ai-top-pick-card-winner":"ai-top-pick-card";const r=e.product,i=Nn(e),o=r.url??"",s=r.cartCode,c=r.inStock,l=!!(i&&s&&c!==!1),g=e.action;i&&t.onProductClick?(n.classList.add("gds-clickable"),n.addEventListener("click",x=>{if(x.target.closest(".gengage-chat-ai-toppick-cta")||x.target.closest(".gengage-chat-favorite-btn")||x.target.closest(".gengage-chat-find-similar-pill"))return;const T=r.name;t.onProductClick?.({sku:i,url:o,...T?{name:T}:{}})})):g&&(n.classList.add("gds-clickable"),n.addEventListener("click",x=>{x.target.closest(".gengage-chat-ai-toppick-cta")||x.target.closest(".gengage-chat-favorite-btn")||x.target.closest(".gengage-chat-find-similar-pill")||t.onAction(g)}));const p=r.name||"Product image",h=!a&&t.isMobile===!0,d=a?zn(e.role,t.i18n)??t.i18n?.roleWinner??"TOP MATCH":zn(e.role,t.i18n);if(d&&!h){const x=document.createElement("span");x.className="gengage-chat-ai-toppick-badge gds-badge",x.dataset.gengagePart="ai-top-pick-role-badge",x.textContent=d,n.appendChild(x)}const b=document.createElement("div");b.className="gengage-chat-ai-toppick-top-row",b.dataset.gengagePart="ai-top-pick-top-row",$c(e,p,b,t,{skipOverlayActions:h});const u=document.createElement("div");if(u.className="gengage-chat-ai-toppick-body",u.dataset.gengagePart="ai-top-pick-body",d&&h){const x=document.createElement("div");x.className="gengage-chat-ai-toppick-role-line",x.dataset.gengagePart="ai-top-pick-role-line",x.textContent=d,u.appendChild(x)}const f=r.name;if(f){const x=document.createElement("div");x.className="gengage-chat-ai-toppick-name",x.dataset.gengagePart="ai-top-pick-name",x.textContent=f,u.appendChild(x)}const m=Uc(r);m&&u.appendChild(m),Hc(r,u,t),e.labels&&e.labels.length>0&&u.appendChild(Zc(e.labels)),b.appendChild(u),n.appendChild(b);const y=document.createElement("div");if(y.className="gengage-chat-ai-toppick-detail",y.dataset.gengagePart="ai-top-pick-detail",a)qc(e,y);else{const x=typeof e.reason=="string"?e.reason.trim():"";if(x){const T=document.createElement("p");T.className="gengage-chat-ai-toppick-snippet",T.dataset.gengagePart="ai-top-pick-snippet",T.textContent=x,y.appendChild(T)}}y.childNodes.length>0&&n.appendChild(y);const k=!!(i&&t.topPicksLoadingSku===i),_=(l||g)&&!h;if(k||l||g){const x=document.createElement("div");if(x.className="gengage-chat-ai-toppick-spinner",x.dataset.gengagePart="ai-top-pick-spinner",x.style.display=k?"":"none",n.appendChild(x),_){const T=document.createElement("button");T.className="gengage-chat-ai-toppick-cta gds-btn gds-btn-primary",T.dataset.gengagePart="ai-top-pick-cta",T.type="button",T.textContent=l?t.i18n?.addToCartButton??"Add to Cart":t.i18n?.viewDetails??"View Details",T.addEventListener("click",P=>{if(P.stopPropagation(),l){t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:i,cartCode:s,quantity:1}});return}if(g){if(g.type==="findSimilar"&&i&&t.onProductClick){const I=r.name;t.onProductClick({sku:i,url:o,...I?{name:I}:{}});return}t.onAction(g)}}),n.appendChild(T)}}return n}function jc(e,t){const a=document.createElement("div");a.className="gengage-chat-ai-top-picks",a.dataset.gengagePart="ai-top-picks";const n=e.props?.suggestions??[];if(n.length===0)return a;const r=document.createElement("div");r.className="gengage-chat-ai-top-picks-scroll",r.dataset.gengagePart="ai-top-picks-scroll";const i=n[0];if(r.appendChild(Mn(i,t,!0)),n.length>1){const o=document.createElement("div");o.className="gengage-chat-ai-top-picks-rest",o.dataset.gengagePart="ai-top-picks-rest";for(let s=1;s<n.length;s++){const c=n[s],l=c.role==="winner";o.appendChild(Mn(c,t,l))}r.appendChild(o)}return a.appendChild(r),a}function Zc(e){const t=document.createElement("div");t.className="gengage-chat-ai-toppick-labels",t.dataset.gengagePart="ai-top-pick-labels";for(const a of e){const n=document.createElement("span");n.className="gengage-chat-ai-toppick-label gds-chip",n.dataset.gengagePart="ai-top-pick-label",n.dataset.sentiment=a.sentiment??"neutral",n.textContent=a.label,t.appendChild(n)}return t}function Vc(e,t){const a=document.createElement("div");a.className="gengage-chat-grounding-review gds-evidence-card",a.dataset.gengagePart="grounding-review-card";const n=e.props??{},r=n.title,i=n.reviewCount,o=n.action,s=t.i18n?.groundingReviewCta??"Read Reviews",c=document.createElement("span");c.className="gengage-chat-grounding-review-icon",c.appendChild(gt(["M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z","M8 9h8","M8 13h6"])),a.appendChild(c);const l=document.createElement("div");l.className="gengage-chat-grounding-review-body",l.dataset.gengagePart="grounding-review-body";const g=document.createElement("div");if(g.className="gengage-chat-grounding-review-title",g.dataset.gengagePart="grounding-review-title",g.textContent=r??t.i18n?.customerReviewsTitle??"Customer Reviews",l.appendChild(g),i){const b=document.createElement("div");b.className="gengage-chat-grounding-review-subtitle",b.dataset.gengagePart="grounding-review-subtitle",b.textContent=(t.i18n?.groundingReviewSubtitle??"{count} yorum mevcut").replace("{count}",i),l.appendChild(b)}a.appendChild(l);const p=document.createElement("span");p.className="gengage-chat-grounding-review-cta",p.dataset.gengagePart="grounding-review-cta";const h=document.createElement("span");h.textContent=s,p.appendChild(h);const d=document.createElement("span");return d.className="gengage-chat-grounding-review-cta-icon",d.appendChild(gt(["M5 12h14","M15 8l4 4-4 4"],14)),p.appendChild(d),a.appendChild(p),o&&(a.classList.add("gds-clickable"),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t.onAction(o)),a.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),t.onAction(o))})),a}function Gc(e){if(e.action.type!=="findSimilar")return e.action;const t=e.action.payload&&typeof e.action.payload=="object"?e.action.payload:null,a=typeof t?.input=="string"&&t.input.trim()||typeof t?.text=="string"&&t.text.trim()||e.name.trim();if(!a)return e.action;const n={text:a,is_suggested_text:1};if(typeof t?.sku=="string"&&t.sku.trim()&&(n.sku=t.sku),Array.isArray(t?.group_skus)){const r=t.group_skus.filter(i=>typeof i=="string"&&i.length>0);r.length>0&&(n.group_skus=r)}return{title:e.action.title,type:"inputText",payload:n}}function Wc(e,t){const a=document.createElement("div");a.className="gengage-chat-grouping-cards",a.dataset.gengagePart="ai-grouping-cards";const n=e.props?.entries??[];if(n.length===0)return a;const r=e.props?.sectionTitle,i=typeof r=="string"&&r.trim().length>0?r.trim():t.i18n?.aiBrowseCategoriesTitle;if(i){const s=document.createElement("h3");s.className="gengage-chat-grouping-section-title",s.textContent=i,a.appendChild(s)}const o=document.createElement("div");o.className="gengage-chat-grouping-cards-scroll",o.dataset.gengagePart="ai-grouping-cards-scroll";for(const s of n){const c=document.createElement("div");if(c.className="gengage-chat-grouping-card gds-card",c.dataset.gengagePart="ai-grouping-card",c.classList.add("gds-clickable"),c.addEventListener("click",()=>t.onAction(Gc(s))),s.image&&we(s.image)){const h=document.createElement("img");h.className="gengage-chat-grouping-card-img",h.dataset.gengagePart="ai-grouping-card-image",h.draggable=!1,h.src=s.image,h.alt=s.name,h.width=64,h.height=64,c.appendChild(h)}const l=document.createElement("div");l.className="gengage-chat-grouping-card-body",l.dataset.gengagePart="ai-grouping-card-body";const g=document.createElement("span");if(g.className="gengage-chat-grouping-card-name",g.dataset.gengagePart="ai-grouping-card-name",g.textContent=s.name,l.appendChild(g),s.labels&&s.labels.length>0){const h=document.createElement("div");h.className="gengage-chat-grouping-card-labels",h.dataset.gengagePart="ai-grouping-card-labels";for(const d of s.labels.slice(0,2)){const b=document.createElement("span");b.className="gengage-chat-grouping-card-label gds-chip",b.textContent=d,h.appendChild(b)}l.appendChild(h)}c.appendChild(l);const p=document.createElement("span");p.className="gengage-chat-grouping-card-arrow",p.textContent="↳",c.insertBefore(p,c.firstChild),o.appendChild(c)}return a.appendChild(o),a}function Kc(e,t){const a=document.createElement("div");a.className="gengage-chat-suggested-search-cards",a.dataset.gengagePart="ai-suggested-search-cards";const n=e.props?.entries??[];if(n.length===0)return a;for(const r of n){const i=document.createElement("div");if(i.className="gengage-chat-suggested-search-card gds-card",i.dataset.gengagePart="ai-suggested-search-card",i.classList.add("gds-clickable"),i.addEventListener("click",()=>t.onAction(r.action)),r.image&&we(r.image)){const c=document.createElement("img");c.className="gengage-chat-suggested-search-card-img",c.dataset.gengagePart="ai-suggested-search-card-image",c.src=r.image,c.alt=r.shortName,c.width=64,c.height=64,i.appendChild(c)}const o=document.createElement("div");o.className="gengage-chat-suggested-search-card-body",o.dataset.gengagePart="ai-suggested-search-card-body";const s=document.createElement("div");s.className="gengage-chat-suggested-search-card-name",s.dataset.gengagePart="ai-suggested-search-card-name",s.textContent=r.shortName,o.appendChild(s),i.appendChild(o),a.appendChild(i)}return a}function Bn(e,t){const a=e.length>=2,n=t.i18n?.compareSelected??"Compare",r=t.comparisonSelectionWarning,i=document.createElement("div");i.className="gengage-chat-comparison-floating-btn",i.dataset.gengagePart="comparison-dock";const o=document.createElement("div");o.className="gengage-chat-comparison-floating-summary";const s=document.createElement("span");s.className="gengage-chat-comparison-floating-count",s.textContent=String(e.length),o.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-comparison-floating-copy";const l=document.createElement("div");if(l.className="gengage-chat-comparison-floating-title",l.textContent=a?`${n} (${e.length})`:t.i18n?.compareMinHint??"Select at least 2 products",c.appendChild(l),r){const p=document.createElement("div");p.className="gengage-chat-comparison-floating-warning",p.setAttribute("role","status"),p.setAttribute("aria-live","polite"),p.textContent=r,c.appendChild(p)}o.appendChild(c),i.appendChild(o);const g=document.createElement("button");if(g.className="gengage-chat-comparison-floating-action gds-btn gds-btn-primary",g.type="button",g.textContent=n,g.disabled=!a,a||g.classList.add("gengage-chat-comparison-floating-action--disabled"),g.addEventListener("click",()=>{a&&t.onAction({title:n,type:"getComparisonTable",payload:{sku_list:[...e],gengage_analytics_source:"floating_compare_dock"}})}),i.appendChild(g),t.onToggleComparisonSku){const p=document.createElement("button");p.className="gengage-chat-comparison-floating-close gds-btn gds-btn-ghost gds-icon-btn",p.dataset.gengagePart="comparison-dock-close",p.type="button",p.setAttribute("aria-label",t.i18n?.closeAriaLabel??"Close"),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>',p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),t.onToggleComparisonSku?.("")}),i.appendChild(p)}return i}function Yc(e){const t=document.createElement("div");t.className="gengage-chat-pros-cons gds-card-soft",t.dataset.gengagePart="pros-cons";const a=e.props?.productName;if(a){const i=document.createElement("h4");i.className="gengage-chat-pros-cons-heading",i.textContent=a,t.appendChild(i)}const n=e.props?.pros,r=e.props?.cons;if(n&&n.length>0){const i=document.createElement("ul");i.className="gengage-chat-pros-cons-list",i.dataset.gengagePart="pros-list";for(const o of n){const s=document.createElement("li");s.className="gengage-chat-pros-cons-item",s.dataset.gengagePart="pros-item";const c=document.createElement("span");c.className="gengage-chat-pros-cons-icon gengage-chat-pros-cons-icon--pro",c.textContent="✓",s.appendChild(c);const l=document.createElement("span");l.textContent=o,s.appendChild(l),i.appendChild(s)}t.appendChild(i)}if(r&&r.length>0){const i=document.createElement("ul");i.className="gengage-chat-pros-cons-list",i.dataset.gengagePart="cons-list";for(const o of r){const s=document.createElement("li");s.className="gengage-chat-pros-cons-item",s.dataset.gengagePart="cons-item";const c=document.createElement("span");c.className="gengage-chat-pros-cons-icon gengage-chat-pros-cons-icon--con",c.textContent="✗",s.appendChild(c);const l=document.createElement("span");l.textContent=o,s.appendChild(l),i.appendChild(s)}t.appendChild(i)}return t}function Jc(e,t){const a=e.props?.groups??[],n=e.props?.filterTags??[],r=document.createElement("div");if(r.className="gengage-chat-categories",r.dataset.gengagePart="categories-container",a.length===0)return r;const i=document.createElement("div");i.className="gengage-chat-categories-tabs gds-toolbar",i.dataset.gengagePart="categories-tab-bar",i.setAttribute("role","tablist");const o=[],s=[],c=l=>{for(let g=0;g<o.length;g++){const p=g===l;o[g].classList.toggle("gengage-chat-categories-tab--active",p),o[g].classList.toggle("is-active",p),o[g].setAttribute("aria-selected",String(p)),o[g].tabIndex=p?0:-1,s[g].style.display=p?"":"none"}};for(let l=0;l<a.length;l++){const g=a[l],p=`gengage-cat-tab-${l}`,h=`gengage-cat-panel-${l}`,d=document.createElement("button");if(d.className="gengage-chat-categories-tab gds-tab",d.type="button",d.dataset.gengagePart="categories-tab",d.id=p,d.setAttribute("role","tab"),d.setAttribute("aria-controls",h),d.setAttribute("aria-selected",String(l===0)),d.tabIndex=l===0?0:-1,l===0&&d.classList.add("gengage-chat-categories-tab--active","is-active"),g.image&&we(g.image)){const f=document.createElement("img");f.className="gengage-chat-categories-tab-image",f.draggable=!1,f.src=g.image,f.alt=g.groupName,f.loading="lazy",Se(f),d.appendChild(f)}const b=document.createElement("span");b.className="gengage-chat-categories-tab-text",b.textContent=g.groupName,d.appendChild(b),d.addEventListener("click",()=>c(l)),d.addEventListener("keydown",f=>{let m=-1;f.key==="ArrowRight"||f.key==="ArrowDown"?m=(l+1)%a.length:f.key==="ArrowLeft"||f.key==="ArrowUp"?m=(l-1+a.length)%a.length:f.key==="Home"?m=0:f.key==="End"&&(m=a.length-1),m>=0&&(f.preventDefault(),c(m),o[m].focus())}),o.push(d),i.appendChild(d);const u=document.createElement("div");u.className="gengage-chat-categories-grid",u.dataset.gengagePart="categories-panel",u.id=h,u.setAttribute("role","tabpanel"),u.setAttribute("aria-labelledby",p),l!==0&&(u.style.display="none");for(const f of g.products){const m=Qc(f,t);u.appendChild(m)}s.push(u)}r.appendChild(i);for(const l of s)r.appendChild(l);if(n.length>0){const l=document.createElement("div");l.className="gengage-chat-categories-filter-tags gds-toolbar",l.dataset.gengagePart="categories-filter-tags";for(const g of n){const p=document.createElement("button");p.className="gengage-chat-categories-filter-tag gds-chip",p.type="button",p.dataset.gengagePart="categories-filter-tag",p.textContent=g.title,g.action&&p.addEventListener("click",()=>{t.onAction(g.action)}),l.appendChild(p)}r.appendChild(l)}return r}function Qc(e,t){const a=document.createElement("div");if(a.className="gengage-chat-product-card gds-card gds-product-card gds-card-interactive",a.dataset.gengagePart="categories-product-card",e.imageUrl&&we(e.imageUrl)){const i=document.createElement("img");i.className="gengage-chat-product-card-img",i.draggable=!1,i.src=e.imageUrl,i.alt=e.name,i.loading="lazy",Se(i),a.appendChild(i)}const n=document.createElement("div");n.className="gengage-chat-product-card-body";const r=document.createElement("div");if(r.className="gengage-chat-product-card-name",r.textContent=e.name,n.appendChild(r),e.price){const i=document.createElement("div");i.className="gengage-chat-product-card-price",i.textContent=K(e.price,t.pricing),n.appendChild(i)}return a.appendChild(n),(t.onProductSelect||t.onAction)&&(a.classList.add("gds-clickable"),a.addEventListener("click",()=>{if(e.sku){t.onAction({title:e.name,type:"launchSingleProduct",payload:{sku:e.sku}});return}t.onProductSelect?.(e)})),a}function Xc(e,t){const a=document.createElement("div");a.className="gengage-chat-handoff-notice gds-evidence-card gds-evidence-card-warning",a.dataset.gengagePart="handoff-notice",a.setAttribute("role","alert");const n=document.createElement("span");n.className="gengage-chat-handoff-notice-icon",n.textContent="👤",n.setAttribute("aria-hidden","true"),a.appendChild(n);const r=document.createElement("h4");r.className="gengage-chat-handoff-notice-heading",r.textContent=t.i18n?.handoffHeading??"Transferring to a support agent",a.appendChild(r);const i=e.props?.summary;if(i){const o=document.createElement("p");o.className="gengage-chat-handoff-notice-summary",o.textContent=i,a.appendChild(o)}return a}function el(e,t){const a=e.props?.product??e.props,n=document.createElement("div");if(n.className="gengage-chat-product-summary gds-card",n.dataset.gengagePart="product-summary-card",!a)return n;n.classList.add("gds-clickable"),n.addEventListener("click",m=>{m.target.closest("a")||t.onProductSelect?.(a)});const r=a.imageUrl;if(r&&fe(r)){const m=document.createElement("div");m.className="gengage-chat-product-summary__image",m.dataset.gengagePart="product-summary-image";const y=document.createElement("img");y.loading="lazy",ue(y,"src",r),y.alt=a.name||"Product image",Se(y),m.appendChild(y),n.appendChild(m)}const i=document.createElement("div");i.className="gengage-chat-product-summary__content",i.dataset.gengagePart="product-summary-content";const o=a.brand,s=a.name;if(s){const m=document.createElement("div");m.className="gengage-chat-product-summary__name",m.dataset.gengagePart="product-summary-name";const y=o&&!s.toLowerCase().startsWith(o.toLowerCase())?`${o} ${s}`:s;m.textContent=y,m.title=y,i.appendChild(m)}const c=a.rating,l=a.reviewCount;if(typeof c=="number"&&Number.isFinite(c)&&c>0){const m=document.createElement("div");if(m.className="gengage-chat-product-summary__rating",m.dataset.gengagePart="product-summary-rating",m.appendChild(ma(c)),typeof l=="number"&&Number.isFinite(l)){const y=document.createElement("span");y.className="gengage-chat-product-summary__review-count",y.textContent=` (${l})`,m.appendChild(y)}i.appendChild(m)}const g=a.price,p=a.originalPrice;if(g){const m=et(t,a),y=pt(t,a),k=!!(p&&p!==g),_=document.createElement("div");_.className="gengage-chat-product-summary__price",_.dataset.gengagePart="product-summary-price";const x=!!(m&&k),T=Tt(t,a);if(x){const P=At({reasonText:m,salePriceFormatted:K(g,t.pricing),...T!==void 0?{logoUrl:T}:{}});if(k&&y==="inline"){_.classList.add("gengage-chat-product-summary__price--inline"),_.appendChild(P);const I=document.createElement("span");I.className="gengage-chat-product-summary__price-sep",I.setAttribute("aria-hidden","true");const F=document.createElement("span");F.className="gengage-chat-product-summary__price-original",F.textContent=K(p,t.pricing),_.appendChild(I),_.appendChild(F)}else{const I=document.createElement("span");I.className="gengage-chat-product-summary__price-original",I.textContent=K(p,t.pricing),_.appendChild(I),_.appendChild(document.createTextNode(" ")),_.appendChild(P)}i.appendChild(_)}else{if(k&&y==="inline"){_.classList.add("gengage-chat-product-summary__price--inline");const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=K(g,t.pricing);const I=document.createElement("span");I.className="gengage-chat-product-summary__price-sep",I.setAttribute("aria-hidden","true");const F=document.createElement("span");F.className="gengage-chat-product-summary__price-original",F.textContent=K(p,t.pricing),_.appendChild(P),_.appendChild(I),_.appendChild(F)}else if(k){const P=document.createElement("span");P.className="gengage-chat-product-summary__price-original",P.textContent=K(p,t.pricing),_.appendChild(P),_.appendChild(document.createTextNode(" "));const I=document.createElement("span");I.className="gengage-chat-product-summary__price-current",I.textContent=K(g,t.pricing),_.appendChild(I)}else{const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=K(g,t.pricing),_.appendChild(P)}if(m){const P=document.createElement("div");P.className="gengage-chat-product-summary__price-stack",P.appendChild(Pt(m)),P.appendChild(_),i.appendChild(P)}else i.appendChild(_)}}n.appendChild(i);const h=a.url,d=a.sku,b=a.cartCode??a.cart_code,u=typeof b=="string"&&b.trim()?b.trim():void 0,f=a.inStock;if(d&&u&&f!==!1){const m=document.createElement("button");m.type="button",m.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",m.dataset.gengagePart="product-summary-cta",m.textContent=t.i18n?.addToCartButton??"Add to Cart",m.addEventListener("click",y=>{y.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:d,cartCode:u,quantity:1}})}),n.appendChild(m)}else if(h&&fe(h)){const m=document.createElement("a");m.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",m.dataset.gengagePart="product-summary-cta",ue(m,"href",h),ue(m,"target","_blank"),ue(m,"rel","noopener noreferrer"),m.textContent=t.i18n?.productCtaLabel??"View",n.appendChild(m)}return n}var tl={PhotoAnalysisCard:({element:e,context:t})=>nc(e,t),BeautyPhotoStep:({element:e,context:t})=>wn(e,t)};function ba(){return window.innerWidth<768}var Rn={ActionButtons:({element:e,context:t})=>rl(e,t),ActionButton:({element:e,context:t})=>il(e,t),ProductCard:({element:e,context:t})=>va(e,t),ProductDetailsPanel:({element:e,context:t})=>El(e,t),ProductGrid:({element:e,spec:t,renderElement:a,context:n})=>Ml(e,t,a,n),ReviewHighlights:({element:e,context:t})=>Oc(e,{emptyReviewsMessage:t.i18n?.emptyReviewsMessage,reviewFilterPositive:t.i18n?.reviewFilterPositive,reviewFilterNegative:t.i18n?.reviewFilterNegative,reviewCustomersMentionSingular:t.i18n?.reviewCustomersMentionSingular,reviewCustomersMentionPlural:t.i18n?.reviewCustomersMentionPlural,reviewSubjectsHeading:t.i18n?.reviewSubjectsHeading}),ComparisonTable:({element:e,context:t})=>Bl(e,t),AITopPicks:({element:e,context:t})=>jc(e,t),GroundingReviewCard:({element:e,context:t})=>Vc(e,t),AIGroupingCards:({element:e,context:t})=>Wc(e,t),AISuggestedSearchCards:({element:e,context:t})=>Kc(e,t),ProsAndCons:({element:e})=>Yc(e),CategoriesContainer:({element:e,context:t})=>Jc(e,t),HandoffNotice:({element:e,context:t})=>Xc(e,t),ProductSummaryCard:({element:e,context:t})=>el(e,t),Divider:({element:e})=>Rl(e),...tl},On=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function al(){return{...Rn}}function nl(e,t,a=Rn,n=On){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-chat-uispec",unknownRenderer:n})}function rl(e,t){const a=document.createElement("div");a.className="gengage-chat-action-buttons";const n=e.props?.buttons;if(n)for(const r of n){const i=document.createElement("button");i.className="gengage-chat-action-btn",i.textContent=r.label,i.addEventListener("click",()=>t.onAction(r.action)),a.appendChild(i)}return a}function il(e,t){const a=document.createElement("button");a.className="gengage-chat-action-btn";const n=e.props?.label;typeof n=="string"&&(a.textContent=n);const r=e.props?.action;return r&&a.addEventListener("click",()=>t.onAction(r)),a}function Dn(e,t,a,n,r){e.replaceChildren();const i=pt(t,a),o=!!(r&&n&&r!==n),s=et(t,a),c=!!(s&&o),l=Tt(t,a);if(!n||parseFloat(n)<=0)return;if(c){const p=At({reasonText:s,salePriceFormatted:K(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const h=document.createElement("div");h.className="gengage-chat-product-card-price-row",h.appendChild(p);const d=document.createElement("span");d.className="gengage-chat-product-card-price-sep",d.setAttribute("aria-hidden","true");const b=document.createElement("span");b.className="gengage-chat-product-card-original-price",b.textContent=K(r,t.pricing),h.appendChild(d),h.appendChild(b),e.appendChild(h);return}if(e.classList.remove("gengage-chat-product-card-price-block--inline"),e.appendChild(p),o){e.appendChild(document.createTextNode(" "));const h=document.createElement("span");h.className="gengage-chat-product-card-original-price",h.textContent=K(r,t.pricing),e.appendChild(h)}return}if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const p=document.createElement("div");p.className="gengage-chat-product-card-price-row";const h=document.createElement("span");h.className="gengage-chat-product-card-current-price",h.textContent=K(n,t.pricing);const d=document.createElement("span");d.className="gengage-chat-product-card-price-sep",d.setAttribute("aria-hidden","true");const b=document.createElement("span");b.className="gengage-chat-product-card-original-price",b.textContent=K(r,t.pricing),p.appendChild(h),p.appendChild(d),p.appendChild(b),e.appendChild(p);return}e.classList.remove("gengage-chat-product-card-price-block--inline");const g=document.createElement("span");if(g.className="gengage-chat-product-card-current-price",g.textContent=K(n,t.pricing),e.appendChild(g),o){e.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-product-card-original-price",p.textContent=K(r,t.pricing),e.appendChild(p)}}function Fn(e,t,a,n,r,i,o){e.classList.remove("gengage-chat-product-details-price--inline"),e.replaceChildren(),e.className="gengage-chat-product-details-price";const s=et(t,a),c=!!(s&&o),l=Tt(t,a);if(c){const p=At({reasonText:s,salePriceFormatted:K(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline"),e.appendChild(p);const h=document.createElement("span");h.className="gengage-chat-product-details-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-product-details-original-price",d.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(d)}else{if(o){const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(document.createTextNode(" "))}e.appendChild(p)}}else if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline");const p=document.createElement("span");p.className="gengage-chat-product-details-current-price",p.textContent=K(n,t.pricing);const h=document.createElement("span");h.className="gengage-chat-product-details-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-product-details-original-price",d.textContent=K(r,t.pricing),e.appendChild(p),e.appendChild(h),e.appendChild(d)}else{if(o){const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(document.createTextNode(" "))}const p=document.createElement("span");p.className="gengage-chat-product-details-current-price",p.textContent=K(n,t.pricing),e.appendChild(p)}const g=Lt(a,"discountPercent","price_discount_rate");if(!t.hideProductDiscountBadge&&typeof g=="number"&&g>0){const p=document.createElement("span");p.className="gengage-chat-product-details-discount-badge",p.textContent=`%${ua(g)}`,e.appendChild(p)}}function va(e,t){const a=document.createElement("div");a.className="gengage-chat-product-card gds-card gds-product-card gds-card-interactive";const n=e.props?.product??e.props;if(!n)return a;const r=n.sku;r&&(a.dataset.sku=r);const i=e.props?.action;(t.onProductSelect||i)&&(a.classList.add("gds-clickable"),a.addEventListener("click",v=>{if(!a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")&&!v.target.closest(".gengage-chat-product-card-atc")&&!v.target.closest(".gengage-chat-product-card-cta")){if(i){t.onAction(i);return}t.onProductSelect?.(n)}}));const o=n.imageUrl;if(o&&fe(o)){const v=document.createElement("div");v.className="gengage-chat-product-card-img-wrapper";const L=document.createElement("img");L.className="gengage-chat-product-card-img",L.loading="lazy",ue(L,"src",o);const R=n.name;R&&(L.alt=R),Se(L),v.appendChild(L);const M=n.discountPercent;if(!t.hideProductDiscountBadge&&typeof M=="number"&&M>0){const A=document.createElement("span");A.className="gengage-chat-product-card-discount-badge",A.textContent=`%${ua(M)}`,v.appendChild(A)}const H=document.createElement("div");H.className="gengage-chat-product-card-img-actions";const q=n.sku;if(q&&t.onFavoriteToggle){const A=document.createElement("button");A.className="gengage-chat-favorite-btn",A.type="button",A.dataset.gengageFavoriteSku=q,A.setAttribute("aria-label",t.i18n?.addToFavoritesLabel??"Add to favorites");const E=t.favoritedSkus?.has(q)??!1;E&&A.classList.add("gengage-chat-favorite-btn--active"),A.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${E?"currentColor":"none"}" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>`,A.addEventListener("click",N=>{N.stopPropagation(),A.classList.toggle("gengage-chat-favorite-btn--active");const z=A.querySelector("svg");z&&z.setAttribute("fill",A.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),t.onFavoriteToggle(q,n)}),H.appendChild(A)}const j=n.sku,w=t.i18n?.findSimilarLabel??"Find Similar";if(j){const A=document.createElement("button");A.className="gengage-chat-find-similar-pill",A.type="button",A.setAttribute("aria-label",w),A.dataset.tooltip=w,A.innerHTML='<span class="gengage-chat-find-similar-pill-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="6.5"/><path d="M16 16l5.5 5.5"/></svg></span>';const E=document.createElement("span");E.className="gengage-chat-find-similar-pill-text",E.textContent=w,A.appendChild(E),A.addEventListener("click",N=>{N.stopPropagation(),t.onAction({title:w,type:"findSimilar",payload:{sku:j,...o?{image_url:o}:{}}})}),H.appendChild(A)}H.childElementCount>0&&v.appendChild(H),a.appendChild(v)}const s=document.createElement("div");s.className="gengage-chat-product-card-body";const c=n.brand;if(c){const v=document.createElement("div");v.className="gengage-chat-product-card-brand",v.textContent=c,s.appendChild(v)}const l=n.rating,g=n.reviewCount,p=n.price,h=n.originalPrice,d=n.price_async,b=et(t,n),u=pt(t,n),f=!!(h&&p&&h!==p&&parseFloat(p)>0),m=!!(b&&f),y=!!(b&&!m||f&&u==="inline"),k=typeof l=="number"&&Number.isFinite(l)&&l>0,_=document.createElement("div");_.className="gengage-chat-product-card-meta-row";const x=document.createElement("div");x.className="gengage-chat-product-card-price gengage-chat-product-card-price-block";const T=y?(()=>{const v=document.createElement("div");return v.className="gengage-chat-product-card-price-stack",b&&!m&&v.appendChild(Pt(b)),v.appendChild(x),v})():x;if(d===!0){const v=document.createElement("span");v.className="gengage-chat-price-skeleton",x.appendChild(v),setTimeout(()=>{v.parentElement&&(p&&parseFloat(p)>0?Dn(x,t,n,p,n.originalPrice):v.remove())},300)}else p&&parseFloat(p)>0&&Dn(x,t,n,p,h);if((x.childElementCount>0||d===!0)&&_.appendChild(T),k){const v=document.createElement("div");v.className="gengage-chat-product-card-rating gengage-chat-product-card-rating-compact";const L=ha(l),R=[`${L.toFixed(1)}`,"out of 5 stars"];typeof g=="number"&&Number.isFinite(g)&&R.push(`(${g} reviews)`),v.setAttribute("aria-label",R.join(" "));const M=document.createElement("span");M.className="gengage-chat-product-card-rating-compact-star",M.setAttribute("aria-hidden","true"),M.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.6l2.58 5.23 5.77.84-4.17 4.07.98 5.75L12 16.78l-5.16 2.71.99-5.75L3.66 9.67l5.76-.84L12 3.6z"/></svg>';const H=document.createElement("span");H.className="gengage-chat-product-card-rating-compact-value",H.textContent=L.toFixed(1),v.appendChild(M),v.appendChild(H),_.appendChild(v)}_.childElementCount===0&&(_.classList.add("gengage-chat-product-card-meta-row--empty"),_.setAttribute("aria-hidden","true")),s.appendChild(_);const P=n.name;if(P){const v=document.createElement("div");v.className="gengage-chat-product-card-name",v.textContent=P,v.title=P,s.appendChild(v)}const I=n.inStock;if(typeof I=="boolean"){const v=document.createElement("div");v.className=`gengage-chat-product-card-stock ${I?"is-in-stock":"is-out-of-stock"}`,v.textContent=I?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",s.appendChild(v)}a.appendChild(s);const F=n.url,X=n.sku,ne=n.cartCode,me=!!(ne&&X&&I!==!1),O=t.i18n?.productCtaLabel??"View";if(me){const v=document.createElement("div");v.className="gengage-chat-product-card-buy-footer";const L=document.createElement("button");L.type="button",L.className="gengage-chat-product-card-buy-trigger",L.textContent=O,L.addEventListener("click",R=>{R.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??O,type:"addToCart",payload:{sku:X,cartCode:ne,quantity:1}})}),v.appendChild(L),a.appendChild(v)}else if(i){const v=document.createElement("button");v.className="gengage-chat-product-card-cta",v.type="button",v.textContent=i.type==="launchSingleProduct"?O:i.title||O,v.addEventListener("click",L=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){L.stopPropagation();return}t.onAction(i)}),a.appendChild(v)}else if(F&&fe(F)){const v=document.createElement("a");v.className="gengage-chat-product-card-cta",ue(v,"href",F),ue(v,"target","_blank"),ue(v,"rel","noopener noreferrer"),v.textContent=O,v.addEventListener("click",L=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){L.preventDefault(),L.stopPropagation();return}t.onProductClick&&X&&(L.preventDefault(),t.onProductClick({sku:X,url:F,...P?{name:P}:{}}))}),a.appendChild(v)}if(t.comparisonSelectMode&&X&&t.onToggleComparisonSku){const v=document.createElement("div");v.className="gengage-chat-comparison-select-wrapper";const L=t.comparisonSelectedSkus?.includes(X)??!1;L&&v.classList.add("gengage-chat-comparison-select-wrapper--selected");const R=n.name??X,M=t.i18n?.comparisonSelectCardHint??"Tap anywhere on the card to add or remove it from comparison.";v.setAttribute("role","group"),v.setAttribute("aria-label",`${String(R)}. ${M}`);const H=document.createElement("button");H.type="button",H.className="gengage-chat-comparison-checkbox",H.dataset.selected=L?"true":"false",H.setAttribute("aria-pressed",L?"true":"false");const q=document.createElement("span");q.className="gengage-chat-comparison-checkbox-icon",q.innerHTML=L?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const j=document.createElement("span");j.className="gengage-chat-comparison-checkbox-label",j.textContent=L?t.i18n?.comparisonSelectedLabel??"Selected":t.i18n?.comparisonSelectLabel??"Select to compare",H.appendChild(q),H.appendChild(j),H.addEventListener("click",A=>{A.stopPropagation(),t.onToggleComparisonSku?.(X)});const w=document.createElement("div");return w.className="gengage-chat-comparison-card-hint",w.setAttribute("aria-hidden","true"),w.textContent=M,v.addEventListener("click",A=>{A.target.closest(".gengage-chat-comparison-checkbox")||(A.stopPropagation(),t.onToggleComparisonSku?.(X))}),v.appendChild(H),v.appendChild(w),v.appendChild(a),v}return a}var Un=new Set(["color","colour","renk","renk kodu","color code"]),ol=new Set(["size","beden","boyut"]),sl=new Set(["finish","bitiş","bitişi"]),cl=["variants","variantOptions","variant_options","productVariants","product_variants","options"],ll=new Set(["H2","H3","H4","P","BR","UL","OL","LI","STRONG","B","EM","I"]),dl=new Set(["SCRIPT","STYLE","NOSCRIPT","IFRAME","OBJECT","EMBED"]);function _e(e,...t){for(const a of t){const n=e[a];if(typeof n=="string"){const r=n.trim();if(r.length>0)return r}}}function Lt(e,...t){for(const a of t){const n=e[a];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const r=Number(n.replace(",","."));if(Number.isFinite(r))return r}}}function It(e,...t){for(const a of t){const n=e[a];if(typeof n=="boolean")return n}}function gl(e,...t){for(const a of t){const n=e[a];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function pl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function hl(e){const t=[...pl(e.images),_e(e,"imageUrl","image_url","image")].filter(a=>!!a&&fe(a));return Array.from(new Set(t))}function ul(e){return typeof DOMParser<"u"?(new DOMParser().parseFromString(e,"text/html").body.textContent??"").replace(/\s+/g," ").trim():e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function ml(e){const t=_e(e,"description_html","descriptionHtml");if(t){const n=ul(t);if(n)return{text:n,html:t}}const a=_e(e,"description");return a?{text:a}:void 0}function Nt(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;const a=t,n=_e(a,"key","name","label","title"),r=a.value,i=typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r).trim():void 0;return!n||!i?null:{key:n,value:i}}).filter(t=>t!==null):e&&typeof e=="object"?Object.entries(e).map(([t,a])=>{const n=typeof a=="string"||typeof a=="number"||typeof a=="boolean"?String(a).trim():void 0;return!t||!n?null:{key:t,value:n}}).filter(t=>t!==null):[]}function $n(e){const t=Nt(e.features);return t.length>0?t:Nt(e.specifications)}function fl(e){const t=e.specifications,a=Nt(t);if(a.length>0)return Array.isArray(t)?a:Object.fromEntries(a.map(r=>[r.key,r.value]));const n=Nt(e.features);return n.length>0?n:void 0}function Re(e,...t){return _e(e,...t)}function Hn(e,...t){return Lt(e,...t)}function qn(e){return Re(e,"value","option_value","attribute_value","label","title","name","variant_name","sku")}function jn(e){const t=Re(e,"type","attribute","option_name","attribute_name");return t||(Re(e,"value")?Re(e,"name","variant_name"):void 0)}function bl(e){const t=jn(e)?.toLowerCase();return!!(_e(e,"color","colour","color_hex","hex","swatch","swatchColor")||t&&Un.has(t))}function Zn(e){if(!e)return;const t=e.trim();if(!(!t||t.includes(";"))&&(typeof CSS<"u"&&CSS.supports?.("color",t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)))return t}function vl(e){const t=Zn(Re(e,"swatchColor","swatch","color_hex","hex","color","colour"));if(t)return t;if(bl(e))return Zn(qn(e))}function yl(e){return Re(e,"image","imageUrl","image_url","swatchImage","swatch_image")}function _l(e){return Hn(e,"price_discounted","priceDiscounted")??Re(e,"price_discounted","priceDiscounted")??Hn(e,"price")??Re(e,"price")}function xl(e){const t=e.trim().toLowerCase();return Un.has(t)||ol.has(t)||sl.has(t)}function wl(e){const t=e.trim().toLowerCase();return t==="renk kodu"?"Renk":t==="color code"?"Color":e.trim()}function kl(e){for(const t of cl){const a=e[t];if(!Array.isArray(a))continue;const n=a.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r));if(n.length>0)return n}}function Cl(e){const t=kl(e);if(t)return t;const a=_e(e,"sku"),n=It(e,"inStock","in_stock"),r=[],i=new Set,o=(c,l)=>{if(!xl(c)||typeof l!="string"&&typeof l!="number"&&typeof l!="boolean")return;const g=String(l).trim();if(!g)return;const p=wl(c),h=`${p.toLowerCase()}:${g.toLowerCase()}`;i.has(h)||(i.add(h),r.push({name:p,value:g,sku:a,inStock:n}))},s=gl(e,"facetHits","facet_hits");if(s)for(const[c,l]of Object.entries(s))o(c,l);for(const c of $n(e))o(c.key,c.value);return r}function Sl(e,t){const a=Array.from(new Set(e.map(jn).filter(n=>!!n)));return a.length===1?`${e.length} ${a[0]}`:t.i18n?.variantsLabel??"Variants"}function El(e,t){const a=document.createElement("article");a.className="gengage-chat-product-details-panel";const n=e.props?.product??e.props;if(!n)return a;const r=_e(n,"name"),i=_e(n,"brand"),o=_e(n,"sku"),s=_e(n,"cartCode","cart_code"),c=_e(n,"price"),l=_e(n,"originalPrice","price_original"),g=It(n,"price_async"),p=et(t,n),h=pt(t,n),d=!!(l&&c&&l!==c),b=It(n,"inStock","in_stock"),u=Lt(n,"reviewCount","review_count"),f=Lt(n,"rating"),m=hl(n),y=$n(n).slice(0,4);if(m.length>1){const v=document.createElement("div");v.className="gengage-chat-product-details-media gengage-chat-product-details-gallery gengage-chat-product-details-img-wrap";const L=document.createElement("img");L.className="gengage-chat-product-details-img",ue(L,"src",m[0]),L.alt=r??"Product image",Se(L),v.appendChild(L);const R=document.createElement("div");R.className="gengage-chat-product-gallery-thumbs";const M=6;let H=null,q=0;const j=t.i18n,w=j?.galleryPrevAriaLabel??"Previous image",A=j?.galleryNextAriaLabel??"Next image",E=$=>$==="prev"?'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>':'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>',N=document.createElement("button");N.type="button",N.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--prev gds-btn gds-btn-ghost gds-icon-btn",N.setAttribute("aria-label",w),N.innerHTML=E("prev");const z=document.createElement("button");z.type="button",z.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--next gds-btn gds-btn-ghost gds-icon-btn",z.setAttribute("aria-label",A),z.innerHTML=E("next");const B=()=>{N.disabled=q<=0,z.disabled=q>=m.length-1},U=$=>{if($<0||$>=m.length||$===q)return;const ie=m[$];if(!ie)return;ue(L,"src",ie);const Y=R.querySelectorAll(".gengage-chat-product-gallery-thumb");H&&H.classList.remove("gengage-chat-product-gallery-thumb--active"),$<M&&Y[$]?(Y[$].classList.add("gengage-chat-product-gallery-thumb--active"),H=Y[$]):H=null,q=$,B()};for(let $=0;$<m.length;$++){const ie=m[$];if($>=M)break;const Y=document.createElement("img");Y.className="gengage-chat-product-gallery-thumb",$===0&&(Y.classList.add("gengage-chat-product-gallery-thumb--active"),H=Y),ue(Y,"src",ie),Y.alt=`${r??"Product"} ${$+1}`,Y.width=48,Y.height=48,Se(Y),Y.addEventListener("click",()=>{U($)}),R.appendChild(Y)}if(m.length>M){const $=document.createElement("span");$.className="gengage-chat-product-gallery-thumb-more",$.textContent=`+${m.length-M}`,R.appendChild($)}N.addEventListener("click",$=>{$.stopPropagation(),U(q-1)}),z.addEventListener("click",$=>{$.stopPropagation(),U(q+1)}),B();let ee=0;const Q=50;L.addEventListener("touchstart",$=>{ee=$.changedTouches[0].clientX},{passive:!0}),L.addEventListener("touchend",$=>{const ie=$.changedTouches[0].clientX,Y=ee-ie;Math.abs(Y)<Q||U(Y>0?Math.min(q+1,m.length-1):Math.max(q-1,0))}),v.appendChild(N),v.appendChild(z),v.appendChild(R),a.appendChild(v)}else if(m.length===1){const v=document.createElement("div");v.className="gengage-chat-product-details-media gengage-chat-product-details-img-wrap";const L=document.createElement("img");L.className="gengage-chat-product-details-img",L.loading="lazy",ue(L,"src",m[0]),Se(L),L.alt=r??"Product image",v.appendChild(L),a.appendChild(v)}const k=document.createElement("div");if(k.className="gengage-chat-product-details-content",i&&(!r||!r.toLowerCase().startsWith(i.toLowerCase()))){const v=document.createElement("div");v.className="gengage-chat-product-details-brand",v.textContent=i,k.appendChild(v)}if(r){const v=document.createElement("h3");v.className="gengage-chat-product-details-title",v.textContent=r,v.title=r,k.appendChild(v)}if(typeof f=="number"&&Number.isFinite(f)&&f>0){const v=document.createElement(o?"button":"div");v.className="gengage-chat-product-details-rating",o&&(v.type="button",v.classList.add("gengage-chat-product-details-rating--clickable"),v.setAttribute("aria-label",t.i18n?.groundingReviewCta??"Read Reviews"),v.addEventListener("click",()=>{t.onAction({title:t.i18n?.customerReviewsTitle??"Customer Reviews",type:"reviewSummary",payload:{sku:o}})})),v.appendChild(ma(f));const L=document.createElement("span");if(L.className="gengage-chat-product-details-rating-value",L.textContent=ha(f).toFixed(1),v.appendChild(L),typeof u=="number"&&Number.isFinite(u)){const R=document.createElement("span");R.className="gengage-chat-product-details-review-count",R.textContent=` (${u})`,v.appendChild(R)}k.appendChild(v)}{const v=!!(p&&d);let L=k;if(p&&!v){const M=document.createElement("div");M.className="gengage-chat-product-details-price-stack",M.appendChild(Pt(p)),k.appendChild(M),L=M}const R=document.createElement("div");if(R.className="gengage-chat-product-details-price",g===!0){const M=document.createElement("span");M.className="gengage-chat-price-skeleton",R.appendChild(M),L.appendChild(R),setTimeout(()=>{if(M.parentElement)if(c&&parseFloat(c)>0)Fn(R,t,n,c,l,h,d);else{const H=R.parentElement;R.remove(),H?.classList.contains("gengage-chat-product-details-price-stack")&&H.remove()}},300)}else if(c&&parseFloat(c)>0)Fn(R,t,n,c,l,h,d),L.appendChild(R);else if(p){const M=L;M.classList.contains("gengage-chat-product-details-price-stack")&&M.remove()}}if(typeof b=="boolean"){const v=document.createElement("div");v.className=`gengage-chat-product-details-stock ${b?"is-in-stock":"is-out-of-stock"}`,v.textContent=b?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",k.appendChild(v)}const _=n.promotions;if(_&&_.length>0){const v=document.createElement("div");v.className="gengage-chat-product-details-promos";for(const L of _.slice(0,3)){if(!L||/%(0(\.0+)?)\s/.test(L))continue;const R=document.createElement("span");R.className="gengage-chat-product-details-promo-badge",R.textContent=L,R.title=L,v.appendChild(R)}v.childElementCount>0&&k.appendChild(v)}if(y.length>0){const v=document.createElement("dl");v.className="gengage-chat-product-details-facts";for(const L of y){const R=document.createElement("div");R.className="gengage-chat-product-details-fact";const M=document.createElement("dt");M.textContent=L.key;const H=document.createElement("dd");H.textContent=L.value,R.appendChild(M),R.appendChild(H),v.appendChild(R)}k.appendChild(v)}const x=Cl(n);if(x.length>0){const v=document.createElement("div");v.className="gengage-chat-product-variants";const L=document.createElement("div");L.className="gengage-chat-product-variants-label",L.textContent=Sl(x,t),v.appendChild(L);const R=document.createElement("div");R.className="gengage-chat-product-variants-list";for(const M of x){const H=qn(M),q=Re(M,"sku");if(!H&&!q)continue;const j=document.createElement("button");j.className="gengage-chat-product-variant-btn gds-chip",j.type="button";const w=H??q??"";j.title=w;const A=It(M,"in_stock","inStock");q&&o&&q===o?(j.classList.add("gengage-chat-product-variant-btn--active"),j.setAttribute("aria-pressed","true")):j.setAttribute("aria-pressed","false"),A===!1&&(j.classList.add("gengage-chat-product-variant-btn--out"),j.disabled=!0);const E=yl(M),N=vl(M);if(E&&fe(E)){const U=document.createElement("img");U.className="gengage-chat-product-variant-swatch gengage-chat-product-variant-swatch--image",ue(U,"src",E),U.alt="",U.setAttribute("aria-hidden","true"),Se(U),j.appendChild(U)}else if(N){const U=document.createElement("span");U.className="gengage-chat-product-variant-swatch",U.setAttribute("aria-hidden","true"),U.style.backgroundColor=N,j.appendChild(U)}const z=document.createElement("span");z.className="gengage-chat-product-variant-label",z.textContent=w,j.appendChild(z);const B=_l(M);if(B&&String(B)!==String(c)){const U=document.createElement("span");U.className="gengage-chat-product-variant-price",U.textContent=K(String(B),t.pricing),j.appendChild(U)}if(q&&q!==o){const U=r??"",ee=(typeof M.value=="string"?M.value.trim():"")||(typeof M.name=="string"?M.name.trim():"")||(typeof M.variant_name=="string"?M.variant_name.trim():"")||"",Q=U.length>0?ee.length>0&&ee!==U?`${U} (${ee})`:U:w;j.addEventListener("click",()=>{t.onAction({title:Q,type:"launchVariant",payload:{sku:q}})})}R.appendChild(j)}R.childElementCount>0&&(v.appendChild(R),k.appendChild(v))}const T=document.createElement("div");T.className="gengage-chat-product-details-actions";const P=e.props?.action;if(P){const v=document.createElement("button");v.className="gengage-chat-product-details-cta gds-btn gds-btn-primary",v.type="button",v.textContent=P.title||t.i18n?.productCtaLabel||"View",v.addEventListener("click",()=>t.onAction(P)),T.appendChild(v)}if(s&&o&&b!==!1){const v=document.createElement("button");v.className="gengage-chat-product-details-atc gds-btn gds-btn-primary",v.type="button",v.textContent=t.i18n?.addToCartButton??"Add to Cart",v.addEventListener("click",()=>{t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:o,cartCode:s,quantity:1}})}),T.appendChild(v)}const I=_e(n,"url");if(!P&&I&&fe(I)){const v=document.createElement("a");v.className="gengage-chat-product-details-cta gds-btn gds-btn-secondary",ue(v,"href",I),ue(v,"target","_blank"),ue(v,"rel","noopener noreferrer"),v.textContent=t.i18n?.viewOnSiteLabel??t.i18n?.productCtaLabel??"View on Site",v.addEventListener("click",L=>{t.onProductClick&&o&&(L.preventDefault(),t.onProductClick({sku:o,url:I,...r?{name:r}:{}}))}),T.appendChild(v)}const F=I;if(F&&fe(F)){let H=function(j,w){const A=document.createElementNS(R,"circle");A.setAttribute("cx",j),A.setAttribute("cy",w),A.setAttribute("r","3"),M.appendChild(A)},q=function(j,w,A,E){const N=document.createElementNS(R,"line");N.setAttribute("x1",j),N.setAttribute("y1",w),N.setAttribute("x2",A),N.setAttribute("y2",E),M.appendChild(N)};var me=H,O=q;const v=document.createElement("button");v.className="gengage-chat-product-details-share gds-btn gds-btn-ghost gds-icon-btn",v.type="button";const L=t.i18n?.shareButton??"Share";v.title=L,v.setAttribute("aria-label",L);const R="http://www.w3.org/2000/svg",M=document.createElementNS(R,"svg");M.setAttribute("width","18"),M.setAttribute("height","18"),M.setAttribute("viewBox","0 0 24 24"),M.setAttribute("fill","none"),M.setAttribute("stroke","currentColor"),M.setAttribute("stroke-width","2"),M.setAttribute("stroke-linecap","round"),M.setAttribute("stroke-linejoin","round"),H("18","5"),H("6","12"),H("18","19"),q("8.59","13.51","15.42","17.49"),q("15.41","6.51","8.59","10.49"),v.appendChild(M),v.addEventListener("click",async()=>{try{navigator.share?await navigator.share({title:r??"",url:F}):navigator.clipboard&&(await navigator.clipboard.writeText(F),v.classList.add("gengage-chat-product-details-share--copied"),setTimeout(()=>v.classList.remove("gengage-chat-product-details-share--copied"),1500))}catch{}}),T.appendChild(v)}T.childElementCount>0&&k.appendChild(T),a.appendChild(k);const X=ml(n),ne=fl(n);return(X||ne)&&a.appendChild(Al(X,ne,t)),a}function ya(e){if(e.nodeType===Node.TEXT_NODE)return document.createTextNode(e.textContent??"");if(e.nodeType!==Node.ELEMENT_NODE)return null;const t=e,a=t.tagName.toUpperCase();if(dl.has(a))return null;if(!ll.has(a)){const r=document.createDocumentFragment();for(const i of Array.from(t.childNodes)){const o=ya(i);o&&r.appendChild(o)}return r}const n=document.createElement(a.toLowerCase());for(const r of Array.from(t.childNodes)){const i=ya(r);i&&n.appendChild(i)}return n}function Pl(e,t){const a=t.split(/\n{2,}/).map(n=>n.replace(/\s+/g," ").trim()).filter(Boolean);if(a.length!==0)for(const n of a){const r=document.createElement("p");r.textContent=n,e.appendChild(r)}}function Tl(e,t){if(e.classList.add("gengage-chat-product-description"),t.html&&typeof DOMParser<"u"){const a=new DOMParser().parseFromString(t.html,"text/html"),n=Array.from(a.body.childNodes).map(r=>ya(r)).filter(r=>!!r&&(r.nodeType===Node.ELEMENT_NODE||!!r.textContent?.trim()));if(n.length>0){for(const r of n)e.appendChild(r);return}}Pl(e,t.text)}function Al(e,t,a){const n=document.createElement("div");n.className="gengage-chat-product-detail-tabs";const r=document.createElement("div");r.className="gengage-chat-product-detail-tab-bar gds-toolbar";const i=[];if(e){const s=document.createElement("button");s.className="gengage-chat-product-detail-tab gds-tab gengage-chat-product-detail-tab--active is-active",s.type="button",s.setAttribute("aria-selected","true"),s.textContent=a.i18n?.productInfoTab??"Product Info",r.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-product-detail-tab-panel",Tl(c,e),i.push(c)}if(t){const s=document.createElement("button");s.className=`gengage-chat-product-detail-tab gds-tab${e?"":" gengage-chat-product-detail-tab--active is-active"}`,s.type="button",s.setAttribute("aria-selected",e?"false":"true"),s.textContent=a.i18n?.specificationsTab??"Specifications",r.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-product-detail-tab-panel",e&&(c.style.display="none");const l=document.createElement("table");l.className="gengage-chat-product-specs-table";const g=Array.isArray(t)?t:Object.entries(t).map(([p,h])=>({key:p,value:h}));for(const p of g){const h=document.createElement("tr"),d=document.createElement("td");d.className="gengage-chat-product-specs-key",d.textContent=p.key;const b=document.createElement("td");b.className="gengage-chat-product-specs-value",b.textContent=p.value,h.appendChild(d),h.appendChild(b),l.appendChild(h)}c.appendChild(l),i.push(c)}const o=r.querySelectorAll(".gengage-chat-product-detail-tab");o.forEach((s,c)=>{s.addEventListener("click",()=>{o.forEach(l=>{l.classList.remove("gengage-chat-product-detail-tab--active","is-active"),l.setAttribute("aria-selected","false")}),s.classList.add("gengage-chat-product-detail-tab--active","is-active"),s.setAttribute("aria-selected","true"),i.forEach((l,g)=>{l.style.display=g===c?"":"none"})})}),n.appendChild(r);for(const s of i)n.appendChild(s);return n}function Vn(e){const t='width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';switch(e){case"related":return`<svg ${t} aria-hidden="true"><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></svg>`;case"priceAsc":return`<svg ${t} aria-hidden="true"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>`;case"priceDesc":return`<svg ${t} aria-hidden="true"><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></svg>`;default:return""}}function Ll(){return'<svg class="gengage-chat-product-sort-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>'}function Il(){return'<svg class="gengage-chat-product-sort-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>'}function Nl(){return'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 3 4 7l4 4"/><path d="M16 21l4-4-4-4"/><path d="M4 7h16"/><path d="M20 17H4"/></svg>'}function Gn(e,t){return e.type===t.type&&e.direction===t.direction}function Wn(e,t,a){if(!a||a.type==="related")return e;const n=e.map(r=>{const i=t.elements[r]?.props?.product,o=i?Number(i.price):NaN;return{id:r,price:Number.isFinite(o)?o:1/0}});return n.sort((r,i)=>r.price===1/0&&i.price===1/0?0:r.price===1/0?1:i.price===1/0?-1:a.direction==="desc"?i.price-r.price:r.price-i.price),n.map(r=>r.id)}function zl(e,t,a,n){const r=Wn(t,a,n),i=new Map;for(const o of Array.from(e.children)){const s=o.dataset.elementId;s&&i.set(s,o)}for(const o of r){const s=i.get(o);s&&e.appendChild(s)}}function Ml(e,t,a,n){const r=document.createElement("div");r.className="gengage-chat-product-grid-wrapper";const i=ka(e),o=i.isConsulting,s=e.children??[],c=document.createElement("div");c.className="gengage-chat-product-grid";const l=n?.panelProductListHeading;if(!o&&s.length>1&&n?.onSortChange){const h=document.createElement("div");h.className="gengage-chat-product-sort-toolbar",h.setAttribute("role","toolbar"),h.setAttribute("aria-label",n.i18n?.sortToolbarAriaLabel??"Sort products");let d=n.productSort??{type:"related"};const b=[{label:n.i18n?.sortRelated??"Related",sortState:{type:"related"},icon:"related"},{label:n.i18n?.sortPriceAsc??"Price ↑",sortState:{type:"price",direction:"asc"},icon:"priceAsc"},{label:n.i18n?.sortPriceDesc??"Price ↓",sortState:{type:"price",direction:"desc"},icon:"priceDesc"}],u=document.createElement("div");u.className="gengage-chat-product-sort-dropdown";const f=document.createElement("button");f.type="button",f.className="gengage-chat-product-sort-trigger gds-btn gds-btn-ghost",f.setAttribute("aria-haspopup","listbox"),f.setAttribute("aria-expanded","false");const m=n.i18n?.sortToolbarAriaLabel??"Sort products",y=document.createElement("span");y.className="gengage-chat-product-sort-trigger-icon";const k=document.createElement("span");k.className="gengage-chat-product-sort-trigger-label";const _=O=>{const v=b.find(L=>Gn(L.sortState,O))??b[0];k.textContent=v.label,y.innerHTML=Vn(v.icon),u.dataset.sortIcon=v.icon,f.setAttribute("aria-label",`${m}: ${v.label}`),f.title=v.label};_(d);const x=document.createElement("span");x.className="gengage-chat-product-sort-trigger-chevron",x.innerHTML=Ll(),f.appendChild(y),f.appendChild(k),f.appendChild(x);const T=document.createElement("div");T.className="gengage-chat-product-sort-menu gds-menu",T.hidden=!0,T.setAttribute("role","listbox"),T.setAttribute("aria-label",m);const P=h.ownerDocument;let I=null;const F=()=>{T.hidden=!0,u.classList.remove("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","false"),I?.abort(),I=null},X=O=>{u.classList.contains("gengage-chat-product-sort-dropdown--open")&&(u.contains(O.target)||F())},ne=O=>{O.key==="Escape"&&(O.preventDefault(),F())},me=()=>{T.hidden=!1,u.classList.add("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","true"),I=new AbortController;const{signal:O}=I;P.addEventListener("click",X,{signal:O}),P.addEventListener("keydown",ne,{capture:!0,signal:O})};f.addEventListener("click",O=>{O.stopPropagation(),u.classList.contains("gengage-chat-product-sort-dropdown--open")?F():me()});for(const O of b){const v=document.createElement("button");v.type="button",v.className="gengage-chat-product-sort-option gds-menu-option",v.setAttribute("role","option");const L=Gn(d,O.sortState);v.setAttribute("aria-selected",L?"true":"false"),L&&v.classList.add("gengage-chat-product-sort-option--active","gds-menu-option-active");const R=O.sortState.type==="related"?"related":`price-${O.sortState.direction??""}`;v.dataset.sortKey=R;const M=document.createElement("span");M.className="gengage-chat-product-sort-option-icon",M.innerHTML=Vn(O.icon);const H=document.createElement("span");H.className="gengage-chat-product-sort-option-label",H.textContent=O.label;const q=document.createElement("span");q.className="gengage-chat-product-sort-option-check",q.innerHTML=Il(),q.setAttribute("aria-hidden","true"),L||q.classList.add("gengage-chat-product-sort-option-check--hidden"),v.appendChild(M),v.appendChild(H),v.appendChild(q),v.addEventListener("click",()=>{d=O.sortState,n.onSortChange?.(O.sortState),zl(c,s,t,O.sortState),T.querySelectorAll(".gengage-chat-product-sort-option").forEach(j=>{const w=j,A=w.dataset.sortKey===R;w.classList.toggle("gengage-chat-product-sort-option--active",A),w.classList.toggle("gds-menu-option-active",A),w.setAttribute("aria-selected",A?"true":"false"),w.querySelector(".gengage-chat-product-sort-option-check")?.classList.toggle("gengage-chat-product-sort-option-check--hidden",!A)}),_(O.sortState),F()}),T.appendChild(v)}if(u.appendChild(f),u.appendChild(T),h.appendChild(u),n.onToggleComparisonSku){const O=document.createElement("button");O.className="gengage-chat-comparison-toggle-btn gds-btn gds-btn-ghost",O.type="button",n.comparisonSelectMode&&O.classList.add("gengage-chat-comparison-toggle-btn--active"),n.isStreaming&&O.classList.add("gengage-chat-comparison-toggle-btn--hidden");const v=document.createElement("span");v.className="gengage-chat-comparison-toggle-icon",v.innerHTML=Nl();const L=document.createElement("span");L.className="gengage-chat-comparison-toggle-label";const R=n.i18n?.compareSelected??"Compare";L.textContent=R,O.setAttribute("aria-label",R),O.title=R,O.appendChild(v),O.appendChild(L),O.addEventListener("click",()=>{n.onToggleComparisonSku?.("")}),h.appendChild(O)}if(l){h.classList.add("gengage-chat-product-sort-toolbar--inline");const O=document.createElement("div");O.className="gengage-chat-product-grid-head";const v=document.createElement("span");v.className="gengage-chat-product-grid-head-title",v.textContent=l,O.appendChild(v);const L=document.createElement("div");L.className="gengage-chat-product-grid-head-actions",L.appendChild(h),O.appendChild(L),r.appendChild(O)}else r.appendChild(h)}else if(l){const h=document.createElement("div");h.className="gengage-chat-product-grid-head";const d=document.createElement("span");d.className="gengage-chat-product-grid-head-title",d.textContent=l,h.appendChild(d),r.appendChild(h)}if(o)$l(r,c,i,n);else{const h=Wn(s,t,n?.productSort);for(const d of h){if(!t.elements[d])continue;const b=a(d);b&&(b.dataset.elementId=d,c.appendChild(b))}}(n?.isMobile??ba())&&c.classList.add("gengage-chat-product-grid--mobile"),e.props?.rankingState==="pending"&&(c.classList.add("gengage-chat-product-grid--pending"),c.inert=!0,c.setAttribute("aria-busy","true")),r.appendChild(c);const g=e.props?.endOfList;if(!o&&g!==!0&&s.length>0){const h=n?.i18n?.viewMoreLabel??"Show More",d=document.createElement("button");d.className="gengage-chat-product-grid-view-more",d.type="button",d.textContent=h,d.addEventListener("click",()=>{n?.onAction({title:h,type:"moreProductList",payload:{}})}),r.appendChild(d)}const p=n?.isMobile??ba();if(n?.comparisonSelectMode&&n.comparisonSelectedSkus&&!p){const h=Bn(n.comparisonSelectedSkus,n);r.appendChild(h)}return r}function Bl(e,t){const a=e.props??{},n=a.keyDifferencesHtml,r=a.recommended,i=a.products??[],o=a.attributes??[],s=a.highlights??[],c=a.specialCases,l=a.recommendedText,g=a.winnerHits,p=a.productActions;if(!r)return document.createElement("div");const h={recommended:r,products:i,attributes:o,highlights:s,specialCases:c,locale:t.locale,onProductClick:({sku:b,name:u})=>{t.onProductClick?.({sku:b,url:"",name:u})},pricing:t.pricing};l!==void 0&&(h.recommendedText=l),g!==void 0&&(h.winnerHits=g),p!==void 0&&(h.productActions=p),n!==void 0&&(h.keyDifferencesHtml=n),t.i18n&&(h.i18n={comparisonHeading:t.i18n.panelTitleComparisonResults,recommendedChoiceLabel:t.i18n.recommendedChoiceLabel,highlightsLabel:t.i18n.highlightsLabel,keyDifferencesLabel:t.i18n.keyDifferencesLabel,viewMoreLabel:t.i18n.viewMoreLabel,specialCasesLabel:t.i18n.specialCasesLabel,addToCartButton:t.i18n.addToCartButton});const d=Pc(h);return(t.isMobile??ba())&&d.classList.add("gengage-chat-comparison--mobile"),d}function Rl(e){const t=document.createElement("hr");t.className="gengage-chat-divider";const a=e.props?.label;if(a){const n=document.createElement("div");n.className="gengage-chat-divider-wrapper";const r=document.createElement("span");r.className="gengage-chat-divider-label",r.textContent=a,n.appendChild(t),n.appendChild(r);const i=document.createElement("hr");return i.className="gengage-chat-divider",n.appendChild(i),n}return t}var zt=new WeakMap;function Kn(e){return{...Xe,...e?.i18n??{}}}function Mt(e){return typeof e.status=="string"?e.status:"ready"}function _a(e){const t=e.findIndex(a=>Mt(a)!=="loading");return t<0?0:t}function Ol(e){if(typeof e!="string")return;const t=e.trim();if(!t)return;if(/^https?:\/\//i.test(t))return t;let a=t.split(/[?#]/)[0];if(a&&(a=a.replace(/^\/+/,""),a.startsWith("remoteConfig/")&&(a=a.slice(13)),!!a))return`https://configs.gengage.ai/assets/${a}`}function Yn(e,t,a,n){const{grid:r,i18n:i}=e;r.innerHTML="",r.classList.remove("gengage-chat-product-grid--consulting-groups");const o=document.createElement("section");o.className="gengage-chat-consulting-loading-panel";const s=document.createElement("h4");s.className="gengage-chat-consulting-loading-panel-title",s.textContent=Bt(t,n,i),o.appendChild(s);const c=document.createElement("p");if(c.className="gengage-chat-consulting-loading-panel-copy",c.textContent=a==="loading"?i.consultingStyleLoadingDescription:i.consultingStyleUnavailableDescription,o.appendChild(c),a==="loading"){const l=document.createElement("div");l.className="gengage-chat-consulting-loading-grid";for(let g=0;g<3;g+=1){const p=document.createElement("div");p.className="gengage-chat-consulting-loading-card",l.appendChild(p)}o.appendChild(l)}r.appendChild(o)}function Bt(e,t,a){const n=r=>a.consultingFallbackStyleLabel.replace("{index}",String(r));return e.style_label??n(t)}function xa(e,t){const a=e.variations[t];if(!a)return;const{grid:n,source:r,ctx:i,i18n:o}=e;n.innerHTML="",n.classList.remove("gengage-chat-product-grid--consulting-groups");const s=Mt(a),c=t+1;if(s==="loading"){Yn(e,a,"loading",c);return}if(s!=="ready"&&(!Array.isArray(a.product_list)||a.product_list.length===0)){Yn(e,a,"unavailable",c);return}const l=Array.isArray(a.product_list)?a.product_list:[],g=r==="watch_expert"?[]:Array.isArray(a.recommendation_groups)?a.recommendation_groups:[];if(g.length>0){n.classList.add("gengage-chat-product-grid--consulting-groups");const p=new Map;for(const m of l){const y=typeof m?.sku=="string"?m.sku:void 0;y&&p.set(y,m)}const h=(m,y,k,_)=>{if(y.length===0)return;const x=document.createElement("section");x.className="gengage-chat-consulting-group";const T=document.createElement("div");T.className="gengage-chat-consulting-group-header";const P=document.createElement("h4");if(P.className="gengage-chat-consulting-group-label",P.textContent=`${m} (${y.length})`,T.appendChild(P),typeof _=="string"&&_.trim().length>0){const F=document.createElement("p");F.className="gengage-chat-consulting-group-reason",F.textContent=_,T.appendChild(F)}x.appendChild(T);const I=document.createElement("div");I.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",k&&I.classList.add("gengage-chat-consulting-group-grid--single-group"),I.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,y.length))));for(const F of y){const X=va({type:"ProductCard",props:{product:F}},i??{onAction:()=>{}});I.appendChild(X)}x.appendChild(I),n.appendChild(x)},d=new Set,b=[];for(const m of g){const y=(Array.isArray(m.skus)?m.skus.filter(x=>typeof x=="string"&&x.trim().length>0):[]).map(x=>(d.add(x),p.get(x))).filter(x=>!!x);if(y.length===0)continue;const k=typeof m.label=="string"&&m.label.trim().length>0?m.label:o.consultingFallbackGroupLabel,_=typeof m.reason=="string"?m.reason:void 0;b.push({labelText:k,products:y,..._!==void 0?{reasonText:_}:{}})}const u=l.filter(m=>{const y=typeof m?.sku=="string"?m.sku:"";return y.length>0&&!d.has(y)});u.length>0&&b.push({labelText:o.consultingOtherCompatibleProductsLabel,products:u});const f=b.length===1;for(const m of b)h(m.labelText,m.products,f,m.reasonText);return}for(const p of l){const h=va({type:"ProductCard",props:{product:p}},i??{onAction:()=>{}});n.appendChild(h)}}function wa(e,t,a,n){const r=Mt(t),i=n.consultingStyleLoadingBadge,o=n.consultingStyleUnavailableBadge;e.classList.remove("gengage-chat-consulting-style-btn--loading","gengage-chat-consulting-style-btn--muted"),r==="loading"?e.classList.add("gengage-chat-consulting-style-btn--loading"):r!=="ready"&&e.classList.add("gengage-chat-consulting-style-btn--muted"),e.setAttribute("aria-label",Bt(t,a+1,n));let s=e.querySelector(".gengage-chat-consulting-style-media");s?s.innerHTML="":(s=document.createElement("div"),s.className="gengage-chat-consulting-style-media",e.appendChild(s));const c=Ol(t.image_url);if(c&&fe(c)){const g=document.createElement("img");g.className="gengage-chat-consulting-style-image",g.draggable=!1,ue(g,"src",c),g.alt=Bt(t,a+1,n),g.loading="lazy",Se(g),s.appendChild(g)}const l=document.createElement("span");if(l.className="gengage-chat-consulting-style-caption",l.textContent=Bt(t,a+1,n),s.appendChild(l),r==="loading"||r!=="ready"){const g=document.createElement("span");g.className="gengage-chat-consulting-style-status",g.textContent=r==="loading"?i:o,s.appendChild(g)}}function Jn(e,t,a,n){e.addEventListener("click",()=>{const r=zt.get(t);r&&r.selectedIndex!==n&&(r.selectedIndex=n,a.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((i,o)=>{i.classList.toggle("gengage-chat-consulting-style-btn--active",o===n)}),xa(r,n))})}function Dl(e,t,a,n,r){const i=Kn(r),o=_a(n),s=document.createElement("div");s.className="gengage-chat-consulting-style-picker";const c={grid:t,source:a,ctx:r,variations:n,i18n:i,selectedIndex:o};zt.set(s,c);const l=document.createElement("div");l.className="gengage-chat-consulting-style-picker-title",l.textContent=(a==="watch_expert"?i.watchStylesPreparedTitle:i.beautyStylesPreparedTitle).replace("{count}",String(n.length)),s.appendChild(l);const g=document.createElement("div");g.className="gengage-chat-consulting-style-grid",s.appendChild(g),n.forEach((p,h)=>{const d=document.createElement("button");d.type="button",d.className="gengage-chat-consulting-style-btn gds-card",h===o&&d.classList.add("gengage-chat-consulting-style-btn--active"),wa(d,p,h,i),Jn(d,s,g,h),g.appendChild(d)}),e.appendChild(s),xa(c,o)}function Fl(e,t,a,n){const r=e.querySelector(".gengage-chat-consulting-style-picker"),i=Ul(e);if(!r||!i)return!1;const o=r.querySelector(".gengage-chat-consulting-style-grid");if(!o)return!1;const s=Kn(n);let c=zt.get(r);if(c)c.grid=i,c.source=t,c.ctx=n,c.variations=a,c.i18n=s;else{const d={grid:i,source:t,ctx:n,variations:a,i18n:s,selectedIndex:_a(a)};zt.set(r,d),c=d}const l=r.querySelector(".gengage-chat-consulting-style-picker-title");l&&(l.textContent=(t==="watch_expert"?s.watchStylesPreparedTitle:s.beautyStylesPreparedTitle).replace("{count}",String(a.length)));const g=c;let p=g.selectedIndex;p>=a.length&&(p=Math.max(0,a.length-1)),p<0&&(p=0),a.length>0&&Mt(a[p]??{})==="loading"&&(p=_a(a)),g.selectedIndex=p;const h=[...o.querySelectorAll(".gengage-chat-consulting-style-btn")];if(h.length===0)return!1;for(let d=0;d<a.length;d+=1){const b=a[d];let u=h[d];u?wa(u,b,d,s):(u=document.createElement("button"),u.type="button",u.className="gengage-chat-consulting-style-btn gds-card",wa(u,b,d,s),Jn(u,r,o,d),o.appendChild(u),h[d]=u)}for(;o.querySelectorAll(".gengage-chat-consulting-style-btn").length>a.length;)o.lastElementChild?.remove();return o.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((d,b)=>{d.classList.toggle("gengage-chat-consulting-style-btn--active",b===g.selectedIndex)}),xa(g,g.selectedIndex),!0}function Ul(e){const t=[...e.children];for(let a=t.length-1;a>=0;a-=1){const n=t[a];if(n.classList.contains("gengage-chat-product-grid"))return n}return e.querySelector(":scope > .gengage-chat-product-grid")}function ka(e){const t=typeof e.props?.source=="string"?e.props.source:void 0,a=(Array.isArray(e.props?.styleVariations)?e.props.styleVariations:[]).filter(n=>typeof n.style_label=="string"&&n.style_label.trim().length>0);return{isConsulting:un(t)&&a.length>0,source:t,styleVariations:a}}function $l(e,t,a,n){Dl(e,t,a.source,a.styleVariations,n)}function Hl(e){return!e.isConsulting||e.styleVariations.length===0?!0:e.styleVariations.some(t=>(typeof t.status=="string"?t.status:"ready")!=="loading")}function ql(e,t,a){return!t.isConsulting||!t.source?!1:Fl(e,t.source,t.styleVariations,a)}var jl=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
49
+ `).filter(a=>a.trim());return t.length<=1?e:"<ul>"+t.map(a=>`<li>${a.trim()}</li>`).join("")+"</ul>"}function Ac(e,t){const a=ke(t);if(!a)return;const n=document.createElement("template");n.innerHTML=a;const r=Array.from(n.content.querySelectorAll("li"));if(r.length>0){for(const o of r){const s=document.createElement("li");s.innerHTML=ke(o.innerHTML),e.appendChild(s)}return}const i=document.createElement("li");Ln(t)?i.innerHTML=a:i.textContent=t,e.appendChild(i)}function Ln(e){return/<\/?[a-z][\s\S]*>/i.test(e)}function gt(e,t=18){const a="http://www.w3.org/2000/svg",n=document.createElementNS(a,"svg");n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","2"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true");for(const r of e){const i=document.createElementNS(a,"path");i.setAttribute("d",r),n.appendChild(i)}return n}var fa="General",In=220,Lc=6;function Ic(e){if(typeof e!="string")return[fa];const t=e.split(/[,;|/]+/).map(a=>a.trim().replace(/\s+/g," ")).filter(a=>a.length>0);return t.length===0?[fa]:Array.from(new Set(t.map(a=>a.toLocaleLowerCase()))).map(a=>t.find(n=>n.toLocaleLowerCase()===a)??fa)}function Nc(e){return e==="positive"||e==="negative"||e==="neutral"?e:"neutral"}function zc(e){if(typeof e!="string")return"";const t=e.trim().replace(/\s+/g," ");return t.length<=In?t:`${t.slice(0,In-3).trimEnd()}...`}function Mc(e){return e.positive>e.negative?"positive":e.negative>e.positive?"negative":"neutral"}function Bc(e){return gt(e==="positive"?["M7 17 17 7","M7 7h10v10"]:e==="negative"?["M7 7 17 17","M17 7v10H7"]:["M5 12h14"],14)}function Rc(e,t="1 customer mentions",a="customers mention"){return e===1?t:`${e} ${a}`}function Oc(e,t){const a=document.createElement("div");a.className="gengage-chat-review-highlights";const n=e.props?.reviews;if(!Array.isArray(n)||n.length===0){const u=document.createElement("div");return u.className="gengage-chat-review-empty",u.textContent=t?.emptyReviewsMessage??"No review summary found.",a.appendChild(u),a}const r=n.filter(u=>u!==null&&typeof u=="object"),i=new Map;for(const u of r){const f=Nc(u.review_class),m=zc(u.review_text),y=Ic(u.review_tag);for(const k of y){const _=k.toLocaleLowerCase();let x=i.get(_);if(x||(x={key:_,label:k,mentions:0,positive:0,negative:0,neutral:0,snippets:[]},i.set(_,x)),x.mentions+=1,f==="positive"?x.positive+=1:f==="negative"?x.negative+=1:x.neutral+=1,m.length>0&&x.snippets.length<Lc&&!x.snippets.some(T=>T.text===m)){const T={text:m,tone:f};u.review_rating!==void 0&&String(u.review_rating).length>0&&(T.rating=u.review_rating),x.snippets.push(T)}}}const o=Array.from(i.values()).sort((u,f)=>f.mentions!==u.mentions?f.mentions-u.mentions:u.label.localeCompare(f.label));if(o.length===0){const u=document.createElement("div");return u.className="gengage-chat-review-empty",u.textContent=t?.emptyReviewsMessage??"No review summary found.",a.appendChild(u),a}const s=(t?.reviewFilterPositive??"positive").toLowerCase(),c=(t?.reviewFilterNegative??"negative").toLowerCase(),l=document.createElement("div");l.className="gengage-chat-review-subjects-heading",l.textContent=t?.reviewSubjectsHeading??"Select to learn more",a.appendChild(l);let g=o[0]?.key??null;const p=document.createElement("div");p.className="gengage-chat-review-subjects gds-toolbar gds-toolbar-compact";const h=document.createElement("section");h.className="gengage-chat-review-detail gds-evidence-card";const d=()=>{for(;h.firstChild;)h.removeChild(h.firstChild);if(!g)return;const u=o.find(k=>k.key===g);if(!u)return;const f=document.createElement("div");f.className="gengage-chat-review-detail-meta";const m=document.createElement("span");if(m.className="gengage-chat-review-detail-mentions",m.textContent=`${Rc(u.mentions,t?.reviewCustomersMentionSingular,t?.reviewCustomersMentionPlural)} "${u.label}"`,f.appendChild(m),u.positive>0){const k=document.createElement("span");k.className="gengage-chat-review-detail-positive",k.textContent=`${u.positive} ${s}`,f.appendChild(k)}if(u.negative>0){const k=document.createElement("span");k.className="gengage-chat-review-detail-negative",k.textContent=`${u.negative} ${c}`,f.appendChild(k)}h.appendChild(f);const y=document.createElement("div");y.className="gengage-chat-review-snippets";for(const k of u.snippets){const _=document.createElement("article");_.className="gengage-chat-review-snippet",_.dataset.tone=k.tone;const x=document.createElement("div");if(x.className="gengage-chat-review-snippet-text",x.textContent=`"${k.text}"`,_.appendChild(x),k.rating!==void 0&&String(k.rating).length>0){const T=document.createElement("div");T.className="gengage-chat-review-snippet-rating",T.textContent=`★ ${String(k.rating)}`,_.appendChild(T)}y.appendChild(_)}h.appendChild(y)},b=()=>{for(const u of p.querySelectorAll(".gengage-chat-review-subject")){const f=u.dataset.subjectKey===g;u.classList.toggle("gengage-chat-review-subject--active",f),u.classList.toggle("gds-chip-active",f),u.setAttribute("aria-pressed",String(f))}};for(const u of o){const f=Mc(u),m=document.createElement("button");m.type="button",m.className="gengage-chat-review-subject gds-chip",m.dataset.subjectKey=u.key,m.dataset.tone=f;const y=document.createElement("span");y.className="gengage-chat-review-subject-icon",y.appendChild(Bc(f)),m.appendChild(y);const k=document.createElement("span");k.className="gengage-chat-review-subject-label",k.textContent=u.label,m.appendChild(k);const _=document.createElement("span");_.className="gengage-chat-review-subject-count",_.textContent=`(${u.mentions})`,m.appendChild(_),m.addEventListener("click",()=>{g=u.key,b(),d()}),p.appendChild(m)}return a.appendChild(p),b(),d(),a.appendChild(h),a}function Dc(e){if(!e)return;const t=e.discountReason??e.discount_reason??e.campaignReason??e.campaign_reason;if(typeof t!="string")return;const a=t.trim();return a.length>0?a:void 0}function et(e,t){if(e.productPriceUi?.showCampaignReason===!0)return Dc(t)}function pt(e,t){const a=t?.originalPriceStyle??t?.price_original_style;if(a==="inline"||a==="strikethrough")return a;const n=e.productPriceUi?.originalPriceStyle;return n==="inline"||n==="strikethrough"?n:"strikethrough"}function Pt(e){const t=document.createElement("div");return t.className="gengage-chat-campaign-reason",t.textContent=e,t}function Tt(e,t){for(const n of["campaignReasonLogoUrl","campaign_reason_logo_url","discountBadgeLogoUrl","discount_badge_logo_url"]){const r=t?.[n];if(typeof r=="string"&&r.trim()){const i=r.trim();if(we(i))return i}}const a=e.productPriceUi?.campaignBadgeLogoUrl;if(typeof a=="string"&&a.trim()){const n=a.trim();if(we(n))return n}}function At(e){const t=document.createElement("div");if(t.className="gengage-chat-campaign-price-badge",t.dataset.gengagePart="campaign-price-badge",e.logoUrl){const i=document.createElement("div");i.className="gengage-chat-campaign-price-badge__logo";const o=document.createElement("img");o.alt="",o.loading="lazy",o.src=e.logoUrl,Se(o),i.appendChild(o),t.appendChild(i)}const a=document.createElement("div");a.className="gengage-chat-campaign-price-badge__body";const n=document.createElement("div");n.className="gengage-chat-campaign-price-badge__reason",n.textContent=e.reasonText;const r=document.createElement("span");return r.className="gengage-chat-campaign-price-badge__sale",r.textContent=e.salePriceFormatted,a.appendChild(n),a.appendChild(r),t.appendChild(a),t}function Nn(e){const t=e.product.sku;if(typeof t=="string"&&t.length>0)return t;const a=e.action?.payload;return a&&typeof a=="object"&&"sku"in a&&typeof a.sku=="string"?a.sku:null}var Fc={winner:"roleWinner",best_value:"roleBestValue",best_alternative:"roleBestAlternative"};function zn(e,t){if(!e||!t)return null;const a=Fc[e];return a?t[a]??e:e}function Uc(e){const t=e.rating,a=typeof t=="number"?t:typeof t=="string"?parseFloat(t):NaN;if(Number.isNaN(a)||a<=0)return null;const n=document.createElement("div");n.className="gengage-chat-ai-toppick-rating",n.dataset.gengagePart="ai-top-pick-rating";const r=document.createElement("span");r.className="gengage-chat-ai-toppick-rating-icon",r.setAttribute("aria-hidden","true"),r.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.6l2.58 5.23 5.77.84-4.17 4.07.98 5.75L12 16.78l-5.16 2.71.99-5.75L3.66 9.67l5.76-.84L12 3.6z"/></svg>';const i=document.createElement("span");return i.className="gengage-chat-ai-toppick-rating-value",i.textContent=a.toFixed(1),n.appendChild(r),n.appendChild(i),n}function $c(e,t,a,n,r){const i=document.createElement("div");i.className="gengage-chat-ai-toppick-media",i.dataset.gengagePart="ai-top-pick-media";const o=e.product,s=o.imageUrl;if(s&&we(s)){const l=document.createElement("img");l.className="gengage-chat-ai-toppick-img",l.dataset.gengagePart="ai-top-pick-image",ue(l,"src",s),l.loading="lazy",l.alt=t,Se(l),i.appendChild(l)}const c=Nn(e);if(c&&!r?.skipOverlayActions){const l=document.createElement("div");if(l.className="gengage-chat-product-card-img-actions",n.onFavoriteToggle){const d=document.createElement("button");d.className="gengage-chat-favorite-btn",d.type="button",d.dataset.gengageFavoriteSku=c,d.setAttribute("aria-label",n.i18n?.addToFavoritesLabel??"Add to favorites");const b=n.favoritedSkus?.has(c)??!1;b&&d.classList.add("gengage-chat-favorite-btn--active"),d.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${b?"currentColor":"none"}" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>`,d.addEventListener("click",u=>{u.stopPropagation(),d.classList.toggle("gengage-chat-favorite-btn--active"),d.querySelector("svg")?.setAttribute("fill",d.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),n.onFavoriteToggle?.(c,o)}),l.appendChild(d)}const g=n.i18n?.findSimilarLabel??"Find Similar",p=document.createElement("button");p.className="gengage-chat-find-similar-pill",p.type="button",p.setAttribute("aria-label",g),p.dataset.tooltip=g,p.innerHTML='<span class="gengage-chat-find-similar-pill-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="6.5"/><path d="M16 16l5.5 5.5"/></svg></span>';const h=document.createElement("span");h.className="gengage-chat-find-similar-pill-text",h.textContent=g,p.appendChild(h),p.addEventListener("click",d=>{d.stopPropagation(),n.onAction({title:g,type:"findSimilar",payload:{sku:c,...s?{image_url:s}:{}}})}),l.appendChild(p),i.appendChild(l)}a.appendChild(i)}function Hc(e,t,a){const n=e.price,r=e.originalPrice;if(!n)return;const i=et(a,e),o=pt(a,e),s=!!(r&&r!==n),c=!!(i&&s),l=Tt(a,e),g=document.createElement("div");if(g.className="gengage-chat-ai-toppick-price",g.dataset.gengagePart="ai-top-pick-price",c){const p=At({reasonText:i,salePriceFormatted:K(n,a.pricing),...l!==void 0?{logoUrl:l}:{}});if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline"),g.appendChild(p);const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=K(r,a.pricing),g.appendChild(h),g.appendChild(d)}else{const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=K(r,a.pricing),g.appendChild(h),g.appendChild(document.createTextNode(" ")),g.appendChild(p)}t.appendChild(g);return}if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline");const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=K(n,a.pricing);const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=K(r,a.pricing),g.appendChild(p),g.appendChild(h),g.appendChild(d)}else if(s){const p=document.createElement("span");p.className="gengage-chat-ai-toppick-original-price",p.textContent=K(r,a.pricing),g.appendChild(p),g.appendChild(document.createTextNode(" "));const h=document.createElement("span");h.className="gengage-chat-ai-toppick-price-current",h.textContent=K(n,a.pricing),g.appendChild(h)}else{const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=K(n,a.pricing),g.appendChild(p)}if(i){const p=document.createElement("div");p.className="gengage-chat-ai-toppick-price-stack",p.appendChild(Pt(i)),p.appendChild(g),t.appendChild(p)}else t.appendChild(g)}function qc(e,t,a){const n=typeof e.reason=="string"?e.reason.trim():"",r=a.hideUserReviews!==!0&&typeof e.reviewHighlight=="string"?e.reviewHighlight.trim():"";if(!(!n&&!r)){if(n){const i=document.createElement("p");i.className="gengage-chat-ai-toppick-reason",i.dataset.gengagePart="ai-top-pick-reason",i.textContent=n,t.appendChild(i)}if(r){const i=document.createElement("div");i.className="gengage-chat-ai-toppick-review",i.dataset.gengagePart="ai-top-pick-review",i.textContent=r,t.appendChild(i)}}}function Mn(e,t,a){const n=document.createElement("div");n.className=a?"gengage-chat-ai-toppick-card gengage-chat-ai-toppick-card--winner gds-card":"gengage-chat-ai-toppick-card gengage-chat-ai-toppick-card--compact gds-card",n.dataset.gengagePart=a?"ai-top-pick-card-winner":"ai-top-pick-card";const r=e.product,i=Nn(e),o=r.url??"",s=r.cartCode,c=r.inStock,l=!!(i&&s&&c!==!1),g=e.action;i&&t.onProductClick?(n.classList.add("gds-clickable"),n.addEventListener("click",x=>{if(x.target.closest(".gengage-chat-ai-toppick-cta")||x.target.closest(".gengage-chat-favorite-btn")||x.target.closest(".gengage-chat-find-similar-pill"))return;const T=r.name;t.onProductClick?.({sku:i,url:o,...T?{name:T}:{}})})):g&&(n.classList.add("gds-clickable"),n.addEventListener("click",x=>{x.target.closest(".gengage-chat-ai-toppick-cta")||x.target.closest(".gengage-chat-favorite-btn")||x.target.closest(".gengage-chat-find-similar-pill")||t.onAction(g)}));const p=r.name||"Product image",h=!a&&t.isMobile===!0,d=a?zn(e.role,t.i18n)??t.i18n?.roleWinner??"TOP MATCH":zn(e.role,t.i18n);if(d&&!h){const x=document.createElement("span");x.className="gengage-chat-ai-toppick-badge gds-badge",x.dataset.gengagePart="ai-top-pick-role-badge",x.textContent=d,n.appendChild(x)}const b=document.createElement("div");b.className="gengage-chat-ai-toppick-top-row",b.dataset.gengagePart="ai-top-pick-top-row",$c(e,p,b,t,{skipOverlayActions:h});const u=document.createElement("div");if(u.className="gengage-chat-ai-toppick-body",u.dataset.gengagePart="ai-top-pick-body",d&&h){const x=document.createElement("div");x.className="gengage-chat-ai-toppick-role-line",x.dataset.gengagePart="ai-top-pick-role-line",x.textContent=d,u.appendChild(x)}const f=r.name;if(f){const x=document.createElement("div");x.className="gengage-chat-ai-toppick-name",x.dataset.gengagePart="ai-top-pick-name",x.textContent=f,u.appendChild(x)}const m=Uc(r);m&&u.appendChild(m),Hc(r,u,t),e.labels&&e.labels.length>0&&u.appendChild(Zc(e.labels)),b.appendChild(u),n.appendChild(b);const y=document.createElement("div");if(y.className="gengage-chat-ai-toppick-detail",y.dataset.gengagePart="ai-top-pick-detail",a)qc(e,y,t);else{const x=typeof e.reason=="string"?e.reason.trim():"";if(x){const T=document.createElement("p");T.className="gengage-chat-ai-toppick-snippet",T.dataset.gengagePart="ai-top-pick-snippet",T.textContent=x,y.appendChild(T)}}y.childNodes.length>0&&n.appendChild(y);const k=!!(i&&t.topPicksLoadingSku===i),_=(l||g)&&!h;if(k||l||g){const x=document.createElement("div");if(x.className="gengage-chat-ai-toppick-spinner",x.dataset.gengagePart="ai-top-pick-spinner",x.style.display=k?"":"none",n.appendChild(x),_){const T=document.createElement("button");T.className="gengage-chat-ai-toppick-cta gds-btn gds-btn-primary",T.dataset.gengagePart="ai-top-pick-cta",T.type="button",T.textContent=l?t.i18n?.addToCartButton??"Add to Cart":t.i18n?.viewDetails??"View Details",T.addEventListener("click",P=>{if(P.stopPropagation(),l){t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:i,cartCode:s,quantity:1}});return}if(g){if(g.type==="findSimilar"&&i&&t.onProductClick){const I=r.name;t.onProductClick({sku:i,url:o,...I?{name:I}:{}});return}t.onAction(g)}}),n.appendChild(T)}}return n}function jc(e,t){const a=document.createElement("div");a.className="gengage-chat-ai-top-picks",a.dataset.gengagePart="ai-top-picks";const n=e.props?.suggestions??[];if(n.length===0)return a;const r=document.createElement("div");r.className="gengage-chat-ai-top-picks-scroll",r.dataset.gengagePart="ai-top-picks-scroll";const i=n[0];if(r.appendChild(Mn(i,t,!0)),n.length>1){const o=document.createElement("div");o.className="gengage-chat-ai-top-picks-rest",o.dataset.gengagePart="ai-top-picks-rest";for(let s=1;s<n.length;s++){const c=n[s],l=c.role==="winner";o.appendChild(Mn(c,t,l))}r.appendChild(o)}return a.appendChild(r),a}function Zc(e){const t=document.createElement("div");t.className="gengage-chat-ai-toppick-labels",t.dataset.gengagePart="ai-top-pick-labels";for(const a of e){const n=document.createElement("span");n.className="gengage-chat-ai-toppick-label gds-chip",n.dataset.gengagePart="ai-top-pick-label",n.dataset.sentiment=a.sentiment??"neutral",n.textContent=a.label,t.appendChild(n)}return t}function Vc(e,t){const a=document.createElement("div");a.className="gengage-chat-grounding-review gds-evidence-card",a.dataset.gengagePart="grounding-review-card";const n=e.props??{},r=n.title,i=n.reviewCount,o=n.action,s=t.i18n?.groundingReviewCta??"Read Reviews",c=document.createElement("span");c.className="gengage-chat-grounding-review-icon",c.appendChild(gt(["M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z","M8 9h8","M8 13h6"])),a.appendChild(c);const l=document.createElement("div");l.className="gengage-chat-grounding-review-body",l.dataset.gengagePart="grounding-review-body";const g=document.createElement("div");if(g.className="gengage-chat-grounding-review-title",g.dataset.gengagePart="grounding-review-title",g.textContent=r??t.i18n?.customerReviewsTitle??"Customer Reviews",l.appendChild(g),i){const b=document.createElement("div");b.className="gengage-chat-grounding-review-subtitle",b.dataset.gengagePart="grounding-review-subtitle",b.textContent=(t.i18n?.groundingReviewSubtitle??"{count} yorum mevcut").replace("{count}",i),l.appendChild(b)}a.appendChild(l);const p=document.createElement("span");p.className="gengage-chat-grounding-review-cta",p.dataset.gengagePart="grounding-review-cta";const h=document.createElement("span");h.textContent=s,p.appendChild(h);const d=document.createElement("span");return d.className="gengage-chat-grounding-review-cta-icon",d.appendChild(gt(["M5 12h14","M15 8l4 4-4 4"],14)),p.appendChild(d),a.appendChild(p),o&&(a.classList.add("gds-clickable"),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t.onAction(o)),a.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),t.onAction(o))})),a}function Gc(e){if(e.action.type!=="findSimilar")return e.action;const t=e.action.payload&&typeof e.action.payload=="object"?e.action.payload:null,a=typeof t?.input=="string"&&t.input.trim()||typeof t?.text=="string"&&t.text.trim()||e.name.trim();if(!a)return e.action;const n={text:a,is_suggested_text:1};if(typeof t?.sku=="string"&&t.sku.trim()&&(n.sku=t.sku),Array.isArray(t?.group_skus)){const r=t.group_skus.filter(i=>typeof i=="string"&&i.length>0);r.length>0&&(n.group_skus=r)}return{title:e.action.title,type:"inputText",payload:n}}function Wc(e,t){const a=document.createElement("div");a.className="gengage-chat-grouping-cards",a.dataset.gengagePart="ai-grouping-cards";const n=e.props?.entries??[];if(n.length===0)return a;const r=e.props?.sectionTitle,i=typeof r=="string"&&r.trim().length>0?r.trim():t.i18n?.aiBrowseCategoriesTitle;if(i){const s=document.createElement("h3");s.className="gengage-chat-grouping-section-title",s.textContent=i,a.appendChild(s)}const o=document.createElement("div");o.className="gengage-chat-grouping-cards-scroll",o.dataset.gengagePart="ai-grouping-cards-scroll";for(const s of n){const c=document.createElement("div");if(c.className="gengage-chat-grouping-card gds-card",c.dataset.gengagePart="ai-grouping-card",c.classList.add("gds-clickable"),c.addEventListener("click",()=>t.onAction(Gc(s))),s.image&&we(s.image)){const h=document.createElement("img");h.className="gengage-chat-grouping-card-img",h.dataset.gengagePart="ai-grouping-card-image",h.draggable=!1,h.src=s.image,h.alt=s.name,h.width=64,h.height=64,c.appendChild(h)}const l=document.createElement("div");l.className="gengage-chat-grouping-card-body",l.dataset.gengagePart="ai-grouping-card-body";const g=document.createElement("span");if(g.className="gengage-chat-grouping-card-name",g.dataset.gengagePart="ai-grouping-card-name",g.textContent=s.name,l.appendChild(g),s.labels&&s.labels.length>0){const h=document.createElement("div");h.className="gengage-chat-grouping-card-labels",h.dataset.gengagePart="ai-grouping-card-labels";for(const d of s.labels.slice(0,2)){const b=document.createElement("span");b.className="gengage-chat-grouping-card-label gds-chip",b.textContent=d,h.appendChild(b)}l.appendChild(h)}c.appendChild(l);const p=document.createElement("span");p.className="gengage-chat-grouping-card-arrow",p.textContent="↳",c.insertBefore(p,c.firstChild),o.appendChild(c)}return a.appendChild(o),a}function Kc(e,t){const a=document.createElement("div");a.className="gengage-chat-suggested-search-cards",a.dataset.gengagePart="ai-suggested-search-cards";const n=e.props?.entries??[];if(n.length===0)return a;for(const r of n){const i=document.createElement("div");if(i.className="gengage-chat-suggested-search-card gds-card",i.dataset.gengagePart="ai-suggested-search-card",i.classList.add("gds-clickable"),i.addEventListener("click",()=>t.onAction(r.action)),r.image&&we(r.image)){const c=document.createElement("img");c.className="gengage-chat-suggested-search-card-img",c.dataset.gengagePart="ai-suggested-search-card-image",c.src=r.image,c.alt=r.shortName,c.width=64,c.height=64,i.appendChild(c)}const o=document.createElement("div");o.className="gengage-chat-suggested-search-card-body",o.dataset.gengagePart="ai-suggested-search-card-body";const s=document.createElement("div");s.className="gengage-chat-suggested-search-card-name",s.dataset.gengagePart="ai-suggested-search-card-name",s.textContent=r.shortName,o.appendChild(s),i.appendChild(o),a.appendChild(i)}return a}function Bn(e,t){const a=e.length>=2,n=t.i18n?.compareSelected??"Compare",r=t.comparisonSelectionWarning,i=document.createElement("div");i.className="gengage-chat-comparison-floating-btn",i.dataset.gengagePart="comparison-dock";const o=document.createElement("div");o.className="gengage-chat-comparison-floating-summary";const s=document.createElement("span");s.className="gengage-chat-comparison-floating-count",s.textContent=String(e.length),o.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-comparison-floating-copy";const l=document.createElement("div");if(l.className="gengage-chat-comparison-floating-title",l.textContent=a?`${n} (${e.length})`:t.i18n?.compareMinHint??"Select at least 2 products",c.appendChild(l),r){const p=document.createElement("div");p.className="gengage-chat-comparison-floating-warning",p.setAttribute("role","status"),p.setAttribute("aria-live","polite"),p.textContent=r,c.appendChild(p)}o.appendChild(c),i.appendChild(o);const g=document.createElement("button");if(g.className="gengage-chat-comparison-floating-action gds-btn gds-btn-primary",g.type="button",g.textContent=n,g.disabled=!a,a||g.classList.add("gengage-chat-comparison-floating-action--disabled"),g.addEventListener("click",()=>{a&&t.onAction({title:n,type:"getComparisonTable",payload:{sku_list:[...e],gengage_analytics_source:"floating_compare_dock"}})}),i.appendChild(g),t.onToggleComparisonSku){const p=document.createElement("button");p.className="gengage-chat-comparison-floating-close gds-btn gds-btn-ghost gds-icon-btn",p.dataset.gengagePart="comparison-dock-close",p.type="button",p.setAttribute("aria-label",t.i18n?.closeAriaLabel??"Close"),p.innerHTML='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" aria-hidden="true"><path d="M18 6L6 18"/><path d="M6 6l12 12"/></svg>',p.addEventListener("click",h=>{h.preventDefault(),h.stopPropagation(),t.onToggleComparisonSku?.("")}),i.appendChild(p)}return i}function Yc(e){const t=document.createElement("div");t.className="gengage-chat-pros-cons gds-card-soft",t.dataset.gengagePart="pros-cons";const a=e.props?.productName;if(a){const i=document.createElement("h4");i.className="gengage-chat-pros-cons-heading",i.textContent=a,t.appendChild(i)}const n=e.props?.pros,r=e.props?.cons;if(n&&n.length>0){const i=document.createElement("ul");i.className="gengage-chat-pros-cons-list",i.dataset.gengagePart="pros-list";for(const o of n){const s=document.createElement("li");s.className="gengage-chat-pros-cons-item",s.dataset.gengagePart="pros-item";const c=document.createElement("span");c.className="gengage-chat-pros-cons-icon gengage-chat-pros-cons-icon--pro",c.textContent="✓",s.appendChild(c);const l=document.createElement("span");l.textContent=o,s.appendChild(l),i.appendChild(s)}t.appendChild(i)}if(r&&r.length>0){const i=document.createElement("ul");i.className="gengage-chat-pros-cons-list",i.dataset.gengagePart="cons-list";for(const o of r){const s=document.createElement("li");s.className="gengage-chat-pros-cons-item",s.dataset.gengagePart="cons-item";const c=document.createElement("span");c.className="gengage-chat-pros-cons-icon gengage-chat-pros-cons-icon--con",c.textContent="✗",s.appendChild(c);const l=document.createElement("span");l.textContent=o,s.appendChild(l),i.appendChild(s)}t.appendChild(i)}return t}function Jc(e,t){const a=e.props?.groups??[],n=e.props?.filterTags??[],r=document.createElement("div");if(r.className="gengage-chat-categories",r.dataset.gengagePart="categories-container",a.length===0)return r;const i=document.createElement("div");i.className="gengage-chat-categories-tabs gds-toolbar",i.dataset.gengagePart="categories-tab-bar",i.setAttribute("role","tablist");const o=[],s=[],c=l=>{for(let g=0;g<o.length;g++){const p=g===l;o[g].classList.toggle("gengage-chat-categories-tab--active",p),o[g].classList.toggle("is-active",p),o[g].setAttribute("aria-selected",String(p)),o[g].tabIndex=p?0:-1,s[g].style.display=p?"":"none"}};for(let l=0;l<a.length;l++){const g=a[l],p=`gengage-cat-tab-${l}`,h=`gengage-cat-panel-${l}`,d=document.createElement("button");if(d.className="gengage-chat-categories-tab gds-tab",d.type="button",d.dataset.gengagePart="categories-tab",d.id=p,d.setAttribute("role","tab"),d.setAttribute("aria-controls",h),d.setAttribute("aria-selected",String(l===0)),d.tabIndex=l===0?0:-1,l===0&&d.classList.add("gengage-chat-categories-tab--active","is-active"),g.image&&we(g.image)){const f=document.createElement("img");f.className="gengage-chat-categories-tab-image",f.draggable=!1,f.src=g.image,f.alt=g.groupName,f.loading="lazy",Se(f),d.appendChild(f)}const b=document.createElement("span");b.className="gengage-chat-categories-tab-text",b.textContent=g.groupName,d.appendChild(b),d.addEventListener("click",()=>c(l)),d.addEventListener("keydown",f=>{let m=-1;f.key==="ArrowRight"||f.key==="ArrowDown"?m=(l+1)%a.length:f.key==="ArrowLeft"||f.key==="ArrowUp"?m=(l-1+a.length)%a.length:f.key==="Home"?m=0:f.key==="End"&&(m=a.length-1),m>=0&&(f.preventDefault(),c(m),o[m].focus())}),o.push(d),i.appendChild(d);const u=document.createElement("div");u.className="gengage-chat-categories-grid",u.dataset.gengagePart="categories-panel",u.id=h,u.setAttribute("role","tabpanel"),u.setAttribute("aria-labelledby",p),l!==0&&(u.style.display="none");for(const f of g.products){const m=Qc(f,t);u.appendChild(m)}s.push(u)}r.appendChild(i);for(const l of s)r.appendChild(l);if(n.length>0){const l=document.createElement("div");l.className="gengage-chat-categories-filter-tags gds-toolbar",l.dataset.gengagePart="categories-filter-tags";for(const g of n){const p=document.createElement("button");p.className="gengage-chat-categories-filter-tag gds-chip",p.type="button",p.dataset.gengagePart="categories-filter-tag",p.textContent=g.title,g.action&&p.addEventListener("click",()=>{t.onAction(g.action)}),l.appendChild(p)}r.appendChild(l)}return r}function Qc(e,t){const a=document.createElement("div");if(a.className="gengage-chat-product-card gds-card gds-product-card gds-card-interactive",a.dataset.gengagePart="categories-product-card",e.imageUrl&&we(e.imageUrl)){const i=document.createElement("img");i.className="gengage-chat-product-card-img",i.draggable=!1,i.src=e.imageUrl,i.alt=e.name,i.loading="lazy",Se(i),a.appendChild(i)}const n=document.createElement("div");n.className="gengage-chat-product-card-body";const r=document.createElement("div");if(r.className="gengage-chat-product-card-name",r.textContent=e.name,n.appendChild(r),e.price){const i=document.createElement("div");i.className="gengage-chat-product-card-price",i.textContent=K(e.price,t.pricing),n.appendChild(i)}return a.appendChild(n),(t.onProductSelect||t.onAction)&&(a.classList.add("gds-clickable"),a.addEventListener("click",()=>{if(e.sku){t.onAction({title:e.name,type:"launchSingleProduct",payload:{sku:e.sku}});return}t.onProductSelect?.(e)})),a}function Xc(e,t){const a=document.createElement("div");a.className="gengage-chat-handoff-notice gds-evidence-card gds-evidence-card-warning",a.dataset.gengagePart="handoff-notice",a.setAttribute("role","alert");const n=document.createElement("span");n.className="gengage-chat-handoff-notice-icon",n.textContent="👤",n.setAttribute("aria-hidden","true"),a.appendChild(n);const r=document.createElement("h4");r.className="gengage-chat-handoff-notice-heading",r.textContent=t.i18n?.handoffHeading??"Transferring to a support agent",a.appendChild(r);const i=e.props?.summary;if(i){const o=document.createElement("p");o.className="gengage-chat-handoff-notice-summary",o.textContent=i,a.appendChild(o)}return a}function el(e,t){const a=e.props?.product??e.props,n=document.createElement("div");if(n.className="gengage-chat-product-summary gds-card",n.dataset.gengagePart="product-summary-card",!a)return n;n.classList.add("gds-clickable"),n.addEventListener("click",m=>{m.target.closest("a")||t.onProductSelect?.(a)});const r=a.imageUrl;if(r&&fe(r)){const m=document.createElement("div");m.className="gengage-chat-product-summary__image",m.dataset.gengagePart="product-summary-image";const y=document.createElement("img");y.loading="lazy",ue(y,"src",r),y.alt=a.name||"Product image",Se(y),m.appendChild(y),n.appendChild(m)}const i=document.createElement("div");i.className="gengage-chat-product-summary__content",i.dataset.gengagePart="product-summary-content";const o=a.brand,s=a.name;if(s){const m=document.createElement("div");m.className="gengage-chat-product-summary__name",m.dataset.gengagePart="product-summary-name";const y=o&&!s.toLowerCase().startsWith(o.toLowerCase())?`${o} ${s}`:s;m.textContent=y,m.title=y,i.appendChild(m)}const c=a.rating,l=a.reviewCount;if(t.hideUserReviews!==!0&&typeof c=="number"&&Number.isFinite(c)&&c>0){const m=document.createElement("div");if(m.className="gengage-chat-product-summary__rating",m.dataset.gengagePart="product-summary-rating",m.appendChild(ma(c)),typeof l=="number"&&Number.isFinite(l)){const y=document.createElement("span");y.className="gengage-chat-product-summary__review-count",y.textContent=` (${l})`,m.appendChild(y)}i.appendChild(m)}const g=a.price,p=a.originalPrice;if(g){const m=et(t,a),y=pt(t,a),k=!!(p&&p!==g),_=document.createElement("div");_.className="gengage-chat-product-summary__price",_.dataset.gengagePart="product-summary-price";const x=!!(m&&k),T=Tt(t,a);if(x){const P=At({reasonText:m,salePriceFormatted:K(g,t.pricing),...T!==void 0?{logoUrl:T}:{}});if(k&&y==="inline"){_.classList.add("gengage-chat-product-summary__price--inline"),_.appendChild(P);const I=document.createElement("span");I.className="gengage-chat-product-summary__price-sep",I.setAttribute("aria-hidden","true");const F=document.createElement("span");F.className="gengage-chat-product-summary__price-original",F.textContent=K(p,t.pricing),_.appendChild(I),_.appendChild(F)}else{const I=document.createElement("span");I.className="gengage-chat-product-summary__price-original",I.textContent=K(p,t.pricing),_.appendChild(I),_.appendChild(document.createTextNode(" ")),_.appendChild(P)}i.appendChild(_)}else{if(k&&y==="inline"){_.classList.add("gengage-chat-product-summary__price--inline");const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=K(g,t.pricing);const I=document.createElement("span");I.className="gengage-chat-product-summary__price-sep",I.setAttribute("aria-hidden","true");const F=document.createElement("span");F.className="gengage-chat-product-summary__price-original",F.textContent=K(p,t.pricing),_.appendChild(P),_.appendChild(I),_.appendChild(F)}else if(k){const P=document.createElement("span");P.className="gengage-chat-product-summary__price-original",P.textContent=K(p,t.pricing),_.appendChild(P),_.appendChild(document.createTextNode(" "));const I=document.createElement("span");I.className="gengage-chat-product-summary__price-current",I.textContent=K(g,t.pricing),_.appendChild(I)}else{const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=K(g,t.pricing),_.appendChild(P)}if(m){const P=document.createElement("div");P.className="gengage-chat-product-summary__price-stack",P.appendChild(Pt(m)),P.appendChild(_),i.appendChild(P)}else i.appendChild(_)}}n.appendChild(i);const h=a.url,d=a.sku,b=a.cartCode??a.cart_code,u=typeof b=="string"&&b.trim()?b.trim():void 0,f=a.inStock;if(d&&u&&f!==!1){const m=document.createElement("button");m.type="button",m.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",m.dataset.gengagePart="product-summary-cta",m.textContent=t.i18n?.addToCartButton??"Add to Cart",m.addEventListener("click",y=>{y.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:d,cartCode:u,quantity:1}})}),n.appendChild(m)}else if(h&&fe(h)){const m=document.createElement("a");m.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",m.dataset.gengagePart="product-summary-cta",ue(m,"href",h),ue(m,"target","_blank"),ue(m,"rel","noopener noreferrer"),m.textContent=t.i18n?.productCtaLabel??"View",n.appendChild(m)}return n}var tl={PhotoAnalysisCard:({element:e,context:t})=>nc(e,t),BeautyPhotoStep:({element:e,context:t})=>wn(e,t)};function ba(){return window.innerWidth<768}var Rn={ActionButtons:({element:e,context:t})=>rl(e,t),ActionButton:({element:e,context:t})=>il(e,t),ProductCard:({element:e,context:t})=>va(e,t),ProductDetailsPanel:({element:e,context:t})=>El(e,t),ProductGrid:({element:e,spec:t,renderElement:a,context:n})=>Ml(e,t,a,n),ReviewHighlights:({element:e,context:t})=>t.hideUserReviews===!0?null:Oc(e,{emptyReviewsMessage:t.i18n?.emptyReviewsMessage,reviewFilterPositive:t.i18n?.reviewFilterPositive,reviewFilterNegative:t.i18n?.reviewFilterNegative,reviewCustomersMentionSingular:t.i18n?.reviewCustomersMentionSingular,reviewCustomersMentionPlural:t.i18n?.reviewCustomersMentionPlural,reviewSubjectsHeading:t.i18n?.reviewSubjectsHeading}),ComparisonTable:({element:e,context:t})=>Bl(e,t),AITopPicks:({element:e,context:t})=>jc(e,t),GroundingReviewCard:({element:e,context:t})=>t.hideUserReviews===!0?null:Vc(e,t),AIGroupingCards:({element:e,context:t})=>Wc(e,t),AISuggestedSearchCards:({element:e,context:t})=>Kc(e,t),ProsAndCons:({element:e})=>Yc(e),CategoriesContainer:({element:e,context:t})=>Jc(e,t),HandoffNotice:({element:e,context:t})=>Xc(e,t),ProductSummaryCard:({element:e,context:t})=>el(e,t),Divider:({element:e})=>Rl(e),...tl},On=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function al(){return{...Rn}}function nl(e,t,a=Rn,n=On){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-chat-uispec",unknownRenderer:n})}function rl(e,t){const a=document.createElement("div");a.className="gengage-chat-action-buttons";const n=e.props?.buttons;if(n)for(const r of n){const i=document.createElement("button");i.className="gengage-chat-action-btn",i.textContent=r.label,i.addEventListener("click",()=>t.onAction(r.action)),a.appendChild(i)}return a}function il(e,t){const a=document.createElement("button");a.className="gengage-chat-action-btn";const n=e.props?.label;typeof n=="string"&&(a.textContent=n);const r=e.props?.action;return r&&a.addEventListener("click",()=>t.onAction(r)),a}function Dn(e,t,a,n,r){e.replaceChildren();const i=pt(t,a),o=!!(r&&n&&r!==n),s=et(t,a),c=!!(s&&o),l=Tt(t,a);if(!n||parseFloat(n)<=0)return;if(c){const p=At({reasonText:s,salePriceFormatted:K(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const h=document.createElement("div");h.className="gengage-chat-product-card-price-row",h.appendChild(p);const d=document.createElement("span");d.className="gengage-chat-product-card-price-sep",d.setAttribute("aria-hidden","true");const b=document.createElement("span");b.className="gengage-chat-product-card-original-price",b.textContent=K(r,t.pricing),h.appendChild(d),h.appendChild(b),e.appendChild(h);return}if(e.classList.remove("gengage-chat-product-card-price-block--inline"),e.appendChild(p),o){e.appendChild(document.createTextNode(" "));const h=document.createElement("span");h.className="gengage-chat-product-card-original-price",h.textContent=K(r,t.pricing),e.appendChild(h)}return}if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const p=document.createElement("div");p.className="gengage-chat-product-card-price-row";const h=document.createElement("span");h.className="gengage-chat-product-card-current-price",h.textContent=K(n,t.pricing);const d=document.createElement("span");d.className="gengage-chat-product-card-price-sep",d.setAttribute("aria-hidden","true");const b=document.createElement("span");b.className="gengage-chat-product-card-original-price",b.textContent=K(r,t.pricing),p.appendChild(h),p.appendChild(d),p.appendChild(b),e.appendChild(p);return}e.classList.remove("gengage-chat-product-card-price-block--inline");const g=document.createElement("span");if(g.className="gengage-chat-product-card-current-price",g.textContent=K(n,t.pricing),e.appendChild(g),o){e.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-product-card-original-price",p.textContent=K(r,t.pricing),e.appendChild(p)}}function Fn(e,t,a,n,r,i,o){e.classList.remove("gengage-chat-product-details-price--inline"),e.replaceChildren(),e.className="gengage-chat-product-details-price";const s=et(t,a),c=!!(s&&o),l=Tt(t,a);if(c){const p=At({reasonText:s,salePriceFormatted:K(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline"),e.appendChild(p);const h=document.createElement("span");h.className="gengage-chat-product-details-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-product-details-original-price",d.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(d)}else{if(o){const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(document.createTextNode(" "))}e.appendChild(p)}}else if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline");const p=document.createElement("span");p.className="gengage-chat-product-details-current-price",p.textContent=K(n,t.pricing);const h=document.createElement("span");h.className="gengage-chat-product-details-price-sep",h.setAttribute("aria-hidden","true");const d=document.createElement("span");d.className="gengage-chat-product-details-original-price",d.textContent=K(r,t.pricing),e.appendChild(p),e.appendChild(h),e.appendChild(d)}else{if(o){const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=K(r,t.pricing),e.appendChild(h),e.appendChild(document.createTextNode(" "))}const p=document.createElement("span");p.className="gengage-chat-product-details-current-price",p.textContent=K(n,t.pricing),e.appendChild(p)}const g=Lt(a,"discountPercent","price_discount_rate");if(!t.hideProductDiscountBadge&&typeof g=="number"&&g>0){const p=document.createElement("span");p.className="gengage-chat-product-details-discount-badge",p.textContent=`%${ua(g)}`,e.appendChild(p)}}function va(e,t){const a=document.createElement("div");a.className="gengage-chat-product-card gds-card gds-product-card gds-card-interactive";const n=e.props?.product??e.props;if(!n)return a;const r=n.sku;r&&(a.dataset.sku=r);const i=e.props?.action;(t.onProductSelect||i)&&(a.classList.add("gds-clickable"),a.addEventListener("click",v=>{if(!a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")&&!v.target.closest(".gengage-chat-product-card-atc")&&!v.target.closest(".gengage-chat-product-card-cta")){if(i){t.onAction(i);return}t.onProductSelect?.(n)}}));const o=n.imageUrl;if(o&&fe(o)){const v=document.createElement("div");v.className="gengage-chat-product-card-img-wrapper";const L=document.createElement("img");L.className="gengage-chat-product-card-img",L.loading="lazy",ue(L,"src",o);const R=n.name;R&&(L.alt=R),Se(L),v.appendChild(L);const M=n.discountPercent;if(!t.hideProductDiscountBadge&&typeof M=="number"&&M>0){const A=document.createElement("span");A.className="gengage-chat-product-card-discount-badge",A.textContent=`%${ua(M)}`,v.appendChild(A)}const H=document.createElement("div");H.className="gengage-chat-product-card-img-actions";const q=n.sku;if(q&&t.onFavoriteToggle){const A=document.createElement("button");A.className="gengage-chat-favorite-btn",A.type="button",A.dataset.gengageFavoriteSku=q,A.setAttribute("aria-label",t.i18n?.addToFavoritesLabel??"Add to favorites");const E=t.favoritedSkus?.has(q)??!1;E&&A.classList.add("gengage-chat-favorite-btn--active"),A.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${E?"currentColor":"none"}" stroke="currentColor" stroke-width="2"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>`,A.addEventListener("click",N=>{N.stopPropagation(),A.classList.toggle("gengage-chat-favorite-btn--active");const z=A.querySelector("svg");z&&z.setAttribute("fill",A.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),t.onFavoriteToggle(q,n)}),H.appendChild(A)}const j=n.sku,w=t.i18n?.findSimilarLabel??"Find Similar";if(j){const A=document.createElement("button");A.className="gengage-chat-find-similar-pill",A.type="button",A.setAttribute("aria-label",w),A.dataset.tooltip=w,A.innerHTML='<span class="gengage-chat-find-similar-pill-icon" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="6.5"/><path d="M16 16l5.5 5.5"/></svg></span>';const E=document.createElement("span");E.className="gengage-chat-find-similar-pill-text",E.textContent=w,A.appendChild(E),A.addEventListener("click",N=>{N.stopPropagation(),t.onAction({title:w,type:"findSimilar",payload:{sku:j,...o?{image_url:o}:{}}})}),H.appendChild(A)}H.childElementCount>0&&v.appendChild(H),a.appendChild(v)}const s=document.createElement("div");s.className="gengage-chat-product-card-body";const c=n.brand;if(c){const v=document.createElement("div");v.className="gengage-chat-product-card-brand",v.textContent=c,s.appendChild(v)}const l=n.rating,g=n.reviewCount,p=n.price,h=n.originalPrice,d=n.price_async,b=et(t,n),u=pt(t,n),f=!!(h&&p&&h!==p&&parseFloat(p)>0),m=!!(b&&f),y=!!(b&&!m||f&&u==="inline"),k=typeof l=="number"&&Number.isFinite(l)&&l>0,_=document.createElement("div");_.className="gengage-chat-product-card-meta-row";const x=document.createElement("div");x.className="gengage-chat-product-card-price gengage-chat-product-card-price-block";const T=y?(()=>{const v=document.createElement("div");return v.className="gengage-chat-product-card-price-stack",b&&!m&&v.appendChild(Pt(b)),v.appendChild(x),v})():x;if(d===!0){const v=document.createElement("span");v.className="gengage-chat-price-skeleton",x.appendChild(v),setTimeout(()=>{v.parentElement&&(p&&parseFloat(p)>0?Dn(x,t,n,p,n.originalPrice):v.remove())},300)}else p&&parseFloat(p)>0&&Dn(x,t,n,p,h);if((x.childElementCount>0||d===!0)&&_.appendChild(T),k){const v=document.createElement("div");v.className="gengage-chat-product-card-rating gengage-chat-product-card-rating-compact";const L=ha(l),R=[`${L.toFixed(1)}`,"out of 5 stars"];typeof g=="number"&&Number.isFinite(g)&&R.push(`(${g} reviews)`),v.setAttribute("aria-label",R.join(" "));const M=document.createElement("span");M.className="gengage-chat-product-card-rating-compact-star",M.setAttribute("aria-hidden","true"),M.innerHTML='<svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M12 3.6l2.58 5.23 5.77.84-4.17 4.07.98 5.75L12 16.78l-5.16 2.71.99-5.75L3.66 9.67l5.76-.84L12 3.6z"/></svg>';const H=document.createElement("span");H.className="gengage-chat-product-card-rating-compact-value",H.textContent=L.toFixed(1),v.appendChild(M),v.appendChild(H),_.appendChild(v)}_.childElementCount===0&&(_.classList.add("gengage-chat-product-card-meta-row--empty"),_.setAttribute("aria-hidden","true")),s.appendChild(_);const P=n.name;if(P){const v=document.createElement("div");v.className="gengage-chat-product-card-name",v.textContent=P,v.title=P,s.appendChild(v)}const I=n.inStock;if(t.hideStockStatus!==!0&&typeof I=="boolean"){const v=document.createElement("div");v.className=`gengage-chat-product-card-stock ${I?"is-in-stock":"is-out-of-stock"}`,v.textContent=I?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",s.appendChild(v)}a.appendChild(s);const F=n.url,X=n.sku,ne=n.cartCode,me=!!(ne&&X&&I!==!1),O=t.i18n?.productCtaLabel??"View";if(me){const v=document.createElement("div");v.className="gengage-chat-product-card-buy-footer";const L=document.createElement("button");L.type="button",L.className="gengage-chat-product-card-buy-trigger",L.textContent=O,L.addEventListener("click",R=>{R.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??O,type:"addToCart",payload:{sku:X,cartCode:ne,quantity:1}})}),v.appendChild(L),a.appendChild(v)}else if(i){const v=document.createElement("button");v.className="gengage-chat-product-card-cta",v.type="button",v.textContent=i.type==="launchSingleProduct"?O:i.title||O,v.addEventListener("click",L=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){L.stopPropagation();return}t.onAction(i)}),a.appendChild(v)}else if(F&&fe(F)){const v=document.createElement("a");v.className="gengage-chat-product-card-cta",ue(v,"href",F),ue(v,"target","_blank"),ue(v,"rel","noopener noreferrer"),v.textContent=O,v.addEventListener("click",L=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){L.preventDefault(),L.stopPropagation();return}t.onProductClick&&X&&(L.preventDefault(),t.onProductClick({sku:X,url:F,...P?{name:P}:{}}))}),a.appendChild(v)}if(t.comparisonSelectMode&&X&&t.onToggleComparisonSku){const v=document.createElement("div");v.className="gengage-chat-comparison-select-wrapper";const L=t.comparisonSelectedSkus?.includes(X)??!1;L&&v.classList.add("gengage-chat-comparison-select-wrapper--selected");const R=n.name??X,M=t.i18n?.comparisonSelectCardHint??"Tap anywhere on the card to add or remove it from comparison.";v.setAttribute("role","group"),v.setAttribute("aria-label",`${String(R)}. ${M}`);const H=document.createElement("button");H.type="button",H.className="gengage-chat-comparison-checkbox",H.dataset.selected=L?"true":"false",H.setAttribute("aria-pressed",L?"true":"false");const q=document.createElement("span");q.className="gengage-chat-comparison-checkbox-icon",q.innerHTML=L?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const j=document.createElement("span");j.className="gengage-chat-comparison-checkbox-label",j.textContent=L?t.i18n?.comparisonSelectedLabel??"Selected":t.i18n?.comparisonSelectLabel??"Select to compare",H.appendChild(q),H.appendChild(j),H.addEventListener("click",A=>{A.stopPropagation(),t.onToggleComparisonSku?.(X)});const w=document.createElement("div");return w.className="gengage-chat-comparison-card-hint",w.setAttribute("aria-hidden","true"),w.textContent=M,v.addEventListener("click",A=>{A.target.closest(".gengage-chat-comparison-checkbox")||(A.stopPropagation(),t.onToggleComparisonSku?.(X))}),v.appendChild(H),v.appendChild(w),v.appendChild(a),v}return a}var Un=new Set(["color","colour","renk","renk kodu","color code"]),ol=new Set(["size","beden","boyut"]),sl=new Set(["finish","bitiş","bitişi"]),cl=["variants","variantOptions","variant_options","productVariants","product_variants","options"],ll=new Set(["H2","H3","H4","P","BR","UL","OL","LI","STRONG","B","EM","I"]),dl=new Set(["SCRIPT","STYLE","NOSCRIPT","IFRAME","OBJECT","EMBED"]);function _e(e,...t){for(const a of t){const n=e[a];if(typeof n=="string"){const r=n.trim();if(r.length>0)return r}}}function Lt(e,...t){for(const a of t){const n=e[a];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){const r=Number(n.replace(",","."));if(Number.isFinite(r))return r}}}function It(e,...t){for(const a of t){const n=e[a];if(typeof n=="boolean")return n}}function gl(e,...t){for(const a of t){const n=e[a];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function pl(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function hl(e){const t=[...pl(e.images),_e(e,"imageUrl","image_url","image")].filter(a=>!!a&&fe(a));return Array.from(new Set(t))}function ul(e){return typeof DOMParser<"u"?(new DOMParser().parseFromString(e,"text/html").body.textContent??"").replace(/\s+/g," ").trim():e.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim()}function ml(e){const t=_e(e,"description_html","descriptionHtml");if(t){const n=ul(t);if(n)return{text:n,html:t}}const a=_e(e,"description");return a?{text:a}:void 0}function Nt(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;const a=t,n=_e(a,"key","name","label","title"),r=a.value,i=typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r).trim():void 0;return!n||!i?null:{key:n,value:i}}).filter(t=>t!==null):e&&typeof e=="object"?Object.entries(e).map(([t,a])=>{const n=typeof a=="string"||typeof a=="number"||typeof a=="boolean"?String(a).trim():void 0;return!t||!n?null:{key:t,value:n}}).filter(t=>t!==null):[]}function $n(e){const t=Nt(e.features);return t.length>0?t:Nt(e.specifications)}function fl(e){const t=e.specifications,a=Nt(t);if(a.length>0)return Array.isArray(t)?a:Object.fromEntries(a.map(r=>[r.key,r.value]));const n=Nt(e.features);return n.length>0?n:void 0}function Re(e,...t){return _e(e,...t)}function Hn(e,...t){return Lt(e,...t)}function qn(e){return Re(e,"value","option_value","attribute_value","label","title","name","variant_name","sku")}function jn(e){const t=Re(e,"type","attribute","option_name","attribute_name");return t||(Re(e,"value")?Re(e,"name","variant_name"):void 0)}function bl(e){const t=jn(e)?.toLowerCase();return!!(_e(e,"color","colour","color_hex","hex","swatch","swatchColor")||t&&Un.has(t))}function Zn(e){if(!e)return;const t=e.trim();if(!(!t||t.includes(";"))&&(typeof CSS<"u"&&CSS.supports?.("color",t)||/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(t)))return t}function vl(e){const t=Zn(Re(e,"swatchColor","swatch","color_hex","hex","color","colour"));if(t)return t;if(bl(e))return Zn(qn(e))}function yl(e){return Re(e,"image","imageUrl","image_url","swatchImage","swatch_image")}function _l(e){return Hn(e,"price_discounted","priceDiscounted")??Re(e,"price_discounted","priceDiscounted")??Hn(e,"price")??Re(e,"price")}function xl(e){const t=e.trim().toLowerCase();return Un.has(t)||ol.has(t)||sl.has(t)}function wl(e){const t=e.trim().toLowerCase();return t==="renk kodu"?"Renk":t==="color code"?"Color":e.trim()}function kl(e){for(const t of cl){const a=e[t];if(!Array.isArray(a))continue;const n=a.filter(r=>!!r&&typeof r=="object"&&!Array.isArray(r));if(n.length>0)return n}}function Cl(e){const t=kl(e);if(t)return t;const a=_e(e,"sku"),n=It(e,"inStock","in_stock"),r=[],i=new Set,o=(c,l)=>{if(!xl(c)||typeof l!="string"&&typeof l!="number"&&typeof l!="boolean")return;const g=String(l).trim();if(!g)return;const p=wl(c),h=`${p.toLowerCase()}:${g.toLowerCase()}`;i.has(h)||(i.add(h),r.push({name:p,value:g,sku:a,inStock:n}))},s=gl(e,"facetHits","facet_hits");if(s)for(const[c,l]of Object.entries(s))o(c,l);for(const c of $n(e))o(c.key,c.value);return r}function Sl(e,t){const a=Array.from(new Set(e.map(jn).filter(n=>!!n)));return a.length===1?`${e.length} ${a[0]}`:t.i18n?.variantsLabel??"Variants"}function El(e,t){const a=document.createElement("article");a.className="gengage-chat-product-details-panel";const n=e.props?.product??e.props;if(!n)return a;const r=_e(n,"name"),i=_e(n,"brand"),o=_e(n,"sku"),s=_e(n,"cartCode","cart_code"),c=_e(n,"price"),l=_e(n,"originalPrice","price_original"),g=It(n,"price_async"),p=et(t,n),h=pt(t,n),d=!!(l&&c&&l!==c),b=It(n,"inStock","in_stock"),u=Lt(n,"reviewCount","review_count"),f=Lt(n,"rating"),m=hl(n),y=$n(n).slice(0,4);if(m.length>1){const v=document.createElement("div");v.className="gengage-chat-product-details-media gengage-chat-product-details-gallery gengage-chat-product-details-img-wrap";const L=document.createElement("img");L.className="gengage-chat-product-details-img",ue(L,"src",m[0]),L.alt=r??"Product image",Se(L),v.appendChild(L);const R=document.createElement("div");R.className="gengage-chat-product-gallery-thumbs";const M=6;let H=null,q=0;const j=t.i18n,w=j?.galleryPrevAriaLabel??"Previous image",A=j?.galleryNextAriaLabel??"Next image",E=$=>$==="prev"?'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>':'<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="9 18 15 12 9 6"/></svg>',N=document.createElement("button");N.type="button",N.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--prev gds-btn gds-btn-ghost gds-icon-btn",N.setAttribute("aria-label",w),N.innerHTML=E("prev");const z=document.createElement("button");z.type="button",z.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--next gds-btn gds-btn-ghost gds-icon-btn",z.setAttribute("aria-label",A),z.innerHTML=E("next");const B=()=>{N.disabled=q<=0,z.disabled=q>=m.length-1},U=$=>{if($<0||$>=m.length||$===q)return;const ie=m[$];if(!ie)return;ue(L,"src",ie);const Y=R.querySelectorAll(".gengage-chat-product-gallery-thumb");H&&H.classList.remove("gengage-chat-product-gallery-thumb--active"),$<M&&Y[$]?(Y[$].classList.add("gengage-chat-product-gallery-thumb--active"),H=Y[$]):H=null,q=$,B()};for(let $=0;$<m.length;$++){const ie=m[$];if($>=M)break;const Y=document.createElement("img");Y.className="gengage-chat-product-gallery-thumb",$===0&&(Y.classList.add("gengage-chat-product-gallery-thumb--active"),H=Y),ue(Y,"src",ie),Y.alt=`${r??"Product"} ${$+1}`,Y.width=48,Y.height=48,Se(Y),Y.addEventListener("click",()=>{U($)}),R.appendChild(Y)}if(m.length>M){const $=document.createElement("span");$.className="gengage-chat-product-gallery-thumb-more",$.textContent=`+${m.length-M}`,R.appendChild($)}N.addEventListener("click",$=>{$.stopPropagation(),U(q-1)}),z.addEventListener("click",$=>{$.stopPropagation(),U(q+1)}),B();let ee=0;const Q=50;L.addEventListener("touchstart",$=>{ee=$.changedTouches[0].clientX},{passive:!0}),L.addEventListener("touchend",$=>{const ie=$.changedTouches[0].clientX,Y=ee-ie;Math.abs(Y)<Q||U(Y>0?Math.min(q+1,m.length-1):Math.max(q-1,0))}),v.appendChild(N),v.appendChild(z),v.appendChild(R),a.appendChild(v)}else if(m.length===1){const v=document.createElement("div");v.className="gengage-chat-product-details-media gengage-chat-product-details-img-wrap";const L=document.createElement("img");L.className="gengage-chat-product-details-img",L.loading="lazy",ue(L,"src",m[0]),Se(L),L.alt=r??"Product image",v.appendChild(L),a.appendChild(v)}const k=document.createElement("div");if(k.className="gengage-chat-product-details-content",i&&(!r||!r.toLowerCase().startsWith(i.toLowerCase()))){const v=document.createElement("div");v.className="gengage-chat-product-details-brand",v.textContent=i,k.appendChild(v)}if(r){const v=document.createElement("h3");v.className="gengage-chat-product-details-title",v.textContent=r,v.title=r,k.appendChild(v)}if(t.hideUserReviews!==!0&&typeof f=="number"&&Number.isFinite(f)&&f>0){const v=document.createElement(o?"button":"div");v.className="gengage-chat-product-details-rating",o&&(v.type="button",v.classList.add("gengage-chat-product-details-rating--clickable"),v.setAttribute("aria-label",t.i18n?.groundingReviewCta??"Read Reviews"),v.addEventListener("click",()=>{t.onAction({title:t.i18n?.customerReviewsTitle??"Customer Reviews",type:"reviewSummary",payload:{sku:o}})})),v.appendChild(ma(f));const L=document.createElement("span");if(L.className="gengage-chat-product-details-rating-value",L.textContent=ha(f).toFixed(1),v.appendChild(L),typeof u=="number"&&Number.isFinite(u)){const R=document.createElement("span");R.className="gengage-chat-product-details-review-count",R.textContent=` (${u})`,v.appendChild(R)}k.appendChild(v)}{const v=!!(p&&d);let L=k;if(p&&!v){const M=document.createElement("div");M.className="gengage-chat-product-details-price-stack",M.appendChild(Pt(p)),k.appendChild(M),L=M}const R=document.createElement("div");if(R.className="gengage-chat-product-details-price",g===!0){const M=document.createElement("span");M.className="gengage-chat-price-skeleton",R.appendChild(M),L.appendChild(R),setTimeout(()=>{if(M.parentElement)if(c&&parseFloat(c)>0)Fn(R,t,n,c,l,h,d);else{const H=R.parentElement;R.remove(),H?.classList.contains("gengage-chat-product-details-price-stack")&&H.remove()}},300)}else if(c&&parseFloat(c)>0)Fn(R,t,n,c,l,h,d),L.appendChild(R);else if(p){const M=L;M.classList.contains("gengage-chat-product-details-price-stack")&&M.remove()}}if(t.hideStockStatus!==!0&&typeof b=="boolean"){const v=document.createElement("div");v.className=`gengage-chat-product-details-stock ${b?"is-in-stock":"is-out-of-stock"}`,v.textContent=b?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",k.appendChild(v)}const _=n.promotions;if(_&&_.length>0){const v=document.createElement("div");v.className="gengage-chat-product-details-promos";for(const L of _.slice(0,3)){if(!L||/%(0(\.0+)?)\s/.test(L))continue;const R=document.createElement("span");R.className="gengage-chat-product-details-promo-badge",R.textContent=L,R.title=L,v.appendChild(R)}v.childElementCount>0&&k.appendChild(v)}if(y.length>0){const v=document.createElement("dl");v.className="gengage-chat-product-details-facts";for(const L of y){const R=document.createElement("div");R.className="gengage-chat-product-details-fact";const M=document.createElement("dt");M.textContent=L.key;const H=document.createElement("dd");H.textContent=L.value,R.appendChild(M),R.appendChild(H),v.appendChild(R)}k.appendChild(v)}const x=Cl(n);if(x.length>0){const v=document.createElement("div");v.className="gengage-chat-product-variants";const L=document.createElement("div");L.className="gengage-chat-product-variants-label",L.textContent=Sl(x,t),v.appendChild(L);const R=document.createElement("div");R.className="gengage-chat-product-variants-list";for(const M of x){const H=qn(M),q=Re(M,"sku");if(!H&&!q)continue;const j=document.createElement("button");j.className="gengage-chat-product-variant-btn gds-chip",j.type="button";const w=H??q??"";j.title=w;const A=It(M,"in_stock","inStock");q&&o&&q===o?(j.classList.add("gengage-chat-product-variant-btn--active"),j.setAttribute("aria-pressed","true")):j.setAttribute("aria-pressed","false"),A===!1&&(j.classList.add("gengage-chat-product-variant-btn--out"),j.disabled=!0);const E=yl(M),N=vl(M);if(E&&fe(E)){const U=document.createElement("img");U.className="gengage-chat-product-variant-swatch gengage-chat-product-variant-swatch--image",ue(U,"src",E),U.alt="",U.setAttribute("aria-hidden","true"),Se(U),j.appendChild(U)}else if(N){const U=document.createElement("span");U.className="gengage-chat-product-variant-swatch",U.setAttribute("aria-hidden","true"),U.style.backgroundColor=N,j.appendChild(U)}const z=document.createElement("span");z.className="gengage-chat-product-variant-label",z.textContent=w,j.appendChild(z);const B=_l(M);if(B&&String(B)!==String(c)){const U=document.createElement("span");U.className="gengage-chat-product-variant-price",U.textContent=K(String(B),t.pricing),j.appendChild(U)}if(q&&q!==o){const U=r??"",ee=(typeof M.value=="string"?M.value.trim():"")||(typeof M.name=="string"?M.name.trim():"")||(typeof M.variant_name=="string"?M.variant_name.trim():"")||"",Q=U.length>0?ee.length>0&&ee!==U?`${U} (${ee})`:U:w;j.addEventListener("click",()=>{t.onAction({title:Q,type:"launchVariant",payload:{sku:q}})})}R.appendChild(j)}R.childElementCount>0&&(v.appendChild(R),k.appendChild(v))}const T=document.createElement("div");T.className="gengage-chat-product-details-actions";const P=e.props?.action;if(P){const v=document.createElement("button");v.className="gengage-chat-product-details-cta gds-btn gds-btn-primary",v.type="button",v.textContent=P.title||t.i18n?.productCtaLabel||"View",v.addEventListener("click",()=>t.onAction(P)),T.appendChild(v)}if(s&&o&&b!==!1){const v=document.createElement("button");v.className="gengage-chat-product-details-atc gds-btn gds-btn-primary",v.type="button",v.textContent=t.i18n?.addToCartButton??"Add to Cart",v.addEventListener("click",()=>{t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:o,cartCode:s,quantity:1}})}),T.appendChild(v)}const I=_e(n,"url");if(!P&&I&&fe(I)){const v=document.createElement("a");v.className="gengage-chat-product-details-cta gds-btn gds-btn-secondary",ue(v,"href",I),ue(v,"target","_blank"),ue(v,"rel","noopener noreferrer"),v.textContent=t.i18n?.viewOnSiteLabel??t.i18n?.productCtaLabel??"View on Site",v.addEventListener("click",L=>{t.onProductClick&&o&&(L.preventDefault(),t.onProductClick({sku:o,url:I,...r?{name:r}:{}}))}),T.appendChild(v)}const F=I;if(F&&fe(F)){let H=function(j,w){const A=document.createElementNS(R,"circle");A.setAttribute("cx",j),A.setAttribute("cy",w),A.setAttribute("r","3"),M.appendChild(A)},q=function(j,w,A,E){const N=document.createElementNS(R,"line");N.setAttribute("x1",j),N.setAttribute("y1",w),N.setAttribute("x2",A),N.setAttribute("y2",E),M.appendChild(N)};var me=H,O=q;const v=document.createElement("button");v.className="gengage-chat-product-details-share gds-btn gds-btn-ghost gds-icon-btn",v.type="button";const L=t.i18n?.shareButton??"Share";v.title=L,v.setAttribute("aria-label",L);const R="http://www.w3.org/2000/svg",M=document.createElementNS(R,"svg");M.setAttribute("width","18"),M.setAttribute("height","18"),M.setAttribute("viewBox","0 0 24 24"),M.setAttribute("fill","none"),M.setAttribute("stroke","currentColor"),M.setAttribute("stroke-width","2"),M.setAttribute("stroke-linecap","round"),M.setAttribute("stroke-linejoin","round"),H("18","5"),H("6","12"),H("18","19"),q("8.59","13.51","15.42","17.49"),q("15.41","6.51","8.59","10.49"),v.appendChild(M),v.addEventListener("click",async()=>{try{navigator.share?await navigator.share({title:r??"",url:F}):navigator.clipboard&&(await navigator.clipboard.writeText(F),v.classList.add("gengage-chat-product-details-share--copied"),setTimeout(()=>v.classList.remove("gengage-chat-product-details-share--copied"),1500))}catch{}}),T.appendChild(v)}T.childElementCount>0&&k.appendChild(T),a.appendChild(k);const X=ml(n),ne=fl(n);return(X||ne)&&a.appendChild(Al(X,ne,t)),a}function ya(e){if(e.nodeType===Node.TEXT_NODE)return document.createTextNode(e.textContent??"");if(e.nodeType!==Node.ELEMENT_NODE)return null;const t=e,a=t.tagName.toUpperCase();if(dl.has(a))return null;if(!ll.has(a)){const r=document.createDocumentFragment();for(const i of Array.from(t.childNodes)){const o=ya(i);o&&r.appendChild(o)}return r}const n=document.createElement(a.toLowerCase());for(const r of Array.from(t.childNodes)){const i=ya(r);i&&n.appendChild(i)}return n}function Pl(e,t){const a=t.split(/\n{2,}/).map(n=>n.replace(/\s+/g," ").trim()).filter(Boolean);if(a.length!==0)for(const n of a){const r=document.createElement("p");r.textContent=n,e.appendChild(r)}}function Tl(e,t){if(e.classList.add("gengage-chat-product-description"),t.html&&typeof DOMParser<"u"){const a=new DOMParser().parseFromString(t.html,"text/html"),n=Array.from(a.body.childNodes).map(r=>ya(r)).filter(r=>!!r&&(r.nodeType===Node.ELEMENT_NODE||!!r.textContent?.trim()));if(n.length>0){for(const r of n)e.appendChild(r);return}}Pl(e,t.text)}function Al(e,t,a){const n=document.createElement("div");n.className="gengage-chat-product-detail-tabs";const r=document.createElement("div");r.className="gengage-chat-product-detail-tab-bar gds-toolbar";const i=[];if(e){const s=document.createElement("button");s.className="gengage-chat-product-detail-tab gds-tab gengage-chat-product-detail-tab--active is-active",s.type="button",s.setAttribute("aria-selected","true"),s.textContent=a.i18n?.productInfoTab??"Product Info",r.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-product-detail-tab-panel",Tl(c,e),i.push(c)}if(t){const s=document.createElement("button");s.className=`gengage-chat-product-detail-tab gds-tab${e?"":" gengage-chat-product-detail-tab--active is-active"}`,s.type="button",s.setAttribute("aria-selected",e?"false":"true"),s.textContent=a.i18n?.specificationsTab??"Specifications",r.appendChild(s);const c=document.createElement("div");c.className="gengage-chat-product-detail-tab-panel",e&&(c.style.display="none");const l=document.createElement("table");l.className="gengage-chat-product-specs-table";const g=Array.isArray(t)?t:Object.entries(t).map(([p,h])=>({key:p,value:h}));for(const p of g){const h=document.createElement("tr"),d=document.createElement("td");d.className="gengage-chat-product-specs-key",d.textContent=p.key;const b=document.createElement("td");b.className="gengage-chat-product-specs-value",b.textContent=p.value,h.appendChild(d),h.appendChild(b),l.appendChild(h)}c.appendChild(l),i.push(c)}const o=r.querySelectorAll(".gengage-chat-product-detail-tab");o.forEach((s,c)=>{s.addEventListener("click",()=>{o.forEach(l=>{l.classList.remove("gengage-chat-product-detail-tab--active","is-active"),l.setAttribute("aria-selected","false")}),s.classList.add("gengage-chat-product-detail-tab--active","is-active"),s.setAttribute("aria-selected","true"),i.forEach((l,g)=>{l.style.display=g===c?"":"none"})})}),n.appendChild(r);for(const s of i)n.appendChild(s);return n}function Vn(e){const t='width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"';switch(e){case"related":return`<svg ${t} aria-hidden="true"><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></svg>`;case"priceAsc":return`<svg ${t} aria-hidden="true"><polyline points="22 7 13.5 15.5 8.5 10.5 2 17"/><polyline points="16 7 22 7 22 13"/></svg>`;case"priceDesc":return`<svg ${t} aria-hidden="true"><polyline points="22 17 13.5 8.5 8.5 13.5 2 7"/><polyline points="16 17 22 17 22 11"/></svg>`;default:return""}}function Ll(){return'<svg class="gengage-chat-product-sort-chevron" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>'}function Il(){return'<svg class="gengage-chat-product-sort-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>'}function Nl(){return'<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 3 4 7l4 4"/><path d="M16 21l4-4-4-4"/><path d="M4 7h16"/><path d="M20 17H4"/></svg>'}function Gn(e,t){return e.type===t.type&&e.direction===t.direction}function Wn(e,t,a){if(!a||a.type==="related")return e;const n=e.map(r=>{const i=t.elements[r]?.props?.product,o=i?Number(i.price):NaN;return{id:r,price:Number.isFinite(o)?o:1/0}});return n.sort((r,i)=>r.price===1/0&&i.price===1/0?0:r.price===1/0?1:i.price===1/0?-1:a.direction==="desc"?i.price-r.price:r.price-i.price),n.map(r=>r.id)}function zl(e,t,a,n){const r=Wn(t,a,n),i=new Map;for(const o of Array.from(e.children)){const s=o.dataset.elementId;s&&i.set(s,o)}for(const o of r){const s=i.get(o);s&&e.appendChild(s)}}function Ml(e,t,a,n){const r=document.createElement("div");r.className="gengage-chat-product-grid-wrapper";const i=ka(e),o=i.isConsulting,s=e.children??[],c=document.createElement("div");c.className="gengage-chat-product-grid";const l=n?.panelProductListHeading;if(!o&&s.length>1&&n?.onSortChange){const h=document.createElement("div");h.className="gengage-chat-product-sort-toolbar",h.setAttribute("role","toolbar"),h.setAttribute("aria-label",n.i18n?.sortToolbarAriaLabel??"Sort products");let d=n.productSort??{type:"related"};const b=[{label:n.i18n?.sortRelated??"Related",sortState:{type:"related"},icon:"related"},{label:n.i18n?.sortPriceAsc??"Price ↑",sortState:{type:"price",direction:"asc"},icon:"priceAsc"},{label:n.i18n?.sortPriceDesc??"Price ↓",sortState:{type:"price",direction:"desc"},icon:"priceDesc"}],u=document.createElement("div");u.className="gengage-chat-product-sort-dropdown";const f=document.createElement("button");f.type="button",f.className="gengage-chat-product-sort-trigger gds-btn gds-btn-ghost",f.setAttribute("aria-haspopup","listbox"),f.setAttribute("aria-expanded","false");const m=n.i18n?.sortToolbarAriaLabel??"Sort products",y=document.createElement("span");y.className="gengage-chat-product-sort-trigger-icon";const k=document.createElement("span");k.className="gengage-chat-product-sort-trigger-label";const _=O=>{const v=b.find(L=>Gn(L.sortState,O))??b[0];k.textContent=v.label,y.innerHTML=Vn(v.icon),u.dataset.sortIcon=v.icon,f.setAttribute("aria-label",`${m}: ${v.label}`),f.title=v.label};_(d);const x=document.createElement("span");x.className="gengage-chat-product-sort-trigger-chevron",x.innerHTML=Ll(),f.appendChild(y),f.appendChild(k),f.appendChild(x);const T=document.createElement("div");T.className="gengage-chat-product-sort-menu gds-menu",T.hidden=!0,T.setAttribute("role","listbox"),T.setAttribute("aria-label",m);const P=h.ownerDocument;let I=null;const F=()=>{T.hidden=!0,u.classList.remove("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","false"),I?.abort(),I=null},X=O=>{u.classList.contains("gengage-chat-product-sort-dropdown--open")&&(u.contains(O.target)||F())},ne=O=>{O.key==="Escape"&&(O.preventDefault(),F())},me=()=>{T.hidden=!1,u.classList.add("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","true"),I=new AbortController;const{signal:O}=I;P.addEventListener("click",X,{signal:O}),P.addEventListener("keydown",ne,{capture:!0,signal:O})};f.addEventListener("click",O=>{O.stopPropagation(),u.classList.contains("gengage-chat-product-sort-dropdown--open")?F():me()});for(const O of b){const v=document.createElement("button");v.type="button",v.className="gengage-chat-product-sort-option gds-menu-option",v.setAttribute("role","option");const L=Gn(d,O.sortState);v.setAttribute("aria-selected",L?"true":"false"),L&&v.classList.add("gengage-chat-product-sort-option--active","gds-menu-option-active");const R=O.sortState.type==="related"?"related":`price-${O.sortState.direction??""}`;v.dataset.sortKey=R;const M=document.createElement("span");M.className="gengage-chat-product-sort-option-icon",M.innerHTML=Vn(O.icon);const H=document.createElement("span");H.className="gengage-chat-product-sort-option-label",H.textContent=O.label;const q=document.createElement("span");q.className="gengage-chat-product-sort-option-check",q.innerHTML=Il(),q.setAttribute("aria-hidden","true"),L||q.classList.add("gengage-chat-product-sort-option-check--hidden"),v.appendChild(M),v.appendChild(H),v.appendChild(q),v.addEventListener("click",()=>{d=O.sortState,n.onSortChange?.(O.sortState),zl(c,s,t,O.sortState),T.querySelectorAll(".gengage-chat-product-sort-option").forEach(j=>{const w=j,A=w.dataset.sortKey===R;w.classList.toggle("gengage-chat-product-sort-option--active",A),w.classList.toggle("gds-menu-option-active",A),w.setAttribute("aria-selected",A?"true":"false"),w.querySelector(".gengage-chat-product-sort-option-check")?.classList.toggle("gengage-chat-product-sort-option-check--hidden",!A)}),_(O.sortState),F()}),T.appendChild(v)}if(u.appendChild(f),u.appendChild(T),h.appendChild(u),n.onToggleComparisonSku){const O=document.createElement("button");O.className="gengage-chat-comparison-toggle-btn gds-btn gds-btn-ghost",O.type="button",n.comparisonSelectMode&&O.classList.add("gengage-chat-comparison-toggle-btn--active"),n.isStreaming&&O.classList.add("gengage-chat-comparison-toggle-btn--hidden");const v=document.createElement("span");v.className="gengage-chat-comparison-toggle-icon",v.innerHTML=Nl();const L=document.createElement("span");L.className="gengage-chat-comparison-toggle-label";const R=n.i18n?.compareSelected??"Compare";L.textContent=R,O.setAttribute("aria-label",R),O.title=R,O.appendChild(v),O.appendChild(L),O.addEventListener("click",()=>{n.onToggleComparisonSku?.("")}),h.appendChild(O)}if(l){h.classList.add("gengage-chat-product-sort-toolbar--inline");const O=document.createElement("div");O.className="gengage-chat-product-grid-head";const v=document.createElement("span");v.className="gengage-chat-product-grid-head-title",v.textContent=l,O.appendChild(v);const L=document.createElement("div");L.className="gengage-chat-product-grid-head-actions",L.appendChild(h),O.appendChild(L),r.appendChild(O)}else r.appendChild(h)}else if(l){const h=document.createElement("div");h.className="gengage-chat-product-grid-head";const d=document.createElement("span");d.className="gengage-chat-product-grid-head-title",d.textContent=l,h.appendChild(d),r.appendChild(h)}if(o)$l(r,c,i,n);else{const h=Wn(s,t,n?.productSort);for(const d of h){if(!t.elements[d])continue;const b=a(d);b&&(b.dataset.elementId=d,c.appendChild(b))}}(n?.isMobile??ba())&&c.classList.add("gengage-chat-product-grid--mobile"),e.props?.rankingState==="pending"&&(c.classList.add("gengage-chat-product-grid--pending"),c.inert=!0,c.setAttribute("aria-busy","true")),r.appendChild(c);const g=e.props?.endOfList;if(!o&&g!==!0&&s.length>0){const h=n?.i18n?.viewMoreLabel??"Show More",d=document.createElement("button");d.className="gengage-chat-product-grid-view-more",d.type="button",d.textContent=h,d.addEventListener("click",()=>{n?.onAction({title:h,type:"moreProductList",payload:{}})}),r.appendChild(d)}const p=n?.isMobile??ba();if(n?.comparisonSelectMode&&n.comparisonSelectedSkus&&!p){const h=Bn(n.comparisonSelectedSkus,n);r.appendChild(h)}return r}function Bl(e,t){const a=e.props??{},n=a.keyDifferencesHtml,r=a.recommended,i=a.products??[],o=a.attributes??[],s=a.highlights??[],c=a.specialCases,l=a.recommendedText,g=a.winnerHits,p=a.productActions;if(!r)return document.createElement("div");const h={recommended:r,products:i,attributes:o,highlights:s,specialCases:c,locale:t.locale,onProductClick:({sku:b,name:u})=>{t.onProductClick?.({sku:b,url:"",name:u})},pricing:t.pricing};l!==void 0&&(h.recommendedText=l),g!==void 0&&(h.winnerHits=g),p!==void 0&&(h.productActions=p),n!==void 0&&(h.keyDifferencesHtml=n),t.i18n&&(h.i18n={comparisonHeading:t.i18n.panelTitleComparisonResults,recommendedChoiceLabel:t.i18n.recommendedChoiceLabel,highlightsLabel:t.i18n.highlightsLabel,keyDifferencesLabel:t.i18n.keyDifferencesLabel,viewMoreLabel:t.i18n.viewMoreLabel,specialCasesLabel:t.i18n.specialCasesLabel,addToCartButton:t.i18n.addToCartButton});const d=Pc(h);return(t.isMobile??ba())&&d.classList.add("gengage-chat-comparison--mobile"),d}function Rl(e){const t=document.createElement("hr");t.className="gengage-chat-divider";const a=e.props?.label;if(a){const n=document.createElement("div");n.className="gengage-chat-divider-wrapper";const r=document.createElement("span");r.className="gengage-chat-divider-label",r.textContent=a,n.appendChild(t),n.appendChild(r);const i=document.createElement("hr");return i.className="gengage-chat-divider",n.appendChild(i),n}return t}var zt=new WeakMap;function Kn(e){return{...Xe,...e?.i18n??{}}}function Mt(e){return typeof e.status=="string"?e.status:"ready"}function _a(e){const t=e.findIndex(a=>Mt(a)!=="loading");return t<0?0:t}function Ol(e){if(typeof e!="string")return;const t=e.trim();if(!t)return;if(/^https?:\/\//i.test(t))return t;let a=t.split(/[?#]/)[0];if(a&&(a=a.replace(/^\/+/,""),a.startsWith("remoteConfig/")&&(a=a.slice(13)),!!a))return`https://configs.gengage.ai/assets/${a}`}function Yn(e,t,a,n){const{grid:r,i18n:i}=e;r.innerHTML="",r.classList.remove("gengage-chat-product-grid--consulting-groups");const o=document.createElement("section");o.className="gengage-chat-consulting-loading-panel";const s=document.createElement("h4");s.className="gengage-chat-consulting-loading-panel-title",s.textContent=Bt(t,n,i),o.appendChild(s);const c=document.createElement("p");if(c.className="gengage-chat-consulting-loading-panel-copy",c.textContent=a==="loading"?i.consultingStyleLoadingDescription:i.consultingStyleUnavailableDescription,o.appendChild(c),a==="loading"){const l=document.createElement("div");l.className="gengage-chat-consulting-loading-grid";for(let g=0;g<3;g+=1){const p=document.createElement("div");p.className="gengage-chat-consulting-loading-card",l.appendChild(p)}o.appendChild(l)}r.appendChild(o)}function Bt(e,t,a){const n=r=>a.consultingFallbackStyleLabel.replace("{index}",String(r));return e.style_label??n(t)}function xa(e,t){const a=e.variations[t];if(!a)return;const{grid:n,source:r,ctx:i,i18n:o}=e;n.innerHTML="",n.classList.remove("gengage-chat-product-grid--consulting-groups");const s=Mt(a),c=t+1;if(s==="loading"){Yn(e,a,"loading",c);return}if(s!=="ready"&&(!Array.isArray(a.product_list)||a.product_list.length===0)){Yn(e,a,"unavailable",c);return}const l=Array.isArray(a.product_list)?a.product_list:[],g=r==="watch_expert"?[]:Array.isArray(a.recommendation_groups)?a.recommendation_groups:[];if(g.length>0){n.classList.add("gengage-chat-product-grid--consulting-groups");const p=new Map;for(const m of l){const y=typeof m?.sku=="string"?m.sku:void 0;y&&p.set(y,m)}const h=(m,y,k,_)=>{if(y.length===0)return;const x=document.createElement("section");x.className="gengage-chat-consulting-group";const T=document.createElement("div");T.className="gengage-chat-consulting-group-header";const P=document.createElement("h4");if(P.className="gengage-chat-consulting-group-label",P.textContent=`${m} (${y.length})`,T.appendChild(P),typeof _=="string"&&_.trim().length>0){const F=document.createElement("p");F.className="gengage-chat-consulting-group-reason",F.textContent=_,T.appendChild(F)}x.appendChild(T);const I=document.createElement("div");I.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",k&&I.classList.add("gengage-chat-consulting-group-grid--single-group"),I.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,y.length))));for(const F of y){const X=va({type:"ProductCard",props:{product:F}},i??{onAction:()=>{}});I.appendChild(X)}x.appendChild(I),n.appendChild(x)},d=new Set,b=[];for(const m of g){const y=(Array.isArray(m.skus)?m.skus.filter(x=>typeof x=="string"&&x.trim().length>0):[]).map(x=>(d.add(x),p.get(x))).filter(x=>!!x);if(y.length===0)continue;const k=typeof m.label=="string"&&m.label.trim().length>0?m.label:o.consultingFallbackGroupLabel,_=typeof m.reason=="string"?m.reason:void 0;b.push({labelText:k,products:y,..._!==void 0?{reasonText:_}:{}})}const u=l.filter(m=>{const y=typeof m?.sku=="string"?m.sku:"";return y.length>0&&!d.has(y)});u.length>0&&b.push({labelText:o.consultingOtherCompatibleProductsLabel,products:u});const f=b.length===1;for(const m of b)h(m.labelText,m.products,f,m.reasonText);return}for(const p of l){const h=va({type:"ProductCard",props:{product:p}},i??{onAction:()=>{}});n.appendChild(h)}}function wa(e,t,a,n){const r=Mt(t),i=n.consultingStyleLoadingBadge,o=n.consultingStyleUnavailableBadge;e.classList.remove("gengage-chat-consulting-style-btn--loading","gengage-chat-consulting-style-btn--muted"),r==="loading"?e.classList.add("gengage-chat-consulting-style-btn--loading"):r!=="ready"&&e.classList.add("gengage-chat-consulting-style-btn--muted"),e.setAttribute("aria-label",Bt(t,a+1,n));let s=e.querySelector(".gengage-chat-consulting-style-media");s?s.innerHTML="":(s=document.createElement("div"),s.className="gengage-chat-consulting-style-media",e.appendChild(s));const c=Ol(t.image_url);if(c&&fe(c)){const g=document.createElement("img");g.className="gengage-chat-consulting-style-image",g.draggable=!1,ue(g,"src",c),g.alt=Bt(t,a+1,n),g.loading="lazy",Se(g),s.appendChild(g)}const l=document.createElement("span");if(l.className="gengage-chat-consulting-style-caption",l.textContent=Bt(t,a+1,n),s.appendChild(l),r==="loading"||r!=="ready"){const g=document.createElement("span");g.className="gengage-chat-consulting-style-status",g.textContent=r==="loading"?i:o,s.appendChild(g)}}function Jn(e,t,a,n){e.addEventListener("click",()=>{const r=zt.get(t);r&&r.selectedIndex!==n&&(r.selectedIndex=n,a.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((i,o)=>{i.classList.toggle("gengage-chat-consulting-style-btn--active",o===n)}),xa(r,n))})}function Dl(e,t,a,n,r){const i=Kn(r),o=_a(n),s=document.createElement("div");s.className="gengage-chat-consulting-style-picker";const c={grid:t,source:a,ctx:r,variations:n,i18n:i,selectedIndex:o};zt.set(s,c);const l=document.createElement("div");l.className="gengage-chat-consulting-style-picker-title",l.textContent=(a==="watch_expert"?i.watchStylesPreparedTitle:i.beautyStylesPreparedTitle).replace("{count}",String(n.length)),s.appendChild(l);const g=document.createElement("div");g.className="gengage-chat-consulting-style-grid",s.appendChild(g),n.forEach((p,h)=>{const d=document.createElement("button");d.type="button",d.className="gengage-chat-consulting-style-btn gds-card",h===o&&d.classList.add("gengage-chat-consulting-style-btn--active"),wa(d,p,h,i),Jn(d,s,g,h),g.appendChild(d)}),e.appendChild(s),xa(c,o)}function Fl(e,t,a,n){const r=e.querySelector(".gengage-chat-consulting-style-picker"),i=Ul(e);if(!r||!i)return!1;const o=r.querySelector(".gengage-chat-consulting-style-grid");if(!o)return!1;const s=Kn(n);let c=zt.get(r);if(c)c.grid=i,c.source=t,c.ctx=n,c.variations=a,c.i18n=s;else{const d={grid:i,source:t,ctx:n,variations:a,i18n:s,selectedIndex:_a(a)};zt.set(r,d),c=d}const l=r.querySelector(".gengage-chat-consulting-style-picker-title");l&&(l.textContent=(t==="watch_expert"?s.watchStylesPreparedTitle:s.beautyStylesPreparedTitle).replace("{count}",String(a.length)));const g=c;let p=g.selectedIndex;p>=a.length&&(p=Math.max(0,a.length-1)),p<0&&(p=0),a.length>0&&Mt(a[p]??{})==="loading"&&(p=_a(a)),g.selectedIndex=p;const h=[...o.querySelectorAll(".gengage-chat-consulting-style-btn")];if(h.length===0)return!1;for(let d=0;d<a.length;d+=1){const b=a[d];let u=h[d];u?wa(u,b,d,s):(u=document.createElement("button"),u.type="button",u.className="gengage-chat-consulting-style-btn gds-card",wa(u,b,d,s),Jn(u,r,o,d),o.appendChild(u),h[d]=u)}for(;o.querySelectorAll(".gengage-chat-consulting-style-btn").length>a.length;)o.lastElementChild?.remove();return o.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((d,b)=>{d.classList.toggle("gengage-chat-consulting-style-btn--active",b===g.selectedIndex)}),xa(g,g.selectedIndex),!0}function Ul(e){const t=[...e.children];for(let a=t.length-1;a>=0;a-=1){const n=t[a];if(n.classList.contains("gengage-chat-product-grid"))return n}return e.querySelector(":scope > .gengage-chat-product-grid")}function ka(e){const t=typeof e.props?.source=="string"?e.props.source:void 0,a=(Array.isArray(e.props?.styleVariations)?e.props.styleVariations:[]).filter(n=>typeof n.style_label=="string"&&n.style_label.trim().length>0);return{isConsulting:un(t)&&a.length>0,source:t,styleVariations:a}}function $l(e,t,a,n){Dl(e,t,a.source,a.styleVariations,n)}function Hl(e){return!e.isConsulting||e.styleVariations.length===0?!0:e.styleVariations.some(t=>(typeof t.status=="string"?t.status:"ready")!=="loading")}function ql(e,t,a){return!t.isConsulting||!t.source?!1:Fl(e,t.source,t.styleVariations,a)}var jl=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
50
50
  <rect x="3" y="7" width="18" height="13" rx="3" fill="currentColor" opacity="0.15"/>
51
51
  <rect x="3" y="7" width="18" height="13" rx="3" stroke="currentColor" stroke-width="1.5"/>
52
52
  <circle cx="9" cy="13" r="1.5" fill="currentColor"/>
@@ -175,4 +175,4 @@ button[data-gengage-part="chat-launcher-button"] img {
175
175
 
176
176
  Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function qr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),d=h.schema;if(d.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(d)):Object.assign(c,d),Object.assign(c,l),o._zod.parent===g)for(const b in c)b==="$ref"||b==="allOf"||b in l||delete c[b];if(d.$ref&&h.def)for(const b in c)b==="$ref"||b==="allOf"||b in h.def&&JSON.stringify(c[b])===JSON.stringify(h.def[b])&&delete c[b]}const p=o._zod.parent;if(p&&p!==g){n(p);const h=e.seen.get(p);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const d in c)d==="$ref"||d==="allOf"||d in h.def&&JSON.stringify(c[d])===JSON.stringify(h.def[d])&&delete c[d]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:Zt(t,"input",e.processors),output:Zt(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ye(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ye(n.element,a);if(n.type==="set")return ye(n.valueType,a);if(n.type==="lazy")return ye(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ye(n.innerType,a);if(n.type==="intersection")return ye(n.left,a)||ye(n.right,a);if(n.type==="record"||n.type==="map")return ye(n.keyType,a)||ye(n.valueType,a);if(n.type==="pipe")return ye(n.in,a)||ye(n.out,a);if(n.type==="object"){for(const r in n.shape)if(ye(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ye(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ye(r,a))return!0;return!!(n.rest&&ye(n.rest,a))}return!1}var Ph=(e,t={})=>a=>{const n=$r({...a,processors:t});return be(e,n),Hr(n,e),qr(n,e)},Zt=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=$r({...r??{},target:i,io:t,processors:a});return be(e,o),Hr(o,e),qr(o,e)},Th={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Ah=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=Th[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},Lh=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},Ih=(e,t,a,n)=>{a.type="boolean"},Nh=(e,t,a,n)=>{a.not={}},zh=(e,t,a,n)=>{},Mh=(e,t,a,n)=>{const r=e._zod.def,i=ir(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Bh=(e,t,a,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];a.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[o]:a.const=o}else i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),i.every(o=>typeof o=="boolean")&&(a.type="boolean"),i.every(o=>o===null)&&(a.type="null"),a.enum=i},Rh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Oh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Dh=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=be(i.element,t,{...n,path:[...n.path,"items"]})},Fh=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=be(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=be(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Uh=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>be(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},$h=(e,t,a,n)=>{const r=e._zod.def,i=be(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=be(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},Hh=(e,t,a,n)=>{const r=e._zod.def,i=be(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},qh=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},jh=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Zh=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Vh=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},Gh=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;be(i,t,n);const o=t.seen.get(e);o.ref=i},Wh=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},jr=(e,t,a,n)=>{const r=e._zod.def;be(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Kh=C("ZodISODateTime",(e,t)=>{Qg.init(e,t),oe.init(e,t)});function Yh(e){return nh(Kh,e)}var Jh=C("ZodISODate",(e,t)=>{Xg.init(e,t),oe.init(e,t)});function Qh(e){return rh(Jh,e)}var Xh=C("ZodISOTime",(e,t)=>{ep.init(e,t),oe.init(e,t)});function eu(e){return ih(Xh,e)}var tu=C("ZodISODuration",(e,t)=>{tp.init(e,t),oe.init(e,t)});function au(e){return oh(tu,e)}var Zr=(e,t)=>{pr.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>jd(e,a)},flatten:{value:a=>qd(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,La,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,La,2)}},isEmpty:{get(){return e.issues.length===0}}})},kf=C("ZodError",Zr),Ee=C("ZodError",Zr,{Parent:Error}),nu=Ba(Ee),ru=Ra(Ee),iu=Ft(Ee),ou=Ut(Ee),su=Gd(Ee),cu=Wd(Ee),lu=Kd(Ee),du=Yd(Ee),gu=Jd(Ee),pu=Qd(Ee),hu=Xd(Ee),uu=eg(Ee),le=C("ZodType",(e,t)=>(ce.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Zt(e,"input"),output:Zt(e,"output")}}),e.toJSONSchema=Ph(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(qe(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>je(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>nu(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>iu(e,a,n),e.parseAsync=async(a,n)=>ru(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>ou(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>su(e,a,n),e.decode=(a,n)=>cu(e,a,n),e.encodeAsync=async(a,n)=>lu(e,a,n),e.decodeAsync=async(a,n)=>du(e,a,n),e.safeEncode=(a,n)=>gu(e,a,n),e.safeDecode=(a,n)=>pu(e,a,n),e.safeEncodeAsync=async(a,n)=>hu(e,a,n),e.safeDecodeAsync=async(a,n)=>uu(e,a,n),e.refine=(a,n)=>e.check(lm(a,n)),e.superRefine=a=>e.check(dm(a)),e.overwrite=a=>e.check(it(a)),e.optional=()=>Xr(e),e.exactOptional=()=>Yu(e),e.nullable=()=>ei(e),e.nullish=()=>Xr(ei(e)),e.nonoptional=a=>am(e,a),e.array=()=>Fu(e),e.or=a=>Hu([e,a]),e.and=a=>ju(e,a),e.transform=a=>ai(e,Wu(a)),e.default=a=>Xu(e,a),e.prefault=a=>tm(e,a),e.catch=a=>rm(e,a),e.pipe=a=>ai(e,a),e.readonly=()=>sm(e),e.describe=a=>{const n=e.clone();return ft.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return ft.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return ft.get(e);const n=e.clone();return ft.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Vr=C("_ZodString",(e,t)=>{Oa.init(e,t),le.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Ah(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(ph(...n)),e.includes=(...n)=>e.check(mh(...n)),e.startsWith=(...n)=>e.check(fh(...n)),e.endsWith=(...n)=>e.check(bh(...n)),e.min=(...n)=>e.check(jt(...n)),e.max=(...n)=>e.check(Fr(...n)),e.length=(...n)=>e.check(Ur(...n)),e.nonempty=(...n)=>e.check(jt(1,...n)),e.lowercase=n=>e.check(hh(n)),e.uppercase=n=>e.check(uh(n)),e.trim=()=>e.check(yh()),e.normalize=(...n)=>e.check(vh(...n)),e.toLowerCase=()=>e.check(_h()),e.toUpperCase=()=>e.check(xh()),e.slugify=()=>e.check(wh())}),mu=C("ZodString",(e,t)=>{Oa.init(e,t),Vr.init(e,t),e.email=a=>e.check(Rp(fu,a)),e.url=a=>e.check($p(bu,a)),e.jwt=a=>e.check(ah(Nu,a)),e.emoji=a=>e.check(Hp(vu,a)),e.guid=a=>e.check(Br(Gr,a)),e.uuid=a=>e.check(Op(Vt,a)),e.uuidv4=a=>e.check(Dp(Vt,a)),e.uuidv6=a=>e.check(Fp(Vt,a)),e.uuidv7=a=>e.check(Up(Vt,a)),e.nanoid=a=>e.check(qp(yu,a)),e.guid=a=>e.check(Br(Gr,a)),e.cuid=a=>e.check(jp(_u,a)),e.cuid2=a=>e.check(Zp(xu,a)),e.ulid=a=>e.check(Vp(wu,a)),e.base64=a=>e.check(Xp(Au,a)),e.base64url=a=>e.check(eh(Lu,a)),e.xid=a=>e.check(Gp(ku,a)),e.ksuid=a=>e.check(Wp(Cu,a)),e.ipv4=a=>e.check(Kp(Su,a)),e.ipv6=a=>e.check(Yp(Eu,a)),e.cidrv4=a=>e.check(Jp(Pu,a)),e.cidrv6=a=>e.check(Qp(Tu,a)),e.e164=a=>e.check(th(Iu,a)),e.datetime=a=>e.check(Yh(a)),e.date=a=>e.check(Qh(a)),e.time=a=>e.check(eu(a)),e.duration=a=>e.check(au(a))});function Pe(e){return Bp(mu,e)}var oe=C("ZodStringFormat",(e,t)=>{re.init(e,t),Vr.init(e,t)}),fu=C("ZodEmail",(e,t)=>{qg.init(e,t),oe.init(e,t)}),Gr=C("ZodGUID",(e,t)=>{$g.init(e,t),oe.init(e,t)}),Vt=C("ZodUUID",(e,t)=>{Hg.init(e,t),oe.init(e,t)}),bu=C("ZodURL",(e,t)=>{jg.init(e,t),oe.init(e,t)}),vu=C("ZodEmoji",(e,t)=>{Zg.init(e,t),oe.init(e,t)}),yu=C("ZodNanoID",(e,t)=>{Vg.init(e,t),oe.init(e,t)}),_u=C("ZodCUID",(e,t)=>{Gg.init(e,t),oe.init(e,t)}),xu=C("ZodCUID2",(e,t)=>{Wg.init(e,t),oe.init(e,t)}),wu=C("ZodULID",(e,t)=>{Kg.init(e,t),oe.init(e,t)}),ku=C("ZodXID",(e,t)=>{Yg.init(e,t),oe.init(e,t)}),Cu=C("ZodKSUID",(e,t)=>{Jg.init(e,t),oe.init(e,t)}),Su=C("ZodIPv4",(e,t)=>{ap.init(e,t),oe.init(e,t)}),Eu=C("ZodIPv6",(e,t)=>{np.init(e,t),oe.init(e,t)}),Pu=C("ZodCIDRv4",(e,t)=>{rp.init(e,t),oe.init(e,t)}),Tu=C("ZodCIDRv6",(e,t)=>{ip.init(e,t),oe.init(e,t)}),Au=C("ZodBase64",(e,t)=>{op.init(e,t),oe.init(e,t)}),Lu=C("ZodBase64URL",(e,t)=>{cp.init(e,t),oe.init(e,t)}),Iu=C("ZodE164",(e,t)=>{lp.init(e,t),oe.init(e,t)}),Nu=C("ZodJWT",(e,t)=>{gp.init(e,t),oe.init(e,t)}),Wr=C("ZodNumber",(e,t)=>{wr.init(e,t),le.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Lh(e,n,r,i),e.gt=(n,r)=>e.check(Or(n,r)),e.gte=(n,r)=>e.check(Ua(n,r)),e.min=(n,r)=>e.check(Ua(n,r)),e.lt=(n,r)=>e.check(Rr(n,r)),e.lte=(n,r)=>e.check(Fa(n,r)),e.max=(n,r)=>e.check(Fa(n,r)),e.int=n=>e.check(Yr(n)),e.safe=n=>e.check(Yr(n)),e.positive=n=>e.check(Or(0,n)),e.nonnegative=n=>e.check(Ua(0,n)),e.negative=n=>e.check(Rr(0,n)),e.nonpositive=n=>e.check(Fa(0,n)),e.multipleOf=(n,r)=>e.check(Dr(n,r)),e.step=(n,r)=>e.check(Dr(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Kr(e){return sh(Wr,e)}var zu=C("ZodNumberFormat",(e,t)=>{pp.init(e,t),Wr.init(e,t)});function Yr(e){return ch(zu,e)}var Mu=C("ZodBoolean",(e,t)=>{hp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ih(e,a,n,r)});function Ke(e){return lh(Mu,e)}var Bu=C("ZodUnknown",(e,t)=>{up.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>zh(e,a,n,r)});function Jr(){return dh(Bu)}var Ru=C("ZodNever",(e,t)=>{mp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Nh(e,a,n,r)});function Ou(e){return gh(Ru,e)}var Du=C("ZodArray",(e,t)=>{fp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Dh(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(jt(a,n)),e.nonempty=a=>e.check(jt(1,a)),e.max=(a,n)=>e.check(Fr(a,n)),e.length=(a,n)=>e.check(Ur(a,n)),e.unwrap=()=>e.element});function Fu(e,t){return kh(Du,e,t)}var Uu=C("ZodObject",(e,t)=>{vp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Fh(e,a,n,r),te(e,"shape",()=>t.shape),e.keyof=()=>Ha(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Jr()}),e.loose=()=>e.clone({...e._zod.def,catchall:Jr()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ou()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Dd(e,a),e.safeExtend=a=>Fd(e,a),e.merge=a=>Ud(e,a),e.pick=a=>Rd(e,a),e.omit=a=>Od(e,a),e.partial=(...a)=>$d(Qr,e,a[0]),e.required=(...a)=>Hd(ti,e,a[0])});function Oe(e,t){return new Uu({type:"object",shape:e??{},...D(t)})}var $u=C("ZodUnion",(e,t)=>{yp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Uh(e,a,n,r),e.options=t.options});function Hu(e,t){return new $u({type:"union",options:e,...D(t)})}var qu=C("ZodIntersection",(e,t)=>{_p.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$h(e,a,n,r)});function ju(e,t){return new qu({type:"intersection",left:e,right:t})}var $a=C("ZodEnum",(e,t)=>{xp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Mh(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new $a({...t,checks:[],...D(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new $a({...t,checks:[],...D(r),entries:i})}});function Ha(e,t){return new $a({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...D(t)})}var Zu=C("ZodLiteral",(e,t)=>{wp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Bh(e,a,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Vu(e,t){return new Zu({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}var Gu=C("ZodTransform",(e,t)=>{kp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Oh(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new rr(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(mt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(mt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Wu(e){return new Gu({type:"transform",transform:e})}var Qr=C("ZodOptional",(e,t)=>{Ar.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>jr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Xr(e){return new Qr({type:"optional",innerType:e})}var Ku=C("ZodExactOptional",(e,t)=>{Cp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>jr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Yu(e){return new Ku({type:"optional",innerType:e})}var Ju=C("ZodNullable",(e,t)=>{Sp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Hh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function ei(e){return new Ju({type:"nullable",innerType:e})}var Qu=C("ZodDefault",(e,t)=>{Ep.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>jh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Xu(e,t){return new Qu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():lr(t)}})}var em=C("ZodPrefault",(e,t)=>{Pp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Zh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function tm(e,t){return new em({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():lr(t)}})}var ti=C("ZodNonOptional",(e,t)=>{Tp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>qh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function am(e,t){return new ti({type:"nonoptional",innerType:e,...D(t)})}var nm=C("ZodCatch",(e,t)=>{Ap.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Vh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function rm(e,t){return new nm({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var im=C("ZodPipe",(e,t)=>{Lp.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Gh(e,a,n,r),e.in=t.in,e.out=t.out});function ai(e,t){return new im({type:"pipe",in:e,out:t})}var om=C("ZodReadonly",(e,t)=>{Ip.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Wh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function sm(e){return new om({type:"readonly",innerType:e})}var cm=C("ZodCustom",(e,t)=>{Np.init(e,t),le.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Rh(e,a,n,r)});function lm(e,t={}){return Ch(cm,e,t)}function dm(e){return Sh(e)}var gm=new Set(["launchSingleProduct","launchProductList","launchHomepage"]);function ni(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function qa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ri(e){return e?.type==="ProductGrid"&&e.props?.similarsAppend===!0}var pm=class st extends kt{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._hostOverflowRestore=null,this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._pinHostViewportScroll=()=>{if(!this._hostScrollLockActive||!this._hostScrollLockViewport||this._hostScrollPinning)return;const a=this._hostScrollLockViewport;window.scrollX===a.x&&window.scrollY===a.y||(this._hostScrollPinning=!0,window.scrollTo(a.x,a.y),this._hostScrollPinning=!1)},this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._gaPrevMainPaneExpanded=!1,this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=Xe,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new md,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new mc}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const u=bd(t.pillLauncher);t.launcherImageUrl=u.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>u.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=Ad,this._shadow.appendChild(a);const n=this.root,r=(u,f)=>{f&&ni(f)&&n.style.setProperty(u,f)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[u,f]of Object.entries(t.theme))u.startsWith("--")&&typeof f=="string"&&r(u,f);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",i.lang=Ue(t.locale),this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const u=document.createElement("div");u.className="gengage-chat-backdrop",u.setAttribute("aria-hidden","true"),u.setAttribute("role","button"),u.setAttribute("tabindex","-1"),u.setAttribute("aria-label",this._i18n.closeAriaLabel),u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),this.close()}),this._backdropEl=u,i.prepend(u)}if(o==="floating"){const u={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?u.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(u.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(u.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(u.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(u.tooltip=t.launcherTooltip),this._launcher=Zl(u),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new dc(s,{i18n:this._i18n,onSend:(u,f)=>this._sendMessage(u,f),onClose:()=>this.close(),onAttachment:u=>this._handleAttachment(u),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:u=>this._handleRollback(u),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(so(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:u=>{u==="close"?this.close():(this._openState=u,this._applyOpenStateClasses())},onThumbnailClick:u=>this._rollbackToThread(u),onLinkClick:u=>{this._saveSessionAndOpenURL(u)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:u=>{this._presentation.pinnedToBottom=u},onUserInteractingChange:u=>{this._presentation.userInteracting=u},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new pd({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new hd({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:u=>this._rollbackToThread(u)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),p=sessionStorage.getItem("gengage_restore_sku"),h=!!(g&&p);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new dd;await u.open(),this._session=new tr(u),await this._restoreFromIndexedDB(h)}catch{this._session=new tr(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const d=()=>this._syncViewportState();if(window.addEventListener("resize",d,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",d)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const f=this._drawer?.getElement();if(!f)return;const m=window.innerHeight-(window.visualViewport?.height??window.innerHeight);f.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,m)}px`)};window.visualViewport.addEventListener("resize",u),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",u))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const b={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(b.allowedOrigins=t.allowedOrigins),this._bridge=new zo(b),this._lastSku=this.config.pageContext?.sku,this._lastPageType=this.config.pageContext?.pageType,this._lastSkuListKey=this.config.pageContext?.skuList?.slice(0,48).join(","),this._initComplete=!0;for(const u of this._pendingActions)this._sendAction(u.action,u.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),pe("gengage:chat:ready",{}),_t("chat"),t.onReady?.()}onUpdate(t){if(this.config.pageContext&&t.pageType!==void 0){const{sku:n,skuList:r,...i}=this.config.pageContext,o={...i};o.pageType==="pdp"&&n!==void 0&&(o.sku=n),o.pageType==="plp"&&r!==void 0&&(o.skuList=r),this.config={...this.config,pageContext:o}}let a=!1;if(t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,a=!0),t.pageType!==void 0&&t.pageType!==this._lastPageType&&(this._lastPageType=t.pageType,a=!0),t.skuList!==void 0){const n=t.skuList.slice(0,48).join(",");n!==this._lastSkuListKey&&(this._lastSkuListKey=n,a=!0)}a&&this._resetForNewPage()}onShow(){this._showDrawer(),this.emit("open"),pe("gengage:chat:open",{state:this._openState}),xt("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.pageType==="pdp"&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._plpLaunched&&this.config.pageContext?.pageType==="plp"&&this.config.pageContext.skuList?.length&&(this._plpLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchProductList",payload:{sku_list:this.config.pageContext.skuList.slice(0,48)}},{silent:!0,isContextPrime:!0,preservePills:!0})),!this._homepageLaunched&&this.config.pageContext?.pageType==="home"&&(this._homepageLaunched=!0,this._contextPrimingInFlight=!0,this._sendAction({title:"",type:"launchHomepage",payload:{}},{silent:!0,isContextPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),pe("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),qs(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${ve(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._plpLaunched=!1,this._homepageLaunched=!1,this._entryContextPrimed=!1,this._contextPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._clearChoicePrompter(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_focusPresentationThread(t,a="smooth",n=!1){this._presentation.requestThreadFocus(t,a),n&&this._drawer?.setPresentationFocus(t),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40)}_scrollInlineIntoView(t,a){if(a){this._focusPresentationThread(a,"auto");return}t.scrollIntoView({behavior:"auto",block:"start"})}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=fd(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=qa(n)?n:qa(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),qa(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&ni(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),this._hasDedicatedContextLaunch()||this._shouldPrimeContextualOpening())return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:ln(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_hasDedicatedContextLaunch(){const t=this.config.pageContext;return t?!!(t.pageType==="pdp"&&t.sku||t.pageType==="plp"&&t.skuList?.length||t.pageType==="home"):!1}_shouldPrimeContextualOpening(){return this._messages.length!==0||this._entryContextPrimed||this._contextPrimingInFlight||this._hasDedicatedContextLaunch()?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening())return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!0})}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:!(!(this._drawer?.isPanelVisible()??!1)||!this._isMobileViewport&&(this._drawer?.isPanelCollapsed()??!1))}_shouldLockHostDocumentScroll(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"||this._isMobileViewport?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock(),this._maybeTrackChatbotMainPaneGa()}_mainPaneExpandedForAnalytics(){const t=this._drawer;return t?.isPanelVisible()?this._isMobileViewport?!0:!t.isPanelCollapsed():!1}_maybeTrackChatbotMainPaneGa(){const t=this._mainPaneExpandedForAnalytics();t&&!this._gaPrevMainPaneExpanded&&go(),this._gaPrevMainPaneExpanded=t}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._shouldLockHostDocumentScroll()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(a.length===0)return!0;if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){if(!(typeof document>"u"||typeof window>"u")){if(!this._hostOverflowRestore){const t=document.documentElement,a=document.body;this._hostOverflowRestore={htmlOverflow:t.style.overflow,bodyOverflow:a?.style.overflow??"",htmlOverscroll:t.style.overscrollBehavior,bodyOverscroll:a?.style.overscrollBehavior??""},t.style.overflow="hidden",t.style.overscrollBehavior="none",a&&(a.style.overflow="hidden",a.style.overscrollBehavior="none"),this._hostScrollLockViewport={x:window.scrollX,y:window.scrollY}}this._hostScrollLockActive||(window.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),window.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),window.addEventListener("scroll",this._pinHostViewportScroll,{capture:!0,passive:!0}),this._hostScrollLockActive=!0)}}_releaseHostDocumentScrollLock(){if(!(typeof document>"u")&&(typeof window<"u"&&(window.removeEventListener("scroll",this._pinHostViewportScroll,{capture:!0}),window.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),window.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0})),this._hostScrollLockActive&&(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1),this._hostScrollLockViewport=null,this._hostScrollPinning=!1,this._hostOverflowRestore)){const t=document.documentElement,a=document.body;t.style.overflow=this._hostOverflowRestore.htmlOverflow,t.style.overscrollBehavior=this._hostOverflowRestore.htmlOverscroll,a&&(a.style.overflow=this._hostOverflowRestore.bodyOverflow,a.style.overscrollBehavior=this._hostOverflowRestore.bodyOverscroll),this._hostOverflowRestore=null}}_handleAttachment(t){const a=$o(t);if(!a.ok){pe("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._contextPrimingInFlight&&(this._abortAllActiveRequests(),this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),po(),this._messages.some(r=>r.role==="user")||ho(),Ne("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._contextPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._clearChoicePrompter()})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._clearChoicePrompter(),a?.preservePanel||id(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const w=this._currentThreadId,A=this._messages.filter(E=>E.threadId!==void 0&&E.threadId>w);this._messages=this._messages.filter(E=>!E.threadId||E.threadId<=w);for(const E of A)this._shadow?.querySelector(`[data-message-id="${ve(E.id)}"]`)?.remove(),this._panel.snapshots.delete(E.id),this._panel.snapshotTypes.delete(E.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(E=>{E instanceof HTMLElement&&E.dataset.threadId&&E.dataset.threadId>w&&E.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=ln();this._currentThreadId=n,this._lastThreadId=n,this._panel&&!gm.has(t.type)&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=a?.silent===!0&&a?.isContextPrime===!0,o=i&&t.type==="launchSingleProduct";if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const w=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,A=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(A!==void 0&&A.role==="user"&&A.content===w)){(!this._messages.some(N=>N.role==="user")||this._drawer?.isKvkkBannerVisible())&&(Ta(this.config.accountId),this._drawer?.hideKvkkBanner());const E=this._createMessage("user",w);E.threadId=n,a?.attachment!==void 0&&(E.attachment=a.attachment),this._drawer?.addMessage(E),a?.attachment!==void 0&&this._modeController.isBeautyConsulting&&this._drawer?.setBeautyPhotoStepCard({visible:!1}),this._messages.push(E)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const w=this._i18n.productNotFoundMessage,A=this._createMessage("assistant",w);A.threadId=n,A.status="done",this._messages.push(A),this._ensureAssistantMessageRendered(A),this._drawer?.updateBotMessage(A.id,w),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",A),this._persistToIndexedDB().catch(()=>{});return}let s=this._currentPanelSource,c=!1;const l=t.type==="user_message"||t.type==="inputText",g=()=>{c||a?.preservePanel||(s=this._currentPanelSource,c=!0)},p=()=>{if(this._drawer?.isPanelLoading()){if(!l&&s){const w=this._buildRenderContext(),A=this._renderPanelFromSource(s,w);this._drawer.setPanelContent(A),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(s)),this._currentPanelSource=s}else this._drawer.clearPanel(),this._currentPanelSource=null;s=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let h="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._focusPresentationThread(n,"smooth",a?.silent||r),a?.preservePanel||(this._contextPrimingInFlight&&!i&&(this._contextPrimingInFlight=!1,this._queuedUserMessages=[]),this._abortAllActiveRequests());const b={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(b.attachment=a.attachment);const u=this._getVisibleMessages().filter(w=>w!==d&&(w.content||w.role==="assistant")).slice(-50).map(w=>({role:w.role==="user"?"user":"model",content:w.content??""})),f={outputLanguage:Td(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:nr(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(f.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(f.viewId=this.config.session.viewId);const m=Ds(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),y={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:m.type,locale:Ue(this.config.locale),meta:f,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(y.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(y.view_id=this.config.session.viewId),m.payload!==void 0&&(y.payload=m.payload),this.config.pageContext?.sku!==void 0&&(y.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(y.page_type=this.config.pageContext.pageType);const k=crypto.randomUUID(),_=Date.now();let x=0,T=!1,P=!1,I=!1,F=!1,X=!1;const ne=fc();let me=null,O=null;const v=()=>{if(this._drawer&&!F){if(!I){this._drawer.setPanelAiZoneState("hidden");return}X?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel})}},L=w=>{if(!me||!this._drawer)return;const A=this._buildRenderContext();A.isStreaming=w;const E=this._renderUISpec(me,A);F=!0,this._drawer.setPanelAiZoneState("results",{resultEl:E}),me=null},R=(w,A,E)=>{if(w==="ProductGrid"||w==="CategoriesContainer"){I=!0,L(E),v();return}A!=="appendSimilars"&&A!=="append"&&(I=!1,F=!1,me=null,this._drawer?.setPanelAiZoneState("hidden"))},M=w=>(w==="ProductGrid"||w==="CategoriesContainer")&&(I||F||me!==null),H=(w,A,E)=>{if(!this._drawer||!this._panel)return;const N=w.elements[w.root];if(E==="ProductGrid"&&N){const z=ka(N);if(z.isConsulting){const B=this._drawer.getPanelContentElement();if(B&&ql(B,z,A)){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._currentPanelSource={kind:"spec",spec:w},this._panel.currentType=E,this._drawer.resyncPanelTopBarFromCurrentContent();return}}}this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer.setComparisonDockContent(null),this._drawer.setPanelContent(this._renderUISpec(w,A),{preserveAiZone:M(E)}),this._currentPanelSource={kind:"spec",spec:w},this._panel.currentType=E},q=(w,A,E,N)=>{if(!this._panel)return;this._drawer?.setDividerPreviewEnabled((this._panel.currentType??w)==="ProductGrid"),w==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const z=this._panel.currentType??w,B=A?.props?.panelTitle;this._panel.updateTopBar(z,B),this._panel.updateExtendedMode(w),this._isMobileViewport&&o&&this._drawer?.hideMobilePanel(),R(w,E,N)};this.track(ta(this.analyticsContext(),{endpoint:"process_action",request_id:k,widget:"chat"}));let j=null;if(j=$s(y,{onTextChunk:(w,A,E)=>{if(!r&&n!==this._activeRequestThreadId||(h+=w,this._drawer?.removeTypingIndicator(),E?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...E.skuToProductItem}),E?.conversationMode&&(this._conversationMode=E.conversationMode),E?.renderHint&&(d.renderHint=E.renderHint),this.track($i(this.analyticsContext(),{request_id:k,chunk_index:x++,widget:"chat"})),!this._drawer))return;let N=h;const z=E?.kvkk===!0||o&&Pa(N);if(A&&z){const U=this.config.accountId;if(!nr(U)){const ee=Ed(N);ee?this._drawer?.showKvkkBanner(ee,()=>{this._drawer?.hideKvkkBanner(),Ta(U)}):Ta(U)}N=Sd(N)}const B=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(B?B.innerHTML=ke(N):(d.content=N,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),A)if(d.content=N,d.status="done",en(),vc(d))this._drawer?.updateBotMessage(d.id,N,"photo_analysis",d.photoAnalysis),d.threadId&&this._focusPresentationThread(d.threadId,"auto");else{const U=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(U){this._activeTypewriter?.cancel();const ee=E?.productMentions;this._activeTypewriter=Ql({container:U,html:ke(N),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,ee&&ee.length>0&&U&&Xl({container:U,mentions:ee,onProductClick:Q=>{this._sendAction({title:ee.find($=>$.sku===Q)?.short_name??Q,type:"launchSingleProduct",payload:{sku:Q}})}})}})}}},onUISpec:(w,A,E,N)=>{if(!r&&n!==this._activeRequestThreadId||A!=="chat")return;N&&(this._clearAssistantPanelLikeStreamClearPanel(),T=!1,O=null);const z=w.elements[w.root],B=z?.type??"unknown";if(bc(B,z?.props??{},ne,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:X},d)){B==="PhotoAnalysisCard"&&d.threadId&&this._focusPresentationThread(d.threadId,"auto");return}const U=ri(z),ee=this.config.productDetailsExtended!==!0&&(B==="ProductDetailsPanel"||U);ee&&!N&&(this._clearAssistantPanelLikeStreamClearPanel(),T=!1);const Q=B==="ProductDetailsPanel"&&E!=="panel"?"panel":E;this.track(Hi(this.analyticsContext(),{request_id:k,chunk_index:x,component_type:B,widget:"chat"}));const $=this._buildRenderContext();if($.isStreaming=!0,B==="ComparisonTable"){const Z=z?.props?.products;io(Array.isArray(Z)?Z.length:0)}if(B==="ProductGrid"){const Z=z?.children?.length??0;co(void 0,Z)}const ie=Q==="panel"&&this._panel?this._panel.toPanelSpec(w):w;if(Q==="panel"&&this._panel&&!ee&&B==="ProductGrid"&&z){const Z=ka(z);if(Z.isConsulting&&!Hl(Z)){O=w;return}Z.isConsulting&&(O=null)}if(Q==="panel"&&this._panel&&!ee){const Z=!P;P=!0;const J=z?.props?.replacePanel===!0,se=z?.props?.rankingState,V=J||se==="pending"||se==="final"?"replace":ud({componentType:B,similarsAppend:z?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:Z});$.panelProductListHeading=void 0,B==="ProductGrid"&&(V==="appendSimilars"?$.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext($,{kind:"spec",spec:ie})),V==="appendSimilars"?this._appendSimilarsToPanel(ie,$):V==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(ie,$)),this._comparisonSelectMode&&this._refreshComparisonUI()):H(ie,$,B),q(B,z,V,!0)}if(B==="ProductDetailsPanel"&&Q==="panel"&&(!d.silent||o)){const Z=z?.props?.product;if(Z){const J={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:Z}}}},se=this._shadow?.querySelector(".gengage-chat-messages");if(se){const V=this._renderUISpec(J,$);d.threadId&&(V.dataset.threadId=d.threadId);const ae=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);ae&&ae.parentNode===se?ae.after(V):se.appendChild(V),this._scrollInlineIntoView(V,d.threadId),this._drawer?.refreshPresentationCollapsed(),P=!0}}}const Y=B==="AITopPicks"||B==="AIGroupingCards",Be=B==="ActionButtons"?z?.props?.buttons:void 0,vt=B==="ActionButtons"&&this._modeController.mode!=="shopping"&&Array.isArray(Be)&&Be.length>0&&Be.every(Z=>Z.action?.type==="inputText");let S=!1,W=!1;if(ee&&U&&($.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),Y&&(!d.silent||i))if(I){const Z=this._renderUISpec(w,$);F=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Z}),S=!0,me=null}else me=w,W=!0;const de=i&&(B==="GroundingReviewCard"||Y);if(!Y&&(!d.silent||de)&&(Q!=="panel"||B==="ProductCard"||ee&&B==="ProductGrid"&&!U)&&(B!=="ActionButtons"||vt)&&!S&&!(W&&Y)){const Z=this._shadow?.querySelector(".gengage-chat-messages");if(Z){const J=this._renderUISpec(w,$);d.threadId&&(J.dataset.threadId=d.threadId),Z.appendChild(J),this._scrollInlineIntoView(J,d.threadId),this._drawer?.refreshPresentationCollapsed(),ee&&B==="ProductGrid"&&(P=!0)}}if((B==="ProductGrid"||B==="ProductCard")&&d.threadId){const Z=z?.children??[],J=B==="ProductGrid"?Z.map(se=>w.elements[se]?.props?.product).filter(Boolean):[z?.props?.product].filter(Boolean);for(const se of J){const V=se.sku,ae=se.imageUrl;V&&ae&&this._thumbnailEntries.push({sku:V,imageUrl:ae,threadId:d.threadId}),V&&this._viewedProductSkus.add(V)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(B==="ProductGrid"||B==="ProductDetailsPanel"){const Z=(B==="ProductGrid"?(z?.children??[]).map(J=>w.elements[J]?.props?.product).filter(Boolean):[z?.props?.product??z?.props].filter(Boolean)).map(J=>J.imageUrl).filter(J=>typeof J=="string").slice(0,5);Z.length>0&&this._bridge?.send("previewImages",{images:Z})}const he=z?.children?.length??0;if(B==="ProductGrid"&&Q==="panel"&&!ee&&he>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!od(this._currentThreadId??"")&&(this._clearChoicePrompter(),this._choicePrompterEl=rd({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}}),this._mountChoicePrompter()&&this._isMobileViewport&&window.visualViewport)){const Z=this._choicePrompterEl,J=()=>{window.visualViewport.height/window.innerHeight<.75&&(Z.remove(),this._choicePrompterEl===Z&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",J))};window.visualViewport.addEventListener("resize",J)}if(B==="ActionButtons"){const Z=z?.props?.buttons;if(Z&&Z.length>0&&!vt){const J=[],se=[];for(const V of Z)if(ad(V)){const ae={label:V.label,action:V.action};V.icon&&(ae.icon=V.icon),J.push(ae)}else se.push(V);J.length>0&&this._drawer?.setInputAreaChips(J.map(V=>({label:V.label,onAction:()=>this._sendAction(V.action),...V.icon?{icon:V.icon}:{}}))),se.length>0&&this._drawer?.setPills(se.map(V=>{const ae={label:V.label,onAction:()=>this._sendAction(V.action)};return V.icon&&(ae.icon=V.icon),V.image&&(ae.image=V.image),V.description&&(ae.description=V.description),ae}))}}v(),d.uiSpec=w},onAction:w=>{if(!(!r&&n!==this._activeRequestThreadId)&&w.type==="action"){const A={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(A.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(A.allowScriptCall=this.config.actionHandling.allowScriptCall),Oo(w,{openChat:()=>this.open(),navigate:E=>{fe(E.url)&&(this._bridge?.send("navigate",E),E.newTab?window.open(E.url,"_blank","noopener,noreferrer"):window.location.href=E.url)},saveSession:E=>this.saveSession(E.sessionId,E.sku),addToCart:E=>{pe("gengage:similar:add-to-cart",E)},scriptCall:E=>{pe("gengage:chat:script-call",E),this.config.onScriptCall?.(E)}},A)}},onMetadata:w=>{if(!(!r&&n!==this._activeRequestThreadId)&&w.type==="metadata"&&w.meta){if(w.meta.panel!==void 0||w.meta.messages!==void 0||w.meta.message_id!==void 0){this._lastBackendContext=w.meta;const E=pa(w.meta.panel);E&&(this._modeController.updateFromContext(E),this._applyUiHints())}if(w.meta.panelLoading){const E=typeof w.meta.panelPendingType=="string"?w.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(E==="productDetails"||E==="productDetailsSimilars")||(T=!0,P=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(E),E&&this._panel?.updateTopBarForLoading(E))}if(w.meta.voice){const E=new CustomEvent("gengage:chat:voice",{detail:{payload:w.meta.voice},bubbles:!1,cancelable:!0}),N=window.dispatchEvent(E);if(uo(),N){const z=w.meta.voice;z.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=Gl(z.audio_base64,z.content_type??"audio/ogg"))}}if((w.meta.redirectTarget||w.meta.redirect)&&(pe("gengage:chat:redirect",{target:w.meta.redirectTarget??null,payload:w.meta.redirect??null}),Ne("redirect","redirect dispatched",{target:w.meta.redirectTarget??null}),this._handleRedirectMetadata(w.meta.redirect)),w.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(T=!0,P=!1,g(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),w.meta.loading){const E=Array.isArray(w.meta.thinkingMessages)?w.meta.thinkingMessages.filter(z=>typeof z=="string"):[],N=typeof w.meta.loadingText=="string"?w.meta.loadingText:void 0;if(E.length>0){const z=N&&this._modeController.shouldCondenseThinking()?[...E.slice(0,2),N]:E;this._drawer?.setThinkingSteps(z)}typeof N=="string"&&N.length>0&&(this._drawer?.addThinkingStep(N),this._bridge?.send("loadingMessage",{text:N}))}w.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",w.meta.visitorDataResponse),w.meta.formType&&this._bridge?.send("glovForm",{type:w.meta.formType,data:w.meta.formPayload}),w.meta.launcherContent&&this._bridge?.send("launcherContent",w.meta.launcherContent),pe("gengage:chat:metadata",{payload:w.meta});const A=w.meta;typeof A.prompt_tokens=="number"&&typeof A.completion_tokens=="number"&&this.track(qi(this.analyticsContext(),{model:w.model??"unknown",prompt_tokens:A.prompt_tokens,completion_tokens:A.completion_tokens,total_tokens:A.total_tokens??A.prompt_tokens+A.completion_tokens}))}},onError:w=>{if(j&&this._abortControllers.delete(j),!r&&n!==this._activeRequestThreadId)return;X=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,v(),me=null,O=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),_c(ne,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const A=P;T&&!P&&p(),T=!1,P=!1;const E=d.content!=null&&d.content.length>0||h.length>0||A,N=d.silent||E,z=typeof navigator<"u"&&navigator.onLine===!1&&sa(w),B=()=>{this._shadow?.querySelector(`[data-message-id="${ve(d.id)}"]`)?.remove();const Q=this._messages.indexOf(d);Q>=0&&this._messages.splice(Q,1)};let U=!1;const ee=()=>{if(z)return;this.emit("error",w);const Q=w.message;Q===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=Q);const $=w.message.trim(),ie=$.length>0?$:this._i18n.errorMessage,Y={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){B(),U=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,Y);return}if(wd(w,ie)){B(),U=!0,this._drawer?.showErrorWithRecovery(ie,Y);return}d.content=ie,d.status="done";const Be=ke(ie.replace(/\r\n/g,`
177
177
  `).split(`
178
- `).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,Be),this._drawer?.showRecoveryPillsOnly(Y)};if(i&&!E)if(o||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const Q=this._i18n.productNotFoundMessage;d.content=Q,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,Q),this._markUnavailableProductContext()}else d.status="done";else if(N)this._drawer?.setPills([]),d.silent||ee();else if(ee(),z)return;i&&(this._contextPrimingInFlight=!1,this._flushQueuedUserMessages()),!U&&d.status==="streaming"&&(d.status="error"),z||this.track(aa(this.analyticsContext(),{request_id:k,error_code:"STREAM_ERROR",error_message:w.message,widget:"chat"}))},onDone:()=>{if(j&&this._abortControllers.delete(j),!r&&n!==this._activeRequestThreadId)return;if(X=!0,O&&this._panel&&this._drawer){const N=this._buildRenderContext();N.isStreaming=!1;const z=O.elements[O.root],B=this._panel.toPanelSpec(O);this._applyPanelListHeadingToContext(N,{kind:"spec",spec:B});const U=z?.type??"ProductGrid";H(B,N,U),q(U,z,"replace",!1),P=!0}O=null,me&&L(!1),v(),this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),yc(ne,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const w=P;if(T&&!P&&p(),T=!1,o&&!h&&!w){const N=this._i18n.productNotFoundMessage;d.content=N,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,N),this._markUnavailableProductContext()}if(P=!1,i){this._contextPrimingInFlight=!1;const N=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),!N&&o&&this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",en()),this._presentation.finalizeAssistantGroup(n);const A=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");A&&(A.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),A.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const E=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,E?()=>{const N=this._buildRenderContext();return this._renderPanelFromSource(E,N)}:void 0),this.track(yt(this.analyticsContext(),{request_id:k,latency_ms:Date.now()-_,chunk_count:x,widget:"chat"})),this.track(ji(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Vi(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},b),this._abortControllers.add(j),!a?.silent&&!r){const w=j;this._drawer?.showStopButton(()=>{w.abort(),this._abortControllers.delete(w),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(n=>!n.silent);if(!this._currentThreadId)return t;const a=this._currentThreadId;return t.filter(n=>!n.threadId||n.threadId<=a)}_appendSimilarsToPanel(t,a){if(!this._drawer)return;const n=this._drawer.getPanelContentElement();if(!n)return;a.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products";const r=this._renderUISpec(t,a);r.classList.add("gengage-chat-product-details-similars"),n.appendChild(r),this._mergePanelSourceWithSimilars(t)}_coerceSkuKey(t){return typeof t=="string"?t.trim():typeof t=="number"&&Number.isFinite(t)?String(t).trim():""}_productSkuKey(t){return t?this._coerceSkuKey(t.sku):""}_pdpPageContextSkuKey(){const t=this.config.pageContext?.pageType;return typeof t!="string"||t.toLowerCase()!=="pdp"?null:this._coerceSkuKey(this.config.pageContext?.sku)||null}_getCurrentPanelProductSku(){const t=this._currentPanelSource;if(!t)return null;let a=null;if(t.kind==="spec"?a=t.spec:t.kind==="productDetailsWithSimilars"&&(a=t.pdpSpec),!a)return null;const n=a.elements[a.root];if(!n||n.type!=="ProductDetailsPanel")return null;const r=n.props,i=r?.product??r;return i&&this._coerceSkuKey(i.sku)||null}_activeSkuForProductSummaryClick(){const t=this._getCurrentPanelProductSku();return t||this._pdpPageContextSkuKey()}_mergePanelSourceWithSimilars(t){const a=this._currentPanelSource;a?.kind==="spec"&&this._panel?.currentType==="ProductDetailsPanel"&&(this._currentPanelSource={kind:"productDetailsWithSimilars",pdpSpec:a.spec,similarsSpec:t})}_renderProductDetailsWithSimilars(t,a,n){this._applyPanelListHeadingToContext(n,{kind:"productDetailsWithSimilars",pdpSpec:t,similarsSpec:a});const r=this._renderUISpec(t,n),i=this._renderUISpec(a,n);return i.classList.add("gengage-chat-product-details-similars"),r.appendChild(i),r}_applyPanelListHeadingToContext(t,a){if(t.panelProductListHeading=void 0,!!this._panel){if(a.kind==="spec"){const n=a.spec.elements[a.spec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._panel.titleForComponent("ProductGrid",n.props?.panelTitle??void 0))}else if(a.kind==="productDetailsWithSimilars"){const n=a.similarsSpec.elements[a.similarsSpec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products")}}}_renderPanelFromSource(t,a){return this._applyPanelListHeadingToContext(a,t),t.kind==="favorites"?this._buildFavoritesPageEl():t.kind==="productDetailsWithSimilars"?this._renderProductDetailsWithSimilars(t.pdpSpec,t.similarsSpec,a):this._renderUISpec(t.spec,a)}_handleRollback(t){const a=this._messages.find(n=>n.id===t);a?.threadId&&this._rollbackToThread(a.threadId)}_ensurePdpPrimeSuggestedUiIfNeeded(){const t=this.config.pageContext?.sku;if(!t||!this._drawer||this._hasUnavailableProductContext())return;const a="product",n=this._resolveContextualOpeningActions(a);if(n.length>0){this._drawer.setInputAreaChips(n.map(r=>({label:r.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(r,a)),...r.icon?{icon:r.icon}:{}})));return}this._drawer.setInputAreaChips([{label:this._i18n.groundingReviewCta,icon:"review",onAction:()=>this._sendAction({title:this._i18n.customerReviewsTitle,type:"reviewSummary",payload:{sku:t}})},{label:this._i18n.findSimilarLabel,icon:"similar",onAction:()=>this._sendAction({title:this._i18n.findSimilarLabel,type:"findSimilar",payload:{sku:t}})}])}_rollbackToThread(t){if(this._panel&&this._panel.threads.length>0&&!this._panel.threads.includes(t)&&!this._messages.some(i=>i.threadId===t))return;this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1),this._lastThreadId!=null&&t===this._lastThreadId?(this._presentation.setFocusedThreadId(t),this._drawer?.setPresentationFocus(t)):(this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null)),this._drawer?.setFormerMessagesButtonVisible(!1);for(const i of this._messages){const o=this._shadow?.querySelector(`[data-message-id="${ve(i.id)}"]`);o&&(i.threadId&&i.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(i=>{i instanceof HTMLElement&&i.dataset.threadId&&i.dataset.threadId>t?i.classList.add("gengage-chat-bubble--hidden"):i instanceof HTMLElement&&i.classList.remove("gengage-chat-bubble--hidden")});const a=this._messages.find(i=>i.role==="assistant"&&i.threadId===t),n=a?this._panel?.restoreForMessage(a.id):!1;n||(this._drawer?.clearPanel(),this._currentPanelSource=null),n&&a&&(this._currentPanelSource=null);const r=this._panel.currentType??"";if(this._panel?.updateTopBar(r),this._drawer?.setPills([]),requestAnimationFrame(()=>{this._drawer?.scrollThreadIntoView(t,"auto")}),this._session?.db&&this.config.session?.sessionId){const i=this.config.session.sessionId;(async()=>{try{const o=await this._session?.db?.loadContext(i,t);o&&(this._lastBackendContext=o.context),await this._session?.db?.deleteContextsAfterThread(i,t)}catch{}})()}}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${ve(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,a){return this._session?this._session.loadPayload(t,a):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const a=this.config.session?.sessionId;if(!a)return;const n=this.config.session?.userId??"",r=this.config.accountId;if(await this._session.loadFavorites(n,r),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size),!t)return;const i=await this._session.db?.loadSession(n,r,a);if(!i||i.messages.length===0)return;const o=this.config.pageContext?.sku;if(o&&i.sku&&i.sku!==o)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=i.currentThreadId,this._lastThreadId=i.lastThreadId,this._currentThreadId&&this._lastThreadId&&this._currentThreadId>this._lastThreadId&&(this._currentThreadId=this._lastThreadId),this._chatCreatedAt=i.createdAt,i.panelThreads&&(this._panel.threads=i.panelThreads),i.thumbnailEntries&&(this._thumbnailEntries=i.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),i.panelSnapshotHtml)for(const[c,l]of Object.entries(i.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=ke(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of i.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const p=await this._loadPayload(l.threadId,l.id);p&&(l.uiSpec=p,this._restoreInlineUISpec(l),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(a,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(a)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${ve(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const p=g.elements[g.root];p&&this._panel?.updateTopBar(p.type)}}}}this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_navigatePanelBack(){const t=this._localPanelHistory.pop();if(t){const a=this._buildRenderContext(),n=this._renderPanelFromSource(t.source,a);this._drawer?.setPanelContent(n),this._drawer?.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(t.source)),this._currentPanelSource=t.source;const r=this._localPanelHistory.length>0||(this._panel?.threads.length??0)>1;this._drawer?.updatePanelTopBar(r,!1,t.title);return}if(this._isMobileViewport){this._drawer?.hideMobilePanel();return}this._panel?.navigateBack()}_shouldUseDividerPreviewForSpec(t){return t.elements[t.root]?.type==="ProductGrid"}_shouldUseDividerPreviewForSource(t){return t?.kind==="spec"?this._shouldUseDividerPreviewForSpec(t.spec):!1}_toggleComparisonSku(t){if(t==="")this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectionWarning=null,this._comparisonSelectMode&&(sd(this._currentThreadId??""),this._clearChoicePrompter()),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,ro());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=st._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${st._MAX_COMPARISON_SELECTION} products`,this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()});return}this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],this._comparisonSelectionWarning=null,ao(t)}this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()})}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t){this._drawer?.setComparisonDockContent(null);return}const a=t.querySelector(".gengage-chat-product-grid-wrapper"),n=a?.querySelector(".gengage-chat-product-grid");if(!a||!n){this._drawer?.setComparisonDockContent(null);return}const r=a.querySelector(".gengage-chat-comparison-toggle-btn");if(r&&r.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const i=n.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const o of i){if(o.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const d=o.parentElement,b=this._comparisonSelectedSkus.includes(o.dataset.sku);d.classList.toggle("gengage-chat-comparison-select-wrapper--selected",b);const u=d.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=b?"true":"false",u.setAttribute("aria-pressed",b?"true":"false");const f=u.querySelector(".gengage-chat-comparison-checkbox-icon"),m=u.querySelector(".gengage-chat-comparison-checkbox-label");f&&(f.innerHTML=b?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>'),m&&(m.textContent=b?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare")}continue}const s=o.dataset.sku,c=document.createElement("div");c.className="gengage-chat-comparison-select-wrapper";const l=this._comparisonSelectedSkus.includes(s);l&&c.classList.add("gengage-chat-comparison-select-wrapper--selected");const g=document.createElement("button");g.type="button",g.className="gengage-chat-comparison-checkbox",g.dataset.selected=l?"true":"false",g.setAttribute("aria-pressed",l?"true":"false");const p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-icon",p.innerHTML=l?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const h=document.createElement("span");h.className="gengage-chat-comparison-checkbox-label",h.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(p),g.appendChild(h),g.addEventListener("click",d=>{d.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",d=>{d.target.closest(".gengage-chat-comparison-checkbox")||(d.stopPropagation(),this._toggleComparisonSku(s))})}}else{const i=n.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const o of i){const s=o.querySelector(".gengage-chat-product-card");s&&o.parentNode&&(o.parentNode.insertBefore(s,o),o.remove())}}if(a.querySelector(".gengage-chat-comparison-floating-btn")?.remove(),this._comparisonSelectMode){const i=Bn(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_clearChoicePrompter(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())}_mountChoicePrompter(){if(!this._choicePrompterEl)return!1;if(this._isMobileViewport)return this._drawer?.setComparisonDockContent(this._choicePrompterEl),!0;const t=this._shadow?.querySelector(".gengage-chat-panel-float");return t?(t.appendChild(this._choicePrompterEl),!0):(this._choicePrompterEl=null,!1)}_parseAddToCartActionPayload(t){if(typeof t!="object"||t===null)return null;const a=t,n=this._coerceAddToCartString(a.sku),r=this._coerceAddToCartString(a.cartCode??a.cart_code);let i=1;return typeof a.quantity=="number"&&Number.isFinite(a.quantity)&&a.quantity>0&&(i=Math.max(1,Math.floor(a.quantity))),!n||!r?null:{sku:n,cartCode:r,quantity:i}}_coerceAddToCartString(t){return typeof t=="string"&&t.length>0?t:typeof t=="number"&&Number.isFinite(t)?String(t):""}_runChatAddToCartFlow(t){if(this.config.onAddToCart!==void 0)try{const r=this.config.onAddToCart(t);r instanceof Promise&&r.catch(i=>console.error("[gengage] onAddToCart",i))}catch(r){console.error("[gengage] onAddToCart",r)}Xa(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};pe("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ga(this.analyticsContext(),{attribution_source:"chat",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:t.quantity,sku:t.sku})),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:t.sku,cart_code:t.cartCode,quantity:t.quantity}},{preservePanel:!0});const n=this._i18n.addedToCartToast??"Added to cart";this._drawer?.showCartToast(n),this._drawer?.flashCartBadge()}_buildRenderContext(){const t={locale:Ue(this.config.locale),onAction:a=>{if(ia(a.title,a.type),a.type==="addToCart"){const r=this._parseAddToCartActionPayload(a.payload);if(r){this._runChatAddToCartFlow(r);return}}if(a.type==="launchSingleProduct"){this._drawer?.setDividerPreviewEnabled(!1);const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?a.payload.sku:void 0,i=this._coerceSkuKey(r),o=this._activeSkuForProductSummaryClick();if(i&&o&&i===o)return;i&&Ja(i,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";Ya(r)}if(a.type==="getComparisonTable"){const r=a.payload,i=r&&typeof r=="object"?r:null,o=i&&typeof i.gengage_analytics_source=="string"?i.gengage_analytics_source:"";let s=[];i&&Array.isArray(i.sku_list)&&(s=i.sku_list.filter(c=>typeof c=="string")),o==="floating_compare_dock"?lo(s):no(s.length>0?s:this._comparisonSelectedSkus)}const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{const n=this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url);if(!n){const r=this._coerceSkuKey(a.sku),i=this._activeSkuForProductSummaryClick();if(r&&i&&r===i)return}if(n)pe("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null,...a.name!==void 0&&a.name!==""?{productName:a.name}:{}}),this._saveSessionAndOpenURL(a.url);else{Ja(a.sku);const r=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:r,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{const n=this._productSkuKey(a),r=this._activeSkuForProductSummaryClick();if(n&&r&&n===r)return;if(this._currentPanelSource){const l=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:l}),this._localPanelHistory.length>st._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const i=this._buildRenderContext(),o={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},s=this._shadow?.querySelector(".gengage-chat-messages");if(s){const l=this._renderUISpec(o,i);this._currentThreadId&&(l.dataset.threadId=this._currentThreadId),s.appendChild(l),this._scrollInlineIntoView(l,this._currentThreadId),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const c={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(c,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:c},this._panel&&(this._panel.currentType="ProductDetailsPanel"),this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,hideProductDiscountBadge:this.config.hideProductDiscountBadge,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:st._MAX_COMPARISON_SELECTION,comparisonSelectionWarning:this._comparisonSelectionWarning,onToggleComparisonSku:a=>{this._toggleComparisonSku(a)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(a,n)=>{this._toggleProductFavorite(a,n)},isMobile:this._isMobileViewport};return t}async _toggleFavorite(t,a){if(!this._session)return;const n=this.config.session?.userId??"",r=this.config.accountId;await this._session.toggleFavorite(n,r,t,a),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size)}_revertFavoriteHeartUi(t){const a=this._shadow?.querySelectorAll(`[data-gengage-favorite-sku="${ve(t)}"]`);if(a?.length)for(const n of a){if(!(n instanceof HTMLButtonElement))continue;n.classList.toggle("gengage-chat-favorite-btn--active");const r=n.querySelector("svg");r&&r.setAttribute("fill",n.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none")}}async _toggleProductFavorite(t,a){const n=!(this._session?.favoritedSkus.has(t)??!1),r={sku:t,product:a,favorited:n,sessionId:this.config.session?.sessionId??null};pe("gengage:chat:product-favorite",r),this._bridge?.send("productFavorite",r);const i=this._eventCallbacks.get("gengage-product-favorite");if(i&&i.size>0){for(const o of i)try{const s=o(r);if((s instanceof Promise?await s:s)===!1){this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}}catch{this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}this._session&&(n?this._session.favoritedSkus.add(t):this._session.favoritedSkus.delete(t),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size));return}if(await this._toggleFavorite(t,a),n){oo(t);const o=a.name??t;this._sendAction({title:o,type:"like",payload:{sku:t}},{preservePanel:!0})}}_openFavoritesPanel(){if(this._drawer){if(this._currentPanelSource){const t=this._drawer.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:t}),this._localPanelHistory.length>st._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}this._drawer.setPanelContent(this._buildFavoritesPageEl()),this._drawer.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"favorites"},this._drawer.updatePanelTopBar(!0,!1,this._i18n.favoritesPageTitle)}}_buildFavoritesPageEl(){const t=this._session?.getFavoriteProducts()??[];if(t.length===0){const i=document.createElement("div");i.className="gengage-chat-favorites-empty";const o=document.createElement("div");o.className="gengage-chat-favorites-empty-icon",o.innerHTML='<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',i.appendChild(o);const s=document.createElement("p");return s.textContent=this._i18n.emptyFavoritesMessage,i.appendChild(s),i}const a={},n=[];for(const[i,o]of t.entries()){const s=`card_${i}`;n.push(s),a[s]={type:"ProductCard",props:{product:{sku:o.sku,name:o.name,imageUrl:o.imageUrl,price:o.price}}}}a.grid={type:"ProductGrid",children:n};const r={root:"grid",elements:a};return this._renderUISpec(r,this._buildRenderContext())}async _runEventCallbacks(t,a){const n=this._eventCallbacks.get(t);if(!(!n||n.size===0))for(const r of n)try{const i=r(a);if((i instanceof Promise?await i:i)===!1){this._handleCallbackFailure(t,a);return}}catch{this._handleCallbackFailure(t,a);return}}_handleCallbackFailure(t,a){if(t==="gengage-cart-add"){const n=this._i18n.cartAddErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}if(t==="gengage-product-favorite"){const n=this._i18n.favoriteToggleErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const a=t.uiSpec,n=a.elements[a.root];if(!n)return;const r=n.type;if(r==="ActionButtons"||r==="ComparisonTable"||ri(n))return;const i=this._buildRenderContext(),o=this._shadow?.querySelector(".gengage-chat-messages");if(!o)return;if(r==="ProductDetailsPanel"){const c=n.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,i);t.threadId&&(g.dataset.threadId=t.threadId),o.appendChild(g),this._drawer?.refreshPresentationCollapsed();return}const s=this._renderUISpec(a,i);t.threadId&&(s.dataset.threadId=t.threadId),o.appendChild(s),this._drawer?.refreshPresentationCollapsed()}_createMessage(t,a){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:a,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Vs(t.locale),...t.i18n}}_resolveUISpecRegistry(){return ea(al(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??On,i=(s,c)=>nl(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}},hm=8e3,um=5e3,mm="https://www.google.com/favicon.ico",De=new Map,ii=!1,ot=null,bt=null,Ye=!1;function fm(e){return typeof e=="string"&&e.toLowerCase().startsWith("tr")}function oi(e){return fm(e)?"İnternet bağlantısında sorun var gibi görünüyor. İstek sürerken yeniden deneyeceğiz.":"Your internet connection looks unstable. We'll keep retrying while this request is active."}function si(){let e;for(const t of De.values())e=t;return e}function ja(){ot&&(clearTimeout(ot),ot=null)}function bm(){bt&&(clearInterval(bt),bt=null)}async function ci(){try{if(typeof navigator<"u"&&navigator.onLine===!1)return!1;if(typeof window<"u"){const a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return navigator.onLine}const e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return await fetch(mm,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:e.signal}),!0}catch{return navigator.onLine}finally{clearTimeout(t)}}catch{return typeof navigator>"u"?!0:navigator.onLine}}function Gt(){Ye=!1,bm(),cn()}function Wt(){ot||Ye||De.size===0||(ot=setTimeout(async()=>{ot=null,!(Ye||De.size===0)&&!await ci()&&De.size>0&&(Ye=!0,ca({source:"sdk",message:oi(si()),sticky:!0}),bt||(bt=setInterval(async()=>{if(De.size===0){Gt();return}await ci()&&(Gt(),Wt())},um)))},hm))}function vm(){ii||typeof window>"u"||(ii=!0,window.addEventListener("online",()=>{Gt(),Wt()}),window.addEventListener("offline",()=>{De.size===0||Ye||(Ye=!0,ja(),ca({source:"sdk",message:oi(si()),sticky:!0}))}))}function li(e){vm();const t=Symbol(e.source);De.set(t,e.locale),Wt();let a=!1;return()=>{if(!a){if(a=!0,De.delete(t),De.size===0){ja(),Gt();return}Ye||(ja(),Wt())}}}async function ym(e,t,a){const n=Et("launcher_action",t),r={uiSpecs:[],actions:[]},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(i.signal=a);const o=await fetch(n,i);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const s={onEvent:c=>{const l=St(c);if(l&&(l.type==="ui_spec"&&r.uiSpecs.push(l.spec),l.type==="ui_spec"&&l.spec.elements)){for(const g of Object.values(l.spec.elements))if(g.type==="ActionButton"&&g.props?.action){const p=g.props.action;r.actions.push(p)}}}};return a!==void 0&&(s.signal=a),await Ct(o,s),r}function di(e){const t=document.createElement("div");t.className="gengage-qna-buttons gds-toolbar",t.dataset.gengagePart="qna-button-row",t.setAttribute("role","group"),t.setAttribute("aria-label",e.quickQuestionsAriaLabel??"Quick questions"),e.orientation==="vertical"&&(t.style.flexDirection="column");for(const a of e.actions){const n=document.createElement("button");n.className="gengage-qna-button gds-chip",n.dataset.gengagePart="qna-quick-question",n.textContent=a.title,n.type="button",n.addEventListener("click",()=>{const r={title:a.title,type:a.type};a.payload!==void 0&&(r.payload=a.payload),e.onAction(r)}),t.appendChild(n)}if(e.ctaText||e.onOpenChat){const a=document.createElement("button");a.className="gengage-qna-cta gds-btn gds-btn-secondary",a.dataset.gengagePart="qna-cta",a.textContent=e.ctaText??e.defaultCtaText??"Ask something else",a.type="button",a.addEventListener("click",()=>{e.onOpenChat?.()}),t.appendChild(a)}return t}function _m(e){const t=document.createElement("div");t.className="gengage-qna-input-wrapper",t.dataset.gengagePart="qna-input-wrapper";const a=document.createElement("div");a.className="gengage-qna-input-combo",a.dataset.gengagePart="qna-input-combo";const n=document.createElement("input");n.type="text",n.className="gengage-qna-input",n.dataset.gengagePart="qna-input",n.setAttribute("aria-label",e.askQuestionAriaLabel??"Ask a question");const r=Array.isArray(e.placeholders)?e.placeholders:e.placeholders?[e.placeholders]:[e.defaultInputPlaceholder??"Ask a question..."];let i=0,o=r[0]??"";n.placeholder=o;let s=null,c=null,l=!1;const g=()=>{s&&clearInterval(s),s=null,c&&clearTimeout(c),c=null,n.classList.remove("gengage-qna-input--fade")},p=()=>r.length>1&&!l&&n.value.trim().length===0,h=()=>{g(),p()&&(s=setInterval(()=>{p()&&(n.classList.add("gengage-qna-input--fade"),c=setTimeout(()=>{i=(i+1)%r.length,o=r[i]??"",n.placeholder=o,n.classList.remove("gengage-qna-input--fade")},180))},3e3))},d=document.createElement("div");d.className="gengage-qna-input-actions",d.dataset.gengagePart="qna-input-actions";const b=document.createElement("button");b.className="gengage-qna-icon-btn gengage-qna-clear gengage-qna-icon-btn--hidden",b.type="button",b.dataset.gengagePart="qna-clear",b.setAttribute("aria-label","Clear question"),b.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6L6 18" /><path d="M6 6L18 18" /></svg>';const u=document.createElement("button");u.className="gengage-qna-icon-btn gengage-qna-send gengage-qna-icon-btn--hidden",u.type="button",u.dataset.gengagePart="qna-send",u.setAttribute("aria-label",e.sendQuestionAriaLabel??"Send question"),u.disabled=!0,u.innerHTML=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M22 2L11 13" /><path d="M22 2L15 22L11 13L2 9L22 2Z" /></svg><span class="gengage-qna-sr-only">${e.ctaLabel??e.sendButtonText??"Ask"}</span>`;const f=()=>{const y=n.value.trim().length>0;b.classList.toggle("gengage-qna-icon-btn--hidden",!y),u.classList.toggle("gengage-qna-icon-btn--hidden",!y),u.classList.toggle("gengage-qna-send--active",y),u.disabled=!y},m=()=>{const y=n.value.trim();y&&(e.onSubmit({title:y,type:"user_message",payload:y}),n.value="",f(),h())};return b.addEventListener("click",()=>{n.value="",f(),n.focus({preventScroll:!0})}),u.addEventListener("click",m),n.addEventListener("focus",()=>{l=!0,g(),n.placeholder=""}),n.addEventListener("blur",()=>{l=!1,n.value.trim().length===0&&(n.placeholder=o),h()}),n.addEventListener("input",()=>{if(f(),n.value.trim().length>0){g();return}n.placeholder=l?"":o,h()}),n.addEventListener("keydown",y=>{y.key==="Enter"&&(y.preventDefault(),m()),y.key==="Escape"&&n.value.length>0&&(n.value="",f(),h())}),d.appendChild(b),d.appendChild(u),a.appendChild(n),a.appendChild(d),t.appendChild(a),f(),h(),t._cleanup=()=>{g()},t}function Kt(e,t){if(!e||typeof e!="object")return null;const a=e,n=a.type;if(typeof n!="string"||n.length===0)return null;const r=a.title,i=a.payload,o=typeof r=="string"&&r.length>0?r:t;if(!o)return null;const s={title:o,type:n};return i!==void 0&&(s.payload=i),s}function gi(e){const t={title:e.title,type:e.type};return e.payload!==void 0&&(t.payload=e.payload),t}function pi(e,t){const a=[],n=e.props?.actions;if(Array.isArray(n))for(const o of n){const s=Kt(o);s&&a.push(s)}const r=e.props?.buttons;if(Array.isArray(r))for(const o of r){if(!o||typeof o!="object")continue;const s=o,c=typeof s.label=="string"?s.label:void 0,l=Kt(s.action,c);l&&a.push(l)}if(e.children)for(const o of e.children){const s=t.elements[o];if(!s||s.type!=="ActionButton")continue;const c=typeof s.props?.label=="string"?s.props.label:void 0,l=Kt(s.props?.action,c);l&&a.push(l)}const i=new Set;return a.filter(o=>i.has(o.title)?!1:(i.add(o.title),!0))}var hi={ButtonRow:({element:e,spec:t,context:a})=>{const n=pi(e,t).map(gi),r=e.props?.orientation,i={actions:n,onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(i.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(i.ctaText=a.ctaText),(r==="horizontal"||r==="vertical")&&(i.orientation=r),di(i)},ActionButtons:({element:e,spec:t,context:a})=>{const n={actions:pi(e,t).map(gi),onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(n.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(n.ctaText=a.ctaText),di(n)},ActionButton:({element:e,context:t})=>{const a=document.createElement("button");a.className="gengage-qna-button gds-chip",a.type="button",a.dataset.gengagePart="qna-action-button";const n=e.props?.label;typeof n=="string"?a.textContent=n:a.textContent=t.i18n.defaultCtaText;const r=Kt(e.props?.action,typeof n=="string"?n:void 0);return r&&a.addEventListener("click",()=>t.onAction(r)),a},TextInput:({element:e,context:t})=>{const a=e.props?.placeholder,n=typeof a=="string"||Array.isArray(a)?a:t.inputPlaceholder,r=typeof e.props?.ctaLabel=="string"?e.props.ctaLabel:void 0,i={onSubmit:t.onAction,askQuestionAriaLabel:t.i18n.askQuestionAriaLabel,defaultInputPlaceholder:t.i18n.defaultInputPlaceholder,sendButtonText:t.i18n.sendButton,sendQuestionAriaLabel:t.i18n.sendQuestionAriaLabel};return n!==void 0&&(i.placeholders=n),r!==void 0&&(i.ctaLabel=r),_m(i)},QuestionHeading:({element:e,context:t})=>{const a=document.createElement("h3");a.className="gengage-qna-heading",a.dataset.gengagePart="qna-heading";const n=e.props?.text,r=t.headingTitleOverride;return a.textContent=typeof r=="string"&&r.trim().length>0?r:typeof n=="string"?n:"",a},ProductCard:()=>null},ui=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function xm(){return{...hi}}function wm(e,t,a=hi,n=ui){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-qna-uispec",unknownRenderer:n})}function km(e){if(!e)return;const t=e.extra;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.visible_skus??t.visibleSkus;if(Array.isArray(n)){const r=n.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()).slice(0,200);if(r.length>0)return r}}const a=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0;return a?[a]:void 0}function mi(e,t){if(!e)return null;const a=e.action;if(!a||typeof a!="object")return null;const n=a,r=n.type;if(typeof r!="string"||r.length===0)return null;const i=n.title,o=typeof i=="string"&&i.length>0?i:typeof t=="string"&&t.length>0?t:"";if(!o)return null;const s=n.payload,c={title:o,type:r};return s!==void 0&&(c.payload=s),c}function Cm(e,t){const a=e.elements[e.root];if(!a)return!1;const n=r=>{if(r.type!=="ActionButton")return!1;const i=r.props;if(!i||typeof i!="object")return!1;const o=typeof i.label=="string"?i.label:void 0;return o===t?!0:mi(i,o)?.title===t};if(a.type==="ActionButton")return n(a);if(a.children)for(const r of a.children){const i=e.elements[r];if(i&&n(i))return!0}if(a.type==="ActionButtons"&&Array.isArray(a.props?.buttons)){for(const r of a.props.buttons)if(r?.label===t||r?.action?.title===t)return!0}return!1}var fi=0;function bi(){return fi+=1,`gengage-merge-${fi}`}function Sm(e,t){const a=e.elements[e.root];if(!a||a.type!=="ButtonRow")return;const n=bi();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n]}function Em(e,t){const a=e.elements[e.root];if(!a||a.type!=="ActionButtons")return;const n=bi();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n];const r=a.props?.buttons??[],i={label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}};a.props={...a.props,buttons:[i,...r]}}function Pm(e){const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,...r.payload!==void 0?{payload:r.payload}:{}}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}function Tm(e){return e.find(t=>{const a=t.elements[t.root];return a?.type==="ActionButtons"||a?.type==="ButtonRow"})}function vi(e,t){const a=e.productContextQuickPillLabel,n={text:a};return t&&t.length>0&&(n.sku_list=t),{title:a,type:"user_message",payload:n}}function Am(e,t,a){const n=a?.skuList,r=[],i=[];for(const c of e){const l=c.elements[c.root];if(l?.type==="ActionButton"){const g=l.props;if(mi(g,typeof g?.label=="string"?g.label:void 0)?.type==="findSimilar"){r.push(vi(t,n));continue}}i.push(c)}if(r.length===0)return e;const o=vi(t,n),s=Tm(i);if(!s)return[...i,Pm([o])];if(!Cm(s,o.title)){const c=s.elements[s.root];c?.type==="ActionButtons"?Em(s,o):c?.type==="ButtonRow"&&Sm(s,o)}return i}var yi={quickQuestionsAriaLabel:"Hızlı sorular",askQuestionAriaLabel:"Soru sorun",defaultInputPlaceholder:"Bir soru sorun...",sendButton:"Sor",sendQuestionAriaLabel:"Soruyu gönder",defaultCtaText:"Başka bir şey sor",redirectingToChat:"Sohbete yönlendiriliyor...",productContextQuickPillLabel:"Bu ürün hakkında ne bilmeliyim?"},Lm={quickQuestionsAriaLabel:"Quick questions",askQuestionAriaLabel:"Ask a question",defaultInputPlaceholder:"Ask a question...",sendButton:"Ask",sendQuestionAriaLabel:"Send question",defaultCtaText:"Ask something else",redirectingToChat:"Redirecting to chat...",productContextQuickPillLabel:"What should I know about this product?"};function Im(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Nm(e){return Im(e)==="en"?Lm:yi}var zm=class extends kt{constructor(...e){super(...e),this._abortController=null,this._debounceTimer=null,this._contentEl=null,this._i18n=yi,this._actionHandler=this._handleAction.bind(this),this._openChatHandler=this._handleOpenChat.bind(this)}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-qna-container",this._contentEl.dataset.gengagePart="qna-container",this._contentEl.lang=Ue(e.locale),this.root.appendChild(this._contentEl);const t=e.pageContext?.sku;t&&(this._lastSku=t,await this._fetchAndRender(t)),_t("qna")}onUpdate(e){const t=e.sku;!t||t===this._lastSku||(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=null,this._lastSku=t,this._fetchAndRender(t)},50))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.2s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._contentEl&&(this._cleanupTextInputTimers(),this._contentEl.remove(),this._contentEl=null)}_abort(){this._abortController?.abort(),this._abortController=null}_resolvedQnaHeaderTitle(){const e=this.config.headerTitle??this.config.headingTitle;if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}_cleanupTextInputTimers(){if(!this._contentEl)return;const e=this._contentEl.querySelectorAll(".gengage-qna-input-wrapper");for(const t of e)t._cleanup?.()}async _fetchAndRender(e){if(this._abort(),this._abortController=new AbortController,!this._contentEl)return;this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const t=this._createLoadingIndicator();this._contentEl.appendChild(t);const a={middlewareUrl:this.config.middlewareUrl},n=crypto.randomUUID(),r=Date.now(),i=li({source:"qna",locale:this.config.locale});this.track(ta(this.analyticsContext(),{endpoint:"launcher_action",request_id:n,widget:"qna"}));try{const o={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e,locale:Ue(this.config.locale)},s=this.config.pageContext?.pageType;s!==void 0&&(o.page_type=s);const c=await ym(o,a,this._abortController.signal);if(this.track(yt(this.analyticsContext(),{request_id:n,latency_ms:Date.now()-r,chunk_count:c.actions.length,widget:"qna"})),this.track(na(this.analyticsContext(),{message_count:c.actions.length,history_ref:n,redaction_level:"none",widget:"qna"})),!this._contentEl)return;this._contentEl.innerHTML="";const l=document.createElement("div");l.className="gengage-qna-panel gds-panel",l.dataset.gengagePart="qna-panel",this._contentEl.appendChild(l);const g=this._specIncludesType(c.uiSpecs,"QuestionHeading"),p=this._resolvedQnaHeaderTitle()??(this.config.showStaticQuestion&&this.config.staticQuestionText?this.config.staticQuestionText:void 0);if(!g&&p){const k=document.createElement("h3");k.className="gengage-qna-heading",k.textContent=p,l.appendChild(k)}const h=this.config.inputPlaceholder;let d;if(h!==!0)d=h??this._i18n.defaultInputPlaceholder;else if(c.actions.length>0){const k=c.actions.filter(_=>_.type==="user_message"||_.title.includes("?")).map(_=>_.title);d=k.length>0?k:this._i18n.defaultInputPlaceholder}else d=this._i18n.defaultInputPlaceholder;const b={onAction:this._actionHandler,i18n:this._i18n},u=this._resolvedQnaHeaderTitle();u!==void 0&&(b.headingTitleOverride=u),this.config.hideButtonRowCta||(b.onOpenChat=this._openChatHandler,this.config.ctaText!==void 0&&(b.ctaText=this.config.ctaText)),d!==void 0&&(b.inputPlaceholder=d);const f=this._buildFallbackActionsSpec(c.actions),m=km(this.config.pageContext),y=(c.uiSpecs.length>0?Am(c.uiSpecs,this._i18n,{skuList:m}):[f]).filter(k=>Object.keys(k.elements).length>0);for(const k of y){const _=this._renderUISpec(k,b);l.appendChild(_)}y.length>0&&xt("qna"),this._specIncludesType(y,"TextInput")||this._insertStandaloneInputBeforePills(l,b,d)}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;if(pe("gengage:global:error",{source:"qna",code:"FETCH_ERROR",message:sn(this.config.locale,o)}),this.track(aa(this.analyticsContext(),{request_id:n,error_code:"FETCH_ERROR",error_message:o instanceof Error?o.message:String(o),widget:"qna"})),this._contentEl){this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const s=document.createElement("div");s.className="gengage-qna-panel",this._contentEl.appendChild(s);const c=this.config.inputPlaceholder===!0?this._i18n.defaultInputPlaceholder:this.config.inputPlaceholder??this._i18n.defaultInputPlaceholder,l={onAction:this._actionHandler,i18n:this._i18n,onOpenChat:this._openChatHandler},g=this._resolvedQnaHeaderTitle();g!==void 0&&(l.headingTitleOverride=g),this.config.ctaText!==void 0&&(l.ctaText=this.config.ctaText),this._appendStandaloneInput(l,c,s)}}finally{i()}}_createLoadingIndicator(){const e=document.createElement("div");e.className="gengage-qna-loading";for(let t=0;t<3;t++){const a=document.createElement("div");a.className="gengage-qna-loading-dot",e.appendChild(a)}return e}_resolveI18n(e){return{...Nm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return ea(xm(),this.config.renderer?.registry)}_renderUISpec(e,t){const a=this._resolveUISpecRegistry(),n=this.config.renderer?.unknownRenderer??ui,r=(o,s)=>wm(o,s,a,n),i=this.config.renderer?.renderUISpec;return i?i(e,t,{registry:a,unknownRenderer:n,defaultRender:r}):r(e,t)}_specIncludesType(e,t){for(const a of e)for(const n of Object.values(a.elements))if(n.type===t)return!0;return!1}_buildFallbackActionsSpec(e){if(e.length===0)return{root:"root",elements:{}};const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,payload:r.payload}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}_insertStandaloneInputBeforePills(e,t,a){const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:a}}}},r=this._renderUISpec(n,t),i=r.querySelector(".gengage-qna-input-wrapper");if(!i)return;const o=e.querySelector(".gengage-qna-uispec"),s=o?.querySelector(":scope > .gengage-qna-buttons");if(o&&s)o.insertBefore(i,s);else if(o){const c=o.querySelector(":scope > .gengage-qna-heading");c?c.insertAdjacentElement("afterend",i):o.prepend(i)}else{e.appendChild(r);return}r.remove()}_appendStandaloneInput(e,t,a){if(!this._contentEl)return;const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:t}}}},r=this._renderUISpec(n,e);(a??this._contentEl).appendChild(r)}_handleAction(e){this._showTransitionIndicator(),ia(e.title,e.type),this.config.onActionSelected?.(e),setTimeout(()=>pe("gengage:qna:action",e),350)}_handleOpenChat(){this._showTransitionIndicator(),this.config.onOpenChat?.(),setTimeout(()=>pe("gengage:qna:open-chat",{}),350)}_showTransitionIndicator(){if(!this._contentEl)return;this._contentEl.querySelector(".gengage-qna-transition-indicator")?.remove(),this._contentEl.classList.add("gengage-qna--transitioning");const e=this._i18n.redirectingToChat??"Redirecting to chat...",t=document.createElement("div");t.className="gengage-qna-transition-indicator",t.textContent=e,(this._contentEl.querySelector(".gengage-qna-panel")??this._contentEl).appendChild(t),setTimeout(()=>{this._contentEl?.classList.remove("gengage-qna--transitioning"),t.remove()},600)}};function _i(e){const t=[];for(const a of Object.values(e))if(a.type==="ProductCard"&&a.props){const n=a.props.product??a.props;typeof n.sku=="string"&&typeof n.name=="string"&&t.push(n)}return t}function xi(e){const t=e.headers.get("Content-Type")??"";return t.includes("application/x-ndjson")||t.includes("text/event-stream")}async function Mm(e,t){const a=[],n={onEvent:r=>{const i=St(r);!i||i.type!=="ui_spec"||a.push(..._i(i.spec.elements))}};return t!==void 0&&(n.signal=t),await Ct(e,n),a}async function Bm(e,t,a){const n=Et("similar_products",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(xi(i))return Mm(i,a);const o=await i.text();if(!o)throw new Error("Empty response body from similar_products endpoint");try{return zs(JSON.parse(o))}catch{throw new Error("Invalid JSON from similar_products endpoint")}}async function Rm(e,t){const a=[];let n=null;const r={onEvent:i=>{const o=St(i);if(o){if(o.type==="metadata"&&o.meta){const s=o.meta.group_name;if(typeof s=="string"){n={name:s,products:[]};const c=o.meta.highlight;typeof c=="string"&&(n.highlight=c),a.push(n)}}o.type==="ui_spec"&&n&&n.products.push(..._i(o.spec.elements))}}};return t!==void 0&&(r.signal=t),await Ct(e,r),a}async function Om(e,t,a){const n=Et("product_groupings",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(xi(i))return Rm(i,a);const o=await i.text();if(!o)return[];try{return Ms(JSON.parse(o))}catch{throw new Error("Invalid JSON from product_groupings endpoint")}}function wi(e){const{product:t,index:a,discountType:n,onClick:r,onAddToCart:i,renderCard:o}=e,s=e.i18n,c=e.pricing;if(e.renderCardElement){const u=e.renderCardElement(t,a);if(u)return u}if(o){const u=document.createElement("div");return u.className="gengage-simrel-card gengage-simrel-card--custom gds-card gds-product-card gds-card-interactive",u.dataset.gengagePart="simrel-product-card",u.innerHTML=ke(o(t,a)),u.addEventListener("click",f=>{f.target.closest(".gengage-simrel-atc")||f.target.closest(".gengage-chat-product-card-atc")||r(t)}),u}const l=document.createElement("article");l.className="gengage-simrel-card gengage-chat-product-card gds-card gds-product-card gds-card-interactive",l.dataset.gengagePart="simrel-product-card",t.inStock===!1&&l.classList.add("gengage-simrel-card--out-of-stock"),l.setAttribute("role","listitem"),l.dataset.sku=t.sku;const g=document.createElement("div");if(g.className="gengage-simrel-card-image gengage-chat-product-card-img-wrapper",g.dataset.gengagePart="simrel-product-card-image",t.imageUrl&&we(t.imageUrl)){const u=document.createElement("img");u.className="gengage-chat-product-card-img",u.src=t.imageUrl,u.alt=t.name,u.loading="lazy",Se(u),g.appendChild(u)}if(n==="badge"&&t.discountPercent&&t.discountPercent>0){const u=document.createElement("span");u.className="gengage-simrel-badge gengage-chat-product-card-discount-badge",u.textContent=`%${ua(t.discountPercent)}`,g.appendChild(u)}l.appendChild(g);const p=document.createElement("div");if(p.className="gengage-simrel-card-info gengage-chat-product-card-body",p.dataset.gengagePart="simrel-product-card-body",t.brand){const u=document.createElement("div");u.className="gengage-simrel-card-brand gengage-chat-product-card-brand",u.textContent=t.brand,p.appendChild(u)}const h=document.createElement("div");if(h.className="gengage-simrel-card-name gengage-chat-product-card-name",h.textContent=t.name,h.title=t.name,p.appendChild(h),t.rating!=null&&t.rating>0){const u=document.createElement("div");if(u.className="gengage-simrel-card-rating gengage-chat-product-card-rating",u.appendChild(ma(t.rating)),t.reviewCount!=null){const f=document.createElement("span");f.className="gengage-simrel-card-review-count gengage-chat-product-card-review-count",f.textContent=` (${t.reviewCount})`,u.appendChild(f)}p.appendChild(u)}const d=document.createElement("div");if(d.className="gengage-simrel-card-price gengage-chat-product-card-price",t.originalPrice&&t.originalPrice!==t.price&&(n==="strike-through"||!n)){const u=document.createElement("span");u.className="gengage-simrel-card-price-original gengage-chat-product-card-original-price",u.textContent=K(t.originalPrice,c),d.appendChild(u)}if(t.price&&parseFloat(t.price)>0){const u=document.createElement("span");u.className="gengage-simrel-card-price-current gengage-chat-product-card-price-current",u.textContent=K(t.price,c),d.appendChild(u)}p.appendChild(d),l.appendChild(p);const b=document.createElement("button");if(b.className="gengage-simrel-card-cta gengage-chat-product-card-cta gds-btn gds-btn-secondary",b.type="button",b.dataset.gengagePart="simrel-product-card-cta",b.textContent=s?.ctaLabel??"View",b.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),r(t)}),l.appendChild(b),t.inStock===!1){const u=document.createElement("div");u.className="gengage-simrel-card-oos",u.textContent=s?.outOfStockLabel??"Out of Stock",l.appendChild(u)}else if(t.cartCode){const u=document.createElement("button");u.className="gengage-simrel-atc gengage-simrel-atc-button gds-btn gds-btn-secondary",u.type="button",u.textContent=s?.addToCartButton??"Add to Cart",u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),i({sku:t.sku,quantity:1,cartCode:t.cartCode})}),l.appendChild(u)}return l.addEventListener("click",u=>{u.target.closest(".gengage-simrel-atc")||u.target.closest(".gengage-chat-product-card-atc")||u.target.closest(".gengage-chat-product-card-cta")||r(t)}),l}function ki(e){const t=document.createElement("div");t.className="gengage-simrel-grid",t.setAttribute("role","list"),t.setAttribute("aria-label",e.i18n?.similarProductsAriaLabel??"Similar products"),e.columns&&t.style.setProperty("--gengage-simrel-columns",String(e.columns));for(let a=0;a<e.products.length;a++){const n={product:e.products[a],index:a,onClick:e.onClick,onAddToCart:e.onAddToCart};e.i18n!==void 0&&(n.i18n=e.i18n),e.discountType!==void 0&&(n.discountType=e.discountType),e.renderCard!==void 0&&(n.renderCard=e.renderCard),e.renderCardElement!==void 0&&(n.renderCardElement=e.renderCardElement);const r=wi(n);t.appendChild(r)}return e.products.length===0&&(t.style.display="none",t.dataset.empty="true"),t}var Dm=0;function Fm(e){const t=Dm++,a=document.createElement("div");if(a.className="gengage-simrel-groups",a.dataset.gengagePart="simrel-groups",e.groups.length===0)return a.style.display="none",a.dataset.empty="true",a;const n=document.createElement("div");n.className="gengage-simrel-tabs gds-toolbar",n.dataset.gengagePart="simrel-tab-bar",n.setAttribute("role","tablist");const r=[],i=[];let o=0;const s=f=>{const m={products:f.products,onClick:e.onClick,onAddToCart:e.onAddToCart};return e.i18n!==void 0&&(m.i18n=e.i18n),e.discountType!==void 0&&(m.discountType=e.discountType),e.renderCard!==void 0&&(m.renderCard=e.renderCard),e.renderCardElement!==void 0&&(m.renderCardElement=e.renderCardElement),e.columns!==void 0&&(m.columns=e.columns),m},c=(f,m=!1)=>{if(m&&f!==o&&e.onGroupingActivate){const x=e.groups[f];e.onGroupingActivate({grouping_label:x.name,grouping_index:f})}o=f;for(let x=0;x<r.length;x++){const T=x===f;r[x].classList.toggle("gengage-simrel-tab--active",T),r[x].setAttribute("aria-selected",String(T)),r[x].tabIndex=T?0:-1}const y=e.groups[f],k=i[f];k.innerHTML="";const _=ki(s(y));k.appendChild(_);for(let x=0;x<i.length;x++){const T=x===f;i[x].style.display=T?"":"none",i[x].tabIndex=T?0:-1}};for(let f=0;f<e.groups.length;f++){const m=e.groups[f],y=`gengage-simrel-tab-${t}-${f}`,k=`gengage-simrel-panel-${t}-${f}`,_=document.createElement("button");_.className="gengage-simrel-tab gds-tab",_.type="button",_.dataset.gengagePart="simrel-tab",_.id=y,_.textContent=m.name,_.setAttribute("role","tab"),_.setAttribute("aria-controls",k),_.setAttribute("aria-selected",String(f===0)),_.tabIndex=f===0?0:-1,f===0&&_.classList.add("gengage-simrel-tab--active"),_.addEventListener("click",()=>c(f,!0)),_.addEventListener("keydown",T=>{let P=-1;T.key==="ArrowRight"||T.key==="ArrowDown"?P=(f+1)%e.groups.length:T.key==="ArrowLeft"||T.key==="ArrowUp"?P=(f-1+e.groups.length)%e.groups.length:T.key==="Home"?P=0:T.key==="End"&&(P=e.groups.length-1),P>=0&&(T.preventDefault(),c(P,!0),r[P].focus())}),r.push(_),n.appendChild(_);const x=document.createElement("div");x.className="gengage-simrel-tab-panel",x.dataset.gengagePart="simrel-tab-panel",x.id=k,x.setAttribute("role","tabpanel"),x.setAttribute("aria-labelledby",y),x.tabIndex=f===0?0:-1,f!==0&&(x.style.display="none"),i.push(x)}const l=document.createElement("button");l.type="button",l.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--left",l.setAttribute("aria-label",e.i18n?.scrollTabsLeft??"Scroll tabs left"),l.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';const g=document.createElement("button");g.type="button",g.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--right",g.setAttribute("aria-label",e.i18n?.scrollTabsRight??"Scroll tabs right"),g.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';const p=200;l.addEventListener("click",()=>{n.scrollBy({left:-p,behavior:"smooth"})}),g.addEventListener("click",()=>{n.scrollBy({left:p,behavior:"smooth"})});const h=()=>{const f=n.scrollLeft<=4,m=n.scrollLeft+n.clientWidth>=n.scrollWidth-4;l.style.display=f?"none":"",g.style.display=m?"none":"",n.classList.toggle("gengage-simrel-tabs--peek-right",!m),n.classList.toggle("gengage-simrel-tabs--peek-left",!f)};n.addEventListener("scroll",h,{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(h).observe(n),l.style.display="none",g.style.display="none",requestAnimationFrame(h);const d=document.createElement("div");d.className="gengage-simrel-tabs-wrapper",d.appendChild(l),d.appendChild(n),d.appendChild(g),a.appendChild(d);const b=i[0],u=ki(s(e.groups[0]));b.appendChild(u);for(const f of i)a.appendChild(f);return a}function Ci(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.sku!="string"||typeof t.name!="string"||typeof t.url!="string")return null;const a={sku:t.sku,name:t.name,url:t.url},n=t.imageUrl;typeof n=="string"&&(a.imageUrl=n);const r=t.price;typeof r=="string"&&(a.price=r);const i=t.originalPrice;typeof i=="string"&&(a.originalPrice=i);const o=t.discountPercent;typeof o=="number"&&(a.discountPercent=o);const s=t.brand;typeof s=="string"&&(a.brand=s);const c=t.rating;typeof c=="number"&&(a.rating=c);const l=t.reviewCount;typeof l=="number"&&(a.reviewCount=l);const g=t.cartCode;typeof g=="string"&&(a.cartCode=g);const p=t.inStock;typeof p=="boolean"&&(a.inStock=p);const h=t.extras;return h!=null&&typeof h=="object"&&(a.extras=h),a}function Um(e){if(!e||typeof e!="object")return null;const t=e,a=t.title,n=t.type;if(typeof a!="string"||typeof n!="string")return null;const r={title:a,type:n};return t.payload!==void 0&&(r.payload=t.payload),r}var Si={ProductGrid:({element:e,renderElement:t,context:a})=>{const n=document.createElement("div");n.className="gengage-simrel-grid",n.setAttribute("role","list");const r=e.props?.columns;let i;typeof r=="number"&&Number.isFinite(r)&&r>0?i=Math.floor(r):typeof a.gridColumns=="number"&&Number.isFinite(a.gridColumns)&&a.gridColumns>0&&(i=Math.floor(a.gridColumns)),i!==void 0&&n.style.setProperty("--gengage-simrel-columns",String(i));for(const o of e.children??[]){const s=t(o);s&&n.appendChild(s)}if(n.children.length===0){const o=document.createElement("div");o.className="gengage-simrel-empty",o.textContent=a.i18n.emptyStateMessage,n.appendChild(o)}return n},ProductCard:({element:e,context:t})=>{const a=Ci(e.props?.product??e.props);if(!a)return null;const n=e.props?.index,r=typeof n=="number"&&Number.isFinite(n)?n:0,i=e.props?.discountType,o=i==="strike-through"||i==="badge"?i:t.discountType,s={product:a,index:r,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n};return o!==void 0&&(s.discountType=o),t.renderCard!==void 0&&(s.renderCard=t.renderCard),t.renderCardElement!==void 0&&(s.renderCardElement=t.renderCardElement),t.pricing!==void 0&&(s.pricing=t.pricing),wi(s)},GroupTabs:({element:e,context:t})=>{const a=e.props?.groups;if(!Array.isArray(a))return null;const n=[];for(const o of a){if(!o||typeof o!="object")continue;const s=o;if(typeof s.name!="string")continue;const c=[];if(Array.isArray(s.products))for(const g of s.products){const p=Ci(g);p&&c.push(p)}const l={name:s.name,products:c};typeof s.highlight=="string"&&(l.highlight=s.highlight),n.push(l)}const r={groups:n,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n},i=e.props?.columns;return typeof i=="number"&&Number.isFinite(i)&&i>0?r.columns=Math.floor(i):typeof t.gridColumns=="number"&&Number.isFinite(t.gridColumns)&&t.gridColumns>0&&(r.columns=Math.floor(t.gridColumns)),t.discountType!==void 0&&(r.discountType=t.discountType),t.renderCard!==void 0&&(r.renderCard=t.renderCard),t.renderCardElement!==void 0&&(r.renderCardElement=t.renderCardElement),t.onGroupingActivate!==void 0&&(r.onGroupingActivate=t.onGroupingActivate),Fm(r)},EmptyState:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-empty";const n=e.props?.message;return a.textContent=typeof n=="string"?n:t.i18n.emptyStateMessage,a},AddToCartButton:({element:e,context:t})=>{const a=e.props?.sku,n=e.props?.cartCode;if(typeof a!="string"||typeof n!="string")return null;const r=document.createElement("button");r.className="gengage-simrel-atc gengage-chat-product-card-cta",r.type="button";const i=e.props?.label;return r.textContent=typeof i=="string"?i:t.i18n.addToCartButton,r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t.onAddToCart({sku:a,quantity:1,cartCode:n})}),r},QuickActions:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-quick-actions";const n=e.props?.actions;if(!Array.isArray(n)||!t.onAction)return a;for(const r of n){if(!r||typeof r!="object")continue;const i=r,o=i.label,s=Um(i.action);if(typeof o!="string"||!s)continue;const c=document.createElement("button");c.className="gengage-simrel-quick-action",c.type="button",c.textContent=o,c.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),t.onAction?.(s)}),a.appendChild(c)}return a}},Ei=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function $m(){return{...Si}}function Hm(e,t,a=Si,n=Ei){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-simrel-uispec",unknownRenderer:n})}var Pi={similarProductsAriaLabel:"Benzer ürünler",emptyStateMessage:"Benzer ürün bulunamadı.",addToCartButton:"Sepete Ekle",ctaLabel:"İncele",outOfStockLabel:"Stokta Yok",decreaseLabel:"Azalt",increaseLabel:"Artır",errorLoadingMessage:"Benzer ürünler yüklenemedi.",retryButtonText:"Tekrar dene",priceSuffix:" TL",scrollTabsLeft:"Sola kaydır",scrollTabsRight:"Sağa kaydır"},qm={similarProductsAriaLabel:"Similar products",emptyStateMessage:"No similar products found.",addToCartButton:"Add to cart",ctaLabel:"View",outOfStockLabel:"Out of Stock",decreaseLabel:"Decrease",increaseLabel:"Increase",errorLoadingMessage:"Could not load similar products.",retryButtonText:"Try again",priceSuffix:"",scrollTabsLeft:"Scroll tabs left",scrollTabsRight:"Scroll tabs right"};function jm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Zm(e){return jm(e)==="en"?qm:Pi}var Vm=12e4;function Gm(e){return e instanceof DOMException&&e.name==="AbortError"}var Wm=class extends kt{constructor(...e){super(...e),this._abortController=null,this._contentEl=null,this._lastResultCount=-1,this._i18n=Pi}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-simrel-container",this._contentEl.dataset.gengagePart="simrel-container",this._contentEl.lang=Ue(e.locale);const t=this._clampGridColumns(e.gridColumns);t!==void 0&&this._contentEl.style.setProperty("--gengage-simrel-columns",String(t)),this.root.appendChild(this._contentEl),this._lastSku=e.sku,await this._fetchAndRender(e.sku),_t("simrel")}onUpdate(e){const t=e.sku;!t||t===this._lastSku&&this._lastResultCount!==0||(this._lastSku=t,this._fetchAndRender(t))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.3s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._contentEl&&(this._contentEl.remove(),this._contentEl=null)}_handleProductClick(e){const t={sku:e.sku,name:e.name,url:e.url};if(e.imageUrl!==void 0&&(t.imageUrl=e.imageUrl),e.price!==void 0&&(t.price=e.price),e.originalPrice!==void 0&&(t.originalPrice=e.originalPrice),e.discountPercent!==void 0&&(t.discountPercent=e.discountPercent),e.brand!==void 0&&(t.brand=e.brand),e.rating!==void 0&&(t.rating=e.rating),e.reviewCount!==void 0&&(t.reviewCount=e.reviewCount),e.cartCode!==void 0&&(t.cartCode=e.cartCode),e.inStock!==void 0&&(t.inStock=e.inStock),this.config.onProductClick?.(t)===!1)return;const a=this.config.session?.sessionId??null;pe("gengage:similar:product-click",{sku:e.sku,url:e.url,sessionId:a,productName:e.name}),this.config.onProductNavigate?.(e.url,e.sku,a)}_handleAddToCart(e){Xa(e.sku,e.quantity),this.config.onAddToCart?.(e),pe("gengage:similar:add-to-cart",e),this.track(Ga(this.analyticsContext(),{attribution_source:"simrel",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:e.quantity,sku:e.sku}))}_abort(){this._abortController?.abort(),this._abortController=null}_isSuperseded(e){return this._abortController?.signal!==e}_emitSimilarProductsImpression(e,t){const a=this.config.session?.sessionId??null;pe("gengage:similar:products-impression",{source_sku:this.config.sku,product_count:e,grouped:t,sessionId:a})}_resolveRequestTimeoutMs(){const e=this.config.requestTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Vm:Math.floor(e)}async _fetchAndRender(e){this._abort();const t=new AbortController;this._abortController=t;const a=t.signal;let n=!1;const r=setTimeout(()=>{n=!0,t.abort()},this._resolveRequestTimeoutMs());if(a.addEventListener("abort",()=>clearTimeout(r),{once:!0}),!this._contentEl)return;this._contentEl.innerHTML="",this._contentEl.style.display="";const i=document.createElement("div");i.className="gengage-simrel-loading",i.dataset.gengagePart="simrel-loading";const o=document.createElement("div");o.className="gengage-simrel-spinner",o.dataset.gengagePart="simrel-loading-spinner",i.appendChild(o),this._contentEl.appendChild(i);const s={middlewareUrl:this.config.middlewareUrl},c=crypto.randomUUID(),l=Date.now(),g=li({source:"simrel",locale:this.config.locale});this.track(ta(this.analyticsContext(),{endpoint:"similar_products",request_id:c,widget:"simrel"}));try{const p={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e};this.config.domain!==void 0&&(p.domain=this.config.domain);const h=await Bm(p,s,a);if(this._lastResultCount=h.length,!this._contentEl)return;if(this._contentEl.innerHTML="",h.length>0)try{const d=h.map(f=>f.sku),b=new Map(h.map(f=>[f.sku,f])),u=(await Om({account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",skus:d},s,a)).map(f=>({...f,products:f.products.map(m=>({...b.get(m.sku),...m})).filter(m=>typeof m.sku=="string"&&typeof m.name=="string"&&typeof m.url=="string")})).filter(f=>f.products.length>0);if(u.length>0&&this._contentEl){const f=this._buildGroupsSpec(u),m=this._renderUISpec(f);this._contentEl.appendChild(m),xt("simrel"),this.track(yt(this.analyticsContext(),{request_id:c,latency_ms:Date.now()-l,chunk_count:u.reduce((y,k)=>y+k.products.length,0),widget:"simrel"})),this.track(na(this.analyticsContext(),{message_count:u.reduce((y,k)=>y+k.products.length,0),history_ref:c,redaction_level:"none",widget:"simrel"})),this._emitSimilarProductsImpression(u.reduce((y,k)=>y+k.products.length,0),!0);return}}catch{}if(this._isSuperseded(a))return;if(this._contentEl){const d=this._buildProductsSpec(h),b=this._renderUISpec(d);this._contentEl.appendChild(b)}h.length>0&&xt("simrel"),this.track(yt(this.analyticsContext(),{request_id:c,latency_ms:Date.now()-l,chunk_count:h.length,widget:"simrel"})),this.track(na(this.analyticsContext(),{message_count:h.length,history_ref:c,redaction_level:"none",widget:"simrel"})),this._emitSimilarProductsImpression(h.length,!1)}catch(p){const h=Gm(p);if(h&&this._isSuperseded(a))return;const d=h&&n?"REQUEST_TIMEOUT":"FETCH_ERROR",b=h&&n?"request_timeout":p instanceof Error?p.message:String(p);if(pe("gengage:global:error",{source:"simrel",code:d,message:sn(this.config.locale,p)}),this.track(aa(this.analyticsContext(),{request_id:c,error_code:d,error_message:b,widget:"simrel"})),this._contentEl){this._contentEl.innerHTML="";const u=document.createElement("div");u.className="gengage-simrel-error";const f=document.createElement("span");f.textContent=this._i18n.errorLoadingMessage,u.appendChild(f);const m=document.createElement("button");m.className="gengage-simrel-retry",m.textContent=this._i18n.retryButtonText,m.addEventListener("click",()=>{this._fetchAndRender(this.config.sku)}),u.appendChild(m),this._contentEl.appendChild(u)}}finally{clearTimeout(r),g()}}_clampGridColumns(e){if(!(e===void 0||typeof e!="number"||!Number.isFinite(e)))return Math.max(1,Math.min(12,Math.floor(e)))}_resolveI18n(e){return{...Zm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return ea($m(),this.config.renderer?.registry)}_buildRenderContext(){const e=this.config.renderCard,t={onClick:n=>this._handleProductClick(n),onAddToCart:n=>this._handleAddToCart(n),onGroupingActivate:n=>{pe("gengage:similar:grouping-click",{grouping_label:n.grouping_label,grouping_index:n.grouping_index,sessionId:this.config.session?.sessionId??null})},i18n:this._i18n};this.config.discountType!==void 0&&(t.discountType=this.config.discountType),e!==void 0&&(t.renderCard=e),this.config.renderCardElement!==void 0&&(t.renderCardElement=this.config.renderCardElement),this.config.pricing!==void 0&&(t.pricing=this.config.pricing);const a=this._clampGridColumns(this.config.gridColumns);return a!==void 0&&(t.gridColumns=a),t}_renderUISpec(e){const t=this._resolveUISpecRegistry(),a=this._buildRenderContext(),n=this.config.renderer?.unknownRenderer??Ei,r=(o,s)=>Hm(o,s,t,n),i=this.config.renderer?.renderUISpec;return i?i(e,a,{registry:t,unknownRenderer:n,defaultRender:r}):r(e,a)}_buildProductsSpec(e){const t={},a=[];for(let i=0;i<e.length;i++){const o=e[i],s=`product-${i}`;a.push(s),t[s]={type:"ProductCard",props:{product:o,index:i,discountType:this.config.discountType}}}const n={layout:"grid"},r=this._clampGridColumns(this.config.gridColumns);return r!==void 0&&(n.columns=r),t.root={type:"ProductGrid",props:n,children:a},{root:"root",elements:t}}_buildGroupsSpec(e){return{root:"root",elements:{root:{type:"GroupTabs",props:{groups:e}}}}}},Ti={findSimilarLabel:"Benzerlerini Bul"},Km={findSimilarLabel:"Find Similar"};function Ym(e,t){return t?.findSimilarLabel?t.findSimilarLabel:(e??"tr").toLowerCase().startsWith("en")?Km.findSimilarLabel:Ti.findSimilarLabel}function Yt(e){const t=typeof e.sku=="string"&&e.sku.length>0?e.sku:void 0,a=typeof e.pageContext?.sku=="string"&&e.pageContext.sku.length>0?e.pageContext.sku:void 0;return t??a}var Jm=class extends kt{constructor(...e){super(...e),this._button=null,this._label=Ti.findSimilarLabel}async onInit(e){this._label=Ym(e.locale,e.i18n),this.root.classList.add("gengage-simbut-root"),window.getComputedStyle(this.root).position==="static"&&(this.root.style.position="relative");const t=document.createElement("button");t.type="button",t.className="gengage-chat-find-similar-pill",t.lang=Ue(e.locale),t.textContent=this._label,this._button=t;const a=()=>{t.disabled=!(Yt(this.config)&&(this.config.onFindSimilar||this.config.chat))};t.addEventListener("click",n=>{n.stopPropagation();const r=Yt(this.config);if(!r)return;const i=this.config.imageUrl,o=typeof i=="string"&&fe(i)?i:void 0;if(ia(this._label,"findSimilar"),Ya(r),this.config.onFindSimilar){this.config.onFindSimilar(o?{sku:r,imageUrl:o}:{sku:r});return}const s=this.config.chat;if(!s)return;const c={title:this._label,type:"findSimilar",payload:o?{sku:r,image_url:o}:{sku:r}};s.openWithAction(c,{sku:r})}),this.root.appendChild(t),a(),_t("simbut")}onUpdate(e){if(!this._button)return;const t=!!Yt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}hide(){this.isVisible&&(this.isVisible=!1,this._button&&(this._button.style.display="none"),this.onHide(),this.emit("hide"))}show(){this.isVisible||(this.isVisible=!0,this._button&&(this._button.style.display=""),this.onShow(),this.emit("show"))}_cleanupRoot(){}onShow(){}onHide(){}onDestroy(){this._button?.remove(),this._button=null}setChat(e){if(this.config.chat=e,this._button){const t=!!Yt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}}},Jt=Oe({enabled:Ke().default(!0)}),Qm=Oe({chat:Pe().optional(),qna:Pe().optional(),simrel:Pe().optional(),simbut:Pe().optional()}),Xm=Oe({}),ef=Ha(["none","x-api-key-header","bearer-header","body-api-key"]),tf=Oe({mode:ef.default("none"),key:Pe().optional(),headerName:Pe().optional(),bodyField:Pe().default("api_key")}),af=Oe({enabled:Ke().default(!0),endpoint:Pe().default("/analytics"),auth:tf.default({mode:"none",bodyField:"api_key"}),fireAndForget:Ke().default(!0),useBeacon:Ke().default(!0),keepaliveFetch:Ke().default(!0),timeoutMs:Kr().int().positive().default(4e3),maxRetries:Kr().int().min(0).max(5).default(1)}),Ai="__gengageWidgetsInit",nf=Oe({idempotencyKey:Pe().default(Ai),requireDomReady:Ke().default(!0)}),rf=Ha(["log-and-ignore","throw","delegate"]),of=Oe({unknownActionPolicy:rf.default("log-and-ignore"),allowScriptCall:Ke().default(!1)}),Cf=Oe({version:Vu("1",{error:'version must be "1"'}),accountId:Pe({error:"accountId must be a non-empty string"}).min(1,{error:"accountId must be a non-empty string"}),middlewareUrl:Pe({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}).url({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}),locale:Pe().optional(),widgets:Oe({chat:Jt.default({enabled:!0}),qna:Jt.default({enabled:!0}),simrel:Jt.optional(),simbut:Jt.default({enabled:!1})}),mounts:Qm.default({}),transport:Xm.default({}),analytics:af.default({enabled:!0,endpoint:"/analytics",auth:{mode:"none",bodyField:"api_key"},fireAndForget:!0,useBeacon:!0,keepaliveFetch:!0,timeoutMs:4e3,maxRetries:1}),gtm:nf.default({idempotencyKey:"__gengageWidgetsInit",requireDomReady:!0}),actionHandling:of.default({unknownActionPolicy:"log-and-ignore",allowScriptCall:!1})}),sf=`${Ai}_overlay_`,cf="#gengage-qna",lf="#gengage-simrel",df="#gengage-simbut";function Li(){const e=window;return e.__gengageOverlayRegistry||(e.__gengageOverlayRegistry={instances:{},pending:{}}),e.__gengageOverlayRegistry}function gf(e){const t={pageType:e.pageContext?.pageType??(e.sku!==void 0?"pdp":"other")},a=e.pageContext;return a?.sku!==void 0&&(t.sku=a.sku),a?.skuList!==void 0&&(t.skuList=a.skuList),a?.price!==void 0&&(t.price=a.price),a?.categoryTree!==void 0&&(t.categoryTree=a.categoryTree),a?.url!==void 0&&(t.url=a.url),a?.extra!==void 0&&(t.extra=a.extra),e.sku!==void 0&&(t.sku=e.sku),t}function pf(e,t){const a={...e,...t,pageType:t.pageType??e.pageType};return t.pageType!==void 0&&t.pageType!==e.pageType?(t.pageType!=="pdp"&&t.sku===void 0&&delete a.sku,t.pageType!=="plp"&&t.skuList===void 0&&delete a.skuList):(t.sku===void 0&&e.sku!==void 0&&(a.sku=e.sku),t.skuList===void 0&&e.skuList!==void 0&&(a.skuList=e.skuList)),a}function Za(e){return e instanceof HTMLElement||document.querySelector(e)?e:null}function Ii(e){return e.idempotencyKey??`${sf}${e.accountId}`}var hf=class{constructor(e,t){this.options=e,this.onDestroy=t,this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,this._analyticsClient=null,this._offQnaWire=null,this._destroyed=!1,this._queue=Promise.resolve(),this._warnedQnaMountMissing=!1,this._warnedSimRelMountMissing=!1,this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this.idempotencyKey=Ii(e),this.session=tn(e.session),this._pageContext=gf(e)}get chat(){return this._chat}get qna(){return this._qna}get simrel(){return this._simrel}get simbut(){return this._simbut}get analyticsClient(){return this._analyticsClient}async init(){window.gengage||(window.gengage={}),window.gengage.sessionId=this.session.sessionId,window.gengage.pageContext=this._pageContext,await this._initChat(),this.options.wireQnaToChat!==!1&&(this._offQnaWire=bo()),await this._syncPdpWidgets(),window.gengage.overlay=this}openChat(e){this._chat?.open(e)}closeChat(){this._chat?.close()}async updateContext(e){this._destroyed||await this._enqueue(async()=>{this._pageContext=pf(this._pageContext,e),window.gengage||(window.gengage={}),window.gengage.pageContext=this._pageContext,this._chat?.update(this._pageContext),this._qna?.update(this._pageContext),this._simrel?.update(this._pageContext),this._simbut?.update(this._pageContext),await this._syncPdpWidgets()})}async updateSku(e,t="pdp"){await this.updateContext({sku:e,pageType:t})}async updatePageContext(e){await this.updateContext(e)}async setPageContext(e){await this.updateContext(e)}destroy(){this._destroyed||(this._destroyed=!0,this._offQnaWire?.(),this._offQnaWire=null,this._chat?.destroy(),this._qna?.destroy(),this._simrel?.destroy(),this._simbut?.destroy(),this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,window.gengage?.overlay===this&&delete window.gengage.overlay,this.onDestroy())}async _initChat(){if(this.options.chat?.enabled===!1)return;const e=this.options.middlewareUrl,t=this.options.chat?.productDetailsExtended??this.options.productDetailsExtended,a=this.options.chat?.isDemoWebsite??this.options.isDemoWebsite,n={accountId:this.options.accountId,middlewareUrl:e,session:this.session,pageContext:this._pageContext,variant:this.options.chat?.variant??"floating"};this.options.theme!==void 0&&(n.theme=this.options.theme),this.options.locale!==void 0&&(n.locale=this.options.locale),this.options.pricing!==void 0&&(n.pricing=this.options.pricing),this.options.chat?.mountTarget!==void 0&&(n.mountTarget=this.options.chat.mountTarget),this.options.chat?.pillLauncher!==void 0&&(n.pillLauncher=this.options.chat.pillLauncher),this.options.chat?.launcherImageUrl!==void 0?n.launcherImageUrl=this.options.chat.launcherImageUrl:this.options.chat?.launcherSvg!==void 0&&(n.launcherSvg=this.options.chat.launcherSvg),this.options.chat?.headerTitle!==void 0&&(n.headerTitle=this.options.chat.headerTitle),this.options.chat?.headerAvatarUrl!==void 0&&(n.headerAvatarUrl=this.options.chat.headerAvatarUrl),this.options.chat?.headerBadge!==void 0&&(n.headerBadge=this.options.chat.headerBadge),this.options.chat?.headerCartUrl!==void 0&&(n.headerCartUrl=this.options.chat.headerCartUrl),this.options.chat?.headerFavoritesToggle!==void 0&&(n.headerFavoritesToggle=this.options.chat.headerFavoritesToggle),this.options.chat?.onFavoritesClick!==void 0&&(n.onFavoritesClick=this.options.chat.onFavoritesClick),this.options.chat?.hideMobileLauncher!==void 0&&(n.hideMobileLauncher=this.options.chat.hideMobileLauncher),this.options.chat?.mobileBreakpoint!==void 0&&(n.mobileBreakpoint=this.options.chat.mobileBreakpoint),this.options.chat?.mobileInitialState!==void 0&&(n.mobileInitialState=this.options.chat.mobileInitialState),this.options.chat?.i18n!==void 0&&(n.i18n=this.options.chat.i18n),this.options.chat?.actionHandling!==void 0&&(n.actionHandling=this.options.chat.actionHandling),this.options.chat?.renderer!==void 0&&(n.renderer=this.options.chat.renderer),t!==void 0&&(n.productDetailsExtended=t),a!==void 0&&(n.isDemoWebsite=a),this.options.chat?.productPriceUi!==void 0&&(n.productPriceUi=this.options.chat.productPriceUi),this.options.chat?.hideProductDiscountBadge!==void 0&&(n.hideProductDiscountBadge=this.options.chat.hideProductDiscountBadge),this.options.onScriptCall!==void 0&&(n.onScriptCall=this.options.onScriptCall),this.options.onAddToCart!==void 0&&(n.onAddToCart=this.options.onAddToCart),this.options.chat?.onOpen!==void 0&&(n.onOpen=this.options.chat.onOpen),this.options.chat?.onClose!==void 0&&(n.onClose=this.options.chat.onClose),this._chat=new pm,await this._chat.init(n)}async _syncPdpWidgets(){if(this._destroyed)return;const e=this._pageContext.sku;if(!(this._pageContext.pageType==="pdp"&&e!==void 0&&e.length>0)){this._qna?.hide(),this._simrel?.hide(),this._simbut?.hide();return}const t=this.options.middlewareUrl;if(this.options.qna?.enabled!==!1){const a=this.options.qna?.mountTarget??cf,n=Za(a);if(n)if(this._warnedQnaMountMissing=!1,this._qna)this._qna.show(),this._qna.update({pageType:"pdp",sku:e});else{const r=new zm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.qna?.ctaText!==void 0&&(i.ctaText=this.options.qna.ctaText),this.options.qna?.hideButtonRowCta!==void 0&&(i.hideButtonRowCta=this.options.qna.hideButtonRowCta),this.options.qna?.inputPlaceholder!==void 0&&(i.inputPlaceholder=this.options.qna.inputPlaceholder),this.options.qna?.i18n!==void 0&&(i.i18n=this.options.qna.i18n),this.options.qna?.renderer!==void 0&&(i.renderer=this.options.qna.renderer);const o=this.options.qna?.headerTitle??this.options.qna?.headingTitle;o!==void 0&&(i.headerTitle=o),await r.init(i),this._qna=r}else this._qna?.destroy(),this._qna=null,this._warnedQnaMountMissing||(console.warn(`[gengage] QNA mount target not found: ${a}`),this._warnedQnaMountMissing=!0)}else this._qna?.destroy(),this._qna=null;if(this.options.simrel!==void 0&&this.options.simrel.enabled!==!1){const a=this.options.simrel?.mountTarget??lf,n=Za(a);if(n)if(this._warnedSimRelMountMissing=!1,this._simrel)this._simrel.show(),this._simrel.update({pageType:"pdp",sku:e});else{const r=new Wm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,sku:e,mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.pricing!==void 0&&(i.pricing=this.options.pricing),this.options.simrel?.discountType!==void 0&&(i.discountType=this.options.simrel.discountType),this.options.simrel?.renderCardElement!==void 0&&(i.renderCardElement=this.options.simrel.renderCardElement),this.options.simrel?.renderer!==void 0&&(i.renderer=this.options.simrel.renderer),this.options.onAddToCart!==void 0&&(i.onAddToCart=this.options.onAddToCart),this.options.onProductNavigate!==void 0?i.onProductNavigate=this.options.onProductNavigate:i.onProductNavigate=(o,s,c)=>{fe(o)&&(this._chat?.saveSession(c??this.session.sessionId,s),window.location.href=o)},await r.init(i),this._simrel=r}else this._simrel?.destroy(),this._simrel=null,this._warnedSimRelMountMissing||(console.warn(`[gengage] SimRel mount target not found: ${a}`),this._warnedSimRelMountMissing=!0)}else this._simrel?.destroy(),this._simrel=null;if(this.options.simbut&&this.options.simbut.enabled!==!1){const a=this.options.simbut.mountTarget??df,n=Za(a),r=this._chat??this.options.simbut.onFindSimilar;if(n&&r)if(this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this._simbut)this._simbut.show(),this._simbut.setChat(this._chat),this._simbut.update({pageType:"pdp",sku:e});else{const i=new Jm,o={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n,chat:this._chat};this.options.theme!==void 0&&(o.theme=this.options.theme),this.options.locale!==void 0&&(o.locale=this.options.locale),this.options.simbut.imageUrl!==void 0&&(o.imageUrl=this.options.simbut.imageUrl),this.options.simbut.i18n!==void 0&&(o.i18n=this.options.simbut.i18n),this.options.simbut.onFindSimilar!==void 0&&(o.onFindSimilar=this.options.simbut.onFindSimilar),await i.init(o),this._simbut=i}else this._simbut?.destroy(),this._simbut=null,!n&&!this._warnedSimButMountMissing?(console.warn(`[gengage] SimBut mount target not found: ${a}`),this._warnedSimButMountMissing=!0):!r&&!this._warnedSimButNoChat&&(console.warn("[gengage] SimBut requires chat to be enabled or simbut.onFindSimilar"),this._warnedSimButNoChat=!0)}else this._simbut?.destroy(),this._simbut=null}_enqueue(e){const t=this._queue.then(e);return this._queue=t.catch(a=>{}),t}};async function uf(e){const t=Ii(e),a=Li(),n=a.instances[t];if(n)return n;const r=a.pending[t];if(r)return r;const i=new hf(e,()=>{const s=Li();delete s.instances[t],delete s.pending[t]}),o=i.init().then(()=>(a.instances[t]=i,delete a.pending[t],i)).catch(s=>{throw delete a.pending[t],Qa({reason:"overlay_init_failed",message:s instanceof Error?s.message:String(s)}),s});return a.pending[t]=o,o}var Ni=["gengage:chat:open","gengage:chat:close","gengage:chat:ready","gengage:chat:add-to-cart","gengage:qna:action","gengage:qna:open-chat","gengage:similar:product-click","gengage:similar:grouping-click","gengage:similar:products-impression","gengage:similar:add-to-cart","gengage:global:error","gengage:context:update"],mf=32,zi="#gengage-qna",Mi="#gengage-simrel";function Sf(e){return e}function ff(e){let t=e;if(typeof e=="string"){const i=e.trim();if(i.length===0)return null;if(!i.startsWith("{")&&!i.startsWith("["))return{type:i};try{t=JSON.parse(i)}catch{return null}}if(!t||typeof t!="object")return null;const a=t,n=[a.type,a.command,a.action,a.event].find(i=>typeof i=="string"&&i.length>0);if(!n)return null;let r=a.payload;if(r===void 0&&"data"in a&&(r=a.data),n==="setSession"&&r===void 0){const i={};typeof a.sessionId=="string"&&(i.sessionId=a.sessionId),typeof a.userId=="string"&&(i.userId=a.userId),(i.sessionId!==void 0||i.userId!==void 0)&&(r=i)}return r===void 0?{type:n}:{type:n,payload:r}}function bf(e){if(typeof e=="string"&&e.length>0)return{sku:e};if(e&&typeof e=="object"&&"sku"in e){const t=e.sku;if(typeof t=="string"&&t.length>0){const a=e.pageType;return a!==void 0?{sku:t,pageType:a}:{sku:t}}}return null}function Va(e,t){return t instanceof HTMLElement?!0:typeof t!="string"?!1:e.document.querySelector(t)!==null}function Bi(e,t,a){if(t instanceof HTMLElement||Va(e,t)||typeof t!="string")return t;if(t.startsWith("#")){const i=t.slice(1);if(i.length>0){const o=e.document.getElementById(i);if(o)return o;const s=e.document.createElement("div");return s.id=i,e.document.body.appendChild(s),s}}const n=e.document.getElementById(a);if(n)return n;const r=e.document.createElement("div");return r.id=a,e.document.body.appendChild(r),r}function Ri(e,t){const a=e.webkit?.messageHandlers?.[t];return a&&typeof a.postMessage=="function"?a.postMessage.bind(a):null}function Qt(e,t){const a=e[t];return a&&typeof a=="object"&&typeof a.postMessage=="function"?a:null}function Oi(e={}){const t=e.win??window,a=e.iosHandlerName??"gengage",n=e.androidInterfaceName??"GengageNative",r=e.reactNativeInterfaceName??"ReactNativeWebView";return Ri(t,a)?"ios":Qt(t,n)?"android":Qt(t,r)?"react-native":"browser"}function Di(e,t={}){const a=t.win??window;if(e.sessionId!==void 0){a.__gengageSessionId=e.sessionId,a.gengage||(a.gengage={}),a.gengage.sessionId=e.sessionId;try{a.sessionStorage.setItem("gengage_session_id",e.sessionId)}catch{}}if(e.userId!==void 0){a.gengage||(a.gengage={});const n=a.gengage,r=n.session??{};r.userId=e.userId,n.session=r}}function Fi(e={}){const t=e.win??window,a=t;if(a.gengageNative)return a.gengageNative;const n=e.iosHandlerName??"gengage",r=e.androidInterfaceName??"GengageNative",i=e.reactNativeInterfaceName??"ReactNativeWebView",o=e.trackedEvents??[...Ni],s=Oi({win:t,iosHandlerName:n,androidInterfaceName:r,reactNativeInterfaceName:i});let c=t.gengage?.overlay??null;const l=[],g=(m,y)=>{const k=y===void 0?{type:m}:{type:m,payload:y};if(s==="ios"){Ri(t,n)?.(k);return}if(s==="android"){Qt(t,r)?.postMessage(JSON.stringify(k));return}if(s==="react-native"){Qt(t,i)?.postMessage(JSON.stringify(k));return}},p=m=>{const y=m.detail;!y||typeof y.namespace!="string"||typeof y.type!="string"||g("bridge_message",{namespace:y.namespace,type:y.type,payload:y.payload})};t.addEventListener("gengage:bridge:message",p);const h=o.map(m=>{const y=k=>{const _=k.detail;g("widget_event",{event:m,detail:_})};return t.addEventListener(m,y),{event:m,handler:y}}),d=m=>{l.length>=mf&&l.shift(),l.push(m)},b=()=>{if(!c||l.length===0)return;const m=l.splice(0,l.length);for(const y of m)u(y)},u=m=>{const y=ff(m);if(!y||typeof y.type!="string"){console.warn("[gengage:native-bridge] Invalid message:",m);return}const k=y.type,_=y.payload;switch(k){case"openChat":c?c.openChat(_&&typeof _=="object"?_:_==="half"||_==="full"?{state:_}:void 0):d(y);return;case"closeChat":c?c.closeChat():d(y);return;case"updateContext":case"updatePageContext":case"setPageContext":c&&_&&typeof _=="object"?c.updateContext(_):c?console.warn(`[gengage:native-bridge] ${k}: missing payload`):d(y);return;case"updateSku":{const x=bf(_);if(c&&x){c.updateSku(x.sku,x.pageType);return}c?console.warn("[gengage:native-bridge] updateSku: missing sku"):d(y);return}case"setSession":_&&typeof _=="object"&&Di(_,{win:t});return;case"destroy":c?.destroy();return;default:t.postMessage({gengage:"native",type:k,payload:_},t.location.origin),e.logUnhandled&&console.warn("[gengage:native-bridge] Unhandled inbound type forwarded:",k)}},f={env:s,sendToNative:g,receive:u,setController(m){c=m,b()},destroy(){t.removeEventListener("gengage:bridge:message",p);for(const m of h)t.removeEventListener(m.event,m.handler);l.splice(0,l.length),t.gengageNative===f&&delete t.gengageNative}};return a.gengageNative=f,f}async function vf(e){const{nativeBridge:t,emitReadyEvent:a=!0,...n}=e,r=Fi(t),i={...n};i.onAddToCart||(i.onAddToCart=l=>{r.sendToNative("addToCart",{sku:l.sku,quantity:l.quantity,cartCode:l.cartCode})}),i.onProductNavigate||(i.onProductNavigate=(l,g,p)=>{r.sendToNative("productNavigate",{url:l,sku:g,sessionId:p})});const o=i.qna?.enabled===!0||i.qna?.mountTarget!==void 0;if(i.qna?.enabled!==!1)if(o){const l=Bi(window,i.qna?.mountTarget??zi,"gengage-qna");i.qna={...i.qna,enabled:!0,mountTarget:l}}else Va(window,zi)||(i.qna={enabled:!1});const s=i.simrel?.enabled===!0||i.simrel?.mountTarget!==void 0;if(i.simrel?.enabled!==!1)if(s){const l=Bi(window,i.simrel?.mountTarget??Mi,"gengage-simrel");i.simrel={...i.simrel,enabled:!0,mountTarget:l}}else Va(window,Mi)||(i.simrel={enabled:!1});const c=await uf(i);return r.setController(c),a&&r.sendToNative("ready",{sessionId:c.session.sessionId,widgets:{chat:c.chat!==null,qna:c.qna!==null,simrel:c.simrel!==null}}),{controller:c,bridge:r,destroy(){c.destroy(),r.destroy()}}}Je.DEFAULT_NATIVE_TRACKED_EVENTS=Ni,Je.applyNativeSession=Di,Je.createNativeWebViewBridge=Fi,Je.detectNativeEnvironment=Oi,Je.initNativeOverlayWidgets=vf})(this.Gengage=this.Gengage||{});
178
+ `).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,Be),this._drawer?.showRecoveryPillsOnly(Y)};if(i&&!E)if(o||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const Q=this._i18n.productNotFoundMessage;d.content=Q,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,Q),this._markUnavailableProductContext()}else d.status="done";else if(N)this._drawer?.setPills([]),d.silent||ee();else if(ee(),z)return;i&&(this._contextPrimingInFlight=!1,this._flushQueuedUserMessages()),!U&&d.status==="streaming"&&(d.status="error"),z||this.track(aa(this.analyticsContext(),{request_id:k,error_code:"STREAM_ERROR",error_message:w.message,widget:"chat"}))},onDone:()=>{if(j&&this._abortControllers.delete(j),!r&&n!==this._activeRequestThreadId)return;if(X=!0,O&&this._panel&&this._drawer){const N=this._buildRenderContext();N.isStreaming=!1;const z=O.elements[O.root],B=this._panel.toPanelSpec(O);this._applyPanelListHeadingToContext(N,{kind:"spec",spec:B});const U=z?.type??"ProductGrid";H(B,N,U),q(U,z,"replace",!1),P=!0}O=null,me&&L(!1),v(),this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),yc(ne,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const w=P;if(T&&!P&&p(),T=!1,o&&!h&&!w){const N=this._i18n.productNotFoundMessage;d.content=N,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,N),this._markUnavailableProductContext()}if(P=!1,i){this._contextPrimingInFlight=!1;const N=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),!N&&o&&this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",en()),this._presentation.finalizeAssistantGroup(n);const A=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");A&&(A.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),A.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const E=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,E?()=>{const N=this._buildRenderContext();return this._renderPanelFromSource(E,N)}:void 0),this.track(yt(this.analyticsContext(),{request_id:k,latency_ms:Date.now()-_,chunk_count:x,widget:"chat"})),this.track(ji(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Vi(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},b),this._abortControllers.add(j),!a?.silent&&!r){const w=j;this._drawer?.showStopButton(()=>{w.abort(),this._abortControllers.delete(w),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(n=>!n.silent);if(!this._currentThreadId)return t;const a=this._currentThreadId;return t.filter(n=>!n.threadId||n.threadId<=a)}_appendSimilarsToPanel(t,a){if(!this._drawer)return;const n=this._drawer.getPanelContentElement();if(!n)return;a.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products";const r=this._renderUISpec(t,a);r.classList.add("gengage-chat-product-details-similars"),n.appendChild(r),this._mergePanelSourceWithSimilars(t)}_coerceSkuKey(t){return typeof t=="string"?t.trim():typeof t=="number"&&Number.isFinite(t)?String(t).trim():""}_productSkuKey(t){return t?this._coerceSkuKey(t.sku):""}_pdpPageContextSkuKey(){const t=this.config.pageContext?.pageType;return typeof t!="string"||t.toLowerCase()!=="pdp"?null:this._coerceSkuKey(this.config.pageContext?.sku)||null}_getCurrentPanelProductSku(){const t=this._currentPanelSource;if(!t)return null;let a=null;if(t.kind==="spec"?a=t.spec:t.kind==="productDetailsWithSimilars"&&(a=t.pdpSpec),!a)return null;const n=a.elements[a.root];if(!n||n.type!=="ProductDetailsPanel")return null;const r=n.props,i=r?.product??r;return i&&this._coerceSkuKey(i.sku)||null}_activeSkuForProductSummaryClick(){const t=this._getCurrentPanelProductSku();return t||this._pdpPageContextSkuKey()}_mergePanelSourceWithSimilars(t){const a=this._currentPanelSource;a?.kind==="spec"&&this._panel?.currentType==="ProductDetailsPanel"&&(this._currentPanelSource={kind:"productDetailsWithSimilars",pdpSpec:a.spec,similarsSpec:t})}_renderProductDetailsWithSimilars(t,a,n){this._applyPanelListHeadingToContext(n,{kind:"productDetailsWithSimilars",pdpSpec:t,similarsSpec:a});const r=this._renderUISpec(t,n),i=this._renderUISpec(a,n);return i.classList.add("gengage-chat-product-details-similars"),r.appendChild(i),r}_applyPanelListHeadingToContext(t,a){if(t.panelProductListHeading=void 0,!!this._panel){if(a.kind==="spec"){const n=a.spec.elements[a.spec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._panel.titleForComponent("ProductGrid",n.props?.panelTitle??void 0))}else if(a.kind==="productDetailsWithSimilars"){const n=a.similarsSpec.elements[a.similarsSpec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products")}}}_renderPanelFromSource(t,a){return this._applyPanelListHeadingToContext(a,t),t.kind==="favorites"?this._buildFavoritesPageEl():t.kind==="productDetailsWithSimilars"?this._renderProductDetailsWithSimilars(t.pdpSpec,t.similarsSpec,a):this._renderUISpec(t.spec,a)}_handleRollback(t){const a=this._messages.find(n=>n.id===t);a?.threadId&&this._rollbackToThread(a.threadId)}_ensurePdpPrimeSuggestedUiIfNeeded(){const t=this.config.pageContext?.sku;if(!t||!this._drawer||this._hasUnavailableProductContext())return;const a="product",n=this._resolveContextualOpeningActions(a);if(n.length>0){this._drawer.setInputAreaChips(n.map(r=>({label:r.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(r,a)),...r.icon?{icon:r.icon}:{}})));return}this._drawer.setInputAreaChips([...this.config.hideUserReviews!==!0?[{label:this._i18n.groundingReviewCta,icon:"review",onAction:()=>this._sendAction({title:this._i18n.customerReviewsTitle,type:"reviewSummary",payload:{sku:t}})}]:[],{label:this._i18n.findSimilarLabel,icon:"similar",onAction:()=>this._sendAction({title:this._i18n.findSimilarLabel,type:"findSimilar",payload:{sku:t}})}])}_rollbackToThread(t){if(this._panel&&this._panel.threads.length>0&&!this._panel.threads.includes(t)&&!this._messages.some(i=>i.threadId===t))return;this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1),this._lastThreadId!=null&&t===this._lastThreadId?(this._presentation.setFocusedThreadId(t),this._drawer?.setPresentationFocus(t)):(this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null)),this._drawer?.setFormerMessagesButtonVisible(!1);for(const i of this._messages){const o=this._shadow?.querySelector(`[data-message-id="${ve(i.id)}"]`);o&&(i.threadId&&i.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(i=>{i instanceof HTMLElement&&i.dataset.threadId&&i.dataset.threadId>t?i.classList.add("gengage-chat-bubble--hidden"):i instanceof HTMLElement&&i.classList.remove("gengage-chat-bubble--hidden")});const a=this._messages.find(i=>i.role==="assistant"&&i.threadId===t),n=a?this._panel?.restoreForMessage(a.id):!1;n||(this._drawer?.clearPanel(),this._currentPanelSource=null),n&&a&&(this._currentPanelSource=null);const r=this._panel.currentType??"";if(this._panel?.updateTopBar(r),this._drawer?.setPills([]),requestAnimationFrame(()=>{this._drawer?.scrollThreadIntoView(t,"auto")}),this._session?.db&&this.config.session?.sessionId){const i=this.config.session.sessionId;(async()=>{try{const o=await this._session?.db?.loadContext(i,t);o&&(this._lastBackendContext=o.context),await this._session?.db?.deleteContextsAfterThread(i,t)}catch{}})()}}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${ve(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,a){return this._session?this._session.loadPayload(t,a):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const a=this.config.session?.sessionId;if(!a)return;const n=this.config.session?.userId??"",r=this.config.accountId;if(await this._session.loadFavorites(n,r),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size),!t)return;const i=await this._session.db?.loadSession(n,r,a);if(!i||i.messages.length===0)return;const o=this.config.pageContext?.sku;if(o&&i.sku&&i.sku!==o)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=i.currentThreadId,this._lastThreadId=i.lastThreadId,this._currentThreadId&&this._lastThreadId&&this._currentThreadId>this._lastThreadId&&(this._currentThreadId=this._lastThreadId),this._chatCreatedAt=i.createdAt,i.panelThreads&&(this._panel.threads=i.panelThreads),i.thumbnailEntries&&(this._thumbnailEntries=i.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),i.panelSnapshotHtml)for(const[c,l]of Object.entries(i.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=ke(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of i.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const p=await this._loadPayload(l.threadId,l.id);p&&(l.uiSpec=p,this._restoreInlineUISpec(l),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(a,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(a)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${ve(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const p=g.elements[g.root];p&&this._panel?.updateTopBar(p.type)}}}}this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_navigatePanelBack(){const t=this._localPanelHistory.pop();if(t){const a=this._buildRenderContext(),n=this._renderPanelFromSource(t.source,a);this._drawer?.setPanelContent(n),this._drawer?.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(t.source)),this._currentPanelSource=t.source;const r=this._localPanelHistory.length>0||(this._panel?.threads.length??0)>1;this._drawer?.updatePanelTopBar(r,!1,t.title);return}if(this._isMobileViewport){this._drawer?.hideMobilePanel();return}this._panel?.navigateBack()}_shouldUseDividerPreviewForSpec(t){return t.elements[t.root]?.type==="ProductGrid"}_shouldUseDividerPreviewForSource(t){return t?.kind==="spec"?this._shouldUseDividerPreviewForSpec(t.spec):!1}_toggleComparisonSku(t){if(t==="")this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectionWarning=null,this._comparisonSelectMode&&(sd(this._currentThreadId??""),this._clearChoicePrompter()),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,ro());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=st._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${st._MAX_COMPARISON_SELECTION} products`,this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()});return}this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],this._comparisonSelectionWarning=null,ao(t)}this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()})}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t){this._drawer?.setComparisonDockContent(null);return}const a=t.querySelector(".gengage-chat-product-grid-wrapper"),n=a?.querySelector(".gengage-chat-product-grid");if(!a||!n){this._drawer?.setComparisonDockContent(null);return}const r=a.querySelector(".gengage-chat-comparison-toggle-btn");if(r&&r.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const i=n.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const o of i){if(o.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const d=o.parentElement,b=this._comparisonSelectedSkus.includes(o.dataset.sku);d.classList.toggle("gengage-chat-comparison-select-wrapper--selected",b);const u=d.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=b?"true":"false",u.setAttribute("aria-pressed",b?"true":"false");const f=u.querySelector(".gengage-chat-comparison-checkbox-icon"),m=u.querySelector(".gengage-chat-comparison-checkbox-label");f&&(f.innerHTML=b?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>'),m&&(m.textContent=b?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare")}continue}const s=o.dataset.sku,c=document.createElement("div");c.className="gengage-chat-comparison-select-wrapper";const l=this._comparisonSelectedSkus.includes(s);l&&c.classList.add("gengage-chat-comparison-select-wrapper--selected");const g=document.createElement("button");g.type="button",g.className="gengage-chat-comparison-checkbox",g.dataset.selected=l?"true":"false",g.setAttribute("aria-pressed",l?"true":"false");const p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-icon",p.innerHTML=l?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const h=document.createElement("span");h.className="gengage-chat-comparison-checkbox-label",h.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(p),g.appendChild(h),g.addEventListener("click",d=>{d.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",d=>{d.target.closest(".gengage-chat-comparison-checkbox")||(d.stopPropagation(),this._toggleComparisonSku(s))})}}else{const i=n.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const o of i){const s=o.querySelector(".gengage-chat-product-card");s&&o.parentNode&&(o.parentNode.insertBefore(s,o),o.remove())}}if(a.querySelector(".gengage-chat-comparison-floating-btn")?.remove(),this._comparisonSelectMode){const i=Bn(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_clearChoicePrompter(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())}_mountChoicePrompter(){if(!this._choicePrompterEl)return!1;if(this._isMobileViewport)return this._drawer?.setComparisonDockContent(this._choicePrompterEl),!0;const t=this._shadow?.querySelector(".gengage-chat-panel-float");return t?(t.appendChild(this._choicePrompterEl),!0):(this._choicePrompterEl=null,!1)}_parseAddToCartActionPayload(t){if(typeof t!="object"||t===null)return null;const a=t,n=this._coerceAddToCartString(a.sku),r=this._coerceAddToCartString(a.cartCode??a.cart_code);let i=1;return typeof a.quantity=="number"&&Number.isFinite(a.quantity)&&a.quantity>0&&(i=Math.max(1,Math.floor(a.quantity))),!n||!r?null:{sku:n,cartCode:r,quantity:i}}_coerceAddToCartString(t){return typeof t=="string"&&t.length>0?t:typeof t=="number"&&Number.isFinite(t)?String(t):""}_runChatAddToCartFlow(t){if(this.config.onAddToCart!==void 0)try{const r=this.config.onAddToCart(t);r instanceof Promise&&r.catch(i=>console.error("[gengage] onAddToCart",i))}catch(r){console.error("[gengage] onAddToCart",r)}Xa(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};pe("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ga(this.analyticsContext(),{attribution_source:"chat",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:t.quantity,sku:t.sku})),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:t.sku,cart_code:t.cartCode,quantity:t.quantity}},{preservePanel:!0});const n=this._i18n.addedToCartToast??"Added to cart";this._drawer?.showCartToast(n),this._drawer?.flashCartBadge()}_buildRenderContext(){const t={locale:Ue(this.config.locale),onAction:a=>{if(ia(a.title,a.type),a.type==="addToCart"){const r=this._parseAddToCartActionPayload(a.payload);if(r){this._runChatAddToCartFlow(r);return}}if(a.type==="launchSingleProduct"){this._drawer?.setDividerPreviewEnabled(!1);const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?a.payload.sku:void 0,i=this._coerceSkuKey(r),o=this._activeSkuForProductSummaryClick();if(i&&o&&i===o)return;i&&Ja(i,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";Ya(r)}if(a.type==="getComparisonTable"){const r=a.payload,i=r&&typeof r=="object"?r:null,o=i&&typeof i.gengage_analytics_source=="string"?i.gengage_analytics_source:"";let s=[];i&&Array.isArray(i.sku_list)&&(s=i.sku_list.filter(c=>typeof c=="string")),o==="floating_compare_dock"?lo(s):no(s.length>0?s:this._comparisonSelectedSkus)}const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{const n=this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url);if(!n){const r=this._coerceSkuKey(a.sku),i=this._activeSkuForProductSummaryClick();if(r&&i&&r===i)return}if(n)pe("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null,...a.name!==void 0&&a.name!==""?{productName:a.name}:{}}),this._saveSessionAndOpenURL(a.url);else{Ja(a.sku);const r=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:r,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{const n=this._productSkuKey(a),r=this._activeSkuForProductSummaryClick();if(n&&r&&n===r)return;if(this._currentPanelSource){const l=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:l}),this._localPanelHistory.length>st._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const i=this._buildRenderContext(),o={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},s=this._shadow?.querySelector(".gengage-chat-messages");if(s){const l=this._renderUISpec(o,i);this._currentThreadId&&(l.dataset.threadId=this._currentThreadId),s.appendChild(l),this._scrollInlineIntoView(l,this._currentThreadId),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const c={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(c,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:c},this._panel&&(this._panel.currentType="ProductDetailsPanel"),this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,hideProductDiscountBadge:this.config.hideProductDiscountBadge,hideUserReviews:this.config.hideUserReviews,hideStockStatus:this.config.hideStockStatus,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:st._MAX_COMPARISON_SELECTION,comparisonSelectionWarning:this._comparisonSelectionWarning,onToggleComparisonSku:a=>{this._toggleComparisonSku(a)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(a,n)=>{this._toggleProductFavorite(a,n)},isMobile:this._isMobileViewport};return t}async _toggleFavorite(t,a){if(!this._session)return;const n=this.config.session?.userId??"",r=this.config.accountId;await this._session.toggleFavorite(n,r,t,a),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size)}_revertFavoriteHeartUi(t){const a=this._shadow?.querySelectorAll(`[data-gengage-favorite-sku="${ve(t)}"]`);if(a?.length)for(const n of a){if(!(n instanceof HTMLButtonElement))continue;n.classList.toggle("gengage-chat-favorite-btn--active");const r=n.querySelector("svg");r&&r.setAttribute("fill",n.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none")}}async _toggleProductFavorite(t,a){const n=!(this._session?.favoritedSkus.has(t)??!1),r={sku:t,product:a,favorited:n,sessionId:this.config.session?.sessionId??null};pe("gengage:chat:product-favorite",r),this._bridge?.send("productFavorite",r);const i=this._eventCallbacks.get("gengage-product-favorite");if(i&&i.size>0){for(const o of i)try{const s=o(r);if((s instanceof Promise?await s:s)===!1){this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}}catch{this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}this._session&&(n?this._session.favoritedSkus.add(t):this._session.favoritedSkus.delete(t),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size));return}if(await this._toggleFavorite(t,a),n){oo(t);const o=a.name??t;this._sendAction({title:o,type:"like",payload:{sku:t}},{preservePanel:!0})}}_openFavoritesPanel(){if(this._drawer){if(this._currentPanelSource){const t=this._drawer.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:t}),this._localPanelHistory.length>st._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}this._drawer.setPanelContent(this._buildFavoritesPageEl()),this._drawer.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"favorites"},this._drawer.updatePanelTopBar(!0,!1,this._i18n.favoritesPageTitle)}}_buildFavoritesPageEl(){const t=this._session?.getFavoriteProducts()??[];if(t.length===0){const i=document.createElement("div");i.className="gengage-chat-favorites-empty";const o=document.createElement("div");o.className="gengage-chat-favorites-empty-icon",o.innerHTML='<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',i.appendChild(o);const s=document.createElement("p");return s.textContent=this._i18n.emptyFavoritesMessage,i.appendChild(s),i}const a={},n=[];for(const[i,o]of t.entries()){const s=`card_${i}`;n.push(s),a[s]={type:"ProductCard",props:{product:{sku:o.sku,name:o.name,imageUrl:o.imageUrl,price:o.price}}}}a.grid={type:"ProductGrid",children:n};const r={root:"grid",elements:a};return this._renderUISpec(r,this._buildRenderContext())}async _runEventCallbacks(t,a){const n=this._eventCallbacks.get(t);if(!(!n||n.size===0))for(const r of n)try{const i=r(a);if((i instanceof Promise?await i:i)===!1){this._handleCallbackFailure(t,a);return}}catch{this._handleCallbackFailure(t,a);return}}_handleCallbackFailure(t,a){if(t==="gengage-cart-add"){const n=this._i18n.cartAddErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}if(t==="gengage-product-favorite"){const n=this._i18n.favoriteToggleErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const a=t.uiSpec,n=a.elements[a.root];if(!n)return;const r=n.type;if(r==="ActionButtons"||r==="ComparisonTable"||ri(n))return;const i=this._buildRenderContext(),o=this._shadow?.querySelector(".gengage-chat-messages");if(!o)return;if(r==="ProductDetailsPanel"){const c=n.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,i);t.threadId&&(g.dataset.threadId=t.threadId),o.appendChild(g),this._drawer?.refreshPresentationCollapsed();return}const s=this._renderUISpec(a,i);t.threadId&&(s.dataset.threadId=t.threadId),o.appendChild(s),this._drawer?.refreshPresentationCollapsed()}_createMessage(t,a){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:a,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Vs(t.locale),...t.i18n}}_resolveUISpecRegistry(){return ea(al(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??On,i=(s,c)=>nl(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}},hm=8e3,um=5e3,mm="https://www.google.com/favicon.ico",De=new Map,ii=!1,ot=null,bt=null,Ye=!1;function fm(e){return typeof e=="string"&&e.toLowerCase().startsWith("tr")}function oi(e){return fm(e)?"İnternet bağlantısında sorun var gibi görünüyor. İstek sürerken yeniden deneyeceğiz.":"Your internet connection looks unstable. We'll keep retrying while this request is active."}function si(){let e;for(const t of De.values())e=t;return e}function ja(){ot&&(clearTimeout(ot),ot=null)}function bm(){bt&&(clearInterval(bt),bt=null)}async function ci(){try{if(typeof navigator<"u"&&navigator.onLine===!1)return!1;if(typeof window<"u"){const a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return navigator.onLine}const e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return await fetch(mm,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:e.signal}),!0}catch{return navigator.onLine}finally{clearTimeout(t)}}catch{return typeof navigator>"u"?!0:navigator.onLine}}function Gt(){Ye=!1,bm(),cn()}function Wt(){ot||Ye||De.size===0||(ot=setTimeout(async()=>{ot=null,!(Ye||De.size===0)&&!await ci()&&De.size>0&&(Ye=!0,ca({source:"sdk",message:oi(si()),sticky:!0}),bt||(bt=setInterval(async()=>{if(De.size===0){Gt();return}await ci()&&(Gt(),Wt())},um)))},hm))}function vm(){ii||typeof window>"u"||(ii=!0,window.addEventListener("online",()=>{Gt(),Wt()}),window.addEventListener("offline",()=>{De.size===0||Ye||(Ye=!0,ja(),ca({source:"sdk",message:oi(si()),sticky:!0}))}))}function li(e){vm();const t=Symbol(e.source);De.set(t,e.locale),Wt();let a=!1;return()=>{if(!a){if(a=!0,De.delete(t),De.size===0){ja(),Gt();return}Ye||(ja(),Wt())}}}async function ym(e,t,a){const n=Et("launcher_action",t),r={uiSpecs:[],actions:[]},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(i.signal=a);const o=await fetch(n,i);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const s={onEvent:c=>{const l=St(c);if(l&&(l.type==="ui_spec"&&r.uiSpecs.push(l.spec),l.type==="ui_spec"&&l.spec.elements)){for(const g of Object.values(l.spec.elements))if(g.type==="ActionButton"&&g.props?.action){const p=g.props.action;r.actions.push(p)}}}};return a!==void 0&&(s.signal=a),await Ct(o,s),r}function di(e){const t=document.createElement("div");t.className="gengage-qna-buttons gds-toolbar",t.dataset.gengagePart="qna-button-row",t.setAttribute("role","group"),t.setAttribute("aria-label",e.quickQuestionsAriaLabel??"Quick questions"),e.orientation==="vertical"&&(t.style.flexDirection="column");for(const a of e.actions){const n=document.createElement("button");n.className="gengage-qna-button gds-chip",n.dataset.gengagePart="qna-quick-question",n.textContent=a.title,n.type="button",n.addEventListener("click",()=>{const r={title:a.title,type:a.type};a.payload!==void 0&&(r.payload=a.payload),e.onAction(r)}),t.appendChild(n)}if(e.ctaText||e.onOpenChat){const a=document.createElement("button");a.className="gengage-qna-cta gds-btn gds-btn-secondary",a.dataset.gengagePart="qna-cta",a.textContent=e.ctaText??e.defaultCtaText??"Ask something else",a.type="button",a.addEventListener("click",()=>{e.onOpenChat?.()}),t.appendChild(a)}return t}function _m(e){const t=document.createElement("div");t.className="gengage-qna-input-wrapper",t.dataset.gengagePart="qna-input-wrapper";const a=document.createElement("div");a.className="gengage-qna-input-combo",a.dataset.gengagePart="qna-input-combo";const n=document.createElement("input");n.type="text",n.className="gengage-qna-input",n.dataset.gengagePart="qna-input",n.setAttribute("aria-label",e.askQuestionAriaLabel??"Ask a question");const r=Array.isArray(e.placeholders)?e.placeholders:e.placeholders?[e.placeholders]:[e.defaultInputPlaceholder??"Ask a question..."];let i=0,o=r[0]??"";n.placeholder=o;let s=null,c=null,l=!1;const g=()=>{s&&clearInterval(s),s=null,c&&clearTimeout(c),c=null,n.classList.remove("gengage-qna-input--fade")},p=()=>r.length>1&&!l&&n.value.trim().length===0,h=()=>{g(),p()&&(s=setInterval(()=>{p()&&(n.classList.add("gengage-qna-input--fade"),c=setTimeout(()=>{i=(i+1)%r.length,o=r[i]??"",n.placeholder=o,n.classList.remove("gengage-qna-input--fade")},180))},3e3))},d=document.createElement("div");d.className="gengage-qna-input-actions",d.dataset.gengagePart="qna-input-actions";const b=document.createElement("button");b.className="gengage-qna-icon-btn gengage-qna-clear gengage-qna-icon-btn--hidden",b.type="button",b.dataset.gengagePart="qna-clear",b.setAttribute("aria-label","Clear question"),b.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6L6 18" /><path d="M6 6L18 18" /></svg>';const u=document.createElement("button");u.className="gengage-qna-icon-btn gengage-qna-send gengage-qna-icon-btn--hidden",u.type="button",u.dataset.gengagePart="qna-send",u.setAttribute("aria-label",e.sendQuestionAriaLabel??"Send question"),u.disabled=!0,u.innerHTML=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M22 2L11 13" /><path d="M22 2L15 22L11 13L2 9L22 2Z" /></svg><span class="gengage-qna-sr-only">${e.ctaLabel??e.sendButtonText??"Ask"}</span>`;const f=()=>{const y=n.value.trim().length>0;b.classList.toggle("gengage-qna-icon-btn--hidden",!y),u.classList.toggle("gengage-qna-icon-btn--hidden",!y),u.classList.toggle("gengage-qna-send--active",y),u.disabled=!y},m=()=>{const y=n.value.trim();y&&(e.onSubmit({title:y,type:"user_message",payload:y}),n.value="",f(),h())};return b.addEventListener("click",()=>{n.value="",f(),n.focus({preventScroll:!0})}),u.addEventListener("click",m),n.addEventListener("focus",()=>{l=!0,g(),n.placeholder=""}),n.addEventListener("blur",()=>{l=!1,n.value.trim().length===0&&(n.placeholder=o),h()}),n.addEventListener("input",()=>{if(f(),n.value.trim().length>0){g();return}n.placeholder=l?"":o,h()}),n.addEventListener("keydown",y=>{y.key==="Enter"&&(y.preventDefault(),m()),y.key==="Escape"&&n.value.length>0&&(n.value="",f(),h())}),d.appendChild(b),d.appendChild(u),a.appendChild(n),a.appendChild(d),t.appendChild(a),f(),h(),t._cleanup=()=>{g()},t}function Kt(e,t){if(!e||typeof e!="object")return null;const a=e,n=a.type;if(typeof n!="string"||n.length===0)return null;const r=a.title,i=a.payload,o=typeof r=="string"&&r.length>0?r:t;if(!o)return null;const s={title:o,type:n};return i!==void 0&&(s.payload=i),s}function gi(e){const t={title:e.title,type:e.type};return e.payload!==void 0&&(t.payload=e.payload),t}function pi(e,t){const a=[],n=e.props?.actions;if(Array.isArray(n))for(const o of n){const s=Kt(o);s&&a.push(s)}const r=e.props?.buttons;if(Array.isArray(r))for(const o of r){if(!o||typeof o!="object")continue;const s=o,c=typeof s.label=="string"?s.label:void 0,l=Kt(s.action,c);l&&a.push(l)}if(e.children)for(const o of e.children){const s=t.elements[o];if(!s||s.type!=="ActionButton")continue;const c=typeof s.props?.label=="string"?s.props.label:void 0,l=Kt(s.props?.action,c);l&&a.push(l)}const i=new Set;return a.filter(o=>i.has(o.title)?!1:(i.add(o.title),!0))}var hi={ButtonRow:({element:e,spec:t,context:a})=>{const n=pi(e,t).map(gi),r=e.props?.orientation,i={actions:n,onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(i.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(i.ctaText=a.ctaText),(r==="horizontal"||r==="vertical")&&(i.orientation=r),di(i)},ActionButtons:({element:e,spec:t,context:a})=>{const n={actions:pi(e,t).map(gi),onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(n.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(n.ctaText=a.ctaText),di(n)},ActionButton:({element:e,context:t})=>{const a=document.createElement("button");a.className="gengage-qna-button gds-chip",a.type="button",a.dataset.gengagePart="qna-action-button";const n=e.props?.label;typeof n=="string"?a.textContent=n:a.textContent=t.i18n.defaultCtaText;const r=Kt(e.props?.action,typeof n=="string"?n:void 0);return r&&a.addEventListener("click",()=>t.onAction(r)),a},TextInput:({element:e,context:t})=>{const a=e.props?.placeholder,n=typeof a=="string"||Array.isArray(a)?a:t.inputPlaceholder,r=typeof e.props?.ctaLabel=="string"?e.props.ctaLabel:void 0,i={onSubmit:t.onAction,askQuestionAriaLabel:t.i18n.askQuestionAriaLabel,defaultInputPlaceholder:t.i18n.defaultInputPlaceholder,sendButtonText:t.i18n.sendButton,sendQuestionAriaLabel:t.i18n.sendQuestionAriaLabel};return n!==void 0&&(i.placeholders=n),r!==void 0&&(i.ctaLabel=r),_m(i)},QuestionHeading:({element:e,context:t})=>{const a=document.createElement("h3");a.className="gengage-qna-heading",a.dataset.gengagePart="qna-heading";const n=e.props?.text,r=t.headingTitleOverride;return a.textContent=typeof r=="string"&&r.trim().length>0?r:typeof n=="string"?n:"",a},ProductCard:()=>null},ui=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function xm(){return{...hi}}function wm(e,t,a=hi,n=ui){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-qna-uispec",unknownRenderer:n})}function km(e){if(!e)return;const t=e.extra;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.visible_skus??t.visibleSkus;if(Array.isArray(n)){const r=n.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()).slice(0,200);if(r.length>0)return r}}const a=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0;return a?[a]:void 0}function mi(e,t){if(!e)return null;const a=e.action;if(!a||typeof a!="object")return null;const n=a,r=n.type;if(typeof r!="string"||r.length===0)return null;const i=n.title,o=typeof i=="string"&&i.length>0?i:typeof t=="string"&&t.length>0?t:"";if(!o)return null;const s=n.payload,c={title:o,type:r};return s!==void 0&&(c.payload=s),c}function Cm(e,t){const a=e.elements[e.root];if(!a)return!1;const n=r=>{if(r.type!=="ActionButton")return!1;const i=r.props;if(!i||typeof i!="object")return!1;const o=typeof i.label=="string"?i.label:void 0;return o===t?!0:mi(i,o)?.title===t};if(a.type==="ActionButton")return n(a);if(a.children)for(const r of a.children){const i=e.elements[r];if(i&&n(i))return!0}if(a.type==="ActionButtons"&&Array.isArray(a.props?.buttons)){for(const r of a.props.buttons)if(r?.label===t||r?.action?.title===t)return!0}return!1}var fi=0;function bi(){return fi+=1,`gengage-merge-${fi}`}function Sm(e,t){const a=e.elements[e.root];if(!a||a.type!=="ButtonRow")return;const n=bi();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n]}function Em(e,t){const a=e.elements[e.root];if(!a||a.type!=="ActionButtons")return;const n=bi();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n];const r=a.props?.buttons??[],i={label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}};a.props={...a.props,buttons:[i,...r]}}function Pm(e){const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,...r.payload!==void 0?{payload:r.payload}:{}}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}function Tm(e){return e.find(t=>{const a=t.elements[t.root];return a?.type==="ActionButtons"||a?.type==="ButtonRow"})}function vi(e,t){const a=e.productContextQuickPillLabel,n={text:a};return t&&t.length>0&&(n.sku_list=t),{title:a,type:"user_message",payload:n}}function Am(e,t,a){const n=a?.skuList,r=[],i=[];for(const c of e){const l=c.elements[c.root];if(l?.type==="ActionButton"){const g=l.props;if(mi(g,typeof g?.label=="string"?g.label:void 0)?.type==="findSimilar"){r.push(vi(t,n));continue}}i.push(c)}if(r.length===0)return e;const o=vi(t,n),s=Tm(i);if(!s)return[...i,Pm([o])];if(!Cm(s,o.title)){const c=s.elements[s.root];c?.type==="ActionButtons"?Em(s,o):c?.type==="ButtonRow"&&Sm(s,o)}return i}var yi={quickQuestionsAriaLabel:"Hızlı sorular",askQuestionAriaLabel:"Soru sorun",defaultInputPlaceholder:"Bir soru sorun...",sendButton:"Sor",sendQuestionAriaLabel:"Soruyu gönder",defaultCtaText:"Başka bir şey sor",redirectingToChat:"Sohbete yönlendiriliyor...",productContextQuickPillLabel:"Bu ürün hakkında ne bilmeliyim?"},Lm={quickQuestionsAriaLabel:"Quick questions",askQuestionAriaLabel:"Ask a question",defaultInputPlaceholder:"Ask a question...",sendButton:"Ask",sendQuestionAriaLabel:"Send question",defaultCtaText:"Ask something else",redirectingToChat:"Redirecting to chat...",productContextQuickPillLabel:"What should I know about this product?"};function Im(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Nm(e){return Im(e)==="en"?Lm:yi}var zm=class extends kt{constructor(...e){super(...e),this._abortController=null,this._debounceTimer=null,this._contentEl=null,this._i18n=yi,this._actionHandler=this._handleAction.bind(this),this._openChatHandler=this._handleOpenChat.bind(this)}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-qna-container",this._contentEl.dataset.gengagePart="qna-container",this._contentEl.lang=Ue(e.locale),this.root.appendChild(this._contentEl);const t=e.pageContext?.sku;t&&(this._lastSku=t,await this._fetchAndRender(t)),_t("qna")}onUpdate(e){const t=e.sku;!t||t===this._lastSku||(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=null,this._lastSku=t,this._fetchAndRender(t)},50))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.2s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._contentEl&&(this._cleanupTextInputTimers(),this._contentEl.remove(),this._contentEl=null)}_abort(){this._abortController?.abort(),this._abortController=null}_resolvedQnaHeaderTitle(){const e=this.config.headerTitle??this.config.headingTitle;if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}_cleanupTextInputTimers(){if(!this._contentEl)return;const e=this._contentEl.querySelectorAll(".gengage-qna-input-wrapper");for(const t of e)t._cleanup?.()}async _fetchAndRender(e){if(this._abort(),this._abortController=new AbortController,!this._contentEl)return;this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const t=this._createLoadingIndicator();this._contentEl.appendChild(t);const a={middlewareUrl:this.config.middlewareUrl},n=crypto.randomUUID(),r=Date.now(),i=li({source:"qna",locale:this.config.locale});this.track(ta(this.analyticsContext(),{endpoint:"launcher_action",request_id:n,widget:"qna"}));try{const o={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e,locale:Ue(this.config.locale)},s=this.config.pageContext?.pageType;s!==void 0&&(o.page_type=s);const c=await ym(o,a,this._abortController.signal);if(this.track(yt(this.analyticsContext(),{request_id:n,latency_ms:Date.now()-r,chunk_count:c.actions.length,widget:"qna"})),this.track(na(this.analyticsContext(),{message_count:c.actions.length,history_ref:n,redaction_level:"none",widget:"qna"})),!this._contentEl)return;this._contentEl.innerHTML="";const l=document.createElement("div");l.className="gengage-qna-panel gds-panel",l.dataset.gengagePart="qna-panel",this._contentEl.appendChild(l);const g=this._specIncludesType(c.uiSpecs,"QuestionHeading"),p=this._resolvedQnaHeaderTitle()??(this.config.showStaticQuestion&&this.config.staticQuestionText?this.config.staticQuestionText:void 0);if(!g&&p){const k=document.createElement("h3");k.className="gengage-qna-heading",k.textContent=p,l.appendChild(k)}const h=this.config.inputPlaceholder;let d;if(h!==!0)d=h??this._i18n.defaultInputPlaceholder;else if(c.actions.length>0){const k=c.actions.filter(_=>_.type==="user_message"||_.title.includes("?")).map(_=>_.title);d=k.length>0?k:this._i18n.defaultInputPlaceholder}else d=this._i18n.defaultInputPlaceholder;const b={onAction:this._actionHandler,i18n:this._i18n},u=this._resolvedQnaHeaderTitle();u!==void 0&&(b.headingTitleOverride=u),this.config.hideButtonRowCta||(b.onOpenChat=this._openChatHandler,this.config.ctaText!==void 0&&(b.ctaText=this.config.ctaText)),d!==void 0&&(b.inputPlaceholder=d);const f=this._buildFallbackActionsSpec(c.actions),m=km(this.config.pageContext),y=(c.uiSpecs.length>0?Am(c.uiSpecs,this._i18n,{skuList:m}):[f]).filter(k=>Object.keys(k.elements).length>0);for(const k of y){const _=this._renderUISpec(k,b);l.appendChild(_)}y.length>0&&xt("qna"),this._specIncludesType(y,"TextInput")||this._insertStandaloneInputBeforePills(l,b,d)}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;if(pe("gengage:global:error",{source:"qna",code:"FETCH_ERROR",message:sn(this.config.locale,o)}),this.track(aa(this.analyticsContext(),{request_id:n,error_code:"FETCH_ERROR",error_message:o instanceof Error?o.message:String(o),widget:"qna"})),this._contentEl){this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const s=document.createElement("div");s.className="gengage-qna-panel",this._contentEl.appendChild(s);const c=this.config.inputPlaceholder===!0?this._i18n.defaultInputPlaceholder:this.config.inputPlaceholder??this._i18n.defaultInputPlaceholder,l={onAction:this._actionHandler,i18n:this._i18n,onOpenChat:this._openChatHandler},g=this._resolvedQnaHeaderTitle();g!==void 0&&(l.headingTitleOverride=g),this.config.ctaText!==void 0&&(l.ctaText=this.config.ctaText),this._appendStandaloneInput(l,c,s)}}finally{i()}}_createLoadingIndicator(){const e=document.createElement("div");e.className="gengage-qna-loading";for(let t=0;t<3;t++){const a=document.createElement("div");a.className="gengage-qna-loading-dot",e.appendChild(a)}return e}_resolveI18n(e){return{...Nm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return ea(xm(),this.config.renderer?.registry)}_renderUISpec(e,t){const a=this._resolveUISpecRegistry(),n=this.config.renderer?.unknownRenderer??ui,r=(o,s)=>wm(o,s,a,n),i=this.config.renderer?.renderUISpec;return i?i(e,t,{registry:a,unknownRenderer:n,defaultRender:r}):r(e,t)}_specIncludesType(e,t){for(const a of e)for(const n of Object.values(a.elements))if(n.type===t)return!0;return!1}_buildFallbackActionsSpec(e){if(e.length===0)return{root:"root",elements:{}};const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,payload:r.payload}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}_insertStandaloneInputBeforePills(e,t,a){const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:a}}}},r=this._renderUISpec(n,t),i=r.querySelector(".gengage-qna-input-wrapper");if(!i)return;const o=e.querySelector(".gengage-qna-uispec"),s=o?.querySelector(":scope > .gengage-qna-buttons");if(o&&s)o.insertBefore(i,s);else if(o){const c=o.querySelector(":scope > .gengage-qna-heading");c?c.insertAdjacentElement("afterend",i):o.prepend(i)}else{e.appendChild(r);return}r.remove()}_appendStandaloneInput(e,t,a){if(!this._contentEl)return;const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:t}}}},r=this._renderUISpec(n,e);(a??this._contentEl).appendChild(r)}_handleAction(e){this._showTransitionIndicator(),ia(e.title,e.type),this.config.onActionSelected?.(e),setTimeout(()=>pe("gengage:qna:action",e),350)}_handleOpenChat(){this._showTransitionIndicator(),this.config.onOpenChat?.(),setTimeout(()=>pe("gengage:qna:open-chat",{}),350)}_showTransitionIndicator(){if(!this._contentEl)return;this._contentEl.querySelector(".gengage-qna-transition-indicator")?.remove(),this._contentEl.classList.add("gengage-qna--transitioning");const e=this._i18n.redirectingToChat??"Redirecting to chat...",t=document.createElement("div");t.className="gengage-qna-transition-indicator",t.textContent=e,(this._contentEl.querySelector(".gengage-qna-panel")??this._contentEl).appendChild(t),setTimeout(()=>{this._contentEl?.classList.remove("gengage-qna--transitioning"),t.remove()},600)}};function _i(e){const t=[];for(const a of Object.values(e))if(a.type==="ProductCard"&&a.props){const n=a.props.product??a.props;typeof n.sku=="string"&&typeof n.name=="string"&&t.push(n)}return t}function xi(e){const t=e.headers.get("Content-Type")??"";return t.includes("application/x-ndjson")||t.includes("text/event-stream")}async function Mm(e,t){const a=[],n={onEvent:r=>{const i=St(r);!i||i.type!=="ui_spec"||a.push(..._i(i.spec.elements))}};return t!==void 0&&(n.signal=t),await Ct(e,n),a}async function Bm(e,t,a){const n=Et("similar_products",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(xi(i))return Mm(i,a);const o=await i.text();if(!o)throw new Error("Empty response body from similar_products endpoint");try{return zs(JSON.parse(o))}catch{throw new Error("Invalid JSON from similar_products endpoint")}}async function Rm(e,t){const a=[];let n=null;const r={onEvent:i=>{const o=St(i);if(o){if(o.type==="metadata"&&o.meta){const s=o.meta.group_name;if(typeof s=="string"){n={name:s,products:[]};const c=o.meta.highlight;typeof c=="string"&&(n.highlight=c),a.push(n)}}o.type==="ui_spec"&&n&&n.products.push(..._i(o.spec.elements))}}};return t!==void 0&&(r.signal=t),await Ct(e,r),a}async function Om(e,t,a){const n=Et("product_groupings",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(xi(i))return Rm(i,a);const o=await i.text();if(!o)return[];try{return Ms(JSON.parse(o))}catch{throw new Error("Invalid JSON from product_groupings endpoint")}}function wi(e){const{product:t,index:a,discountType:n,onClick:r,onAddToCart:i,renderCard:o}=e,s=e.i18n,c=e.pricing;if(e.renderCardElement){const u=e.renderCardElement(t,a);if(u)return u}if(o){const u=document.createElement("div");return u.className="gengage-simrel-card gengage-simrel-card--custom gds-card gds-product-card gds-card-interactive",u.dataset.gengagePart="simrel-product-card",u.innerHTML=ke(o(t,a)),u.addEventListener("click",f=>{f.target.closest(".gengage-simrel-atc")||f.target.closest(".gengage-chat-product-card-atc")||r(t)}),u}const l=document.createElement("article");l.className="gengage-simrel-card gengage-chat-product-card gds-card gds-product-card gds-card-interactive",l.dataset.gengagePart="simrel-product-card",t.inStock===!1&&l.classList.add("gengage-simrel-card--out-of-stock"),l.setAttribute("role","listitem"),l.dataset.sku=t.sku;const g=document.createElement("div");if(g.className="gengage-simrel-card-image gengage-chat-product-card-img-wrapper",g.dataset.gengagePart="simrel-product-card-image",t.imageUrl&&we(t.imageUrl)){const u=document.createElement("img");u.className="gengage-chat-product-card-img",u.src=t.imageUrl,u.alt=t.name,u.loading="lazy",Se(u),g.appendChild(u)}if(n==="badge"&&t.discountPercent&&t.discountPercent>0){const u=document.createElement("span");u.className="gengage-simrel-badge gengage-chat-product-card-discount-badge",u.textContent=`%${ua(t.discountPercent)}`,g.appendChild(u)}l.appendChild(g);const p=document.createElement("div");if(p.className="gengage-simrel-card-info gengage-chat-product-card-body",p.dataset.gengagePart="simrel-product-card-body",t.brand){const u=document.createElement("div");u.className="gengage-simrel-card-brand gengage-chat-product-card-brand",u.textContent=t.brand,p.appendChild(u)}const h=document.createElement("div");if(h.className="gengage-simrel-card-name gengage-chat-product-card-name",h.textContent=t.name,h.title=t.name,p.appendChild(h),t.rating!=null&&t.rating>0){const u=document.createElement("div");if(u.className="gengage-simrel-card-rating gengage-chat-product-card-rating",u.appendChild(ma(t.rating)),t.reviewCount!=null){const f=document.createElement("span");f.className="gengage-simrel-card-review-count gengage-chat-product-card-review-count",f.textContent=` (${t.reviewCount})`,u.appendChild(f)}p.appendChild(u)}const d=document.createElement("div");if(d.className="gengage-simrel-card-price gengage-chat-product-card-price",t.originalPrice&&t.originalPrice!==t.price&&(n==="strike-through"||!n)){const u=document.createElement("span");u.className="gengage-simrel-card-price-original gengage-chat-product-card-original-price",u.textContent=K(t.originalPrice,c),d.appendChild(u)}if(t.price&&parseFloat(t.price)>0){const u=document.createElement("span");u.className="gengage-simrel-card-price-current gengage-chat-product-card-price-current",u.textContent=K(t.price,c),d.appendChild(u)}p.appendChild(d),l.appendChild(p);const b=document.createElement("button");if(b.className="gengage-simrel-card-cta gengage-chat-product-card-cta gds-btn gds-btn-secondary",b.type="button",b.dataset.gengagePart="simrel-product-card-cta",b.textContent=s?.ctaLabel??"View",b.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),r(t)}),l.appendChild(b),t.inStock===!1){const u=document.createElement("div");u.className="gengage-simrel-card-oos",u.textContent=s?.outOfStockLabel??"Out of Stock",l.appendChild(u)}else if(t.cartCode){const u=document.createElement("button");u.className="gengage-simrel-atc gengage-simrel-atc-button gds-btn gds-btn-secondary",u.type="button",u.textContent=s?.addToCartButton??"Add to Cart",u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),i({sku:t.sku,quantity:1,cartCode:t.cartCode})}),l.appendChild(u)}return l.addEventListener("click",u=>{u.target.closest(".gengage-simrel-atc")||u.target.closest(".gengage-chat-product-card-atc")||u.target.closest(".gengage-chat-product-card-cta")||r(t)}),l}function ki(e){const t=document.createElement("div");t.className="gengage-simrel-grid",t.setAttribute("role","list"),t.setAttribute("aria-label",e.i18n?.similarProductsAriaLabel??"Similar products"),e.columns&&t.style.setProperty("--gengage-simrel-columns",String(e.columns));for(let a=0;a<e.products.length;a++){const n={product:e.products[a],index:a,onClick:e.onClick,onAddToCart:e.onAddToCart};e.i18n!==void 0&&(n.i18n=e.i18n),e.discountType!==void 0&&(n.discountType=e.discountType),e.renderCard!==void 0&&(n.renderCard=e.renderCard),e.renderCardElement!==void 0&&(n.renderCardElement=e.renderCardElement);const r=wi(n);t.appendChild(r)}return e.products.length===0&&(t.style.display="none",t.dataset.empty="true"),t}var Dm=0;function Fm(e){const t=Dm++,a=document.createElement("div");if(a.className="gengage-simrel-groups",a.dataset.gengagePart="simrel-groups",e.groups.length===0)return a.style.display="none",a.dataset.empty="true",a;const n=document.createElement("div");n.className="gengage-simrel-tabs gds-toolbar",n.dataset.gengagePart="simrel-tab-bar",n.setAttribute("role","tablist");const r=[],i=[];let o=0;const s=f=>{const m={products:f.products,onClick:e.onClick,onAddToCart:e.onAddToCart};return e.i18n!==void 0&&(m.i18n=e.i18n),e.discountType!==void 0&&(m.discountType=e.discountType),e.renderCard!==void 0&&(m.renderCard=e.renderCard),e.renderCardElement!==void 0&&(m.renderCardElement=e.renderCardElement),e.columns!==void 0&&(m.columns=e.columns),m},c=(f,m=!1)=>{if(m&&f!==o&&e.onGroupingActivate){const x=e.groups[f];e.onGroupingActivate({grouping_label:x.name,grouping_index:f})}o=f;for(let x=0;x<r.length;x++){const T=x===f;r[x].classList.toggle("gengage-simrel-tab--active",T),r[x].setAttribute("aria-selected",String(T)),r[x].tabIndex=T?0:-1}const y=e.groups[f],k=i[f];k.innerHTML="";const _=ki(s(y));k.appendChild(_);for(let x=0;x<i.length;x++){const T=x===f;i[x].style.display=T?"":"none",i[x].tabIndex=T?0:-1}};for(let f=0;f<e.groups.length;f++){const m=e.groups[f],y=`gengage-simrel-tab-${t}-${f}`,k=`gengage-simrel-panel-${t}-${f}`,_=document.createElement("button");_.className="gengage-simrel-tab gds-tab",_.type="button",_.dataset.gengagePart="simrel-tab",_.id=y,_.textContent=m.name,_.setAttribute("role","tab"),_.setAttribute("aria-controls",k),_.setAttribute("aria-selected",String(f===0)),_.tabIndex=f===0?0:-1,f===0&&_.classList.add("gengage-simrel-tab--active"),_.addEventListener("click",()=>c(f,!0)),_.addEventListener("keydown",T=>{let P=-1;T.key==="ArrowRight"||T.key==="ArrowDown"?P=(f+1)%e.groups.length:T.key==="ArrowLeft"||T.key==="ArrowUp"?P=(f-1+e.groups.length)%e.groups.length:T.key==="Home"?P=0:T.key==="End"&&(P=e.groups.length-1),P>=0&&(T.preventDefault(),c(P,!0),r[P].focus())}),r.push(_),n.appendChild(_);const x=document.createElement("div");x.className="gengage-simrel-tab-panel",x.dataset.gengagePart="simrel-tab-panel",x.id=k,x.setAttribute("role","tabpanel"),x.setAttribute("aria-labelledby",y),x.tabIndex=f===0?0:-1,f!==0&&(x.style.display="none"),i.push(x)}const l=document.createElement("button");l.type="button",l.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--left",l.setAttribute("aria-label",e.i18n?.scrollTabsLeft??"Scroll tabs left"),l.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';const g=document.createElement("button");g.type="button",g.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--right",g.setAttribute("aria-label",e.i18n?.scrollTabsRight??"Scroll tabs right"),g.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';const p=200;l.addEventListener("click",()=>{n.scrollBy({left:-p,behavior:"smooth"})}),g.addEventListener("click",()=>{n.scrollBy({left:p,behavior:"smooth"})});const h=()=>{const f=n.scrollLeft<=4,m=n.scrollLeft+n.clientWidth>=n.scrollWidth-4;l.style.display=f?"none":"",g.style.display=m?"none":"",n.classList.toggle("gengage-simrel-tabs--peek-right",!m),n.classList.toggle("gengage-simrel-tabs--peek-left",!f)};n.addEventListener("scroll",h,{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(h).observe(n),l.style.display="none",g.style.display="none",requestAnimationFrame(h);const d=document.createElement("div");d.className="gengage-simrel-tabs-wrapper",d.appendChild(l),d.appendChild(n),d.appendChild(g),a.appendChild(d);const b=i[0],u=ki(s(e.groups[0]));b.appendChild(u);for(const f of i)a.appendChild(f);return a}function Ci(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.sku!="string"||typeof t.name!="string"||typeof t.url!="string")return null;const a={sku:t.sku,name:t.name,url:t.url},n=t.imageUrl;typeof n=="string"&&(a.imageUrl=n);const r=t.price;typeof r=="string"&&(a.price=r);const i=t.originalPrice;typeof i=="string"&&(a.originalPrice=i);const o=t.discountPercent;typeof o=="number"&&(a.discountPercent=o);const s=t.brand;typeof s=="string"&&(a.brand=s);const c=t.rating;typeof c=="number"&&(a.rating=c);const l=t.reviewCount;typeof l=="number"&&(a.reviewCount=l);const g=t.cartCode;typeof g=="string"&&(a.cartCode=g);const p=t.inStock;typeof p=="boolean"&&(a.inStock=p);const h=t.extras;return h!=null&&typeof h=="object"&&(a.extras=h),a}function Um(e){if(!e||typeof e!="object")return null;const t=e,a=t.title,n=t.type;if(typeof a!="string"||typeof n!="string")return null;const r={title:a,type:n};return t.payload!==void 0&&(r.payload=t.payload),r}var Si={ProductGrid:({element:e,renderElement:t,context:a})=>{const n=document.createElement("div");n.className="gengage-simrel-grid",n.setAttribute("role","list");const r=e.props?.columns;let i;typeof r=="number"&&Number.isFinite(r)&&r>0?i=Math.floor(r):typeof a.gridColumns=="number"&&Number.isFinite(a.gridColumns)&&a.gridColumns>0&&(i=Math.floor(a.gridColumns)),i!==void 0&&n.style.setProperty("--gengage-simrel-columns",String(i));for(const o of e.children??[]){const s=t(o);s&&n.appendChild(s)}if(n.children.length===0){const o=document.createElement("div");o.className="gengage-simrel-empty",o.textContent=a.i18n.emptyStateMessage,n.appendChild(o)}return n},ProductCard:({element:e,context:t})=>{const a=Ci(e.props?.product??e.props);if(!a)return null;const n=e.props?.index,r=typeof n=="number"&&Number.isFinite(n)?n:0,i=e.props?.discountType,o=i==="strike-through"||i==="badge"?i:t.discountType,s={product:a,index:r,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n};return o!==void 0&&(s.discountType=o),t.renderCard!==void 0&&(s.renderCard=t.renderCard),t.renderCardElement!==void 0&&(s.renderCardElement=t.renderCardElement),t.pricing!==void 0&&(s.pricing=t.pricing),wi(s)},GroupTabs:({element:e,context:t})=>{const a=e.props?.groups;if(!Array.isArray(a))return null;const n=[];for(const o of a){if(!o||typeof o!="object")continue;const s=o;if(typeof s.name!="string")continue;const c=[];if(Array.isArray(s.products))for(const g of s.products){const p=Ci(g);p&&c.push(p)}const l={name:s.name,products:c};typeof s.highlight=="string"&&(l.highlight=s.highlight),n.push(l)}const r={groups:n,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n},i=e.props?.columns;return typeof i=="number"&&Number.isFinite(i)&&i>0?r.columns=Math.floor(i):typeof t.gridColumns=="number"&&Number.isFinite(t.gridColumns)&&t.gridColumns>0&&(r.columns=Math.floor(t.gridColumns)),t.discountType!==void 0&&(r.discountType=t.discountType),t.renderCard!==void 0&&(r.renderCard=t.renderCard),t.renderCardElement!==void 0&&(r.renderCardElement=t.renderCardElement),t.onGroupingActivate!==void 0&&(r.onGroupingActivate=t.onGroupingActivate),Fm(r)},EmptyState:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-empty";const n=e.props?.message;return a.textContent=typeof n=="string"?n:t.i18n.emptyStateMessage,a},AddToCartButton:({element:e,context:t})=>{const a=e.props?.sku,n=e.props?.cartCode;if(typeof a!="string"||typeof n!="string")return null;const r=document.createElement("button");r.className="gengage-simrel-atc gengage-chat-product-card-cta",r.type="button";const i=e.props?.label;return r.textContent=typeof i=="string"?i:t.i18n.addToCartButton,r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t.onAddToCart({sku:a,quantity:1,cartCode:n})}),r},QuickActions:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-quick-actions";const n=e.props?.actions;if(!Array.isArray(n)||!t.onAction)return a;for(const r of n){if(!r||typeof r!="object")continue;const i=r,o=i.label,s=Um(i.action);if(typeof o!="string"||!s)continue;const c=document.createElement("button");c.className="gengage-simrel-quick-action",c.type="button",c.textContent=o,c.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),t.onAction?.(s)}),a.appendChild(c)}return a}},Ei=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function $m(){return{...Si}}function Hm(e,t,a=Si,n=Ei){return Xt({spec:e,context:t,registry:a,containerClassName:"gengage-simrel-uispec",unknownRenderer:n})}var Pi={similarProductsAriaLabel:"Benzer ürünler",emptyStateMessage:"Benzer ürün bulunamadı.",addToCartButton:"Sepete Ekle",ctaLabel:"İncele",outOfStockLabel:"Stokta Yok",decreaseLabel:"Azalt",increaseLabel:"Artır",errorLoadingMessage:"Benzer ürünler yüklenemedi.",retryButtonText:"Tekrar dene",priceSuffix:" TL",scrollTabsLeft:"Sola kaydır",scrollTabsRight:"Sağa kaydır"},qm={similarProductsAriaLabel:"Similar products",emptyStateMessage:"No similar products found.",addToCartButton:"Add to cart",ctaLabel:"View",outOfStockLabel:"Out of Stock",decreaseLabel:"Decrease",increaseLabel:"Increase",errorLoadingMessage:"Could not load similar products.",retryButtonText:"Try again",priceSuffix:"",scrollTabsLeft:"Scroll tabs left",scrollTabsRight:"Scroll tabs right"};function jm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Zm(e){return jm(e)==="en"?qm:Pi}var Vm=12e4;function Gm(e){return e instanceof DOMException&&e.name==="AbortError"}var Wm=class extends kt{constructor(...e){super(...e),this._abortController=null,this._contentEl=null,this._lastResultCount=-1,this._i18n=Pi}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-simrel-container",this._contentEl.dataset.gengagePart="simrel-container",this._contentEl.lang=Ue(e.locale);const t=this._clampGridColumns(e.gridColumns);t!==void 0&&this._contentEl.style.setProperty("--gengage-simrel-columns",String(t)),this.root.appendChild(this._contentEl),this._lastSku=e.sku,await this._fetchAndRender(e.sku),_t("simrel")}onUpdate(e){const t=e.sku;!t||t===this._lastSku&&this._lastResultCount!==0||(this._lastSku=t,this._fetchAndRender(t))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.3s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._contentEl&&(this._contentEl.remove(),this._contentEl=null)}_handleProductClick(e){const t={sku:e.sku,name:e.name,url:e.url};if(e.imageUrl!==void 0&&(t.imageUrl=e.imageUrl),e.price!==void 0&&(t.price=e.price),e.originalPrice!==void 0&&(t.originalPrice=e.originalPrice),e.discountPercent!==void 0&&(t.discountPercent=e.discountPercent),e.brand!==void 0&&(t.brand=e.brand),e.rating!==void 0&&(t.rating=e.rating),e.reviewCount!==void 0&&(t.reviewCount=e.reviewCount),e.cartCode!==void 0&&(t.cartCode=e.cartCode),e.inStock!==void 0&&(t.inStock=e.inStock),this.config.onProductClick?.(t)===!1)return;const a=this.config.session?.sessionId??null;pe("gengage:similar:product-click",{sku:e.sku,url:e.url,sessionId:a,productName:e.name}),this.config.onProductNavigate?.(e.url,e.sku,a)}_handleAddToCart(e){Xa(e.sku,e.quantity),this.config.onAddToCart?.(e),pe("gengage:similar:add-to-cart",e),this.track(Ga(this.analyticsContext(),{attribution_source:"simrel",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:e.quantity,sku:e.sku}))}_abort(){this._abortController?.abort(),this._abortController=null}_isSuperseded(e){return this._abortController?.signal!==e}_emitSimilarProductsImpression(e,t){const a=this.config.session?.sessionId??null;pe("gengage:similar:products-impression",{source_sku:this.config.sku,product_count:e,grouped:t,sessionId:a})}_resolveRequestTimeoutMs(){const e=this.config.requestTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?Vm:Math.floor(e)}async _fetchAndRender(e){this._abort();const t=new AbortController;this._abortController=t;const a=t.signal;let n=!1;const r=setTimeout(()=>{n=!0,t.abort()},this._resolveRequestTimeoutMs());if(a.addEventListener("abort",()=>clearTimeout(r),{once:!0}),!this._contentEl)return;this._contentEl.innerHTML="",this._contentEl.style.display="";const i=document.createElement("div");i.className="gengage-simrel-loading",i.dataset.gengagePart="simrel-loading";const o=document.createElement("div");o.className="gengage-simrel-spinner",o.dataset.gengagePart="simrel-loading-spinner",i.appendChild(o),this._contentEl.appendChild(i);const s={middlewareUrl:this.config.middlewareUrl},c=crypto.randomUUID(),l=Date.now(),g=li({source:"simrel",locale:this.config.locale});this.track(ta(this.analyticsContext(),{endpoint:"similar_products",request_id:c,widget:"simrel"}));try{const p={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e};this.config.domain!==void 0&&(p.domain=this.config.domain);const h=await Bm(p,s,a);if(this._lastResultCount=h.length,!this._contentEl)return;if(this._contentEl.innerHTML="",h.length>0)try{const d=h.map(f=>f.sku),b=new Map(h.map(f=>[f.sku,f])),u=(await Om({account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",skus:d},s,a)).map(f=>({...f,products:f.products.map(m=>({...b.get(m.sku),...m})).filter(m=>typeof m.sku=="string"&&typeof m.name=="string"&&typeof m.url=="string")})).filter(f=>f.products.length>0);if(u.length>0&&this._contentEl){const f=this._buildGroupsSpec(u),m=this._renderUISpec(f);this._contentEl.appendChild(m),xt("simrel"),this.track(yt(this.analyticsContext(),{request_id:c,latency_ms:Date.now()-l,chunk_count:u.reduce((y,k)=>y+k.products.length,0),widget:"simrel"})),this.track(na(this.analyticsContext(),{message_count:u.reduce((y,k)=>y+k.products.length,0),history_ref:c,redaction_level:"none",widget:"simrel"})),this._emitSimilarProductsImpression(u.reduce((y,k)=>y+k.products.length,0),!0);return}}catch{}if(this._isSuperseded(a))return;if(this._contentEl){const d=this._buildProductsSpec(h),b=this._renderUISpec(d);this._contentEl.appendChild(b)}h.length>0&&xt("simrel"),this.track(yt(this.analyticsContext(),{request_id:c,latency_ms:Date.now()-l,chunk_count:h.length,widget:"simrel"})),this.track(na(this.analyticsContext(),{message_count:h.length,history_ref:c,redaction_level:"none",widget:"simrel"})),this._emitSimilarProductsImpression(h.length,!1)}catch(p){const h=Gm(p);if(h&&this._isSuperseded(a))return;const d=h&&n?"REQUEST_TIMEOUT":"FETCH_ERROR",b=h&&n?"request_timeout":p instanceof Error?p.message:String(p);if(pe("gengage:global:error",{source:"simrel",code:d,message:sn(this.config.locale,p)}),this.track(aa(this.analyticsContext(),{request_id:c,error_code:d,error_message:b,widget:"simrel"})),this._contentEl){this._contentEl.innerHTML="";const u=document.createElement("div");u.className="gengage-simrel-error";const f=document.createElement("span");f.textContent=this._i18n.errorLoadingMessage,u.appendChild(f);const m=document.createElement("button");m.className="gengage-simrel-retry",m.textContent=this._i18n.retryButtonText,m.addEventListener("click",()=>{this._fetchAndRender(this.config.sku)}),u.appendChild(m),this._contentEl.appendChild(u)}}finally{clearTimeout(r),g()}}_clampGridColumns(e){if(!(e===void 0||typeof e!="number"||!Number.isFinite(e)))return Math.max(1,Math.min(12,Math.floor(e)))}_resolveI18n(e){return{...Zm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return ea($m(),this.config.renderer?.registry)}_buildRenderContext(){const e=this.config.renderCard,t={onClick:n=>this._handleProductClick(n),onAddToCart:n=>this._handleAddToCart(n),onGroupingActivate:n=>{pe("gengage:similar:grouping-click",{grouping_label:n.grouping_label,grouping_index:n.grouping_index,sessionId:this.config.session?.sessionId??null})},i18n:this._i18n};this.config.discountType!==void 0&&(t.discountType=this.config.discountType),e!==void 0&&(t.renderCard=e),this.config.renderCardElement!==void 0&&(t.renderCardElement=this.config.renderCardElement),this.config.pricing!==void 0&&(t.pricing=this.config.pricing);const a=this._clampGridColumns(this.config.gridColumns);return a!==void 0&&(t.gridColumns=a),t}_renderUISpec(e){const t=this._resolveUISpecRegistry(),a=this._buildRenderContext(),n=this.config.renderer?.unknownRenderer??Ei,r=(o,s)=>Hm(o,s,t,n),i=this.config.renderer?.renderUISpec;return i?i(e,a,{registry:t,unknownRenderer:n,defaultRender:r}):r(e,a)}_buildProductsSpec(e){const t={},a=[];for(let i=0;i<e.length;i++){const o=e[i],s=`product-${i}`;a.push(s),t[s]={type:"ProductCard",props:{product:o,index:i,discountType:this.config.discountType}}}const n={layout:"grid"},r=this._clampGridColumns(this.config.gridColumns);return r!==void 0&&(n.columns=r),t.root={type:"ProductGrid",props:n,children:a},{root:"root",elements:t}}_buildGroupsSpec(e){return{root:"root",elements:{root:{type:"GroupTabs",props:{groups:e}}}}}},Ti={findSimilarLabel:"Benzerlerini Bul"},Km={findSimilarLabel:"Find Similar"};function Ym(e,t){return t?.findSimilarLabel?t.findSimilarLabel:(e??"tr").toLowerCase().startsWith("en")?Km.findSimilarLabel:Ti.findSimilarLabel}function Yt(e){const t=typeof e.sku=="string"&&e.sku.length>0?e.sku:void 0,a=typeof e.pageContext?.sku=="string"&&e.pageContext.sku.length>0?e.pageContext.sku:void 0;return t??a}var Jm=class extends kt{constructor(...e){super(...e),this._button=null,this._label=Ti.findSimilarLabel}async onInit(e){this._label=Ym(e.locale,e.i18n),this.root.classList.add("gengage-simbut-root"),window.getComputedStyle(this.root).position==="static"&&(this.root.style.position="relative");const t=document.createElement("button");t.type="button",t.className="gengage-chat-find-similar-pill",t.lang=Ue(e.locale),t.textContent=this._label,this._button=t;const a=()=>{t.disabled=!(Yt(this.config)&&(this.config.onFindSimilar||this.config.chat))};t.addEventListener("click",n=>{n.stopPropagation();const r=Yt(this.config);if(!r)return;const i=this.config.imageUrl,o=typeof i=="string"&&fe(i)?i:void 0;if(ia(this._label,"findSimilar"),Ya(r),this.config.onFindSimilar){this.config.onFindSimilar(o?{sku:r,imageUrl:o}:{sku:r});return}const s=this.config.chat;if(!s)return;const c={title:this._label,type:"findSimilar",payload:o?{sku:r,image_url:o}:{sku:r}};s.openWithAction(c,{sku:r})}),this.root.appendChild(t),a(),_t("simbut")}onUpdate(e){if(!this._button)return;const t=!!Yt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}hide(){this.isVisible&&(this.isVisible=!1,this._button&&(this._button.style.display="none"),this.onHide(),this.emit("hide"))}show(){this.isVisible||(this.isVisible=!0,this._button&&(this._button.style.display=""),this.onShow(),this.emit("show"))}_cleanupRoot(){}onShow(){}onHide(){}onDestroy(){this._button?.remove(),this._button=null}setChat(e){if(this.config.chat=e,this._button){const t=!!Yt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}}},Jt=Oe({enabled:Ke().default(!0)}),Qm=Oe({chat:Pe().optional(),qna:Pe().optional(),simrel:Pe().optional(),simbut:Pe().optional()}),Xm=Oe({}),ef=Ha(["none","x-api-key-header","bearer-header","body-api-key"]),tf=Oe({mode:ef.default("none"),key:Pe().optional(),headerName:Pe().optional(),bodyField:Pe().default("api_key")}),af=Oe({enabled:Ke().default(!0),endpoint:Pe().default("/analytics"),auth:tf.default({mode:"none",bodyField:"api_key"}),fireAndForget:Ke().default(!0),useBeacon:Ke().default(!0),keepaliveFetch:Ke().default(!0),timeoutMs:Kr().int().positive().default(4e3),maxRetries:Kr().int().min(0).max(5).default(1)}),Ai="__gengageWidgetsInit",nf=Oe({idempotencyKey:Pe().default(Ai),requireDomReady:Ke().default(!0)}),rf=Ha(["log-and-ignore","throw","delegate"]),of=Oe({unknownActionPolicy:rf.default("log-and-ignore"),allowScriptCall:Ke().default(!1)}),Cf=Oe({version:Vu("1",{error:'version must be "1"'}),accountId:Pe({error:"accountId must be a non-empty string"}).min(1,{error:"accountId must be a non-empty string"}),middlewareUrl:Pe({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}).url({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}),locale:Pe().optional(),widgets:Oe({chat:Jt.default({enabled:!0}),qna:Jt.default({enabled:!0}),simrel:Jt.optional(),simbut:Jt.default({enabled:!1})}),mounts:Qm.default({}),transport:Xm.default({}),analytics:af.default({enabled:!0,endpoint:"/analytics",auth:{mode:"none",bodyField:"api_key"},fireAndForget:!0,useBeacon:!0,keepaliveFetch:!0,timeoutMs:4e3,maxRetries:1}),gtm:nf.default({idempotencyKey:"__gengageWidgetsInit",requireDomReady:!0}),actionHandling:of.default({unknownActionPolicy:"log-and-ignore",allowScriptCall:!1})}),sf=`${Ai}_overlay_`,cf="#gengage-qna",lf="#gengage-simrel",df="#gengage-simbut";function Li(){const e=window;return e.__gengageOverlayRegistry||(e.__gengageOverlayRegistry={instances:{},pending:{}}),e.__gengageOverlayRegistry}function gf(e){const t={pageType:e.pageContext?.pageType??(e.sku!==void 0?"pdp":"other")},a=e.pageContext;return a?.sku!==void 0&&(t.sku=a.sku),a?.skuList!==void 0&&(t.skuList=a.skuList),a?.price!==void 0&&(t.price=a.price),a?.categoryTree!==void 0&&(t.categoryTree=a.categoryTree),a?.url!==void 0&&(t.url=a.url),a?.extra!==void 0&&(t.extra=a.extra),e.sku!==void 0&&(t.sku=e.sku),t}function pf(e,t){const a={...e,...t,pageType:t.pageType??e.pageType};return t.pageType!==void 0&&t.pageType!==e.pageType?(t.pageType!=="pdp"&&t.sku===void 0&&delete a.sku,t.pageType!=="plp"&&t.skuList===void 0&&delete a.skuList):(t.sku===void 0&&e.sku!==void 0&&(a.sku=e.sku),t.skuList===void 0&&e.skuList!==void 0&&(a.skuList=e.skuList)),a}function Za(e){return e instanceof HTMLElement||document.querySelector(e)?e:null}function Ii(e){return e.idempotencyKey??`${sf}${e.accountId}`}var hf=class{constructor(e,t){this.options=e,this.onDestroy=t,this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,this._analyticsClient=null,this._offQnaWire=null,this._destroyed=!1,this._queue=Promise.resolve(),this._warnedQnaMountMissing=!1,this._warnedSimRelMountMissing=!1,this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this.idempotencyKey=Ii(e),this.session=tn(e.session),this._pageContext=gf(e)}get chat(){return this._chat}get qna(){return this._qna}get simrel(){return this._simrel}get simbut(){return this._simbut}get analyticsClient(){return this._analyticsClient}async init(){window.gengage||(window.gengage={}),window.gengage.sessionId=this.session.sessionId,window.gengage.pageContext=this._pageContext,await this._initChat(),this.options.wireQnaToChat!==!1&&(this._offQnaWire=bo()),await this._syncPdpWidgets(),window.gengage.overlay=this}openChat(e){this._chat?.open(e)}closeChat(){this._chat?.close()}async updateContext(e){this._destroyed||await this._enqueue(async()=>{this._pageContext=pf(this._pageContext,e),window.gengage||(window.gengage={}),window.gengage.pageContext=this._pageContext,this._chat?.update(this._pageContext),this._qna?.update(this._pageContext),this._simrel?.update(this._pageContext),this._simbut?.update(this._pageContext),await this._syncPdpWidgets()})}async updateSku(e,t="pdp"){await this.updateContext({sku:e,pageType:t})}async updatePageContext(e){await this.updateContext(e)}async setPageContext(e){await this.updateContext(e)}destroy(){this._destroyed||(this._destroyed=!0,this._offQnaWire?.(),this._offQnaWire=null,this._chat?.destroy(),this._qna?.destroy(),this._simrel?.destroy(),this._simbut?.destroy(),this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,window.gengage?.overlay===this&&delete window.gengage.overlay,this.onDestroy())}async _initChat(){if(this.options.chat?.enabled===!1)return;const e=this.options.middlewareUrl,t=this.options.chat?.productDetailsExtended??this.options.productDetailsExtended,a=this.options.chat?.isDemoWebsite??this.options.isDemoWebsite,n={accountId:this.options.accountId,middlewareUrl:e,session:this.session,pageContext:this._pageContext,variant:this.options.chat?.variant??"floating"};this.options.theme!==void 0&&(n.theme=this.options.theme),this.options.locale!==void 0&&(n.locale=this.options.locale),this.options.pricing!==void 0&&(n.pricing=this.options.pricing),this.options.chat?.mountTarget!==void 0&&(n.mountTarget=this.options.chat.mountTarget),this.options.chat?.pillLauncher!==void 0&&(n.pillLauncher=this.options.chat.pillLauncher),this.options.chat?.launcherImageUrl!==void 0?n.launcherImageUrl=this.options.chat.launcherImageUrl:this.options.chat?.launcherSvg!==void 0&&(n.launcherSvg=this.options.chat.launcherSvg),this.options.chat?.headerTitle!==void 0&&(n.headerTitle=this.options.chat.headerTitle),this.options.chat?.headerAvatarUrl!==void 0&&(n.headerAvatarUrl=this.options.chat.headerAvatarUrl),this.options.chat?.headerBadge!==void 0&&(n.headerBadge=this.options.chat.headerBadge),this.options.chat?.headerCartUrl!==void 0&&(n.headerCartUrl=this.options.chat.headerCartUrl),this.options.chat?.headerFavoritesToggle!==void 0&&(n.headerFavoritesToggle=this.options.chat.headerFavoritesToggle),this.options.chat?.onFavoritesClick!==void 0&&(n.onFavoritesClick=this.options.chat.onFavoritesClick),this.options.chat?.hideMobileLauncher!==void 0&&(n.hideMobileLauncher=this.options.chat.hideMobileLauncher),this.options.chat?.mobileBreakpoint!==void 0&&(n.mobileBreakpoint=this.options.chat.mobileBreakpoint),this.options.chat?.mobileInitialState!==void 0&&(n.mobileInitialState=this.options.chat.mobileInitialState),this.options.chat?.i18n!==void 0&&(n.i18n=this.options.chat.i18n),this.options.chat?.actionHandling!==void 0&&(n.actionHandling=this.options.chat.actionHandling),this.options.chat?.renderer!==void 0&&(n.renderer=this.options.chat.renderer),t!==void 0&&(n.productDetailsExtended=t),a!==void 0&&(n.isDemoWebsite=a),this.options.chat?.productPriceUi!==void 0&&(n.productPriceUi=this.options.chat.productPriceUi),this.options.chat?.hideProductDiscountBadge!==void 0&&(n.hideProductDiscountBadge=this.options.chat.hideProductDiscountBadge),this.options.chat?.hideUserReviews!==void 0&&(n.hideUserReviews=this.options.chat.hideUserReviews),this.options.chat?.hideStockStatus!==void 0&&(n.hideStockStatus=this.options.chat.hideStockStatus),this.options.onScriptCall!==void 0&&(n.onScriptCall=this.options.onScriptCall),this.options.onAddToCart!==void 0&&(n.onAddToCart=this.options.onAddToCart),this.options.chat?.onOpen!==void 0&&(n.onOpen=this.options.chat.onOpen),this.options.chat?.onClose!==void 0&&(n.onClose=this.options.chat.onClose),this._chat=new pm,await this._chat.init(n)}async _syncPdpWidgets(){if(this._destroyed)return;const e=this._pageContext.sku;if(!(this._pageContext.pageType==="pdp"&&e!==void 0&&e.length>0)){this._qna?.hide(),this._simrel?.hide(),this._simbut?.hide();return}const t=this.options.middlewareUrl;if(this.options.qna?.enabled!==!1){const a=this.options.qna?.mountTarget??cf,n=Za(a);if(n)if(this._warnedQnaMountMissing=!1,this._qna)this._qna.show(),this._qna.update({pageType:"pdp",sku:e});else{const r=new zm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.qna?.ctaText!==void 0&&(i.ctaText=this.options.qna.ctaText),this.options.qna?.hideButtonRowCta!==void 0&&(i.hideButtonRowCta=this.options.qna.hideButtonRowCta),this.options.qna?.inputPlaceholder!==void 0&&(i.inputPlaceholder=this.options.qna.inputPlaceholder),this.options.qna?.i18n!==void 0&&(i.i18n=this.options.qna.i18n),this.options.qna?.renderer!==void 0&&(i.renderer=this.options.qna.renderer);const o=this.options.qna?.headerTitle??this.options.qna?.headingTitle;o!==void 0&&(i.headerTitle=o),await r.init(i),this._qna=r}else this._qna?.destroy(),this._qna=null,this._warnedQnaMountMissing||(console.warn(`[gengage] QNA mount target not found: ${a}`),this._warnedQnaMountMissing=!0)}else this._qna?.destroy(),this._qna=null;if(this.options.simrel!==void 0&&this.options.simrel.enabled!==!1){const a=this.options.simrel?.mountTarget??lf,n=Za(a);if(n)if(this._warnedSimRelMountMissing=!1,this._simrel)this._simrel.show(),this._simrel.update({pageType:"pdp",sku:e});else{const r=new Wm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,sku:e,mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.pricing!==void 0&&(i.pricing=this.options.pricing),this.options.simrel?.discountType!==void 0&&(i.discountType=this.options.simrel.discountType),this.options.simrel?.renderCardElement!==void 0&&(i.renderCardElement=this.options.simrel.renderCardElement),this.options.simrel?.renderer!==void 0&&(i.renderer=this.options.simrel.renderer),this.options.onAddToCart!==void 0&&(i.onAddToCart=this.options.onAddToCart),this.options.onProductNavigate!==void 0?i.onProductNavigate=this.options.onProductNavigate:i.onProductNavigate=(o,s,c)=>{fe(o)&&(this._chat?.saveSession(c??this.session.sessionId,s),window.location.href=o)},await r.init(i),this._simrel=r}else this._simrel?.destroy(),this._simrel=null,this._warnedSimRelMountMissing||(console.warn(`[gengage] SimRel mount target not found: ${a}`),this._warnedSimRelMountMissing=!0)}else this._simrel?.destroy(),this._simrel=null;if(this.options.simbut&&this.options.simbut.enabled!==!1){const a=this.options.simbut.mountTarget??df,n=Za(a),r=this._chat??this.options.simbut.onFindSimilar;if(n&&r)if(this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this._simbut)this._simbut.show(),this._simbut.setChat(this._chat),this._simbut.update({pageType:"pdp",sku:e});else{const i=new Jm,o={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n,chat:this._chat};this.options.theme!==void 0&&(o.theme=this.options.theme),this.options.locale!==void 0&&(o.locale=this.options.locale),this.options.simbut.imageUrl!==void 0&&(o.imageUrl=this.options.simbut.imageUrl),this.options.simbut.i18n!==void 0&&(o.i18n=this.options.simbut.i18n),this.options.simbut.onFindSimilar!==void 0&&(o.onFindSimilar=this.options.simbut.onFindSimilar),await i.init(o),this._simbut=i}else this._simbut?.destroy(),this._simbut=null,!n&&!this._warnedSimButMountMissing?(console.warn(`[gengage] SimBut mount target not found: ${a}`),this._warnedSimButMountMissing=!0):!r&&!this._warnedSimButNoChat&&(console.warn("[gengage] SimBut requires chat to be enabled or simbut.onFindSimilar"),this._warnedSimButNoChat=!0)}else this._simbut?.destroy(),this._simbut=null}_enqueue(e){const t=this._queue.then(e);return this._queue=t.catch(a=>{}),t}};async function uf(e){const t=Ii(e),a=Li(),n=a.instances[t];if(n)return n;const r=a.pending[t];if(r)return r;const i=new hf(e,()=>{const s=Li();delete s.instances[t],delete s.pending[t]}),o=i.init().then(()=>(a.instances[t]=i,delete a.pending[t],i)).catch(s=>{throw delete a.pending[t],Qa({reason:"overlay_init_failed",message:s instanceof Error?s.message:String(s)}),s});return a.pending[t]=o,o}var Ni=["gengage:chat:open","gengage:chat:close","gengage:chat:ready","gengage:chat:add-to-cart","gengage:qna:action","gengage:qna:open-chat","gengage:similar:product-click","gengage:similar:grouping-click","gengage:similar:products-impression","gengage:similar:add-to-cart","gengage:global:error","gengage:context:update"],mf=32,zi="#gengage-qna",Mi="#gengage-simrel";function Sf(e){return e}function ff(e){let t=e;if(typeof e=="string"){const i=e.trim();if(i.length===0)return null;if(!i.startsWith("{")&&!i.startsWith("["))return{type:i};try{t=JSON.parse(i)}catch{return null}}if(!t||typeof t!="object")return null;const a=t,n=[a.type,a.command,a.action,a.event].find(i=>typeof i=="string"&&i.length>0);if(!n)return null;let r=a.payload;if(r===void 0&&"data"in a&&(r=a.data),n==="setSession"&&r===void 0){const i={};typeof a.sessionId=="string"&&(i.sessionId=a.sessionId),typeof a.userId=="string"&&(i.userId=a.userId),(i.sessionId!==void 0||i.userId!==void 0)&&(r=i)}return r===void 0?{type:n}:{type:n,payload:r}}function bf(e){if(typeof e=="string"&&e.length>0)return{sku:e};if(e&&typeof e=="object"&&"sku"in e){const t=e.sku;if(typeof t=="string"&&t.length>0){const a=e.pageType;return a!==void 0?{sku:t,pageType:a}:{sku:t}}}return null}function Va(e,t){return t instanceof HTMLElement?!0:typeof t!="string"?!1:e.document.querySelector(t)!==null}function Bi(e,t,a){if(t instanceof HTMLElement||Va(e,t)||typeof t!="string")return t;if(t.startsWith("#")){const i=t.slice(1);if(i.length>0){const o=e.document.getElementById(i);if(o)return o;const s=e.document.createElement("div");return s.id=i,e.document.body.appendChild(s),s}}const n=e.document.getElementById(a);if(n)return n;const r=e.document.createElement("div");return r.id=a,e.document.body.appendChild(r),r}function Ri(e,t){const a=e.webkit?.messageHandlers?.[t];return a&&typeof a.postMessage=="function"?a.postMessage.bind(a):null}function Qt(e,t){const a=e[t];return a&&typeof a=="object"&&typeof a.postMessage=="function"?a:null}function Oi(e={}){const t=e.win??window,a=e.iosHandlerName??"gengage",n=e.androidInterfaceName??"GengageNative",r=e.reactNativeInterfaceName??"ReactNativeWebView";return Ri(t,a)?"ios":Qt(t,n)?"android":Qt(t,r)?"react-native":"browser"}function Di(e,t={}){const a=t.win??window;if(e.sessionId!==void 0){a.__gengageSessionId=e.sessionId,a.gengage||(a.gengage={}),a.gengage.sessionId=e.sessionId;try{a.sessionStorage.setItem("gengage_session_id",e.sessionId)}catch{}}if(e.userId!==void 0){a.gengage||(a.gengage={});const n=a.gengage,r=n.session??{};r.userId=e.userId,n.session=r}}function Fi(e={}){const t=e.win??window,a=t;if(a.gengageNative)return a.gengageNative;const n=e.iosHandlerName??"gengage",r=e.androidInterfaceName??"GengageNative",i=e.reactNativeInterfaceName??"ReactNativeWebView",o=e.trackedEvents??[...Ni],s=Oi({win:t,iosHandlerName:n,androidInterfaceName:r,reactNativeInterfaceName:i});let c=t.gengage?.overlay??null;const l=[],g=(m,y)=>{const k=y===void 0?{type:m}:{type:m,payload:y};if(s==="ios"){Ri(t,n)?.(k);return}if(s==="android"){Qt(t,r)?.postMessage(JSON.stringify(k));return}if(s==="react-native"){Qt(t,i)?.postMessage(JSON.stringify(k));return}},p=m=>{const y=m.detail;!y||typeof y.namespace!="string"||typeof y.type!="string"||g("bridge_message",{namespace:y.namespace,type:y.type,payload:y.payload})};t.addEventListener("gengage:bridge:message",p);const h=o.map(m=>{const y=k=>{const _=k.detail;g("widget_event",{event:m,detail:_})};return t.addEventListener(m,y),{event:m,handler:y}}),d=m=>{l.length>=mf&&l.shift(),l.push(m)},b=()=>{if(!c||l.length===0)return;const m=l.splice(0,l.length);for(const y of m)u(y)},u=m=>{const y=ff(m);if(!y||typeof y.type!="string"){console.warn("[gengage:native-bridge] Invalid message:",m);return}const k=y.type,_=y.payload;switch(k){case"openChat":c?c.openChat(_&&typeof _=="object"?_:_==="half"||_==="full"?{state:_}:void 0):d(y);return;case"closeChat":c?c.closeChat():d(y);return;case"updateContext":case"updatePageContext":case"setPageContext":c&&_&&typeof _=="object"?c.updateContext(_):c?console.warn(`[gengage:native-bridge] ${k}: missing payload`):d(y);return;case"updateSku":{const x=bf(_);if(c&&x){c.updateSku(x.sku,x.pageType);return}c?console.warn("[gengage:native-bridge] updateSku: missing sku"):d(y);return}case"setSession":_&&typeof _=="object"&&Di(_,{win:t});return;case"destroy":c?.destroy();return;default:t.postMessage({gengage:"native",type:k,payload:_},t.location.origin),e.logUnhandled&&console.warn("[gengage:native-bridge] Unhandled inbound type forwarded:",k)}},f={env:s,sendToNative:g,receive:u,setController(m){c=m,b()},destroy(){t.removeEventListener("gengage:bridge:message",p);for(const m of h)t.removeEventListener(m.event,m.handler);l.splice(0,l.length),t.gengageNative===f&&delete t.gengageNative}};return a.gengageNative=f,f}async function vf(e){const{nativeBridge:t,emitReadyEvent:a=!0,...n}=e,r=Fi(t),i={...n};i.onAddToCart||(i.onAddToCart=l=>{r.sendToNative("addToCart",{sku:l.sku,quantity:l.quantity,cartCode:l.cartCode})}),i.onProductNavigate||(i.onProductNavigate=(l,g,p)=>{r.sendToNative("productNavigate",{url:l,sku:g,sessionId:p})});const o=i.qna?.enabled===!0||i.qna?.mountTarget!==void 0;if(i.qna?.enabled!==!1)if(o){const l=Bi(window,i.qna?.mountTarget??zi,"gengage-qna");i.qna={...i.qna,enabled:!0,mountTarget:l}}else Va(window,zi)||(i.qna={enabled:!1});const s=i.simrel?.enabled===!0||i.simrel?.mountTarget!==void 0;if(i.simrel?.enabled!==!1)if(s){const l=Bi(window,i.simrel?.mountTarget??Mi,"gengage-simrel");i.simrel={...i.simrel,enabled:!0,mountTarget:l}}else Va(window,Mi)||(i.simrel={enabled:!1});const c=await uf(i);return r.setController(c),a&&r.sendToNative("ready",{sessionId:c.session.sessionId,widgets:{chat:c.chat!==null,qna:c.qna!==null,simrel:c.simrel!==null}}),{controller:c,bridge:r,destroy(){c.destroy(),r.destroy()}}}Je.DEFAULT_NATIVE_TRACKED_EVENTS=Ni,Je.applyNativeSession=Di,Je.createNativeWebViewBridge=Fi,Je.detectNativeEnvironment=Oi,Je.initNativeOverlayWidgets=vf})(this.Gengage=this.Gengage||{});