@gengage/assistant-fe 0.3.23 → 0.3.24
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-DBJ8ZWch.js → chat-q65kDKeT.js} +1 -1
- package/dist/chat.iife.js +1 -1
- package/dist/chat.js +1 -1
- package/dist/{common-BJZB1LIH.js → common-uTYBcG11.js} +1 -1
- package/dist/common.js +3 -3
- package/dist/index.js +3 -3
- package/dist/{native-webview-111Or6o1.js → native-webview-5TioIwea.js} +1 -1
- package/dist/native.iife.js +1 -1
- package/dist/native.js +1 -1
- package/package.json +8 -16
- package/dist/chat-BOkLnT1i.cjs +0 -93
- package/dist/chat.cjs +0 -1
- package/dist/common-0GWnpStO.cjs +0 -1
- package/dist/common.cjs +0 -1
- package/dist/connection-warning-YQiIRXrz.cjs +0 -1
- package/dist/ga-datalayer-BVppFxqk.cjs +0 -47
- package/dist/index.cjs +0 -1
- package/dist/native-webview-BePZBK3U.cjs +0 -1
- package/dist/native.cjs +0 -1
- package/dist/product-utils-DLXQQJbh.cjs +0 -1
- package/dist/qna-DwG8AJJf.cjs +0 -1
- package/dist/qna.cjs +0 -1
- package/dist/schemas-B7jnyzQI.cjs +0 -40
- package/dist/simbut-D_ycY_MQ.cjs +0 -1
- package/dist/simbut.cjs +0 -1
- package/dist/simrel-DdP4lur9.cjs +0 -1
- package/dist/simrel.cjs +0 -1
package/dist/native.iife.js
CHANGED
|
@@ -173,6 +173,6 @@ button[data-gengage-part="chat-launcher-button"] img {
|
|
|
173
173
|
|
|
174
174
|
`)}u.write("payload.value = newResult;"),u.write("return payload;");const C=u.compile();return(v,w)=>C(h,v,w)};let i;const o=Lt,s=!Sa.jitless,l=s&&yd.value,g=t.catchall;let d;e._zod.parse=(h,u)=>{d??(d=n.value);const f=h.value;return o(f)?s&&l&&u?.async===!1&&u.jitless!==!0?(i||(i=r(t.shape)),h=i(h,u),g?vr([],f,h,u,d,e):h):a(h,u):(h.issues.push({expected:"object",code:"invalid_type",input:f,inst:e}),h)}});function yr(e,t,a,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!at(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:a,errors:e.map(i=>i.issues.map(o=>Ve(o,n,je())))}),t)}var Qg=S("$ZodUnion",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Y(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Y(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Y(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>Aa(i.source)).join("|")})$`)}});const a=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(a)return n(r,i);let o=!1;const s=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}return o?Promise.all(s).then(c=>yr(c,r,e,i)):yr(s,r,e,i)}}),Xg=S("$ZodIntersection",(e,t)=>{ae.init(e,t),e._zod.parse=(a,n)=>{const r=a.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([s,c])=>_r(a,s,c)):_r(a,i,o)}});function Na(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(gt(e)&>(t)){const a=Object.keys(t),n=Object.keys(e).filter(i=>a.indexOf(i)!==-1),r={...e,...t};for(const i of n){const o=Na(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};r[i]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const a=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=Na(r,i);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}function _r(e,t,a){const n=new Map;let r;for(const s of t.issues)if(s.code==="unrecognized_keys"){r??(r=s);for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(s);for(const s of a.issues)if(s.code==="unrecognized_keys")for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(s);const i=[...n].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&r&&e.issues.push({...r,keys:i}),at(e))return e;const o=Na(t.value,a.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var ep=S("$ZodEnum",(e,t)=>{ae.init(e,t);const a=Zn(t.entries),n=new Set(a);e._zod.values=n,e._zod.pattern=new RegExp(`^(${a.filter(r=>_d.has(typeof r)).map(r=>typeof r=="string"?tt(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:a,input:o,inst:e}),r}}),tp=S("$ZodLiteral",(e,t)=>{if(ae.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const a=new Set(t.values);e._zod.values=a,e._zod.pattern=new RegExp(`^(${t.values.map(n=>typeof n=="string"?tt(n):n?tt(n.toString()):String(n)).join("|")})$`),e._zod.parse=(n,r)=>{const i=n.value;return a.has(i)||n.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),n}}),ap=S("$ZodTransform",(e,t)=>{ae.init(e,t),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(e.constructor.name);const r=t.transform(a.value,a);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(a.value=i,a));if(r instanceof Promise)throw new et;return a.value=r,a}});function xr(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var wr=S("$ZodOptional",(e,t)=>{ae.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Y(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Y(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${Aa(a.source)})?$`):void 0}),e._zod.parse=(a,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>xr(i,a.value)):xr(r,a.value)}return a.value===void 0?a:t.innerType._zod.run(a,n)}}),np=S("$ZodExactOptional",(e,t)=>{wr.init(e,t),Y(e._zod,"values",()=>t.innerType._zod.values),Y(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(a,n)=>t.innerType._zod.run(a,n)}),rp=S("$ZodNullable",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.innerType._zod.optin),Y(e._zod,"optout",()=>t.innerType._zod.optout),Y(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${Aa(a.source)}|null)$`):void 0}),Y(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(a,n)=>a.value===null?a:t.innerType._zod.run(a,n)}),ip=S("$ZodDefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",Y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);if(a.value===void 0)return a.value=t.defaultValue,a;const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>kr(i,t)):kr(r,t)}});function kr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var op=S("$ZodPrefault",(e,t)=>{ae.init(e,t),e._zod.optin="optional",Y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>(n.direction==="backward"||a.value===void 0&&(a.value=t.defaultValue),t.innerType._zod.run(a,n))}),sp=S("$ZodNonOptional",(e,t)=>{ae.init(e,t),Y(e._zod,"values",()=>{const a=t.innerType._zod.values;return a?new Set([...a].filter(n=>n!==void 0)):void 0}),e._zod.parse=(a,n)=>{const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>Cr(i,e)):Cr(r,e)}});function Cr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var cp=S("$ZodCatch",(e,t)=>{ae.init(e,t),Y(e._zod,"optin",()=>t.innerType._zod.optin),Y(e._zod,"optout",()=>t.innerType._zod.optout),Y(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>(a.value=i.value,i.issues.length&&(a.value=t.catchValue({...a,error:{issues:i.issues.map(o=>Ve(o,n,je()))},input:a.value}),a.issues=[]),a)):(a.value=r.value,r.issues.length&&(a.value=t.catchValue({...a,error:{issues:r.issues.map(i=>Ve(i,n,je()))},input:a.value}),a.issues=[]),a)}}),lp=S("$ZodPipe",(e,t)=>{ae.init(e,t),Y(e._zod,"values",()=>t.in._zod.values),Y(e._zod,"optin",()=>t.in._zod.optin),Y(e._zod,"optout",()=>t.out._zod.optout),Y(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(a,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(a,n);return i instanceof Promise?i.then(o=>Dt(o,t.in,n)):Dt(i,t.in,n)}const r=t.in._zod.run(a,n);return r instanceof Promise?r.then(i=>Dt(i,t.out,n)):Dt(r,t.out,n)}});function Dt(e,t,a){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},a)}var dp=S("$ZodReadonly",(e,t)=>{ae.init(e,t),Y(e._zod,"propValues",()=>t.innerType._zod.propValues),Y(e._zod,"values",()=>t.innerType._zod.values),Y(e._zod,"optin",()=>t.innerType?._zod?.optin),Y(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(Sr):Sr(r)}});function Sr(e){return e.value=Object.freeze(e.value),e}var gp=S("$ZodCustom",(e,t)=>{he.init(e,t),ae.init(e,t),e._zod.parse=(a,n)=>a,e._zod.check=a=>{const n=a.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>Er(i,a,n,e));Er(r,a,n,e)}});function Er(e,t,a,n){if(!e){const r={code:"custom",input:a,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(pt(r))}}var Tr,pp=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const a=t[0];return this._map.set(e,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const a={...this.get(t)??{}};delete a.id;const n={...a,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function hp(){return new pp}(Tr=globalThis).__zod_globalRegistry??(Tr.__zod_globalRegistry=hp());var Me=globalThis.__zod_globalRegistry;function up(e,t){return new e({type:"string",...D(t)})}function mp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...D(t)})}function Pr(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...D(t)})}function fp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...D(t)})}function bp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...D(t)})}function vp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...D(t)})}function yp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...D(t)})}function _p(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...D(t)})}function xp(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...D(t)})}function wp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...D(t)})}function kp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...D(t)})}function Cp(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...D(t)})}function Sp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...D(t)})}function Ep(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...D(t)})}function Tp(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...D(t)})}function Pp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...D(t)})}function Ap(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...D(t)})}function Lp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...D(t)})}function Ip(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...D(t)})}function Np(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...D(t)})}function zp(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...D(t)})}function Mp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...D(t)})}function Bp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...D(t)})}function Rp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...D(t)})}function Op(e,t){return new e({type:"string",format:"date",check:"string_format",...D(t)})}function Dp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...D(t)})}function Fp(e,t){return new e({type:"string",format:"duration",check:"string_format",...D(t)})}function $p(e,t){return new e({type:"number",checks:[],...D(t)})}function Up(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...D(t)})}function Hp(e,t){return new e({type:"boolean",...D(t)})}function qp(e){return new e({type:"unknown"})}function jp(e,t){return new e({type:"never",...D(t)})}function Ar(e,t){return new pr({check:"less_than",...D(t),value:e,inclusive:!1})}function za(e,t){return new pr({check:"less_than",...D(t),value:e,inclusive:!0})}function Lr(e,t){return new hr({check:"greater_than",...D(t),value:e,inclusive:!1})}function Ma(e,t){return new hr({check:"greater_than",...D(t),value:e,inclusive:!0})}function Ir(e,t){return new og({check:"multiple_of",...D(t),value:e})}function Nr(e,t){return new cg({check:"max_length",...D(t),maximum:e})}function Ft(e,t){return new lg({check:"min_length",...D(t),minimum:e})}function zr(e,t){return new dg({check:"length_equals",...D(t),length:e})}function Zp(e,t){return new gg({check:"string_format",format:"regex",...D(t),pattern:e})}function Vp(e){return new pg({check:"string_format",format:"lowercase",...D(e)})}function Wp(e){return new hg({check:"string_format",format:"uppercase",...D(e)})}function Gp(e,t){return new ug({check:"string_format",format:"includes",...D(t),includes:e})}function Kp(e,t){return new mg({check:"string_format",format:"starts_with",...D(t),prefix:e})}function Yp(e,t){return new fg({check:"string_format",format:"ends_with",...D(t),suffix:e})}function nt(e){return new bg({check:"overwrite",tx:e})}function Jp(e){return nt(t=>t.normalize(e))}function Qp(){return nt(e=>e.trim())}function Xp(){return nt(e=>e.toLowerCase())}function eh(){return nt(e=>e.toUpperCase())}function th(){return nt(e=>vd(e))}function ah(e,t,a){return new e({type:"array",element:t,...D(a)})}function nh(e,t,a){return new e({type:"custom",check:"custom",fn:t,...D(a)})}function rh(e){const t=ih(a=>(a.addIssue=n=>{if(typeof n=="string")a.issues.push(pt(n,a.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),a.issues.push(pt(r))}},e(a.value,a)));return t}function ih(e,t){const a=new he({check:"custom",...D(t)});return a._zod.check=e,a}function oh(e){const t=new he({check:"describe"});return t._zod.onattach=[a=>{const n=Me.get(a)??{};Me.add(a,{...n,description:e})}],t._zod.check=()=>{},t}function sh(e){const t=new he({check:"meta"});return t._zod.onattach=[a=>{const n=Me.get(a)??{};Me.add(a,{...n,...e})}],t._zod.check=()=>{},t}function Mr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??Me,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ge(e,t,a={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,a.schemaPath.includes(e)&&(i.cycle=a.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:a.path};t.seen.set(e,o);const s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{const l={...a,schemaPath:[...a.schemaPath,e],path:a.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const d=o.schema,h=t.processors[r.type];if(!h)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);h(e,t,d,l)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),ge(g,t,l),t.seen.get(g).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&ue(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function Br(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const s=e.metadataRegistry.get(o[0])?.id;if(s){const c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}const r=o=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(o[0])?.id,d=e.external.uri??(u=>u);if(g)return{ref:d(g)};const h=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=h,{defId:h,ref:`${d("__shared")}#/${s}/${h}`}}if(o[1]===a)return{ref:"#"};const c=`#/${s}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},i=o=>{if(o[1].schema.$ref)return;const s=o[1],{ref:c,defId:l}=r(o);s.def={...s.schema},l&&(s.defId=l);const g=s.schema;for(const d in g)delete g[d];g.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
|
|
175
175
|
|
|
176
|
-
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function Rr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),u=h.schema;if(u.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(u)):Object.assign(c,u),Object.assign(c,l),o._zod.parent===g)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(u.$ref&&h.def)for(const f in c)f==="$ref"||f==="allOf"||f in h.def&&JSON.stringify(c[f])===JSON.stringify(h.def[f])&&delete c[f]}const d=o._zod.parent;if(d&&d!==g){n(d);const h=e.seen.get(d);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const u in c)u==="$ref"||u==="allOf"||u in h.def&&JSON.stringify(c[u])===JSON.stringify(h.def[u])&&delete c[u]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:$t(t,"input",e.processors),output:$t(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ue(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ue(n.element,a);if(n.type==="set")return ue(n.valueType,a);if(n.type==="lazy")return ue(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ue(n.innerType,a);if(n.type==="intersection")return ue(n.left,a)||ue(n.right,a);if(n.type==="record"||n.type==="map")return ue(n.keyType,a)||ue(n.valueType,a);if(n.type==="pipe")return ue(n.in,a)||ue(n.out,a);if(n.type==="object"){for(const r in n.shape)if(ue(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ue(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ue(r,a))return!0;return!!(n.rest&&ue(n.rest,a))}return!1}var ch=(e,t={})=>a=>{const n=Mr({...a,processors:t});return ge(e,n),Br(n,e),Rr(n,e)},$t=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=Mr({...r??{},target:i,io:t,processors:a});return ge(e,o),Br(o,e),Rr(o,e)},lh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dh=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=lh[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},gh=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},ph=(e,t,a,n)=>{a.type="boolean"},hh=(e,t,a,n)=>{a.not={}},uh=(e,t,a,n)=>{},mh=(e,t,a,n)=>{const r=e._zod.def,i=Zn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},fh=(e,t,a,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];a.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[o]:a.const=o}else i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),i.every(o=>typeof o=="boolean")&&(a.type="boolean"),i.every(o=>o===null)&&(a.type="null"),a.enum=i},bh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yh=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=ge(i.element,t,{...n,path:[...n.path,"items"]})},_h=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=ge(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ge(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},xh=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ge(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},wh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ge(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},kh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Ch=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Sh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Eh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Th=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},Ph=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;ge(i,t,n);const o=t.seen.get(e);o.ref=i},Ah=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},Or=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Lh=S("ZodISODateTime",(e,t)=>{Ig.init(e,t),te.init(e,t)});function Ih(e){return Rp(Lh,e)}var Nh=S("ZodISODate",(e,t)=>{Ng.init(e,t),te.init(e,t)});function zh(e){return Op(Nh,e)}var Mh=S("ZodISOTime",(e,t)=>{zg.init(e,t),te.init(e,t)});function Bh(e){return Dp(Mh,e)}var Rh=S("ZodISODuration",(e,t)=>{Mg.init(e,t),te.init(e,t)});function Oh(e){return Fp(Rh,e)}var Dr=(e,t)=>{Qn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Id(e,a)},flatten:{value:a=>Ld(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,Ea,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,Ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},gf=S("ZodError",Dr),ke=S("ZodError",Dr,{Parent:Error}),Dh=Nt(ke),Fh=zt(ke),$h=Mt(ke),Uh=Bt(ke),Hh=Xn(ke),qh=er(ke),jh=tr(ke),Zh=ar(ke),Vh=nr(ke),Wh=rr(ke),Gh=ir(ke),Kh=or(ke),ne=S("ZodType",(e,t)=>(ae.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$t(e,"input"),output:$t(e,"output")}}),e.toJSONSchema=ch(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ue(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>He(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Dh(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>$h(e,a,n),e.parseAsync=async(a,n)=>Fh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Uh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Hh(e,a,n),e.decode=(a,n)=>qh(e,a,n),e.encodeAsync=async(a,n)=>jh(e,a,n),e.decodeAsync=async(a,n)=>Zh(e,a,n),e.safeEncode=(a,n)=>Vh(e,a,n),e.safeDecode=(a,n)=>Wh(e,a,n),e.safeEncodeAsync=async(a,n)=>Gh(e,a,n),e.safeDecodeAsync=async(a,n)=>Kh(e,a,n),e.refine=(a,n)=>e.check(ju(a,n)),e.superRefine=a=>e.check(Zu(a)),e.overwrite=a=>e.check(nt(a)),e.optional=()=>Vr(e),e.exactOptional=()=>Iu(e),e.nullable=()=>Wr(e),e.nullish=()=>Vr(Wr(e)),e.nonoptional=a=>Ou(e,a),e.array=()=>_u(e),e.or=a=>ku([e,a]),e.and=a=>Su(e,a),e.transform=a=>Kr(e,Au(a)),e.default=a=>Mu(e,a),e.prefault=a=>Ru(e,a),e.catch=a=>Fu(e,a),e.pipe=a=>Kr(e,a),e.readonly=()=>Hu(e),e.describe=a=>{const n=e.clone();return Me.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return Me.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return Me.get(e);const n=e.clone();return Me.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Fr=S("_ZodString",(e,t)=>{Ia.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dh(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(Zp(...n)),e.includes=(...n)=>e.check(Gp(...n)),e.startsWith=(...n)=>e.check(Kp(...n)),e.endsWith=(...n)=>e.check(Yp(...n)),e.min=(...n)=>e.check(Ft(...n)),e.max=(...n)=>e.check(Nr(...n)),e.length=(...n)=>e.check(zr(...n)),e.nonempty=(...n)=>e.check(Ft(1,...n)),e.lowercase=n=>e.check(Vp(n)),e.uppercase=n=>e.check(Wp(n)),e.trim=()=>e.check(Qp()),e.normalize=(...n)=>e.check(Jp(...n)),e.toLowerCase=()=>e.check(Xp()),e.toUpperCase=()=>e.check(eh()),e.slugify=()=>e.check(th())}),Yh=S("ZodString",(e,t)=>{Ia.init(e,t),Fr.init(e,t),e.email=a=>e.check(mp(Jh,a)),e.url=a=>e.check(_p(Qh,a)),e.jwt=a=>e.check(Bp(hu,a)),e.emoji=a=>e.check(xp(Xh,a)),e.guid=a=>e.check(Pr($r,a)),e.uuid=a=>e.check(fp(Ut,a)),e.uuidv4=a=>e.check(bp(Ut,a)),e.uuidv6=a=>e.check(vp(Ut,a)),e.uuidv7=a=>e.check(yp(Ut,a)),e.nanoid=a=>e.check(wp(eu,a)),e.guid=a=>e.check(Pr($r,a)),e.cuid=a=>e.check(kp(tu,a)),e.cuid2=a=>e.check(Cp(au,a)),e.ulid=a=>e.check(Sp(nu,a)),e.base64=a=>e.check(Np(du,a)),e.base64url=a=>e.check(zp(gu,a)),e.xid=a=>e.check(Ep(ru,a)),e.ksuid=a=>e.check(Tp(iu,a)),e.ipv4=a=>e.check(Pp(ou,a)),e.ipv6=a=>e.check(Ap(su,a)),e.cidrv4=a=>e.check(Lp(cu,a)),e.cidrv6=a=>e.check(Ip(lu,a)),e.e164=a=>e.check(Mp(pu,a)),e.datetime=a=>e.check(Ih(a)),e.date=a=>e.check(zh(a)),e.time=a=>e.check(Bh(a)),e.duration=a=>e.check(Oh(a))});function Ce(e){return up(Yh,e)}var te=S("ZodStringFormat",(e,t)=>{ee.init(e,t),Fr.init(e,t)}),Jh=S("ZodEmail",(e,t)=>{wg.init(e,t),te.init(e,t)}),$r=S("ZodGUID",(e,t)=>{_g.init(e,t),te.init(e,t)}),Ut=S("ZodUUID",(e,t)=>{xg.init(e,t),te.init(e,t)}),Qh=S("ZodURL",(e,t)=>{kg.init(e,t),te.init(e,t)}),Xh=S("ZodEmoji",(e,t)=>{Cg.init(e,t),te.init(e,t)}),eu=S("ZodNanoID",(e,t)=>{Sg.init(e,t),te.init(e,t)}),tu=S("ZodCUID",(e,t)=>{Eg.init(e,t),te.init(e,t)}),au=S("ZodCUID2",(e,t)=>{Tg.init(e,t),te.init(e,t)}),nu=S("ZodULID",(e,t)=>{Pg.init(e,t),te.init(e,t)}),ru=S("ZodXID",(e,t)=>{Ag.init(e,t),te.init(e,t)}),iu=S("ZodKSUID",(e,t)=>{Lg.init(e,t),te.init(e,t)}),ou=S("ZodIPv4",(e,t)=>{Bg.init(e,t),te.init(e,t)}),su=S("ZodIPv6",(e,t)=>{Rg.init(e,t),te.init(e,t)}),cu=S("ZodCIDRv4",(e,t)=>{Og.init(e,t),te.init(e,t)}),lu=S("ZodCIDRv6",(e,t)=>{Dg.init(e,t),te.init(e,t)}),du=S("ZodBase64",(e,t)=>{Fg.init(e,t),te.init(e,t)}),gu=S("ZodBase64URL",(e,t)=>{Ug.init(e,t),te.init(e,t)}),pu=S("ZodE164",(e,t)=>{Hg.init(e,t),te.init(e,t)}),hu=S("ZodJWT",(e,t)=>{jg.init(e,t),te.init(e,t)}),Ur=S("ZodNumber",(e,t)=>{mr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gh(e,n,r,i),e.gt=(n,r)=>e.check(Lr(n,r)),e.gte=(n,r)=>e.check(Ma(n,r)),e.min=(n,r)=>e.check(Ma(n,r)),e.lt=(n,r)=>e.check(Ar(n,r)),e.lte=(n,r)=>e.check(za(n,r)),e.max=(n,r)=>e.check(za(n,r)),e.int=n=>e.check(qr(n)),e.safe=n=>e.check(qr(n)),e.positive=n=>e.check(Lr(0,n)),e.nonnegative=n=>e.check(Ma(0,n)),e.negative=n=>e.check(Ar(0,n)),e.nonpositive=n=>e.check(za(0,n)),e.multipleOf=(n,r)=>e.check(Ir(n,r)),e.step=(n,r)=>e.check(Ir(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Hr(e){return $p(Ur,e)}var uu=S("ZodNumberFormat",(e,t)=>{Zg.init(e,t),Ur.init(e,t)});function qr(e){return Up(uu,e)}var mu=S("ZodBoolean",(e,t)=>{Vg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ph(e,a,n,r)});function We(e){return Hp(mu,e)}var fu=S("ZodUnknown",(e,t)=>{Wg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>uh(e,a,n,r)});function jr(){return qp(fu)}var bu=S("ZodNever",(e,t)=>{Gg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>hh(e,a,n,r)});function vu(e){return jp(bu,e)}var yu=S("ZodArray",(e,t)=>{Kg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>yh(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ft(a,n)),e.nonempty=a=>e.check(Ft(1,a)),e.max=(a,n)=>e.check(Nr(a,n)),e.length=(a,n)=>e.check(zr(a,n)),e.unwrap=()=>e.element});function _u(e,t){return ah(yu,e,t)}var xu=S("ZodObject",(e,t)=>{Jg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>_h(e,a,n,r),Y(e,"shape",()=>t.shape),e.keyof=()=>Ra(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:jr()}),e.loose=()=>e.clone({...e._zod.def,catchall:jr()}),e.strict=()=>e.clone({...e._zod.def,catchall:vu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Sd(e,a),e.safeExtend=a=>Ed(e,a),e.merge=a=>Td(e,a),e.pick=a=>kd(e,a),e.omit=a=>Cd(e,a),e.partial=(...a)=>Pd(Zr,e,a[0]),e.required=(...a)=>Ad(Gr,e,a[0])});function Be(e,t){return new xu({type:"object",shape:e??{},...D(t)})}var wu=S("ZodUnion",(e,t)=>{Qg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>xh(e,a,n,r),e.options=t.options});function ku(e,t){return new wu({type:"union",options:e,...D(t)})}var Cu=S("ZodIntersection",(e,t)=>{Xg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wh(e,a,n,r)});function Su(e,t){return new Cu({type:"intersection",left:e,right:t})}var Ba=S("ZodEnum",(e,t)=>{ep.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mh(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})}});function Ra(e,t){return new Ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...D(t)})}var Eu=S("ZodLiteral",(e,t)=>{tp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>fh(e,a,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Tu(e,t){return new Eu({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}var Pu=S("ZodTransform",(e,t)=>{ap.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>vh(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(pt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(pt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Au(e){return new Pu({type:"transform",transform:e})}var Zr=S("ZodOptional",(e,t)=>{wr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Vr(e){return new Zr({type:"optional",innerType:e})}var Lu=S("ZodExactOptional",(e,t)=>{np.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Lu({type:"optional",innerType:e})}var Nu=S("ZodNullable",(e,t)=>{rp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Wr(e){return new Nu({type:"nullable",innerType:e})}var zu=S("ZodDefault",(e,t)=>{ip.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Sh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mu(e,t){return new zu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Bu=S("ZodPrefault",(e,t)=>{op.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ru(e,t){return new Bu({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Gr=S("ZodNonOptional",(e,t)=>{sp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ch(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ou(e,t){return new Gr({type:"nonoptional",innerType:e,...D(t)})}var Du=S("ZodCatch",(e,t)=>{cp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fu(e,t){return new Du({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $u=S("ZodPipe",(e,t)=>{lp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ph(e,a,n,r),e.in=t.in,e.out=t.out});function Kr(e,t){return new $u({type:"pipe",in:e,out:t})}var Uu=S("ZodReadonly",(e,t)=>{dp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ah(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Hu(e){return new Uu({type:"readonly",innerType:e})}var qu=S("ZodCustom",(e,t)=>{gp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>bh(e,a,n,r)});function ju(e,t={}){return nh(qu,e,t)}function Zu(e){return rh(e)}var pf=oh,hf=sh;function Yr(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Oa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Vu=class it extends ft{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=ca,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new Zl,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new Gs}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const p=Wl(t.pillLauncher);t.launcherImageUrl=p.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>p.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=id,this._shadow.appendChild(a);const n=this.root,r=(p,m)=>{m&&Yr(m)&&n.style.setProperty(p,m)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[p,m]of Object.entries(t.theme))p.startsWith("--")&&typeof m=="string"&&r(p,m);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const p=document.createElement("div");p.className="gengage-chat-backdrop",p.setAttribute("aria-hidden","true"),p.setAttribute("role","button"),p.setAttribute("tabindex","-1"),p.setAttribute("aria-label",this._i18n.closeAriaLabel),p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),this.close()}),this._backdropEl=p,i.prepend(p)}if(o==="floating"){const p={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?p.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(p.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(p.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(p.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(p.tooltip=t.launcherTooltip),this._launcher=tc(p),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new qs(s,{i18n:this._i18n,onSend:(p,m)=>this._sendMessage(p,m),onClose:()=>this.close(),onAttachment:p=>this._handleAttachment(p),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:p=>this._handleRollback(p),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(pd(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:p=>{p==="close"?this.close():(this._openState=p,this._applyOpenStateClasses())},onThumbnailClick:p=>this._rollbackToThread(p),onLinkClick:p=>{this._saveSessionAndOpenURL(p)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:p=>{this._presentation.pinnedToBottom=p},onUserInteractingChange:p=>{this._presentation.userInteracting=p},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Hl({onChange:p=>this._panel?.notifyExtension(p),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new ql({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:p=>this._rollbackToThread(p)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),d=sessionStorage.getItem("gengage_restore_sku"),h=!!(g&&d);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const p=new $l;await p.open(),this._session=new Dn(p),await this._restoreFromIndexedDB(h)}catch{this._session=new Dn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const u=()=>this._syncViewportState();if(window.addEventListener("resize",u,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",u)),window.visualViewport){const p=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const m=this._drawer?.getElement();if(!m)return;const b=window.innerHeight-(window.visualViewport?.height??window.innerHeight);m.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,b)}px`)};window.visualViewport.addEventListener("resize",p),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",p))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const f={namespace:"chat",onMessage:p=>this._handleBridgeMessage(p)};t.allowedOrigins!==void 0&&(f.allowedOrigins=t.allowedOrigins),this._bridge=new po(f),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const p of this._pendingActions)this._sendAction(p.action,p.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),ce("gengage:chat:ready",{}),Pt("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),ce("gengage:chat:open",{state:this._openState}),At("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),ce("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),ws(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${CSS.escape(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=Vl(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=Oa(n)?n:Oa(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),Oa(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Yr(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ja(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!0})}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=_o(t);if(!a.ok){ce("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(wa(this.config.accountId),this._drawer?.hideKvkkBanner()),ud(),this._messages.some(r=>r.role==="user")||md(),Le("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Bl(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const _=this._currentThreadId,y=this._messages.filter(x=>x.threadId!==void 0&&x.threadId>_);this._messages=this._messages.filter(x=>!x.threadId||x.threadId<=_);for(const x of y)this._shadow?.querySelector(`[data-message-id="${CSS.escape(x.id)}"]`)?.remove(),this._panel.snapshots.delete(x.id),this._panel.snapshotTypes.delete(x.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(x=>{x instanceof HTMLElement&&x.dataset.threadId&&x.dataset.threadId>_&&x.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ja();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const _=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,y=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(y!==void 0&&y.role==="user"&&y.content===_)){const x=this._createMessage("user",_);x.threadId=n,a?.attachment!==void 0&&(x.attachment=a.attachment),this._drawer?.addMessage(x),this._messages.push(x)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const _=this._i18n.productNotFoundMessage,y=this._createMessage("assistant",_);y.threadId=n,y.status="done",this._messages.push(y),this._ensureAssistantMessageRendered(y),this._drawer?.updateBotMessage(y.id,_),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",y),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const _=this._buildRenderContext(),y=this._renderPanelFromSource(o,_);this._drawer.setPanelContent(y),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const h={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(h.attachment=a.attachment);const u=this._getVisibleMessages().filter(_=>_!==d&&(_.content||_.role==="assistant")).slice(-50).map(_=>({role:_.role==="user"?"user":"model",content:_.content??""})),f={outputLanguage:rd(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:$n(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(f.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(f.viewId=this.config.session.viewId);const p=bs(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),m={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:p.type,locale:this.config.locale??"tr",meta:f,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(m.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(m.view_id=this.config.session.viewId),p.payload!==void 0&&(m.payload=p.payload),this.config.pageContext?.sku!==void 0&&(m.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(m.page_type=this.config.pageContext.pageType);const b=crypto.randomUUID(),C=Date.now();let v=0,w=!1,k=!1,A=!1,B=!1,I=!1;const H=Ks();let Q=null;const K=()=>{if(this._drawer){if(this._isMobileViewport||!A){this._drawer.setPanelAiZoneState("hidden");return}B||(I?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(Qt(this.analyticsContext(),{endpoint:"process_action",request_id:b,widget:"chat"}));let N=null;if(N=_s(m,{onTextChunk:(_,y,x)=>{if(!r&&n!==this._activeRequestThreadId||(g+=_,this._drawer?.removeTypingIndicator(),x?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...x.skuToProductItem}),x?.conversationMode&&(this._conversationMode=x.conversationMode),x?.renderHint&&(d.renderHint=x.renderHint),this.track(zi(this.analyticsContext(),{request_id:b,chunk_index:v++,widget:"chat"})),!this._drawer))return;let E=g;const L=x?.kvkk===!0||xa(E);if(y&&L){const R=this.config.accountId;if(!$n(R)){const P=ad(E);P?this._drawer?.showKvkkBanner(P,()=>{this._drawer?.hideKvkkBanner(),wa(R)}):wa(R)}E=td(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=_e(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),y)if(d.content=E,d.status="done",qn(),Js(d))this._drawer?.updateBotMessage(d.id,E,"photo_analysis",d.photoAnalysis);else{const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R){this._activeTypewriter?.cancel();const P=x?.productMentions;this._activeTypewriter=Pl({container:R,html:_e(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,P&&P.length>0&&R&&Al({container:R,mentions:P,onProductClick:$=>{this._sendAction({title:P.find(F=>F.sku===$)?.short_name??$,type:"launchSingleProduct",payload:{sku:$}})}})}})}}},onUISpec:(_,y,x,E)=>{if(!r&&n!==this._activeRequestThreadId||y!=="chat")return;E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const L=_.elements[_.root],z=L?.type??"unknown";if(Ys(z,L?.props??{},H,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:I},d))return;const R=z==="ProductGrid"&&L?.props?.similarsAppend===!0,P=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||R);P&&!E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const $=z==="ProductDetailsPanel"&&x!=="panel"?"panel":x;this.track(Mi(this.analyticsContext(),{request_id:b,chunk_index:v,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const U=L?.props?.products;dd(Array.isArray(U)?U.length:0)}if(z==="ProductGrid"){const U=L?.children?.length??0;hd(void 0,U)}const V=$==="panel"&&this._panel?this._panel.toPanelSpec(_):_;if($==="panel"&&this._panel&&!P){const U=!k;k=!0;const M=jl({componentType:z,similarsAppend:L?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:U});F.panelProductListHeading=void 0,z==="ProductGrid"&&(M==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:V})),M==="appendSimilars"?this._appendSimilarsToPanel(V,F):M==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(V,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(V,F)),this._currentPanelSource={kind:"spec",spec:V},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const G=this._panel.currentType??z,O=L?.props?.panelTitle;if(this._panel.updateTopBar(G,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(A=!this._isMobileViewport,Q){const re=this._buildRenderContext();re.isStreaming=!0;const Gt=this._renderUISpec(Q,re);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Gt}),Q=null}}else M!=="appendSimilars"&&M!=="append"&&(A=!1,Q=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&$==="panel"&&(!d.silent||i)){const U=L?.props?.product;if(U){const M={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:U}}}},G=this._shadow?.querySelector(".gengage-chat-messages");if(G){const O=this._renderUISpec(M,F);d.threadId&&(O.dataset.threadId=d.threadId);const re=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);re&&re.parentNode===G?re.after(O):G.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),k=!0}}}const J=z==="AITopPicks"||z==="AIGroupingCards";let X=!1,oe=!1;if(P&&R&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),J&&!this._isMobileViewport&&!d.silent)if(A){const U=this._renderUISpec(_,F);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:U}),X=!0,Q=null}else Q=_,oe=!0;const j=i&&z==="GroundingReviewCard";if((!d.silent||j)&&($!=="panel"||z==="ProductCard"||P&&z==="ProductGrid"&&(!R||this._isMobileViewport))&&z!=="ActionButtons"&&!X&&!(oe&&J)){const U=this._shadow?.querySelector(".gengage-chat-messages");if(U){const M=this._renderUISpec(_,F);d.threadId&&(M.dataset.threadId=d.threadId),U.appendChild(M),M.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),P&&z==="ProductGrid"&&(k=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const U=L?.children??[],M=z==="ProductGrid"?U.map(G=>_.elements[G]?.props?.product).filter(Boolean):[L?.props?.product].filter(Boolean);for(const G of M){const O=G.sku,re=G.imageUrl;O&&re&&this._thumbnailEntries.push({sku:O,imageUrl:re,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const U=(z==="ProductGrid"?(L?.children??[]).map(M=>_.elements[M]?.props?.product).filter(Boolean):[L?.props?.product??L?.props].filter(Boolean)).map(M=>M.imageUrl).filter(M=>typeof M=="string").slice(0,5);U.length>0&&this._bridge?.send("previewImages",{images:U})}const be=L?.children?.length??0;if(z==="ProductGrid"&&$==="panel"&&!P&&be>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!Rl(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(M=>M.remove()),this._choicePrompterEl=Ml({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const U=this._shadow?.querySelector(".gengage-chat-panel-float");if(U){if(U.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const M=this._choicePrompterEl,G=()=>{window.visualViewport.height/window.innerHeight<.75&&(M.remove(),this._choicePrompterEl===M&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",G))};window.visualViewport.addEventListener("resize",G)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const U=L?.props?.buttons;if(U&&U.length>0){const M=[],G=[];for(const O of U)if(Nl(O)){const re={label:O.label,action:O.action};O.icon&&(re.icon=O.icon),M.push(re)}else G.push(O);M.length>0&&this._drawer?.setInputAreaChips(M.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),G.length>0&&this._drawer?.setPills(G.map(O=>{const re={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(re.icon=O.icon),O.image&&(re.image=O.image),O.description&&(re.description=O.description),re}))}}K(),d.uiSpec=_},onAction:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="action"){const y={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(y.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(y.allowScriptCall=this.config.actionHandling.allowScriptCall),fo(_,{openChat:()=>this.open(),navigate:x=>{pe(x.url)&&(this._bridge?.send("navigate",x),x.newTab?window.open(x.url,"_blank","noopener,noreferrer"):window.location.href=x.url)},saveSession:x=>this.saveSession(x.sessionId,x.sku),addToCart:x=>{ce("gengage:similar:add-to-cart",x)},scriptCall:x=>{ce("gengage:chat:script-call",x),this.config.onScriptCall?.(x)}},y)}},onMetadata:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="metadata"&&_.meta){if(_.meta.panel!==void 0||_.meta.messages!==void 0||_.meta.message_id!==void 0){this._lastBackendContext=_.meta;const x=ga(_.meta.panel);x&&(this._modeController.updateFromContext(x),this._applyUiHints())}if(_.meta.panelLoading){const x=typeof _.meta.panelPendingType=="string"?_.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(x==="productDetails"||x==="productDetailsSimilars")||(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(x),x&&this._panel?.updateTopBarForLoading(x))}if(_.meta.voice){const x=new CustomEvent("gengage:chat:voice",{detail:{payload:_.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(x);if(fd(),E){const L=_.meta.voice;L.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=nc(L.audio_base64,L.content_type??"audio/ogg"))}}if((_.meta.redirectTarget||_.meta.redirect)&&(ce("gengage:chat:redirect",{target:_.meta.redirectTarget??null,payload:_.meta.redirect??null}),Le("redirect","redirect dispatched",{target:_.meta.redirectTarget??null}),this._handleRedirectMetadata(_.meta.redirect)),_.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),_.meta.loading){const x=Array.isArray(_.meta.thinkingMessages)?_.meta.thinkingMessages.filter(L=>typeof L=="string"):[],E=typeof _.meta.loadingText=="string"?_.meta.loadingText:void 0;if(x.length>0){const L=E&&this._modeController.shouldCondenseThinking()?[...x.slice(0,2),E]:x;this._drawer?.setThinkingSteps(L)}typeof E=="string"&&E.length>0&&(this._drawer?.addThinkingStep(E),this._bridge?.send("loadingMessage",{text:E}))}_.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",_.meta.visitorDataResponse),_.meta.formType&&this._bridge?.send("glovOtokoc",{type:_.meta.formType,data:_.meta.formPayload}),_.meta.launcherContent&&this._bridge?.send("launcherContent",_.meta.launcherContent),ce("gengage:chat:metadata",{payload:_.meta});const y=_.meta;typeof y.prompt_tokens=="number"&&typeof y.completion_tokens=="number"&&this.track(Bi(this.analyticsContext(),{model:_.model??"unknown",prompt_tokens:y.prompt_tokens,completion_tokens:y.completion_tokens,total_tokens:y.total_tokens??y.prompt_tokens+y.completion_tokens}))}},onError:_=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;I=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,K(),Q=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),Xs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const y=k;w&&!k&&l(),w=!1,k=!1;const x=d.silent||d.content!=null&&d.content.length>0||g.length>0||y,E=typeof navigator<"u"&&navigator.onLine===!1&&na(_),L=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const P=this._messages.indexOf(d);P>=0&&this._messages.splice(P,1)};let z=!1;const R=()=>{if(E)return;this.emit("error",_);const P=_.message;P===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=P);const $=_.message.trim(),F=$.length>0?$:this._i18n.errorMessage,V={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){L(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,V);return}if(Ql(_,F)){L(),z=!0,this._drawer?.showErrorWithRecovery(F,V);return}d.content=F,d.status="done";const J=_e(F.replace(/\r\n/g,`
|
|
176
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function Rr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const h=e.seen.get(g),u=h.schema;if(u.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(u)):Object.assign(c,u),Object.assign(c,l),o._zod.parent===g)for(const f in c)f==="$ref"||f==="allOf"||f in l||delete c[f];if(u.$ref&&h.def)for(const f in c)f==="$ref"||f==="allOf"||f in h.def&&JSON.stringify(c[f])===JSON.stringify(h.def[f])&&delete c[f]}const d=o._zod.parent;if(d&&d!==g){n(d);const h=e.seen.get(d);if(h?.schema.$ref&&(c.$ref=h.schema.$ref,h.def))for(const u in c)u==="$ref"||u==="allOf"||u in h.def&&JSON.stringify(c[u])===JSON.stringify(h.def[u])&&delete c[u]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:$t(t,"input",e.processors),output:$t(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function ue(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ue(n.element,a);if(n.type==="set")return ue(n.valueType,a);if(n.type==="lazy")return ue(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return ue(n.innerType,a);if(n.type==="intersection")return ue(n.left,a)||ue(n.right,a);if(n.type==="record"||n.type==="map")return ue(n.keyType,a)||ue(n.valueType,a);if(n.type==="pipe")return ue(n.in,a)||ue(n.out,a);if(n.type==="object"){for(const r in n.shape)if(ue(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(ue(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(ue(r,a))return!0;return!!(n.rest&&ue(n.rest,a))}return!1}var ch=(e,t={})=>a=>{const n=Mr({...a,processors:t});return ge(e,n),Br(n,e),Rr(n,e)},$t=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=Mr({...r??{},target:i,io:t,processors:a});return ge(e,o),Br(o,e),Rr(o,e)},lh={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dh=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=lh[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},gh=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},ph=(e,t,a,n)=>{a.type="boolean"},hh=(e,t,a,n)=>{a.not={}},uh=(e,t,a,n)=>{},mh=(e,t,a,n)=>{const r=e._zod.def,i=Zn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},fh=(e,t,a,n)=>{const r=e._zod.def,i=[];for(const o of r.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(o))}else i.push(o);if(i.length!==0)if(i.length===1){const o=i[0];a.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?a.enum=[o]:a.const=o}else i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),i.every(o=>typeof o=="boolean")&&(a.type="boolean"),i.every(o=>o===null)&&(a.type="null"),a.enum=i},bh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vh=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yh=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=ge(i.element,t,{...n,path:[...n.path,"items"]})},_h=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=ge(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ge(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},xh=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ge(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},wh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ge(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},kh=(e,t,a,n)=>{const r=e._zod.def,i=ge(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Ch=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Sh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Eh=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Th=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},Ph=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;ge(i,t,n);const o=t.seen.get(e);o.ref=i},Ah=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},Or=(e,t,a,n)=>{const r=e._zod.def;ge(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Lh=S("ZodISODateTime",(e,t)=>{Ig.init(e,t),te.init(e,t)});function Ih(e){return Rp(Lh,e)}var Nh=S("ZodISODate",(e,t)=>{Ng.init(e,t),te.init(e,t)});function zh(e){return Op(Nh,e)}var Mh=S("ZodISOTime",(e,t)=>{zg.init(e,t),te.init(e,t)});function Bh(e){return Dp(Mh,e)}var Rh=S("ZodISODuration",(e,t)=>{Mg.init(e,t),te.init(e,t)});function Oh(e){return Fp(Rh,e)}var Dr=(e,t)=>{Qn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Id(e,a)},flatten:{value:a=>Ld(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,Ea,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,Ea,2)}},isEmpty:{get(){return e.issues.length===0}}})},gf=S("ZodError",Dr),ke=S("ZodError",Dr,{Parent:Error}),Dh=Nt(ke),Fh=zt(ke),$h=Mt(ke),Uh=Bt(ke),Hh=Xn(ke),qh=er(ke),jh=tr(ke),Zh=ar(ke),Vh=nr(ke),Wh=rr(ke),Gh=ir(ke),Kh=or(ke),ne=S("ZodType",(e,t)=>(ae.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:$t(e,"input"),output:$t(e,"output")}}),e.toJSONSchema=ch(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ue(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>He(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Dh(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>$h(e,a,n),e.parseAsync=async(a,n)=>Fh(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Uh(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Hh(e,a,n),e.decode=(a,n)=>qh(e,a,n),e.encodeAsync=async(a,n)=>jh(e,a,n),e.decodeAsync=async(a,n)=>Zh(e,a,n),e.safeEncode=(a,n)=>Vh(e,a,n),e.safeDecode=(a,n)=>Wh(e,a,n),e.safeEncodeAsync=async(a,n)=>Gh(e,a,n),e.safeDecodeAsync=async(a,n)=>Kh(e,a,n),e.refine=(a,n)=>e.check(ju(a,n)),e.superRefine=a=>e.check(Zu(a)),e.overwrite=a=>e.check(nt(a)),e.optional=()=>Vr(e),e.exactOptional=()=>Iu(e),e.nullable=()=>Wr(e),e.nullish=()=>Vr(Wr(e)),e.nonoptional=a=>Ou(e,a),e.array=()=>_u(e),e.or=a=>ku([e,a]),e.and=a=>Su(e,a),e.transform=a=>Kr(e,Au(a)),e.default=a=>Mu(e,a),e.prefault=a=>Ru(e,a),e.catch=a=>Fu(e,a),e.pipe=a=>Kr(e,a),e.readonly=()=>Hu(e),e.describe=a=>{const n=e.clone();return Me.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return Me.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return Me.get(e);const n=e.clone();return Me.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),Fr=S("_ZodString",(e,t)=>{Ia.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dh(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(Zp(...n)),e.includes=(...n)=>e.check(Gp(...n)),e.startsWith=(...n)=>e.check(Kp(...n)),e.endsWith=(...n)=>e.check(Yp(...n)),e.min=(...n)=>e.check(Ft(...n)),e.max=(...n)=>e.check(Nr(...n)),e.length=(...n)=>e.check(zr(...n)),e.nonempty=(...n)=>e.check(Ft(1,...n)),e.lowercase=n=>e.check(Vp(n)),e.uppercase=n=>e.check(Wp(n)),e.trim=()=>e.check(Qp()),e.normalize=(...n)=>e.check(Jp(...n)),e.toLowerCase=()=>e.check(Xp()),e.toUpperCase=()=>e.check(eh()),e.slugify=()=>e.check(th())}),Yh=S("ZodString",(e,t)=>{Ia.init(e,t),Fr.init(e,t),e.email=a=>e.check(mp(Jh,a)),e.url=a=>e.check(_p(Qh,a)),e.jwt=a=>e.check(Bp(hu,a)),e.emoji=a=>e.check(xp(Xh,a)),e.guid=a=>e.check(Pr($r,a)),e.uuid=a=>e.check(fp(Ut,a)),e.uuidv4=a=>e.check(bp(Ut,a)),e.uuidv6=a=>e.check(vp(Ut,a)),e.uuidv7=a=>e.check(yp(Ut,a)),e.nanoid=a=>e.check(wp(eu,a)),e.guid=a=>e.check(Pr($r,a)),e.cuid=a=>e.check(kp(tu,a)),e.cuid2=a=>e.check(Cp(au,a)),e.ulid=a=>e.check(Sp(nu,a)),e.base64=a=>e.check(Np(du,a)),e.base64url=a=>e.check(zp(gu,a)),e.xid=a=>e.check(Ep(ru,a)),e.ksuid=a=>e.check(Tp(iu,a)),e.ipv4=a=>e.check(Pp(ou,a)),e.ipv6=a=>e.check(Ap(su,a)),e.cidrv4=a=>e.check(Lp(cu,a)),e.cidrv6=a=>e.check(Ip(lu,a)),e.e164=a=>e.check(Mp(pu,a)),e.datetime=a=>e.check(Ih(a)),e.date=a=>e.check(zh(a)),e.time=a=>e.check(Bh(a)),e.duration=a=>e.check(Oh(a))});function Ce(e){return up(Yh,e)}var te=S("ZodStringFormat",(e,t)=>{ee.init(e,t),Fr.init(e,t)}),Jh=S("ZodEmail",(e,t)=>{wg.init(e,t),te.init(e,t)}),$r=S("ZodGUID",(e,t)=>{_g.init(e,t),te.init(e,t)}),Ut=S("ZodUUID",(e,t)=>{xg.init(e,t),te.init(e,t)}),Qh=S("ZodURL",(e,t)=>{kg.init(e,t),te.init(e,t)}),Xh=S("ZodEmoji",(e,t)=>{Cg.init(e,t),te.init(e,t)}),eu=S("ZodNanoID",(e,t)=>{Sg.init(e,t),te.init(e,t)}),tu=S("ZodCUID",(e,t)=>{Eg.init(e,t),te.init(e,t)}),au=S("ZodCUID2",(e,t)=>{Tg.init(e,t),te.init(e,t)}),nu=S("ZodULID",(e,t)=>{Pg.init(e,t),te.init(e,t)}),ru=S("ZodXID",(e,t)=>{Ag.init(e,t),te.init(e,t)}),iu=S("ZodKSUID",(e,t)=>{Lg.init(e,t),te.init(e,t)}),ou=S("ZodIPv4",(e,t)=>{Bg.init(e,t),te.init(e,t)}),su=S("ZodIPv6",(e,t)=>{Rg.init(e,t),te.init(e,t)}),cu=S("ZodCIDRv4",(e,t)=>{Og.init(e,t),te.init(e,t)}),lu=S("ZodCIDRv6",(e,t)=>{Dg.init(e,t),te.init(e,t)}),du=S("ZodBase64",(e,t)=>{Fg.init(e,t),te.init(e,t)}),gu=S("ZodBase64URL",(e,t)=>{Ug.init(e,t),te.init(e,t)}),pu=S("ZodE164",(e,t)=>{Hg.init(e,t),te.init(e,t)}),hu=S("ZodJWT",(e,t)=>{jg.init(e,t),te.init(e,t)}),Ur=S("ZodNumber",(e,t)=>{mr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gh(e,n,r,i),e.gt=(n,r)=>e.check(Lr(n,r)),e.gte=(n,r)=>e.check(Ma(n,r)),e.min=(n,r)=>e.check(Ma(n,r)),e.lt=(n,r)=>e.check(Ar(n,r)),e.lte=(n,r)=>e.check(za(n,r)),e.max=(n,r)=>e.check(za(n,r)),e.int=n=>e.check(qr(n)),e.safe=n=>e.check(qr(n)),e.positive=n=>e.check(Lr(0,n)),e.nonnegative=n=>e.check(Ma(0,n)),e.negative=n=>e.check(Ar(0,n)),e.nonpositive=n=>e.check(za(0,n)),e.multipleOf=(n,r)=>e.check(Ir(n,r)),e.step=(n,r)=>e.check(Ir(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Hr(e){return $p(Ur,e)}var uu=S("ZodNumberFormat",(e,t)=>{Zg.init(e,t),Ur.init(e,t)});function qr(e){return Up(uu,e)}var mu=S("ZodBoolean",(e,t)=>{Vg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>ph(e,a,n,r)});function We(e){return Hp(mu,e)}var fu=S("ZodUnknown",(e,t)=>{Wg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>uh(e,a,n,r)});function jr(){return qp(fu)}var bu=S("ZodNever",(e,t)=>{Gg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>hh(e,a,n,r)});function vu(e){return jp(bu,e)}var yu=S("ZodArray",(e,t)=>{Kg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>yh(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Ft(a,n)),e.nonempty=a=>e.check(Ft(1,a)),e.max=(a,n)=>e.check(Nr(a,n)),e.length=(a,n)=>e.check(zr(a,n)),e.unwrap=()=>e.element});function _u(e,t){return ah(yu,e,t)}var xu=S("ZodObject",(e,t)=>{Jg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>_h(e,a,n,r),Y(e,"shape",()=>t.shape),e.keyof=()=>Ra(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:jr()}),e.loose=()=>e.clone({...e._zod.def,catchall:jr()}),e.strict=()=>e.clone({...e._zod.def,catchall:vu()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Sd(e,a),e.safeExtend=a=>Ed(e,a),e.merge=a=>Td(e,a),e.pick=a=>kd(e,a),e.omit=a=>Cd(e,a),e.partial=(...a)=>Pd(Zr,e,a[0]),e.required=(...a)=>Ad(Gr,e,a[0])});function Be(e,t){return new xu({type:"object",shape:e??{},...D(t)})}var wu=S("ZodUnion",(e,t)=>{Qg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>xh(e,a,n,r),e.options=t.options});function ku(e,t){return new wu({type:"union",options:e,...D(t)})}var Cu=S("ZodIntersection",(e,t)=>{Xg.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wh(e,a,n,r)});function Su(e,t){return new Cu({type:"intersection",left:e,right:t})}var Ba=S("ZodEnum",(e,t)=>{ep.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mh(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new Ba({...t,checks:[],...D(r),entries:i})}});function Ra(e,t){return new Ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...D(t)})}var Eu=S("ZodLiteral",(e,t)=>{tp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>fh(e,a,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Tu(e,t){return new Eu({type:"literal",values:Array.isArray(e)?e:[e],...D(t)})}var Pu=S("ZodTransform",(e,t)=>{ap.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>vh(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new jn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(pt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(pt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Au(e){return new Pu({type:"transform",transform:e})}var Zr=S("ZodOptional",(e,t)=>{wr.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Vr(e){return new Zr({type:"optional",innerType:e})}var Lu=S("ZodExactOptional",(e,t)=>{np.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Or(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Iu(e){return new Lu({type:"optional",innerType:e})}var Nu=S("ZodNullable",(e,t)=>{rp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Wr(e){return new Nu({type:"nullable",innerType:e})}var zu=S("ZodDefault",(e,t)=>{ip.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Sh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Mu(e,t){return new zu({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Bu=S("ZodPrefault",(e,t)=>{op.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Eh(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ru(e,t){return new Bu({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Kn(t)}})}var Gr=S("ZodNonOptional",(e,t)=>{sp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ch(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Ou(e,t){return new Gr({type:"nonoptional",innerType:e,...D(t)})}var Du=S("ZodCatch",(e,t)=>{cp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Th(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fu(e,t){return new Du({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var $u=S("ZodPipe",(e,t)=>{lp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ph(e,a,n,r),e.in=t.in,e.out=t.out});function Kr(e,t){return new $u({type:"pipe",in:e,out:t})}var Uu=S("ZodReadonly",(e,t)=>{dp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ah(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Hu(e){return new Uu({type:"readonly",innerType:e})}var qu=S("ZodCustom",(e,t)=>{gp.init(e,t),ne.init(e,t),e._zod.processJSONSchema=(a,n,r)=>bh(e,a,n,r)});function ju(e,t={}){return nh(qu,e,t)}function Zu(e){return rh(e)}var pf=oh,hf=sh;function Yr(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function Oa(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Vu=class it extends ft{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=ca,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new Zl,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new Gs}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const p=Wl(t.pillLauncher);t.launcherImageUrl=p.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>p.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=id,this._shadow.appendChild(a);const n=this.root,r=(p,m)=>{m&&Yr(m)&&n.style.setProperty(p,m)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[p,m]of Object.entries(t.theme))p.startsWith("--")&&typeof m=="string"&&r(p,m);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const p=document.createElement("div");p.className="gengage-chat-backdrop",p.setAttribute("aria-hidden","true"),p.setAttribute("role","button"),p.setAttribute("tabindex","-1"),p.setAttribute("aria-label",this._i18n.closeAriaLabel),p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),this.close()}),this._backdropEl=p,i.prepend(p)}if(o==="floating"){const p={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?p.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(p.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(p.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(p.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(p.tooltip=t.launcherTooltip),this._launcher=tc(p),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new qs(s,{i18n:this._i18n,onSend:(p,m)=>this._sendMessage(p,m),onClose:()=>this.close(),onAttachment:p=>this._handleAttachment(p),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:p=>this._handleRollback(p),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(pd(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:p=>{p==="close"?this.close():(this._openState=p,this._applyOpenStateClasses())},onThumbnailClick:p=>this._rollbackToThread(p),onLinkClick:p=>{this._saveSessionAndOpenURL(p)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:p=>{this._presentation.pinnedToBottom=p},onUserInteractingChange:p=>{this._presentation.userInteracting=p},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Hl({onChange:p=>this._panel?.notifyExtension(p),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new ql({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:p=>this._rollbackToThread(p)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),d=sessionStorage.getItem("gengage_restore_sku"),h=!!(g&&d);h&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const p=new $l;await p.open(),this._session=new Dn(p),await this._restoreFromIndexedDB(h)}catch{this._session=new Dn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const u=()=>this._syncViewportState();if(window.addEventListener("resize",u,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",u)),window.visualViewport){const p=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const m=this._drawer?.getElement();if(!m)return;const b=window.innerHeight-(window.visualViewport?.height??window.innerHeight);m.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,b)}px`)};window.visualViewport.addEventListener("resize",p),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",p))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const f={namespace:"chat",onMessage:p=>this._handleBridgeMessage(p)};t.allowedOrigins!==void 0&&(f.allowedOrigins=t.allowedOrigins),this._bridge=new po(f),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const p of this._pendingActions)this._sendAction(p.action,p.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),ce("gengage:chat:ready",{}),Pt("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),ce("gengage:chat:open",{state:this._openState}),At("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),ce("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),ws(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${CSS.escape(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=Vl(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=Oa(n)?n:Oa(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),Oa(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Yr(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ja(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!0})}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=_o(t);if(!a.ok){ce("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(wa(this.config.accountId),this._drawer?.hideKvkkBanner()),ud(),this._messages.some(r=>r.role==="user")||md(),Le("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Bl(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const _=this._currentThreadId,y=this._messages.filter(x=>x.threadId!==void 0&&x.threadId>_);this._messages=this._messages.filter(x=>!x.threadId||x.threadId<=_);for(const x of y)this._shadow?.querySelector(`[data-message-id="${CSS.escape(x.id)}"]`)?.remove(),this._panel.snapshots.delete(x.id),this._panel.snapshotTypes.delete(x.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(x=>{x instanceof HTMLElement&&x.dataset.threadId&&x.dataset.threadId>_&&x.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ja();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const _=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,y=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(y!==void 0&&y.role==="user"&&y.content===_)){const x=this._createMessage("user",_);x.threadId=n,a?.attachment!==void 0&&(x.attachment=a.attachment),this._drawer?.addMessage(x),this._messages.push(x)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const _=this._i18n.productNotFoundMessage,y=this._createMessage("assistant",_);y.threadId=n,y.status="done",this._messages.push(y),this._ensureAssistantMessageRendered(y),this._drawer?.updateBotMessage(y.id,_),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",y),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const _=this._buildRenderContext(),y=this._renderPanelFromSource(o,_);this._drawer.setPanelContent(y),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const h={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(h.attachment=a.attachment);const u=this._getVisibleMessages().filter(_=>_!==d&&(_.content||_.role==="assistant")).slice(-50).map(_=>({role:_.role==="user"?"user":"model",content:_.content??""})),f={outputLanguage:rd(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:$n(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(f.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(f.viewId=this.config.session.viewId);const p=bs(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),m={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:p.type,locale:this.config.locale??"tr",meta:f,context:{...this._lastBackendContext??{},messages:u,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(m.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(m.view_id=this.config.session.viewId),p.payload!==void 0&&(m.payload=p.payload),this.config.pageContext?.sku!==void 0&&(m.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(m.page_type=this.config.pageContext.pageType);const b=crypto.randomUUID(),C=Date.now();let v=0,w=!1,k=!1,A=!1,B=!1,I=!1;const H=Ks();let Q=null;const K=()=>{if(this._drawer){if(this._isMobileViewport||!A){this._drawer.setPanelAiZoneState("hidden");return}B||(I?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(Qt(this.analyticsContext(),{endpoint:"process_action",request_id:b,widget:"chat"}));let N=null;if(N=_s(m,{onTextChunk:(_,y,x)=>{if(!r&&n!==this._activeRequestThreadId||(g+=_,this._drawer?.removeTypingIndicator(),x?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,...x.skuToProductItem}),x?.conversationMode&&(this._conversationMode=x.conversationMode),x?.renderHint&&(d.renderHint=x.renderHint),this.track(zi(this.analyticsContext(),{request_id:b,chunk_index:v++,widget:"chat"})),!this._drawer))return;let E=g;const L=x?.kvkk===!0||i&&xa(E);if(y&&L){const R=this.config.accountId;if(!$n(R)){const P=ad(E);P?this._drawer?.showKvkkBanner(P,()=>{this._drawer?.hideKvkkBanner(),wa(R)}):wa(R)}E=td(E)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=_e(E):(d.content=E,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),y)if(d.content=E,d.status="done",qn(),Js(d))this._drawer?.updateBotMessage(d.id,E,"photo_analysis",d.photoAnalysis);else{const R=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(R){this._activeTypewriter?.cancel();const P=x?.productMentions;this._activeTypewriter=Pl({container:R,html:_e(E),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,P&&P.length>0&&R&&Al({container:R,mentions:P,onProductClick:$=>{this._sendAction({title:P.find(F=>F.sku===$)?.short_name??$,type:"launchSingleProduct",payload:{sku:$}})}})}})}}},onUISpec:(_,y,x,E)=>{if(!r&&n!==this._activeRequestThreadId||y!=="chat")return;E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const L=_.elements[_.root],z=L?.type??"unknown";if(Ys(z,L?.props??{},H,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:I},d))return;const R=z==="ProductGrid"&&L?.props?.similarsAppend===!0,P=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||R);P&&!E&&(this._clearAssistantPanelLikeStreamClearPanel(),w=!1);const $=z==="ProductDetailsPanel"&&x!=="panel"?"panel":x;this.track(Mi(this.analyticsContext(),{request_id:b,chunk_index:v,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const U=L?.props?.products;dd(Array.isArray(U)?U.length:0)}if(z==="ProductGrid"){const U=L?.children?.length??0;hd(void 0,U)}const V=$==="panel"&&this._panel?this._panel.toPanelSpec(_):_;if($==="panel"&&this._panel&&!P){const U=!k;k=!0;const M=jl({componentType:z,similarsAppend:L?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:U});F.panelProductListHeading=void 0,z==="ProductGrid"&&(M==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:V})),M==="appendSimilars"?this._appendSimilarsToPanel(V,F):M==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(V,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(V,F)),this._currentPanelSource={kind:"spec",spec:V},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const G=this._panel.currentType??z,O=L?.props?.panelTitle;if(this._panel.updateTopBar(G,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(A=!this._isMobileViewport,Q){const re=this._buildRenderContext();re.isStreaming=!0;const Gt=this._renderUISpec(Q,re);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Gt}),Q=null}}else M!=="appendSimilars"&&M!=="append"&&(A=!1,Q=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&$==="panel"&&(!d.silent||i)){const U=L?.props?.product;if(U){const M={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:U}}}},G=this._shadow?.querySelector(".gengage-chat-messages");if(G){const O=this._renderUISpec(M,F);d.threadId&&(O.dataset.threadId=d.threadId);const re=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);re&&re.parentNode===G?re.after(O):G.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),k=!0}}}const J=z==="AITopPicks"||z==="AIGroupingCards";let X=!1,oe=!1;if(P&&R&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),J&&!this._isMobileViewport&&!d.silent)if(A){const U=this._renderUISpec(_,F);B=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:U}),X=!0,Q=null}else Q=_,oe=!0;const j=i&&z==="GroundingReviewCard";if((!d.silent||j)&&($!=="panel"||z==="ProductCard"||P&&z==="ProductGrid"&&(!R||this._isMobileViewport))&&z!=="ActionButtons"&&!X&&!(oe&&J)){const U=this._shadow?.querySelector(".gengage-chat-messages");if(U){const M=this._renderUISpec(_,F);d.threadId&&(M.dataset.threadId=d.threadId),U.appendChild(M),M.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),P&&z==="ProductGrid"&&(k=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const U=L?.children??[],M=z==="ProductGrid"?U.map(G=>_.elements[G]?.props?.product).filter(Boolean):[L?.props?.product].filter(Boolean);for(const G of M){const O=G.sku,re=G.imageUrl;O&&re&&this._thumbnailEntries.push({sku:O,imageUrl:re,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const U=(z==="ProductGrid"?(L?.children??[]).map(M=>_.elements[M]?.props?.product).filter(Boolean):[L?.props?.product??L?.props].filter(Boolean)).map(M=>M.imageUrl).filter(M=>typeof M=="string").slice(0,5);U.length>0&&this._bridge?.send("previewImages",{images:U})}const be=L?.children?.length??0;if(z==="ProductGrid"&&$==="panel"&&!P&&be>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!Rl(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(M=>M.remove()),this._choicePrompterEl=Ml({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const U=this._shadow?.querySelector(".gengage-chat-panel-float");if(U){if(U.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const M=this._choicePrompterEl,G=()=>{window.visualViewport.height/window.innerHeight<.75&&(M.remove(),this._choicePrompterEl===M&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",G))};window.visualViewport.addEventListener("resize",G)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const U=L?.props?.buttons;if(U&&U.length>0){const M=[],G=[];for(const O of U)if(Nl(O)){const re={label:O.label,action:O.action};O.icon&&(re.icon=O.icon),M.push(re)}else G.push(O);M.length>0&&this._drawer?.setInputAreaChips(M.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),G.length>0&&this._drawer?.setPills(G.map(O=>{const re={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(re.icon=O.icon),O.image&&(re.image=O.image),O.description&&(re.description=O.description),re}))}}K(),d.uiSpec=_},onAction:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="action"){const y={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(y.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(y.allowScriptCall=this.config.actionHandling.allowScriptCall),fo(_,{openChat:()=>this.open(),navigate:x=>{pe(x.url)&&(this._bridge?.send("navigate",x),x.newTab?window.open(x.url,"_blank","noopener,noreferrer"):window.location.href=x.url)},saveSession:x=>this.saveSession(x.sessionId,x.sku),addToCart:x=>{ce("gengage:similar:add-to-cart",x)},scriptCall:x=>{ce("gengage:chat:script-call",x),this.config.onScriptCall?.(x)}},y)}},onMetadata:_=>{if(!(!r&&n!==this._activeRequestThreadId)&&_.type==="metadata"&&_.meta){if(_.meta.panel!==void 0||_.meta.messages!==void 0||_.meta.message_id!==void 0){this._lastBackendContext=_.meta;const x=ga(_.meta.panel);x&&(this._modeController.updateFromContext(x),this._applyUiHints())}if(_.meta.panelLoading){const x=typeof _.meta.panelPendingType=="string"?_.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(x==="productDetails"||x==="productDetailsSimilars")||(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(x),x&&this._panel?.updateTopBarForLoading(x))}if(_.meta.voice){const x=new CustomEvent("gengage:chat:voice",{detail:{payload:_.meta.voice},bubbles:!1,cancelable:!0}),E=window.dispatchEvent(x);if(fd(),E){const L=_.meta.voice;L.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=nc(L.audio_base64,L.content_type??"audio/ogg"))}}if((_.meta.redirectTarget||_.meta.redirect)&&(ce("gengage:chat:redirect",{target:_.meta.redirectTarget??null,payload:_.meta.redirect??null}),Le("redirect","redirect dispatched",{target:_.meta.redirectTarget??null}),this._handleRedirectMetadata(_.meta.redirect)),_.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(w=!0,k=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),_.meta.loading){const x=Array.isArray(_.meta.thinkingMessages)?_.meta.thinkingMessages.filter(L=>typeof L=="string"):[],E=typeof _.meta.loadingText=="string"?_.meta.loadingText:void 0;if(x.length>0){const L=E&&this._modeController.shouldCondenseThinking()?[...x.slice(0,2),E]:x;this._drawer?.setThinkingSteps(L)}typeof E=="string"&&E.length>0&&(this._drawer?.addThinkingStep(E),this._bridge?.send("loadingMessage",{text:E}))}_.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",_.meta.visitorDataResponse),_.meta.formType&&this._bridge?.send("glovOtokoc",{type:_.meta.formType,data:_.meta.formPayload}),_.meta.launcherContent&&this._bridge?.send("launcherContent",_.meta.launcherContent),ce("gengage:chat:metadata",{payload:_.meta});const y=_.meta;typeof y.prompt_tokens=="number"&&typeof y.completion_tokens=="number"&&this.track(Bi(this.analyticsContext(),{model:_.model??"unknown",prompt_tokens:y.prompt_tokens,completion_tokens:y.completion_tokens,total_tokens:y.total_tokens??y.prompt_tokens+y.completion_tokens}))}},onError:_=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;I=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,K(),Q=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),Xs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const y=k;w&&!k&&l(),w=!1,k=!1;const x=d.silent||d.content!=null&&d.content.length>0||g.length>0||y,E=typeof navigator<"u"&&navigator.onLine===!1&&na(_),L=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const P=this._messages.indexOf(d);P>=0&&this._messages.splice(P,1)};let z=!1;const R=()=>{if(E)return;this.emit("error",_);const P=_.message;P===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=P);const $=_.message.trim(),F=$.length>0?$:this._i18n.errorMessage,V={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){L(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,V);return}if(Ql(_,F)){L(),z=!0,this._drawer?.showErrorWithRecovery(F,V);return}d.content=F,d.status="done";const J=_e(F.replace(/\r\n/g,`
|
|
177
177
|
`).split(`
|
|
178
178
|
`).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,J),this._drawer?.showRecoveryPillsOnly(V)};if(x)this._drawer?.setPills([]),d.silent||R();else if(i||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const P=this._i18n.productNotFoundMessage;d.content=P,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,P),this._markUnavailableProductContext()}else if(R(),E)return;i&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),!z&&d.status==="streaming"&&(d.status="error"),E||this.track(Xt(this.analyticsContext(),{request_id:b,error_code:"STREAM_ERROR",error_message:_.message,widget:"chat"}))},onDone:()=>{if(N&&this._abortControllers.delete(N),!r&&n!==this._activeRequestThreadId)return;if(I=!0,K(),Q){const E=this._buildRenderContext();E.isStreaming=!1;const L=this._shadow?.querySelector(".gengage-chat-messages");if(L){const z=this._renderUISpec(Q,E);d.threadId&&(z.dataset.threadId=d.threadId),L.appendChild(z),z.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}Q=null}this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),Qs(H,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const _=k;if(w&&!k&&l(),w=!1,i&&!g&&!_){const E=this._i18n.productNotFoundMessage;d.content=E,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,E),this._markUnavailableProductContext()}if(k=!1,i){this._pdpPrimingInFlight=!1;const E=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),E||this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",qn()),this._presentation.finalizeAssistantGroup(n);const y=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");y&&(y.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),y.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const x=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,x?()=>{const E=this._buildRenderContext();return this._renderPanelFromSource(x,E)}:void 0),this.track(ut(this.analyticsContext(),{request_id:b,latency_ms:Date.now()-C,chunk_count:v,widget:"chat"})),this.track(Ri(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Di(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},h),this._abortControllers.add(N),!a?.silent&&!r){const _=N;this._drawer?.showStopButton(()=>{_.abort(),this._abortControllers.delete(_),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(n=>!n.silent);if(!this._currentThreadId)return t;const a=this._currentThreadId;return t.filter(n=>!n.threadId||n.threadId<=a)}_appendSimilarsToPanel(t,a){if(!this._drawer)return;const n=this._drawer.getPanelContentElement();if(!n)return;a.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products";const r=this._renderUISpec(t,a);r.classList.add("gengage-chat-product-details-similars"),n.appendChild(r),this._mergePanelSourceWithSimilars(t)}_mergePanelSourceWithSimilars(t){const a=this._currentPanelSource;a?.kind==="spec"&&this._panel?.currentType==="ProductDetailsPanel"&&(this._currentPanelSource={kind:"productDetailsWithSimilars",pdpSpec:a.spec,similarsSpec:t})}_renderProductDetailsWithSimilars(t,a,n){this._applyPanelListHeadingToContext(n,{kind:"productDetailsWithSimilars",pdpSpec:t,similarsSpec:a});const r=this._renderUISpec(t,n),i=this._renderUISpec(a,n);return i.classList.add("gengage-chat-product-details-similars"),r.appendChild(i),r}_applyPanelListHeadingToContext(t,a){if(t.panelProductListHeading=void 0,!!this._panel){if(a.kind==="spec"){const n=a.spec.elements[a.spec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._panel.titleForComponent("ProductGrid",n.props?.panelTitle??void 0))}else if(a.kind==="productDetailsWithSimilars"){const n=a.similarsSpec.elements[a.similarsSpec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products")}}}_renderPanelFromSource(t,a){return this._applyPanelListHeadingToContext(a,t),t.kind==="favorites"?this._buildFavoritesPageEl():t.kind==="productDetailsWithSimilars"?this._renderProductDetailsWithSimilars(t.pdpSpec,t.similarsSpec,a):this._renderUISpec(t.spec,a)}_handleRollback(t){const a=this._messages.find(n=>n.id===t);a?.threadId&&this._rollbackToThread(a.threadId)}_ensurePdpPrimeSuggestedUiIfNeeded(){const t=this.config.pageContext?.sku;if(!t||!this._drawer||this._hasUnavailableProductContext())return;const a="product",n=this._resolveContextualOpeningActions(a);if(n.length>0){this._drawer.setInputAreaChips(n.map(r=>({label:r.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(r,a)),...r.icon?{icon:r.icon}:{}})));return}this._drawer.setInputAreaChips([{label:this._i18n.groundingReviewCta,icon:"review",onAction:()=>this._sendAction({title:this._i18n.customerReviewsTitle,type:"reviewSummary",payload:{sku:t}})},{label:this._i18n.findSimilarLabel,icon:"similar",onAction:()=>this._sendAction({title:this._i18n.findSimilarLabel,type:"findSimilar",payload:{sku:t}})}])}_rollbackToThread(t){if(this._panel&&this._panel.threads.length>0&&!this._panel.threads.includes(t)&&!this._messages.some(i=>i.threadId===t))return;this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1),this._lastThreadId!=null&&t===this._lastThreadId?(this._presentation.setFocusedThreadId(t),this._drawer?.setPresentationFocus(t)):(this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null)),this._drawer?.setFormerMessagesButtonVisible(!1);for(const i of this._messages){const o=this._shadow?.querySelector(`[data-message-id="${CSS.escape(i.id)}"]`);o&&(i.threadId&&i.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(i=>{i instanceof HTMLElement&&i.dataset.threadId&&i.dataset.threadId>t?i.classList.add("gengage-chat-bubble--hidden"):i instanceof HTMLElement&&i.classList.remove("gengage-chat-bubble--hidden")});const a=this._messages.find(i=>i.role==="assistant"&&i.threadId===t),n=a?this._panel?.restoreForMessage(a.id):!1;n||(this._drawer?.clearPanel(),this._currentPanelSource=null),n&&a&&(this._currentPanelSource=null);const r=this._panel.currentType??"";if(this._panel?.updateTopBar(r),this._drawer?.setPills([]),requestAnimationFrame(()=>{this._drawer?.scrollThreadIntoView(t,"auto")}),this._session?.db&&this.config.session?.sessionId){const i=this.config.session.sessionId;(async()=>{try{const o=await this._session?.db?.loadContext(i,t);o&&(this._lastBackendContext=o.context),await this._session?.db?.deleteContextsAfterThread(i,t)}catch{}})()}}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${CSS.escape(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,a){return this._session?this._session.loadPayload(t,a):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const a=this.config.session?.sessionId;if(!a)return;const n=this.config.session?.userId??"",r=this.config.accountId;if(await this._session.loadFavorites(n,r),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size),!t)return;const i=await this._session.db?.loadSession(n,r,a);if(!i||i.messages.length===0)return;const o=this.config.pageContext?.sku;if(o&&i.sku&&i.sku!==o)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=i.currentThreadId,this._lastThreadId=i.lastThreadId,this._currentThreadId&&this._lastThreadId&&this._currentThreadId>this._lastThreadId&&(this._currentThreadId=this._lastThreadId),this._chatCreatedAt=i.createdAt,i.panelThreads&&(this._panel.threads=i.panelThreads),i.thumbnailEntries&&(this._thumbnailEntries=i.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),i.panelSnapshotHtml)for(const[c,l]of Object.entries(i.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=_e(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of i.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,this._restoreInlineUISpec(l),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(a,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(a)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${CSS.escape(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const d=g.elements[g.root];d&&this._panel?.updateTopBar(d.type)}}}}this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_navigatePanelBack(){const t=this._localPanelHistory.pop();if(t){const a=this._buildRenderContext(),n=this._renderPanelFromSource(t.source,a);this._drawer?.setPanelContent(n),this._drawer?.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(t.source)),this._currentPanelSource=t.source;const r=this._localPanelHistory.length>0||(this._panel?.threads.length??0)>1;this._drawer?.updatePanelTopBar(r,!1,t.title);return}if(this._isMobileViewport){this._drawer?.hideMobilePanel();return}this._panel?.navigateBack()}_shouldUseDividerPreviewForSpec(t){return t.elements[t.root]?.type==="ProductGrid"}_shouldUseDividerPreviewForSource(t){return t?.kind==="spec"?this._shouldUseDividerPreviewForSpec(t.spec):!1}_toggleComparisonSku(t){if(t==="")this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectionWarning=null,this._comparisonSelectMode&&(Ol(this._currentThreadId??""),this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(a=>a.remove())),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,ld());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=it._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${it._MAX_COMPARISON_SELECTION} products`,this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()});return}this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],this._comparisonSelectionWarning=null,sd(t)}this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()})}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t){this._drawer?.setComparisonDockContent(null);return}const a=t.querySelector(".gengage-chat-product-grid-wrapper"),n=a?.querySelector(".gengage-chat-product-grid");if(!a||!n){this._drawer?.setComparisonDockContent(null);return}const r=a.querySelector(".gengage-chat-comparison-toggle-btn");if(r&&r.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const i=n.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const o of i){if(o.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const u=o.parentElement,f=this._comparisonSelectedSkus.includes(o.dataset.sku);u.classList.toggle("gengage-chat-comparison-select-wrapper--selected",f);const p=u.querySelector(".gengage-chat-comparison-checkbox");if(p){p.dataset.selected=f?"true":"false",p.setAttribute("aria-pressed",f?"true":"false");const m=p.querySelector(".gengage-chat-comparison-checkbox-icon"),b=p.querySelector(".gengage-chat-comparison-checkbox-label");m&&(m.innerHTML=f?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>'),b&&(b.textContent=f?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare")}continue}const s=o.dataset.sku,c=document.createElement("div");c.className="gengage-chat-comparison-select-wrapper";const l=this._comparisonSelectedSkus.includes(s);l&&c.classList.add("gengage-chat-comparison-select-wrapper--selected");const g=document.createElement("button");g.type="button",g.className="gengage-chat-comparison-checkbox",g.dataset.selected=l?"true":"false",g.setAttribute("aria-pressed",l?"true":"false");const d=document.createElement("span");d.className="gengage-chat-comparison-checkbox-icon",d.innerHTML=l?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const h=document.createElement("span");h.className="gengage-chat-comparison-checkbox-label",h.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(d),g.appendChild(h),g.addEventListener("click",u=>{u.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",u=>{u.target.closest(".gengage-chat-comparison-checkbox")||(u.stopPropagation(),this._toggleComparisonSku(s))})}}else{const i=n.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const o of i){const s=o.querySelector(".gengage-chat-product-card");s&&o.parentNode&&(o.parentNode.insertBefore(s,o),o.remove())}}if(a.querySelector(".gengage-chat-comparison-floating-btn")?.remove(),this._comparisonSelectMode){const i=wn(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_parseAddToCartActionPayload(t){if(typeof t!="object"||t===null)return null;const a=t,n=this._coerceAddToCartString(a.sku),r=this._coerceAddToCartString(a.cartCode??a.cart_code);let i=1;return typeof a.quantity=="number"&&Number.isFinite(a.quantity)&&a.quantity>0&&(i=Math.max(1,Math.floor(a.quantity))),!n||!r?null:{sku:n,cartCode:r,quantity:i}}_coerceAddToCartString(t){return typeof t=="string"&&t.length>0?t:typeof t=="number"&&Number.isFinite(t)?String(t):""}_runChatAddToCartFlow(t){if(this.config.onAddToCart!==void 0)try{const r=this.config.onAddToCart(t);r instanceof Promise&&r.catch(i=>console.error("[gengage] onAddToCart",i))}catch(r){console.error("[gengage] onAddToCart",r)}Hn(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};ce("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ua(this.analyticsContext(),{attribution_source:"chat",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:t.quantity,sku:t.sku})),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:t.sku,cart_code:t.cartCode,quantity:t.quantity}},{preservePanel:!0});const n=this._i18n.addedToCartToast??"Added to cart";this._drawer?.showCartToast(n),this._drawer?.flashCartBadge()}_buildRenderContext(){const t={onAction:a=>{if(ka(a.title,a.type),a.type==="addToCart"){const r=this._parseAddToCartActionPayload(a.payload);if(r){this._runChatAddToCartFlow(r);return}}if(a.type==="launchSingleProduct"){this._drawer?.setDividerPreviewEnabled(!1);const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";r&&Ca(r,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";Un(r)}a.type==="getComparisonTable"&&cd(this._comparisonSelectedSkus);const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{if(Ca(a.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url))ce("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(a.url);else{const n=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:n,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{if(this._currentPanelSource){const s=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:s}),this._localPanelHistory.length>it._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const n=this._buildRenderContext(),r={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},i=this._shadow?.querySelector(".gengage-chat-messages");if(i){const s=this._renderUISpec(r,n);this._currentThreadId&&(s.dataset.threadId=this._currentThreadId),i.appendChild(s),s.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const o={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(o,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:o},this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:it._MAX_COMPARISON_SELECTION,comparisonSelectionWarning:this._comparisonSelectionWarning,onToggleComparisonSku:a=>{this._toggleComparisonSku(a)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(a,n)=>{this._toggleProductFavorite(a,n)},isMobile:this._isMobileViewport};return t}async _toggleFavorite(t,a){if(!this._session)return;const n=this.config.session?.userId??"",r=this.config.accountId;await this._session.toggleFavorite(n,r,t,a),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size)}_revertFavoriteHeartUi(t){const a=this._shadow?.querySelectorAll(`[data-gengage-favorite-sku="${CSS.escape(t)}"]`);if(a?.length)for(const n of a){if(!(n instanceof HTMLButtonElement))continue;n.classList.toggle("gengage-chat-favorite-btn--active");const r=n.querySelector("svg");r&&r.setAttribute("fill",n.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none")}}async _toggleProductFavorite(t,a){const n=!(this._session?.favoritedSkus.has(t)??!1),r={sku:t,product:a,favorited:n,sessionId:this.config.session?.sessionId??null};ce("gengage:chat:product-favorite",r),this._bridge?.send("productFavorite",r);const i=this._eventCallbacks.get("gengage-product-favorite");if(i&&i.size>0){for(const o of i)try{const s=o(r);if((s instanceof Promise?await s:s)===!1){this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}}catch{this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}this._session&&(n?this._session.favoritedSkus.add(t):this._session.favoritedSkus.delete(t),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size));return}if(await this._toggleFavorite(t,a),n){gd(t);const o=a.name??t;this._sendAction({title:o,type:"like",payload:{sku:t}},{preservePanel:!0})}}_openFavoritesPanel(){if(this._drawer){if(this._currentPanelSource){const t=this._drawer.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:t}),this._localPanelHistory.length>it._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}this._drawer.setPanelContent(this._buildFavoritesPageEl()),this._drawer.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"favorites"},this._drawer.updatePanelTopBar(!0,!1,this._i18n.favoritesPageTitle)}}_buildFavoritesPageEl(){const t=this._session?.getFavoriteProducts()??[];if(t.length===0){const i=document.createElement("div");i.className="gengage-chat-favorites-empty";const o=document.createElement("div");o.className="gengage-chat-favorites-empty-icon",o.innerHTML='<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',i.appendChild(o);const s=document.createElement("p");return s.textContent=this._i18n.emptyFavoritesMessage,i.appendChild(s),i}const a={},n=[];for(const[i,o]of t.entries()){const s=`card_${i}`;n.push(s),a[s]={type:"ProductCard",props:{product:{sku:o.sku,name:o.name,imageUrl:o.imageUrl,price:o.price}}}}a.grid={type:"ProductGrid",children:n};const r={root:"grid",elements:a};return this._renderUISpec(r,this._buildRenderContext())}async _runEventCallbacks(t,a){const n=this._eventCallbacks.get(t);if(!(!n||n.size===0))for(const r of n)try{const i=r(a);if((i instanceof Promise?await i:i)===!1){this._handleCallbackFailure(t,a);return}}catch{this._handleCallbackFailure(t,a);return}}_handleCallbackFailure(t,a){if(t==="gengage-cart-add"){const n=this._i18n.cartAddErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}if(t==="gengage-product-favorite"){const n=this._i18n.favoriteToggleErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const a=t.uiSpec,n=a.elements[a.root];if(!n)return;const r=n.type;if(r==="ActionButtons"||r==="ComparisonTable"||r==="ProductGrid"&&n.props?.similarsAppend===!0&&(this.config.productDetailsExtended===!0||!this._isMobileViewport))return;const i=this._buildRenderContext(),o=this._shadow?.querySelector(".gengage-chat-messages");if(!o)return;if(r==="ProductDetailsPanel"){const c=n.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,i);t.threadId&&(g.dataset.threadId=t.threadId),o.appendChild(g),this._drawer?.refreshPresentationCollapsed();return}const s=this._renderUISpec(a,i);t.threadId&&(s.dataset.threadId=t.threadId),o.appendChild(s),this._drawer?.refreshPresentationCollapsed()}_createMessage(t,a){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:a,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Ss(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Jt(qc(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??Cn,i=(s,c)=>jc(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}},Wu=8e3,Gu=5e3,Ku="https://www.google.com/favicon.ico",Re=new Map,Jr=!1,rt=null,ht=null,Ge=!1;function Yu(e){return typeof e=="string"&&e.toLowerCase().startsWith("tr")}function Qr(e){return Yu(e)?"İnternet bağlantısında sorun var gibi görünüyor. İstek sürerken yeniden deneyeceğiz.":"Your internet connection looks unstable. We'll keep retrying while this request is active."}function Xr(){let e;for(const t of Re.values())e=t;return e}function Da(){rt&&(clearTimeout(rt),rt=null)}function Ju(){ht&&(clearInterval(ht),ht=null)}async function ei(){try{if(typeof navigator<"u"&&navigator.onLine===!1)return!1;if(typeof window<"u"){const a=window.location.hostname;if(a==="localhost"||a==="127.0.0.1")return navigator.onLine}const e=new AbortController,t=setTimeout(()=>e.abort(),3e3);try{return await fetch(Ku,{method:"HEAD",mode:"no-cors",cache:"no-cache",signal:e.signal}),!0}catch{return navigator.onLine}finally{clearTimeout(t)}}catch{return typeof navigator>"u"?!0:navigator.onLine}}function Ht(){Ge=!1,Ju(),Ya()}function qt(){rt||Ge||Re.size===0||(rt=setTimeout(async()=>{rt=null,!(Ge||Re.size===0)&&!await ei()&&Re.size>0&&(Ge=!0,ra({source:"sdk",message:Qr(Xr()),sticky:!0}),ht||(ht=setInterval(async()=>{if(Re.size===0){Ht();return}await ei()&&(Ht(),qt())},Gu)))},Wu))}function Qu(){Jr||typeof window>"u"||(Jr=!0,window.addEventListener("online",()=>{Ht(),qt()}),window.addEventListener("offline",()=>{Re.size===0||Ge||(Ge=!0,Da(),ra({source:"sdk",message:Qr(Xr()),sticky:!0}))}))}function ti(e){Qu();const t=Symbol(e.source);Re.set(t,e.locale),qt();let a=!1;return()=>{if(!a){if(a=!0,Re.delete(t),Re.size===0){Da(),Ht();return}Ge||(Da(),qt())}}}async function Xu(e,t,a){const n=yt("launcher_action",t),r={uiSpecs:[],actions:[]},i={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(i.signal=a);const o=await fetch(n,i);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);const s={onEvent:c=>{const l=vt(c);if(l&&(l.type==="ui_spec"&&r.uiSpecs.push(l.spec),l.type==="ui_spec"&&l.spec.elements)){for(const g of Object.values(l.spec.elements))if(g.type==="ActionButton"&&g.props?.action){const d=g.props.action;r.actions.push(d)}}}};return a!==void 0&&(s.signal=a),await bt(o,s),r}function ai(e){const t=document.createElement("div");t.className="gengage-qna-buttons gds-toolbar",t.dataset.gengagePart="qna-button-row",t.setAttribute("role","group"),t.setAttribute("aria-label",e.quickQuestionsAriaLabel??"Quick questions"),e.orientation==="vertical"&&(t.style.flexDirection="column");for(const a of e.actions){const n=document.createElement("button");n.className="gengage-qna-button gds-chip",n.dataset.gengagePart="qna-quick-question",n.textContent=a.title,n.type="button",n.addEventListener("click",()=>{const r={title:a.title,type:a.type};a.payload!==void 0&&(r.payload=a.payload),e.onAction(r)}),t.appendChild(n)}if(e.ctaText||e.onOpenChat){const a=document.createElement("button");a.className="gengage-qna-cta gds-btn gds-btn-secondary",a.dataset.gengagePart="qna-cta",a.textContent=e.ctaText??e.defaultCtaText??"Ask something else",a.type="button",a.addEventListener("click",()=>{e.onOpenChat?.()}),t.appendChild(a)}return t}function em(e){const t=document.createElement("div");t.className="gengage-qna-input-wrapper",t.dataset.gengagePart="qna-input-wrapper";const a=document.createElement("div");a.className="gengage-qna-input-combo",a.dataset.gengagePart="qna-input-combo";const n=document.createElement("input");n.type="text",n.className="gengage-qna-input",n.dataset.gengagePart="qna-input",n.setAttribute("aria-label",e.askQuestionAriaLabel??"Ask a question");const r=Array.isArray(e.placeholders)?e.placeholders:e.placeholders?[e.placeholders]:[e.defaultInputPlaceholder??"Ask a question..."];let i=0,o=r[0]??"";n.placeholder=o;let s=null,c=null,l=!1;const g=()=>{s&&clearInterval(s),s=null,c&&clearTimeout(c),c=null,n.classList.remove("gengage-qna-input--fade")},d=()=>r.length>1&&!l&&n.value.trim().length===0,h=()=>{g(),d()&&(s=setInterval(()=>{d()&&(n.classList.add("gengage-qna-input--fade"),c=setTimeout(()=>{i=(i+1)%r.length,o=r[i]??"",n.placeholder=o,n.classList.remove("gengage-qna-input--fade")},180))},3e3))},u=document.createElement("div");u.className="gengage-qna-input-actions",u.dataset.gengagePart="qna-input-actions";const f=document.createElement("button");f.className="gengage-qna-icon-btn gengage-qna-clear gengage-qna-icon-btn--hidden",f.type="button",f.dataset.gengagePart="qna-clear",f.setAttribute("aria-label","Clear question"),f.innerHTML='<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M18 6L6 18" /><path d="M6 6L18 18" /></svg>';const p=document.createElement("button");p.className="gengage-qna-icon-btn gengage-qna-send gengage-qna-icon-btn--hidden",p.type="button",p.dataset.gengagePart="qna-send",p.setAttribute("aria-label",e.sendQuestionAriaLabel??"Send question"),p.disabled=!0,p.innerHTML=`<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M22 2L11 13" /><path d="M22 2L15 22L11 13L2 9L22 2Z" /></svg><span class="gengage-qna-sr-only">${e.ctaLabel??e.sendButtonText??"Ask"}</span>`;const m=()=>{const C=n.value.trim().length>0;f.classList.toggle("gengage-qna-icon-btn--hidden",!C),p.classList.toggle("gengage-qna-icon-btn--hidden",!C),p.classList.toggle("gengage-qna-send--active",C),p.disabled=!C},b=()=>{const C=n.value.trim();C&&(e.onSubmit({title:C,type:"user_message",payload:C}),n.value="",m(),h())};return f.addEventListener("click",()=>{n.value="",m(),n.focus({preventScroll:!0})}),p.addEventListener("click",b),n.addEventListener("focus",()=>{l=!0,g(),n.placeholder=""}),n.addEventListener("blur",()=>{l=!1,n.value.trim().length===0&&(n.placeholder=o),h()}),n.addEventListener("input",()=>{if(m(),n.value.trim().length>0){g();return}n.placeholder=l?"":o,h()}),n.addEventListener("keydown",C=>{C.key==="Enter"&&(C.preventDefault(),b()),C.key==="Escape"&&n.value.length>0&&(n.value="",m(),h())}),u.appendChild(f),u.appendChild(p),a.appendChild(n),a.appendChild(u),t.appendChild(a),m(),h(),t._cleanup=()=>{g()},t}function jt(e,t){if(!e||typeof e!="object")return null;const a=e,n=a.type;if(typeof n!="string"||n.length===0)return null;const r=a.title,i=a.payload,o=typeof r=="string"&&r.length>0?r:t;if(!o)return null;const s={title:o,type:n};return i!==void 0&&(s.payload=i),s}function ni(e){const t={title:e.title,type:e.type};return e.payload!==void 0&&(t.payload=e.payload),t}function ri(e,t){const a=[],n=e.props?.actions;if(Array.isArray(n))for(const o of n){const s=jt(o);s&&a.push(s)}const r=e.props?.buttons;if(Array.isArray(r))for(const o of r){if(!o||typeof o!="object")continue;const s=o,c=typeof s.label=="string"?s.label:void 0,l=jt(s.action,c);l&&a.push(l)}if(e.children)for(const o of e.children){const s=t.elements[o];if(!s||s.type!=="ActionButton")continue;const c=typeof s.props?.label=="string"?s.props.label:void 0,l=jt(s.props?.action,c);l&&a.push(l)}const i=new Set;return a.filter(o=>i.has(o.title)?!1:(i.add(o.title),!0))}var ii={ButtonRow:({element:e,spec:t,context:a})=>{const n=ri(e,t).map(ni),r=e.props?.orientation,i={actions:n,onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(i.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(i.ctaText=a.ctaText),(r==="horizontal"||r==="vertical")&&(i.orientation=r),ai(i)},ActionButtons:({element:e,spec:t,context:a})=>{const n={actions:ri(e,t).map(ni),onAction:a.onAction,defaultCtaText:a.i18n.defaultCtaText,quickQuestionsAriaLabel:a.i18n.quickQuestionsAriaLabel};return a.onOpenChat!==void 0&&(n.onOpenChat=a.onOpenChat),a.ctaText!==void 0&&(n.ctaText=a.ctaText),ai(n)},ActionButton:({element:e,context:t})=>{const a=document.createElement("button");a.className="gengage-qna-button gds-chip",a.type="button",a.dataset.gengagePart="qna-action-button";const n=e.props?.label;typeof n=="string"?a.textContent=n:a.textContent=t.i18n.defaultCtaText;const r=jt(e.props?.action,typeof n=="string"?n:void 0);return r&&a.addEventListener("click",()=>t.onAction(r)),a},TextInput:({element:e,context:t})=>{const a=e.props?.placeholder,n=typeof a=="string"||Array.isArray(a)?a:t.inputPlaceholder,r=typeof e.props?.ctaLabel=="string"?e.props.ctaLabel:void 0,i={onSubmit:t.onAction,askQuestionAriaLabel:t.i18n.askQuestionAriaLabel,defaultInputPlaceholder:t.i18n.defaultInputPlaceholder,sendButtonText:t.i18n.sendButton,sendQuestionAriaLabel:t.i18n.sendQuestionAriaLabel};return n!==void 0&&(i.placeholders=n),r!==void 0&&(i.ctaLabel=r),em(i)},QuestionHeading:({element:e,context:t})=>{const a=document.createElement("h3");a.className="gengage-qna-heading",a.dataset.gengagePart="qna-heading";const n=e.props?.text,r=t.headingTitleOverride;return a.textContent=typeof r=="string"&&r.trim().length>0?r:typeof n=="string"?n:"",a},ProductCard:()=>null},oi=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function tm(){return{...ii}}function am(e,t,a=ii,n=oi){return Yt({spec:e,context:t,registry:a,containerClassName:"gengage-qna-uispec",unknownRenderer:n})}function nm(e){if(!e)return;const t=e.extra;if(t&&typeof t=="object"&&!Array.isArray(t)){const n=t.visible_skus??t.visibleSkus;if(Array.isArray(n)){const r=n.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()).slice(0,200);if(r.length>0)return r}}const a=typeof e.sku=="string"&&e.sku.trim()?e.sku.trim():void 0;return a?[a]:void 0}function si(e,t){if(!e)return null;const a=e.action;if(!a||typeof a!="object")return null;const n=a,r=n.type;if(typeof r!="string"||r.length===0)return null;const i=n.title,o=typeof i=="string"&&i.length>0?i:typeof t=="string"&&t.length>0?t:"";if(!o)return null;const s=n.payload,c={title:o,type:r};return s!==void 0&&(c.payload=s),c}function rm(e,t){const a=e.elements[e.root];if(!a)return!1;const n=r=>{if(r.type!=="ActionButton")return!1;const i=r.props;if(!i||typeof i!="object")return!1;const o=typeof i.label=="string"?i.label:void 0;return o===t?!0:si(i,o)?.title===t};if(a.type==="ActionButton")return n(a);if(a.children)for(const r of a.children){const i=e.elements[r];if(i&&n(i))return!0}if(a.type==="ActionButtons"&&Array.isArray(a.props?.buttons)){for(const r of a.props.buttons)if(r?.label===t||r?.action?.title===t)return!0}return!1}var ci=0;function li(){return ci+=1,`gengage-merge-${ci}`}function im(e,t){const a=e.elements[e.root];if(!a||a.type!=="ButtonRow")return;const n=li();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n]}function om(e,t){const a=e.elements[e.root];if(!a||a.type!=="ActionButtons")return;const n=li();e.elements[n]={type:"ActionButton",props:{label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}}},a.children=a.children?[n,...a.children]:[n];const r=a.props?.buttons??[],i={label:t.title,action:{title:t.title,type:t.type,...t.payload!==void 0?{payload:t.payload}:{}}};a.props={...a.props,buttons:[i,...r]}}function sm(e){const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,...r.payload!==void 0?{payload:r.payload}:{}}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}function cm(e){return e.find(t=>{const a=t.elements[t.root];return a?.type==="ActionButtons"||a?.type==="ButtonRow"})}function di(e,t){const a=e.productContextQuickPillLabel,n={text:a};return t&&t.length>0&&(n.sku_list=t),{title:a,type:"user_message",payload:n}}function lm(e,t,a){const n=a?.skuList,r=[],i=[];for(const c of e){const l=c.elements[c.root];if(l?.type==="ActionButton"){const g=l.props;if(si(g,typeof g?.label=="string"?g.label:void 0)?.type==="findSimilar"){r.push(di(t,n));continue}}i.push(c)}if(r.length===0)return e;const o=di(t,n),s=cm(i);if(!s)return[...i,sm([o])];if(!rm(s,o.title)){const c=s.elements[s.root];c?.type==="ActionButtons"?om(s,o):c?.type==="ButtonRow"&&im(s,o)}return i}var gi={quickQuestionsAriaLabel:"Hızlı sorular",askQuestionAriaLabel:"Soru sorun",defaultInputPlaceholder:"Bir soru sorun...",sendButton:"Sor",sendQuestionAriaLabel:"Soruyu gönder",defaultCtaText:"Başka bir şey sor",redirectingToChat:"Sohbete yönlendiriliyor...",productContextQuickPillLabel:"Bu ürün hakkında ne bilmeliyim?"},dm={quickQuestionsAriaLabel:"Quick questions",askQuestionAriaLabel:"Ask a question",defaultInputPlaceholder:"Ask a question...",sendButton:"Ask",sendQuestionAriaLabel:"Send question",defaultCtaText:"Ask something else",redirectingToChat:"Redirecting to chat...",productContextQuickPillLabel:"What should I know about this product?"};function gm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function pm(e){return gm(e)==="en"?dm:gi}var hm=class extends ft{constructor(...e){super(...e),this._abortController=null,this._debounceTimer=null,this._contentEl=null,this._i18n=gi,this._actionHandler=this._handleAction.bind(this),this._openChatHandler=this._handleOpenChat.bind(this)}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-qna-container",this._contentEl.dataset.gengagePart="qna-container",this.root.appendChild(this._contentEl);const t=e.pageContext?.sku;t&&(this._lastSku=t,await this._fetchAndRender(t)),Pt("qna")}onUpdate(e){const t=e.sku;!t||t===this._lastSku||(this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout(()=>{this._debounceTimer=null,this._lastSku=t,this._fetchAndRender(t)},50))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.2s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._contentEl&&(this._cleanupTextInputTimers(),this._contentEl.remove(),this._contentEl=null)}_abort(){this._abortController?.abort(),this._abortController=null}_resolvedQnaHeaderTitle(){const e=this.config.headerTitle??this.config.headingTitle;if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}_cleanupTextInputTimers(){if(!this._contentEl)return;const e=this._contentEl.querySelectorAll(".gengage-qna-input-wrapper");for(const t of e)t._cleanup?.()}async _fetchAndRender(e){if(this._abort(),this._abortController=new AbortController,!this._contentEl)return;this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const t=this._createLoadingIndicator();this._contentEl.appendChild(t);const a={middlewareUrl:this.config.middlewareUrl},n=crypto.randomUUID(),r=Date.now(),i=ti({source:"qna",locale:this.config.locale});this.track(Qt(this.analyticsContext(),{endpoint:"launcher_action",request_id:n,widget:"qna"}));try{const o={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e,locale:this.config.locale??"tr"},s=this.config.pageContext?.pageType;s!==void 0&&(o.page_type=s);const c=await Xu(o,a,this._abortController.signal);if(this.track(ut(this.analyticsContext(),{request_id:n,latency_ms:Date.now()-r,chunk_count:c.actions.length,widget:"qna"})),this.track(ea(this.analyticsContext(),{message_count:c.actions.length,history_ref:n,redaction_level:"none",widget:"qna"})),!this._contentEl)return;this._contentEl.innerHTML="";const l=document.createElement("div");l.className="gengage-qna-panel gds-panel",l.dataset.gengagePart="qna-panel",this._contentEl.appendChild(l);const g=this._specIncludesType(c.uiSpecs,"QuestionHeading"),d=this._resolvedQnaHeaderTitle()??(this.config.showStaticQuestion&&this.config.staticQuestionText?this.config.staticQuestionText:void 0);if(!g&&d){const v=document.createElement("h3");v.className="gengage-qna-heading",v.textContent=d,l.appendChild(v)}const h=this.config.inputPlaceholder;let u;if(h!==!0)u=h??this._i18n.defaultInputPlaceholder;else if(c.actions.length>0){const v=c.actions.filter(w=>w.type==="user_message"||w.title.includes("?")).map(w=>w.title);u=v.length>0?v:this._i18n.defaultInputPlaceholder}else u=this._i18n.defaultInputPlaceholder;const f={onAction:this._actionHandler,i18n:this._i18n},p=this._resolvedQnaHeaderTitle();p!==void 0&&(f.headingTitleOverride=p),this.config.hideButtonRowCta||(f.onOpenChat=this._openChatHandler,this.config.ctaText!==void 0&&(f.ctaText=this.config.ctaText)),u!==void 0&&(f.inputPlaceholder=u);const m=this._buildFallbackActionsSpec(c.actions),b=nm(this.config.pageContext),C=(c.uiSpecs.length>0?lm(c.uiSpecs,this._i18n,{skuList:b}):[m]).filter(v=>Object.keys(v.elements).length>0);for(const v of C){const w=this._renderUISpec(v,f);l.appendChild(w)}C.length>0&&At("qna"),this._specIncludesType(C,"TextInput")||this._insertStandaloneInputBeforePills(l,f,u)}catch(o){if(o instanceof DOMException&&o.name==="AbortError")return;if(ce("gengage:global:error",{source:"qna",code:"FETCH_ERROR",message:Ka(this.config.locale,o)}),this.track(Xt(this.analyticsContext(),{request_id:n,error_code:"FETCH_ERROR",error_message:o instanceof Error?o.message:String(o),widget:"qna"})),this._contentEl){this._cleanupTextInputTimers(),this._contentEl.innerHTML="";const s=document.createElement("div");s.className="gengage-qna-panel",this._contentEl.appendChild(s);const c=this.config.inputPlaceholder===!0?this._i18n.defaultInputPlaceholder:this.config.inputPlaceholder??this._i18n.defaultInputPlaceholder,l={onAction:this._actionHandler,i18n:this._i18n,onOpenChat:this._openChatHandler},g=this._resolvedQnaHeaderTitle();g!==void 0&&(l.headingTitleOverride=g),this.config.ctaText!==void 0&&(l.ctaText=this.config.ctaText),this._appendStandaloneInput(l,c,s)}}finally{i()}}_createLoadingIndicator(){const e=document.createElement("div");e.className="gengage-qna-loading";for(let t=0;t<3;t++){const a=document.createElement("div");a.className="gengage-qna-loading-dot",e.appendChild(a)}return e}_resolveI18n(e){return{...pm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return Jt(tm(),this.config.renderer?.registry)}_renderUISpec(e,t){const a=this._resolveUISpecRegistry(),n=this.config.renderer?.unknownRenderer??oi,r=(o,s)=>am(o,s,a,n),i=this.config.renderer?.renderUISpec;return i?i(e,t,{registry:a,unknownRenderer:n,defaultRender:r}):r(e,t)}_specIncludesType(e,t){for(const a of e)for(const n of Object.values(a.elements))if(n.type===t)return!0;return!1}_buildFallbackActionsSpec(e){if(e.length===0)return{root:"root",elements:{}};const t={},a=[];for(let n=0;n<e.length;n++){const r=e[n],i=`action-${n}`;a.push(i),t[i]={type:"ActionButton",props:{label:r.title,action:{title:r.title,type:r.type,payload:r.payload}}}}return t.root={type:"ButtonRow",children:a},{root:"root",elements:t}}_insertStandaloneInputBeforePills(e,t,a){const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:a}}}},r=this._renderUISpec(n,t),i=r.querySelector(".gengage-qna-input-wrapper");if(!i)return;const o=e.querySelector(".gengage-qna-uispec"),s=o?.querySelector(":scope > .gengage-qna-buttons");if(o&&s)o.insertBefore(i,s);else if(o){const c=o.querySelector(":scope > .gengage-qna-heading");c?c.insertAdjacentElement("afterend",i):o.prepend(i)}else{e.appendChild(r);return}r.remove()}_appendStandaloneInput(e,t,a){if(!this._contentEl)return;const n={root:"root",elements:{root:{type:"TextInput",props:{placeholder:t}}}},r=this._renderUISpec(n,e);(a??this._contentEl).appendChild(r)}_handleAction(e){this._showTransitionIndicator(),ka(e.title,e.type),this.config.onActionSelected?.(e),setTimeout(()=>ce("gengage:qna:action",e),350)}_handleOpenChat(){this._showTransitionIndicator(),this.config.onOpenChat?.(),setTimeout(()=>ce("gengage:qna:open-chat",{}),350)}_showTransitionIndicator(){if(!this._contentEl)return;this._contentEl.querySelector(".gengage-qna-transition-indicator")?.remove(),this._contentEl.classList.add("gengage-qna--transitioning");const e=this._i18n.redirectingToChat??"Redirecting to chat...",t=document.createElement("div");t.className="gengage-qna-transition-indicator",t.textContent=e,(this._contentEl.querySelector(".gengage-qna-panel")??this._contentEl).appendChild(t),setTimeout(()=>{this._contentEl?.classList.remove("gengage-qna--transitioning"),t.remove()},600)}};function pi(e){const t=[];for(const a of Object.values(e))if(a.type==="ProductCard"&&a.props){const n=a.props.product??a.props;typeof n.sku=="string"&&typeof n.name=="string"&&t.push(n)}return t}function hi(e){const t=e.headers.get("Content-Type")??"";return t.includes("application/x-ndjson")||t.includes("text/event-stream")}async function um(e,t){const a=[],n={onEvent:r=>{const i=vt(r);!i||i.type!=="ui_spec"||a.push(...pi(i.spec.elements))}};return t!==void 0&&(n.signal=t),await bt(e,n),a}async function mm(e,t,a){const n=yt("similar_products",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(hi(i))return um(i,a);const o=await i.text();if(!o)throw new Error("Empty response body from similar_products endpoint");try{return ps(JSON.parse(o))}catch{throw new Error("Invalid JSON from similar_products endpoint")}}async function fm(e,t){const a=[];let n=null;const r={onEvent:i=>{const o=vt(i);if(o){if(o.type==="metadata"&&o.meta){const s=o.meta.group_name;if(typeof s=="string"){n={name:s,products:[]};const c=o.meta.highlight;typeof c=="string"&&(n.highlight=c),a.push(n)}}o.type==="ui_spec"&&n&&n.products.push(...pi(o.spec.elements))}}};return t!==void 0&&(r.signal=t),await bt(e,r),a}async function bm(e,t,a){const n=yt("product_groupings",t),r={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)};a!==void 0&&(r.signal=a);const i=await fetch(n,r);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);if(hi(i))return fm(i,a);const o=await i.text();if(!o)return[];try{return hs(JSON.parse(o))}catch{throw new Error("Invalid JSON from product_groupings endpoint")}}function ui(e){const{product:t,index:a,discountType:n,onClick:r,onAddToCart:i,renderCard:o}=e,s=e.i18n,c=e.pricing;if(e.renderCardElement){const p=e.renderCardElement(t,a);if(p)return p}if(o){const p=document.createElement("div");return p.className="gengage-simrel-card gengage-simrel-card--custom gds-card gds-product-card gds-card-interactive",p.dataset.gengagePart="simrel-product-card",p.innerHTML=_e(o(t,a)),p.addEventListener("click",m=>{m.target.closest(".gengage-simrel-atc")||m.target.closest(".gengage-chat-product-card-atc")||r(t)}),p}const l=document.createElement("article");l.className="gengage-simrel-card gengage-chat-product-card gds-card gds-product-card gds-card-interactive",l.dataset.gengagePart="simrel-product-card",t.inStock===!1&&l.classList.add("gengage-simrel-card--out-of-stock"),l.setAttribute("role","listitem"),l.dataset.sku=t.sku;const g=document.createElement("div");if(g.className="gengage-simrel-card-image gengage-chat-product-card-img-wrapper",g.dataset.gengagePart="simrel-product-card-image",t.imageUrl&&ye(t.imageUrl)){const p=document.createElement("img");p.className="gengage-chat-product-card-img",p.src=t.imageUrl,p.alt=t.name,p.loading="lazy",Se(p),g.appendChild(p)}if(n==="badge"&&t.discountPercent&&t.discountPercent>0){const p=document.createElement("span");p.className="gengage-simrel-badge gengage-chat-product-card-discount-badge",p.textContent=`%${ma(t.discountPercent)}`,g.appendChild(p)}l.appendChild(g);const d=document.createElement("div");if(d.className="gengage-simrel-card-info gengage-chat-product-card-body",d.dataset.gengagePart="simrel-product-card-body",t.brand){const p=document.createElement("div");p.className="gengage-simrel-card-brand gengage-chat-product-card-brand",p.textContent=t.brand,d.appendChild(p)}const h=document.createElement("div");if(h.className="gengage-simrel-card-name gengage-chat-product-card-name",h.textContent=t.name,h.title=t.name,d.appendChild(h),t.rating!=null&&t.rating>0){const p=document.createElement("div");if(p.className="gengage-simrel-card-rating gengage-chat-product-card-rating",p.appendChild(fa(t.rating)),t.reviewCount!=null){const m=document.createElement("span");m.className="gengage-simrel-card-review-count gengage-chat-product-card-review-count",m.textContent=` (${t.reviewCount})`,p.appendChild(m)}d.appendChild(p)}const u=document.createElement("div");if(u.className="gengage-simrel-card-price gengage-chat-product-card-price",t.originalPrice&&t.originalPrice!==t.price&&(n==="strike-through"||!n)){const p=document.createElement("span");p.className="gengage-simrel-card-price-original gengage-chat-product-card-original-price",p.textContent=q(t.originalPrice,c),u.appendChild(p)}if(t.price&&parseFloat(t.price)>0){const p=document.createElement("span");p.className="gengage-simrel-card-price-current gengage-chat-product-card-price-current",p.textContent=q(t.price,c),u.appendChild(p)}d.appendChild(u),l.appendChild(d);const f=document.createElement("button");if(f.className="gengage-simrel-card-cta gengage-chat-product-card-cta gds-btn gds-btn-secondary",f.type="button",f.dataset.gengagePart="simrel-product-card-cta",f.textContent=s?.ctaLabel??"View",f.addEventListener("click",p=>{p.preventDefault(),p.stopPropagation(),r(t)}),l.appendChild(f),t.inStock===!1){const p=document.createElement("div");p.className="gengage-simrel-card-oos",p.textContent=s?.outOfStockLabel??"Out of Stock",l.appendChild(p)}else if(t.cartCode){const p=document.createElement("button");p.className="gengage-simrel-atc gengage-simrel-atc-button gds-btn gds-btn-secondary",p.type="button",p.textContent=s?.addToCartButton??"Add to Cart",p.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),i({sku:t.sku,quantity:1,cartCode:t.cartCode})}),l.appendChild(p)}return l.addEventListener("click",p=>{p.target.closest(".gengage-simrel-atc")||p.target.closest(".gengage-chat-product-card-atc")||p.target.closest(".gengage-chat-product-card-cta")||r(t)}),l}function mi(e){const t=document.createElement("div");t.className="gengage-simrel-grid",t.setAttribute("role","list"),t.setAttribute("aria-label",e.i18n?.similarProductsAriaLabel??"Similar products"),e.columns&&t.style.setProperty("--gengage-simrel-columns",String(e.columns));for(let a=0;a<e.products.length;a++){const n={product:e.products[a],index:a,onClick:e.onClick,onAddToCart:e.onAddToCart};e.i18n!==void 0&&(n.i18n=e.i18n),e.discountType!==void 0&&(n.discountType=e.discountType),e.renderCard!==void 0&&(n.renderCard=e.renderCard),e.renderCardElement!==void 0&&(n.renderCardElement=e.renderCardElement);const r=ui(n);t.appendChild(r)}return e.products.length===0&&(t.style.display="none",t.dataset.empty="true"),t}var vm=0;function ym(e){const t=vm++,a=document.createElement("div");if(a.className="gengage-simrel-groups",a.dataset.gengagePart="simrel-groups",e.groups.length===0)return a.style.display="none",a.dataset.empty="true",a;const n=document.createElement("div");n.className="gengage-simrel-tabs gds-toolbar",n.dataset.gengagePart="simrel-tab-bar",n.setAttribute("role","tablist");const r=[],i=[],o=p=>{const m={products:p.products,onClick:e.onClick,onAddToCart:e.onAddToCart};return e.i18n!==void 0&&(m.i18n=e.i18n),e.discountType!==void 0&&(m.discountType=e.discountType),e.renderCard!==void 0&&(m.renderCard=e.renderCard),e.renderCardElement!==void 0&&(m.renderCardElement=e.renderCardElement),e.columns!==void 0&&(m.columns=e.columns),m},s=p=>{for(let v=0;v<r.length;v++){const w=v===p;r[v].classList.toggle("gengage-simrel-tab--active",w),r[v].setAttribute("aria-selected",String(w)),r[v].tabIndex=w?0:-1}const m=e.groups[p],b=i[p];b.innerHTML="";const C=mi(o(m));b.appendChild(C);for(let v=0;v<i.length;v++){const w=v===p;i[v].style.display=w?"":"none",i[v].tabIndex=w?0:-1}};for(let p=0;p<e.groups.length;p++){const m=e.groups[p],b=`gengage-simrel-tab-${t}-${p}`,C=`gengage-simrel-panel-${t}-${p}`,v=document.createElement("button");v.className="gengage-simrel-tab gds-tab",v.type="button",v.dataset.gengagePart="simrel-tab",v.id=b,v.textContent=m.name,v.setAttribute("role","tab"),v.setAttribute("aria-controls",C),v.setAttribute("aria-selected",String(p===0)),v.tabIndex=p===0?0:-1,p===0&&v.classList.add("gengage-simrel-tab--active"),v.addEventListener("click",()=>s(p)),v.addEventListener("keydown",k=>{let A=-1;k.key==="ArrowRight"||k.key==="ArrowDown"?A=(p+1)%e.groups.length:k.key==="ArrowLeft"||k.key==="ArrowUp"?A=(p-1+e.groups.length)%e.groups.length:k.key==="Home"?A=0:k.key==="End"&&(A=e.groups.length-1),A>=0&&(k.preventDefault(),s(A),r[A].focus())}),r.push(v),n.appendChild(v);const w=document.createElement("div");w.className="gengage-simrel-tab-panel",w.dataset.gengagePart="simrel-tab-panel",w.id=C,w.setAttribute("role","tabpanel"),w.setAttribute("aria-labelledby",b),w.tabIndex=p===0?0:-1,p!==0&&(w.style.display="none"),i.push(w)}const c=document.createElement("button");c.type="button",c.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--left",c.setAttribute("aria-label",e.i18n?.scrollTabsLeft??"Scroll tabs left"),c.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"/></svg>';const l=document.createElement("button");l.type="button",l.className="gengage-simrel-tabs-arrow gengage-simrel-tabs-arrow--right",l.setAttribute("aria-label",e.i18n?.scrollTabsRight??"Scroll tabs right"),l.innerHTML='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"/></svg>';const g=200;c.addEventListener("click",()=>{n.scrollBy({left:-g,behavior:"smooth"})}),l.addEventListener("click",()=>{n.scrollBy({left:g,behavior:"smooth"})});const d=()=>{const p=n.scrollLeft<=4,m=n.scrollLeft+n.clientWidth>=n.scrollWidth-4;c.style.display=p?"none":"",l.style.display=m?"none":"",n.classList.toggle("gengage-simrel-tabs--peek-right",!m),n.classList.toggle("gengage-simrel-tabs--peek-left",!p)};n.addEventListener("scroll",d,{passive:!0}),typeof ResizeObserver<"u"&&new ResizeObserver(d).observe(n),c.style.display="none",l.style.display="none",requestAnimationFrame(d);const h=document.createElement("div");h.className="gengage-simrel-tabs-wrapper",h.appendChild(c),h.appendChild(n),h.appendChild(l),a.appendChild(h);const u=i[0],f=mi(o(e.groups[0]));u.appendChild(f);for(const p of i)a.appendChild(p);return a}function fi(e){if(!e||typeof e!="object")return null;const t=e;if(typeof t.sku!="string"||typeof t.name!="string"||typeof t.url!="string")return null;const a={sku:t.sku,name:t.name,url:t.url},n=t.imageUrl;typeof n=="string"&&(a.imageUrl=n);const r=t.price;typeof r=="string"&&(a.price=r);const i=t.originalPrice;typeof i=="string"&&(a.originalPrice=i);const o=t.discountPercent;typeof o=="number"&&(a.discountPercent=o);const s=t.brand;typeof s=="string"&&(a.brand=s);const c=t.rating;typeof c=="number"&&(a.rating=c);const l=t.reviewCount;typeof l=="number"&&(a.reviewCount=l);const g=t.cartCode;typeof g=="string"&&(a.cartCode=g);const d=t.inStock;typeof d=="boolean"&&(a.inStock=d);const h=t.extras;return h!=null&&typeof h=="object"&&(a.extras=h),a}function _m(e){if(!e||typeof e!="object")return null;const t=e,a=t.title,n=t.type;if(typeof a!="string"||typeof n!="string")return null;const r={title:a,type:n};return t.payload!==void 0&&(r.payload=t.payload),r}var bi={ProductGrid:({element:e,renderElement:t,context:a})=>{const n=document.createElement("div");n.className="gengage-simrel-grid",n.setAttribute("role","list");const r=e.props?.columns;let i;typeof r=="number"&&Number.isFinite(r)&&r>0?i=Math.floor(r):typeof a.gridColumns=="number"&&Number.isFinite(a.gridColumns)&&a.gridColumns>0&&(i=Math.floor(a.gridColumns)),i!==void 0&&n.style.setProperty("--gengage-simrel-columns",String(i));for(const o of e.children??[]){const s=t(o);s&&n.appendChild(s)}if(n.children.length===0){const o=document.createElement("div");o.className="gengage-simrel-empty",o.textContent=a.i18n.emptyStateMessage,n.appendChild(o)}return n},ProductCard:({element:e,context:t})=>{const a=fi(e.props?.product??e.props);if(!a)return null;const n=e.props?.index,r=typeof n=="number"&&Number.isFinite(n)?n:0,i=e.props?.discountType,o=i==="strike-through"||i==="badge"?i:t.discountType,s={product:a,index:r,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n};return o!==void 0&&(s.discountType=o),t.renderCard!==void 0&&(s.renderCard=t.renderCard),t.renderCardElement!==void 0&&(s.renderCardElement=t.renderCardElement),t.pricing!==void 0&&(s.pricing=t.pricing),ui(s)},GroupTabs:({element:e,context:t})=>{const a=e.props?.groups;if(!Array.isArray(a))return null;const n=[];for(const o of a){if(!o||typeof o!="object")continue;const s=o;if(typeof s.name!="string")continue;const c=[];if(Array.isArray(s.products))for(const g of s.products){const d=fi(g);d&&c.push(d)}const l={name:s.name,products:c};typeof s.highlight=="string"&&(l.highlight=s.highlight),n.push(l)}const r={groups:n,onClick:t.onClick,onAddToCart:t.onAddToCart,i18n:t.i18n},i=e.props?.columns;return typeof i=="number"&&Number.isFinite(i)&&i>0?r.columns=Math.floor(i):typeof t.gridColumns=="number"&&Number.isFinite(t.gridColumns)&&t.gridColumns>0&&(r.columns=Math.floor(t.gridColumns)),t.discountType!==void 0&&(r.discountType=t.discountType),t.renderCard!==void 0&&(r.renderCard=t.renderCard),t.renderCardElement!==void 0&&(r.renderCardElement=t.renderCardElement),ym(r)},EmptyState:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-empty";const n=e.props?.message;return a.textContent=typeof n=="string"?n:t.i18n.emptyStateMessage,a},AddToCartButton:({element:e,context:t})=>{const a=e.props?.sku,n=e.props?.cartCode;if(typeof a!="string"||typeof n!="string")return null;const r=document.createElement("button");r.className="gengage-simrel-atc gengage-chat-product-card-cta",r.type="button";const i=e.props?.label;return r.textContent=typeof i=="string"?i:t.i18n.addToCartButton,r.addEventListener("click",o=>{o.preventDefault(),o.stopPropagation(),t.onAddToCart({sku:a,quantity:1,cartCode:n})}),r},QuickActions:({element:e,context:t})=>{const a=document.createElement("div");a.className="gengage-simrel-quick-actions";const n=e.props?.actions;if(!Array.isArray(n)||!t.onAction)return a;for(const r of n){if(!r||typeof r!="object")continue;const i=r,o=i.label,s=_m(i.action);if(typeof o!="string"||!s)continue;const c=document.createElement("button");c.className="gengage-simrel-quick-action",c.type="button",c.textContent=o,c.addEventListener("click",l=>{l.preventDefault(),l.stopPropagation(),t.onAction?.(s)}),a.appendChild(c)}return a}},vi=({element:e,renderElement:t})=>{if(!e.children||e.children.length===0)return null;const a=document.createElement("div");for(const n of e.children){const r=t(n);r&&a.appendChild(r)}return a};function xm(){return{...bi}}function wm(e,t,a=bi,n=vi){return Yt({spec:e,context:t,registry:a,containerClassName:"gengage-simrel-uispec",unknownRenderer:n})}var yi={similarProductsAriaLabel:"Benzer ürünler",emptyStateMessage:"Benzer ürün bulunamadı.",addToCartButton:"Sepete Ekle",ctaLabel:"İncele",outOfStockLabel:"Stokta Yok",decreaseLabel:"Azalt",increaseLabel:"Artır",errorLoadingMessage:"Benzer ürünler yüklenemedi.",retryButtonText:"Tekrar dene",priceSuffix:" TL",scrollTabsLeft:"Sola kaydır",scrollTabsRight:"Sağa kaydır"},km={similarProductsAriaLabel:"Similar products",emptyStateMessage:"No similar products found.",addToCartButton:"Add to cart",ctaLabel:"View",outOfStockLabel:"Out of Stock",decreaseLabel:"Decrease",increaseLabel:"Increase",errorLoadingMessage:"Could not load similar products.",retryButtonText:"Try again",priceSuffix:"",scrollTabsLeft:"Scroll tabs left",scrollTabsRight:"Scroll tabs right"};function Cm(e){return e?e.toLowerCase().split("-")[0]??"tr":"tr"}function Sm(e){return Cm(e)==="en"?km:yi}var Em=class extends ft{constructor(...e){super(...e),this._abortController=null,this._contentEl=null,this._lastResultCount=-1,this._i18n=yi}async onInit(e){this._i18n=this._resolveI18n(e),this._contentEl=document.createElement("div"),this._contentEl.className="gengage-simrel-container",this._contentEl.dataset.gengagePart="simrel-container";const t=this._clampGridColumns(e.gridColumns);t!==void 0&&this._contentEl.style.setProperty("--gengage-simrel-columns",String(t)),this.root.appendChild(this._contentEl),this._lastSku=e.sku,await this._fetchAndRender(e.sku),Pt("simrel")}onUpdate(e){const t=e.sku;!t||t===this._lastSku&&this._lastResultCount!==0||(this._lastSku=t,this._fetchAndRender(t))}onShow(){this._contentEl&&(this._contentEl.style.opacity="0",this._contentEl.style.transition="opacity 0.3s ease-in",requestAnimationFrame(()=>{this._contentEl&&(this._contentEl.style.opacity="1")}))}onHide(){}onDestroy(){this._abort(),this._contentEl&&(this._contentEl.remove(),this._contentEl=null)}_handleProductClick(e){const t={sku:e.sku,name:e.name,url:e.url};if(e.imageUrl!==void 0&&(t.imageUrl=e.imageUrl),e.price!==void 0&&(t.price=e.price),e.originalPrice!==void 0&&(t.originalPrice=e.originalPrice),e.discountPercent!==void 0&&(t.discountPercent=e.discountPercent),e.brand!==void 0&&(t.brand=e.brand),e.rating!==void 0&&(t.rating=e.rating),e.reviewCount!==void 0&&(t.reviewCount=e.reviewCount),e.cartCode!==void 0&&(t.cartCode=e.cartCode),e.inStock!==void 0&&(t.inStock=e.inStock),this.config.onProductClick?.(t)===!1)return;Ca(e.sku,e.name);const a=this.config.session?.sessionId??null;ce("gengage:similar:product-click",{sku:e.sku,url:e.url,sessionId:a}),this.config.onProductNavigate?.(e.url,e.sku,a)}_handleAddToCart(e){Hn(e.sku,e.quantity),this.config.onAddToCart?.(e),ce("gengage:similar:add-to-cart",e),this.track(Ua(this.analyticsContext(),{attribution_source:"simrel",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:e.quantity,sku:e.sku}))}_abort(){this._abortController?.abort(),this._abortController=null}_isSuperseded(e){return this._abortController?.signal!==e}async _fetchAndRender(e){this._abort(),this._abortController=new AbortController;const t=this._abortController.signal,a=setTimeout(()=>this._abortController?.abort(),1e4);if(t.addEventListener("abort",()=>clearTimeout(a)),!this._contentEl)return;this._contentEl.innerHTML="",this._contentEl.style.display="";const n=document.createElement("div");n.className="gengage-simrel-loading",n.dataset.gengagePart="simrel-loading";const r=document.createElement("div");r.className="gengage-simrel-spinner",r.dataset.gengagePart="simrel-loading-spinner",n.appendChild(r),this._contentEl.appendChild(n);const i={middlewareUrl:this.config.middlewareUrl},o=crypto.randomUUID(),s=Date.now(),c=ti({source:"simrel",locale:this.config.locale});this.track(Qt(this.analyticsContext(),{endpoint:"similar_products",request_id:o,widget:"simrel"}));try{const l={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",sku:e};this.config.domain!==void 0&&(l.domain=this.config.domain);const g=await mm(l,i,t);if(this._lastResultCount=g.length,!this._contentEl)return;if(this._contentEl.innerHTML="",g.length>0)try{const d=g.map(f=>f.sku),h=new Map(g.map(f=>[f.sku,f])),u=(await bm({account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",skus:d},i,t)).map(f=>({...f,products:f.products.map(p=>({...h.get(p.sku),...p})).filter(p=>typeof p.sku=="string"&&typeof p.name=="string"&&typeof p.url=="string")})).filter(f=>f.products.length>0);if(u.length>0&&this._contentEl){const f=this._buildGroupsSpec(u),p=this._renderUISpec(f);this._contentEl.appendChild(p),At("simrel"),this.track(ut(this.analyticsContext(),{request_id:o,latency_ms:Date.now()-s,chunk_count:u.reduce((m,b)=>m+b.products.length,0),widget:"simrel"})),this.track(ea(this.analyticsContext(),{message_count:u.reduce((m,b)=>m+b.products.length,0),history_ref:o,redaction_level:"none",widget:"simrel"}));return}}catch{}if(this._isSuperseded(t))return;if(this._contentEl){const d=this._buildProductsSpec(g),h=this._renderUISpec(d);this._contentEl.appendChild(h)}g.length>0&&At("simrel"),this.track(ut(this.analyticsContext(),{request_id:o,latency_ms:Date.now()-s,chunk_count:g.length,widget:"simrel"})),this.track(ea(this.analyticsContext(),{message_count:g.length,history_ref:o,redaction_level:"none",widget:"simrel"}))}catch(l){if(l instanceof DOMException&&l.name==="AbortError"&&this._isSuperseded(t))return;if(ce("gengage:global:error",{source:"simrel",code:"FETCH_ERROR",message:Ka(this.config.locale,l)}),this.track(Xt(this.analyticsContext(),{request_id:o,error_code:"FETCH_ERROR",error_message:l instanceof Error?l.message:String(l),widget:"simrel"})),this._contentEl){this._contentEl.innerHTML="";const g=document.createElement("div");g.className="gengage-simrel-error";const d=document.createElement("span");d.textContent=this._i18n.errorLoadingMessage,g.appendChild(d);const h=document.createElement("button");h.className="gengage-simrel-retry",h.textContent=this._i18n.retryButtonText,h.addEventListener("click",()=>{this._fetchAndRender(this.config.sku)}),g.appendChild(h),this._contentEl.appendChild(g)}}finally{c()}}_clampGridColumns(e){if(!(e===void 0||typeof e!="number"||!Number.isFinite(e)))return Math.max(1,Math.min(12,Math.floor(e)))}_resolveI18n(e){return{...Sm(e.locale),...e.i18n}}_resolveUISpecRegistry(){return Jt(xm(),this.config.renderer?.registry)}_buildRenderContext(){const e=this.config.renderCard,t={onClick:n=>this._handleProductClick(n),onAddToCart:n=>this._handleAddToCart(n),i18n:this._i18n};this.config.discountType!==void 0&&(t.discountType=this.config.discountType),e!==void 0&&(t.renderCard=e),this.config.renderCardElement!==void 0&&(t.renderCardElement=this.config.renderCardElement),this.config.pricing!==void 0&&(t.pricing=this.config.pricing);const a=this._clampGridColumns(this.config.gridColumns);return a!==void 0&&(t.gridColumns=a),t}_renderUISpec(e){const t=this._resolveUISpecRegistry(),a=this._buildRenderContext(),n=this.config.renderer?.unknownRenderer??vi,r=(o,s)=>wm(o,s,t,n),i=this.config.renderer?.renderUISpec;return i?i(e,a,{registry:t,unknownRenderer:n,defaultRender:r}):r(e,a)}_buildProductsSpec(e){const t={},a=[];for(let i=0;i<e.length;i++){const o=e[i],s=`product-${i}`;a.push(s),t[s]={type:"ProductCard",props:{product:o,index:i,discountType:this.config.discountType}}}const n={layout:"grid"},r=this._clampGridColumns(this.config.gridColumns);return r!==void 0&&(n.columns=r),t.root={type:"ProductGrid",props:n,children:a},{root:"root",elements:t}}_buildGroupsSpec(e){return{root:"root",elements:{root:{type:"GroupTabs",props:{groups:e}}}}}},_i={findSimilarLabel:"Benzerlerini Bul"},Tm={findSimilarLabel:"Find Similar"};function Pm(e,t){return t?.findSimilarLabel?t.findSimilarLabel:(e??"tr").toLowerCase().startsWith("en")?Tm.findSimilarLabel:_i.findSimilarLabel}function Zt(e){const t=typeof e.sku=="string"&&e.sku.length>0?e.sku:void 0,a=typeof e.pageContext?.sku=="string"&&e.pageContext.sku.length>0?e.pageContext.sku:void 0;return t??a}var Am=class extends ft{constructor(...e){super(...e),this._button=null,this._label=_i.findSimilarLabel}async onInit(e){this._label=Pm(e.locale,e.i18n),this.root.classList.add("gengage-simbut-root"),window.getComputedStyle(this.root).position==="static"&&(this.root.style.position="relative");const t=document.createElement("button");t.type="button",t.className="gengage-chat-find-similar-pill",t.textContent=this._label,this._button=t;const a=()=>{t.disabled=!(Zt(this.config)&&(this.config.onFindSimilar||this.config.chat))};t.addEventListener("click",n=>{n.stopPropagation();const r=Zt(this.config);if(!r)return;const i=this.config.imageUrl,o=typeof i=="string"&&pe(i)?i:void 0;if(ka(this._label,"findSimilar"),Un(r),this.config.onFindSimilar){this.config.onFindSimilar(o?{sku:r,imageUrl:o}:{sku:r});return}const s=this.config.chat;if(!s)return;const c={title:this._label,type:"findSimilar",payload:o?{sku:r,image_url:o}:{sku:r}};s.openWithAction(c,{sku:r})}),this.root.appendChild(t),a(),Pt("simbut")}onUpdate(e){if(!this._button)return;const t=!!Zt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}hide(){this.isVisible&&(this.isVisible=!1,this._button&&(this._button.style.display="none"),this.onHide(),this.emit("hide"))}show(){this.isVisible||(this.isVisible=!0,this._button&&(this._button.style.display=""),this.onShow(),this.emit("show"))}_cleanupRoot(){}onShow(){}onHide(){}onDestroy(){this._button?.remove(),this._button=null}setChat(e){if(this.config.chat=e,this._button){const t=!!Zt(this.config)&&(!!this.config.onFindSimilar||!!this.config.chat);this._button.disabled=!t}}},Vt=Be({enabled:We().default(!0)}),Lm=Be({chat:Ce().optional(),qna:Ce().optional(),simrel:Ce().optional(),simbut:Ce().optional()}),Im=Be({}),Nm=Ra(["none","x-api-key-header","bearer-header","body-api-key"]),zm=Be({mode:Nm.default("none"),key:Ce().optional(),headerName:Ce().optional(),bodyField:Ce().default("api_key")}),Mm=Be({enabled:We().default(!0),endpoint:Ce().default("/analytics"),auth:zm.default({mode:"none",bodyField:"api_key"}),fireAndForget:We().default(!0),useBeacon:We().default(!0),keepaliveFetch:We().default(!0),timeoutMs:Hr().int().positive().default(4e3),maxRetries:Hr().int().min(0).max(5).default(1)}),xi="__gengageWidgetsInit",Bm=Be({idempotencyKey:Ce().default(xi),requireDomReady:We().default(!0)}),Rm=Ra(["log-and-ignore","throw","delegate"]),Om=Be({unknownActionPolicy:Rm.default("log-and-ignore"),allowScriptCall:We().default(!1)}),uf=Be({version:Tu("1",{error:'version must be "1"'}),accountId:Ce({error:"accountId must be a non-empty string"}).min(1,{error:"accountId must be a non-empty string"}),middlewareUrl:Ce({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}).url({error:'middlewareUrl must be a valid URL (e.g. "https://your-backend.example.com")'}),locale:Ce().optional(),widgets:Be({chat:Vt.default({enabled:!0}),qna:Vt.default({enabled:!0}),simrel:Vt.default({enabled:!0}),simbut:Vt.default({enabled:!1})}),mounts:Lm.default({}),transport:Im.default({}),analytics:Mm.default({enabled:!0,endpoint:"/analytics",auth:{mode:"none",bodyField:"api_key"},fireAndForget:!0,useBeacon:!0,keepaliveFetch:!0,timeoutMs:4e3,maxRetries:1}),gtm:Bm.default({idempotencyKey:"__gengageWidgetsInit",requireDomReady:!0}),actionHandling:Om.default({unknownActionPolicy:"log-and-ignore",allowScriptCall:!1})}),Dm=`${xi}_overlay_`,Fm="#gengage-qna",$m="#gengage-simrel",Um="#gengage-simbut";function wi(){const e=window;return e.__gengageOverlayRegistry||(e.__gengageOverlayRegistry={instances:{},pending:{}}),e.__gengageOverlayRegistry}function Hm(e){const t={pageType:e.pageContext?.pageType??(e.sku!==void 0?"pdp":"other")},a=e.pageContext;return a?.sku!==void 0&&(t.sku=a.sku),a?.price!==void 0&&(t.price=a.price),a?.categoryTree!==void 0&&(t.categoryTree=a.categoryTree),a?.url!==void 0&&(t.url=a.url),a?.extra!==void 0&&(t.extra=a.extra),e.sku!==void 0&&(t.sku=e.sku),t}function qm(e,t){const a={...e,...t,pageType:t.pageType??e.pageType};return t.sku===void 0&&e.sku!==void 0&&(a.sku=e.sku),a}function Fa(e){return e instanceof HTMLElement||document.querySelector(e)?e:null}function ki(e){return e.idempotencyKey??`${Dm}${e.accountId}`}var jm=class{constructor(e,t){this.options=e,this.onDestroy=t,this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,this._analyticsClient=null,this._offQnaWire=null,this._destroyed=!1,this._queue=Promise.resolve(),this._warnedQnaMountMissing=!1,this._warnedSimRelMountMissing=!1,this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this.idempotencyKey=ki(e),this.session=ja(e.session),this._pageContext=Hm(e)}get chat(){return this._chat}get qna(){return this._qna}get simrel(){return this._simrel}get simbut(){return this._simbut}get analyticsClient(){return this._analyticsClient}async init(){window.gengage||(window.gengage={}),window.gengage.sessionId=this.session.sessionId,window.gengage.pageContext=this._pageContext,await this._initChat(),this.options.wireQnaToChat!==!1&&(this._offQnaWire=Ki()),await this._syncPdpWidgets(),window.gengage.overlay=this}openChat(e){this._chat?.open(e)}closeChat(){this._chat?.close()}async updateContext(e){this._destroyed||await this._enqueue(async()=>{this._pageContext=qm(this._pageContext,e),window.gengage||(window.gengage={}),window.gengage.pageContext=this._pageContext,this._chat?.update(e),this._qna?.update(e),this._simrel?.update(e),this._simbut?.update(e),await this._syncPdpWidgets()})}async updateSku(e,t="pdp"){await this.updateContext({sku:e,pageType:t})}destroy(){this._destroyed||(this._destroyed=!0,this._offQnaWire?.(),this._offQnaWire=null,this._chat?.destroy(),this._qna?.destroy(),this._simrel?.destroy(),this._simbut?.destroy(),this._chat=null,this._qna=null,this._simrel=null,this._simbut=null,window.gengage?.overlay===this&&delete window.gengage.overlay,this.onDestroy())}async _initChat(){if(this.options.chat?.enabled===!1)return;const e=this.options.middlewareUrl,t=this.options.chat?.productDetailsExtended??this.options.productDetailsExtended,a=this.options.chat?.isDemoWebsite??this.options.isDemoWebsite,n={accountId:this.options.accountId,middlewareUrl:e,session:this.session,pageContext:this._pageContext,variant:this.options.chat?.variant??"floating"};this.options.theme!==void 0&&(n.theme=this.options.theme),this.options.locale!==void 0&&(n.locale=this.options.locale),this.options.pricing!==void 0&&(n.pricing=this.options.pricing),this.options.chat?.mountTarget!==void 0&&(n.mountTarget=this.options.chat.mountTarget),this.options.chat?.pillLauncher!==void 0&&(n.pillLauncher=this.options.chat.pillLauncher),this.options.chat?.launcherImageUrl!==void 0?n.launcherImageUrl=this.options.chat.launcherImageUrl:this.options.chat?.launcherSvg!==void 0&&(n.launcherSvg=this.options.chat.launcherSvg),this.options.chat?.headerTitle!==void 0&&(n.headerTitle=this.options.chat.headerTitle),this.options.chat?.headerAvatarUrl!==void 0&&(n.headerAvatarUrl=this.options.chat.headerAvatarUrl),this.options.chat?.headerBadge!==void 0&&(n.headerBadge=this.options.chat.headerBadge),this.options.chat?.headerCartUrl!==void 0&&(n.headerCartUrl=this.options.chat.headerCartUrl),this.options.chat?.headerFavoritesToggle!==void 0&&(n.headerFavoritesToggle=this.options.chat.headerFavoritesToggle),this.options.chat?.onFavoritesClick!==void 0&&(n.onFavoritesClick=this.options.chat.onFavoritesClick),this.options.chat?.hideMobileLauncher!==void 0&&(n.hideMobileLauncher=this.options.chat.hideMobileLauncher),this.options.chat?.mobileBreakpoint!==void 0&&(n.mobileBreakpoint=this.options.chat.mobileBreakpoint),this.options.chat?.mobileInitialState!==void 0&&(n.mobileInitialState=this.options.chat.mobileInitialState),this.options.chat?.i18n!==void 0&&(n.i18n=this.options.chat.i18n),this.options.chat?.actionHandling!==void 0&&(n.actionHandling=this.options.chat.actionHandling),this.options.chat?.renderer!==void 0&&(n.renderer=this.options.chat.renderer),t!==void 0&&(n.productDetailsExtended=t),a!==void 0&&(n.isDemoWebsite=a),this.options.chat?.productPriceUi!==void 0&&(n.productPriceUi=this.options.chat.productPriceUi),this.options.onScriptCall!==void 0&&(n.onScriptCall=this.options.onScriptCall),this.options.onAddToCart!==void 0&&(n.onAddToCart=this.options.onAddToCart),this.options.chat?.onOpen!==void 0&&(n.onOpen=this.options.chat.onOpen),this.options.chat?.onClose!==void 0&&(n.onClose=this.options.chat.onClose),this._chat=new Vu,await this._chat.init(n)}async _syncPdpWidgets(){if(this._destroyed)return;const e=this._pageContext.sku;if(!(this._pageContext.pageType==="pdp"&&e!==void 0&&e.length>0)){this._qna?.hide(),this._simrel?.hide(),this._simbut?.hide();return}const t=this.options.middlewareUrl;if(this.options.qna?.enabled!==!1){const a=this.options.qna?.mountTarget??Fm,n=Fa(a);if(n)if(this._warnedQnaMountMissing=!1,this._qna)this._qna.show(),this._qna.update({pageType:"pdp",sku:e});else{const r=new hm,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.qna?.ctaText!==void 0&&(i.ctaText=this.options.qna.ctaText),this.options.qna?.hideButtonRowCta!==void 0&&(i.hideButtonRowCta=this.options.qna.hideButtonRowCta),this.options.qna?.inputPlaceholder!==void 0&&(i.inputPlaceholder=this.options.qna.inputPlaceholder),this.options.qna?.i18n!==void 0&&(i.i18n=this.options.qna.i18n),this.options.qna?.renderer!==void 0&&(i.renderer=this.options.qna.renderer);const o=this.options.qna?.headerTitle??this.options.qna?.headingTitle;o!==void 0&&(i.headerTitle=o),await r.init(i),this._qna=r}else this._qna?.destroy(),this._qna=null,this._warnedQnaMountMissing||(console.warn(`[gengage] QNA mount target not found: ${a}`),this._warnedQnaMountMissing=!0)}else this._qna?.destroy(),this._qna=null;if(this.options.simrel?.enabled!==!1){const a=this.options.simrel?.mountTarget??$m,n=Fa(a);if(n)if(this._warnedSimRelMountMissing=!1,this._simrel)this._simrel.show(),this._simrel.update({pageType:"pdp",sku:e});else{const r=new Em,i={accountId:this.options.accountId,middlewareUrl:t,session:this.session,sku:e,mountTarget:n};this.options.theme!==void 0&&(i.theme=this.options.theme),this.options.pricing!==void 0&&(i.pricing=this.options.pricing),this.options.simrel?.discountType!==void 0&&(i.discountType=this.options.simrel.discountType),this.options.simrel?.renderCardElement!==void 0&&(i.renderCardElement=this.options.simrel.renderCardElement),this.options.simrel?.renderer!==void 0&&(i.renderer=this.options.simrel.renderer),this.options.onAddToCart!==void 0&&(i.onAddToCart=this.options.onAddToCart),this.options.onProductNavigate!==void 0?i.onProductNavigate=this.options.onProductNavigate:i.onProductNavigate=(o,s,c)=>{pe(o)&&(this._chat?.saveSession(c??this.session.sessionId,s),window.location.href=o)},await r.init(i),this._simrel=r}else this._simrel?.destroy(),this._simrel=null,this._warnedSimRelMountMissing||(console.warn(`[gengage] SimRel mount target not found: ${a}`),this._warnedSimRelMountMissing=!0)}else this._simrel?.destroy(),this._simrel=null;if(this.options.simbut&&this.options.simbut.enabled!==!1){const a=this.options.simbut.mountTarget??Um,n=Fa(a),r=this._chat??this.options.simbut.onFindSimilar;if(n&&r)if(this._warnedSimButMountMissing=!1,this._warnedSimButNoChat=!1,this._simbut)this._simbut.show(),this._simbut.setChat(this._chat),this._simbut.update({pageType:"pdp",sku:e});else{const i=new Am,o={accountId:this.options.accountId,middlewareUrl:t,session:this.session,pageContext:{pageType:"pdp",sku:e},mountTarget:n,chat:this._chat};this.options.theme!==void 0&&(o.theme=this.options.theme),this.options.locale!==void 0&&(o.locale=this.options.locale),this.options.simbut.imageUrl!==void 0&&(o.imageUrl=this.options.simbut.imageUrl),this.options.simbut.i18n!==void 0&&(o.i18n=this.options.simbut.i18n),this.options.simbut.onFindSimilar!==void 0&&(o.onFindSimilar=this.options.simbut.onFindSimilar),await i.init(o),this._simbut=i}else this._simbut?.destroy(),this._simbut=null,!n&&!this._warnedSimButMountMissing?(console.warn(`[gengage] SimBut mount target not found: ${a}`),this._warnedSimButMountMissing=!0):!r&&!this._warnedSimButNoChat&&(console.warn("[gengage] SimBut requires chat to be enabled or simbut.onFindSimilar"),this._warnedSimButNoChat=!0)}else this._simbut?.destroy(),this._simbut=null}_enqueue(e){const t=this._queue.then(e);return this._queue=t.catch(a=>{}),t}};async function Zm(e){const t=ki(e),a=wi(),n=a.instances[t];if(n)return n;const r=a.pending[t];if(r)return r;const i=new jm(e,()=>{const s=wi();delete s.instances[t],delete s.pending[t]}),o=i.init().then(()=>(a.instances[t]=i,delete a.pending[t],i)).catch(s=>{throw delete a.pending[t],s});return a.pending[t]=o,o}var Ci=["gengage:chat:open","gengage:chat:close","gengage:chat:ready","gengage:chat:add-to-cart","gengage:qna:action","gengage:qna:open-chat","gengage:similar:product-click","gengage:similar:add-to-cart","gengage:global:error","gengage:context:update"],Vm=32,Si="#gengage-qna",Ei="#gengage-simrel";function mf(e){return e}function Wm(e){let t=e;if(typeof e=="string"){const i=e.trim();if(i.length===0)return null;if(!i.startsWith("{")&&!i.startsWith("["))return{type:i};try{t=JSON.parse(i)}catch{return null}}if(!t||typeof t!="object")return null;const a=t,n=[a.type,a.command,a.action,a.event].find(i=>typeof i=="string"&&i.length>0);if(!n)return null;let r=a.payload;if(r===void 0&&"data"in a&&(r=a.data),n==="setSession"&&r===void 0){const i={};typeof a.sessionId=="string"&&(i.sessionId=a.sessionId),typeof a.userId=="string"&&(i.userId=a.userId),(i.sessionId!==void 0||i.userId!==void 0)&&(r=i)}return r===void 0?{type:n}:{type:n,payload:r}}function Gm(e){if(typeof e=="string"&&e.length>0)return{sku:e};if(e&&typeof e=="object"&&"sku"in e){const t=e.sku;if(typeof t=="string"&&t.length>0){const a=e.pageType;return a!==void 0?{sku:t,pageType:a}:{sku:t}}}return null}function $a(e,t){return t instanceof HTMLElement?!0:typeof t!="string"?!1:e.document.querySelector(t)!==null}function Ti(e,t,a){if(t instanceof HTMLElement||$a(e,t)||typeof t!="string")return t;if(t.startsWith("#")){const i=t.slice(1);if(i.length>0){const o=e.document.getElementById(i);if(o)return o;const s=e.document.createElement("div");return s.id=i,e.document.body.appendChild(s),s}}const n=e.document.getElementById(a);if(n)return n;const r=e.document.createElement("div");return r.id=a,e.document.body.appendChild(r),r}function Pi(e,t){const a=e.webkit?.messageHandlers?.[t];return a&&typeof a.postMessage=="function"?a.postMessage.bind(a):null}function Wt(e,t){const a=e[t];return a&&typeof a=="object"&&typeof a.postMessage=="function"?a:null}function Ai(e={}){const t=e.win??window,a=e.iosHandlerName??"gengage",n=e.androidInterfaceName??"GengageNative",r=e.reactNativeInterfaceName??"ReactNativeWebView";return Pi(t,a)?"ios":Wt(t,n)?"android":Wt(t,r)?"react-native":"browser"}function Li(e,t={}){const a=t.win??window;if(e.sessionId!==void 0){a.__gengageSessionId=e.sessionId,a.gengage||(a.gengage={}),a.gengage.sessionId=e.sessionId;try{a.sessionStorage.setItem("gengage_session_id",e.sessionId)}catch{}}if(e.userId!==void 0){a.gengage||(a.gengage={});const n=a.gengage,r=n.session??{};r.userId=e.userId,n.session=r}}function Ii(e={}){const t=e.win??window,a=t;if(a.gengageNative)return a.gengageNative;const n=e.iosHandlerName??"gengage",r=e.androidInterfaceName??"GengageNative",i=e.reactNativeInterfaceName??"ReactNativeWebView",o=e.trackedEvents??[...Ci],s=Ai({win:t,iosHandlerName:n,androidInterfaceName:r,reactNativeInterfaceName:i});let c=t.gengage?.overlay??null;const l=[],g=(b,C)=>{const v=C===void 0?{type:b}:{type:b,payload:C};if(s==="ios"){Pi(t,n)?.(v);return}if(s==="android"){Wt(t,r)?.postMessage(JSON.stringify(v));return}if(s==="react-native"){Wt(t,i)?.postMessage(JSON.stringify(v));return}},d=b=>{const C=b.detail;!C||typeof C.namespace!="string"||typeof C.type!="string"||g("bridge_message",{namespace:C.namespace,type:C.type,payload:C.payload})};t.addEventListener("gengage:bridge:message",d);const h=o.map(b=>{const C=v=>{const w=v.detail;g("widget_event",{event:b,detail:w})};return t.addEventListener(b,C),{event:b,handler:C}}),u=b=>{l.length>=Vm&&l.shift(),l.push(b)},f=()=>{if(!c||l.length===0)return;const b=l.splice(0,l.length);for(const C of b)p(C)},p=b=>{const C=Wm(b);if(!C||typeof C.type!="string"){console.warn("[gengage:native-bridge] Invalid message:",b);return}const v=C.type,w=C.payload;switch(v){case"openChat":c?c.openChat(w&&typeof w=="object"?w:w==="half"||w==="full"?{state:w}:void 0):u(C);return;case"closeChat":c?c.closeChat():u(C);return;case"updateContext":c&&w&&typeof w=="object"?c.updateContext(w):c?console.warn("[gengage:native-bridge] updateContext: missing payload"):u(C);return;case"updateSku":{const k=Gm(w);if(c&&k){c.updateSku(k.sku,k.pageType);return}c?console.warn("[gengage:native-bridge] updateSku: missing sku"):u(C);return}case"setSession":w&&typeof w=="object"&&Li(w,{win:t});return;case"destroy":c?.destroy();return;default:t.postMessage({gengage:"native",type:v,payload:w},t.location.origin),e.logUnhandled&&console.warn("[gengage:native-bridge] Unhandled inbound type forwarded:",v)}},m={env:s,sendToNative:g,receive:p,setController(b){c=b,f()},destroy(){t.removeEventListener("gengage:bridge:message",d);for(const b of h)t.removeEventListener(b.event,b.handler);l.splice(0,l.length),t.gengageNative===m&&delete t.gengageNative}};return a.gengageNative=m,m}async function Km(e){const{nativeBridge:t,emitReadyEvent:a=!0,...n}=e,r=Ii(t),i={...n};i.onAddToCart||(i.onAddToCart=l=>{r.sendToNative("addToCart",{sku:l.sku,quantity:l.quantity,cartCode:l.cartCode})}),i.onProductNavigate||(i.onProductNavigate=(l,g,d)=>{r.sendToNative("productNavigate",{url:l,sku:g,sessionId:d})});const o=i.qna?.enabled===!0||i.qna?.mountTarget!==void 0;if(i.qna?.enabled!==!1)if(o){const l=Ti(window,i.qna?.mountTarget??Si,"gengage-qna");i.qna={...i.qna,enabled:!0,mountTarget:l}}else $a(window,Si)||(i.qna={enabled:!1});const s=i.simrel?.enabled===!0||i.simrel?.mountTarget!==void 0;if(i.simrel?.enabled!==!1)if(s){const l=Ti(window,i.simrel?.mountTarget??Ei,"gengage-simrel");i.simrel={...i.simrel,enabled:!0,mountTarget:l}}else $a(window,Ei)||(i.simrel={enabled:!1});const c=await Zm(i);return r.setController(c),a&&r.sendToNative("ready",{sessionId:c.session.sessionId,widgets:{chat:c.chat!==null,qna:c.qna!==null,simrel:c.simrel!==null}}),{controller:c,bridge:r,destroy(){c.destroy(),r.destroy()}}}Ye.DEFAULT_NATIVE_TRACKED_EVENTS=Ci,Ye.applyNativeSession=Li,Ye.createNativeWebViewBridge=Ii,Ye.detectNativeEnvironment=Ai,Ye.initNativeOverlayWidgets=Km})(this.Gengage=this.Gengage||{});
|