@gengage/assistant-fe 0.3.23 → 0.3.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6145,7 +6145,7 @@ var Kr = class Ae extends Ea {
6145
6145
  widget: "chat"
6146
6146
  })), !this._drawer)) return;
6147
6147
  let A = g;
6148
- const M = y?.kvkk === !0 || ot(A);
6148
+ const M = y?.kvkk === !0 || r && ot(A);
6149
6149
  if (_ && M) {
6150
6150
  const z = this.config.accountId;
6151
6151
  if (!Et(z)) {
package/dist/chat.iife.js CHANGED
@@ -173,6 +173,6 @@ button[data-gengage-part="chat-launcher-button"] img {
173
173
 
174
174
  `)}h.write("payload.value = newResult;"),h.write("return payload;");const M=h.compile();return(C,P)=>M(p,C,P)};let i;const o=Pt,s=!sa.jitless,l=s&&Ll.value,g=t.catchall;let d;e._zod.parse=(p,h)=>{d??(d=n.value);const m=p.value;return o(m)?s&&l&&h?.async===!1&&h.jitless!==!0?(i||(i=r(t.shape)),p=i(p,h),g?Yn([],m,p,h,d,e):p):a(p,h):(p.issues.push({expected:"object",code:"invalid_type",input:m,inst:e}),p)}});function Jn(e,t,a,n){for(const i of e)if(i.issues.length===0)return t.value=i.value,t;const r=e.filter(i=>!it(i));return r.length===1?(t.value=r[0].value,r[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:a,errors:e.map(i=>i.issues.map(o=>Ve(o,n,je())))}),t)}var cg=k("$ZodUnion",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Q(e._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Q(e._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Q(e._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>ga(i.source)).join("|")})$`)}});const a=t.options.length===1,n=t.options[0]._zod.run;e._zod.parse=(r,i)=>{if(a)return n(r,i);let o=!1;const s=[];for(const c of t.options){const l=c._zod.run({value:r.value,issues:[]},i);if(l instanceof Promise)s.push(l),o=!0;else{if(l.issues.length===0)return l;s.push(l)}}return o?Promise.all(s).then(c=>Jn(c,r,e,i)):Jn(s,r,e,i)}}),lg=k("$ZodIntersection",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{const r=a.value,i=t.left._zod.run({value:r,issues:[]},n),o=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||o instanceof Promise?Promise.all([i,o]).then(([s,c])=>Xn(a,s,c)):Xn(a,i,o)}});function ua(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(rt(e)&&rt(t)){const a=Object.keys(t),n=Object.keys(e).filter(i=>a.indexOf(i)!==-1),r={...e,...t};for(const i of n){const o=ua(e[i],t[i]);if(!o.valid)return{valid:!1,mergeErrorPath:[i,...o.mergeErrorPath]};r[i]=o.data}return{valid:!0,data:r}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const a=[];for(let n=0;n<e.length;n++){const r=e[n],i=t[n],o=ua(r,i);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};a.push(o.data)}return{valid:!0,data:a}}return{valid:!1,mergeErrorPath:[]}}function Xn(e,t,a){const n=new Map;let r;for(const s of t.issues)if(s.code==="unrecognized_keys"){r??(r=s);for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).l=!0}else e.issues.push(s);for(const s of a.issues)if(s.code==="unrecognized_keys")for(const c of s.keys)n.has(c)||n.set(c,{}),n.get(c).r=!0;else e.issues.push(s);const i=[...n].filter(([,s])=>s.l&&s.r).map(([s])=>s);if(i.length&&r&&e.issues.push({...r,keys:i}),it(e))return e;const o=ua(t.value,a.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}var dg=k("$ZodRecord",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{const r=a.value;if(!rt(r))return a.issues.push({expected:"record",code:"invalid_type",input:r,inst:e}),a;const i=[],o=t.keyType._zod.values;if(o){a.value={};const s=new Set;for(const l of o)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){s.add(typeof l=="number"?l.toString():l);const g=t.valueType._zod.run({value:r[l],issues:[]},n);g instanceof Promise?i.push(g.then(d=>{d.issues.length&&a.issues.push(...ot(l,d.issues)),a.value[l]=d.value})):(g.issues.length&&a.issues.push(...ot(l,g.issues)),a.value[l]=g.value)}let c;for(const l in r)s.has(l)||(c=c??[],c.push(l));c&&c.length>0&&a.issues.push({code:"unrecognized_keys",input:r,inst:e,keys:c})}else{a.value={};for(const s of Reflect.ownKeys(r)){if(s==="__proto__")continue;let c=t.keyType._zod.run({value:s,issues:[]},n);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof s=="string"&&Un.test(s)&&c.issues.length){const g=t.keyType._zod.run({value:Number(s),issues:[]},n);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(c=g)}if(c.issues.length){t.mode==="loose"?a.value[s]=r[s]:a.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(g=>Ve(g,n,je())),input:s,path:[s],inst:e});continue}const l=t.valueType._zod.run({value:r[s],issues:[]},n);l instanceof Promise?i.push(l.then(g=>{g.issues.length&&a.issues.push(...ot(s,g.issues)),a.value[c.value]=g.value})):(l.issues.length&&a.issues.push(...ot(s,l.issues)),a.value[c.value]=l.value)}}return i.length?Promise.all(i).then(()=>a):a}}),gg=k("$ZodEnum",(e,t)=>{ie.init(e,t);const a=kn(t.entries),n=new Set(a);e._zod.values=n,e._zod.pattern=new RegExp(`^(${a.filter(r=>Il.has(typeof r)).map(r=>typeof r=="string"?At(r):r.toString()).join("|")})$`),e._zod.parse=(r,i)=>{const o=r.value;return n.has(o)||r.issues.push({code:"invalid_value",values:a,input:o,inst:e}),r}}),pg=k("$ZodTransform",(e,t)=>{ie.init(e,t),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(e.constructor.name);const r=t.transform(a.value,a);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(i=>(a.value=i,a));if(r instanceof Promise)throw new nt;return a.value=r,a}});function Qn(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}var er=k("$ZodOptional",(e,t)=>{ie.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Q(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${ga(a.source)})?$`):void 0}),e._zod.parse=(a,n)=>{if(t.innerType._zod.optin==="optional"){const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>Qn(i,a.value)):Qn(r,a.value)}return a.value===void 0?a:t.innerType._zod.run(a,n)}}),hg=k("$ZodExactOptional",(e,t)=>{er.init(e,t),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(a,n)=>t.innerType._zod.run(a,n)}),ug=k("$ZodNullable",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"pattern",()=>{const a=t.innerType._zod.pattern;return a?new RegExp(`^(${ga(a.source)}|null)$`):void 0}),Q(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(a,n)=>a.value===null?a:t.innerType._zod.run(a,n)}),mg=k("$ZodDefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);if(a.value===void 0)return a.value=t.defaultValue,a;const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>tr(i,t)):tr(r,t)}});function tr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var fg=k("$ZodPrefault",(e,t)=>{ie.init(e,t),e._zod.optin="optional",Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>(n.direction==="backward"||a.value===void 0&&(a.value=t.defaultValue),t.innerType._zod.run(a,n))}),bg=k("$ZodNonOptional",(e,t)=>{ie.init(e,t),Q(e._zod,"values",()=>{const a=t.innerType._zod.values;return a?new Set([...a].filter(n=>n!==void 0)):void 0}),e._zod.parse=(a,n)=>{const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>ar(i,e)):ar(r,e)}});function ar(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}var vg=k("$ZodCatch",(e,t)=>{ie.init(e,t),Q(e._zod,"optin",()=>t.innerType._zod.optin),Q(e._zod,"optout",()=>t.innerType._zod.optout),Q(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(i=>(a.value=i.value,i.issues.length&&(a.value=t.catchValue({...a,error:{issues:i.issues.map(o=>Ve(o,n,je()))},input:a.value}),a.issues=[]),a)):(a.value=r.value,r.issues.length&&(a.value=t.catchValue({...a,error:{issues:r.issues.map(i=>Ve(i,n,je()))},input:a.value}),a.issues=[]),a)}}),yg=k("$ZodPipe",(e,t)=>{ie.init(e,t),Q(e._zod,"values",()=>t.in._zod.values),Q(e._zod,"optin",()=>t.in._zod.optin),Q(e._zod,"optout",()=>t.out._zod.optout),Q(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(a,n)=>{if(n.direction==="backward"){const i=t.out._zod.run(a,n);return i instanceof Promise?i.then(o=>Rt(o,t.in,n)):Rt(i,t.in,n)}const r=t.in._zod.run(a,n);return r instanceof Promise?r.then(i=>Rt(i,t.out,n)):Rt(r,t.out,n)}});function Rt(e,t,a){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},a)}var _g=k("$ZodReadonly",(e,t)=>{ie.init(e,t),Q(e._zod,"propValues",()=>t.innerType._zod.propValues),Q(e._zod,"values",()=>t.innerType._zod.values),Q(e._zod,"optin",()=>t.innerType?._zod?.optin),Q(e._zod,"optout",()=>t.innerType?._zod?.optout),e._zod.parse=(a,n)=>{if(n.direction==="backward")return t.innerType._zod.run(a,n);const r=t.innerType._zod.run(a,n);return r instanceof Promise?r.then(nr):nr(r)}});function nr(e){return e.value=Object.freeze(e.value),e}var xg=k("$ZodCustom",(e,t)=>{ue.init(e,t),ie.init(e,t),e._zod.parse=(a,n)=>a,e._zod.check=a=>{const n=a.value,r=t.fn(n);if(r instanceof Promise)return r.then(i=>rr(i,a,n,e));rr(r,a,n,e)}});function rr(e,t,a,n){if(!e){const r={code:"custom",input:a,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(r.params=n._zod.def.params),t.issues.push(mt(r))}}var ir,wg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const a=t[0];return this._map.set(e,a),a&&typeof a=="object"&&"id"in a&&this._idmap.set(a.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const a={...this.get(t)??{}};delete a.id;const n={...a,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function kg(){return new wg}(ir=globalThis).__zod_globalRegistry??(ir.__zod_globalRegistry=kg());var $e=globalThis.__zod_globalRegistry;function Cg(e,t){return new e({type:"string",...$(t)})}function Sg(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...$(t)})}function or(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...$(t)})}function Eg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...$(t)})}function Pg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...$(t)})}function Ag(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...$(t)})}function Tg(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...$(t)})}function Lg(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...$(t)})}function Ig(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...$(t)})}function Ng(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...$(t)})}function zg(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...$(t)})}function Mg(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...$(t)})}function Bg(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...$(t)})}function Rg(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...$(t)})}function Dg(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...$(t)})}function Og(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...$(t)})}function $g(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...$(t)})}function Fg(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...$(t)})}function Hg(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...$(t)})}function Ug(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...$(t)})}function jg(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...$(t)})}function Zg(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...$(t)})}function qg(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...$(t)})}function Vg(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...$(t)})}function Gg(e,t){return new e({type:"string",format:"date",check:"string_format",...$(t)})}function Wg(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...$(t)})}function Kg(e,t){return new e({type:"string",format:"duration",check:"string_format",...$(t)})}function Yg(e,t){return new e({type:"number",checks:[],...$(t)})}function Jg(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...$(t)})}function Xg(e,t){return new e({type:"boolean",...$(t)})}function Qg(e){return new e({type:"unknown"})}function ep(e,t){return new e({type:"never",...$(t)})}function sr(e,t){return new Zn({check:"less_than",...$(t),value:e,inclusive:!1})}function ma(e,t){return new Zn({check:"less_than",...$(t),value:e,inclusive:!0})}function cr(e,t){return new qn({check:"greater_than",...$(t),value:e,inclusive:!1})}function fa(e,t){return new qn({check:"greater_than",...$(t),value:e,inclusive:!0})}function lr(e,t){return new fd({check:"multiple_of",...$(t),value:e})}function dr(e,t){return new vd({check:"max_length",...$(t),maximum:e})}function Dt(e,t){return new yd({check:"min_length",...$(t),minimum:e})}function gr(e,t){return new _d({check:"length_equals",...$(t),length:e})}function tp(e,t){return new xd({check:"string_format",format:"regex",...$(t),pattern:e})}function ap(e){return new wd({check:"string_format",format:"lowercase",...$(e)})}function np(e){return new kd({check:"string_format",format:"uppercase",...$(e)})}function rp(e,t){return new Cd({check:"string_format",format:"includes",...$(t),includes:e})}function ip(e,t){return new Sd({check:"string_format",format:"starts_with",...$(t),prefix:e})}function op(e,t){return new Ed({check:"string_format",format:"ends_with",...$(t),suffix:e})}function st(e){return new Pd({check:"overwrite",tx:e})}function sp(e){return st(t=>t.normalize(e))}function cp(){return st(e=>e.trim())}function lp(){return st(e=>e.toLowerCase())}function dp(){return st(e=>e.toUpperCase())}function gp(){return st(e=>Tl(e))}function pp(e,t,a){return new e({type:"array",element:t,...$(a)})}function hp(e,t,a){return new e({type:"custom",check:"custom",fn:t,...$(a)})}function up(e){const t=mp(a=>(a.addIssue=n=>{if(typeof n=="string")a.issues.push(mt(n,a.value,t._zod.def));else{const r=n;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=a.value),r.inst??(r.inst=t),r.continue??(r.continue=!t._zod.def.abort),a.issues.push(mt(r))}},e(a.value,a)));return t}function mp(e,t){const a=new ue({check:"custom",...$(t)});return a._zod.check=e,a}function fp(e){const t=new ue({check:"describe"});return t._zod.onattach=[a=>{const n=$e.get(a)??{};$e.add(a,{...n,description:e})}],t._zod.check=()=>{},t}function bp(e){const t=new ue({check:"meta"});return t._zod.onattach=[a=>{const n=$e.get(a)??{};$e.add(a,{...n,...e})}],t._zod.check=()=>{},t}function pr(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??$e,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,cycles:e?.cycles??"ref",reused:e?.reused??"inline",external:e?.external??void 0}}function ce(e,t,a={path:[],schemaPath:[]}){var n;const r=e._zod.def,i=t.seen.get(e);if(i)return i.count++,a.schemaPath.includes(e)&&(i.cycle=a.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:a.path};t.seen.set(e,o);const s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{const l={...a,schemaPath:[...a.schemaPath,e],path:a.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,l);else{const d=o.schema,p=t.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(e,t,d,l)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),ce(g,t,l),t.seen.get(g).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),t.io==="input"&&me(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function hr(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=new Map;for(const o of e.seen.entries()){const s=e.metadataRegistry.get(o[0])?.id;if(s){const c=n.get(s);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${s}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(s,o[0])}}const r=o=>{const s=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const g=e.external.registry.get(o[0])?.id,d=e.external.uri??(h=>h);if(g)return{ref:d(g)};const p=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=p,{defId:p,ref:`${d("__shared")}#/${s}/${p}`}}if(o[1]===a)return{ref:"#"};const c=`#/${s}/`,l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:c+l}},i=o=>{if(o[1].schema.$ref)return;const s=o[1],{ref:c,defId:l}=r(o);s.def={...s.schema},l&&(s.defId=l);const g=s.schema;for(const d in g)delete g[d];g.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const s=o[1];if(s.cycle)throw new Error(`Cycle detected: #/${s.cycle?.join("/")}/<root>
175
175
 
176
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function ur(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const p=e.seen.get(g),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,l),o._zod.parent===g)for(const m in c)m==="$ref"||m==="allOf"||m in l||delete c[m];if(h.$ref&&p.def)for(const m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}const d=o._zod.parent;if(d&&d!==g){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(const h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ot(t,"input",e.processors),output:Ot(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function me(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return me(n.element,a);if(n.type==="set")return me(n.valueType,a);if(n.type==="lazy")return me(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return me(n.innerType,a);if(n.type==="intersection")return me(n.left,a)||me(n.right,a);if(n.type==="record"||n.type==="map")return me(n.keyType,a)||me(n.valueType,a);if(n.type==="pipe")return me(n.in,a)||me(n.out,a);if(n.type==="object"){for(const r in n.shape)if(me(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(me(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(me(r,a))return!0;return!!(n.rest&&me(n.rest,a))}return!1}var vp=(e,t={})=>a=>{const n=pr({...a,processors:t});return ce(e,n),hr(n,e),ur(n,e)},Ot=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=pr({...r??{},target:i,io:t,processors:a});return ce(e,o),hr(o,e),ur(o,e)},yp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_p=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=yp[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},xp=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},wp=(e,t,a,n)=>{a.type="boolean"},kp=(e,t,a,n)=>{a.not={}},Cp=(e,t,a,n)=>{},Sp=(e,t,a,n)=>{const r=e._zod.def,i=kn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Ep=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Pp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ap=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=ce(i.element,t,{...n,path:[...n.path,"items"]})},Tp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=ce(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ce(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Lp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ce(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Ip=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ce(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},Np=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=ce(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=ce(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=ce(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},zp=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Mp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Bp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Rp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Dp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},Op=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;ce(i,t,n);const o=t.seen.get(e);o.ref=i},$p=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},mr=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Fp=k("ZodISODateTime",(e,t)=>{Hd.init(e,t),re.init(e,t)});function Hp(e){return Vg(Fp,e)}var Up=k("ZodISODate",(e,t)=>{Ud.init(e,t),re.init(e,t)});function jp(e){return Gg(Up,e)}var Zp=k("ZodISOTime",(e,t)=>{jd.init(e,t),re.init(e,t)});function qp(e){return Wg(Zp,e)}var Vp=k("ZodISODuration",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Gp(e){return Kg(Vp,e)}var fr=(e,t)=>{Tn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Ul(e,a)},flatten:{value:a=>Hl(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ca,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ca,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ru=k("ZodError",fr),Se=k("ZodError",fr,{Parent:Error}),Wp=Lt(Se),Kp=It(Se),Yp=Nt(Se),Jp=zt(Se),Xp=Ln(Se),Qp=In(Se),eh=Nn(Se),th=zn(Se),ah=Mn(Se),nh=Bn(Se),rh=Rn(Se),ih=Dn(Se),oe=k("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ot(e,"input"),output:Ot(e,"output")}}),e.toJSONSchema=vp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ze(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>qe(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Wp(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>Yp(e,a,n),e.parseAsync=async(a,n)=>Kp(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Jp(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Xp(e,a,n),e.decode=(a,n)=>Qp(e,a,n),e.encodeAsync=async(a,n)=>eh(e,a,n),e.decodeAsync=async(a,n)=>th(e,a,n),e.safeEncode=(a,n)=>ah(e,a,n),e.safeDecode=(a,n)=>nh(e,a,n),e.safeEncodeAsync=async(a,n)=>rh(e,a,n),e.safeDecodeAsync=async(a,n)=>ih(e,a,n),e.refine=(a,n)=>e.check(Jh(a,n)),e.superRefine=a=>e.check(Xh(a)),e.overwrite=a=>e.check(st(a)),e.optional=()=>wr(e),e.exactOptional=()=>Oh(e),e.nullable=()=>kr(e),e.nullish=()=>wr(kr(e)),e.nonoptional=a=>Zh(e,a),e.array=()=>W(e),e.or=a=>ct([e,a]),e.and=a=>zh(e,a),e.transform=a=>Sr(e,Rh(a)),e.default=a=>Hh(e,a),e.prefault=a=>jh(e,a),e.catch=a=>Vh(e,a),e.pipe=a=>Sr(e,a),e.readonly=()=>Kh(e),e.describe=a=>{const n=e.clone();return $e.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return $e.get(e);const n=e.clone();return $e.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),br=k("_ZodString",(e,t)=>{ha.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_p(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(tp(...n)),e.includes=(...n)=>e.check(rp(...n)),e.startsWith=(...n)=>e.check(ip(...n)),e.endsWith=(...n)=>e.check(op(...n)),e.min=(...n)=>e.check(Dt(...n)),e.max=(...n)=>e.check(dr(...n)),e.length=(...n)=>e.check(gr(...n)),e.nonempty=(...n)=>e.check(Dt(1,...n)),e.lowercase=n=>e.check(ap(n)),e.uppercase=n=>e.check(np(n)),e.trim=()=>e.check(cp()),e.normalize=(...n)=>e.check(sp(...n)),e.toLowerCase=()=>e.check(lp()),e.toUpperCase=()=>e.check(dp()),e.slugify=()=>e.check(gp())}),oh=k("ZodString",(e,t)=>{ha.init(e,t),br.init(e,t),e.email=a=>e.check(Sg(sh,a)),e.url=a=>e.check(Lg(ch,a)),e.jwt=a=>e.check(qg(kh,a)),e.emoji=a=>e.check(Ig(lh,a)),e.guid=a=>e.check(or(vr,a)),e.uuid=a=>e.check(Eg($t,a)),e.uuidv4=a=>e.check(Pg($t,a)),e.uuidv6=a=>e.check(Ag($t,a)),e.uuidv7=a=>e.check(Tg($t,a)),e.nanoid=a=>e.check(Ng(dh,a)),e.guid=a=>e.check(or(vr,a)),e.cuid=a=>e.check(zg(gh,a)),e.cuid2=a=>e.check(Mg(ph,a)),e.ulid=a=>e.check(Bg(hh,a)),e.base64=a=>e.check(Ug(_h,a)),e.base64url=a=>e.check(jg(xh,a)),e.xid=a=>e.check(Rg(uh,a)),e.ksuid=a=>e.check(Dg(mh,a)),e.ipv4=a=>e.check(Og(fh,a)),e.ipv6=a=>e.check($g(bh,a)),e.cidrv4=a=>e.check(Fg(vh,a)),e.cidrv6=a=>e.check(Hg(yh,a)),e.e164=a=>e.check(Zg(wh,a)),e.datetime=a=>e.check(Hp(a)),e.date=a=>e.check(jp(a)),e.time=a=>e.check(qp(a)),e.duration=a=>e.check(Gp(a))});function x(e){return Cg(oh,e)}var re=k("ZodStringFormat",(e,t)=>{ne.init(e,t),br.init(e,t)}),sh=k("ZodEmail",(e,t)=>{Nd.init(e,t),re.init(e,t)}),vr=k("ZodGUID",(e,t)=>{Ld.init(e,t),re.init(e,t)}),$t=k("ZodUUID",(e,t)=>{Id.init(e,t),re.init(e,t)}),ch=k("ZodURL",(e,t)=>{zd.init(e,t),re.init(e,t)}),lh=k("ZodEmoji",(e,t)=>{Md.init(e,t),re.init(e,t)}),dh=k("ZodNanoID",(e,t)=>{Bd.init(e,t),re.init(e,t)}),gh=k("ZodCUID",(e,t)=>{Rd.init(e,t),re.init(e,t)}),ph=k("ZodCUID2",(e,t)=>{Dd.init(e,t),re.init(e,t)}),hh=k("ZodULID",(e,t)=>{Od.init(e,t),re.init(e,t)}),uh=k("ZodXID",(e,t)=>{$d.init(e,t),re.init(e,t)}),mh=k("ZodKSUID",(e,t)=>{Fd.init(e,t),re.init(e,t)}),fh=k("ZodIPv4",(e,t)=>{qd.init(e,t),re.init(e,t)}),bh=k("ZodIPv6",(e,t)=>{Vd.init(e,t),re.init(e,t)}),vh=k("ZodCIDRv4",(e,t)=>{Gd.init(e,t),re.init(e,t)}),yh=k("ZodCIDRv6",(e,t)=>{Wd.init(e,t),re.init(e,t)}),_h=k("ZodBase64",(e,t)=>{Kd.init(e,t),re.init(e,t)}),xh=k("ZodBase64URL",(e,t)=>{Jd.init(e,t),re.init(e,t)}),wh=k("ZodE164",(e,t)=>{Xd.init(e,t),re.init(e,t)}),kh=k("ZodJWT",(e,t)=>{eg.init(e,t),re.init(e,t)}),yr=k("ZodNumber",(e,t)=>{Gn.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xp(e,n,r,i),e.gt=(n,r)=>e.check(cr(n,r)),e.gte=(n,r)=>e.check(fa(n,r)),e.min=(n,r)=>e.check(fa(n,r)),e.lt=(n,r)=>e.check(sr(n,r)),e.lte=(n,r)=>e.check(ma(n,r)),e.max=(n,r)=>e.check(ma(n,r)),e.int=n=>e.check(_r(n)),e.safe=n=>e.check(_r(n)),e.positive=n=>e.check(cr(0,n)),e.nonnegative=n=>e.check(fa(0,n)),e.negative=n=>e.check(sr(0,n)),e.nonpositive=n=>e.check(ma(0,n)),e.multipleOf=(n,r)=>e.check(lr(n,r)),e.step=(n,r)=>e.check(lr(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Ie(e){return Yg(yr,e)}var Ch=k("ZodNumberFormat",(e,t)=>{tg.init(e,t),yr.init(e,t)});function _r(e){return Jg(Ch,e)}var Sh=k("ZodBoolean",(e,t)=>{ag.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wp(e,a,n,r)});function Ke(e){return Xg(Sh,e)}var Eh=k("ZodUnknown",(e,t)=>{ng.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Cp(e,a,n,r)});function ye(){return Qg(Eh)}var Ph=k("ZodNever",(e,t)=>{rg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kp(e,a,n,r)});function Ah(e){return ep(Ph,e)}var Th=k("ZodArray",(e,t)=>{ig.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ap(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Dt(a,n)),e.nonempty=a=>e.check(Dt(1,a)),e.max=(a,n)=>e.check(dr(a,n)),e.length=(a,n)=>e.check(gr(a,n)),e.unwrap=()=>e.element});function W(e,t){return pp(Th,e,t)}var Lh=k("ZodObject",(e,t)=>{sg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Tp(e,a,n,r),Q(e,"shape",()=>t.shape),e.keyof=()=>ft(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ye()}),e.loose=()=>e.clone({...e._zod.def,catchall:ye()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ah()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Rl(e,a),e.safeExtend=a=>Dl(e,a),e.merge=a=>Ol(e,a),e.pick=a=>Ml(e,a),e.omit=a=>Bl(e,a),e.partial=(...a)=>$l(xr,e,a[0]),e.required=(...a)=>Fl(Cr,e,a[0])});function H(e,t){return new Lh({type:"object",shape:e??{},...$(t)})}var Ih=k("ZodUnion",(e,t)=>{cg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Lp(e,a,n,r),e.options=t.options});function ct(e,t){return new Ih({type:"union",options:e,...$(t)})}var Nh=k("ZodIntersection",(e,t)=>{lg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ip(e,a,n,r)});function zh(e,t){return new Nh({type:"intersection",left:e,right:t})}var Mh=k("ZodRecord",(e,t)=>{dg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Np(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ye(e,t,a){return new Mh({type:"record",keyType:e,valueType:t,...$(a)})}var ba=k("ZodEnum",(e,t)=>{gg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sp(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ba({...t,checks:[],...$(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new ba({...t,checks:[],...$(r),entries:i})}});function ft(e,t){return new ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...$(t)})}var Bh=k("ZodTransform",(e,t)=>{pg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Pp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(mt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(mt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Rh(e){return new Bh({type:"transform",transform:e})}var xr=k("ZodOptional",(e,t)=>{er.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function wr(e){return new xr({type:"optional",innerType:e})}var Dh=k("ZodExactOptional",(e,t)=>{hg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Oh(e){return new Dh({type:"optional",innerType:e})}var $h=k("ZodNullable",(e,t)=>{ug.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>zp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function kr(e){return new $h({type:"nullable",innerType:e})}var Fh=k("ZodDefault",(e,t)=>{mg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Bp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hh(e,t){return new Fh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Uh=k("ZodPrefault",(e,t)=>{fg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Rp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function jh(e,t){return new Uh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Cr=k("ZodNonOptional",(e,t)=>{bg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Mp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Zh(e,t){return new Cr({type:"nonoptional",innerType:e,...$(t)})}var qh=k("ZodCatch",(e,t)=>{vg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Dp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vh(e,t){return new qh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Gh=k("ZodPipe",(e,t)=>{yg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Op(e,a,n,r),e.in=t.in,e.out=t.out});function Sr(e,t){return new Gh({type:"pipe",in:e,out:t})}var Wh=k("ZodReadonly",(e,t)=>{_g.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Kh(e){return new Wh({type:"readonly",innerType:e})}var Yh=k("ZodCustom",(e,t)=>{xg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ep(e,a,n,r)});function Jh(e,t={}){return hp(Yh,e,t)}function Xh(e){return up(e)}var Du=fp,Ou=bp,Qh=H({role:ft(["user","assistant"]),content:x(),timestamp:Ie().optional()}),eu=H({sku:x(),name:x(),imageUrl:x().url().optional(),price:x().optional(),originalPrice:x().optional(),url:x().url(),ctaLabel:x().optional()}),tu=H({buttons:W(H({label:x(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),au=H({}),nu=H({label:x().optional()}),Er=H({sku:x(),name:x(),price:x(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional()}),ru=H({recommended:Er,products:W(Er),attributes:W(H({label:x(),values:W(x())})),highlights:W(x()),specialCases:W(x()).optional(),recommendedText:x().optional(),winnerHits:Ye(x(),H({positive:W(x()).optional(),negative:W(x()).optional()})).optional(),productActions:Ye(x(),H({title:x(),type:x(),payload:ye().optional()})).optional()}),iu=H({label:x(),sentiment:ft(["positive","negative","neutral"]).optional()}),ou=H({product:Ye(x(),ye()),role:x().optional(),reason:x().optional(),labels:W(iu).optional(),expertQualityScore:Ie().optional(),reviewHighlight:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()}).optional()}),su=H({suggestions:W(ou)}),cu=H({title:x().optional(),text:x().optional(),reviewCount:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}),lu=H({entries:W(H({name:x(),image:x().optional(),description:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),du=H({entries:W(H({shortName:x(),detailedMessage:x().optional(),whyDifferent:x().optional(),image:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),Pr=H({title:x(),type:x(),payload:ye().optional()}),bt=H({name:x().optional(),value:x().optional(),option_value:x().optional(),attribute_value:x().optional(),type:x().optional(),attribute:x().optional(),option_name:x().optional(),attribute_name:x().optional(),variant_name:x().optional(),sku:x().optional(),price:ct([Ie(),x()]).optional(),price_discounted:ct([Ie(),x()]).optional(),image:x().optional(),imageUrl:x().optional(),image_url:x().optional(),color:x().optional(),colour:x().optional(),color_hex:x().optional(),hex:x().optional(),swatch:x().optional(),swatchColor:x().optional(),in_stock:Ke().optional(),inStock:Ke().optional()}),gu=H({product:H({sku:x().optional(),name:x().optional(),images:W(x()).optional(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional(),price:x().optional(),originalPrice:x().optional(),discountReason:x().optional(),discount_reason:x().optional(),campaignReason:x().optional(),campaign_reason:x().optional(),originalPriceStyle:ft(["strikethrough","inline"]).optional(),price_original_style:ft(["strikethrough","inline"]).optional(),price_discount_rate:Ie().optional(),price_async:Ke().optional(),inStock:Ke().optional(),promotions:W(x()).optional(),variants:W(bt).optional(),variantOptions:W(bt).optional(),variant_options:W(bt).optional(),productVariants:W(bt).optional(),product_variants:W(bt).optional(),url:x().optional(),cartCode:x().optional(),description:x().optional(),description_html:x().optional(),descriptionHtml:x().optional(),facet_hits:Ye(x(),ye()).optional(),facetHits:Ye(x(),ye()).optional(),features:W(H({name:x().optional(),key:x().optional(),label:x().optional(),value:ct([x(),Ie(),Ke()]).optional()})).optional(),specifications:ct([Ye(x(),x()),W(H({key:x(),value:x()}))]).optional()}).optional(),action:Pr.optional()}),pu=H({endOfList:Ke().optional()}),hu=H({review_class:x().optional(),review_text:x().optional(),review_rating:ct([x(),Ie()]).optional(),review_tag:x().optional()}),uu=H({reviews:W(hu).optional()}),mu=H({productName:x().optional(),pros:W(x()).optional(),cons:W(x()).optional()}),fu=H({groups:W(H({groupName:x(),products:W(Ye(x(),ye())).optional()})).optional(),filterTags:W(H({title:x(),action:Pr.optional()})).optional()}),bu=H({summary:x().optional(),products_discussed:W(x()).optional(),user_sentiment:x().optional()}),vu=H({summary:x(),clues:W(x()),strengths:W(x()).optional(),focus_points:W(x()).optional(),celeb_style:x().optional(),celeb_style_reason:x().optional(),details:W(x()).optional(),next_question:x().optional(),style_images:W(x()).optional()}),yu=H({processing:Ke().optional(),title:x().optional(),description:x().optional(),upload_label:x().optional(),skip_label:x().optional()}),_u={components:{MessageBubble:{schema:Qh,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:eu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:tu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:au,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:nu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ru,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:cu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:lu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:du,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:gu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:pu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:uu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:mu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:fu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:vu,description:"Structured photo analysis card with strengths, focus points, celeb vibe, details, and follow-up question."},BeautyPhotoStep:{schema:yu,description:"Transient selfie upload prompt for beauty consulting init flow."}}};function Ar(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function va(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Tr=class lt extends ui{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=Gt,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new bn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new ns}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const u=Qc(t.pillLauncher);t.launcherImageUrl=u.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>u.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=gl,this._shadow.appendChild(a);const n=this.root,r=(u,f)=>{f&&Ar(f)&&n.style.setProperty(u,f)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[u,f]of Object.entries(t.theme))u.startsWith("--")&&typeof f=="string"&&r(u,f);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const u=document.createElement("div");u.className="gengage-chat-backdrop",u.setAttribute("aria-hidden","true"),u.setAttribute("role","button"),u.setAttribute("tabindex","-1"),u.setAttribute("aria-label",this._i18n.closeAriaLabel),u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),this.close()}),this._backdropEl=u,i.prepend(u)}if(o==="floating"){const u={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?u.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(u.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(u.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(u.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(u.tooltip=t.launcherTooltip),this._launcher=ds(u),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new Xo(s,{i18n:this._i18n,onSend:(u,f)=>this._sendMessage(u,f),onClose:()=>this.close(),onAttachment:u=>this._handleAttachment(u),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:u=>this._handleRollback(u),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(wl(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:u=>{u==="close"?this.close():(this._openState=u,this._applyOpenStateClasses())},onThumbnailClick:u=>this._rollbackToThread(u),onLinkClick:u=>{this._saveSessionAndOpenURL(u)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:u=>{this._presentation.pinnedToBottom=u},onUserInteractingChange:u=>{this._presentation.userInteracting=u},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Kc({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Yc({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:u=>this._rollbackToThread(u)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),d=sessionStorage.getItem("gengage_restore_sku"),p=!!(g&&d);p&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new Gc;await u.open(),this._session=new fn(u),await this._restoreFromIndexedDB(p)}catch{this._session=new fn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const h=()=>this._syncViewportState();if(window.addEventListener("resize",h,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",h)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const f=this._drawer?.getElement();if(!f)return;const y=window.innerHeight-(window.visualViewport?.height??window.innerHeight);f.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,y)}px`)};window.visualViewport.addEventListener("resize",u),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",u))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const m={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(m.allowedOrigins=t.allowedOrigins),this._bridge=new fi(m),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const u of this._pendingActions)this._sendAction(u.action,u.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),we("gengage:chat:ready",{}),hl("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),we("gengage:chat:open",{state:this._openState}),ul("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),we("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),Da(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${CSS.escape(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=Xc(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=va(n)?n:va(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),va(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Ar(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ea(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!0})}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=Ci(t);if(!a.ok){we("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(oa(this.config.accountId),this._drawer?.hideKvkkBanner()),Sl(),this._messages.some(r=>r.role==="user")||El(),Me("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Uc(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const v=this._currentThreadId,b=this._messages.filter(_=>_.threadId!==void 0&&_.threadId>v);this._messages=this._messages.filter(_=>!_.threadId||_.threadId<=v);for(const _ of b)this._shadow?.querySelector(`[data-message-id="${CSS.escape(_.id)}"]`)?.remove(),this._panel.snapshots.delete(_.id),this._panel.snapshotTypes.delete(_.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(_=>{_ instanceof HTMLElement&&_.dataset.threadId&&_.dataset.threadId>v&&_.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ea();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const v=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,b=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(b!==void 0&&b.role==="user"&&b.content===v)){const _=this._createMessage("user",v);_.threadId=n,a?.attachment!==void 0&&(_.attachment=a.attachment),this._drawer?.addMessage(_),this._messages.push(_)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const v=this._i18n.productNotFoundMessage,b=this._createMessage("assistant",v);b.threadId=n,b.status="done",this._messages.push(b),this._ensureAssistantMessageRendered(b),this._drawer?.updateBotMessage(b.id,v),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",b),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const v=this._buildRenderContext(),b=this._renderPanelFromSource(o,v);this._drawer.setPanelContent(b),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const p={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(p.attachment=a.attachment);const h=this._getVisibleMessages().filter(v=>v!==d&&(v.content||v.role==="assistant")).slice(-50).map(v=>({role:v.role==="user"?"user":"model",content:v.content??""})),m={outputLanguage:dl(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:yn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(m.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(m.viewId=this.config.session.viewId);const u=ko(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),f={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:u.type,locale:this.config.locale??"tr",meta:m,context:{...this._lastBackendContext??{},messages:h,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(f.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(f.view_id=this.config.session.viewId),u.payload!==void 0&&(f.payload=u.payload),this.config.pageContext?.sku!==void 0&&(f.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(f.page_type=this.config.pageContext.pageType);const y=crypto.randomUUID(),M=Date.now();let C=0,P=!1,w=!1,N=!1,R=!1,L=!1;const Z=rs();let te=null;const X=()=>{if(this._drawer){if(this._isMobileViewport||!N){this._drawer.setPanelAiZoneState("hidden");return}R||(L?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(zr(this.analyticsContext(),{endpoint:"process_action",request_id:y,widget:"chat"}));let I=null;if(I=Eo(f,{onTextChunk:(v,b,_)=>{if(!r&&n!==this._activeRequestThreadId||(g+=v,this._drawer?.removeTypingIndicator(),_?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,..._.skuToProductItem}),_?.conversationMode&&(this._conversationMode=_.conversationMode),_?.renderHint&&(d.renderHint=_.renderHint),this.track(Mr(this.analyticsContext(),{request_id:y,chunk_index:C++,widget:"chat"})),!this._drawer))return;let S=g;const T=_?.kvkk===!0||ia(S);if(b&&T){const D=this.config.accountId;if(!yn(D)){const A=cl(S);A?this._drawer?.showKvkkBanner(A,()=>{this._drawer?.hideKvkkBanner(),oa(D)}):oa(D)}S=sl(S)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=Ae(S):(d.content=S,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),b)if(d.content=S,d.status="done",xn(),os(d))this._drawer?.updateBotMessage(d.id,S,"photo_analysis",d.photoAnalysis);else{const D=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(D){this._activeTypewriter?.cancel();const A=_?.productMentions;this._activeTypewriter=Bc({container:D,html:Ae(S),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,A&&A.length>0&&D&&Rc({container:D,mentions:A,onProductClick:U=>{this._sendAction({title:A.find(F=>F.sku===U)?.short_name??U,type:"launchSingleProduct",payload:{sku:U}})}})}})}}},onUISpec:(v,b,_,S)=>{if(!r&&n!==this._activeRequestThreadId||b!=="chat")return;S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const T=v.elements[v.root],z=T?.type??"unknown";if(is(z,T?.props??{},Z,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:L},d))return;const D=z==="ProductGrid"&&T?.props?.similarsAppend===!0,A=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||D);A&&!S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const U=z==="ProductDetailsPanel"&&_!=="panel"?"panel":_;this.track(Br(this.analyticsContext(),{request_id:y,chunk_index:C,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const j=T?.props?.products;_l(Array.isArray(j)?j.length:0)}if(z==="ProductGrid"){const j=T?.children?.length??0;kl(void 0,j)}const K=U==="panel"&&this._panel?this._panel.toPanelSpec(v):v;if(U==="panel"&&this._panel&&!A){const j=!w;w=!0;const B=Jc({componentType:z,similarsAppend:T?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:j});F.panelProductListHeading=void 0,z==="ProductGrid"&&(B==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:K})),B==="appendSimilars"?this._appendSimilarsToPanel(K,F):B==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(K,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(K,F)),this._currentPanelSource={kind:"spec",spec:K},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const J=this._panel.currentType??z,O=T?.props?.panelTitle;if(this._panel.updateTopBar(J,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(N=!this._isMobileViewport,te){const se=this._buildRenderContext();se.isStreaming=!0;const Ft=this._renderUISpec(te,se);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Ft}),te=null}}else B!=="appendSimilars"&&B!=="append"&&(N=!1,te=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&U==="panel"&&(!d.silent||i)){const j=T?.props?.product;if(j){const B={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:j}}}},J=this._shadow?.querySelector(".gengage-chat-messages");if(J){const O=this._renderUISpec(B,F);d.threadId&&(O.dataset.threadId=d.threadId);const se=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);se&&se.parentNode===J?se.after(O):J.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),w=!0}}}const ee=z==="AITopPicks"||z==="AIGroupingCards";let ae=!1,de=!1;if(A&&D&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),ee&&!this._isMobileViewport&&!d.silent)if(N){const j=this._renderUISpec(v,F);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:j}),ae=!0,te=null}else te=v,de=!0;const q=i&&z==="GroundingReviewCard";if((!d.silent||q)&&(U!=="panel"||z==="ProductCard"||A&&z==="ProductGrid"&&(!D||this._isMobileViewport))&&z!=="ActionButtons"&&!ae&&!(de&&ee)){const j=this._shadow?.querySelector(".gengage-chat-messages");if(j){const B=this._renderUISpec(v,F);d.threadId&&(B.dataset.threadId=d.threadId),j.appendChild(B),B.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),A&&z==="ProductGrid"&&(w=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const j=T?.children??[],B=z==="ProductGrid"?j.map(J=>v.elements[J]?.props?.product).filter(Boolean):[T?.props?.product].filter(Boolean);for(const J of B){const O=J.sku,se=J.imageUrl;O&&se&&this._thumbnailEntries.push({sku:O,imageUrl:se,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const j=(z==="ProductGrid"?(T?.children??[]).map(B=>v.elements[B]?.props?.product).filter(Boolean):[T?.props?.product??T?.props].filter(Boolean)).map(B=>B.imageUrl).filter(B=>typeof B=="string").slice(0,5);j.length>0&&this._bridge?.send("previewImages",{images:j})}const _e=T?.children?.length??0;if(z==="ProductGrid"&&U==="panel"&&!A&&_e>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!jc(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(B=>B.remove()),this._choicePrompterEl=Hc({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const j=this._shadow?.querySelector(".gengage-chat-panel-float");if(j){if(j.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const B=this._choicePrompterEl,J=()=>{window.visualViewport.height/window.innerHeight<.75&&(B.remove(),this._choicePrompterEl===B&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",J))};window.visualViewport.addEventListener("resize",J)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const j=T?.props?.buttons;if(j&&j.length>0){const B=[],J=[];for(const O of j)if($c(O)){const se={label:O.label,action:O.action};O.icon&&(se.icon=O.icon),B.push(se)}else J.push(O);B.length>0&&this._drawer?.setInputAreaChips(B.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),J.length>0&&this._drawer?.setPills(J.map(O=>{const se={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(se.icon=O.icon),O.image&&(se.image=O.image),O.description&&(se.description=O.description),se}))}}X(),d.uiSpec=v},onAction:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="action"){const b={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(b.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(b.allowScriptCall=this.config.actionHandling.allowScriptCall),_i(v,{openChat:()=>this.open(),navigate:_=>{fe(_.url)&&(this._bridge?.send("navigate",_),_.newTab?window.open(_.url,"_blank","noopener,noreferrer"):window.location.href=_.url)},saveSession:_=>this.saveSession(_.sessionId,_.sku),addToCart:_=>{we("gengage:similar:add-to-cart",_)},scriptCall:_=>{we("gengage:chat:script-call",_),this.config.onScriptCall?.(_)}},b)}},onMetadata:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="metadata"&&v.meta){if(v.meta.panel!==void 0||v.meta.messages!==void 0||v.meta.message_id!==void 0){this._lastBackendContext=v.meta;const _=Yt(v.meta.panel);_&&(this._modeController.updateFromContext(_),this._applyUiHints())}if(v.meta.panelLoading){const _=typeof v.meta.panelPendingType=="string"?v.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(_==="productDetails"||_==="productDetailsSimilars")||(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(_),_&&this._panel?.updateTopBarForLoading(_))}if(v.meta.voice){const _=new CustomEvent("gengage:chat:voice",{detail:{payload:v.meta.voice},bubbles:!1,cancelable:!0}),S=window.dispatchEvent(_);if(Pl(),S){const T=v.meta.voice;T.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=ps(T.audio_base64,T.content_type??"audio/ogg"))}}if((v.meta.redirectTarget||v.meta.redirect)&&(we("gengage:chat:redirect",{target:v.meta.redirectTarget??null,payload:v.meta.redirect??null}),Me("redirect","redirect dispatched",{target:v.meta.redirectTarget??null}),this._handleRedirectMetadata(v.meta.redirect)),v.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),v.meta.loading){const _=Array.isArray(v.meta.thinkingMessages)?v.meta.thinkingMessages.filter(T=>typeof T=="string"):[],S=typeof v.meta.loadingText=="string"?v.meta.loadingText:void 0;if(_.length>0){const T=S&&this._modeController.shouldCondenseThinking()?[..._.slice(0,2),S]:_;this._drawer?.setThinkingSteps(T)}typeof S=="string"&&S.length>0&&(this._drawer?.addThinkingStep(S),this._bridge?.send("loadingMessage",{text:S}))}v.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",v.meta.visitorDataResponse),v.meta.formType&&this._bridge?.send("glovOtokoc",{type:v.meta.formType,data:v.meta.formPayload}),v.meta.launcherContent&&this._bridge?.send("launcherContent",v.meta.launcherContent),we("gengage:chat:metadata",{payload:v.meta});const b=v.meta;typeof b.prompt_tokens=="number"&&typeof b.completion_tokens=="number"&&this.track(Or(this.analyticsContext(),{model:v.model??"unknown",prompt_tokens:b.prompt_tokens,completion_tokens:b.completion_tokens,total_tokens:b.total_tokens??b.prompt_tokens+b.completion_tokens}))}},onError:v=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;L=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,X(),te=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),cs(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const b=w;P&&!w&&l(),P=!1,w=!1;const _=d.silent||d.content!=null&&d.content.length>0||g.length>0||b,S=typeof navigator<"u"&&navigator.onLine===!1&&Sa(v),T=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const A=this._messages.indexOf(d);A>=0&&this._messages.splice(A,1)};let z=!1;const D=()=>{if(S)return;this.emit("error",v);const A=v.message;A===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=A);const U=v.message.trim(),F=U.length>0?U:this._i18n.errorMessage,K={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){T(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,K);return}if(rl(v,F)){T(),z=!0,this._drawer?.showErrorWithRecovery(F,K);return}d.content=F,d.status="done";const ee=Ae(F.replace(/\r\n/g,`
176
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const s=o[1];if(t===o[0]){i(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){i(o);continue}}if(e.metadataRegistry.get(o[0])?.id){i(o);continue}if(s.cycle){i(o);continue}if(s.count>1&&e.reused==="ref"){i(o);continue}}}function ur(e,t){const a=e.seen.get(t);if(!a)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=o=>{const s=e.seen.get(o);if(s.ref===null)return;const c=s.def??s.schema,l={...c},g=s.ref;if(s.ref=null,g){n(g);const p=e.seen.get(g),h=p.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(c.allOf=c.allOf??[],c.allOf.push(h)):Object.assign(c,h),Object.assign(c,l),o._zod.parent===g)for(const m in c)m==="$ref"||m==="allOf"||m in l||delete c[m];if(h.$ref&&p.def)for(const m in c)m==="$ref"||m==="allOf"||m in p.def&&JSON.stringify(c[m])===JSON.stringify(p.def[m])&&delete c[m]}const d=o._zod.parent;if(d&&d!==g){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(c.$ref=p.schema.$ref,p.def))for(const h in c)h==="$ref"||h==="allOf"||h in p.def&&JSON.stringify(c[h])===JSON.stringify(p.def[h])&&delete c[h]}e.override({zodSchema:o,jsonSchema:c,path:s.path??[]})};for(const o of[...e.seen.entries()].reverse())n(o[0]);const r={};if(e.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const o=e.external.registry.get(t)?.id;if(!o)throw new Error("Schema is missing an `id` property");r.$id=e.external.uri(o)}Object.assign(r,a.def??a.schema);const i=e.external?.defs??{};for(const o of e.seen.entries()){const s=o[1];s.def&&s.defId&&(i[s.defId]=s.def)}e.external||Object.keys(i).length>0&&(e.target==="draft-2020-12"?r.$defs=i:r.definitions=i);try{const o=JSON.parse(JSON.stringify(r));return Object.defineProperty(o,"~standard",{value:{...t["~standard"],jsonSchema:{input:Ot(t,"input",e.processors),output:Ot(t,"output",e.processors)}},enumerable:!1,writable:!1}),o}catch{throw new Error("Error converting schema to JSON.")}}function me(e,t){const a=t??{seen:new Set};if(a.seen.has(e))return!1;a.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return me(n.element,a);if(n.type==="set")return me(n.valueType,a);if(n.type==="lazy")return me(n.getter(),a);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault")return me(n.innerType,a);if(n.type==="intersection")return me(n.left,a)||me(n.right,a);if(n.type==="record"||n.type==="map")return me(n.keyType,a)||me(n.valueType,a);if(n.type==="pipe")return me(n.in,a)||me(n.out,a);if(n.type==="object"){for(const r in n.shape)if(me(n.shape[r],a))return!0;return!1}if(n.type==="union"){for(const r of n.options)if(me(r,a))return!0;return!1}if(n.type==="tuple"){for(const r of n.items)if(me(r,a))return!0;return!!(n.rest&&me(n.rest,a))}return!1}var vp=(e,t={})=>a=>{const n=pr({...a,processors:t});return ce(e,n),hr(n,e),ur(n,e)},Ot=(e,t,a={})=>n=>{const{libraryOptions:r,target:i}=n??{},o=pr({...r??{},target:i,io:t,processors:a});return ce(e,o),hr(o,e),ur(o,e)},yp={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},_p=(e,t,a,n)=>{const r=a;r.type="string";const{minimum:i,maximum:o,format:s,patterns:c,contentEncoding:l}=e._zod.bag;if(typeof i=="number"&&(r.minLength=i),typeof o=="number"&&(r.maxLength=o),s&&(r.format=yp[s]??s,r.format===""&&delete r.format,s==="time"&&delete r.format),l&&(r.contentEncoding=l),c&&c.size>0){const g=[...c];g.length===1?r.pattern=g[0].source:g.length>1&&(r.allOf=[...g.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},xp=(e,t,a,n)=>{const r=a,{minimum:i,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:g}=e._zod.bag;typeof s=="string"&&s.includes("int")?r.type="integer":r.type="number",typeof g=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.minimum=g,r.exclusiveMinimum=!0):r.exclusiveMinimum=g),typeof i=="number"&&(r.minimum=i,typeof g=="number"&&t.target!=="draft-04"&&(g>=i?delete r.minimum:delete r.exclusiveMinimum)),typeof l=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(r.maximum=l,r.exclusiveMaximum=!0):r.exclusiveMaximum=l),typeof o=="number"&&(r.maximum=o,typeof l=="number"&&t.target!=="draft-04"&&(l<=o?delete r.maximum:delete r.exclusiveMaximum)),typeof c=="number"&&(r.multipleOf=c)},wp=(e,t,a,n)=>{a.type="boolean"},kp=(e,t,a,n)=>{a.not={}},Cp=(e,t,a,n)=>{},Sp=(e,t,a,n)=>{const r=e._zod.def,i=kn(r.entries);i.every(o=>typeof o=="number")&&(a.type="number"),i.every(o=>typeof o=="string")&&(a.type="string"),a.enum=i},Ep=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Pp=(e,t,a,n)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ap=(e,t,a,n)=>{const r=a,i=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o=="number"&&(r.minItems=o),typeof s=="number"&&(r.maxItems=s),r.type="array",r.items=ce(i.element,t,{...n,path:[...n.path,"items"]})},Tp=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object",r.properties={};const o=i.shape;for(const l in o)r.properties[l]=ce(o[l],t,{...n,path:[...n.path,"properties",l]});const s=new Set(Object.keys(o)),c=new Set([...s].filter(l=>{const g=i.shape[l]._zod;return t.io==="input"?g.optin===void 0:g.optout===void 0}));c.size>0&&(r.required=Array.from(c)),i.catchall?._zod.def.type==="never"?r.additionalProperties=!1:i.catchall?i.catchall&&(r.additionalProperties=ce(i.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(r.additionalProperties=!1)},Lp=(e,t,a,n)=>{const r=e._zod.def,i=r.inclusive===!1,o=r.options.map((s,c)=>ce(s,t,{...n,path:[...n.path,i?"oneOf":"anyOf",c]}));i?a.oneOf=o:a.anyOf=o},Ip=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.left,t,{...n,path:[...n.path,"allOf",0]}),o=ce(r.right,t,{...n,path:[...n.path,"allOf",1]}),s=c=>"allOf"in c&&Object.keys(c).length===1;a.allOf=[...s(i)?i.allOf:[i],...s(o)?o.allOf:[o]]},Np=(e,t,a,n)=>{const r=a,i=e._zod.def;r.type="object";const o=i.keyType,s=o._zod.bag?.patterns;if(i.mode==="loose"&&s&&s.size>0){const l=ce(i.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});r.patternProperties={};for(const g of s)r.patternProperties[g.source]=l}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(r.propertyNames=ce(i.keyType,t,{...n,path:[...n.path,"propertyNames"]})),r.additionalProperties=ce(i.valueType,t,{...n,path:[...n.path,"additionalProperties"]});const c=o._zod.values;if(c){const l=[...c].filter(g=>typeof g=="string"||typeof g=="number");l.length>0&&(r.required=l)}},zp=(e,t,a,n)=>{const r=e._zod.def,i=ce(r.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=r.innerType,a.nullable=!0):a.anyOf=[i,{type:"null"}]},Mp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Bp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.default=JSON.parse(JSON.stringify(r.defaultValue))},Rp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,t.io==="input"&&(a._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},Dp=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType;let o;try{o=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}a.default=o},Op=(e,t,a,n)=>{const r=e._zod.def,i=t.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;ce(i,t,n);const o=t.seen.get(e);o.ref=i},$p=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType,a.readOnly=!0},mr=(e,t,a,n)=>{const r=e._zod.def;ce(r.innerType,t,n);const i=t.seen.get(e);i.ref=r.innerType},Fp=k("ZodISODateTime",(e,t)=>{Hd.init(e,t),re.init(e,t)});function Hp(e){return Vg(Fp,e)}var Up=k("ZodISODate",(e,t)=>{Ud.init(e,t),re.init(e,t)});function jp(e){return Gg(Up,e)}var Zp=k("ZodISOTime",(e,t)=>{jd.init(e,t),re.init(e,t)});function qp(e){return Wg(Zp,e)}var Vp=k("ZodISODuration",(e,t)=>{Zd.init(e,t),re.init(e,t)});function Gp(e){return Kg(Vp,e)}var fr=(e,t)=>{Tn.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:a=>Ul(e,a)},flatten:{value:a=>Hl(e,a)},addIssue:{value:a=>{e.issues.push(a),e.message=JSON.stringify(e.issues,ca,2)}},addIssues:{value:a=>{e.issues.push(...a),e.message=JSON.stringify(e.issues,ca,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ru=k("ZodError",fr),Se=k("ZodError",fr,{Parent:Error}),Wp=Lt(Se),Kp=It(Se),Yp=Nt(Se),Jp=zt(Se),Xp=Ln(Se),Qp=In(Se),eh=Nn(Se),th=zn(Se),ah=Mn(Se),nh=Bn(Se),rh=Rn(Se),ih=Dn(Se),oe=k("ZodType",(e,t)=>(ie.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:Ot(e,"input"),output:Ot(e,"output")}}),e.toJSONSchema=vp(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...a)=>e.clone(Ze(t,{checks:[...t.checks??[],...a.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0}),e.with=e.check,e.clone=(a,n)=>qe(e,a,n),e.brand=()=>e,e.register=((a,n)=>(a.add(e,n),e)),e.parse=(a,n)=>Wp(e,a,n,{callee:e.parse}),e.safeParse=(a,n)=>Yp(e,a,n),e.parseAsync=async(a,n)=>Kp(e,a,n,{callee:e.parseAsync}),e.safeParseAsync=async(a,n)=>Jp(e,a,n),e.spa=e.safeParseAsync,e.encode=(a,n)=>Xp(e,a,n),e.decode=(a,n)=>Qp(e,a,n),e.encodeAsync=async(a,n)=>eh(e,a,n),e.decodeAsync=async(a,n)=>th(e,a,n),e.safeEncode=(a,n)=>ah(e,a,n),e.safeDecode=(a,n)=>nh(e,a,n),e.safeEncodeAsync=async(a,n)=>rh(e,a,n),e.safeDecodeAsync=async(a,n)=>ih(e,a,n),e.refine=(a,n)=>e.check(Jh(a,n)),e.superRefine=a=>e.check(Xh(a)),e.overwrite=a=>e.check(st(a)),e.optional=()=>wr(e),e.exactOptional=()=>Oh(e),e.nullable=()=>kr(e),e.nullish=()=>wr(kr(e)),e.nonoptional=a=>Zh(e,a),e.array=()=>W(e),e.or=a=>ct([e,a]),e.and=a=>zh(e,a),e.transform=a=>Sr(e,Rh(a)),e.default=a=>Hh(e,a),e.prefault=a=>jh(e,a),e.catch=a=>Vh(e,a),e.pipe=a=>Sr(e,a),e.readonly=()=>Kh(e),e.describe=a=>{const n=e.clone();return $e.add(n,{description:a}),n},Object.defineProperty(e,"description",{get(){return $e.get(e)?.description},configurable:!0}),e.meta=(...a)=>{if(a.length===0)return $e.get(e);const n=e.clone();return $e.add(n,a[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=a=>a(e),e)),br=k("_ZodString",(e,t)=>{ha.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_p(e,n,r,i);const a=e._zod.bag;e.format=a.format??null,e.minLength=a.minimum??null,e.maxLength=a.maximum??null,e.regex=(...n)=>e.check(tp(...n)),e.includes=(...n)=>e.check(rp(...n)),e.startsWith=(...n)=>e.check(ip(...n)),e.endsWith=(...n)=>e.check(op(...n)),e.min=(...n)=>e.check(Dt(...n)),e.max=(...n)=>e.check(dr(...n)),e.length=(...n)=>e.check(gr(...n)),e.nonempty=(...n)=>e.check(Dt(1,...n)),e.lowercase=n=>e.check(ap(n)),e.uppercase=n=>e.check(np(n)),e.trim=()=>e.check(cp()),e.normalize=(...n)=>e.check(sp(...n)),e.toLowerCase=()=>e.check(lp()),e.toUpperCase=()=>e.check(dp()),e.slugify=()=>e.check(gp())}),oh=k("ZodString",(e,t)=>{ha.init(e,t),br.init(e,t),e.email=a=>e.check(Sg(sh,a)),e.url=a=>e.check(Lg(ch,a)),e.jwt=a=>e.check(qg(kh,a)),e.emoji=a=>e.check(Ig(lh,a)),e.guid=a=>e.check(or(vr,a)),e.uuid=a=>e.check(Eg($t,a)),e.uuidv4=a=>e.check(Pg($t,a)),e.uuidv6=a=>e.check(Ag($t,a)),e.uuidv7=a=>e.check(Tg($t,a)),e.nanoid=a=>e.check(Ng(dh,a)),e.guid=a=>e.check(or(vr,a)),e.cuid=a=>e.check(zg(gh,a)),e.cuid2=a=>e.check(Mg(ph,a)),e.ulid=a=>e.check(Bg(hh,a)),e.base64=a=>e.check(Ug(_h,a)),e.base64url=a=>e.check(jg(xh,a)),e.xid=a=>e.check(Rg(uh,a)),e.ksuid=a=>e.check(Dg(mh,a)),e.ipv4=a=>e.check(Og(fh,a)),e.ipv6=a=>e.check($g(bh,a)),e.cidrv4=a=>e.check(Fg(vh,a)),e.cidrv6=a=>e.check(Hg(yh,a)),e.e164=a=>e.check(Zg(wh,a)),e.datetime=a=>e.check(Hp(a)),e.date=a=>e.check(jp(a)),e.time=a=>e.check(qp(a)),e.duration=a=>e.check(Gp(a))});function x(e){return Cg(oh,e)}var re=k("ZodStringFormat",(e,t)=>{ne.init(e,t),br.init(e,t)}),sh=k("ZodEmail",(e,t)=>{Nd.init(e,t),re.init(e,t)}),vr=k("ZodGUID",(e,t)=>{Ld.init(e,t),re.init(e,t)}),$t=k("ZodUUID",(e,t)=>{Id.init(e,t),re.init(e,t)}),ch=k("ZodURL",(e,t)=>{zd.init(e,t),re.init(e,t)}),lh=k("ZodEmoji",(e,t)=>{Md.init(e,t),re.init(e,t)}),dh=k("ZodNanoID",(e,t)=>{Bd.init(e,t),re.init(e,t)}),gh=k("ZodCUID",(e,t)=>{Rd.init(e,t),re.init(e,t)}),ph=k("ZodCUID2",(e,t)=>{Dd.init(e,t),re.init(e,t)}),hh=k("ZodULID",(e,t)=>{Od.init(e,t),re.init(e,t)}),uh=k("ZodXID",(e,t)=>{$d.init(e,t),re.init(e,t)}),mh=k("ZodKSUID",(e,t)=>{Fd.init(e,t),re.init(e,t)}),fh=k("ZodIPv4",(e,t)=>{qd.init(e,t),re.init(e,t)}),bh=k("ZodIPv6",(e,t)=>{Vd.init(e,t),re.init(e,t)}),vh=k("ZodCIDRv4",(e,t)=>{Gd.init(e,t),re.init(e,t)}),yh=k("ZodCIDRv6",(e,t)=>{Wd.init(e,t),re.init(e,t)}),_h=k("ZodBase64",(e,t)=>{Kd.init(e,t),re.init(e,t)}),xh=k("ZodBase64URL",(e,t)=>{Jd.init(e,t),re.init(e,t)}),wh=k("ZodE164",(e,t)=>{Xd.init(e,t),re.init(e,t)}),kh=k("ZodJWT",(e,t)=>{eg.init(e,t),re.init(e,t)}),yr=k("ZodNumber",(e,t)=>{Gn.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xp(e,n,r,i),e.gt=(n,r)=>e.check(cr(n,r)),e.gte=(n,r)=>e.check(fa(n,r)),e.min=(n,r)=>e.check(fa(n,r)),e.lt=(n,r)=>e.check(sr(n,r)),e.lte=(n,r)=>e.check(ma(n,r)),e.max=(n,r)=>e.check(ma(n,r)),e.int=n=>e.check(_r(n)),e.safe=n=>e.check(_r(n)),e.positive=n=>e.check(cr(0,n)),e.nonnegative=n=>e.check(fa(0,n)),e.negative=n=>e.check(sr(0,n)),e.nonpositive=n=>e.check(ma(0,n)),e.multipleOf=(n,r)=>e.check(lr(n,r)),e.step=(n,r)=>e.check(lr(n,r)),e.finite=()=>e;const a=e._zod.bag;e.minValue=Math.max(a.minimum??Number.NEGATIVE_INFINITY,a.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(a.maximum??Number.POSITIVE_INFINITY,a.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(a.format??"").includes("int")||Number.isSafeInteger(a.multipleOf??.5),e.isFinite=!0,e.format=a.format??null});function Ie(e){return Yg(yr,e)}var Ch=k("ZodNumberFormat",(e,t)=>{tg.init(e,t),yr.init(e,t)});function _r(e){return Jg(Ch,e)}var Sh=k("ZodBoolean",(e,t)=>{ag.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>wp(e,a,n,r)});function Ke(e){return Xg(Sh,e)}var Eh=k("ZodUnknown",(e,t)=>{ng.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Cp(e,a,n,r)});function ye(){return Qg(Eh)}var Ph=k("ZodNever",(e,t)=>{rg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>kp(e,a,n,r)});function Ah(e){return ep(Ph,e)}var Th=k("ZodArray",(e,t)=>{ig.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ap(e,a,n,r),e.element=t.element,e.min=(a,n)=>e.check(Dt(a,n)),e.nonempty=a=>e.check(Dt(1,a)),e.max=(a,n)=>e.check(dr(a,n)),e.length=(a,n)=>e.check(gr(a,n)),e.unwrap=()=>e.element});function W(e,t){return pp(Th,e,t)}var Lh=k("ZodObject",(e,t)=>{sg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Tp(e,a,n,r),Q(e,"shape",()=>t.shape),e.keyof=()=>ft(Object.keys(e._zod.def.shape)),e.catchall=a=>e.clone({...e._zod.def,catchall:a}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ye()}),e.loose=()=>e.clone({...e._zod.def,catchall:ye()}),e.strict=()=>e.clone({...e._zod.def,catchall:Ah()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=a=>Rl(e,a),e.safeExtend=a=>Dl(e,a),e.merge=a=>Ol(e,a),e.pick=a=>Ml(e,a),e.omit=a=>Bl(e,a),e.partial=(...a)=>$l(xr,e,a[0]),e.required=(...a)=>Fl(Cr,e,a[0])});function H(e,t){return new Lh({type:"object",shape:e??{},...$(t)})}var Ih=k("ZodUnion",(e,t)=>{cg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Lp(e,a,n,r),e.options=t.options});function ct(e,t){return new Ih({type:"union",options:e,...$(t)})}var Nh=k("ZodIntersection",(e,t)=>{lg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ip(e,a,n,r)});function zh(e,t){return new Nh({type:"intersection",left:e,right:t})}var Mh=k("ZodRecord",(e,t)=>{dg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Np(e,a,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ye(e,t,a){return new Mh({type:"record",keyType:e,valueType:t,...$(a)})}var ba=k("ZodEnum",(e,t)=>{gg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,r,i)=>Sp(e,n,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const a=new Set(Object.keys(t.entries));e.extract=(n,r)=>{const i={};for(const o of n)if(a.has(o))i[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new ba({...t,checks:[],...$(r),entries:i})},e.exclude=(n,r)=>{const i={...t.entries};for(const o of n)if(a.has(o))delete i[o];else throw new Error(`Key ${o} not found in enum`);return new ba({...t,checks:[],...$(r),entries:i})}});function ft(e,t){return new ba({type:"enum",entries:Array.isArray(e)?Object.fromEntries(e.map(a=>[a,a])):e,...$(t)})}var Bh=k("ZodTransform",(e,t)=>{pg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Pp(e,a,n,r),e._zod.parse=(a,n)=>{if(n.direction==="backward")throw new wn(e.constructor.name);a.addIssue=i=>{if(typeof i=="string")a.issues.push(mt(i,a.value,t));else{const o=i;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=a.value),o.inst??(o.inst=e),a.issues.push(mt(o))}};const r=t.transform(a.value,a);return r instanceof Promise?r.then(i=>(a.value=i,a)):(a.value=r,a)}});function Rh(e){return new Bh({type:"transform",transform:e})}var xr=k("ZodOptional",(e,t)=>{er.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function wr(e){return new xr({type:"optional",innerType:e})}var Dh=k("ZodExactOptional",(e,t)=>{hg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>mr(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Oh(e){return new Dh({type:"optional",innerType:e})}var $h=k("ZodNullable",(e,t)=>{ug.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>zp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function kr(e){return new $h({type:"nullable",innerType:e})}var Fh=k("ZodDefault",(e,t)=>{mg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Bp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hh(e,t){return new Fh({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Uh=k("ZodPrefault",(e,t)=>{fg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Rp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function jh(e,t){return new Uh({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Pn(t)}})}var Cr=k("ZodNonOptional",(e,t)=>{bg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Mp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Zh(e,t){return new Cr({type:"nonoptional",innerType:e,...$(t)})}var qh=k("ZodCatch",(e,t)=>{vg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Dp(e,a,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Vh(e,t){return new qh({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}var Gh=k("ZodPipe",(e,t)=>{yg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Op(e,a,n,r),e.in=t.in,e.out=t.out});function Sr(e,t){return new Gh({type:"pipe",in:e,out:t})}var Wh=k("ZodReadonly",(e,t)=>{_g.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>$p(e,a,n,r),e.unwrap=()=>e._zod.def.innerType});function Kh(e){return new Wh({type:"readonly",innerType:e})}var Yh=k("ZodCustom",(e,t)=>{xg.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(a,n,r)=>Ep(e,a,n,r)});function Jh(e,t={}){return hp(Yh,e,t)}function Xh(e){return up(e)}var Du=fp,Ou=bp,Qh=H({role:ft(["user","assistant"]),content:x(),timestamp:Ie().optional()}),eu=H({sku:x(),name:x(),imageUrl:x().url().optional(),price:x().optional(),originalPrice:x().optional(),url:x().url(),ctaLabel:x().optional()}),tu=H({buttons:W(H({label:x(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),au=H({}),nu=H({label:x().optional()}),Er=H({sku:x(),name:x(),price:x(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional()}),ru=H({recommended:Er,products:W(Er),attributes:W(H({label:x(),values:W(x())})),highlights:W(x()),specialCases:W(x()).optional(),recommendedText:x().optional(),winnerHits:Ye(x(),H({positive:W(x()).optional(),negative:W(x()).optional()})).optional(),productActions:Ye(x(),H({title:x(),type:x(),payload:ye().optional()})).optional()}),iu=H({label:x(),sentiment:ft(["positive","negative","neutral"]).optional()}),ou=H({product:Ye(x(),ye()),role:x().optional(),reason:x().optional(),labels:W(iu).optional(),expertQualityScore:Ie().optional(),reviewHighlight:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()}).optional()}),su=H({suggestions:W(ou)}),cu=H({title:x().optional(),text:x().optional(),reviewCount:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}),lu=H({entries:W(H({name:x(),image:x().optional(),description:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),du=H({entries:W(H({shortName:x(),detailedMessage:x().optional(),whyDifferent:x().optional(),image:x().optional(),action:H({title:x(),type:x(),payload:ye().optional()})}))}),Pr=H({title:x(),type:x(),payload:ye().optional()}),bt=H({name:x().optional(),value:x().optional(),option_value:x().optional(),attribute_value:x().optional(),type:x().optional(),attribute:x().optional(),option_name:x().optional(),attribute_name:x().optional(),variant_name:x().optional(),sku:x().optional(),price:ct([Ie(),x()]).optional(),price_discounted:ct([Ie(),x()]).optional(),image:x().optional(),imageUrl:x().optional(),image_url:x().optional(),color:x().optional(),colour:x().optional(),color_hex:x().optional(),hex:x().optional(),swatch:x().optional(),swatchColor:x().optional(),in_stock:Ke().optional(),inStock:Ke().optional()}),gu=H({product:H({sku:x().optional(),name:x().optional(),images:W(x()).optional(),imageUrl:x().optional(),rating:Ie().optional(),reviewCount:Ie().optional(),price:x().optional(),originalPrice:x().optional(),discountReason:x().optional(),discount_reason:x().optional(),campaignReason:x().optional(),campaign_reason:x().optional(),originalPriceStyle:ft(["strikethrough","inline"]).optional(),price_original_style:ft(["strikethrough","inline"]).optional(),price_discount_rate:Ie().optional(),price_async:Ke().optional(),inStock:Ke().optional(),promotions:W(x()).optional(),variants:W(bt).optional(),variantOptions:W(bt).optional(),variant_options:W(bt).optional(),productVariants:W(bt).optional(),product_variants:W(bt).optional(),url:x().optional(),cartCode:x().optional(),description:x().optional(),description_html:x().optional(),descriptionHtml:x().optional(),facet_hits:Ye(x(),ye()).optional(),facetHits:Ye(x(),ye()).optional(),features:W(H({name:x().optional(),key:x().optional(),label:x().optional(),value:ct([x(),Ie(),Ke()]).optional()})).optional(),specifications:ct([Ye(x(),x()),W(H({key:x(),value:x()}))]).optional()}).optional(),action:Pr.optional()}),pu=H({endOfList:Ke().optional()}),hu=H({review_class:x().optional(),review_text:x().optional(),review_rating:ct([x(),Ie()]).optional(),review_tag:x().optional()}),uu=H({reviews:W(hu).optional()}),mu=H({productName:x().optional(),pros:W(x()).optional(),cons:W(x()).optional()}),fu=H({groups:W(H({groupName:x(),products:W(Ye(x(),ye())).optional()})).optional(),filterTags:W(H({title:x(),action:Pr.optional()})).optional()}),bu=H({summary:x().optional(),products_discussed:W(x()).optional(),user_sentiment:x().optional()}),vu=H({summary:x(),clues:W(x()),strengths:W(x()).optional(),focus_points:W(x()).optional(),celeb_style:x().optional(),celeb_style_reason:x().optional(),details:W(x()).optional(),next_question:x().optional(),style_images:W(x()).optional()}),yu=H({processing:Ke().optional(),title:x().optional(),description:x().optional(),upload_label:x().optional(),skip_label:x().optional()}),_u={components:{MessageBubble:{schema:Qh,description:"A single chat message bubble for user or assistant turns."},ProductCard:{schema:eu,description:"A product card rendered inline in the chat stream."},ActionButtons:{schema:tu,description:"A horizontal row of quick-reply action buttons."},TypingIndicator:{schema:au,description:"An animated indicator shown while the assistant is typing."},Divider:{schema:nu,description:"A horizontal rule with an optional label."},ComparisonTable:{schema:ru,description:"A product comparison table with recommended pick, attribute rows, and highlights."},AITopPicks:{schema:su,description:"Rich AI-curated product suggestion cards with roles, sentiment labels, scores, and review quotes."},GroundingReviewCard:{schema:cu,description:"A card showing review grounding data with review count and CTA."},AIGroupingCards:{schema:lu,description:"Category grouping cards with images and labels for product discovery."},AISuggestedSearchCards:{schema:du,description:"Suggested search cards with images, descriptions, and differentiation."},ProductDetailsPanel:{schema:gu,description:"Full product detail view with images, specs, variants, and purchase actions."},ProductGrid:{schema:pu,description:'A scrollable grid of ProductCard children with optional "more" pagination.'},ReviewHighlights:{schema:uu,description:"A list of highlighted customer reviews with sentiment and ratings."},ProsAndCons:{schema:mu,description:"A pros and cons list for a product."},CategoriesContainer:{schema:fu,description:"Tabbed product groups with optional filter tag buttons."},HandoffNotice:{schema:bu,description:"A notice shown when the conversation is escalated to a human agent."},PhotoAnalysisCard:{schema:vu,description:"Structured photo analysis card with strengths, focus points, celeb vibe, details, and follow-up question."},BeautyPhotoStep:{schema:yu,description:"Transient selfie upload prompt for beauty consulting init flow."}}};function Ar(e){return e.length>120?!1:/^[a-zA-Z0-9#(),.\s%/\-]+$/.test(e)}function va(e){return typeof e=="object"&&e!==null&&typeof e.type=="string"}var Tr=class lt extends ui{constructor(...t){super(...t),this._shadow=null,this._rootEl=null,this._backdropEl=null,this._launcher=null,this._drawer=null,this._bridge=null,this._drawerVisible=!1,this._pillLauncherApply=null,this._hostScrollLockActive=!1,this._preventHostDocumentTouchMove=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._preventHostDocumentWheel=a=>{this._hostScrollLockActive&&(this._hostScrollEventShouldReachChatScroller(a)||a.preventDefault())},this._messages=[],this._currentMessageId=0,this._abortControllers=new Set,this._currentThreadId=null,this._lastThreadId=null,this._chatCreatedAt="",this._lastBackendContext=null,this._productSort={type:"related"},this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._comparisonRefreshRafId=null,this._viewedProductSkus=new Set,this._thumbnailEntries=[],this._choicePrompterEl=null,this._openState="full",this._mobileBreakpoint=768,this._isMobileViewport=!1,this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._i18n=Gt,this._extendedModeManager=null,this._activeTypewriter=null,this._activeTtsHandle=null,this._activeRequestThreadId=null,this._skuToProductItem={},this._conversationMode=null,this._initComplete=!1,this._pendingActions=[],this._bridgeContext=null,this._cartQuantity=null,this._threadsWithFirstBot=new Set,this._panel=null,this._localPanelHistory=[],this._currentPanelSource=null,this._session=null,this._presentation=new bn,this._eventCallbacks=new Map,this._lastSentAction=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._modeController=new ns}static{this._MAX_COMPARISON_SELECTION=5}static{this._MAX_PANEL_HISTORY=10}get _assistantMode(){return this._modeController.mode}set _assistantMode(t){this._modeController.mode=t}get _uiHints(){return this._modeController.uiHints}set _uiHints(t){this._modeController.uiHints=t}async onInit(t){if(this._i18n=this._resolveI18n(t),this._chatCreatedAt=new Date().toISOString(),t.pillLauncher){const u=Qc(t.pillLauncher);t.launcherImageUrl=u.launcherImageUrl,t.headerAvatarUrl===void 0&&(t.headerAvatarUrl=t.pillLauncher.avatarUrl),this._pillLauncherApply=()=>u.apply(this._shadow??void 0)}this._shadow=this.root.attachShadow({mode:"open"});const a=document.createElement("style");a.textContent=gl,this._shadow.appendChild(a);const n=this.root,r=(u,f)=>{f&&Ar(f)&&n.style.setProperty(u,f)};if(r("--gengage-chat-header-bg",t.headerBg),r("--gengage-chat-header-foreground",t.headerForeground),t.theme)for(const[u,f]of Object.entries(t.theme))u.startsWith("--")&&typeof f=="string"&&r(u,f);this._applyDiscountedPriceColorVar(t.productPriceUi?.discountedPriceColor);const i=document.createElement("div");i.className="gengage-chat-root",this._rootEl=i,this._shadow.appendChild(i);const o=t.variant??"floating";if(o==="inline"&&i.classList.add("gengage-chat--inline"),o!=="inline"){const u=document.createElement("div");u.className="gengage-chat-backdrop",u.setAttribute("aria-hidden","true"),u.setAttribute("role","button"),u.setAttribute("tabindex","-1"),u.setAttribute("aria-label",this._i18n.closeAriaLabel),u.addEventListener("click",f=>{f.preventDefault(),f.stopPropagation(),this.close()}),this._backdropEl=u,i.prepend(u)}if(o==="floating"){const u={onClick:()=>this.open(),ariaLabel:this._i18n.openButton};t.launcherImageUrl!==void 0?u.imageUrl=t.launcherImageUrl:t.launcherSvg!==void 0&&(u.svgMarkup=t.launcherSvg),t.hideMobileLauncher!==void 0&&(u.hideMobile=t.hideMobileLauncher),t.mobileBreakpoint!==void 0&&(u.mobileBreakpoint=t.mobileBreakpoint),t.launcherTooltip!==void 0&&(u.tooltip=t.launcherTooltip),this._launcher=ds(u),i.appendChild(this._launcher.container)}o==="overlay"&&i.classList.add("gengage-chat--overlay");const s=document.createElement("div");i.appendChild(s),this._drawer=new Xo(s,{i18n:this._i18n,onSend:(u,f)=>this._sendMessage(u,f),onClose:()=>this.close(),onAttachment:u=>this._handleAttachment(u),onPanelToggle:()=>{this._drawer?.persistPanelState(t.accountId)},onHostShellSync:()=>{this._applyOpenStateClasses()},onRollback:u=>this._handleRollback(u),onPanelBack:()=>this._navigatePanelBack(),onPanelForward:()=>this._panel?.navigateForward(),onPanelClose:()=>{if(this._isMobileViewport){this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[];return}this._localPanelHistory=[],this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._currentPanelSource=null},headerTitle:t.headerTitle,headerAvatarUrl:t.headerAvatarUrl,launcherImageUrl:t.launcherImageUrl,headerBadge:t.headerBadge,headerCartUrl:t.headerCartUrl,showHeaderFavorites:typeof t.onFavoritesClick=="function"||t.headerFavoritesToggle===!0,onCartClick:()=>{t.headerCartUrl?this._saveSessionAndOpenURL(t.headerCartUrl):t.onCartClick?.()},onFavoritesClick:()=>{if(wl(),typeof t.onFavoritesClick=="function"){t.onFavoritesClick();return}this._openFavoritesPanel()},getMobileState:()=>this._openState??"full",getMobileViewport:()=>this._isMobileViewport,onMobileSnap:u=>{u==="close"?this.close():(this._openState=u,this._applyOpenStateClasses())},onThumbnailClick:u=>this._rollbackToThread(u),onLinkClick:u=>{this._saveSessionAndOpenURL(u)},voiceEnabled:t.voiceEnabled,voiceLang:t.locale?`${t.locale.split("-")[0]??"tr"}-${(t.locale.split("-")[1]??t.locale.split("-")[0]??"TR").toUpperCase()}`:void 0,presentation:{onPinnedToBottomChange:u=>{this._presentation.pinnedToBottom=u},onUserInteractingChange:u=>{this._presentation.userInteracting=u},onFormerMessagesHint:()=>{this._presentation.focusedThreadId&&this._hasMultipleThreadIds()&&this._drawer?.setFormerMessagesButtonVisible(!0)},shouldBlockSoftAutoScroll:()=>this._presentation.shouldBlockStreamAutoScroll(),onReleasePresentationFocus:()=>this._releasePresentationFocus()}}),this._applyUiHints(),this._extendedModeManager=new Kc({onChange:u=>this._panel?.notifyExtension(u),productDetailsInPanel:(t.isDemoWebsite??!1)&&(t.productDetailsExtended??!1)}),this._panel=new Yc({drawer:()=>this._drawer,shadow:()=>this._shadow,currentThreadId:()=>this._currentThreadId,bridge:()=>this._bridge,extendedModeManager:()=>this._extendedModeManager,i18n:()=>this._i18n,rollbackToThread:u=>this._rollbackToThread(u)}),o!=="inline"&&this._drawer.getElement().classList.add("gengage-chat-drawer--hidden");const c=this._drawer.restorePanelState(t.accountId),l=t.panelMode??"auto";l==="collapsed"?this._drawer.setPanelCollapsed(!0):l==="expanded"&&this._drawer.setForceExpanded();const g=sessionStorage.getItem("gengage_restore_session_id"),d=sessionStorage.getItem("gengage_restore_sku"),p=!!(g&&d);p&&(sessionStorage.removeItem("gengage_restore_session_id"),sessionStorage.removeItem("gengage_restore_sku"));try{const u=new Gc;await u.open(),this._session=new fn(u),await this._restoreFromIndexedDB(p)}catch{this._session=new fn(null)}this._registerPublicAPI(),t.mobileInitialState!==void 0&&(this._openState=t.mobileInitialState),this._mobileBreakpoint=t.mobileBreakpoint??768,this._syncViewportState();const h=()=>this._syncViewportState();if(window.addEventListener("resize",h,{passive:!0}),this.addCleanup(()=>window.removeEventListener("resize",h)),window.visualViewport){const u=()=>{if(!this._drawerVisible||!this._isMobileViewport)return;const f=this._drawer?.getElement();if(!f)return;const y=window.innerHeight-(window.visualViewport?.height??window.innerHeight);f.style.setProperty("--gengage-keyboard-offset",`${Math.max(0,y)}px`)};window.visualViewport.addEventListener("resize",u),this.addCleanup(()=>window.visualViewport?.removeEventListener("resize",u))}o==="inline"&&(this._drawerVisible=!0,this.isVisible=!0,this._applyOpenStateClasses(),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60));const m={namespace:"chat",onMessage:u=>this._handleBridgeMessage(u)};t.allowedOrigins!==void 0&&(m.allowedOrigins=t.allowedOrigins),this._bridge=new fi(m),this._lastSku=this.config.pageContext?.sku,this._initComplete=!0;for(const u of this._pendingActions)this._sendAction(u.action,u.options);this._pendingActions=[],this._pillLauncherApply&&o==="floating"&&(await this._pillLauncherApply(),this._pillLauncherApply=null),we("gengage:chat:ready",{}),hl("chat"),t.onReady?.()}onUpdate(t){t.sku!==void 0&&t.sku!==this._lastSku&&(this._lastSku=t.sku,this._resetForNewPage())}onShow(){this._showDrawer(),this.emit("open"),we("gengage:chat:open",{state:this._openState}),ul("chat"),this.config.onOpen?.(),this._showWelcomeIfNeeded(),this._maybePrimeEntryContextOpening(),!this._pdpLaunched&&this.config.pageContext?.sku&&(this._pdpLaunched=!0,this._pdpPrimingInFlight=!0,this._sendAction({title:"",type:"launchSingleProduct",payload:{sku:this.config.pageContext.sku,...this._resolveContextualOpeningMessage("product")?{opening_message:this._resolveContextualOpeningMessage("product")}:{},...this._resolveContextualOpeningGuidance("product")?{opening_guidance:this._resolveContextualOpeningGuidance("product")}:{}}},{silent:!0,isPdpPrime:!0,preservePills:!0}))}onHide(){(this.config.variant??"floating")==="floating"&&(this.root.style.display=""),this._hideDrawer(),this.emit("close"),we("gengage:chat:close",{}),this.config.onClose?.()}onDestroy(){this._releaseHostDocumentScrollLock(),this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._comparisonRefreshRafId!==null&&(cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=null),this._drawer?.destroy(),Da(),this._drawer=null,this._bridge?.destroy(),this._bridge=null,this._extendedModeManager=null,this._panel?.destroy(),this._panel=null,this._session?.close(),this._session=null,this._localPanelHistory=[],this._currentPanelSource=null,window.gengage&&delete window.gengage.chat,this._shadow&&(this._shadow.innerHTML="",this._shadow=null),this._rootEl=null}open(t){t?.state!==void 0&&(this._openState=t.state,this._drawerVisible&&this._applyOpenStateClasses()),this.show(),t?.initialMessage!==void 0&&this._sendMessage(t.initialMessage)}openWithAction(t,a){a?.sku!==void 0&&this.update({sku:a.sku}),this._pdpLaunched=!0,a?.state!==void 0?this._openState=a.state:this._isMobileViewport&&(this._openState="half"),this.show(),this._drawerVisible&&this._applyOpenStateClasses(),this._sendAction(t)}sendMessage(t){this._sendMessage(t)}sendAction(t,a){this._sendAction(t,a)}close(){this.hide()}saveSession(t,a){sessionStorage.setItem("gengage_restore_session_id",t),sessionStorage.setItem("gengage_restore_sku",a)}get isOpen(){return this._drawerVisible}addCallback(t,a){let n=this._eventCallbacks.get(t);return n||(n=new Set,this._eventCallbacks.set(t,n)),n.add(a),()=>{n.delete(a),n.size===0&&this._eventCallbacks.delete(t)}}_applyDiscountedPriceColorVar(t){const a=this.root;t==="client"?a.style.setProperty("--gengage-discounted-price-color","var(--client-primary)"):a.style.removeProperty("--gengage-discounted-price-color")}_abortAllActiveRequests(){for(const t of this._abortControllers)t.abort();this._abortControllers.clear()}_pruneEmptyStreamingAssistantPlaceholders(){const t=[];let a=!1;for(const n of this._messages){if(n.role==="assistant"&&(n.status==="streaming"||n.status==="done")&&(n.content==null||n.content.length===0)){if(n.threadId){this._threadsWithFirstBot.delete(n.threadId),this._presentation.finalizeAssistantGroup(n.threadId),this._shadow?.querySelectorAll(`[data-thread-id="${CSS.escape(n.threadId)}"]:not([data-message-id])`).forEach(i=>i.remove()),this._panel&&(this._panel.threads=this._panel.threads.filter(i=>i!==n.threadId));const r=this._thumbnailEntries.length;this._thumbnailEntries=this._thumbnailEntries.filter(i=>i.threadId!==n.threadId),this._thumbnailEntries.length!==r&&(a=!0)}this._drawer?.removeMessageBubble(n.id),this._panel?.snapshots.delete(n.id),this._panel?.snapshotTypes.delete(n.id);continue}t.push(n)}this._messages.length=0,this._messages.push(...t),a&&this._drawer?.setThumbnails(this._thumbnailEntries)}_resetForNewPage(){this._activeRequestThreadId=null,this._abortAllActiveRequests(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._messages.length=0,this._drawer?.clearMessages(),this._drawer?.clearPanel(),this._currentPanelSource=null,this._panel.snapshots.clear(),this._panel.threads=[],this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._viewedProductSkus.clear(),this._currentThreadId=null,this._lastThreadId=null,this._lastBackendContext=null,this._chatCreatedAt=new Date().toISOString(),this._pdpLaunched=!1,this._entryContextPrimed=!1,this._pdpPrimingInFlight=!1,this._queuedUserMessages=[],this._productContextUnavailableSku=null,this._presentation.reset(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1),this._modeController.reset()&&(this._drawer?.setInputPlaceholder(this._i18n.inputPlaceholder),this._drawer?.setAttachmentControlsVisible(!0),this._drawer?.setBeautyPhotoStepCard({visible:!1}))}_clearAssistantPanelLikeStreamClearPanel(){this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._drawer?.clearPanel(),this._currentPanelSource=null,this._thumbnailEntries=[],this._drawer?.setThumbnails([]),this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._panel&&(this._panel.currentType=null,this._panel.updateExtendedMode(""),this._panel.updateTopBar(""))}_flushPresentationScroll(){const t=this._presentation.scrollRequest;if(!t||!this._drawer)return;let a=!1;t.type==="thread"&&t.threadId?(a=this._drawer.scrollThreadIntoView(t.threadId,t.behavior),a||(this._drawer.scrollToBottomPresentation(t.behavior),a=!0)):t.type==="bottom"&&(this._drawer.scrollToBottomPresentation(t.behavior),a=!0),a&&this._presentation.consumeScrollRequest(t.id)}_releasePresentationFocus(){this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_hasMultipleThreadIds(){const t=new Set;for(const a of this._messages)a.threadId&&t.add(a.threadId);return t.size>1}_orderedThreadIds(){const t=[],a=new Set;for(const n of this._messages)n.threadId&&!a.has(n.threadId)&&(a.add(n.threadId),t.push(n.threadId));return t}_maybeAutoAnchorUnreadAssistant(){if(!this._drawer||!this._presentation.shown)return;const t=this._orderedThreadIds();if(t.length===0)return;const a=Xc(t,this._presentation);if(!a)return;const n=`${a}:assistant`;this._presentation.lastAutoAnchoredGroupId!==n&&(this._presentation.userInteracting&&!this._presentation.pinnedToBottom||this._drawer.scrollThreadIntoView(a,"smooth")&&this._presentation.markGroupAutoAnchored(n))}_handleBridgeMessage(t){switch(t.type){case"openChat":this.open();break;case"closeChat":this.close();break;case"startNewChatWithLauncherAction":{const a=t.payload,n=a?.action,r=va(n)?n:va(a)?a:null;r&&this._sendAction(r,{silent:!0}),this.open();break}case"startNewChatWithDetailContext":{const a=t.payload;if(a&&typeof a=="object"){this._bridgeContext=a;const n=a.sku;if(n&&this.update({sku:n}),va(a.action)){this._pdpLaunched=!0,this.open(),this._sendAction(a.action);break}}this.open();break}case"launcherAction":{const a=t.payload?.action;a&&typeof a=="object"&&"type"in a&&this._sendAction(a);break}case"scrollToBottom":this._presentation.requestScrollToBottom("smooth"),setTimeout(()=>this._flushPresentationScroll(),40);break;case"addToCardHandler":this._bridge?.send("addToCardResult",t.payload);break;case"cartQuantityHandler":{const a=t.payload;a&&"quantity"in a&&typeof a.quantity=="number"&&(this._cartQuantity=a.quantity);break}case"favoritesCountHandler":{const a=t.payload?.count;typeof a=="number"&&a>=0&&this._drawer?.updateFavoritesBadge(a);break}case"minimizeRequestedByUser":this._extendedModeManager?.setHiddenByUser(!0);break;case"bgColorChange":{const a=t.payload?.color;typeof a=="string"&&Ar(a)&&this._shadow&&this._shadow.host.style.setProperty("--gengage-chat-bg",a);break}default:break}}_registerPublicAPI(){window.gengage||(window.gengage={}),window.gengage.chat={open:t=>this.open(t),openWithAction:(t,a)=>this.openWithAction(t,a),sendMessage:t=>this.sendMessage(t),sendAction:(t,a)=>this.sendAction(t,a),close:()=>this.close(),saveSession:(t,a)=>this.saveSession(t,a),get isOpen(){return!1},on:(t,a)=>this.on(t,a),trackCheckout:(t,a)=>this.trackCheckout(t,a),flushMeteringSummary:t=>this.flushMeteringSummary(t),addCallback:(t,a)=>this.addCallback(t,a)},Object.defineProperty(window.gengage.chat,"isOpen",{get:()=>this._drawerVisible})}_showDrawer(){if(this._drawerVisible)return;this._drawerVisible=!0;const t=this._drawer?.getElement();t&&t.classList.remove("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._drawer?.trapFocus(),this._isMobileViewport&&this._openState==="half"||this._drawer?.focusInput(),this._extendedModeManager?.setChatShown(!0),this._presentation.setShown(!0),setTimeout(()=>this._maybeAutoAnchorUnreadAssistant(),60)}_showWelcomeIfNeeded(){if(this._messages.length!==0)return;const t=this._resolveOpeningContextKey(),a=this._resolveContextualOpeningActions(t);if(a.length>0&&this._drawer?.setPills(a.map(i=>({label:i.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(i,t))}))),t==="product"&&this.config.pageContext?.sku||this._shouldPrimeContextualOpening(t))return;const n=this._resolveContextualOpeningMessage(t);if(!n)return;const r={id:Ea(),role:"assistant",content:n,timestamp:Date.now(),status:"done"};this._messages.push(r),this._drawer?.addMessage(r)}_resolveOpeningContextKey(){switch(this.config.pageContext?.pageType){case"home":return"home";case"search":case"plp":return"listing";case"pdp":return"product";default:return"default"}}_resolveContextualOpeningMessage(t=this._resolveOpeningContextKey()){return this.config.openingMessagesByContext?.[t]??(t!=="default"?this.config.openingMessagesByContext?.default:void 0)??this.config.welcomeMessage}_resolveContextualOpeningGuidance(t=this._resolveOpeningContextKey()){return this.config.openingGuidanceByContext?.[t]??(t!=="default"?this.config.openingGuidanceByContext?.default:void 0)}_resolveContextualOpeningActions(t=this._resolveOpeningContextKey()){const a=this.config.welcomeActionsByContext?.[t]??(t!=="default"?this.config.welcomeActionsByContext?.default:void 0);return a?.length?a.filter(n=>typeof n?.title=="string"&&n.title.trim().length>0):(this.config.welcomeActions??[]).filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>({title:n}))}_resolveContextualOpeningAction(t,a=this._resolveOpeningContextKey()){const n=t.title.trim(),r=this.config.pageContext?.sku??this._readContextStringField("sku"),i=this._readContextStringListField("visible_skus")??[];return t.icon==="review"&&r?{title:n,type:"reviewSummary",payload:{sku:r}}:t.icon==="similar"&&r?{title:n,type:"findSimilar",payload:{sku:r}}:t.icon==="compare"&&a==="listing"&&i.length>=2?{title:n,type:"getComparisonTable",payload:{sku_list:i.slice(0,2)}}:{title:n,type:"user_message",payload:n}}_readContextStringField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(o,s)=>s.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];return typeof i=="string"&&i.trim().length>0?i.trim():void 0}_readContextStringListField(t){const a=this.config.pageContext,n=a?.extra&&typeof a.extra=="object"&&!Array.isArray(a.extra)?a.extra:void 0,r=t.replace(/_([a-z])/g,(s,c)=>c.toUpperCase()),i=a?.[t]??n?.[t]??a?.[r]??n?.[r];if(!Array.isArray(i))return;const o=i.filter(s=>typeof s=="string"&&s.trim().length>0);return o.length>0?o:void 0}_buildEntryOpeningPageDetails(){const t={};t.url=this.config.pageContext?.url??window.location.href;const a=this._readContextStringField("page_title");a&&(t.page_title=a);const n=this._readContextStringField("page_description");n&&(t.page_description=n);const r=this._readContextStringField("search_query");r&&(t.search_query=r);const i=this._readContextStringListField("visible_skus");i?.length&&(t.visible_skus=i);const o=this._readContextStringListField("popular_searches");o?.length&&(t.popular_searches=o);const s=this.config.pageContext?.categoryTree??this._readContextStringListField("category_path");return s?.length&&(t.category_path=s),Object.keys(t).length>0?t:void 0}_shouldPrimeContextualOpening(t=this._resolveOpeningContextKey()){return this._messages.length!==0||this._entryContextPrimed||this._pdpPrimingInFlight||t==="product"?!1:!!(this.config.openingMessagesByContext||this.config.openingGuidanceByContext||this.config.welcomeActionsByContext)}_maybePrimeEntryContextOpening(){const t=this._resolveOpeningContextKey();if(!this._shouldPrimeContextualOpening(t))return;this._entryContextPrimed=!0;const a={text:"",is_entry_context_opening:1,opening_context_key:t},n=this._buildEntryOpeningPageDetails();n&&(a.page_details=n);const r=this._resolveContextualOpeningMessage(t);r&&(a.opening_message=r);const i=this._resolveContextualOpeningGuidance(t);i&&(a.opening_guidance=i),this._sendAction({title:"",type:"user_message",payload:a},{silent:!0,preservePills:!0})}_hideDrawer(){if(!this._drawerVisible)return;this._drawer?.releaseFocus(),this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._drawerVisible=!1,this._openState="full";const t=this._drawer?.getElement();t&&t.classList.add("gengage-chat-drawer--hidden"),this._applyOpenStateClasses(),this._extendedModeManager?.setChatShown(!1),this._presentation.setShown(!1),this._drawer?.setPresentationFocus(null),this._drawer?.setFormerMessagesButtonVisible(!1)}_syncViewportState(){if(this._rootEl){if(this._isMobileViewport=window.innerWidth<=this._mobileBreakpoint,this._rootEl.classList.toggle("gengage-chat-root--mobile",this._isMobileViewport),this._launcher){const t=this._isMobileViewport&&this.config.hideMobileLauncher===!0;this._launcher.container.classList.toggle("gengage-chat-launcher--hidden-mobile",t)}this._applyOpenStateClasses()}}_isMaximizedForHostChrome(){if(!this._drawerVisible)return!1;const t=this.config.variant??"floating";return t==="inline"?!1:t==="overlay"?!0:this._drawer?.isPanelVisible()??!1}_applyOpenStateClasses(){if(!this._rootEl)return;const t=this._drawerVisible&&this._isMobileViewport&&this._openState==="half",a=this._drawerVisible&&this._isMobileViewport&&this._openState==="full",n=this._isMaximizedForHostChrome();if(this._rootEl.classList.toggle("gengage-chat-root--open",this._drawerVisible),this._rootEl.classList.toggle("gengage-chat-root--mobile-half",t),this._rootEl.classList.toggle("gengage-chat-root--mobile-full",a),this._rootEl.classList.toggle("gengage-chat-root--maximized-host-chrome",n),this._backdropEl){const r=n&&(this.config.variant??"floating")!=="inline";this._backdropEl.setAttribute("aria-hidden",r?"false":"true")}this._syncHostDocumentScrollLock()}_syncHostDocumentScrollLock(){if(!(typeof document>"u")){if((this.config.variant??"floating")==="inline"){this._releaseHostDocumentScrollLock();return}this._isMaximizedForHostChrome()?this._applyHostDocumentScrollLock():this._releaseHostDocumentScrollLock()}}_hostScrollEventShouldReachChatScroller(t){try{const a=t.composedPath();if(!a.includes(this.root))return!1;for(const n of a){if(n===this.root)break;if(!(n instanceof HTMLElement))continue;if(this._backdropEl&&(n===this._backdropEl||this._backdropEl.contains(n)))return!1;const r=window.getComputedStyle(n),i=(r.overflowY==="auto"||r.overflowY==="scroll")&&n.scrollHeight>n.clientHeight+1,o=(r.overflowX==="auto"||r.overflowX==="scroll")&&n.scrollWidth>n.clientWidth+1;if(i||o)return!0}return!1}catch{return!1}}_applyHostDocumentScrollLock(){typeof document>"u"||this._hostScrollLockActive||(document.addEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0,passive:!1}),document.addEventListener("wheel",this._preventHostDocumentWheel,{capture:!0,passive:!1}),this._hostScrollLockActive=!0)}_releaseHostDocumentScrollLock(){typeof document>"u"||!this._hostScrollLockActive||(document.removeEventListener("touchmove",this._preventHostDocumentTouchMove,{capture:!0}),document.removeEventListener("wheel",this._preventHostDocumentWheel,{capture:!0}),this._hostScrollLockActive=!1)}_handleAttachment(t){const a=Ci(t);if(!a.ok){we("gengage:global:error",{message:a.reason==="invalid_type"?this._i18n.invalidFileType:this._i18n.fileTooLarge,source:"chat"});return}this._drawer?.stageAttachment(t)}_sendMessage(t,a){this._pdpPrimingInFlight&&(this._abortAllActiveRequests(),this._pdpPrimingInFlight=!1,this._queuedUserMessages=[]),(!this._messages.some(r=>r.role==="user")||this._drawer?.isKvkkBannerVisible())&&(oa(this.config.accountId),this._drawer?.hideKvkkBanner()),Sl(),this._messages.some(r=>r.role==="user")||El(),Me("chat","sendMessage",{mode:this._assistantMode,hasAttachment:a!==void 0,textLength:t.length});const n=a!==void 0?{title:t,type:this._modeController.resolveAttachmentActionType(),payload:t?{text:t}:{}}:{title:t,type:"user_message",payload:t};a!==void 0?this._sendAction(n,{attachment:a}):this._sendAction(n)}_flushQueuedUserMessages(){if(this._pdpPrimingInFlight||this._queuedUserMessages.length===0)return;const t=[...this._queuedUserMessages];this._queuedUserMessages=[];for(const a of t)this._sendMessage(a.text,a.attachment)}_applyUiHints(){this._modeController.applyUiHints(this._drawer,this._i18n.inputPlaceholder,()=>{this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(t=>t.remove())})}_handleRedirectMetadata(t){this._modeController.handleRedirect(t)}_sendAction(t,a){if(this._activeTypewriter?.cancel(),this._activeTypewriter=null,this._activeTtsHandle?.stop(),this._activeTtsHandle=null,this._lastSentAction={action:t,options:a},!this._initComplete){this._pendingActions.length<10&&this._pendingActions.push({action:t,options:a});return}if(this._choicePrompterEl?.remove(),this._choicePrompterEl=null,a?.preservePanel||Uc(),!a?.preservePanel&&this._comparisonSelectMode&&t.type!=="getComparisonTable"&&(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[]),a?.preservePanel||(this._localPanelHistory=[]),this._currentThreadId&&this._lastThreadId&&this._lastThreadId>this._currentThreadId){const v=this._currentThreadId,b=this._messages.filter(_=>_.threadId!==void 0&&_.threadId>v);this._messages=this._messages.filter(_=>!_.threadId||_.threadId<=v);for(const _ of b)this._shadow?.querySelector(`[data-message-id="${CSS.escape(_.id)}"]`)?.remove(),this._panel.snapshots.delete(_.id),this._panel.snapshotTypes.delete(_.id);this._shadow?.querySelectorAll("[data-thread-id]")?.forEach(_=>{_ instanceof HTMLElement&&_.dataset.threadId&&_.dataset.threadId>v&&_.remove()})}a?.preservePills||this._drawer?.setPills([]),this._drawer?.clearInputAreaChips(),this._bridge?.send("isResponding",!0);const n=Ea();this._currentThreadId=n,this._lastThreadId=n,this._panel&&t.type!=="launchSingleProduct"&&(this._panel.lastActionType=t.type);const r=a?.preservePanel===!0,i=t.type==="launchSingleProduct"&&a?.silent===!0&&a?.isPdpPrime===!0;if(r||(this._activeRequestThreadId=n),!a?.silent&&!r&&this._drawer?.setPresentationFocus(n),!a?.silent){const v=typeof t.payload=="string"?t.payload:typeof t.payload?.text=="string"?t.payload.text:t.title,b=this._messages.length>0?this._messages[this._messages.length-1]:void 0;if(!(b!==void 0&&b.role==="user"&&b.content===v)){const _=this._createMessage("user",v);_.threadId=n,a?.attachment!==void 0&&(_.attachment=a.attachment),this._drawer?.addMessage(_),this._messages.push(_)}}if(!a?.silent&&this._assistantMode==="shopping"&&this._hasUnavailableProductContext()&&(t.type==="user_message"||t.type==="inputText")){const v=this._i18n.productNotFoundMessage,b=this._createMessage("assistant",v);b.threadId=n,b.status="done",this._messages.push(b),this._ensureAssistantMessageRendered(b),this._drawer?.updateBotMessage(b.id,v),this._drawer?.setPresentationFocus(n),this._bridge?.send("isResponding",!1),this.emit("message",b),this._persistToIndexedDB().catch(()=>{});return}let o=this._currentPanelSource,s=!1;const c=()=>{s||a?.preservePanel||(o=this._currentPanelSource,s=!0)},l=()=>{if(this._drawer?.isPanelLoading()){if(o){const v=this._buildRenderContext(),b=this._renderPanelFromSource(o,v);this._drawer.setPanelContent(b),this._drawer.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(o)),this._currentPanelSource=o}else this._drawer.clearPanel(),this._currentPanelSource=null;o=null}};t.type==="getComparisonTable"&&(this._drawer?.showPanelLoading("comparisonTable"),this._panel?.updateTopBarForLoading("comparisonTable")),!a?.silent&&!r&&this._pruneEmptyStreamingAssistantPlaceholders(),this._drawer?.showTypingIndicator();let g="";const d=this._createMessage("assistant","");d.threadId=n,d.status="streaming",a?.silent&&(d.silent=!0),this._messages.push(d),this._presentation.registerAssistantActivity(n),this._presentation.requestThreadFocus(n,"smooth"),(a?.silent||r)&&this._drawer?.setPresentationFocus(n),this._drawer?.setFormerMessagesButtonVisible(!1),setTimeout(()=>this._flushPresentationScroll(),40),a?.preservePanel||this._abortAllActiveRequests();const p={middlewareUrl:this.config.middlewareUrl,...this.config.accountId?{accountId:this.config.accountId}:{}};a?.attachment!==void 0&&(p.attachment=a.attachment);const h=this._getVisibleMessages().filter(v=>v!==d&&(v.content||v.role==="assistant")).slice(-50).map(v=>({role:v.role==="user"?"user":"model",content:v.content??""})),m={outputLanguage:dl(this.config.locale),parentUrl:window.location.href,windowWidth:String(window.innerWidth),windowHeight:String(window.innerHeight),selfUrl:"",id:this.config.session?.sessionId??"",userId:this.config.session?.userId??"",appId:this.config.accountId,threads:[],createdAt:this._chatCreatedAt,kvkkApproved:yn(this.config.accountId),voiceEnabled:this.config.voiceEnabled??!1,threadId:n,isControlGroup:this.config.session?.abTestVariant==="control",isMobile:this._isMobileViewport};this._modeController.isShopping||(m.assistantMode=this._modeController.mode),this.config.session?.viewId!==void 0&&(m.viewId=this.config.session.viewId);const u=ko(t,{pageContext:this.config.pageContext,backendContext:this._lastBackendContext,isMobile:this._isMobileViewport}),f={account_id:this.config.accountId,session_id:this.config.session?.sessionId??"",correlation_id:this.config.session?.sessionId??"",type:u.type,locale:this.config.locale??"tr",meta:m,context:{...this._lastBackendContext??{},messages:h,session_id:this.config.session?.sessionId??""}};this.config.session?.userId!==void 0&&(f.user_id=this.config.session.userId),this.config.session?.viewId!==void 0&&(f.view_id=this.config.session.viewId),u.payload!==void 0&&(f.payload=u.payload),this.config.pageContext?.sku!==void 0&&(f.sku=this.config.pageContext.sku),this.config.pageContext?.pageType!==void 0&&(f.page_type=this.config.pageContext.pageType);const y=crypto.randomUUID(),M=Date.now();let C=0,P=!1,w=!1,N=!1,R=!1,L=!1;const Z=rs();let te=null;const X=()=>{if(this._drawer){if(this._isMobileViewport||!N){this._drawer.setPanelAiZoneState("hidden");return}R||(L?this._drawer.setPanelAiZoneState("hidden"):this._drawer.setPanelAiZoneState("analyzing",{analyzingLabel:this._i18n.aiAnalysisAnalyzingLabel}))}};this.track(zr(this.analyticsContext(),{endpoint:"process_action",request_id:y,widget:"chat"}));let I=null;if(I=Eo(f,{onTextChunk:(v,b,_)=>{if(!r&&n!==this._activeRequestThreadId||(g+=v,this._drawer?.removeTypingIndicator(),_?.skuToProductItem&&(this._skuToProductItem={...this._skuToProductItem,..._.skuToProductItem}),_?.conversationMode&&(this._conversationMode=_.conversationMode),_?.renderHint&&(d.renderHint=_.renderHint),this.track(Mr(this.analyticsContext(),{request_id:y,chunk_index:C++,widget:"chat"})),!this._drawer))return;let S=g;const T=_?.kvkk===!0||i&&ia(S);if(b&&T){const D=this.config.accountId;if(!yn(D)){const A=cl(S);A?this._drawer?.showKvkkBanner(A,()=>{this._drawer?.hideKvkkBanner(),oa(D)}):oa(D)}S=sl(S)}const z=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(z?z.innerHTML=Ae(S):(d.content=S,d.role==="assistant"&&d.threadId&&!this._threadsWithFirstBot.has(d.threadId)&&(this._threadsWithFirstBot.add(d.threadId),this._drawer.markFirstBotMessage(d.id)),this._drawer.addMessage(d)),b)if(d.content=S,d.status="done",xn(),os(d))this._drawer?.updateBotMessage(d.id,S,"photo_analysis",d.photoAnalysis);else{const D=this._shadow?.querySelector(`[data-message-id="${d.id}"] .gengage-chat-bubble-text`);if(D){this._activeTypewriter?.cancel();const A=_?.productMentions;this._activeTypewriter=Bc({container:D,html:Ae(S),onTick:()=>this._drawer?.scrollToBottomIfNeeded(),onComplete:()=>{this._activeTypewriter=null,A&&A.length>0&&D&&Rc({container:D,mentions:A,onProductClick:U=>{this._sendAction({title:A.find(F=>F.sku===U)?.short_name??U,type:"launchSingleProduct",payload:{sku:U}})}})}})}}},onUISpec:(v,b,_,S)=>{if(!r&&n!==this._activeRequestThreadId||b!=="chat")return;S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const T=v.elements[v.root],z=T?.type??"unknown";if(is(z,T?.props??{},Z,{drawer:this._drawer,ensureRendered:()=>this._ensureAssistantMessageRendered(d),cancelTypewriter:()=>{this._activeTypewriter?.cancel(),this._activeTypewriter=null},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:L},d))return;const D=z==="ProductGrid"&&T?.props?.similarsAppend===!0,A=this.config.productDetailsExtended!==!0&&(z==="ProductDetailsPanel"||D);A&&!S&&(this._clearAssistantPanelLikeStreamClearPanel(),P=!1);const U=z==="ProductDetailsPanel"&&_!=="panel"?"panel":_;this.track(Br(this.analyticsContext(),{request_id:y,chunk_index:C,component_type:z,widget:"chat"}));const F=this._buildRenderContext();if(F.isStreaming=!0,z==="ComparisonTable"){const j=T?.props?.products;_l(Array.isArray(j)?j.length:0)}if(z==="ProductGrid"){const j=T?.children?.length??0;kl(void 0,j)}const K=U==="panel"&&this._panel?this._panel.toPanelSpec(v):v;if(U==="panel"&&this._panel&&!A){const j=!w;w=!0;const B=Jc({componentType:z,similarsAppend:T?.props?.similarsAppend===!0,currentPanelType:this._panel.currentType,hasPanelContent:this._drawer?.hasPanelContent()??!1,isPanelLoading:this._drawer?.isPanelLoading()??!1,isFirstPanelContentInStream:j});F.panelProductListHeading=void 0,z==="ProductGrid"&&(B==="appendSimilars"?F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products":this._applyPanelListHeadingToContext(F,{kind:"spec",spec:K})),B==="appendSimilars"?this._appendSimilarsToPanel(K,F):B==="append"?(this._drawer?.appendPanelContent(this._renderUISpec(K,F)),this._comparisonSelectMode&&this._refreshComparisonUI()):(this._comparisonSelectMode=!1,this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,this._drawer?.setComparisonDockContent(null),this._drawer?.setPanelContent(this._renderUISpec(K,F)),this._currentPanelSource={kind:"spec",spec:K},this._panel.currentType=z),this._drawer?.setDividerPreviewEnabled((this._panel.currentType??z)==="ProductGrid"),z==="ProductDetailsPanel"&&t.type==="launchSingleProduct"&&this._clearUnavailableProductContext(),d.threadId&&!this._panel.threads.includes(d.threadId)&&this._panel.threads.push(d.threadId);const J=this._panel.currentType??z,O=T?.props?.panelTitle;if(this._panel.updateTopBar(J,O),this._panel.updateExtendedMode(z),this._isMobileViewport&&i&&this._drawer?.hideMobilePanel(),z==="ProductGrid"||z==="CategoriesContainer"){if(N=!this._isMobileViewport,te){const se=this._buildRenderContext();se.isStreaming=!0;const Ft=this._renderUISpec(te,se);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:Ft}),te=null}}else B!=="appendSimilars"&&B!=="append"&&(N=!1,te=null,this._drawer?.setPanelAiZoneState("hidden"))}if(z==="ProductDetailsPanel"&&U==="panel"&&(!d.silent||i)){const j=T?.props?.product;if(j){const B={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:j}}}},J=this._shadow?.querySelector(".gengage-chat-messages");if(J){const O=this._renderUISpec(B,F);d.threadId&&(O.dataset.threadId=d.threadId);const se=this._shadow?.querySelector(`[data-message-id="${d.id}"]`);se&&se.parentNode===J?se.after(O):J.appendChild(O),O.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),w=!0}}}const ee=z==="AITopPicks"||z==="AIGroupingCards";let ae=!1,de=!1;if(A&&D&&(F.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products"),ee&&!this._isMobileViewport&&!d.silent)if(N){const j=this._renderUISpec(v,F);R=!0,this._drawer?.setPanelAiZoneState("results",{resultEl:j}),ae=!0,te=null}else te=v,de=!0;const q=i&&z==="GroundingReviewCard";if((!d.silent||q)&&(U!=="panel"||z==="ProductCard"||A&&z==="ProductGrid"&&(!D||this._isMobileViewport))&&z!=="ActionButtons"&&!ae&&!(de&&ee)){const j=this._shadow?.querySelector(".gengage-chat-messages");if(j){const B=this._renderUISpec(v,F);d.threadId&&(B.dataset.threadId=d.threadId),j.appendChild(B),B.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed(),A&&z==="ProductGrid"&&(w=!0)}}if((z==="ProductGrid"||z==="ProductCard")&&d.threadId){const j=T?.children??[],B=z==="ProductGrid"?j.map(J=>v.elements[J]?.props?.product).filter(Boolean):[T?.props?.product].filter(Boolean);for(const J of B){const O=J.sku,se=J.imageUrl;O&&se&&this._thumbnailEntries.push({sku:O,imageUrl:se,threadId:d.threadId}),O&&this._viewedProductSkus.add(O)}this._drawer?.setThumbnails(this._thumbnailEntries)}if(z==="ProductGrid"||z==="ProductDetailsPanel"){const j=(z==="ProductGrid"?(T?.children??[]).map(B=>v.elements[B]?.props?.product).filter(Boolean):[T?.props?.product??T?.props].filter(Boolean)).map(B=>B.imageUrl).filter(B=>typeof B=="string").slice(0,5);j.length>0&&this._bridge?.send("previewImages",{images:j})}const _e=T?.children?.length??0;if(z==="ProductGrid"&&U==="panel"&&!A&&_e>1&&!this._modeController.isChoicePrompterHidden&&!this._comparisonSelectMode&&!jc(this._currentThreadId??"")){this._choicePrompterEl?.remove(),this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(B=>B.remove()),this._choicePrompterEl=Hc({heading:this._i18n.choicePrompterHeading,suggestion:this._i18n.choicePrompterSuggestion,ctaLabel:this._i18n.choicePrompterCta,threadId:this._currentThreadId??"",dismissAriaLabel:this._i18n.dismissAriaLabel,onCtaClick:()=>{this._comparisonSelectMode=!0,this._choicePrompterEl=null,this._refreshComparisonUI()},onDismiss:()=>{this._choicePrompterEl=null}});const j=this._shadow?.querySelector(".gengage-chat-panel-float");if(j){if(j.appendChild(this._choicePrompterEl),this._isMobileViewport&&window.visualViewport){const B=this._choicePrompterEl,J=()=>{window.visualViewport.height/window.innerHeight<.75&&(B.remove(),this._choicePrompterEl===B&&(this._choicePrompterEl=null),window.visualViewport.removeEventListener("resize",J))};window.visualViewport.addEventListener("resize",J)}}else this._choicePrompterEl=null}if(z==="ActionButtons"){const j=T?.props?.buttons;if(j&&j.length>0){const B=[],J=[];for(const O of j)if($c(O)){const se={label:O.label,action:O.action};O.icon&&(se.icon=O.icon),B.push(se)}else J.push(O);B.length>0&&this._drawer?.setInputAreaChips(B.map(O=>({label:O.label,onAction:()=>this._sendAction(O.action),...O.icon?{icon:O.icon}:{}}))),J.length>0&&this._drawer?.setPills(J.map(O=>{const se={label:O.label,onAction:()=>this._sendAction(O.action)};return O.icon&&(se.icon=O.icon),O.image&&(se.image=O.image),O.description&&(se.description=O.description),se}))}}X(),d.uiSpec=v},onAction:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="action"){const b={};this.config.actionHandling?.unknownActionPolicy!==void 0&&(b.unknownActionPolicy=this.config.actionHandling.unknownActionPolicy),this.config.actionHandling?.allowScriptCall!==void 0&&(b.allowScriptCall=this.config.actionHandling.allowScriptCall),_i(v,{openChat:()=>this.open(),navigate:_=>{fe(_.url)&&(this._bridge?.send("navigate",_),_.newTab?window.open(_.url,"_blank","noopener,noreferrer"):window.location.href=_.url)},saveSession:_=>this.saveSession(_.sessionId,_.sku),addToCart:_=>{we("gengage:similar:add-to-cart",_)},scriptCall:_=>{we("gengage:chat:script-call",_),this.config.onScriptCall?.(_)}},b)}},onMetadata:v=>{if(!(!r&&n!==this._activeRequestThreadId)&&v.type==="metadata"&&v.meta){if(v.meta.panel!==void 0||v.meta.messages!==void 0||v.meta.message_id!==void 0){this._lastBackendContext=v.meta;const _=Yt(v.meta.panel);_&&(this._modeController.updateFromContext(_),this._applyUiHints())}if(v.meta.panelLoading){const _=typeof v.meta.panelPendingType=="string"?v.meta.panelPendingType:void 0;this.config.productDetailsExtended!==!0&&(_==="productDetails"||_==="productDetailsSimilars")||(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(_),_&&this._panel?.updateTopBarForLoading(_))}if(v.meta.voice){const _=new CustomEvent("gengage:chat:voice",{detail:{payload:v.meta.voice},bubbles:!1,cancelable:!0}),S=window.dispatchEvent(_);if(Pl(),S){const T=v.meta.voice;T.audio_base64&&(this._activeTtsHandle?.stop(),this._activeTtsHandle=ps(T.audio_base64,T.content_type??"audio/ogg"))}}if((v.meta.redirectTarget||v.meta.redirect)&&(we("gengage:chat:redirect",{target:v.meta.redirectTarget??null,payload:v.meta.redirect??null}),Me("redirect","redirect dispatched",{target:v.meta.redirectTarget??null}),this._handleRedirectMetadata(v.meta.redirect)),v.meta.analyzeAnimation&&this.config.productDetailsExtended===!0&&(P=!0,w=!1,c(),this._panel&&(this._panel.currentType=null),this._drawer?.showPanelLoading(),this._panel?.updateTopBarForLoading("productDetails")),v.meta.loading){const _=Array.isArray(v.meta.thinkingMessages)?v.meta.thinkingMessages.filter(T=>typeof T=="string"):[],S=typeof v.meta.loadingText=="string"?v.meta.loadingText:void 0;if(_.length>0){const T=S&&this._modeController.shouldCondenseThinking()?[..._.slice(0,2),S]:_;this._drawer?.setThinkingSteps(T)}typeof S=="string"&&S.length>0&&(this._drawer?.addThinkingStep(S),this._bridge?.send("loadingMessage",{text:S}))}v.meta.visitorDataResponse&&this._bridge?.send("engagingMessage",v.meta.visitorDataResponse),v.meta.formType&&this._bridge?.send("glovOtokoc",{type:v.meta.formType,data:v.meta.formPayload}),v.meta.launcherContent&&this._bridge?.send("launcherContent",v.meta.launcherContent),we("gengage:chat:metadata",{payload:v.meta});const b=v.meta;typeof b.prompt_tokens=="number"&&typeof b.completion_tokens=="number"&&this.track(Or(this.analyticsContext(),{model:v.model??"unknown",prompt_tokens:b.prompt_tokens,completion_tokens:b.completion_tokens,total_tokens:b.total_tokens??b.prompt_tokens+b.completion_tokens}))}},onError:v=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;L=!0,this._activeTypewriter?.cancel(),this._activeTypewriter=null,X(),te=null,this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),this._drawer?.clearInputAreaChips(),cs(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const b=w;P&&!w&&l(),P=!1,w=!1;const _=d.silent||d.content!=null&&d.content.length>0||g.length>0||b,S=typeof navigator<"u"&&navigator.onLine===!1&&Sa(v),T=()=>{this._shadow?.querySelector(`[data-message-id="${CSS.escape(d.id)}"]`)?.remove();const A=this._messages.indexOf(d);A>=0&&this._messages.splice(A,1)};let z=!1;const D=()=>{if(S)return;this.emit("error",v);const A=v.message;A===this._lastErrorMessage?this._consecutiveErrorCount++:(this._consecutiveErrorCount=1,this._lastErrorMessage=A);const U=v.message.trim(),F=U.length>0?U:this._i18n.errorMessage,K={onRetry:()=>{this._lastSentAction&&this._sendAction(this._lastSentAction.action,this._lastSentAction.options)},onNewQuestion:()=>{this._drawer?.focusInput()}};if(this._consecutiveErrorCount>=2){T(),z=!0,this._drawer?.showErrorWithRecovery(this._i18n.accountInactiveMessage,K);return}if(rl(v,F)){T(),z=!0,this._drawer?.showErrorWithRecovery(F,K);return}d.content=F,d.status="done";const ee=Ae(F.replace(/\r\n/g,`
177
177
  `).split(`
178
178
  `).join("<br />"));this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,ee),this._drawer?.showRecoveryPillsOnly(K)};if(_)this._drawer?.setPills([]),d.silent||D();else if(i||this._hasUnavailableProductContext()){this._drawer?.setPills([]);const A=this._i18n.productNotFoundMessage;d.content=A,d.status="done",this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,A),this._markUnavailableProductContext()}else if(D(),S)return;i&&(this._pdpPrimingInFlight=!1,this._flushQueuedUserMessages()),!z&&d.status==="streaming"&&(d.status="error"),S||this.track(Dr(this.analyticsContext(),{request_id:y,error_code:"STREAM_ERROR",error_message:v.message,widget:"chat"}))},onDone:()=>{if(I&&this._abortControllers.delete(I),!r&&n!==this._activeRequestThreadId)return;if(L=!0,X(),te){const S=this._buildRenderContext();S.isStreaming=!1;const T=this._shadow?.querySelector(".gengage-chat-messages");if(T){const z=this._renderUISpec(te,S);d.threadId&&(z.dataset.threadId=d.threadId),T.appendChild(z),z.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}te=null}this._activeRequestThreadId=null,this._consecutiveErrorCount=0,this._lastErrorMessage="",this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),this._drawer?.removeTypingIndicator(),ss(Z,{drawer:this._drawer,ensureRendered:()=>{},cancelTypewriter:()=>{},sendSkipMessage:()=>this._sendMessage(this._i18n.beautyPhotoStepSkipMessage),streamDone:!0});const v=w;if(P&&!w&&l(),P=!1,i&&!g&&!v){const S=this._i18n.productNotFoundMessage;d.content=S,this._ensureAssistantMessageRendered(d),this._drawer?.updateBotMessage(d.id,S),this._markUnavailableProductContext()}if(w=!1,i){this._pdpPrimingInFlight=!1;const S=this._queuedUserMessages.length>0;this._flushQueuedUserMessages(),S||this._ensurePdpPrimeSuggestedUiIfNeeded()}d.status==="streaming"&&(d.status="done",xn()),this._presentation.finalizeAssistantGroup(n);const b=this._shadow?.querySelector(".gengage-chat-comparison-toggle-btn--hidden");b&&(b.classList.remove("gengage-chat-comparison-toggle-btn--hidden"),b.classList.add("gengage-chat-comparison-toggle-btn--reveal")),this.emit("message",d);const _=this._currentPanelSource;this._panel?.snapshotForMessage(d.id,_?()=>{const S=this._buildRenderContext();return this._renderPanelFromSource(_,S)}:void 0),this.track(Rr(this.analyticsContext(),{request_id:y,latency_ms:Date.now()-M,chunk_count:C,widget:"chat"})),this.track($r(this.analyticsContext(),{meter_key:"chat_request",quantity:1,unit:"request"})),this.track(Hr(this.analyticsContext(),{message_count:this._messages.length,history_ref:this.config.session?.sessionId??"",redaction_level:"none"})),this._persistToIndexedDB().catch(()=>{})}},p),this._abortControllers.add(I),!a?.silent&&!r){const v=I;this._drawer?.showStopButton(()=>{v.abort(),this._abortControllers.delete(v),this._drawer?.removeTypingIndicator(),this._bridge?.send("isResponding",!1),this._bridge?.send("loadingMessage",{text:null}),d.status==="streaming"&&(d.status="done")})}}_getVisibleMessages(){const t=this._messages.filter(n=>!n.silent);if(!this._currentThreadId)return t;const a=this._currentThreadId;return t.filter(n=>!n.threadId||n.threadId<=a)}_appendSimilarsToPanel(t,a){if(!this._drawer)return;const n=this._drawer.getPanelContentElement();if(!n)return;a.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products";const r=this._renderUISpec(t,a);r.classList.add("gengage-chat-product-details-similars"),n.appendChild(r),this._mergePanelSourceWithSimilars(t)}_mergePanelSourceWithSimilars(t){const a=this._currentPanelSource;a?.kind==="spec"&&this._panel?.currentType==="ProductDetailsPanel"&&(this._currentPanelSource={kind:"productDetailsWithSimilars",pdpSpec:a.spec,similarsSpec:t})}_renderProductDetailsWithSimilars(t,a,n){this._applyPanelListHeadingToContext(n,{kind:"productDetailsWithSimilars",pdpSpec:t,similarsSpec:a});const r=this._renderUISpec(t,n),i=this._renderUISpec(a,n);return i.classList.add("gengage-chat-product-details-similars"),r.appendChild(i),r}_applyPanelListHeadingToContext(t,a){if(t.panelProductListHeading=void 0,!!this._panel){if(a.kind==="spec"){const n=a.spec.elements[a.spec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._panel.titleForComponent("ProductGrid",n.props?.panelTitle??void 0))}else if(a.kind==="productDetailsWithSimilars"){const n=a.similarsSpec.elements[a.similarsSpec.root];n?.type==="ProductGrid"&&(n.children?.length??0)>0&&(t.panelProductListHeading=this._i18n.similarProductsLabel??"Similar Products")}}}_renderPanelFromSource(t,a){return this._applyPanelListHeadingToContext(a,t),t.kind==="favorites"?this._buildFavoritesPageEl():t.kind==="productDetailsWithSimilars"?this._renderProductDetailsWithSimilars(t.pdpSpec,t.similarsSpec,a):this._renderUISpec(t.spec,a)}_handleRollback(t){const a=this._messages.find(n=>n.id===t);a?.threadId&&this._rollbackToThread(a.threadId)}_ensurePdpPrimeSuggestedUiIfNeeded(){const t=this.config.pageContext?.sku;if(!t||!this._drawer||this._hasUnavailableProductContext())return;const a="product",n=this._resolveContextualOpeningActions(a);if(n.length>0){this._drawer.setInputAreaChips(n.map(r=>({label:r.title,onAction:()=>this._sendAction(this._resolveContextualOpeningAction(r,a)),...r.icon?{icon:r.icon}:{}})));return}this._drawer.setInputAreaChips([{label:this._i18n.groundingReviewCta,icon:"review",onAction:()=>this._sendAction({title:this._i18n.customerReviewsTitle,type:"reviewSummary",payload:{sku:t}})},{label:this._i18n.findSimilarLabel,icon:"similar",onAction:()=>this._sendAction({title:this._i18n.findSimilarLabel,type:"findSimilar",payload:{sku:t}})}])}_rollbackToThread(t){if(this._panel&&this._panel.threads.length>0&&!this._panel.threads.includes(t)&&!this._messages.some(i=>i.threadId===t))return;this._currentThreadId=t,this._extendedModeManager?.setHiddenByUser(!1),this._lastThreadId!=null&&t===this._lastThreadId?(this._presentation.setFocusedThreadId(t),this._drawer?.setPresentationFocus(t)):(this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null)),this._drawer?.setFormerMessagesButtonVisible(!1);for(const i of this._messages){const o=this._shadow?.querySelector(`[data-message-id="${CSS.escape(i.id)}"]`);o&&(i.threadId&&i.threadId>t?o.classList.add("gengage-chat-bubble--hidden"):o.classList.remove("gengage-chat-bubble--hidden"))}this._shadow?.querySelectorAll("[data-thread-id]").forEach(i=>{i instanceof HTMLElement&&i.dataset.threadId&&i.dataset.threadId>t?i.classList.add("gengage-chat-bubble--hidden"):i instanceof HTMLElement&&i.classList.remove("gengage-chat-bubble--hidden")});const a=this._messages.find(i=>i.role==="assistant"&&i.threadId===t),n=a?this._panel?.restoreForMessage(a.id):!1;n||(this._drawer?.clearPanel(),this._currentPanelSource=null),n&&a&&(this._currentPanelSource=null);const r=this._panel.currentType??"";if(this._panel?.updateTopBar(r),this._drawer?.setPills([]),requestAnimationFrame(()=>{this._drawer?.scrollThreadIntoView(t,"auto")}),this._session?.db&&this.config.session?.sessionId){const i=this.config.session.sessionId;(async()=>{try{const o=await this._session?.db?.loadContext(i,t);o&&(this._lastBackendContext=o.context),await this._session?.db?.deleteContextsAfterThread(i,t)}catch{}})()}}async _persistToIndexedDB(){!this._session||!this.config.session?.sessionId||await this._session.persist({userId:this.config.session.userId??"",appId:this.config.accountId,sessionId:this.config.session.sessionId,messages:this._messages,currentThreadId:this._currentThreadId,lastThreadId:this._lastThreadId,chatCreatedAt:this._chatCreatedAt,panelSnapshots:this._panel?.snapshots??new Map,panelThreads:this._panel?.threads??[],thumbnailEntries:this._thumbnailEntries,lastBackendContext:this._lastBackendContext,sku:this.config.pageContext?.sku})}_isSameOriginUrl(t){try{return t.trim()?new URL(t,window.location.href).origin===window.location.origin:!1}catch{return!1}}_markUnavailableProductContext(){this._productContextUnavailableSku=this.config.pageContext?.sku??null}_clearUnavailableProductContext(){this._productContextUnavailableSku=null}_hasUnavailableProductContext(){const t=this.config.pageContext?.sku;return t!==void 0&&t.length>0&&this._productContextUnavailableSku===t}_ensureAssistantMessageRendered(t){if(!(this._shadow?.querySelector(`[data-message-id="${CSS.escape(t.id)}"]`)||!this._drawer)){if(t.role==="assistant"&&t.threadId&&!this._threadsWithFirstBot.has(t.threadId)){this._threadsWithFirstBot.add(t.threadId),this._drawer.addMessage(t),this._drawer.markFirstBotMessage(t.id);return}this._drawer.addMessage(t)}}async _saveSessionAndOpenURL(t){this._session&&await this._session.saveAndOpenURL(t,()=>this._persistToIndexedDB(),this._bridge)}async _loadPayload(t,a){return this._session?this._session.loadPayload(t,a):null}async _restoreFromIndexedDB(t){if(!this._session?.db)return;const a=this.config.session?.sessionId;if(!a)return;const n=this.config.session?.userId??"",r=this.config.accountId;if(await this._session.loadFavorites(n,r),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size),!t)return;const i=await this._session.db?.loadSession(n,r,a);if(!i||i.messages.length===0)return;const o=this.config.pageContext?.sku;if(o&&i.sku&&i.sku!==o)return;if(this._pdpLaunched=!0,this._drawer?.lockScrollForRestore(),this._currentThreadId=i.currentThreadId,this._lastThreadId=i.lastThreadId,this._currentThreadId&&this._lastThreadId&&this._currentThreadId>this._lastThreadId&&(this._currentThreadId=this._lastThreadId),this._chatCreatedAt=i.createdAt,i.panelThreads&&(this._panel.threads=i.panelThreads),i.thumbnailEntries&&(this._thumbnailEntries=i.thumbnailEntries,this._drawer?.setThumbnails(this._thumbnailEntries)),i.panelSnapshotHtml)for(const[c,l]of Object.entries(i.panelSnapshotHtml)){const g=document.createElement("div");g.innerHTML=Ae(l),this._panel.snapshots.set(c,g)}let s=0;for(const c of i.messages){const l={id:c.id,role:c.role,timestamp:c.timestamp,status:c.status};if(c.threadId!==void 0&&(l.threadId=c.threadId),c.content!==void 0&&(l.content=c.content),c.silent&&(l.silent=!0),this._messages.push(l),l.silent)continue;l.role==="assistant"&&l.threadId&&!this._threadsWithFirstBot.has(l.threadId)&&(this._threadsWithFirstBot.add(l.threadId),this._drawer?.markFirstBotMessage(l.id)),this._drawer?.addMessage(l);const g=parseInt(c.id.replace("msg-",""),10);if(!isNaN(g)&&g>s&&(s=g),l.role==="assistant"&&l.threadId){const d=await this._loadPayload(l.threadId,l.id);d&&(l.uiSpec=d,this._restoreInlineUISpec(l),delete l.uiSpec)}}if(s>this._currentMessageId&&(this._currentMessageId=s),this._currentThreadId){let c=await this._session.db?.loadContext(a,this._currentThreadId);c||(c=await this._session.db?.loadLatestContext(a)),c&&(this._lastBackendContext=c.context)}if(this._currentThreadId){const c=[...this._messages].reverse().find(l=>l.role==="assistant"&&l.threadId===this._currentThreadId&&!l.silent);c&&this._panel.snapshots.has(c.id)&&this._panel?.restoreForMessage(c.id)}if(this._currentThreadId){const c=this._currentThreadId;for(const l of this._messages)l.threadId&&l.threadId>c&&this._shadow?.querySelector(`[data-message-id="${CSS.escape(l.id)}"]`)?.classList.add("gengage-chat-bubble--hidden");this._shadow?.querySelectorAll("[data-thread-id]").forEach(l=>{l instanceof HTMLElement&&l.dataset.threadId&&l.dataset.threadId>c&&l.classList.add("gengage-chat-bubble--hidden")})}if(this._panel.threads.length>0&&this._currentThreadId){const c=this._panel.threads[this._panel.threads.length-1];if(c){const l=[...this._messages].reverse().find(g=>g.role==="assistant"&&g.threadId===c);if(l?.threadId){const g=await this._loadPayload(l.threadId,l.id);if(g){const d=g.elements[g.root];d&&this._panel?.updateTopBar(d.type)}}}}this._presentation.releaseFocusedThread(),this._drawer?.setPresentationFocus(null),setTimeout(()=>{this._drawer?.scrollToLastThread()},550)}_navigatePanelBack(){const t=this._localPanelHistory.pop();if(t){const a=this._buildRenderContext(),n=this._renderPanelFromSource(t.source,a);this._drawer?.setPanelContent(n),this._drawer?.setDividerPreviewEnabled(this._shouldUseDividerPreviewForSource(t.source)),this._currentPanelSource=t.source;const r=this._localPanelHistory.length>0||(this._panel?.threads.length??0)>1;this._drawer?.updatePanelTopBar(r,!1,t.title);return}if(this._isMobileViewport){this._drawer?.hideMobilePanel();return}this._panel?.navigateBack()}_shouldUseDividerPreviewForSpec(t){return t.elements[t.root]?.type==="ProductGrid"}_shouldUseDividerPreviewForSource(t){return t?.kind==="spec"?this._shouldUseDividerPreviewForSpec(t.spec):!1}_toggleComparisonSku(t){if(t==="")this._comparisonSelectMode=!this._comparisonSelectMode,this._comparisonSelectionWarning=null,this._comparisonSelectMode&&(Zc(this._currentThreadId??""),this._choicePrompterEl?.remove(),this._choicePrompterEl=null,this._shadow?.querySelectorAll(".gengage-chat-choice-prompter").forEach(a=>a.remove())),this._comparisonSelectMode||(this._comparisonSelectedSkus=[],this._comparisonSelectionWarning=null,yl());else if(this._comparisonSelectedSkus.indexOf(t)>=0)this._comparisonSelectedSkus=this._comparisonSelectedSkus.filter(a=>a!==t),this._comparisonSelectionWarning=null;else{if(this._comparisonSelectedSkus.length>=lt._MAX_COMPARISON_SELECTION){this._comparisonSelectionWarning=this._i18n.compareMaxHint??`You can select up to ${lt._MAX_COMPARISON_SELECTION} products`,this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()});return}this._comparisonSelectedSkus=[...this._comparisonSelectedSkus,t],this._comparisonSelectionWarning=null,bl(t)}this._comparisonRefreshRafId!==null&&cancelAnimationFrame(this._comparisonRefreshRafId),this._comparisonRefreshRafId=requestAnimationFrame(()=>{this._comparisonRefreshRafId=null,this._refreshComparisonUI()})}_refreshComparisonUI(){const t=this._shadow?.querySelector(".gengage-chat-panel");if(!t){this._drawer?.setComparisonDockContent(null);return}const a=t.querySelector(".gengage-chat-product-grid-wrapper"),n=a?.querySelector(".gengage-chat-product-grid");if(!a||!n){this._drawer?.setComparisonDockContent(null);return}const r=a.querySelector(".gengage-chat-comparison-toggle-btn");if(r&&r.classList.toggle("gengage-chat-comparison-toggle-btn--active",this._comparisonSelectMode),this._comparisonSelectMode){const i=n.querySelectorAll(".gengage-chat-product-card[data-sku]");for(const o of i){if(o.parentElement?.classList.contains("gengage-chat-comparison-select-wrapper")){const h=o.parentElement,m=this._comparisonSelectedSkus.includes(o.dataset.sku);h.classList.toggle("gengage-chat-comparison-select-wrapper--selected",m);const u=h.querySelector(".gengage-chat-comparison-checkbox");if(u){u.dataset.selected=m?"true":"false",u.setAttribute("aria-pressed",m?"true":"false");const f=u.querySelector(".gengage-chat-comparison-checkbox-icon"),y=u.querySelector(".gengage-chat-comparison-checkbox-label");f&&(f.innerHTML=m?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>'),y&&(y.textContent=m?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare")}continue}const s=o.dataset.sku,c=document.createElement("div");c.className="gengage-chat-comparison-select-wrapper";const l=this._comparisonSelectedSkus.includes(s);l&&c.classList.add("gengage-chat-comparison-select-wrapper--selected");const g=document.createElement("button");g.type="button",g.className="gengage-chat-comparison-checkbox",g.dataset.selected=l?"true":"false",g.setAttribute("aria-pressed",l?"true":"false");const d=document.createElement("span");d.className="gengage-chat-comparison-checkbox-icon",d.innerHTML=l?'<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>':'<span class="gengage-chat-comparison-checkbox-dot"></span>';const p=document.createElement("span");p.className="gengage-chat-comparison-checkbox-label",p.textContent=l?this._i18n.comparisonSelectedLabel??"Selected":this._i18n.comparisonSelectLabel??"Select to compare",g.appendChild(d),g.appendChild(p),g.addEventListener("click",h=>{h.stopPropagation(),this._toggleComparisonSku(s)}),o.parentNode.insertBefore(c,o),c.appendChild(g),c.appendChild(o),c.classList.add("gds-clickable"),c.addEventListener("click",h=>{h.target.closest(".gengage-chat-comparison-checkbox")||(h.stopPropagation(),this._toggleComparisonSku(s))})}}else{const i=n.querySelectorAll(".gengage-chat-comparison-select-wrapper");for(const o of i){const s=o.querySelector(".gengage-chat-product-card");s&&o.parentNode&&(o.parentNode.insertBefore(s,o),o.remove())}}if(a.querySelector(".gengage-chat-comparison-floating-btn")?.remove(),this._comparisonSelectMode){const i=Xa(this._comparisonSelectedSkus,this._buildRenderContext());this._isMobileViewport?this._drawer?.setComparisonDockContent(i):(this._drawer?.setComparisonDockContent(null),a.appendChild(i))}else this._drawer?.setComparisonDockContent(null)}_parseAddToCartActionPayload(t){if(typeof t!="object"||t===null)return null;const a=t,n=this._coerceAddToCartString(a.sku),r=this._coerceAddToCartString(a.cartCode??a.cart_code);let i=1;return typeof a.quantity=="number"&&Number.isFinite(a.quantity)&&a.quantity>0&&(i=Math.max(1,Math.floor(a.quantity))),!n||!r?null:{sku:n,cartCode:r,quantity:i}}_coerceAddToCartString(t){return typeof t=="string"&&t.length>0?t:typeof t=="number"&&Number.isFinite(t)?String(t):""}_runChatAddToCartFlow(t){if(this.config.onAddToCart!==void 0)try{const r=this.config.onAddToCart(t);r instanceof Promise&&r.catch(i=>console.error("[gengage] onAddToCart",i))}catch(r){console.error("[gengage] onAddToCart",r)}Cl(t.sku,t.quantity);const a={...t,sessionId:this.config.session?.sessionId??null};we("gengage:chat:add-to-cart",a),this._bridge?.send("addToCart",t),this._runEventCallbacks("gengage-cart-add",a),this.track(Ur(this.analyticsContext(),{attribution_source:"chat",attribution_action_id:crypto.randomUUID(),cart_value:0,currency:this.config.pricing?.currencyCode??"TRY",line_items:t.quantity,sku:t.sku})),this._sendAction({title:this._i18n.addToCartButton??"Add to Cart",type:"addToCart",payload:{sku:t.sku,cart_code:t.cartCode,quantity:t.quantity}},{preservePanel:!0});const n=this._i18n.addedToCartToast??"Added to cart";this._drawer?.showCartToast(n),this._drawer?.flashCartBadge()}_buildRenderContext(){const t={onAction:a=>{if(ml(a.title,a.type),a.type==="addToCart"){const r=this._parseAddToCartActionPayload(a.payload);if(r){this._runChatAddToCartFlow(r);return}}if(a.type==="launchSingleProduct"){this._drawer?.setDividerPreviewEnabled(!1);const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";r&&_n(r,a.title)}if(a.type==="findSimilar"){const r=typeof a.payload=="object"&&a.payload!==null&&"sku"in a.payload?String(a.payload.sku):"";fl(r)}a.type==="getComparisonTable"&&vl(this._comparisonSelectedSkus);const n=a.type==="addToCart"||a.type==="like";this._sendAction(a,n?{preservePanel:!0}:void 0)},onProductClick:a=>{if(_n(a.sku),this.config.isDemoWebsite!==!0&&this._isSameOriginUrl(a.url))we("gengage:similar:product-click",{sku:a.sku,url:a.url,sessionId:this.config.session?.sessionId??null}),this._saveSessionAndOpenURL(a.url);else{const n=a.name?.trim()?a.name.trim():a.sku;this._sendAction({title:n,type:"launchSingleProduct",payload:{sku:a.sku}})}},onAddToCart:a=>{this._runChatAddToCartFlow(a)},onProductSelect:a=>{if(this._currentPanelSource){const s=this._drawer?.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:s}),this._localPanelHistory.length>lt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}const n=this._buildRenderContext(),r={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:a}}}},i=this._shadow?.querySelector(".gengage-chat-messages");if(i){const s=this._renderUISpec(r,n);this._currentThreadId&&(s.dataset.threadId=this._currentThreadId),i.appendChild(s),s.scrollIntoView({behavior:"auto",block:"end"}),this._drawer?.refreshPresentationCollapsed()}if(this.config.productDetailsExtended!==!0){this._clearAssistantPanelLikeStreamClearPanel();return}const o={root:"root",elements:{root:{type:"ProductDetailsPanel",props:{product:a}}}};this._drawer?.setPanelContent(this._renderUISpec(o,t)),this._drawer?.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"spec",spec:o},this._drawer?.updatePanelTopBar(!0,!1,this._i18n.panelTitleProductDetails)},i18n:this._i18n,pricing:this.config.pricing,productPriceUi:this.config.productPriceUi,productSort:this._productSort,onSortChange:a=>{this._productSort=a},comparisonSelectMode:this._comparisonSelectMode,comparisonSelectedSkus:this._comparisonSelectedSkus,comparisonMaxSelection:lt._MAX_COMPARISON_SELECTION,comparisonSelectionWarning:this._comparisonSelectionWarning,onToggleComparisonSku:a=>{this._toggleComparisonSku(a)},favoritedSkus:this._session?.favoritedSkus??new Set,onFavoriteToggle:(a,n)=>{this._toggleProductFavorite(a,n)},isMobile:this._isMobileViewport};return t}async _toggleFavorite(t,a){if(!this._session)return;const n=this.config.session?.userId??"",r=this.config.accountId;await this._session.toggleFavorite(n,r,t,a),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size)}_revertFavoriteHeartUi(t){const a=this._shadow?.querySelectorAll(`[data-gengage-favorite-sku="${CSS.escape(t)}"]`);if(a?.length)for(const n of a){if(!(n instanceof HTMLButtonElement))continue;n.classList.toggle("gengage-chat-favorite-btn--active");const r=n.querySelector("svg");r&&r.setAttribute("fill",n.classList.contains("gengage-chat-favorite-btn--active")?"currentColor":"none")}}async _toggleProductFavorite(t,a){const n=!(this._session?.favoritedSkus.has(t)??!1),r={sku:t,product:a,favorited:n,sessionId:this.config.session?.sessionId??null};we("gengage:chat:product-favorite",r),this._bridge?.send("productFavorite",r);const i=this._eventCallbacks.get("gengage-product-favorite");if(i&&i.size>0){for(const o of i)try{const s=o(r);if((s instanceof Promise?await s:s)===!1){this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}}catch{this._revertFavoriteHeartUi(t),this._handleCallbackFailure("gengage-product-favorite",r);return}this._session&&(n?this._session.favoritedSkus.add(t):this._session.favoritedSkus.delete(t),this._drawer?.updateFavoritesBadge(this._session.favoritedSkus.size));return}if(await this._toggleFavorite(t,a),n){xl(t);const o=a.name??t;this._sendAction({title:o,type:"like",payload:{sku:t}},{preservePanel:!0})}}_openFavoritesPanel(){if(this._drawer){if(this._currentPanelSource){const t=this._drawer.getPanelTopBarTitle()??"";this._localPanelHistory.push({source:this._currentPanelSource,title:t}),this._localPanelHistory.length>lt._MAX_PANEL_HISTORY&&this._localPanelHistory.shift()}this._drawer.setPanelContent(this._buildFavoritesPageEl()),this._drawer.setDividerPreviewEnabled(!1),this._currentPanelSource={kind:"favorites"},this._drawer.updatePanelTopBar(!0,!1,this._i18n.favoritesPageTitle)}}_buildFavoritesPageEl(){const t=this._session?.getFavoriteProducts()??[];if(t.length===0){const i=document.createElement("div");i.className="gengage-chat-favorites-empty";const o=document.createElement("div");o.className="gengage-chat-favorites-empty-icon",o.innerHTML='<svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>',i.appendChild(o);const s=document.createElement("p");return s.textContent=this._i18n.emptyFavoritesMessage,i.appendChild(s),i}const a={},n=[];for(const[i,o]of t.entries()){const s=`card_${i}`;n.push(s),a[s]={type:"ProductCard",props:{product:{sku:o.sku,name:o.name,imageUrl:o.imageUrl,price:o.price}}}}a.grid={type:"ProductGrid",children:n};const r={root:"grid",elements:a};return this._renderUISpec(r,this._buildRenderContext())}async _runEventCallbacks(t,a){const n=this._eventCallbacks.get(t);if(!(!n||n.size===0))for(const r of n)try{const i=r(a);if((i instanceof Promise?await i:i)===!1){this._handleCallbackFailure(t,a);return}}catch{this._handleCallbackFailure(t,a);return}}_handleCallbackFailure(t,a){if(t==="gengage-cart-add"){const n=this._i18n.cartAddErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}if(t==="gengage-product-favorite"){const n=this._i18n.favoriteToggleErrorMessage,r=this._createMessage("assistant",n);this._currentThreadId&&(r.threadId=this._currentThreadId),this._messages.push(r),this._drawer?.addMessage(r)}}_restoreInlineUISpec(t){if(!t.uiSpec||!this._drawer)return;const a=t.uiSpec,n=a.elements[a.root];if(!n)return;const r=n.type;if(r==="ActionButtons"||r==="ComparisonTable"||r==="ProductGrid"&&n.props?.similarsAppend===!0&&(this.config.productDetailsExtended===!0||!this._isMobileViewport))return;const i=this._buildRenderContext(),o=this._shadow?.querySelector(".gengage-chat-messages");if(!o)return;if(r==="ProductDetailsPanel"){const c=n.props?.product;if(!c)return;const l={root:"root",elements:{root:{type:"ProductSummaryCard",props:{product:c}}}},g=this._renderUISpec(l,i);t.threadId&&(g.dataset.threadId=t.threadId),o.appendChild(g),this._drawer?.refreshPresentationCollapsed();return}const s=this._renderUISpec(a,i);t.threadId&&(s.dataset.threadId=t.threadId),o.appendChild(s),this._drawer?.refreshPresentationCollapsed()}_createMessage(t,a){return this._currentMessageId++,{id:`msg-${this._currentMessageId}`,role:t,content:a,timestamp:Date.now(),status:"done"}}_resolveI18n(t){return{...Mo(t.locale),...t.i18n}}_resolveUISpecRegistry(){return Nr(en(),this.config.renderer?.registry)}_renderUISpec(t,a){const n=this._resolveUISpecRegistry(),r=this.config.renderer?.unknownRenderer??ta,i=(s,c)=>tn(s,c,n,r),o=this.config.renderer?.renderUISpec;return o?o(t,a,{registry:n,unknownRenderer:r,defaultRender:i}):i(t,a)}};function xu(){return new Tr}Ee.CHAT_SCROLL_ELEMENT_ID=vt,Ee.ChatPresentationState=bn,Ee.GengageChat=Tr,Ee.chatCatalog=_u,Ee.createChatWidget=xu,Ee.createDefaultChatUISpecRegistry=en,Ee.defaultChatUnknownUISpecRenderer=ta,Ee.getChatScrollElement=Io,Ee.invalidateChatScrollCache=Da,Ee.renderUISpec=tn})(this.Gengage=this.Gengage||{});
package/dist/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as e, c as t, d as r, f as s, n, o as C, p as c, r as h, s as l, t as o } from "./chat-DBJ8ZWch.js";
1
+ import { a as e, c as t, d as r, f as s, n, o as C, p as c, r as h, s as l, t as o } from "./chat-q65kDKeT.js";
2
2
  export {
3
3
  r as CHAT_SCROLL_ELEMENT_ID,
4
4
  e as ChatPresentationState,
@@ -1,5 +1,5 @@
1
1
  import { f as u } from "./schemas-CTbgsvNJ.js";
2
- import { h, l as f } from "./native-webview-111Or6o1.js";
2
+ import { h, l as f } from "./native-webview-5TioIwea.js";
3
3
  var m = {
4
4
  enabled: !0,
5
5
  endpoint: "/analytics",
package/dist/common.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { C as a, S as t, b as s, d as r, f as n, g as i, h as o, m as c, p as m, v as l, w as g, x as d, y as u } from "./schemas-CTbgsvNJ.js";
2
2
  import { $ as E, A as S, D as h, E as v, F as y, G as C, H as f, I as A, J as T, K as w, L as U, M as W, N as I, O as P, P as D, Q as k, S as R, T as b, U as G, V as O, W as N, X as x, Y as L, Z as M, et as _, j as H, k as z, q as B, v as F, w as K, x as V, y as Q } from "./ga-datalayer-BwxWX-cr.js";
3
- import { i as Z, l as j, m as J, u as X } from "./chat-DBJ8ZWch.js";
3
+ import { i as Z, l as j, m as J, u as X } from "./chat-q65kDKeT.js";
4
4
  import { n as $, t as ee } from "./connection-warning-CHHi3BAf.js";
5
- import { a as te, c as se, d as re, f as ne, h as ie, i as oe, l as ce, m as me, n as le, o as ge, p as de, r as ue, s as pe, u as Ee } from "./native-webview-111Or6o1.js";
6
- import { a as he, c as ve, d as ye, f as Ce, i as fe, l as Ae, n as Te, o as we, p as Ue, r as We, s as Ie, t as Pe, u as De } from "./common-BJZB1LIH.js";
5
+ import { a as te, c as se, d as re, f as ne, h as ie, i as oe, l as ce, m as me, n as le, o as ge, p as de, r as ue, s as pe, u as Ee } from "./native-webview-5TioIwea.js";
6
+ import { a as he, c as ve, d as ye, f as Ce, i as fe, l as Ae, n as Te, o as we, p as Ue, r as We, s as Ie, t as Pe, u as De } from "./common-uTYBcG11.js";
7
7
  export {
8
8
  Ee as AccountRuntimeConfigSchema,
9
9
  re as AnalyticsAuthModeSchema,
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { C as a, b as t, d as s, f as i, w as n, x as r } from "./schemas-CTbgsvNJ.js";
2
2
  import { A as c, D as m, E as l, F as d, I as g, L as p, N as u, O as S, P as f, k as C, v as U } from "./ga-datalayer-BwxWX-cr.js";
3
- import { c as A, i as I, l as y, m as R, n as D, o as E, s as T, t as W, u as w } from "./chat-DBJ8ZWch.js";
3
+ import { c as A, i as I, l as y, m as R, n as D, o as E, s as T, t as W, u as w } from "./chat-q65kDKeT.js";
4
4
  import { t as N } from "./connection-warning-CHHi3BAf.js";
5
5
  import { a as P, i as k, n as G, o as L, t as Q } from "./qna-DXCQtwLq.js";
6
6
  import { a as b, i as x, n as B, o as F, t as M } from "./simrel-DP2EMyua.js";
7
7
  import { n as H, t as K } from "./simbut-BBXTlzOg.js";
8
- import { a as Z, c as j, d as q, f as J, h as X, i as Y, l as $, m as ee, n as ae, o as te, p as se, r as ie, s as ne, u as re } from "./native-webview-111Or6o1.js";
9
- import { a as ce, c as me, d as le, i as de, l as ge, n as pe, o as ue, p as Se, r as fe, s as Ce, t as Ue, u as he } from "./common-BJZB1LIH.js";
8
+ import { a as Z, c as j, d as q, f as J, h as X, i as Y, l as $, m as ee, n as ae, o as te, p as se, r as ie, s as ne, u as re } from "./native-webview-5TioIwea.js";
9
+ import { a as ce, c as me, d as le, i as de, l as ge, n as pe, o as ue, p as Se, r as fe, s as Ce, t as Ue, u as he } from "./common-uTYBcG11.js";
10
10
  export {
11
11
  re as AccountRuntimeConfigSchema,
12
12
  q as AnalyticsAuthModeSchema,
@@ -1,6 +1,6 @@
1
1
  import { a as M, c as h, i as D, o as f, r as m, t as x } from "./schemas-CTbgsvNJ.js";
2
2
  import { I as H, M as Q, b as k, z as K } from "./ga-datalayer-BwxWX-cr.js";
3
- import { t as V } from "./chat-DBJ8ZWch.js";
3
+ import { t as V } from "./chat-q65kDKeT.js";
4
4
  import { t as j } from "./qna-DXCQtwLq.js";
5
5
  import { t as $ } from "./simrel-DP2EMyua.js";
6
6
  import { t as G } from "./simbut-BBXTlzOg.js";