@gengage/assistant-fe 0.3.23 → 0.3.25
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.
- package/dist/chat/catalog.d.ts +2 -4
- package/dist/chat/components/ChatDrawer.d.ts +1 -2
- package/dist/chat/components/PhotoAnalysisCard.d.ts +1 -2
- package/dist/chat/types.d.ts +1 -2
- package/dist/{chat-DBJ8ZWch.js → chat-B1bVP6dh.js} +295 -297
- package/dist/chat.iife.js +4 -4
- package/dist/chat.js +1 -1
- package/dist/{common-BJZB1LIH.js → common-B-CaKFN9.js} +1 -1
- package/dist/common.js +3 -3
- package/dist/index.js +3 -3
- package/dist/{native-webview-111Or6o1.js → native-webview-Dx5logj9.js} +1 -1
- package/dist/native.iife.js +2 -2
- package/dist/native.js +1 -1
- package/package.json +8 -16
- package/dist/chat-BOkLnT1i.cjs +0 -93
- package/dist/chat.cjs +0 -1
- package/dist/common-0GWnpStO.cjs +0 -1
- package/dist/common.cjs +0 -1
- package/dist/connection-warning-YQiIRXrz.cjs +0 -1
- package/dist/ga-datalayer-BVppFxqk.cjs +0 -47
- package/dist/index.cjs +0 -1
- package/dist/native-webview-BePZBK3U.cjs +0 -1
- package/dist/native.cjs +0 -1
- package/dist/product-utils-DLXQQJbh.cjs +0 -1
- package/dist/qna-DwG8AJJf.cjs +0 -1
- package/dist/qna.cjs +0 -1
- package/dist/schemas-B7jnyzQI.cjs +0 -40
- package/dist/simbut-D_ycY_MQ.cjs +0 -1
- package/dist/simbut.cjs +0 -1
- package/dist/simrel-DdP4lur9.cjs +0 -1
- package/dist/simrel.cjs +0 -1
package/dist/chat.iife.js
CHANGED
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
`,document.head.appendChild(e)}var dt=null;function hi(){if(dt!==null)return dt;try{dt=localStorage.getItem("gengage:debug")==="1"}catch{dt=!1}return dt}function Me(e,t,a){if(!hi())return;const n=[`[gengage:${e}]`,t];a!==void 0&&n.push(a),console.debug(...n)}var ui=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=Qr(e.theme);this.config={...e,theme:t,session:Xr(e.session)},this.root=this._resolveMount(e.mountTarget),this._applyTheme(t),ii();const a=xa("gengage:context:update",n=>this.update(n));this._cleanups.push(a),Me("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,Me("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"?jr:Zr;this.track(a(this.analyticsContext(),t))}flushMeteringSummary(e){this.track(Fr(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-${mi(t)}`;this.root.style.setProperty(n,a)}}}};function mi(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function Ea(){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 fi=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("*")&&vi()&&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(!bi(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 bi(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.gengage=="string"&&typeof t.type=="string"}function vi(){try{return typeof process<"u"&&process.env.NODE_ENV!=="production"}catch{return!1}}var yi=console;function _i(e,t,a={}){const n=e.action,r=a.logger??yi;switch(Me("action",`routing action: ${n.kind}`,n),n.kind){case"open_chat":t.openChat?.(n.payload);return;case"navigate":{if(typeof n.url!="string"){Xe(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}xi(n.url,i);return}case"save_session":if(typeof n.sessionId!="string"||typeof n.sku!="string"){Xe(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"){Xe(n,t,a,r);return}t.addToCart?.({sku:n.sku,quantity:n.quantity,cartCode:n.cartCode});return;case"script_call":{if(a.allowScriptCall===!1){Xe(n,t,a,r);return}if(typeof n.name!="string"){Xe(n,t,a,r);return}const i=wi(n.payload)?n.payload:void 0;t.scriptCall?.({name:n.name,...i!==void 0&&{payload:i}});return}default:Xe(n,t,a,r)}}function Xe(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 xi(e,t){if(!(typeof window>"u")){if(!fe(e)){console.warn("[gengage] Blocked navigation to unsafe URL:",e);return}if(t){window.open(e,"_blank","noopener,noreferrer");return}window.location.href=e}}function wi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var ki=["image/jpeg","image/png","image/webp"],ku=5*1024*1024;function Ci(e){return ki.includes(e.type)?e.size>5242880?{ok:!1,reason:"too_large"}:{ok:!0}:{ok:!1,reason:"invalid_type"}}function Pa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function Si(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 Aa(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 Pa(r)?(Me("stream",`event: ${r.type}`,r),t.onEvent(r),r.type==="done"?(t.onDone?.(),!0):!1):!1}catch{const r=Si(n);if(r.length>1){for(const i of r)try{const o=JSON.parse(i);if(!Pa(o))continue;if(t.onEvent(o),o.type==="done")return t.onDone?.(),!0}catch{}return!1}return!1}}async function Ei(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(m=>(clearTimeout(l),m)),new Promise(m=>{l=setTimeout(()=>m(o),i)})]):c);if(g===o){s=!0,await a.cancel();break}const{done:d,value:p}=g;if(d)break;r+=n.decode(p,{stream:!0});const h=r.split(`
|
|
48
|
-
`);r=h.pop()??"";for(const m of h)if(Aa(m,t))return}if(r.trim()&&Aa(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 Ta=3,Pi=(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():""},Zt=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>Pi(a,t)).filter(Boolean):[];function Ai(e){const t=(e.display_keywords??[]).flatMap(r=>Zt(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,Ta);const n=[...Zt(e.chosen_attribute,{stripLeadingStopWords:!0}),...Zt(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,Ta)}function Ti(e){return Ai(e).join(" • ")}var Li=["beauty_consulting","watch_expert"];function La(e){return typeof e=="string"&&Li.includes(e)}function Ii(e){if(typeof e.type!="string")return null;if(Ni(e))return e;const t=e;switch(t.type){case"outputText":return zi(t);case"suggestedActions":return Mi(t);case"productList":return Bi(t);case"productDetails":return Ri(t);case"productDetailsSimilars":return Di(t);case"comparisonTable":return Oi(t);case"context":return Ui(t);case"chatStreamEnd":return ji();case"loading":return Zi(t);case"panelLoading":return qi(t);case"similarLoading":return Vi(t);case"redirect":return Gi(t);case"error":return Wi(t);case"dummy":return Ki(t);case"launcherAction":return Yi(t);case"text":return qt(t);case"productItem":return Ji(t);case"text_image":return Ia(t);case"quick_qna":return Na(t);case"reviewHighlights":return Xi(t);case"aiProductSuggestions":return to(t);case"aiProductGroupings":return ao(t);case"aiSuggestedSearches":return no(t);case"prosAndCons":return Qi(t);case"getGroundingReview":return ro(t);case"voice":return oo(t);case"visitorDataResponse":return eo(t);case"productListPreview":return io();case"groupList":return so(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return co(t);case"launcherContent":return go(t);case"handoff":return lo(t);case"uiSpec":return yo(t);default:return null}}function Ni(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=ke(e.spec);return n?typeof n.root=="string"&&ke(n.elements)!==null:!1}case"action":{const a=ke(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 zi(e){const t=V(e.payload.text,e.payload.plain_text)??"",a=V(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 Mi(e){return za((e.payload.actions??[]).map(t=>{const a=V(t.title)??"",n=Be(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(Vt),"chat")}function Bi(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=V(o.style_label),c=V(o.style_mood),l=V(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(p=>{const h=ke(p);return h?Ba(ke(h.product_detail)??ke(h.product)??h):null}).filter(Vt),d=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(p=>({label:V(p.label)??"",reason:V(p.reason)??"",skus:Array.isArray(p.skus)?p.skus.filter(h=>typeof h=="string"&&h.trim().length>0):[]})):[];return{style_label:s??"",style_mood:c??"",...l?{image_url:l}:{},product_list:g,recommendation_groups:d}}).filter(o=>o.product_list.length>0),a=e.payload.product_list??[],n=La(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?po(n,"chat"):Ma(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),Object.keys(o).length>0&&(i.props={...i.props,...o})}return r}function Ri(e){const t=e.payload.productDetails;if(!t)return uo("chat");const a=Qe(t);return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:{...t,...a}}}}},panelHint:"panel"}}function Di(e){const t=Ma(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function Oi(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 y=Qe(f);o.push(y)}const s=$i(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 d=bo(n?.special_considerations),p=n?.recommended_choice,h=n?.winner_hits,m={};for(const f of o){const y=f.sku;y&&(m[y]={title:f.name??y,type:"launchSingleProduct",payload:{sku:y}})}const u={products:o,attributes:s,highlights:g,productActions:m};return l&&(u.recommended=l),d.length>0&&(u.specialCases=d),p&&(u.recommendedText=p),h&&(u.winnerHits=h),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 $i(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 d=a.criteria_view??a.criteria_view_short??{},p=a.compared_field_names??Object.keys(e),h=[];for(const m of p){const u=e[m];if(!u||!Array.isArray(u))continue;const f=d[m]??m;h.push({label:f,values:u.map(y=>typeof y=="string"?y:String(y??""))})}return h}const o=e,s=t.map(d=>String(d.sku??"")).filter(d=>d.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:Fi(o)).filter(d=>d!=="name"&&d!=="name_short"&&!d.endsWith("_short")),g=[];for(const d of l){const p=s.map(m=>{const u=o[m];if(!u||typeof u!="object")return"";const f=u[`${d}_short`],y=u[d];return Hi(f??y)});if(p.every(m=>m.length===0))continue;const h=c[d]??d;g.push({label:h,values:p})}return g}function Fi(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 Hi(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Ui(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function ji(){return{type:"done"}}function Zi(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 qi(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Vi(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Gi(e){const t=V(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:V(e.payload.to)}}}function Wi(e){return{type:"error",code:"BACKEND_ERROR",message:V(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function Ki(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function Yi(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),Na({type:"quick_qna",payload:r})}const a=ke(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),Ia({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=ke(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),qt({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function qt(e){const t={text:V(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 Ji(e){return ho(e.payload,"qna")}function Ia(e){const t=V(e.payload.text)??"",a=Be(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),qt({type:"text",payload:n})}function Na(e){return za((e.payload.action_list??[]).map(t=>{const a=V(t.title)??"",n=Be(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(Vt),"qna")}function Xi(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 Qi(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 eo(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function to(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=mo(r);if(!i)continue;const o={product:i},s=Be(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 ao(e){const t=e.payload.product_groupings??[],a=[];for(let n=0;n<t.length;n++){const r=t[n];if(!r)continue;const i=V(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Be(r.requestDetails??o,i);if(!s)continue;const c={name:i,action:s};if(Array.isArray(r.labels)){const l=r.labels.filter(g=>typeof g=="string");l.length>0&&(c.labels=l)}typeof r.image=="string"&&(c.image=r.image),a.push(c)}return a.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:a}}}}}}function no(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=V(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=V(r.detailed_user_message);s&&(o.text=s);const c=ke(ke(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(y=>typeof y=="string"));const g=V(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const d={type:"inputText",payload:o},p=Be(r.requestDetails,i),h=p?.type==="findSimilar"&&typeof o.text=="string"?Be(d,i):p??Be(d,i);if(!h)continue;const m={shortName:i,action:h},u=V(r.detailed_user_message);u&&u!==i&&(m.detailedMessage=u);const f=Ti(r);f&&f!==i&&f!==(u??"")&&(m.whyDifferent=f),typeof r.image=="string"&&(m.image=r.image),a.push(m)}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 ro(e){const t=e.payload,a=Be(t.requestDetails??t.request_details,V(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 io(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function oo(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function so(e){const t=e.payload.group_list??[],a=[];for(const r of t){const i=r.group_name??"",o=(r.product_list??[]).map(Qe);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=Be(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 co(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function lo(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 go(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function za(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 Ma(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=Qe(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 po(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 ho(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Qe(e),index:0}}}}}}function uo(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function mo(e){const t=V(e.sku),a=V(e.short_name),n={...ke(e.product_item)??e},r=V(e.discount_reason,e.discountReason);return r&&!V(n.discount_reason,n.discountReason)&&(n.discount_reason=r),Ba(n,t,a)}function Ba(e,t,a){const n=V(e.sku,t),r=V(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=V(e.brand);o&&(i.brand=o);const s=V(e.url);s&&(i.url=s);const c=fo(e.images);if(c.length>0)i.images=c;else{const u=V(e.image,e.image_url,e.imageUrl);u&&(i.images=[u])}const l=gt(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=gt(e.price);g!==void 0&&(i.price=g);const d=gt(e.rating);d!==void 0&&(i.rating=d);const p=gt(e.review_count)??gt(e.reviewCount);p!==void 0&&(i.review_count=p);const h=V(e.cart_code,e.cartCode);h&&(i.cart_code=h),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const m=V(e.discount_reason,e.discountReason);return m&&(i.discount_reason=m),Qe(i)}function Be(e,t){const a=ke(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 ke(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function V(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function fo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function bo(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 gt(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 Vt(e){return e!=null}var vo=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 Qe(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=V(e.brand),o=V(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:V(e.url)??""},l=e.images?.[0];l&&(c.imageUrl=l),e.images&&e.images.length>1&&(c.images=e.images),a!=null&&(c.price=String(a)),n!=null&&(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,d={};let p=!1;for(const h of Object.keys(g))vo.has(h)||(d[h]=g[h],p=!0);return p&&(c.extras=d),c}function yo(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 _o={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function xo(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 wo(e,t){return`${xo(t?.middlewareUrl)}/chat${_o[e]}`}function ko(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":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 Co={user_message:"inputText"};function So(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=Co[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function Eo(e,t,a){const n=wo("process_action",a),r=new AbortController;return(async()=>{try{const o=So(e),s=a.attachment!==void 0;let c;if(s){const p=new FormData;p.append("request",o),a.attachment!==void 0&&p.append("attachment",a.attachment),c={method:"POST",body:p,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 p=l.statusText;try{const h=await l.json(),m=h.detail??h.message??h.error;typeof m=="string"&&(p=m)}catch{}t.onError(new Error(`HTTP ${l.status}: ${p}`));return}let g=!1;const d=()=>{g||(g=!0,t.onDone())};await Ei(l,{onEvent:p=>{const h=Ii(p);if(h)switch(h.type){case"text_chunk":t.onTextChunk(h.content,h.final===!0,{productMentions:h.productMentions,skuToProductItem:h.skuToProductItem,conversationMode:h.conversationMode,renderHint:h.renderHint,kvkk:h.kvkk});break;case"ui_spec":t.onUISpec(h.spec,h.widget,h.panelHint,h.clearPanel===!0);break;case"action":t.onAction(h);break;case"metadata":t.onMetadata(h);break;case"error":t.onError(new Error(h.message));break;case"done":d();break}},onError:t.onError,signal:r.signal}),d()}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;t.onError(o instanceof Error?o:new Error(String(o)))}})(),r}var Po=["chat_debug","presentation_debug"],Ao=["gengage_chat_debug","gengage_presentation_debug"];function To(){if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search);if(Po.some(t=>e.get(t)==="1"))return!0;try{return Ao.some(t=>window.localStorage.getItem(t)==="1")}catch{return!1}}function Lo(e,t,a){if(!To())return;const n=(window.__gengageChatPresentationDebugSeq??0)+1;window.__gengageChatPresentationDebugSeq=n;const r={seq:n,time:new Date().toISOString(),scope:e,message:t,payload:a};window.__gengageChatPresentationDebugLog||(window.__gengageChatPresentationDebugLog=[]),window.__gengageChatPresentationDebugLog.push(r),window.__gengageChatPresentationDebugLog.length>400&&window.__gengageChatPresentationDebugLog.shift();const i=`[gengage-chat-debug #${n}][${e}] ${t}`;a===void 0?console.debug(i):console.debug(i,a)}var vt="gengage-chat-scroll",et=null;function Ra(e){et=e}function Io(){if(et&&et.isConnected)return et;et=null;const e=document.getElementById(vt);return e||(Lo("chat-scroll","failed to resolve scroll container (not registered)",{id:vt}),null)}function Da(){et=null}var Gt={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:"Düşünüyorum...",loadingSequenceGeneric:["Sizin için en önemli noktaları anlıyorum","Ürünleri, yorumları ve özellikleri inceliyorum","En güçlü seçenekleri hazırlıyorum"],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:"En Beğendiğim",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",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",photoAnalysisSeeMoreLabel:"Detaylı analizi gör",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"},No={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:"Thinking...",loadingSequenceGeneric:["Understanding what matters most","Reviewing products, reviews, and specs","Preparing the best options to review"],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",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",photoAnalysisSeeMoreLabel:"See detailed analysis",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 zo(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Mo(e){return zo(e)==="en"?No:Gt}function Bo(){return Oa()!==null}function Oa(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var Ro=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=Oa();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=Do(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 Do(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 Oo(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=Ae(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 $o=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??""}},Fo=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,Pe(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 Ho(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 $a(e,t,a){const n=e.props??{},r=n.processing===!0,i=document.createElement("div");i.className="gengage-chat-beauty-photo-step-card";const o=document.createElement("span");o.className="gengage-chat-beauty-photo-step-icon",o.setAttribute("aria-hidden","true"),o.textContent="✦";const s=document.createElement("div");s.className="gengage-chat-beauty-photo-step-content";const c=document.createElement("div");c.className="gengage-chat-beauty-photo-step-title",c.textContent=(typeof n.title=="string"?n.title:void 0)??t.i18n?.beautyPhotoStepTitle??"Upload a Photo";const l=document.createElement("p");l.className="gengage-chat-beauty-photo-step-desc",l.textContent=(typeof n.description=="string"?n.description:void 0)??t.i18n?.beautyPhotoStepDescription??"Share a selfie so we can analyze your skin and recommend the right products.";const g=document.createElement("div");g.className="gengage-chat-beauty-photo-step-actions";const d=document.createElement("button");d.type="button",d.className="gengage-chat-beauty-photo-step-upload gds-btn gds-btn-primary",d.textContent=r?t.i18n?.beautyPhotoStepProcessing??"Analyzing...":(typeof n.upload_label=="string"?n.upload_label:void 0)??t.i18n?.beautyPhotoStepUpload??"Upload Photo",d.disabled=r,a?.onUpload&&d.addEventListener("click",()=>a.onUpload());const p=document.createElement("button");return p.type="button",p.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",p.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??t.i18n?.beautyPhotoStepSkip??"Skip",a?.onSkip&&p.addEventListener("click",()=>a.onSkip()),g.appendChild(d),g.appendChild(p),s.appendChild(c),s.appendChild(l),s.appendChild(g),i.appendChild(o),i.appendChild(s),i}function Uo(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 jo(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=Uo(e,t);i.hidden=!1,i.innerHTML="";const o=$a({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 Fa(e){const t=typeof e.summary=="string"?e.summary:"",a=Array.isArray(e.clues)?e.clues.filter(g=>typeof g=="string"):[],n=Array.isArray(e.strengths)?e.strengths.filter(g=>typeof g=="string"):[],r=Array.isArray(e.focus_points)?e.focus_points.filter(g=>typeof g=="string"):[],i=Array.isArray(e.details)?e.details.filter(g=>typeof g=="string"):[];if(!t&&a.length===0&&n.length===0&&r.length===0&&i.length===0)return null;const o={summary:t,clues:a},s=typeof e.celeb_style=="string"?e.celeb_style:void 0,c=typeof e.celeb_style_reason=="string"?e.celeb_style_reason:void 0,l=typeof e.next_question=="string"?e.next_question:void 0;return n.length>0&&(o.strengths=n),r.length>0&&(o.focusPoints=r),i.length>0&&(o.details=i),s&&(o.celebStyle=s),c&&(o.celebStyleReason=c),l&&(o.nextQuestion=l),o}function Wt(e){const t=e.details&&e.details.length>0?e.details:e.clues;return e.strengths&&e.strengths.length>0||e.focusPoints&&e.focusPoints.length>0?{...e,details:t}:t.length<3?{...e,details:t}:{...e,strengths:t.slice(0,2),focusPoints:t.slice(2,4),details:t}}function Ha(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 Kt(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 l=document.createElement("p");l.className="gengage-chat-photo-analysis-summary",l.textContent=t.summary,r.appendChild(l)}const i=document.createElement("div");i.className="gengage-chat-photo-analysis-highlights";const o=Ha(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=Ha(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 l=document.createElement("section");l.className="gengage-chat-photo-analysis-section gengage-chat-photo-analysis-section--celeb";const g=document.createElement("h4");g.className="gengage-chat-photo-analysis-section-title",g.textContent=e.celebStyle;const d=document.createElement("p");if(d.className="gengage-chat-photo-analysis-celeb-name",d.textContent=t.celebStyle,l.appendChild(g),l.appendChild(d),t.celebStyleReason){const p=document.createElement("p");p.className="gengage-chat-photo-analysis-celeb-reason",p.textContent=t.celebStyleReason,l.appendChild(p)}r.appendChild(l)}const c=(t.details&&t.details.length>0?t.details:t.clues).filter(Boolean);if(c.length>0){const l=document.createElement("details");l.className="gengage-chat-photo-analysis-details";const g=document.createElement("summary");g.className="gengage-chat-photo-analysis-details-summary",g.textContent=e.seeMore;const d=document.createElement("ul");d.className="gengage-chat-photo-analysis-points";for(const p of c){const h=document.createElement("li");h.textContent=p,d.appendChild(h)}l.appendChild(g),l.appendChild(d),r.appendChild(l)}if(t.nextQuestion){const l=document.createElement("p");l.className="gengage-chat-photo-analysis-next",l.textContent=t.nextQuestion,r.appendChild(l)}return a.appendChild(n),a.appendChild(r),a}function Zo(e){return{badge:e?.i18n?.photoAnalysisBadge??"Skin Analysis",strengths:e?.i18n?.photoAnalysisStrengthsLabel??"Your strengths",focus:e?.i18n?.photoAnalysisFocusLabel??"Focus points",celebStyle:e?.i18n?.photoAnalysisCelebStyleLabel??"Celeb style match",seeMore:e?.i18n?.photoAnalysisSeeMoreLabel??"See detailed analysis"}}function qo(e,t){const a=Wt(Fa(e.props??{})??{summary:"",clues:[]});return Kt(Zo(t),a)}function Vo(e,t,a,n){if(e.innerHTML="",n){e.appendChild(Kt(a,Wt(n)));return}const r=t.split(/(?<=[.!?])\s+/).map(l=>l.trim()).filter(Boolean),i=r[0]??t,o=r.slice(1).filter(l=>!l.includes("?")).slice(0,4),s=r.find(l=>l.includes("?")),c=Wt({summary:i,clues:o,details:o,...s?{nextQuestion:s}:{}});e.appendChild(Kt(a,c))}var Cu='<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>',Ua={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>'},Go=Gt,Wo=1400,Ko=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function Yo(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(Ko)?.[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 Jo(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?Yo(await t):null}catch{}return null}var Xo=class{_renderPhotoAnalysisCard(e,t,a){Vo(e,t,{badge:this.i18n.photoAnalysisBadge,strengths:this.i18n.photoAnalysisStrengthsLabel,focus:this.i18n.photoAnalysisFocusLabel,celebStyle:this.i18n.photoAnalysisCelebStyleLabel,seeMore:this.i18n.photoAnalysisSeeMoreLabel},a)}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._panelListScrollAnimToken=0,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={...Go,...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 E=document.createElement("div");E.className="gengage-chat-drawer-handle",E.dataset.gengagePart="chat-drawer-handle",E.setAttribute("aria-hidden","true"),E.style.pointerEvents="none",r=E}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 E=document.createElement("img");E.className="gengage-chat-header-avatar",c&&E.classList.add("gengage-chat-header-avatar--logo"),E.dataset.gengagePart="chat-header-avatar",E.src=s,E.alt=t.headerTitle??"Assistant",o.appendChild(E)}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 d=document.createElement("span");if(d.className="gengage-chat-header-title",d.dataset.gengagePart="chat-header-title",d.textContent=t.headerTitle??this.i18n.headerTitle??"Product Expert",g.appendChild(d),t.headerBadge){const E=document.createElement("span");E.className="gengage-chat-header-badge gds-badge gds-badge-brand",E.dataset.gengagePart="chat-header-badge",E.textContent=t.headerBadge,g.appendChild(E)}l.appendChild(g);const p=document.createElement("a");p.className="gengage-chat-header-powered",p.dataset.gengagePart="chat-header-powered-by",p.href="https://gengage.ai/",p.target="_blank",p.rel="noopener noreferrer",p.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(p),o.appendChild(l),i.appendChild(o);const h=document.createElement("div");h.className="gengage-chat-header-right",h.dataset.gengagePart="chat-header-actions";{const E=document.createElement("button");E.type="button",E.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-reopen-panel",E.setAttribute("aria-label",this.i18n.showPanelAriaLabel),E.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>',E.addEventListener("click",()=>this._showMobilePanelFromBtn()),h.appendChild(E),this._reopenPanelBtn=E}{const E=document.createElement("button");E.type="button",E.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-cart",E.setAttribute("aria-label",this.i18n.cartAriaLabel),E.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>',E.addEventListener("click",()=>t.onCartClick?.()),h.appendChild(E),this._cartBtn=E}if(t.onNewChat){const E=document.createElement("button");E.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-new-chat",E.type="button",E.setAttribute("aria-label",this.i18n.newChatButton),E.title=this.i18n.newChatButton,E.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>',E.addEventListener("click",()=>t.onNewChat?.()),h.appendChild(E)}const m=document.createElement("button");if(m.className="gengage-chat-close gds-btn gds-btn-ghost gds-icon-btn",m.dataset.gengagePart="chat-header-close",m.type="button",m.setAttribute("aria-label",this.i18n.closeButton),m.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>',m.addEventListener("click",t.onClose),t.showHeaderFavorites){const E=document.createElement("button");E.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-favorites",E.type="button",E.setAttribute("aria-label",this.i18n.favoritesAriaLabel),E.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 Y=document.createElement("span");Y.className="gengage-chat-header-fav-badge",Y.dataset.gengagePart="chat-header-favorites-badge",Y.setAttribute("aria-hidden","true"),Y.style.display="none",E.appendChild(Y),this._favBadgeEl=Y,E.addEventListener("click",()=>{t.onFavoritesClick?.()}),h.appendChild(E)}h.appendChild(m),r&&i.insertBefore(r,i.firstChild),i.appendChild(h);{let Y=0,le=0,pe=!1;const ve=xe=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||xe.target.closest('button, a, input, [role="button"]'))return;const Ne=xe.changedTouches?.[0];Ne&&(Y=Ne.clientY,le=0,pe=!0,this.root.style.transition="none")},Fe=xe=>{if(!pe)return;const Ne=xe.changedTouches?.[0];if(!Ne)return;le=Ne.clientY-Y;const wu=(t.getMobileState?.()??"full")==="full"?Math.max(0,le):le;xe.preventDefault(),this.root.style.transform=`translateY(${wu}px)`},Je=()=>{if(!pe)return;pe=!1;const xe=t.getMobileState?.()??"full";let Ne;le>72?Ne=xe==="full"?"half":"close":le<-72&&xe==="half"?Ne="full":Ne=xe,this.root.style.transition="",Ne==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Ne)),le=0},Ht=()=>{pe&&(pe=!1,le=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",ve,{passive:!0}),i.addEventListener("touchmove",Fe,{passive:!1}),i.addEventListener("touchend",Je,{passive:!0}),i.addEventListener("touchcancel",Ht,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",ve),i.removeEventListener("touchmove",Fe),i.removeEventListener("touchend",Je),i.removeEventListener("touchcancel",Ht)})}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 $o({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 y=document.createElement("button");y.className="gengage-chat-panel-divider-toggle gds-btn gds-btn-ghost",y.dataset.gengagePart="chat-panel-divider-toggle",y.type="button",y.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),y.setAttribute("title",this.i18n.togglePanelAriaLabel),y.textContent="»",y.addEventListener("click",()=>{if(this._ignoreNextDividerClick){this._ignoreNextDividerClick=!1;return}this.togglePanel(),this._onPanelToggle?.()});let M=null,C=null;const P=24,w=E=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const Y=E.changedTouches?.[0];Y&&(M=Y.clientX,C=Y.clientY)},N=E=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||M===null||C===null)return;const Y=E.changedTouches?.[0];if(!Y)return;const le=Y.clientX-M,pe=Y.clientY-C;if(M=null,C=null,Math.abs(pe)<P||Math.abs(pe)<Math.abs(le))return;const ve=pe<0;ve!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(ve),this._onPanelToggle?.())};this._dividerEl.addEventListener("touchstart",w,{passive:!0}),this._dividerEl.addEventListener("touchend",N,{passive:!0}),this._cleanups.push(()=>{this._dividerEl.removeEventListener("touchstart",w),this._dividerEl.removeEventListener("touchend",N)}),this._dividerEl.appendChild(y),u.appendChild(this._dividerEl);const R=document.createElement("div");R.className="gengage-chat-conversation",R.dataset.gengagePart="chat-conversation",this._conversationEl=R,R.appendChild(i);const L=document.createElement("div");L.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",L.dataset.gengagePart="chat-offline-bar",L.setAttribute("role","status"),L.setAttribute("aria-live","polite"),L.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&L.classList.add("gengage-chat-offline-bar--visible"),R.appendChild(L);const Z=()=>L.classList.add("gengage-chat-offline-bar--visible"),te=()=>L.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",Z),window.addEventListener("online",te),this._cleanups.push(()=>{window.removeEventListener("offline",Z),window.removeEventListener("online",te)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",R.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=vt,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),Ra(this.messagesEl);const X=document.createElement("button");X.type="button",X.className="gengage-chat-former-messages-btn gds-chip",X.dataset.gengagePart="chat-former-messages-button",X.textContent=this.i18n.showFormerMessagesButton,X.setAttribute("aria-label",this.i18n.showFormerMessagesButton),X.style.display="none",X.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(X),this._formerMessagesBtn=X;const I=()=>{this._userInteractionUntil=Date.now()+2e3};let v=!1;const b=()=>this._options.presentation,_=()=>{v||(v=!0,requestAnimationFrame(()=>{v=!1;const{scrollTop:E,scrollHeight:Y,clientHeight:le}=this.messagesEl,pe=Y-E-le;this._userScrolledUp=pe>10;const ve=this._presentationPinned?pe<96:pe<32,Fe=Date.now(),Je=Fe<this._programmaticScrollUntil,Ht=!ve&&Fe<this._userInteractionUntil,xe=Je?!1:Ht;ve!==this._presentationPinned&&(this._presentationPinned=ve,b()?.onPinnedToBottomChange?.(ve)),xe!==this._presentationUserInteracting&&(this._presentationUserInteracting=xe,b()?.onUserInteractingChange?.(xe))}))};this.messagesEl.addEventListener("scroll",_,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",_)});const S=E=>{I(),E.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",S,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",S));const T=E=>{I(),this._touchStartY=E.touches[0]?.clientY??null},z=E=>{I();const Y=E.touches[0]?.clientY,le=this._touchStartY;typeof Y=="number"&&typeof le=="number"&&Y-le>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",T,{passive:!0}),this.messagesEl.addEventListener("touchmove",z,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",T),this.messagesEl.removeEventListener("touchmove",z)}),R.appendChild(this.messagesEl),this._thumbnailsColumn=new Fo({onThumbnailClick:E=>t.onThumbnailClick?.(E)}),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 D=document.createElement("div");D.className="gengage-chat-pills-scroll",D.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(D);const A=document.createElement("button");A.className="gengage-chat-pills-arrow gds-btn gds-btn-ghost",A.dataset.gengagePart="chat-suggestion-pills-more",A.type="button",A.setAttribute("aria-label",this.i18n.moreSuggestionsAriaLabel),A.textContent="›",A.addEventListener("click",()=>{D.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(A);let U=!1;const F=()=>{U||(U=!0,requestAnimationFrame(()=>{U=!1;const E=D.scrollLeft+D.clientWidth>=D.scrollWidth-4;A.style.display=E?"none":""}))};D.addEventListener("scroll",F,{passive:!0}),this._cleanups.push(()=>{D.removeEventListener("scroll",F)}),R.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",R.appendChild(this._inputChipsEl);const K=document.createElement("div");K.className="gengage-chat-input-area",K.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",E=>{E.key==="Enter"&&!E.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!E.shiftKey)&&(E.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",E=>{const Y=E.clipboardData;if(!Y)return;let le=null;const pe=Y.files?.[0];if(pe&&pe.type.startsWith("image/"))le=pe;else if(Y.items?.length)for(let ve=0;ve<Y.items.length;ve++){const Fe=Y.items[ve];if(Fe?.kind==="file"&&Fe.type.startsWith("image/")){const Je=Fe.getAsFile();if(Je){le=Je;break}}}le&&(E.preventDefault(),this._routeAttachmentFile(le))}),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 E=this._fileInput.files?.[0];E&&this._routeAttachmentFile(E),this._fileInput.value=""});const ee=document.createElement("div");ee.className="gengage-chat-attach-wrap",ee.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=ee;const ae=document.createElement("button");this._attachBtn=ae,ae.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",ae.dataset.gengagePart="chat-attach-button",ae.type="button",ae.setAttribute("aria-label",this.i18n.attachImageButton),ae.setAttribute("aria-haspopup","menu"),ae.setAttribute("aria-expanded","false"),ae.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>',ae.addEventListener("click",E=>{E.stopPropagation(),this._toggleAttachMenu()});const de=document.createElement("div");this._attachMenuEl=de,de.className="gengage-chat-attach-menu gds-menu",de.dataset.gengagePart="chat-attach-menu",de.setAttribute("role","menu"),de.setAttribute("hidden","");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-select-photo",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"><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>`,q.addEventListener("click",E=>{E.stopPropagation(),this._closeAttachMenu(),this._fileInput.click()});const _e=document.createElement("div");_e.className="gengage-chat-attach-menu-sep",_e.dataset.gengagePart="chat-attach-menu-separator",_e.setAttribute("aria-hidden","true");const j=document.createElement("button");j.type="button",j.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",j.dataset.gengagePart="chat-attach-menu-paste",j.setAttribute("role","menuitem"),j.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>`,j.addEventListener("click",E=>{E.stopPropagation();const Y=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(Y)}),de.appendChild(q),de.appendChild(_e),de.appendChild(j),ee.appendChild(ae),ee.appendChild(de),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 B=document.createElement("img");B.className="gengage-chat-attachment-preview-thumb",B.dataset.gengagePart="chat-attachment-preview-thumb",B.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const J=document.createElement("button");J.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",J.dataset.gengagePart="chat-attachment-preview-remove",J.type="button",J.setAttribute("aria-label",this.i18n.removeAttachmentButton),J.textContent="×",J.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(B),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(J),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 E=this._sendStopHandler;this.hideStopButton(),E();return}this._submit()}),K.addEventListener("dragover",E=>{E.preventDefault(),K.classList.add("gengage-chat-input-area--dragover")}),K.addEventListener("dragleave",()=>{K.classList.remove("gengage-chat-input-area--dragover")}),K.addEventListener("drop",E=>{E.preventDefault(),K.classList.remove("gengage-chat-input-area--dragover");const Y=E.dataTransfer?.files[0];Y&&this._routeAttachmentFile(Y)});const O=document.createElement("div");O.className="gengage-chat-input-pill gds-input-shell",O.dataset.gengagePart="chat-input-shell",O.appendChild(ee),O.appendChild(this.inputEl),this._voiceEnabled&&Bo()&&(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()),O.appendChild(this._micBtn),this._voiceInput=new Ro({onInterim:E=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=E,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:E=>{this.inputEl.value=E},onAutoSubmit:E=>{this.inputEl.value=E,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:E=>{E==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(E,Y)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),O.appendChild(this.sendBtn),K.appendChild(this._previewStrip),K.appendChild(this._fileInput),K.appendChild(O),R.appendChild(K),u.appendChild(R),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(R),this._setupHorizontalSwipe(this._panelEl);const se=document.createElement("div");se.className="gengage-chat-footer",se.dataset.gengagePart="chat-footer",se.textContent=this.i18n.poweredBy,this.root.appendChild(se);const Ft=E=>{E.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",Ft),this._cleanups.push(()=>this.root.removeEventListener("keydown",Ft)),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.content,e.photoAnalysis)):a.innerHTML=Ae(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="${CSS.escape(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=Ua[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&&Pe(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=Oo({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=jo(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 Jo(e);if(t){this._routeAttachmentFile(t),this._closeAttachMenu();return}we("gengage:global:error",{message:this.i18n.clipboardNoImageMessage,source:"chat"}),this._closeAttachMenu()}getPendingAttachment(){return this._pendingAttachment}setPanelAiZoneState(e,t){if(this._panelAiZoneEl.isConnected){if(this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,e==="hidden"){this._panelAiZoneEl.innerHTML="",this._panelAiZoneEl.setAttribute("hidden","");return}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))}}_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){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelVisible&&this._panelEl.classList.add("gengage-chat-panel--transitioning"),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||(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._panelEl.classList.remove("gengage-chat-panel--transitioning"),this._updateScrollAffordance(),this._smoothScrollPanelListToTop()}),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync()}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||(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}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 R=0;R<2;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",R===1&&L.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(L)}const d=document.createElement("div");d.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-price",g.appendChild(d),c.appendChild(l),c.appendChild(g),o.appendChild(c);const p=document.createElement("div");p.className="gengage-chat-comparison-highlights";const h=document.createElement("div");h.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",p.appendChild(h);const m=document.createElement("ul");m.className="gengage-chat-comparison-skeleton-hl-list";for(let R=0;R<3;R++){const L=document.createElement("li"),Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",R===1&&Z.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),R===2&&Z.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),L.appendChild(Z),m.appendChild(L)}p.appendChild(m),o.appendChild(p),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 y=document.createElement("div");y.className="gengage-chat-comparison-key-differences-content";for(let R=0;R<4;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",y.appendChild(L)}u.appendChild(y),i.appendChild(u);const M=document.createElement("div");M.className="gengage-chat-comparison-special gengage-chat-comparison-special--skeleton";const C=document.createElement("div");C.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-special-line",M.appendChild(C),i.appendChild(M);const P=document.createElement("div");P.className="gengage-chat-comparison-skeleton-table-wrap";const w=document.createElement("div");w.className="gengage-chat-comparison-skeleton-table-head";const N=document.createElement("div");N.className="gengage-chat-comparison-skeleton-table-corner",w.appendChild(N);for(let R=0;R<3;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-table-col";const Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const te=document.createElement("div");te.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const X=document.createElement("div");X.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",L.appendChild(Z),L.appendChild(te),L.appendChild(X),w.appendChild(L)}P.appendChild(w);for(let R=0;R<3;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-table-row";const Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",L.appendChild(Z);for(let te=0;te<3;te++){const X=document.createElement("div");X.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",L.appendChild(X)}P.appendChild(L)}i.appendChild(P),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||(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(){const e=this._panelEl;if(typeof window<"u"&&(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches??!1)){e.scrollTop=0;return}this._panelListScrollAnimToken+=1;const t=this._panelListScrollAnimToken;requestAnimationFrame(()=>{if(t!==this._panelListScrollAnimToken)return;const a=Math.max(0,e.scrollHeight-e.clientHeight);if(a<=0)return;const n=Math.min(160,Math.max(48,a*.28));e.scrollTop=n;const r=Math.min(720,Math.max(380,320+Math.sqrt(n)*28)),i=performance.now(),o=c=>1-(1-c)**5,s=c=>{if(t!==this._panelListScrollAnimToken)return;const l=c-i,g=Math.min(1,l/r);e.scrollTop=n*(1-o(g)),g<1?requestAnimationFrame(s):e.scrollTop=0};requestAnimationFrame(s)})}_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()}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)},Wo))}_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="${CSS.escape(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,t,n)):(r.classList.remove("gengage-chat-bubble--photo-analysis"),i.innerHTML=Ae(t)),this._scrollToBottom(!1)}markFirstBotMessage(e){this._firstBotMessageIds.add(e);const t=this.messagesEl.querySelector(`[data-message-id="${CSS.escape(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="${CSS.escape(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="${CSS.escape(e)}"]`);let n=null;for(let i=0;i<a.length;i++){const o=a[i];if(o instanceof HTMLElement&&!o.classList.contains("gengage-chat-bubble--presentation-collapsed")){n=o;break}}if(!n&&a.length>0&&a[0]instanceof HTMLElement&&(n=a[0]),!n)return!1;const r=Math.max(n.offsetTop-20,0);return this._programmaticScrollUntil=Date.now()+700,this._scrollMessagesTo(r,t),!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=Ua[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)||!Pe(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(){Ra(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}},ja=["beauty_consulting","watch_expert","booking"],Qo=["shopping",...ja];function es(e){return typeof e=="string"&&Qo.includes(e)?e:null}function Yt(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function ts(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function as(e){const t=Yt(e);if(!t)return null;const a=ts(t.assistant_mode,t.assistantMode);return!a||!ja.includes(a)?null:a}var ns=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){Me("mode","redirect metadata received",e);const t=as(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Me("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=es(t);a?this._mode=a:Me("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=Yt(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 rs(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function is(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=Fa(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):(Me("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Ho(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 os(e){return e.renderHint==="photo_analysis"}function ss(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function cs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var ls=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
48
|
+
`);r=h.pop()??"";for(const m of h)if(Aa(m,t))return}if(r.trim()&&Aa(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 Ta=3,Pi=(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():""},Zt=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>Pi(a,t)).filter(Boolean):[];function Ai(e){const t=(e.display_keywords??[]).flatMap(r=>Zt(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,Ta);const n=[...Zt(e.chosen_attribute,{stripLeadingStopWords:!0}),...Zt(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,Ta)}function Ti(e){return Ai(e).join(" • ")}var Li=["beauty_consulting","watch_expert"];function La(e){return typeof e=="string"&&Li.includes(e)}function Ii(e){if(typeof e.type!="string")return null;if(Ni(e))return e;const t=e;switch(t.type){case"outputText":return zi(t);case"suggestedActions":return Mi(t);case"productList":return Bi(t);case"productDetails":return Ri(t);case"productDetailsSimilars":return Di(t);case"comparisonTable":return Oi(t);case"context":return Ui(t);case"chatStreamEnd":return ji();case"loading":return Zi(t);case"panelLoading":return qi(t);case"similarLoading":return Vi(t);case"redirect":return Gi(t);case"error":return Wi(t);case"dummy":return Ki(t);case"launcherAction":return Yi(t);case"text":return qt(t);case"productItem":return Ji(t);case"text_image":return Ia(t);case"quick_qna":return Na(t);case"reviewHighlights":return Xi(t);case"aiProductSuggestions":return to(t);case"aiProductGroupings":return ao(t);case"aiSuggestedSearches":return no(t);case"prosAndCons":return Qi(t);case"getGroundingReview":return ro(t);case"voice":return oo(t);case"visitorDataResponse":return eo(t);case"productListPreview":return io();case"groupList":return so(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return co(t);case"launcherContent":return go(t);case"handoff":return lo(t);case"uiSpec":return yo(t);default:return null}}function Ni(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=ke(e.spec);return n?typeof n.root=="string"&&ke(n.elements)!==null:!1}case"action":{const a=ke(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 zi(e){const t=V(e.payload.text,e.payload.plain_text)??"",a=V(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 Mi(e){return za((e.payload.actions??[]).map(t=>{const a=V(t.title)??"",n=Be(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(Vt),"chat")}function Bi(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=V(o.style_label),c=V(o.style_mood),l=V(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(p=>{const h=ke(p);return h?Ba(ke(h.product_detail)??ke(h.product)??h):null}).filter(Vt),d=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(p=>({label:V(p.label)??"",reason:V(p.reason)??"",skus:Array.isArray(p.skus)?p.skus.filter(h=>typeof h=="string"&&h.trim().length>0):[]})):[];return{style_label:s??"",style_mood:c??"",...l?{image_url:l}:{},product_list:g,recommendation_groups:d}}).filter(o=>o.product_list.length>0),a=e.payload.product_list??[],n=La(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?po(n,"chat"):Ma(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),Object.keys(o).length>0&&(i.props={...i.props,...o})}return r}function Ri(e){const t=e.payload.productDetails;if(!t)return uo("chat");const a=Qe(t);return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:{...t,...a}}}}},panelHint:"panel"}}function Di(e){const t=Ma(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function Oi(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 y=Qe(f);o.push(y)}const s=$i(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 d=bo(n?.special_considerations),p=n?.recommended_choice,h=n?.winner_hits,m={};for(const f of o){const y=f.sku;y&&(m[y]={title:f.name??y,type:"launchSingleProduct",payload:{sku:y}})}const u={products:o,attributes:s,highlights:g,productActions:m};return l&&(u.recommended=l),d.length>0&&(u.specialCases=d),p&&(u.recommendedText=p),h&&(u.winnerHits=h),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 $i(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 d=a.criteria_view??a.criteria_view_short??{},p=a.compared_field_names??Object.keys(e),h=[];for(const m of p){const u=e[m];if(!u||!Array.isArray(u))continue;const f=d[m]??m;h.push({label:f,values:u.map(y=>typeof y=="string"?y:String(y??""))})}return h}const o=e,s=t.map(d=>String(d.sku??"")).filter(d=>d.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:Fi(o)).filter(d=>d!=="name"&&d!=="name_short"&&!d.endsWith("_short")),g=[];for(const d of l){const p=s.map(m=>{const u=o[m];if(!u||typeof u!="object")return"";const f=u[`${d}_short`],y=u[d];return Hi(f??y)});if(p.every(m=>m.length===0))continue;const h=c[d]??d;g.push({label:h,values:p})}return g}function Fi(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 Hi(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Ui(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function ji(){return{type:"done"}}function Zi(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 qi(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Vi(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Gi(e){const t=V(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:V(e.payload.to)}}}function Wi(e){return{type:"error",code:"BACKEND_ERROR",message:V(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function Ki(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function Yi(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),Na({type:"quick_qna",payload:r})}const a=ke(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),Ia({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=ke(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),qt({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function qt(e){const t={text:V(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 Ji(e){return ho(e.payload,"qna")}function Ia(e){const t=V(e.payload.text)??"",a=Be(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),qt({type:"text",payload:n})}function Na(e){return za((e.payload.action_list??[]).map(t=>{const a=V(t.title)??"",n=Be(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(Vt),"qna")}function Xi(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 Qi(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 eo(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function to(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=mo(r);if(!i)continue;const o={product:i},s=Be(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 ao(e){const t=e.payload.product_groupings??[],a=[];for(let n=0;n<t.length;n++){const r=t[n];if(!r)continue;const i=V(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Be(r.requestDetails??o,i);if(!s)continue;const c={name:i,action:s};if(Array.isArray(r.labels)){const l=r.labels.filter(g=>typeof g=="string");l.length>0&&(c.labels=l)}typeof r.image=="string"&&(c.image=r.image),a.push(c)}return a.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:a}}}}}}function no(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=V(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=V(r.detailed_user_message);s&&(o.text=s);const c=ke(ke(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(y=>typeof y=="string"));const g=V(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const d={type:"inputText",payload:o},p=Be(r.requestDetails,i),h=p?.type==="findSimilar"&&typeof o.text=="string"?Be(d,i):p??Be(d,i);if(!h)continue;const m={shortName:i,action:h},u=V(r.detailed_user_message);u&&u!==i&&(m.detailedMessage=u);const f=Ti(r);f&&f!==i&&f!==(u??"")&&(m.whyDifferent=f),typeof r.image=="string"&&(m.image=r.image),a.push(m)}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 ro(e){const t=e.payload,a=Be(t.requestDetails??t.request_details,V(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 io(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function oo(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function so(e){const t=e.payload.group_list??[],a=[];for(const r of t){const i=r.group_name??"",o=(r.product_list??[]).map(Qe);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=Be(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 co(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function lo(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 go(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function za(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 Ma(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=Qe(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 po(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 ho(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Qe(e),index:0}}}}}}function uo(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function mo(e){const t=V(e.sku),a=V(e.short_name),n={...ke(e.product_item)??e},r=V(e.discount_reason,e.discountReason);return r&&!V(n.discount_reason,n.discountReason)&&(n.discount_reason=r),Ba(n,t,a)}function Ba(e,t,a){const n=V(e.sku,t),r=V(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=V(e.brand);o&&(i.brand=o);const s=V(e.url);s&&(i.url=s);const c=fo(e.images);if(c.length>0)i.images=c;else{const u=V(e.image,e.image_url,e.imageUrl);u&&(i.images=[u])}const l=gt(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=gt(e.price);g!==void 0&&(i.price=g);const d=gt(e.rating);d!==void 0&&(i.rating=d);const p=gt(e.review_count)??gt(e.reviewCount);p!==void 0&&(i.review_count=p);const h=V(e.cart_code,e.cartCode);h&&(i.cart_code=h),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const m=V(e.discount_reason,e.discountReason);return m&&(i.discount_reason=m),Qe(i)}function Be(e,t){const a=ke(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 ke(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function V(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function fo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function bo(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 gt(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 Vt(e){return e!=null}var vo=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 Qe(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=V(e.brand),o=V(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:V(e.url)??""},l=e.images?.[0];l&&(c.imageUrl=l),e.images&&e.images.length>1&&(c.images=e.images),a!=null&&(c.price=String(a)),n!=null&&(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,d={};let p=!1;for(const h of Object.keys(g))vo.has(h)||(d[h]=g[h],p=!0);return p&&(c.extras=d),c}function yo(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 _o={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function xo(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 wo(e,t){return`${xo(t?.middlewareUrl)}/chat${_o[e]}`}function ko(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":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 Co={user_message:"inputText"};function So(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=Co[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function Eo(e,t,a){const n=wo("process_action",a),r=new AbortController;return(async()=>{try{const o=So(e),s=a.attachment!==void 0;let c;if(s){const p=new FormData;p.append("request",o),a.attachment!==void 0&&p.append("attachment",a.attachment),c={method:"POST",body:p,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 p=l.statusText;try{const h=await l.json(),m=h.detail??h.message??h.error;typeof m=="string"&&(p=m)}catch{}t.onError(new Error(`HTTP ${l.status}: ${p}`));return}let g=!1;const d=()=>{g||(g=!0,t.onDone())};await Ei(l,{onEvent:p=>{const h=Ii(p);if(h)switch(h.type){case"text_chunk":t.onTextChunk(h.content,h.final===!0,{productMentions:h.productMentions,skuToProductItem:h.skuToProductItem,conversationMode:h.conversationMode,renderHint:h.renderHint,kvkk:h.kvkk});break;case"ui_spec":t.onUISpec(h.spec,h.widget,h.panelHint,h.clearPanel===!0);break;case"action":t.onAction(h);break;case"metadata":t.onMetadata(h);break;case"error":t.onError(new Error(h.message));break;case"done":d();break}},onError:t.onError,signal:r.signal}),d()}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;t.onError(o instanceof Error?o:new Error(String(o)))}})(),r}var Po=["chat_debug","presentation_debug"],Ao=["gengage_chat_debug","gengage_presentation_debug"];function To(){if(typeof window>"u")return!1;const e=new URLSearchParams(window.location.search);if(Po.some(t=>e.get(t)==="1"))return!0;try{return Ao.some(t=>window.localStorage.getItem(t)==="1")}catch{return!1}}function Lo(e,t,a){if(!To())return;const n=(window.__gengageChatPresentationDebugSeq??0)+1;window.__gengageChatPresentationDebugSeq=n;const r={seq:n,time:new Date().toISOString(),scope:e,message:t,payload:a};window.__gengageChatPresentationDebugLog||(window.__gengageChatPresentationDebugLog=[]),window.__gengageChatPresentationDebugLog.push(r),window.__gengageChatPresentationDebugLog.length>400&&window.__gengageChatPresentationDebugLog.shift();const i=`[gengage-chat-debug #${n}][${e}] ${t}`;a===void 0?console.debug(i):console.debug(i,a)}var vt="gengage-chat-scroll",et=null;function Ra(e){et=e}function Io(){if(et&&et.isConnected)return et;et=null;const e=document.getElementById(vt);return e||(Lo("chat-scroll","failed to resolve scroll container (not registered)",{id:vt}),null)}function Da(){et=null}var Gt={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:"Düşünüyorum...",loadingSequenceGeneric:["Sizin için en önemli noktaları anlıyorum","Ürünleri, yorumları ve özellikleri inceliyorum","En güçlü seçenekleri hazırlıyorum"],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:"En Beğendiğim",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",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",photoAnalysisSeeMoreLabel:"Detaylı analizi gör",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"},No={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:"Thinking...",loadingSequenceGeneric:["Understanding what matters most","Reviewing products, reviews, and specs","Preparing the best options to review"],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",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",photoAnalysisSeeMoreLabel:"See detailed analysis",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 zo(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Mo(e){return zo(e)==="en"?No:Gt}function Bo(){return Oa()!==null}function Oa(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var Ro=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=Oa();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=Do(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 Do(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 Oo(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=Ae(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 $o=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??""}},Fo=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,Pe(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 Ho(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 $a(e,t,a){const n=e.props??{},r=n.processing===!0,i=document.createElement("div");i.className="gengage-chat-beauty-photo-step-card";const o=document.createElement("span");o.className="gengage-chat-beauty-photo-step-icon",o.setAttribute("aria-hidden","true"),o.textContent="✦";const s=document.createElement("div");s.className="gengage-chat-beauty-photo-step-content";const c=document.createElement("div");c.className="gengage-chat-beauty-photo-step-title",c.textContent=(typeof n.title=="string"?n.title:void 0)??t.i18n?.beautyPhotoStepTitle??"Upload a Photo";const l=document.createElement("p");l.className="gengage-chat-beauty-photo-step-desc",l.textContent=(typeof n.description=="string"?n.description:void 0)??t.i18n?.beautyPhotoStepDescription??"Share a selfie so we can analyze your skin and recommend the right products.";const g=document.createElement("div");g.className="gengage-chat-beauty-photo-step-actions";const d=document.createElement("button");d.type="button",d.className="gengage-chat-beauty-photo-step-upload gds-btn gds-btn-primary",d.textContent=r?t.i18n?.beautyPhotoStepProcessing??"Analyzing...":(typeof n.upload_label=="string"?n.upload_label:void 0)??t.i18n?.beautyPhotoStepUpload??"Upload Photo",d.disabled=r,a?.onUpload&&d.addEventListener("click",()=>a.onUpload());const p=document.createElement("button");return p.type="button",p.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",p.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??t.i18n?.beautyPhotoStepSkip??"Skip",a?.onSkip&&p.addEventListener("click",()=>a.onSkip()),g.appendChild(d),g.appendChild(p),s.appendChild(c),s.appendChild(l),s.appendChild(g),i.appendChild(o),i.appendChild(s),i}function Uo(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 jo(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=Uo(e,t);i.hidden=!1,i.innerHTML="";const o=$a({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 Fa(e){const t=typeof e.summary=="string"?e.summary:"",a=Array.isArray(e.strengths)?e.strengths.filter(l=>typeof l=="string"):[],n=Array.isArray(e.focus_points)?e.focus_points.filter(l=>typeof l=="string"):[],r=Array.isArray(e.details)?e.details.filter(l=>typeof l=="string"):[];if(!t&&a.length===0&&n.length===0&&r.length===0)return null;const i={summary:t,details:r},o=typeof e.celeb_style=="string"?e.celeb_style:void 0,s=typeof e.celeb_style_reason=="string"?e.celeb_style_reason:void 0,c=typeof e.next_question=="string"?e.next_question:void 0;return a.length>0&&(i.strengths=a),n.length>0&&(i.focusPoints=n),o&&(i.celebStyle=o),s&&(i.celebStyleReason=s),c&&(i.nextQuestion=c),i}function Wt(e){const t=e.details;return e.strengths&&e.strengths.length>0||e.focusPoints&&e.focusPoints.length>0?{...e,details:t}:t.length<3?{...e,details:t}:{...e,strengths:t.slice(0,2),focusPoints:t.slice(2,4),details:t}}function Ha(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 Kt(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 l=document.createElement("p");l.className="gengage-chat-photo-analysis-summary",l.textContent=t.summary,r.appendChild(l)}const i=document.createElement("div");i.className="gengage-chat-photo-analysis-highlights";const o=Ha(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=Ha(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 l=document.createElement("section");l.className="gengage-chat-photo-analysis-section gengage-chat-photo-analysis-section--celeb";const g=document.createElement("h4");g.className="gengage-chat-photo-analysis-section-title",g.textContent=e.celebStyle;const d=document.createElement("p");if(d.className="gengage-chat-photo-analysis-celeb-name",d.textContent=t.celebStyle,l.appendChild(g),l.appendChild(d),t.celebStyleReason){const p=document.createElement("p");p.className="gengage-chat-photo-analysis-celeb-reason",p.textContent=t.celebStyleReason,l.appendChild(p)}r.appendChild(l)}const c=t.details.filter(Boolean);if(c.length>0){const l=document.createElement("details");l.className="gengage-chat-photo-analysis-details";const g=document.createElement("summary");g.className="gengage-chat-photo-analysis-details-summary",g.textContent=e.seeMore;const d=document.createElement("ul");d.className="gengage-chat-photo-analysis-points";for(const p of c){const h=document.createElement("li");h.textContent=p,d.appendChild(h)}l.appendChild(g),l.appendChild(d),r.appendChild(l)}if(t.nextQuestion){const l=document.createElement("p");l.className="gengage-chat-photo-analysis-next",l.textContent=t.nextQuestion,r.appendChild(l)}return a.appendChild(n),a.appendChild(r),a}function Zo(e){return{badge:e?.i18n?.photoAnalysisBadge??"Skin Analysis",strengths:e?.i18n?.photoAnalysisStrengthsLabel??"Your strengths",focus:e?.i18n?.photoAnalysisFocusLabel??"Focus points",celebStyle:e?.i18n?.photoAnalysisCelebStyleLabel??"Celeb style match",seeMore:e?.i18n?.photoAnalysisSeeMoreLabel??"See detailed analysis"}}function qo(e,t){const a=Wt(Fa(e.props??{})??{summary:"",details:[]});return Kt(Zo(t),a)}function Vo(e,t,a,n){if(e.innerHTML="",n){e.appendChild(Kt(a,Wt(n)));return}const r=t.split(/(?<=[.!?])\s+/).map(l=>l.trim()).filter(Boolean),i=r[0]??t,o=r.slice(1).filter(l=>!l.includes("?")).slice(0,4),s=r.find(l=>l.includes("?")),c=Wt({summary:i,details:o,...s?{nextQuestion:s}:{}});e.appendChild(Kt(a,c))}var Cu='<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>',Ua={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>'},Go=Gt,Wo=1400,Ko=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function Yo(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(Ko)?.[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 Jo(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?Yo(await t):null}catch{}return null}var Xo=class{_renderPhotoAnalysisCard(e,t,a){Vo(e,t,{badge:this.i18n.photoAnalysisBadge,strengths:this.i18n.photoAnalysisStrengthsLabel,focus:this.i18n.photoAnalysisFocusLabel,celebStyle:this.i18n.photoAnalysisCelebStyleLabel,seeMore:this.i18n.photoAnalysisSeeMoreLabel},a)}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._panelListScrollAnimToken=0,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={...Go,...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 E=document.createElement("div");E.className="gengage-chat-drawer-handle",E.dataset.gengagePart="chat-drawer-handle",E.setAttribute("aria-hidden","true"),E.style.pointerEvents="none",r=E}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 E=document.createElement("img");E.className="gengage-chat-header-avatar",c&&E.classList.add("gengage-chat-header-avatar--logo"),E.dataset.gengagePart="chat-header-avatar",E.src=s,E.alt=t.headerTitle??"Assistant",o.appendChild(E)}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 d=document.createElement("span");if(d.className="gengage-chat-header-title",d.dataset.gengagePart="chat-header-title",d.textContent=t.headerTitle??this.i18n.headerTitle??"Product Expert",g.appendChild(d),t.headerBadge){const E=document.createElement("span");E.className="gengage-chat-header-badge gds-badge gds-badge-brand",E.dataset.gengagePart="chat-header-badge",E.textContent=t.headerBadge,g.appendChild(E)}l.appendChild(g);const p=document.createElement("a");p.className="gengage-chat-header-powered",p.dataset.gengagePart="chat-header-powered-by",p.href="https://gengage.ai/",p.target="_blank",p.rel="noopener noreferrer",p.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(p),o.appendChild(l),i.appendChild(o);const h=document.createElement("div");h.className="gengage-chat-header-right",h.dataset.gengagePart="chat-header-actions";{const E=document.createElement("button");E.type="button",E.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-reopen-panel",E.setAttribute("aria-label",this.i18n.showPanelAriaLabel),E.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>',E.addEventListener("click",()=>this._showMobilePanelFromBtn()),h.appendChild(E),this._reopenPanelBtn=E}{const E=document.createElement("button");E.type="button",E.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-cart",E.setAttribute("aria-label",this.i18n.cartAriaLabel),E.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>',E.addEventListener("click",()=>t.onCartClick?.()),h.appendChild(E),this._cartBtn=E}if(t.onNewChat){const E=document.createElement("button");E.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-new-chat",E.type="button",E.setAttribute("aria-label",this.i18n.newChatButton),E.title=this.i18n.newChatButton,E.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>',E.addEventListener("click",()=>t.onNewChat?.()),h.appendChild(E)}const m=document.createElement("button");if(m.className="gengage-chat-close gds-btn gds-btn-ghost gds-icon-btn",m.dataset.gengagePart="chat-header-close",m.type="button",m.setAttribute("aria-label",this.i18n.closeButton),m.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>',m.addEventListener("click",t.onClose),t.showHeaderFavorites){const E=document.createElement("button");E.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",E.dataset.gengagePart="chat-header-favorites",E.type="button",E.setAttribute("aria-label",this.i18n.favoritesAriaLabel),E.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 K=document.createElement("span");K.className="gengage-chat-header-fav-badge",K.dataset.gengagePart="chat-header-favorites-badge",K.setAttribute("aria-hidden","true"),K.style.display="none",E.appendChild(K),this._favBadgeEl=K,E.addEventListener("click",()=>{t.onFavoritesClick?.()}),h.appendChild(E)}h.appendChild(m),r&&i.insertBefore(r,i.firstChild),i.appendChild(h);{let K=0,le=0,pe=!1;const ve=xe=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||xe.target.closest('button, a, input, [role="button"]'))return;const Ne=xe.changedTouches?.[0];Ne&&(K=Ne.clientY,le=0,pe=!0,this.root.style.transition="none")},Fe=xe=>{if(!pe)return;const Ne=xe.changedTouches?.[0];if(!Ne)return;le=Ne.clientY-K;const wu=(t.getMobileState?.()??"full")==="full"?Math.max(0,le):le;xe.preventDefault(),this.root.style.transform=`translateY(${wu}px)`},Je=()=>{if(!pe)return;pe=!1;const xe=t.getMobileState?.()??"full";let Ne;le>72?Ne=xe==="full"?"half":"close":le<-72&&xe==="half"?Ne="full":Ne=xe,this.root.style.transition="",Ne==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Ne)),le=0},Ht=()=>{pe&&(pe=!1,le=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",ve,{passive:!0}),i.addEventListener("touchmove",Fe,{passive:!1}),i.addEventListener("touchend",Je,{passive:!0}),i.addEventListener("touchcancel",Ht,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",ve),i.removeEventListener("touchmove",Fe),i.removeEventListener("touchend",Je),i.removeEventListener("touchcancel",Ht)})}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 $o({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 y=document.createElement("button");y.className="gengage-chat-panel-divider-toggle gds-btn gds-btn-ghost",y.dataset.gengagePart="chat-panel-divider-toggle",y.type="button",y.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),y.setAttribute("title",this.i18n.togglePanelAriaLabel),y.textContent="»",y.addEventListener("click",()=>{if(this._ignoreNextDividerClick){this._ignoreNextDividerClick=!1;return}this.togglePanel(),this._onPanelToggle?.()});let M=null,C=null;const P=24,w=E=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const K=E.changedTouches?.[0];K&&(M=K.clientX,C=K.clientY)},N=E=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||M===null||C===null)return;const K=E.changedTouches?.[0];if(!K)return;const le=K.clientX-M,pe=K.clientY-C;if(M=null,C=null,Math.abs(pe)<P||Math.abs(pe)<Math.abs(le))return;const ve=pe<0;ve!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(ve),this._onPanelToggle?.())};this._dividerEl.addEventListener("touchstart",w,{passive:!0}),this._dividerEl.addEventListener("touchend",N,{passive:!0}),this._cleanups.push(()=>{this._dividerEl.removeEventListener("touchstart",w),this._dividerEl.removeEventListener("touchend",N)}),this._dividerEl.appendChild(y),u.appendChild(this._dividerEl);const R=document.createElement("div");R.className="gengage-chat-conversation",R.dataset.gengagePart="chat-conversation",this._conversationEl=R,R.appendChild(i);const L=document.createElement("div");L.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",L.dataset.gengagePart="chat-offline-bar",L.setAttribute("role","status"),L.setAttribute("aria-live","polite"),L.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&L.classList.add("gengage-chat-offline-bar--visible"),R.appendChild(L);const Z=()=>L.classList.add("gengage-chat-offline-bar--visible"),te=()=>L.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",Z),window.addEventListener("online",te),this._cleanups.push(()=>{window.removeEventListener("offline",Z),window.removeEventListener("online",te)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",R.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=vt,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),Ra(this.messagesEl);const X=document.createElement("button");X.type="button",X.className="gengage-chat-former-messages-btn gds-chip",X.dataset.gengagePart="chat-former-messages-button",X.textContent=this.i18n.showFormerMessagesButton,X.setAttribute("aria-label",this.i18n.showFormerMessagesButton),X.style.display="none",X.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(X),this._formerMessagesBtn=X;const I=()=>{this._userInteractionUntil=Date.now()+2e3};let v=!1;const b=()=>this._options.presentation,_=()=>{v||(v=!0,requestAnimationFrame(()=>{v=!1;const{scrollTop:E,scrollHeight:K,clientHeight:le}=this.messagesEl,pe=K-E-le;this._userScrolledUp=pe>10;const ve=this._presentationPinned?pe<96:pe<32,Fe=Date.now(),Je=Fe<this._programmaticScrollUntil,Ht=!ve&&Fe<this._userInteractionUntil,xe=Je?!1:Ht;ve!==this._presentationPinned&&(this._presentationPinned=ve,b()?.onPinnedToBottomChange?.(ve)),xe!==this._presentationUserInteracting&&(this._presentationUserInteracting=xe,b()?.onUserInteractingChange?.(xe))}))};this.messagesEl.addEventListener("scroll",_,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",_)});const S=E=>{I(),E.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",S,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",S));const T=E=>{I(),this._touchStartY=E.touches[0]?.clientY??null},z=E=>{I();const K=E.touches[0]?.clientY,le=this._touchStartY;typeof K=="number"&&typeof le=="number"&&K-le>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",T,{passive:!0}),this.messagesEl.addEventListener("touchmove",z,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",T),this.messagesEl.removeEventListener("touchmove",z)}),R.appendChild(this.messagesEl),this._thumbnailsColumn=new Fo({onThumbnailClick:E=>t.onThumbnailClick?.(E)}),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 D=document.createElement("div");D.className="gengage-chat-pills-scroll",D.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(D);const A=document.createElement("button");A.className="gengage-chat-pills-arrow gds-btn gds-btn-ghost",A.dataset.gengagePart="chat-suggestion-pills-more",A.type="button",A.setAttribute("aria-label",this.i18n.moreSuggestionsAriaLabel),A.textContent="›",A.addEventListener("click",()=>{D.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(A);let U=!1;const F=()=>{U||(U=!0,requestAnimationFrame(()=>{U=!1;const E=D.scrollLeft+D.clientWidth>=D.scrollWidth-4;A.style.display=E?"none":""}))};D.addEventListener("scroll",F,{passive:!0}),this._cleanups.push(()=>{D.removeEventListener("scroll",F)}),R.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",R.appendChild(this._inputChipsEl);const W=document.createElement("div");W.className="gengage-chat-input-area",W.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",E=>{E.key==="Enter"&&!E.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!E.shiftKey)&&(E.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",E=>{const K=E.clipboardData;if(!K)return;let le=null;const pe=K.files?.[0];if(pe&&pe.type.startsWith("image/"))le=pe;else if(K.items?.length)for(let ve=0;ve<K.items.length;ve++){const Fe=K.items[ve];if(Fe?.kind==="file"&&Fe.type.startsWith("image/")){const Je=Fe.getAsFile();if(Je){le=Je;break}}}le&&(E.preventDefault(),this._routeAttachmentFile(le))}),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 E=this._fileInput.files?.[0];E&&this._routeAttachmentFile(E),this._fileInput.value=""});const ee=document.createElement("div");ee.className="gengage-chat-attach-wrap",ee.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=ee;const ae=document.createElement("button");this._attachBtn=ae,ae.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",ae.dataset.gengagePart="chat-attach-button",ae.type="button",ae.setAttribute("aria-label",this.i18n.attachImageButton),ae.setAttribute("aria-haspopup","menu"),ae.setAttribute("aria-expanded","false"),ae.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>',ae.addEventListener("click",E=>{E.stopPropagation(),this._toggleAttachMenu()});const de=document.createElement("div");this._attachMenuEl=de,de.className="gengage-chat-attach-menu gds-menu",de.dataset.gengagePart="chat-attach-menu",de.setAttribute("role","menu"),de.setAttribute("hidden","");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-select-photo",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"><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>`,q.addEventListener("click",E=>{E.stopPropagation(),this._closeAttachMenu(),this._fileInput.click()});const _e=document.createElement("div");_e.className="gengage-chat-attach-menu-sep",_e.dataset.gengagePart="chat-attach-menu-separator",_e.setAttribute("aria-hidden","true");const j=document.createElement("button");j.type="button",j.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",j.dataset.gengagePart="chat-attach-menu-paste",j.setAttribute("role","menuitem"),j.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>`,j.addEventListener("click",E=>{E.stopPropagation();const K=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(K)}),de.appendChild(q),de.appendChild(_e),de.appendChild(j),ee.appendChild(ae),ee.appendChild(de),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 B=document.createElement("img");B.className="gengage-chat-attachment-preview-thumb",B.dataset.gengagePart="chat-attachment-preview-thumb",B.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const J=document.createElement("button");J.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",J.dataset.gengagePart="chat-attachment-preview-remove",J.type="button",J.setAttribute("aria-label",this.i18n.removeAttachmentButton),J.textContent="×",J.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(B),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(J),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 E=this._sendStopHandler;this.hideStopButton(),E();return}this._submit()}),W.addEventListener("dragover",E=>{E.preventDefault(),W.classList.add("gengage-chat-input-area--dragover")}),W.addEventListener("dragleave",()=>{W.classList.remove("gengage-chat-input-area--dragover")}),W.addEventListener("drop",E=>{E.preventDefault(),W.classList.remove("gengage-chat-input-area--dragover");const K=E.dataTransfer?.files[0];K&&this._routeAttachmentFile(K)});const O=document.createElement("div");O.className="gengage-chat-input-pill gds-input-shell",O.dataset.gengagePart="chat-input-shell",O.appendChild(ee),O.appendChild(this.inputEl),this._voiceEnabled&&Bo()&&(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()),O.appendChild(this._micBtn),this._voiceInput=new Ro({onInterim:E=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=E,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:E=>{this.inputEl.value=E},onAutoSubmit:E=>{this.inputEl.value=E,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:E=>{E==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(E,K)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),O.appendChild(this.sendBtn),W.appendChild(this._previewStrip),W.appendChild(this._fileInput),W.appendChild(O),R.appendChild(W),u.appendChild(R),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(R),this._setupHorizontalSwipe(this._panelEl);const se=document.createElement("div");se.className="gengage-chat-footer",se.dataset.gengagePart="chat-footer",se.textContent=this.i18n.poweredBy,this.root.appendChild(se);const Ft=E=>{E.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",Ft),this._cleanups.push(()=>this.root.removeEventListener("keydown",Ft)),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.content,e.photoAnalysis)):a.innerHTML=Ae(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="${CSS.escape(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=Ua[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&&Pe(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=Oo({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=jo(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 Jo(e);if(t){this._routeAttachmentFile(t),this._closeAttachMenu();return}we("gengage:global:error",{message:this.i18n.clipboardNoImageMessage,source:"chat"}),this._closeAttachMenu()}getPendingAttachment(){return this._pendingAttachment}setPanelAiZoneState(e,t){if(this._panelAiZoneEl.isConnected){if(this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,e==="hidden"){this._panelAiZoneEl.innerHTML="",this._panelAiZoneEl.setAttribute("hidden","");return}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))}}_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){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelVisible&&this._panelEl.classList.add("gengage-chat-panel--transitioning"),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||(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._panelEl.classList.remove("gengage-chat-panel--transitioning"),this._updateScrollAffordance(),this._smoothScrollPanelListToTop()}),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync()}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||(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}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 R=0;R<2;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",R===1&&L.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(L)}const d=document.createElement("div");d.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-price",g.appendChild(d),c.appendChild(l),c.appendChild(g),o.appendChild(c);const p=document.createElement("div");p.className="gengage-chat-comparison-highlights";const h=document.createElement("div");h.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",p.appendChild(h);const m=document.createElement("ul");m.className="gengage-chat-comparison-skeleton-hl-list";for(let R=0;R<3;R++){const L=document.createElement("li"),Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",R===1&&Z.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),R===2&&Z.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),L.appendChild(Z),m.appendChild(L)}p.appendChild(m),o.appendChild(p),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 y=document.createElement("div");y.className="gengage-chat-comparison-key-differences-content";for(let R=0;R<4;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",y.appendChild(L)}u.appendChild(y),i.appendChild(u);const M=document.createElement("div");M.className="gengage-chat-comparison-special gengage-chat-comparison-special--skeleton";const C=document.createElement("div");C.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-special-line",M.appendChild(C),i.appendChild(M);const P=document.createElement("div");P.className="gengage-chat-comparison-skeleton-table-wrap";const w=document.createElement("div");w.className="gengage-chat-comparison-skeleton-table-head";const N=document.createElement("div");N.className="gengage-chat-comparison-skeleton-table-corner",w.appendChild(N);for(let R=0;R<3;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-table-col";const Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const te=document.createElement("div");te.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const X=document.createElement("div");X.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",L.appendChild(Z),L.appendChild(te),L.appendChild(X),w.appendChild(L)}P.appendChild(w);for(let R=0;R<3;R++){const L=document.createElement("div");L.className="gengage-chat-comparison-skeleton-table-row";const Z=document.createElement("div");Z.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",L.appendChild(Z);for(let te=0;te<3;te++){const X=document.createElement("div");X.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",L.appendChild(X)}P.appendChild(L)}i.appendChild(P),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||(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(){const e=this._panelEl;if(typeof window<"u"&&(window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches??!1)){e.scrollTop=0;return}this._panelListScrollAnimToken+=1;const t=this._panelListScrollAnimToken;requestAnimationFrame(()=>{if(t!==this._panelListScrollAnimToken)return;const a=Math.max(0,e.scrollHeight-e.clientHeight);if(a<=0)return;const n=Math.min(160,Math.max(48,a*.28));e.scrollTop=n;const r=Math.min(720,Math.max(380,320+Math.sqrt(n)*28)),i=performance.now(),o=c=>1-(1-c)**5,s=c=>{if(t!==this._panelListScrollAnimToken)return;const l=c-i,g=Math.min(1,l/r);e.scrollTop=n*(1-o(g)),g<1?requestAnimationFrame(s):e.scrollTop=0};requestAnimationFrame(s)})}_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()}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)},Wo))}_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="${CSS.escape(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,t,n)):(r.classList.remove("gengage-chat-bubble--photo-analysis"),i.innerHTML=Ae(t)),this._scrollToBottom(!1)}markFirstBotMessage(e){this._firstBotMessageIds.add(e);const t=this.messagesEl.querySelector(`[data-message-id="${CSS.escape(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="${CSS.escape(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="${CSS.escape(e)}"]`);let n=null;for(let i=0;i<a.length;i++){const o=a[i];if(o instanceof HTMLElement&&!o.classList.contains("gengage-chat-bubble--presentation-collapsed")){n=o;break}}if(!n&&a.length>0&&a[0]instanceof HTMLElement&&(n=a[0]),!n)return!1;const r=Math.max(n.offsetTop-20,0);return this._programmaticScrollUntil=Date.now()+700,this._scrollMessagesTo(r,t),!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=Ua[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)||!Pe(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(){Ra(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}},ja=["beauty_consulting","watch_expert","booking"],Qo=["shopping",...ja];function es(e){return typeof e=="string"&&Qo.includes(e)?e:null}function Yt(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function ts(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function as(e){const t=Yt(e);if(!t)return null;const a=ts(t.assistant_mode,t.assistantMode);return!a||!ja.includes(a)?null:a}var ns=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){Me("mode","redirect metadata received",e);const t=as(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Me("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=es(t);a?this._mode=a:Me("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=Yt(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 rs(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function is(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=Fa(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):(Me("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Ho(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 os(e){return e.renderHint==="photo_analysis"}function ss(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function cs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var ls=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
49
49
|
<rect x="3" y="7" width="18" height="13" rx="3" fill="currentColor" opacity="0.15"/>
|
|
50
50
|
<rect x="3" y="7" width="18" height="13" rx="3" stroke="currentColor" stroke-width="1.5"/>
|
|
51
51
|
<circle cx="9" cy="13" r="1.5" fill="currentColor"/>
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
<path d="M1 12V14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
57
57
|
<path d="M23 12V14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
58
58
|
</svg>`;function ds(e){const t=document.createElement("div");t.className="gengage-chat-launcher-container",t.dataset.gengagePart="chat-launcher-container";const a=document.createElement("div");a.className="gengage-chat-launcher-content-area",a.dataset.gengagePart="chat-launcher-content-primary",t.appendChild(a);const n=document.createElement("button");if(n.type="button",n.setAttribute("aria-label",e.ariaLabel??"Open chat"),e.imageUrl){n.className="gengage-chat-launcher gengage-chat-launcher--image-mode";const i=document.createElement("img");i.src=e.imageUrl,i.alt="",i.draggable=!1,n.appendChild(i)}else n.className="gengage-chat-launcher",n.innerHTML=e.svgMarkup??ls;if(n.dataset.gengagePart="chat-launcher-button",e.tooltip!==void 0){const i=document.createElement("span");i.className="gengage-chat-launcher-tooltip",i.dataset.gengagePart="chat-launcher-tooltip",i.textContent=e.tooltip,n.appendChild(i)}e.hideMobile&&(t.dataset.hideMobile="1"),e.mobileBreakpoint!==void 0&&(t.dataset.mobileBreakpoint=String(e.mobileBreakpoint)),n.addEventListener("click",e.onClick),t.appendChild(n);const r=document.createElement("div");return r.className="gengage-chat-launcher-content-area-bottom",r.dataset.gengagePart="chat-launcher-content-secondary",t.appendChild(r),{container:t,button:n,contentArea:a,contentAreaBottom:r}}var gs=new Set(["audio/ogg","audio/mpeg","audio/mp3","audio/wav","audio/webm","audio/aac","audio/mp4"]),Za=new Set;function Jt(e){e.pause(),e.removeAttribute("src"),e.load(),Za.delete(e)}function ps(e,t="audio/ogg"){const a=t.split(";")[0].trim();if(!gs.has(a))return null;try{const n=new Audio(`data:${t};base64,${e}`);return Za.add(n),n.addEventListener("ended",()=>Jt(n),{once:!0}),n.play().catch(()=>{Jt(n)}),{stop:()=>Jt(n)}}catch{return null}}var hs={currencyCode:"TRY",currencySymbol:"TL",currencyPosition:"suffix",thousandsSeparator:".",decimalSeparator:",",alwaysShowDecimals:!1};function G(e,t){const a=Number(e);if(!Number.isFinite(a)||a<0)return e;const n={...hs,...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 us={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 ms(e,t){return t?.[e]??us[e]??e.replace(/_/g," ").replace(/^\w/,a=>a.toUpperCase())}function qa(e){if(typeof e!="string")return!1;const t=Number(e);return Number.isFinite(t)&&t>0}function fs(e){const t=typeof e=="number"?e:typeof e=="string"?Number(e):NaN;return Number.isFinite(t)&&t>0}function bs(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 vs(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 d=document.createElement("div");d.className="gengage-chat-comparison-recommended-body",d.classList.add("gds-clickable"),d.tabIndex=0,d.setAttribute("role","button"),d.setAttribute("aria-label",t.name);const p=document.createElement("div");if(p.className="gengage-chat-comparison-recommended-media",t.imageUrl&&Pe(t.imageUrl)){const y=document.createElement("img");y.src=t.imageUrl,y.alt=t.name,y.loading="lazy",y.addEventListener("error",()=>{y.style.display="none"},{once:!0}),p.appendChild(y)}else{const y=document.createElement("div");y.className="gengage-chat-comparison-recommended-placeholder",y.setAttribute("aria-hidden","true"),p.appendChild(y)}d.appendChild(p);const h=document.createElement("div");h.className="gengage-chat-comparison-recommended-info";const m=document.createElement("div");m.className="gengage-chat-comparison-recommended-title",m.textContent=t.name,h.appendChild(m);const u=document.createElement("div");if(u.className="gengage-chat-comparison-recommended-meta",fs(t.rating)&&u.appendChild(bs(t.rating)),qa(t.price)){const y=document.createElement("div");y.className="gengage-chat-comparison-recommended-price",y.textContent=G(t.price,e.pricing),u.appendChild(y)}if(u.childElementCount>0&&h.appendChild(u),e.recommendedText){const y=document.createElement("p");y.className="gengage-chat-comparison-recommended-text",y.innerHTML=Ae(e.recommendedText),h.appendChild(y)}d.appendChild(h);const f=()=>{o({sku:t.sku,name:t.name})};if(d.addEventListener("click",f),d.addEventListener("keydown",y=>{y.key!=="Enter"&&y.key!==" "||(y.preventDefault(),f())}),l.appendChild(d),r.length>0){const y=document.createElement("div");y.className="gengage-chat-comparison-highlights",y.dataset.gengagePart="comparison-highlights";const M=document.createElement("div");M.className="gengage-chat-comparison-highlights-label",M.textContent=s?.highlightsLabel??"Key Highlights",y.appendChild(M);const C=document.createElement("ul");for(const P of r){const w=document.createElement("li");w.textContent=P,C.appendChild(w)}y.appendChild(C),l.appendChild(y)}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 d=document.createElement("span");d.className="gengage-chat-comparison-key-differences-summary-label",d.textContent=s?.keyDifferencesLabel??"Key Differences";const p=document.createElement("span");p.className="gengage-chat-comparison-key-differences-summary-meta",p.textContent=s?.viewMoreLabel??"Show More",g.appendChild(d),g.appendChild(p),l.appendChild(g);const h=document.createElement("div");h.className="gengage-chat-comparison-key-differences-content",h.innerHTML=Ae(ys(e.keyDifferencesHtml)),l.appendChild(h),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 d=document.createElement("ul");for(const p of i)_s(d,p);d.childElementCount>0&&l.appendChild(d),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"),d=document.createElement("tr"),p=document.createElement("th");d.appendChild(p);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 y=document.createElement("div");y.className="gengage-chat-comparison-table-header-cell gengage-chat-comparison-table-header-cell--clickable gds-clickable",y.tabIndex=0,y.setAttribute("role","button"),y.setAttribute("aria-label",u.name),y.title=u.name;const M=()=>{o({sku:u.sku,name:u.name})};if(y.addEventListener("click",M),y.addEventListener("keydown",P=>{P.key!=="Enter"&&P.key!==" "||(P.preventDefault(),M())}),u.imageUrl&&Pe(u.imageUrl)){const P=document.createElement("img");P.src=u.imageUrl,P.alt=u.name,P.loading="lazy",P.addEventListener("error",()=>{P.style.display="none"},{once:!0}),y.appendChild(P)}else{const P=document.createElement("div");P.className="gengage-chat-comparison-table-header-img-placeholder",P.setAttribute("aria-hidden","true"),y.appendChild(P)}const C=document.createElement("div");if(C.className="gengage-chat-comparison-table-product-name",C.textContent=u.name,y.appendChild(C),qa(u.price)){const P=document.createElement("div");P.className="gengage-chat-comparison-table-price",P.textContent=G(u.price,e.pricing),y.appendChild(P)}f.appendChild(y),d.appendChild(f)}g.appendChild(d),l.appendChild(g);const h=document.createElement("tbody");for(const u of n){const f=document.createElement("tr"),y=document.createElement("td");y.className="gengage-chat-comparison-label",y.textContent=ms(u.label,s?.criteriaLabels),f.appendChild(y);for(let M=0;M<u.values.length;M++){const C=document.createElement("td");a[M]?.sku===t?.sku&&(C.className="gengage-chat-comparison-selected gds-comparison-table-winner-cell"),C.textContent=u.values[M]??"",f.appendChild(C)}h.appendChild(f)}l.appendChild(h);const m=document.createElement("div");m.className="gengage-chat-comparison-table-wrapper",m.dataset.gengagePart="comparison-table-wrapper",m.appendChild(l),c.appendChild(m)}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 d=g[0],p=g[g.length-1];l.shiftKey&&document.activeElement===d?(l.preventDefault(),p.focus()):!l.shiftKey&&document.activeElement===p&&(l.preventDefault(),d.focus())}),c}function ys(e){if(/<[uo]l[\s>]/i.test(e)||/<li[\s>]/i.test(e))return e;const t=e.split(`
|
|
59
|
-
`).filter(a=>a.trim());return t.length<=1?e:"<ul>"+t.map(a=>`<li>${a.trim()}</li>`).join("")+"</ul>"}function _s(e,t){const a=Ae(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=Ae(o.innerHTML),e.appendChild(s)}return}const i=document.createElement("li");xs(t)?i.innerHTML=a:i.textContent=t,e.appendChild(i)}function xs(e){return/<\/?[a-z][\s\S]*>/i.test(e)}function pt(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 Xt="General",Va=220,ws=6;function ks(e){if(typeof e!="string")return[Xt];const t=e.split(/[,;|/]+/).map(a=>a.trim().replace(/\s+/g," ")).filter(a=>a.length>0);return t.length===0?[Xt]:Array.from(new Set(t.map(a=>a.toLocaleLowerCase()))).map(a=>t.find(n=>n.toLocaleLowerCase()===a)??Xt)}function Cs(e){return e==="positive"||e==="negative"||e==="neutral"?e:"neutral"}function Ss(e){if(typeof e!="string")return"";const t=e.trim().replace(/\s+/g," ");return t.length<=Va?t:`${t.slice(0,Va-3).trimEnd()}...`}function Es(e){return e.positive>e.negative?"positive":e.negative>e.positive?"negative":"neutral"}function Ps(e){return pt(e==="positive"?["M7 17 17 7","M7 7h10v10"]:e==="negative"?["M7 7 17 17","M17 7v10H7"]:["M5 12h14"],14)}function As(e,t="1 customer mentions",a="customers mention"){return e===1?t:`${e} ${a}`}function Ts(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=Cs(u.review_class),y=Ss(u.review_text),M=ks(u.review_tag);for(const C of M){const P=C.toLocaleLowerCase();let w=i.get(P);if(w||(w={key:P,label:C,mentions:0,positive:0,negative:0,neutral:0,snippets:[]},i.set(P,w)),w.mentions+=1,f==="positive"?w.positive+=1:f==="negative"?w.negative+=1:w.neutral+=1,y.length>0&&w.snippets.length<ws&&!w.snippets.some(N=>N.text===y)){const N={text:y,tone:f};u.review_rating!==void 0&&String(u.review_rating).length>0&&(N.rating=u.review_rating),w.snippets.push(N)}}}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 d=document.createElement("div");d.className="gengage-chat-review-subjects gds-toolbar gds-toolbar-compact";const p=document.createElement("section");p.className="gengage-chat-review-detail gds-evidence-card";const h=()=>{for(;p.firstChild;)p.removeChild(p.firstChild);if(!g)return;const u=o.find(C=>C.key===g);if(!u)return;const f=document.createElement("div");f.className="gengage-chat-review-detail-meta";const y=document.createElement("span");if(y.className="gengage-chat-review-detail-mentions",y.textContent=`${As(u.mentions,t?.reviewCustomersMentionSingular,t?.reviewCustomersMentionPlural)} "${u.label}"`,f.appendChild(y),u.positive>0){const C=document.createElement("span");C.className="gengage-chat-review-detail-positive",C.textContent=`${u.positive} ${s}`,f.appendChild(C)}if(u.negative>0){const C=document.createElement("span");C.className="gengage-chat-review-detail-negative",C.textContent=`${u.negative} ${c}`,f.appendChild(C)}p.appendChild(f);const M=document.createElement("div");M.className="gengage-chat-review-snippets";for(const C of u.snippets){const P=document.createElement("article");P.className="gengage-chat-review-snippet",P.dataset.tone=C.tone;const w=document.createElement("div");if(w.className="gengage-chat-review-snippet-text",w.textContent=`"${C.text}"`,P.appendChild(w),C.rating!==void 0&&String(C.rating).length>0){const N=document.createElement("div");N.className="gengage-chat-review-snippet-rating",N.textContent=`★ ${String(C.rating)}`,P.appendChild(N)}M.appendChild(P)}p.appendChild(M)},m=()=>{for(const u of d.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=Es(u),y=document.createElement("button");y.type="button",y.className="gengage-chat-review-subject gds-chip",y.dataset.subjectKey=u.key,y.dataset.tone=f;const M=document.createElement("span");M.className="gengage-chat-review-subject-icon",M.appendChild(Ps(f)),y.appendChild(M);const C=document.createElement("span");C.className="gengage-chat-review-subject-label",C.textContent=u.label,y.appendChild(C);const P=document.createElement("span");P.className="gengage-chat-review-subject-count",P.textContent=`(${u.mentions})`,y.appendChild(P),y.addEventListener("click",()=>{g=u.key,m(),h()}),d.appendChild(y)}return a.appendChild(d),m(),h(),a.appendChild(p),a}function Qt(e){return Number.isFinite(e)?Math.max(0,Math.min(5,e)):0}function Ga(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Wa(e){const t=Qt(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 Re(e){e.addEventListener("error",()=>{e.style.display="none"},{once:!0})}function Ls(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 tt(e,t){if(e.productPriceUi?.showCampaignReason===!0)return Ls(t)}function ht(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 yt(e){const t=document.createElement("div");return t.className="gengage-chat-campaign-reason",t.textContent=e,t}function _t(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(Pe(i))return i}}const a=e.productPriceUi?.campaignBadgeLogoUrl;if(typeof a=="string"&&a.trim()){const n=a.trim();if(Pe(n))return n}}function xt(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,Re(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 Ka(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 Is={winner:"roleWinner",best_value:"roleBestValue",best_alternative:"roleBestAlternative"};function Ya(e,t){if(!e||!t)return null;const a=Is[e];return a?t[a]??e:e}function Ns(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 zs(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&&Pe(s)){const l=document.createElement("img");l.className="gengage-chat-ai-toppick-img",l.dataset.gengagePart="ai-top-pick-image",ge(l,"src",s),l.loading="lazy",l.alt=t,Re(l),i.appendChild(l)}const c=Ka(e);if(c&&!r?.skipOverlayActions){const l=document.createElement("div");if(l.className="gengage-chat-product-card-img-actions",n.onFavoriteToggle){const h=document.createElement("button");h.className="gengage-chat-favorite-btn",h.type="button",h.dataset.gengageFavoriteSku=c,h.setAttribute("aria-label",n.i18n?.addToFavoritesLabel??"Add to favorites");const m=n.favoritedSkus?.has(c)??!1;m&&h.classList.add("gengage-chat-favorite-btn--active"),h.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${m?"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>`,h.addEventListener("click",u=>{u.stopPropagation(),h.classList.toggle("gengage-chat-favorite-btn--active"),h.querySelector("svg")?.setAttribute("fill",h.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),n.onFavoriteToggle?.(c,o)}),l.appendChild(h)}const g=n.i18n?.findSimilarLabel??"Find Similar",d=document.createElement("button");d.className="gengage-chat-find-similar-pill",d.type="button",d.setAttribute("aria-label",g),d.dataset.tooltip=g,d.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 p=document.createElement("span");p.className="gengage-chat-find-similar-pill-text",p.textContent=g,d.appendChild(p),d.addEventListener("click",h=>{h.stopPropagation(),n.onAction({title:g,type:"findSimilar",payload:{sku:c,...s?{image_url:s}:{}}})}),l.appendChild(d),i.appendChild(l)}a.appendChild(i)}function Ms(e,t,a){const n=e.price,r=e.originalPrice;if(!n)return;const i=tt(a,e),o=ht(a,e),s=!!(r&&r!==n),c=!!(i&&s),l=_t(a,e),g=document.createElement("div");if(g.className="gengage-chat-ai-toppick-price",g.dataset.gengagePart="ai-top-pick-price",c){const d=xt({reasonText:i,salePriceFormatted:G(n,a.pricing),...l!==void 0?{logoUrl:l}:{}});if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline"),g.appendChild(d);const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=G(r,a.pricing),g.appendChild(p),g.appendChild(h)}else{const p=document.createElement("span");p.className="gengage-chat-ai-toppick-original-price",p.textContent=G(r,a.pricing),g.appendChild(p),g.appendChild(document.createTextNode(" ")),g.appendChild(d)}t.appendChild(g);return}if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-price-current",d.textContent=G(n,a.pricing);const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=G(r,a.pricing),g.appendChild(d),g.appendChild(p),g.appendChild(h)}else if(s){const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=G(r,a.pricing),g.appendChild(d),g.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=G(n,a.pricing),g.appendChild(p)}else{const d=document.createElement("span");d.className="gengage-chat-ai-toppick-price-current",d.textContent=G(n,a.pricing),g.appendChild(d)}if(i){const d=document.createElement("div");d.className="gengage-chat-ai-toppick-price-stack",d.appendChild(yt(i)),d.appendChild(g),t.appendChild(d)}else t.appendChild(g)}function Bs(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 Ja(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=Ka(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",w=>{w.target.closest(".gengage-chat-ai-toppick-cta")||w.target.closest(".gengage-chat-favorite-btn")||w.target.closest(".gengage-chat-find-similar-pill")||t.onProductClick?.({sku:i,url:o})})):g&&(n.classList.add("gds-clickable"),n.addEventListener("click",w=>{w.target.closest(".gengage-chat-ai-toppick-cta")||w.target.closest(".gengage-chat-favorite-btn")||w.target.closest(".gengage-chat-find-similar-pill")||t.onAction(g)}));const d=r.name||"Product image",p=!a&&t.isMobile===!0,h=a?Ya(e.role,t.i18n)??t.i18n?.roleWinner??"TOP MATCH":Ya(e.role,t.i18n);if(h&&!p){const w=document.createElement("span");w.className="gengage-chat-ai-toppick-badge gds-badge",w.dataset.gengagePart="ai-top-pick-role-badge",w.textContent=h,n.appendChild(w)}const m=document.createElement("div");m.className="gengage-chat-ai-toppick-top-row",m.dataset.gengagePart="ai-top-pick-top-row",zs(e,d,m,t,{skipOverlayActions:p});const u=document.createElement("div");if(u.className="gengage-chat-ai-toppick-body",u.dataset.gengagePart="ai-top-pick-body",h&&p){const w=document.createElement("div");w.className="gengage-chat-ai-toppick-role-line",w.dataset.gengagePart="ai-top-pick-role-line",w.textContent=h,u.appendChild(w)}const f=r.name;if(f){const w=document.createElement("div");w.className="gengage-chat-ai-toppick-name",w.dataset.gengagePart="ai-top-pick-name",w.textContent=f,u.appendChild(w)}const y=Ns(r);y&&u.appendChild(y),Ms(r,u,t),e.labels&&e.labels.length>0&&u.appendChild(Ds(e.labels)),m.appendChild(u),n.appendChild(m);const M=document.createElement("div");if(M.className="gengage-chat-ai-toppick-detail",M.dataset.gengagePart="ai-top-pick-detail",a)Bs(e,M);else{const w=typeof e.reason=="string"?e.reason.trim():"";if(w){const N=document.createElement("p");N.className="gengage-chat-ai-toppick-snippet",N.dataset.gengagePart="ai-top-pick-snippet",N.textContent=w,M.appendChild(N)}}M.childNodes.length>0&&n.appendChild(M);const C=!!(i&&t.topPicksLoadingSku===i),P=(l||g)&&!p;if(C||l||g){const w=document.createElement("div");if(w.className="gengage-chat-ai-toppick-spinner",w.dataset.gengagePart="ai-top-pick-spinner",w.style.display=C?"":"none",n.appendChild(w),P){const N=document.createElement("button");N.className="gengage-chat-ai-toppick-cta gds-btn gds-btn-primary",N.dataset.gengagePart="ai-top-pick-cta",N.type="button",N.textContent=l?t.i18n?.addToCartButton??"Add to Cart":t.i18n?.viewDetails??"View Details",N.addEventListener("click",R=>{if(R.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){t.onProductClick({sku:i,url:o});return}t.onAction(g)}}),n.appendChild(N)}}return n}function Rs(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("h3");r.className="gengage-chat-ai-top-picks-title",r.dataset.gengagePart="ai-top-picks-title",r.textContent=t.i18n?.aiTopPicksTitle??"Top Picks",a.appendChild(r);const i=document.createElement("div");i.className="gengage-chat-ai-top-picks-scroll",i.dataset.gengagePart="ai-top-picks-scroll";const o=n[0];if(i.appendChild(Ja(o,t,!0)),n.length>1){const s=document.createElement("div");s.className="gengage-chat-ai-top-picks-rest",s.dataset.gengagePart="ai-top-picks-rest";for(let c=1;c<n.length;c++){const l=n[c],g=l.role==="winner";s.appendChild(Ja(l,t,g))}i.appendChild(s)}return a.appendChild(i),a}function Ds(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 Os(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(pt(["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 m=document.createElement("div");m.className="gengage-chat-grounding-review-subtitle",m.dataset.gengagePart="grounding-review-subtitle",m.textContent=(t.i18n?.groundingReviewSubtitle??"{count} yorum mevcut").replace("{count}",i),l.appendChild(m)}a.appendChild(l);const d=document.createElement("span");d.className="gengage-chat-grounding-review-cta",d.dataset.gengagePart="grounding-review-cta";const p=document.createElement("span");p.textContent=s,d.appendChild(p);const h=document.createElement("span");return h.className="gengage-chat-grounding-review-cta-icon",h.appendChild(pt(["M5 12h14","M15 8l4 4-4 4"],14)),d.appendChild(h),a.appendChild(d),o&&(a.classList.add("gds-clickable"),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t.onAction(o)),a.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),t.onAction(o))})),a}function $s(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 Fs(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($s(s))),s.image&&Pe(s.image)){const p=document.createElement("img");p.className="gengage-chat-grouping-card-img",p.dataset.gengagePart="ai-grouping-card-image",p.src=s.image,p.alt=s.name,p.width=64,p.height=64,c.appendChild(p)}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 p=document.createElement("div");p.className="gengage-chat-grouping-card-labels",p.dataset.gengagePart="ai-grouping-card-labels";for(const h of s.labels.slice(0,2)){const m=document.createElement("span");m.className="gengage-chat-grouping-card-label gds-chip",m.textContent=h,p.appendChild(m)}l.appendChild(p)}c.appendChild(l);const d=document.createElement("span");d.className="gengage-chat-grouping-card-arrow",d.textContent="↳",c.insertBefore(d,c.firstChild),o.appendChild(c)}return a.appendChild(o),a}function Hs(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&&Pe(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 Xa(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 d=document.createElement("div");d.className="gengage-chat-comparison-floating-warning",d.setAttribute("role","status"),d.setAttribute("aria-live","polite"),d.textContent=r,c.appendChild(d)}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]}})}),i.appendChild(g),t.onToggleComparisonSku){const d=document.createElement("button");d.className="gengage-chat-comparison-floating-close gds-btn gds-btn-ghost gds-icon-btn",d.dataset.gengagePart="comparison-dock-close",d.type="button",d.setAttribute("aria-label",t.i18n?.closeAriaLabel??"Close"),d.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>',d.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),t.onToggleComparisonSku?.("")}),i.appendChild(d)}return i}function Us(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 js(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 d=g===l;o[g].classList.toggle("gengage-chat-categories-tab--active",d),o[g].classList.toggle("is-active",d),o[g].setAttribute("aria-selected",String(d)),o[g].tabIndex=d?0:-1,s[g].style.display=d?"":"none"}};for(let l=0;l<a.length;l++){const g=a[l],d=`gengage-cat-tab-${l}`,p=`gengage-cat-panel-${l}`,h=document.createElement("button");h.className="gengage-chat-categories-tab gds-tab",h.type="button",h.dataset.gengagePart="categories-tab",h.id=d,h.setAttribute("role","tab"),h.setAttribute("aria-controls",p),h.setAttribute("aria-selected",String(l===0)),h.tabIndex=l===0?0:-1,l===0&&h.classList.add("gengage-chat-categories-tab--active","is-active"),h.textContent=g.groupName,h.addEventListener("click",()=>c(l)),h.addEventListener("keydown",u=>{let f=-1;u.key==="ArrowRight"||u.key==="ArrowDown"?f=(l+1)%a.length:u.key==="ArrowLeft"||u.key==="ArrowUp"?f=(l-1+a.length)%a.length:u.key==="Home"?f=0:u.key==="End"&&(f=a.length-1),f>=0&&(u.preventDefault(),c(f),o[f].focus())}),o.push(h),i.appendChild(h);const m=document.createElement("div");m.className="gengage-chat-categories-grid",m.dataset.gengagePart="categories-panel",m.id=p,m.setAttribute("role","tabpanel"),m.setAttribute("aria-labelledby",d),l!==0&&(m.style.display="none");for(const u of g.products){const f=Zs(u,t);m.appendChild(f)}s.push(m)}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 d=document.createElement("button");d.className="gengage-chat-categories-filter-tag gds-chip",d.type="button",d.dataset.gengagePart="categories-filter-tag",d.textContent=g.title,g.action&&d.addEventListener("click",()=>{t.onAction(g.action)}),l.appendChild(d)}r.appendChild(l)}return r}function Zs(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&&Pe(e.imageUrl)){const i=document.createElement("img");i.className="gengage-chat-product-card-img",i.src=e.imageUrl,i.alt=e.name,i.loading="lazy",Re(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=G(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 qs(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 Vs(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",h=>{h.target.closest("a")||t.onProductSelect?.(a)});const r=a.imageUrl;if(r&&fe(r)){const h=document.createElement("div");h.className="gengage-chat-product-summary__image",h.dataset.gengagePart="product-summary-image";const m=document.createElement("img");m.loading="lazy",ge(m,"src",r),m.alt=a.name||"Product image",Re(m),h.appendChild(m),n.appendChild(h)}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 h=document.createElement("div");h.className="gengage-chat-product-summary__name",h.dataset.gengagePart="product-summary-name";const m=o&&!s.toLowerCase().startsWith(o.toLowerCase())?`${o} ${s}`:s;h.textContent=m,h.title=m,i.appendChild(h)}const c=a.rating,l=a.reviewCount;if(typeof c=="number"&&Number.isFinite(c)&&c>0){const h=document.createElement("div");if(h.className="gengage-chat-product-summary__rating",h.dataset.gengagePart="product-summary-rating",h.appendChild(Wa(c)),typeof l=="number"&&Number.isFinite(l)){const m=document.createElement("span");m.className="gengage-chat-product-summary__review-count",m.textContent=` (${l})`,h.appendChild(m)}i.appendChild(h)}const g=a.price,d=a.originalPrice;if(g){const h=tt(t,a),m=ht(t,a),u=!!(d&&d!==g),f=document.createElement("div");f.className="gengage-chat-product-summary__price",f.dataset.gengagePart="product-summary-price";const y=!!(h&&u),M=_t(t,a);if(y){const C=xt({reasonText:h,salePriceFormatted:G(g,t.pricing),...M!==void 0?{logoUrl:M}:{}});if(u&&m==="inline"){f.classList.add("gengage-chat-product-summary__price--inline"),f.appendChild(C);const P=document.createElement("span");P.className="gengage-chat-product-summary__price-sep",P.setAttribute("aria-hidden","true");const w=document.createElement("span");w.className="gengage-chat-product-summary__price-original",w.textContent=G(d,t.pricing),f.appendChild(P),f.appendChild(w)}else{const P=document.createElement("span");P.className="gengage-chat-product-summary__price-original",P.textContent=G(d,t.pricing),f.appendChild(P),f.appendChild(document.createTextNode(" ")),f.appendChild(C)}i.appendChild(f)}else{if(u&&m==="inline"){f.classList.add("gengage-chat-product-summary__price--inline");const C=document.createElement("span");C.className="gengage-chat-product-summary__price-current",C.textContent=G(g,t.pricing);const P=document.createElement("span");P.className="gengage-chat-product-summary__price-sep",P.setAttribute("aria-hidden","true");const w=document.createElement("span");w.className="gengage-chat-product-summary__price-original",w.textContent=G(d,t.pricing),f.appendChild(C),f.appendChild(P),f.appendChild(w)}else if(u){const C=document.createElement("span");C.className="gengage-chat-product-summary__price-original",C.textContent=G(d,t.pricing),f.appendChild(C),f.appendChild(document.createTextNode(" "));const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=G(g,t.pricing),f.appendChild(P)}else{const C=document.createElement("span");C.className="gengage-chat-product-summary__price-current",C.textContent=G(g,t.pricing),f.appendChild(C)}if(h){const C=document.createElement("div");C.className="gengage-chat-product-summary__price-stack",C.appendChild(yt(h)),C.appendChild(f),i.appendChild(C)}else i.appendChild(f)}}n.appendChild(i);const p=a.url;if(p&&fe(p)){const h=document.createElement("a");h.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",h.dataset.gengagePart="product-summary-cta",ge(h,"href",p),ge(h,"target","_blank"),ge(h,"rel","noopener noreferrer"),h.textContent=t.i18n?.productCtaLabel??"View",n.appendChild(h)}return n}var Gs={PhotoAnalysisCard:({element:e,context:t})=>qo(e,t),BeautyPhotoStep:({element:e,context:t})=>$a(e,t)};function Ws(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 Ks(e,t,a,n,r){const i=document.createElement("div");i.className="gengage-chat-consulting-style-picker";const o=document.createElement("div");o.className="gengage-chat-consulting-style-picker-title",o.textContent=(a==="watch_expert"?r?.i18n?.watchStylesPreparedTitle??"Prepared {count} style directions for you":r?.i18n?.beautyStylesPreparedTitle??"Prepared {count} beauty styles for you").replace("{count}",String(n.length)),i.appendChild(o);const s=document.createElement("div");s.className="gengage-chat-consulting-style-grid",i.appendChild(s);const c=g=>{t.innerHTML="";const d=Array.isArray(g.product_list)?g.product_list:[],p=Array.isArray(g.recommendation_groups)?g.recommendation_groups:[];if(p.length>0){const h=new Map;for(const f of d){const y=typeof f?.sku=="string"?f.sku:void 0;y&&h.set(y,f)}const m=new Set;for(const f of p){const y=Array.isArray(f.skus)?f.skus.filter(L=>typeof L=="string"&&L.trim().length>0):[],M=y.map(L=>(m.add(L),h.get(L))).filter(L=>!!L);if(M.length===0)continue;const C=document.createElement("section");C.className="gengage-chat-consulting-group";const P=document.createElement("div");P.className="gengage-chat-consulting-group-header";const w=document.createElement("h4");w.className="gengage-chat-consulting-group-label";const N=typeof f.label=="string"&&f.label.trim().length>0?f.label:"Öneri";if(w.textContent=y.length>0?`${N} (${y.length})`:N,P.appendChild(w),typeof f.reason=="string"&&f.reason.trim().length>0){const L=document.createElement("p");L.className="gengage-chat-consulting-group-reason",L.textContent=f.reason,P.appendChild(L)}C.appendChild(P);const R=document.createElement("div");R.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",R.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,M.length))));for(const L of M){const Z=wt({type:"ProductCard",props:{product:L}},r??{onAction:()=>{}});R.appendChild(Z)}C.appendChild(R),t.appendChild(C)}const u=d.filter(f=>{const y=typeof f?.sku=="string"?f.sku:"";return y.length>0&&!m.has(y)});if(u.length>0){const f=document.createElement("div");f.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",f.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,u.length))));for(const y of u){const M=wt({type:"ProductCard",props:{product:y}},r??{onAction:()=>{}});f.appendChild(M)}t.appendChild(f)}return}for(const h of d){const m=wt({type:"ProductCard",props:{product:h}},r??{onAction:()=>{}});t.appendChild(m)}};let l=0;n.forEach((g,d)=>{const p=document.createElement("button");p.type="button",p.className="gengage-chat-consulting-style-btn gds-card",d===0&&p.classList.add("gengage-chat-consulting-style-btn--active"),p.setAttribute("aria-label",g.style_label??`Style ${d+1}`);const h=document.createElement("div");h.className="gengage-chat-consulting-style-media";const m=Ws(g.image_url);if(m&&fe(m)){const f=document.createElement("img");f.className="gengage-chat-consulting-style-image",ge(f,"src",m),f.alt=g.style_label??`Style ${d+1}`,f.loading="lazy",Re(f),h.appendChild(f)}const u=document.createElement("span");u.className="gengage-chat-consulting-style-caption",u.textContent=g.style_label??`Style ${d+1}`,h.appendChild(u),p.appendChild(h),p.addEventListener("click",()=>{l!==d&&(l=d,s.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((f,y)=>f.classList.toggle("gengage-chat-consulting-style-btn--active",y===d)),c(g))}),s.appendChild(p)}),e.appendChild(i),c(n[0]??{})}function Ys(e){const t=typeof e.props?.source=="string"?e.props.source:void 0,a=(Array.isArray(e.props?.styleVariations)?e.props.styleVariations:[]).filter(n=>Array.isArray(n.product_list)&&n.product_list.length>0);return{isConsulting:La(t)&&a.length>0,source:t,styleVariations:a}}function Js(e,t,a,n){Ks(e,t,a.source,a.styleVariations,n)}function ea(){return window.innerWidth<768}var Qa={ActionButtons:({element:e,context:t})=>Xs(e,t),ActionButton:({element:e,context:t})=>Qs(e,t),ProductCard:({element:e,context:t})=>wt(e,t),ProductDetailsPanel:({element:e,context:t})=>_c(e,t),ProductGrid:({element:e,spec:t,renderElement:a,context:n})=>Ac(e,t,a,n),ReviewHighlights:({element:e,context:t})=>Ts(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})=>Tc(e,t),AITopPicks:({element:e,context:t})=>Rs(e,t),GroundingReviewCard:({element:e,context:t})=>Os(e,t),AIGroupingCards:({element:e,context:t})=>Fs(e,t),AISuggestedSearchCards:({element:e,context:t})=>Hs(e,t),ProsAndCons:({element:e})=>Us(e),CategoriesContainer:({element:e,context:t})=>js(e,t),HandoffNotice:({element:e,context:t})=>qs(e,t),ProductSummaryCard:({element:e,context:t})=>Vs(e,t),Divider:({element:e})=>Lc(e),...Gs},ta=({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 en(){return{...Qa}}function tn(e,t,a=Qa,n=ta){return Ir({spec:e,context:t,registry:a,containerClassName:"gengage-chat-uispec",unknownRenderer:n})}function Xs(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 Qs(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 an(e,t,a,n,r){e.replaceChildren();const i=ht(t,a),o=!!(r&&n&&r!==n),s=tt(t,a),c=!!(s&&o),l=_t(t,a);if(!n||parseFloat(n)<=0)return;if(c){const d=xt({reasonText:s,salePriceFormatted:G(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});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",p.appendChild(d);const h=document.createElement("span");h.className="gengage-chat-product-card-price-sep",h.setAttribute("aria-hidden","true");const m=document.createElement("span");m.className="gengage-chat-product-card-original-price",m.textContent=G(r,t.pricing),p.appendChild(h),p.appendChild(m),e.appendChild(p);return}if(e.classList.remove("gengage-chat-product-card-price-block--inline"),e.appendChild(d),o){e.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-product-card-original-price",p.textContent=G(r,t.pricing),e.appendChild(p)}return}if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const d=document.createElement("div");d.className="gengage-chat-product-card-price-row";const p=document.createElement("span");p.className="gengage-chat-product-card-current-price",p.textContent=G(n,t.pricing);const h=document.createElement("span");h.className="gengage-chat-product-card-price-sep",h.setAttribute("aria-hidden","true");const m=document.createElement("span");m.className="gengage-chat-product-card-original-price",m.textContent=G(r,t.pricing),d.appendChild(p),d.appendChild(h),d.appendChild(m),e.appendChild(d);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=G(n,t.pricing),e.appendChild(g),o){e.appendChild(document.createTextNode(" "));const d=document.createElement("span");d.className="gengage-chat-product-card-original-price",d.textContent=G(r,t.pricing),e.appendChild(d)}}function nn(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=tt(t,a),c=!!(s&&o),l=_t(t,a);if(c){const d=xt({reasonText:s,salePriceFormatted:G(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline"),e.appendChild(d);const p=document.createElement("span");p.className="gengage-chat-product-details-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(h)}else{if(o){const p=document.createElement("span");p.className="gengage-chat-product-details-original-price",p.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(document.createTextNode(" "))}e.appendChild(d)}}else if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline");const d=document.createElement("span");d.className="gengage-chat-product-details-current-price",d.textContent=G(n,t.pricing);const p=document.createElement("span");p.className="gengage-chat-product-details-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=G(r,t.pricing),e.appendChild(d),e.appendChild(p),e.appendChild(h)}else{if(o){const p=document.createElement("span");p.className="gengage-chat-product-details-original-price",p.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(document.createTextNode(" "))}const d=document.createElement("span");d.className="gengage-chat-product-details-current-price",d.textContent=G(n,t.pricing),e.appendChild(d)}const g=kt(a,"discountPercent","price_discount_rate");if(typeof g=="number"&&g>0){const d=document.createElement("span");d.className="gengage-chat-product-details-discount-badge",d.textContent=`%${Ga(g)}`,e.appendChild(d)}}function wt(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",I=>{if(!a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")&&!I.target.closest(".gengage-chat-product-card-atc")&&!I.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 I=document.createElement("div");I.className="gengage-chat-product-card-img-wrapper";const v=document.createElement("img");v.className="gengage-chat-product-card-img",v.loading="lazy",ge(v,"src",o);const b=n.name;b&&(v.alt=b),Re(v),I.appendChild(v);const _=n.discountPercent;if(typeof _=="number"&&_>0){const A=document.createElement("span");A.className="gengage-chat-product-card-discount-badge",A.textContent=`%${Ga(_)}`,I.appendChild(A)}const S=document.createElement("div");S.className="gengage-chat-product-card-img-actions";const T=n.sku;if(T&&t.onFavoriteToggle){const A=document.createElement("button");A.className="gengage-chat-favorite-btn",A.type="button",A.dataset.gengageFavoriteSku=T,A.setAttribute("aria-label",t.i18n?.addToFavoritesLabel??"Add to favorites");const U=t.favoritedSkus?.has(T)??!1;U&&A.classList.add("gengage-chat-favorite-btn--active"),A.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${U?"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",F=>{F.stopPropagation(),A.classList.toggle("gengage-chat-favorite-btn--active");const K=A.querySelector("svg");K&&K.setAttribute("fill",A.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),t.onFavoriteToggle(T,n)}),S.appendChild(A)}const z=n.sku,D=t.i18n?.findSimilarLabel??"Find Similar";if(z){const A=document.createElement("button");A.className="gengage-chat-find-similar-pill",A.type="button",A.setAttribute("aria-label",D),A.dataset.tooltip=D,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 U=document.createElement("span");U.className="gengage-chat-find-similar-pill-text",U.textContent=D,A.appendChild(U),A.addEventListener("click",F=>{F.stopPropagation(),t.onAction({title:D,type:"findSimilar",payload:{sku:z,...o?{image_url:o}:{}}})}),S.appendChild(A)}S.childElementCount>0&&I.appendChild(S),a.appendChild(I)}const s=document.createElement("div");s.className="gengage-chat-product-card-body";const c=n.brand;if(c){const I=document.createElement("div");I.className="gengage-chat-product-card-brand",I.textContent=c,s.appendChild(I)}const l=n.rating,g=n.reviewCount,d=n.price,p=n.originalPrice,h=n.price_async,m=tt(t,n),u=ht(t,n),f=!!(m||p&&d&&p!==d&&parseFloat(d)>0&&u==="inline"),y=typeof l=="number"&&Number.isFinite(l)&&l>0,M=document.createElement("div");M.className="gengage-chat-product-card-meta-row";const C=document.createElement("div");C.className="gengage-chat-product-card-price gengage-chat-product-card-price-block";const P=f?(()=>{const I=document.createElement("div");return I.className="gengage-chat-product-card-price-stack",m&&I.appendChild(yt(m)),I.appendChild(C),I})():C;if(h===!0){const I=document.createElement("span");I.className="gengage-chat-price-skeleton",C.appendChild(I),setTimeout(()=>{I.parentElement&&(d&&parseFloat(d)>0?an(C,t,n,d,n.originalPrice):I.remove())},300)}else d&&parseFloat(d)>0&&an(C,t,n,d,p);if((C.childElementCount>0||h===!0)&&M.appendChild(P),y){const I=document.createElement("div");I.className="gengage-chat-product-card-rating gengage-chat-product-card-rating-compact";const v=Qt(l),b=[`${v.toFixed(1)}`,"out of 5 stars"];typeof g=="number"&&Number.isFinite(g)&&b.push(`(${g} reviews)`),I.setAttribute("aria-label",b.join(" "));const _=document.createElement("span");_.className="gengage-chat-product-card-rating-compact-star",_.setAttribute("aria-hidden","true"),_.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 S=document.createElement("span");S.className="gengage-chat-product-card-rating-compact-value",S.textContent=v.toFixed(1),I.appendChild(_),I.appendChild(S),M.appendChild(I)}M.childElementCount===0&&(M.classList.add("gengage-chat-product-card-meta-row--empty"),M.setAttribute("aria-hidden","true")),s.appendChild(M);const w=n.name;if(w){const I=document.createElement("div");I.className="gengage-chat-product-card-name",I.textContent=w,I.title=w,s.appendChild(I)}const N=n.inStock;if(typeof N=="boolean"){const I=document.createElement("div");I.className=`gengage-chat-product-card-stock ${N?"is-in-stock":"is-out-of-stock"}`,I.textContent=N?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",s.appendChild(I)}a.appendChild(s);const R=n.url,L=n.sku,Z=n.cartCode,te=!!(Z&&L&&N!==!1),X=t.i18n?.productCtaLabel??"View";if(te){const I=document.createElement("div");I.className="gengage-chat-product-card-buy-footer";const v=document.createElement("button");v.type="button",v.className="gengage-chat-product-card-buy-trigger",v.textContent=X,v.addEventListener("click",b=>{b.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??X,type:"addToCart",payload:{sku:L,cartCode:Z,quantity:1}})}),I.appendChild(v),a.appendChild(I)}else if(i){const I=document.createElement("button");I.className="gengage-chat-product-card-cta",I.type="button",I.textContent=i.type==="launchSingleProduct"?X:i.title||X,I.addEventListener("click",v=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){v.stopPropagation();return}t.onAction(i)}),a.appendChild(I)}else if(R&&fe(R)){const I=document.createElement("a");I.className="gengage-chat-product-card-cta",ge(I,"href",R),ge(I,"target","_blank"),ge(I,"rel","noopener noreferrer"),I.textContent=X,I.addEventListener("click",v=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){v.preventDefault(),v.stopPropagation();return}t.onProductClick&&L&&(v.preventDefault(),t.onProductClick({sku:L,url:R}))}),a.appendChild(I)}if(t.comparisonSelectMode&&L&&t.onToggleComparisonSku){const I=document.createElement("div");I.className="gengage-chat-comparison-select-wrapper";const v=t.comparisonSelectedSkus?.includes(L)??!1;v&&I.classList.add("gengage-chat-comparison-select-wrapper--selected");const b=n.name??L,_=t.i18n?.comparisonSelectCardHint??"Tap anywhere on the card to add or remove it from comparison.";I.setAttribute("role","group"),I.setAttribute("aria-label",`${String(b)}. ${_}`);const S=document.createElement("button");S.type="button",S.className="gengage-chat-comparison-checkbox",S.dataset.selected=v?"true":"false",S.setAttribute("aria-pressed",v?"true":"false");const T=document.createElement("span");T.className="gengage-chat-comparison-checkbox-icon",T.innerHTML=v?'<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 z=document.createElement("span");z.className="gengage-chat-comparison-checkbox-label",z.textContent=v?t.i18n?.comparisonSelectedLabel??"Selected":t.i18n?.comparisonSelectLabel??"Select to compare",S.appendChild(T),S.appendChild(z),S.addEventListener("click",A=>{A.stopPropagation(),t.onToggleComparisonSku?.(L)});const D=document.createElement("div");return D.className="gengage-chat-comparison-card-hint",D.setAttribute("aria-hidden","true"),D.textContent=_,I.addEventListener("click",A=>{A.target.closest(".gengage-chat-comparison-checkbox")||(A.stopPropagation(),t.onToggleComparisonSku?.(L))}),I.appendChild(S),I.appendChild(D),I.appendChild(a),I}return a}var rn=new Set(["color","colour","renk","renk kodu","color code"]),ec=new Set(["size","beden","boyut"]),tc=new Set(["finish","bitiş","bitişi"]),ac=["variants","variantOptions","variant_options","productVariants","product_variants","options"],nc=new Set(["H2","H3","H4","P","BR","UL","OL","LI","STRONG","B","EM","I"]),rc=new Set(["SCRIPT","STYLE","NOSCRIPT","IFRAME","OBJECT","EMBED"]);function be(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 kt(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 Ct(e,...t){for(const a of t){const n=e[a];if(typeof n=="boolean")return n}}function ic(e,...t){for(const a of t){const n=e[a];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function oc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function sc(e){const t=[...oc(e.images),be(e,"imageUrl","image_url","image")].filter(a=>!!a&&fe(a));return Array.from(new Set(t))}function cc(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 lc(e){const t=be(e,"description_html","descriptionHtml");if(t){const n=cc(t);if(n)return{text:n,html:t}}const a=be(e,"description");return a?{text:a}:void 0}function St(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;const a=t,n=be(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 on(e){const t=St(e.features);return t.length>0?t:St(e.specifications)}function dc(e){const t=e.specifications,a=St(t);if(a.length>0)return Array.isArray(t)?a:Object.fromEntries(a.map(r=>[r.key,r.value]));const n=St(e.features);return n.length>0?n:void 0}function Oe(e,...t){return be(e,...t)}function sn(e,...t){return kt(e,...t)}function cn(e){return Oe(e,"value","option_value","attribute_value","label","title","name","variant_name","sku")}function ln(e){const t=Oe(e,"type","attribute","option_name","attribute_name");return t||(Oe(e,"value")?Oe(e,"name","variant_name"):void 0)}function gc(e){const t=ln(e)?.toLowerCase();return!!(be(e,"color","colour","color_hex","hex","swatch","swatchColor")||t&&rn.has(t))}function dn(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 pc(e){const t=dn(Oe(e,"swatchColor","swatch","color_hex","hex","color","colour"));if(t)return t;if(gc(e))return dn(cn(e))}function hc(e){return Oe(e,"image","imageUrl","image_url","swatchImage","swatch_image")}function uc(e){return sn(e,"price_discounted","priceDiscounted")??Oe(e,"price_discounted","priceDiscounted")??sn(e,"price")??Oe(e,"price")}function mc(e){const t=e.trim().toLowerCase();return rn.has(t)||ec.has(t)||tc.has(t)}function fc(e){const t=e.trim().toLowerCase();return t==="renk kodu"?"Renk":t==="color code"?"Color":e.trim()}function bc(e){for(const t of ac){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 vc(e){const t=bc(e);if(t)return t;const a=be(e,"sku"),n=Ct(e,"inStock","in_stock"),r=[],i=new Set,o=(c,l)=>{if(!mc(c)||typeof l!="string"&&typeof l!="number"&&typeof l!="boolean")return;const g=String(l).trim();if(!g)return;const d=fc(c),p=`${d.toLowerCase()}:${g.toLowerCase()}`;i.has(p)||(i.add(p),r.push({name:d,value:g,sku:a,inStock:n}))},s=ic(e,"facetHits","facet_hits");if(s)for(const[c,l]of Object.entries(s))o(c,l);for(const c of on(e))o(c.key,c.value);return r}function yc(e,t){const a=Array.from(new Set(e.map(ln).filter(n=>!!n)));return a.length===1?`${e.length} ${a[0]}`:t.i18n?.variantsLabel??"Variants"}function _c(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=be(n,"name"),i=be(n,"brand"),o=be(n,"sku"),s=be(n,"cartCode","cart_code"),c=be(n,"price"),l=be(n,"originalPrice","price_original"),g=Ct(n,"price_async"),d=tt(t,n),p=ht(t,n),h=!!(l&&c&&l!==c),m=Ct(n,"inStock","in_stock"),u=kt(n,"reviewCount","review_count"),f=kt(n,"rating"),y=sc(n),M=on(n).slice(0,4);if(y.length>1){const b=document.createElement("div");b.className="gengage-chat-product-details-media gengage-chat-product-details-gallery gengage-chat-product-details-img-wrap";const _=document.createElement("img");_.className="gengage-chat-product-details-img",ge(_,"src",y[0]),_.alt=r??"Product image",Re(_),b.appendChild(_);const S=document.createElement("div");S.className="gengage-chat-product-gallery-thumbs";const T=6;let z=null,D=0;const A=t.i18n,U=A?.galleryPrevAriaLabel??"Previous image",F=A?.galleryNextAriaLabel??"Next image",K=B=>B==="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>',ee=document.createElement("button");ee.type="button",ee.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--prev gds-btn gds-btn-ghost gds-icon-btn",ee.setAttribute("aria-label",U),ee.innerHTML=K("prev");const ae=document.createElement("button");ae.type="button",ae.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--next gds-btn gds-btn-ghost gds-icon-btn",ae.setAttribute("aria-label",F),ae.innerHTML=K("next");const de=()=>{ee.disabled=D<=0,ae.disabled=D>=y.length-1},q=B=>{if(B<0||B>=y.length||B===D)return;const J=y[B];if(!J)return;ge(_,"src",J);const O=S.querySelectorAll(".gengage-chat-product-gallery-thumb");z&&z.classList.remove("gengage-chat-product-gallery-thumb--active"),B<T&&O[B]?(O[B].classList.add("gengage-chat-product-gallery-thumb--active"),z=O[B]):z=null,D=B,de()};for(let B=0;B<y.length;B++){const J=y[B];if(B>=T)break;const O=document.createElement("img");O.className="gengage-chat-product-gallery-thumb",B===0&&(O.classList.add("gengage-chat-product-gallery-thumb--active"),z=O),ge(O,"src",J),O.alt=`${r??"Product"} ${B+1}`,O.width=48,O.height=48,Re(O),O.addEventListener("click",()=>{q(B)}),S.appendChild(O)}if(y.length>T){const B=document.createElement("span");B.className="gengage-chat-product-gallery-thumb-more",B.textContent=`+${y.length-T}`,S.appendChild(B)}ee.addEventListener("click",B=>{B.stopPropagation(),q(D-1)}),ae.addEventListener("click",B=>{B.stopPropagation(),q(D+1)}),de();let _e=0;const j=50;_.addEventListener("touchstart",B=>{_e=B.changedTouches[0].clientX},{passive:!0}),_.addEventListener("touchend",B=>{const J=B.changedTouches[0].clientX,O=_e-J;Math.abs(O)<j||q(O>0?Math.min(D+1,y.length-1):Math.max(D-1,0))}),b.appendChild(ee),b.appendChild(ae),b.appendChild(S),a.appendChild(b)}else if(y.length===1){const b=document.createElement("div");b.className="gengage-chat-product-details-media gengage-chat-product-details-img-wrap";const _=document.createElement("img");_.className="gengage-chat-product-details-img",_.loading="lazy",ge(_,"src",y[0]),Re(_),_.alt=r??"Product image",b.appendChild(_),a.appendChild(b)}const C=document.createElement("div");if(C.className="gengage-chat-product-details-content",i&&(!r||!r.toLowerCase().startsWith(i.toLowerCase()))){const b=document.createElement("div");b.className="gengage-chat-product-details-brand",b.textContent=i,C.appendChild(b)}if(r){const b=document.createElement("h3");b.className="gengage-chat-product-details-title",b.textContent=r,b.title=r,C.appendChild(b)}if(typeof f=="number"&&Number.isFinite(f)&&f>0){const b=document.createElement(o?"button":"div");b.className="gengage-chat-product-details-rating",o&&(b.type="button",b.classList.add("gengage-chat-product-details-rating--clickable"),b.setAttribute("aria-label",t.i18n?.groundingReviewCta??"Read Reviews"),b.addEventListener("click",()=>{t.onAction({title:t.i18n?.customerReviewsTitle??"Customer Reviews",type:"reviewSummary",payload:{sku:o}})})),b.appendChild(Wa(f));const _=document.createElement("span");if(_.className="gengage-chat-product-details-rating-value",_.textContent=Qt(f).toFixed(1),b.appendChild(_),typeof u=="number"&&Number.isFinite(u)){const S=document.createElement("span");S.className="gengage-chat-product-details-review-count",S.textContent=` (${u})`,b.appendChild(S)}C.appendChild(b)}{let b=C;if(d){const S=document.createElement("div");S.className="gengage-chat-product-details-price-stack",S.appendChild(yt(d)),C.appendChild(S),b=S}const _=document.createElement("div");if(_.className="gengage-chat-product-details-price",g===!0){const S=document.createElement("span");S.className="gengage-chat-price-skeleton",_.appendChild(S),b.appendChild(_),setTimeout(()=>{if(S.parentElement)if(c&&parseFloat(c)>0)nn(_,t,n,c,l,p,h);else{const T=_.parentElement;_.remove(),T?.classList.contains("gengage-chat-product-details-price-stack")&&T.remove()}},300)}else if(c&&parseFloat(c)>0)nn(_,t,n,c,l,p,h),b.appendChild(_);else if(d){const S=b;S.classList.contains("gengage-chat-product-details-price-stack")&&S.remove()}}if(typeof m=="boolean"){const b=document.createElement("div");b.className=`gengage-chat-product-details-stock ${m?"is-in-stock":"is-out-of-stock"}`,b.textContent=m?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",C.appendChild(b)}const P=n.promotions;if(P&&P.length>0){const b=document.createElement("div");b.className="gengage-chat-product-details-promos";for(const _ of P.slice(0,3)){if(!_||/%(0(\.0+)?)\s/.test(_))continue;const S=document.createElement("span");S.className="gengage-chat-product-details-promo-badge",S.textContent=_,S.title=_,b.appendChild(S)}b.childElementCount>0&&C.appendChild(b)}if(M.length>0){const b=document.createElement("dl");b.className="gengage-chat-product-details-facts";for(const _ of M){const S=document.createElement("div");S.className="gengage-chat-product-details-fact";const T=document.createElement("dt");T.textContent=_.key;const z=document.createElement("dd");z.textContent=_.value,S.appendChild(T),S.appendChild(z),b.appendChild(S)}C.appendChild(b)}const w=vc(n);if(w.length>0){const b=document.createElement("div");b.className="gengage-chat-product-variants";const _=document.createElement("div");_.className="gengage-chat-product-variants-label",_.textContent=yc(w,t),b.appendChild(_);const S=document.createElement("div");S.className="gengage-chat-product-variants-list";for(const T of w){const z=cn(T),D=Oe(T,"sku");if(!z&&!D)continue;const A=document.createElement("button");A.className="gengage-chat-product-variant-btn gds-chip",A.type="button";const U=z??D??"";A.title=U;const F=Ct(T,"in_stock","inStock");D&&o&&D===o?(A.classList.add("gengage-chat-product-variant-btn--active"),A.setAttribute("aria-pressed","true")):A.setAttribute("aria-pressed","false"),F===!1&&(A.classList.add("gengage-chat-product-variant-btn--out"),A.disabled=!0);const K=hc(T),ee=pc(T);if(K&&fe(K)){const q=document.createElement("img");q.className="gengage-chat-product-variant-swatch gengage-chat-product-variant-swatch--image",ge(q,"src",K),q.alt="",q.setAttribute("aria-hidden","true"),Re(q),A.appendChild(q)}else if(ee){const q=document.createElement("span");q.className="gengage-chat-product-variant-swatch",q.setAttribute("aria-hidden","true"),q.style.backgroundColor=ee,A.appendChild(q)}const ae=document.createElement("span");ae.className="gengage-chat-product-variant-label",ae.textContent=U,A.appendChild(ae);const de=uc(T);if(de&&String(de)!==String(c)){const q=document.createElement("span");q.className="gengage-chat-product-variant-price",q.textContent=G(String(de),t.pricing),A.appendChild(q)}if(D&&D!==o){const q=r??"",_e=(typeof T.value=="string"?T.value.trim():"")||(typeof T.name=="string"?T.name.trim():"")||(typeof T.variant_name=="string"?T.variant_name.trim():"")||"",j=q.length>0?_e.length>0&&_e!==q?`${q} (${_e})`:q:U;A.addEventListener("click",()=>{t.onAction({title:j,type:"launchVariant",payload:{sku:D}})})}S.appendChild(A)}S.childElementCount>0&&(b.appendChild(S),C.appendChild(b))}const N=document.createElement("div");N.className="gengage-chat-product-details-actions";const R=e.props?.action;if(R){const b=document.createElement("button");b.className="gengage-chat-product-details-cta gds-btn gds-btn-primary",b.type="button",b.textContent=R.title||t.i18n?.productCtaLabel||"View",b.addEventListener("click",()=>t.onAction(R)),N.appendChild(b)}if(s&&o&&m!==!1){const b=document.createElement("button");b.className="gengage-chat-product-details-atc gds-btn gds-btn-primary",b.type="button",b.textContent=t.i18n?.addToCartButton??"Add to Cart",b.addEventListener("click",()=>{t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:o,cartCode:s,quantity:1}})}),N.appendChild(b)}const L=be(n,"url");if(!R&&L&&fe(L)){const b=document.createElement("a");b.className="gengage-chat-product-details-cta gds-btn gds-btn-secondary",ge(b,"href",L),ge(b,"target","_blank"),ge(b,"rel","noopener noreferrer"),b.textContent=t.i18n?.viewOnSiteLabel??t.i18n?.productCtaLabel??"View on Site",b.addEventListener("click",_=>{t.onProductClick&&o&&(_.preventDefault(),t.onProductClick({sku:o,url:L}))}),N.appendChild(b)}const Z=L;if(Z&&fe(Z)){let z=function(A,U){const F=document.createElementNS(S,"circle");F.setAttribute("cx",A),F.setAttribute("cy",U),F.setAttribute("r","3"),T.appendChild(F)},D=function(A,U,F,K){const ee=document.createElementNS(S,"line");ee.setAttribute("x1",A),ee.setAttribute("y1",U),ee.setAttribute("x2",F),ee.setAttribute("y2",K),T.appendChild(ee)};var I=z,v=D;const b=document.createElement("button");b.className="gengage-chat-product-details-share gds-btn gds-btn-ghost gds-icon-btn",b.type="button";const _=t.i18n?.shareButton??"Share";b.title=_,b.setAttribute("aria-label",_);const S="http://www.w3.org/2000/svg",T=document.createElementNS(S,"svg");T.setAttribute("width","18"),T.setAttribute("height","18"),T.setAttribute("viewBox","0 0 24 24"),T.setAttribute("fill","none"),T.setAttribute("stroke","currentColor"),T.setAttribute("stroke-width","2"),T.setAttribute("stroke-linecap","round"),T.setAttribute("stroke-linejoin","round"),z("18","5"),z("6","12"),z("18","19"),D("8.59","13.51","15.42","17.49"),D("15.41","6.51","8.59","10.49"),b.appendChild(T),b.addEventListener("click",async()=>{try{navigator.share?await navigator.share({title:r??"",url:Z}):navigator.clipboard&&(await navigator.clipboard.writeText(Z),b.classList.add("gengage-chat-product-details-share--copied"),setTimeout(()=>b.classList.remove("gengage-chat-product-details-share--copied"),1500))}catch{}}),N.appendChild(b)}N.childElementCount>0&&C.appendChild(N),a.appendChild(C);const te=lc(n),X=dc(n);return(te||X)&&a.appendChild(kc(te,X,t)),a}function aa(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(rc.has(a))return null;if(!nc.has(a)){const r=document.createDocumentFragment();for(const i of Array.from(t.childNodes)){const o=aa(i);o&&r.appendChild(o)}return r}const n=document.createElement(a.toLowerCase());for(const r of Array.from(t.childNodes)){const i=aa(r);i&&n.appendChild(i)}return n}function xc(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 wc(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=>aa(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}}xc(e,t.text)}function kc(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",wc(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(([d,p])=>({key:d,value:p}));for(const d of g){const p=document.createElement("tr"),h=document.createElement("td");h.className="gengage-chat-product-specs-key",h.textContent=d.key;const m=document.createElement("td");m.className="gengage-chat-product-specs-value",m.textContent=d.value,p.appendChild(h),p.appendChild(m),l.appendChild(p)}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 gn(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 Cc(){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 Sc(){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 Ec(){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 pn(e,t){return e.type===t.type&&e.direction===t.direction}function hn(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 Pc(e,t,a,n){const r=hn(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 Ac(e,t,a,n){const r=document.createElement("div");r.className="gengage-chat-product-grid-wrapper";const i=Ys(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 p=document.createElement("div");p.className="gengage-chat-product-sort-toolbar",p.setAttribute("role","toolbar"),p.setAttribute("aria-label",n.i18n?.sortToolbarAriaLabel??"Sort products");let h=n.productSort??{type:"related"};const m=[{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 y=n.i18n?.sortToolbarAriaLabel??"Sort products",M=document.createElement("span");M.className="gengage-chat-product-sort-trigger-icon";const C=document.createElement("span");C.className="gengage-chat-product-sort-trigger-label";const P=v=>{const b=m.find(_=>pn(_.sortState,v))??m[0];C.textContent=b.label,M.innerHTML=gn(b.icon),u.dataset.sortIcon=b.icon,f.setAttribute("aria-label",`${y}: ${b.label}`),f.title=b.label};P(h);const w=document.createElement("span");w.className="gengage-chat-product-sort-trigger-chevron",w.innerHTML=Cc(),f.appendChild(M),f.appendChild(C),f.appendChild(w);const N=document.createElement("div");N.className="gengage-chat-product-sort-menu gds-menu",N.hidden=!0,N.setAttribute("role","listbox"),N.setAttribute("aria-label",y);const R=p.ownerDocument;let L=null;const Z=()=>{N.hidden=!0,u.classList.remove("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","false"),L?.abort(),L=null},te=v=>{u.classList.contains("gengage-chat-product-sort-dropdown--open")&&(u.contains(v.target)||Z())},X=v=>{v.key==="Escape"&&(v.preventDefault(),Z())},I=()=>{N.hidden=!1,u.classList.add("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","true"),L=new AbortController;const{signal:v}=L;R.addEventListener("click",te,{signal:v}),R.addEventListener("keydown",X,{capture:!0,signal:v})};f.addEventListener("click",v=>{v.stopPropagation(),u.classList.contains("gengage-chat-product-sort-dropdown--open")?Z():I()});for(const v of m){const b=document.createElement("button");b.type="button",b.className="gengage-chat-product-sort-option gds-menu-option",b.setAttribute("role","option");const _=pn(h,v.sortState);b.setAttribute("aria-selected",_?"true":"false"),_&&b.classList.add("gengage-chat-product-sort-option--active","gds-menu-option-active");const S=v.sortState.type==="related"?"related":`price-${v.sortState.direction??""}`;b.dataset.sortKey=S;const T=document.createElement("span");T.className="gengage-chat-product-sort-option-icon",T.innerHTML=gn(v.icon);const z=document.createElement("span");z.className="gengage-chat-product-sort-option-label",z.textContent=v.label;const D=document.createElement("span");D.className="gengage-chat-product-sort-option-check",D.innerHTML=Sc(),D.setAttribute("aria-hidden","true"),_||D.classList.add("gengage-chat-product-sort-option-check--hidden"),b.appendChild(T),b.appendChild(z),b.appendChild(D),b.addEventListener("click",()=>{h=v.sortState,n.onSortChange?.(v.sortState),Pc(c,s,t,v.sortState),N.querySelectorAll(".gengage-chat-product-sort-option").forEach(A=>{const U=A,F=U.dataset.sortKey===S;U.classList.toggle("gengage-chat-product-sort-option--active",F),U.classList.toggle("gds-menu-option-active",F),U.setAttribute("aria-selected",F?"true":"false"),U.querySelector(".gengage-chat-product-sort-option-check")?.classList.toggle("gengage-chat-product-sort-option-check--hidden",!F)}),P(v.sortState),Z()}),N.appendChild(b)}if(u.appendChild(f),u.appendChild(N),p.appendChild(u),n.onToggleComparisonSku){const v=document.createElement("button");v.className="gengage-chat-comparison-toggle-btn gds-btn gds-btn-ghost",v.type="button",n.comparisonSelectMode&&v.classList.add("gengage-chat-comparison-toggle-btn--active"),n.isStreaming&&v.classList.add("gengage-chat-comparison-toggle-btn--hidden");const b=document.createElement("span");b.className="gengage-chat-comparison-toggle-icon",b.innerHTML=Ec();const _=document.createElement("span");_.className="gengage-chat-comparison-toggle-label";const S=n.i18n?.compareSelected??"Compare";_.textContent=S,v.setAttribute("aria-label",S),v.title=S,v.appendChild(b),v.appendChild(_),v.addEventListener("click",()=>{n.onToggleComparisonSku?.("")}),p.appendChild(v)}if(l){p.classList.add("gengage-chat-product-sort-toolbar--inline");const v=document.createElement("div");v.className="gengage-chat-product-grid-head";const b=document.createElement("span");b.className="gengage-chat-product-grid-head-title",b.textContent=l,v.appendChild(b);const _=document.createElement("div");_.className="gengage-chat-product-grid-head-actions",_.appendChild(p),v.appendChild(_),r.appendChild(v)}else r.appendChild(p)}else if(l){const p=document.createElement("div");p.className="gengage-chat-product-grid-head";const h=document.createElement("span");h.className="gengage-chat-product-grid-head-title",h.textContent=l,p.appendChild(h),r.appendChild(p)}if(o)Js(r,c,i,n);else{const p=hn(s,t,n?.productSort);for(const h of p){if(!t.elements[h])continue;const m=a(h);m&&(m.dataset.elementId=h,c.appendChild(m))}}(n?.isMobile??ea())&&c.classList.add("gengage-chat-product-grid--mobile"),r.appendChild(c);const g=e.props?.endOfList;if(!o&&g!==!0&&s.length>0){const p=n?.i18n?.viewMoreLabel??"Show More",h=document.createElement("button");h.className="gengage-chat-product-grid-view-more",h.type="button",h.textContent=p,h.addEventListener("click",()=>{n?.onAction({title:p,type:"moreProductList",payload:{}})}),r.appendChild(h)}const d=n?.isMobile??ea();if(n?.comparisonSelectMode&&n.comparisonSelectedSkus&&!d){const p=Xa(n.comparisonSelectedSkus,n);r.appendChild(p)}return r}function Tc(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,d=a.productActions;if(!r)return document.createElement("div");const p={recommended:r,products:i,attributes:o,highlights:s,specialCases:c,onProductClick:({sku:m,name:u})=>{t.onProductClick?.({sku:m,url:"",name:u})},pricing:t.pricing};l!==void 0&&(p.recommendedText=l),g!==void 0&&(p.winnerHits=g),d!==void 0&&(p.productActions=d),n!==void 0&&(p.keyDifferencesHtml=n),t.i18n&&(p.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 h=vs(p);return(t.isMobile??ea())&&h.classList.add("gengage-chat-comparison--mobile"),h}function Lc(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 Ic=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","UL","OL","BLOCKQUOTE","PRE","TABLE","SECTION","HR","FIGURE","FIGCAPTION","DL","DT","DD"]);function Nc(e){const t=[];let a=[];for(const n of e)n.nodeType===Node.ELEMENT_NODE&&Ic.has(n.tagName)?(a.length>0&&(t.push(a),a=[]),t.push([n])):a.push(n);return a.length>0&&t.push(a),t}function zc(e){for(const t of e)for(const a of t)if(a.nodeType===Node.ELEMENT_NODE&&(a.tagName==="TABLE"||a.querySelector?.("table")))return!0;return!1}function Mc(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Bc(e){const{container:t,html:a,delayMs:n=30,onTick:r,onComplete:i}=e,o=document.createElement("template");o.innerHTML=a;const s=Nc(o.content.childNodes);if(Mc()||s.length<=1||zc(s))return t.innerHTML=a,i?.(),{complete(){},cancel(){},isRunning:!1};t.innerHTML="";let c=0,l=null,g=!0;function d(){if(!g||c>=s.length){g=!1,i?.();return}const p=s[c],h=document.createElement("span");h.className="gengage-chat-typewriter-block";for(const m of p)h.appendChild(m.cloneNode(!0));t.appendChild(h),c++,r?.(),c<s.length?l=setTimeout(d,n):(g=!1,i?.())}return d(),{complete(){g&&(l!==null&&clearTimeout(l),g=!1,t.innerHTML=a,i?.())},cancel(){l!==null&&clearTimeout(l),g=!1},get isRunning(){return g}}}function un(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function Rc(e){const{container:t,mentions:a,onProductClick:n}=e;if(a.length===0)return;const r=new Map;for(const i of a)i.short_name.length!==0&&r.set(i.short_name.toLowerCase(),i);if(r.size!==0)for(const[i,o]of r){const s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let c=s.nextNode(),l=!1;for(;c&&!l;){const g=c.textContent??"",d=g.toLowerCase().indexOf(i);if(d===-1){c=s.nextNode();continue}const p=d>0?g[d-1]:void 0,h=g[d+o.short_name.length];if(un(p)||un(h)){c=s.nextNode();continue}const m=g.slice(0,d),u=g.slice(d,d+o.short_name.length),f=g.slice(d+o.short_name.length),y=c.parentNode;if(!y){c=s.nextNode();continue}const M=document.createElement("a");M.className="gengage-product-mention",M.textContent=u,M.href="#",M.addEventListener("click",C=>{C.preventDefault(),n(o.sku)}),m&&y.insertBefore(document.createTextNode(m),c),y.insertBefore(M,c),f&&y.insertBefore(document.createTextNode(f),c),y.removeChild(c),l=!0}}}var Dc=new Set(["search","info","review","similar"]),Oc=new Set(["quickAnswer","reviewSummary","searchDiscovery","launchDiscovery","exploreTogetherV2"]);function $c(e){return!!(e.icon&&Dc.has(e.icon)||e.action?.type&&Oc.has(e.action.type))}var Et="gengage_choice_prompter_dismissed",Fc="gengage_choice_prompter_dismissed_global";function Hc(e){const t=document.createElement("div");t.className="gengage-chat-choice-prompter gds-card",t.dataset.gengagePart="choice-prompter";const a=document.createElement("div");a.className="gengage-chat-choice-prompter-copy";const n=document.createElement("div");n.className="gengage-chat-choice-prompter-heading",n.textContent=e.heading,a.appendChild(n);const r=document.createElement("div");r.className="gengage-chat-choice-prompter-suggestion",r.textContent=e.suggestion,a.appendChild(r),t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="gengage-chat-choice-prompter-cta gds-btn gds-btn-primary",i.dataset.gengagePart="choice-prompter-cta",i.textContent=e.ctaLabel,i.addEventListener("click",()=>{na(e.threadId),t.remove(),e.onCtaClick()}),t.appendChild(i);const o=document.createElement("button");return o.type="button",o.className="gengage-chat-choice-prompter-dismiss",o.dataset.gengagePart="choice-prompter-dismiss",o.textContent="×",o.setAttribute("aria-label",e.dismissAriaLabel??"Dismiss"),o.addEventListener("click",()=>{na(e.threadId),t.remove(),e.onDismiss?.()}),t.appendChild(o),t}function Uc(){try{sessionStorage.removeItem(Et),sessionStorage.removeItem(Fc)}catch{}}function jc(e){try{const t=sessionStorage.getItem(Et);return t?JSON.parse(t).includes(e):!1}catch{return!1}}function na(e){try{const t=sessionStorage.getItem(Et),a=t?JSON.parse(t):[];a.includes(e)||a.push(e),sessionStorage.setItem(Et,JSON.stringify(a))}catch{}}function Zc(e){e&&na(e)}var qc="gengage_assistant",Vc=3,Ue="sessions",Te="context",De="payload",Le="favorites";function ut(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error)})}function at(e){return new Promise((t,a)=>{e.oncomplete=()=>t(),e.onerror=()=>a(e.error),e.onabort=()=>a(e.error??new DOMException("Transaction aborted"))})}var Gc=class{constructor(e=qc,t=Vc){this._db=null,this._dbName=e,this._version=t}async open(){return this._db?this._db:new Promise((e,t)=>{const a=indexedDB.open(this._dbName,this._version);a.onupgradeneeded=n=>{const r=a.result,i=n.oldVersion;i<1&&(r.createObjectStore(Ue,{keyPath:["userId","appId","sessionId"]}),r.createObjectStore(Te,{keyPath:["sessionId","threadId"]}),r.createObjectStore(De,{keyPath:["threadId","messageId"]}).createIndex("threadId","threadId",{unique:!1}),r.createObjectStore(Le,{keyPath:["userId","appId","sku"]})),i>=1&&i<2&&(r.objectStoreNames.contains(Ue)&&r.deleteObjectStore(Ue),r.objectStoreNames.contains(De)&&r.deleteObjectStore(De),r.createObjectStore(Ue,{keyPath:["userId","appId","sessionId"]}),r.createObjectStore(De,{keyPath:["threadId","messageId"]}).createIndex("threadId","threadId",{unique:!1}),r.objectStoreNames.contains(Te)||r.createObjectStore(Te,{keyPath:["sessionId","threadId"]})),i<3&&(r.objectStoreNames.contains(Le)||r.createObjectStore(Le,{keyPath:["userId","appId","sku"]}))},a.onsuccess=()=>{this._db=a.result,e(this._db)},a.onerror=()=>t(a.error)})}close(){this._db?.close(),this._db=null}async saveSession(e){const t=this._requireDb().transaction(Ue,"readwrite");t.objectStore(Ue).put(e),await at(t)}async loadSession(e,t,a){return await ut(this._requireDb().transaction(Ue,"readonly").objectStore(Ue).get([e,t,a]))??null}async saveContext(e){const t=this._requireDb().transaction(Te,"readwrite");t.objectStore(Te).put(e),await at(t)}async loadContext(e,t){return await ut(this._requireDb().transaction(Te,"readonly").objectStore(Te).get([e,t]))??null}async deleteContextsAfterThread(e,t){const a=this._requireDb().transaction(Te,"readwrite"),n=a.objectStore(Te).openCursor();await new Promise((r,i)=>{n.onsuccess=()=>{const o=n.result;if(!o){r();return}const s=o.value;if(s.sessionId===e&&s.threadId>t)try{o.delete()}catch{}o.continue()},n.onerror=()=>i(n.error)}),await at(a)}async loadLatestContext(e){const t=this._requireDb().transaction(Te,"readonly").objectStore(Te),a=IDBKeyRange.bound([e,""],[e,""]);return new Promise((n,r)=>{const i=t.openCursor(a,"prev");i.onsuccess=()=>{const o=i.result;n(o?o.value:null)},i.onerror=()=>r(i.error)})}async savePayload(e){const t=this._requireDb().transaction(De,"readwrite");t.objectStore(De).put(e),await at(t)}async loadPayload(e,t){return await ut(this._requireDb().transaction(De,"readonly").objectStore(De).get([e,t]))??null}async loadPayloadsByThread(e){const t=this._requireDb().transaction(De,"readonly").objectStore(De).index("threadId"),a=[];return new Promise((n,r)=>{const i=t.openCursor(IDBKeyRange.only(e));i.onsuccess=()=>{const o=i.result;if(!o){n(a);return}a.push(o.value),o.continue()},i.onerror=()=>r(i.error)})}async saveFavorite(e){const t=this._requireDb().transaction(Le,"readwrite");t.objectStore(Le).put(e),await at(t)}async removeFavorite(e,t,a){const n=this._requireDb().transaction(Le,"readwrite");n.objectStore(Le).delete([e,t,a]),await at(n)}async loadFavorites(e,t){return(await ut(this._requireDb().transaction(Le,"readonly").objectStore(Le).getAll())).filter(a=>a.userId===e&&a.appId===t)}async isFavorite(e,t,a){return await ut(this._requireDb().transaction(Le,"readonly").objectStore(Le).get([e,t,a]))!==void 0}_requireDb(){if(!this._db)throw new Error("GengageIndexedDB: database not open. Call open() first.");return this._db}},Wc=["comparisonTable","groupList","productDetailsSimilars","productList"],Kc=class{constructor(e){this._lockCount=1,this._hiddenByUser=!1,this._lastPanelContentType=null,this._chatShown=!1,this._isFavoritesMode=!1,this._lastExtended=!1,this._onChange=e.onChange;const t=new Set(Wc);e.productDetailsInPanel&&t.add("productDetails"),this._panelContentTypes=t}get isExtended(){return this._lockCount===0&&!this._hiddenByUser&&!this._isFavoritesMode&&this._lastPanelContentType!==null&&this._panelContentTypes.has(this._lastPanelContentType)&&this._chatShown}unlock(){this._lockCount>0&&this._lockCount--,this._checkStateChange()}lock(){this._lockCount++,this._checkStateChange()}setHiddenByUser(e){this._hiddenByUser=e,this._checkStateChange()}setChatShown(e){this._chatShown=e,this._checkStateChange()}setFavoritesMode(e){this._isFavoritesMode=e,this._checkStateChange()}setPanelContentType(e){this._lastPanelContentType=e,this._checkStateChange()}_checkStateChange(){const e=this.isExtended;e!==this._lastExtended&&(this._lastExtended=e,this._onChange(e))}},Yc=class{constructor(e){this.deps=e,this.snapshots=new Map,this._snapshotRebuilders=new Map,this.snapshotTypes=new Map,this.activePanelMessageId=null,this.currentType=null,this.threads=[],this.lastActionType=null}snapshotForMessage(e,t){const a=this.deps.drawer();if(!a?.hasPanelContent()||a.isPanelLoading())return;const n=a.getPanelContentElement();if(!n)return;const r=n.cloneNode(!0);this.snapshots.set(e,r),t&&this._snapshotRebuilders.set(e,t),this.currentType&&this.snapshotTypes.set(e,this.currentType)}restoreForMessage(e){const t=this._snapshotRebuilders.get(e),a=this.snapshots.get(e);if(!t&&!a)return!1;const n=this.deps.shadow(),r=this.deps.drawer();this.activePanelMessageId&&n?.querySelector(`[data-message-id="${CSS.escape(this.activePanelMessageId)}"]`)?.classList.remove("gengage-chat-bubble--active"),n?.querySelector(`[data-message-id="${CSS.escape(e)}"]`)?.classList.add("gengage-chat-bubble--active"),this.activePanelMessageId=e;const i=t?t():a.cloneNode(!0);r?.setPanelContent(i);const o=this.snapshotTypes.get(e);if(r?.setDividerPreviewEnabled(o==="ProductGrid"),o)if(this.currentType=o,i.querySelector(".gengage-chat-product-grid-head-title")&&o==="ProductGrid"){const s=this.deps.currentThreadId();if(s){const c=this.threads.indexOf(s),l=c>0,g=c>=0&&c<this.threads.length-1;this.deps.drawer()?.updatePanelTopBar(l,g,"")}}else this.updateTopBar(o);return!0}notifyExtension(e){const t=this.deps.bridge();e?setTimeout(()=>t?.send("maximize-pdp",{}),350):setTimeout(()=>t?.send("minify-pdp",{}),200)}titleForComponent(e,t){if(t)return t;const a=this.deps.i18n();switch(e){case"ProductDetailsPanel":return a.panelTitleProductDetails;case"ProductGrid":return mn(this.lastActionType)?a.panelTitleSearchResults:a.panelTitleSimilarProducts;case"ComparisonTable":return a.panelTitleComparisonResults;case"AIGroupingCards":return a.panelTitleCategories;default:return""}}updateTopBar(e,t,a){const n=this.deps.currentThreadId();if(!n)return;const r=this.threads.indexOf(n),i=r>0,o=r>=0&&r<this.threads.length-1,s=a!==void 0?a:this.titleForComponent(e,t);this.deps.drawer()?.updatePanelTopBar(i,o,s)}updateTopBarForLoading(e){const t=this.deps.i18n(),a={productDetails:t.panelTitleProductDetails,productList:mn(this.lastActionType)?t.panelTitleSearchResults:t.panelTitleSimilarProducts,comparisonTable:t.panelTitleComparisonResults,groupList:t.panelTitleCategories}[e]??"";if(a){const n=this.deps.currentThreadId(),r=n?this.threads.indexOf(n):-1,i=r>0,o=r>=0&&r<this.threads.length-1;this.deps.drawer()?.updatePanelTopBar(i,o,a)}}updateExtendedMode(e){const t={ComparisonTable:"comparisonTable",AIGroupingCards:"groupList",ProductDetailsPanel:"productDetails",ProductGrid:"productList"}[e]??null;this.deps.extendedModeManager()?.setPanelContentType(t)}navigateBack(){const e=this.deps.currentThreadId();if(!e)return;const t=this.threads.indexOf(e);if(t>0){const a=this.threads[t-1];a&&this.deps.rollbackToThread(a)}}navigateForward(){const e=this.deps.currentThreadId();if(!e)return;const t=this.threads.indexOf(e);if(t>=0&&t<this.threads.length-1){const a=this.threads[t+1];a&&this.deps.rollbackToThread(a)}}toPanelSpec(e){const t=e.elements[e.root];if(!t||t.type!=="ProductCard")return e;const a={...t,type:"ProductDetailsPanel"};return{root:e.root,elements:{...e.elements,[e.root]:a}}}destroy(){this.snapshots.clear(),this._snapshotRebuilders.clear(),this.snapshotTypes.clear(),this.activePanelMessageId=null,this.currentType=null,this.threads=[]}};function mn(e){return e==="user_message"||e==="inputText"}function Jc(e){return e.similarsAppend&&e.currentPanelType==="ProductDetailsPanel"&&e.hasPanelContent&&!e.isPanelLoading?"appendSimilars":e.componentType==="ProductGrid"&&!e.isFirstPanelContentInStream&&e.hasPanelContent&&!e.isPanelLoading?"append":"replace"}var fn=class{constructor(e){this.favoritedSkus=new Set,this._favoritesCache=new Map,this._persistLock=Promise.resolve(),this._db=e}get db(){return this._db}set db(e){this._db=e}async persist(e){if(!this._db)return;const t=this._persistLock;let a;this._persistLock=new Promise(n=>{a=n}),await t;try{await this._persistImpl(e)}finally{a()}}async _persistImpl(e){if(!this._db)return;const t=e.messages.map(n=>{const r={id:n.id,role:n.role,timestamp:n.timestamp,status:n.status==="streaming"?"done":n.status};return n.threadId!==void 0&&(r.threadId=n.threadId),n.content!==void 0&&(r.content=n.content),n.silent&&(r.silent=!0),r}),a={};for(const[n,r]of e.panelSnapshots)r.querySelector(".gengage-chat-panel-skeleton")||(a[n]=r.innerHTML);await this._db.saveSession({userId:e.userId,appId:e.appId,sessionId:e.sessionId,messages:t,currentThreadId:e.currentThreadId,lastThreadId:e.lastThreadId,createdAt:e.chatCreatedAt,panelThreads:e.panelThreads.length>0?e.panelThreads:void 0,thumbnailEntries:e.thumbnailEntries.length>0?e.thumbnailEntries:void 0,panelSnapshotHtml:Object.keys(a).length>0?a:void 0,sku:e.sku}),e.lastBackendContext&&e.currentThreadId&&await this._db.saveContext({sessionId:e.sessionId,threadId:e.currentThreadId,context:e.lastBackendContext});for(const n of e.messages)n.uiSpec&&n.threadId&&await this._db.savePayload({threadId:n.threadId,messageId:n.id,uiSpec:n.uiSpec})}async saveAndOpenURL(e,t,a){try{await t()}catch{}a?.send("openURLInNewTab",{url:e}),fe(e)&&(window.location.href=e)}async loadPayload(e,t){if(!this._db)return null;for(let a=0;a<3;a++){try{const n=await this._db.loadPayload(e,t);if(n)return n.uiSpec}catch{}a<2&&await new Promise(n=>setTimeout(n,100))}return null}async loadFavorites(e,t){if(this._db)try{const a=await this._db.loadFavorites(e,t);for(const n of a)this.favoritedSkus.add(n.sku),this._favoritesCache.set(n.sku,n)}catch{}}getFavoriteProducts(){return[...this._favoritesCache.values()].sort((e,t)=>(t.savedAt??"").localeCompare(e.savedAt??""))}async toggleFavorite(e,t,a,n){if(this.favoritedSkus.has(a))this.favoritedSkus.delete(a),this._favoritesCache.delete(a),this._db&&await this._db.removeFavorite(e,t,a);else{const r={userId:e,appId:t,sku:a,name:n.name,imageUrl:n.imageUrl,price:n.price,savedAt:new Date().toISOString()};this.favoritedSkus.add(a),this._favoritesCache.set(a,r),this._db&&await this._db.saveFavorite(r)}}close(){this._db?.close(),this._db=null}},ra=e=>`${e}:assistant`,bn=class{constructor(){this.groups={},this.pinnedToBottom=!0,this.userInteracting=!1,this.focusedThreadId=null,this.shown=!1,this.lastAutoAnchoredGroupId=null,this.scrollRequest=null,this._nextScrollId=1}setShown(e){this.shown=e,e||(this.userInteracting=!1,this.pinnedToBottom=!0,this.focusedThreadId=null,this.scrollRequest=null)}reset(){this.groups={},this.pinnedToBottom=!0,this.userInteracting=!1,this.focusedThreadId=null,this.lastAutoAnchoredGroupId=null,this.scrollRequest=null}registerAssistantActivity(e){const t=ra(e),a=this.groups[t],n=this.shown&&this.pinnedToBottom&&!this.userInteracting?"active_unread":"unseen";this.groups[t]={id:t,threadId:e,readState:a?.readState==="seen"?n:a?.readState??n,status:"streaming",updatedAt:Date.now()},a?.readState==="seen"&&this.lastAutoAnchoredGroupId===t&&(this.lastAutoAnchoredGroupId=null)}finalizeAssistantGroup(e){const t=ra(e),a=this.groups[t];a&&(a.status="complete",a.updatedAt=Date.now())}setGroupReadStates(e){const t=Date.now();for(const{groupId:a,readState:n}of e){const r=this.groups[a];!r||r.readState===n||(r.readState=n,r.updatedAt=t)}}requestThreadFocus(e,t="smooth"){this.focusedThreadId=e,this.scrollRequest={id:this._nextScrollId++,type:"thread",threadId:e,behavior:t}}requestScrollToBottom(e="smooth"){this.scrollRequest={id:this._nextScrollId++,type:"bottom",behavior:e}}consumeScrollRequest(e){this.scrollRequest?.id===e&&(this.scrollRequest=null)}releaseFocusedThread(){this.focusedThreadId=null}setFocusedThreadId(e){this.focusedThreadId=e}markGroupAutoAnchored(e){this.lastAutoAnchoredGroupId=e}shouldBlockStreamAutoScroll(){return this.shown&&this.userInteracting&&!this.pinnedToBottom}getAssistantReadState(e){return this.groups[ra(e)]?.readState}};function Xc(e,t){for(let a=e.length-1;a>=0;a--){const n=e[a],r=t.getAssistantReadState(n);if(r!==void 0&&r!=="seen")return n}return null}function Qc(e){const{label:t,avatarUrl:a,primaryColor:n,secondaryColor:r="#111827",fontFamily:i="inherit",labelClassName:o="gengage-pill-launcher-label",styleId:s="gengage-pill-launcher-style",mobileBreakpoint:c=768,desktopWidth:l="188px",desktopHeight:g="60px",iconSize:d="46px"}=e,p=`${parseInt(l,10)-14}px`,h=`${parseInt(g,10)-4}px`,m=`${parseInt(d,10)-4}px`,u=`
|
|
59
|
+
`).filter(a=>a.trim());return t.length<=1?e:"<ul>"+t.map(a=>`<li>${a.trim()}</li>`).join("")+"</ul>"}function _s(e,t){const a=Ae(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=Ae(o.innerHTML),e.appendChild(s)}return}const i=document.createElement("li");xs(t)?i.innerHTML=a:i.textContent=t,e.appendChild(i)}function xs(e){return/<\/?[a-z][\s\S]*>/i.test(e)}function pt(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 Xt="General",Va=220,ws=6;function ks(e){if(typeof e!="string")return[Xt];const t=e.split(/[,;|/]+/).map(a=>a.trim().replace(/\s+/g," ")).filter(a=>a.length>0);return t.length===0?[Xt]:Array.from(new Set(t.map(a=>a.toLocaleLowerCase()))).map(a=>t.find(n=>n.toLocaleLowerCase()===a)??Xt)}function Cs(e){return e==="positive"||e==="negative"||e==="neutral"?e:"neutral"}function Ss(e){if(typeof e!="string")return"";const t=e.trim().replace(/\s+/g," ");return t.length<=Va?t:`${t.slice(0,Va-3).trimEnd()}...`}function Es(e){return e.positive>e.negative?"positive":e.negative>e.positive?"negative":"neutral"}function Ps(e){return pt(e==="positive"?["M7 17 17 7","M7 7h10v10"]:e==="negative"?["M7 7 17 17","M17 7v10H7"]:["M5 12h14"],14)}function As(e,t="1 customer mentions",a="customers mention"){return e===1?t:`${e} ${a}`}function Ts(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=Cs(u.review_class),y=Ss(u.review_text),M=ks(u.review_tag);for(const C of M){const P=C.toLocaleLowerCase();let w=i.get(P);if(w||(w={key:P,label:C,mentions:0,positive:0,negative:0,neutral:0,snippets:[]},i.set(P,w)),w.mentions+=1,f==="positive"?w.positive+=1:f==="negative"?w.negative+=1:w.neutral+=1,y.length>0&&w.snippets.length<ws&&!w.snippets.some(N=>N.text===y)){const N={text:y,tone:f};u.review_rating!==void 0&&String(u.review_rating).length>0&&(N.rating=u.review_rating),w.snippets.push(N)}}}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 d=document.createElement("div");d.className="gengage-chat-review-subjects gds-toolbar gds-toolbar-compact";const p=document.createElement("section");p.className="gengage-chat-review-detail gds-evidence-card";const h=()=>{for(;p.firstChild;)p.removeChild(p.firstChild);if(!g)return;const u=o.find(C=>C.key===g);if(!u)return;const f=document.createElement("div");f.className="gengage-chat-review-detail-meta";const y=document.createElement("span");if(y.className="gengage-chat-review-detail-mentions",y.textContent=`${As(u.mentions,t?.reviewCustomersMentionSingular,t?.reviewCustomersMentionPlural)} "${u.label}"`,f.appendChild(y),u.positive>0){const C=document.createElement("span");C.className="gengage-chat-review-detail-positive",C.textContent=`${u.positive} ${s}`,f.appendChild(C)}if(u.negative>0){const C=document.createElement("span");C.className="gengage-chat-review-detail-negative",C.textContent=`${u.negative} ${c}`,f.appendChild(C)}p.appendChild(f);const M=document.createElement("div");M.className="gengage-chat-review-snippets";for(const C of u.snippets){const P=document.createElement("article");P.className="gengage-chat-review-snippet",P.dataset.tone=C.tone;const w=document.createElement("div");if(w.className="gengage-chat-review-snippet-text",w.textContent=`"${C.text}"`,P.appendChild(w),C.rating!==void 0&&String(C.rating).length>0){const N=document.createElement("div");N.className="gengage-chat-review-snippet-rating",N.textContent=`★ ${String(C.rating)}`,P.appendChild(N)}M.appendChild(P)}p.appendChild(M)},m=()=>{for(const u of d.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=Es(u),y=document.createElement("button");y.type="button",y.className="gengage-chat-review-subject gds-chip",y.dataset.subjectKey=u.key,y.dataset.tone=f;const M=document.createElement("span");M.className="gengage-chat-review-subject-icon",M.appendChild(Ps(f)),y.appendChild(M);const C=document.createElement("span");C.className="gengage-chat-review-subject-label",C.textContent=u.label,y.appendChild(C);const P=document.createElement("span");P.className="gengage-chat-review-subject-count",P.textContent=`(${u.mentions})`,y.appendChild(P),y.addEventListener("click",()=>{g=u.key,m(),h()}),d.appendChild(y)}return a.appendChild(d),m(),h(),a.appendChild(p),a}function Qt(e){return Number.isFinite(e)?Math.max(0,Math.min(5,e)):0}function Ga(e){return Number.isFinite(e)?Math.max(0,Math.min(100,Math.round(e))):0}function Wa(e){const t=Qt(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 Re(e){e.addEventListener("error",()=>{e.style.display="none"},{once:!0})}function Ls(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 tt(e,t){if(e.productPriceUi?.showCampaignReason===!0)return Ls(t)}function ht(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 yt(e){const t=document.createElement("div");return t.className="gengage-chat-campaign-reason",t.textContent=e,t}function _t(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(Pe(i))return i}}const a=e.productPriceUi?.campaignBadgeLogoUrl;if(typeof a=="string"&&a.trim()){const n=a.trim();if(Pe(n))return n}}function xt(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,Re(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 Ka(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 Is={winner:"roleWinner",best_value:"roleBestValue",best_alternative:"roleBestAlternative"};function Ya(e,t){if(!e||!t)return null;const a=Is[e];return a?t[a]??e:e}function Ns(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 zs(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&&Pe(s)){const l=document.createElement("img");l.className="gengage-chat-ai-toppick-img",l.dataset.gengagePart="ai-top-pick-image",ge(l,"src",s),l.loading="lazy",l.alt=t,Re(l),i.appendChild(l)}const c=Ka(e);if(c&&!r?.skipOverlayActions){const l=document.createElement("div");if(l.className="gengage-chat-product-card-img-actions",n.onFavoriteToggle){const h=document.createElement("button");h.className="gengage-chat-favorite-btn",h.type="button",h.dataset.gengageFavoriteSku=c,h.setAttribute("aria-label",n.i18n?.addToFavoritesLabel??"Add to favorites");const m=n.favoritedSkus?.has(c)??!1;m&&h.classList.add("gengage-chat-favorite-btn--active"),h.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${m?"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>`,h.addEventListener("click",u=>{u.stopPropagation(),h.classList.toggle("gengage-chat-favorite-btn--active"),h.querySelector("svg")?.setAttribute("fill",h.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),n.onFavoriteToggle?.(c,o)}),l.appendChild(h)}const g=n.i18n?.findSimilarLabel??"Find Similar",d=document.createElement("button");d.className="gengage-chat-find-similar-pill",d.type="button",d.setAttribute("aria-label",g),d.dataset.tooltip=g,d.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 p=document.createElement("span");p.className="gengage-chat-find-similar-pill-text",p.textContent=g,d.appendChild(p),d.addEventListener("click",h=>{h.stopPropagation(),n.onAction({title:g,type:"findSimilar",payload:{sku:c,...s?{image_url:s}:{}}})}),l.appendChild(d),i.appendChild(l)}a.appendChild(i)}function Ms(e,t,a){const n=e.price,r=e.originalPrice;if(!n)return;const i=tt(a,e),o=ht(a,e),s=!!(r&&r!==n),c=!!(i&&s),l=_t(a,e),g=document.createElement("div");if(g.className="gengage-chat-ai-toppick-price",g.dataset.gengagePart="ai-top-pick-price",c){const d=xt({reasonText:i,salePriceFormatted:G(n,a.pricing),...l!==void 0?{logoUrl:l}:{}});if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline"),g.appendChild(d);const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=G(r,a.pricing),g.appendChild(p),g.appendChild(h)}else{const p=document.createElement("span");p.className="gengage-chat-ai-toppick-original-price",p.textContent=G(r,a.pricing),g.appendChild(p),g.appendChild(document.createTextNode(" ")),g.appendChild(d)}t.appendChild(g);return}if(s&&o==="inline"){g.classList.add("gengage-chat-ai-toppick-price--inline");const d=document.createElement("span");d.className="gengage-chat-ai-toppick-price-current",d.textContent=G(n,a.pricing);const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-ai-toppick-original-price",h.textContent=G(r,a.pricing),g.appendChild(d),g.appendChild(p),g.appendChild(h)}else if(s){const d=document.createElement("span");d.className="gengage-chat-ai-toppick-original-price",d.textContent=G(r,a.pricing),g.appendChild(d),g.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-ai-toppick-price-current",p.textContent=G(n,a.pricing),g.appendChild(p)}else{const d=document.createElement("span");d.className="gengage-chat-ai-toppick-price-current",d.textContent=G(n,a.pricing),g.appendChild(d)}if(i){const d=document.createElement("div");d.className="gengage-chat-ai-toppick-price-stack",d.appendChild(yt(i)),d.appendChild(g),t.appendChild(d)}else t.appendChild(g)}function Bs(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 Ja(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=Ka(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",w=>{w.target.closest(".gengage-chat-ai-toppick-cta")||w.target.closest(".gengage-chat-favorite-btn")||w.target.closest(".gengage-chat-find-similar-pill")||t.onProductClick?.({sku:i,url:o})})):g&&(n.classList.add("gds-clickable"),n.addEventListener("click",w=>{w.target.closest(".gengage-chat-ai-toppick-cta")||w.target.closest(".gengage-chat-favorite-btn")||w.target.closest(".gengage-chat-find-similar-pill")||t.onAction(g)}));const d=r.name||"Product image",p=!a&&t.isMobile===!0,h=a?Ya(e.role,t.i18n)??t.i18n?.roleWinner??"TOP MATCH":Ya(e.role,t.i18n);if(h&&!p){const w=document.createElement("span");w.className="gengage-chat-ai-toppick-badge gds-badge",w.dataset.gengagePart="ai-top-pick-role-badge",w.textContent=h,n.appendChild(w)}const m=document.createElement("div");m.className="gengage-chat-ai-toppick-top-row",m.dataset.gengagePart="ai-top-pick-top-row",zs(e,d,m,t,{skipOverlayActions:p});const u=document.createElement("div");if(u.className="gengage-chat-ai-toppick-body",u.dataset.gengagePart="ai-top-pick-body",h&&p){const w=document.createElement("div");w.className="gengage-chat-ai-toppick-role-line",w.dataset.gengagePart="ai-top-pick-role-line",w.textContent=h,u.appendChild(w)}const f=r.name;if(f){const w=document.createElement("div");w.className="gengage-chat-ai-toppick-name",w.dataset.gengagePart="ai-top-pick-name",w.textContent=f,u.appendChild(w)}const y=Ns(r);y&&u.appendChild(y),Ms(r,u,t),e.labels&&e.labels.length>0&&u.appendChild(Ds(e.labels)),m.appendChild(u),n.appendChild(m);const M=document.createElement("div");if(M.className="gengage-chat-ai-toppick-detail",M.dataset.gengagePart="ai-top-pick-detail",a)Bs(e,M);else{const w=typeof e.reason=="string"?e.reason.trim():"";if(w){const N=document.createElement("p");N.className="gengage-chat-ai-toppick-snippet",N.dataset.gengagePart="ai-top-pick-snippet",N.textContent=w,M.appendChild(N)}}M.childNodes.length>0&&n.appendChild(M);const C=!!(i&&t.topPicksLoadingSku===i),P=(l||g)&&!p;if(C||l||g){const w=document.createElement("div");if(w.className="gengage-chat-ai-toppick-spinner",w.dataset.gengagePart="ai-top-pick-spinner",w.style.display=C?"":"none",n.appendChild(w),P){const N=document.createElement("button");N.className="gengage-chat-ai-toppick-cta gds-btn gds-btn-primary",N.dataset.gengagePart="ai-top-pick-cta",N.type="button",N.textContent=l?t.i18n?.addToCartButton??"Add to Cart":t.i18n?.viewDetails??"View Details",N.addEventListener("click",R=>{if(R.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){t.onProductClick({sku:i,url:o});return}t.onAction(g)}}),n.appendChild(N)}}return n}function Rs(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("h3");r.className="gengage-chat-ai-top-picks-title",r.dataset.gengagePart="ai-top-picks-title",r.textContent=t.i18n?.aiTopPicksTitle??"Top Picks",a.appendChild(r);const i=document.createElement("div");i.className="gengage-chat-ai-top-picks-scroll",i.dataset.gengagePart="ai-top-picks-scroll";const o=n[0];if(i.appendChild(Ja(o,t,!0)),n.length>1){const s=document.createElement("div");s.className="gengage-chat-ai-top-picks-rest",s.dataset.gengagePart="ai-top-picks-rest";for(let c=1;c<n.length;c++){const l=n[c],g=l.role==="winner";s.appendChild(Ja(l,t,g))}i.appendChild(s)}return a.appendChild(i),a}function Ds(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 Os(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(pt(["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 m=document.createElement("div");m.className="gengage-chat-grounding-review-subtitle",m.dataset.gengagePart="grounding-review-subtitle",m.textContent=(t.i18n?.groundingReviewSubtitle??"{count} yorum mevcut").replace("{count}",i),l.appendChild(m)}a.appendChild(l);const d=document.createElement("span");d.className="gengage-chat-grounding-review-cta",d.dataset.gengagePart="grounding-review-cta";const p=document.createElement("span");p.textContent=s,d.appendChild(p);const h=document.createElement("span");return h.className="gengage-chat-grounding-review-cta-icon",h.appendChild(pt(["M5 12h14","M15 8l4 4-4 4"],14)),d.appendChild(h),a.appendChild(d),o&&(a.classList.add("gds-clickable"),a.setAttribute("role","button"),a.setAttribute("tabindex","0"),a.addEventListener("click",()=>t.onAction(o)),a.addEventListener("keydown",m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),t.onAction(o))})),a}function $s(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 Fs(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($s(s))),s.image&&Pe(s.image)){const p=document.createElement("img");p.className="gengage-chat-grouping-card-img",p.dataset.gengagePart="ai-grouping-card-image",p.src=s.image,p.alt=s.name,p.width=64,p.height=64,c.appendChild(p)}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 p=document.createElement("div");p.className="gengage-chat-grouping-card-labels",p.dataset.gengagePart="ai-grouping-card-labels";for(const h of s.labels.slice(0,2)){const m=document.createElement("span");m.className="gengage-chat-grouping-card-label gds-chip",m.textContent=h,p.appendChild(m)}l.appendChild(p)}c.appendChild(l);const d=document.createElement("span");d.className="gengage-chat-grouping-card-arrow",d.textContent="↳",c.insertBefore(d,c.firstChild),o.appendChild(c)}return a.appendChild(o),a}function Hs(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&&Pe(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 Xa(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 d=document.createElement("div");d.className="gengage-chat-comparison-floating-warning",d.setAttribute("role","status"),d.setAttribute("aria-live","polite"),d.textContent=r,c.appendChild(d)}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]}})}),i.appendChild(g),t.onToggleComparisonSku){const d=document.createElement("button");d.className="gengage-chat-comparison-floating-close gds-btn gds-btn-ghost gds-icon-btn",d.dataset.gengagePart="comparison-dock-close",d.type="button",d.setAttribute("aria-label",t.i18n?.closeAriaLabel??"Close"),d.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>',d.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),t.onToggleComparisonSku?.("")}),i.appendChild(d)}return i}function Us(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 js(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 d=g===l;o[g].classList.toggle("gengage-chat-categories-tab--active",d),o[g].classList.toggle("is-active",d),o[g].setAttribute("aria-selected",String(d)),o[g].tabIndex=d?0:-1,s[g].style.display=d?"":"none"}};for(let l=0;l<a.length;l++){const g=a[l],d=`gengage-cat-tab-${l}`,p=`gengage-cat-panel-${l}`,h=document.createElement("button");h.className="gengage-chat-categories-tab gds-tab",h.type="button",h.dataset.gengagePart="categories-tab",h.id=d,h.setAttribute("role","tab"),h.setAttribute("aria-controls",p),h.setAttribute("aria-selected",String(l===0)),h.tabIndex=l===0?0:-1,l===0&&h.classList.add("gengage-chat-categories-tab--active","is-active"),h.textContent=g.groupName,h.addEventListener("click",()=>c(l)),h.addEventListener("keydown",u=>{let f=-1;u.key==="ArrowRight"||u.key==="ArrowDown"?f=(l+1)%a.length:u.key==="ArrowLeft"||u.key==="ArrowUp"?f=(l-1+a.length)%a.length:u.key==="Home"?f=0:u.key==="End"&&(f=a.length-1),f>=0&&(u.preventDefault(),c(f),o[f].focus())}),o.push(h),i.appendChild(h);const m=document.createElement("div");m.className="gengage-chat-categories-grid",m.dataset.gengagePart="categories-panel",m.id=p,m.setAttribute("role","tabpanel"),m.setAttribute("aria-labelledby",d),l!==0&&(m.style.display="none");for(const u of g.products){const f=Zs(u,t);m.appendChild(f)}s.push(m)}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 d=document.createElement("button");d.className="gengage-chat-categories-filter-tag gds-chip",d.type="button",d.dataset.gengagePart="categories-filter-tag",d.textContent=g.title,g.action&&d.addEventListener("click",()=>{t.onAction(g.action)}),l.appendChild(d)}r.appendChild(l)}return r}function Zs(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&&Pe(e.imageUrl)){const i=document.createElement("img");i.className="gengage-chat-product-card-img",i.src=e.imageUrl,i.alt=e.name,i.loading="lazy",Re(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=G(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 qs(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 Vs(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",h=>{h.target.closest("a")||t.onProductSelect?.(a)});const r=a.imageUrl;if(r&&fe(r)){const h=document.createElement("div");h.className="gengage-chat-product-summary__image",h.dataset.gengagePart="product-summary-image";const m=document.createElement("img");m.loading="lazy",ge(m,"src",r),m.alt=a.name||"Product image",Re(m),h.appendChild(m),n.appendChild(h)}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 h=document.createElement("div");h.className="gengage-chat-product-summary__name",h.dataset.gengagePart="product-summary-name";const m=o&&!s.toLowerCase().startsWith(o.toLowerCase())?`${o} ${s}`:s;h.textContent=m,h.title=m,i.appendChild(h)}const c=a.rating,l=a.reviewCount;if(typeof c=="number"&&Number.isFinite(c)&&c>0){const h=document.createElement("div");if(h.className="gengage-chat-product-summary__rating",h.dataset.gengagePart="product-summary-rating",h.appendChild(Wa(c)),typeof l=="number"&&Number.isFinite(l)){const m=document.createElement("span");m.className="gengage-chat-product-summary__review-count",m.textContent=` (${l})`,h.appendChild(m)}i.appendChild(h)}const g=a.price,d=a.originalPrice;if(g){const h=tt(t,a),m=ht(t,a),u=!!(d&&d!==g),f=document.createElement("div");f.className="gengage-chat-product-summary__price",f.dataset.gengagePart="product-summary-price";const y=!!(h&&u),M=_t(t,a);if(y){const C=xt({reasonText:h,salePriceFormatted:G(g,t.pricing),...M!==void 0?{logoUrl:M}:{}});if(u&&m==="inline"){f.classList.add("gengage-chat-product-summary__price--inline"),f.appendChild(C);const P=document.createElement("span");P.className="gengage-chat-product-summary__price-sep",P.setAttribute("aria-hidden","true");const w=document.createElement("span");w.className="gengage-chat-product-summary__price-original",w.textContent=G(d,t.pricing),f.appendChild(P),f.appendChild(w)}else{const P=document.createElement("span");P.className="gengage-chat-product-summary__price-original",P.textContent=G(d,t.pricing),f.appendChild(P),f.appendChild(document.createTextNode(" ")),f.appendChild(C)}i.appendChild(f)}else{if(u&&m==="inline"){f.classList.add("gengage-chat-product-summary__price--inline");const C=document.createElement("span");C.className="gengage-chat-product-summary__price-current",C.textContent=G(g,t.pricing);const P=document.createElement("span");P.className="gengage-chat-product-summary__price-sep",P.setAttribute("aria-hidden","true");const w=document.createElement("span");w.className="gengage-chat-product-summary__price-original",w.textContent=G(d,t.pricing),f.appendChild(C),f.appendChild(P),f.appendChild(w)}else if(u){const C=document.createElement("span");C.className="gengage-chat-product-summary__price-original",C.textContent=G(d,t.pricing),f.appendChild(C),f.appendChild(document.createTextNode(" "));const P=document.createElement("span");P.className="gengage-chat-product-summary__price-current",P.textContent=G(g,t.pricing),f.appendChild(P)}else{const C=document.createElement("span");C.className="gengage-chat-product-summary__price-current",C.textContent=G(g,t.pricing),f.appendChild(C)}if(h){const C=document.createElement("div");C.className="gengage-chat-product-summary__price-stack",C.appendChild(yt(h)),C.appendChild(f),i.appendChild(C)}else i.appendChild(f)}}n.appendChild(i);const p=a.url;if(p&&fe(p)){const h=document.createElement("a");h.className="gengage-chat-product-summary__cta gds-chip gds-chip-active",h.dataset.gengagePart="product-summary-cta",ge(h,"href",p),ge(h,"target","_blank"),ge(h,"rel","noopener noreferrer"),h.textContent=t.i18n?.productCtaLabel??"View",n.appendChild(h)}return n}var Gs={PhotoAnalysisCard:({element:e,context:t})=>qo(e,t),BeautyPhotoStep:({element:e,context:t})=>$a(e,t)};function Ws(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 Ks(e,t,a,n,r){const i=document.createElement("div");i.className="gengage-chat-consulting-style-picker";const o=document.createElement("div");o.className="gengage-chat-consulting-style-picker-title",o.textContent=(a==="watch_expert"?r?.i18n?.watchStylesPreparedTitle??"Prepared {count} style directions for you":r?.i18n?.beautyStylesPreparedTitle??"Prepared {count} beauty styles for you").replace("{count}",String(n.length)),i.appendChild(o);const s=document.createElement("div");s.className="gengage-chat-consulting-style-grid",i.appendChild(s);const c=g=>{t.innerHTML="";const d=Array.isArray(g.product_list)?g.product_list:[],p=Array.isArray(g.recommendation_groups)?g.recommendation_groups:[];if(p.length>0){const h=new Map;for(const f of d){const y=typeof f?.sku=="string"?f.sku:void 0;y&&h.set(y,f)}const m=new Set;for(const f of p){const y=Array.isArray(f.skus)?f.skus.filter(L=>typeof L=="string"&&L.trim().length>0):[],M=y.map(L=>(m.add(L),h.get(L))).filter(L=>!!L);if(M.length===0)continue;const C=document.createElement("section");C.className="gengage-chat-consulting-group";const P=document.createElement("div");P.className="gengage-chat-consulting-group-header";const w=document.createElement("h4");w.className="gengage-chat-consulting-group-label";const N=typeof f.label=="string"&&f.label.trim().length>0?f.label:"Öneri";if(w.textContent=y.length>0?`${N} (${y.length})`:N,P.appendChild(w),typeof f.reason=="string"&&f.reason.trim().length>0){const L=document.createElement("p");L.className="gengage-chat-consulting-group-reason",L.textContent=f.reason,P.appendChild(L)}C.appendChild(P);const R=document.createElement("div");R.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",R.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,M.length))));for(const L of M){const Z=wt({type:"ProductCard",props:{product:L}},r??{onAction:()=>{}});R.appendChild(Z)}C.appendChild(R),t.appendChild(C)}const u=d.filter(f=>{const y=typeof f?.sku=="string"?f.sku:"";return y.length>0&&!m.has(y)});if(u.length>0){const f=document.createElement("div");f.className="gengage-chat-product-grid gengage-chat-consulting-group-grid",f.style.setProperty("--consulting-group-columns",String(Math.max(1,Math.min(4,u.length))));for(const y of u){const M=wt({type:"ProductCard",props:{product:y}},r??{onAction:()=>{}});f.appendChild(M)}t.appendChild(f)}return}for(const h of d){const m=wt({type:"ProductCard",props:{product:h}},r??{onAction:()=>{}});t.appendChild(m)}};let l=0;n.forEach((g,d)=>{const p=document.createElement("button");p.type="button",p.className="gengage-chat-consulting-style-btn gds-card",d===0&&p.classList.add("gengage-chat-consulting-style-btn--active"),p.setAttribute("aria-label",g.style_label??`Style ${d+1}`);const h=document.createElement("div");h.className="gengage-chat-consulting-style-media";const m=Ws(g.image_url);if(m&&fe(m)){const f=document.createElement("img");f.className="gengage-chat-consulting-style-image",ge(f,"src",m),f.alt=g.style_label??`Style ${d+1}`,f.loading="lazy",Re(f),h.appendChild(f)}const u=document.createElement("span");u.className="gengage-chat-consulting-style-caption",u.textContent=g.style_label??`Style ${d+1}`,h.appendChild(u),p.appendChild(h),p.addEventListener("click",()=>{l!==d&&(l=d,s.querySelectorAll(".gengage-chat-consulting-style-btn").forEach((f,y)=>f.classList.toggle("gengage-chat-consulting-style-btn--active",y===d)),c(g))}),s.appendChild(p)}),e.appendChild(i),c(n[0]??{})}function Ys(e){const t=typeof e.props?.source=="string"?e.props.source:void 0,a=(Array.isArray(e.props?.styleVariations)?e.props.styleVariations:[]).filter(n=>Array.isArray(n.product_list)&&n.product_list.length>0);return{isConsulting:La(t)&&a.length>0,source:t,styleVariations:a}}function Js(e,t,a,n){Ks(e,t,a.source,a.styleVariations,n)}function ea(){return window.innerWidth<768}var Qa={ActionButtons:({element:e,context:t})=>Xs(e,t),ActionButton:({element:e,context:t})=>Qs(e,t),ProductCard:({element:e,context:t})=>wt(e,t),ProductDetailsPanel:({element:e,context:t})=>_c(e,t),ProductGrid:({element:e,spec:t,renderElement:a,context:n})=>Ac(e,t,a,n),ReviewHighlights:({element:e,context:t})=>Ts(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})=>Tc(e,t),AITopPicks:({element:e,context:t})=>Rs(e,t),GroundingReviewCard:({element:e,context:t})=>Os(e,t),AIGroupingCards:({element:e,context:t})=>Fs(e,t),AISuggestedSearchCards:({element:e,context:t})=>Hs(e,t),ProsAndCons:({element:e})=>Us(e),CategoriesContainer:({element:e,context:t})=>js(e,t),HandoffNotice:({element:e,context:t})=>qs(e,t),ProductSummaryCard:({element:e,context:t})=>Vs(e,t),Divider:({element:e})=>Lc(e),...Gs},ta=({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 en(){return{...Qa}}function tn(e,t,a=Qa,n=ta){return Ir({spec:e,context:t,registry:a,containerClassName:"gengage-chat-uispec",unknownRenderer:n})}function Xs(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 Qs(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 an(e,t,a,n,r){e.replaceChildren();const i=ht(t,a),o=!!(r&&n&&r!==n),s=tt(t,a),c=!!(s&&o),l=_t(t,a);if(!n||parseFloat(n)<=0)return;if(c){const d=xt({reasonText:s,salePriceFormatted:G(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});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",p.appendChild(d);const h=document.createElement("span");h.className="gengage-chat-product-card-price-sep",h.setAttribute("aria-hidden","true");const m=document.createElement("span");m.className="gengage-chat-product-card-original-price",m.textContent=G(r,t.pricing),p.appendChild(h),p.appendChild(m),e.appendChild(p);return}if(e.classList.remove("gengage-chat-product-card-price-block--inline"),e.appendChild(d),o){e.appendChild(document.createTextNode(" "));const p=document.createElement("span");p.className="gengage-chat-product-card-original-price",p.textContent=G(r,t.pricing),e.appendChild(p)}return}if(o&&i==="inline"){e.classList.add("gengage-chat-product-card-price-block--inline");const d=document.createElement("div");d.className="gengage-chat-product-card-price-row";const p=document.createElement("span");p.className="gengage-chat-product-card-current-price",p.textContent=G(n,t.pricing);const h=document.createElement("span");h.className="gengage-chat-product-card-price-sep",h.setAttribute("aria-hidden","true");const m=document.createElement("span");m.className="gengage-chat-product-card-original-price",m.textContent=G(r,t.pricing),d.appendChild(p),d.appendChild(h),d.appendChild(m),e.appendChild(d);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=G(n,t.pricing),e.appendChild(g),o){e.appendChild(document.createTextNode(" "));const d=document.createElement("span");d.className="gengage-chat-product-card-original-price",d.textContent=G(r,t.pricing),e.appendChild(d)}}function nn(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=tt(t,a),c=!!(s&&o),l=_t(t,a);if(c){const d=xt({reasonText:s,salePriceFormatted:G(n,t.pricing),...l!==void 0?{logoUrl:l}:{}});if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline"),e.appendChild(d);const p=document.createElement("span");p.className="gengage-chat-product-details-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(h)}else{if(o){const p=document.createElement("span");p.className="gengage-chat-product-details-original-price",p.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(document.createTextNode(" "))}e.appendChild(d)}}else if(o&&i==="inline"){e.classList.add("gengage-chat-product-details-price--inline");const d=document.createElement("span");d.className="gengage-chat-product-details-current-price",d.textContent=G(n,t.pricing);const p=document.createElement("span");p.className="gengage-chat-product-details-price-sep",p.setAttribute("aria-hidden","true");const h=document.createElement("span");h.className="gengage-chat-product-details-original-price",h.textContent=G(r,t.pricing),e.appendChild(d),e.appendChild(p),e.appendChild(h)}else{if(o){const p=document.createElement("span");p.className="gengage-chat-product-details-original-price",p.textContent=G(r,t.pricing),e.appendChild(p),e.appendChild(document.createTextNode(" "))}const d=document.createElement("span");d.className="gengage-chat-product-details-current-price",d.textContent=G(n,t.pricing),e.appendChild(d)}const g=kt(a,"discountPercent","price_discount_rate");if(typeof g=="number"&&g>0){const d=document.createElement("span");d.className="gengage-chat-product-details-discount-badge",d.textContent=`%${Ga(g)}`,e.appendChild(d)}}function wt(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",I=>{if(!a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")&&!I.target.closest(".gengage-chat-product-card-atc")&&!I.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 I=document.createElement("div");I.className="gengage-chat-product-card-img-wrapper";const v=document.createElement("img");v.className="gengage-chat-product-card-img",v.loading="lazy",ge(v,"src",o);const b=n.name;b&&(v.alt=b),Re(v),I.appendChild(v);const _=n.discountPercent;if(typeof _=="number"&&_>0){const A=document.createElement("span");A.className="gengage-chat-product-card-discount-badge",A.textContent=`%${Ga(_)}`,I.appendChild(A)}const S=document.createElement("div");S.className="gengage-chat-product-card-img-actions";const T=n.sku;if(T&&t.onFavoriteToggle){const A=document.createElement("button");A.className="gengage-chat-favorite-btn",A.type="button",A.dataset.gengageFavoriteSku=T,A.setAttribute("aria-label",t.i18n?.addToFavoritesLabel??"Add to favorites");const U=t.favoritedSkus?.has(T)??!1;U&&A.classList.add("gengage-chat-favorite-btn--active"),A.innerHTML=`<svg width="14" height="14" viewBox="0 0 24 24" fill="${U?"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",F=>{F.stopPropagation(),A.classList.toggle("gengage-chat-favorite-btn--active");const W=A.querySelector("svg");W&&W.setAttribute("fill",A.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none"),t.onFavoriteToggle(T,n)}),S.appendChild(A)}const z=n.sku,D=t.i18n?.findSimilarLabel??"Find Similar";if(z){const A=document.createElement("button");A.className="gengage-chat-find-similar-pill",A.type="button",A.setAttribute("aria-label",D),A.dataset.tooltip=D,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 U=document.createElement("span");U.className="gengage-chat-find-similar-pill-text",U.textContent=D,A.appendChild(U),A.addEventListener("click",F=>{F.stopPropagation(),t.onAction({title:D,type:"findSimilar",payload:{sku:z,...o?{image_url:o}:{}}})}),S.appendChild(A)}S.childElementCount>0&&I.appendChild(S),a.appendChild(I)}const s=document.createElement("div");s.className="gengage-chat-product-card-body";const c=n.brand;if(c){const I=document.createElement("div");I.className="gengage-chat-product-card-brand",I.textContent=c,s.appendChild(I)}const l=n.rating,g=n.reviewCount,d=n.price,p=n.originalPrice,h=n.price_async,m=tt(t,n),u=ht(t,n),f=!!(m||p&&d&&p!==d&&parseFloat(d)>0&&u==="inline"),y=typeof l=="number"&&Number.isFinite(l)&&l>0,M=document.createElement("div");M.className="gengage-chat-product-card-meta-row";const C=document.createElement("div");C.className="gengage-chat-product-card-price gengage-chat-product-card-price-block";const P=f?(()=>{const I=document.createElement("div");return I.className="gengage-chat-product-card-price-stack",m&&I.appendChild(yt(m)),I.appendChild(C),I})():C;if(h===!0){const I=document.createElement("span");I.className="gengage-chat-price-skeleton",C.appendChild(I),setTimeout(()=>{I.parentElement&&(d&&parseFloat(d)>0?an(C,t,n,d,n.originalPrice):I.remove())},300)}else d&&parseFloat(d)>0&&an(C,t,n,d,p);if((C.childElementCount>0||h===!0)&&M.appendChild(P),y){const I=document.createElement("div");I.className="gengage-chat-product-card-rating gengage-chat-product-card-rating-compact";const v=Qt(l),b=[`${v.toFixed(1)}`,"out of 5 stars"];typeof g=="number"&&Number.isFinite(g)&&b.push(`(${g} reviews)`),I.setAttribute("aria-label",b.join(" "));const _=document.createElement("span");_.className="gengage-chat-product-card-rating-compact-star",_.setAttribute("aria-hidden","true"),_.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 S=document.createElement("span");S.className="gengage-chat-product-card-rating-compact-value",S.textContent=v.toFixed(1),I.appendChild(_),I.appendChild(S),M.appendChild(I)}M.childElementCount===0&&(M.classList.add("gengage-chat-product-card-meta-row--empty"),M.setAttribute("aria-hidden","true")),s.appendChild(M);const w=n.name;if(w){const I=document.createElement("div");I.className="gengage-chat-product-card-name",I.textContent=w,I.title=w,s.appendChild(I)}const N=n.inStock;if(typeof N=="boolean"){const I=document.createElement("div");I.className=`gengage-chat-product-card-stock ${N?"is-in-stock":"is-out-of-stock"}`,I.textContent=N?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",s.appendChild(I)}a.appendChild(s);const R=n.url,L=n.sku,Z=n.cartCode,te=!!(Z&&L&&N!==!1),X=t.i18n?.productCtaLabel??"View";if(te){const I=document.createElement("div");I.className="gengage-chat-product-card-buy-footer";const v=document.createElement("button");v.type="button",v.className="gengage-chat-product-card-buy-trigger",v.textContent=X,v.addEventListener("click",b=>{b.stopPropagation(),t.onAction({title:t.i18n?.addToCartButton??X,type:"addToCart",payload:{sku:L,cartCode:Z,quantity:1}})}),I.appendChild(v),a.appendChild(I)}else if(i){const I=document.createElement("button");I.className="gengage-chat-product-card-cta",I.type="button",I.textContent=i.type==="launchSingleProduct"?X:i.title||X,I.addEventListener("click",v=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){v.stopPropagation();return}t.onAction(i)}),a.appendChild(I)}else if(R&&fe(R)){const I=document.createElement("a");I.className="gengage-chat-product-card-cta",ge(I,"href",R),ge(I,"target","_blank"),ge(I,"rel","noopener noreferrer"),I.textContent=X,I.addEventListener("click",v=>{if(a.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){v.preventDefault(),v.stopPropagation();return}t.onProductClick&&L&&(v.preventDefault(),t.onProductClick({sku:L,url:R}))}),a.appendChild(I)}if(t.comparisonSelectMode&&L&&t.onToggleComparisonSku){const I=document.createElement("div");I.className="gengage-chat-comparison-select-wrapper";const v=t.comparisonSelectedSkus?.includes(L)??!1;v&&I.classList.add("gengage-chat-comparison-select-wrapper--selected");const b=n.name??L,_=t.i18n?.comparisonSelectCardHint??"Tap anywhere on the card to add or remove it from comparison.";I.setAttribute("role","group"),I.setAttribute("aria-label",`${String(b)}. ${_}`);const S=document.createElement("button");S.type="button",S.className="gengage-chat-comparison-checkbox",S.dataset.selected=v?"true":"false",S.setAttribute("aria-pressed",v?"true":"false");const T=document.createElement("span");T.className="gengage-chat-comparison-checkbox-icon",T.innerHTML=v?'<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 z=document.createElement("span");z.className="gengage-chat-comparison-checkbox-label",z.textContent=v?t.i18n?.comparisonSelectedLabel??"Selected":t.i18n?.comparisonSelectLabel??"Select to compare",S.appendChild(T),S.appendChild(z),S.addEventListener("click",A=>{A.stopPropagation(),t.onToggleComparisonSku?.(L)});const D=document.createElement("div");return D.className="gengage-chat-comparison-card-hint",D.setAttribute("aria-hidden","true"),D.textContent=_,I.addEventListener("click",A=>{A.target.closest(".gengage-chat-comparison-checkbox")||(A.stopPropagation(),t.onToggleComparisonSku?.(L))}),I.appendChild(S),I.appendChild(D),I.appendChild(a),I}return a}var rn=new Set(["color","colour","renk","renk kodu","color code"]),ec=new Set(["size","beden","boyut"]),tc=new Set(["finish","bitiş","bitişi"]),ac=["variants","variantOptions","variant_options","productVariants","product_variants","options"],nc=new Set(["H2","H3","H4","P","BR","UL","OL","LI","STRONG","B","EM","I"]),rc=new Set(["SCRIPT","STYLE","NOSCRIPT","IFRAME","OBJECT","EMBED"]);function be(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 kt(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 Ct(e,...t){for(const a of t){const n=e[a];if(typeof n=="boolean")return n}}function ic(e,...t){for(const a of t){const n=e[a];if(n&&typeof n=="object"&&!Array.isArray(n))return n}}function oc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function sc(e){const t=[...oc(e.images),be(e,"imageUrl","image_url","image")].filter(a=>!!a&&fe(a));return Array.from(new Set(t))}function cc(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 lc(e){const t=be(e,"description_html","descriptionHtml");if(t){const n=cc(t);if(n)return{text:n,html:t}}const a=be(e,"description");return a?{text:a}:void 0}function St(e){return Array.isArray(e)?e.map(t=>{if(!t||typeof t!="object")return null;const a=t,n=be(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 on(e){const t=St(e.features);return t.length>0?t:St(e.specifications)}function dc(e){const t=e.specifications,a=St(t);if(a.length>0)return Array.isArray(t)?a:Object.fromEntries(a.map(r=>[r.key,r.value]));const n=St(e.features);return n.length>0?n:void 0}function Oe(e,...t){return be(e,...t)}function sn(e,...t){return kt(e,...t)}function cn(e){return Oe(e,"value","option_value","attribute_value","label","title","name","variant_name","sku")}function ln(e){const t=Oe(e,"type","attribute","option_name","attribute_name");return t||(Oe(e,"value")?Oe(e,"name","variant_name"):void 0)}function gc(e){const t=ln(e)?.toLowerCase();return!!(be(e,"color","colour","color_hex","hex","swatch","swatchColor")||t&&rn.has(t))}function dn(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 pc(e){const t=dn(Oe(e,"swatchColor","swatch","color_hex","hex","color","colour"));if(t)return t;if(gc(e))return dn(cn(e))}function hc(e){return Oe(e,"image","imageUrl","image_url","swatchImage","swatch_image")}function uc(e){return sn(e,"price_discounted","priceDiscounted")??Oe(e,"price_discounted","priceDiscounted")??sn(e,"price")??Oe(e,"price")}function mc(e){const t=e.trim().toLowerCase();return rn.has(t)||ec.has(t)||tc.has(t)}function fc(e){const t=e.trim().toLowerCase();return t==="renk kodu"?"Renk":t==="color code"?"Color":e.trim()}function bc(e){for(const t of ac){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 vc(e){const t=bc(e);if(t)return t;const a=be(e,"sku"),n=Ct(e,"inStock","in_stock"),r=[],i=new Set,o=(c,l)=>{if(!mc(c)||typeof l!="string"&&typeof l!="number"&&typeof l!="boolean")return;const g=String(l).trim();if(!g)return;const d=fc(c),p=`${d.toLowerCase()}:${g.toLowerCase()}`;i.has(p)||(i.add(p),r.push({name:d,value:g,sku:a,inStock:n}))},s=ic(e,"facetHits","facet_hits");if(s)for(const[c,l]of Object.entries(s))o(c,l);for(const c of on(e))o(c.key,c.value);return r}function yc(e,t){const a=Array.from(new Set(e.map(ln).filter(n=>!!n)));return a.length===1?`${e.length} ${a[0]}`:t.i18n?.variantsLabel??"Variants"}function _c(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=be(n,"name"),i=be(n,"brand"),o=be(n,"sku"),s=be(n,"cartCode","cart_code"),c=be(n,"price"),l=be(n,"originalPrice","price_original"),g=Ct(n,"price_async"),d=tt(t,n),p=ht(t,n),h=!!(l&&c&&l!==c),m=Ct(n,"inStock","in_stock"),u=kt(n,"reviewCount","review_count"),f=kt(n,"rating"),y=sc(n),M=on(n).slice(0,4);if(y.length>1){const b=document.createElement("div");b.className="gengage-chat-product-details-media gengage-chat-product-details-gallery gengage-chat-product-details-img-wrap";const _=document.createElement("img");_.className="gengage-chat-product-details-img",ge(_,"src",y[0]),_.alt=r??"Product image",Re(_),b.appendChild(_);const S=document.createElement("div");S.className="gengage-chat-product-gallery-thumbs";const T=6;let z=null,D=0;const A=t.i18n,U=A?.galleryPrevAriaLabel??"Previous image",F=A?.galleryNextAriaLabel??"Next image",W=B=>B==="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>',ee=document.createElement("button");ee.type="button",ee.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--prev gds-btn gds-btn-ghost gds-icon-btn",ee.setAttribute("aria-label",U),ee.innerHTML=W("prev");const ae=document.createElement("button");ae.type="button",ae.className="gengage-chat-product-gallery-nav gengage-chat-product-gallery-nav--next gds-btn gds-btn-ghost gds-icon-btn",ae.setAttribute("aria-label",F),ae.innerHTML=W("next");const de=()=>{ee.disabled=D<=0,ae.disabled=D>=y.length-1},q=B=>{if(B<0||B>=y.length||B===D)return;const J=y[B];if(!J)return;ge(_,"src",J);const O=S.querySelectorAll(".gengage-chat-product-gallery-thumb");z&&z.classList.remove("gengage-chat-product-gallery-thumb--active"),B<T&&O[B]?(O[B].classList.add("gengage-chat-product-gallery-thumb--active"),z=O[B]):z=null,D=B,de()};for(let B=0;B<y.length;B++){const J=y[B];if(B>=T)break;const O=document.createElement("img");O.className="gengage-chat-product-gallery-thumb",B===0&&(O.classList.add("gengage-chat-product-gallery-thumb--active"),z=O),ge(O,"src",J),O.alt=`${r??"Product"} ${B+1}`,O.width=48,O.height=48,Re(O),O.addEventListener("click",()=>{q(B)}),S.appendChild(O)}if(y.length>T){const B=document.createElement("span");B.className="gengage-chat-product-gallery-thumb-more",B.textContent=`+${y.length-T}`,S.appendChild(B)}ee.addEventListener("click",B=>{B.stopPropagation(),q(D-1)}),ae.addEventListener("click",B=>{B.stopPropagation(),q(D+1)}),de();let _e=0;const j=50;_.addEventListener("touchstart",B=>{_e=B.changedTouches[0].clientX},{passive:!0}),_.addEventListener("touchend",B=>{const J=B.changedTouches[0].clientX,O=_e-J;Math.abs(O)<j||q(O>0?Math.min(D+1,y.length-1):Math.max(D-1,0))}),b.appendChild(ee),b.appendChild(ae),b.appendChild(S),a.appendChild(b)}else if(y.length===1){const b=document.createElement("div");b.className="gengage-chat-product-details-media gengage-chat-product-details-img-wrap";const _=document.createElement("img");_.className="gengage-chat-product-details-img",_.loading="lazy",ge(_,"src",y[0]),Re(_),_.alt=r??"Product image",b.appendChild(_),a.appendChild(b)}const C=document.createElement("div");if(C.className="gengage-chat-product-details-content",i&&(!r||!r.toLowerCase().startsWith(i.toLowerCase()))){const b=document.createElement("div");b.className="gengage-chat-product-details-brand",b.textContent=i,C.appendChild(b)}if(r){const b=document.createElement("h3");b.className="gengage-chat-product-details-title",b.textContent=r,b.title=r,C.appendChild(b)}if(typeof f=="number"&&Number.isFinite(f)&&f>0){const b=document.createElement(o?"button":"div");b.className="gengage-chat-product-details-rating",o&&(b.type="button",b.classList.add("gengage-chat-product-details-rating--clickable"),b.setAttribute("aria-label",t.i18n?.groundingReviewCta??"Read Reviews"),b.addEventListener("click",()=>{t.onAction({title:t.i18n?.customerReviewsTitle??"Customer Reviews",type:"reviewSummary",payload:{sku:o}})})),b.appendChild(Wa(f));const _=document.createElement("span");if(_.className="gengage-chat-product-details-rating-value",_.textContent=Qt(f).toFixed(1),b.appendChild(_),typeof u=="number"&&Number.isFinite(u)){const S=document.createElement("span");S.className="gengage-chat-product-details-review-count",S.textContent=` (${u})`,b.appendChild(S)}C.appendChild(b)}{let b=C;if(d){const S=document.createElement("div");S.className="gengage-chat-product-details-price-stack",S.appendChild(yt(d)),C.appendChild(S),b=S}const _=document.createElement("div");if(_.className="gengage-chat-product-details-price",g===!0){const S=document.createElement("span");S.className="gengage-chat-price-skeleton",_.appendChild(S),b.appendChild(_),setTimeout(()=>{if(S.parentElement)if(c&&parseFloat(c)>0)nn(_,t,n,c,l,p,h);else{const T=_.parentElement;_.remove(),T?.classList.contains("gengage-chat-product-details-price-stack")&&T.remove()}},300)}else if(c&&parseFloat(c)>0)nn(_,t,n,c,l,p,h),b.appendChild(_);else if(d){const S=b;S.classList.contains("gengage-chat-product-details-price-stack")&&S.remove()}}if(typeof m=="boolean"){const b=document.createElement("div");b.className=`gengage-chat-product-details-stock ${m?"is-in-stock":"is-out-of-stock"}`,b.textContent=m?t.i18n?.inStockLabel??"In Stock":t.i18n?.outOfStockLabel??"Out of Stock",C.appendChild(b)}const P=n.promotions;if(P&&P.length>0){const b=document.createElement("div");b.className="gengage-chat-product-details-promos";for(const _ of P.slice(0,3)){if(!_||/%(0(\.0+)?)\s/.test(_))continue;const S=document.createElement("span");S.className="gengage-chat-product-details-promo-badge",S.textContent=_,S.title=_,b.appendChild(S)}b.childElementCount>0&&C.appendChild(b)}if(M.length>0){const b=document.createElement("dl");b.className="gengage-chat-product-details-facts";for(const _ of M){const S=document.createElement("div");S.className="gengage-chat-product-details-fact";const T=document.createElement("dt");T.textContent=_.key;const z=document.createElement("dd");z.textContent=_.value,S.appendChild(T),S.appendChild(z),b.appendChild(S)}C.appendChild(b)}const w=vc(n);if(w.length>0){const b=document.createElement("div");b.className="gengage-chat-product-variants";const _=document.createElement("div");_.className="gengage-chat-product-variants-label",_.textContent=yc(w,t),b.appendChild(_);const S=document.createElement("div");S.className="gengage-chat-product-variants-list";for(const T of w){const z=cn(T),D=Oe(T,"sku");if(!z&&!D)continue;const A=document.createElement("button");A.className="gengage-chat-product-variant-btn gds-chip",A.type="button";const U=z??D??"";A.title=U;const F=Ct(T,"in_stock","inStock");D&&o&&D===o?(A.classList.add("gengage-chat-product-variant-btn--active"),A.setAttribute("aria-pressed","true")):A.setAttribute("aria-pressed","false"),F===!1&&(A.classList.add("gengage-chat-product-variant-btn--out"),A.disabled=!0);const W=hc(T),ee=pc(T);if(W&&fe(W)){const q=document.createElement("img");q.className="gengage-chat-product-variant-swatch gengage-chat-product-variant-swatch--image",ge(q,"src",W),q.alt="",q.setAttribute("aria-hidden","true"),Re(q),A.appendChild(q)}else if(ee){const q=document.createElement("span");q.className="gengage-chat-product-variant-swatch",q.setAttribute("aria-hidden","true"),q.style.backgroundColor=ee,A.appendChild(q)}const ae=document.createElement("span");ae.className="gengage-chat-product-variant-label",ae.textContent=U,A.appendChild(ae);const de=uc(T);if(de&&String(de)!==String(c)){const q=document.createElement("span");q.className="gengage-chat-product-variant-price",q.textContent=G(String(de),t.pricing),A.appendChild(q)}if(D&&D!==o){const q=r??"",_e=(typeof T.value=="string"?T.value.trim():"")||(typeof T.name=="string"?T.name.trim():"")||(typeof T.variant_name=="string"?T.variant_name.trim():"")||"",j=q.length>0?_e.length>0&&_e!==q?`${q} (${_e})`:q:U;A.addEventListener("click",()=>{t.onAction({title:j,type:"launchVariant",payload:{sku:D}})})}S.appendChild(A)}S.childElementCount>0&&(b.appendChild(S),C.appendChild(b))}const N=document.createElement("div");N.className="gengage-chat-product-details-actions";const R=e.props?.action;if(R){const b=document.createElement("button");b.className="gengage-chat-product-details-cta gds-btn gds-btn-primary",b.type="button",b.textContent=R.title||t.i18n?.productCtaLabel||"View",b.addEventListener("click",()=>t.onAction(R)),N.appendChild(b)}if(s&&o&&m!==!1){const b=document.createElement("button");b.className="gengage-chat-product-details-atc gds-btn gds-btn-primary",b.type="button",b.textContent=t.i18n?.addToCartButton??"Add to Cart",b.addEventListener("click",()=>{t.onAction({title:t.i18n?.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:o,cartCode:s,quantity:1}})}),N.appendChild(b)}const L=be(n,"url");if(!R&&L&&fe(L)){const b=document.createElement("a");b.className="gengage-chat-product-details-cta gds-btn gds-btn-secondary",ge(b,"href",L),ge(b,"target","_blank"),ge(b,"rel","noopener noreferrer"),b.textContent=t.i18n?.viewOnSiteLabel??t.i18n?.productCtaLabel??"View on Site",b.addEventListener("click",_=>{t.onProductClick&&o&&(_.preventDefault(),t.onProductClick({sku:o,url:L}))}),N.appendChild(b)}const Z=L;if(Z&&fe(Z)){let z=function(A,U){const F=document.createElementNS(S,"circle");F.setAttribute("cx",A),F.setAttribute("cy",U),F.setAttribute("r","3"),T.appendChild(F)},D=function(A,U,F,W){const ee=document.createElementNS(S,"line");ee.setAttribute("x1",A),ee.setAttribute("y1",U),ee.setAttribute("x2",F),ee.setAttribute("y2",W),T.appendChild(ee)};var I=z,v=D;const b=document.createElement("button");b.className="gengage-chat-product-details-share gds-btn gds-btn-ghost gds-icon-btn",b.type="button";const _=t.i18n?.shareButton??"Share";b.title=_,b.setAttribute("aria-label",_);const S="http://www.w3.org/2000/svg",T=document.createElementNS(S,"svg");T.setAttribute("width","18"),T.setAttribute("height","18"),T.setAttribute("viewBox","0 0 24 24"),T.setAttribute("fill","none"),T.setAttribute("stroke","currentColor"),T.setAttribute("stroke-width","2"),T.setAttribute("stroke-linecap","round"),T.setAttribute("stroke-linejoin","round"),z("18","5"),z("6","12"),z("18","19"),D("8.59","13.51","15.42","17.49"),D("15.41","6.51","8.59","10.49"),b.appendChild(T),b.addEventListener("click",async()=>{try{navigator.share?await navigator.share({title:r??"",url:Z}):navigator.clipboard&&(await navigator.clipboard.writeText(Z),b.classList.add("gengage-chat-product-details-share--copied"),setTimeout(()=>b.classList.remove("gengage-chat-product-details-share--copied"),1500))}catch{}}),N.appendChild(b)}N.childElementCount>0&&C.appendChild(N),a.appendChild(C);const te=lc(n),X=dc(n);return(te||X)&&a.appendChild(kc(te,X,t)),a}function aa(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(rc.has(a))return null;if(!nc.has(a)){const r=document.createDocumentFragment();for(const i of Array.from(t.childNodes)){const o=aa(i);o&&r.appendChild(o)}return r}const n=document.createElement(a.toLowerCase());for(const r of Array.from(t.childNodes)){const i=aa(r);i&&n.appendChild(i)}return n}function xc(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 wc(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=>aa(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}}xc(e,t.text)}function kc(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",wc(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(([d,p])=>({key:d,value:p}));for(const d of g){const p=document.createElement("tr"),h=document.createElement("td");h.className="gengage-chat-product-specs-key",h.textContent=d.key;const m=document.createElement("td");m.className="gengage-chat-product-specs-value",m.textContent=d.value,p.appendChild(h),p.appendChild(m),l.appendChild(p)}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 gn(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 Cc(){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 Sc(){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 Ec(){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 pn(e,t){return e.type===t.type&&e.direction===t.direction}function hn(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 Pc(e,t,a,n){const r=hn(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 Ac(e,t,a,n){const r=document.createElement("div");r.className="gengage-chat-product-grid-wrapper";const i=Ys(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 p=document.createElement("div");p.className="gengage-chat-product-sort-toolbar",p.setAttribute("role","toolbar"),p.setAttribute("aria-label",n.i18n?.sortToolbarAriaLabel??"Sort products");let h=n.productSort??{type:"related"};const m=[{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 y=n.i18n?.sortToolbarAriaLabel??"Sort products",M=document.createElement("span");M.className="gengage-chat-product-sort-trigger-icon";const C=document.createElement("span");C.className="gengage-chat-product-sort-trigger-label";const P=v=>{const b=m.find(_=>pn(_.sortState,v))??m[0];C.textContent=b.label,M.innerHTML=gn(b.icon),u.dataset.sortIcon=b.icon,f.setAttribute("aria-label",`${y}: ${b.label}`),f.title=b.label};P(h);const w=document.createElement("span");w.className="gengage-chat-product-sort-trigger-chevron",w.innerHTML=Cc(),f.appendChild(M),f.appendChild(C),f.appendChild(w);const N=document.createElement("div");N.className="gengage-chat-product-sort-menu gds-menu",N.hidden=!0,N.setAttribute("role","listbox"),N.setAttribute("aria-label",y);const R=p.ownerDocument;let L=null;const Z=()=>{N.hidden=!0,u.classList.remove("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","false"),L?.abort(),L=null},te=v=>{u.classList.contains("gengage-chat-product-sort-dropdown--open")&&(u.contains(v.target)||Z())},X=v=>{v.key==="Escape"&&(v.preventDefault(),Z())},I=()=>{N.hidden=!1,u.classList.add("gengage-chat-product-sort-dropdown--open"),f.setAttribute("aria-expanded","true"),L=new AbortController;const{signal:v}=L;R.addEventListener("click",te,{signal:v}),R.addEventListener("keydown",X,{capture:!0,signal:v})};f.addEventListener("click",v=>{v.stopPropagation(),u.classList.contains("gengage-chat-product-sort-dropdown--open")?Z():I()});for(const v of m){const b=document.createElement("button");b.type="button",b.className="gengage-chat-product-sort-option gds-menu-option",b.setAttribute("role","option");const _=pn(h,v.sortState);b.setAttribute("aria-selected",_?"true":"false"),_&&b.classList.add("gengage-chat-product-sort-option--active","gds-menu-option-active");const S=v.sortState.type==="related"?"related":`price-${v.sortState.direction??""}`;b.dataset.sortKey=S;const T=document.createElement("span");T.className="gengage-chat-product-sort-option-icon",T.innerHTML=gn(v.icon);const z=document.createElement("span");z.className="gengage-chat-product-sort-option-label",z.textContent=v.label;const D=document.createElement("span");D.className="gengage-chat-product-sort-option-check",D.innerHTML=Sc(),D.setAttribute("aria-hidden","true"),_||D.classList.add("gengage-chat-product-sort-option-check--hidden"),b.appendChild(T),b.appendChild(z),b.appendChild(D),b.addEventListener("click",()=>{h=v.sortState,n.onSortChange?.(v.sortState),Pc(c,s,t,v.sortState),N.querySelectorAll(".gengage-chat-product-sort-option").forEach(A=>{const U=A,F=U.dataset.sortKey===S;U.classList.toggle("gengage-chat-product-sort-option--active",F),U.classList.toggle("gds-menu-option-active",F),U.setAttribute("aria-selected",F?"true":"false"),U.querySelector(".gengage-chat-product-sort-option-check")?.classList.toggle("gengage-chat-product-sort-option-check--hidden",!F)}),P(v.sortState),Z()}),N.appendChild(b)}if(u.appendChild(f),u.appendChild(N),p.appendChild(u),n.onToggleComparisonSku){const v=document.createElement("button");v.className="gengage-chat-comparison-toggle-btn gds-btn gds-btn-ghost",v.type="button",n.comparisonSelectMode&&v.classList.add("gengage-chat-comparison-toggle-btn--active"),n.isStreaming&&v.classList.add("gengage-chat-comparison-toggle-btn--hidden");const b=document.createElement("span");b.className="gengage-chat-comparison-toggle-icon",b.innerHTML=Ec();const _=document.createElement("span");_.className="gengage-chat-comparison-toggle-label";const S=n.i18n?.compareSelected??"Compare";_.textContent=S,v.setAttribute("aria-label",S),v.title=S,v.appendChild(b),v.appendChild(_),v.addEventListener("click",()=>{n.onToggleComparisonSku?.("")}),p.appendChild(v)}if(l){p.classList.add("gengage-chat-product-sort-toolbar--inline");const v=document.createElement("div");v.className="gengage-chat-product-grid-head";const b=document.createElement("span");b.className="gengage-chat-product-grid-head-title",b.textContent=l,v.appendChild(b);const _=document.createElement("div");_.className="gengage-chat-product-grid-head-actions",_.appendChild(p),v.appendChild(_),r.appendChild(v)}else r.appendChild(p)}else if(l){const p=document.createElement("div");p.className="gengage-chat-product-grid-head";const h=document.createElement("span");h.className="gengage-chat-product-grid-head-title",h.textContent=l,p.appendChild(h),r.appendChild(p)}if(o)Js(r,c,i,n);else{const p=hn(s,t,n?.productSort);for(const h of p){if(!t.elements[h])continue;const m=a(h);m&&(m.dataset.elementId=h,c.appendChild(m))}}(n?.isMobile??ea())&&c.classList.add("gengage-chat-product-grid--mobile"),r.appendChild(c);const g=e.props?.endOfList;if(!o&&g!==!0&&s.length>0){const p=n?.i18n?.viewMoreLabel??"Show More",h=document.createElement("button");h.className="gengage-chat-product-grid-view-more",h.type="button",h.textContent=p,h.addEventListener("click",()=>{n?.onAction({title:p,type:"moreProductList",payload:{}})}),r.appendChild(h)}const d=n?.isMobile??ea();if(n?.comparisonSelectMode&&n.comparisonSelectedSkus&&!d){const p=Xa(n.comparisonSelectedSkus,n);r.appendChild(p)}return r}function Tc(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,d=a.productActions;if(!r)return document.createElement("div");const p={recommended:r,products:i,attributes:o,highlights:s,specialCases:c,onProductClick:({sku:m,name:u})=>{t.onProductClick?.({sku:m,url:"",name:u})},pricing:t.pricing};l!==void 0&&(p.recommendedText=l),g!==void 0&&(p.winnerHits=g),d!==void 0&&(p.productActions=d),n!==void 0&&(p.keyDifferencesHtml=n),t.i18n&&(p.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 h=vs(p);return(t.isMobile??ea())&&h.classList.add("gengage-chat-comparison--mobile"),h}function Lc(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 Ic=new Set(["P","DIV","H1","H2","H3","H4","H5","H6","LI","UL","OL","BLOCKQUOTE","PRE","TABLE","SECTION","HR","FIGURE","FIGCAPTION","DL","DT","DD"]);function Nc(e){const t=[];let a=[];for(const n of e)n.nodeType===Node.ELEMENT_NODE&&Ic.has(n.tagName)?(a.length>0&&(t.push(a),a=[]),t.push([n])):a.push(n);return a.length>0&&t.push(a),t}function zc(e){for(const t of e)for(const a of t)if(a.nodeType===Node.ELEMENT_NODE&&(a.tagName==="TABLE"||a.querySelector?.("table")))return!0;return!1}function Mc(){return typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches}function Bc(e){const{container:t,html:a,delayMs:n=30,onTick:r,onComplete:i}=e,o=document.createElement("template");o.innerHTML=a;const s=Nc(o.content.childNodes);if(Mc()||s.length<=1||zc(s))return t.innerHTML=a,i?.(),{complete(){},cancel(){},isRunning:!1};t.innerHTML="";let c=0,l=null,g=!0;function d(){if(!g||c>=s.length){g=!1,i?.();return}const p=s[c],h=document.createElement("span");h.className="gengage-chat-typewriter-block";for(const m of p)h.appendChild(m.cloneNode(!0));t.appendChild(h),c++,r?.(),c<s.length?l=setTimeout(d,n):(g=!1,i?.())}return d(),{complete(){g&&(l!==null&&clearTimeout(l),g=!1,t.innerHTML=a,i?.())},cancel(){l!==null&&clearTimeout(l),g=!1},get isRunning(){return g}}}function un(e){return e!==void 0&&/[\p{L}\p{N}_]/u.test(e)}function Rc(e){const{container:t,mentions:a,onProductClick:n}=e;if(a.length===0)return;const r=new Map;for(const i of a)i.short_name.length!==0&&r.set(i.short_name.toLowerCase(),i);if(r.size!==0)for(const[i,o]of r){const s=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);let c=s.nextNode(),l=!1;for(;c&&!l;){const g=c.textContent??"",d=g.toLowerCase().indexOf(i);if(d===-1){c=s.nextNode();continue}const p=d>0?g[d-1]:void 0,h=g[d+o.short_name.length];if(un(p)||un(h)){c=s.nextNode();continue}const m=g.slice(0,d),u=g.slice(d,d+o.short_name.length),f=g.slice(d+o.short_name.length),y=c.parentNode;if(!y){c=s.nextNode();continue}const M=document.createElement("a");M.className="gengage-product-mention",M.textContent=u,M.href="#",M.addEventListener("click",C=>{C.preventDefault(),n(o.sku)}),m&&y.insertBefore(document.createTextNode(m),c),y.insertBefore(M,c),f&&y.insertBefore(document.createTextNode(f),c),y.removeChild(c),l=!0}}}var Dc=new Set(["search","info","review","similar"]),Oc=new Set(["quickAnswer","reviewSummary","searchDiscovery","launchDiscovery","exploreTogetherV2"]);function $c(e){return!!(e.icon&&Dc.has(e.icon)||e.action?.type&&Oc.has(e.action.type))}var Et="gengage_choice_prompter_dismissed",Fc="gengage_choice_prompter_dismissed_global";function Hc(e){const t=document.createElement("div");t.className="gengage-chat-choice-prompter gds-card",t.dataset.gengagePart="choice-prompter";const a=document.createElement("div");a.className="gengage-chat-choice-prompter-copy";const n=document.createElement("div");n.className="gengage-chat-choice-prompter-heading",n.textContent=e.heading,a.appendChild(n);const r=document.createElement("div");r.className="gengage-chat-choice-prompter-suggestion",r.textContent=e.suggestion,a.appendChild(r),t.appendChild(a);const i=document.createElement("button");i.type="button",i.className="gengage-chat-choice-prompter-cta gds-btn gds-btn-primary",i.dataset.gengagePart="choice-prompter-cta",i.textContent=e.ctaLabel,i.addEventListener("click",()=>{na(e.threadId),t.remove(),e.onCtaClick()}),t.appendChild(i);const o=document.createElement("button");return o.type="button",o.className="gengage-chat-choice-prompter-dismiss",o.dataset.gengagePart="choice-prompter-dismiss",o.textContent="×",o.setAttribute("aria-label",e.dismissAriaLabel??"Dismiss"),o.addEventListener("click",()=>{na(e.threadId),t.remove(),e.onDismiss?.()}),t.appendChild(o),t}function Uc(){try{sessionStorage.removeItem(Et),sessionStorage.removeItem(Fc)}catch{}}function jc(e){try{const t=sessionStorage.getItem(Et);return t?JSON.parse(t).includes(e):!1}catch{return!1}}function na(e){try{const t=sessionStorage.getItem(Et),a=t?JSON.parse(t):[];a.includes(e)||a.push(e),sessionStorage.setItem(Et,JSON.stringify(a))}catch{}}function Zc(e){e&&na(e)}var qc="gengage_assistant",Vc=3,Ue="sessions",Te="context",De="payload",Le="favorites";function ut(e){return new Promise((t,a)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>a(e.error)})}function at(e){return new Promise((t,a)=>{e.oncomplete=()=>t(),e.onerror=()=>a(e.error),e.onabort=()=>a(e.error??new DOMException("Transaction aborted"))})}var Gc=class{constructor(e=qc,t=Vc){this._db=null,this._dbName=e,this._version=t}async open(){return this._db?this._db:new Promise((e,t)=>{const a=indexedDB.open(this._dbName,this._version);a.onupgradeneeded=n=>{const r=a.result,i=n.oldVersion;i<1&&(r.createObjectStore(Ue,{keyPath:["userId","appId","sessionId"]}),r.createObjectStore(Te,{keyPath:["sessionId","threadId"]}),r.createObjectStore(De,{keyPath:["threadId","messageId"]}).createIndex("threadId","threadId",{unique:!1}),r.createObjectStore(Le,{keyPath:["userId","appId","sku"]})),i>=1&&i<2&&(r.objectStoreNames.contains(Ue)&&r.deleteObjectStore(Ue),r.objectStoreNames.contains(De)&&r.deleteObjectStore(De),r.createObjectStore(Ue,{keyPath:["userId","appId","sessionId"]}),r.createObjectStore(De,{keyPath:["threadId","messageId"]}).createIndex("threadId","threadId",{unique:!1}),r.objectStoreNames.contains(Te)||r.createObjectStore(Te,{keyPath:["sessionId","threadId"]})),i<3&&(r.objectStoreNames.contains(Le)||r.createObjectStore(Le,{keyPath:["userId","appId","sku"]}))},a.onsuccess=()=>{this._db=a.result,e(this._db)},a.onerror=()=>t(a.error)})}close(){this._db?.close(),this._db=null}async saveSession(e){const t=this._requireDb().transaction(Ue,"readwrite");t.objectStore(Ue).put(e),await at(t)}async loadSession(e,t,a){return await ut(this._requireDb().transaction(Ue,"readonly").objectStore(Ue).get([e,t,a]))??null}async saveContext(e){const t=this._requireDb().transaction(Te,"readwrite");t.objectStore(Te).put(e),await at(t)}async loadContext(e,t){return await ut(this._requireDb().transaction(Te,"readonly").objectStore(Te).get([e,t]))??null}async deleteContextsAfterThread(e,t){const a=this._requireDb().transaction(Te,"readwrite"),n=a.objectStore(Te).openCursor();await new Promise((r,i)=>{n.onsuccess=()=>{const o=n.result;if(!o){r();return}const s=o.value;if(s.sessionId===e&&s.threadId>t)try{o.delete()}catch{}o.continue()},n.onerror=()=>i(n.error)}),await at(a)}async loadLatestContext(e){const t=this._requireDb().transaction(Te,"readonly").objectStore(Te),a=IDBKeyRange.bound([e,""],[e,""]);return new Promise((n,r)=>{const i=t.openCursor(a,"prev");i.onsuccess=()=>{const o=i.result;n(o?o.value:null)},i.onerror=()=>r(i.error)})}async savePayload(e){const t=this._requireDb().transaction(De,"readwrite");t.objectStore(De).put(e),await at(t)}async loadPayload(e,t){return await ut(this._requireDb().transaction(De,"readonly").objectStore(De).get([e,t]))??null}async loadPayloadsByThread(e){const t=this._requireDb().transaction(De,"readonly").objectStore(De).index("threadId"),a=[];return new Promise((n,r)=>{const i=t.openCursor(IDBKeyRange.only(e));i.onsuccess=()=>{const o=i.result;if(!o){n(a);return}a.push(o.value),o.continue()},i.onerror=()=>r(i.error)})}async saveFavorite(e){const t=this._requireDb().transaction(Le,"readwrite");t.objectStore(Le).put(e),await at(t)}async removeFavorite(e,t,a){const n=this._requireDb().transaction(Le,"readwrite");n.objectStore(Le).delete([e,t,a]),await at(n)}async loadFavorites(e,t){return(await ut(this._requireDb().transaction(Le,"readonly").objectStore(Le).getAll())).filter(a=>a.userId===e&&a.appId===t)}async isFavorite(e,t,a){return await ut(this._requireDb().transaction(Le,"readonly").objectStore(Le).get([e,t,a]))!==void 0}_requireDb(){if(!this._db)throw new Error("GengageIndexedDB: database not open. Call open() first.");return this._db}},Wc=["comparisonTable","groupList","productDetailsSimilars","productList"],Kc=class{constructor(e){this._lockCount=1,this._hiddenByUser=!1,this._lastPanelContentType=null,this._chatShown=!1,this._isFavoritesMode=!1,this._lastExtended=!1,this._onChange=e.onChange;const t=new Set(Wc);e.productDetailsInPanel&&t.add("productDetails"),this._panelContentTypes=t}get isExtended(){return this._lockCount===0&&!this._hiddenByUser&&!this._isFavoritesMode&&this._lastPanelContentType!==null&&this._panelContentTypes.has(this._lastPanelContentType)&&this._chatShown}unlock(){this._lockCount>0&&this._lockCount--,this._checkStateChange()}lock(){this._lockCount++,this._checkStateChange()}setHiddenByUser(e){this._hiddenByUser=e,this._checkStateChange()}setChatShown(e){this._chatShown=e,this._checkStateChange()}setFavoritesMode(e){this._isFavoritesMode=e,this._checkStateChange()}setPanelContentType(e){this._lastPanelContentType=e,this._checkStateChange()}_checkStateChange(){const e=this.isExtended;e!==this._lastExtended&&(this._lastExtended=e,this._onChange(e))}},Yc=class{constructor(e){this.deps=e,this.snapshots=new Map,this._snapshotRebuilders=new Map,this.snapshotTypes=new Map,this.activePanelMessageId=null,this.currentType=null,this.threads=[],this.lastActionType=null}snapshotForMessage(e,t){const a=this.deps.drawer();if(!a?.hasPanelContent()||a.isPanelLoading())return;const n=a.getPanelContentElement();if(!n)return;const r=n.cloneNode(!0);this.snapshots.set(e,r),t&&this._snapshotRebuilders.set(e,t),this.currentType&&this.snapshotTypes.set(e,this.currentType)}restoreForMessage(e){const t=this._snapshotRebuilders.get(e),a=this.snapshots.get(e);if(!t&&!a)return!1;const n=this.deps.shadow(),r=this.deps.drawer();this.activePanelMessageId&&n?.querySelector(`[data-message-id="${CSS.escape(this.activePanelMessageId)}"]`)?.classList.remove("gengage-chat-bubble--active"),n?.querySelector(`[data-message-id="${CSS.escape(e)}"]`)?.classList.add("gengage-chat-bubble--active"),this.activePanelMessageId=e;const i=t?t():a.cloneNode(!0);r?.setPanelContent(i);const o=this.snapshotTypes.get(e);if(r?.setDividerPreviewEnabled(o==="ProductGrid"),o)if(this.currentType=o,i.querySelector(".gengage-chat-product-grid-head-title")&&o==="ProductGrid"){const s=this.deps.currentThreadId();if(s){const c=this.threads.indexOf(s),l=c>0,g=c>=0&&c<this.threads.length-1;this.deps.drawer()?.updatePanelTopBar(l,g,"")}}else this.updateTopBar(o);return!0}notifyExtension(e){const t=this.deps.bridge();e?setTimeout(()=>t?.send("maximize-pdp",{}),350):setTimeout(()=>t?.send("minify-pdp",{}),200)}titleForComponent(e,t){if(t)return t;const a=this.deps.i18n();switch(e){case"ProductDetailsPanel":return a.panelTitleProductDetails;case"ProductGrid":return mn(this.lastActionType)?a.panelTitleSearchResults:a.panelTitleSimilarProducts;case"ComparisonTable":return a.panelTitleComparisonResults;case"AIGroupingCards":return a.panelTitleCategories;default:return""}}updateTopBar(e,t,a){const n=this.deps.currentThreadId();if(!n)return;const r=this.threads.indexOf(n),i=r>0,o=r>=0&&r<this.threads.length-1,s=a!==void 0?a:this.titleForComponent(e,t);this.deps.drawer()?.updatePanelTopBar(i,o,s)}updateTopBarForLoading(e){const t=this.deps.i18n(),a={productDetails:t.panelTitleProductDetails,productList:mn(this.lastActionType)?t.panelTitleSearchResults:t.panelTitleSimilarProducts,comparisonTable:t.panelTitleComparisonResults,groupList:t.panelTitleCategories}[e]??"";if(a){const n=this.deps.currentThreadId(),r=n?this.threads.indexOf(n):-1,i=r>0,o=r>=0&&r<this.threads.length-1;this.deps.drawer()?.updatePanelTopBar(i,o,a)}}updateExtendedMode(e){const t={ComparisonTable:"comparisonTable",AIGroupingCards:"groupList",ProductDetailsPanel:"productDetails",ProductGrid:"productList"}[e]??null;this.deps.extendedModeManager()?.setPanelContentType(t)}navigateBack(){const e=this.deps.currentThreadId();if(!e)return;const t=this.threads.indexOf(e);if(t>0){const a=this.threads[t-1];a&&this.deps.rollbackToThread(a)}}navigateForward(){const e=this.deps.currentThreadId();if(!e)return;const t=this.threads.indexOf(e);if(t>=0&&t<this.threads.length-1){const a=this.threads[t+1];a&&this.deps.rollbackToThread(a)}}toPanelSpec(e){const t=e.elements[e.root];if(!t||t.type!=="ProductCard")return e;const a={...t,type:"ProductDetailsPanel"};return{root:e.root,elements:{...e.elements,[e.root]:a}}}destroy(){this.snapshots.clear(),this._snapshotRebuilders.clear(),this.snapshotTypes.clear(),this.activePanelMessageId=null,this.currentType=null,this.threads=[]}};function mn(e){return e==="user_message"||e==="inputText"}function Jc(e){return e.similarsAppend&&e.currentPanelType==="ProductDetailsPanel"&&e.hasPanelContent&&!e.isPanelLoading?"appendSimilars":e.componentType==="ProductGrid"&&!e.isFirstPanelContentInStream&&e.hasPanelContent&&!e.isPanelLoading?"append":"replace"}var fn=class{constructor(e){this.favoritedSkus=new Set,this._favoritesCache=new Map,this._persistLock=Promise.resolve(),this._db=e}get db(){return this._db}set db(e){this._db=e}async persist(e){if(!this._db)return;const t=this._persistLock;let a;this._persistLock=new Promise(n=>{a=n}),await t;try{await this._persistImpl(e)}finally{a()}}async _persistImpl(e){if(!this._db)return;const t=e.messages.map(n=>{const r={id:n.id,role:n.role,timestamp:n.timestamp,status:n.status==="streaming"?"done":n.status};return n.threadId!==void 0&&(r.threadId=n.threadId),n.content!==void 0&&(r.content=n.content),n.silent&&(r.silent=!0),r}),a={};for(const[n,r]of e.panelSnapshots)r.querySelector(".gengage-chat-panel-skeleton")||(a[n]=r.innerHTML);await this._db.saveSession({userId:e.userId,appId:e.appId,sessionId:e.sessionId,messages:t,currentThreadId:e.currentThreadId,lastThreadId:e.lastThreadId,createdAt:e.chatCreatedAt,panelThreads:e.panelThreads.length>0?e.panelThreads:void 0,thumbnailEntries:e.thumbnailEntries.length>0?e.thumbnailEntries:void 0,panelSnapshotHtml:Object.keys(a).length>0?a:void 0,sku:e.sku}),e.lastBackendContext&&e.currentThreadId&&await this._db.saveContext({sessionId:e.sessionId,threadId:e.currentThreadId,context:e.lastBackendContext});for(const n of e.messages)n.uiSpec&&n.threadId&&await this._db.savePayload({threadId:n.threadId,messageId:n.id,uiSpec:n.uiSpec})}async saveAndOpenURL(e,t,a){try{await t()}catch{}a?.send("openURLInNewTab",{url:e}),fe(e)&&(window.location.href=e)}async loadPayload(e,t){if(!this._db)return null;for(let a=0;a<3;a++){try{const n=await this._db.loadPayload(e,t);if(n)return n.uiSpec}catch{}a<2&&await new Promise(n=>setTimeout(n,100))}return null}async loadFavorites(e,t){if(this._db)try{const a=await this._db.loadFavorites(e,t);for(const n of a)this.favoritedSkus.add(n.sku),this._favoritesCache.set(n.sku,n)}catch{}}getFavoriteProducts(){return[...this._favoritesCache.values()].sort((e,t)=>(t.savedAt??"").localeCompare(e.savedAt??""))}async toggleFavorite(e,t,a,n){if(this.favoritedSkus.has(a))this.favoritedSkus.delete(a),this._favoritesCache.delete(a),this._db&&await this._db.removeFavorite(e,t,a);else{const r={userId:e,appId:t,sku:a,name:n.name,imageUrl:n.imageUrl,price:n.price,savedAt:new Date().toISOString()};this.favoritedSkus.add(a),this._favoritesCache.set(a,r),this._db&&await this._db.saveFavorite(r)}}close(){this._db?.close(),this._db=null}},ra=e=>`${e}:assistant`,bn=class{constructor(){this.groups={},this.pinnedToBottom=!0,this.userInteracting=!1,this.focusedThreadId=null,this.shown=!1,this.lastAutoAnchoredGroupId=null,this.scrollRequest=null,this._nextScrollId=1}setShown(e){this.shown=e,e||(this.userInteracting=!1,this.pinnedToBottom=!0,this.focusedThreadId=null,this.scrollRequest=null)}reset(){this.groups={},this.pinnedToBottom=!0,this.userInteracting=!1,this.focusedThreadId=null,this.lastAutoAnchoredGroupId=null,this.scrollRequest=null}registerAssistantActivity(e){const t=ra(e),a=this.groups[t],n=this.shown&&this.pinnedToBottom&&!this.userInteracting?"active_unread":"unseen";this.groups[t]={id:t,threadId:e,readState:a?.readState==="seen"?n:a?.readState??n,status:"streaming",updatedAt:Date.now()},a?.readState==="seen"&&this.lastAutoAnchoredGroupId===t&&(this.lastAutoAnchoredGroupId=null)}finalizeAssistantGroup(e){const t=ra(e),a=this.groups[t];a&&(a.status="complete",a.updatedAt=Date.now())}setGroupReadStates(e){const t=Date.now();for(const{groupId:a,readState:n}of e){const r=this.groups[a];!r||r.readState===n||(r.readState=n,r.updatedAt=t)}}requestThreadFocus(e,t="smooth"){this.focusedThreadId=e,this.scrollRequest={id:this._nextScrollId++,type:"thread",threadId:e,behavior:t}}requestScrollToBottom(e="smooth"){this.scrollRequest={id:this._nextScrollId++,type:"bottom",behavior:e}}consumeScrollRequest(e){this.scrollRequest?.id===e&&(this.scrollRequest=null)}releaseFocusedThread(){this.focusedThreadId=null}setFocusedThreadId(e){this.focusedThreadId=e}markGroupAutoAnchored(e){this.lastAutoAnchoredGroupId=e}shouldBlockStreamAutoScroll(){return this.shown&&this.userInteracting&&!this.pinnedToBottom}getAssistantReadState(e){return this.groups[ra(e)]?.readState}};function Xc(e,t){for(let a=e.length-1;a>=0;a--){const n=e[a],r=t.getAssistantReadState(n);if(r!==void 0&&r!=="seen")return n}return null}function Qc(e){const{label:t,avatarUrl:a,primaryColor:n,secondaryColor:r="#111827",fontFamily:i="inherit",labelClassName:o="gengage-pill-launcher-label",styleId:s="gengage-pill-launcher-style",mobileBreakpoint:c=768,desktopWidth:l="188px",desktopHeight:g="60px",iconSize:d="46px"}=e,p=`${parseInt(l,10)-14}px`,h=`${parseInt(g,10)-4}px`,m=`${parseInt(d,10)-4}px`,u=`
|
|
60
60
|
:host {
|
|
61
61
|
--pill-primary: ${n};
|
|
62
62
|
--pill-secondary: ${r};
|
|
@@ -173,6 +173,6 @@ button[data-gengage-part="chat-launcher-button"] img {
|
|
|
173
173
|
|
|
174
174
|
`)}h.write("payload.value = newResult;"),h.write("return payload;");const M=h.compile();return(C,P)=>M(p,C,P)};let i;const o=Pt,s=!sa.jitless,l=s&&Ll.value,g=t.catchall;let d;e._zod.parse=(p,h)=>{d??(d=n.value);const m=p.value;return o(m)?s&&l&&h?.async===!1&&h.jitless!==!0?(i||(i=r(t.shape)),p=i(p,h),g?Yn([],m,p,h,d,e):p):a(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),p)}});function Jn(e,t,a,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!it(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:a,errors:e.map(i=>i.issues.map(o=>Ve(o,n,je())))}),t)}var cg=k("$ZodUnion",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Q(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>ga(i.source)).join("|")})$`)}});const a=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(a)return n(r,i);let o=!1;const s=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}return o?Promise.all(s).then(c=>Jn(c,r,e,i)):Jn(s,r,e,i)}}),lg=k("$ZodIntersection",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{const r=a.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([s,c])=>Xn(a,s,c)):Xn(a,i,o)}});function ua(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(rt(e)&&rt(t)){const a=Object.keys(t),n=Object.keys(e).filter(i=>a.indexOf(i)!==-1),r={...e,...t};for(const i of n){const o=ua(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};r[i]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const a=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=ua(r,i);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}function Xn(e,t,a){const n=new Map;let r;for(const s of t.issues)if(s.code==="unrecognized_keys"){r??(r=s);for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(s);for(const s of a.issues)if(s.code==="unrecognized_keys")for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(s);const i=[...n].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&r&&e.issues.push({...r,keys:i}),it(e))return e;const o=ua(t.value,a.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var dg=k("$ZodRecord",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{const r=a.value;if(!rt(r))return a.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),a;const i=[],o=t.keyType._zod.values;if(o){a.value={};const s=new Set;for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){s.add(typeof l=="number"?l.toString():l);const g=t.valueType._zod.run({value:r[l],issues:[]},n);g instanceof Promise?i.push(g.then(d=>{d.issues.length&&a.issues.push(...ot(l,d.issues)),a.value[l]=d.value})):(g.issues.length&&a.issues.push(...ot(l,g.issues)),a.value[l]=g.value)}let c;for(const l in r)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&a.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{a.value={};for(const s of Reflect.ownKeys(r)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&Un.test(s)&&c.issues.length){const g=t.keyType._zod.run({value:Number(s),issues:[]},n);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(c=g)}if(c.issues.length){t.mode==="loose"?a.value[s]=r[s]:a.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(g=>Ve(g,n,je())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:r[s],issues:[]},n);l instanceof Promise?i.push(l.then(g=>{g.issues.length&&a.issues.push(...ot(s,g.issues)),a.value[c.value]=g.value})):(l.issues.length&&a.issues.push(...ot(s,l.issues)),a.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>a):a}}),gg=k("$ZodEnum",(e,t)=>{ie.init(e,t);const a=kn(t.entries),n=new Set(a);e._zod.values=n,e._zod.pattern=new RegExp(`^(${a.filter(r=>Il.has(typeof r)).map(r=>typeof r=="string"?At(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:a,input:o,inst:e}),r}}),pg=k("$ZodTransform",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(e.constructor.name);const r=t.transform(a.value,a);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(a.value=i,a));if(r instanceof Promise)throw new nt;return a.value=r,a}});function Qn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var er=k("$ZodOptional",(e,t)=>{ie.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${ga(a.source)})?$`):void 0}),e._zod.parse=(a,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>Qn(i,a.value)):Qn(r,a.value)}return a.value===void 0?a:t.innerType._zod.run(a,n)}}),hg=k("$ZodExactOptional",(e,t)=>{er.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(a,n)=>t.innerType._zod.run(a,n)}),ug=k("$ZodNullable",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${ga(a.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(a,n)=>a.value===null?a:t.innerType._zod.run(a,n)}),mg=k("$ZodDefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);if(a.value===void 0)return a.value=t.defaultValue,a;const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>tr(i,t)):tr(r,t)}});function tr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var fg=k("$ZodPrefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>(n.direction==="backward"||a.value===void 0&&(a.value=t.defaultValue),t.innerType._zod.run(a,n))}),bg=k("$ZodNonOptional",(e,t)=>{ie.init(e,t),Q(e._zod,"values",()=>{const a=t.innerType._zod.values;return a?new Set([...a].filter(n=>n!==void 0)):void 0}),e._zod.parse=(a,n)=>{const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>ar(i,e)):ar(r,e)}});function ar(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var vg=k("$ZodCatch",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>(a.value=i.value,i.issues.length&&(a.value=t.catchValue({...a,error:{issues:i.issues.map(o=>Ve(o,n,je()))},input:a.value}),a.issues=[]),a)):(a.value=r.value,r.issues.length&&(a.value=t.catchValue({...a,error:{issues:r.issues.map(i=>Ve(i,n,je()))},input:a.value}),a.issues=[]),a)}}),yg=k("$ZodPipe",(e,t)=>{ie.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(a,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(a,n);return i instanceof Promise?i.then(o=>Rt(o,t.in,n)):Rt(i,t.in,n)}const r=t.in._zod.run(a,n);return r instanceof Promise?r.then(i=>Rt(i,t.out,n)):Rt(r,t.out,n)}});function Rt(e,t,a){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},a)}var _g=k("$ZodReadonly",(e,t)=>{ie.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(nr):nr(r)}});function nr(e){return e.value=Object.freeze(e.value),e}var xg=k("$ZodCustom",(e,t)=>{ue.init(e,t),ie.init(e,t),e._zod.parse=(a,n)=>a,e._zod.check=a=>{const n=a.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>rr(i,a,n,e));rr(r,a,n,e)}});function rr(e,t,a,n){if(!e){const r={code:"custom",input:a,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(mt(r))}}var ir,wg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const a=t[0];return this._map.set(e,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const a={...this.get(t)??{}};delete a.id;const n={...a,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function kg(){return new wg}(ir=globalThis).__zod_globalRegistry??(ir.__zod_globalRegistry=kg());var $e=globalThis.__zod_globalRegistry;function Cg(e,t){return new e({type:"string",...$(t)})}function Sg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...$(t)})}function or(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...$(t)})}function Eg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...$(t)})}function Pg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(t)})}function Ag(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(t)})}function Tg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(t)})}function Lg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...$(t)})}function Ig(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...$(t)})}function Ng(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(t)})}function zg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...$(t)})}function Mg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(t)})}function Bg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...$(t)})}function Rg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...$(t)})}function Dg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(t)})}function Og(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(t)})}function $g(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(t)})}function Fg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(t)})}function Hg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(t)})}function Ug(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...$(t)})}function jg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...$(t)})}function Zg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...$(t)})}function qg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...$(t)})}function Vg(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(t)})}function Gg(e,t){return new e({type:"string",format:"date",check:"string_format",...$(t)})}function Wg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...$(t)})}function Kg(e,t){return new e({type:"string",format:"duration",check:"string_format",...$(t)})}function Yg(e,t){return new e({type:"number",checks:[],...$(t)})}function Jg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...$(t)})}function Xg(e,t){return new e({type:"boolean",...$(t)})}function Qg(e){return new e({type:"unknown"})}function ep(e,t){return new e({type:"never",...$(t)})}function sr(e,t){return new Zn({check:"less_than",...$(t),value:e,inclusive:!1})}function ma(e,t){return new Zn({check:"less_than",...$(t),value:e,inclusive:!0})}function cr(e,t){return new qn({check:"greater_than",...$(t),value:e,inclusive:!1})}function fa(e,t){return new qn({check:"greater_than",...$(t),value:e,inclusive:!0})}function lr(e,t){return new fd({check:"multiple_of",...$(t),value:e})}function dr(e,t){return new vd({check:"max_length",...$(t),maximum:e})}function Dt(e,t){return new yd({check:"min_length",...$(t),minimum:e})}function gr(e,t){return new _d({check:"length_equals",...$(t),length:e})}function tp(e,t){return new xd({check:"string_format",format:"regex",...$(t),pattern:e})}function ap(e){return new wd({check:"string_format",format:"lowercase",...$(e)})}function np(e){return new kd({check:"string_format",format:"uppercase",...$(e)})}function rp(e,t){return new Cd({check:"string_format",format:"includes",...$(t),includes:e})}function ip(e,t){return new Sd({check:"string_format",format:"starts_with",...$(t),prefix:e})}function op(e,t){return new Ed({check:"string_format",format:"ends_with",...$(t),suffix:e})}function st(e){return new Pd({check:"overwrite",tx:e})}function sp(e){return st(t=>t.normalize(e))}function cp(){return st(e=>e.trim())}function lp(){return st(e=>e.toLowerCase())}function dp(){return st(e=>e.toUpperCase())}function gp(){return st(e=>Tl(e))}function pp(e,t,a){return new e({type:"array",element:t,...$(a)})}function hp(e,t,a){return new e({type:"custom",check:"custom",fn:t,...$(a)})}function up(e){const t=mp(a=>(a.addIssue=n=>{if(typeof n=="string")a.issues.push(mt(n,a.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),a.issues.push(mt(r))}},e(a.value,a)));return t}function mp(e,t){const a=new ue({check:"custom",...$(t)});return a._zod.check=e,a}function fp(e){const t=new ue({check:"describe"});return t._zod.onattach=[a=>{const n=$e.get(a)??{};$e.add(a,{...n,description:e})}],t._zod.check=()=>{},t}function bp(e){const t=new ue({check:"meta"});return t._zod.onattach=[a=>{const n=$e.get(a)??{};$e.add(a,{...n,...e})}],t._zod.check=()=>{},t}function pr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??$e,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ce(e,t,a={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,a.schemaPath.includes(e)&&(i.cycle=a.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:a.path};t.seen.set(e,o);const s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{const l={...a,schemaPath:[...a.schemaPath,e],path:a.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const d=o.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,d,l)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),ce(g,t,l),t.seen.get(g).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&me(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function hr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const s=e.metadataRegistry.get(o[0])?.id;if(s){const c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}const r=o=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(o[0])?.id,d=e.external.uri??(h=>h);if(g)return{ref:d(g)};const p=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=p,{defId:p,ref:`${d("__shared")}#/${s}/${p}`}}if(o[1]===a)return{ref:"#"};const c=`#/${s}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},i=o=>{if(o[1].schema.$ref)return;const s=o[1],{ref:c,defId:l}=r(o);s.def={...s.schema},l&&(s.defId=l);const g=s.schema;for(const d in g)delete g[d];g.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
175
175
|
|
|
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 ur(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 p=e.seen.get(g),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,l),o._zod.parent===g)for(const m in c)m==="$ref"||m==="allOf"||m in l||delete c[m];if(h.$ref&&p.def)for(const m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}const d=o._zod.parent;if(d&&d!==g){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(const h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}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:Ot(t,"input",e.processors),output:Ot(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function me(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 me(n.element,a);if(n.type==="set")return me(n.valueType,a);if(n.type==="lazy")return me(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 me(n.innerType,a);if(n.type==="intersection")return me(n.left,a)||me(n.right,a);if(n.type==="record"||n.type==="map")return me(n.keyType,a)||me(n.valueType,a);if(n.type==="pipe")return me(n.in,a)||me(n.out,a);if(n.type==="object"){for(const r in n.shape)if(me(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(me(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(me(r,a))return!0;return!!(n.rest&&me(n.rest,a))}return!1}var vp=(e,t={})=>a=>{const n=pr({...a,processors:t});return ce(e,n),hr(n,e),ur(n,e)},Ot=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=pr({...r??{},target:i,io:t,processors:a});return ce(e,o),hr(o,e),ur(o,e)},yp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_p=(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=yp[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(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},xp=(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)},wp=(e,t,a,n)=>{a.type="boolean"},kp=(e,t,a,n)=>{a.not={}},Cp=(e,t,a,n)=>{},Sp=(e,t,a,n)=>{const r=e._zod.def,i=kn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Ep=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Pp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ap=(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=ce(i.element,t,{...n,path:[...n.path,"items"]})},Tp=(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]=ce(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=ce(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Lp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ce(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Ip=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ce(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]]},Np=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=ce(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=ce(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=ce(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},zp=(e,t,a,n)=>{const r=e._zod.def,i=ce(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"}]},Mp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Bp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Rp=(e,t,a,n)=>{const r=e._zod.def;ce(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)))},Dp=(e,t,a,n)=>{const r=e._zod.def;ce(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},Op=(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;ce(i,t,n);const o=t.seen.get(e);o.ref=i},$p=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},mr=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Fp=k("ZodISODateTime",(e,t)=>{Hd.init(e,t),re.init(e,t)});function Hp(e){return Vg(Fp,e)}var Up=k("ZodISODate",(e,t)=>{Ud.init(e,t),re.init(e,t)});function jp(e){return Gg(Up,e)}var Zp=k("ZodISOTime",(e,t)=>{jd.init(e,t),re.init(e,t)});function qp(e){return Wg(Zp,e)}var Vp=k("ZodISODuration",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Gp(e){return Kg(Vp,e)}var fr=(e,t)=>{Tn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Ul(e,a)},flatten:{value:a=>Hl(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ca,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ca,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ru=k("ZodError",fr),Se=k("ZodError",fr,{Parent:Error}),Wp=Lt(Se),Kp=It(Se),Yp=Nt(Se),Jp=zt(Se),Xp=Ln(Se),Qp=In(Se),eh=Nn(Se),th=zn(Se),ah=Mn(Se),nh=Bn(Se),rh=Rn(Se),ih=Dn(Se),oe=k("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ot(e,"input"),output:Ot(e,"output")}}),e.toJSONSchema=vp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ze(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)=>qe(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Wp(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>Yp(e,a,n),e.parseAsync=async(a,n)=>Kp(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Jp(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Xp(e,a,n),e.decode=(a,n)=>Qp(e,a,n),e.encodeAsync=async(a,n)=>eh(e,a,n),e.decodeAsync=async(a,n)=>th(e,a,n),e.safeEncode=(a,n)=>ah(e,a,n),e.safeDecode=(a,n)=>nh(e,a,n),e.safeEncodeAsync=async(a,n)=>rh(e,a,n),e.safeDecodeAsync=async(a,n)=>ih(e,a,n),e.refine=(a,n)=>e.check(Jh(a,n)),e.superRefine=a=>e.check(Xh(a)),e.overwrite=a=>e.check(st(a)),e.optional=()=>wr(e),e.exactOptional=()=>Oh(e),e.nullable=()=>kr(e),e.nullish=()=>wr(kr(e)),e.nonoptional=a=>Zh(e,a),e.array=()=>W(e),e.or=a=>ct([e,a]),e.and=a=>zh(e,a),e.transform=a=>Sr(e,Rh(a)),e.default=a=>Hh(e,a),e.prefault=a=>jh(e,a),e.catch=a=>Vh(e,a),e.pipe=a=>Sr(e,a),e.readonly=()=>Kh(e),e.describe=a=>{const n=e.clone();return $e.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return $e.get(e);const n=e.clone();return $e.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),br=k("_ZodString",(e,t)=>{ha.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_p(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(tp(...n)),e.includes=(...n)=>e.check(rp(...n)),e.startsWith=(...n)=>e.check(ip(...n)),e.endsWith=(...n)=>e.check(op(...n)),e.min=(...n)=>e.check(Dt(...n)),e.max=(...n)=>e.check(dr(...n)),e.length=(...n)=>e.check(gr(...n)),e.nonempty=(...n)=>e.check(Dt(1,...n)),e.lowercase=n=>e.check(ap(n)),e.uppercase=n=>e.check(np(n)),e.trim=()=>e.check(cp()),e.normalize=(...n)=>e.check(sp(...n)),e.toLowerCase=()=>e.check(lp()),e.toUpperCase=()=>e.check(dp()),e.slugify=()=>e.check(gp())}),oh=k("ZodString",(e,t)=>{ha.init(e,t),br.init(e,t),e.email=a=>e.check(Sg(sh,a)),e.url=a=>e.check(Lg(ch,a)),e.jwt=a=>e.check(qg(kh,a)),e.emoji=a=>e.check(Ig(lh,a)),e.guid=a=>e.check(or(vr,a)),e.uuid=a=>e.check(Eg($t,a)),e.uuidv4=a=>e.check(Pg($t,a)),e.uuidv6=a=>e.check(Ag($t,a)),e.uuidv7=a=>e.check(Tg($t,a)),e.nanoid=a=>e.check(Ng(dh,a)),e.guid=a=>e.check(or(vr,a)),e.cuid=a=>e.check(zg(gh,a)),e.cuid2=a=>e.check(Mg(ph,a)),e.ulid=a=>e.check(Bg(hh,a)),e.base64=a=>e.check(Ug(_h,a)),e.base64url=a=>e.check(jg(xh,a)),e.xid=a=>e.check(Rg(uh,a)),e.ksuid=a=>e.check(Dg(mh,a)),e.ipv4=a=>e.check(Og(fh,a)),e.ipv6=a=>e.check($g(bh,a)),e.cidrv4=a=>e.check(Fg(vh,a)),e.cidrv6=a=>e.check(Hg(yh,a)),e.e164=a=>e.check(Zg(wh,a)),e.datetime=a=>e.check(Hp(a)),e.date=a=>e.check(jp(a)),e.time=a=>e.check(qp(a)),e.duration=a=>e.check(Gp(a))});function x(e){return Cg(oh,e)}var re=k("ZodStringFormat",(e,t)=>{ne.init(e,t),br.init(e,t)}),sh=k("ZodEmail",(e,t)=>{Nd.init(e,t),re.init(e,t)}),vr=k("ZodGUID",(e,t)=>{Ld.init(e,t),re.init(e,t)}),$t=k("ZodUUID",(e,t)=>{Id.init(e,t),re.init(e,t)}),ch=k("ZodURL",(e,t)=>{zd.init(e,t),re.init(e,t)}),lh=k("ZodEmoji",(e,t)=>{Md.init(e,t),re.init(e,t)}),dh=k("ZodNanoID",(e,t)=>{Bd.init(e,t),re.init(e,t)}),gh=k("ZodCUID",(e,t)=>{Rd.init(e,t),re.init(e,t)}),ph=k("ZodCUID2",(e,t)=>{Dd.init(e,t),re.init(e,t)}),hh=k("ZodULID",(e,t)=>{Od.init(e,t),re.init(e,t)}),uh=k("ZodXID",(e,t)=>{$d.init(e,t),re.init(e,t)}),mh=k("ZodKSUID",(e,t)=>{Fd.init(e,t),re.init(e,t)}),fh=k("ZodIPv4",(e,t)=>{qd.init(e,t),re.init(e,t)}),bh=k("ZodIPv6",(e,t)=>{Vd.init(e,t),re.init(e,t)}),vh=k("ZodCIDRv4",(e,t)=>{Gd.init(e,t),re.init(e,t)}),yh=k("ZodCIDRv6",(e,t)=>{Wd.init(e,t),re.init(e,t)}),_h=k("ZodBase64",(e,t)=>{Kd.init(e,t),re.init(e,t)}),xh=k("ZodBase64URL",(e,t)=>{Jd.init(e,t),re.init(e,t)}),wh=k("ZodE164",(e,t)=>{Xd.init(e,t),re.init(e,t)}),kh=k("ZodJWT",(e,t)=>{eg.init(e,t),re.init(e,t)}),yr=k("ZodNumber",(e,t)=>{Gn.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xp(e,n,r,i),e.gt=(n,r)=>e.check(cr(n,r)),e.gte=(n,r)=>e.check(fa(n,r)),e.min=(n,r)=>e.check(fa(n,r)),e.lt=(n,r)=>e.check(sr(n,r)),e.lte=(n,r)=>e.check(ma(n,r)),e.max=(n,r)=>e.check(ma(n,r)),e.int=n=>e.check(_r(n)),e.safe=n=>e.check(_r(n)),e.positive=n=>e.check(cr(0,n)),e.nonnegative=n=>e.check(fa(0,n)),e.negative=n=>e.check(sr(0,n)),e.nonpositive=n=>e.check(ma(0,n)),e.multipleOf=(n,r)=>e.check(lr(n,r)),e.step=(n,r)=>e.check(lr(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 Ie(e){return Yg(yr,e)}var Ch=k("ZodNumberFormat",(e,t)=>{tg.init(e,t),yr.init(e,t)});function _r(e){return Jg(Ch,e)}var Sh=k("ZodBoolean",(e,t)=>{ag.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wp(e,a,n,r)});function Ke(e){return Xg(Sh,e)}var Eh=k("ZodUnknown",(e,t)=>{ng.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Cp(e,a,n,r)});function ye(){return Qg(Eh)}var Ph=k("ZodNever",(e,t)=>{rg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kp(e,a,n,r)});function Ah(e){return ep(Ph,e)}var Th=k("ZodArray",(e,t)=>{ig.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ap(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Dt(a,n)),e.nonempty=a=>e.check(Dt(1,a)),e.max=(a,n)=>e.check(dr(a,n)),e.length=(a,n)=>e.check(gr(a,n)),e.unwrap=()=>e.element});function W(e,t){return pp(Th,e,t)}var Lh=k("ZodObject",(e,t)=>{sg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Tp(e,a,n,r),Q(e,"shape",()=>t.shape),e.keyof=()=>ft(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ye()}),e.loose=()=>e.clone({...e._zod.def,catchall:ye()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ah()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Rl(e,a),e.safeExtend=a=>Dl(e,a),e.merge=a=>Ol(e,a),e.pick=a=>Ml(e,a),e.omit=a=>Bl(e,a),e.partial=(...a)=>$l(xr,e,a[0]),e.required=(...a)=>Fl(Cr,e,a[0])});function H(e,t){return new Lh({type:"object",shape:e??{},...$(t)})}var Ih=k("ZodUnion",(e,t)=>{cg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Lp(e,a,n,r),e.options=t.options});function ct(e,t){return new Ih({type:"union",options:e,...$(t)})}var Nh=k("ZodIntersection",(e,t)=>{lg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ip(e,a,n,r)});function zh(e,t){return new Nh({type:"intersection",left:e,right:t})}var Mh=k("ZodRecord",(e,t)=>{dg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Np(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ye(e,t,a){return new Mh({type:"record",keyType:e,valueType:t,...$(a)})}var ba=k("ZodEnum",(e,t)=>{gg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sp(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 ba({...t,checks:[],...$(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 ba({...t,checks:[],...$(r),entries:i})}});function ft(e,t){return new ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...$(t)})}var Bh=k("ZodTransform",(e,t)=>{pg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Pp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(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 Rh(e){return new Bh({type:"transform",transform:e})}var xr=k("ZodOptional",(e,t)=>{er.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function wr(e){return new xr({type:"optional",innerType:e})}var Dh=k("ZodExactOptional",(e,t)=>{hg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Oh(e){return new Dh({type:"optional",innerType:e})}var $h=k("ZodNullable",(e,t)=>{ug.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>zp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function kr(e){return new $h({type:"nullable",innerType:e})}var Fh=k("ZodDefault",(e,t)=>{mg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Bp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hh(e,t){return new Fh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Uh=k("ZodPrefault",(e,t)=>{fg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Rp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function jh(e,t){return new Uh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Cr=k("ZodNonOptional",(e,t)=>{bg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Mp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Zh(e,t){return new Cr({type:"nonoptional",innerType:e,...$(t)})}var qh=k("ZodCatch",(e,t)=>{vg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Dp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vh(e,t){return new qh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Gh=k("ZodPipe",(e,t)=>{yg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Op(e,a,n,r),e.in=t.in,e.out=t.out});function Sr(e,t){return new Gh({type:"pipe",in:e,out:t})}var Wh=k("ZodReadonly",(e,t)=>{_g.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Kh(e){return new Wh({type:"readonly",innerType:e})}var Yh=k("ZodCustom",(e,t)=>{xg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ep(e,a,n,r)});function Jh(e,t={}){return hp(Yh,e,t)}function Xh(e){return up(e)}var Du=fp,Ou=bp,Qh=H({role:ft(["user","assistant"]),content:x(),timestamp:Ie().optional()}),eu=H({sku:x(),name:x(),imageUrl:x().url().optional(),price:x().optional(),originalPrice:x().optional(),url:x().url(),ctaLabel:x().optional()}),tu=H({buttons:W(H({label:x(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),au=H({}),nu=H({label:x().optional()}),Er=H({sku:x(),name:x(),price:x(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional()}),ru=H({recommended:Er,products:W(Er),attributes:W(H({label:x(),values:W(x())})),highlights:W(x()),specialCases:W(x()).optional(),recommendedText:x().optional(),winnerHits:Ye(x(),H({positive:W(x()).optional(),negative:W(x()).optional()})).optional(),productActions:Ye(x(),H({title:x(),type:x(),payload:ye().optional()})).optional()}),iu=H({label:x(),sentiment:ft(["positive","negative","neutral"]).optional()}),ou=H({product:Ye(x(),ye()),role:x().optional(),reason:x().optional(),labels:W(iu).optional(),expertQualityScore:Ie().optional(),reviewHighlight:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()}).optional()}),su=H({suggestions:W(ou)}),cu=H({title:x().optional(),text:x().optional(),reviewCount:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}),lu=H({entries:W(H({name:x(),image:x().optional(),description:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),du=H({entries:W(H({shortName:x(),detailedMessage:x().optional(),whyDifferent:x().optional(),image:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),Pr=H({title:x(),type:x(),payload:ye().optional()}),bt=H({name:x().optional(),value:x().optional(),option_value:x().optional(),attribute_value:x().optional(),type:x().optional(),attribute:x().optional(),option_name:x().optional(),attribute_name:x().optional(),variant_name:x().optional(),sku:x().optional(),price:ct([Ie(),x()]).optional(),price_discounted:ct([Ie(),x()]).optional(),image:x().optional(),imageUrl:x().optional(),image_url:x().optional(),color:x().optional(),colour:x().optional(),color_hex:x().optional(),hex:x().optional(),swatch:x().optional(),swatchColor:x().optional(),in_stock:Ke().optional(),inStock:Ke().optional()}),gu=H({product:H({sku:x().optional(),name:x().optional(),images:W(x()).optional(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional(),price:x().optional(),originalPrice:x().optional(),discountReason:x().optional(),discount_reason:x().optional(),campaignReason:x().optional(),campaign_reason:x().optional(),originalPriceStyle:ft(["strikethrough","inline"]).optional(),price_original_style:ft(["strikethrough","inline"]).optional(),price_discount_rate:Ie().optional(),price_async:Ke().optional(),inStock:Ke().optional(),promotions:W(x()).optional(),variants:W(bt).optional(),variantOptions:W(bt).optional(),variant_options:W(bt).optional(),productVariants:W(bt).optional(),product_variants:W(bt).optional(),url:x().optional(),cartCode:x().optional(),description:x().optional(),description_html:x().optional(),descriptionHtml:x().optional(),facet_hits:Ye(x(),ye()).optional(),facetHits:Ye(x(),ye()).optional(),features:W(H({name:x().optional(),key:x().optional(),label:x().optional(),value:ct([x(),Ie(),Ke()]).optional()})).optional(),specifications:ct([Ye(x(),x()),W(H({key:x(),value:x()}))]).optional()}).optional(),action:Pr.optional()}),pu=H({endOfList:Ke().optional()}),hu=H({review_class:x().optional(),review_text:x().optional(),review_rating:ct([x(),Ie()]).optional(),review_tag:x().optional()}),uu=H({reviews:W(hu).optional()}),mu=H({productName:x().optional(),pros:W(x()).optional(),cons:W(x()).optional()}),fu=H({groups:W(H({groupName:x(),products:W(Ye(x(),ye())).optional()})).optional(),filterTags:W(H({title:x(),action:Pr.optional()})).optional()}),bu=H({summary:x().optional(),products_discussed:W(x()).optional(),user_sentiment:x().optional()}),vu=H({summary:x(),clues:W(x()),strengths:W(x()).optional(),focus_points:W(x()).optional(),celeb_style:x().optional(),celeb_style_reason:x().optional(),details:W(x()).optional(),next_question:x().optional(),style_images:W(x()).optional()}),yu=H({processing:Ke().optional(),title:x().optional(),description:x().optional(),upload_label:x().optional(),skip_label:x().optional()}),_u={components:{MessageBubble:{schema:Qh,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:eu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:tu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:au,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:nu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ru,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:cu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:lu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:du,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:gu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:pu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:uu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:mu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:fu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:vu,description:"Structured photo analysis card with strengths, focus points, celeb vibe, details, and follow-up question."},BeautyPhotoStep:{schema:yu,description:"Transient selfie upload prompt for beauty consulting init flow."}}};function Ar(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function va(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Tr=class lt extends ui{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._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},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._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=Gt,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 bn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new ns}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=Qc(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=gl,this._shadow.appendChild(a);const n=this.root,r=(u,f)=>{f&&Ar(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",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=ds(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 Xo(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(wl(),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 Kc({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Yc({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"),d=sessionStorage.getItem("gengage_restore_sku"),p=!!(g&&d);p&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new Gc;await u.open(),this._session=new fn(u),await this._restoreFromIndexedDB(p)}catch{this._session=new fn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const h=()=>this._syncViewportState();if(window.addEventListener("resize",h,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",h)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const f=this._drawer?.getElement();if(!f)return;const y=window.innerHeight-(window.visualViewport?.height??window.innerHeight);f.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,y)}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 m={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(m.allowedOrigins=t.allowedOrigins),this._bridge=new fi(m),this._lastSku=this.config.pageContext?.sku,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),we("gengage:chat:ready",{}),hl("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),we("gengage:chat:open",{state:this._openState}),ul("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!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,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),we("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(),Da(),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="${CSS.escape(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._entryContextPrimed=!1,this._pdpPrimingInFlight=!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._choicePrompterEl?.remove(),this._choicePrompterEl=null,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)}_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=Xc(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=va(n)?n:va(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}),va(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"&&Ar(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))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ea(),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}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))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}_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()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();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(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=Ci(t);if(!a.ok){we("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._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(oa(this.config.accountId),this._drawer?.hideKvkkBanner()),Sl(),this._messages.some(r=>r.role==="user")||El(),Me("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._pdpPrimingInFlight||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._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_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._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Uc(),!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 v=this._currentThreadId,b=this._messages.filter(_=>_.threadId!==void 0&&_.threadId>v);this._messages=this._messages.filter(_=>!_.threadId||_.threadId<=v);for(const _ of b)this._shadow?.querySelector(`[data-message-id="${CSS.escape(_.id)}"]`)?.remove(),this._panel.snapshots.delete(_.id),this._panel.snapshotTypes.delete(_.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(_=>{_ instanceof HTMLElement&&_.dataset.threadId&&_.dataset.threadId>v&&_.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ea();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const v=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,b=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(b!==void 0&&b.role==="user"&&b.content===v)){const _=this._createMessage("user",v);_.threadId=n,a?.attachment!==void 0&&(_.attachment=a.attachment),this._drawer?.addMessage(_),this._messages.push(_)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const v=this._i18n.productNotFoundMessage,b=this._createMessage("assistant",v);b.threadId=n,b.status="done",this._messages.push(b),this._ensureAssistantMessageRendered(b),this._drawer?.updateBotMessage(b.id,v),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",b),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const v=this._buildRenderContext(),b=this._renderPanelFromSource(o,v);this._drawer.setPanelContent(b),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";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._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const p={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(p.attachment=a.attachment);const h=this._getVisibleMessages().filter(v=>v!==d&&(v.content||v.role==="assistant")).slice(-50).map(v=>({role:v.role==="user"?"user":"model",content:v.content??""})),m={outputLanguage:dl(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:yn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(m.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(m.viewId=this.config.session.viewId);const u=ko(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),f={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:u.type,locale:this.config.locale??"tr",meta:m,context:{...this._lastBackendContext??{},messages:h,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(f.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(f.view_id=this.config.session.viewId),u.payload!==void 0&&(f.payload=u.payload),this.config.pageContext?.sku!==void 0&&(f.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(f.page_type=this.config.pageContext.pageType);const y=crypto.randomUUID(),M=Date.now();let C=0,P=!1,w=!1,N=!1,R=!1,L=!1;const Z=rs();let te=null;const X=()=>{if(this._drawer){if(this._isMobileViewport||!N){this._drawer.setPanelAiZoneState("hidden");return}R||(L?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(zr(this.analyticsContext(),{endpoint:"process_action",request_id:y,widget:"chat"}));let I=null;if(I=Eo(f,{onTextChunk:(v,b,_)=>{if(!r&&n!==this._activeRequestThreadId||(g+=v,this._drawer?.removeTypingIndicator(),_?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,..._.skuToProductItem}),_?.conversationMode&&(this._conversationMode=_.conversationMode),_?.renderHint&&(d.renderHint=_.renderHint),this.track(Mr(this.analyticsContext(),{request_id:y,chunk_index:C++,widget:"chat"})),!this._drawer))return;let S=g;const T=_?.kvkk===!0||ia(S);if(b&&T){const D=this.config.accountId;if(!yn(D)){const A=cl(S);A?this._drawer?.showKvkkBanner(A,()=>{this._drawer?.hideKvkkBanner(),oa(D)}):oa(D)}S=sl(S)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=Ae(S):(d.content=S,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),b)if(d.content=S,d.status="done",xn(),os(d))this._drawer?.updateBotMessage(d.id,S,"photo_analysis",d.photoAnalysis);else{const D=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(D){this._activeTypewriter?.cancel();const A=_?.productMentions;this._activeTypewriter=Bc({container:D,html:Ae(S),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,A&&A.length>0&&D&&Rc({container:D,mentions:A,onProductClick:U=>{this._sendAction({title:A.find(F=>F.sku===U)?.short_name??U,type:"launchSingleProduct",payload:{sku:U}})}})}})}}},onUISpec:(v,b,_,S)=>{if(!r&&n!==this._activeRequestThreadId||b!=="chat")return;S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const T=v.elements[v.root],z=T?.type??"unknown";if(is(z,T?.props??{},Z,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:L},d))return;const D=z==="ProductGrid"&&T?.props?.similarsAppend===!0,A=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||D);A&&!S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const U=z==="ProductDetailsPanel"&&_!=="panel"?"panel":_;this.track(Br(this.analyticsContext(),{request_id:y,chunk_index:C,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const j=T?.props?.products;_l(Array.isArray(j)?j.length:0)}if(z==="ProductGrid"){const j=T?.children?.length??0;kl(void 0,j)}const K=U==="panel"&&this._panel?this._panel.toPanelSpec(v):v;if(U==="panel"&&this._panel&&!A){const j=!w;w=!0;const B=Jc({componentType:z,similarsAppend:T?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:j});F.panelProductListHeading=void 0,z==="ProductGrid"&&(B==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:K})),B==="appendSimilars"?this._appendSimilarsToPanel(K,F):B==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(K,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(K,F)),this._currentPanelSource={kind:"spec",spec:K},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const J=this._panel.currentType??z,O=T?.props?.panelTitle;if(this._panel.updateTopBar(J,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(N=!this._isMobileViewport,te){const se=this._buildRenderContext();se.isStreaming=!0;const Ft=this._renderUISpec(te,se);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Ft}),te=null}}else B!=="appendSimilars"&&B!=="append"&&(N=!1,te=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&U==="panel"&&(!d.silent||i)){const j=T?.props?.product;if(j){const B={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:j}}}},J=this._shadow?.querySelector(".gengage-chat-messages");if(J){const O=this._renderUISpec(B,F);d.threadId&&(O.dataset.threadId=d.threadId);const se=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);se&&se.parentNode===J?se.after(O):J.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),w=!0}}}const ee=z==="AITopPicks"||z==="AIGroupingCards";let ae=!1,de=!1;if(A&&D&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),ee&&!this._isMobileViewport&&!d.silent)if(N){const j=this._renderUISpec(v,F);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:j}),ae=!0,te=null}else te=v,de=!0;const q=i&&z==="GroundingReviewCard";if((!d.silent||q)&&(U!=="panel"||z==="ProductCard"||A&&z==="ProductGrid"&&(!D||this._isMobileViewport))&&z!=="ActionButtons"&&!ae&&!(de&&ee)){const j=this._shadow?.querySelector(".gengage-chat-messages");if(j){const B=this._renderUISpec(v,F);d.threadId&&(B.dataset.threadId=d.threadId),j.appendChild(B),B.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),A&&z==="ProductGrid"&&(w=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const j=T?.children??[],B=z==="ProductGrid"?j.map(J=>v.elements[J]?.props?.product).filter(Boolean):[T?.props?.product].filter(Boolean);for(const J of B){const O=J.sku,se=J.imageUrl;O&&se&&this._thumbnailEntries.push({sku:O,imageUrl:se,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const j=(z==="ProductGrid"?(T?.children??[]).map(B=>v.elements[B]?.props?.product).filter(Boolean):[T?.props?.product??T?.props].filter(Boolean)).map(B=>B.imageUrl).filter(B=>typeof B=="string").slice(0,5);j.length>0&&this._bridge?.send("previewImages",{images:j})}const _e=T?.children?.length??0;if(z==="ProductGrid"&&U==="panel"&&!A&&_e>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!jc(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(B=>B.remove()),this._choicePrompterEl=Hc({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}});const j=this._shadow?.querySelector(".gengage-chat-panel-float");if(j){if(j.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const B=this._choicePrompterEl,J=()=>{window.visualViewport.height/window.innerHeight<.75&&(B.remove(),this._choicePrompterEl===B&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",J))};window.visualViewport.addEventListener("resize",J)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const j=T?.props?.buttons;if(j&&j.length>0){const B=[],J=[];for(const O of j)if($c(O)){const se={label:O.label,action:O.action};O.icon&&(se.icon=O.icon),B.push(se)}else J.push(O);B.length>0&&this._drawer?.setInputAreaChips(B.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),J.length>0&&this._drawer?.setPills(J.map(O=>{const se={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(se.icon=O.icon),O.image&&(se.image=O.image),O.description&&(se.description=O.description),se}))}}X(),d.uiSpec=v},onAction:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="action"){const b={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(b.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(b.allowScriptCall=this.config.actionHandling.allowScriptCall),_i(v,{openChat:()=>this.open(),navigate:_=>{fe(_.url)&&(this._bridge?.send("navigate",_),_.newTab?window.open(_.url,"_blank","noopener,noreferrer"):window.location.href=_.url)},saveSession:_=>this.saveSession(_.sessionId,_.sku),addToCart:_=>{we("gengage:similar:add-to-cart",_)},scriptCall:_=>{we("gengage:chat:script-call",_),this.config.onScriptCall?.(_)}},b)}},onMetadata:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="metadata"&&v.meta){if(v.meta.panel!==void 0||v.meta.messages!==void 0||v.meta.message_id!==void 0){this._lastBackendContext=v.meta;const _=Yt(v.meta.panel);_&&(this._modeController.updateFromContext(_),this._applyUiHints())}if(v.meta.panelLoading){const _=typeof v.meta.panelPendingType=="string"?v.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(_==="productDetails"||_==="productDetailsSimilars")||(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(_),_&&this._panel?.updateTopBarForLoading(_))}if(v.meta.voice){const _=new CustomEvent("gengage:chat:voice",{detail:{payload:v.meta.voice},bubbles:!1,cancelable:!0}),S=window.dispatchEvent(_);if(Pl(),S){const T=v.meta.voice;T.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=ps(T.audio_base64,T.content_type??"audio/ogg"))}}if((v.meta.redirectTarget||v.meta.redirect)&&(we("gengage:chat:redirect",{target:v.meta.redirectTarget??null,payload:v.meta.redirect??null}),Me("redirect","redirect dispatched",{target:v.meta.redirectTarget??null}),this._handleRedirectMetadata(v.meta.redirect)),v.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),v.meta.loading){const _=Array.isArray(v.meta.thinkingMessages)?v.meta.thinkingMessages.filter(T=>typeof T=="string"):[],S=typeof v.meta.loadingText=="string"?v.meta.loadingText:void 0;if(_.length>0){const T=S&&this._modeController.shouldCondenseThinking()?[..._.slice(0,2),S]:_;this._drawer?.setThinkingSteps(T)}typeof S=="string"&&S.length>0&&(this._drawer?.addThinkingStep(S),this._bridge?.send("loadingMessage",{text:S}))}v.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",v.meta.visitorDataResponse),v.meta.formType&&this._bridge?.send("glovOtokoc",{type:v.meta.formType,data:v.meta.formPayload}),v.meta.launcherContent&&this._bridge?.send("launcherContent",v.meta.launcherContent),we("gengage:chat:metadata",{payload:v.meta});const b=v.meta;typeof b.prompt_tokens=="number"&&typeof b.completion_tokens=="number"&&this.track(Or(this.analyticsContext(),{model:v.model??"unknown",prompt_tokens:b.prompt_tokens,completion_tokens:b.completion_tokens,total_tokens:b.total_tokens??b.prompt_tokens+b.completion_tokens}))}},onError:v=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;L=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,X(),te=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),cs(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const b=w;P&&!w&&l(),P=!1,w=!1;const _=d.silent||d.content!=null&&d.content.length>0||g.length>0||b,S=typeof navigator<"u"&&navigator.onLine===!1&&Sa(v),T=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const A=this._messages.indexOf(d);A>=0&&this._messages.splice(A,1)};let z=!1;const D=()=>{if(S)return;this.emit("error",v);const A=v.message;A===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=A);const U=v.message.trim(),F=U.length>0?U:this._i18n.errorMessage,K={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){T(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,K);return}if(rl(v,F)){T(),z=!0,this._drawer?.showErrorWithRecovery(F,K);return}d.content=F,d.status="done";const ee=Ae(F.replace(/\r\n/g,`
|
|
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 ur(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 p=e.seen.get(g),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,l),o._zod.parent===g)for(const m in c)m==="$ref"||m==="allOf"||m in l||delete c[m];if(h.$ref&&p.def)for(const m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}const d=o._zod.parent;if(d&&d!==g){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(const h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}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:Ot(t,"input",e.processors),output:Ot(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function me(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 me(n.element,a);if(n.type==="set")return me(n.valueType,a);if(n.type==="lazy")return me(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 me(n.innerType,a);if(n.type==="intersection")return me(n.left,a)||me(n.right,a);if(n.type==="record"||n.type==="map")return me(n.keyType,a)||me(n.valueType,a);if(n.type==="pipe")return me(n.in,a)||me(n.out,a);if(n.type==="object"){for(const r in n.shape)if(me(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(me(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(me(r,a))return!0;return!!(n.rest&&me(n.rest,a))}return!1}var vp=(e,t={})=>a=>{const n=pr({...a,processors:t});return ce(e,n),hr(n,e),ur(n,e)},Ot=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=pr({...r??{},target:i,io:t,processors:a});return ce(e,o),hr(o,e),ur(o,e)},yp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_p=(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=yp[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(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},xp=(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)},wp=(e,t,a,n)=>{a.type="boolean"},kp=(e,t,a,n)=>{a.not={}},Cp=(e,t,a,n)=>{},Sp=(e,t,a,n)=>{const r=e._zod.def,i=kn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Ep=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Pp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ap=(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=ce(i.element,t,{...n,path:[...n.path,"items"]})},Tp=(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]=ce(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=ce(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Lp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ce(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Ip=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ce(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]]},Np=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=ce(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=ce(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=ce(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},zp=(e,t,a,n)=>{const r=e._zod.def,i=ce(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"}]},Mp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Bp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Rp=(e,t,a,n)=>{const r=e._zod.def;ce(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)))},Dp=(e,t,a,n)=>{const r=e._zod.def;ce(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},Op=(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;ce(i,t,n);const o=t.seen.get(e);o.ref=i},$p=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},mr=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Fp=k("ZodISODateTime",(e,t)=>{Hd.init(e,t),re.init(e,t)});function Hp(e){return Vg(Fp,e)}var Up=k("ZodISODate",(e,t)=>{Ud.init(e,t),re.init(e,t)});function jp(e){return Gg(Up,e)}var Zp=k("ZodISOTime",(e,t)=>{jd.init(e,t),re.init(e,t)});function qp(e){return Wg(Zp,e)}var Vp=k("ZodISODuration",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Gp(e){return Kg(Vp,e)}var fr=(e,t)=>{Tn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Ul(e,a)},flatten:{value:a=>Hl(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ca,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ca,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ru=k("ZodError",fr),Se=k("ZodError",fr,{Parent:Error}),Wp=Lt(Se),Kp=It(Se),Yp=Nt(Se),Jp=zt(Se),Xp=Ln(Se),Qp=In(Se),eh=Nn(Se),th=zn(Se),ah=Mn(Se),nh=Bn(Se),rh=Rn(Se),ih=Dn(Se),oe=k("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ot(e,"input"),output:Ot(e,"output")}}),e.toJSONSchema=vp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ze(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)=>qe(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Wp(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>Yp(e,a,n),e.parseAsync=async(a,n)=>Kp(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Jp(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Xp(e,a,n),e.decode=(a,n)=>Qp(e,a,n),e.encodeAsync=async(a,n)=>eh(e,a,n),e.decodeAsync=async(a,n)=>th(e,a,n),e.safeEncode=(a,n)=>ah(e,a,n),e.safeDecode=(a,n)=>nh(e,a,n),e.safeEncodeAsync=async(a,n)=>rh(e,a,n),e.safeDecodeAsync=async(a,n)=>ih(e,a,n),e.refine=(a,n)=>e.check(Jh(a,n)),e.superRefine=a=>e.check(Xh(a)),e.overwrite=a=>e.check(st(a)),e.optional=()=>wr(e),e.exactOptional=()=>Oh(e),e.nullable=()=>kr(e),e.nullish=()=>wr(kr(e)),e.nonoptional=a=>Zh(e,a),e.array=()=>Y(e),e.or=a=>ct([e,a]),e.and=a=>zh(e,a),e.transform=a=>Sr(e,Rh(a)),e.default=a=>Hh(e,a),e.prefault=a=>jh(e,a),e.catch=a=>Vh(e,a),e.pipe=a=>Sr(e,a),e.readonly=()=>Kh(e),e.describe=a=>{const n=e.clone();return $e.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return $e.get(e);const n=e.clone();return $e.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),br=k("_ZodString",(e,t)=>{ha.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_p(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(tp(...n)),e.includes=(...n)=>e.check(rp(...n)),e.startsWith=(...n)=>e.check(ip(...n)),e.endsWith=(...n)=>e.check(op(...n)),e.min=(...n)=>e.check(Dt(...n)),e.max=(...n)=>e.check(dr(...n)),e.length=(...n)=>e.check(gr(...n)),e.nonempty=(...n)=>e.check(Dt(1,...n)),e.lowercase=n=>e.check(ap(n)),e.uppercase=n=>e.check(np(n)),e.trim=()=>e.check(cp()),e.normalize=(...n)=>e.check(sp(...n)),e.toLowerCase=()=>e.check(lp()),e.toUpperCase=()=>e.check(dp()),e.slugify=()=>e.check(gp())}),oh=k("ZodString",(e,t)=>{ha.init(e,t),br.init(e,t),e.email=a=>e.check(Sg(sh,a)),e.url=a=>e.check(Lg(ch,a)),e.jwt=a=>e.check(qg(kh,a)),e.emoji=a=>e.check(Ig(lh,a)),e.guid=a=>e.check(or(vr,a)),e.uuid=a=>e.check(Eg($t,a)),e.uuidv4=a=>e.check(Pg($t,a)),e.uuidv6=a=>e.check(Ag($t,a)),e.uuidv7=a=>e.check(Tg($t,a)),e.nanoid=a=>e.check(Ng(dh,a)),e.guid=a=>e.check(or(vr,a)),e.cuid=a=>e.check(zg(gh,a)),e.cuid2=a=>e.check(Mg(ph,a)),e.ulid=a=>e.check(Bg(hh,a)),e.base64=a=>e.check(Ug(_h,a)),e.base64url=a=>e.check(jg(xh,a)),e.xid=a=>e.check(Rg(uh,a)),e.ksuid=a=>e.check(Dg(mh,a)),e.ipv4=a=>e.check(Og(fh,a)),e.ipv6=a=>e.check($g(bh,a)),e.cidrv4=a=>e.check(Fg(vh,a)),e.cidrv6=a=>e.check(Hg(yh,a)),e.e164=a=>e.check(Zg(wh,a)),e.datetime=a=>e.check(Hp(a)),e.date=a=>e.check(jp(a)),e.time=a=>e.check(qp(a)),e.duration=a=>e.check(Gp(a))});function x(e){return Cg(oh,e)}var re=k("ZodStringFormat",(e,t)=>{ne.init(e,t),br.init(e,t)}),sh=k("ZodEmail",(e,t)=>{Nd.init(e,t),re.init(e,t)}),vr=k("ZodGUID",(e,t)=>{Ld.init(e,t),re.init(e,t)}),$t=k("ZodUUID",(e,t)=>{Id.init(e,t),re.init(e,t)}),ch=k("ZodURL",(e,t)=>{zd.init(e,t),re.init(e,t)}),lh=k("ZodEmoji",(e,t)=>{Md.init(e,t),re.init(e,t)}),dh=k("ZodNanoID",(e,t)=>{Bd.init(e,t),re.init(e,t)}),gh=k("ZodCUID",(e,t)=>{Rd.init(e,t),re.init(e,t)}),ph=k("ZodCUID2",(e,t)=>{Dd.init(e,t),re.init(e,t)}),hh=k("ZodULID",(e,t)=>{Od.init(e,t),re.init(e,t)}),uh=k("ZodXID",(e,t)=>{$d.init(e,t),re.init(e,t)}),mh=k("ZodKSUID",(e,t)=>{Fd.init(e,t),re.init(e,t)}),fh=k("ZodIPv4",(e,t)=>{qd.init(e,t),re.init(e,t)}),bh=k("ZodIPv6",(e,t)=>{Vd.init(e,t),re.init(e,t)}),vh=k("ZodCIDRv4",(e,t)=>{Gd.init(e,t),re.init(e,t)}),yh=k("ZodCIDRv6",(e,t)=>{Wd.init(e,t),re.init(e,t)}),_h=k("ZodBase64",(e,t)=>{Kd.init(e,t),re.init(e,t)}),xh=k("ZodBase64URL",(e,t)=>{Jd.init(e,t),re.init(e,t)}),wh=k("ZodE164",(e,t)=>{Xd.init(e,t),re.init(e,t)}),kh=k("ZodJWT",(e,t)=>{eg.init(e,t),re.init(e,t)}),yr=k("ZodNumber",(e,t)=>{Gn.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xp(e,n,r,i),e.gt=(n,r)=>e.check(cr(n,r)),e.gte=(n,r)=>e.check(fa(n,r)),e.min=(n,r)=>e.check(fa(n,r)),e.lt=(n,r)=>e.check(sr(n,r)),e.lte=(n,r)=>e.check(ma(n,r)),e.max=(n,r)=>e.check(ma(n,r)),e.int=n=>e.check(_r(n)),e.safe=n=>e.check(_r(n)),e.positive=n=>e.check(cr(0,n)),e.nonnegative=n=>e.check(fa(0,n)),e.negative=n=>e.check(sr(0,n)),e.nonpositive=n=>e.check(ma(0,n)),e.multipleOf=(n,r)=>e.check(lr(n,r)),e.step=(n,r)=>e.check(lr(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 Ie(e){return Yg(yr,e)}var Ch=k("ZodNumberFormat",(e,t)=>{tg.init(e,t),yr.init(e,t)});function _r(e){return Jg(Ch,e)}var Sh=k("ZodBoolean",(e,t)=>{ag.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wp(e,a,n,r)});function Ke(e){return Xg(Sh,e)}var Eh=k("ZodUnknown",(e,t)=>{ng.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Cp(e,a,n,r)});function ye(){return Qg(Eh)}var Ph=k("ZodNever",(e,t)=>{rg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kp(e,a,n,r)});function Ah(e){return ep(Ph,e)}var Th=k("ZodArray",(e,t)=>{ig.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ap(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Dt(a,n)),e.nonempty=a=>e.check(Dt(1,a)),e.max=(a,n)=>e.check(dr(a,n)),e.length=(a,n)=>e.check(gr(a,n)),e.unwrap=()=>e.element});function Y(e,t){return pp(Th,e,t)}var Lh=k("ZodObject",(e,t)=>{sg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Tp(e,a,n,r),Q(e,"shape",()=>t.shape),e.keyof=()=>ft(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ye()}),e.loose=()=>e.clone({...e._zod.def,catchall:ye()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ah()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Rl(e,a),e.safeExtend=a=>Dl(e,a),e.merge=a=>Ol(e,a),e.pick=a=>Ml(e,a),e.omit=a=>Bl(e,a),e.partial=(...a)=>$l(xr,e,a[0]),e.required=(...a)=>Fl(Cr,e,a[0])});function H(e,t){return new Lh({type:"object",shape:e??{},...$(t)})}var Ih=k("ZodUnion",(e,t)=>{cg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Lp(e,a,n,r),e.options=t.options});function ct(e,t){return new Ih({type:"union",options:e,...$(t)})}var Nh=k("ZodIntersection",(e,t)=>{lg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ip(e,a,n,r)});function zh(e,t){return new Nh({type:"intersection",left:e,right:t})}var Mh=k("ZodRecord",(e,t)=>{dg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Np(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ye(e,t,a){return new Mh({type:"record",keyType:e,valueType:t,...$(a)})}var ba=k("ZodEnum",(e,t)=>{gg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sp(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 ba({...t,checks:[],...$(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 ba({...t,checks:[],...$(r),entries:i})}});function ft(e,t){return new ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...$(t)})}var Bh=k("ZodTransform",(e,t)=>{pg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Pp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(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 Rh(e){return new Bh({type:"transform",transform:e})}var xr=k("ZodOptional",(e,t)=>{er.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function wr(e){return new xr({type:"optional",innerType:e})}var Dh=k("ZodExactOptional",(e,t)=>{hg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Oh(e){return new Dh({type:"optional",innerType:e})}var $h=k("ZodNullable",(e,t)=>{ug.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>zp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function kr(e){return new $h({type:"nullable",innerType:e})}var Fh=k("ZodDefault",(e,t)=>{mg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Bp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hh(e,t){return new Fh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Uh=k("ZodPrefault",(e,t)=>{fg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Rp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function jh(e,t){return new Uh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Cr=k("ZodNonOptional",(e,t)=>{bg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Mp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Zh(e,t){return new Cr({type:"nonoptional",innerType:e,...$(t)})}var qh=k("ZodCatch",(e,t)=>{vg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Dp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vh(e,t){return new qh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Gh=k("ZodPipe",(e,t)=>{yg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Op(e,a,n,r),e.in=t.in,e.out=t.out});function Sr(e,t){return new Gh({type:"pipe",in:e,out:t})}var Wh=k("ZodReadonly",(e,t)=>{_g.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Kh(e){return new Wh({type:"readonly",innerType:e})}var Yh=k("ZodCustom",(e,t)=>{xg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ep(e,a,n,r)});function Jh(e,t={}){return hp(Yh,e,t)}function Xh(e){return up(e)}var Du=fp,Ou=bp,Qh=H({role:ft(["user","assistant"]),content:x(),timestamp:Ie().optional()}),eu=H({sku:x(),name:x(),imageUrl:x().url().optional(),price:x().optional(),originalPrice:x().optional(),url:x().url(),ctaLabel:x().optional()}),tu=H({buttons:Y(H({label:x(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),au=H({}),nu=H({label:x().optional()}),Er=H({sku:x(),name:x(),price:x(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional()}),ru=H({recommended:Er,products:Y(Er),attributes:Y(H({label:x(),values:Y(x())})),highlights:Y(x()),specialCases:Y(x()).optional(),recommendedText:x().optional(),winnerHits:Ye(x(),H({positive:Y(x()).optional(),negative:Y(x()).optional()})).optional(),productActions:Ye(x(),H({title:x(),type:x(),payload:ye().optional()})).optional()}),iu=H({label:x(),sentiment:ft(["positive","negative","neutral"]).optional()}),ou=H({product:Ye(x(),ye()),role:x().optional(),reason:x().optional(),labels:Y(iu).optional(),expertQualityScore:Ie().optional(),reviewHighlight:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()}).optional()}),su=H({suggestions:Y(ou)}),cu=H({title:x().optional(),text:x().optional(),reviewCount:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}),lu=H({entries:Y(H({name:x(),image:x().optional(),description:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),du=H({entries:Y(H({shortName:x(),detailedMessage:x().optional(),whyDifferent:x().optional(),image:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),Pr=H({title:x(),type:x(),payload:ye().optional()}),bt=H({name:x().optional(),value:x().optional(),option_value:x().optional(),attribute_value:x().optional(),type:x().optional(),attribute:x().optional(),option_name:x().optional(),attribute_name:x().optional(),variant_name:x().optional(),sku:x().optional(),price:ct([Ie(),x()]).optional(),price_discounted:ct([Ie(),x()]).optional(),image:x().optional(),imageUrl:x().optional(),image_url:x().optional(),color:x().optional(),colour:x().optional(),color_hex:x().optional(),hex:x().optional(),swatch:x().optional(),swatchColor:x().optional(),in_stock:Ke().optional(),inStock:Ke().optional()}),gu=H({product:H({sku:x().optional(),name:x().optional(),images:Y(x()).optional(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional(),price:x().optional(),originalPrice:x().optional(),discountReason:x().optional(),discount_reason:x().optional(),campaignReason:x().optional(),campaign_reason:x().optional(),originalPriceStyle:ft(["strikethrough","inline"]).optional(),price_original_style:ft(["strikethrough","inline"]).optional(),price_discount_rate:Ie().optional(),price_async:Ke().optional(),inStock:Ke().optional(),promotions:Y(x()).optional(),variants:Y(bt).optional(),variantOptions:Y(bt).optional(),variant_options:Y(bt).optional(),productVariants:Y(bt).optional(),product_variants:Y(bt).optional(),url:x().optional(),cartCode:x().optional(),description:x().optional(),description_html:x().optional(),descriptionHtml:x().optional(),facet_hits:Ye(x(),ye()).optional(),facetHits:Ye(x(),ye()).optional(),features:Y(H({name:x().optional(),key:x().optional(),label:x().optional(),value:ct([x(),Ie(),Ke()]).optional()})).optional(),specifications:ct([Ye(x(),x()),Y(H({key:x(),value:x()}))]).optional()}).optional(),action:Pr.optional()}),pu=H({endOfList:Ke().optional()}),hu=H({review_class:x().optional(),review_text:x().optional(),review_rating:ct([x(),Ie()]).optional(),review_tag:x().optional()}),uu=H({reviews:Y(hu).optional()}),mu=H({productName:x().optional(),pros:Y(x()).optional(),cons:Y(x()).optional()}),fu=H({groups:Y(H({groupName:x(),products:Y(Ye(x(),ye())).optional()})).optional(),filterTags:Y(H({title:x(),action:Pr.optional()})).optional()}),bu=H({summary:x().optional(),products_discussed:Y(x()).optional(),user_sentiment:x().optional()}),vu=H({summary:x(),strengths:Y(x()).optional(),focus_points:Y(x()).optional(),celeb_style:x().optional(),celeb_style_reason:x().optional(),details:Y(x()),next_question:x().optional(),style_images:Y(x()).optional()}),yu=H({processing:Ke().optional(),title:x().optional(),description:x().optional(),upload_label:x().optional(),skip_label:x().optional()}),_u={components:{MessageBubble:{schema:Qh,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:eu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:tu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:au,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:nu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ru,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:cu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:lu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:du,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:gu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:pu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:uu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:mu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:fu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:vu,description:"Structured photo analysis card with strengths, focus points, celeb vibe, details, and follow-up question."},BeautyPhotoStep:{schema:yu,description:"Transient selfie upload prompt for beauty consulting init flow."}}};function Ar(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function va(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Tr=class lt extends ui{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._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},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._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=Gt,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 bn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new ns}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=Qc(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=gl,this._shadow.appendChild(a);const n=this.root,r=(u,f)=>{f&&Ar(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",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=ds(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 Xo(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(wl(),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 Kc({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Yc({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"),d=sessionStorage.getItem("gengage_restore_sku"),p=!!(g&&d);p&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new Gc;await u.open(),this._session=new fn(u),await this._restoreFromIndexedDB(p)}catch{this._session=new fn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const h=()=>this._syncViewportState();if(window.addEventListener("resize",h,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",h)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const f=this._drawer?.getElement();if(!f)return;const y=window.innerHeight-(window.visualViewport?.height??window.innerHeight);f.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,y)}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 m={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(m.allowedOrigins=t.allowedOrigins),this._bridge=new fi(m),this._lastSku=this.config.pageContext?.sku,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),we("gengage:chat:ready",{}),hl("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),we("gengage:chat:open",{state:this._openState}),ul("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!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,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),we("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(),Da(),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="${CSS.escape(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._entryContextPrimed=!1,this._pdpPrimingInFlight=!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._choicePrompterEl?.remove(),this._choicePrompterEl=null,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)}_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=Xc(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=va(n)?n:va(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}),va(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"&&Ar(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))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ea(),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}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))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}_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()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();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(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=Ci(t);if(!a.ok){we("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._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(oa(this.config.accountId),this._drawer?.hideKvkkBanner()),Sl(),this._messages.some(r=>r.role==="user")||El(),Me("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._pdpPrimingInFlight||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._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_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._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Uc(),!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 v=this._currentThreadId,b=this._messages.filter(_=>_.threadId!==void 0&&_.threadId>v);this._messages=this._messages.filter(_=>!_.threadId||_.threadId<=v);for(const _ of b)this._shadow?.querySelector(`[data-message-id="${CSS.escape(_.id)}"]`)?.remove(),this._panel.snapshots.delete(_.id),this._panel.snapshotTypes.delete(_.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(_=>{_ instanceof HTMLElement&&_.dataset.threadId&&_.dataset.threadId>v&&_.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ea();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const v=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,b=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(b!==void 0&&b.role==="user"&&b.content===v)){const _=this._createMessage("user",v);_.threadId=n,a?.attachment!==void 0&&(_.attachment=a.attachment),this._drawer?.addMessage(_),this._messages.push(_)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const v=this._i18n.productNotFoundMessage,b=this._createMessage("assistant",v);b.threadId=n,b.status="done",this._messages.push(b),this._ensureAssistantMessageRendered(b),this._drawer?.updateBotMessage(b.id,v),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",b),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const v=this._buildRenderContext(),b=this._renderPanelFromSource(o,v);this._drawer.setPanelContent(b),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";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._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const p={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(p.attachment=a.attachment);const h=this._getVisibleMessages().filter(v=>v!==d&&(v.content||v.role==="assistant")).slice(-50).map(v=>({role:v.role==="user"?"user":"model",content:v.content??""})),m={outputLanguage:dl(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:yn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(m.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(m.viewId=this.config.session.viewId);const u=ko(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),f={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:u.type,locale:this.config.locale??"tr",meta:m,context:{...this._lastBackendContext??{},messages:h,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(f.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(f.view_id=this.config.session.viewId),u.payload!==void 0&&(f.payload=u.payload),this.config.pageContext?.sku!==void 0&&(f.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(f.page_type=this.config.pageContext.pageType);const y=crypto.randomUUID(),M=Date.now();let C=0,P=!1,w=!1,N=!1,R=!1,L=!1;const Z=rs();let te=null;const X=()=>{if(this._drawer){if(this._isMobileViewport||!N){this._drawer.setPanelAiZoneState("hidden");return}R||(L?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(zr(this.analyticsContext(),{endpoint:"process_action",request_id:y,widget:"chat"}));let I=null;if(I=Eo(f,{onTextChunk:(v,b,_)=>{if(!r&&n!==this._activeRequestThreadId||(g+=v,this._drawer?.removeTypingIndicator(),_?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,..._.skuToProductItem}),_?.conversationMode&&(this._conversationMode=_.conversationMode),_?.renderHint&&(d.renderHint=_.renderHint),this.track(Mr(this.analyticsContext(),{request_id:y,chunk_index:C++,widget:"chat"})),!this._drawer))return;let S=g;const T=_?.kvkk===!0||i&&ia(S);if(b&&T){const D=this.config.accountId;if(!yn(D)){const A=cl(S);A?this._drawer?.showKvkkBanner(A,()=>{this._drawer?.hideKvkkBanner(),oa(D)}):oa(D)}S=sl(S)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=Ae(S):(d.content=S,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),b)if(d.content=S,d.status="done",xn(),os(d))this._drawer?.updateBotMessage(d.id,S,"photo_analysis",d.photoAnalysis);else{const D=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(D){this._activeTypewriter?.cancel();const A=_?.productMentions;this._activeTypewriter=Bc({container:D,html:Ae(S),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,A&&A.length>0&&D&&Rc({container:D,mentions:A,onProductClick:U=>{this._sendAction({title:A.find(F=>F.sku===U)?.short_name??U,type:"launchSingleProduct",payload:{sku:U}})}})}})}}},onUISpec:(v,b,_,S)=>{if(!r&&n!==this._activeRequestThreadId||b!=="chat")return;S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const T=v.elements[v.root],z=T?.type??"unknown";if(is(z,T?.props??{},Z,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:L},d))return;const D=z==="ProductGrid"&&T?.props?.similarsAppend===!0,A=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||D);A&&!S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const U=z==="ProductDetailsPanel"&&_!=="panel"?"panel":_;this.track(Br(this.analyticsContext(),{request_id:y,chunk_index:C,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const j=T?.props?.products;_l(Array.isArray(j)?j.length:0)}if(z==="ProductGrid"){const j=T?.children?.length??0;kl(void 0,j)}const W=U==="panel"&&this._panel?this._panel.toPanelSpec(v):v;if(U==="panel"&&this._panel&&!A){const j=!w;w=!0;const B=Jc({componentType:z,similarsAppend:T?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:j});F.panelProductListHeading=void 0,z==="ProductGrid"&&(B==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:W})),B==="appendSimilars"?this._appendSimilarsToPanel(W,F):B==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(W,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(W,F)),this._currentPanelSource={kind:"spec",spec:W},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const J=this._panel.currentType??z,O=T?.props?.panelTitle;if(this._panel.updateTopBar(J,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(N=!this._isMobileViewport,te){const se=this._buildRenderContext();se.isStreaming=!0;const Ft=this._renderUISpec(te,se);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Ft}),te=null}}else B!=="appendSimilars"&&B!=="append"&&(N=!1,te=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&U==="panel"&&(!d.silent||i)){const j=T?.props?.product;if(j){const B={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:j}}}},J=this._shadow?.querySelector(".gengage-chat-messages");if(J){const O=this._renderUISpec(B,F);d.threadId&&(O.dataset.threadId=d.threadId);const se=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);se&&se.parentNode===J?se.after(O):J.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),w=!0}}}const ee=z==="AITopPicks"||z==="AIGroupingCards";let ae=!1,de=!1;if(A&&D&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),ee&&!this._isMobileViewport&&!d.silent)if(N){const j=this._renderUISpec(v,F);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:j}),ae=!0,te=null}else te=v,de=!0;const q=i&&z==="GroundingReviewCard";if((!d.silent||q)&&(U!=="panel"||z==="ProductCard"||A&&z==="ProductGrid"&&(!D||this._isMobileViewport))&&z!=="ActionButtons"&&!ae&&!(de&&ee)){const j=this._shadow?.querySelector(".gengage-chat-messages");if(j){const B=this._renderUISpec(v,F);d.threadId&&(B.dataset.threadId=d.threadId),j.appendChild(B),B.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),A&&z==="ProductGrid"&&(w=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const j=T?.children??[],B=z==="ProductGrid"?j.map(J=>v.elements[J]?.props?.product).filter(Boolean):[T?.props?.product].filter(Boolean);for(const J of B){const O=J.sku,se=J.imageUrl;O&&se&&this._thumbnailEntries.push({sku:O,imageUrl:se,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const j=(z==="ProductGrid"?(T?.children??[]).map(B=>v.elements[B]?.props?.product).filter(Boolean):[T?.props?.product??T?.props].filter(Boolean)).map(B=>B.imageUrl).filter(B=>typeof B=="string").slice(0,5);j.length>0&&this._bridge?.send("previewImages",{images:j})}const _e=T?.children?.length??0;if(z==="ProductGrid"&&U==="panel"&&!A&&_e>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!jc(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(B=>B.remove()),this._choicePrompterEl=Hc({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}});const j=this._shadow?.querySelector(".gengage-chat-panel-float");if(j){if(j.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const B=this._choicePrompterEl,J=()=>{window.visualViewport.height/window.innerHeight<.75&&(B.remove(),this._choicePrompterEl===B&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",J))};window.visualViewport.addEventListener("resize",J)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const j=T?.props?.buttons;if(j&&j.length>0){const B=[],J=[];for(const O of j)if($c(O)){const se={label:O.label,action:O.action};O.icon&&(se.icon=O.icon),B.push(se)}else J.push(O);B.length>0&&this._drawer?.setInputAreaChips(B.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),J.length>0&&this._drawer?.setPills(J.map(O=>{const se={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(se.icon=O.icon),O.image&&(se.image=O.image),O.description&&(se.description=O.description),se}))}}X(),d.uiSpec=v},onAction:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="action"){const b={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(b.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(b.allowScriptCall=this.config.actionHandling.allowScriptCall),_i(v,{openChat:()=>this.open(),navigate:_=>{fe(_.url)&&(this._bridge?.send("navigate",_),_.newTab?window.open(_.url,"_blank","noopener,noreferrer"):window.location.href=_.url)},saveSession:_=>this.saveSession(_.sessionId,_.sku),addToCart:_=>{we("gengage:similar:add-to-cart",_)},scriptCall:_=>{we("gengage:chat:script-call",_),this.config.onScriptCall?.(_)}},b)}},onMetadata:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="metadata"&&v.meta){if(v.meta.panel!==void 0||v.meta.messages!==void 0||v.meta.message_id!==void 0){this._lastBackendContext=v.meta;const _=Yt(v.meta.panel);_&&(this._modeController.updateFromContext(_),this._applyUiHints())}if(v.meta.panelLoading){const _=typeof v.meta.panelPendingType=="string"?v.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(_==="productDetails"||_==="productDetailsSimilars")||(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(_),_&&this._panel?.updateTopBarForLoading(_))}if(v.meta.voice){const _=new CustomEvent("gengage:chat:voice",{detail:{payload:v.meta.voice},bubbles:!1,cancelable:!0}),S=window.dispatchEvent(_);if(Pl(),S){const T=v.meta.voice;T.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=ps(T.audio_base64,T.content_type??"audio/ogg"))}}if((v.meta.redirectTarget||v.meta.redirect)&&(we("gengage:chat:redirect",{target:v.meta.redirectTarget??null,payload:v.meta.redirect??null}),Me("redirect","redirect dispatched",{target:v.meta.redirectTarget??null}),this._handleRedirectMetadata(v.meta.redirect)),v.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),v.meta.loading){const _=Array.isArray(v.meta.thinkingMessages)?v.meta.thinkingMessages.filter(T=>typeof T=="string"):[],S=typeof v.meta.loadingText=="string"?v.meta.loadingText:void 0;if(_.length>0){const T=S&&this._modeController.shouldCondenseThinking()?[..._.slice(0,2),S]:_;this._drawer?.setThinkingSteps(T)}typeof S=="string"&&S.length>0&&(this._drawer?.addThinkingStep(S),this._bridge?.send("loadingMessage",{text:S}))}v.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",v.meta.visitorDataResponse),v.meta.formType&&this._bridge?.send("glovOtokoc",{type:v.meta.formType,data:v.meta.formPayload}),v.meta.launcherContent&&this._bridge?.send("launcherContent",v.meta.launcherContent),we("gengage:chat:metadata",{payload:v.meta});const b=v.meta;typeof b.prompt_tokens=="number"&&typeof b.completion_tokens=="number"&&this.track(Or(this.analyticsContext(),{model:v.model??"unknown",prompt_tokens:b.prompt_tokens,completion_tokens:b.completion_tokens,total_tokens:b.total_tokens??b.prompt_tokens+b.completion_tokens}))}},onError:v=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;L=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,X(),te=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),cs(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const b=w;P&&!w&&l(),P=!1,w=!1;const _=d.silent||d.content!=null&&d.content.length>0||g.length>0||b,S=typeof navigator<"u"&&navigator.onLine===!1&&Sa(v),T=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const A=this._messages.indexOf(d);A>=0&&this._messages.splice(A,1)};let z=!1;const D=()=>{if(S)return;this.emit("error",v);const A=v.message;A===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=A);const U=v.message.trim(),F=U.length>0?U:this._i18n.errorMessage,W={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){T(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,W);return}if(rl(v,F)){T(),z=!0,this._drawer?.showErrorWithRecovery(F,W);return}d.content=F,d.status="done";const ee=Ae(F.replace(/\r\n/g,`
|
|
177
177
|
`).split(`
|
|
178
|
-
`).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,ee),this._drawer?.showRecoveryPillsOnly(K)};if(_)this._drawer?.setPills([]),d.silent||D();else if(i||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const A=this._i18n.productNotFoundMessage;d.content=A,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,A),this._markUnavailableProductContext()}else if(D(),S)return;i&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),!z&&d.status==="streaming"&&(d.status="error"),S||this.track(Dr(this.analyticsContext(),{request_id:y,error_code:"STREAM_ERROR",error_message:v.message,widget:"chat"}))},onDone:()=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;if(L=!0,X(),te){const S=this._buildRenderContext();S.isStreaming=!1;const T=this._shadow?.querySelector(".gengage-chat-messages");if(T){const z=this._renderUISpec(te,S);d.threadId&&(z.dataset.threadId=d.threadId),T.appendChild(z),z.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}te=null}this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),ss(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const v=w;if(P&&!w&&l(),P=!1,i&&!g&&!v){const S=this._i18n.productNotFoundMessage;d.content=S,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,S),this._markUnavailableProductContext()}if(w=!1,i){this._pdpPrimingInFlight=!1;const S=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),S||this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",xn()),this._presentation.finalizeAssistantGroup(n);const b=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");b&&(b.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),b.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const _=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,_?()=>{const S=this._buildRenderContext();return this._renderPanelFromSource(_,S)}:void 0),this.track(Rr(this.analyticsContext(),{request_id:y,latency_ms:Date.now()-M,chunk_count:C,widget:"chat"})),this.track($r(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Hr(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},p),this._abortControllers.add(I),!a?.silent&&!r){const v=I;this._drawer?.showStopButton(()=>{v.abort(),this._abortControllers.delete(v),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)}_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="${CSS.escape(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="${CSS.escape(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=Ae(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 d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,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="${CSS.escape(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 d=g.elements[g.root];d&&this._panel?.updateTopBar(d.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&&(Zc(this._currentThreadId??""),this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(a=>a.remove())),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,yl());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=lt._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${lt._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,bl(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 h=o.parentElement,m=this._comparisonSelectedSkus.includes(o.dataset.sku);h.classList.toggle("gengage-chat-comparison-select-wrapper--selected",m);const u=h.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=m?"true":"false",u.setAttribute("aria-pressed",m?"true":"false");const f=u.querySelector(".gengage-chat-comparison-checkbox-icon"),y=u.querySelector(".gengage-chat-comparison-checkbox-label");f&&(f.innerHTML=m?'<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>'),y&&(y.textContent=m?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 d=document.createElement("span");d.className="gengage-chat-comparison-checkbox-icon",d.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 p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-label",p.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(d),g.appendChild(p),g.addEventListener("click",h=>{h.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",h=>{h.target.closest(".gengage-chat-comparison-checkbox")||(h.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=Xa(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_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)}Cl(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};we("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ur(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={onAction:a=>{if(ml(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?String(a.payload.sku):"";r&&_n(r,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";fl(r)}a.type==="getComparisonTable"&&vl(this._comparisonSelectedSkus);const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{if(_n(a.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url))we("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(a.url);else{const n=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:n,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{if(this._currentPanelSource){const s=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:s}),this._localPanelHistory.length>lt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const n=this._buildRenderContext(),r={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},i=this._shadow?.querySelector(".gengage-chat-messages");if(i){const s=this._renderUISpec(r,n);this._currentThreadId&&(s.dataset.threadId=this._currentThreadId),i.appendChild(s),s.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const o={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(o,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:o},this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:lt._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="${CSS.escape(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};we("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){xl(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>lt._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"||r==="ProductGrid"&&n.props?.similarsAppend===!0&&(this.config.productDetailsExtended===!0||!this._isMobileViewport))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{...Mo(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Nr(en(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??ta,i=(s,c)=>tn(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}};function xu(){return new Tr}Ee.CHAT_SCROLL_ELEMENT_ID=vt,Ee.ChatPresentationState=bn,Ee.GengageChat=Tr,Ee.chatCatalog=_u,Ee.createChatWidget=xu,Ee.createDefaultChatUISpecRegistry=en,Ee.defaultChatUnknownUISpecRenderer=ta,Ee.getChatScrollElement=Io,Ee.invalidateChatScrollCache=Da,Ee.renderUISpec=tn})(this.Gengage=this.Gengage||{});
|
|
178
|
+
`).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,ee),this._drawer?.showRecoveryPillsOnly(W)};if(_)this._drawer?.setPills([]),d.silent||D();else if(i||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const A=this._i18n.productNotFoundMessage;d.content=A,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,A),this._markUnavailableProductContext()}else if(D(),S)return;i&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),!z&&d.status==="streaming"&&(d.status="error"),S||this.track(Dr(this.analyticsContext(),{request_id:y,error_code:"STREAM_ERROR",error_message:v.message,widget:"chat"}))},onDone:()=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;if(L=!0,X(),te){const S=this._buildRenderContext();S.isStreaming=!1;const T=this._shadow?.querySelector(".gengage-chat-messages");if(T){const z=this._renderUISpec(te,S);d.threadId&&(z.dataset.threadId=d.threadId),T.appendChild(z),z.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}te=null}this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),ss(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const v=w;if(P&&!w&&l(),P=!1,i&&!g&&!v){const S=this._i18n.productNotFoundMessage;d.content=S,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,S),this._markUnavailableProductContext()}if(w=!1,i){this._pdpPrimingInFlight=!1;const S=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),S||this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",xn()),this._presentation.finalizeAssistantGroup(n);const b=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");b&&(b.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),b.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const _=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,_?()=>{const S=this._buildRenderContext();return this._renderPanelFromSource(_,S)}:void 0),this.track(Rr(this.analyticsContext(),{request_id:y,latency_ms:Date.now()-M,chunk_count:C,widget:"chat"})),this.track($r(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Hr(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},p),this._abortControllers.add(I),!a?.silent&&!r){const v=I;this._drawer?.showStopButton(()=>{v.abort(),this._abortControllers.delete(v),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)}_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="${CSS.escape(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="${CSS.escape(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=Ae(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 d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,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="${CSS.escape(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 d=g.elements[g.root];d&&this._panel?.updateTopBar(d.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&&(Zc(this._currentThreadId??""),this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(a=>a.remove())),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,yl());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=lt._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${lt._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,bl(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 h=o.parentElement,m=this._comparisonSelectedSkus.includes(o.dataset.sku);h.classList.toggle("gengage-chat-comparison-select-wrapper--selected",m);const u=h.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=m?"true":"false",u.setAttribute("aria-pressed",m?"true":"false");const f=u.querySelector(".gengage-chat-comparison-checkbox-icon"),y=u.querySelector(".gengage-chat-comparison-checkbox-label");f&&(f.innerHTML=m?'<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>'),y&&(y.textContent=m?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 d=document.createElement("span");d.className="gengage-chat-comparison-checkbox-icon",d.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 p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-label",p.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(d),g.appendChild(p),g.addEventListener("click",h=>{h.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",h=>{h.target.closest(".gengage-chat-comparison-checkbox")||(h.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=Xa(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_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)}Cl(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};we("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ur(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={onAction:a=>{if(ml(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?String(a.payload.sku):"";r&&_n(r,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";fl(r)}a.type==="getComparisonTable"&&vl(this._comparisonSelectedSkus);const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{if(_n(a.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url))we("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(a.url);else{const n=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:n,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{if(this._currentPanelSource){const s=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:s}),this._localPanelHistory.length>lt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const n=this._buildRenderContext(),r={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},i=this._shadow?.querySelector(".gengage-chat-messages");if(i){const s=this._renderUISpec(r,n);this._currentThreadId&&(s.dataset.threadId=this._currentThreadId),i.appendChild(s),s.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const o={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(o,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:o},this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:lt._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="${CSS.escape(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};we("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){xl(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>lt._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"||r==="ProductGrid"&&n.props?.similarsAppend===!0&&(this.config.productDetailsExtended===!0||!this._isMobileViewport))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{...Mo(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Nr(en(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??ta,i=(s,c)=>tn(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}};function xu(){return new Tr}Ee.CHAT_SCROLL_ELEMENT_ID=vt,Ee.ChatPresentationState=bn,Ee.GengageChat=Tr,Ee.chatCatalog=_u,Ee.createChatWidget=xu,Ee.createDefaultChatUISpecRegistry=en,Ee.defaultChatUnknownUISpecRenderer=ta,Ee.getChatScrollElement=Io,Ee.invalidateChatScrollCache=Da,Ee.renderUISpec=tn})(this.Gengage=this.Gengage||{});
|