@gengage/assistant-fe 0.3.31 → 0.3.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chat-nqCbqHSH.js → chat-DXNI4Pf-.js} +1 -1
- package/dist/chat.iife.js +1 -1
- package/dist/chat.js +1 -1
- package/dist/{common-Dup_GEOS.js → common-BrRNxG_a.js} +2 -2
- package/dist/common.js +4 -4
- package/dist/index.js +6 -6
- package/dist/{native-webview-kqutfGgA.js → native-webview-CPeT9zIq.js} +4 -4
- package/dist/native.iife.js +1 -1
- package/dist/native.js +1 -1
- package/dist/{qna-R1-EoKwH.js → qna-BuBvAr2H.js} +1 -1
- package/dist/qna.iife.js +1 -1
- package/dist/qna.js +1 -1
- package/dist/{schemas-BG_cvFvP.js → schemas-DBRIy5NT.js} +1 -1
- package/dist/{simrel-BREHamN-.js → simrel-BRh5eB2K.js} +1 -1
- package/dist/simrel.iife.js +1 -1
- package/dist/simrel.js +1 -1
- package/package.json +1 -1
package/dist/native.iife.js
CHANGED
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
`,document.head.appendChild(e)}var st=null;function to(){if(st!==null)return st;try{st=localStorage.getItem("gengage:debug")==="1"}catch{st=!1}return st}function Ie(e,t,a){if(!to())return;const n=[`[gengage:${e}]`,t];a!==void 0&&n.push(a),console.debug(...n)}var vt=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=qi(e.theme);this.config={...e,theme:t,session:Ha(e.session)},this.root=this._resolveMount(e.mountTarget),this._applyTheme(t),Ki();const a=bt("gengage:context:update",n=>this.update(n));this._cleanups.push(a),Ie("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,Ie("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"?Ii:Ni;this.track(a(this.analyticsContext(),t))}flushMeteringSummary(e){this.track(Ai(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-${ao(t)}`;this.root.style.setProperty(n,a)}}}};function ao(e){return e.replace(/([A-Z])/g,"-$1").toLowerCase()}function Ka(){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 no=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("*")&&io()&&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(!ro(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 ro(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.gengage=="string"&&typeof t.type=="string"}function io(){try{return typeof process<"u"&&process.env.NODE_ENV!=="production"}catch{return!1}}var oo=console;function so(e,t,a={}){const n=e.action,r=a.logger??oo;switch(Ie("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(!ge(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}co(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=lo(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 co(e,t){if(!(typeof window>"u")){if(!ge(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 lo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function he(e){const t=globalThis.CSS?.escape;if(typeof t=="function")return t(e);const a=Array.from(e);return a.map((n,r)=>{const i=n.codePointAt(0);return i===void 0?"":i===0?"�":i>=1&&i<=31||i===127||r===0&&i>=48&&i<=57||r===1&&a[0]==="-"&&i>=48&&i<=57?`\\${i.toString(16)} `:r===0&&n==="-"&&a.length===1?"\\-":i>=128||/[A-Za-z0-9_-]/.test(n)?n:`\\${n}`}).join("")}var go=["image/jpeg","image/png","image/webp"],Ym=5*1024*1024;function po(e){return go.includes(e.type)?e.size>5242880?{ok:!1,reason:"too_large"}:{ok:!0}:{ok:!1,reason:"invalid_type"}}function Ya(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}function ho(e){const t=[];let a=0,n=!1,r=!1,i=0;for(let o=0;o<e.length;o++){const s=e[o];if(r){r=!1;continue}if(s==="\\"&&n){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"&&a++,s==="}"&&(a--,a===0&&(t.push(e.slice(i,o+1)),i=o+1)))}return t.length>0?t:[e]}function Ja(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 Ya(r)?(Ie("stream",`event: ${r.type}`,r),t.onEvent(r),r.type==="done"?(t.onDone?.(),!0):!1):!1}catch{const r=ho(n);if(r.length>1){for(const i of r)try{const o=JSON.parse(i);if(!Ya(o))continue;if(t.onEvent(o),o.type==="done")return t.onDone?.(),!0}catch{}return!1}return!1}}async function yt(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:h,value:u}=g;if(h)break;r+=n.decode(u,{stream:!0});const d=r.split(`
|
|
48
|
-
`);r=d.pop()??"";for(const f of d)if(Ja(f,t))return}if(r.trim()&&Ja(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 Qa=3,uo=(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():""},ra=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>uo(a,t)).filter(Boolean):[];function mo(e){const t=(e.display_keywords??[]).flatMap(r=>ra(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,Qa);const n=[...ra(e.chosen_attribute,{stripLeadingStopWords:!0}),...ra(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,Qa)}function fo(e){return mo(e).join(" • ")}var bo=["beauty_consulting","watch_expert"];function Xa(e){return typeof e=="string"&&bo.includes(e)}function _t(e){if(typeof e.type!="string")return null;if(vo(e))return e;const t=e;switch(t.type){case"outputText":return yo(t);case"suggestedActions":return _o(t);case"productList":return xo(t);case"productDetails":return wo(t);case"productDetailsSimilars":return ko(t);case"comparisonTable":return Co(t);case"context":return Po(t);case"chatStreamEnd":return Ao();case"loading":return Lo(t);case"panelLoading":return Io(t);case"similarLoading":return No(t);case"redirect":return zo(t);case"error":return Mo(t);case"dummy":return Bo(t);case"launcherAction":return Ro(t);case"text":return ia(t);case"productItem":return Oo(t);case"text_image":return en(t);case"quick_qna":return tn(t);case"reviewHighlights":return Do(t);case"aiProductSuggestions":return $o(t);case"aiProductGroupings":return Ho(t);case"aiSuggestedSearches":return qo(t);case"prosAndCons":return Fo(t);case"getGroundingReview":return jo(t);case"voice":return Vo(t);case"visitorDataResponse":return Uo(t);case"productListPreview":return Zo();case"groupList":return Wo(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return Go(t);case"launcherContent":return Yo(t);case"handoff":return Ko(t);case"uiSpec":return os(t);default:return null}}function vo(e){const t=e.type;if(typeof t!="string")return!1;switch(t){case"metadata":return typeof e.sessionId=="string"&&typeof e.model=="string";case"text_chunk":return typeof e.content=="string";case"ui_spec":{const a=e.widget;if(a!=="chat"&&a!=="qna"&&a!=="simrel")return!1;const n=ke(e.spec);return n?typeof n.root=="string"&&ke(n.elements)!==null:!1}case"action":{const a=ke(e.action);return a!==null&&typeof a.kind=="string"}case"error":return typeof e.code=="string"&&typeof e.message=="string";case"done":return!0;default:return!1}}function yo(e){const t=K(e.payload.text,e.payload.plain_text)??"",a=K(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 _o(e){return an((e.payload.actions??[]).map(t=>{const a=K(t.title)??"",n=Ne(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(xt),"chat")}function xo(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=K(o.style_label);if(!s)return null;const c=K(o.style_mood),l=K(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(u=>{const d=ke(u);return d?rn(ke(d.product_detail)??ke(d.product)??d):null}).filter(xt),h=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(u=>({label:K(u.label)??"",reason:K(u.reason)??"",skus:Array.isArray(u.skus)?u.skus.filter(d=>typeof d=="string"&&d.trim().length>0):[]})):[];return{style_label:s,style_mood:c??"",...l?{image_url:l}:{},...typeof o.status=="string"?{status:o.status}:{},product_list:g,recommendation_groups:h}}).filter(xt),a=e.payload.product_list??[],n=Xa(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?Jo(n,"chat"):nn(a,"chat");r.panelHint="panel";const i=r.spec.elements[r.spec.root];if(i){const o={};typeof e.payload.offset=="number"&&(o.offset=e.payload.offset),typeof e.payload.end_of_list=="boolean"&&(o.endOfList=e.payload.end_of_list),typeof e.payload.title=="string"&&(o.panelTitle=e.payload.title),typeof e.payload.source=="string"&&(o.source=e.payload.source),t.length>0&&(o.styleVariations=t),e.payload.replace_panel===!0&&(o.replacePanel=!0),Object.keys(o).length>0&&(i.props={...i.props,...o})}return r}function wo(e){const t=e.payload.productDetails;if(!t)return Xo("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 ko(e){const t=nn(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function Co(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=So(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 h=as(n?.special_considerations),u=n?.recommended_choice,d=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),h.length>0&&(p.specialCases=h),u&&(p.recommendedText=u),d&&(p.winnerHits=d),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 So(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 h=a.criteria_view??a.criteria_view_short??{},u=a.compared_field_names??Object.keys(e),d=[];for(const f of u){const p=e[f];if(!p||!Array.isArray(p))continue;const m=h[f]??f;d.push({label:m,values:p.map(b=>typeof b=="string"?b:String(b??""))})}return d}const o=e,s=t.map(h=>String(h.sku??"")).filter(h=>h.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:Eo(o)).filter(h=>h!=="name"&&h!=="name_short"&&!h.endsWith("_short")),g=[];for(const h of l){const u=s.map(f=>{const p=o[f];if(!p||typeof p!="object")return"";const m=p[`${h}_short`],b=p[h];return To(m??b)});if(u.every(f=>f.length===0))continue;const d=c[h]??h;g.push({label:d,values:u})}return g}function Eo(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 To(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Po(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function Ao(){return{type:"done"}}function Lo(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 Io(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function No(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function zo(e){const t=K(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:K(e.payload.to)}}}function Mo(e){return{type:"error",code:"BACKEND_ERROR",message:K(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function Bo(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function Ro(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),tn({type:"quick_qna",payload:r})}const a=ke(t.action);if(a){const r={action:a},i=typeof t.text=="string"?t.text:void 0,o=typeof t.image_url=="string"?t.image_url:void 0,s=typeof t.theme=="string"?t.theme:void 0;return i!==void 0&&(r.text=i),o!==void 0&&(r.image_url=o),s!==void 0&&(r.theme=s),en({type:"text_image",payload:r})}const n=typeof t.text=="string"?t.text:"";if(n){const r={text:n},i=typeof t.type=="string"?t.type:void 0,o=typeof t.theme=="string"?t.theme:void 0,s=ke(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),ia({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function ia(e){const t={text:K(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 Oo(e){return Qo(e.payload,"qna")}function en(e){const t=K(e.payload.text)??"",a=Ne(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),ia({type:"text",payload:n})}function tn(e){return an((e.payload.action_list??[]).map(t=>{const a=K(t.title)??"",n=Ne(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(xt),"qna")}function Do(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 Fo(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 Uo(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function $o(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=es(r);if(!i)continue;const o={product:i},s=Ne(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 Ho(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=K(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Ne(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 qo(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=K(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=K(r.detailed_user_message);s&&(o.text=s);const c=ke(ke(r.requestDetails)?.payload),l=c?.group_skus;r.group_skus&&Array.isArray(r.group_skus)?o.group_skus=r.group_skus:Array.isArray(l)&&(o.group_skus=l.filter(b=>typeof b=="string"));const g=K(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const h={type:"inputText",payload:o},u=Ne(r.requestDetails,i),d=u?.type==="findSimilar"&&typeof o.text=="string"?Ne(h,i):u??Ne(h,i);if(!d)continue;const f={shortName:i,action:d},p=K(r.detailed_user_message);p&&p!==i&&(f.detailedMessage=p);const m=fo(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 jo(e){const t=e.payload,a=Ne(t.requestDetails??t.request_details,K(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 Zo(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function Vo(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function Wo(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=Ne(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 Go(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function Ko(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 Yo(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function an(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 nn(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 Jo(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 Qo(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Fe(e),index:0}}}}}}function Xo(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function es(e){const t=K(e.sku),a=K(e.short_name),n={...ke(e.product_item)??e},r=K(e.discount_reason,e.discountReason);return r&&!K(n.discount_reason,n.discountReason)&&(n.discount_reason=r),rn(n,t,a)}function rn(e,t,a){const n=K(e.sku,t),r=K(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=K(e.brand);o&&(i.brand=o);const s=K(e.url);s&&(i.url=s);const c=ts(e.images);if(c.length>0)i.images=c;else{const p=K(e.image,e.image_url,e.imageUrl);p&&(i.images=[p])}const l=ct(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=ct(e.price);g!==void 0&&(i.price=g);const h=ct(e.rating);h!==void 0&&(i.rating=h);const u=ct(e.review_count)??ct(e.reviewCount);u!==void 0&&(i.review_count=u);const d=K(e.cart_code,e.cartCode);d&&(i.cart_code=d),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const f=K(e.discount_reason,e.discountReason);return f&&(i.discount_reason=f),Fe(i)}function Ne(e,t){const a=ke(e);if(!a)return null;const n=a.type;if(typeof n!="string"||n.length===0)return null;const r={title:t||n,type:n};return a.payload!==void 0&&(r.payload=a.payload),r}function ke(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function K(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function ts(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function as(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 ct(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 xt(e){return e!=null}var ns=new Set(["sku","name","brand","images","price","price_discounted","price_discount_rate","price_currency","discount_reason","url","rating","review_count","cart_code","in_stock","description","description_html","features","specifications","facet_tags","short_name","category_ids","category_names","variants","facet_hits","promotions"]);function 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=K(e.brand),o=K(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:K(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,h={};let u=!1;for(const d of Object.keys(g))ns.has(d)||(h[d]=g[d],u=!0);return u&&(c.extras=h),c}function rs(e){return e.results.map(Fe)}function is(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 os(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 ss={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function cs(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 wt(e,t){return`${cs(t?.middlewareUrl)}/chat${ss[e]}`}function ls(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"launchProductList":return e;case"launchHomepage":return e;case"addToCart":{const i={};return"error_message"in n||(i.error_message=""),{...e,payload:r(i)}}case"reviewSummary":{const i={};return t.pageContext?.sku&&!("sku"in n)&&(i.sku=t.pageContext.sku),Object.keys(i).length===0?e:{...e,payload:r(i)}}default:return e}}var ds={user_message:"inputText"};function gs(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=ds[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function ps(e,t,a){const n=wt("process_action",a),r=new AbortController;return(async()=>{try{const o=gs(e),s=a.attachment!==void 0;let c;if(s){const u=new FormData;u.append("request",o),a.attachment!==void 0&&u.append("attachment",a.attachment),c={method:"POST",body:u,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 u=l.statusText;try{const d=await l.json(),f=d.detail??d.message??d.error;typeof f=="string"&&(u=f)}catch{}t.onError(new Error(`HTTP ${l.status}: ${u}`));return}let g=!1;const h=()=>{g||(g=!0,t.onDone())};await yt(l,{onEvent:u=>{const d=_t(u);if(d)switch(d.type){case"text_chunk":t.onTextChunk(d.content,d.final===!0,{productMentions:d.productMentions,skuToProductItem:d.skuToProductItem,conversationMode:d.conversationMode,renderHint:d.renderHint,kvkk:d.kvkk});break;case"ui_spec":t.onUISpec(d.spec,d.widget,d.panelHint,d.clearPanel===!0);break;case"action":t.onAction(d);break;case"metadata":t.onMetadata(d);break;case"error":t.onError(new Error(d.message));break;case"done":h();break}},onError:t.onError,signal:r.signal}),h()}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;t.onError(o instanceof Error?o:new Error(String(o)))}})(),r}var hs="gengage-chat-scroll",on=null;function sn(e){on=e}function us(){on=null}var Qe={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:"Size Özel Seçimim",roleBestValue:"En Uygun Fiyatlı",roleBestAlternative:"En İyi Alternatif",viewDetails:"Detayları Gör",groundingReviewCta:"Yorumları Oku",groundingReviewSubtitle:"{count} yorum mevcut",variantsLabel:"Varyantlar",sortRelated:"Önerilen",sortPriceAsc:"Fiyat düşükten yükseğe",sortPriceDesc:"Fiyat yüksekten düşüğe",sortToolbarAriaLabel:"Ürünleri sırala",compareSelected:"Karşılaştır",compareMinHint:"En az 2 ürün seçin",compareMaxHint:"En fazla 5 ürün seçebilirsiniz",comparisonSelectLabel:"Karşılaştırmak için seç",comparisonSelectedLabel:"Seçildi",comparisonSelectCardHint:"Karşılaştırmaya eklemek veya çıkarmak için kartın herhangi bir yerine dokunun.",comparisonPreparingLabel:"Karşılaştırma tablosu hazırlanıyor…",panelTitleProductDetails:"Ürün Detayı",panelTitleSimilarProducts:"Benzer Ürünler",panelTitleComparisonResults:"Karşılaştırma Sonuçları",panelTitleCategories:"Kategoriler",panelTitleSearchResults:"Arama Sonuçları",inStockLabel:"Stokta",outOfStockLabel:"Tükendi",findSimilarLabel:"Benzerlerini Bul",galleryPrevAriaLabel:"Önceki görsel",galleryNextAriaLabel:"Sonraki görsel",beautyStylesPreparedTitle:"Sizin için {count} farklı stil hazırladım",watchStylesPreparedTitle:"Sizin için {count} farklı stil yönü hazırladım",consultingOtherCompatibleProductsLabel:"Diğer Uyumlu Ürünler",consultingFallbackGroupLabel:"Öneri",consultingFallbackStyleLabel:"Stil {index}",consultingStyleLoadingDescription:"Bu stil için ürünleri toplamaya devam ediyorum. Panel kısa süre içinde yenilenir.",consultingStyleUnavailableDescription:"Bu stil için şu anda yeterli ürün eşleşmesi çıkaramadım. Diğer stilleri inceleyebilirsiniz.",consultingStyleLoadingBadge:"Yükleniyor",consultingStyleUnavailableBadge:"Hazır değil",choicePrompterHeading:"Kararsız mı kaldın?",choicePrompterSuggestion:"Ürünleri seçip karşılaştırabilirsin",choicePrompterCta:"Seç ve Karşılaştır",viewMoreLabel:"Daha Fazla Göster",similarProductsLabel:"Benzer Ürünler",addToCartButton:"Sepete Ekle",addedToCartToast:"Sepete eklendi",shareButton:"Paylaş",productInfoTab:"Ürün Bilgileri",specificationsTab:"Teknik Özellikler",recommendedChoiceLabel:"Önerilen Seçim",highlightsLabel:"Öne Çıkan Özellikler",keyDifferencesLabel:"Temel Farklar",specialCasesLabel:"Özel Durumlar İçin",emptyReviewsMessage:"Yorum özeti bulunamadı.",closeAriaLabel:"Kapat",startChatLabel:"Sohbete Başla",voiceButton:"Sesli giriş",voiceListening:"Dinleniyor...",voiceNotSupported:"Sesli giriş bu tarayıcıda desteklenmiyor.",voicePermissionDenied:"Mikrofon erişimi reddedildi.",voiceError:"Sesli giriş hatası.",handoffHeading:"Destek temsilcisine aktarılıyor",productNotFoundMessage:"Bu ürün bilgisi şu an kullanılamıyor. Başka bir konuda yardımcı olabilirim.",stopGenerating:"Yanıtı Durdur",offlineMessage:"Çevrimdışısınız — bağlantı kurulduğunda mesajlar gönderilecek.",cartAriaLabel:"Sepetim",favoritesAriaLabel:"Favorilerim",showPanelAriaLabel:"Sonuçları Göster",addToFavoritesLabel:"Favorilere ekle",customerReviewsTitle:"Müşteri Yorumları",togglePanelAriaLabel:"Paneli aç/kapat",chatMessagesAriaLabel:"Sohbet mesajları",suggestionsAriaLabel:"Öneriler",moreSuggestionsAriaLabel:"Daha fazla öneri",rollbackAriaLabel:"Bu mesaja geri dön",backAriaLabel:"Geri",forwardAriaLabel:"İleri",closePanelAriaLabel:"Paneli kapat",dismissAriaLabel:"Kapat",cartAddErrorMessage:"Üzgünüm sepete ekleyemedim, bir sorunla karşılaştım.",favoriteToggleErrorMessage:"Favoriler güncellenemedi. Lütfen tekrar deneyin.",reviewFilterPositive:"Olumlu",reviewFilterNegative:"Olumsuz",decreaseLabel:"Azalt",increaseLabel:"Artır",reviewCustomersMentionSingular:"1 müşteri bahsediyor",reviewCustomersMentionPlural:"müşteri bahsediyor",reviewSubjectsHeading:"İncelemek için seçin",tryAgainButton:"Tekrar dene",askSomethingElseButton:"Başka bir şey sor",accountInactiveMessage:"Bu hesap şu an aktif değil. Lütfen daha sonra tekrar deneyin.",favoritesPageTitle:"Favorilerim",emptyFavoritesMessage:"Henüz favori ürün yok. Bir ürünü kalp ikonuna tıklayarak favorilere ekleyebilirsin.",showFormerMessagesButton:"↑ Önceki mesajları göster",aiAnalysisAnalyzingLabel:"Ürünler analiz ediliyor...",aiBrowseCategoriesTitle:"Kategorilere Göz At",photoAnalysisBadge:"Cilt Analizi",photoAnalysisStrengthsLabel:"Öne Çıkanlar",photoAnalysisFocusLabel:"Odak Noktaları",photoAnalysisCelebStyleLabel:"Celeb Vibe Eşleşmesi",beautyPhotoStepTitle:"Selfie ile kişiselleştir",beautyPhotoStepDescription:"İstersen net bir profil fotoğrafı yükle, sana özel önerilerde bulunayım.",beautyPhotoStepUpload:"Fotoğraf Yükle",beautyPhotoStepProcessing:"Fotoğraf işleniyor...",beautyPhotoStepSkip:"Geç",beautyPhotoStepSkipMessage:"Fotoğraf adımını geçiyorum"},ms={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",consultingOtherCompatibleProductsLabel:"Other compatible products",consultingFallbackGroupLabel:"Recommendation",consultingFallbackStyleLabel:"Style {index}",consultingStyleLoadingDescription:"I am still collecting products for this style. The panel will refresh shortly.",consultingStyleUnavailableDescription:"I could not find enough product matches for this style yet. You can review the other styles.",consultingStyleLoadingBadge:"Loading",consultingStyleUnavailableBadge:"Not ready",choicePrompterHeading:"Can't decide?",choicePrompterSuggestion:"Select products to compare them",choicePrompterCta:"Select & Compare",viewMoreLabel:"Show More",similarProductsLabel:"Similar Products",addToCartButton:"Add to Cart",addedToCartToast:"Added to cart",shareButton:"Share",productInfoTab:"Product Info",specificationsTab:"Specifications",recommendedChoiceLabel:"Recommended Choice",highlightsLabel:"Key Highlights",keyDifferencesLabel:"Key Differences",specialCasesLabel:"For Special Cases",emptyReviewsMessage:"No review summary found.",closeAriaLabel:"Close",startChatLabel:"Start Chat",voiceButton:"Voice input",voiceListening:"Listening...",voiceNotSupported:"Voice input is not supported in this browser.",voicePermissionDenied:"Microphone access denied.",voiceError:"Voice input error.",handoffHeading:"Transferring to a support agent",productNotFoundMessage:"Product information is currently unavailable. I can help with something else.",stopGenerating:"Stop generating",offlineMessage:"You're offline — messages will send when you reconnect.",cartAriaLabel:"My cart",favoritesAriaLabel:"My favorites",showPanelAriaLabel:"Show Results",addToFavoritesLabel:"Add to favorites",customerReviewsTitle:"Customer Reviews",togglePanelAriaLabel:"Toggle panel",chatMessagesAriaLabel:"Chat messages",suggestionsAriaLabel:"Suggestions",moreSuggestionsAriaLabel:"More suggestions",rollbackAriaLabel:"Rollback to this message",backAriaLabel:"Back",forwardAriaLabel:"Forward",closePanelAriaLabel:"Close panel",dismissAriaLabel:"Dismiss",cartAddErrorMessage:"Sorry, I couldn't add that to your cart. Something went wrong.",favoriteToggleErrorMessage:"We couldn't update favorites. Please try again.",reviewFilterPositive:"Positive",reviewFilterNegative:"Negative",decreaseLabel:"Decrease",increaseLabel:"Increase",reviewCustomersMentionSingular:"1 customer mentions",reviewCustomersMentionPlural:"customers mention",reviewSubjectsHeading:"Select to learn more",tryAgainButton:"Try again",askSomethingElseButton:"Ask something else",accountInactiveMessage:"This account is currently inactive. Please try again later.",favoritesPageTitle:"My Favorites",emptyFavoritesMessage:"No favorites yet. Heart a product to save it here.",showFormerMessagesButton:"↑ Show earlier messages",aiAnalysisAnalyzingLabel:"Analyzing products...",aiBrowseCategoriesTitle:"Browse categories",photoAnalysisBadge:"Skin Analysis",photoAnalysisStrengthsLabel:"Your strengths",photoAnalysisFocusLabel:"Focus points",photoAnalysisCelebStyleLabel:"Celeb style match",beautyPhotoStepTitle:"Personalize with a selfie",beautyPhotoStepDescription:"Upload a clear profile photo so I can give you personalized recommendations.",beautyPhotoStepUpload:"Upload Photo",beautyPhotoStepProcessing:"Processing photo...",beautyPhotoStepSkip:"Skip",beautyPhotoStepSkipMessage:"Skip the photo step"};function fs(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function bs(e){return fs(e)==="en"?ms:Qe}function vs(){return cn()!==null}function cn(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var ys=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=cn();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=_s(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 _s(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 xs(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=we(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 ws=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??""}},ks=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,xe(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 Cs(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 ln(e,t,a){const n=e.props??{},r=n.processing===!0,i={...Qe,...t.i18n??{}},o=document.createElement("div");o.className="gengage-chat-beauty-photo-step-card";const s=document.createElement("span");s.className="gengage-chat-beauty-photo-step-icon",s.setAttribute("aria-hidden","true"),s.textContent="✦";const c=document.createElement("div");c.className="gengage-chat-beauty-photo-step-content";const l=document.createElement("div");l.className="gengage-chat-beauty-photo-step-title",l.textContent=(typeof n.title=="string"?n.title:void 0)??i.beautyPhotoStepTitle;const g=document.createElement("p");g.className="gengage-chat-beauty-photo-step-desc",g.textContent=(typeof n.description=="string"?n.description:void 0)??i.beautyPhotoStepDescription;const h=document.createElement("div");h.className="gengage-chat-beauty-photo-step-actions";const u=document.createElement("button");u.type="button",u.className="gengage-chat-beauty-photo-step-upload gds-btn gds-btn-primary",u.textContent=r?i.beautyPhotoStepProcessing:(typeof n.upload_label=="string"?n.upload_label:void 0)??i.beautyPhotoStepUpload,u.disabled=r,a?.onUpload&&u.addEventListener("click",()=>a.onUpload());const d=document.createElement("button");return d.type="button",d.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",d.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??i.beautyPhotoStepSkip,a?.onSkip&&d.addEventListener("click",()=>a.onSkip()),h.appendChild(u),h.appendChild(d),c.appendChild(l),c.appendChild(g),c.appendChild(h),o.appendChild(s),o.appendChild(c),o}function Ss(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 Es(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=Ss(e,t);i.hidden=!1,i.innerHTML="";const o=ln({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 dn(e){const t=typeof e.summary=="string"?e.summary:"",a=Array.isArray(e.strengths)?e.strengths.filter(c=>typeof c=="string"):[],n=Array.isArray(e.focus_points)?e.focus_points.filter(c=>typeof c=="string"):[];if(!t&&a.length===0&&n.length===0)return null;const r={summary:t},i=typeof e.celeb_style=="string"?e.celeb_style:void 0,o=typeof e.celeb_style_reason=="string"?e.celeb_style_reason:void 0,s=typeof e.next_question=="string"?e.next_question:void 0;return a.length>0&&(r.strengths=a),n.length>0&&(r.focusPoints=n),i&&(r.celebStyle=i),o&&(r.celebStyleReason=o),s&&(r.nextQuestion=s),r}function gn(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 pn(e,t){const a=document.createElement("div");a.className="gengage-chat-photo-analysis-card";const n=document.createElement("div");n.className="gengage-chat-photo-analysis-badge",n.textContent=e.badge;const r=document.createElement("div");if(r.className="gengage-chat-photo-analysis-body",t.summary){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-summary",c.textContent=t.summary,r.appendChild(c)}const i=document.createElement("div");i.className="gengage-chat-photo-analysis-highlights";const o=gn(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=gn(e.focus,t.focusPoints??[],"gengage-chat-photo-analysis-section--focus");if(o&&i.appendChild(o),s&&i.appendChild(s),i.childElementCount>0&&r.appendChild(i),t.celebStyle){const c=document.createElement("section");c.className="gengage-chat-photo-analysis-section gengage-chat-photo-analysis-section--celeb";const l=document.createElement("h4");l.className="gengage-chat-photo-analysis-section-title",l.textContent=e.celebStyle;const g=document.createElement("p");if(g.className="gengage-chat-photo-analysis-celeb-name",g.textContent=t.celebStyle,c.appendChild(l),c.appendChild(g),t.celebStyleReason){const h=document.createElement("p");h.className="gengage-chat-photo-analysis-celeb-reason",h.textContent=t.celebStyleReason,c.appendChild(h)}r.appendChild(c)}if(t.nextQuestion){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-next",c.textContent=t.nextQuestion,r.appendChild(c)}return a.appendChild(n),a.appendChild(r),a}function Ts(e){const t={...Qe,...e?.i18n??{}};return{badge:t.photoAnalysisBadge,strengths:t.photoAnalysisStrengthsLabel,focus:t.photoAnalysisFocusLabel,celebStyle:t.photoAnalysisCelebStyleLabel}}function Ps(e,t){const a=dn(e.props??{})??{summary:""};return pn(Ts(t),a)}function As(e,t,a){e.innerHTML="",a&&e.appendChild(pn(t,a))}var Jm='<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>',hn={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>'},Ls=Qe,Is=1400,Ns=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function zs(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(Ns)?.[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 Ms(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?zs(await t):null}catch{}return null}var Bs=class{_renderPhotoAnalysisCard(e,t){As(e,{badge:this.i18n.photoAnalysisBadge,strengths:this.i18n.photoAnalysisStrengthsLabel,focus:this.i18n.photoAnalysisFocusLabel,celebStyle:this.i18n.photoAnalysisCelebStyleLabel},t)}constructor(e,t){this._sendStopHandler=null,this._panelVisible=!1,this._panelCollapsed=!1,this._dividerPreviewEnabled=!1,this._onPanelToggle=void 0,this._onHostShellSync=void 0,this._pendingAttachment=null,this._onAttachment=void 0,this._onRollback=void 0,this._onLinkClick=void 0,this._userScrolledUp=!1,this._scrollLockedUntil=0,this._favBadgeEl=null,this._thinkingSteps=[],this._firstBotMessageIds=new Set,this._voiceInput=null,this._micBtn=null,this._voiceEnabled=!1,this._voiceLang="tr-TR",this._ignoreNextDividerClick=!1,this._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={...Ls,...t.i18n},this.onSend=t.onSend,t.onPanelToggle!==void 0&&(this._onPanelToggle=t.onPanelToggle),t.onHostShellSync!==void 0&&(this._onHostShellSync=t.onHostShellSync),t.onAttachment!==void 0&&(this._onAttachment=t.onAttachment),t.onRollback!==void 0&&(this._onRollback=t.onRollback),t.onLinkClick!==void 0&&(this._onLinkClick=t.onLinkClick),t.voiceEnabled&&(this._voiceEnabled=!0),t.voiceLang!==void 0&&(this._voiceLang=t.voiceLang),this.root=document.createElement("div"),this.root.className="gengage-chat-drawer gds-panel",this.root.dataset.gengagePart="chat-drawer",this.root.setAttribute("role","dialog"),this.root.setAttribute("aria-label",this.i18n.headerTitle??"Chat"),this.root.setAttribute("aria-modal","true");const a="gengage-chat-dialog-desc",n=document.createElement("span");n.id=a,n.className="gengage-sr-only",n.textContent=this.i18n.headerTitle??"AI shopping assistant",this.root.appendChild(n),this.root.setAttribute("aria-describedby",a);let r=null;{const S=document.createElement("div");S.className="gengage-chat-drawer-handle",S.dataset.gengagePart="chat-drawer-handle",S.setAttribute("aria-hidden","true"),S.style.pointerEvents="none",r=S}const i=document.createElement("div");i.className="gengage-chat-header gds-shell-header",i.dataset.gengagePart="chat-header";const o=document.createElement("div");o.className="gengage-chat-header-left",o.dataset.gengagePart="chat-header-left";const s=t.headerAvatarUrl??t.launcherImageUrl,c=typeof t.headerAvatarUrl=="string"&&t.headerAvatarUrl.length>0&&t.headerAvatarUrl!==t.launcherImageUrl;if(s){const S=document.createElement("img");S.className="gengage-chat-header-avatar",c&&S.classList.add("gengage-chat-header-avatar--logo"),S.dataset.gengagePart="chat-header-avatar",S.src=s,S.alt=t.headerTitle??"Assistant",o.appendChild(S)}const l=document.createElement("div");l.className="gengage-chat-header-info",l.dataset.gengagePart="chat-header-info";const g=document.createElement("div");g.className="gengage-chat-header-title-row",g.dataset.gengagePart="chat-header-title-row";const h=document.createElement("span");if(h.className="gengage-chat-header-title",h.dataset.gengagePart="chat-header-title",h.textContent=t.headerTitle??this.i18n.headerTitle??"Product Expert",g.appendChild(h),t.headerBadge){const S=document.createElement("span");S.className="gengage-chat-header-badge gds-badge gds-badge-brand",S.dataset.gengagePart="chat-header-badge",S.textContent=t.headerBadge,g.appendChild(S)}l.appendChild(g);const u=document.createElement("a");u.className="gengage-chat-header-powered",u.dataset.gengagePart="chat-header-powered-by",u.href="https://gengage.ai/",u.target="_blank",u.rel="noopener noreferrer",u.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(u),o.appendChild(l),i.appendChild(o);const d=document.createElement("div");d.className="gengage-chat-header-right",d.dataset.gengagePart="chat-header-actions";{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-reopen-panel",S.setAttribute("aria-label",this.i18n.showPanelAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></svg>',S.addEventListener("click",()=>this._showMobilePanelFromBtn()),d.appendChild(S),this._reopenPanelBtn=S}{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-cart",S.setAttribute("aria-label",this.i18n.cartAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>',S.addEventListener("click",()=>t.onCartClick?.()),d.appendChild(S),this._cartBtn=S}if(t.onNewChat){const S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-new-chat",S.type="button",S.setAttribute("aria-label",this.i18n.newChatButton),S.title=this.i18n.newChatButton,S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>',S.addEventListener("click",()=>t.onNewChat?.()),d.appendChild(S)}const 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 S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-favorites",S.type="button",S.setAttribute("aria-label",this.i18n.favoritesAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';const R=document.createElement("span");R.className="gengage-chat-header-fav-badge",R.dataset.gengagePart="chat-header-favorites-badge",R.setAttribute("aria-hidden","true"),R.style.display="none",S.appendChild(R),this._favBadgeEl=R,S.addEventListener("click",()=>{t.onFavoritesClick?.()}),d.appendChild(S)}d.appendChild(f),r&&i.insertBefore(r,i.firstChild),i.appendChild(d);{let R=0,V=0,oe=!1;const ye=_e=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||_e.target.closest('button, a, input, [role="button"]'))return;const Ae=_e.changedTouches?.[0];Ae&&(R=Ae.clientY,V=0,oe=!0,this.root.style.transition="none")},Oe=_e=>{if(!oe)return;const Ae=_e.changedTouches?.[0];if(!Ae)return;V=Ae.clientY-R;const Km=(t.getMobileState?.()??"full")==="full"?Math.max(0,V):V;_e.preventDefault(),this.root.style.transform=`translateY(${Km}px)`},Ke=()=>{if(!oe)return;oe=!1;const _e=t.getMobileState?.()??"full";let Ae;V>72?Ae=_e==="full"?"half":"close":V<-72&&_e==="half"?Ae="full":Ae=_e,this.root.style.transition="",Ae==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Ae)),V=0},Gt=()=>{oe&&(oe=!1,V=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",ye,{passive:!0}),i.addEventListener("touchmove",Oe,{passive:!1}),i.addEventListener("touchend",Ke,{passive:!0}),i.addEventListener("touchcancel",Gt,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",ye),i.removeEventListener("touchmove",Oe),i.removeEventListener("touchend",Ke),i.removeEventListener("touchcancel",Gt)})}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 ws({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 w=null,v=null;const x=24,k=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const R=S.changedTouches?.[0];R&&(w=R.clientX,v=R.clientY)},A=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||w===null||v===null)return;const R=S.changedTouches?.[0];if(!R)return;const V=R.clientX-w,oe=R.clientY-v;if(w=null,v=null,Math.abs(oe)<x||Math.abs(oe)<Math.abs(V))return;const ye=oe<0;ye!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(ye),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 L=document.createElement("div");L.className="gengage-chat-conversation",L.dataset.gengagePart="chat-conversation",this._conversationEl=L,L.appendChild(i);const M=document.createElement("div");M.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",M.dataset.gengagePart="chat-offline-bar",M.setAttribute("role","status"),M.setAttribute("aria-live","polite"),M.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&M.classList.add("gengage-chat-offline-bar--visible"),L.appendChild(M);const W=()=>M.classList.add("gengage-chat-offline-bar--visible"),$=()=>M.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",W),window.addEventListener("online",$),this._cleanups.push(()=>{window.removeEventListener("offline",W),window.removeEventListener("online",$)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",L.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=hs,this.messagesEl.className="gengage-chat-messages",this.messagesEl.dataset.gengagePart="chat-messages",this.messagesEl.setAttribute("role","log"),this.messagesEl.setAttribute("aria-live","polite"),this.messagesEl.setAttribute("aria-atomic","false"),this.messagesEl.setAttribute("aria-label",this.i18n.chatMessagesAriaLabel),sn(this.messagesEl);const D=document.createElement("button");D.type="button",D.className="gengage-chat-former-messages-btn gds-chip",D.dataset.gengagePart="chat-former-messages-button",D.textContent=this.i18n.showFormerMessagesButton,D.setAttribute("aria-label",this.i18n.showFormerMessagesButton),D.style.display="none",D.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(D),this._formerMessagesBtn=D;const I=()=>{this._userInteractionUntil=Date.now()+2e3};let z=!1;const _=()=>this._options.presentation,y=()=>{z||(z=!0,requestAnimationFrame(()=>{z=!1;const{scrollTop:S,scrollHeight:R,clientHeight:V}=this.messagesEl,oe=R-S-V;this._userScrolledUp=oe>10;const ye=this._presentationPinned?oe<96:oe<32,Oe=Date.now(),Ke=Oe<this._programmaticScrollUntil,Gt=!ye&&Oe<this._userInteractionUntil,_e=Ke?!1:Gt;ye!==this._presentationPinned&&(this._presentationPinned=ye,_()?.onPinnedToBottomChange?.(ye)),_e!==this._presentationUserInteracting&&(this._presentationUserInteracting=_e,_()?.onUserInteractingChange?.(_e))}))};this.messagesEl.addEventListener("scroll",y,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",y)});const T=S=>{I(),S.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",T,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",T));const C=S=>{I(),this._touchStartY=S.touches[0]?.clientY??null},B=S=>{I();const R=S.touches[0]?.clientY,V=this._touchStartY;typeof R=="number"&&typeof V=="number"&&R-V>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",C,{passive:!0}),this.messagesEl.addEventListener("touchmove",B,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",C),this.messagesEl.removeEventListener("touchmove",B)}),L.appendChild(this.messagesEl),this._thumbnailsColumn=new ks({onThumbnailClick:S=>t.onThumbnailClick?.(S)}),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelFloatingEl=document.createElement("div"),this._panelFloatingEl.className="gengage-chat-panel-float",this._panelFloatingEl.dataset.gengagePart="chat-panel-floating-layer",this._panelEl.appendChild(this._panelFloatingEl),this._resetPanelAiZoneElement(),this._pillsEl=document.createElement("div"),this._pillsEl.className="gengage-chat-pills",this._pillsEl.dataset.gengagePart="chat-suggestion-pills",this._pillsEl.setAttribute("role","toolbar"),this._pillsEl.setAttribute("aria-label",this.i18n.suggestionsAriaLabel),this._pillsEl.style.display="none";const N=document.createElement("div");N.className="gengage-chat-pills-scroll",N.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(N);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",()=>{N.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(P);let F=!1;const H=()=>{F||(F=!0,requestAnimationFrame(()=>{F=!1;const S=N.scrollLeft+N.clientWidth>=N.scrollWidth-4;P.style.display=S?"none":""}))};N.addEventListener("scroll",H,{passive:!0}),this._cleanups.push(()=>{N.removeEventListener("scroll",H)}),L.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",L.appendChild(this._inputChipsEl);const U=document.createElement("div");U.className="gengage-chat-input-area",U.dataset.gengagePart="chat-input-area",this.inputEl=document.createElement("textarea"),this.inputEl.className="gengage-chat-input",this.inputEl.dataset.gengagePart="chat-input",this.inputEl.rows=1,this.inputEl.placeholder=this.i18n.inputPlaceholder,this.inputEl.addEventListener("input",()=>{this._resizeRafId!==null&&cancelAnimationFrame(this._resizeRafId),this._resizeRafId=requestAnimationFrame(()=>{this._resizeRafId=null,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`}),this._updateSendEnabled()}),this.inputEl.addEventListener("keydown",S=>{S.key==="Enter"&&!S.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!S.shiftKey)&&(S.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",S=>{const R=S.clipboardData;if(!R)return;let V=null;const oe=R.files?.[0];if(oe&&oe.type.startsWith("image/"))V=oe;else if(R.items?.length)for(let ye=0;ye<R.items.length;ye++){const Oe=R.items[ye];if(Oe?.kind==="file"&&Oe.type.startsWith("image/")){const Ke=Oe.getAsFile();if(Ke){V=Ke;break}}}V&&(S.preventDefault(),this._routeAttachmentFile(V))}),this._fileInput=document.createElement("input"),this._fileInput.type="file",this._fileInput.accept="image/jpeg,image/png,image/webp",this._fileInput.style.display="none",this._fileInput.addEventListener("change",()=>{const S=this._fileInput.files?.[0];S&&this._routeAttachmentFile(S),this._fileInput.value=""});const q=document.createElement("div");q.className="gengage-chat-attach-wrap",q.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=q;const Y=document.createElement("button");this._attachBtn=Y,Y.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",Y.dataset.gengagePart="chat-attach-button",Y.type="button",Y.setAttribute("aria-label",this.i18n.attachImageButton),Y.setAttribute("aria-haspopup","menu"),Y.setAttribute("aria-expanded","false"),Y.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>',Y.addEventListener("click",S=>{S.stopPropagation(),this._toggleAttachMenu()});const ae=document.createElement("div");this._attachMenuEl=ae,ae.className="gengage-chat-attach-menu gds-menu",ae.dataset.gengagePart="chat-attach-menu",ae.setAttribute("role","menu"),ae.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",S=>{S.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 ve=document.createElement("button");ve.type="button",ve.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",ve.dataset.gengagePart="chat-attach-menu-paste",ve.setAttribute("role","menuitem"),ve.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>`,ve.addEventListener("click",S=>{S.stopPropagation();const R=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(R)}),ae.appendChild(j),ae.appendChild(be),ae.appendChild(ve),q.appendChild(Y),q.appendChild(ae),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 Z=document.createElement("img");Z.className="gengage-chat-attachment-preview-thumb",Z.dataset.gengagePart="chat-attachment-preview-thumb",Z.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const pe=document.createElement("button");pe.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",pe.dataset.gengagePart="chat-attachment-preview-remove",pe.type="button",pe.setAttribute("aria-label",this.i18n.removeAttachmentButton),pe.textContent="×",pe.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(Z),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(pe),this.sendBtn=document.createElement("button"),this.sendBtn.className="gengage-chat-send gds-btn gds-btn-primary",this.sendBtn.dataset.gengagePart="chat-send",this.sendBtn.type="button",this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-label",this.i18n.sendButton),this.sendBtn.dataset.tooltip=this.i18n.sendButton,this._renderSendButtonIcon("send"),this.sendBtn.addEventListener("click",()=>{if(this._sendStopHandler){const S=this._sendStopHandler;this.hideStopButton(),S();return}this._submit()}),U.addEventListener("dragover",S=>{S.preventDefault(),U.classList.add("gengage-chat-input-area--dragover")}),U.addEventListener("dragleave",()=>{U.classList.remove("gengage-chat-input-area--dragover")}),U.addEventListener("drop",S=>{S.preventDefault(),U.classList.remove("gengage-chat-input-area--dragover");const R=S.dataTransfer?.files[0];R&&this._routeAttachmentFile(R)});const ee=document.createElement("div");ee.className="gengage-chat-input-pill gds-input-shell",ee.dataset.gengagePart="chat-input-shell",ee.appendChild(q),ee.appendChild(this.inputEl),this._voiceEnabled&&vs()&&(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()),ee.appendChild(this._micBtn),this._voiceInput=new ys({onInterim:S=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=S,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:S=>{this.inputEl.value=S},onAutoSubmit:S=>{this.inputEl.value=S,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:S=>{S==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(S,R)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),ee.appendChild(this.sendBtn),U.appendChild(this._previewStrip),U.appendChild(this._fileInput),U.appendChild(ee),L.appendChild(U),p.appendChild(L),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(L),this._setupHorizontalSwipe(this._panelEl);const J=document.createElement("div");J.className="gengage-chat-footer",J.dataset.gengagePart="chat-footer",J.textContent=this.i18n.poweredBy,this.root.appendChild(J);const X=S=>{S.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",X),this._cleanups.push(()=>this.root.removeEventListener("keydown",X)),e.appendChild(this.root)}addMessage(e){const t=document.createElement("div");if(t.className=`gengage-chat-bubble gds-message ${e.role==="assistant"?"gds-message-assistant":"gds-message-user"} gengage-chat-bubble--${e.role}`,t.dataset.gengagePart=e.role==="assistant"?"chat-message-assistant":"chat-message-user",t.setAttribute("role","listitem"),t.dataset.messageId=e.id,e.threadId&&(t.dataset.threadId=e.threadId),this._firstBotMessageIds.has(e.id)&&t.classList.add("gengage-chat-bubble--first"),e.attachment){const a=document.createElement("img");a.className="gengage-chat-attachment-thumb";const n=URL.createObjectURL(e.attachment);a.src=n,a.alt=e.attachment.name,a.addEventListener("load",()=>URL.revokeObjectURL(n),{once:!0}),a.addEventListener("error",()=>URL.revokeObjectURL(n),{once:!0}),t.insertBefore(a,t.firstChild)}if(e.content){const a=document.createElement("div");if(a.className="gengage-chat-bubble-text",a.dataset.gengagePart="chat-message-text",e.role==="assistant"){if(e.renderHint==="photo_analysis"?(t.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(a,e.photoAnalysis)):a.innerHTML=we(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="${he(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=hn[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&&xe(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=xs({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=Es(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 Ms(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=!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=!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 L=0;L<2;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",L===1&&M.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(M)}const h=document.createElement("div");h.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-price",g.appendChild(h),c.appendChild(l),c.appendChild(g),o.appendChild(c);const u=document.createElement("div");u.className="gengage-chat-comparison-highlights";const d=document.createElement("div");d.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",u.appendChild(d);const f=document.createElement("ul");f.className="gengage-chat-comparison-skeleton-hl-list";for(let L=0;L<3;L++){const M=document.createElement("li"),W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",L===1&&W.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),L===2&&W.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),M.appendChild(W),f.appendChild(M)}u.appendChild(f),o.appendChild(u),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 L=0;L<4;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",b.appendChild(M)}p.appendChild(b),i.appendChild(p);const w=document.createElement("div");w.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",w.appendChild(v),i.appendChild(w);const x=document.createElement("div");x.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 L=0;L<3;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-table-col";const W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const $=document.createElement("div");$.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const D=document.createElement("div");D.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",M.appendChild(W),M.appendChild($),M.appendChild(D),k.appendChild(M)}x.appendChild(k);for(let L=0;L<3;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-table-row";const W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",M.appendChild(W);for(let $=0;$<3;$++){const D=document.createElement("div");D.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",M.appendChild(D)}x.appendChild(M)}i.appendChild(x),t.appendChild(i);break}default:t.appendChild(n);for(let i=0;i<3;i++){const o=document.createElement("div");o.className="gengage-chat-panel-skeleton-block",t.appendChild(o)}break}this._panelEl.appendChild(t),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel"),this._syncDividerPreview(),this._emitHostShellSync()}updatePanelTopBar(e,t,a){const n=this._options.getMobileViewport?.()??!1;this._panelTopBar.update(n?!0:e,t,a);const r=this.getPanelContentElement();r&&this._syncPanelTopBarTitleFromContent(r)}getPanelTopBarTitle(){return this._panelTopBar.getTitle()}updateFavoritesBadge(e){this._favBadgeEl&&(e>0?(this._favBadgeEl.textContent=e>99?"99+":String(e),this._favBadgeEl.style.display=""):this._favBadgeEl.style.display="none")}clearPanel(){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelEl.innerHTML="",this._resetPanelAiZoneElement(),this._panelEl.appendChild(this._panelTopBar.getElement()),this._panelEl.appendChild(this._panelAiZoneEl),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelTopBar.setActions(null),this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible","gengage-chat-panel--collapsed"),this.root.classList.remove("gengage-chat-drawer--with-panel"),this._dividerEl.classList.add("gengage-chat-panel-divider--hidden"),this._dividerPreviewEnabled=!1,this._syncDividerPreview(),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this.setComparisonDockContent(null),this._emitHostShellSync()}setComparisonDockContent(e){this._comparisonDockSlotEl.replaceChildren(),e&&this._comparisonDockSlotEl.appendChild(e)}hideMobilePanel(){this._panelVisible&&(this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="flex"),this._emitHostShellSync())}_showMobilePanelFromBtn(){this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync())}expandPanel(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._syncDividerPreview(),this._emitHostShellSync()}setForceExpanded(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._syncDividerPreview(),this._emitHostShellSync()}_smoothScrollPanelListToTop(){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)},Is))}_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="${he(e)}"]`);if(!r)return;let i=r.querySelector(".gengage-chat-bubble-text");i||(i=document.createElement("div"),i.className="gengage-chat-bubble-text",r.appendChild(i)),a==="photo_analysis"?(r.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(i,n)):(r.classList.remove("gengage-chat-bubble--photo-analysis"),i.innerHTML=we(t)),this._scrollToBottom(!1)}markFirstBotMessage(e){this._firstBotMessageIds.add(e);const t=this.messagesEl.querySelector(`[data-message-id="${he(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="${he(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="${he(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=hn[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)||!xe(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(){sn(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}},un=["beauty_consulting","watch_expert","booking"],Rs=["shopping",...un];function Os(e){return typeof e=="string"&&Rs.includes(e)?e:null}function oa(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function Ds(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function Fs(e){const t=oa(e);if(!t)return null;const a=Ds(t.assistant_mode,t.assistantMode);return!a||!un.includes(a)?null:a}var Us=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){Ie("mode","redirect metadata received",e);const t=Fs(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Ie("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=Os(t);a?this._mode=a:Ie("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=oa(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 $s(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function Hs(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=dn(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):(Ie("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Cs(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 qs(e){return e.renderHint==="photo_analysis"}function js(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function Zs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var Vs=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
48
|
+
`);r=d.pop()??"";for(const f of d)if(Ja(f,t))return}if(r.trim()&&Ja(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 Qa=3,uo=(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():""},ra=(e,t)=>e?e.split(/[•,;:/()]|(?:\sve\s)|(?:\sand\s)|(?:\sile\s)|(?:\sfor\s)|(?:\swith\s)/i).map(a=>uo(a,t)).filter(Boolean):[];function mo(e){const t=(e.display_keywords??[]).flatMap(r=>ra(r,{stripLeadingStopWords:!0})),a=t.filter((r,i)=>t.indexOf(r)===i);if(a.length>0)return a.slice(0,Qa);const n=[...ra(e.chosen_attribute,{stripLeadingStopWords:!0}),...ra(e.short_name)];return n.filter((r,i)=>n.indexOf(r)===i).slice(0,Qa)}function fo(e){return mo(e).join(" • ")}var bo=["beauty_consulting","watch_expert"];function Xa(e){return typeof e=="string"&&bo.includes(e)}function _t(e){if(typeof e.type!="string")return null;if(vo(e))return e;const t=e;switch(t.type){case"outputText":return yo(t);case"suggestedActions":return _o(t);case"productList":return xo(t);case"productDetails":return wo(t);case"productDetailsSimilars":return ko(t);case"comparisonTable":return Co(t);case"context":return Po(t);case"chatStreamEnd":return Ao();case"loading":return Lo(t);case"panelLoading":return Io(t);case"similarLoading":return No(t);case"redirect":return zo(t);case"error":return Mo(t);case"dummy":return Bo(t);case"launcherAction":return Ro(t);case"text":return ia(t);case"productItem":return Oo(t);case"text_image":return en(t);case"quick_qna":return tn(t);case"reviewHighlights":return Do(t);case"aiProductSuggestions":return $o(t);case"aiProductGroupings":return Ho(t);case"aiSuggestedSearches":return qo(t);case"prosAndCons":return Fo(t);case"getGroundingReview":return jo(t);case"voice":return Vo(t);case"visitorDataResponse":return Uo(t);case"productListPreview":return Zo();case"groupList":return Wo(t);case"formGetInfo":case"formTestDrive":case"formServiceRequest":case"launchFormPage":return Go(t);case"launcherContent":return Yo(t);case"handoff":return Ko(t);case"uiSpec":return os(t);default:return null}}function vo(e){const t=e.type;if(typeof t!="string")return!1;switch(t){case"metadata":return typeof e.sessionId=="string"&&typeof e.model=="string";case"text_chunk":return typeof e.content=="string";case"ui_spec":{const a=e.widget;if(a!=="chat"&&a!=="qna"&&a!=="simrel")return!1;const n=ke(e.spec);return n?typeof n.root=="string"&&ke(n.elements)!==null:!1}case"action":{const a=ke(e.action);return a!==null&&typeof a.kind=="string"}case"error":return typeof e.code=="string"&&typeof e.message=="string";case"done":return!0;default:return!1}}function yo(e){const t=K(e.payload.text,e.payload.plain_text)??"",a=K(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 _o(e){return an((e.payload.actions??[]).map(t=>{const a=K(t.title)??"",n=Ne(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(xt),"chat")}function xo(e){const t=(Array.isArray(e.payload.style_variations)?e.payload.style_variations:[]).map(o=>{const s=K(o.style_label);if(!s)return null;const c=K(o.style_mood),l=K(o.image_url??void 0),g=(Array.isArray(o.product_list)?o.product_list:[]).map(u=>{const d=ke(u);return d?rn(ke(d.product_detail)??ke(d.product)??d):null}).filter(xt),h=Array.isArray(o.recommendation_groups)?o.recommendation_groups.map(u=>({label:K(u.label)??"",reason:K(u.reason)??"",skus:Array.isArray(u.skus)?u.skus.filter(d=>typeof d=="string"&&d.trim().length>0):[]})):[];return{style_label:s,style_mood:c??"",...l?{image_url:l}:{},...typeof o.status=="string"?{status:o.status}:{},product_list:g,recommendation_groups:h}}).filter(xt),a=e.payload.product_list??[],n=Xa(e.payload.source)&&t.length>0?t[0].product_list:null,r=n?Jo(n,"chat"):nn(a,"chat");r.panelHint="panel";const i=r.spec.elements[r.spec.root];if(i){const o={};typeof e.payload.offset=="number"&&(o.offset=e.payload.offset),typeof e.payload.end_of_list=="boolean"&&(o.endOfList=e.payload.end_of_list),typeof e.payload.title=="string"&&(o.panelTitle=e.payload.title),typeof e.payload.source=="string"&&(o.source=e.payload.source),t.length>0&&(o.styleVariations=t),e.payload.replace_panel===!0&&(o.replacePanel=!0),Object.keys(o).length>0&&(i.props={...i.props,...o})}return r}function wo(e){const t=e.payload.productDetails;if(!t)return Xo("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 ko(e){const t=nn(e.payload.similarProducts??[],"chat"),a=t.spec.elements[t.spec.root];return a&&(a.props={...a.props,similarsAppend:!0}),{...t,panelHint:"panel"}}function Co(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=So(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 h=as(n?.special_considerations),u=n?.recommended_choice,d=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),h.length>0&&(p.specialCases=h),u&&(p.recommendedText=u),d&&(p.winnerHits=d),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 So(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 h=a.criteria_view??a.criteria_view_short??{},u=a.compared_field_names??Object.keys(e),d=[];for(const f of u){const p=e[f];if(!p||!Array.isArray(p))continue;const m=h[f]??f;d.push({label:m,values:p.map(b=>typeof b=="string"?b:String(b??""))})}return d}const o=e,s=t.map(h=>String(h.sku??"")).filter(h=>h.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:Eo(o)).filter(h=>h!=="name"&&h!=="name_short"&&!h.endsWith("_short")),g=[];for(const h of l){const u=s.map(f=>{const p=o[f];if(!p||typeof p!="object")return"";const m=p[`${h}_short`],b=p[h];return To(m??b)});if(u.every(f=>f.length===0))continue;const d=c[h]??h;g.push({label:d,values:u})}return g}function Eo(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 To(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):""}function Po(e){return{type:"metadata",sessionId:"",model:"",meta:{panel:e.payload.panel,messages:e.payload.messages,message_id:e.payload.message_id}}}function Ao(){return{type:"done"}}function Lo(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 Io(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,panelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function No(e){return{type:"metadata",sessionId:"",model:"",meta:{loading:!0,similarPanelLoading:!0,panelPendingType:e.payload?.pending_type,loadingText:e.payload?.text}}}function zo(e){const t=K(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:K(e.payload.to)}}}function Mo(e){return{type:"error",code:"BACKEND_ERROR",message:K(e.payload?.text,e.payload?.message,e.payload?.error)??"Backend returned an error"}}function Bo(e){return{type:"metadata",sessionId:"",model:"",meta:{noop:!0}}}function Ro(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),tn({type:"quick_qna",payload:r})}const a=ke(t.action);if(a){const r={action:a},i=typeof t.text=="string"?t.text:void 0,o=typeof t.image_url=="string"?t.image_url:void 0,s=typeof t.theme=="string"?t.theme:void 0;return i!==void 0&&(r.text=i),o!==void 0&&(r.image_url=o),s!==void 0&&(r.theme=s),en({type:"text_image",payload:r})}const n=typeof t.text=="string"?t.text:"";if(n){const r={text:n},i=typeof t.type=="string"?t.type:void 0,o=typeof t.theme=="string"?t.theme:void 0,s=ke(t.payload)??void 0;return i!==void 0&&(r.type=i),s!==void 0&&(r.payload=s),o!==void 0&&(r.theme=o),ia({type:"text",payload:r})}return{type:"metadata",sessionId:"",model:"",meta:{launcherAction:t}}}function ia(e){const t={text:K(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 Oo(e){return Qo(e.payload,"qna")}function en(e){const t=K(e.payload.text)??"",a=Ne(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),ia({type:"text",payload:n})}function tn(e){return an((e.payload.action_list??[]).map(t=>{const a=K(t.title)??"",n=Ne(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(xt),"qna")}function Do(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 Fo(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 Uo(e){return{type:"metadata",sessionId:"",model:"",meta:{visitorDataResponse:e.payload}}}function $o(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=es(r);if(!i)continue;const o={product:i},s=Ne(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 Ho(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=K(r.name)??"",o=r.sku&&r.sku.length>0?{type:"findSimilar",payload:{sku:r.sku}}:void 0,s=Ne(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 qo(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=K(r.short_name,r.chosen_attribute,r.detailed_user_message)??`Search ${n+1}`,o={},s=K(r.detailed_user_message);s&&(o.text=s);const c=ke(ke(r.requestDetails)?.payload),l=c?.group_skus;r.group_skus&&Array.isArray(r.group_skus)?o.group_skus=r.group_skus:Array.isArray(l)&&(o.group_skus=l.filter(b=>typeof b=="string"));const g=K(r.sku,r.representative_product_sku,c?.sku);g&&(o.sku=g),o.is_suggested_text=1;const h={type:"inputText",payload:o},u=Ne(r.requestDetails,i),d=u?.type==="findSimilar"&&typeof o.text=="string"?Ne(h,i):u??Ne(h,i);if(!d)continue;const f={shortName:i,action:d},p=K(r.detailed_user_message);p&&p!==i&&(f.detailedMessage=p);const m=fo(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 jo(e){const t=e.payload,a=Ne(t.requestDetails??t.request_details,K(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 Zo(){return{type:"metadata",sessionId:"",model:"",meta:{analyzeAnimation:!0}}}function Vo(e){return{type:"metadata",sessionId:"",model:"",meta:{voice:e.payload}}}function Wo(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=Ne(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 Go(e){return{type:"metadata",sessionId:"",model:"",meta:{formType:e.type,formPayload:e.payload??{}}}}function Ko(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 Yo(e){return{type:"metadata",sessionId:"",model:"",meta:{launcherContent:e.payload??{}}}}function an(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 nn(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 Jo(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 Qo(e,t){return{type:"ui_spec",widget:t,spec:{root:"root",elements:{root:{type:"ProductCard",props:{product:Fe(e),index:0}}}}}}function Xo(e){return{type:"ui_spec",widget:e,spec:{root:"root",elements:{root:{type:"ActionButtons",props:{buttons:[]},children:[]}}}}}function es(e){const t=K(e.sku),a=K(e.short_name),n={...ke(e.product_item)??e},r=K(e.discount_reason,e.discountReason);return r&&!K(n.discount_reason,n.discountReason)&&(n.discount_reason=r),rn(n,t,a)}function rn(e,t,a){const n=K(e.sku,t),r=K(e.name,a);if(!n||!r)return null;const i={sku:n,name:r},o=K(e.brand);o&&(i.brand=o);const s=K(e.url);s&&(i.url=s);const c=ts(e.images);if(c.length>0)i.images=c;else{const p=K(e.image,e.image_url,e.imageUrl);p&&(i.images=[p])}const l=ct(e.price_discounted);l!==void 0&&(i.price_discounted=l);const g=ct(e.price);g!==void 0&&(i.price=g);const h=ct(e.rating);h!==void 0&&(i.rating=h);const u=ct(e.review_count)??ct(e.reviewCount);u!==void 0&&(i.review_count=u);const d=K(e.cart_code,e.cartCode);d&&(i.cart_code=d),typeof e.in_stock=="boolean"&&(i.in_stock=e.in_stock),typeof e.inStock=="boolean"&&(i.in_stock=e.inStock);const f=K(e.discount_reason,e.discountReason);return f&&(i.discount_reason=f),Fe(i)}function Ne(e,t){const a=ke(e);if(!a)return null;const n=a.type;if(typeof n!="string"||n.length===0)return null;const r={title:t||n,type:n};return a.payload!==void 0&&(r.payload=a.payload),r}function ke(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function K(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function ts(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function as(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 ct(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 xt(e){return e!=null}var ns=new Set(["sku","name","brand","images","price","price_discounted","price_discount_rate","price_currency","discount_reason","url","rating","review_count","cart_code","in_stock","description","description_html","features","specifications","facet_tags","short_name","category_ids","category_names","variants","facet_hits","promotions"]);function 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=K(e.brand),o=K(e.name)??e.sku,s=i&&!o.toLowerCase().startsWith(i.toLowerCase())?`${i} ${o}`:o,c={sku:e.sku,name:s,url:K(e.url)??""},l=e.images?.[0];l&&(c.imageUrl=l),e.images&&e.images.length>1&&(c.images=e.images),a!=null&&a>0&&(c.price=String(a)),n!=null&&n>0&&(c.originalPrice=String(n)),r!==void 0&&(c.discountPercent=r),i!==void 0&&(c.brand=i),e.rating!==void 0&&(c.rating=e.rating),e.review_count!==void 0&&(c.reviewCount=e.review_count),e.cart_code!==void 0&&(c.cartCode=e.cart_code),e.in_stock!==void 0&&(c.inStock=e.in_stock),e.variants&&e.variants.length>0&&(c.variants=e.variants),e.discount_reason!==void 0&&(c.discountReason=e.discount_reason),e.promotions&&e.promotions.length>0&&(c.promotions=e.promotions),e.description!==void 0&&(c.description=e.description),e.description_html!==void 0&&(c.descriptionHtml=e.description_html),e.features&&e.features.length>0&&(c.features=e.features),e.specifications!==void 0&&(c.specifications=e.specifications),e.facet_hits&&(c.facetHits=e.facet_hits),e.short_name!==void 0&&(c.shortName=e.short_name);const g=e,h={};let u=!1;for(const d of Object.keys(g))ns.has(d)||(h[d]=g[d],u=!0);return u&&(c.extras=h),c}function rs(e){return e.results.map(Fe)}function is(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 os(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 ss={process_action:"/process_action",launcher_action:"/launcher_action",similar_products:"/similar_products",product_groupings:"/product_groupings"};function cs(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 wt(e,t){return`${cs(t?.middlewareUrl)}/chat${ss[e]}`}function ls(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"launchProductList":return e;case"launchHomepage":return e;case"addToCart":{const i={};return"error_message"in n||(i.error_message=""),{...e,payload:r(i)}}case"reviewSummary":{const i={};return t.pageContext?.sku&&!("sku"in n)&&(i.sku=t.pageContext.sku),Object.keys(i).length===0?e:{...e,payload:r(i)}}default:return e}}var ds={user_message:"inputText"};function gs(e){const{action:t,type:a,payload:n,...r}=e,i=a??t?.type??"inputText",o=n??t?.payload,s=ds[i]??i,c={...r,type:s};return o!==void 0&&(c.payload=typeof o=="string"?{text:o}:o),JSON.stringify(c)}function ps(e,t,a){const n=wt("process_action",a),r=new AbortController;return(async()=>{try{const o=gs(e),s=a.attachment!==void 0;let c;if(s){const u=new FormData;u.append("request",o),a.attachment!==void 0&&u.append("attachment",a.attachment),c={method:"POST",body:u,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 u=l.statusText;try{const d=await l.json(),f=d.detail??d.message??d.error;typeof f=="string"&&(u=f)}catch{}t.onError(new Error(`HTTP ${l.status}: ${u}`));return}let g=!1;const h=()=>{g||(g=!0,t.onDone())};await yt(l,{onEvent:u=>{const d=_t(u);if(d)switch(d.type){case"text_chunk":t.onTextChunk(d.content,d.final===!0,{productMentions:d.productMentions,skuToProductItem:d.skuToProductItem,conversationMode:d.conversationMode,renderHint:d.renderHint,kvkk:d.kvkk});break;case"ui_spec":t.onUISpec(d.spec,d.widget,d.panelHint,d.clearPanel===!0);break;case"action":t.onAction(d);break;case"metadata":t.onMetadata(d);break;case"error":t.onError(new Error(d.message));break;case"done":h();break}},onError:t.onError,signal:r.signal}),h()}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;t.onError(o instanceof Error?o:new Error(String(o)))}})(),r}var hs="gengage-chat-scroll",on=null;function sn(e){on=e}function us(){on=null}var Qe={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:"Size Özel Seçimim",roleBestValue:"En Uygun Fiyatlı",roleBestAlternative:"En İyi Alternatif",viewDetails:"Detayları Gör",groundingReviewCta:"Yorumları Oku",groundingReviewSubtitle:"{count} yorum mevcut",variantsLabel:"Varyantlar",sortRelated:"Önerilen",sortPriceAsc:"Fiyat düşükten yükseğe",sortPriceDesc:"Fiyat yüksekten düşüğe",sortToolbarAriaLabel:"Ürünleri sırala",compareSelected:"Karşılaştır",compareMinHint:"En az 2 ürün seçin",compareMaxHint:"En fazla 5 ürün seçebilirsiniz",comparisonSelectLabel:"Karşılaştırmak için seç",comparisonSelectedLabel:"Seçildi",comparisonSelectCardHint:"Karşılaştırmaya eklemek veya çıkarmak için kartın herhangi bir yerine dokunun.",comparisonPreparingLabel:"Karşılaştırma tablosu hazırlanıyor…",panelTitleProductDetails:"Ürün Detayı",panelTitleSimilarProducts:"Benzer Ürünler",panelTitleComparisonResults:"Karşılaştırma Sonuçları",panelTitleCategories:"Kategoriler",panelTitleSearchResults:"Arama Sonuçları",inStockLabel:"Stokta",outOfStockLabel:"Tükendi",findSimilarLabel:"Benzerlerini Bul",galleryPrevAriaLabel:"Önceki görsel",galleryNextAriaLabel:"Sonraki görsel",beautyStylesPreparedTitle:"Sizin için {count} farklı stil hazırladım",watchStylesPreparedTitle:"Sizin için {count} farklı stil yönü hazırladım",consultingOtherCompatibleProductsLabel:"Diğer Uyumlu Ürünler",consultingFallbackGroupLabel:"Öneri",consultingFallbackStyleLabel:"Stil {index}",consultingStyleLoadingDescription:"Bu stil için ürünleri toplamaya devam ediyorum. Panel kısa süre içinde yenilenir.",consultingStyleUnavailableDescription:"Bu stil için şu anda yeterli ürün eşleşmesi çıkaramadım. Diğer stilleri inceleyebilirsiniz.",consultingStyleLoadingBadge:"Yükleniyor",consultingStyleUnavailableBadge:"Hazır değil",choicePrompterHeading:"Kararsız mı kaldın?",choicePrompterSuggestion:"Ürünleri seçip karşılaştırabilirsin",choicePrompterCta:"Seç ve Karşılaştır",viewMoreLabel:"Daha Fazla Göster",similarProductsLabel:"Benzer Ürünler",addToCartButton:"Sepete Ekle",addedToCartToast:"Sepete eklendi",shareButton:"Paylaş",productInfoTab:"Ürün Bilgileri",specificationsTab:"Teknik Özellikler",recommendedChoiceLabel:"Önerilen Seçim",highlightsLabel:"Öne Çıkan Özellikler",keyDifferencesLabel:"Temel Farklar",specialCasesLabel:"Özel Durumlar İçin",emptyReviewsMessage:"Yorum özeti bulunamadı.",closeAriaLabel:"Kapat",startChatLabel:"Sohbete Başla",voiceButton:"Sesli giriş",voiceListening:"Dinleniyor...",voiceNotSupported:"Sesli giriş bu tarayıcıda desteklenmiyor.",voicePermissionDenied:"Mikrofon erişimi reddedildi.",voiceError:"Sesli giriş hatası.",handoffHeading:"Destek temsilcisine aktarılıyor",productNotFoundMessage:"Bu ürün bilgisi şu an kullanılamıyor. Başka bir konuda yardımcı olabilirim.",stopGenerating:"Yanıtı Durdur",offlineMessage:"Çevrimdışısınız — bağlantı kurulduğunda mesajlar gönderilecek.",cartAriaLabel:"Sepetim",favoritesAriaLabel:"Favorilerim",showPanelAriaLabel:"Sonuçları Göster",addToFavoritesLabel:"Favorilere ekle",customerReviewsTitle:"Müşteri Yorumları",togglePanelAriaLabel:"Paneli aç/kapat",chatMessagesAriaLabel:"Sohbet mesajları",suggestionsAriaLabel:"Öneriler",moreSuggestionsAriaLabel:"Daha fazla öneri",rollbackAriaLabel:"Bu mesaja geri dön",backAriaLabel:"Geri",forwardAriaLabel:"İleri",closePanelAriaLabel:"Paneli kapat",dismissAriaLabel:"Kapat",cartAddErrorMessage:"Üzgünüm sepete ekleyemedim, bir sorunla karşılaştım.",favoriteToggleErrorMessage:"Favoriler güncellenemedi. Lütfen tekrar deneyin.",reviewFilterPositive:"Olumlu",reviewFilterNegative:"Olumsuz",decreaseLabel:"Azalt",increaseLabel:"Artır",reviewCustomersMentionSingular:"1 müşteri bahsediyor",reviewCustomersMentionPlural:"müşteri bahsediyor",reviewSubjectsHeading:"İncelemek için seçin",tryAgainButton:"Tekrar dene",askSomethingElseButton:"Başka bir şey sor",accountInactiveMessage:"Bu hesap şu an aktif değil. Lütfen daha sonra tekrar deneyin.",favoritesPageTitle:"Favorilerim",emptyFavoritesMessage:"Henüz favori ürün yok. Bir ürünü kalp ikonuna tıklayarak favorilere ekleyebilirsin.",showFormerMessagesButton:"↑ Önceki mesajları göster",aiAnalysisAnalyzingLabel:"Ürünler analiz ediliyor...",aiBrowseCategoriesTitle:"Kategorilere Göz At",photoAnalysisBadge:"Cilt Analizi",photoAnalysisStrengthsLabel:"Öne Çıkanlar",photoAnalysisFocusLabel:"Odak Noktaları",photoAnalysisCelebStyleLabel:"Celeb Vibe Eşleşmesi",beautyPhotoStepTitle:"Selfie ile kişiselleştir",beautyPhotoStepDescription:"İstersen net bir profil fotoğrafı yükle, sana özel önerilerde bulunayım.",beautyPhotoStepUpload:"Fotoğraf Yükle",beautyPhotoStepProcessing:"Fotoğraf işleniyor...",beautyPhotoStepSkip:"Geç",beautyPhotoStepSkipMessage:"Fotoğraf adımını geçiyorum"},ms={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",consultingOtherCompatibleProductsLabel:"Other compatible products",consultingFallbackGroupLabel:"Recommendation",consultingFallbackStyleLabel:"Style {index}",consultingStyleLoadingDescription:"I am still collecting products for this style. The panel will refresh shortly.",consultingStyleUnavailableDescription:"I could not find enough product matches for this style yet. You can review the other styles.",consultingStyleLoadingBadge:"Loading",consultingStyleUnavailableBadge:"Not ready",choicePrompterHeading:"Can't decide?",choicePrompterSuggestion:"Select products to compare them",choicePrompterCta:"Select & Compare",viewMoreLabel:"Show More",similarProductsLabel:"Similar Products",addToCartButton:"Add to Cart",addedToCartToast:"Added to cart",shareButton:"Share",productInfoTab:"Product Info",specificationsTab:"Specifications",recommendedChoiceLabel:"Recommended Choice",highlightsLabel:"Key Highlights",keyDifferencesLabel:"Key Differences",specialCasesLabel:"For Special Cases",emptyReviewsMessage:"No review summary found.",closeAriaLabel:"Close",startChatLabel:"Start Chat",voiceButton:"Voice input",voiceListening:"Listening...",voiceNotSupported:"Voice input is not supported in this browser.",voicePermissionDenied:"Microphone access denied.",voiceError:"Voice input error.",handoffHeading:"Transferring to a support agent",productNotFoundMessage:"Product information is currently unavailable. I can help with something else.",stopGenerating:"Stop generating",offlineMessage:"You're offline — messages will send when you reconnect.",cartAriaLabel:"My cart",favoritesAriaLabel:"My favorites",showPanelAriaLabel:"Show Results",addToFavoritesLabel:"Add to favorites",customerReviewsTitle:"Customer Reviews",togglePanelAriaLabel:"Toggle panel",chatMessagesAriaLabel:"Chat messages",suggestionsAriaLabel:"Suggestions",moreSuggestionsAriaLabel:"More suggestions",rollbackAriaLabel:"Rollback to this message",backAriaLabel:"Back",forwardAriaLabel:"Forward",closePanelAriaLabel:"Close panel",dismissAriaLabel:"Dismiss",cartAddErrorMessage:"Sorry, I couldn't add that to your cart. Something went wrong.",favoriteToggleErrorMessage:"We couldn't update favorites. Please try again.",reviewFilterPositive:"Positive",reviewFilterNegative:"Negative",decreaseLabel:"Decrease",increaseLabel:"Increase",reviewCustomersMentionSingular:"1 customer mentions",reviewCustomersMentionPlural:"customers mention",reviewSubjectsHeading:"Select to learn more",tryAgainButton:"Try again",askSomethingElseButton:"Ask something else",accountInactiveMessage:"This account is currently inactive. Please try again later.",favoritesPageTitle:"My Favorites",emptyFavoritesMessage:"No favorites yet. Heart a product to save it here.",showFormerMessagesButton:"↑ Show earlier messages",aiAnalysisAnalyzingLabel:"Analyzing products...",aiBrowseCategoriesTitle:"Browse categories",photoAnalysisBadge:"Skin Analysis",photoAnalysisStrengthsLabel:"Your strengths",photoAnalysisFocusLabel:"Focus points",photoAnalysisCelebStyleLabel:"Celeb style match",beautyPhotoStepTitle:"Personalize with a selfie",beautyPhotoStepDescription:"Upload a clear profile photo so I can give you personalized recommendations.",beautyPhotoStepUpload:"Upload Photo",beautyPhotoStepProcessing:"Processing photo...",beautyPhotoStepSkip:"Skip",beautyPhotoStepSkipMessage:"Skip the photo step"};function fs(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function bs(e){return fs(e)==="en"?ms:Qe}function vs(){return cn()!==null}function cn(){const e=globalThis;return e.SpeechRecognition??e.webkitSpeechRecognition??null}var ys=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=cn();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=_s(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 _s(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 xs(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=we(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 ws=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??""}},ks=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,xe(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 Cs(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 ln(e,t,a){const n=e.props??{},r=n.processing===!0,i={...Qe,...t.i18n??{}},o=document.createElement("div");o.className="gengage-chat-beauty-photo-step-card";const s=document.createElement("span");s.className="gengage-chat-beauty-photo-step-icon",s.setAttribute("aria-hidden","true"),s.textContent="✦";const c=document.createElement("div");c.className="gengage-chat-beauty-photo-step-content";const l=document.createElement("div");l.className="gengage-chat-beauty-photo-step-title",l.textContent=(typeof n.title=="string"?n.title:void 0)??i.beautyPhotoStepTitle;const g=document.createElement("p");g.className="gengage-chat-beauty-photo-step-desc",g.textContent=(typeof n.description=="string"?n.description:void 0)??i.beautyPhotoStepDescription;const h=document.createElement("div");h.className="gengage-chat-beauty-photo-step-actions";const u=document.createElement("button");u.type="button",u.className="gengage-chat-beauty-photo-step-upload gds-btn gds-btn-primary",u.textContent=r?i.beautyPhotoStepProcessing:(typeof n.upload_label=="string"?n.upload_label:void 0)??i.beautyPhotoStepUpload,u.disabled=r,a?.onUpload&&u.addEventListener("click",()=>a.onUpload());const d=document.createElement("button");return d.type="button",d.className="gengage-chat-beauty-photo-step-skip gds-btn gds-btn-ghost",d.textContent=(typeof n.skip_label=="string"?n.skip_label:void 0)??i.beautyPhotoStepSkip,a?.onSkip&&d.addEventListener("click",()=>a.onSkip()),h.appendChild(u),h.appendChild(d),c.appendChild(l),c.appendChild(g),c.appendChild(h),o.appendChild(s),o.appendChild(c),o}function Ss(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 Es(e,t,a,n,r){if(!a.visible)return e&&(e.hidden=!0,e.innerHTML=""),e;const i=Ss(e,t);i.hidden=!1,i.innerHTML="";const o=ln({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 dn(e){const t=typeof e.summary=="string"?e.summary:"",a=Array.isArray(e.strengths)?e.strengths.filter(c=>typeof c=="string"):[],n=Array.isArray(e.focus_points)?e.focus_points.filter(c=>typeof c=="string"):[];if(!t&&a.length===0&&n.length===0)return null;const r={summary:t},i=typeof e.celeb_style=="string"?e.celeb_style:void 0,o=typeof e.celeb_style_reason=="string"?e.celeb_style_reason:void 0,s=typeof e.next_question=="string"?e.next_question:void 0;return a.length>0&&(r.strengths=a),n.length>0&&(r.focusPoints=n),i&&(r.celebStyle=i),o&&(r.celebStyleReason=o),s&&(r.nextQuestion=s),r}function gn(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 pn(e,t){const a=document.createElement("div");a.className="gengage-chat-photo-analysis-card";const n=document.createElement("div");n.className="gengage-chat-photo-analysis-badge",n.textContent=e.badge;const r=document.createElement("div");if(r.className="gengage-chat-photo-analysis-body",t.summary){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-summary",c.textContent=t.summary,r.appendChild(c)}const i=document.createElement("div");i.className="gengage-chat-photo-analysis-highlights";const o=gn(e.strengths,t.strengths??[],"gengage-chat-photo-analysis-section--strengths"),s=gn(e.focus,t.focusPoints??[],"gengage-chat-photo-analysis-section--focus");if(o&&i.appendChild(o),s&&i.appendChild(s),i.childElementCount>0&&r.appendChild(i),t.celebStyle){const c=document.createElement("section");c.className="gengage-chat-photo-analysis-section gengage-chat-photo-analysis-section--celeb";const l=document.createElement("h4");l.className="gengage-chat-photo-analysis-section-title",l.textContent=e.celebStyle;const g=document.createElement("p");if(g.className="gengage-chat-photo-analysis-celeb-name",g.textContent=t.celebStyle,c.appendChild(l),c.appendChild(g),t.celebStyleReason){const h=document.createElement("p");h.className="gengage-chat-photo-analysis-celeb-reason",h.textContent=t.celebStyleReason,c.appendChild(h)}r.appendChild(c)}if(t.nextQuestion){const c=document.createElement("p");c.className="gengage-chat-photo-analysis-next",c.textContent=t.nextQuestion,r.appendChild(c)}return a.appendChild(n),a.appendChild(r),a}function Ts(e){const t={...Qe,...e?.i18n??{}};return{badge:t.photoAnalysisBadge,strengths:t.photoAnalysisStrengthsLabel,focus:t.photoAnalysisFocusLabel,celebStyle:t.photoAnalysisCelebStyleLabel}}function Ps(e,t){const a=dn(e.props??{})??{summary:""};return pn(Ts(t),a)}function As(e,t,a){e.innerHTML="",a&&e.appendChild(pn(t,a))}var Jm='<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>',hn={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>'},Ls=Qe,Is=1400,Ns=/data:image\/(png|jpeg|jpg|webp);base64,[A-Za-z0-9+/=]+/gi;async function zs(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(Ns)?.[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 Ms(e){try{const t=e??(typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():null);return t?zs(await t):null}catch{}return null}var Bs=class{_renderPhotoAnalysisCard(e,t){As(e,{badge:this.i18n.photoAnalysisBadge,strengths:this.i18n.photoAnalysisStrengthsLabel,focus:this.i18n.photoAnalysisFocusLabel,celebStyle:this.i18n.photoAnalysisCelebStyleLabel},t)}constructor(e,t){this._sendStopHandler=null,this._panelVisible=!1,this._panelCollapsed=!1,this._dividerPreviewEnabled=!1,this._onPanelToggle=void 0,this._onHostShellSync=void 0,this._pendingAttachment=null,this._onAttachment=void 0,this._onRollback=void 0,this._onLinkClick=void 0,this._userScrolledUp=!1,this._scrollLockedUntil=0,this._favBadgeEl=null,this._thinkingSteps=[],this._firstBotMessageIds=new Set,this._voiceInput=null,this._micBtn=null,this._voiceEnabled=!1,this._voiceLang="tr-TR",this._ignoreNextDividerClick=!1,this._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={...Ls,...t.i18n},this.onSend=t.onSend,t.onPanelToggle!==void 0&&(this._onPanelToggle=t.onPanelToggle),t.onHostShellSync!==void 0&&(this._onHostShellSync=t.onHostShellSync),t.onAttachment!==void 0&&(this._onAttachment=t.onAttachment),t.onRollback!==void 0&&(this._onRollback=t.onRollback),t.onLinkClick!==void 0&&(this._onLinkClick=t.onLinkClick),t.voiceEnabled&&(this._voiceEnabled=!0),t.voiceLang!==void 0&&(this._voiceLang=t.voiceLang),this.root=document.createElement("div"),this.root.className="gengage-chat-drawer gds-panel",this.root.dataset.gengagePart="chat-drawer",this.root.setAttribute("role","dialog"),this.root.setAttribute("aria-label",this.i18n.headerTitle??"Chat"),this.root.setAttribute("aria-modal","true");const a="gengage-chat-dialog-desc",n=document.createElement("span");n.id=a,n.className="gengage-sr-only",n.textContent=this.i18n.headerTitle??"AI shopping assistant",this.root.appendChild(n),this.root.setAttribute("aria-describedby",a);let r=null;{const S=document.createElement("div");S.className="gengage-chat-drawer-handle",S.dataset.gengagePart="chat-drawer-handle",S.setAttribute("aria-hidden","true"),S.style.pointerEvents="none",r=S}const i=document.createElement("div");i.className="gengage-chat-header gds-shell-header",i.dataset.gengagePart="chat-header";const o=document.createElement("div");o.className="gengage-chat-header-left",o.dataset.gengagePart="chat-header-left";const s=t.headerAvatarUrl??t.launcherImageUrl,c=typeof t.headerAvatarUrl=="string"&&t.headerAvatarUrl.length>0&&t.headerAvatarUrl!==t.launcherImageUrl;if(s){const S=document.createElement("img");S.className="gengage-chat-header-avatar",c&&S.classList.add("gengage-chat-header-avatar--logo"),S.dataset.gengagePart="chat-header-avatar",S.src=s,S.alt=t.headerTitle??"Assistant",o.appendChild(S)}const l=document.createElement("div");l.className="gengage-chat-header-info",l.dataset.gengagePart="chat-header-info";const g=document.createElement("div");g.className="gengage-chat-header-title-row",g.dataset.gengagePart="chat-header-title-row";const h=document.createElement("span");if(h.className="gengage-chat-header-title",h.dataset.gengagePart="chat-header-title",h.textContent=t.headerTitle??this.i18n.headerTitle??"Product Expert",g.appendChild(h),t.headerBadge){const S=document.createElement("span");S.className="gengage-chat-header-badge gds-badge gds-badge-brand",S.dataset.gengagePart="chat-header-badge",S.textContent=t.headerBadge,g.appendChild(S)}l.appendChild(g);const u=document.createElement("a");u.className="gengage-chat-header-powered",u.dataset.gengagePart="chat-header-powered-by",u.href="https://gengage.ai/",u.target="_blank",u.rel="noopener noreferrer",u.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(u),o.appendChild(l),i.appendChild(o);const d=document.createElement("div");d.className="gengage-chat-header-right",d.dataset.gengagePart="chat-header-actions";{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gengage-chat-header-btn--reopen-panel gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-reopen-panel",S.setAttribute("aria-label",this.i18n.showPanelAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="9" y1="3" x2="9" y2="21"/></svg>',S.addEventListener("click",()=>this._showMobilePanelFromBtn()),d.appendChild(S),this._reopenPanelBtn=S}{const S=document.createElement("button");S.type="button",S.className="gengage-chat-header-btn gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-cart",S.setAttribute("aria-label",this.i18n.cartAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/></svg>',S.addEventListener("click",()=>t.onCartClick?.()),d.appendChild(S),this._cartBtn=S}if(t.onNewChat){const S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-new-chat gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-new-chat",S.type="button",S.setAttribute("aria-label",this.i18n.newChatButton),S.title=this.i18n.newChatButton,S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/></svg>',S.addEventListener("click",()=>t.onNewChat?.()),d.appendChild(S)}const 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 S=document.createElement("button");S.className="gengage-chat-header-btn gengage-chat-header-btn--fav gds-btn gds-btn-ghost gds-icon-btn",S.dataset.gengagePart="chat-header-favorites",S.type="button",S.setAttribute("aria-label",this.i18n.favoritesAriaLabel),S.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>';const R=document.createElement("span");R.className="gengage-chat-header-fav-badge",R.dataset.gengagePart="chat-header-favorites-badge",R.setAttribute("aria-hidden","true"),R.style.display="none",S.appendChild(R),this._favBadgeEl=R,S.addEventListener("click",()=>{t.onFavoritesClick?.()}),d.appendChild(S)}d.appendChild(f),r&&i.insertBefore(r,i.firstChild),i.appendChild(d);{let R=0,V=0,oe=!1;const ye=_e=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||_e.target.closest('button, a, input, [role="button"]'))return;const Ae=_e.changedTouches?.[0];Ae&&(R=Ae.clientY,V=0,oe=!0,this.root.style.transition="none")},Oe=_e=>{if(!oe)return;const Ae=_e.changedTouches?.[0];if(!Ae)return;V=Ae.clientY-R;const Km=(t.getMobileState?.()??"full")==="full"?Math.max(0,V):V;_e.preventDefault(),this.root.style.transform=`translateY(${Km}px)`},Ke=()=>{if(!oe)return;oe=!1;const _e=t.getMobileState?.()??"full";let Ae;V>72?Ae=_e==="full"?"half":"close":V<-72&&_e==="half"?Ae="full":Ae=_e,this.root.style.transition="",Ae==="close"?(this.root.style.transform="translateY(100%)",setTimeout(()=>{this.root.style.transform="",t.onMobileSnap?.("close")},280)):(this.root.style.transform="",t.onMobileSnap?.(Ae)),V=0},Gt=()=>{oe&&(oe=!1,V=0,this.root.style.transition="",this.root.style.transform="")};i.addEventListener("touchstart",ye,{passive:!0}),i.addEventListener("touchmove",Oe,{passive:!1}),i.addEventListener("touchend",Ke,{passive:!0}),i.addEventListener("touchcancel",Gt,{passive:!0}),this._cleanups.push(()=>{i.removeEventListener("touchstart",ye),i.removeEventListener("touchmove",Oe),i.removeEventListener("touchend",Ke),i.removeEventListener("touchcancel",Gt)})}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 ws({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 w=null,v=null;const x=24,k=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768))return;const R=S.changedTouches?.[0];R&&(w=R.clientX,v=R.clientY)},A=S=>{if(!(this._options.getMobileViewport?.()??window.innerWidth<=768)||w===null||v===null)return;const R=S.changedTouches?.[0];if(!R)return;const V=R.clientX-w,oe=R.clientY-v;if(w=null,v=null,Math.abs(oe)<x||Math.abs(oe)<Math.abs(V))return;const ye=oe<0;ye!==this._panelCollapsed&&(this._ignoreNextDividerClick=!0,this.setPanelCollapsed(ye),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 L=document.createElement("div");L.className="gengage-chat-conversation",L.dataset.gengagePart="chat-conversation",this._conversationEl=L,L.appendChild(i);const M=document.createElement("div");M.className="gengage-chat-offline-bar gds-evidence-card gds-evidence-card-warning",M.dataset.gengagePart="chat-offline-bar",M.setAttribute("role","status"),M.setAttribute("aria-live","polite"),M.textContent=this.i18n.offlineMessage,typeof navigator<"u"&&!navigator.onLine&&M.classList.add("gengage-chat-offline-bar--visible"),L.appendChild(M);const W=()=>M.classList.add("gengage-chat-offline-bar--visible"),$=()=>M.classList.remove("gengage-chat-offline-bar--visible");window.addEventListener("offline",W),window.addEventListener("online",$),this._cleanups.push(()=>{window.removeEventListener("offline",W),window.removeEventListener("online",$)}),this._kvkkSlot=document.createElement("div"),this._kvkkSlot.className="gengage-chat-kvkk-slot",this._kvkkSlot.dataset.gengagePart="chat-kvkk-slot",L.appendChild(this._kvkkSlot),this.messagesEl=document.createElement("div"),this.messagesEl.id=hs,this.messagesEl.className="gengage-chat-messages",this.messagesEl.dataset.gengagePart="chat-messages",this.messagesEl.setAttribute("role","log"),this.messagesEl.setAttribute("aria-live","polite"),this.messagesEl.setAttribute("aria-atomic","false"),this.messagesEl.setAttribute("aria-label",this.i18n.chatMessagesAriaLabel),sn(this.messagesEl);const D=document.createElement("button");D.type="button",D.className="gengage-chat-former-messages-btn gds-chip",D.dataset.gengagePart="chat-former-messages-button",D.textContent=this.i18n.showFormerMessagesButton,D.setAttribute("aria-label",this.i18n.showFormerMessagesButton),D.style.display="none",D.addEventListener("click",()=>{this._options.presentation?.onReleasePresentationFocus?.()}),this.messagesEl.appendChild(D),this._formerMessagesBtn=D;const I=()=>{this._userInteractionUntil=Date.now()+2e3};let z=!1;const _=()=>this._options.presentation,y=()=>{z||(z=!0,requestAnimationFrame(()=>{z=!1;const{scrollTop:S,scrollHeight:R,clientHeight:V}=this.messagesEl,oe=R-S-V;this._userScrolledUp=oe>10;const ye=this._presentationPinned?oe<96:oe<32,Oe=Date.now(),Ke=Oe<this._programmaticScrollUntil,Gt=!ye&&Oe<this._userInteractionUntil,_e=Ke?!1:Gt;ye!==this._presentationPinned&&(this._presentationPinned=ye,_()?.onPinnedToBottomChange?.(ye)),_e!==this._presentationUserInteracting&&(this._presentationUserInteracting=_e,_()?.onUserInteractingChange?.(_e))}))};this.messagesEl.addEventListener("scroll",y,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("scroll",y)});const T=S=>{I(),S.deltaY<-6&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("wheel",T,{passive:!0}),this._cleanups.push(()=>this.messagesEl.removeEventListener("wheel",T));const C=S=>{I(),this._touchStartY=S.touches[0]?.clientY??null},B=S=>{I();const R=S.touches[0]?.clientY,V=this._touchStartY;typeof R=="number"&&typeof V=="number"&&R-V>10&&this._presentationFocusThreadId&&this._options.presentation?.onFormerMessagesHint?.()};this.messagesEl.addEventListener("touchstart",C,{passive:!0}),this.messagesEl.addEventListener("touchmove",B,{passive:!0}),this._cleanups.push(()=>{this.messagesEl.removeEventListener("touchstart",C),this.messagesEl.removeEventListener("touchmove",B)}),L.appendChild(this.messagesEl),this._thumbnailsColumn=new ks({onThumbnailClick:S=>t.onThumbnailClick?.(S)}),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelFloatingEl=document.createElement("div"),this._panelFloatingEl.className="gengage-chat-panel-float",this._panelFloatingEl.dataset.gengagePart="chat-panel-floating-layer",this._panelEl.appendChild(this._panelFloatingEl),this._resetPanelAiZoneElement(),this._pillsEl=document.createElement("div"),this._pillsEl.className="gengage-chat-pills",this._pillsEl.dataset.gengagePart="chat-suggestion-pills",this._pillsEl.setAttribute("role","toolbar"),this._pillsEl.setAttribute("aria-label",this.i18n.suggestionsAriaLabel),this._pillsEl.style.display="none";const N=document.createElement("div");N.className="gengage-chat-pills-scroll",N.dataset.gengagePart="chat-suggestion-pills-scroll",this._pillsEl.appendChild(N);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",()=>{N.scrollBy({left:150,behavior:"smooth"})}),this._pillsEl.appendChild(P);let F=!1;const H=()=>{F||(F=!0,requestAnimationFrame(()=>{F=!1;const S=N.scrollLeft+N.clientWidth>=N.scrollWidth-4;P.style.display=S?"none":""}))};N.addEventListener("scroll",H,{passive:!0}),this._cleanups.push(()=>{N.removeEventListener("scroll",H)}),L.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",L.appendChild(this._inputChipsEl);const U=document.createElement("div");U.className="gengage-chat-input-area",U.dataset.gengagePart="chat-input-area",this.inputEl=document.createElement("textarea"),this.inputEl.className="gengage-chat-input",this.inputEl.dataset.gengagePart="chat-input",this.inputEl.rows=1,this.inputEl.placeholder=this.i18n.inputPlaceholder,this.inputEl.addEventListener("input",()=>{this._resizeRafId!==null&&cancelAnimationFrame(this._resizeRafId),this._resizeRafId=requestAnimationFrame(()=>{this._resizeRafId=null,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`}),this._updateSendEnabled()}),this.inputEl.addEventListener("keydown",S=>{S.key==="Enter"&&!S.isComposing&&((this._options.getMobileViewport?.()??window.innerWidth<=768)||!S.shiftKey)&&(S.preventDefault(),this._submit())}),this.inputEl.addEventListener("paste",S=>{const R=S.clipboardData;if(!R)return;let V=null;const oe=R.files?.[0];if(oe&&oe.type.startsWith("image/"))V=oe;else if(R.items?.length)for(let ye=0;ye<R.items.length;ye++){const Oe=R.items[ye];if(Oe?.kind==="file"&&Oe.type.startsWith("image/")){const Ke=Oe.getAsFile();if(Ke){V=Ke;break}}}V&&(S.preventDefault(),this._routeAttachmentFile(V))}),this._fileInput=document.createElement("input"),this._fileInput.type="file",this._fileInput.accept="image/jpeg,image/png,image/webp",this._fileInput.style.display="none",this._fileInput.addEventListener("change",()=>{const S=this._fileInput.files?.[0];S&&this._routeAttachmentFile(S),this._fileInput.value=""});const q=document.createElement("div");q.className="gengage-chat-attach-wrap",q.dataset.gengagePart="chat-attach-wrap",this._attachWrapEl=q;const Y=document.createElement("button");this._attachBtn=Y,Y.className="gengage-chat-attach-btn gds-btn gds-btn-ghost",Y.dataset.gengagePart="chat-attach-button",Y.type="button",Y.setAttribute("aria-label",this.i18n.attachImageButton),Y.setAttribute("aria-haspopup","menu"),Y.setAttribute("aria-expanded","false"),Y.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>',Y.addEventListener("click",S=>{S.stopPropagation(),this._toggleAttachMenu()});const ae=document.createElement("div");this._attachMenuEl=ae,ae.className="gengage-chat-attach-menu gds-menu",ae.dataset.gengagePart="chat-attach-menu",ae.setAttribute("role","menu"),ae.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",S=>{S.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 ve=document.createElement("button");ve.type="button",ve.className="gengage-chat-attach-menu-item gds-btn gds-btn-ghost",ve.dataset.gengagePart="chat-attach-menu-paste",ve.setAttribute("role","menuitem"),ve.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>`,ve.addEventListener("click",S=>{S.stopPropagation();const R=typeof navigator.clipboard?.read=="function"?navigator.clipboard.read():void 0;this._pasteImageFromClipboardMenu(R)}),ae.appendChild(j),ae.appendChild(be),ae.appendChild(ve),q.appendChild(Y),q.appendChild(ae),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 Z=document.createElement("img");Z.className="gengage-chat-attachment-preview-thumb",Z.dataset.gengagePart="chat-attachment-preview-thumb",Z.alt="",this._previewName=document.createElement("span"),this._previewName.className="gengage-chat-attachment-name",this._previewName.dataset.gengagePart="chat-attachment-preview-name";const pe=document.createElement("button");pe.className="gengage-chat-attachment-remove gds-btn gds-btn-ghost",pe.dataset.gengagePart="chat-attachment-preview-remove",pe.type="button",pe.setAttribute("aria-label",this.i18n.removeAttachmentButton),pe.textContent="×",pe.addEventListener("click",()=>this.clearAttachment()),this._previewStrip.appendChild(Z),this._previewStrip.appendChild(this._previewName),this._previewStrip.appendChild(pe),this.sendBtn=document.createElement("button"),this.sendBtn.className="gengage-chat-send gds-btn gds-btn-primary",this.sendBtn.dataset.gengagePart="chat-send",this.sendBtn.type="button",this.sendBtn.disabled=!0,this.sendBtn.setAttribute("aria-label",this.i18n.sendButton),this.sendBtn.dataset.tooltip=this.i18n.sendButton,this._renderSendButtonIcon("send"),this.sendBtn.addEventListener("click",()=>{if(this._sendStopHandler){const S=this._sendStopHandler;this.hideStopButton(),S();return}this._submit()}),U.addEventListener("dragover",S=>{S.preventDefault(),U.classList.add("gengage-chat-input-area--dragover")}),U.addEventListener("dragleave",()=>{U.classList.remove("gengage-chat-input-area--dragover")}),U.addEventListener("drop",S=>{S.preventDefault(),U.classList.remove("gengage-chat-input-area--dragover");const R=S.dataTransfer?.files[0];R&&this._routeAttachmentFile(R)});const ee=document.createElement("div");ee.className="gengage-chat-input-pill gds-input-shell",ee.dataset.gengagePart="chat-input-shell",ee.appendChild(q),ee.appendChild(this.inputEl),this._voiceEnabled&&vs()&&(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()),ee.appendChild(this._micBtn),this._voiceInput=new ys({onInterim:S=>{this._resizeRafId!==null&&(cancelAnimationFrame(this._resizeRafId),this._resizeRafId=null),this.inputEl.value=S,this.inputEl.style.height="auto",this.inputEl.style.height=`${Math.min(this.inputEl.scrollHeight,120)}px`},onFinal:S=>{this.inputEl.value=S},onAutoSubmit:S=>{this.inputEl.value=S,this._micBtn?.classList.remove("gengage-chat-mic-btn--active"),this._submit()},onStateChange:S=>{S==="listening"?this._micBtn?.classList.add("gengage-chat-mic-btn--active"):this._micBtn?.classList.remove("gengage-chat-mic-btn--active")},onError:(S,R)=>{this._micBtn?.classList.remove("gengage-chat-mic-btn--active")}},{lang:this._voiceLang})),ee.appendChild(this.sendBtn),U.appendChild(this._previewStrip),U.appendChild(this._fileInput),U.appendChild(ee),L.appendChild(U),p.appendChild(L),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(L),this._setupHorizontalSwipe(this._panelEl);const J=document.createElement("div");J.className="gengage-chat-footer",J.dataset.gengagePart="chat-footer",J.textContent=this.i18n.poweredBy,this.root.appendChild(J);const X=S=>{S.key==="Escape"&&t.onClose()};this.root.addEventListener("keydown",X),this._cleanups.push(()=>this.root.removeEventListener("keydown",X)),e.appendChild(this.root)}addMessage(e){const t=document.createElement("div");if(t.className=`gengage-chat-bubble gds-message ${e.role==="assistant"?"gds-message-assistant":"gds-message-user"} gengage-chat-bubble--${e.role}`,t.dataset.gengagePart=e.role==="assistant"?"chat-message-assistant":"chat-message-user",t.setAttribute("role","listitem"),t.dataset.messageId=e.id,e.threadId&&(t.dataset.threadId=e.threadId),this._firstBotMessageIds.has(e.id)&&t.classList.add("gengage-chat-bubble--first"),e.attachment){const a=document.createElement("img");a.className="gengage-chat-attachment-thumb";const n=URL.createObjectURL(e.attachment);a.src=n,a.alt=e.attachment.name,a.addEventListener("load",()=>URL.revokeObjectURL(n),{once:!0}),a.addEventListener("error",()=>URL.revokeObjectURL(n),{once:!0}),t.insertBefore(a,t.firstChild)}if(e.content){const a=document.createElement("div");if(a.className="gengage-chat-bubble-text",a.dataset.gengagePart="chat-message-text",e.role==="assistant"){if(e.renderHint==="photo_analysis"?(t.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(a,e.photoAnalysis)):a.innerHTML=we(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="${he(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=hn[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&&xe(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=xs({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=Es(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 Ms(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=!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=!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 L=0;L<2;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-title",L===1&&M.classList.add("gengage-chat-comparison-skeleton-rec-title--short"),g.appendChild(M)}const h=document.createElement("div");h.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-rec-price",g.appendChild(h),c.appendChild(l),c.appendChild(g),o.appendChild(c);const u=document.createElement("div");u.className="gengage-chat-comparison-highlights";const d=document.createElement("div");d.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-label",u.appendChild(d);const f=document.createElement("ul");f.className="gengage-chat-comparison-skeleton-hl-list";for(let L=0;L<3;L++){const M=document.createElement("li"),W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-hl-line",L===1&&W.classList.add("gengage-chat-comparison-skeleton-hl-line--medium"),L===2&&W.classList.add("gengage-chat-comparison-skeleton-hl-line--short"),M.appendChild(W),f.appendChild(M)}u.appendChild(f),o.appendChild(u),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 L=0;L<4;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-kd-line",b.appendChild(M)}p.appendChild(b),i.appendChild(p);const w=document.createElement("div");w.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",w.appendChild(v),i.appendChild(w);const x=document.createElement("div");x.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 L=0;L<3;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-table-col";const W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-img";const $=document.createElement("div");$.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-name";const D=document.createElement("div");D.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-th-price",M.appendChild(W),M.appendChild($),M.appendChild(D),k.appendChild(M)}x.appendChild(k);for(let L=0;L<3;L++){const M=document.createElement("div");M.className="gengage-chat-comparison-skeleton-table-row";const W=document.createElement("div");W.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-label",M.appendChild(W);for(let $=0;$<3;$++){const D=document.createElement("div");D.className="gengage-chat-comparison-skeleton-shimmer gengage-chat-comparison-skeleton-table-cell",M.appendChild(D)}x.appendChild(M)}i.appendChild(x),t.appendChild(i);break}default:t.appendChild(n);for(let i=0;i<3;i++){const o=document.createElement("div");o.className="gengage-chat-panel-skeleton-block",t.appendChild(o)}break}this._panelEl.appendChild(t),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel"),this._syncDividerPreview(),this._emitHostShellSync()}updatePanelTopBar(e,t,a){const n=this._options.getMobileViewport?.()??!1;this._panelTopBar.update(n?!0:e,t,a);const r=this.getPanelContentElement();r&&this._syncPanelTopBarTitleFromContent(r)}getPanelTopBarTitle(){return this._panelTopBar.getTitle()}updateFavoritesBadge(e){this._favBadgeEl&&(e>0?(this._favBadgeEl.textContent=e>99?"99+":String(e),this._favBadgeEl.style.display=""):this._favBadgeEl.style.display="none")}clearPanel(){this._destroyLoadingBinding(this._panelLoadingBinding),this._panelLoadingBinding=null,this._destroyLoadingBinding(this._panelAiZoneLoadingBinding),this._panelAiZoneLoadingBinding=null,this._panelEl.innerHTML="",this._resetPanelAiZoneElement(),this._panelEl.appendChild(this._panelTopBar.getElement()),this._panelEl.appendChild(this._panelAiZoneEl),this._panelEl.appendChild(this._thumbnailsColumn.getElement()),this._panelEl.appendChild(this._panelFloatingEl),this._panelTopBar.setActions(null),this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible","gengage-chat-panel--collapsed"),this.root.classList.remove("gengage-chat-drawer--with-panel"),this._dividerEl.classList.add("gengage-chat-panel-divider--hidden"),this._dividerPreviewEnabled=!1,this._syncDividerPreview(),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this.setComparisonDockContent(null),this._emitHostShellSync()}setComparisonDockContent(e){this._comparisonDockSlotEl.replaceChildren(),e&&this._comparisonDockSlotEl.appendChild(e)}hideMobilePanel(){this._panelVisible&&(this._panelVisible=!1,this._panelEl.classList.remove("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="flex"),this._emitHostShellSync())}_showMobilePanelFromBtn(){this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this._reopenPanelBtn&&(this._reopenPanelBtn.style.display="none"),this._emitHostShellSync())}expandPanel(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._syncDividerPreview(),this._emitHostShellSync()}setForceExpanded(){this._panelCollapsed=!1,this._panelEl.classList.remove("gengage-chat-panel--collapsed"),this._panelVisible||(this._panelVisible=!0,this._panelEl.classList.add("gengage-chat-panel--visible"),this.root.classList.add("gengage-chat-drawer--with-panel")),this._dividerEl.classList.remove("gengage-chat-panel-divider--hidden"),this._syncDividerPreview(),this._emitHostShellSync()}_smoothScrollPanelListToTop(){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)},Is))}_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="${he(e)}"]`);if(!r)return;let i=r.querySelector(".gengage-chat-bubble-text");i||(i=document.createElement("div"),i.className="gengage-chat-bubble-text",r.appendChild(i)),a==="photo_analysis"?(r.classList.add("gengage-chat-bubble--photo-analysis"),this._renderPhotoAnalysisCard(i,n)):(r.classList.remove("gengage-chat-bubble--photo-analysis"),i.innerHTML=we(t)),this._scrollToBottom(!1)}markFirstBotMessage(e){this._firstBotMessageIds.add(e);const t=this.messagesEl.querySelector(`[data-message-id="${he(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="${he(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="${he(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=hn[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)||!xe(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(){sn(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}},un=["beauty_consulting","watch_expert","booking"],Rs=["shopping",...un];function Os(e){return typeof e=="string"&&Rs.includes(e)?e:null}function oa(e){return e==null||typeof e!="object"||Array.isArray(e)?null:e}function Ds(...e){for(const t of e)if(typeof t=="string"){const a=t.trim();if(a.length>0)return a}}function Fs(e){const t=oa(e);if(!t)return null;const a=Ds(t.assistant_mode,t.assistantMode);return!a||!un.includes(a)?null:a}var Us=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){Ie("mode","redirect metadata received",e);const t=Fs(e);return t?(this.switchMode(t),!0):!1}switchMode(e){const t=this._mode;this._mode=e,Ie("mode","assistant mode switched",{from:t,to:e})}updateFromContext(e){const t=e.assistant_mode;if(typeof t=="string"&&t){const a=Os(t);a?this._mode=a:Ie("mode","ignoring unrecognised assistant_mode from context",t)}else t===null&&(this._mode="shopping");this._uiHints=oa(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 $s(){return{streamIncludedBeautyPhotoStep:!1,pendingPhotoStepSkip:!1}}function Hs(e,t,a,n,r){if(e==="PhotoAnalysisCard"){const i=dn(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):(Ie("beauty","PhotoAnalysisCard parse failed, falling through to generic renderer",t),!1)}if(e==="BeautyPhotoStep"){a.streamIncludedBeautyPhotoStep=!0;const i=Cs(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 qs(e){return e.renderHint==="photo_analysis"}function js(e,t){e.streamIncludedBeautyPhotoStep||t.drawer?.setBeautyPhotoStepCard({visible:!1}),e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}function Zs(e,t){e.pendingPhotoStepSkip&&(e.pendingPhotoStepSkip=!1,t.sendSkipMessage())}var Vs=`<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"/>
|