@gengage/assistant-fe 0.3.39 → 0.3.40

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