@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.
@@ -45,7 +45,7 @@
45
45
  }
46
46
  }
47
47
  `,document.head.appendChild(e)}var ot=null;function lo(){if(ot!==null)return ot;try{ot=localStorage.getItem("gengage:debug")==="1"}catch{ot=!1}return ot}function Le(e,t,a){if(!lo())return;const n=[`[gengage:${e}]`,t];a!==void 0&&n.push(a),console.debug(...n)}var ft=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=Ji(e.theme);this.config={...e,theme:t,session:ja(e.session)},this.root=this._resolveMount(e.mountTarget),this._applyTheme(t),no();const a=mt("gengage:context:update",n=>this.update(n));this._cleanups.push(a),Le("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,Le("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"?Fi:$i;this.track(a(this.analyticsContext(),t))}flushMeteringSummary(e){this.track(Oi(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-${go(t)}`;this.root.style.setProperty(n,a)}}}};function go(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function Ja(){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 po=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("*")&&uo()&&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(!ho(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 ho(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.gengage=="string"&&typeof t.type=="string"}function uo(){try{return typeof process<"u"&&process.env.NODE_ENV!=="production"}catch{return!1}}var mo=console;function fo(e,t,a={}){const n=e.action,r=a.logger??mo;switch(Le("action",`routing action: ${n.kind}`,n),n.kind){case"open_chat":t.openChat?.(n.payload);return;case"navigate":{if(typeof n.url!="string"){Je(n,t,a,r);return}if(!pe(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}bo(n.url,i);return}case"save_session":if(typeof n.sessionId!="string"||typeof n.sku!="string"){Je(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"){Je(n,t,a,r);return}t.addToCart?.({sku:n.sku,quantity:n.quantity,cartCode:n.cartCode});return;case"script_call":{if(a.allowScriptCall===!1){Je(n,t,a,r);return}if(typeof n.name!="string"){Je(n,t,a,r);return}const i=vo(n.payload)?n.payload:void 0;t.scriptCall?.({name:n.name,...i!==void 0&&{payload:i}});return}default:Je(n,t,a,r)}}function Je(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 bo(e,t){if(!(typeof window>"u")){if(!pe(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 vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var yo=["image/jpeg","image/png","image/webp"],Jm=5*1024*1024;function _o(e){return yo.includes(e.type)?e.size>5242880?{ok:!1,reason:"too_large"}:{ok:!0}:{ok:!1,reason:"invalid_type"}}function Qa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function xo(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 Xa(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 Qa(r)?(Le("stream",`event: ${r.type}`,r),t.onEvent(r),r.type==="done"?(t.onDone?.(),!0):!1):!1}catch{const r=xo(n);if(r.length>1){for(const i of r)try{const o=JSON.parse(i);if(!Qa(o))continue;if(t.onEvent(o),o.type==="done")return t.onDone?.(),!0}catch{}return!1}return!1}}async function bt(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(f=>(clearTimeout(l),f)),new Promise(f=>{l=setTimeout(()=>f(o),i)})]):c);if(g===o){s=!0,await a.cancel();break}const{done:d,value:h}=g;if(d)break;r+=n.decode(h,{stream:!0});const u=r.split(`
48
- `);r=u.pop()??"";for(const f of u)if(Xa(f,t))return}if(r.trim()&&Xa(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 en=3,wo=(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():""},ia=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>wo(a,t)).filter(Boolean):[];function ko(e){const t=(e.display_keywords??[]).flatMap(r=>ia(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,en);const n=[...ia(e.chosen_attribute,{stripLeadingStopWords:!0}),...ia(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,en)}function Co(e){return ko(e).join(" • ")}var So=["beauty_consulting","watch_expert"];function tn(e){return typeof e=="string"&&So.includes(e)}function vt(e){if(typeof e.type!="string")return null;if(Eo(e))return e;const t=e;switch(t.type){case"outputText":return To(t);case"suggestedActions":return Po(t);case"productList":return Ao(t);case"productDetails":return Lo(t);case"productDetailsSimilars":return Io(t);case"comparisonTable":return No(t);case"context":return Ro(t);case"chatStreamEnd":return Oo();case"loading":return Do(t);case"panelLoading":return Fo(t);case"similarLoading":return $o(t);case"redirect":return Uo(t);case"error":return Ho(t);case"dummy":return qo(t);case"launcherAction":return jo(t);case"text":return oa(t);case"productItem":return Zo(t);case"text_image":return an(t);case"quick_qna":return nn(t);case"reviewHighlights":return Vo(t);case"aiProductSuggestions":return Ko(t);case"aiProductGroupings":return Yo(t);case"aiSuggestedSearches":return Jo(t);case"prosAndCons":return Wo(t);case"getGroundingReview":return Qo(t);case"voice":return es(t);case"visitorDataResponse":return Go(t);case"productListPreview":return Xo();case"groupList":return ts(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return as(t);case"launcherContent":return rs(t);case"handoff":return ns(t);case"uiSpec":return us(t);default:return null}}function Eo(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=xe(e.spec);return n?typeof n.root=="string"&&xe(n.elements)!==null:!1}case"action":{const a=xe(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 To(e){const t=Z(e.payload.text,e.payload.plain_text)??"",a=Z(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 Po(e){return rn((e.payload.actions??[]).map(t=>{const a=Z(t.title)??"",n=Ie(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(sa),"chat")}function Ao(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=Z(o.style_label),c=Z(o.style_mood),l=Z(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(h=>{const u=xe(h);return u?sn(xe(u.product_detail)??xe(u.product)??u):null}).filter(sa),d=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(h=>({label:Z(h.label)??"",reason:Z(h.reason)??"",skus:Array.isArray(h.skus)?h.skus.filter(u=>typeof u=="string"&&u.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=tn(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?is(n,"chat"):on(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 Lo(e){const t=e.payload.productDetails;if(!t)return ss("chat");const a=Fe(t);return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:{...t,...a}}}}},panelHint:"panel"}}function Io(e){const t=on(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function No(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 m of t){const b=Fe(m);o.push(b)}const s=zo(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(m=>m.sku===c)??o[0]:o[0],g=[];if(Array.isArray(n?.key_differences))for(const m of n.key_differences)typeof m=="string"&&g.push(m);const d=ds(n?.special_considerations),h=n?.recommended_choice,u=n?.winner_hits,f={};for(const m of o){const b=m.sku;b&&(f[b]={title:m.name??b,type:"launchSingleProduct",payload:{sku:b}})}const p={products:o,attributes:s,highlights:g,productActions:f};return l&&(p.recommended=l),d.length>0&&(p.specialCases=d),h&&(p.recommendedText=h),u&&(p.winnerHits=u),typeof n?.key_differences=="string"&&(p.keyDifferencesHtml=n.key_differences),n?.special_considerations&&(p.specialConsiderations=n.special_considerations),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:p}}},panelHint:"panel"}}function zo(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??{},h=a.compared_field_names??Object.keys(e),u=[];for(const f of h){const p=e[f];if(!p||!Array.isArray(p))continue;const m=d[f]??f;u.push({label:m,values:p.map(b=>typeof b=="string"?b:String(b??""))})}return u}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:Mo(o)).filter(d=>d!=="name"&&d!=="name_short"&&!d.endsWith("_short")),g=[];for(const d of l){const h=s.map(f=>{const p=o[f];if(!p||typeof p!="object")return"";const m=p[`${d}_short`],b=p[d];return Bo(m??b)});if(h.every(f=>f.length===0))continue;const u=c[d]??d;g.push({label:u,values:h})}return g}function Mo(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 Bo(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Ro(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function Oo(){return{type:"done"}}function Do(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 Fo(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function $o(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Uo(e){const t=Z(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:Z(e.payload.to)}}}function Ho(e){return{type:"error",code:"BACKEND_ERROR",message:Z(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function qo(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function jo(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),nn({type:"quick_qna",payload:r})}const a=xe(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),an({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=xe(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),oa({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function oa(e){const t={text:Z(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 Zo(e){return os(e.payload,"qna")}function an(e){const t=Z(e.payload.text)??"",a=Ie(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),oa({type:"text",payload:n})}function nn(e){return rn((e.payload.action_list??[]).map(t=>{const a=Z(t.title)??"",n=Ie(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(sa),"qna")}function Vo(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 Wo(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 Go(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function Ko(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=cs(r);if(!i)continue;const o={product:i},s=Ie(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 Yo(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=Z(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Ie(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 Jo(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=Z(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=Z(r.detailed_user_message);s&&(o.text=s);const c=xe(xe(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(b=>typeof b=="string"));const g=Z(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const d={type:"inputText",payload:o},h=Ie(r.requestDetails,i),u=h?.type==="findSimilar"&&typeof o.text=="string"?Ie(d,i):h??Ie(d,i);if(!u)continue;const f={shortName:i,action:u},p=Z(r.detailed_user_message);p&&p!==i&&(f.detailedMessage=p);const m=Co(r);m&&m!==i&&m!==(p??"")&&(f.whyDifferent=m),typeof r.image=="string"&&(f.image=r.image),a.push(f)}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 Qo(e){const t=e.payload,a=Ie(t.requestDetails??t.request_details,Z(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 Xo(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function es(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function ts(e){const t=e.payload.group_list??[],a=[];for(const r of t){const i=r.group_name??"",o=(r.product_list??[]).map(Fe);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=Ie(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 as(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function ns(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 rs(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function rn(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 on(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=Fe(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 is(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 os(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Fe(e),index:0}}}}}}function ss(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function cs(e){const t=Z(e.sku),a=Z(e.short_name),n={...xe(e.product_item)??e},r=Z(e.discount_reason,e.discountReason);return r&&!Z(n.discount_reason,n.discountReason)&&(n.discount_reason=r),sn(n,t,a)}function sn(e,t,a){const n=Z(e.sku,t),r=Z(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=Z(e.brand);o&&(i.brand=o);const s=Z(e.url);s&&(i.url=s);const c=ls(e.images);if(c.length>0)i.images=c;else{const p=Z(e.image,e.image_url,e.imageUrl);p&&(i.images=[p])}const l=st(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=st(e.price);g!==void 0&&(i.price=g);const d=st(e.rating);d!==void 0&&(i.rating=d);const h=st(e.review_count)??st(e.reviewCount);h!==void 0&&(i.review_count=h);const u=Z(e.cart_code,e.cartCode);u&&(i.cart_code=u),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const f=Z(e.discount_reason,e.discountReason);return f&&(i.discount_reason=f),Fe(i)}function Ie(e,t){const a=xe(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 xe(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Z(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function ls(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ds(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 st(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 sa(e){return e!=null}var gs=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 Fe(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=Z(e.brand),o=Z(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:Z(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 h=!1;for(const u of Object.keys(g))gs.has(u)||(d[u]=g[u],h=!0);return h&&(c.extras=d),c}function ps(e){return e.results.map(Fe)}function hs(e){return e.product_groupings.map(t=>{const a={name:t.name,products:(t.group_products??[]).map(Fe)};return t.highlight!==void 0&&(a.highlight=t.highlight),a})}function us(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 ms={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function fs(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 yt(e,t){return`${fs(t?.middlewareUrl)}/chat${ms[e]}`}function bs(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 vs={user_message:"inputText"};function ys(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=vs[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function _s(e,t,a){const n=yt("process_action",a),r=new AbortController;return(async()=>{try{const o=ys(e),s=a.attachment!==void 0;let c;if(s){const h=new FormData;h.append("request",o),a.attachment!==void 0&&h.append("attachment",a.attachment),c={method:"POST",body:h,signal:r.signal}}else c={method:"POST",headers:{"Content-Type":"application/json"},body:o,signal:r.signal};const l=await fetch(n,c);if(!l.ok){let h=l.statusText;try{const u=await l.json(),f=u.detail??u.message??u.error;typeof f=="string"&&(h=f)}catch{}t.onError(new Error(`HTTP ${l.status}: ${h}`));return}let g=!1;const d=()=>{g||(g=!0,t.onDone())};await bt(l,{onEvent:h=>{const u=vt(h);if(u)switch(u.type){case"text_chunk":t.onTextChunk(u.content,u.final===!0,{productMentions:u.productMentions,skuToProductItem:u.skuToProductItem,conversationMode:u.conversationMode,renderHint:u.renderHint,kvkk:u.kvkk});break;case"ui_spec":t.onUISpec(u.spec,u.widget,u.panelHint,u.clearPanel===!0);break;case"action":t.onAction(u);break;case"metadata":t.onMetadata(u);break;case"error":t.onError(new Error(u.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 xs="gengage-chat-scroll",cn=null;function ln(e){cn=e}function ws(){cn=null}var ca={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"},ks={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 Cs(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Ss(e){return Cs(e)==="en"?ks:ca}function Es(){return dn()!==null}function dn(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var Ts=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=dn();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=Ps(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 Ps(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 As(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=_e(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 Ls=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??""}},Is=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,ye(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 Ns(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 gn(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 h=document.createElement("button");return h.type="button",h.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",h.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??t.i18n?.beautyPhotoStepSkip??"Skip",a?.onSkip&&h.addEventListener("click",()=>a.onSkip()),g.appendChild(d),g.appendChild(h),s.appendChild(c),s.appendChild(l),s.appendChild(g),i.appendChild(o),i.appendChild(s),i}function zs(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 Ms(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=zs(e,t);i.hidden=!1,i.innerHTML="";const o=gn({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 pn(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 la(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 hn(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 da(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=hn(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=hn(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 h=document.createElement("p");h.className="gengage-chat-photo-analysis-celeb-reason",h.textContent=t.celebStyleReason,l.appendChild(h)}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 h of c){const u=document.createElement("li");u.textContent=h,d.appendChild(u)}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 Bs(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 Rs(e,t){const a=la(pn(e.props??{})??{summary:"",clues:[]});return da(Bs(t),a)}function Os(e,t,a,n){if(e.innerHTML="",n){e.appendChild(da(a,la(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=la({summary:i,clues:o,details:o,...s?{nextQuestion:s}:{}});e.appendChild(da(a,c))}var Qm='<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>',un={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>'},Ds=ca,Fs=1400,$s=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function Us(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($s)?.[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 Hs(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?Us(await t):null}catch{}return null}var qs=class{_renderPhotoAnalysisCard(e,t,a){Os(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={...Ds,...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 T=document.createElement("div");T.className="gengage-chat-drawer-handle",T.dataset.gengagePart="chat-drawer-handle",T.setAttribute("aria-hidden","true"),T.style.pointerEvents="none",r=T}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 T=document.createElement("img");T.className="gengage-chat-header-avatar",c&&T.classList.add("gengage-chat-header-avatar--logo"),T.dataset.gengagePart="chat-header-avatar",T.src=s,T.alt=t.headerTitle??"Assistant",o.appendChild(T)}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 T=document.createElement("span");T.className="gengage-chat-header-badge gds-badge gds-badge-brand",T.dataset.gengagePart="chat-header-badge",T.textContent=t.headerBadge,g.appendChild(T)}l.appendChild(g);const h=document.createElement("a");h.className="gengage-chat-header-powered",h.dataset.gengagePart="chat-header-powered-by",h.href="https://gengage.ai/",h.target="_blank",h.rel="noopener noreferrer",h.innerHTML=`<svg viewBox="0 0 15 15" fill="none" aria-hidden="true"><path d="M15 5.88941C12.2201 5.88941 9.72762 7.14107 8.05571 9.11059H0C2.77991 9.11059 5.27238 7.85893 6.94429 5.88941H15Z" fill="currentColor"/><path d="M9.10964 0C9.10964 2.24394 8.29524 4.30038 6.94429 5.88941C5.27238 7.85962 2.77922 9.11059 0 9.11059V5.88941C3.24802 5.88941 5.89036 3.2465 5.89036 0H9.10964Z" fill="currentColor" fill-opacity="0.68"/><path d="M15 5.88941V9.11059C11.752 9.11059 9.10964 11.7535 9.10964 15H5.89036C5.89036 12.7561 6.70476 10.6996 8.05571 9.11059C9.72762 7.14038 12.2208 5.88941 15 5.88941Z" fill="currentColor" fill-opacity="0.68"/></svg>${this.i18n.poweredBy}`,l.appendChild(h),o.appendChild(l),i.appendChild(o);const u=document.createElement("div");u.className="gengage-chat-header-right",u.dataset.gengagePart="chat-header-actions";{const T=document.createElement("button");T.type="button",T.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-reopen-panel",T.setAttribute("aria-label",this.i18n.showPanelAriaLabel),T.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>',T.addEventListener("click",()=>this._showMobilePanelFromBtn()),u.appendChild(T),this._reopenPanelBtn=T}{const T=document.createElement("button");T.type="button",T.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-cart",T.setAttribute("aria-label",this.i18n.cartAriaLabel),T.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>',T.addEventListener("click",()=>t.onCartClick?.()),u.appendChild(T),this._cartBtn=T}if(t.onNewChat){const T=document.createElement("button");T.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-new-chat",T.type="button",T.setAttribute("aria-label",this.i18n.newChatButton),T.title=this.i18n.newChatButton,T.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>',T.addEventListener("click",()=>t.onNewChat?.()),u.appendChild(T)}const f=document.createElement("button");if(f.className="gengage-chat-close gds-btn gds-btn-ghost gds-icon-btn",f.dataset.gengagePart="chat-header-close",f.type="button",f.setAttribute("aria-label",this.i18n.closeButton),f.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>',f.addEventListener("click",t.onClose),t.showHeaderFavorites){const T=document.createElement("button");T.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-favorites",T.type="button",T.setAttribute("aria-label",this.i18n.favoritesAriaLabel),T.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';const W=document.createElement("span");W.className="gengage-chat-header-fav-badge",W.dataset.gengagePart="chat-header-favorites-badge",W.setAttribute("aria-hidden","true"),W.style.display="none",T.appendChild(W),this._favBadgeEl=W,T.addEventListener("click",()=>{t.onFavoritesClick?.()}),u.appendChild(T)}u.appendChild(f),r&&i.insertBefore(r,i.firstChild),i.appendChild(u);{let W=0,ie=0,le=!1;const fe=ve=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||ve.target.closest('button, a, input, [role="button"]'))return;const Pe=ve.changedTouches?.[0];Pe&&(W=Pe.clientY,ie=0,le=!0,this.root.style.transition="none")},Oe=ve=>{if(!le)return;const Pe=ve.changedTouches?.[0];if(!Pe)return;ie=Pe.clientY-W;const Ym=(t.getMobileState?.()??"full")==="full"?Math.max(0,ie):ie;ve.preventDefault(),this.root.style.transform=`translateY(${Ym}px)`},Ke=()=>{if(!le)return;le=!1;const ve=t.getMobileState?.()??"full";let Pe;ie>72?Pe=ve==="full"?"half":"close":ie<-72&&ve==="half"?Pe="full":Pe=ve,this.root.style.transition="",Pe==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Pe)),ie=0},Kt=()=>{le&&(le=!1,ie=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",fe,{passive:!0}),i.addEventListener("touchmove",Oe,{passive:!1}),i.addEventListener("touchend",Ke,{passive:!0}),i.addEventListener("touchcancel",Kt,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",fe),i.removeEventListener("touchmove",Oe),i.removeEventListener("touchend",Ke),i.removeEventListener("touchcancel",Kt)})}const p=document.createElement("div");p.className="gengage-chat-body",p.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 Ls({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 m=()=>this._updateScrollAffordance();this._panelEl.addEventListener("scroll",m,{passive:!0}),this._cleanups.push(()=>this._panelEl.removeEventListener("scroll",m)),p.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 b=document.createElement("button");b.className="gengage-chat-panel-divider-toggle gds-btn gds-btn-ghost",b.dataset.gengagePart="chat-panel-divider-toggle",b.type="button",b.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),b.setAttribute("title",this.i18n.togglePanelAriaLabel),b.textContent="»",b.addEventListener("click",()=>{if(this._ignoreNextDividerClick){this._ignoreNextDividerClick=!1;return}this.togglePanel(),this._onPanelToggle?.()});let C=null,v=null;const w=24,k=T=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const W=T.changedTouches?.[0];W&&(C=W.clientX,v=W.clientY)},A=T=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||C===null||v===null)return;const W=T.changedTouches?.[0];if(!W)return;const ie=W.clientX-C,le=W.clientY-v;if(C=null,v=null,Math.abs(le)<w||Math.abs(le)<Math.abs(ie))return;const fe=le<0;fe!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(fe),this._onPanelToggle?.())};this._dividerEl.addEventListener("touchstart",k,{passive:!0}),this._dividerEl.addEventListener("touchend",A,{passive:!0}),this._cleanups.push(()=>{this._dividerEl.removeEventListener("touchstart",k),this._dividerEl.removeEventListener("touchend",A)}),this._dividerEl.appendChild(b),p.appendChild(this._dividerEl);const B=document.createElement("div");B.className="gengage-chat-conversation",B.dataset.gengagePart="chat-conversation",this._conversationEl=B,B.appendChild(i);const I=document.createElement("div");I.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",I.dataset.gengagePart="chat-offline-bar",I.setAttribute("role","status"),I.setAttribute("aria-live","polite"),I.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&I.classList.add("gengage-chat-offline-bar--visible"),B.appendChild(I);const H=()=>I.classList.add("gengage-chat-offline-bar--visible"),Q=()=>I.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",H),window.addEventListener("online",Q),this._cleanups.push(()=>{window.removeEventListener("offline",H),window.removeEventListener("online",Q)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",B.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=xs,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),ln(this.messagesEl);const K=document.createElement("button");K.type="button",K.className="gengage-chat-former-messages-btn gds-chip",K.dataset.gengagePart="chat-former-messages-button",K.textContent=this.i18n.showFormerMessagesButton,K.setAttribute("aria-label",this.i18n.showFormerMessagesButton),K.style.display="none",K.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(K),this._formerMessagesBtn=K;const N=()=>{this._userInteractionUntil=Date.now()+2e3};let _=!1;const y=()=>this._options.presentation,x=()=>{_||(_=!0,requestAnimationFrame(()=>{_=!1;const{scrollTop:T,scrollHeight:W,clientHeight:ie}=this.messagesEl,le=W-T-ie;this._userScrolledUp=le>10;const fe=this._presentationPinned?le<96:le<32,Oe=Date.now(),Ke=Oe<this._programmaticScrollUntil,Kt=!fe&&Oe<this._userInteractionUntil,ve=Ke?!1:Kt;fe!==this._presentationPinned&&(this._presentationPinned=fe,y()?.onPinnedToBottomChange?.(fe)),ve!==this._presentationUserInteracting&&(this._presentationUserInteracting=ve,y()?.onUserInteractingChange?.(ve))}))};this.messagesEl.addEventListener("scroll",x,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",x)});const E=T=>{N(),T.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",E,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",E));const L=T=>{N(),this._touchStartY=T.touches[0]?.clientY??null},z=T=>{N();const W=T.touches[0]?.clientY,ie=this._touchStartY;typeof W=="number"&&typeof ie=="number"&&W-ie>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",L,{passive:!0}),this.messagesEl.addEventListener("touchmove",z,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",L),this.messagesEl.removeEventListener("touchmove",z)}),B.appendChild(this.messagesEl),this._thumbnailsColumn=new Is({onThumbnailClick:T=>t.onThumbnailClick?.(T)}),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 R=document.createElement("div");R.className="gengage-chat-pills-scroll",R.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(R);const P=document.createElement("button");P.className="gengage-chat-pills-arrow gds-btn gds-btn-ghost",P.dataset.gengagePart="chat-suggestion-pills-more",P.type="button",P.setAttribute("aria-label",this.i18n.moreSuggestionsAriaLabel),P.textContent="›",P.addEventListener("click",()=>{R.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(P);let $=!1;const F=()=>{$||($=!0,requestAnimationFrame(()=>{$=!1;const T=R.scrollLeft+R.clientWidth>=R.scrollWidth-4;P.style.display=T?"none":""}))};R.addEventListener("scroll",F,{passive:!0}),this._cleanups.push(()=>{R.removeEventListener("scroll",F)}),B.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",B.appendChild(this._inputChipsEl);const V=document.createElement("div");V.className="gengage-chat-input-area",V.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",T=>{T.key==="Enter"&&!T.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!T.shiftKey)&&(T.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",T=>{const W=T.clipboardData;if(!W)return;let ie=null;const le=W.files?.[0];if(le&&le.type.startsWith("image/"))ie=le;else if(W.items?.length)for(let fe=0;fe<W.items.length;fe++){const Oe=W.items[fe];if(Oe?.kind==="file"&&Oe.type.startsWith("image/")){const Ke=Oe.getAsFile();if(Ke){ie=Ke;break}}}ie&&(T.preventDefault(),this._routeAttachmentFile(ie))}),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 T=this._fileInput.files?.[0];T&&this._routeAttachmentFile(T),this._fileInput.value=""});const J=document.createElement("div");J.className="gengage-chat-attach-wrap",J.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=J;const X=document.createElement("button");this._attachBtn=X,X.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",X.dataset.gengagePart="chat-attach-button",X.type="button",X.setAttribute("aria-label",this.i18n.attachImageButton),X.setAttribute("aria-haspopup","menu"),X.setAttribute("aria-expanded","false"),X.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>',X.addEventListener("click",T=>{T.stopPropagation(),this._toggleAttachMenu()});const oe=document.createElement("div");this._attachMenuEl=oe,oe.className="gengage-chat-attach-menu gds-menu",oe.dataset.gengagePart="chat-attach-menu",oe.setAttribute("role","menu"),oe.setAttribute("hidden","");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-select-photo",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"><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>`,j.addEventListener("click",T=>{T.stopPropagation(),this._closeAttachMenu(),this._fileInput.click()});const be=document.createElement("div");be.className="gengage-chat-attach-menu-sep",be.dataset.gengagePart="chat-attach-menu-separator",be.setAttribute("aria-hidden","true");const U=document.createElement("button");U.type="button",U.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",U.dataset.gengagePart="chat-attach-menu-paste",U.setAttribute("role","menuitem"),U.innerHTML=`<span class="gengage-chat-attach-menu-icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" 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>`,U.addEventListener("click",T=>{T.stopPropagation();const W=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(W)}),oe.appendChild(j),oe.appendChild(be),oe.appendChild(U),J.appendChild(X),J.appendChild(oe),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 M=document.createElement("img");M.className="gengage-chat-attachment-preview-thumb",M.dataset.gengagePart="chat-attachment-preview-thumb",M.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const G=document.createElement("button");G.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",G.dataset.gengagePart="chat-attachment-preview-remove",G.type="button",G.setAttribute("aria-label",this.i18n.removeAttachmentButton),G.textContent="×",G.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(M),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(G),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 T=this._sendStopHandler;this.hideStopButton(),T();return}this._submit()}),V.addEventListener("dragover",T=>{T.preventDefault(),V.classList.add("gengage-chat-input-area--dragover")}),V.addEventListener("dragleave",()=>{V.classList.remove("gengage-chat-input-area--dragover")}),V.addEventListener("drop",T=>{T.preventDefault(),V.classList.remove("gengage-chat-input-area--dragover");const W=T.dataTransfer?.files[0];W&&this._routeAttachmentFile(W)});const O=document.createElement("div");O.className="gengage-chat-input-pill gds-input-shell",O.dataset.gengagePart="chat-input-shell",O.appendChild(J),O.appendChild(this.inputEl),this._voiceEnabled&&Es()&&(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 Ts({onInterim:T=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=T,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:T=>{this.inputEl.value=T},onAutoSubmit:T=>{this.inputEl.value=T,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:T=>{T==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(T,W)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),O.appendChild(this.sendBtn),V.appendChild(this._previewStrip),V.appendChild(this._fileInput),V.appendChild(O),B.appendChild(V),p.appendChild(B),this._comparisonDockSlotEl=document.createElement("div"),this._comparisonDockSlotEl.className="gengage-chat-comparison-dock-slot",this._comparisonDockSlotEl.dataset.gengagePart="comparison-dock-slot",p.appendChild(this._comparisonDockSlotEl),this.root.appendChild(p),this._setupHorizontalSwipe(B),this._setupHorizontalSwipe(this._panelEl);const re=document.createElement("div");re.className="gengage-chat-footer",re.dataset.gengagePart="chat-footer",re.textContent=this.i18n.poweredBy,this.root.appendChild(re);const Gt=T=>{T.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",Gt),this._cleanups.push(()=>this.root.removeEventListener("keydown",Gt)),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=_e(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=un[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&&ye(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=As({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=Ms(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 Hs(e);if(t){this._routeAttachmentFile(t),this._closeAttachMenu();return}ce("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 B=0;B<2;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",B===1&&I.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(I)}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 h=document.createElement("div");h.className="gengage-chat-comparison-highlights";const u=document.createElement("div");u.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",h.appendChild(u);const f=document.createElement("ul");f.className="gengage-chat-comparison-skeleton-hl-list";for(let B=0;B<3;B++){const I=document.createElement("li"),H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",B===1&&H.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),B===2&&H.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),I.appendChild(H),f.appendChild(I)}h.appendChild(f),o.appendChild(h),i.appendChild(o);const p=document.createElement("div");p.className="gengage-chat-comparison-key-differences";const m=document.createElement("div");m.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-heading",p.appendChild(m);const b=document.createElement("div");b.className="gengage-chat-comparison-key-differences-content";for(let B=0;B<4;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",b.appendChild(I)}p.appendChild(b),i.appendChild(p);const C=document.createElement("div");C.className="gengage-chat-comparison-special gengage-chat-comparison-special--skeleton";const v=document.createElement("div");v.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-special-line",C.appendChild(v),i.appendChild(C);const w=document.createElement("div");w.className="gengage-chat-comparison-skeleton-table-wrap";const k=document.createElement("div");k.className="gengage-chat-comparison-skeleton-table-head";const A=document.createElement("div");A.className="gengage-chat-comparison-skeleton-table-corner",k.appendChild(A);for(let B=0;B<3;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-col";const H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const Q=document.createElement("div");Q.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const K=document.createElement("div");K.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",I.appendChild(H),I.appendChild(Q),I.appendChild(K),k.appendChild(I)}w.appendChild(k);for(let B=0;B<3;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-row";const H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",I.appendChild(H);for(let Q=0;Q<3;Q++){const K=document.createElement("div");K.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",I.appendChild(K)}w.appendChild(I)}i.appendChild(w),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)},Fs))}_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=_e(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=un[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)||!ye(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(){ln(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}},mn=["beauty_consulting","watch_expert","booking"],js=["shopping",...mn];function Zs(e){return typeof e=="string"&&js.includes(e)?e:null}function ga(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function Vs(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function Ws(e){const t=ga(e);if(!t)return null;const a=Vs(t.assistant_mode,t.assistantMode);return!a||!mn.includes(a)?null:a}var Gs=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){Le("mode","redirect metadata received",e);const t=Ws(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Le("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=Zs(t);a?this._mode=a:Le("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=ga(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 Ks(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function Ys(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=pn(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):(Le("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Ns(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 Js(e){return e.renderHint==="photo_analysis"}function Qs(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function Xs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var ec=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
48
+ `);r=u.pop()??"";for(const f of u)if(Xa(f,t))return}if(r.trim()&&Xa(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 en=3,wo=(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():""},ia=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>wo(a,t)).filter(Boolean):[];function ko(e){const t=(e.display_keywords??[]).flatMap(r=>ia(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,en);const n=[...ia(e.chosen_attribute,{stripLeadingStopWords:!0}),...ia(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,en)}function Co(e){return ko(e).join(" • ")}var So=["beauty_consulting","watch_expert"];function tn(e){return typeof e=="string"&&So.includes(e)}function vt(e){if(typeof e.type!="string")return null;if(Eo(e))return e;const t=e;switch(t.type){case"outputText":return To(t);case"suggestedActions":return Po(t);case"productList":return Ao(t);case"productDetails":return Lo(t);case"productDetailsSimilars":return Io(t);case"comparisonTable":return No(t);case"context":return Ro(t);case"chatStreamEnd":return Oo();case"loading":return Do(t);case"panelLoading":return Fo(t);case"similarLoading":return $o(t);case"redirect":return Uo(t);case"error":return Ho(t);case"dummy":return qo(t);case"launcherAction":return jo(t);case"text":return oa(t);case"productItem":return Zo(t);case"text_image":return an(t);case"quick_qna":return nn(t);case"reviewHighlights":return Vo(t);case"aiProductSuggestions":return Ko(t);case"aiProductGroupings":return Yo(t);case"aiSuggestedSearches":return Jo(t);case"prosAndCons":return Wo(t);case"getGroundingReview":return Qo(t);case"voice":return es(t);case"visitorDataResponse":return Go(t);case"productListPreview":return Xo();case"groupList":return ts(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return as(t);case"launcherContent":return rs(t);case"handoff":return ns(t);case"uiSpec":return us(t);default:return null}}function Eo(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=xe(e.spec);return n?typeof n.root=="string"&&xe(n.elements)!==null:!1}case"action":{const a=xe(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 To(e){const t=Z(e.payload.text,e.payload.plain_text)??"",a=Z(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 Po(e){return rn((e.payload.actions??[]).map(t=>{const a=Z(t.title)??"",n=Ie(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(sa),"chat")}function Ao(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=Z(o.style_label),c=Z(o.style_mood),l=Z(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(h=>{const u=xe(h);return u?sn(xe(u.product_detail)??xe(u.product)??u):null}).filter(sa),d=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(h=>({label:Z(h.label)??"",reason:Z(h.reason)??"",skus:Array.isArray(h.skus)?h.skus.filter(u=>typeof u=="string"&&u.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=tn(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?is(n,"chat"):on(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 Lo(e){const t=e.payload.productDetails;if(!t)return ss("chat");const a=Fe(t);return{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:{...t,...a}}}}},panelHint:"panel"}}function Io(e){const t=on(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function No(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 m of t){const b=Fe(m);o.push(b)}const s=zo(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(m=>m.sku===c)??o[0]:o[0],g=[];if(Array.isArray(n?.key_differences))for(const m of n.key_differences)typeof m=="string"&&g.push(m);const d=ds(n?.special_considerations),h=n?.recommended_choice,u=n?.winner_hits,f={};for(const m of o){const b=m.sku;b&&(f[b]={title:m.name??b,type:"launchSingleProduct",payload:{sku:b}})}const p={products:o,attributes:s,highlights:g,productActions:f};return l&&(p.recommended=l),d.length>0&&(p.specialCases=d),h&&(p.recommendedText=h),u&&(p.winnerHits=u),typeof n?.key_differences=="string"&&(p.keyDifferencesHtml=n.key_differences),n?.special_considerations&&(p.specialConsiderations=n.special_considerations),{type:"ui_spec",widget:"chat",spec:{root:"root",elements:{root:{type:"ComparisonTable",props:p}}},panelHint:"panel"}}function zo(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??{},h=a.compared_field_names??Object.keys(e),u=[];for(const f of h){const p=e[f];if(!p||!Array.isArray(p))continue;const m=d[f]??f;u.push({label:m,values:p.map(b=>typeof b=="string"?b:String(b??""))})}return u}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:Mo(o)).filter(d=>d!=="name"&&d!=="name_short"&&!d.endsWith("_short")),g=[];for(const d of l){const h=s.map(f=>{const p=o[f];if(!p||typeof p!="object")return"";const m=p[`${d}_short`],b=p[d];return Bo(m??b)});if(h.every(f=>f.length===0))continue;const u=c[d]??d;g.push({label:u,values:h})}return g}function Mo(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 Bo(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Ro(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function Oo(){return{type:"done"}}function Do(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 Fo(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function $o(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function Uo(e){const t=Z(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:Z(e.payload.to)}}}function Ho(e){return{type:"error",code:"BACKEND_ERROR",message:Z(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function qo(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function jo(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),nn({type:"quick_qna",payload:r})}const a=xe(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),an({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=xe(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),oa({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function oa(e){const t={text:Z(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 Zo(e){return os(e.payload,"qna")}function an(e){const t=Z(e.payload.text)??"",a=Ie(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),oa({type:"text",payload:n})}function nn(e){return rn((e.payload.action_list??[]).map(t=>{const a=Z(t.title)??"",n=Ie(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(sa),"qna")}function Vo(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 Wo(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 Go(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function Ko(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=cs(r);if(!i)continue;const o={product:i},s=Ie(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 Yo(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=Z(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Ie(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 Jo(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=Z(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=Z(r.detailed_user_message);s&&(o.text=s);const c=xe(xe(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(b=>typeof b=="string"));const g=Z(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const d={type:"inputText",payload:o},h=Ie(r.requestDetails,i),u=h?.type==="findSimilar"&&typeof o.text=="string"?Ie(d,i):h??Ie(d,i);if(!u)continue;const f={shortName:i,action:u},p=Z(r.detailed_user_message);p&&p!==i&&(f.detailedMessage=p);const m=Co(r);m&&m!==i&&m!==(p??"")&&(f.whyDifferent=m),typeof r.image=="string"&&(f.image=r.image),a.push(f)}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 Qo(e){const t=e.payload,a=Ie(t.requestDetails??t.request_details,Z(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 Xo(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function es(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function ts(e){const t=e.payload.group_list??[],a=[];for(const r of t){const i=r.group_name??"",o=(r.product_list??[]).map(Fe);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=Ie(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 as(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function ns(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 rs(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function rn(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 on(e,t){const a={},n=[];for(let r=0;r<e.length;r++){const i=e[r];if(!i)continue;const o=Fe(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 is(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 os(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Fe(e),index:0}}}}}}function ss(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function cs(e){const t=Z(e.sku),a=Z(e.short_name),n={...xe(e.product_item)??e},r=Z(e.discount_reason,e.discountReason);return r&&!Z(n.discount_reason,n.discountReason)&&(n.discount_reason=r),sn(n,t,a)}function sn(e,t,a){const n=Z(e.sku,t),r=Z(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=Z(e.brand);o&&(i.brand=o);const s=Z(e.url);s&&(i.url=s);const c=ls(e.images);if(c.length>0)i.images=c;else{const p=Z(e.image,e.image_url,e.imageUrl);p&&(i.images=[p])}const l=st(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=st(e.price);g!==void 0&&(i.price=g);const d=st(e.rating);d!==void 0&&(i.rating=d);const h=st(e.review_count)??st(e.reviewCount);h!==void 0&&(i.review_count=h);const u=Z(e.cart_code,e.cartCode);u&&(i.cart_code=u),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const f=Z(e.discount_reason,e.discountReason);return f&&(i.discount_reason=f),Fe(i)}function Ie(e,t){const a=xe(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 xe(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Z(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function ls(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function ds(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 st(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 sa(e){return e!=null}var gs=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 Fe(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=Z(e.brand),o=Z(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:Z(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 h=!1;for(const u of Object.keys(g))gs.has(u)||(d[u]=g[u],h=!0);return h&&(c.extras=d),c}function ps(e){return e.results.map(Fe)}function hs(e){return e.product_groupings.map(t=>{const a={name:t.name,products:(t.group_products??[]).map(Fe)};return t.highlight!==void 0&&(a.highlight=t.highlight),a})}function us(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 ms={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function fs(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 yt(e,t){return`${fs(t?.middlewareUrl)}/chat${ms[e]}`}function bs(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 vs={user_message:"inputText"};function ys(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=vs[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function _s(e,t,a){const n=yt("process_action",a),r=new AbortController;return(async()=>{try{const o=ys(e),s=a.attachment!==void 0;let c;if(s){const h=new FormData;h.append("request",o),a.attachment!==void 0&&h.append("attachment",a.attachment),c={method:"POST",body:h,signal:r.signal}}else c={method:"POST",headers:{"Content-Type":"application/json"},body:o,signal:r.signal};const l=await fetch(n,c);if(!l.ok){let h=l.statusText;try{const u=await l.json(),f=u.detail??u.message??u.error;typeof f=="string"&&(h=f)}catch{}t.onError(new Error(`HTTP ${l.status}: ${h}`));return}let g=!1;const d=()=>{g||(g=!0,t.onDone())};await bt(l,{onEvent:h=>{const u=vt(h);if(u)switch(u.type){case"text_chunk":t.onTextChunk(u.content,u.final===!0,{productMentions:u.productMentions,skuToProductItem:u.skuToProductItem,conversationMode:u.conversationMode,renderHint:u.renderHint,kvkk:u.kvkk});break;case"ui_spec":t.onUISpec(u.spec,u.widget,u.panelHint,u.clearPanel===!0);break;case"action":t.onAction(u);break;case"metadata":t.onMetadata(u);break;case"error":t.onError(new Error(u.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 xs="gengage-chat-scroll",cn=null;function ln(e){cn=e}function ws(){cn=null}var ca={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"},ks={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 Cs(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Ss(e){return Cs(e)==="en"?ks:ca}function Es(){return dn()!==null}function dn(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var Ts=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=dn();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=Ps(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 Ps(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 As(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=_e(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 Ls=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??""}},Is=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,ye(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 Ns(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 gn(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 h=document.createElement("button");return h.type="button",h.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",h.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??t.i18n?.beautyPhotoStepSkip??"Skip",a?.onSkip&&h.addEventListener("click",()=>a.onSkip()),g.appendChild(d),g.appendChild(h),s.appendChild(c),s.appendChild(l),s.appendChild(g),i.appendChild(o),i.appendChild(s),i}function zs(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 Ms(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=zs(e,t);i.hidden=!1,i.innerHTML="";const o=gn({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 pn(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 la(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 hn(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 da(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=hn(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=hn(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 h=document.createElement("p");h.className="gengage-chat-photo-analysis-celeb-reason",h.textContent=t.celebStyleReason,l.appendChild(h)}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 h of c){const u=document.createElement("li");u.textContent=h,d.appendChild(u)}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 Bs(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 Rs(e,t){const a=la(pn(e.props??{})??{summary:"",details:[]});return da(Bs(t),a)}function Os(e,t,a,n){if(e.innerHTML="",n){e.appendChild(da(a,la(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=la({summary:i,details:o,...s?{nextQuestion:s}:{}});e.appendChild(da(a,c))}var Qm='<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>',un={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>'},Ds=ca,Fs=1400,$s=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function Us(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($s)?.[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 Hs(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?Us(await t):null}catch{}return null}var qs=class{_renderPhotoAnalysisCard(e,t,a){Os(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={...Ds,...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 T=document.createElement("div");T.className="gengage-chat-drawer-handle",T.dataset.gengagePart="chat-drawer-handle",T.setAttribute("aria-hidden","true"),T.style.pointerEvents="none",r=T}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 T=document.createElement("img");T.className="gengage-chat-header-avatar",c&&T.classList.add("gengage-chat-header-avatar--logo"),T.dataset.gengagePart="chat-header-avatar",T.src=s,T.alt=t.headerTitle??"Assistant",o.appendChild(T)}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 T=document.createElement("span");T.className="gengage-chat-header-badge gds-badge gds-badge-brand",T.dataset.gengagePart="chat-header-badge",T.textContent=t.headerBadge,g.appendChild(T)}l.appendChild(g);const h=document.createElement("a");h.className="gengage-chat-header-powered",h.dataset.gengagePart="chat-header-powered-by",h.href="https://gengage.ai/",h.target="_blank",h.rel="noopener noreferrer",h.innerHTML=`<svg viewBox="0 0 15 15" fill="none" aria-hidden="true"><path d="M15 5.88941C12.2201 5.88941 9.72762 7.14107 8.05571 9.11059H0C2.77991 9.11059 5.27238 7.85893 6.94429 5.88941H15Z" fill="currentColor"/><path d="M9.10964 0C9.10964 2.24394 8.29524 4.30038 6.94429 5.88941C5.27238 7.85962 2.77922 9.11059 0 9.11059V5.88941C3.24802 5.88941 5.89036 3.2465 5.89036 0H9.10964Z" fill="currentColor" fill-opacity="0.68"/><path d="M15 5.88941V9.11059C11.752 9.11059 9.10964 11.7535 9.10964 15H5.89036C5.89036 12.7561 6.70476 10.6996 8.05571 9.11059C9.72762 7.14038 12.2208 5.88941 15 5.88941Z" fill="currentColor" fill-opacity="0.68"/></svg>${this.i18n.poweredBy}`,l.appendChild(h),o.appendChild(l),i.appendChild(o);const u=document.createElement("div");u.className="gengage-chat-header-right",u.dataset.gengagePart="chat-header-actions";{const T=document.createElement("button");T.type="button",T.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-reopen-panel",T.setAttribute("aria-label",this.i18n.showPanelAriaLabel),T.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>',T.addEventListener("click",()=>this._showMobilePanelFromBtn()),u.appendChild(T),this._reopenPanelBtn=T}{const T=document.createElement("button");T.type="button",T.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-cart",T.setAttribute("aria-label",this.i18n.cartAriaLabel),T.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>',T.addEventListener("click",()=>t.onCartClick?.()),u.appendChild(T),this._cartBtn=T}if(t.onNewChat){const T=document.createElement("button");T.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-new-chat",T.type="button",T.setAttribute("aria-label",this.i18n.newChatButton),T.title=this.i18n.newChatButton,T.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>',T.addEventListener("click",()=>t.onNewChat?.()),u.appendChild(T)}const f=document.createElement("button");if(f.className="gengage-chat-close gds-btn gds-btn-ghost gds-icon-btn",f.dataset.gengagePart="chat-header-close",f.type="button",f.setAttribute("aria-label",this.i18n.closeButton),f.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>',f.addEventListener("click",t.onClose),t.showHeaderFavorites){const T=document.createElement("button");T.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",T.dataset.gengagePart="chat-header-favorites",T.type="button",T.setAttribute("aria-label",this.i18n.favoritesAriaLabel),T.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';const W=document.createElement("span");W.className="gengage-chat-header-fav-badge",W.dataset.gengagePart="chat-header-favorites-badge",W.setAttribute("aria-hidden","true"),W.style.display="none",T.appendChild(W),this._favBadgeEl=W,T.addEventListener("click",()=>{t.onFavoritesClick?.()}),u.appendChild(T)}u.appendChild(f),r&&i.insertBefore(r,i.firstChild),i.appendChild(u);{let W=0,ie=0,le=!1;const fe=ve=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||ve.target.closest('button, a, input, [role="button"]'))return;const Pe=ve.changedTouches?.[0];Pe&&(W=Pe.clientY,ie=0,le=!0,this.root.style.transition="none")},Oe=ve=>{if(!le)return;const Pe=ve.changedTouches?.[0];if(!Pe)return;ie=Pe.clientY-W;const Ym=(t.getMobileState?.()??"full")==="full"?Math.max(0,ie):ie;ve.preventDefault(),this.root.style.transform=`translateY(${Ym}px)`},Ke=()=>{if(!le)return;le=!1;const ve=t.getMobileState?.()??"full";let Pe;ie>72?Pe=ve==="full"?"half":"close":ie<-72&&ve==="half"?Pe="full":Pe=ve,this.root.style.transition="",Pe==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Pe)),ie=0},Kt=()=>{le&&(le=!1,ie=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",fe,{passive:!0}),i.addEventListener("touchmove",Oe,{passive:!1}),i.addEventListener("touchend",Ke,{passive:!0}),i.addEventListener("touchcancel",Kt,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",fe),i.removeEventListener("touchmove",Oe),i.removeEventListener("touchend",Ke),i.removeEventListener("touchcancel",Kt)})}const p=document.createElement("div");p.className="gengage-chat-body",p.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 Ls({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 m=()=>this._updateScrollAffordance();this._panelEl.addEventListener("scroll",m,{passive:!0}),this._cleanups.push(()=>this._panelEl.removeEventListener("scroll",m)),p.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 b=document.createElement("button");b.className="gengage-chat-panel-divider-toggle gds-btn gds-btn-ghost",b.dataset.gengagePart="chat-panel-divider-toggle",b.type="button",b.setAttribute("aria-label",this.i18n.togglePanelAriaLabel),b.setAttribute("title",this.i18n.togglePanelAriaLabel),b.textContent="»",b.addEventListener("click",()=>{if(this._ignoreNextDividerClick){this._ignoreNextDividerClick=!1;return}this.togglePanel(),this._onPanelToggle?.()});let C=null,v=null;const w=24,k=T=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const W=T.changedTouches?.[0];W&&(C=W.clientX,v=W.clientY)},A=T=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||C===null||v===null)return;const W=T.changedTouches?.[0];if(!W)return;const ie=W.clientX-C,le=W.clientY-v;if(C=null,v=null,Math.abs(le)<w||Math.abs(le)<Math.abs(ie))return;const fe=le<0;fe!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(fe),this._onPanelToggle?.())};this._dividerEl.addEventListener("touchstart",k,{passive:!0}),this._dividerEl.addEventListener("touchend",A,{passive:!0}),this._cleanups.push(()=>{this._dividerEl.removeEventListener("touchstart",k),this._dividerEl.removeEventListener("touchend",A)}),this._dividerEl.appendChild(b),p.appendChild(this._dividerEl);const B=document.createElement("div");B.className="gengage-chat-conversation",B.dataset.gengagePart="chat-conversation",this._conversationEl=B,B.appendChild(i);const I=document.createElement("div");I.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",I.dataset.gengagePart="chat-offline-bar",I.setAttribute("role","status"),I.setAttribute("aria-live","polite"),I.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&I.classList.add("gengage-chat-offline-bar--visible"),B.appendChild(I);const H=()=>I.classList.add("gengage-chat-offline-bar--visible"),Q=()=>I.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",H),window.addEventListener("online",Q),this._cleanups.push(()=>{window.removeEventListener("offline",H),window.removeEventListener("online",Q)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",B.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=xs,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),ln(this.messagesEl);const K=document.createElement("button");K.type="button",K.className="gengage-chat-former-messages-btn gds-chip",K.dataset.gengagePart="chat-former-messages-button",K.textContent=this.i18n.showFormerMessagesButton,K.setAttribute("aria-label",this.i18n.showFormerMessagesButton),K.style.display="none",K.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(K),this._formerMessagesBtn=K;const N=()=>{this._userInteractionUntil=Date.now()+2e3};let _=!1;const y=()=>this._options.presentation,x=()=>{_||(_=!0,requestAnimationFrame(()=>{_=!1;const{scrollTop:T,scrollHeight:W,clientHeight:ie}=this.messagesEl,le=W-T-ie;this._userScrolledUp=le>10;const fe=this._presentationPinned?le<96:le<32,Oe=Date.now(),Ke=Oe<this._programmaticScrollUntil,Kt=!fe&&Oe<this._userInteractionUntil,ve=Ke?!1:Kt;fe!==this._presentationPinned&&(this._presentationPinned=fe,y()?.onPinnedToBottomChange?.(fe)),ve!==this._presentationUserInteracting&&(this._presentationUserInteracting=ve,y()?.onUserInteractingChange?.(ve))}))};this.messagesEl.addEventListener("scroll",x,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",x)});const E=T=>{N(),T.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",E,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",E));const L=T=>{N(),this._touchStartY=T.touches[0]?.clientY??null},z=T=>{N();const W=T.touches[0]?.clientY,ie=this._touchStartY;typeof W=="number"&&typeof ie=="number"&&W-ie>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",L,{passive:!0}),this.messagesEl.addEventListener("touchmove",z,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",L),this.messagesEl.removeEventListener("touchmove",z)}),B.appendChild(this.messagesEl),this._thumbnailsColumn=new Is({onThumbnailClick:T=>t.onThumbnailClick?.(T)}),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 R=document.createElement("div");R.className="gengage-chat-pills-scroll",R.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(R);const P=document.createElement("button");P.className="gengage-chat-pills-arrow gds-btn gds-btn-ghost",P.dataset.gengagePart="chat-suggestion-pills-more",P.type="button",P.setAttribute("aria-label",this.i18n.moreSuggestionsAriaLabel),P.textContent="›",P.addEventListener("click",()=>{R.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(P);let $=!1;const F=()=>{$||($=!0,requestAnimationFrame(()=>{$=!1;const T=R.scrollLeft+R.clientWidth>=R.scrollWidth-4;P.style.display=T?"none":""}))};R.addEventListener("scroll",F,{passive:!0}),this._cleanups.push(()=>{R.removeEventListener("scroll",F)}),B.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",B.appendChild(this._inputChipsEl);const V=document.createElement("div");V.className="gengage-chat-input-area",V.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",T=>{T.key==="Enter"&&!T.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!T.shiftKey)&&(T.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",T=>{const W=T.clipboardData;if(!W)return;let ie=null;const le=W.files?.[0];if(le&&le.type.startsWith("image/"))ie=le;else if(W.items?.length)for(let fe=0;fe<W.items.length;fe++){const Oe=W.items[fe];if(Oe?.kind==="file"&&Oe.type.startsWith("image/")){const Ke=Oe.getAsFile();if(Ke){ie=Ke;break}}}ie&&(T.preventDefault(),this._routeAttachmentFile(ie))}),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 T=this._fileInput.files?.[0];T&&this._routeAttachmentFile(T),this._fileInput.value=""});const J=document.createElement("div");J.className="gengage-chat-attach-wrap",J.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=J;const X=document.createElement("button");this._attachBtn=X,X.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",X.dataset.gengagePart="chat-attach-button",X.type="button",X.setAttribute("aria-label",this.i18n.attachImageButton),X.setAttribute("aria-haspopup","menu"),X.setAttribute("aria-expanded","false"),X.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>',X.addEventListener("click",T=>{T.stopPropagation(),this._toggleAttachMenu()});const oe=document.createElement("div");this._attachMenuEl=oe,oe.className="gengage-chat-attach-menu gds-menu",oe.dataset.gengagePart="chat-attach-menu",oe.setAttribute("role","menu"),oe.setAttribute("hidden","");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-select-photo",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"><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>`,j.addEventListener("click",T=>{T.stopPropagation(),this._closeAttachMenu(),this._fileInput.click()});const be=document.createElement("div");be.className="gengage-chat-attach-menu-sep",be.dataset.gengagePart="chat-attach-menu-separator",be.setAttribute("aria-hidden","true");const U=document.createElement("button");U.type="button",U.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",U.dataset.gengagePart="chat-attach-menu-paste",U.setAttribute("role","menuitem"),U.innerHTML=`<span class="gengage-chat-attach-menu-icon" aria-hidden="true"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" 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>`,U.addEventListener("click",T=>{T.stopPropagation();const W=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(W)}),oe.appendChild(j),oe.appendChild(be),oe.appendChild(U),J.appendChild(X),J.appendChild(oe),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 M=document.createElement("img");M.className="gengage-chat-attachment-preview-thumb",M.dataset.gengagePart="chat-attachment-preview-thumb",M.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const G=document.createElement("button");G.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",G.dataset.gengagePart="chat-attachment-preview-remove",G.type="button",G.setAttribute("aria-label",this.i18n.removeAttachmentButton),G.textContent="×",G.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(M),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(G),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 T=this._sendStopHandler;this.hideStopButton(),T();return}this._submit()}),V.addEventListener("dragover",T=>{T.preventDefault(),V.classList.add("gengage-chat-input-area--dragover")}),V.addEventListener("dragleave",()=>{V.classList.remove("gengage-chat-input-area--dragover")}),V.addEventListener("drop",T=>{T.preventDefault(),V.classList.remove("gengage-chat-input-area--dragover");const W=T.dataTransfer?.files[0];W&&this._routeAttachmentFile(W)});const O=document.createElement("div");O.className="gengage-chat-input-pill gds-input-shell",O.dataset.gengagePart="chat-input-shell",O.appendChild(J),O.appendChild(this.inputEl),this._voiceEnabled&&Es()&&(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 Ts({onInterim:T=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=T,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:T=>{this.inputEl.value=T},onAutoSubmit:T=>{this.inputEl.value=T,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:T=>{T==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(T,W)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),O.appendChild(this.sendBtn),V.appendChild(this._previewStrip),V.appendChild(this._fileInput),V.appendChild(O),B.appendChild(V),p.appendChild(B),this._comparisonDockSlotEl=document.createElement("div"),this._comparisonDockSlotEl.className="gengage-chat-comparison-dock-slot",this._comparisonDockSlotEl.dataset.gengagePart="comparison-dock-slot",p.appendChild(this._comparisonDockSlotEl),this.root.appendChild(p),this._setupHorizontalSwipe(B),this._setupHorizontalSwipe(this._panelEl);const re=document.createElement("div");re.className="gengage-chat-footer",re.dataset.gengagePart="chat-footer",re.textContent=this.i18n.poweredBy,this.root.appendChild(re);const Gt=T=>{T.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",Gt),this._cleanups.push(()=>this.root.removeEventListener("keydown",Gt)),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=_e(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=un[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&&ye(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=As({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=Ms(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 Hs(e);if(t){this._routeAttachmentFile(t),this._closeAttachMenu();return}ce("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 B=0;B<2;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",B===1&&I.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(I)}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 h=document.createElement("div");h.className="gengage-chat-comparison-highlights";const u=document.createElement("div");u.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",h.appendChild(u);const f=document.createElement("ul");f.className="gengage-chat-comparison-skeleton-hl-list";for(let B=0;B<3;B++){const I=document.createElement("li"),H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",B===1&&H.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),B===2&&H.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),I.appendChild(H),f.appendChild(I)}h.appendChild(f),o.appendChild(h),i.appendChild(o);const p=document.createElement("div");p.className="gengage-chat-comparison-key-differences";const m=document.createElement("div");m.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-heading",p.appendChild(m);const b=document.createElement("div");b.className="gengage-chat-comparison-key-differences-content";for(let B=0;B<4;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",b.appendChild(I)}p.appendChild(b),i.appendChild(p);const C=document.createElement("div");C.className="gengage-chat-comparison-special gengage-chat-comparison-special--skeleton";const v=document.createElement("div");v.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-special-line",C.appendChild(v),i.appendChild(C);const w=document.createElement("div");w.className="gengage-chat-comparison-skeleton-table-wrap";const k=document.createElement("div");k.className="gengage-chat-comparison-skeleton-table-head";const A=document.createElement("div");A.className="gengage-chat-comparison-skeleton-table-corner",k.appendChild(A);for(let B=0;B<3;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-col";const H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const Q=document.createElement("div");Q.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const K=document.createElement("div");K.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",I.appendChild(H),I.appendChild(Q),I.appendChild(K),k.appendChild(I)}w.appendChild(k);for(let B=0;B<3;B++){const I=document.createElement("div");I.className="gengage-chat-comparison-skeleton-table-row";const H=document.createElement("div");H.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",I.appendChild(H);for(let Q=0;Q<3;Q++){const K=document.createElement("div");K.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",I.appendChild(K)}w.appendChild(I)}i.appendChild(w),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)},Fs))}_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=_e(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=un[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)||!ye(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(){ln(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}},mn=["beauty_consulting","watch_expert","booking"],js=["shopping",...mn];function Zs(e){return typeof e=="string"&&js.includes(e)?e:null}function ga(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function Vs(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function Ws(e){const t=ga(e);if(!t)return null;const a=Vs(t.assistant_mode,t.assistantMode);return!a||!mn.includes(a)?null:a}var Gs=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){Le("mode","redirect metadata received",e);const t=Ws(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Le("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=Zs(t);a?this._mode=a:Le("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=ga(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 Ks(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function Ys(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=pn(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):(Le("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Ns(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 Js(e){return e.renderHint==="photo_analysis"}function Qs(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function Xs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var ec=`<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"/>
@@ -173,6 +173,6 @@ button[data-gengage-part="chat-launcher-button"] img {
173
173
 
174
174
  `)}u.write("payload.value = newResult;"),u.write("return payload;");const C=u.compile();return(v,w)=>C(h,v,w)};let i;const o=Lt,s=!Sa.jitless,l=s&&yd.value,g=t.catchall;let d;e._zod.parse=(h,u)=>{d??(d=n.value);const f=h.value;return o(f)?s&&l&&u?.async===!1&&u.jitless!==!0?(i||(i=r(t.shape)),h=i(h,u),g?vr([],f,h,u,d,e):h):a(h,u):(h.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),h)}});function yr(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=>!at(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 Qg=S("$ZodUnion",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Y(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Y(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Y(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=>Aa(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=>yr(c,r,e,i)):yr(s,r,e,i)}}),Xg=S("$ZodIntersection",(e,t)=>{ae.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])=>_r(a,s,c)):_r(a,i,o)}});function Na(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(gt(e)&&gt(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=Na(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=Na(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 _r(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}),at(e))return e;const o=Na(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 ep=S("$ZodEnum",(e,t)=>{ae.init(e,t);const a=Zn(t.entries),n=new Set(a);e._zod.values=n,e._zod.pattern=new RegExp(`^(${a.filter(r=>_d.has(typeof r)).map(r=>typeof r=="string"?tt(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}}),tp=S("$ZodLiteral",(e,t)=>{if(ae.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const a=new Set(t.values);e._zod.values=a,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?tt(n):n?tt(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const i=n.value;return a.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),ap=S("$ZodTransform",(e,t)=>{ae.init(e,t),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(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 et;return a.value=r,a}});function xr(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var wr=S("$ZodOptional",(e,t)=>{ae.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Y(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Y(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${Aa(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=>xr(i,a.value)):xr(r,a.value)}return a.value===void 0?a:t.innerType._zod.run(a,n)}}),np=S("$ZodExactOptional",(e,t)=>{wr.init(e,t),Y(e._zod,"values",()=>t.innerType._zod.values),Y(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(a,n)=>t.innerType._zod.run(a,n)}),rp=S("$ZodNullable",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.innerType._zod.optin),Y(e._zod,"optout",()=>t.innerType._zod.optout),Y(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${Aa(a.source)}|null)$`):void 0}),Y(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)}),ip=S("$ZodDefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",Y(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=>kr(i,t)):kr(r,t)}});function kr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var op=S("$ZodPrefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",Y(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))}),sp=S("$ZodNonOptional",(e,t)=>{ae.init(e,t),Y(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=>Cr(i,e)):Cr(r,e)}});function Cr(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 cp=S("$ZodCatch",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.innerType._zod.optin),Y(e._zod,"optout",()=>t.innerType._zod.optout),Y(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)}}),lp=S("$ZodPipe",(e,t)=>{ae.init(e,t),Y(e._zod,"values",()=>t.in._zod.values),Y(e._zod,"optin",()=>t.in._zod.optin),Y(e._zod,"optout",()=>t.out._zod.optout),Y(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=>Dt(o,t.in,n)):Dt(i,t.in,n)}const r=t.in._zod.run(a,n);return r instanceof Promise?r.then(i=>Dt(i,t.out,n)):Dt(r,t.out,n)}});function Dt(e,t,a){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},a)}var dp=S("$ZodReadonly",(e,t)=>{ae.init(e,t),Y(e._zod,"propValues",()=>t.innerType._zod.propValues),Y(e._zod,"values",()=>t.innerType._zod.values),Y(e._zod,"optin",()=>t.innerType?._zod?.optin),Y(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(Sr):Sr(r)}});function Sr(e){return e.value=Object.freeze(e.value),e}var gp=S("$ZodCustom",(e,t)=>{he.init(e,t),ae.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=>Er(i,a,n,e));Er(r,a,n,e)}});function Er(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(pt(r))}}var Tr,pp=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 hp(){return new pp}(Tr=globalThis).__zod_globalRegistry??(Tr.__zod_globalRegistry=hp());var Me=globalThis.__zod_globalRegistry;function up(e,t){return new e({type:"string",...D(t)})}function mp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...D(t)})}function Pr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...D(t)})}function fp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...D(t)})}function bp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(t)})}function vp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(t)})}function yp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(t)})}function _p(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...D(t)})}function xp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...D(t)})}function wp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(t)})}function kp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...D(t)})}function Cp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(t)})}function Sp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...D(t)})}function Ep(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...D(t)})}function Tp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(t)})}function Pp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(t)})}function Ap(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(t)})}function Lp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(t)})}function Ip(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(t)})}function Np(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...D(t)})}function zp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...D(t)})}function Mp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...D(t)})}function Bp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...D(t)})}function Rp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(t)})}function Op(e,t){return new e({type:"string",format:"date",check:"string_format",...D(t)})}function Dp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...D(t)})}function Fp(e,t){return new e({type:"string",format:"duration",check:"string_format",...D(t)})}function $p(e,t){return new e({type:"number",checks:[],...D(t)})}function Up(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...D(t)})}function Hp(e,t){return new e({type:"boolean",...D(t)})}function qp(e){return new e({type:"unknown"})}function jp(e,t){return new e({type:"never",...D(t)})}function Ar(e,t){return new pr({check:"less_than",...D(t),value:e,inclusive:!1})}function za(e,t){return new pr({check:"less_than",...D(t),value:e,inclusive:!0})}function Lr(e,t){return new hr({check:"greater_than",...D(t),value:e,inclusive:!1})}function Ma(e,t){return new hr({check:"greater_than",...D(t),value:e,inclusive:!0})}function Ir(e,t){return new og({check:"multiple_of",...D(t),value:e})}function Nr(e,t){return new cg({check:"max_length",...D(t),maximum:e})}function Ft(e,t){return new lg({check:"min_length",...D(t),minimum:e})}function zr(e,t){return new dg({check:"length_equals",...D(t),length:e})}function Zp(e,t){return new gg({check:"string_format",format:"regex",...D(t),pattern:e})}function Vp(e){return new pg({check:"string_format",format:"lowercase",...D(e)})}function Wp(e){return new hg({check:"string_format",format:"uppercase",...D(e)})}function Gp(e,t){return new ug({check:"string_format",format:"includes",...D(t),includes:e})}function Kp(e,t){return new mg({check:"string_format",format:"starts_with",...D(t),prefix:e})}function Yp(e,t){return new fg({check:"string_format",format:"ends_with",...D(t),suffix:e})}function nt(e){return new bg({check:"overwrite",tx:e})}function Jp(e){return nt(t=>t.normalize(e))}function Qp(){return nt(e=>e.trim())}function Xp(){return nt(e=>e.toLowerCase())}function eh(){return nt(e=>e.toUpperCase())}function th(){return nt(e=>vd(e))}function ah(e,t,a){return new e({type:"array",element:t,...D(a)})}function nh(e,t,a){return new e({type:"custom",check:"custom",fn:t,...D(a)})}function rh(e){const t=ih(a=>(a.addIssue=n=>{if(typeof n=="string")a.issues.push(pt(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(pt(r))}},e(a.value,a)));return t}function ih(e,t){const a=new he({check:"custom",...D(t)});return a._zod.check=e,a}function oh(e){const t=new he({check:"describe"});return t._zod.onattach=[a=>{const n=Me.get(a)??{};Me.add(a,{...n,description:e})}],t._zod.check=()=>{},t}function sh(e){const t=new he({check:"meta"});return t._zod.onattach=[a=>{const n=Me.get(a)??{};Me.add(a,{...n,...e})}],t._zod.check=()=>{},t}function Mr(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??Me,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 ge(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,h=t.processors[r.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,d,l)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),ge(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"&&ue(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 Br(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??(u=>u);if(g)return{ref:d(g)};const h=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=h,{defId:h,ref:`${d("__shared")}#/${s}/${h}`}}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 Rr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),u=h.schema;if(u.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(u)):Object.assign(c,u),Object.assign(c,l),o._zod.parent===g)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(u.$ref&&h.def)for(const f in c)f==="$ref"||f==="allOf"||f in h.def&&JSON.stringify(c[f])===JSON.stringify(h.def[f])&&delete c[f]}const d=o._zod.parent;if(d&&d!==g){n(d);const h=e.seen.get(d);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const u in c)u==="$ref"||u==="allOf"||u in h.def&&JSON.stringify(c[u])===JSON.stringify(h.def[u])&&delete c[u]}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:$t(t,"input",e.processors),output:$t(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ue(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 ue(n.element,a);if(n.type==="set")return ue(n.valueType,a);if(n.type==="lazy")return ue(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 ue(n.innerType,a);if(n.type==="intersection")return ue(n.left,a)||ue(n.right,a);if(n.type==="record"||n.type==="map")return ue(n.keyType,a)||ue(n.valueType,a);if(n.type==="pipe")return ue(n.in,a)||ue(n.out,a);if(n.type==="object"){for(const r in n.shape)if(ue(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ue(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ue(r,a))return!0;return!!(n.rest&&ue(n.rest,a))}return!1}var ch=(e,t={})=>a=>{const n=Mr({...a,processors:t});return ge(e,n),Br(n,e),Rr(n,e)},$t=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=Mr({...r??{},target:i,io:t,processors:a});return ge(e,o),Br(o,e),Rr(o,e)},lh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dh=(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=lh[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}))])}},gh=(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)},ph=(e,t,a,n)=>{a.type="boolean"},hh=(e,t,a,n)=>{a.not={}},uh=(e,t,a,n)=>{},mh=(e,t,a,n)=>{const r=e._zod.def,i=Zn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},fh=(e,t,a,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];a.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[o]:a.const=o}else i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),i.every(o=>typeof o=="boolean")&&(a.type="boolean"),i.every(o=>o===null)&&(a.type="null"),a.enum=i},bh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yh=(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=ge(i.element,t,{...n,path:[...n.path,"items"]})},_h=(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]=ge(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=ge(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},xh=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ge(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},wh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ge(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]]},kh=(e,t,a,n)=>{const r=e._zod.def,i=ge(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"}]},Ch=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Sh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Eh=(e,t,a,n)=>{const r=e._zod.def;ge(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)))},Th=(e,t,a,n)=>{const r=e._zod.def;ge(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},Ph=(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;ge(i,t,n);const o=t.seen.get(e);o.ref=i},Ah=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},Or=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Lh=S("ZodISODateTime",(e,t)=>{Ig.init(e,t),te.init(e,t)});function Ih(e){return Rp(Lh,e)}var Nh=S("ZodISODate",(e,t)=>{Ng.init(e,t),te.init(e,t)});function zh(e){return Op(Nh,e)}var Mh=S("ZodISOTime",(e,t)=>{zg.init(e,t),te.init(e,t)});function Bh(e){return Dp(Mh,e)}var Rh=S("ZodISODuration",(e,t)=>{Mg.init(e,t),te.init(e,t)});function Oh(e){return Fp(Rh,e)}var Dr=(e,t)=>{Qn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Id(e,a)},flatten:{value:a=>Ld(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,Ea,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,Ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},gf=S("ZodError",Dr),ke=S("ZodError",Dr,{Parent:Error}),Dh=Nt(ke),Fh=zt(ke),$h=Mt(ke),Uh=Bt(ke),Hh=Xn(ke),qh=er(ke),jh=tr(ke),Zh=ar(ke),Vh=nr(ke),Wh=rr(ke),Gh=ir(ke),Kh=or(ke),ne=S("ZodType",(e,t)=>(ae.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$t(e,"input"),output:$t(e,"output")}}),e.toJSONSchema=ch(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ue(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)=>He(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Dh(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>$h(e,a,n),e.parseAsync=async(a,n)=>Fh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Uh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Hh(e,a,n),e.decode=(a,n)=>qh(e,a,n),e.encodeAsync=async(a,n)=>jh(e,a,n),e.decodeAsync=async(a,n)=>Zh(e,a,n),e.safeEncode=(a,n)=>Vh(e,a,n),e.safeDecode=(a,n)=>Wh(e,a,n),e.safeEncodeAsync=async(a,n)=>Gh(e,a,n),e.safeDecodeAsync=async(a,n)=>Kh(e,a,n),e.refine=(a,n)=>e.check(ju(a,n)),e.superRefine=a=>e.check(Zu(a)),e.overwrite=a=>e.check(nt(a)),e.optional=()=>Vr(e),e.exactOptional=()=>Iu(e),e.nullable=()=>Wr(e),e.nullish=()=>Vr(Wr(e)),e.nonoptional=a=>Ou(e,a),e.array=()=>_u(e),e.or=a=>ku([e,a]),e.and=a=>Su(e,a),e.transform=a=>Kr(e,Au(a)),e.default=a=>Mu(e,a),e.prefault=a=>Ru(e,a),e.catch=a=>Fu(e,a),e.pipe=a=>Kr(e,a),e.readonly=()=>Hu(e),e.describe=a=>{const n=e.clone();return Me.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return Me.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return Me.get(e);const n=e.clone();return Me.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Fr=S("_ZodString",(e,t)=>{Ia.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dh(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(Zp(...n)),e.includes=(...n)=>e.check(Gp(...n)),e.startsWith=(...n)=>e.check(Kp(...n)),e.endsWith=(...n)=>e.check(Yp(...n)),e.min=(...n)=>e.check(Ft(...n)),e.max=(...n)=>e.check(Nr(...n)),e.length=(...n)=>e.check(zr(...n)),e.nonempty=(...n)=>e.check(Ft(1,...n)),e.lowercase=n=>e.check(Vp(n)),e.uppercase=n=>e.check(Wp(n)),e.trim=()=>e.check(Qp()),e.normalize=(...n)=>e.check(Jp(...n)),e.toLowerCase=()=>e.check(Xp()),e.toUpperCase=()=>e.check(eh()),e.slugify=()=>e.check(th())}),Yh=S("ZodString",(e,t)=>{Ia.init(e,t),Fr.init(e,t),e.email=a=>e.check(mp(Jh,a)),e.url=a=>e.check(_p(Qh,a)),e.jwt=a=>e.check(Bp(hu,a)),e.emoji=a=>e.check(xp(Xh,a)),e.guid=a=>e.check(Pr($r,a)),e.uuid=a=>e.check(fp(Ut,a)),e.uuidv4=a=>e.check(bp(Ut,a)),e.uuidv6=a=>e.check(vp(Ut,a)),e.uuidv7=a=>e.check(yp(Ut,a)),e.nanoid=a=>e.check(wp(eu,a)),e.guid=a=>e.check(Pr($r,a)),e.cuid=a=>e.check(kp(tu,a)),e.cuid2=a=>e.check(Cp(au,a)),e.ulid=a=>e.check(Sp(nu,a)),e.base64=a=>e.check(Np(du,a)),e.base64url=a=>e.check(zp(gu,a)),e.xid=a=>e.check(Ep(ru,a)),e.ksuid=a=>e.check(Tp(iu,a)),e.ipv4=a=>e.check(Pp(ou,a)),e.ipv6=a=>e.check(Ap(su,a)),e.cidrv4=a=>e.check(Lp(cu,a)),e.cidrv6=a=>e.check(Ip(lu,a)),e.e164=a=>e.check(Mp(pu,a)),e.datetime=a=>e.check(Ih(a)),e.date=a=>e.check(zh(a)),e.time=a=>e.check(Bh(a)),e.duration=a=>e.check(Oh(a))});function Ce(e){return up(Yh,e)}var te=S("ZodStringFormat",(e,t)=>{ee.init(e,t),Fr.init(e,t)}),Jh=S("ZodEmail",(e,t)=>{wg.init(e,t),te.init(e,t)}),$r=S("ZodGUID",(e,t)=>{_g.init(e,t),te.init(e,t)}),Ut=S("ZodUUID",(e,t)=>{xg.init(e,t),te.init(e,t)}),Qh=S("ZodURL",(e,t)=>{kg.init(e,t),te.init(e,t)}),Xh=S("ZodEmoji",(e,t)=>{Cg.init(e,t),te.init(e,t)}),eu=S("ZodNanoID",(e,t)=>{Sg.init(e,t),te.init(e,t)}),tu=S("ZodCUID",(e,t)=>{Eg.init(e,t),te.init(e,t)}),au=S("ZodCUID2",(e,t)=>{Tg.init(e,t),te.init(e,t)}),nu=S("ZodULID",(e,t)=>{Pg.init(e,t),te.init(e,t)}),ru=S("ZodXID",(e,t)=>{Ag.init(e,t),te.init(e,t)}),iu=S("ZodKSUID",(e,t)=>{Lg.init(e,t),te.init(e,t)}),ou=S("ZodIPv4",(e,t)=>{Bg.init(e,t),te.init(e,t)}),su=S("ZodIPv6",(e,t)=>{Rg.init(e,t),te.init(e,t)}),cu=S("ZodCIDRv4",(e,t)=>{Og.init(e,t),te.init(e,t)}),lu=S("ZodCIDRv6",(e,t)=>{Dg.init(e,t),te.init(e,t)}),du=S("ZodBase64",(e,t)=>{Fg.init(e,t),te.init(e,t)}),gu=S("ZodBase64URL",(e,t)=>{Ug.init(e,t),te.init(e,t)}),pu=S("ZodE164",(e,t)=>{Hg.init(e,t),te.init(e,t)}),hu=S("ZodJWT",(e,t)=>{jg.init(e,t),te.init(e,t)}),Ur=S("ZodNumber",(e,t)=>{mr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gh(e,n,r,i),e.gt=(n,r)=>e.check(Lr(n,r)),e.gte=(n,r)=>e.check(Ma(n,r)),e.min=(n,r)=>e.check(Ma(n,r)),e.lt=(n,r)=>e.check(Ar(n,r)),e.lte=(n,r)=>e.check(za(n,r)),e.max=(n,r)=>e.check(za(n,r)),e.int=n=>e.check(qr(n)),e.safe=n=>e.check(qr(n)),e.positive=n=>e.check(Lr(0,n)),e.nonnegative=n=>e.check(Ma(0,n)),e.negative=n=>e.check(Ar(0,n)),e.nonpositive=n=>e.check(za(0,n)),e.multipleOf=(n,r)=>e.check(Ir(n,r)),e.step=(n,r)=>e.check(Ir(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 Hr(e){return $p(Ur,e)}var uu=S("ZodNumberFormat",(e,t)=>{Zg.init(e,t),Ur.init(e,t)});function qr(e){return Up(uu,e)}var mu=S("ZodBoolean",(e,t)=>{Vg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ph(e,a,n,r)});function We(e){return Hp(mu,e)}var fu=S("ZodUnknown",(e,t)=>{Wg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>uh(e,a,n,r)});function jr(){return qp(fu)}var bu=S("ZodNever",(e,t)=>{Gg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>hh(e,a,n,r)});function vu(e){return jp(bu,e)}var yu=S("ZodArray",(e,t)=>{Kg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>yh(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ft(a,n)),e.nonempty=a=>e.check(Ft(1,a)),e.max=(a,n)=>e.check(Nr(a,n)),e.length=(a,n)=>e.check(zr(a,n)),e.unwrap=()=>e.element});function _u(e,t){return ah(yu,e,t)}var xu=S("ZodObject",(e,t)=>{Jg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>_h(e,a,n,r),Y(e,"shape",()=>t.shape),e.keyof=()=>Ra(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:jr()}),e.loose=()=>e.clone({...e._zod.def,catchall:jr()}),e.strict=()=>e.clone({...e._zod.def,catchall:vu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Sd(e,a),e.safeExtend=a=>Ed(e,a),e.merge=a=>Td(e,a),e.pick=a=>kd(e,a),e.omit=a=>Cd(e,a),e.partial=(...a)=>Pd(Zr,e,a[0]),e.required=(...a)=>Ad(Gr,e,a[0])});function Be(e,t){return new xu({type:"object",shape:e??{},...D(t)})}var wu=S("ZodUnion",(e,t)=>{Qg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>xh(e,a,n,r),e.options=t.options});function ku(e,t){return new wu({type:"union",options:e,...D(t)})}var Cu=S("ZodIntersection",(e,t)=>{Xg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wh(e,a,n,r)});function Su(e,t){return new Cu({type:"intersection",left:e,right:t})}var Ba=S("ZodEnum",(e,t)=>{ep.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mh(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})}});function Ra(e,t){return new Ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...D(t)})}var Eu=S("ZodLiteral",(e,t)=>{tp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>fh(e,a,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Tu(e,t){return new Eu({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}var Pu=S("ZodTransform",(e,t)=>{ap.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>vh(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(pt(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(pt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Au(e){return new Pu({type:"transform",transform:e})}var Zr=S("ZodOptional",(e,t)=>{wr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Vr(e){return new Zr({type:"optional",innerType:e})}var Lu=S("ZodExactOptional",(e,t)=>{np.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Lu({type:"optional",innerType:e})}var Nu=S("ZodNullable",(e,t)=>{rp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Wr(e){return new Nu({type:"nullable",innerType:e})}var zu=S("ZodDefault",(e,t)=>{ip.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Sh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mu(e,t){return new zu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Bu=S("ZodPrefault",(e,t)=>{op.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ru(e,t){return new Bu({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Gr=S("ZodNonOptional",(e,t)=>{sp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ch(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ou(e,t){return new Gr({type:"nonoptional",innerType:e,...D(t)})}var Du=S("ZodCatch",(e,t)=>{cp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fu(e,t){return new Du({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $u=S("ZodPipe",(e,t)=>{lp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ph(e,a,n,r),e.in=t.in,e.out=t.out});function Kr(e,t){return new $u({type:"pipe",in:e,out:t})}var Uu=S("ZodReadonly",(e,t)=>{dp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ah(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Hu(e){return new Uu({type:"readonly",innerType:e})}var qu=S("ZodCustom",(e,t)=>{gp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>bh(e,a,n,r)});function ju(e,t={}){return nh(qu,e,t)}function Zu(e){return rh(e)}var pf=oh,hf=sh;function Yr(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Oa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Vu=class it extends ft{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=ca,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 Zl,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new Gs}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 p=Wl(t.pillLauncher);t.launcherImageUrl=p.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>p.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=id,this._shadow.appendChild(a);const n=this.root,r=(p,m)=>{m&&Yr(m)&&n.style.setProperty(p,m)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[p,m]of Object.entries(t.theme))p.startsWith("--")&&typeof m=="string"&&r(p,m);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 p=document.createElement("div");p.className="gengage-chat-backdrop",p.setAttribute("aria-hidden","true"),p.setAttribute("role","button"),p.setAttribute("tabindex","-1"),p.setAttribute("aria-label",this._i18n.closeAriaLabel),p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),this.close()}),this._backdropEl=p,i.prepend(p)}if(o==="floating"){const p={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?p.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(p.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(p.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(p.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(p.tooltip=t.launcherTooltip),this._launcher=tc(p),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new qs(s,{i18n:this._i18n,onSend:(p,m)=>this._sendMessage(p,m),onClose:()=>this.close(),onAttachment:p=>this._handleAttachment(p),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:p=>this._handleRollback(p),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(pd(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:p=>{p==="close"?this.close():(this._openState=p,this._applyOpenStateClasses())},onThumbnailClick:p=>this._rollbackToThread(p),onLinkClick:p=>{this._saveSessionAndOpenURL(p)},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:p=>{this._presentation.pinnedToBottom=p},onUserInteractingChange:p=>{this._presentation.userInteracting=p},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Hl({onChange:p=>this._panel?.notifyExtension(p),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new ql({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:p=>this._rollbackToThread(p)}),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"),h=!!(g&&d);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const p=new $l;await p.open(),this._session=new Dn(p),await this._restoreFromIndexedDB(h)}catch{this._session=new Dn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const u=()=>this._syncViewportState();if(window.addEventListener("resize",u,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",u)),window.visualViewport){const p=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const m=this._drawer?.getElement();if(!m)return;const b=window.innerHeight-(window.visualViewport?.height??window.innerHeight);m.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,b)}px`)};window.visualViewport.addEventListener("resize",p),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",p))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const f={namespace:"chat",onMessage:p=>this._handleBridgeMessage(p)};t.allowedOrigins!==void 0&&(f.allowedOrigins=t.allowedOrigins),this._bridge=new po(f),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const p of this._pendingActions)this._sendAction(p.action,p.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),ce("gengage:chat:ready",{}),Pt("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"),ce("gengage:chat:open",{state:this._openState}),At("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"),ce("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(),ws(),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=Vl(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=Oa(n)?n:Oa(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}),Oa(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"&&Yr(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:Ja(),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=_o(t);if(!a.ok){ce("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())&&(wa(this.config.accountId),this._drawer?.hideKvkkBanner()),ud(),this._messages.some(r=>r.role==="user")||md(),Le("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||Bl(),!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 _=this._currentThreadId,y=this._messages.filter(x=>x.threadId!==void 0&&x.threadId>_);this._messages=this._messages.filter(x=>!x.threadId||x.threadId<=_);for(const x of y)this._shadow?.querySelector(`[data-message-id="${CSS.escape(x.id)}"]`)?.remove(),this._panel.snapshots.delete(x.id),this._panel.snapshotTypes.delete(x.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(x=>{x instanceof HTMLElement&&x.dataset.threadId&&x.dataset.threadId>_&&x.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ja();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 _=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,y=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(y!==void 0&&y.role==="user"&&y.content===_)){const x=this._createMessage("user",_);x.threadId=n,a?.attachment!==void 0&&(x.attachment=a.attachment),this._drawer?.addMessage(x),this._messages.push(x)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const _=this._i18n.productNotFoundMessage,y=this._createMessage("assistant",_);y.threadId=n,y.status="done",this._messages.push(y),this._ensureAssistantMessageRendered(y),this._drawer?.updateBotMessage(y.id,_),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",y),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 _=this._buildRenderContext(),y=this._renderPanelFromSource(o,_);this._drawer.setPanelContent(y),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 h={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(h.attachment=a.attachment);const u=this._getVisibleMessages().filter(_=>_!==d&&(_.content||_.role==="assistant")).slice(-50).map(_=>({role:_.role==="user"?"user":"model",content:_.content??""})),f={outputLanguage:rd(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:$n(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(f.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(f.viewId=this.config.session.viewId);const p=bs(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),m={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:p.type,locale:this.config.locale??"tr",meta:f,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(m.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(m.view_id=this.config.session.viewId),p.payload!==void 0&&(m.payload=p.payload),this.config.pageContext?.sku!==void 0&&(m.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(m.page_type=this.config.pageContext.pageType);const b=crypto.randomUUID(),C=Date.now();let v=0,w=!1,k=!1,A=!1,B=!1,I=!1;const H=Ks();let Q=null;const K=()=>{if(this._drawer){if(this._isMobileViewport||!A){this._drawer.setPanelAiZoneState("hidden");return}B||(I?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(Qt(this.analyticsContext(),{endpoint:"process_action",request_id:b,widget:"chat"}));let N=null;if(N=_s(m,{onTextChunk:(_,y,x)=>{if(!r&&n!==this._activeRequestThreadId||(g+=_,this._drawer?.removeTypingIndicator(),x?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...x.skuToProductItem}),x?.conversationMode&&(this._conversationMode=x.conversationMode),x?.renderHint&&(d.renderHint=x.renderHint),this.track(zi(this.analyticsContext(),{request_id:b,chunk_index:v++,widget:"chat"})),!this._drawer))return;let E=g;const L=x?.kvkk===!0||xa(E);if(y&&L){const R=this.config.accountId;if(!$n(R)){const P=ad(E);P?this._drawer?.showKvkkBanner(P,()=>{this._drawer?.hideKvkkBanner(),wa(R)}):wa(R)}E=td(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=_e(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),y)if(d.content=E,d.status="done",qn(),Js(d))this._drawer?.updateBotMessage(d.id,E,"photo_analysis",d.photoAnalysis);else{const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R){this._activeTypewriter?.cancel();const P=x?.productMentions;this._activeTypewriter=Pl({container:R,html:_e(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,P&&P.length>0&&R&&Al({container:R,mentions:P,onProductClick:$=>{this._sendAction({title:P.find(F=>F.sku===$)?.short_name??$,type:"launchSingleProduct",payload:{sku:$}})}})}})}}},onUISpec:(_,y,x,E)=>{if(!r&&n!==this._activeRequestThreadId||y!=="chat")return;E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const L=_.elements[_.root],z=L?.type??"unknown";if(Ys(z,L?.props??{},H,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:I},d))return;const R=z==="ProductGrid"&&L?.props?.similarsAppend===!0,P=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||R);P&&!E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const $=z==="ProductDetailsPanel"&&x!=="panel"?"panel":x;this.track(Mi(this.analyticsContext(),{request_id:b,chunk_index:v,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const U=L?.props?.products;dd(Array.isArray(U)?U.length:0)}if(z==="ProductGrid"){const U=L?.children?.length??0;hd(void 0,U)}const V=$==="panel"&&this._panel?this._panel.toPanelSpec(_):_;if($==="panel"&&this._panel&&!P){const U=!k;k=!0;const M=jl({componentType:z,similarsAppend:L?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:U});F.panelProductListHeading=void 0,z==="ProductGrid"&&(M==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:V})),M==="appendSimilars"?this._appendSimilarsToPanel(V,F):M==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(V,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(V,F)),this._currentPanelSource={kind:"spec",spec:V},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 G=this._panel.currentType??z,O=L?.props?.panelTitle;if(this._panel.updateTopBar(G,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(A=!this._isMobileViewport,Q){const re=this._buildRenderContext();re.isStreaming=!0;const Gt=this._renderUISpec(Q,re);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Gt}),Q=null}}else M!=="appendSimilars"&&M!=="append"&&(A=!1,Q=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&$==="panel"&&(!d.silent||i)){const U=L?.props?.product;if(U){const M={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:U}}}},G=this._shadow?.querySelector(".gengage-chat-messages");if(G){const O=this._renderUISpec(M,F);d.threadId&&(O.dataset.threadId=d.threadId);const re=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);re&&re.parentNode===G?re.after(O):G.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),k=!0}}}const J=z==="AITopPicks"||z==="AIGroupingCards";let X=!1,oe=!1;if(P&&R&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),J&&!this._isMobileViewport&&!d.silent)if(A){const U=this._renderUISpec(_,F);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:U}),X=!0,Q=null}else Q=_,oe=!0;const j=i&&z==="GroundingReviewCard";if((!d.silent||j)&&($!=="panel"||z==="ProductCard"||P&&z==="ProductGrid"&&(!R||this._isMobileViewport))&&z!=="ActionButtons"&&!X&&!(oe&&J)){const U=this._shadow?.querySelector(".gengage-chat-messages");if(U){const M=this._renderUISpec(_,F);d.threadId&&(M.dataset.threadId=d.threadId),U.appendChild(M),M.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),P&&z==="ProductGrid"&&(k=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const U=L?.children??[],M=z==="ProductGrid"?U.map(G=>_.elements[G]?.props?.product).filter(Boolean):[L?.props?.product].filter(Boolean);for(const G of M){const O=G.sku,re=G.imageUrl;O&&re&&this._thumbnailEntries.push({sku:O,imageUrl:re,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const U=(z==="ProductGrid"?(L?.children??[]).map(M=>_.elements[M]?.props?.product).filter(Boolean):[L?.props?.product??L?.props].filter(Boolean)).map(M=>M.imageUrl).filter(M=>typeof M=="string").slice(0,5);U.length>0&&this._bridge?.send("previewImages",{images:U})}const be=L?.children?.length??0;if(z==="ProductGrid"&&$==="panel"&&!P&&be>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!Rl(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(M=>M.remove()),this._choicePrompterEl=Ml({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 U=this._shadow?.querySelector(".gengage-chat-panel-float");if(U){if(U.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const M=this._choicePrompterEl,G=()=>{window.visualViewport.height/window.innerHeight<.75&&(M.remove(),this._choicePrompterEl===M&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",G))};window.visualViewport.addEventListener("resize",G)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const U=L?.props?.buttons;if(U&&U.length>0){const M=[],G=[];for(const O of U)if(Nl(O)){const re={label:O.label,action:O.action};O.icon&&(re.icon=O.icon),M.push(re)}else G.push(O);M.length>0&&this._drawer?.setInputAreaChips(M.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),G.length>0&&this._drawer?.setPills(G.map(O=>{const re={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(re.icon=O.icon),O.image&&(re.image=O.image),O.description&&(re.description=O.description),re}))}}K(),d.uiSpec=_},onAction:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="action"){const y={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(y.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(y.allowScriptCall=this.config.actionHandling.allowScriptCall),fo(_,{openChat:()=>this.open(),navigate:x=>{pe(x.url)&&(this._bridge?.send("navigate",x),x.newTab?window.open(x.url,"_blank","noopener,noreferrer"):window.location.href=x.url)},saveSession:x=>this.saveSession(x.sessionId,x.sku),addToCart:x=>{ce("gengage:similar:add-to-cart",x)},scriptCall:x=>{ce("gengage:chat:script-call",x),this.config.onScriptCall?.(x)}},y)}},onMetadata:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="metadata"&&_.meta){if(_.meta.panel!==void 0||_.meta.messages!==void 0||_.meta.message_id!==void 0){this._lastBackendContext=_.meta;const x=ga(_.meta.panel);x&&(this._modeController.updateFromContext(x),this._applyUiHints())}if(_.meta.panelLoading){const x=typeof _.meta.panelPendingType=="string"?_.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(x==="productDetails"||x==="productDetailsSimilars")||(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(x),x&&this._panel?.updateTopBarForLoading(x))}if(_.meta.voice){const x=new CustomEvent("gengage:chat:voice",{detail:{payload:_.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(x);if(fd(),E){const L=_.meta.voice;L.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=nc(L.audio_base64,L.content_type??"audio/ogg"))}}if((_.meta.redirectTarget||_.meta.redirect)&&(ce("gengage:chat:redirect",{target:_.meta.redirectTarget??null,payload:_.meta.redirect??null}),Le("redirect","redirect dispatched",{target:_.meta.redirectTarget??null}),this._handleRedirectMetadata(_.meta.redirect)),_.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),_.meta.loading){const x=Array.isArray(_.meta.thinkingMessages)?_.meta.thinkingMessages.filter(L=>typeof L=="string"):[],E=typeof _.meta.loadingText=="string"?_.meta.loadingText:void 0;if(x.length>0){const L=E&&this._modeController.shouldCondenseThinking()?[...x.slice(0,2),E]:x;this._drawer?.setThinkingSteps(L)}typeof E=="string"&&E.length>0&&(this._drawer?.addThinkingStep(E),this._bridge?.send("loadingMessage",{text:E}))}_.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",_.meta.visitorDataResponse),_.meta.formType&&this._bridge?.send("glovOtokoc",{type:_.meta.formType,data:_.meta.formPayload}),_.meta.launcherContent&&this._bridge?.send("launcherContent",_.meta.launcherContent),ce("gengage:chat:metadata",{payload:_.meta});const y=_.meta;typeof y.prompt_tokens=="number"&&typeof y.completion_tokens=="number"&&this.track(Bi(this.analyticsContext(),{model:_.model??"unknown",prompt_tokens:y.prompt_tokens,completion_tokens:y.completion_tokens,total_tokens:y.total_tokens??y.prompt_tokens+y.completion_tokens}))}},onError:_=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;I=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,K(),Q=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),Xs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const y=k;w&&!k&&l(),w=!1,k=!1;const x=d.silent||d.content!=null&&d.content.length>0||g.length>0||y,E=typeof navigator<"u"&&navigator.onLine===!1&&na(_),L=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const P=this._messages.indexOf(d);P>=0&&this._messages.splice(P,1)};let z=!1;const R=()=>{if(E)return;this.emit("error",_);const P=_.message;P===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=P);const $=_.message.trim(),F=$.length>0?$:this._i18n.errorMessage,V={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){L(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,V);return}if(Ql(_,F)){L(),z=!0,this._drawer?.showErrorWithRecovery(F,V);return}d.content=F,d.status="done";const J=_e(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 Rr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),u=h.schema;if(u.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(u)):Object.assign(c,u),Object.assign(c,l),o._zod.parent===g)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(u.$ref&&h.def)for(const f in c)f==="$ref"||f==="allOf"||f in h.def&&JSON.stringify(c[f])===JSON.stringify(h.def[f])&&delete c[f]}const d=o._zod.parent;if(d&&d!==g){n(d);const h=e.seen.get(d);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const u in c)u==="$ref"||u==="allOf"||u in h.def&&JSON.stringify(c[u])===JSON.stringify(h.def[u])&&delete c[u]}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:$t(t,"input",e.processors),output:$t(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ue(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 ue(n.element,a);if(n.type==="set")return ue(n.valueType,a);if(n.type==="lazy")return ue(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 ue(n.innerType,a);if(n.type==="intersection")return ue(n.left,a)||ue(n.right,a);if(n.type==="record"||n.type==="map")return ue(n.keyType,a)||ue(n.valueType,a);if(n.type==="pipe")return ue(n.in,a)||ue(n.out,a);if(n.type==="object"){for(const r in n.shape)if(ue(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ue(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ue(r,a))return!0;return!!(n.rest&&ue(n.rest,a))}return!1}var ch=(e,t={})=>a=>{const n=Mr({...a,processors:t});return ge(e,n),Br(n,e),Rr(n,e)},$t=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=Mr({...r??{},target:i,io:t,processors:a});return ge(e,o),Br(o,e),Rr(o,e)},lh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dh=(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=lh[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}))])}},gh=(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)},ph=(e,t,a,n)=>{a.type="boolean"},hh=(e,t,a,n)=>{a.not={}},uh=(e,t,a,n)=>{},mh=(e,t,a,n)=>{const r=e._zod.def,i=Zn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},fh=(e,t,a,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];a.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[o]:a.const=o}else i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),i.every(o=>typeof o=="boolean")&&(a.type="boolean"),i.every(o=>o===null)&&(a.type="null"),a.enum=i},bh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yh=(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=ge(i.element,t,{...n,path:[...n.path,"items"]})},_h=(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]=ge(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=ge(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},xh=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ge(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},wh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ge(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]]},kh=(e,t,a,n)=>{const r=e._zod.def,i=ge(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"}]},Ch=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Sh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Eh=(e,t,a,n)=>{const r=e._zod.def;ge(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)))},Th=(e,t,a,n)=>{const r=e._zod.def;ge(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},Ph=(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;ge(i,t,n);const o=t.seen.get(e);o.ref=i},Ah=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},Or=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Lh=S("ZodISODateTime",(e,t)=>{Ig.init(e,t),te.init(e,t)});function Ih(e){return Rp(Lh,e)}var Nh=S("ZodISODate",(e,t)=>{Ng.init(e,t),te.init(e,t)});function zh(e){return Op(Nh,e)}var Mh=S("ZodISOTime",(e,t)=>{zg.init(e,t),te.init(e,t)});function Bh(e){return Dp(Mh,e)}var Rh=S("ZodISODuration",(e,t)=>{Mg.init(e,t),te.init(e,t)});function Oh(e){return Fp(Rh,e)}var Dr=(e,t)=>{Qn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Id(e,a)},flatten:{value:a=>Ld(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,Ea,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,Ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},gf=S("ZodError",Dr),ke=S("ZodError",Dr,{Parent:Error}),Dh=Nt(ke),Fh=zt(ke),$h=Mt(ke),Uh=Bt(ke),Hh=Xn(ke),qh=er(ke),jh=tr(ke),Zh=ar(ke),Vh=nr(ke),Wh=rr(ke),Gh=ir(ke),Kh=or(ke),ne=S("ZodType",(e,t)=>(ae.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$t(e,"input"),output:$t(e,"output")}}),e.toJSONSchema=ch(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ue(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)=>He(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Dh(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>$h(e,a,n),e.parseAsync=async(a,n)=>Fh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Uh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Hh(e,a,n),e.decode=(a,n)=>qh(e,a,n),e.encodeAsync=async(a,n)=>jh(e,a,n),e.decodeAsync=async(a,n)=>Zh(e,a,n),e.safeEncode=(a,n)=>Vh(e,a,n),e.safeDecode=(a,n)=>Wh(e,a,n),e.safeEncodeAsync=async(a,n)=>Gh(e,a,n),e.safeDecodeAsync=async(a,n)=>Kh(e,a,n),e.refine=(a,n)=>e.check(ju(a,n)),e.superRefine=a=>e.check(Zu(a)),e.overwrite=a=>e.check(nt(a)),e.optional=()=>Vr(e),e.exactOptional=()=>Iu(e),e.nullable=()=>Wr(e),e.nullish=()=>Vr(Wr(e)),e.nonoptional=a=>Ou(e,a),e.array=()=>_u(e),e.or=a=>ku([e,a]),e.and=a=>Su(e,a),e.transform=a=>Kr(e,Au(a)),e.default=a=>Mu(e,a),e.prefault=a=>Ru(e,a),e.catch=a=>Fu(e,a),e.pipe=a=>Kr(e,a),e.readonly=()=>Hu(e),e.describe=a=>{const n=e.clone();return Me.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return Me.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return Me.get(e);const n=e.clone();return Me.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Fr=S("_ZodString",(e,t)=>{Ia.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dh(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(Zp(...n)),e.includes=(...n)=>e.check(Gp(...n)),e.startsWith=(...n)=>e.check(Kp(...n)),e.endsWith=(...n)=>e.check(Yp(...n)),e.min=(...n)=>e.check(Ft(...n)),e.max=(...n)=>e.check(Nr(...n)),e.length=(...n)=>e.check(zr(...n)),e.nonempty=(...n)=>e.check(Ft(1,...n)),e.lowercase=n=>e.check(Vp(n)),e.uppercase=n=>e.check(Wp(n)),e.trim=()=>e.check(Qp()),e.normalize=(...n)=>e.check(Jp(...n)),e.toLowerCase=()=>e.check(Xp()),e.toUpperCase=()=>e.check(eh()),e.slugify=()=>e.check(th())}),Yh=S("ZodString",(e,t)=>{Ia.init(e,t),Fr.init(e,t),e.email=a=>e.check(mp(Jh,a)),e.url=a=>e.check(_p(Qh,a)),e.jwt=a=>e.check(Bp(hu,a)),e.emoji=a=>e.check(xp(Xh,a)),e.guid=a=>e.check(Pr($r,a)),e.uuid=a=>e.check(fp(Ut,a)),e.uuidv4=a=>e.check(bp(Ut,a)),e.uuidv6=a=>e.check(vp(Ut,a)),e.uuidv7=a=>e.check(yp(Ut,a)),e.nanoid=a=>e.check(wp(eu,a)),e.guid=a=>e.check(Pr($r,a)),e.cuid=a=>e.check(kp(tu,a)),e.cuid2=a=>e.check(Cp(au,a)),e.ulid=a=>e.check(Sp(nu,a)),e.base64=a=>e.check(Np(du,a)),e.base64url=a=>e.check(zp(gu,a)),e.xid=a=>e.check(Ep(ru,a)),e.ksuid=a=>e.check(Tp(iu,a)),e.ipv4=a=>e.check(Pp(ou,a)),e.ipv6=a=>e.check(Ap(su,a)),e.cidrv4=a=>e.check(Lp(cu,a)),e.cidrv6=a=>e.check(Ip(lu,a)),e.e164=a=>e.check(Mp(pu,a)),e.datetime=a=>e.check(Ih(a)),e.date=a=>e.check(zh(a)),e.time=a=>e.check(Bh(a)),e.duration=a=>e.check(Oh(a))});function Ce(e){return up(Yh,e)}var te=S("ZodStringFormat",(e,t)=>{ee.init(e,t),Fr.init(e,t)}),Jh=S("ZodEmail",(e,t)=>{wg.init(e,t),te.init(e,t)}),$r=S("ZodGUID",(e,t)=>{_g.init(e,t),te.init(e,t)}),Ut=S("ZodUUID",(e,t)=>{xg.init(e,t),te.init(e,t)}),Qh=S("ZodURL",(e,t)=>{kg.init(e,t),te.init(e,t)}),Xh=S("ZodEmoji",(e,t)=>{Cg.init(e,t),te.init(e,t)}),eu=S("ZodNanoID",(e,t)=>{Sg.init(e,t),te.init(e,t)}),tu=S("ZodCUID",(e,t)=>{Eg.init(e,t),te.init(e,t)}),au=S("ZodCUID2",(e,t)=>{Tg.init(e,t),te.init(e,t)}),nu=S("ZodULID",(e,t)=>{Pg.init(e,t),te.init(e,t)}),ru=S("ZodXID",(e,t)=>{Ag.init(e,t),te.init(e,t)}),iu=S("ZodKSUID",(e,t)=>{Lg.init(e,t),te.init(e,t)}),ou=S("ZodIPv4",(e,t)=>{Bg.init(e,t),te.init(e,t)}),su=S("ZodIPv6",(e,t)=>{Rg.init(e,t),te.init(e,t)}),cu=S("ZodCIDRv4",(e,t)=>{Og.init(e,t),te.init(e,t)}),lu=S("ZodCIDRv6",(e,t)=>{Dg.init(e,t),te.init(e,t)}),du=S("ZodBase64",(e,t)=>{Fg.init(e,t),te.init(e,t)}),gu=S("ZodBase64URL",(e,t)=>{Ug.init(e,t),te.init(e,t)}),pu=S("ZodE164",(e,t)=>{Hg.init(e,t),te.init(e,t)}),hu=S("ZodJWT",(e,t)=>{jg.init(e,t),te.init(e,t)}),Ur=S("ZodNumber",(e,t)=>{mr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gh(e,n,r,i),e.gt=(n,r)=>e.check(Lr(n,r)),e.gte=(n,r)=>e.check(Ma(n,r)),e.min=(n,r)=>e.check(Ma(n,r)),e.lt=(n,r)=>e.check(Ar(n,r)),e.lte=(n,r)=>e.check(za(n,r)),e.max=(n,r)=>e.check(za(n,r)),e.int=n=>e.check(qr(n)),e.safe=n=>e.check(qr(n)),e.positive=n=>e.check(Lr(0,n)),e.nonnegative=n=>e.check(Ma(0,n)),e.negative=n=>e.check(Ar(0,n)),e.nonpositive=n=>e.check(za(0,n)),e.multipleOf=(n,r)=>e.check(Ir(n,r)),e.step=(n,r)=>e.check(Ir(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 Hr(e){return $p(Ur,e)}var uu=S("ZodNumberFormat",(e,t)=>{Zg.init(e,t),Ur.init(e,t)});function qr(e){return Up(uu,e)}var mu=S("ZodBoolean",(e,t)=>{Vg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ph(e,a,n,r)});function We(e){return Hp(mu,e)}var fu=S("ZodUnknown",(e,t)=>{Wg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>uh(e,a,n,r)});function jr(){return qp(fu)}var bu=S("ZodNever",(e,t)=>{Gg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>hh(e,a,n,r)});function vu(e){return jp(bu,e)}var yu=S("ZodArray",(e,t)=>{Kg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>yh(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ft(a,n)),e.nonempty=a=>e.check(Ft(1,a)),e.max=(a,n)=>e.check(Nr(a,n)),e.length=(a,n)=>e.check(zr(a,n)),e.unwrap=()=>e.element});function _u(e,t){return ah(yu,e,t)}var xu=S("ZodObject",(e,t)=>{Jg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>_h(e,a,n,r),Y(e,"shape",()=>t.shape),e.keyof=()=>Ra(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:jr()}),e.loose=()=>e.clone({...e._zod.def,catchall:jr()}),e.strict=()=>e.clone({...e._zod.def,catchall:vu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Sd(e,a),e.safeExtend=a=>Ed(e,a),e.merge=a=>Td(e,a),e.pick=a=>kd(e,a),e.omit=a=>Cd(e,a),e.partial=(...a)=>Pd(Zr,e,a[0]),e.required=(...a)=>Ad(Gr,e,a[0])});function Be(e,t){return new xu({type:"object",shape:e??{},...D(t)})}var wu=S("ZodUnion",(e,t)=>{Qg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>xh(e,a,n,r),e.options=t.options});function ku(e,t){return new wu({type:"union",options:e,...D(t)})}var Cu=S("ZodIntersection",(e,t)=>{Xg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wh(e,a,n,r)});function Su(e,t){return new Cu({type:"intersection",left:e,right:t})}var Ba=S("ZodEnum",(e,t)=>{ep.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mh(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})}});function Ra(e,t){return new Ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...D(t)})}var Eu=S("ZodLiteral",(e,t)=>{tp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>fh(e,a,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Tu(e,t){return new Eu({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}var Pu=S("ZodTransform",(e,t)=>{ap.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>vh(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(pt(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(pt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Au(e){return new Pu({type:"transform",transform:e})}var Zr=S("ZodOptional",(e,t)=>{wr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Vr(e){return new Zr({type:"optional",innerType:e})}var Lu=S("ZodExactOptional",(e,t)=>{np.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Lu({type:"optional",innerType:e})}var Nu=S("ZodNullable",(e,t)=>{rp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Wr(e){return new Nu({type:"nullable",innerType:e})}var zu=S("ZodDefault",(e,t)=>{ip.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Sh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mu(e,t){return new zu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Bu=S("ZodPrefault",(e,t)=>{op.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ru(e,t){return new Bu({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Gr=S("ZodNonOptional",(e,t)=>{sp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ch(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ou(e,t){return new Gr({type:"nonoptional",innerType:e,...D(t)})}var Du=S("ZodCatch",(e,t)=>{cp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fu(e,t){return new Du({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $u=S("ZodPipe",(e,t)=>{lp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ph(e,a,n,r),e.in=t.in,e.out=t.out});function Kr(e,t){return new $u({type:"pipe",in:e,out:t})}var Uu=S("ZodReadonly",(e,t)=>{dp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ah(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Hu(e){return new Uu({type:"readonly",innerType:e})}var qu=S("ZodCustom",(e,t)=>{gp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>bh(e,a,n,r)});function ju(e,t={}){return nh(qu,e,t)}function Zu(e){return rh(e)}var pf=oh,hf=sh;function Yr(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Oa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Vu=class it extends ft{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=ca,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 Zl,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new Gs}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 p=Wl(t.pillLauncher);t.launcherImageUrl=p.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>p.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=id,this._shadow.appendChild(a);const n=this.root,r=(p,m)=>{m&&Yr(m)&&n.style.setProperty(p,m)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[p,m]of Object.entries(t.theme))p.startsWith("--")&&typeof m=="string"&&r(p,m);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 p=document.createElement("div");p.className="gengage-chat-backdrop",p.setAttribute("aria-hidden","true"),p.setAttribute("role","button"),p.setAttribute("tabindex","-1"),p.setAttribute("aria-label",this._i18n.closeAriaLabel),p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),this.close()}),this._backdropEl=p,i.prepend(p)}if(o==="floating"){const p={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?p.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(p.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(p.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(p.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(p.tooltip=t.launcherTooltip),this._launcher=tc(p),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new qs(s,{i18n:this._i18n,onSend:(p,m)=>this._sendMessage(p,m),onClose:()=>this.close(),onAttachment:p=>this._handleAttachment(p),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:p=>this._handleRollback(p),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(pd(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:p=>{p==="close"?this.close():(this._openState=p,this._applyOpenStateClasses())},onThumbnailClick:p=>this._rollbackToThread(p),onLinkClick:p=>{this._saveSessionAndOpenURL(p)},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:p=>{this._presentation.pinnedToBottom=p},onUserInteractingChange:p=>{this._presentation.userInteracting=p},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Hl({onChange:p=>this._panel?.notifyExtension(p),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new ql({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:p=>this._rollbackToThread(p)}),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"),h=!!(g&&d);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const p=new $l;await p.open(),this._session=new Dn(p),await this._restoreFromIndexedDB(h)}catch{this._session=new Dn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const u=()=>this._syncViewportState();if(window.addEventListener("resize",u,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",u)),window.visualViewport){const p=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const m=this._drawer?.getElement();if(!m)return;const b=window.innerHeight-(window.visualViewport?.height??window.innerHeight);m.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,b)}px`)};window.visualViewport.addEventListener("resize",p),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",p))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const f={namespace:"chat",onMessage:p=>this._handleBridgeMessage(p)};t.allowedOrigins!==void 0&&(f.allowedOrigins=t.allowedOrigins),this._bridge=new po(f),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const p of this._pendingActions)this._sendAction(p.action,p.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),ce("gengage:chat:ready",{}),Pt("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"),ce("gengage:chat:open",{state:this._openState}),At("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"),ce("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(),ws(),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=Vl(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=Oa(n)?n:Oa(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}),Oa(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"&&Yr(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:Ja(),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=_o(t);if(!a.ok){ce("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())&&(wa(this.config.accountId),this._drawer?.hideKvkkBanner()),ud(),this._messages.some(r=>r.role==="user")||md(),Le("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||Bl(),!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 _=this._currentThreadId,y=this._messages.filter(x=>x.threadId!==void 0&&x.threadId>_);this._messages=this._messages.filter(x=>!x.threadId||x.threadId<=_);for(const x of y)this._shadow?.querySelector(`[data-message-id="${CSS.escape(x.id)}"]`)?.remove(),this._panel.snapshots.delete(x.id),this._panel.snapshotTypes.delete(x.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(x=>{x instanceof HTMLElement&&x.dataset.threadId&&x.dataset.threadId>_&&x.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ja();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 _=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,y=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(y!==void 0&&y.role==="user"&&y.content===_)){const x=this._createMessage("user",_);x.threadId=n,a?.attachment!==void 0&&(x.attachment=a.attachment),this._drawer?.addMessage(x),this._messages.push(x)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const _=this._i18n.productNotFoundMessage,y=this._createMessage("assistant",_);y.threadId=n,y.status="done",this._messages.push(y),this._ensureAssistantMessageRendered(y),this._drawer?.updateBotMessage(y.id,_),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",y),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 _=this._buildRenderContext(),y=this._renderPanelFromSource(o,_);this._drawer.setPanelContent(y),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 h={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(h.attachment=a.attachment);const u=this._getVisibleMessages().filter(_=>_!==d&&(_.content||_.role==="assistant")).slice(-50).map(_=>({role:_.role==="user"?"user":"model",content:_.content??""})),f={outputLanguage:rd(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:$n(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(f.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(f.viewId=this.config.session.viewId);const p=bs(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),m={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:p.type,locale:this.config.locale??"tr",meta:f,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(m.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(m.view_id=this.config.session.viewId),p.payload!==void 0&&(m.payload=p.payload),this.config.pageContext?.sku!==void 0&&(m.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(m.page_type=this.config.pageContext.pageType);const b=crypto.randomUUID(),C=Date.now();let v=0,w=!1,k=!1,A=!1,B=!1,I=!1;const H=Ks();let Q=null;const K=()=>{if(this._drawer){if(this._isMobileViewport||!A){this._drawer.setPanelAiZoneState("hidden");return}B||(I?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(Qt(this.analyticsContext(),{endpoint:"process_action",request_id:b,widget:"chat"}));let N=null;if(N=_s(m,{onTextChunk:(_,y,x)=>{if(!r&&n!==this._activeRequestThreadId||(g+=_,this._drawer?.removeTypingIndicator(),x?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...x.skuToProductItem}),x?.conversationMode&&(this._conversationMode=x.conversationMode),x?.renderHint&&(d.renderHint=x.renderHint),this.track(zi(this.analyticsContext(),{request_id:b,chunk_index:v++,widget:"chat"})),!this._drawer))return;let E=g;const L=x?.kvkk===!0||i&&xa(E);if(y&&L){const R=this.config.accountId;if(!$n(R)){const P=ad(E);P?this._drawer?.showKvkkBanner(P,()=>{this._drawer?.hideKvkkBanner(),wa(R)}):wa(R)}E=td(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=_e(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),y)if(d.content=E,d.status="done",qn(),Js(d))this._drawer?.updateBotMessage(d.id,E,"photo_analysis",d.photoAnalysis);else{const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R){this._activeTypewriter?.cancel();const P=x?.productMentions;this._activeTypewriter=Pl({container:R,html:_e(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,P&&P.length>0&&R&&Al({container:R,mentions:P,onProductClick:$=>{this._sendAction({title:P.find(F=>F.sku===$)?.short_name??$,type:"launchSingleProduct",payload:{sku:$}})}})}})}}},onUISpec:(_,y,x,E)=>{if(!r&&n!==this._activeRequestThreadId||y!=="chat")return;E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const L=_.elements[_.root],z=L?.type??"unknown";if(Ys(z,L?.props??{},H,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:I},d))return;const R=z==="ProductGrid"&&L?.props?.similarsAppend===!0,P=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||R);P&&!E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const $=z==="ProductDetailsPanel"&&x!=="panel"?"panel":x;this.track(Mi(this.analyticsContext(),{request_id:b,chunk_index:v,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const U=L?.props?.products;dd(Array.isArray(U)?U.length:0)}if(z==="ProductGrid"){const U=L?.children?.length??0;hd(void 0,U)}const V=$==="panel"&&this._panel?this._panel.toPanelSpec(_):_;if($==="panel"&&this._panel&&!P){const U=!k;k=!0;const M=jl({componentType:z,similarsAppend:L?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:U});F.panelProductListHeading=void 0,z==="ProductGrid"&&(M==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:V})),M==="appendSimilars"?this._appendSimilarsToPanel(V,F):M==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(V,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(V,F)),this._currentPanelSource={kind:"spec",spec:V},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 G=this._panel.currentType??z,O=L?.props?.panelTitle;if(this._panel.updateTopBar(G,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(A=!this._isMobileViewport,Q){const re=this._buildRenderContext();re.isStreaming=!0;const Gt=this._renderUISpec(Q,re);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Gt}),Q=null}}else M!=="appendSimilars"&&M!=="append"&&(A=!1,Q=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&$==="panel"&&(!d.silent||i)){const U=L?.props?.product;if(U){const M={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:U}}}},G=this._shadow?.querySelector(".gengage-chat-messages");if(G){const O=this._renderUISpec(M,F);d.threadId&&(O.dataset.threadId=d.threadId);const re=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);re&&re.parentNode===G?re.after(O):G.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),k=!0}}}const J=z==="AITopPicks"||z==="AIGroupingCards";let X=!1,oe=!1;if(P&&R&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),J&&!this._isMobileViewport&&!d.silent)if(A){const U=this._renderUISpec(_,F);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:U}),X=!0,Q=null}else Q=_,oe=!0;const j=i&&z==="GroundingReviewCard";if((!d.silent||j)&&($!=="panel"||z==="ProductCard"||P&&z==="ProductGrid"&&(!R||this._isMobileViewport))&&z!=="ActionButtons"&&!X&&!(oe&&J)){const U=this._shadow?.querySelector(".gengage-chat-messages");if(U){const M=this._renderUISpec(_,F);d.threadId&&(M.dataset.threadId=d.threadId),U.appendChild(M),M.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),P&&z==="ProductGrid"&&(k=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const U=L?.children??[],M=z==="ProductGrid"?U.map(G=>_.elements[G]?.props?.product).filter(Boolean):[L?.props?.product].filter(Boolean);for(const G of M){const O=G.sku,re=G.imageUrl;O&&re&&this._thumbnailEntries.push({sku:O,imageUrl:re,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const U=(z==="ProductGrid"?(L?.children??[]).map(M=>_.elements[M]?.props?.product).filter(Boolean):[L?.props?.product??L?.props].filter(Boolean)).map(M=>M.imageUrl).filter(M=>typeof M=="string").slice(0,5);U.length>0&&this._bridge?.send("previewImages",{images:U})}const be=L?.children?.length??0;if(z==="ProductGrid"&&$==="panel"&&!P&&be>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!Rl(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(M=>M.remove()),this._choicePrompterEl=Ml({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 U=this._shadow?.querySelector(".gengage-chat-panel-float");if(U){if(U.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const M=this._choicePrompterEl,G=()=>{window.visualViewport.height/window.innerHeight<.75&&(M.remove(),this._choicePrompterEl===M&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",G))};window.visualViewport.addEventListener("resize",G)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const U=L?.props?.buttons;if(U&&U.length>0){const M=[],G=[];for(const O of U)if(Nl(O)){const re={label:O.label,action:O.action};O.icon&&(re.icon=O.icon),M.push(re)}else G.push(O);M.length>0&&this._drawer?.setInputAreaChips(M.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),G.length>0&&this._drawer?.setPills(G.map(O=>{const re={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(re.icon=O.icon),O.image&&(re.image=O.image),O.description&&(re.description=O.description),re}))}}K(),d.uiSpec=_},onAction:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="action"){const y={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(y.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(y.allowScriptCall=this.config.actionHandling.allowScriptCall),fo(_,{openChat:()=>this.open(),navigate:x=>{pe(x.url)&&(this._bridge?.send("navigate",x),x.newTab?window.open(x.url,"_blank","noopener,noreferrer"):window.location.href=x.url)},saveSession:x=>this.saveSession(x.sessionId,x.sku),addToCart:x=>{ce("gengage:similar:add-to-cart",x)},scriptCall:x=>{ce("gengage:chat:script-call",x),this.config.onScriptCall?.(x)}},y)}},onMetadata:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="metadata"&&_.meta){if(_.meta.panel!==void 0||_.meta.messages!==void 0||_.meta.message_id!==void 0){this._lastBackendContext=_.meta;const x=ga(_.meta.panel);x&&(this._modeController.updateFromContext(x),this._applyUiHints())}if(_.meta.panelLoading){const x=typeof _.meta.panelPendingType=="string"?_.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(x==="productDetails"||x==="productDetailsSimilars")||(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(x),x&&this._panel?.updateTopBarForLoading(x))}if(_.meta.voice){const x=new CustomEvent("gengage:chat:voice",{detail:{payload:_.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(x);if(fd(),E){const L=_.meta.voice;L.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=nc(L.audio_base64,L.content_type??"audio/ogg"))}}if((_.meta.redirectTarget||_.meta.redirect)&&(ce("gengage:chat:redirect",{target:_.meta.redirectTarget??null,payload:_.meta.redirect??null}),Le("redirect","redirect dispatched",{target:_.meta.redirectTarget??null}),this._handleRedirectMetadata(_.meta.redirect)),_.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),_.meta.loading){const x=Array.isArray(_.meta.thinkingMessages)?_.meta.thinkingMessages.filter(L=>typeof L=="string"):[],E=typeof _.meta.loadingText=="string"?_.meta.loadingText:void 0;if(x.length>0){const L=E&&this._modeController.shouldCondenseThinking()?[...x.slice(0,2),E]:x;this._drawer?.setThinkingSteps(L)}typeof E=="string"&&E.length>0&&(this._drawer?.addThinkingStep(E),this._bridge?.send("loadingMessage",{text:E}))}_.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",_.meta.visitorDataResponse),_.meta.formType&&this._bridge?.send("glovOtokoc",{type:_.meta.formType,data:_.meta.formPayload}),_.meta.launcherContent&&this._bridge?.send("launcherContent",_.meta.launcherContent),ce("gengage:chat:metadata",{payload:_.meta});const y=_.meta;typeof y.prompt_tokens=="number"&&typeof y.completion_tokens=="number"&&this.track(Bi(this.analyticsContext(),{model:_.model??"unknown",prompt_tokens:y.prompt_tokens,completion_tokens:y.completion_tokens,total_tokens:y.total_tokens??y.prompt_tokens+y.completion_tokens}))}},onError:_=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;I=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,K(),Q=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),Xs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const y=k;w&&!k&&l(),w=!1,k=!1;const x=d.silent||d.content!=null&&d.content.length>0||g.length>0||y,E=typeof navigator<"u"&&navigator.onLine===!1&&na(_),L=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const P=this._messages.indexOf(d);P>=0&&this._messages.splice(P,1)};let z=!1;const R=()=>{if(E)return;this.emit("error",_);const P=_.message;P===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=P);const $=_.message.trim(),F=$.length>0?$:this._i18n.errorMessage,V={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){L(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,V);return}if(Ql(_,F)){L(),z=!0,this._drawer?.showErrorWithRecovery(F,V);return}d.content=F,d.status="done";const J=_e(F.replace(/\r\n/g,`
177
177
  `).split(`
178
178
  `).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,J),this._drawer?.showRecoveryPillsOnly(V)};if(x)this._drawer?.setPills([]),d.silent||R();else if(i||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const P=this._i18n.productNotFoundMessage;d.content=P,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,P),this._markUnavailableProductContext()}else if(R(),E)return;i&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),!z&&d.status==="streaming"&&(d.status="error"),E||this.track(Xt(this.analyticsContext(),{request_id:b,error_code:"STREAM_ERROR",error_message:_.message,widget:"chat"}))},onDone:()=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;if(I=!0,K(),Q){const E=this._buildRenderContext();E.isStreaming=!1;const L=this._shadow?.querySelector(".gengage-chat-messages");if(L){const z=this._renderUISpec(Q,E);d.threadId&&(z.dataset.threadId=d.threadId),L.appendChild(z),z.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}Q=null}this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),Qs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const _=k;if(w&&!k&&l(),w=!1,i&&!g&&!_){const E=this._i18n.productNotFoundMessage;d.content=E,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,E),this._markUnavailableProductContext()}if(k=!1,i){this._pdpPrimingInFlight=!1;const E=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),E||this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",qn()),this._presentation.finalizeAssistantGroup(n);const y=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");y&&(y.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),y.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const x=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,x?()=>{const E=this._buildRenderContext();return this._renderPanelFromSource(x,E)}:void 0),this.track(ut(this.analyticsContext(),{request_id:b,latency_ms:Date.now()-C,chunk_count:v,widget:"chat"})),this.track(Ri(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Di(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},h),this._abortControllers.add(N),!a?.silent&&!r){const _=N;this._drawer?.showStopButton(()=>{_.abort(),this._abortControllers.delete(_),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=_e(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&&(Ol(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,ld());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=it._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${it._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,sd(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 u=o.parentElement,f=this._comparisonSelectedSkus.includes(o.dataset.sku);u.classList.toggle("gengage-chat-comparison-select-wrapper--selected",f);const p=u.querySelector(".gengage-chat-comparison-checkbox");if(p){p.dataset.selected=f?"true":"false",p.setAttribute("aria-pressed",f?"true":"false");const m=p.querySelector(".gengage-chat-comparison-checkbox-icon"),b=p.querySelector(".gengage-chat-comparison-checkbox-label");m&&(m.innerHTML=f?'<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>'),b&&(b.textContent=f?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 h=document.createElement("span");h.className="gengage-chat-comparison-checkbox-label",h.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(d),g.appendChild(h),g.addEventListener("click",u=>{u.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",u=>{u.target.closest(".gengage-chat-comparison-checkbox")||(u.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=wn(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)}Hn(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};ce("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ua(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(ka(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&&Ca(r,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";Un(r)}a.type==="getComparisonTable"&&cd(this._comparisonSelectedSkus);const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{if(Ca(a.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url))ce("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>it._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:it._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};ce("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){gd(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>it._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{...Ss(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Jt(qc(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??Cn,i=(s,c)=>jc(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}},Wu=8e3,Gu=5e3,Ku="https://www.google.com/favicon.ico",Re=new Map,Jr=!1,rt=null,ht=null,Ge=!1;function Yu(e){return typeof e=="string"&&e.toLowerCase().startsWith("tr")}function Qr(e){return Yu(e)?"İnternet bağlantısında sorun var gibi görünüyor. İstek sürerken yeniden deneyeceğiz.":"Your internet connection looks unstable. We'll keep retrying while this request is active."}function Xr(){let e;for(const t of Re.values())e=t;return e}function Da(){rt&&(clearTimeout(rt),rt=null)}function Ju(){ht&&(clearInterval(ht),ht=null)}async function ei(){try{if(typeof navigator<"u"&&navigator.onLine===!1)return!1;if(typeof window<"u"){const a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return navigator.onLine}const e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return await fetch(Ku,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:e.signal}),!0}catch{return navigator.onLine}finally{clearTimeout(t)}}catch{return typeof navigator>"u"?!0:navigator.onLine}}function Ht(){Ge=!1,Ju(),Ya()}function qt(){rt||Ge||Re.size===0||(rt=setTimeout(async()=>{rt=null,!(Ge||Re.size===0)&&!await ei()&&Re.size>0&&(Ge=!0,ra({source:"sdk",message:Qr(Xr()),sticky:!0}),ht||(ht=setInterval(async()=>{if(Re.size===0){Ht();return}await ei()&&(Ht(),qt())},Gu)))},Wu))}function Qu(){Jr||typeof window>"u"||(Jr=!0,window.addEventListener("online",()=>{Ht(),qt()}),window.addEventListener("offline",()=>{Re.size===0||Ge||(Ge=!0,Da(),ra({source:"sdk",message:Qr(Xr()),sticky:!0}))}))}function ti(e){Qu();const t=Symbol(e.source);Re.set(t,e.locale),qt();let a=!1;return()=>{if(!a){if(a=!0,Re.delete(t),Re.size===0){Da(),Ht();return}Ge||(Da(),qt())}}}async function Xu(e,t,a){const n=yt("launcher_action",t),r={uiSpecs:[],actions:[]},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(i.signal=a);const o=await fetch(n,i);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const s={onEvent:c=>{const l=vt(c);if(l&&(l.type==="ui_spec"&&r.uiSpecs.push(l.spec),l.type==="ui_spec"&&l.spec.elements)){for(const g of Object.values(l.spec.elements))if(g.type==="ActionButton"&&g.props?.action){const d=g.props.action;r.actions.push(d)}}}};return a!==void 0&&(s.signal=a),await bt(o,s),r}function ai(e){const t=document.createElement("div");t.className="gengage-qna-buttons gds-toolbar",t.dataset.gengagePart="qna-button-row",t.setAttribute("role","group"),t.setAttribute("aria-label",e.quickQuestionsAriaLabel??"Quick questions"),e.orientation==="vertical"&&(t.style.flexDirection="column");for(const a of e.actions){const n=document.createElement("button");n.className="gengage-qna-button gds-chip",n.dataset.gengagePart="qna-quick-question",n.textContent=a.title,n.type="button",n.addEventListener("click",()=>{const r={title:a.title,type:a.type};a.payload!==void 0&&(r.payload=a.payload),e.onAction(r)}),t.appendChild(n)}if(e.ctaText||e.onOpenChat){const a=document.createElement("button");a.className="gengage-qna-cta gds-btn gds-btn-secondary",a.dataset.gengagePart="qna-cta",a.textContent=e.ctaText??e.defaultCtaText??"Ask something else",a.type="button",a.addEventListener("click",()=>{e.onOpenChat?.()}),t.appendChild(a)}return t}function em(e){const t=document.createElement("div");t.className="gengage-qna-input-wrapper",t.dataset.gengagePart="qna-input-wrapper";const a=document.createElement("div");a.className="gengage-qna-input-combo",a.dataset.gengagePart="qna-input-combo";const n=document.createElement("input");n.type="text",n.className="gengage-qna-input",n.dataset.gengagePart="qna-input",n.setAttribute("aria-label",e.askQuestionAriaLabel??"Ask a question");const r=Array.isArray(e.placeholders)?e.placeholders:e.placeholders?[e.placeholders]:[e.defaultInputPlaceholder??"Ask a question..."];let i=0,o=r[0]??"";n.placeholder=o;let s=null,c=null,l=!1;const g=()=>{s&&clearInterval(s),s=null,c&&clearTimeout(c),c=null,n.classList.remove("gengage-qna-input--fade")},d=()=>r.length>1&&!l&&n.value.trim().length===0,h=()=>{g(),d()&&(s=setInterval(()=>{d()&&(n.classList.add("gengage-qna-input--fade"),c=setTimeout(()=>{i=(i+1)%r.length,o=r[i]??"",n.placeholder=o,n.classList.remove("gengage-qna-input--fade")},180))},3e3))},u=document.createElement("div");u.className="gengage-qna-input-actions",u.dataset.gengagePart="qna-input-actions";const f=document.createElement("button");f.className="gengage-qna-icon-btn gengage-qna-clear gengage-qna-icon-btn--hidden",f.type="button",f.dataset.gengagePart="qna-clear",f.setAttribute("aria-label","Clear question"),f.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6L6 18" /><path d="M6 6L18 18" /></svg>';const p=document.createElement("button");p.className="gengage-qna-icon-btn gengage-qna-send gengage-qna-icon-btn--hidden",p.type="button",p.dataset.gengagePart="qna-send",p.setAttribute("aria-label",e.sendQuestionAriaLabel??"Send question"),p.disabled=!0,p.innerHTML=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M22 2L11 13" /><path d="M22 2L15 22L11 13L2 9L22 2Z" /></svg><span class="gengage-qna-sr-only">${e.ctaLabel??e.sendButtonText??"Ask"}</span>`;const m=()=>{const C=n.value.trim().length>0;f.classList.toggle("gengage-qna-icon-btn--hidden",!C),p.classList.toggle("gengage-qna-icon-btn--hidden",!C),p.classList.toggle("gengage-qna-send--active",C),p.disabled=!C},b=()=>{const C=n.value.trim();C&&(e.onSubmit({title:C,type:"user_message",payload:C}),n.value="",m(),h())};return f.addEventListener("click",()=>{n.value="",m(),n.focus({preventScroll:!0})}),p.addEventListener("click",b),n.addEventListener("focus",()=>{l=!0,g(),n.placeholder=""}),n.addEventListener("blur",()=>{l=!1,n.value.trim().length===0&&(n.placeholder=o),h()}),n.addEventListener("input",()=>{if(m(),n.value.trim().length>0){g();return}n.placeholder=l?"":o,h()}),n.addEventListener("keydown",C=>{C.key==="Enter"&&(C.preventDefault(),b()),C.key==="Escape"&&n.value.length>0&&(n.value="",m(),h())}),u.appendChild(f),u.appendChild(p),a.appendChild(n),a.appendChild(u),t.appendChild(a),m(),h(),t._cleanup=()=>{g()},t}function jt(e,t){if(!e||typeof e!="object")return null;const a=e,n=a.type;if(typeof n!="string"||n.length===0)return null;const r=a.title,i=a.payload,o=typeof r=="string"&&r.length>0?r:t;if(!o)return null;const s={title:o,type:n};return i!==void 0&&(s.payload=i),s}function ni(e){const t={title:e.title,type:e.type};return e.payload!==void 0&&(t.payload=e.payload),t}function ri(e,t){const a=[],n=e.props?.actions;if(Array.isArray(n))for(const o of n){const s=jt(o);s&&a.push(s)}const r=e.props?.buttons;if(Array.isArray(r))for(const o of r){if(!o||typeof o!="object")continue;const s=o,c=typeof s.label=="string"?s.label:void 0,l=jt(s.action,c);l&&a.push(l)}if(e.children)for(const o of e.children){const s=t.elements[o];if(!s||s.type!=="ActionButton")continue;const c=typeof s.props?.label=="string"?s.props.label:void 0,l=jt(s.props?.action,c);l&&a.push(l)}const i=new Set;return a.filter(o=>i.has(o.title)?!1:(i.add(o.title),!0))}var ii={ButtonRow:({element:e,spec:t,context:a})=>{const n=ri(e,t).map(ni),r=e.props?.orientation,i={actions:n,onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(i.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(i.ctaText=a.ctaText),(r==="horizontal"||r==="vertical")&&(i.orientation=r),ai(i)},ActionButtons:({element:e,spec:t,context:a})=>{const n={actions:ri(e,t).map(ni),onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(n.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(n.ctaText=a.ctaText),ai(n)},ActionButton:({element:e,context:t})=>{const a=document.createElement("button");a.className="gengage-qna-button gds-chip",a.type="button",a.dataset.gengagePart="qna-action-button";const n=e.props?.label;typeof n=="string"?a.textContent=n:a.textContent=t.i18n.defaultCtaText;const r=jt(e.props?.action,typeof n=="string"?n:void 0);return r&&a.addEventListener("click",()=>t.onAction(r)),a},TextInput:({element:e,context:t})=>{const a=e.props?.placeholder,n=typeof a=="string"||Array.isArray(a)?a:t.inputPlaceholder,r=typeof e.props?.ctaLabel=="string"?e.props.ctaLabel:void 0,i={onSubmit:t.onAction,askQuestionAriaLabel:t.i18n.askQuestionAriaLabel,defaultInputPlaceholder:t.i18n.defaultInputPlaceholder,sendButtonText:t.i18n.sendButton,sendQuestionAriaLabel:t.i18n.sendQuestionAriaLabel};return n!==void 0&&(i.placeholders=n),r!==void 0&&(i.ctaLabel=r),em(i)},QuestionHeading:({element:e,context:t})=>{const a=document.createElement("h3");a.className="gengage-qna-heading",a.dataset.gengagePart="qna-heading";const n=e.props?.text,r=t.headingTitleOverride;return a.textContent=typeof r=="string"&&r.trim().length>0?r:typeof n=="string"?n:"",a},ProductCard:()=>null},oi=({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 tm(){return{...ii}}function am(e,t,a=ii,n=oi){return Yt({spec:e,context:t,registry:a,containerClassName:"gengage-qna-uispec",unknownRenderer:n})}function nm(e){if(!e)return;const t=e.extra;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.visible_skus??t.visibleSkus;if(Array.isArray(n)){const r=n.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()).slice(0,200);if(r.length>0)return r}}const a=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0;return a?[a]:void 0}function si(e,t){if(!e)return null;const a=e.action;if(!a||typeof a!="object")return null;const n=a,r=n.type;if(typeof r!="string"||r.length===0)return null;const i=n.title,o=typeof i=="string"&&i.length>0?i:typeof t=="string"&&t.length>0?t:"";if(!o)return null;const s=n.payload,c={title:o,type:r};return s!==void 0&&(c.payload=s),c}function rm(e,t){const a=e.elements[e.root];if(!a)return!1;const n=r=>{if(r.type!=="ActionButton")return!1;const i=r.props;if(!i||typeof i!="object")return!1;const o=typeof i.label=="string"?i.label:void 0;return o===t?!0:si(i,o)?.title===t};if(a.type==="ActionButton")return n(a);if(a.children)for(const r of a.children){const i=e.elements[r];if(i&&n(i))return!0}if(a.type==="ActionButtons"&&Array.isArray(a.props?.buttons)){for(const r of a.props.buttons)if(r?.label===t||r?.action?.title===t)return!0}return!1}var ci=0;function li(){return ci+=1,`gengage-merge-${ci}`}function im(e,t){const a=e.elements[e.root];if(!a||a.type!=="ButtonRow")return;const n=li();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n]}function om(e,t){const a=e.elements[e.root];if(!a||a.type!=="ActionButtons")return;const n=li();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n];const r=a.props?.buttons??[],i={label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}};a.props={...a.props,buttons:[i,...r]}}function sm(e){const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,...r.payload!==void 0?{payload:r.payload}:{}}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}function cm(e){return e.find(t=>{const a=t.elements[t.root];return a?.type==="ActionButtons"||a?.type==="ButtonRow"})}function di(e,t){const a=e.productContextQuickPillLabel,n={text:a};return t&&t.length>0&&(n.sku_list=t),{title:a,type:"user_message",payload:n}}function lm(e,t,a){const n=a?.skuList,r=[],i=[];for(const c of e){const l=c.elements[c.root];if(l?.type==="ActionButton"){const g=l.props;if(si(g,typeof g?.label=="string"?g.label:void 0)?.type==="findSimilar"){r.push(di(t,n));continue}}i.push(c)}if(r.length===0)return e;const o=di(t,n),s=cm(i);if(!s)return[...i,sm([o])];if(!rm(s,o.title)){const c=s.elements[s.root];c?.type==="ActionButtons"?om(s,o):c?.type==="ButtonRow"&&im(s,o)}return i}var gi={quickQuestionsAriaLabel:"Hızlı sorular",askQuestionAriaLabel:"Soru sorun",defaultInputPlaceholder:"Bir soru sorun...",sendButton:"Sor",sendQuestionAriaLabel:"Soruyu gönder",defaultCtaText:"Başka bir şey sor",redirectingToChat:"Sohbete yönlendiriliyor...",productContextQuickPillLabel:"Bu ürün hakkında ne bilmeliyim?"},dm={quickQuestionsAriaLabel:"Quick questions",askQuestionAriaLabel:"Ask a question",defaultInputPlaceholder:"Ask a question...",sendButton:"Ask",sendQuestionAriaLabel:"Send question",defaultCtaText:"Ask something else",redirectingToChat:"Redirecting to chat...",productContextQuickPillLabel:"What should I know about this product?"};function gm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function pm(e){return gm(e)==="en"?dm:gi}var hm=class extends ft{constructor(...e){super(...e),this._abortController=null,this._debounceTimer=null,this._contentEl=null,this._i18n=gi,this._actionHandler=this._handleAction.bind(this),this._openChatHandler=this._handleOpenChat.bind(this)}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-qna-container",this._contentEl.dataset.gengagePart="qna-container",this.root.appendChild(this._contentEl);const t=e.pageContext?.sku;t&&(this._lastSku=t,await this._fetchAndRender(t)),Pt("qna")}onUpdate(e){const t=e.sku;!t||t===this._lastSku||(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=null,this._lastSku=t,this._fetchAndRender(t)},50))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.2s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._contentEl&&(this._cleanupTextInputTimers(),this._contentEl.remove(),this._contentEl=null)}_abort(){this._abortController?.abort(),this._abortController=null}_resolvedQnaHeaderTitle(){const e=this.config.headerTitle??this.config.headingTitle;if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}_cleanupTextInputTimers(){if(!this._contentEl)return;const e=this._contentEl.querySelectorAll(".gengage-qna-input-wrapper");for(const t of e)t._cleanup?.()}async _fetchAndRender(e){if(this._abort(),this._abortController=new AbortController,!this._contentEl)return;this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const t=this._createLoadingIndicator();this._contentEl.appendChild(t);const a={middlewareUrl:this.config.middlewareUrl},n=crypto.randomUUID(),r=Date.now(),i=ti({source:"qna",locale:this.config.locale});this.track(Qt(this.analyticsContext(),{endpoint:"launcher_action",request_id:n,widget:"qna"}));try{const o={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e,locale:this.config.locale??"tr"},s=this.config.pageContext?.pageType;s!==void 0&&(o.page_type=s);const c=await Xu(o,a,this._abortController.signal);if(this.track(ut(this.analyticsContext(),{request_id:n,latency_ms:Date.now()-r,chunk_count:c.actions.length,widget:"qna"})),this.track(ea(this.analyticsContext(),{message_count:c.actions.length,history_ref:n,redaction_level:"none",widget:"qna"})),!this._contentEl)return;this._contentEl.innerHTML="";const l=document.createElement("div");l.className="gengage-qna-panel gds-panel",l.dataset.gengagePart="qna-panel",this._contentEl.appendChild(l);const g=this._specIncludesType(c.uiSpecs,"QuestionHeading"),d=this._resolvedQnaHeaderTitle()??(this.config.showStaticQuestion&&this.config.staticQuestionText?this.config.staticQuestionText:void 0);if(!g&&d){const v=document.createElement("h3");v.className="gengage-qna-heading",v.textContent=d,l.appendChild(v)}const h=this.config.inputPlaceholder;let u;if(h!==!0)u=h??this._i18n.defaultInputPlaceholder;else if(c.actions.length>0){const v=c.actions.filter(w=>w.type==="user_message"||w.title.includes("?")).map(w=>w.title);u=v.length>0?v:this._i18n.defaultInputPlaceholder}else u=this._i18n.defaultInputPlaceholder;const f={onAction:this._actionHandler,i18n:this._i18n},p=this._resolvedQnaHeaderTitle();p!==void 0&&(f.headingTitleOverride=p),this.config.hideButtonRowCta||(f.onOpenChat=this._openChatHandler,this.config.ctaText!==void 0&&(f.ctaText=this.config.ctaText)),u!==void 0&&(f.inputPlaceholder=u);const m=this._buildFallbackActionsSpec(c.actions),b=nm(this.config.pageContext),C=(c.uiSpecs.length>0?lm(c.uiSpecs,this._i18n,{skuList:b}):[m]).filter(v=>Object.keys(v.elements).length>0);for(const v of C){const w=this._renderUISpec(v,f);l.appendChild(w)}C.length>0&&At("qna"),this._specIncludesType(C,"TextInput")||this._insertStandaloneInputBeforePills(l,f,u)}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;if(ce("gengage:global:error",{source:"qna",code:"FETCH_ERROR",message:Ka(this.config.locale,o)}),this.track(Xt(this.analyticsContext(),{request_id:n,error_code:"FETCH_ERROR",error_message:o instanceof Error?o.message:String(o),widget:"qna"})),this._contentEl){this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const s=document.createElement("div");s.className="gengage-qna-panel",this._contentEl.appendChild(s);const c=this.config.inputPlaceholder===!0?this._i18n.defaultInputPlaceholder:this.config.inputPlaceholder??this._i18n.defaultInputPlaceholder,l={onAction:this._actionHandler,i18n:this._i18n,onOpenChat:this._openChatHandler},g=this._resolvedQnaHeaderTitle();g!==void 0&&(l.headingTitleOverride=g),this.config.ctaText!==void 0&&(l.ctaText=this.config.ctaText),this._appendStandaloneInput(l,c,s)}}finally{i()}}_createLoadingIndicator(){const e=document.createElement("div");e.className="gengage-qna-loading";for(let t=0;t<3;t++){const a=document.createElement("div");a.className="gengage-qna-loading-dot",e.appendChild(a)}return e}_resolveI18n(e){return{...pm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return Jt(tm(),this.config.renderer?.registry)}_renderUISpec(e,t){const a=this._resolveUISpecRegistry(),n=this.config.renderer?.unknownRenderer??oi,r=(o,s)=>am(o,s,a,n),i=this.config.renderer?.renderUISpec;return i?i(e,t,{registry:a,unknownRenderer:n,defaultRender:r}):r(e,t)}_specIncludesType(e,t){for(const a of e)for(const n of Object.values(a.elements))if(n.type===t)return!0;return!1}_buildFallbackActionsSpec(e){if(e.length===0)return{root:"root",elements:{}};const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,payload:r.payload}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}_insertStandaloneInputBeforePills(e,t,a){const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:a}}}},r=this._renderUISpec(n,t),i=r.querySelector(".gengage-qna-input-wrapper");if(!i)return;const o=e.querySelector(".gengage-qna-uispec"),s=o?.querySelector(":scope > .gengage-qna-buttons");if(o&&s)o.insertBefore(i,s);else if(o){const c=o.querySelector(":scope > .gengage-qna-heading");c?c.insertAdjacentElement("afterend",i):o.prepend(i)}else{e.appendChild(r);return}r.remove()}_appendStandaloneInput(e,t,a){if(!this._contentEl)return;const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:t}}}},r=this._renderUISpec(n,e);(a??this._contentEl).appendChild(r)}_handleAction(e){this._showTransitionIndicator(),ka(e.title,e.type),this.config.onActionSelected?.(e),setTimeout(()=>ce("gengage:qna:action",e),350)}_handleOpenChat(){this._showTransitionIndicator(),this.config.onOpenChat?.(),setTimeout(()=>ce("gengage:qna:open-chat",{}),350)}_showTransitionIndicator(){if(!this._contentEl)return;this._contentEl.querySelector(".gengage-qna-transition-indicator")?.remove(),this._contentEl.classList.add("gengage-qna--transitioning");const e=this._i18n.redirectingToChat??"Redirecting to chat...",t=document.createElement("div");t.className="gengage-qna-transition-indicator",t.textContent=e,(this._contentEl.querySelector(".gengage-qna-panel")??this._contentEl).appendChild(t),setTimeout(()=>{this._contentEl?.classList.remove("gengage-qna--transitioning"),t.remove()},600)}};function pi(e){const t=[];for(const a of Object.values(e))if(a.type==="ProductCard"&&a.props){const n=a.props.product??a.props;typeof n.sku=="string"&&typeof n.name=="string"&&t.push(n)}return t}function hi(e){const t=e.headers.get("Content-Type")??"";return t.includes("application/x-ndjson")||t.includes("text/event-stream")}async function um(e,t){const a=[],n={onEvent:r=>{const i=vt(r);!i||i.type!=="ui_spec"||a.push(...pi(i.spec.elements))}};return t!==void 0&&(n.signal=t),await bt(e,n),a}async function mm(e,t,a){const n=yt("similar_products",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(hi(i))return um(i,a);const o=await i.text();if(!o)throw new Error("Empty response body from similar_products endpoint");try{return ps(JSON.parse(o))}catch{throw new Error("Invalid JSON from similar_products endpoint")}}async function fm(e,t){const a=[];let n=null;const r={onEvent:i=>{const o=vt(i);if(o){if(o.type==="metadata"&&o.meta){const s=o.meta.group_name;if(typeof s=="string"){n={name:s,products:[]};const c=o.meta.highlight;typeof c=="string"&&(n.highlight=c),a.push(n)}}o.type==="ui_spec"&&n&&n.products.push(...pi(o.spec.elements))}}};return t!==void 0&&(r.signal=t),await bt(e,r),a}async function bm(e,t,a){const n=yt("product_groupings",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(hi(i))return fm(i,a);const o=await i.text();if(!o)return[];try{return hs(JSON.parse(o))}catch{throw new Error("Invalid JSON from product_groupings endpoint")}}function ui(e){const{product:t,index:a,discountType:n,onClick:r,onAddToCart:i,renderCard:o}=e,s=e.i18n,c=e.pricing;if(e.renderCardElement){const p=e.renderCardElement(t,a);if(p)return p}if(o){const p=document.createElement("div");return p.className="gengage-simrel-card gengage-simrel-card--custom gds-card gds-product-card gds-card-interactive",p.dataset.gengagePart="simrel-product-card",p.innerHTML=_e(o(t,a)),p.addEventListener("click",m=>{m.target.closest(".gengage-simrel-atc")||m.target.closest(".gengage-chat-product-card-atc")||r(t)}),p}const l=document.createElement("article");l.className="gengage-simrel-card gengage-chat-product-card gds-card gds-product-card gds-card-interactive",l.dataset.gengagePart="simrel-product-card",t.inStock===!1&&l.classList.add("gengage-simrel-card--out-of-stock"),l.setAttribute("role","listitem"),l.dataset.sku=t.sku;const g=document.createElement("div");if(g.className="gengage-simrel-card-image gengage-chat-product-card-img-wrapper",g.dataset.gengagePart="simrel-product-card-image",t.imageUrl&&ye(t.imageUrl)){const p=document.createElement("img");p.className="gengage-chat-product-card-img",p.src=t.imageUrl,p.alt=t.name,p.loading="lazy",Se(p),g.appendChild(p)}if(n==="badge"&&t.discountPercent&&t.discountPercent>0){const p=document.createElement("span");p.className="gengage-simrel-badge gengage-chat-product-card-discount-badge",p.textContent=`%${ma(t.discountPercent)}`,g.appendChild(p)}l.appendChild(g);const d=document.createElement("div");if(d.className="gengage-simrel-card-info gengage-chat-product-card-body",d.dataset.gengagePart="simrel-product-card-body",t.brand){const p=document.createElement("div");p.className="gengage-simrel-card-brand gengage-chat-product-card-brand",p.textContent=t.brand,d.appendChild(p)}const h=document.createElement("div");if(h.className="gengage-simrel-card-name gengage-chat-product-card-name",h.textContent=t.name,h.title=t.name,d.appendChild(h),t.rating!=null&&t.rating>0){const p=document.createElement("div");if(p.className="gengage-simrel-card-rating gengage-chat-product-card-rating",p.appendChild(fa(t.rating)),t.reviewCount!=null){const m=document.createElement("span");m.className="gengage-simrel-card-review-count gengage-chat-product-card-review-count",m.textContent=` (${t.reviewCount})`,p.appendChild(m)}d.appendChild(p)}const u=document.createElement("div");if(u.className="gengage-simrel-card-price gengage-chat-product-card-price",t.originalPrice&&t.originalPrice!==t.price&&(n==="strike-through"||!n)){const p=document.createElement("span");p.className="gengage-simrel-card-price-original gengage-chat-product-card-original-price",p.textContent=q(t.originalPrice,c),u.appendChild(p)}if(t.price&&parseFloat(t.price)>0){const p=document.createElement("span");p.className="gengage-simrel-card-price-current gengage-chat-product-card-price-current",p.textContent=q(t.price,c),u.appendChild(p)}d.appendChild(u),l.appendChild(d);const f=document.createElement("button");if(f.className="gengage-simrel-card-cta gengage-chat-product-card-cta gds-btn gds-btn-secondary",f.type="button",f.dataset.gengagePart="simrel-product-card-cta",f.textContent=s?.ctaLabel??"View",f.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),r(t)}),l.appendChild(f),t.inStock===!1){const p=document.createElement("div");p.className="gengage-simrel-card-oos",p.textContent=s?.outOfStockLabel??"Out of Stock",l.appendChild(p)}else if(t.cartCode){const p=document.createElement("button");p.className="gengage-simrel-atc gengage-simrel-atc-button gds-btn gds-btn-secondary",p.type="button",p.textContent=s?.addToCartButton??"Add to Cart",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),i({sku:t.sku,quantity:1,cartCode:t.cartCode})}),l.appendChild(p)}return l.addEventListener("click",p=>{p.target.closest(".gengage-simrel-atc")||p.target.closest(".gengage-chat-product-card-atc")||p.target.closest(".gengage-chat-product-card-cta")||r(t)}),l}function mi(e){const t=document.createElement("div");t.className="gengage-simrel-grid",t.setAttribute("role","list"),t.setAttribute("aria-label",e.i18n?.similarProductsAriaLabel??"Similar products"),e.columns&&t.style.setProperty("--gengage-simrel-columns",String(e.columns));for(let a=0;a<e.products.length;a++){const n={product:e.products[a],index:a,onClick:e.onClick,onAddToCart:e.onAddToCart};e.i18n!==void 0&&(n.i18n=e.i18n),e.discountType!==void 0&&(n.discountType=e.discountType),e.renderCard!==void 0&&(n.renderCard=e.renderCard),e.renderCardElement!==void 0&&(n.renderCardElement=e.renderCardElement);const r=ui(n);t.appendChild(r)}return e.products.length===0&&(t.style.display="none",t.dataset.empty="true"),t}var vm=0;function ym(e){const t=vm++,a=document.createElement("div");if(a.className="gengage-simrel-groups",a.dataset.gengagePart="simrel-groups",e.groups.length===0)return a.style.display="none",a.dataset.empty="true",a;const n=document.createElement("div");n.className="gengage-simrel-tabs gds-toolbar",n.dataset.gengagePart="simrel-tab-bar",n.setAttribute("role","tablist");const r=[],i=[],o=p=>{const m={products:p.products,onClick:e.onClick,onAddToCart:e.onAddToCart};return e.i18n!==void 0&&(m.i18n=e.i18n),e.discountType!==void 0&&(m.discountType=e.discountType),e.renderCard!==void 0&&(m.renderCard=e.renderCard),e.renderCardElement!==void 0&&(m.renderCardElement=e.renderCardElement),e.columns!==void 0&&(m.columns=e.columns),m},s=p=>{for(let v=0;v<r.length;v++){const w=v===p;r[v].classList.toggle("gengage-simrel-tab--active",w),r[v].setAttribute("aria-selected",String(w)),r[v].tabIndex=w?0:-1}const m=e.groups[p],b=i[p];b.innerHTML="";const C=mi(o(m));b.appendChild(C);for(let v=0;v<i.length;v++){const w=v===p;i[v].style.display=w?"":"none",i[v].tabIndex=w?0:-1}};for(let p=0;p<e.groups.length;p++){const m=e.groups[p],b=`gengage-simrel-tab-${t}-${p}`,C=`gengage-simrel-panel-${t}-${p}`,v=document.createElement("button");v.className="gengage-simrel-tab gds-tab",v.type="button",v.dataset.gengagePart="simrel-tab",v.id=b,v.textContent=m.name,v.setAttribute("role","tab"),v.setAttribute("aria-controls",C),v.setAttribute("aria-selected",String(p===0)),v.tabIndex=p===0?0:-1,p===0&&v.classList.add("gengage-simrel-tab--active"),v.addEventListener("click",()=>s(p)),v.addEventListener("keydown",k=>{let A=-1;k.key==="ArrowRight"||k.key==="ArrowDown"?A=(p+1)%e.groups.length:k.key==="ArrowLeft"||k.key==="ArrowUp"?A=(p-1+e.groups.length)%e.groups.length:k.key==="Home"?A=0:k.key==="End"&&(A=e.groups.length-1),A>=0&&(k.preventDefault(),s(A),r[A].focus())}),r.push(v),n.appendChild(v);const w=document.createElement("div");w.className="gengage-simrel-tab-panel",w.dataset.gengagePart="simrel-tab-panel",w.id=C,w.setAttribute("role","tabpanel"),w.setAttribute("aria-labelledby",b),w.tabIndex=p===0?0:-1,p!==0&&(w.style.display="none"),i.push(w)}const c=document.createElement("button");c.type="button",c.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--left",c.setAttribute("aria-label",e.i18n?.scrollTabsLeft??"Scroll tabs left"),c.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';const l=document.createElement("button");l.type="button",l.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--right",l.setAttribute("aria-label",e.i18n?.scrollTabsRight??"Scroll tabs right"),l.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';const g=200;c.addEventListener("click",()=>{n.scrollBy({left:-g,behavior:"smooth"})}),l.addEventListener("click",()=>{n.scrollBy({left:g,behavior:"smooth"})});const d=()=>{const p=n.scrollLeft<=4,m=n.scrollLeft+n.clientWidth>=n.scrollWidth-4;c.style.display=p?"none":"",l.style.display=m?"none":"",n.classList.toggle("gengage-simrel-tabs--peek-right",!m),n.classList.toggle("gengage-simrel-tabs--peek-left",!p)};n.addEventListener("scroll",d,{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(d).observe(n),c.style.display="none",l.style.display="none",requestAnimationFrame(d);const h=document.createElement("div");h.className="gengage-simrel-tabs-wrapper",h.appendChild(c),h.appendChild(n),h.appendChild(l),a.appendChild(h);const u=i[0],f=mi(o(e.groups[0]));u.appendChild(f);for(const p of i)a.appendChild(p);return a}function fi(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.sku!="string"||typeof t.name!="string"||typeof t.url!="string")return null;const a={sku:t.sku,name:t.name,url:t.url},n=t.imageUrl;typeof n=="string"&&(a.imageUrl=n);const r=t.price;typeof r=="string"&&(a.price=r);const i=t.originalPrice;typeof i=="string"&&(a.originalPrice=i);const o=t.discountPercent;typeof o=="number"&&(a.discountPercent=o);const s=t.brand;typeof s=="string"&&(a.brand=s);const c=t.rating;typeof c=="number"&&(a.rating=c);const l=t.reviewCount;typeof l=="number"&&(a.reviewCount=l);const g=t.cartCode;typeof g=="string"&&(a.cartCode=g);const d=t.inStock;typeof d=="boolean"&&(a.inStock=d);const h=t.extras;return h!=null&&typeof h=="object"&&(a.extras=h),a}function _m(e){if(!e||typeof e!="object")return null;const t=e,a=t.title,n=t.type;if(typeof a!="string"||typeof n!="string")return null;const r={title:a,type:n};return t.payload!==void 0&&(r.payload=t.payload),r}var bi={ProductGrid:({element:e,renderElement:t,context:a})=>{const n=document.createElement("div");n.className="gengage-simrel-grid",n.setAttribute("role","list");const r=e.props?.columns;let i;typeof r=="number"&&Number.isFinite(r)&&r>0?i=Math.floor(r):typeof a.gridColumns=="number"&&Number.isFinite(a.gridColumns)&&a.gridColumns>0&&(i=Math.floor(a.gridColumns)),i!==void 0&&n.style.setProperty("--gengage-simrel-columns",String(i));for(const o of e.children??[]){const s=t(o);s&&n.appendChild(s)}if(n.children.length===0){const o=document.createElement("div");o.className="gengage-simrel-empty",o.textContent=a.i18n.emptyStateMessage,n.appendChild(o)}return n},ProductCard:({element:e,context:t})=>{const a=fi(e.props?.product??e.props);if(!a)return null;const n=e.props?.index,r=typeof n=="number"&&Number.isFinite(n)?n:0,i=e.props?.discountType,o=i==="strike-through"||i==="badge"?i:t.discountType,s={product:a,index:r,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n};return o!==void 0&&(s.discountType=o),t.renderCard!==void 0&&(s.renderCard=t.renderCard),t.renderCardElement!==void 0&&(s.renderCardElement=t.renderCardElement),t.pricing!==void 0&&(s.pricing=t.pricing),ui(s)},GroupTabs:({element:e,context:t})=>{const a=e.props?.groups;if(!Array.isArray(a))return null;const n=[];for(const o of a){if(!o||typeof o!="object")continue;const s=o;if(typeof s.name!="string")continue;const c=[];if(Array.isArray(s.products))for(const g of s.products){const d=fi(g);d&&c.push(d)}const l={name:s.name,products:c};typeof s.highlight=="string"&&(l.highlight=s.highlight),n.push(l)}const r={groups:n,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n},i=e.props?.columns;return typeof i=="number"&&Number.isFinite(i)&&i>0?r.columns=Math.floor(i):typeof t.gridColumns=="number"&&Number.isFinite(t.gridColumns)&&t.gridColumns>0&&(r.columns=Math.floor(t.gridColumns)),t.discountType!==void 0&&(r.discountType=t.discountType),t.renderCard!==void 0&&(r.renderCard=t.renderCard),t.renderCardElement!==void 0&&(r.renderCardElement=t.renderCardElement),ym(r)},EmptyState:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-empty";const n=e.props?.message;return a.textContent=typeof n=="string"?n:t.i18n.emptyStateMessage,a},AddToCartButton:({element:e,context:t})=>{const a=e.props?.sku,n=e.props?.cartCode;if(typeof a!="string"||typeof n!="string")return null;const r=document.createElement("button");r.className="gengage-simrel-atc gengage-chat-product-card-cta",r.type="button";const i=e.props?.label;return r.textContent=typeof i=="string"?i:t.i18n.addToCartButton,r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t.onAddToCart({sku:a,quantity:1,cartCode:n})}),r},QuickActions:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-quick-actions";const n=e.props?.actions;if(!Array.isArray(n)||!t.onAction)return a;for(const r of n){if(!r||typeof r!="object")continue;const i=r,o=i.label,s=_m(i.action);if(typeof o!="string"||!s)continue;const c=document.createElement("button");c.className="gengage-simrel-quick-action",c.type="button",c.textContent=o,c.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),t.onAction?.(s)}),a.appendChild(c)}return a}},vi=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function xm(){return{...bi}}function wm(e,t,a=bi,n=vi){return Yt({spec:e,context:t,registry:a,containerClassName:"gengage-simrel-uispec",unknownRenderer:n})}var yi={similarProductsAriaLabel:"Benzer ürünler",emptyStateMessage:"Benzer ürün bulunamadı.",addToCartButton:"Sepete Ekle",ctaLabel:"İncele",outOfStockLabel:"Stokta Yok",decreaseLabel:"Azalt",increaseLabel:"Artır",errorLoadingMessage:"Benzer ürünler yüklenemedi.",retryButtonText:"Tekrar dene",priceSuffix:" TL",scrollTabsLeft:"Sola kaydır",scrollTabsRight:"Sağa kaydır"},km={similarProductsAriaLabel:"Similar products",emptyStateMessage:"No similar products found.",addToCartButton:"Add to cart",ctaLabel:"View",outOfStockLabel:"Out of Stock",decreaseLabel:"Decrease",increaseLabel:"Increase",errorLoadingMessage:"Could not load similar products.",retryButtonText:"Try again",priceSuffix:"",scrollTabsLeft:"Scroll tabs left",scrollTabsRight:"Scroll tabs right"};function Cm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Sm(e){return Cm(e)==="en"?km:yi}var Em=class extends ft{constructor(...e){super(...e),this._abortController=null,this._contentEl=null,this._lastResultCount=-1,this._i18n=yi}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-simrel-container",this._contentEl.dataset.gengagePart="simrel-container";const t=this._clampGridColumns(e.gridColumns);t!==void 0&&this._contentEl.style.setProperty("--gengage-simrel-columns",String(t)),this.root.appendChild(this._contentEl),this._lastSku=e.sku,await this._fetchAndRender(e.sku),Pt("simrel")}onUpdate(e){const t=e.sku;!t||t===this._lastSku&&this._lastResultCount!==0||(this._lastSku=t,this._fetchAndRender(t))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.3s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._contentEl&&(this._contentEl.remove(),this._contentEl=null)}_handleProductClick(e){const t={sku:e.sku,name:e.name,url:e.url};if(e.imageUrl!==void 0&&(t.imageUrl=e.imageUrl),e.price!==void 0&&(t.price=e.price),e.originalPrice!==void 0&&(t.originalPrice=e.originalPrice),e.discountPercent!==void 0&&(t.discountPercent=e.discountPercent),e.brand!==void 0&&(t.brand=e.brand),e.rating!==void 0&&(t.rating=e.rating),e.reviewCount!==void 0&&(t.reviewCount=e.reviewCount),e.cartCode!==void 0&&(t.cartCode=e.cartCode),e.inStock!==void 0&&(t.inStock=e.inStock),this.config.onProductClick?.(t)===!1)return;Ca(e.sku,e.name);const a=this.config.session?.sessionId??null;ce("gengage:similar:product-click",{sku:e.sku,url:e.url,sessionId:a}),this.config.onProductNavigate?.(e.url,e.sku,a)}_handleAddToCart(e){Hn(e.sku,e.quantity),this.config.onAddToCart?.(e),ce("gengage:similar:add-to-cart",e),this.track(Ua(this.analyticsContext(),{attribution_source:"simrel",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:e.quantity,sku:e.sku}))}_abort(){this._abortController?.abort(),this._abortController=null}_isSuperseded(e){return this._abortController?.signal!==e}async _fetchAndRender(e){this._abort(),this._abortController=new AbortController;const t=this._abortController.signal,a=setTimeout(()=>this._abortController?.abort(),1e4);if(t.addEventListener("abort",()=>clearTimeout(a)),!this._contentEl)return;this._contentEl.innerHTML="",this._contentEl.style.display="";const n=document.createElement("div");n.className="gengage-simrel-loading",n.dataset.gengagePart="simrel-loading";const r=document.createElement("div");r.className="gengage-simrel-spinner",r.dataset.gengagePart="simrel-loading-spinner",n.appendChild(r),this._contentEl.appendChild(n);const i={middlewareUrl:this.config.middlewareUrl},o=crypto.randomUUID(),s=Date.now(),c=ti({source:"simrel",locale:this.config.locale});this.track(Qt(this.analyticsContext(),{endpoint:"similar_products",request_id:o,widget:"simrel"}));try{const l={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e};this.config.domain!==void 0&&(l.domain=this.config.domain);const g=await mm(l,i,t);if(this._lastResultCount=g.length,!this._contentEl)return;if(this._contentEl.innerHTML="",g.length>0)try{const d=g.map(f=>f.sku),h=new Map(g.map(f=>[f.sku,f])),u=(await bm({account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",skus:d},i,t)).map(f=>({...f,products:f.products.map(p=>({...h.get(p.sku),...p})).filter(p=>typeof p.sku=="string"&&typeof p.name=="string"&&typeof p.url=="string")})).filter(f=>f.products.length>0);if(u.length>0&&this._contentEl){const f=this._buildGroupsSpec(u),p=this._renderUISpec(f);this._contentEl.appendChild(p),At("simrel"),this.track(ut(this.analyticsContext(),{request_id:o,latency_ms:Date.now()-s,chunk_count:u.reduce((m,b)=>m+b.products.length,0),widget:"simrel"})),this.track(ea(this.analyticsContext(),{message_count:u.reduce((m,b)=>m+b.products.length,0),history_ref:o,redaction_level:"none",widget:"simrel"}));return}}catch{}if(this._isSuperseded(t))return;if(this._contentEl){const d=this._buildProductsSpec(g),h=this._renderUISpec(d);this._contentEl.appendChild(h)}g.length>0&&At("simrel"),this.track(ut(this.analyticsContext(),{request_id:o,latency_ms:Date.now()-s,chunk_count:g.length,widget:"simrel"})),this.track(ea(this.analyticsContext(),{message_count:g.length,history_ref:o,redaction_level:"none",widget:"simrel"}))}catch(l){if(l instanceof DOMException&&l.name==="AbortError"&&this._isSuperseded(t))return;if(ce("gengage:global:error",{source:"simrel",code:"FETCH_ERROR",message:Ka(this.config.locale,l)}),this.track(Xt(this.analyticsContext(),{request_id:o,error_code:"FETCH_ERROR",error_message:l instanceof Error?l.message:String(l),widget:"simrel"})),this._contentEl){this._contentEl.innerHTML="";const g=document.createElement("div");g.className="gengage-simrel-error";const d=document.createElement("span");d.textContent=this._i18n.errorLoadingMessage,g.appendChild(d);const h=document.createElement("button");h.className="gengage-simrel-retry",h.textContent=this._i18n.retryButtonText,h.addEventListener("click",()=>{this._fetchAndRender(this.config.sku)}),g.appendChild(h),this._contentEl.appendChild(g)}}finally{c()}}_clampGridColumns(e){if(!(e===void 0||typeof e!="number"||!Number.isFinite(e)))return Math.max(1,Math.min(12,Math.floor(e)))}_resolveI18n(e){return{...Sm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return Jt(xm(),this.config.renderer?.registry)}_buildRenderContext(){const e=this.config.renderCard,t={onClick:n=>this._handleProductClick(n),onAddToCart:n=>this._handleAddToCart(n),i18n:this._i18n};this.config.discountType!==void 0&&(t.discountType=this.config.discountType),e!==void 0&&(t.renderCard=e),this.config.renderCardElement!==void 0&&(t.renderCardElement=this.config.renderCardElement),this.config.pricing!==void 0&&(t.pricing=this.config.pricing);const a=this._clampGridColumns(this.config.gridColumns);return a!==void 0&&(t.gridColumns=a),t}_renderUISpec(e){const t=this._resolveUISpecRegistry(),a=this._buildRenderContext(),n=this.config.renderer?.unknownRenderer??vi,r=(o,s)=>wm(o,s,t,n),i=this.config.renderer?.renderUISpec;return i?i(e,a,{registry:t,unknownRenderer:n,defaultRender:r}):r(e,a)}_buildProductsSpec(e){const t={},a=[];for(let i=0;i<e.length;i++){const o=e[i],s=`product-${i}`;a.push(s),t[s]={type:"ProductCard",props:{product:o,index:i,discountType:this.config.discountType}}}const n={layout:"grid"},r=this._clampGridColumns(this.config.gridColumns);return r!==void 0&&(n.columns=r),t.root={type:"ProductGrid",props:n,children:a},{root:"root",elements:t}}_buildGroupsSpec(e){return{root:"root",elements:{root:{type:"GroupTabs",props:{groups:e}}}}}},_i={findSimilarLabel:"Benzerlerini Bul"},Tm={findSimilarLabel:"Find Similar"};function Pm(e,t){return t?.findSimilarLabel?t.findSimilarLabel:(e??"tr").toLowerCase().startsWith("en")?Tm.findSimilarLabel:_i.findSimilarLabel}function Zt(e){const t=typeof e.sku=="string"&&e.sku.length>0?e.sku:void 0,a=typeof e.pageContext?.sku=="string"&&e.pageContext.sku.length>0?e.pageContext.sku:void 0;return t??a}var Am=class extends ft{constructor(...e){super(...e),this._button=null,this._label=_i.findSimilarLabel}async onInit(e){this._label=Pm(e.locale,e.i18n),this.root.classList.add("gengage-simbut-root"),window.getComputedStyle(this.root).position==="static"&&(this.root.style.position="relative");const t=document.createElement("button");t.type="button",t.className="gengage-chat-find-similar-pill",t.textContent=this._label,this._button=t;const a=()=>{t.disabled=!(Zt(this.config)&&(this.config.onFindSimilar||this.config.chat))};t.addEventListener("click",n=>{n.stopPropagation();const r=Zt(this.config);if(!r)return;const i=this.config.imageUrl,o=typeof i=="string"&&pe(i)?i:void 0;if(ka(this._label,"findSimilar"),Un(r),this.config.onFindSimilar){this.config.onFindSimilar(o?{sku:r,imageUrl:o}:{sku:r});return}const s=this.config.chat;if(!s)return;const c={title:this._label,type:"findSimilar",payload:o?{sku:r,image_url:o}:{sku:r}};s.openWithAction(c,{sku:r})}),this.root.appendChild(t),a(),Pt("simbut")}onUpdate(e){if(!this._button)return;const t=!!Zt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}hide(){this.isVisible&&(this.isVisible=!1,this._button&&(this._button.style.display="none"),this.onHide(),this.emit("hide"))}show(){this.isVisible||(this.isVisible=!0,this._button&&(this._button.style.display=""),this.onShow(),this.emit("show"))}_cleanupRoot(){}onShow(){}onHide(){}onDestroy(){this._button?.remove(),this._button=null}setChat(e){if(this.config.chat=e,this._button){const t=!!Zt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}}},Vt=Be({enabled:We().default(!0)}),Lm=Be({chat:Ce().optional(),qna:Ce().optional(),simrel:Ce().optional(),simbut:Ce().optional()}),Im=Be({}),Nm=Ra(["none","x-api-key-header","bearer-header","body-api-key"]),zm=Be({mode:Nm.default("none"),key:Ce().optional(),headerName:Ce().optional(),bodyField:Ce().default("api_key")}),Mm=Be({enabled:We().default(!0),endpoint:Ce().default("/analytics"),auth:zm.default({mode:"none",bodyField:"api_key"}),fireAndForget:We().default(!0),useBeacon:We().default(!0),keepaliveFetch:We().default(!0),timeoutMs:Hr().int().positive().default(4e3),maxRetries:Hr().int().min(0).max(5).default(1)}),xi="__gengageWidgetsInit",Bm=Be({idempotencyKey:Ce().default(xi),requireDomReady:We().default(!0)}),Rm=Ra(["log-and-ignore","throw","delegate"]),Om=Be({unknownActionPolicy:Rm.default("log-and-ignore"),allowScriptCall:We().default(!1)}),uf=Be({version:Tu("1",{error:'version must be "1"'}),accountId:Ce({error:"accountId must be a non-empty string"}).min(1,{error:"accountId must be a non-empty string"}),middlewareUrl:Ce({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}).url({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}),locale:Ce().optional(),widgets:Be({chat:Vt.default({enabled:!0}),qna:Vt.default({enabled:!0}),simrel:Vt.default({enabled:!0}),simbut:Vt.default({enabled:!1})}),mounts:Lm.default({}),transport:Im.default({}),analytics:Mm.default({enabled:!0,endpoint:"/analytics",auth:{mode:"none",bodyField:"api_key"},fireAndForget:!0,useBeacon:!0,keepaliveFetch:!0,timeoutMs:4e3,maxRetries:1}),gtm:Bm.default({idempotencyKey:"__gengageWidgetsInit",requireDomReady:!0}),actionHandling:Om.default({unknownActionPolicy:"log-and-ignore",allowScriptCall:!1})}),Dm=`${xi}_overlay_`,Fm="#gengage-qna",$m="#gengage-simrel",Um="#gengage-simbut";function wi(){const e=window;return e.__gengageOverlayRegistry||(e.__gengageOverlayRegistry={instances:{},pending:{}}),e.__gengageOverlayRegistry}function Hm(e){const t={pageType:e.pageContext?.pageType??(e.sku!==void 0?"pdp":"other")},a=e.pageContext;return a?.sku!==void 0&&(t.sku=a.sku),a?.price!==void 0&&(t.price=a.price),a?.categoryTree!==void 0&&(t.categoryTree=a.categoryTree),a?.url!==void 0&&(t.url=a.url),a?.extra!==void 0&&(t.extra=a.extra),e.sku!==void 0&&(t.sku=e.sku),t}function qm(e,t){const a={...e,...t,pageType:t.pageType??e.pageType};return t.sku===void 0&&e.sku!==void 0&&(a.sku=e.sku),a}function Fa(e){return e instanceof HTMLElement||document.querySelector(e)?e:null}function ki(e){return e.idempotencyKey??`${Dm}${e.accountId}`}var jm=class{constructor(e,t){this.options=e,this.onDestroy=t,this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,this._analyticsClient=null,this._offQnaWire=null,this._destroyed=!1,this._queue=Promise.resolve(),this._warnedQnaMountMissing=!1,this._warnedSimRelMountMissing=!1,this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this.idempotencyKey=ki(e),this.session=ja(e.session),this._pageContext=Hm(e)}get chat(){return this._chat}get qna(){return this._qna}get simrel(){return this._simrel}get simbut(){return this._simbut}get analyticsClient(){return this._analyticsClient}async init(){window.gengage||(window.gengage={}),window.gengage.sessionId=this.session.sessionId,window.gengage.pageContext=this._pageContext,await this._initChat(),this.options.wireQnaToChat!==!1&&(this._offQnaWire=Ki()),await this._syncPdpWidgets(),window.gengage.overlay=this}openChat(e){this._chat?.open(e)}closeChat(){this._chat?.close()}async updateContext(e){this._destroyed||await this._enqueue(async()=>{this._pageContext=qm(this._pageContext,e),window.gengage||(window.gengage={}),window.gengage.pageContext=this._pageContext,this._chat?.update(e),this._qna?.update(e),this._simrel?.update(e),this._simbut?.update(e),await this._syncPdpWidgets()})}async updateSku(e,t="pdp"){await this.updateContext({sku:e,pageType:t})}destroy(){this._destroyed||(this._destroyed=!0,this._offQnaWire?.(),this._offQnaWire=null,this._chat?.destroy(),this._qna?.destroy(),this._simrel?.destroy(),this._simbut?.destroy(),this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,window.gengage?.overlay===this&&delete window.gengage.overlay,this.onDestroy())}async _initChat(){if(this.options.chat?.enabled===!1)return;const e=this.options.middlewareUrl,t=this.options.chat?.productDetailsExtended??this.options.productDetailsExtended,a=this.options.chat?.isDemoWebsite??this.options.isDemoWebsite,n={accountId:this.options.accountId,middlewareUrl:e,session:this.session,pageContext:this._pageContext,variant:this.options.chat?.variant??"floating"};this.options.theme!==void 0&&(n.theme=this.options.theme),this.options.locale!==void 0&&(n.locale=this.options.locale),this.options.pricing!==void 0&&(n.pricing=this.options.pricing),this.options.chat?.mountTarget!==void 0&&(n.mountTarget=this.options.chat.mountTarget),this.options.chat?.pillLauncher!==void 0&&(n.pillLauncher=this.options.chat.pillLauncher),this.options.chat?.launcherImageUrl!==void 0?n.launcherImageUrl=this.options.chat.launcherImageUrl:this.options.chat?.launcherSvg!==void 0&&(n.launcherSvg=this.options.chat.launcherSvg),this.options.chat?.headerTitle!==void 0&&(n.headerTitle=this.options.chat.headerTitle),this.options.chat?.headerAvatarUrl!==void 0&&(n.headerAvatarUrl=this.options.chat.headerAvatarUrl),this.options.chat?.headerBadge!==void 0&&(n.headerBadge=this.options.chat.headerBadge),this.options.chat?.headerCartUrl!==void 0&&(n.headerCartUrl=this.options.chat.headerCartUrl),this.options.chat?.headerFavoritesToggle!==void 0&&(n.headerFavoritesToggle=this.options.chat.headerFavoritesToggle),this.options.chat?.onFavoritesClick!==void 0&&(n.onFavoritesClick=this.options.chat.onFavoritesClick),this.options.chat?.hideMobileLauncher!==void 0&&(n.hideMobileLauncher=this.options.chat.hideMobileLauncher),this.options.chat?.mobileBreakpoint!==void 0&&(n.mobileBreakpoint=this.options.chat.mobileBreakpoint),this.options.chat?.mobileInitialState!==void 0&&(n.mobileInitialState=this.options.chat.mobileInitialState),this.options.chat?.i18n!==void 0&&(n.i18n=this.options.chat.i18n),this.options.chat?.actionHandling!==void 0&&(n.actionHandling=this.options.chat.actionHandling),this.options.chat?.renderer!==void 0&&(n.renderer=this.options.chat.renderer),t!==void 0&&(n.productDetailsExtended=t),a!==void 0&&(n.isDemoWebsite=a),this.options.chat?.productPriceUi!==void 0&&(n.productPriceUi=this.options.chat.productPriceUi),this.options.onScriptCall!==void 0&&(n.onScriptCall=this.options.onScriptCall),this.options.onAddToCart!==void 0&&(n.onAddToCart=this.options.onAddToCart),this.options.chat?.onOpen!==void 0&&(n.onOpen=this.options.chat.onOpen),this.options.chat?.onClose!==void 0&&(n.onClose=this.options.chat.onClose),this._chat=new Vu,await this._chat.init(n)}async _syncPdpWidgets(){if(this._destroyed)return;const e=this._pageContext.sku;if(!(this._pageContext.pageType==="pdp"&&e!==void 0&&e.length>0)){this._qna?.hide(),this._simrel?.hide(),this._simbut?.hide();return}const t=this.options.middlewareUrl;if(this.options.qna?.enabled!==!1){const a=this.options.qna?.mountTarget??Fm,n=Fa(a);if(n)if(this._warnedQnaMountMissing=!1,this._qna)this._qna.show(),this._qna.update({pageType:"pdp",sku:e});else{const r=new hm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.qna?.ctaText!==void 0&&(i.ctaText=this.options.qna.ctaText),this.options.qna?.hideButtonRowCta!==void 0&&(i.hideButtonRowCta=this.options.qna.hideButtonRowCta),this.options.qna?.inputPlaceholder!==void 0&&(i.inputPlaceholder=this.options.qna.inputPlaceholder),this.options.qna?.i18n!==void 0&&(i.i18n=this.options.qna.i18n),this.options.qna?.renderer!==void 0&&(i.renderer=this.options.qna.renderer);const o=this.options.qna?.headerTitle??this.options.qna?.headingTitle;o!==void 0&&(i.headerTitle=o),await r.init(i),this._qna=r}else this._qna?.destroy(),this._qna=null,this._warnedQnaMountMissing||(console.warn(`[gengage] QNA mount target not found: ${a}`),this._warnedQnaMountMissing=!0)}else this._qna?.destroy(),this._qna=null;if(this.options.simrel?.enabled!==!1){const a=this.options.simrel?.mountTarget??$m,n=Fa(a);if(n)if(this._warnedSimRelMountMissing=!1,this._simrel)this._simrel.show(),this._simrel.update({pageType:"pdp",sku:e});else{const r=new Em,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,sku:e,mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.pricing!==void 0&&(i.pricing=this.options.pricing),this.options.simrel?.discountType!==void 0&&(i.discountType=this.options.simrel.discountType),this.options.simrel?.renderCardElement!==void 0&&(i.renderCardElement=this.options.simrel.renderCardElement),this.options.simrel?.renderer!==void 0&&(i.renderer=this.options.simrel.renderer),this.options.onAddToCart!==void 0&&(i.onAddToCart=this.options.onAddToCart),this.options.onProductNavigate!==void 0?i.onProductNavigate=this.options.onProductNavigate:i.onProductNavigate=(o,s,c)=>{pe(o)&&(this._chat?.saveSession(c??this.session.sessionId,s),window.location.href=o)},await r.init(i),this._simrel=r}else this._simrel?.destroy(),this._simrel=null,this._warnedSimRelMountMissing||(console.warn(`[gengage] SimRel mount target not found: ${a}`),this._warnedSimRelMountMissing=!0)}else this._simrel?.destroy(),this._simrel=null;if(this.options.simbut&&this.options.simbut.enabled!==!1){const a=this.options.simbut.mountTarget??Um,n=Fa(a),r=this._chat??this.options.simbut.onFindSimilar;if(n&&r)if(this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this._simbut)this._simbut.show(),this._simbut.setChat(this._chat),this._simbut.update({pageType:"pdp",sku:e});else{const i=new Am,o={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n,chat:this._chat};this.options.theme!==void 0&&(o.theme=this.options.theme),this.options.locale!==void 0&&(o.locale=this.options.locale),this.options.simbut.imageUrl!==void 0&&(o.imageUrl=this.options.simbut.imageUrl),this.options.simbut.i18n!==void 0&&(o.i18n=this.options.simbut.i18n),this.options.simbut.onFindSimilar!==void 0&&(o.onFindSimilar=this.options.simbut.onFindSimilar),await i.init(o),this._simbut=i}else this._simbut?.destroy(),this._simbut=null,!n&&!this._warnedSimButMountMissing?(console.warn(`[gengage] SimBut mount target not found: ${a}`),this._warnedSimButMountMissing=!0):!r&&!this._warnedSimButNoChat&&(console.warn("[gengage] SimBut requires chat to be enabled or simbut.onFindSimilar"),this._warnedSimButNoChat=!0)}else this._simbut?.destroy(),this._simbut=null}_enqueue(e){const t=this._queue.then(e);return this._queue=t.catch(a=>{}),t}};async function Zm(e){const t=ki(e),a=wi(),n=a.instances[t];if(n)return n;const r=a.pending[t];if(r)return r;const i=new jm(e,()=>{const s=wi();delete s.instances[t],delete s.pending[t]}),o=i.init().then(()=>(a.instances[t]=i,delete a.pending[t],i)).catch(s=>{throw delete a.pending[t],s});return a.pending[t]=o,o}var Ci=["gengage:chat:open","gengage:chat:close","gengage:chat:ready","gengage:chat:add-to-cart","gengage:qna:action","gengage:qna:open-chat","gengage:similar:product-click","gengage:similar:add-to-cart","gengage:global:error","gengage:context:update"],Vm=32,Si="#gengage-qna",Ei="#gengage-simrel";function mf(e){return e}function Wm(e){let t=e;if(typeof e=="string"){const i=e.trim();if(i.length===0)return null;if(!i.startsWith("{")&&!i.startsWith("["))return{type:i};try{t=JSON.parse(i)}catch{return null}}if(!t||typeof t!="object")return null;const a=t,n=[a.type,a.command,a.action,a.event].find(i=>typeof i=="string"&&i.length>0);if(!n)return null;let r=a.payload;if(r===void 0&&"data"in a&&(r=a.data),n==="setSession"&&r===void 0){const i={};typeof a.sessionId=="string"&&(i.sessionId=a.sessionId),typeof a.userId=="string"&&(i.userId=a.userId),(i.sessionId!==void 0||i.userId!==void 0)&&(r=i)}return r===void 0?{type:n}:{type:n,payload:r}}function Gm(e){if(typeof e=="string"&&e.length>0)return{sku:e};if(e&&typeof e=="object"&&"sku"in e){const t=e.sku;if(typeof t=="string"&&t.length>0){const a=e.pageType;return a!==void 0?{sku:t,pageType:a}:{sku:t}}}return null}function $a(e,t){return t instanceof HTMLElement?!0:typeof t!="string"?!1:e.document.querySelector(t)!==null}function Ti(e,t,a){if(t instanceof HTMLElement||$a(e,t)||typeof t!="string")return t;if(t.startsWith("#")){const i=t.slice(1);if(i.length>0){const o=e.document.getElementById(i);if(o)return o;const s=e.document.createElement("div");return s.id=i,e.document.body.appendChild(s),s}}const n=e.document.getElementById(a);if(n)return n;const r=e.document.createElement("div");return r.id=a,e.document.body.appendChild(r),r}function Pi(e,t){const a=e.webkit?.messageHandlers?.[t];return a&&typeof a.postMessage=="function"?a.postMessage.bind(a):null}function Wt(e,t){const a=e[t];return a&&typeof a=="object"&&typeof a.postMessage=="function"?a:null}function Ai(e={}){const t=e.win??window,a=e.iosHandlerName??"gengage",n=e.androidInterfaceName??"GengageNative",r=e.reactNativeInterfaceName??"ReactNativeWebView";return Pi(t,a)?"ios":Wt(t,n)?"android":Wt(t,r)?"react-native":"browser"}function Li(e,t={}){const a=t.win??window;if(e.sessionId!==void 0){a.__gengageSessionId=e.sessionId,a.gengage||(a.gengage={}),a.gengage.sessionId=e.sessionId;try{a.sessionStorage.setItem("gengage_session_id",e.sessionId)}catch{}}if(e.userId!==void 0){a.gengage||(a.gengage={});const n=a.gengage,r=n.session??{};r.userId=e.userId,n.session=r}}function Ii(e={}){const t=e.win??window,a=t;if(a.gengageNative)return a.gengageNative;const n=e.iosHandlerName??"gengage",r=e.androidInterfaceName??"GengageNative",i=e.reactNativeInterfaceName??"ReactNativeWebView",o=e.trackedEvents??[...Ci],s=Ai({win:t,iosHandlerName:n,androidInterfaceName:r,reactNativeInterfaceName:i});let c=t.gengage?.overlay??null;const l=[],g=(b,C)=>{const v=C===void 0?{type:b}:{type:b,payload:C};if(s==="ios"){Pi(t,n)?.(v);return}if(s==="android"){Wt(t,r)?.postMessage(JSON.stringify(v));return}if(s==="react-native"){Wt(t,i)?.postMessage(JSON.stringify(v));return}},d=b=>{const C=b.detail;!C||typeof C.namespace!="string"||typeof C.type!="string"||g("bridge_message",{namespace:C.namespace,type:C.type,payload:C.payload})};t.addEventListener("gengage:bridge:message",d);const h=o.map(b=>{const C=v=>{const w=v.detail;g("widget_event",{event:b,detail:w})};return t.addEventListener(b,C),{event:b,handler:C}}),u=b=>{l.length>=Vm&&l.shift(),l.push(b)},f=()=>{if(!c||l.length===0)return;const b=l.splice(0,l.length);for(const C of b)p(C)},p=b=>{const C=Wm(b);if(!C||typeof C.type!="string"){console.warn("[gengage:native-bridge] Invalid message:",b);return}const v=C.type,w=C.payload;switch(v){case"openChat":c?c.openChat(w&&typeof w=="object"?w:w==="half"||w==="full"?{state:w}:void 0):u(C);return;case"closeChat":c?c.closeChat():u(C);return;case"updateContext":c&&w&&typeof w=="object"?c.updateContext(w):c?console.warn("[gengage:native-bridge] updateContext: missing payload"):u(C);return;case"updateSku":{const k=Gm(w);if(c&&k){c.updateSku(k.sku,k.pageType);return}c?console.warn("[gengage:native-bridge] updateSku: missing sku"):u(C);return}case"setSession":w&&typeof w=="object"&&Li(w,{win:t});return;case"destroy":c?.destroy();return;default:t.postMessage({gengage:"native",type:v,payload:w},t.location.origin),e.logUnhandled&&console.warn("[gengage:native-bridge] Unhandled inbound type forwarded:",v)}},m={env:s,sendToNative:g,receive:p,setController(b){c=b,f()},destroy(){t.removeEventListener("gengage:bridge:message",d);for(const b of h)t.removeEventListener(b.event,b.handler);l.splice(0,l.length),t.gengageNative===m&&delete t.gengageNative}};return a.gengageNative=m,m}async function Km(e){const{nativeBridge:t,emitReadyEvent:a=!0,...n}=e,r=Ii(t),i={...n};i.onAddToCart||(i.onAddToCart=l=>{r.sendToNative("addToCart",{sku:l.sku,quantity:l.quantity,cartCode:l.cartCode})}),i.onProductNavigate||(i.onProductNavigate=(l,g,d)=>{r.sendToNative("productNavigate",{url:l,sku:g,sessionId:d})});const o=i.qna?.enabled===!0||i.qna?.mountTarget!==void 0;if(i.qna?.enabled!==!1)if(o){const l=Ti(window,i.qna?.mountTarget??Si,"gengage-qna");i.qna={...i.qna,enabled:!0,mountTarget:l}}else $a(window,Si)||(i.qna={enabled:!1});const s=i.simrel?.enabled===!0||i.simrel?.mountTarget!==void 0;if(i.simrel?.enabled!==!1)if(s){const l=Ti(window,i.simrel?.mountTarget??Ei,"gengage-simrel");i.simrel={...i.simrel,enabled:!0,mountTarget:l}}else $a(window,Ei)||(i.simrel={enabled:!1});const c=await Zm(i);return r.setController(c),a&&r.sendToNative("ready",{sessionId:c.session.sessionId,widgets:{chat:c.chat!==null,qna:c.qna!==null,simrel:c.simrel!==null}}),{controller:c,bridge:r,destroy(){c.destroy(),r.destroy()}}}Ye.DEFAULT_NATIVE_TRACKED_EVENTS=Ci,Ye.applyNativeSession=Li,Ye.createNativeWebViewBridge=Ii,Ye.detectNativeEnvironment=Ai,Ye.initNativeOverlayWidgets=Km})(this.Gengage=this.Gengage||{});