@magicx-eng/ai-autocomplete-vanilla 0.53.0 → 0.53.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- function T(t){return t==="date"||t==="date-range"}function B(t){return t?.type?.kind==="date"?"date":t?.type?.kind==="date_range"?"date-range":"options"}var Ae=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var Vi="https://api.ai-autocomplete.com",q=`${Vi}/api/suggest`,ke=new Map([["api.ai-autocomplete.com","cdn.ai-autocomplete.com"],["dev-api.ai-autocomplete.com","dev-cdn.ai-autocomplete.com"]]),Gn=new WeakMap;function fe(t){return t?.type==="accessToken"}function qi(t){if(!(!t||fe(t)))return t}function Le(t){let e=Gn.get(t.getAccessToken);return e||(e=new Ae(t),Gn.set(t.getAccessToken,e)),e}function Re(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function Me(t){let e=qi(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function he(t){return t.map(e=>({parameter:e.parameter,text:e.text}))}var Vn="skipped";function be(t,e){if(e.length===0)return t;let n=new Set(t.map(i=>i.parameter)),r=e.filter(i=>!n.has(i.parameter)).map(i=>({placeholder:"",parameter:i.parameter,text:Vn,kind:null}));return r.length>0?[...t,...r]:t}var Ki="0.53.0",zn="1.0",qn=!1;function zi(t,e){return{placeholder:t.placeholder,parameter:t.parameter,...e&&{text:t.value??t.text},kind:t.kind}}function te(t){return t??(typeof navigator<"u"?navigator.language:"en-US")}function ji(t,e,n,r,i,s,o,a,l,u,d,c){let f=e.find(g=>g.parameter==="contact"&&g.metadata?.contact_account_count)?.metadata?.contact_account_count,p=typeof f=="number"?f:void 0;return{data:{raw_query:t,accepts_traditional_autocomplete:!0,completed_params:be(e.map(g=>zi(g,n)),l??[]),...o&&o.length>0&&{identified_params:he(o)},...a&&a.length>0&&{recently_suggested:a},...p!=null&&{contact_account_count:p},...u!==void 0&&{additional_context:u}},meta:{request_id:i,request_at:new Date().toISOString(),language:te(d),...c?.code&&Number.isFinite(c.rate)&&c.rate>0&&{currency:c.code,currency_rate:c.rate,...c.country!==void 0&&{country:c.country}},client_version:Ki,session_id:r,source:s,schema_version:zn}}}async function Kn(t,e,n,r,i){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:r,signal:i})}async function jn(t,e,n){let r=n.apiConfig,i=!n.maskCompletedText,s=ji(t,e,i,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext,n.language,n.currency),o=Re(r),a=r?.endpoint??q,l=JSON.stringify(s);if(fe(r)){let c=Le(r),f=await c.getToken(),p=await Kn(a,o,f,l,n.signal);if(p.status===401){let g=await c.getToken(!0);p=await Kn(a,o,g,l,n.signal)}if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}let u=Me(r);!u&&!qn&&(qn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),u&&(o.Authorization=u);let d=await fetch(a,{method:"POST",headers:o,body:l,signal:n.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}var De=/[\p{L}\p{N}]/u,Yi=/['\u2019-]/;function Yn(t,e,n){let r=t[e];if(r===void 0)return!1;if(De.test(r))return!0;let i=t[e+n];return Yi.test(r)&&i!==void 0&&De.test(i)}function Qi(t,e,n){let r=e+n.length;return!(De.test(n[0])&&Yn(t,e-1,-1)||De.test(n[n.length-1])&&Yn(t,r,1))}function U(t,e,n=0,r=()=>!0){if(e.length===0)return t.indexOf(e,n);let i=-1,s=t.indexOf(e,n);for(;s!==-1;){if(r(s)){if(Qi(t,s,e))return s;i===-1&&(i=s)}s=t.indexOf(e,s+1)}return i}function D(t,e){let n=t,r={},i=[],s=[],o=0;for(let a of e){let l=(r[a.parameter]??0)+1;r[a.parameter]=l;let d=`{{${a.parameter.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,c=p=>U(n,a.text,p,g=>!s.some(S=>g<S.end&&g+a.text.length>S.start)),f=c(o);if(f===-1&&(f=c(0)),f!==-1){n=n.slice(0,f)+d+n.slice(f+a.text.length);let p=d.length-a.text.length;for(let g of s)g.start>=f+a.text.length&&(g.start+=p,g.end+=p);s.push({start:f,end:f+d.length}),o=f>=o?f+d.length:o+p}i.push({...a,placeholder:d})}return{rawQuery:n,completedParams:i}}function K(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function Ne(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function Se(t,e,n){let r=t.slice(e);if(n||e===0||t[e-1]===" ")return r;let i=r.indexOf(" ");return i===-1?"":r.slice(i+1)}function Qn(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let r=n.split(" "),i=e.toLowerCase();for(let s=0;s<r.length;s++){let o=r.slice(s).join(" ");if(i.startsWith(o.toLowerCase())){let a=n.length-o.length;return t.length-a}}return 0}function Xn(t){return t.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase().replace(/[_\-\s]+/g," ")}function Xi(t,e){let n=Xn(t).trim();return n.startsWith(e)||n.includes(` ${e}`)}function ne(t,e,n=!1){if(!t)return[];let r=e.trimStart();if(!r)return t;let i=n?Xn(r).trimStart():"";if(i)return t.filter(o=>!o.is_tappable||Xi(o.text,i));let s=r.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(s))}function _e(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let r=n.toLowerCase();return t.find(i=>i.is_tappable&&i.text.toLowerCase()===r)??null}function ye(t,e,n,r,i){let s=Se(e,n,r),o=_e(t,s);if(o||!i||!s.trim())return o;if(s===e.slice(n))return null;let a=e.lastIndexOf(" ",n-1)+1;return _e(t,e.slice(a))}function Jn(t,e){return e?t.map(n=>e[n.parameter]?{...n,options:[]}:n):t}function Ji(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function $(t){let e=Ji(t);return e.length>0?e.join(" "):t}function z(t,e){return t.parameter||e}function wt(t){return{parameter:t,suggestionParameter:t,suggestionValueType:{kind:"traditional_autocomplete"},suggestionPlaceholder:$(t)}}function He(t,e){let n=z(e,t.suggestionParameter);return t.suggestionValueType?.kind==="traditional_autocomplete"?wt(n):{parameter:n,suggestionParameter:t.suggestionParameter,suggestionValueType:t.suggestionValueType,suggestionPlaceholder:t.suggestionPlaceholder}}function E(t){return t?.type?.kind==="traditional_autocomplete"}function Zn(t){let e=t?.replace(/[_\-\s]+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):void 0}function Fe(t){return E(t)||t?.smart_suggestion===!0}function It(t){return t.some(E)?t.filter(e=>!E(e)):t}function Ct(t,e){return t.some(n=>E(n)&&!n.text)?t.map(n=>E(n)&&!n.text?{...n,text:e}:n):t}var Ot='<svg viewBox="0 0 20 20" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false"><path class="aia-sparkle-large" d="M8 5C8.5 9.5 10.5 11.5 15 12C10.5 12.5 8.5 14.5 8 19C7.5 14.5 5.5 12.5 1 12C5.5 11.5 7.5 9.5 8 5Z"/><path class="aia-sparkle-small" d="M16 1C16.2 3 17 3.8 19 4C17 4.2 16.2 5 16 7C15.8 5 15 4.2 13 4C15 3.8 15.8 3 16 1Z"/></svg>';function At(t){return t.some(e=>!E(e))}function er(t,e){let n=0,r=e;for(let i of t)n+=i.value.length,i.type!=="text"&&(r=Math.max(r,n));return r}function tr(t,e){let n=0;for(let r of t){let i=n+r.value.length;if(r.type==="text"&&i>e&&r.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=i}return!0}function nr(t,e){let n=[],r=new Set;for(let i of[...t,...e])i.parameter==="placeholder"||E(i)||r.has(i.parameter)||(r.add(i.parameter),n.push({parameter:i.parameter,text:i.text}));return n}function rr(t,e,n){if(t===e)return n;let r=Math.min(t.length,e.length),i=0;for(;i<r&&t[i]===e[i];)i++;if(i>=n)return n;let s=0;for(;s<r-i&&t[t.length-1-s]===e[e.length-1-s];)s++;return t.length-s<=n?n+(e.length-t.length):null}function We(t,e){let n=[],r=[],i=0;for(let s of e){let o=U(t,s.text,i);if(o===-1){r.push(s);continue}n.push({start:o,end:o+s.text.length,param:s}),i=o+s.text.length}return{located:n,missing:r}}function Be(t,e){let{located:n}=We(t,e);return n.length>0?n[n.length-1].end:0}function ir(t,e,n){let r=[],i=[],s=0;for(let o of n){let a=U(t,o.text,s,l=>!e.some(u=>l<u.end&&l+o.text.length>u.start));if(a===-1){i.push(o);continue}r.push({start:a,end:a+o.text.length,param:o}),s=a+o.text.length}return{located:r,missing:i}}function or(t,e,n=[]){let r=We(t,e).located,i=ir(t,r,n).located,s=[...r.map(u=>({start:u.start,end:u.end,segment:{type:"completed",value:u.param.text,param:u.param}})),...i.map(u=>({start:u.start,end:u.end,segment:{type:"identified",value:u.param.text,param:u.param}}))].sort((u,d)=>u.start-d.start),o=[],a=0;for(let u of s)u.start>a&&o.push({type:"text",value:t.slice(a,u.start)}),o.push(u.segment),a=u.end;let l=t.slice(a);return l&&o.push({type:"text",value:l}),o}function sr(t,e){let{located:n,missing:r}=We(t,e);return{valid:n.map(i=>i.param),invalid:r}}function xe(t,e,n){let r=We(t,e).located,{located:i,missing:s}=ir(t,r,n);return{valid:i.map(o=>o.param),invalid:s}}function ar(t,e,n){let r=e?.endpoint??q,i=r.replace(/\/suggest(?=[?#]|$)/,`/starting-state/${encodeURIComponent(t)}${Zi(n)}`);if(i!==r)return i.replace(/^https:\/\/([^/?#]+)/,(s,o)=>{let a=ke.get(o);return a?`https://${a}`:s})}function Zi(t){let e=t?.replace(/_/g,"-").toLowerCase()??"",[n,r=""]=e.split("-");return n!=="zh"?/^[a-z]{2,3}$/.test(n)?`/${n}`:"":/^[a-z]{4}$/.test(r)?r==="hant"?"/zh-TW":"/zh":["tw","hk","mo"].includes(r)?"/zh-TW":"/zh"}async function lr(t){try{let e=await t;if(!e.ok)return null;let n=await e.json();return Array.isArray(n?.data?.suggestions)?n:null}catch{return null}}function eo(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var to=100,no=300,ro=2,Ue=class{constructor(e,n,r,i,s,o,a,l,u,d={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=r;this.getMaskCompletedText=i;this.getOnError=s;this.getSessionId=o;this.getSource=a;this.getAdditionalContext=l;this.getLanguage=u;this.callbacks=d;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null;this.phraseExactMatch=!1}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(r=>{(r.text!==e||r.completedParams!==n)&&(e=r.text,n=r.completedParams,this.scheduleFetch())})}isPhraseExactMatch(){return this.phraseExactMatch}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){this.abortController?.abort();let r=new AbortController;this.abortController=r;let i=++this.fetchVersion,s=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:r.signal,isCurrent:()=>i===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let o=this.store.get(),a=o.pendingSpan?nr(o.pendingSpan.snapshot,o.actionableSuggestions):void 0,l=crypto.randomUUID(),u=e===""&&n.length===0&&o.skippedParams.length===0&&o.identifiedParams.length===0?this.startingStateUrl():void 0,d=u?await lr(fetch(u,{signal:r.signal})):null;if(i!==this.fetchVersion)return;let c=d??await jn(e,n,{sessionId:this.getSessionId(),requestId:l,source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:r.signal,apiConfig:this.getApiConfig(),identifiedParams:o.identifiedParams,recentlySuggested:a,skippedParams:o.skippedParams,additionalContext:this.getAdditionalContext(),language:this.getLanguage(),currency:this.callbacks.getCurrency?.()});if(i!==this.fetchVersion)return;this.phraseExactMatch=c.meta?.phrase_exact_match===!0;let f=(c.data.suggestions??[]).find(E),p=f?[]:c.data.input??[],g=p.filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),parameter:v.parameter,text:v.text,...v.type?{type:v.type}:{}})),S=this.callbacks.isWordOpen?.()??!1,x=this.store.get().text.toLowerCase(),b=v=>S&&x.endsWith(v.text.toLowerCase()),m=g.filter(v=>!b(v));S&&this.callbacks.holdIdentified?.(g.filter(b));let h=f?[f]:Jn(c.data.suggestions??[],this.getOptionOverrides()),y=p,I=y[y.length-1],P=this.store.get().text,O,R;if(I?.state==="in_progress"){R=!0;let v=P.toLowerCase().lastIndexOf(I.text.toLowerCase());O=v!==-1?v:s}else R=!1,O=s;let A=h.filter(v=>v.parameter!=="placeholder")[0],L=null;if(A&&!E(A)&&!S&&!T(B(A))){let v=ye(A.options,P,O,R,this.phraseExactMatch);v&&(L={id:crypto.randomUUID(),placeholder:"",parameter:z(v,A.parameter),text:v.text,value:v.value,kind:v.kind,suggestionParameter:A.parameter,suggestionValueType:A.type,suggestionPlaceholder:A.text,options:A.options??[],metadata:v.metadata,icon:v.icon,icon_svg:v.icon_svg,image_url:v.image_url},h=h.filter(H=>H!==A),this.callbacks.onAutoMatch?.({active:A,matched:v,rawQuery:e}))}let V=c.data.custom_fields??null,Z=this.callbacks.productsForResponse?.(V);this.store.set(v=>{let H=L?[...v.completedParams,L]:v.completedParams,Tt=xe(v.text,H,m).valid,Et=new Set(o.skippedParams.map(M=>M.id)),w=new Set(v.skippedParams.filter(M=>!Et.has(M.id)).map(M=>M.parameter));return{suggestions:w.size>0?h.filter(M=>M.parameter==="placeholder"||!w.has(M.parameter)):h,isLoading:!1,isReady:c.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:O,filterInProgress:R,identifiedParams:Tt,customFields:V,traditionalAutocomplete:c.meta?.traditional_autocomplete===!0,...Z!==void 0?{products:Z}:{},...L?{completedParams:H}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:c.meta?.funnel_telemetry===!0,visibleImpression:c.meta?.visible_impression===!0})}catch(o){let a=eo(o);i===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(i===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}startingStateUrl(){let e=this.callbacks.getProductId?.();return e?ar(e,this.getApiConfig(),te(this.getLanguage())):void 0}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(ro)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},to),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1,!0,!0),no)}attemptFetch(e,n=!1,r=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let s=this.callbacks.consumerTick?.(i,e)??"no";if(s==="asked")return!0;if(s==="owns")return!1;let o=i.suggestions.filter(P=>P.parameter==="placeholder").map(P=>P.text).join(" "),a=K(i.text,i.filterBase,o),l=Se(i.text,a,i.filterInProgress),u=i.suggestions.filter(P=>P.parameter!=="placeholder"),d=E(u[0])?void 0:u[0],c=T(i.activeFormatType),p=(d&&!c?ne(d.options,l,i.traditionalAutocomplete):[]).filter(P=>P.is_tappable),g=d&&!c&&!this.callbacks.isWordOpen?.()?ye(d.options,i.text,a,i.filterInProgress,this.phraseExactMatch)!==null:!1,S=l.trim().length>0,x=r&&i.products.length>0;if(p.length>0&&!g&&S&&!x||Ne(i.text,i.completedParams.length,o))return!1;let{rawQuery:b,completedParams:m}=D(i.text,i.completedParams),h=b.length<i.lastRawQuery.length,y=Math.abs(b.length-i.lastRawQuery.length),I=n&&b!==i.lastRawQuery;return h||y>=e||I?(this.doFetch(b,m),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var io="(hover: none) and (pointer: coarse)";var oo="[data-aia-dropdown], [data-aia-input-wrapper]",so=["a[href]","button","input","select","textarea","label","summary","[contenteditable]:not([contenteditable='false'])","[role='button']","[role='link']","[tabindex]:not([tabindex='-1'])"].join(", "),$e=class{constructor(e,n){this.store=e;this.container=n;this.listening=!1;this.declined=!1;this.pressOutside=!1;this.pressWhileFocused=!1;this.recheckTimer=null;this.releaseTimer=null;this.onPointerDown=e=>{let n=e.composedPath(),r=this.isInside(n);this.pressOutside=!r;let i=this.store.get();this.pressWhileFocused=i.isFocused,!(r||!i.isFocused)&&(this.declined=n.some(s=>s instanceof Element&&s.matches(so)),this.declined&&i.dropdownHeld?this.store.set({dropdownHeld:!1}):!this.declined&&!i.dropdownHeld&&i.isDropdownOpen&&this.store.set({dropdownHeld:!0}))};this.onPointerCancel=()=>{this.pressOutside=!1,this.pressWhileFocused&&this.declined&&this.scheduleRecheck(),this.pressWhileFocused=!1};this.onPointerUp=e=>{let n=this.pressOutside&&!this.isInside(e.composedPath()),r=this.pressWhileFocused;if(this.pressOutside=!1,this.pressWhileFocused=!1,r){this.declined&&this.scheduleRecheck();return}!n||this.store.get().isFocused||(this.cancelRelease(),this.releaseTimer=setTimeout(()=>{this.releaseTimer=null;let i=this.store.get();i.dropdownHeld&&!i.isFocused&&this.store.set({dropdownHeld:!1})},150))};this.touchPrimary=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(io):null,this.unsubscribe=e.subscribe(()=>this.sync())}dispose(){this.unsubscribe(),this.listen(!1),this.cancelRelease(),this.recheckTimer!==null&&clearTimeout(this.recheckTimer),this.recheckTimer=null}sync(){let e=this.store.get(),n=this.touchPrimary?.matches??!1;e.isFocused||(this.declined=!1),e.isDropdownOpen?e.isFocused&&!e.dropdownHeld&&!this.declined&&n&&this.store.set({dropdownHeld:!0}):e.dropdownHeld&&this.store.set({dropdownHeld:!1});let r=this.store.get();this.listen(n&&r.isDropdownOpen),r.isFocused&&this.cancelRelease()}listen(e){if(!(e===this.listening||typeof document>"u")){if(this.listening=e,e){document.addEventListener("pointerdown",this.onPointerDown,!0),document.addEventListener("pointerup",this.onPointerUp,!0),document.addEventListener("pointercancel",this.onPointerCancel,!0);return}document.removeEventListener("pointerdown",this.onPointerDown,!0),document.removeEventListener("pointerup",this.onPointerUp,!0),document.removeEventListener("pointercancel",this.onPointerCancel,!0),this.pressOutside=!1}}scheduleRecheck(){this.recheckTimer!==null&&clearTimeout(this.recheckTimer),this.recheckTimer=setTimeout(()=>{this.recheckTimer=null,!(!this.declined||!this.store.get().isFocused)&&(this.declined=!1,this.sync())},150)}cancelRelease(){this.releaseTimer!==null&&(clearTimeout(this.releaseTimer),this.releaseTimer=null)}isInside(e){let n=this.container,r=n?.getRootNode(),i=typeof ShadowRoot<"u"&&r instanceof ShadowRoot?r.host:null;for(let s of e)if(s===n||s===i||s instanceof Element&&s.matches(oo))return!0;return!1}};var le=["January","February","March","April","May","June","July","August","September","October","November","December"],Ge=["S","M","T","W","T","F","S"],ur=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pr="aiaDate",mr="aiaDay",cr=t=>String(t).padStart(2,"0");function F(t){return`${t.getFullYear()}-${cr(t.getMonth()+1)}-${cr(t.getDate())}`}function kt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function ao(t){let e=kt(t).getTime()-kt(new Date).getTime();return Math.round(e/864e5)}function gr(t){let e=ao(t);return e>=0&&e<7?ur[t.getDay()]:ce(t)}function ce(t){return t.getFullYear()===new Date().getFullYear()?`${le[t.getMonth()]} ${t.getDate()}`:`${le[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function Ve(t){if(!t)return null;let e=ur.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=kt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let r=le.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(r<0)return null;let i=Number(n[2]),s=n[3]?Number(n[3]):new Date().getFullYear(),o=new Date(s,r,i);return o.getMonth()!==r||o.getDate()!==i?null:o}function Lt(t){return`${le[t.month]} ${t.year}`}function Rt(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function fr(t){return{year:t.getFullYear(),month:t.getMonth()}}function Mt(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function dr(){return{text:"",is_tappable:!1,kind:null}}function Dt(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),r=[];for(let i=0;i<e;i++)r.push(dr());for(let i=1;i<=n;i++){let s=new Date(t.year,t.month,i);r.push({text:gr(s),is_tappable:!0,kind:null,metadata:{[pr]:F(s),[mr]:i}})}for(;r.length%Ge.length!==0;)r.push(dr());return r}function _t(t){let e=Ve(t);return e?F(e):null}function G(t){let e=t?.metadata?.[pr];return typeof e=="string"?e:null}function Nt(t){let e=t?.metadata?.[mr];return typeof e=="number"?e:null}function lo(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function re(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&lo(e)?e:t.ownerDocument??t}function _(t){return t.ownerDocument??t}function co(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function hr(t){let e=re(t);return!co(e)||typeof e.getSelection=="function"?null:e}function br(t){let e=hr(t);if(!e)return null;let n=_(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function Sr(t,e){let n=t,r;try{r=n.getComposedRanges({shadowRoots:[e]})}catch{r=n.getComposedRanges(e)}return r.length>0?r[0]:null}function Ht(t){let n=re(t).getSelection?.();return n||(_(t).getSelection?.()??null)}function j(t){let e=Ht(t);if(!e||e.rangeCount===0)return null;let n=br(t);if(n){let r=Sr(e,n);return r?{node:r.startContainer,offset:r.startOffset,collapsed:r.startContainer===r.endContainer&&r.startOffset===r.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function qe(t){let e=Ht(t);if(!e||e.rangeCount===0)return null;let n=br(t);if(!n)return e.getRangeAt(0);let r=Sr(e,n);if(!r)return null;let i=_(t).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function ve(t,e,n){let r=Ht(t);if(!r)return null;if(hr(t))return r.collapse(e,n),r;let i=_(t).createRange();return i.setStart(e,n),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function Ke(t,e){let n=t?re(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var ze=2,uo="magicx-aia";function yr(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function po(t){let e=_(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let r=t;for(;r&&r!==e.body&&r!==e.documentElement;){let i=r.scrollWidth>r.clientWidth,s=r.scrollHeight>r.clientHeight;if(i||s){let o=n.getComputedStyle(r);if(i&&yr(o.overflowX)||s&&yr(o.overflowY))return r}if(r.classList.contains(uo))return null;r=r.parentElement}return null}function Ft(t){let e=qe(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=po(t);if(!n||typeof e.getBoundingClientRect!="function")return;let r=e.getBoundingClientRect();if(r.height===0)return;let i=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let s=i.left+n.clientLeft,o=s+n.clientWidth;r.right>o?n.scrollLeft+=r.right-o+ze:r.left<s&&(n.scrollLeft-=s-r.left+ze)}if(n.scrollHeight>n.clientHeight){let s=i.top+n.clientTop,o=s+n.clientHeight;r.bottom>o?n.scrollTop+=r.bottom-o+ze:r.top<s&&(n.scrollTop-=s-r.top+ze)}}var vr='[contenteditable="false"]',Bt="strong[data-param-id]",de;function mo(){if(de!==void 0)return de;let t=globalThis.Intl.Segmenter;if(!t)return de=null,null;try{de=new t(void 0,{granularity:"grapheme"})}catch{de=null}return de??null}function je(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(vr))return!0;n=n.parentNode}return!1}function Ye(t){return _(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return je(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Qe(t){let e=Ye(t),n="",r=e.nextNode();for(;r;)n+=r.data,r=e.nextNode();return n}function Ut(t){let e=Ye(t),n=0,r=e.nextNode();for(;r;)n+=r.data.length,r=e.nextNode();return n}function W(t){let e=j(t);if(!e)return null;let n=e.node,r=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let i=n;if(je(i,t)&&i!==t)return null;let s=0;for(let o=0;o<r&&o<i.childNodes.length;o++)s+=$t(i.childNodes[o],t);return s+Wt(i,t)}return n.nodeType!==Node.TEXT_NODE||je(n,t)?null:Wt(n,t)+r}function $t(t,e){if(t.nodeType===Node.TEXT_NODE)return je(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(vr))return 0;let r=0;for(let i of Array.from(n.childNodes))r+=$t(i,e);return r}function Wt(t,e){let n=Ye(e),r=0,i=n.nextNode();for(;i;){if(i===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(i))return r;r+=i.data.length,i=n.nextNode()}return r}function N(t,e){let n=_(t),r=Math.max(0,Math.min(e,Ut(t))),i=Ye(t),s=0,o=null,a=0,l=i.nextNode(),u=null;for(;l;){let c=l.data.length;if(r<s+c){o=l,a=r-s;break}if(r===s+c){let f=i.nextNode();f?(o=f,a=0):(o=l,a=c);break}s+=c,u=l,l=i.nextNode()}let d=n.createRange();if(o){let c=o.parentElement?.closest('strong[data-seg="completed"]');c&&c!==t&&t.contains(c)?a===0?d.setStartBefore(c):a===o.data.length?d.setStartAfter(c):d.setStart(o,a):d.setStart(o,a)}else u?d.setStart(u,u.data.length):d.setStart(t,0);d.collapse(!0),ve(t,d.startContainer,d.startOffset)&&(go(t,d,r),Ft(t))}function xr(t,e){if(!t||!e.contains(t))return null;let r=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(Bt)??null;return r&&e.contains(r)?r:null}function go(t,e,n){let r=xr(j(t)?.node??null,t);if(r&&r!==xr(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${r.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function Pr(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let r=W(t);return r!==null&&n===`${r}:${e}`}function Tr(t){return re(t).activeElement===t}function Gt(t,e){if(!e||e.nodeType===void 0)return null;let n=e,i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Bt);if(!i||!t.contains(i))return null;let s=j(t);return s&&!s.collapsed?null:i.dataset.paramId??null}function Vt(t,e){let n=null;for(let o of t.querySelectorAll(Bt))if(o.dataset.paramId===e){n=o;break}if(!n)return;let r=Wt(n,t),i=r+$t(n,t),s=W(t);s!=null&&s>=r&&s<=i||N(t,r)}function qt(t){let e=W(t);return e==null?!1:e>=Ut(t)}function Kt(t,e){if(e<=0)return 0;let n=mo();if(!n)return e-1;let r=t.slice(0,e),i=0;for(let{index:s}of n.segment(r))s<e&&(i=s);return i}function ie(t,e,n=[],r={}){let{rawQuery:i,completedParams:s}=D(t,e);return{query:t.trim(),raw_query:i,completed_params:be(s,n),identified_params:he(r.identifiedParams??[]),is_ready:r.isReady??!1,...r.customFields?{custom_fields:r.customFields}:{}}}function zt(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?qt(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function jt(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?W(t):null}var Xe=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){if(e.isComposing||e.keyCode===229)return;let n=this.store.get(),{listboxId:r,getOnSubmit:i}=this.ctx,s=e.target instanceof Node?e.target:null,o=this.getEffectiveColumns(s),a=i(),l=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let u=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=zt(e.target,n),c=!!n.editingParam;if(!d&&!c&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(u)break;e.preventDefault();let g=T(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(l.length===0)return;this.store.set({activeDropdownIndex:g});break}if(e.preventDefault(),l.length===0)return;if(T(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let g=Math.floor((n.filteredOptions.length-1)/o);if(Math.floor(n.activeDropdownIndex/o)===g){this.store.set({activeDropdownIndex:-1});break}}let f=l.indexOf(n.activeDropdownIndex),p=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[p]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!u)break;let f=zt(e.target,n),p=!!n.editingParam;if(!f&&!p)break;e.preventDefault();let g=T(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(o)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:g});break}if(l.length===0)return;this.store.set({activeDropdownIndex:g});break}if(l.length===0)break;if(e.preventDefault(),T(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(n.activeDropdownIndex),c=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[c]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),T(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%o<o-1){let f=n.activeDropdownIndex+1;f<n.filteredOptions.length&&n.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,f=n.editingTail;this.ctx.exitEditMode?.(),N(c,f);break}zt(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),T(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%o>0){let d=n.activeDropdownIndex-1;d>=0&&n.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let d=jt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,c=n.editingAnchor;this.ctx.exitEditMode?.(),N(d,c);break}if(this.ctx.startEditingParamAtCaret){let d=jt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let d=jt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable)this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,r,s);else if(a){this.ctx.endTypedWord?.();let d=this.store.get();a(ie(d.text,d.completedParams,d.skippedParams,{identifiedParams:d.identifiedParams,isReady:d.isReady,customFields:d.customFields}))&&this.ctx.afterSubmit?.()}break}case"Tab":{if(this.ctx.endTypedWord?.()){e.preventDefault();break}let d=n.filteredOptions.map((p,g)=>p.is_tappable?g:-1).filter(p=>p!==-1);if(d.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let p=e.shiftKey?d[d.length-1]:d[0];this.store.set({pillTapped:!0,activeDropdownIndex:p});break}e.preventDefault();let c=d.indexOf(n.activeDropdownIndex),f;if(c<0)f=e.shiftKey?d.length-1:0;else{let p=e.shiftKey?-1:1;f=(c+p+d.length)%d.length}this.store.set({activeDropdownIndex:d[f]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,c=n.editingTail;this.ctx.exitEditMode?.(),N(d,c)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let i=Math.floor((n.filteredOptions.length-1)/e)*e;for(let s=i;s<n.filteredOptions.length;s++)if(n.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,n){let r=F(new Date),i=e.filteredOptions.findIndex(o=>G(o)===r);if(i>=0)return i;let s=e.filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1);return(n?s[s.length-1]:s[0])??0}stepDateDay(e,n){for(let r=e.activeDropdownIndex+n;r>=0&&r<e.filteredOptions.length;r+=n)if(e.filteredOptions[r]?.is_tappable){this.store.set({activeDropdownIndex:r});return}}stepDateWeek(e,n){let r=e.activeDropdownIndex+n;this.store.set({activeDropdownIndex:e.filteredOptions[r]?.is_tappable?r:-1})}getTappableIndices(e){let r=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),i=Array.from({length:e},()=>[]);for(let s of r)i[s%e].push(s);return i.flat()}getEffectiveColumns(e){let n=Ke(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let i=Ke(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let s=getComputedStyle(i).gridTemplateColumns;if(s&&s!=="none"){let o=s.split(" ").filter(Boolean).length;if(o>0)return o}if(i===n)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,n,r,i){let s=Ke(i,`${r}-option-${e}`);s?s.click():this.ctx.selectOption(n[e])}};var Je=class{constructor(e,n,r={}){this.store=e;this.getOverrides=n;this.callbacks=r;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){let r=this.resolveTarget(e);if(!r||this.missCovers(r.parameter,r.query))return"no";let i=this.current;if(i&&i.key===r.key){if(i.query===r.query)return"owns";let s=Math.abs(r.query.length-i.query.length),o=r.query.length<i.query.length;if(n>1&&!o&&s<n)return"owns"}return this.ask(r),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(T(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionParameter)?{mode:"edit",key:n.id,parameter:n.suggestionParameter,suggestion:{parameter:n.suggestionParameter,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let r=e.actionableSuggestions[0];return!r||!this.hasOverride(r.parameter)?null:{mode:"pill",key:r,parameter:r.parameter,suggestion:r,query:e.optionQuery}}missCovers(e,n){return this.lastMiss!=null&&this.lastMiss.parameter===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.parameter],r=++this.version;if(!n||this.missCovers(e.parameter,e.query)){this.current={key:e.key,parameter:e.parameter,query:e.query,abort:null},this.setSearch(e,"done");return}let i=new AbortController;this.current={key:e.key,parameter:e.parameter,query:e.query,abort:i};let s;try{s=n(e.query,i.signal,e.suggestion)}catch(o){this.logOnce(o),this.commit(e,[],r);return}if(Array.isArray(s)){this.commit(e,s,r);return}this.setSearch(e,"loading"),this.await(e,s,i.signal,r)}async await(e,n,r,i){let s;try{let o=await n;if(r.aborted||i!==this.version)return;s=Array.isArray(o)?o:[]}catch(o){if(r.aborted||i!==this.version||fo(o))return;this.logOnce(o),s=[]}this.commit(e,s,i)}commit(e,n,r){if(r!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;n.length===0?this.lastMiss={parameter:e.parameter,query:e.query}:this.lastMiss?.parameter===e.parameter&&(this.lastMiss=null);let s={parameter:e.parameter,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(o=>({editingParam:o.editingParam&&o.editingParam.id===e.key?{...o.editingParam,options:n}:o.editingParam,optionSearch:s}));else{let o={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=o),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?o:l),optionSearch:s}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let r=this.store.get().optionSearch;r&&r.parameter===e.parameter&&r.query===e.query&&r.status===n||this.store.set({optionSearch:{parameter:e.parameter,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function fo(t){return t instanceof Error&&t.name==="AbortError"}var Ze=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),r=n.suggestions.filter(u=>u.parameter!=="placeholder");if(e<0||e>=r.length)return;let i=r[e];if(E(i))return;let s=r.filter((u,d)=>d!==e),o=n.suggestions.filter(u=>u.parameter==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:u}=D(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:u,selectedPill:i.text,otherPills:s.map(d=>d.text)})}let a=[...o,i,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(u=>u.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var wr="/products/",Er="https://relative.invalid";function ho(t){if(!t)return;let e;try{e=new URL(t,`${Er}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===Er?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function Ir(t,e){let n=ho(t.item_url)??So(t);return{id:t.source_id,title:t.title,...n&&{url:n},imageUrl:t.image_url||null,...t.price&&{price:bo(t.price,t.currency,e)},...t.vendor&&{vendor:t.vendor},...typeof t.available=="boolean"&&{available:t.available}}}function bo(t,e,n){if(n===void 0||!e||!/^\d+(\.\d+)?$/.test(t))return t;try{return new Intl.NumberFormat(n,{style:"currency",currency:e}).format(Number(t))}catch{return t}}function So(t){if(!t.handle)return;let e=`${wr}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function Yt(t,e){return(t?.items.matched??[]).map(n=>Ir(n,e))}var et=class{constructor(e,n,r=()=>!0,i=()=>{},s=()=>{}){this.store=e;this.getConfig=n;this.isEnabled=r;this.getLanguage=i;this.getMapper=s;this.hasLoggedError=!1;this.hasLoggedMapperError=!1}forResponse(e){if(!this.isEnabled())return[];if(this.getConfig())return;let n=Yt(e,te(this.getLanguage())),r=this.getMapper();if(!r)return n;try{let i=r(n,e?.items.matched??[]);if(Array.isArray(i))return i}catch(i){this.hasLoggedMapperError||(this.hasLoggedMapperError=!0,console.warn("[AIAutocomplete] mapProducts failed. The original cards are shown.",i))}return n}async run(e,n,r){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(r);return}let s=()=>n.aborted||!r()||!this.owns(i);try{let o=await i.fetch(e,n);if(s())return;let a=i.transform(o),l=Array.isArray(a)?a:[],u=i.limit!=null?l.slice(0,i.limit):l;if(s())return;this.commit(u)}catch(o){if(n.aborted||yo(o)||(this.logOnce(o),s()))return;this.clear(r)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}refresh(){if(this.getConfig())return;let e=this.forResponse(this.store.get().customFields);e!==void 0&&this.commit(e)}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function yo(t){return t instanceof Error&&t.name==="AbortError"}function xo(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Cr(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:le.findIndex(n=>n.toLowerCase().startsWith(e))}function vo(t,e,n){let r=new Date(n.getFullYear(),t,e);if(r.getMonth()!==t||r.getDate()!==e)return null;let i=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(r>=i)return r;let s=new Date(n.getFullYear()+1,t,e);return s.getMonth()===t&&s.getDate()===e?s:null}function Or(t,e,n){let r=new Date(t,e,n);return r.getMonth()===e&&r.getDate()===n?r:null}function Pe(t,e={}){if(!t)return null;let n=e.today??new Date,r=xo(t.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(r);if(i){let l=Or(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?F(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(r);if(s){let l=Cr(s[1]);if(l>=0)return tt(l,Number(s[2]),s[3],n)}let o=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(o){let l=Cr(o[2]);if(l>=0)return tt(l,Number(o[1]),o[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(r);if(a){let l=Number(a[1]),u=Number(a[2]);return l>12&&u<=12?tt(u-1,l,a[3],n):u>12&&l<=12?tt(l-1,u,a[3],n):null}return null}function tt(t,e,n,r){if(n){if(n.length!==4)return null;let s=Or(Number(n),t,e);return s?F(s):null}let i=vo(t,e,r);return i?F(i):null}function Qt(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:Pe(t.text,e)}var kr=" - ",Jt="aiaDateRangeStart",Zt="aiaDateRangeEnd";function Te(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var Xt=/^\d{4}-\d{2}-\d{2}$/;function Ar(t){if(!Xt.test(t))return null;let[e,n,r]=t.split("-").map(Number),i=new Date(e,n-1,r);return i.getMonth()===n-1&&i.getDate()===r?i:null}var Po=/\s+(?:to|through|thru|until|til|till)\s+/g,To=/[-–—]/g;function Eo(t){let e=[];for(let n of[Po,To]){n.lastIndex=0;let r=n.exec(t);for(;r!==null;)e.push([t.slice(0,r.index),t.slice(r.index+r[0].length)]),r=n.exec(t)}return e}function nt(t,e={}){if(!t)return null;let n=new Set,r=null;for(let[i,s]of Eo(t.trim())){let o=Pe(i.trim(),e);if(!o)continue;let a=Pe(s.trim(),e);!a||a<o||(n.add(`${o}|${a}`),r={start:o,end:a})}return n.size===1?r:null}function Lr(t){let e=Ar(t.start),n=Ar(t.end);return!e||!n?"":t.start===t.end?ce(e):`${ce(e)}${kr}${ce(n)}`}function Rr(t,e){let n=Te(t,e);return{text:Lr(n),is_tappable:!0,kind:null,metadata:{[Jt]:n.start,[Zt]:n.end}}}function Ee(t,e={}){let n=t?.metadata?.[Jt],r=t?.metadata?.[Zt];return typeof n=="string"&&typeof r=="string"&&Xt.test(n)&&Xt.test(r)?Te(n,r):nt(t?.text,e)}var rt="(max-width: 768px)";var wo="var(--aia-option-row-height, 37px)",Io="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Mr(t,e){return e?en(1,Math.min(t,5)):en(1,Math.min(t,4))}function en(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${wo} + ${Io})`}}function nn(t,e){return!e&&t>=5}function rn(t,e,n,r){if(!(!e&&t>=5&&Co(n,r))){let o=Mr(t,e);return{...o,template:tn(o.cols),scrollHintIndices:!e&&t>o.rows?[o.rows-1]:[]}}let s=6;return{...en(2,3),template:tn(2),scrollHintIndices:t>s?[s-2,s-1]:[]}}function Co(t,e){return!t||t.length===0||e==null||e<=0||t.some(r=>r<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function on(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let o of e){let a=o.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let r=Array.from(n.children).map(o=>o.offsetWidth);n.remove();let i=getComputedStyle(t),s=t.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:r,gridWidth:s}}function tn(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function sn(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(rt).matches}function an(t,e){return!t||t.length!==e.length?!1:t.every((n,r)=>n.text===e[r].text)}function Dr(t,e){let n=e.dropdownTrigger??"auto",r=e.closeDropdownOnBlur??!0,o=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=r?t.isFocused||t.dropdownHeld:!0;return o&&a}if(n==="auto"){let a=r?t.isFocused||t.dropdownHeld:!0,l=t.text.replace(/\s+$/,"").length,u=t.caretOffset==null||t.caretOffset>=l;return(o||t.isLoading)&&a&&u}return n==="manual"?(o||t.isLoading)&&t.pillTapped:!1}function we(t){if(t.editingIdentified){let{parameter:n,anchor:r}=t.editingIdentified;return`identified:${n}@${r}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.parameter??""}`}function _r(t){if(!t)return Rt();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Oo(t){let e=Ve(t);return e?fr(e):Rt()}function Nr(t,e){let n=or(t.text,t.completedParams,t.identifiedParams),r=t.suggestions.filter(w=>w.parameter!=="placeholder"),i=r[0],s=t.suggestions.filter(w=>w.parameter==="placeholder").map(w=>w.text).join(" "),o=K(t.text,Math.min(t.filterBase,t.text.length),s),l=o===0&&Ne(t.text,t.completedParams.length,s)?"":Se(t.text,o,t.filterInProgress),u=i?.options??[],d=t.editingParam!=null&&t.editingAnchor!=null,c,f,p,g;if(d&&t.editingParam&&t.editingAnchor!=null){let w=t.editingParam.id,ee=t.completedParams.some(Gi=>Gi.id===w),M=t.caretOffset??t.editingAnchor,$n=ee?"":t.text.slice(t.editingAnchor,M);f=$n.trim(),p=t.editingParam.options,g=t.editingParam.suggestionParameter,c=ne(t.editingParam.options,$n)}else f=l.trim(),p=u,g=i?.parameter,c=E(i)?u.map(w=>({...w,matchedText:t.text.slice(Be(t.text,t.completedParams)),parameterLabel:Zn(w.parameter)})):ne(u,l,t.traditionalAutocomplete);let S=t.optionSearch,x=S!=null&&g!=null&&S.parameter===g;x&&S.status==="done"&&S.query===f&&(c=p);let b=x&&S.status==="loading",m=e.showNonTappableOptions===!1;m&&(c=c.filter(w=>w.is_tappable));let h=t.editingIdentified,y=d?t.editingParam&&{type:t.editingParam.suggestionValueType}:i,I=h?h.format:B(y),P=d&&I==="date-range"?Ee(t.editingParam):null,O=null,R=null;if(T(I)){let w=we({...t,actionableSuggestions:r}),ee=t.dateViewMonth;O=ee&&ee.key===w?{year:ee.year,month:ee.month}:h?_r(h.iso):P?_r(P.start):Oo(t.editingParam?.text),c=Dt(O);let M=t.pendingRangeStart;I==="date-range"&&M&&M.key===w&&(R=M.iso)}let C=w=>m?w.is_tappable:!0,A;if(d){let w=t.editingParam?.options??[];A=t.editingParam!=null&&w.filter(C).length===0}else A=i!=null&&u.filter(C).length===0;let L=Dr({inEditMode:d||h!=null,filteredOptionsLength:c.length,isFocused:t.isFocused,dropdownHeld:t.dropdownHeld,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||b,pillTapped:t.pillTapped,activePillHasNoOptions:A,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),V=L&&t.activeDropdownIndex>=0&&!!c[t.activeDropdownIndex]?.is_tappable,Z=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,v=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||b||Z,H=v&&t.skeletonOptions!==null,Tt=H&&t.skeletonOptions?t.skeletonOptions:c,Et=H?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:r,filteredOptions:c,dropdownLoading:v,dropdownOptions:Tt,dropdownSuggestion:Et,skeletonExiting:Z,activeFormatType:I,dateView:O,dateRangeStart:R,placeholderText:s,optionQuery:f,isSearchingOptions:b,isDropdownOpen:L,isActivePillSelected:V}}function it(t){return t.mode==="fresh"?Ao(t):ko(t)}function Ao(t){let{text:e,completedParams:n,suggestions:r,filterBase:i,filterInProgress:s,phraseExactMatch:o}=t,l=r.filter(y=>y.parameter!=="placeholder"&&!E(y))[0];if(!l?.options)return null;let u=r.filter(y=>y.parameter==="placeholder").map(y=>y.text).join(" "),d=K(e,i,u),c=ye(l.options,e,d,s,o===!0);if(!c)return null;let f=c.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(f),g=p>=0?p:Math.max(0,e.length-c.text.length),S=g+c.text.length,x=e.slice(g,S),m=S<e.length&&e[S]===" "?S+1:S,h={id:crypto.randomUUID(),placeholder:"",parameter:z(c,l.parameter),text:x,value:c.value,kind:c.kind,suggestionParameter:l.parameter,suggestionValueType:l.type,suggestionPlaceholder:l.text,options:l.options??[],metadata:c.metadata,icon:c.icon,icon_svg:c.icon_svg,image_url:c.image_url};return{patch:{text:e,completedParams:[...n,h],suggestions:r.filter(y=>y!==l),filterBase:m,newParamId:h.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m,option:c}}function ko(t){let{text:e,completedParams:n,editingParam:r,editingAnchor:i,editingTail:s}=t;if(n.some(h=>h.id===r.id))return null;let o=e.slice(i,s),a=_e(r.options,o);if(!a)return null;let l=a.text.toLowerCase(),u=o.toLowerCase().lastIndexOf(l),d=i+Math.max(0,u),c=d+a.text.length,f=e.slice(d,c),p=c<e.length&&e[c]===" "?c+1:c,g=e.length,S={id:crypto.randomUUID(),placeholder:"",...He(r,a),text:f,value:a.value,kind:a.kind,options:r.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},x=n.length,b=0;for(let h=0;h<n.length;h++){let y=U(e,n[h].text,b);if(y!==-1){if(y>=p){x=h;break}b=y+n[h].text.length}}let m=[...n];return m.splice(x,0,S),{patch:{text:e,completedParams:m,newParamId:S.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1},caretPos:g,option:a}}function Hr(t){return t.slice(t.search(/\S*$/))}function Fr(t){return t.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase()}function Wr(t,e){let n="",r=0;for(let i of t){if(n+=Fr(i),r+=i.length,n.length>=e.length)return n.startsWith(e)?r+(t.slice(r).match(/^\p{M}*/u)?.[0].length??0):0;if(!e.startsWith(n))return 0}return 0}function ln(t){return[...t].map(Fr).join("")}function ot(t,e){if(/\s$/.test(e))return null;let n=e.split(/\s+/).filter(Boolean).map(ln),r=[...t.matchAll(/\S+/g)].map(i=>({index:i.index??0,text:i[0],folded:ln(i[0])}));for(let i=n.length;i>=1;i--){let s=n.slice(n.length-i),o=s[i-1];for(let a=0;a+i<=r.length;a++){if(!s.slice(0,-1).every((c,f)=>r[a+f].folded===c))continue;let u=r[a+i-1],d=Wr(u.text,o);if(d>0)return{typedWords:i,start:r[a].index,end:u.index+d}}}return null}function cn(t,e){let n=e?ot(t,e):null;if(n&&n.typedWords>1)return[{text:t.slice(0,n.start),bold:!1},{text:t.slice(n.start,n.end),bold:!0},{text:t.slice(n.end),bold:!1}].filter(o=>o.text!=="");let r=e?Hr(e):"",i=ln(r);if(!i)return[{text:t,bold:!1}];let s=[];for(let o of t.split(/(\s+)/)){if(o==="")continue;let a=/^\s/.test(o)?0:Wr(o,i);a>0&&s.push({text:o.slice(0,a),bold:!0});let l=a>0?o.slice(a):o;l&&s.push({text:l,bold:!1})}return s}var Lo=6e4;function Ro(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function Mo(t){return(t??q).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Do(t){return fe(t)?`Bearer ${await Le(t).getToken()}`:Me(t)}async function Br(t){try{let e=Mo(t.apiConfig?.endpoint),n=Re(t.apiConfig),r=await Do(t.apiConfig);r&&(n.Authorization=r);let i=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,...t.language&&{language:t.language},at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:i,...t.keepalive&&Ro(i)<=Lo&&{keepalive:!0}})}catch{}}function oe(t,e){let n=t.findIndex(r=>r.text===e);return n>=0?n+1:null}var dn=t=>t.toLowerCase().split(/\s+/).filter(Boolean);function _o(t,e,n){let r=dn(t??"");if(r.length===0)return"";let s=dn(e).slice(-r.length),o=dn(n).slice(0,r.length);return s.join(" ")===r.join(" ")||o.join(" ")===r.join(" ")?"":(t??"").trim().split(/\s+/).join(" ")}function Ur(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let r=E(n),i=e.parameter;if(r&&!i)return null;let s=r&&i?i:z(e,n.parameter),o=r?t.text.length:t.filterBase,a=t.text.slice(0,o),l=a.length===0&&t.text.length===0,u=a.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(l||u)&&t.placeholderText&&(a=`${t.placeholderText} `);let d=Math.min(Be(t.text,t.completedParams),a.length);if(r){let P=[...a.slice(d).matchAll(/\S+/g)],O=ot(e.text,a.slice(d)),R=P[P.length-(O?.typedWords??1)];a=a.slice(0,R?d+(R.index??0):Math.max(a.lastIndexOf(" ")+1,d))}else{let P=Qn(a.slice(d),e.text);P>0&&(a=a.slice(0,a.length-P))}let c=a.length>0&&a[a.length-1]!==" ",p=T(B(n))?_o(n.lead_in,a,e.text):"",g=`${a}${c?" ":""}${p?`${p} `:""}${e.text} `,x=(l||u||r&&a.length===0)&&g.length>0?g[0].toUpperCase()+g.slice(1):g,b=x.toLowerCase().lastIndexOf(e.text.toLowerCase()),m=b>=0?x.slice(b,b+e.text.length):e.text,h=r?wt(s):{parameter:s,suggestionParameter:n.parameter,suggestionValueType:n.type,suggestionPlaceholder:n.text},y={id:crypto.randomUUID(),placeholder:"",...h,text:m,value:e.value,kind:e.kind,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},I=t.actionableSuggestions.length-1;return{patch:{text:x,filterBase:x.length,completedParams:[...t.completedParams,y],newParamId:y.id,caretOffset:x.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(P=>P.text!==e.text).map(P=>P.text),key:r?s:n.parameter,position:oe(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:I}}function st(t){let e=T(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,r=n?{parameter:n.suggestionParameter,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?r:null,skeletonRequested:!1}}function at(t,e,n){let r=t.slice(0,e),i=t.slice(n),s=(r===""||r.endsWith(" "))&&i.startsWith(" ");return s&&(i=i.slice(1)),{text:r+i,removed:n-e+(s?1:0)}}var lt=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let r=n.completedParams.find(o=>o.id===e);if(!r)return;let i=0,s=-1;for(let o of n.completedParams){let a=U(n.text,o.text,i);if(a!==-1){if(o.id===e){s=a;break}i=a+o.text.length}}s<0||this.deps.store.set({editingParam:r,editingAnchor:s,editingTail:s+r.text.length,caretOffset:s+r.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let n=this.deps.store.get(),r=n.editingParam,i=n.editingAnchor,s=n.editingTail;if(!r||i==null||s==null||!n.completedParams.some(l=>l.id===r.id))return!1;let{text:o}=e===""?at(n.text,i,s):{text:n.text.slice(0,i)+e+n.text.slice(s)},a=i+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(u=>u.id!==r.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),r={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(r.editingParam=null,r.editingAnchor=null,r.editingTail=null,r.activeDropdownIndex=-1):n.editingTail!=null&&(r.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(r),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),r=n.editingParam,i=n.editingAnchor,s=n.editingTail;if(!r||i==null||s==null)return;let o=He(r,e);this.deps.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:r.options.filter(m=>m.text!==e.text).map(m=>m.text),key:o.suggestionParameter,position:oe(r.options,e.text),chip_origin:"tap"});let a=n.text.slice(0,i),l=n.text.slice(s),u=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,c=l.length===0||l[0]!==" "?`${u} `:u,f=a+c+l,p=f.length,g={id:crypto.randomUUID(),placeholder:"",...o,text:u,value:e.value,kind:e.kind,options:r.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=n.completedParams.findIndex(m=>m.id===r.id),x=n.completedParams.filter(m=>m.id!==r.id),b=S>=0?Math.min(S,x.length):x.length;x.splice(b,0,g),this.deps.store.set({text:f,completedParams:x,newParamId:g.id,filterBase:p,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:p,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...st(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(p),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=it({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var No=33,Ho=70,Fo=120,Wo=50,ue="data-aia-placeholder-leaving",pe=new WeakMap;function ct(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function Bo(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Gr(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function Vr(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(Gr(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],r=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>Vr(t,e),33+r)}function $r(t,e){Gr(t,e,0),e.timer=setTimeout(()=>Vr(t,e),33)}function qr(t,e){let n=pe.get(t);if(e===""){n&&(ct(n),pe.delete(t)),t.removeAttribute(ue),delete t.dataset.placeholder;return}if(n?.target===e)return;if(Bo(t)){n&&ct(n),t.removeAttribute(ue),pe.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let r={target:e,shown:0,timer:null},i=n&&n.shown>0?n:null;if(n&&ct(n),pe.set(t,r),i){t.setAttribute(ue,""),r.timer=setTimeout(()=>{r.timer=null,t.removeAttribute(ue),t.isConnected&&$r(t,r)},170);return}t.removeAttribute(ue),$r(t,r)}function Kr(t){let e=pe.get(t);e&&(ct(e),pe.delete(t))}var zr="https://ai-autocomplete.com";function un(t=zr){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}var jr={language:"en",proceed:"to proceed",select:"to select",skipHint:"to skip",skip:"skip",skipLabel:"Skip",products:"Products",soldOut:"Sold out",submit:"Submit",scrollArrow:"Scroll down for more options",keepTyping:"Keep typing"},Uo={language:"es",proceed:"para continuar",select:"para seleccionar",skipHint:"para omitir",skip:"omitir",skipLabel:"Omitir",products:"Productos",soldOut:"Agotado",submit:"Buscar",scrollArrow:"Despl\xE1zate para ver m\xE1s opciones",keepTyping:"Sigue escribiendo"},pn={en:jr,es:Uo,fr:{language:"fr",proceed:"pour continuer",select:"pour s\xE9lectionner",skipHint:"pour passer",skip:"passer",skipLabel:"Passer",products:"Produits",soldOut:"\xC9puis\xE9",submit:"Rechercher",scrollArrow:"Faites d\xE9filer pour voir plus d\u2019options",keepTyping:"Continuez \xE0 taper"},"pt-BR":{language:"pt-BR",proceed:"para continuar",select:"para selecionar",skipHint:"para pular",skip:"pular",skipLabel:"Pular",products:"Produtos",soldOut:"Esgotado",submit:"Buscar",scrollArrow:"Role para ver mais op\xE7\xF5es",keepTyping:"Continue digitando"},it:{language:"it",proceed:"per continuare",select:"per selezionare",skipHint:"per saltare",skip:"salta",skipLabel:"Salta",products:"Prodotti",soldOut:"Esaurito",submit:"Cerca",scrollArrow:"Scorri per vedere altre opzioni",keepTyping:"Continua a scrivere"},tr:{language:"tr",proceed:"devam etmek i\xE7in",select:"se\xE7mek i\xE7in",skipHint:"atlamak i\xE7in",skip:"atla",skipLabel:"Atla",products:"\xDCr\xFCnler",soldOut:"T\xFCkendi",submit:"Ara",scrollArrow:"Daha fazla se\xE7enek i\xE7in kayd\u0131r",keepTyping:"Yazmaya devam et"},id:{language:"id",proceed:"untuk melanjutkan",select:"untuk memilih",skipHint:"untuk melewati",skip:"lewati",skipLabel:"Lewati",products:"Produk",soldOut:"Habis",submit:"Cari",scrollArrow:"Gulir untuk melihat opsi lainnya",keepTyping:"Teruskan mengetik"},pl:{language:"pl",proceed:"aby kontynuowa\u0107",select:"aby wybra\u0107",skipHint:"aby pomin\u0105\u0107",skip:"pomi\u0144",skipLabel:"Pomi\u0144",products:"Produkty",soldOut:"Wyprzedane",submit:"Szukaj",scrollArrow:"Przewi\u0144, aby zobaczy\u0107 wi\u0119cej opcji",keepTyping:"Pisz dalej"},de:{language:"de",proceed:"zum Fortfahren",select:"zum Ausw\xE4hlen",skipHint:"zum \xDCberspringen",skip:"\xFCberspringen",skipLabel:"\xDCberspringen",products:"Produkte",soldOut:"Ausverkauft",submit:"Suchen",scrollArrow:"Scrolle f\xFCr weitere Optionen",keepTyping:"Weitertippen"},nl:{language:"nl",proceed:"om door te gaan",select:"om te selecteren",skipHint:"om over te slaan",skip:"overslaan",skipLabel:"Overslaan",products:"Producten",soldOut:"Uitverkocht",submit:"Zoeken",scrollArrow:"Scrol voor meer opties",keepTyping:"Blijf typen"},sv:{language:"sv",proceed:"f\xF6r att forts\xE4tta",select:"f\xF6r att v\xE4lja",skipHint:"f\xF6r att hoppa \xF6ver",skip:"hoppa \xF6ver",skipLabel:"Hoppa \xF6ver",products:"Produkter",soldOut:"Sluts\xE5ld",submit:"S\xF6k",scrollArrow:"Skrolla f\xF6r fler alternativ",keepTyping:"Forts\xE4tt skriva"},nb:{language:"nb",proceed:"for \xE5 fortsette",select:"for \xE5 velge",skipHint:"for \xE5 hoppe over",skip:"hopp over",skipLabel:"Hopp over",products:"Produkter",soldOut:"Utsolgt",submit:"S\xF8k",scrollArrow:"Rull ned for \xE5 se flere alternativer",keepTyping:"Fortsett \xE5 skrive"},da:{language:"da",proceed:"for at forts\xE6tte",select:"for at v\xE6lge",skipHint:"for at springe over",skip:"spring over",skipLabel:"Spring over",products:"Produkter",soldOut:"Udsolgt",submit:"S\xF8g",scrollArrow:"Rul for flere muligheder",keepTyping:"Forts\xE6t med at skrive"},fi:{language:"fi",proceed:"jatkaaksesi",select:"valitaksesi",skipHint:"ohittaaksesi",skip:"ohita",skipLabel:"Ohita",products:"Tuotteet",soldOut:"Loppuunmyyty",submit:"Hae",scrollArrow:"Vierit\xE4 n\xE4hd\xE4ksesi lis\xE4\xE4 vaihtoehtoja",keepTyping:"Jatka kirjoittamista"},ja:{language:"ja",proceed:"\u3067\u6B21\u3078",select:"\u3067\u9078\u629E",skipHint:"\u3067\u30B9\u30AD\u30C3\u30D7",skip:"\u30B9\u30AD\u30C3\u30D7",skipLabel:"\u30B9\u30AD\u30C3\u30D7",products:"\u5546\u54C1",soldOut:"\u58F2\u308A\u5207\u308C",submit:"\u691C\u7D22",scrollArrow:"\u30B9\u30AF\u30ED\u30FC\u30EB\u3057\u3066\u4ED6\u306E\u5019\u88DC\u3092\u898B\u308B",keepTyping:"\u5165\u529B\u3092\u7D9A\u3051\u308B"},ko:{language:"ko",proceed:"\uACC4\uC18D",select:"\uC120\uD0DD",skipHint:"\uAC74\uB108\uB6F0\uAE30",skip:"\uAC74\uB108\uB6F0\uAE30",skipLabel:"\uAC74\uB108\uB6F0\uAE30",products:"\uC0C1\uD488",soldOut:"\uD488\uC808",submit:"\uAC80\uC0C9",scrollArrow:"\uB354 \uB9CE\uC740 \uC635\uC158\uC744 \uBCF4\uB824\uBA74 \uC2A4\uD06C\uB864\uD558\uC138\uC694",keepTyping:"\uACC4\uC18D \uC785\uB825\uD558\uC138\uC694"},"zh-CN":{language:"zh-CN",proceed:"\u7EE7\u7EED",select:"\u9009\u62E9",skipHint:"\u8DF3\u8FC7",skip:"\u8DF3\u8FC7",skipLabel:"\u8DF3\u8FC7",products:"\u5546\u54C1",soldOut:"\u552E\u7F44",submit:"\u641C\u7D22",scrollArrow:"\u5411\u4E0B\u6EDA\u52A8\u67E5\u770B\u66F4\u591A\u9009\u9879",keepTyping:"\u7EE7\u7EED\u8F93\u5165"},"zh-TW":{language:"zh-TW",proceed:"\u7E7C\u7E8C",select:"\u9078\u64C7",skipHint:"\u7565\u904E",skip:"\u7565\u904E",skipLabel:"\u7565\u904E",products:"\u5546\u54C1",soldOut:"\u552E\u5B8C",submit:"\u641C\u5C0B",scrollArrow:"\u5411\u4E0B\u6372\u52D5\u67E5\u770B\u66F4\u591A\u9078\u9805",keepTyping:"\u7E7C\u7E8C\u8F38\u5165"}},$o={pt:"pt-BR",no:"nb",nn:"nb"};function k(t){let[e,...n]=t?.toLowerCase().split("-")??[];if(e==="zh"){let i=n.some(s=>["hant","tw","hk","mo"].includes(s));return pn[i?"zh-TW":"zh-CN"]}let r=$o[e]??e;return Object.prototype.hasOwnProperty.call(pn,r)?pn[r]:jr}function mn(t,e,n=k()){return t?{key:"enter",hint:n.proceed}:e?{key:"tab",hint:n.select}:{key:"\u2192",hint:n.skipHint}}function gn(t){let e=o=>{o.ctrlKey||Yr(o.target,t,o.deltaX,o.deltaY)||o.preventDefault()},n=0,r=0,i=o=>{let a=o.touches[0];a&&(n=a.clientX,r=a.clientY)},s=o=>{if(o.touches.length!==1)return;let a=o.touches[0],l=n-a.clientX,u=r-a.clientY;n=a.clientX,r=a.clientY,o.cancelable&&!Yr(o.target,t,l,u)&&o.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",i,{passive:!0}),t.addEventListener("touchmove",s,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",i),t.removeEventListener("touchmove",s)}}function Yr(t,e,n,r){let i=t instanceof Element?t:null;for(;i;){if(r!==0&&Go(i,r)||n!==0&&Vo(i,n))return!0;if(i===e)break;i=i.parentElement}return!1}var Qr=/^(auto|scroll|overlay)$/;function Go(t,e){return t.scrollHeight<=t.clientHeight||!Qr.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function Vo(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!Qr.test(n.overflowX))return!1;let r=Math.abs(t.scrollLeft),i=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?r<i-1:r>0}var Xr=new WeakMap,Jr=new WeakSet;function Y(t,e,n){if(Xr.set(t,n),Jr.has(t))return;Jr.add(t);let r=()=>Xr.get(t),i=s=>{if(!(s instanceof Element))return null;let o=s.closest(e.itemSelector);return o&&t.contains(o)?o:null};e.onClick&&t.addEventListener("click",s=>{let o=i(s.target);o&&e.onClick?.(o,r(),s)}),e.onEnter&&t.addEventListener("mouseenter",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onEnter?.(o,r())},!0),e.onLeave&&t.addEventListener("mouseleave",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onLeave?.(o,r())},!0),e.preventMousedown&&t.addEventListener("mousedown",s=>s.preventDefault())}function Q(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function X(t){t.offsetWidth}var qo={selectedIso:null,selectedRange:null,rangeStart:null};function Ie(t){if(!T(t.activeFormatType))return qo;let e=t.editingIdentified;if(e){let{iso:r,isoEnd:i}=e;return{selectedIso:i?null:r,selectedRange:r&&i?Te(r,i):null,rangeStart:t.dateRangeStart}}let n=Ee(t.editingParam);return{selectedIso:n?null:_t(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function fn(t){return t.pendingStart?Te(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function hn(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:r}=e,i=t===n||r!=null&&(t===r.start||t===r.end),s=r!=null&&t>r.start&&t<r.end;return{selected:i,inRange:s}}var Zr="data-aia-key";function J(t,e,n){let r=new Map;for(let o of Array.from(t.children)){let a=o.getAttribute(Zr);a!=null&&r.set(a,o)}let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=n.keyOf(a,o);i.add(l);let u=r.get(l);u||(u=n.create(a,o),u.setAttribute(Zr,l)),n.update?.(u,a,o),t.children[o]!==u&&t.insertBefore(u,t.children[o]??null),s.push(u)}for(let[o,a]of r)i.has(o)||a.remove();return s}function ei(t,e){if(!e.interactive)return null;let n=e.options[Q(t)];return n?.is_tappable?n:null}var Ko={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=ei(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&ei(t,e)&&e.callbacks.onHighlight(Q(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,Q(t))}};function ni(t,e,n,r,i,s,o,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=Yo(),t.appendChild(l),X(l);for(let c of l.querySelectorAll(".magicx-aia-datepicker-nav"))c.disabled=!1}Y(l,Ko,{options:e,callbacks:o,interactive:a});let u=l.querySelector(".magicx-aia-datepicker-month");u&&(u.textContent=Lt(i));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&zo(d,e,n,r,s)}function zo(t,e,n,r,i){let s=F(new Date),o=fn({pendingStart:i.rangeStart,highlightedIso:G(e[n]),selected:i.selectedRange});J(t,e,{keyOf:(a,l)=>G(a)??`pad-${l}`,create:a=>jo(a),update:(a,l,u)=>{let d=G(l),c=hn(d,{selectedIso:i.selectedIso,range:o}),f=u===n&&l.is_tappable;a.id=`${r}-option-${u}`,a.dataset.aiaIndex=String(u),a.setAttribute("aria-selected",String(f)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<s),a.classList.toggle("magicx-aia-date-cell--highlighted",f),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===s),a.classList.toggle("magicx-aia-date-cell--selected",c.selected),a.classList.toggle("magicx-aia-date-cell--in-range",c.inRange)}})}function jo(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=Nt(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let r=document.createElement("span");return r.className="magicx-aia-date-cell-number",r.textContent=String(n),e.appendChild(r),e}function Yo(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(ti("prev","Previous month","\u2039"),n,ti("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let s of Ge){let o=document.createElement("span");o.className="magicx-aia-datepicker-weekday",o.textContent=s,r.appendChild(o)}let i=document.createElement("div");return i.className="magicx-aia-datepicker-grid",i.setAttribute("data-aia-date-grid",""),t.append(e,r,i),t}function ti(t,e,n){let r=document.createElement("button");return r.type="button",r.tabIndex=-1,r.className="magicx-aia-datepicker-nav",r.setAttribute(`data-aia-date-${t}`,""),r.setAttribute("aria-label",e),r.textContent=n,r.disabled=!0,r}var Qo={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},ri=[125,69];function ii(t,e){return e?1:t===0?.7:t===1?.4:.2}function dt(t,e,n,r,i=!1,s=!1,o=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),Y(a,Qo,{onSelectPill:r,loading:s}),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<ri.length;l++){let u=ri[l],d=document.createElement("span");d.setAttribute("data-aia-pill-skeleton",""),d.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,d.style.width=`${u}px`,d.style.opacity=String(ii(l,!1)),a.appendChild(d)}return}s?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();J(a,e,{keyOf:l=>`${l.type?.kind??""}|${Fe(l)?1:0}|${l.parameter}|${l.text}`,create:l=>{let u=document.createElement("button");if(u.type="button",u.tabIndex=-1,u.setAttribute("data-aia-pill",""),u.setAttribute("contenteditable","false"),Fe(l)){u.setAttribute("data-aia-smart-suggestion",E(l)?"header":"");let d=document.createElement("span");d.className="magicx-aia-smart-suggestion-text",d.textContent=l.text;let c=document.createElement("span");c.className="magicx-aia-smart-suggestion-sparkle",c.innerHTML=Ot,u.append(d,c)}else u.textContent=l.text;return u.disabled=!0,u},update:(l,u,d)=>{let c=l,f=o&&d===n&&!s,p=["magicx-aia-pill"];i&&p.push("magicx-aia-pill--rounded"),s&&p.push("magicx-aia-pill--skeleton"),c.className=p.join(" "),c.style.width="",c.style.opacity=String(ii(d,f)),c.dataset.aiaPillIndex=String(d),s?c.setAttribute("data-aia-loading",""):c.removeAttribute("data-aia-loading")}}),X(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=s}function bn(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Xo=32;function oi(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,r=e.deltaX||0;if(!n||Math.abs(r)>=Math.abs(n))return null;let i=t.scrollWidth-t.clientWidth;if(i<=1)return null;let s=t.scrollLeft,o=n;return e.deltaMode===1?o*=32:e.deltaMode===2&&(o*=t.clientWidth),Math.max(0,Math.min(i,s+o))}function Sn(t){let e=n=>{let r=oi(t,n);r!==null&&(n.preventDefault(),t.scrollLeft=r)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var si=Intl.Segmenter,ai=si?new si(void 0,{granularity:"grapheme"}):null;function yn(t){let e=t.trim().normalize("NFC").toUpperCase();if(ai)for(let n of ai.segment(e))return n.segment;return Array.from(e)[0]??"?"}var xn=120,Jo=360;function Zo(t){let e=t.pathname;return t.hostname==="cdn.shopify.com"&&e.startsWith("/s/files/")||e.startsWith("/cdn/shop/")?/\.png$/i.test(e)?{format:"pjpg"}:/\.webp$/i.test(e)?{format:null}:null:null}function li(t,e){let n;try{n=new URL(t,typeof document>"u"?void 0:document.baseURI)}catch{return t}let r=Zo(n);return r?(n.searchParams.set("width",String(e)),r.format&&n.searchParams.set("format",r.format),t.startsWith("/")&&!t.startsWith("//")?`${n.pathname}${n.search}${n.hash}`:n.href):t}function vn(t,e){let n=li(t,e);return n===t?[t]:[n,t]}function ut(t){let e=t?.trim();return e?vn(e,360):[]}function es(t){return ut(t)[0]}var Pn=new WeakMap,Tn=new WeakMap,ci=new WeakMap;function di(t,e,n,r,i,s="row",o="image",a=k()){let l=t.querySelector(".magicx-aia-products");if(e.length===0){l?.remove();return}if(!l){l=document.createElement("section"),l.className="magicx-aia-products",l.setAttribute("data-aia-products",""),l.setAttribute("role","group"),l.setAttribute("aria-labelledby",`${n}-products-label`);let c=document.createElement("div");c.className="magicx-aia-products-label",c.id=`${n}-products-label`,c.setAttribute("data-aia-products-label",""),c.textContent=a.products;let f=document.createElement("div");f.className="magicx-aia-products-row",f.setAttribute("data-aia-products-row",""),Sn(f),l.append(c,f),t.appendChild(l)}l.setAttribute("data-aia-products-layout",s);let u=l.querySelector(".magicx-aia-products-label");u&&u.textContent!==a.products&&(u.textContent=a.products);let d=l.querySelector(".magicx-aia-products-row");if(d){J(d,e,{keyOf:c=>ns(c),create:c=>rs(c,r,i,o,a),update:(c,f,p)=>{Pn.set(c,f),ts(c,f.price),c.id=`${n}-product-${p}`,c.dataset.aiaIndex=String(p),ci.get(c)?.(o);let g=c.querySelector(".magicx-aia-product-badge");g&&g.textContent!==a.soldOut&&(g.textContent=a.soldOut)}}),X(d);for(let c of d.querySelectorAll("[data-aia-product]")){let f=Tn.get(c);f&&(Tn.delete(c),f())}}}function En(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let r of n)r.tabIndex=e?0:-1}function ts(t,e){let n=t.querySelector(".magicx-aia-product-price");if(!e){n?.remove();return}n||(n=document.createElement("span"),n.className="magicx-aia-product-price",t.querySelector(".magicx-aia-product-title")?.after(n)),n.textContent!==e&&(n.textContent=e)}function ns(t){return[t.id,t.title,t.url,t.imageUrl,t.vendor,t.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function rs(t,e,n,r,i){let s=document.createElement("a");s.className="magicx-aia-product",s.setAttribute("data-aia-product",""),s.setAttribute("role","option"),s.setAttribute("aria-selected","false"),s.tabIndex=0;let o=document.createElement("span");o.className="magicx-aia-product-media",o.setAttribute("aria-hidden","true");let a=ut(t.imageUrl),l=a[0],u=!!l,d=()=>{o.replaceChildren(),o.removeAttribute("data-aia-image-loaded"),o.toggleAttribute("data-aia-product-placeholder",r==="image"),o.toggleAttribute("data-aia-product-initial",r==="initial"),r==="initial"&&(o.textContent=yn(t.title))};if(ci.set(s,p=>{p!==r&&(r=p,u||d())}),l){let p=document.createElement("img"),g=0;p.onload=()=>o.setAttribute("data-aia-image-loaded",""),p.onerror=()=>{let S=a[++g];if(S){p.src=S;return}u=!1,d()},p.className="magicx-aia-product-image",p.src=l,p.alt="",p.loading="lazy",p.decoding="async",o.appendChild(p)}else d();s.appendChild(o);let c=document.createElement("span");if(c.className="magicx-aia-product-body",t.vendor){let p=document.createElement("span");p.className="magicx-aia-product-vendor",p.textContent=t.vendor,c.appendChild(p)}let f=document.createElement("span");if(f.className="magicx-aia-product-title",f.textContent=t.title,c.appendChild(f),t.available===!1){s.setAttribute("data-aia-product-sold-out","");let p=document.createElement("span");p.className="magicx-aia-product-badge",p.textContent=i.soldOut,c.appendChild(p)}return s.appendChild(c),Tn.set(s,()=>{t.url&&(s.href=t.url),s.addEventListener("click",p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0||(p.preventDefault(),e(Pn.get(s)??t))})}),s.addEventListener("keydown",p=>{p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),e(Pn.get(s)??t))}),s.addEventListener("focus",()=>n(!0)),s.addEventListener("blur",p=>{p.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),s}var is=80,os=150,ss=280,as=16,wn="--aia-option-enter-delay";function In(t,e,n,r="below"){let i=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,t)/i);if(r!=="above")return s*80;let o=Math.max(1,Math.ceil(Math.max(0,n)/i));return Math.max(0,o-1-s)*80}function Cn(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}var ui="http://www.w3.org/2000/svg",ls=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function cs(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var ds=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],us=/^[a-zA-Z0-9#.,%\s()-]+$/;function ps(t){let e=[];for(let n of ds){let r=t.getAttribute(n);r===null||!us.test(r)||/url\s*\(/i.test(r)||e.push(`${n}: ${r.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function pi(t){for(let e of Array.from(t.attributes))cs(e.name,e.value)&&t.removeAttribute(e.name);ps(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!ls.has(n.localName)||n.namespaceURI!==ui?n.remove():pi(n)}else e.remove()}function se(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==ui||e.getElementsByTagName("parsererror").length>0?null:(pi(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function pt(t){return t.text}function ae(t){return gt(t)[0]??null}function gt(t){let e=ms(t);return e?vn(e,120):[]}function ms(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function Ce(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var mi={one:"item",other:"items"};function gs(t,e=mi){let n=Ce(t);if(n===null)return null;let r=typeof e=="string"?e:t===1?e.one:e.other;return r===""?n:`${n} ${r}`}function gi(t){return ae(t.image_url)!==null}var mt=new Map;function fs(t){let e=t.icon_svg;if(!e)return!1;let n=mt.get(e);return n===void 0&&(n=se(e)!==null,mt.size>=256&&mt.clear(),mt.set(e,n)),n}function On(t,e,n){return!e&&!n?!1:t.every(r=>!r.is_tappable||n&&gi(r)||e&&fs(r))}var fi=new WeakMap;function hs(t,e,n){let r=e.length,i=sn(),s=fi.get(t),o=n&&s&&an(s.options,e)?s.plan:null,a=!o&&!n&&nn(r,i)?on(t):null,l=o??rn(r,i,a?.rowWidths??null,a?.gridWidth??null);return n||fi.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((u,d)=>{u.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(d))}),l.cols}function hi(t,e){if(e.loading||!e.interactive)return null;let n=e.options[Q(t)];return n?.is_tappable?n:null}var bs={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=hi(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{hi(t,e)&&e.onHighlight(Q(t))},onLeave:(t,e)=>e.onHighlight(-1,Q(t))};function bi(t,e,n,r,i,s,o,a="",l="below",u=!0,d=!0,c=!0,f=!0){let p=t.querySelector(".aia-grid");if(e.length===0){p?.remove();return}p||(p=document.createElement("div"),p.className="aia-grid magicx-aia-grid",p.setAttribute("data-scroll",""),p.style.setProperty("--aia-grid-min","250px"),p.style.setProperty("--aia-grid-max","1fr"),p.style.setProperty("--aia-grid-gap","0"),t.appendChild(p)),Y(p,bs,{options:e,onSelect:r,onHighlight:i,loading:o,interactive:f});let g=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a;let S=On(e,u,d);Ss(p,e,n,s,o,{showIcons:u&&S,showImages:d&&S,showCounts:c});let x=hs(p,e,o);ys(p,e.length,x,o,l),g&&(p.scrollTop=0)}function Ss(t,e,n,r,i,s){let o=i?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:u,showCounts:d}=s,c=l?g=>g.icon??g.icon_svg??"":()=>"",f=u?g=>ae(g.image_url)??"":()=>"",p=d?g=>Ce(g.item_count)??"":()=>"";J(t,e,{keyOf:g=>`${g.text}\0${g.parameterLabel??""}\0${c(g)}\0${f(g)}\0${p(g)}\0${o}\0${a}`,create:(g,S)=>{let x=xs(g,i,s);return i||(x.dataset.aiaEntering=""),x},update:(g,S,x)=>{if(An.get(g)!==(S.matchedText??"")){let m=g.querySelector(".magicx-aia-option-text");m&&Si(m,S),An.set(g,S.matchedText??"")}let b=x===n&&!i;g.id=`${r}-option-${x}`,g.dataset.aiaIndex=String(x),g.setAttribute("aria-selected",String(b)),g.classList.toggle("magicx-aia-option--highlighted",b)}})}function ys(t,e,n,r,i){for(let s of t.querySelectorAll("[data-aia-entering]")){if(!r){let o=Number.parseInt(s.dataset.aiaIndex??"-1",10);o>=0&&s.style.setProperty(wn,`${In(o,n,e,i)}ms`)}delete s.dataset.aiaEntering}}var An=new WeakMap;function Si(t,e){if(t.replaceChildren(),e.matchedText)for(let n of cn(pt(e),e.matchedText))if(n.bold){let r=document.createElement("strong");r.className="magicx-aia-option-match",r.textContent=n.text,t.appendChild(r)}else t.appendChild(document.createTextNode(n.text));else t.appendChild(document.createTextNode(pt(e)));if(e.parameterLabel){t.appendChild(document.createTextNode(" "));let n=document.createElement("span");n.className="magicx-aia-option-parameter",n.textContent=e.parameterLabel,t.appendChild(n)}}function xs(t,e,{showIcons:n,showImages:r,showCounts:i}){let s=document.createElement("div");s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),e&&s.setAttribute("data-aia-loading",""),s.tabIndex=e||!t.is_tappable?-1:0;let o=["magicx-aia-option"];t.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),s.className=o.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=r?gt(t.image_url):[],u=l[0];if(u){let p=document.createElement("span");p.className="magicx-aia-option-image",p.setAttribute("aria-hidden","true");let g=document.createElement("img");g.setAttribute("alt",""),g.setAttribute("loading","lazy"),g.setAttribute("decoding","async"),g.setAttribute("referrerpolicy","no-referrer"),g.setAttribute("draggable","false");let S=0;g.onload=()=>p.setAttribute("data-aia-image-loaded",""),g.onerror=()=>{let x=l[++S];x?g.src=x:g.hidden=!0},g.src=u,p.appendChild(g),a.appendChild(p),s.dataset.aiaImage=""}let d=!u&&n&&t.icon_svg?se(t.icon_svg):null;if(d){let p=document.createElement("span");p.className="magicx-aia-option-icon",p.setAttribute("aria-hidden","true"),p.innerHTML=d,a.appendChild(p),t.icon&&(s.dataset.aiaIcon=t.icon)}let c=document.createElement("span");if(c.className="magicx-aia-option-text",Si(c,t),An.set(s,t.matchedText??""),a.appendChild(c),t.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=t.tag,a.appendChild(p)}let f=i?Ce(t.item_count):null;if(f!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=f,a.appendChild(p),s.dataset.aiaItemCount=String(t.item_count)}return s.appendChild(a),s}var yi="magicx-aia-scroll-arrow",xi="data-aia-scroll-arrow",me="data-aia-visible",vi=1e3,Pi=160,Ti="--aia-scroll-arrow-bottom",vs="Scroll down for more options",Ps="[data-aia-products-label]",Ts=4,Es=8,ws=240;function Is(t,e,n,r){let i=t.scrollTop,s=n?.requestAnimationFrame,o=t.ownerDocument?.visibilityState==="hidden";if(!s||o||kn(t)){t.scrollTop=i+e,r();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),u=()=>{let d=Math.min(1,(l()-a)/ws),c=1-(1-d)*(1-d);t.scrollTop=i+e*c,d<1?s.call(n,u):r()};s.call(n,u)}function Cs(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let r=t.createElementNS(e,"path");return r.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(r),n}function Ei(t=document,e=k()){let n=t.createElement("button");return n.type="button",n.tabIndex=-1,n.className=yi,n.setAttribute(xi,""),n.setAttribute("aria-label",e.scrollArrow),n.setAttribute("aria-hidden","true"),n.disabled=!0,n.appendChild(Cs(t)),n}function Os(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function kn(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ln({dropdown:t,grid:e,button:n}){let r=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;n.disabled=!0;let s=null,o=null,a=null,l=null,u=m=>{if(m){if(n.hasAttribute(me))return;if(n.setAttribute(me,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),kn(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&n.hasAttribute(me)&&(n.disabled=!1)},vi)}else n.removeAttribute(me),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},d=m=>{let h=0,y=m;for(;y&&y!==t;)h+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return h},c=()=>{let m=t.querySelector(Ps),h;if(m){let y=d(m)+m.offsetHeight/2;h=t.clientHeight-y-n.offsetHeight/2}else{let y=d(e),I=r&&Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0;h=t.clientHeight-(y+e.offsetHeight)+(I>0?0:Es)}n.style.setProperty(Ti,`${Math.max(0,Math.round(h))}px`)},f=()=>{if(i||o!==null||a!==null)return;let m=e.querySelector("[data-aia-option][data-aia-loading]")!==null,h=e.scrollHeight-e.clientHeight-e.scrollTop;u(!m&&h>Ts)},p=()=>{if(i)return;c();let m=e.getAttribute("data-aia-group")??"";if(m!==s){s=m,u(!1),o!==null&&clearTimeout(o);let h=e.querySelectorAll("[data-aia-option]").length,y=kn(e)?0:Cn(h,Os(e));o=setTimeout(()=>{o=null,f()},y);return}f()},g=()=>{i||o!==null||(u(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,f()},Pi))};e.addEventListener("scroll",g,{passive:!0});let S=m=>m.preventDefault(),x=()=>{let m=r?(Number.parseFloat(r.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0):0,h=Math.max(1,e.clientHeight-m);Is(e,h,r,g)};n.addEventListener("mousedown",S),n.addEventListener("click",x);let b=null;return r&&typeof r.ResizeObserver=="function"&&(b=new r.ResizeObserver(()=>{c(),f()}),b.observe(e)),p(),{update:p,destroy(){i||(i=!0,o!==null&&clearTimeout(o),o=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,n.disabled=!0,e.removeEventListener("scroll",g),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),b?.disconnect(),n.removeAttribute(me),n.setAttribute("aria-hidden","true"))}}}var ge="data-aia-fit",ft="--aia-dropdown-fit-height";function Rn({dropdown:t,isOpen:e}){let n=t.ownerDocument?.defaultView??null,r=!1,i=!1,s=null,o=null,a=null,l=()=>{t.removeAttribute(ge),t.style.removeProperty(ft)},u=p=>{let S=`${s}|${(p??t).scrollHeight}|${t.offsetWidth}`;if(a?.key===S)return a.height;let x=p?.scrollTop??0;t.removeAttribute(ge);let b=t.offsetHeight;return t.setAttribute(ge,""),p&&x&&(p.scrollTop=x),a={key:S,height:b},b},d=()=>{if(r)return;if(!e()){i=!1;return}i||(i=!0,l());let p=t.hasAttribute(ge),g=t.querySelector(".aia-grid")?.getAttribute("data-aia-group")??null,S=g!==s;s=g;let x=ks(t,n);if(x===null)return;let b=As(t);if(p){if(u(b)<=x){l();return}}else if(t.offsetHeight<=x)return;let m=`${Math.max(160,Math.floor(x))}px`;t.style.getPropertyValue(ft)!==m&&t.style.setProperty(ft,m),p?S&&b&&(b.scrollTop=0):t.setAttribute(ge,"")},c=()=>{r||o!==null||!n||(o=n.requestAnimationFrame(()=>{o=null,d()}))},f=n?.visualViewport??null;return f?.addEventListener("resize",c),f?.addEventListener("scroll",c),n?.addEventListener("resize",c),n?.addEventListener("scroll",c,{capture:!0,passive:!0}),d(),{update:d,destroy(){r||(r=!0,o!==null&&n?.cancelAnimationFrame(o),f?.removeEventListener("resize",c),f?.removeEventListener("scroll",c),n?.removeEventListener("resize",c),n?.removeEventListener("scroll",c,{capture:!0}))}}}function As(t){for(let e of Array.from(t.children))if(e.classList.contains("aia-stack"))return e;return null}function ks(t,e){if(!e)return null;let n=e.visualViewport,r=n?n.offsetTop:0,i=n?n.height:e.innerHeight;if(!i)return null;let s=t.offsetParent,o=s?s.getBoundingClientRect().top:0,a=s?o+t.offsetTop:t.getBoundingClientRect().top;return t.closest("[data-options-position]")?.getAttribute("data-options-position")==="above"?(s?a+t.offsetHeight:t.getBoundingClientRect().bottom)-r-8:r+i-a-8}var Ls=[159,119,164];function St(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),gn(e),e}var ht=new WeakMap;function Rs(t,e,n){let r=ht.get(t);if(r||(r={button:Ei(t.ownerDocument,n),grid:null,controller:null},t.appendChild(r.button),ht.set(t,r)),r.button.getAttribute("aria-label")!==n.scrollArrow&&r.button.setAttribute("aria-label",n.scrollArrow),r.grid!==e&&(r.controller?.destroy(),r.controller=null,r.grid=e,e)){r.controller=Ln({dropdown:t,grid:e,button:r.button});return}r.controller?.update()}var bt=new WeakMap;function wi(t){let e=bt.get(t);if(e){e.update();return}bt.set(t,Rn({dropdown:t,isOpen:()=>t.classList.contains("magicx-aia-dropdown--visible")}))}function Mn(t){bt.get(t)?.destroy(),bt.delete(t);let e=ht.get(t);e&&(e.controller?.destroy(),ht.delete(t))}function yt(t,e){let n=e.strings??k(),{filteredOptions:r,activeIndex:i,isOpen:s,isLoading:o,showPills:a,isActivePillSelected:l,onSelect:u,onHighlight:d,onPillClick:c,onSkip:f}=e,p=Ct(e.pills,n.keepTyping),g=At(p),S=a&&p.length>0,x=r.length>0,b=e.products.length>0,m=s&&(x||S||o||b);if(m?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),o?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!m){En(t,!1),wi(t);return}b?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let h=t.querySelector(".aia-stack");h||(h=document.createElement("div"),h.className="aia-stack",h.style.setProperty("--aia-stack-space","8px"),t.appendChild(h));let y=e.showSkipButton&&g&&!e.isInputEmpty,I=S||o&&a||y,P=h.querySelector(".magicx-aia-pill-bar");if(I){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),h.insertBefore(P,h.firstChild));let v=P.querySelector(".magicx-aia-pill-scroll");v||(v=document.createElement("span"),v.className="magicx-aia-pill-scroll",v.setAttribute("data-aia-pill-scroll",""),P.insertBefore(v,P.firstChild)),dt(v,a?p:[],0,c,!0,o&&a,l),_s(P,y,o||e.skipDisabled,p[0],f,n)}else P&&P.remove();let O=e.suggestions[0],R=O?`${O.parameter} ${O.text}`:"",C=T(e.formatType),A=C&&!o;bi(h,C?[]:r,i,u,d,e.listboxId,o,R,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Rs(t,h.querySelector(".aia-grid"),n),ni(h,A?r:[],i,e.listboxId,A?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:u,onHighlight:d,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let L=h.querySelector(".magicx-aia-skeleton-bars");if(o&&(!x||C)){if(!L){L=document.createElement("div"),L.className="magicx-aia-skeleton-bars",L.setAttribute("data-aia-skeleton-bars","");for(let v of Ls){let H=document.createElement("span");H.className="magicx-aia-skeleton-bar",H.style.width=`${v}px`,L.appendChild(H)}h.appendChild(L)}}else L&&L.remove();di(h,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image",n),En(t,!0);let V=h.querySelector(".magicx-aia-footer")??Hs(n),Z=i>=0&&!!r[i]?.is_tappable;Ns(V,mn(Z,e.isInputEmpty,n)),V.isConnected||h.appendChild(V),Ms(h,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"]),wi(t)}function Ms(t,e){let n=e.map(r=>t.querySelector(`:scope > ${r}`)).filter(r=>r!==null);for(let r=0;r<n.length;r++)t.children[r]!==n[r]&&t.insertBefore(n[r],t.children[r]??null)}var Ds={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function _s(t,e,n,r,i,s){Y(t,Ds,{onSkip:i,loading:n});let o=t.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent=s.skip,o.disabled=!0,t.appendChild(o),X(o)),o.textContent!==s.skip&&(o.textContent=s.skip),o.setAttribute("aria-label",r?`${s.skipLabel} ${r.text}`:s.skipLabel),o.disabled=n}function Ns(t,{key:e,hint:n}){let r=t.querySelector(".magicx-aia-footer-key"),i=t.querySelector(".magicx-aia-footer-hint");!r||!i||(r.textContent!==e&&(r.textContent=e),i.textContent!==n&&(i.textContent=n))}function Hs(t){let e=document.createElement("footer");e.className="magicx-aia-footer",e.setAttribute("data-aia-footer","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-row",n.setAttribute("data-align","center"),n.setAttribute("data-justify","between"),n.setAttribute("data-nowrap","");let r=document.createElement("div");r.className="aia-cluster magicx-aia-footer-hint-group",r.setAttribute("data-align","center"),r.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let s=document.createElement("span");s.className="magicx-aia-footer-hint",s.textContent=t.select,r.append(i,s);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=un(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let l=document.createElement("span");return l.className="magicx-aia-footer-badge",l.textContent="Autocomplete",o.append(a,l),n.append(r,o),e.append(n),e}function Ii(t,e){let n=St(e.listboxId);return t.appendChild(n),{dropdown:n}}function Dn(t,e,n){let r=Ie(e);yt(t.dropdown,{strings:n.strings,suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:$(e.editingIdentified.parameter),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:r.selectedIso,selectedDateRange:r.selectedRange,dateRangeStart:r.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(i,s)=>{s!==void 0&&n.store.get().activeDropdownIndex!==s||n.store.set({activeDropdownIndex:i})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:i=>n.store.set({isFocused:i})})}var Fs=6,Ws=.3;function Ci(t){return t<=0?"0px":`${(-Math.min(Ws,2*Fs/t)).toFixed(3)}px`}var Oi=new Map;function Bs(t,e,n){let r=Oi.get(e);if(r!==void 0){t.style.setProperty("--aia-chip-image-fit",r),t.setAttribute("data-aia-image-loaded","");return}let i=n.createElement("img");i.setAttribute("referrerpolicy","no-referrer"),i.onload=()=>{if(!t.isConnected)return;t.setAttribute("data-aia-image-loaded","");let s=t.getBoundingClientRect().height,o=Number.parseFloat(getComputedStyle(t).fontSize);if(!(s>0&&o>0&&i.naturalWidth>0&&i.naturalHeight>0))return;let a=`${(s/o*(i.naturalWidth/i.naturalHeight)).toFixed(3)}em`;Oi.set(e,a),t.style.setProperty("--aia-chip-image-fit",a)},i.src=e}function _n(t){let{input:e,segments:n,newParamId:r,editingParamId:i,placeholderText:s,isFocused:o}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,u=n.length===0;e.dataset.aiaEmpty=u?"true":"false",qr(e,u?s:"");let d=n.map(m=>m.type==="completed"?`${m.type}:${m.value}${a?m.param.icon??m.param.icon_svg??"":""}${l?ae(m.param.image_url)??"":""}`:`${m.type}:${m.value}`).join("\0"),c=e.dataset.segKey??"",f=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===c&&(r??"")===f&&(i??"")===p)return;if(d===c){e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";for(let m of e.querySelectorAll("strong[data-param-id]")){let h=m.dataset.paramId,y=m.dataset.seg==="completed"&&h===r;m.classList.toggle("magicx-aia-shimmer-revealed",y),m.classList.toggle("magicx-aia-shimmer-sweep",y),m.classList.toggle("magicx-aia-segment--editing",h===i)}return}let g=o?W(e):null;e.dataset.segKey=d,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let S=_(e),x=S.createDocumentFragment(),b=0;for(let m of n)if(b+=m.value.length,m.type==="completed"){let h=S.createElement("strong");h.dataset.seg="completed",h.dataset.paramId=m.param.id;let y=m.param.id===r,I=m.param.id===i,P=["magicx-aia-segment","magicx-aia-segment--completed"];y&&P.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),I&&P.push("magicx-aia-segment--editing"),h.className=P.join(" "),h.style.letterSpacing=Ci(m.value.length);let O=l?ae(m.param.image_url):null;if(O){let C=S.createElement("span");C.className="magicx-aia-segment-image",C.setAttribute("contenteditable","false"),C.setAttribute("aria-hidden","true"),C.style.setProperty("--aia-chip-image",`url("${O}")`),Bs(C,O,S),h.appendChild(C),h.dataset.aiaImage=""}let R=!O&&a&&m.param.icon_svg?se(m.param.icon_svg):null;if(R){let C=S.createElement("span");C.className="magicx-aia-segment-icon",C.setAttribute("contenteditable","false"),C.setAttribute("aria-hidden","true"),C.innerHTML=R,h.appendChild(C),m.param.icon&&(h.dataset.aiaIcon=m.param.icon)}h.appendChild(S.createTextNode(m.value)),x.appendChild(h)}else if(m.type==="identified"){let h=S.createElement("strong");h.dataset.seg="identified",h.dataset.paramId=m.param.id;let y=["magicx-aia-segment","magicx-aia-segment--completed"];m.param.id===i&&y.push("magicx-aia-segment--editing"),h.className=y.join(" "),h.style.letterSpacing=Ci(m.value.length),h.textContent=m.value,x.appendChild(h)}else x.appendChild(S.createTextNode(m.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(b),g!=null?N(e,Math.max(0,Math.min(g,b))):o&&Tr(e)&&N(e,b)}var Us='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ai(t=k()){let e=document.createElement("button");return e.type="button",e.className="magicx-aia-submit",e.setAttribute("aria-label",t.submit),e.setAttribute("data-aia-submit",""),e.innerHTML=Us.replace('aria-label="Submit"',`aria-label="${t.submit}"`),e}function $s(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function ki(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let r=n.getBoundingClientRect(),i=t.getBoundingClientRect();r.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Li(t,e){let{listboxId:n}=e,r=St(n);t.appendChild(r);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),t.appendChild(i);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),i.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",$s()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",n),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,u=null;e.submitButton===void 0?(l=Ai(e.strings),i.appendChild(l),u=l):e.submitButton!==null&&(u=e.submitButton,u.hasAttribute("data-aia-submit")||u.setAttribute("data-aia-submit",""),u.setAttribute("data-aia-submit-slot",""),i.appendChild(u));let d=new AbortController,{signal:c}=d,f=!1,p=0,g=()=>{let b=Qe(o),h=b.length>0&&b[0]!==b[0].toUpperCase()?b[0].toUpperCase()+b.slice(1):b;e.handleChange(h)},S=()=>{let b=j(o)?.node??null;if(!b||!o.contains(b))return null;let y=(b.nodeType===Node.ELEMENT_NODE?b:b.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&Pr(o,y)?null:y};if(i.addEventListener("click",b=>{b.target?.closest("[data-aia-pill]")||o.focus()},{signal:c}),o.addEventListener("input",()=>{f||(p=performance.now(),g(),e.handleCaretAfterInput(W(o)))},{signal:c}),_(o).addEventListener("selectionchange",()=>{let b=j(o);if(!b||!o.contains(b.node))return;let m=b.collapsed?S():null,h=e.store.get(),y=h.editingParam?.id??h.editingIdentified?.id??null;if(m&&m!==y){e.startEditingParam(m);return}performance.now()-p<50||e.handleCaretMove(W(o))},{signal:c}),o.addEventListener("click",b=>{let m=Gt(o,b.target);m&&(e.startEditingParam(m),Vt(o,m))},{signal:c}),o.addEventListener("compositionstart",()=>{f=!0,o.setAttribute("data-aia-composing","true")},{signal:c}),o.addEventListener("compositionend",()=>{f=!1,o.removeAttribute("data-aia-composing"),g()},{signal:c}),o.addEventListener("beforeinput",b=>{let m=b,h=m.inputType;if(h==="insertParagraph"||h==="insertLineBreak"||h==="insertFromDrop"){b.preventDefault();return}if(h.startsWith("insert")||h.startsWith("delete")){let y=h.startsWith("delete")?"":m.data??"";e.replaceEditingRange(y)&&b.preventDefault()}},{signal:c}),o.addEventListener("paste",b=>{b.preventDefault();let m=(b.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let h=_(o),y=qe(o);if(!y||!o.contains(y.startContainer))return;y.deleteContents();let I=h.createTextNode(m);y.insertNode(I),y.setStartAfter(I),ve(o,y.startContainer,y.startOffset),g()},{signal:c}),o.addEventListener("keydown",b=>e.handleKeyDown(b),{signal:c}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),u&&u.addEventListener("click",b=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;b.stopPropagation(),e.onSubmit(ie(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1){o.focus();let b=j(o);(!b||!o.contains(b.node))&&ve(o,o,0)}if(typeof ResizeObserver<"u"){let b=new ResizeObserver(()=>ki(o,a));b.observe(o),d.signal.addEventListener("abort",()=>b.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:r,submitButton:l,abort:d}}function Nn(t,e,n){let{input:r,inlinePillContainer:i,dropdown:s,submitButton:o}=t,{pillPlacement:a,setActivePill:l,selectOption:u,store:d}=n;r.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${n.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?r.setAttribute("aria-activedescendant",c):r.removeAttribute("aria-activedescendant"),o){let b=n.strings??k();o.getAttribute("aria-label")!==b.submit&&o.setAttribute("aria-label",b.submit);let m=o.querySelector("svg");m&&m.getAttribute("aria-label")!==b.submit&&m.setAttribute("aria-label",b.submit);let h=!!e.text||e.completedParams.length>0;o.disabled=!h}let f=r.dataset.newParamId??"",p=e.newParamId!==null&&e.newParamId!==f;if(_n({input:r,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,m=It(e.actionableSuggestions);b||m.length>0?dt(i,m,0,l,!1,b,e.isActivePillSelected):bn(i)}else bn(i);ki(r,i),p?(r.focus(),N(r,e.caretOffset??e.text.length)):e.isFocused&&Qe(r)!==e.text&&N(r,e.text.length);let g=e.editingParam?{parameter:e.editingParam.suggestionParameter,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{parameter:e.editingIdentified.parameter,text:$(e.editingIdentified.parameter),required:!0,options:[]}:null,S=e.dropdownSuggestion??g??e.actionableSuggestions[0],x=Ie(e);yt(s,{strings:n.strings,suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:g?[g]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:u,onHighlight:(b,m)=>{m!==void 0&&d.get().activeDropdownIndex!==m||d.set({activeDropdownIndex:b})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:b=>d.set({isFocused:b})})}function Hn(t){let e=t,n=new Set,r=[],i=!1;return{get:()=>e,set:s=>{let o=typeof s=="function"?s(e):s,a=e;if(e={...e,...o},r.push([e,a]),!i){i=!0;try{let l=0;for(let u=r.shift();u;u=r.shift()){if(++l>1e4)throw r.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[d,c]=u;for(let f of n)f(d,c)}}catch(l){throw r.length=0,l}finally{i=!1}}},subscribe:s=>(n.add(s),()=>{n.delete(s)})}}function Ri(t,e){let n,r,i=s=>(s!==n&&(n=s,r=e(s)),r);return{get:()=>{let s=t.get();return{...s,...i(s)}},set:s=>{typeof s=="function"?t.set(o=>{let a={...o,...i(o)};return s(a)}):t.set(s)},peek:s=>{let o={...t.get(),...s};return{...o,...e(o)}},subscribe:s=>t.subscribe((o,a)=>{let l={...a,...i(a)},u={...o,...i(o)};s(u,l)})}}var Fn=new WeakSet,Mi=new WeakMap;function _i(t){return t.nodeType===Node.DOCUMENT_NODE}function Gs(t){return _i(t)?t:t.ownerDocument}function Vs(t){let e=Mi.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let r=new n;return typeof r.replaceSync!="function"?null:(r.replaceSync(Hi),Mi.set(t,r),r)}catch{return null}}function Di(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Hi,e.appendChild(n)}function Ni(t){if(typeof document>"u")return;let e=t??document;if(Fn.has(e))return;let n=Gs(e);if(_i(e)){let s=e.head??e.documentElement;if(!s)return;Di(n,s),Fn.add(e);return}let r=Vs(n),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):Di(n,e),Fn.add(e)}var Hi=`.aia-stack {
1
+ function T(t){return t==="date"||t==="date-range"}function U(t){return t?.type?.kind==="date"?"date":t?.type?.kind==="date_range"?"date-range":"options"}var Le=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var qi="https://api.ai-autocomplete.com",K=`${qi}/api/suggest`,Re=new Map([["api.ai-autocomplete.com","cdn.ai-autocomplete.com"],["dev-api.ai-autocomplete.com","dev-cdn.ai-autocomplete.com"]]),Gn=new WeakMap;function he(t){return t?.type==="accessToken"}function Ki(t){if(!(!t||he(t)))return t}function Me(t){let e=Gn.get(t.getAccessToken);return e||(e=new Le(t),Gn.set(t.getAccessToken,e)),e}function De(t){return{"Content-Type":"application/json",...t?.appIdentifier&&{"X-App-Identifier":t.appIdentifier},...t?.headers}}function _e(t){let e=Ki(t),n=e?.apiKey;return n?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(n)}`:`Bearer ${n}`:null}function be(t){return t.map(e=>({parameter:e.parameter,text:e.text}))}var Vn="skipped";function Se(t,e){if(e.length===0)return t;let n=new Set(t.map(i=>i.parameter)),r=e.filter(i=>!n.has(i.parameter)).map(i=>({placeholder:"",parameter:i.parameter,text:Vn,kind:null}));return r.length>0?[...t,...r]:t}var zi="0.53.1",zn="1.0",qn=!1;function ji(t,e){return{placeholder:t.placeholder,parameter:t.parameter,...e&&{text:t.value??t.text},kind:t.kind}}function te(t){return t??(typeof navigator<"u"?navigator.language:"en-US")}function Yi(t,e,n,r,i,s,o,a,l,d,c,u){let f=e.find(m=>m.parameter==="contact"&&m.metadata?.contact_account_count)?.metadata?.contact_account_count,p=typeof f=="number"?f:void 0;return{data:{raw_query:t,accepts_traditional_autocomplete:!0,completed_params:Se(e.map(m=>ji(m,n)),l??[]),...o&&o.length>0&&{identified_params:be(o)},...a&&a.length>0&&{recently_suggested:a},...p!=null&&{contact_account_count:p},...d!==void 0&&{additional_context:d}},meta:{request_id:i,request_at:new Date().toISOString(),language:te(c),...u?.code&&Number.isFinite(u.rate)&&u.rate>0&&{currency:u.code,currency_rate:u.rate,...u.country!==void 0&&{country:u.country}},client_version:zi,session_id:r,source:s,schema_version:zn}}}async function Kn(t,e,n,r,i){return fetch(t,{method:"POST",headers:{...e,Authorization:`Bearer ${n}`},body:r,signal:i})}async function jn(t,e,n){let r=n.apiConfig,i=!n.maskCompletedText,s=Yi(t,e,i,n.sessionId,n.requestId??crypto.randomUUID(),n.source,n.identifiedParams,n.recentlySuggested,n.skippedParams,n.additionalContext,n.language,n.currency),o=De(r),a=r?.endpoint??K,l=JSON.stringify(s);if(he(r)){let u=Me(r),f=await u.getToken(),p=await Kn(a,o,f,l,n.signal);if(p.status===401){let m=await u.getToken(!0);p=await Kn(a,o,m,l,n.signal)}if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}let d=_e(r);!d&&!qn&&(qn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),d&&(o.Authorization=d);let c=await fetch(a,{method:"POST",headers:o,body:l,signal:n.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}var Ne=/[\p{L}\p{N}]/u,Qi=/['\u2019-]/;function Yn(t,e,n){let r=t[e];if(r===void 0)return!1;if(Ne.test(r))return!0;let i=t[e+n];return Qi.test(r)&&i!==void 0&&Ne.test(i)}function Xi(t,e,n){let r=e+n.length;return!(Ne.test(n[0])&&Yn(t,e-1,-1)||Ne.test(n[n.length-1])&&Yn(t,r,1))}function $(t,e,n=0,r=()=>!0){if(e.length===0)return t.indexOf(e,n);let i=-1,s=t.indexOf(e,n);for(;s!==-1;){if(r(s)){if(Xi(t,s,e))return s;i===-1&&(i=s)}s=t.indexOf(e,s+1)}return i}function D(t,e){let n=t,r={},i=[],s=[],o=0;for(let a of e){let l=(r[a.parameter]??0)+1;r[a.parameter]=l;let c=`{{${a.parameter.toUpperCase().replace(/\s+/g,"_")}_${l}}}`,u=p=>$(n,a.text,p,m=>!s.some(S=>m<S.end&&m+a.text.length>S.start)),f=u(o);if(f===-1&&(f=u(0)),f!==-1){n=n.slice(0,f)+c+n.slice(f+a.text.length);let p=c.length-a.text.length;for(let m of s)m.start>=f+a.text.length&&(m.start+=p,m.end+=p);s.push({start:f,end:f+c.length}),o=f>=o?f+c.length:o+p}i.push({...a,placeholder:c})}return{rawQuery:n,completedParams:i}}function z(t,e,n){return e>0||!n?e:t.toLowerCase().startsWith(n.toLowerCase())?n.length:e}function Fe(t,e,n){return e===0&&t.length>0&&n.length>0&&n.toLowerCase().startsWith(t.toLowerCase())}function ye(t,e,n){let r=t.slice(e);if(n||e===0||t[e-1]===" ")return r;let i=r.indexOf(" ");return i===-1?"":r.slice(i+1)}function Qn(t,e){let n=t.trimEnd().replace(/\s+/g," ");if(n.length===0||e.length===0)return 0;let r=n.split(" "),i=e.toLowerCase();for(let s=0;s<r.length;s++){let o=r.slice(s).join(" ");if(i.startsWith(o.toLowerCase())){let a=n.length-o.length;return t.length-a}}return 0}function Xn(t){return t.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase().replace(/[_\-\s]+/g," ")}function Ji(t,e){let n=Xn(t).trim();return n.startsWith(e)||n.includes(` ${e}`)}function ne(t,e,n=!1){if(!t)return[];let r=e.trimStart();if(!r)return t;let i=n?Xn(r).trimStart():"";if(i)return t.filter(o=>!o.is_tappable||Ji(o.text,i));let s=r.toLowerCase();return t.filter(o=>!o.is_tappable||o.text.toLowerCase().includes(s))}function He(t,e){if(!t)return null;let n=e.trim();if(!n)return null;let r=n.toLowerCase();return t.find(i=>i.is_tappable&&i.text.toLowerCase()===r)??null}function xe(t,e,n,r,i){let s=ye(e,n,r),o=He(t,s);if(o||!i||!s.trim())return o;if(s===e.slice(n))return null;let a=e.lastIndexOf(" ",n-1)+1;return He(t,e.slice(a))}function Jn(t,e){return e?t.map(n=>e[n.parameter]?{...n,options:[]}:n):t}function Zi(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function G(t){let e=Zi(t);return e.length>0?e.join(" "):t}function B(t,e){return t.parameter||e}function ve(t){return{parameter:t,suggestionParameter:t,suggestionValueType:{kind:"traditional_autocomplete"},suggestionPlaceholder:G(t)}}function We(t,e){let n=B(e,t.suggestionParameter);return t.suggestionValueType?.kind==="traditional_autocomplete"?ve(n):{parameter:n,suggestionParameter:t.suggestionParameter,suggestionValueType:t.suggestionValueType,suggestionPlaceholder:t.suggestionPlaceholder}}function E(t){return t?.type?.kind==="traditional_autocomplete"}function Zn(t){let e=t?.replace(/[_\-\s]+/g," ").trim();return e?e.charAt(0).toUpperCase()+e.slice(1):void 0}function Be(t){return E(t)||t?.smart_suggestion===!0}function It(t){return t.some(E)?t.filter(e=>!E(e)):t}function Ct(t,e){return t.some(n=>E(n)&&!n.text)?t.map(n=>E(n)&&!n.text?{...n,text:e}:n):t}var Ot='<svg viewBox="0 0 20 20" width="1em" height="1em" fill="currentColor" aria-hidden="true" focusable="false"><path class="aia-sparkle-large" d="M8 5C8.5 9.5 10.5 11.5 15 12C10.5 12.5 8.5 14.5 8 19C7.5 14.5 5.5 12.5 1 12C5.5 11.5 7.5 9.5 8 5Z"/><path class="aia-sparkle-small" d="M16 1C16.2 3 17 3.8 19 4C17 4.2 16.2 5 16 7C15.8 5 15 4.2 13 4C15 3.8 15.8 3 16 1Z"/></svg>';function At(t){return t.some(e=>!E(e))}function er(t,e){let n=0,r=e;for(let i of t)n+=i.value.length,i.type!=="text"&&(r=Math.max(r,n));return r}function tr(t,e){let n=0;for(let r of t){let i=n+r.value.length;if(r.type==="text"&&i>e&&r.value.slice(Math.max(e-n,0)).trim().length>0)return!1;n=i}return!0}function nr(t,e){let n=[],r=new Set;for(let i of[...t,...e])i.parameter==="placeholder"||E(i)||r.has(i.parameter)||(r.add(i.parameter),n.push({parameter:i.parameter,text:i.text}));return n}function rr(t,e,n){if(t===e)return n;let r=Math.min(t.length,e.length),i=0;for(;i<r&&t[i]===e[i];)i++;if(i>=n)return n;let s=0;for(;s<r-i&&t[t.length-1-s]===e[e.length-1-s];)s++;return t.length-s<=n?n+(e.length-t.length):null}function Ue(t,e){let n=[],r=[],i=0;for(let s of e){let o=$(t,s.text,i);if(o===-1){r.push(s);continue}n.push({start:o,end:o+s.text.length,param:s}),i=o+s.text.length}return{located:n,missing:r}}function le(t,e){let{located:n}=Ue(t,e);return n.length>0?n[n.length-1].end:0}function ir(t,e,n){let r=[],i=[],s=0;for(let o of n){let a=$(t,o.text,s,l=>!e.some(d=>l<d.end&&l+o.text.length>d.start));if(a===-1){i.push(o);continue}r.push({start:a,end:a+o.text.length,param:o}),s=a+o.text.length}return{located:r,missing:i}}function or(t,e,n=[]){let r=Ue(t,e).located,i=ir(t,r,n).located,s=[...r.map(d=>({start:d.start,end:d.end,segment:{type:"completed",value:d.param.text,param:d.param}})),...i.map(d=>({start:d.start,end:d.end,segment:{type:"identified",value:d.param.text,param:d.param}}))].sort((d,c)=>d.start-c.start),o=[],a=0;for(let d of s)d.start>a&&o.push({type:"text",value:t.slice(a,d.start)}),o.push(d.segment),a=d.end;let l=t.slice(a);return l&&o.push({type:"text",value:l}),o}function sr(t,e){let{located:n,missing:r}=Ue(t,e);return{valid:n.map(i=>i.param),invalid:r}}function Pe(t,e,n){let r=Ue(t,e).located,{located:i,missing:s}=ir(t,r,n);return{valid:i.map(o=>o.param),invalid:s}}function ar(t,e,n){let r=e?.endpoint??K,i=r.replace(/\/suggest(?=[?#]|$)/,`/starting-state/${encodeURIComponent(t)}${eo(n)}`);if(i!==r)return i.replace(/^https:\/\/([^/?#]+)/,(s,o)=>{let a=Re.get(o);return a?`https://${a}`:s})}function eo(t){let e=t?.replace(/_/g,"-").toLowerCase()??"",[n,r=""]=e.split("-");return n!=="zh"?/^[a-z]{2,3}$/.test(n)?`/${n}`:"":/^[a-z]{4}$/.test(r)?r==="hant"?"/zh-TW":"/zh":["tw","hk","mo"].includes(r)?"/zh-TW":"/zh"}async function lr(t){try{let e=await t;if(!e.ok)return null;let n=await e.json();return Array.isArray(n?.data?.suggestions)?n:null}catch{return null}}function to(t){if(t instanceof Error)return t;try{return new Error(String(t))}catch{return new Error("Unknown error")}}var no=100,ro=300,io=2,$e=class{constructor(e,n,r,i,s,o,a,l,d,c={}){this.store=e;this.getApiConfig=n;this.getOptionOverrides=r;this.getMaskCompletedText=i;this.getOnError=s;this.getSessionId=o;this.getSource=a;this.getAdditionalContext=l;this.getLanguage=d;this.callbacks=c;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null;this.phraseExactMatch=!1}start(){this.doFetch("",[]);let e=this.store.get().text,n=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(r=>{(r.text!==e||r.completedParams!==n)&&(e=r.text,n=r.completedParams,this.scheduleFetch())})}isPhraseExactMatch(){return this.phraseExactMatch}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,n){this.abortController?.abort();let r=new AbortController;this.abortController=r;let i=++this.fetchVersion,s=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:r.signal,isCurrent:()=>i===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let o=this.store.get(),a=o.pendingSpan?nr(o.pendingSpan.snapshot,o.actionableSuggestions):void 0,l=crypto.randomUUID(),d=e===""&&n.length===0&&o.skippedParams.length===0&&o.identifiedParams.length===0?this.startingStateUrl():void 0,c=d?await lr(fetch(d,{signal:r.signal})):null;if(i!==this.fetchVersion)return;let u=c??await jn(e,n,{sessionId:this.getSessionId(),requestId:l,source:this.getSource(),maskCompletedText:this.getMaskCompletedText(),signal:r.signal,apiConfig:this.getApiConfig(),identifiedParams:o.identifiedParams,recentlySuggested:a,skippedParams:o.skippedParams,additionalContext:this.getAdditionalContext(),language:this.getLanguage(),currency:this.callbacks.getCurrency?.()});if(i!==this.fetchVersion)return;this.phraseExactMatch=u.meta?.phrase_exact_match===!0;let f=(u.data.suggestions??[]).find(E),p=f?[]:u.data.input??[],m=p.filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),parameter:v.parameter,text:v.text,...v.type?{type:v.type}:{}})),S=this.callbacks.isWordOpen?.()??!1,x=this.store.get().text.toLowerCase(),h=v=>S&&x.endsWith(v.text.toLowerCase()),g=m.filter(v=>!h(v));S&&this.callbacks.holdIdentified?.(m.filter(h));let b=f?[f]:Jn(u.data.suggestions??[],this.getOptionOverrides()),y=p,I=y[y.length-1],P=this.store.get().text,O,R;if(I?.state==="in_progress"){R=!0;let v=P.toLowerCase().lastIndexOf(I.text.toLowerCase());O=v!==-1?v:s}else R=!1,O=s;let A=b.filter(v=>v.parameter!=="placeholder")[0],L=null;if(A&&!E(A)&&!S&&!T(U(A))){let v=xe(A.options,P,O,R,this.phraseExactMatch);v&&(L={id:crypto.randomUUID(),placeholder:"",parameter:B(v,A.parameter),text:v.text,value:v.value,kind:v.kind,suggestionParameter:A.parameter,suggestionValueType:A.type,suggestionPlaceholder:A.text,options:A.options??[],metadata:v.metadata,icon:v.icon,icon_svg:v.icon_svg,image_url:v.image_url},b=b.filter(H=>H!==A),this.callbacks.onAutoMatch?.({active:A,matched:v,rawQuery:e}))}let q=u.data.custom_fields??null,Z=this.callbacks.productsForResponse?.(q);this.store.set(v=>{let H=L?[...v.completedParams,L]:v.completedParams,Et=Pe(v.text,H,g).valid,wt=new Set(o.skippedParams.map(M=>M.id)),w=new Set(v.skippedParams.filter(M=>!wt.has(M.id)).map(M=>M.parameter));return{suggestions:w.size>0?b.filter(M=>M.parameter==="placeholder"||!w.has(M.parameter)):b,isLoading:!1,isReady:u.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:O,filterInProgress:R,identifiedParams:Et,customFields:q,traditionalAutocomplete:u.meta?.traditional_autocomplete===!0,...Z!==void 0?{products:Z}:{},...L?{completedParams:H}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:u.meta?.funnel_telemetry===!0,visibleImpression:u.meta?.visible_impression===!0})}catch(o){let a=to(o);i===this.fetchVersion&&(this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a))}finally{if(i===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}startingStateUrl(){let e=this.callbacks.getProductId?.();return e?ar(e,this.getApiConfig(),te(this.getLanguage())):void 0}attemptNow(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.attemptFetch(1,!0)}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}this.debounceTimer=setTimeout(()=>{this.attemptFetch(io)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},no),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1,!0,!0),ro)}attemptFetch(e,n=!1,r=!1){let i=this.store.get();if(!i.text&&i.completedParams.length===0)return this.doFetch("",[]),!0;let s=this.callbacks.consumerTick?.(i,e)??"no";if(s==="asked")return!0;if(s==="owns")return!1;let o=i.suggestions.filter(P=>P.parameter==="placeholder").map(P=>P.text).join(" "),a=z(i.text,i.filterBase,o),l=ye(i.text,a,i.filterInProgress),d=i.suggestions.filter(P=>P.parameter!=="placeholder"),c=E(d[0])?void 0:d[0],u=T(i.activeFormatType),p=(c&&!u?ne(c.options,l,i.traditionalAutocomplete):[]).filter(P=>P.is_tappable),m=c&&!u&&!this.callbacks.isWordOpen?.()?xe(c.options,i.text,a,i.filterInProgress,this.phraseExactMatch)!==null:!1,S=l.trim().length>0,x=r&&i.products.length>0;if(p.length>0&&!m&&S&&!x||Fe(i.text,i.completedParams.length,o))return!1;let{rawQuery:h,completedParams:g}=D(i.text,i.completedParams),b=h.length<i.lastRawQuery.length,y=Math.abs(h.length-i.lastRawQuery.length),I=n&&h!==i.lastRawQuery;return b||y>=e||I?(this.doFetch(h,g),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var oo="(hover: none) and (pointer: coarse)";var so="[data-aia-dropdown], [data-aia-input-wrapper]",ao=["a[href]","button","input","select","textarea","label","summary","[contenteditable]:not([contenteditable='false'])","[role='button']","[role='link']","[tabindex]:not([tabindex='-1'])"].join(", "),Ge=class{constructor(e,n){this.store=e;this.container=n;this.listening=!1;this.declined=!1;this.pressOutside=!1;this.pressWhileFocused=!1;this.recheckTimer=null;this.releaseTimer=null;this.onPointerDown=e=>{let n=e.composedPath(),r=this.isInside(n);this.pressOutside=!r;let i=this.store.get();this.pressWhileFocused=i.isFocused,!(r||!i.isFocused)&&(this.declined=n.some(s=>s instanceof Element&&s.matches(ao)),this.declined&&i.dropdownHeld?this.store.set({dropdownHeld:!1}):!this.declined&&!i.dropdownHeld&&i.isDropdownOpen&&this.store.set({dropdownHeld:!0}))};this.onPointerCancel=()=>{this.pressOutside=!1,this.pressWhileFocused&&this.declined&&this.scheduleRecheck(),this.pressWhileFocused=!1};this.onPointerUp=e=>{let n=this.pressOutside&&!this.isInside(e.composedPath()),r=this.pressWhileFocused;if(this.pressOutside=!1,this.pressWhileFocused=!1,r){this.declined&&this.scheduleRecheck();return}!n||this.store.get().isFocused||(this.cancelRelease(),this.releaseTimer=setTimeout(()=>{this.releaseTimer=null;let i=this.store.get();i.dropdownHeld&&!i.isFocused&&this.store.set({dropdownHeld:!1})},150))};this.touchPrimary=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia(oo):null,this.unsubscribe=e.subscribe(()=>this.sync())}dispose(){this.unsubscribe(),this.listen(!1),this.cancelRelease(),this.recheckTimer!==null&&clearTimeout(this.recheckTimer),this.recheckTimer=null}sync(){let e=this.store.get(),n=this.touchPrimary?.matches??!1;e.isFocused||(this.declined=!1),e.isDropdownOpen?e.isFocused&&!e.dropdownHeld&&!this.declined&&n&&this.store.set({dropdownHeld:!0}):e.dropdownHeld&&this.store.set({dropdownHeld:!1});let r=this.store.get();this.listen(n&&r.isDropdownOpen),r.isFocused&&this.cancelRelease()}listen(e){if(!(e===this.listening||typeof document>"u")){if(this.listening=e,e){document.addEventListener("pointerdown",this.onPointerDown,!0),document.addEventListener("pointerup",this.onPointerUp,!0),document.addEventListener("pointercancel",this.onPointerCancel,!0);return}document.removeEventListener("pointerdown",this.onPointerDown,!0),document.removeEventListener("pointerup",this.onPointerUp,!0),document.removeEventListener("pointercancel",this.onPointerCancel,!0),this.pressOutside=!1}}scheduleRecheck(){this.recheckTimer!==null&&clearTimeout(this.recheckTimer),this.recheckTimer=setTimeout(()=>{this.recheckTimer=null,!(!this.declined||!this.store.get().isFocused)&&(this.declined=!1,this.sync())},150)}cancelRelease(){this.releaseTimer!==null&&(clearTimeout(this.releaseTimer),this.releaseTimer=null)}isInside(e){let n=this.container,r=n?.getRootNode(),i=typeof ShadowRoot<"u"&&r instanceof ShadowRoot?r.host:null;for(let s of e)if(s===n||s===i||s instanceof Element&&s.matches(so))return!0;return!1}};var ce=["January","February","March","April","May","June","July","August","September","October","November","December"],Ve=["S","M","T","W","T","F","S"],ur=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],pr="aiaDate",mr="aiaDay",cr=t=>String(t).padStart(2,"0");function F(t){return`${t.getFullYear()}-${cr(t.getMonth()+1)}-${cr(t.getDate())}`}function kt(t){return new Date(t.getFullYear(),t.getMonth(),t.getDate())}function lo(t){let e=kt(t).getTime()-kt(new Date).getTime();return Math.round(e/864e5)}function gr(t){let e=lo(t);return e>=0&&e<7?ur[t.getDay()]:de(t)}function de(t){return t.getFullYear()===new Date().getFullYear()?`${ce[t.getMonth()]} ${t.getDate()}`:`${ce[t.getMonth()]} ${t.getDate()} ${t.getFullYear()}`}function qe(t){if(!t)return null;let e=ur.findIndex(a=>a.toLowerCase()===t.trim().toLowerCase());if(e>=0){let a=kt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let n=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(t);if(!n)return null;let r=ce.findIndex(a=>a.toLowerCase()===n[1].toLowerCase());if(r<0)return null;let i=Number(n[2]),s=n[3]?Number(n[3]):new Date().getFullYear(),o=new Date(s,r,i);return o.getMonth()!==r||o.getDate()!==i?null:o}function Lt(t){return`${ce[t.month]} ${t.year}`}function Rt(){let t=new Date;return{year:t.getFullYear(),month:t.getMonth()}}function fr(t){return{year:t.getFullYear(),month:t.getMonth()}}function Mt(t,e){let n=new Date(t.year,t.month+e,1);return{year:n.getFullYear(),month:n.getMonth()}}function dr(){return{text:"",is_tappable:!1,kind:null}}function Dt(t){let e=new Date(t.year,t.month,1).getDay(),n=new Date(t.year,t.month+1,0).getDate(),r=[];for(let i=0;i<e;i++)r.push(dr());for(let i=1;i<=n;i++){let s=new Date(t.year,t.month,i);r.push({text:gr(s),is_tappable:!0,kind:null,metadata:{[pr]:F(s),[mr]:i}})}for(;r.length%Ve.length!==0;)r.push(dr());return r}function _t(t){let e=qe(t);return e?F(e):null}function V(t){let e=t?.metadata?.[pr];return typeof e=="string"?e:null}function Nt(t){let e=t?.metadata?.[mr];return typeof e=="number"?e:null}function co(t){return t.nodeType===Node.DOCUMENT_NODE?!0:t.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in t}function re(t){let e=typeof t.getRootNode=="function"?t.getRootNode():null;return e&&co(e)?e:t.ownerDocument??t}function _(t){return t.ownerDocument??t}function uo(t){return t.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function hr(t){let e=re(t);return!uo(e)||typeof e.getSelection=="function"?null:e}function br(t){let e=hr(t);if(!e)return null;let n=_(t).getSelection?.();return!n||typeof n.getComposedRanges!="function"?null:e}function Sr(t,e){let n=t,r;try{r=n.getComposedRanges({shadowRoots:[e]})}catch{r=n.getComposedRanges(e)}return r.length>0?r[0]:null}function Ht(t){let n=re(t).getSelection?.();return n||(_(t).getSelection?.()??null)}function j(t){let e=Ht(t);if(!e||e.rangeCount===0)return null;let n=br(t);if(n){let r=Sr(e,n);return r?{node:r.startContainer,offset:r.startOffset,collapsed:r.startContainer===r.endContainer&&r.startOffset===r.endOffset}:null}return e.anchorNode?{node:e.anchorNode,offset:e.anchorOffset,collapsed:e.isCollapsed}:null}function Ke(t){let e=Ht(t);if(!e||e.rangeCount===0)return null;let n=br(t);if(!n)return e.getRangeAt(0);let r=Sr(e,n);if(!r)return null;let i=_(t).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function Te(t,e,n){let r=Ht(t);if(!r)return null;if(hr(t))return r.collapse(e,n),r;let i=_(t).createRange();return i.setStart(e,n),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function ze(t,e){let n=t?re(t):typeof document<"u"?document:null;return n?typeof n.getElementById=="function"?n.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var je=2,po="magicx-aia";function yr(t){return t==="auto"||t==="scroll"||t==="hidden"||t==="overlay"}function mo(t){let e=_(t),n=e.defaultView;if(!n?.getComputedStyle)return null;let r=t;for(;r&&r!==e.body&&r!==e.documentElement;){let i=r.scrollWidth>r.clientWidth,s=r.scrollHeight>r.clientHeight;if(i||s){let o=n.getComputedStyle(r);if(i&&yr(o.overflowX)||s&&yr(o.overflowY))return r}if(r.classList.contains(po))return null;r=r.parentElement}return null}function Ft(t){let e=Ke(t);if(!e||!e.collapsed||!t.contains(e.startContainer))return;let n=mo(t);if(!n||typeof e.getBoundingClientRect!="function")return;let r=e.getBoundingClientRect();if(r.height===0)return;let i=n.getBoundingClientRect();if(n.scrollWidth>n.clientWidth){let s=i.left+n.clientLeft,o=s+n.clientWidth;r.right>o?n.scrollLeft+=r.right-o+je:r.left<s&&(n.scrollLeft-=s-r.left+je)}if(n.scrollHeight>n.clientHeight){let s=i.top+n.clientTop,o=s+n.clientHeight;r.bottom>o?n.scrollTop+=r.bottom-o+je:r.top<s&&(n.scrollTop-=s-r.top+je)}}var vr='[contenteditable="false"]',Bt="strong[data-param-id]",ue;function go(){if(ue!==void 0)return ue;let t=globalThis.Intl.Segmenter;if(!t)return ue=null,null;try{ue=new t(void 0,{granularity:"grapheme"})}catch{ue=null}return ue??null}function Ye(t,e){let n=t;for(;n&&n!==e;){if(n.nodeType===Node.ELEMENT_NODE&&n.matches(vr))return!0;n=n.parentNode}return!1}function Qe(t){return _(t).createTreeWalker(t,NodeFilter.SHOW_TEXT,{acceptNode(e){return Ye(e,t)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Xe(t){let e=Qe(t),n="",r=e.nextNode();for(;r;)n+=r.data,r=e.nextNode();return n}function Ut(t){let e=Qe(t),n=0,r=e.nextNode();for(;r;)n+=r.data.length,r=e.nextNode();return n}function W(t){let e=j(t);if(!e)return null;let n=e.node,r=e.offset;if(!t.contains(n))return null;if(n.nodeType===Node.ELEMENT_NODE){let i=n;if(Ye(i,t)&&i!==t)return null;let s=0;for(let o=0;o<r&&o<i.childNodes.length;o++)s+=$t(i.childNodes[o],t);return s+Wt(i,t)}return n.nodeType!==Node.TEXT_NODE||Ye(n,t)?null:Wt(n,t)+r}function $t(t,e){if(t.nodeType===Node.TEXT_NODE)return Ye(t,e)?0:t.data.length;if(t.nodeType!==Node.ELEMENT_NODE)return 0;let n=t;if(n.matches(vr))return 0;let r=0;for(let i of Array.from(n.childNodes))r+=$t(i,e);return r}function Wt(t,e){let n=Qe(e),r=0,i=n.nextNode();for(;i;){if(i===t||t.nodeType===Node.ELEMENT_NODE&&t.contains(i))return r;r+=i.data.length,i=n.nextNode()}return r}function N(t,e){let n=_(t),r=Math.max(0,Math.min(e,Ut(t))),i=Qe(t),s=0,o=null,a=0,l=i.nextNode(),d=null;for(;l;){let u=l.data.length;if(r<s+u){o=l,a=r-s;break}if(r===s+u){let f=i.nextNode();f?(o=f,a=0):(o=l,a=u);break}s+=u,d=l,l=i.nextNode()}let c=n.createRange();if(o){let u=o.parentElement?.closest('strong[data-seg="completed"]');u&&u!==t&&t.contains(u)?a===0?c.setStartBefore(u):a===o.data.length?c.setStartAfter(u):c.setStart(o,a):c.setStart(o,a)}else d?c.setStart(d,d.data.length):c.setStart(t,0);c.collapse(!0),Te(t,c.startContainer,c.startOffset)&&(fo(t,c,r),Ft(t))}function xr(t,e){if(!t||!e.contains(t))return null;let r=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(Bt)??null;return r&&e.contains(r)?r:null}function fo(t,e,n){let r=xr(j(t)?.node??null,t);if(r&&r!==xr(e.startContainer,t)){t.dataset.aiaCaretEscapedChip=`${n}:${r.dataset.paramId}`;return}delete t.dataset.aiaCaretEscapedChip}function Pr(t,e){let n=t.dataset.aiaCaretEscapedChip;if(!n)return!1;let r=W(t);return r!==null&&n===`${r}:${e}`}function Tr(t){return re(t).activeElement===t}function Gt(t,e){if(!e||e.nodeType===void 0)return null;let n=e,i=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Bt);if(!i||!t.contains(i))return null;let s=j(t);return s&&!s.collapsed?null:i.dataset.paramId??null}function Vt(t,e){let n=null;for(let o of t.querySelectorAll(Bt))if(o.dataset.paramId===e){n=o;break}if(!n)return;let r=Wt(n,t),i=r+$t(n,t),s=W(t);s!=null&&s>=r&&s<=i||N(t,r)}function qt(t){let e=W(t);return e==null?!1:e>=Ut(t)}function Kt(t,e){if(e<=0)return 0;let n=go();if(!n)return e-1;let r=t.slice(0,e),i=0;for(let{index:s}of n.segment(r))s<e&&(i=s);return i}function ie(t,e,n=[],r={}){let{rawQuery:i,completedParams:s}=D(t,e);return{query:t.trim(),raw_query:i,completed_params:Se(s,n),identified_params:be(r.identifiedParams??[]),is_ready:r.isReady??!1,...r.customFields?{custom_fields:r.customFields}:{}}}function zt(t,e){return t instanceof HTMLTextAreaElement||t instanceof HTMLInputElement?t.selectionStart!=null&&t.selectionStart===t.value.length:t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?qt(t):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function jt(t){return t instanceof HTMLElement&&t.hasAttribute("data-aia-input")?W(t):null}var Je=class{constructor(e,n){this.store=e;this.ctx=n}handleKeyDown(e){if(e.isComposing||e.keyCode===229)return;let n=this.store.get(),{listboxId:r,getOnSubmit:i}=this.ctx,s=e.target instanceof Node?e.target:null,o=this.getEffectiveColumns(s),a=i(),l=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let c=zt(e.target,n),u=!!n.editingParam;if(!c&&!u&&n.activeDropdownIndex<0)break;if(n.activeDropdownIndex<0){if(d)break;e.preventDefault();let m=T(n.activeFormatType)?this.dateEntryIndex(n,!1):l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:m});break}if(l.length===0)return;this.store.set({activeDropdownIndex:m});break}if(e.preventDefault(),l.length===0)return;if(T(n.activeFormatType)){this.stepDateWeek(n,7);break}if(n.filteredOptions.length>0){let m=Math.floor((n.filteredOptions.length-1)/o);if(Math.floor(n.activeDropdownIndex/o)===m){this.store.set({activeDropdownIndex:-1});break}}let f=l.indexOf(n.activeDropdownIndex),p=f<l.length-1?f+1:0;this.store.set({activeDropdownIndex:l[p]});break}case"ArrowUp":{if(n.activeDropdownIndex<0){if(!d)break;let f=zt(e.target,n),p=!!n.editingParam;if(!f&&!p)break;e.preventDefault();let m=T(n.activeFormatType)?this.dateEntryIndex(n,!0):this.firstTappableInBottomRow(o)??l[0]??0;if(!n.isDropdownOpen&&n.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:m});break}if(l.length===0)return;this.store.set({activeDropdownIndex:m});break}if(l.length===0)break;if(e.preventDefault(),T(n.activeFormatType)){this.stepDateWeek(n,-7);break}if(n.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let c=l.indexOf(n.activeDropdownIndex),u=c>0?c-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),T(n.activeFormatType)){this.stepDateDay(n,1);break}if(n.activeDropdownIndex%o<o-1){let f=n.activeDropdownIndex+1;f<n.filteredOptions.length&&n.filteredOptions[f]?.is_tappable&&this.store.set({activeDropdownIndex:f})}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,f=n.editingTail;this.ctx.exitEditMode?.(),N(u,f);break}zt(e.target,n)&&n.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(n.activeDropdownIndex>=0){if(e.preventDefault(),T(n.activeFormatType)){this.stepDateDay(n,-1);break}if(n.activeDropdownIndex%o>0){let c=n.activeDropdownIndex-1;c>=0&&n.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c});break}if(!n.editingParam&&this.ctx.startEditingParamAtCaret){let c=jt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)}break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingAnchor!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingAnchor;this.ctx.exitEditMode?.(),N(c,u);break}if(this.ctx.startEditingParamAtCaret){let c=jt(e.target);c!=null&&this.ctx.startEditingParamAtCaret(c)&&e.preventDefault()}break}case"Backspace":{if(n.editingParam||!this.ctx.removeParamAtCaret)break;let c=jt(e.target);if(c==null)break;this.ctx.removeParamAtCaret(c)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),n.activeDropdownIndex>=0&&n.filteredOptions[n.activeDropdownIndex]?.is_tappable)this.clickOrSelect(n.activeDropdownIndex,n.filteredOptions,r,s);else if(a){this.ctx.endTypedWord?.(!0);let c=this.store.get();a(ie(c.text,c.completedParams,c.skippedParams,{identifiedParams:c.identifiedParams,isReady:c.isReady,customFields:c.customFields}))&&this.ctx.afterSubmit?.()}break}case"Tab":{if(this.ctx.endTypedWord?.()){e.preventDefault();break}let c=n.filteredOptions.map((p,m)=>p.is_tappable?m:-1).filter(p=>p!==-1);if(c.length===0)break;if(!n.isDropdownOpen){if(n.actionableSuggestions.length===0)break;e.preventDefault();let p=e.shiftKey?c[c.length-1]:c[0];this.store.set({pillTapped:!0,activeDropdownIndex:p});break}e.preventDefault();let u=c.indexOf(n.activeDropdownIndex),f;if(u<0)f=e.shiftKey?c.length-1:0;else{let p=e.shiftKey?-1:1;f=(u+p+c.length)%c.length}this.store.set({activeDropdownIndex:c[f]});break}case"Escape":{if(n.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(n.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(n.editingParam&&e.target instanceof HTMLElement&&n.editingTail!=null){let c=e.target.closest("[data-aia-input]")??e.target,u=n.editingTail;this.ctx.exitEditMode?.(),N(c,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let n=this.store.get();if(n.filteredOptions.length===0)return null;let i=Math.floor((n.filteredOptions.length-1)/e)*e;for(let s=i;s<n.filteredOptions.length;s++)if(n.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,n){let r=F(new Date),i=e.filteredOptions.findIndex(o=>V(o)===r);if(i>=0)return i;let s=e.filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1);return(n?s[s.length-1]:s[0])??0}stepDateDay(e,n){for(let r=e.activeDropdownIndex+n;r>=0&&r<e.filteredOptions.length;r+=n)if(e.filteredOptions[r]?.is_tappable){this.store.set({activeDropdownIndex:r});return}}stepDateWeek(e,n){let r=e.activeDropdownIndex+n;this.store.set({activeDropdownIndex:e.filteredOptions[r]?.is_tappable?r:-1})}getTappableIndices(e){let r=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),i=Array.from({length:e},()=>[]);for(let s of r)i[s%e].push(s);return i.flat()}getEffectiveColumns(e){let n=ze(e,this.ctx.listboxId);if(!n)return this.ctx.columns;let i=ze(e,`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let s=getComputedStyle(i).gridTemplateColumns;if(s&&s!=="none"){let o=s.split(" ").filter(Boolean).length;if(o>0)return o}if(i===n)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,n,r,i){let s=ze(i,`${r}-option-${e}`);s?s.click():this.ctx.selectOption(n[e])}};var Ze=class{constructor(e,n,r={}){this.store=e;this.getOverrides=n;this.callbacks=r;this.unsubscribe=null;this.current=null;this.version=0;this.lastMiss=null;this.hasLoggedError=!1}start(){this.unsubscribe=this.store.subscribe(e=>this.sync(e)),this.sync(this.store.get())}dispose(){this.unsubscribe?.(),this.unsubscribe=null,this.cancel(),this.current=null}reset(){this.cancel(),this.current=null,this.lastMiss=null}refresh(){this.reset(),this.sync(this.store.get())}hasOverride(e){return!!this.getOverrides()?.[e]}owns(e,n){return this.hasOverride(e)&&!this.missCovers(e,n)}tick(e,n){let r=this.resolveTarget(e);if(!r||this.missCovers(r.parameter,r.query))return"no";let i=this.current;if(i&&i.key===r.key){if(i.query===r.query)return"owns";let s=Math.abs(r.query.length-i.query.length),o=r.query.length<i.query.length;if(n>1&&!o&&s<n)return"owns"}return this.ask(r),"asked"}sync(e){let n=this.resolveTarget(e);if(!n){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===n.key||this.ask(n)}resolveTarget(e){if(T(e.activeFormatType)||e.editingIdentified)return null;let n=e.editingParam;if(n&&e.editingAnchor!=null)return this.hasOverride(n.suggestionParameter)?{mode:"edit",key:n.id,parameter:n.suggestionParameter,suggestion:{parameter:n.suggestionParameter,text:n.suggestionPlaceholder,required:!0,options:n.options},query:e.optionQuery}:null;let r=e.actionableSuggestions[0];return!r||!this.hasOverride(r.parameter)?null:{mode:"pill",key:r,parameter:r.parameter,suggestion:r,query:e.optionQuery}}missCovers(e,n){return this.lastMiss!=null&&this.lastMiss.parameter===e&&this.lastMiss.query===n}ask(e){this.cancel();let n=this.getOverrides()?.[e.parameter],r=++this.version;if(!n||this.missCovers(e.parameter,e.query)){this.current={key:e.key,parameter:e.parameter,query:e.query,abort:null},this.setSearch(e,"done");return}let i=new AbortController;this.current={key:e.key,parameter:e.parameter,query:e.query,abort:i};let s;try{s=n(e.query,i.signal,e.suggestion)}catch(o){this.logOnce(o),this.commit(e,[],r);return}if(Array.isArray(s)){this.commit(e,s,r);return}this.setSearch(e,"loading"),this.await(e,s,i.signal,r)}async await(e,n,r,i){let s;try{let o=await n;if(r.aborted||i!==this.version)return;s=Array.isArray(o)?o:[]}catch(o){if(r.aborted||i!==this.version||ho(o))return;this.logOnce(o),s=[]}this.commit(e,s,i)}commit(e,n,r){if(r!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;n.length===0?this.lastMiss={parameter:e.parameter,query:e.query}:this.lastMiss?.parameter===e.parameter&&(this.lastMiss=null);let s={parameter:e.parameter,query:e.query,status:"done"};if(e.mode==="edit")this.store.set(o=>({editingParam:o.editingParam&&o.editingParam.id===e.key?{...o.editingParam,options:n}:o.editingParam,optionSearch:s}));else{let o={...e.suggestion,options:n};this.current&&this.current.key===e.key&&(this.current.key=o),this.store.set(a=>({suggestions:a.suggestions.map(l=>l===e.suggestion?o:l),optionSearch:s}))}n.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,n){let r=this.store.get().optionSearch;r&&r.parameter===e.parameter&&r.query===e.query&&r.status===n||this.store.set({optionSearch:{parameter:e.parameter,query:e.query,status:n}})}cancel(){this.current?.abort?.abort(),this.version++}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] an optionOverrides entry threw or rejected \u2014 treated as no options. Later failures on this instance are not logged.",e))}};function ho(t){return t instanceof Error&&t.name==="AbortError"}var et=class{constructor(e,n={}){this.store=e;this.callbacks=n}setActivePill(e){let n=this.store.get(),r=n.suggestions.filter(d=>d.parameter!=="placeholder");if(e<0||e>=r.length)return;let i=r[e];if(E(i))return;let s=r.filter((d,c)=>c!==e),o=n.suggestions.filter(d=>d.parameter==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:d}=D(n.text,n.completedParams);this.callbacks.onPillSelected({rawQuery:d,selectedPill:i.text,otherPills:s.map(c=>c.text)})}let a=[...o,i,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(d=>d.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(n=>({completedParams:n.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var wr="/products/",Er="https://relative.invalid";function bo(t){if(!t)return;let e;try{e=new URL(t,`${Er}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return t.startsWith("/")?e.origin===Er?t:void 0:/^https?:\/\//i.test(t)?t:void 0}function Ir(t,e){let n=bo(t.item_url)??yo(t);return{id:t.source_id,title:t.title,...n&&{url:n},imageUrl:t.image_url||null,...t.price&&{price:So(t.price,t.currency,e)},...t.vendor&&{vendor:t.vendor},...typeof t.available=="boolean"&&{available:t.available}}}function So(t,e,n){if(n===void 0||!e||!/^\d+(\.\d+)?$/.test(t))return t;try{return new Intl.NumberFormat(n,{style:"currency",currency:e}).format(Number(t))}catch{return t}}function yo(t){if(!t.handle)return;let e=`${wr}${encodeURIComponent(t.handle)}`;return t.variant_id?`${e}?variant=${encodeURIComponent(t.variant_id)}`:e}function Yt(t,e){return(t?.items.matched??[]).map(n=>Ir(n,e))}var tt=class{constructor(e,n,r=()=>!0,i=()=>{},s=()=>{}){this.store=e;this.getConfig=n;this.isEnabled=r;this.getLanguage=i;this.getMapper=s;this.hasLoggedError=!1;this.hasLoggedMapperError=!1}forResponse(e){if(!this.isEnabled())return[];if(this.getConfig())return;let n=Yt(e,te(this.getLanguage())),r=this.getMapper();if(!r)return n;try{let i=r(n,e?.items.matched??[]);if(Array.isArray(i))return i}catch(i){this.hasLoggedMapperError||(this.hasLoggedMapperError=!0,console.warn("[AIAutocomplete] mapProducts failed. The original cards are shown.",i))}return n}async run(e,n,r){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(r);return}let s=()=>n.aborted||!r()||!this.owns(i);try{let o=await i.fetch(e,n);if(s())return;let a=i.transform(o),l=Array.isArray(a)?a:[],d=i.limit!=null?l.slice(0,i.limit):l;if(s())return;this.commit(d)}catch(o){if(n.aborted||xo(o)||(this.logOnce(o),s()))return;this.clear(r)}}owns(e){return this.isEnabled()&&this.getConfig()===e}resync(){let e=this.forResponse(this.store.get().customFields);this.commit(e??[])}refresh(){if(this.getConfig())return;let e=this.forResponse(this.store.get().customFields);e!==void 0&&this.commit(e)}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function xo(t){return t instanceof Error&&t.name==="AbortError"}function vo(t){return t.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function Cr(t){let e=t.toLowerCase().replace(/\.$/,"");return e.length<3?-1:ce.findIndex(n=>n.toLowerCase().startsWith(e))}function Po(t,e,n){let r=new Date(n.getFullYear(),t,e);if(r.getMonth()!==t||r.getDate()!==e)return null;let i=new Date(n.getFullYear(),n.getMonth(),n.getDate());if(r>=i)return r;let s=new Date(n.getFullYear()+1,t,e);return s.getMonth()===t&&s.getDate()===e?s:null}function Or(t,e,n){let r=new Date(t,e,n);return r.getMonth()===e&&r.getDate()===n?r:null}function Ee(t,e={}){if(!t)return null;let n=e.today??new Date,r=vo(t.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(r);if(i){let l=Or(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?F(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(r);if(s){let l=Cr(s[1]);if(l>=0)return nt(l,Number(s[2]),s[3],n)}let o=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(o){let l=Cr(o[2]);if(l>=0)return nt(l,Number(o[1]),o[3],n)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(r);if(a){let l=Number(a[1]),d=Number(a[2]);return l>12&&d<=12?nt(d-1,l,a[3],n):d>12&&l<=12?nt(l-1,d,a[3],n):null}return null}function nt(t,e,n,r){if(n){if(n.length!==4)return null;let s=Or(Number(n),t,e);return s?F(s):null}let i=Po(t,e,r);return i?F(i):null}function Qt(t,e={}){let n=t.isoDate;return typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n)?n:Ee(t.text,e)}var kr=" - ",Jt="aiaDateRangeStart",Zt="aiaDateRangeEnd";function we(t,e){return t<=e?{start:t,end:e}:{start:e,end:t}}var Xt=/^\d{4}-\d{2}-\d{2}$/;function Ar(t){if(!Xt.test(t))return null;let[e,n,r]=t.split("-").map(Number),i=new Date(e,n-1,r);return i.getMonth()===n-1&&i.getDate()===r?i:null}var To=/\s+(?:to|through|thru|until|til|till)\s+/g,Eo=/[-–—]/g;function wo(t){let e=[];for(let n of[To,Eo]){n.lastIndex=0;let r=n.exec(t);for(;r!==null;)e.push([t.slice(0,r.index),t.slice(r.index+r[0].length)]),r=n.exec(t)}return e}function rt(t,e={}){if(!t)return null;let n=new Set,r=null;for(let[i,s]of wo(t.trim())){let o=Ee(i.trim(),e);if(!o)continue;let a=Ee(s.trim(),e);!a||a<o||(n.add(`${o}|${a}`),r={start:o,end:a})}return n.size===1?r:null}function Lr(t){let e=Ar(t.start),n=Ar(t.end);return!e||!n?"":t.start===t.end?de(e):`${de(e)}${kr}${de(n)}`}function Rr(t,e){let n=we(t,e);return{text:Lr(n),is_tappable:!0,kind:null,metadata:{[Jt]:n.start,[Zt]:n.end}}}function Ie(t,e={}){let n=t?.metadata?.[Jt],r=t?.metadata?.[Zt];return typeof n=="string"&&typeof r=="string"&&Xt.test(n)&&Xt.test(r)?we(n,r):rt(t?.text,e)}var it="(max-width: 768px)";var Io="var(--aia-option-row-height, 37px)",Co="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function Mr(t,e){return e?en(1,Math.min(t,5)):en(1,Math.min(t,4))}function en(t,e){return{cols:t,rows:e,maxHeight:`calc(${e} * ${Io} + ${Co})`}}function nn(t,e){return!e&&t>=5}function rn(t,e,n,r){if(!(!e&&t>=5&&Oo(n,r))){let o=Mr(t,e);return{...o,template:tn(o.cols),scrollHintIndices:!e&&t>o.rows?[o.rows-1]:[]}}let s=6;return{...en(2,3),template:tn(2),scrollHintIndices:t>s?[s-2,s-1]:[]}}function Oo(t,e){return!t||t.length===0||e==null||e<=0||t.some(r=>r<=0)?!1:Math.ceil(Math.max(...t))*2<=e}function on(t){if(typeof document>"u")return null;let e=Array.from(t.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let n=document.createElement("div");n.style.cssText="position:absolute;visibility:hidden;left:-9999px;top:0;";for(let o of e){let a=o.cloneNode(!0);a.removeAttribute("id"),a.removeAttribute("role"),a.removeAttribute("aria-selected"),a.style.whiteSpace="nowrap",a.style.width="max-content",n.appendChild(a)}t.appendChild(n);let r=Array.from(n.children).map(o=>o.offsetWidth);n.remove();let i=getComputedStyle(t),s=t.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:r,gridWidth:s}}function tn(t){return Array.from({length:t},()=>"minmax(0,1fr)").join(" ")}function sn(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(it).matches}function an(t,e){return!t||t.length!==e.length?!1:t.every((n,r)=>n.text===e[r].text)}function Dr(t,e){let n=e.dropdownTrigger??"auto",r=e.closeDropdownOnBlur??!0,o=t.filteredOptionsLength>0||t.activePillHasNoOptions||t.hasProducts;if(t.inEditMode){let a=r?t.isFocused||t.dropdownHeld:!0;return o&&a}if(n==="auto"){let a=r?t.isFocused||t.dropdownHeld:!0,l=t.text.replace(/\s+$/,"").length,d=t.caretOffset==null||t.caretOffset>=l;return(o||t.isLoading)&&a&&d}return n==="manual"?(o||t.isLoading)&&t.pillTapped:!1}function Ce(t){if(t.editingIdentified){let{parameter:n,anchor:r}=t.editingIdentified;return`identified:${n}@${r}`}return t.editingParam!=null&&t.editingAnchor!=null?`edit:${t.editingParam?.id}`:`pill:${t.actionableSuggestions[0]?.parameter??""}`}function _r(t){if(!t)return Rt();let[e,n]=t.split("-").map(Number);return{year:e,month:n-1}}function Ao(t){let e=qe(t);return e?fr(e):Rt()}function Nr(t,e){let n=or(t.text,t.completedParams,t.identifiedParams),r=t.suggestions.filter(w=>w.parameter!=="placeholder"),i=r[0],s=t.suggestions.filter(w=>w.parameter==="placeholder").map(w=>w.text).join(" "),o=z(t.text,Math.min(t.filterBase,t.text.length),s),l=o===0&&Fe(t.text,t.completedParams.length,s)?"":ye(t.text,o,t.filterInProgress),d=i?.options??[],c=t.editingParam!=null&&t.editingAnchor!=null,u,f,p,m;if(c&&t.editingParam&&t.editingAnchor!=null){let w=t.editingParam.id,ee=t.completedParams.some(Vi=>Vi.id===w),M=t.caretOffset??t.editingAnchor,$n=ee?"":t.text.slice(t.editingAnchor,M);f=$n.trim(),p=t.editingParam.options,m=t.editingParam.suggestionParameter,u=ne(t.editingParam.options,$n)}else f=l.trim(),p=d,m=i?.parameter,u=E(i)?d.map(w=>({...w,matchedText:t.text.slice(le(t.text,t.completedParams)),parameterLabel:Zn(w.parameter)})):ne(d,l,t.traditionalAutocomplete);let S=t.optionSearch,x=S!=null&&m!=null&&S.parameter===m;x&&S.status==="done"&&S.query===f&&(u=p);let h=x&&S.status==="loading",g=e.showNonTappableOptions===!1;g&&(u=u.filter(w=>w.is_tappable));let b=t.editingIdentified,y=c?t.editingParam&&{type:t.editingParam.suggestionValueType}:i,I=b?b.format:U(y),P=c&&I==="date-range"?Ie(t.editingParam):null,O=null,R=null;if(T(I)){let w=Ce({...t,actionableSuggestions:r}),ee=t.dateViewMonth;O=ee&&ee.key===w?{year:ee.year,month:ee.month}:b?_r(b.iso):P?_r(P.start):Ao(t.editingParam?.text),u=Dt(O);let M=t.pendingRangeStart;I==="date-range"&&M&&M.key===w&&(R=M.iso)}let C=w=>g?w.is_tappable:!0,A;if(c){let w=t.editingParam?.options??[];A=t.editingParam!=null&&w.filter(C).length===0}else A=i!=null&&d.filter(C).length===0;let L=Dr({inEditMode:c||b!=null,filteredOptionsLength:u.length,isFocused:t.isFocused,dropdownHeld:t.dropdownHeld,text:t.text,caretOffset:t.caretOffset,isLoading:t.isLoading||h,pillTapped:t.pillTapped,activePillHasNoOptions:A,hasProducts:t.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),q=L&&t.activeDropdownIndex>=0&&!!u[t.activeDropdownIndex]?.is_tappable,Z=t.skeletonOptions!==null&&t.skeletonRequested&&!t.isLoading&&!t.editingParam&&!t.inSelectionAnimation,v=t.isLoading&&!t.editingParam&&!t.inSelectionAnimation||h||Z,H=v&&t.skeletonOptions!==null,Et=H&&t.skeletonOptions?t.skeletonOptions:u,wt=H?t.skeletonSuggestion:null;return{segments:n,actionableSuggestions:r,filteredOptions:u,dropdownLoading:v,dropdownOptions:Et,dropdownSuggestion:wt,skeletonExiting:Z,activeFormatType:I,dateView:O,dateRangeStart:R,placeholderText:s,optionQuery:f,isSearchingOptions:h,isDropdownOpen:L,isActivePillSelected:q}}function ot(t){return t.mode!=="edit"?Lo(t):Ro(t)}function ko(t,e,n){let r=t.find(E);if(!r?.options)return null;let i=e.slice(le(e,n)).trim().toLowerCase();if(!i)return null;let s=r.options.filter(l=>l.is_tappable&&l.text.trim().toLowerCase()===i);if(new Set(s.map(l=>B(l,r.parameter))).size!==1)return null;let a=s[0];return{suggestion:r,option:a,matchText:a.text.trim()}}function Hr(t){let{text:e,suggestions:n,filterBase:r,filterInProgress:i,phraseExactMatch:s}=t,o=n.find(c=>c.parameter!=="placeholder"&&!E(c));if(!o?.options)return null;let a=n.filter(c=>c.parameter==="placeholder").map(c=>c.text).join(" "),l=z(e,r,a),d=xe(o.options,e,l,i,s===!0);return d?{suggestion:o,option:d,matchText:d.text}:null}function Lo(t){let{text:e,completedParams:n,suggestions:r}=t,i=t.mode==="submit"?(t.finishWord?Hr(t):null)??ko(r,e,n):Hr(t);if(!i)return null;let{suggestion:s,option:o,matchText:a}=i,l=a.toLowerCase(),d=e.toLowerCase().lastIndexOf(l),c=d>=0?d:Math.max(0,e.length-o.text.length),u=c+a.length,f=e.slice(c,u),m=u<e.length&&e[u]===" "?u+1:u,S={id:crypto.randomUUID(),placeholder:"",parameter:B(o,s.parameter),text:f,value:o.value,kind:o.kind,suggestionParameter:s.parameter,suggestionValueType:s.type,suggestionPlaceholder:s.text,...t.mode==="submit"&&E(s)?ve(B(o,s.parameter)):{},options:s.options??[],metadata:o.metadata,icon:o.icon,icon_svg:o.icon_svg,image_url:o.image_url};return{patch:{text:e,completedParams:[...n,S],suggestions:r.filter(x=>x!==s),filterBase:m,newParamId:S.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m,option:o,suggestion:s}}function Ro(t){let{text:e,completedParams:n,editingParam:r,editingAnchor:i,editingTail:s}=t;if(n.some(b=>b.id===r.id))return null;let o=e.slice(i,s),a=He(r.options,o);if(!a)return null;let l=a.text.toLowerCase(),d=o.toLowerCase().lastIndexOf(l),c=i+Math.max(0,d),u=c+a.text.length,f=e.slice(c,u),p=u<e.length&&e[u]===" "?u+1:u,m=e.length,S={id:crypto.randomUUID(),placeholder:"",...We(r,a),text:f,value:a.value,kind:a.kind,options:r.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},x=n.length,h=0;for(let b=0;b<n.length;b++){let y=$(e,n[b].text,h);if(y!==-1){if(y>=p){x=b;break}h=y+n[b].text.length}}let g=[...n];return g.splice(x,0,S),{patch:{text:e,completedParams:g,newParamId:S.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1},caretPos:m,option:a}}function Fr(t){return t.slice(t.search(/\S*$/))}function Wr(t){return t.normalize("NFD").replace(/\p{M}/gu,"").toLowerCase()}function Br(t,e){let n="",r=0;for(let i of t){if(n+=Wr(i),r+=i.length,n.length>=e.length)return n.startsWith(e)?r+(t.slice(r).match(/^\p{M}*/u)?.[0].length??0):0;if(!e.startsWith(n))return 0}return 0}function ln(t){return[...t].map(Wr).join("")}function st(t,e){if(/\s$/.test(e))return null;let n=e.split(/\s+/).filter(Boolean).map(ln),r=[...t.matchAll(/\S+/g)].map(i=>({index:i.index??0,text:i[0],folded:ln(i[0])}));for(let i=n.length;i>=1;i--){let s=n.slice(n.length-i),o=s[i-1];for(let a=0;a+i<=r.length;a++){if(!s.slice(0,-1).every((u,f)=>r[a+f].folded===u))continue;let d=r[a+i-1],c=Br(d.text,o);if(c>0)return{typedWords:i,start:r[a].index,end:d.index+c}}}return null}function cn(t,e){let n=e?st(t,e):null;if(n&&n.typedWords>1)return[{text:t.slice(0,n.start),bold:!1},{text:t.slice(n.start,n.end),bold:!0},{text:t.slice(n.end),bold:!1}].filter(o=>o.text!=="");let r=e?Fr(e):"",i=ln(r);if(!i)return[{text:t,bold:!1}];let s=[];for(let o of t.split(/(\s+)/)){if(o==="")continue;let a=/^\s/.test(o)?0:Br(o,i);a>0&&s.push({text:o.slice(0,a),bold:!0});let l=a>0?o.slice(a):o;l&&s.push({text:l,bold:!1})}return s}var Mo=6e4;function Do(t){return typeof TextEncoder>"u"?t.length*3:new TextEncoder().encode(t).length}function _o(t){return(t??K).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function No(t){return he(t)?`Bearer ${await Me(t).getToken()}`:_e(t)}async function Ur(t){try{let e=_o(t.apiConfig?.endpoint),n=De(t.apiConfig),r=await No(t.apiConfig);r&&(n.Authorization=r);let i=JSON.stringify({source:t.source,session_id:t.sessionId,...t.visitorId&&{visitor_id:t.visitorId},...t.requestId&&{request_id:t.requestId},type:t.type,...t.language&&{language:t.language},at:new Date().toISOString(),query_data:t.queryData});await fetch(e,{method:"POST",headers:n,body:i,...t.keepalive&&Do(i)<=Mo&&{keepalive:!0}})}catch{}}function oe(t,e){let n=t.findIndex(r=>r.text===e);return n>=0?n+1:null}var dn=t=>t.toLowerCase().split(/\s+/).filter(Boolean);function Ho(t,e,n){let r=dn(t??"");if(r.length===0)return"";let s=dn(e).slice(-r.length),o=dn(n).slice(0,r.length);return s.join(" ")===r.join(" ")||o.join(" ")===r.join(" ")?"":(t??"").trim().split(/\s+/).join(" ")}function $r(t,e){let n=t.actionableSuggestions[0];if(!n)return null;let r=E(n),i=e.parameter;if(r&&!i)return null;let s=r&&i?i:B(e,n.parameter),o=r?t.text.length:t.filterBase,a=t.text.slice(0,o),l=a.length===0&&t.text.length===0,d=a.length===0&&t.text.length>0&&t.placeholderText.length>0&&t.placeholderText.toLowerCase().startsWith(t.text.toLowerCase());(l||d)&&t.placeholderText&&(a=`${t.placeholderText} `);let c=Math.min(le(t.text,t.completedParams),a.length);if(r){let P=[...a.slice(c).matchAll(/\S+/g)],O=st(e.text,a.slice(c)),R=P[P.length-(O?.typedWords??1)];a=a.slice(0,R?c+(R.index??0):Math.max(a.lastIndexOf(" ")+1,c))}else{let P=Qn(a.slice(c),e.text);P>0&&(a=a.slice(0,a.length-P))}let u=a.length>0&&a[a.length-1]!==" ",p=T(U(n))?Ho(n.lead_in,a,e.text):"",m=`${a}${u?" ":""}${p?`${p} `:""}${e.text} `,x=(l||d||r&&a.length===0)&&m.length>0?m[0].toUpperCase()+m.slice(1):m,h=x.toLowerCase().lastIndexOf(e.text.toLowerCase()),g=h>=0?x.slice(h,h+e.text.length):e.text,b=r?ve(s):{parameter:s,suggestionParameter:n.parameter,suggestionValueType:n.type,suggestionPlaceholder:n.text},y={id:crypto.randomUUID(),placeholder:"",...b,text:g,value:e.value,kind:e.kind,options:n.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},I=t.actionableSuggestions.length-1;return{patch:{text:x,filterBase:x.length,completedParams:[...t.completedParams,y],newParamId:y.id,caretOffset:x.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:t.filteredOptions.filter(P=>P.text!==e.text).map(P=>P.text),key:r?s:n.parameter,position:oe(n.options??[],e.text)},consumedSuggestion:n,remainingActionable:I}}function at(t){let e=T(t.activeFormatType)||t.filteredOptions.length===0?null:t.filteredOptions,n=t.editingParam,r=n?{parameter:n.suggestionParameter,text:n.suggestionPlaceholder,required:!0,options:n.options}:t.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?r:null,skeletonRequested:!1}}function lt(t,e,n){let r=t.slice(0,e),i=t.slice(n),s=(r===""||r.endsWith(" "))&&i.startsWith(" ");return s&&(i=i.slice(1)),{text:r+i,removed:n-e+(s?1:0)}}var ct=class{constructor(e){this.deps=e}start(e){let n=this.deps.store.get();if(n.editingParam?.id===e)return;let r=n.completedParams.find(o=>o.id===e);if(!r)return;let i=0,s=-1;for(let o of n.completedParams){let a=$(n.text,o.text,i);if(a!==-1){if(o.id===e){s=a;break}i=a+o.text.length}}s<0||this.deps.store.set({editingParam:r,editingAnchor:s,editingTail:s+r.text.length,caretOffset:s+r.text.length,activeDropdownIndex:-1,editingIdentified:null})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let n=this.deps.store.get(),r=n.editingParam,i=n.editingAnchor,s=n.editingTail;if(!r||i==null||s==null||!n.completedParams.some(l=>l.id===r.id))return!1;let{text:o}=e===""?lt(n.text,i,s):{text:n.text.slice(0,i)+e+n.text.slice(s)},a=i+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(d=>d.id!==r.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let n=this.deps.store.get(),r={caretOffset:e};n.editingParam&&n.editingAnchor!=null&&e!=null&&(e<n.editingAnchor?(r.editingParam=null,r.editingAnchor=null,r.editingTail=null,r.activeDropdownIndex=-1):n.editingTail!=null&&(r.editingTail=Math.max(n.editingTail,e))),this.deps.store.set(r),this.promoteIfExact()}caretMove(e){let n=this.deps.store.get();if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null&&e!=null&&(e<n.editingAnchor||e>n.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let n=this.deps.store.get(),r=n.editingParam,i=n.editingAnchor,s=n.editingTail;if(!r||i==null||s==null)return;let o=We(r,e);this.deps.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:r.options.filter(g=>g.text!==e.text).map(g=>g.text),key:o.suggestionParameter,position:oe(r.options,e.text),chip_origin:"tap"});let a=n.text.slice(0,i),l=n.text.slice(s),d=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,u=l.length===0||l[0]!==" "?`${d} `:d,f=a+u+l,p=f.length,m={id:crypto.randomUUID(),placeholder:"",...o,text:d,value:e.value,kind:e.kind,options:r.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},S=n.completedParams.findIndex(g=>g.id===r.id),x=n.completedParams.filter(g=>g.id!==r.id),h=S>=0?Math.min(S,x.length):x.length;x.splice(h,0,m),this.deps.store.set({text:f,completedParams:x,newParamId:m.id,filterBase:p,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:p,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...at(n)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(p),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let n=ot({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});n&&(this.deps.store.set(n.patch),this.deps.scheduleSetCursor(n.caretPos))}};var Fo=33,Wo=70,Bo=120,Uo=50,pe="data-aia-placeholder-leaving",me=new WeakMap;function dt(t){t.timer!==null&&(clearTimeout(t.timer),t.timer=null)}function $o(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Vr(t,e,n){e.shown=n,t.dataset.placeholder=e.target.slice(0,n)}function qr(t,e){if(e.timer=null,!t.isConnected||e.shown>=e.target.length||(Vr(t,e,e.shown+1),e.shown>=e.target.length))return;let n=e.target[e.shown-1],r=n===" "||n==="-"?70:0;e.timer=setTimeout(()=>qr(t,e),33+r)}function Gr(t,e){Vr(t,e,0),e.timer=setTimeout(()=>qr(t,e),33)}function Kr(t,e){let n=me.get(t);if(e===""){n&&(dt(n),me.delete(t)),t.removeAttribute(pe),delete t.dataset.placeholder;return}if(n?.target===e)return;if($o(t)){n&&dt(n),t.removeAttribute(pe),me.set(t,{target:e,shown:e.length,timer:null}),t.dataset.placeholder=e;return}let r={target:e,shown:0,timer:null},i=n&&n.shown>0?n:null;if(n&&dt(n),me.set(t,r),i){t.setAttribute(pe,""),r.timer=setTimeout(()=>{r.timer=null,t.removeAttribute(pe),t.isConnected&&Gr(t,r)},170);return}t.removeAttribute(pe),Gr(t,r)}function zr(t){let e=me.get(t);e&&(dt(e),me.delete(t))}var jr="https://ai-autocomplete.com";function un(t=jr){try{if(typeof window>"u"||!window.location)return t;let e=window.location.hostname;if(!e)return t;let n=new URL(t);return n.searchParams.set("utm_source",e),n.toString()}catch{return t}}var Yr={language:"en",proceed:"to proceed",select:"to select",skipHint:"to skip",skip:"skip",skipLabel:"Skip",products:"Products",soldOut:"Sold out",submit:"Submit",scrollArrow:"Scroll down for more options",keepTyping:"Keep typing"},Go={language:"es",proceed:"para continuar",select:"para seleccionar",skipHint:"para omitir",skip:"omitir",skipLabel:"Omitir",products:"Productos",soldOut:"Agotado",submit:"Buscar",scrollArrow:"Despl\xE1zate para ver m\xE1s opciones",keepTyping:"Sigue escribiendo"},pn={en:Yr,es:Go,fr:{language:"fr",proceed:"pour continuer",select:"pour s\xE9lectionner",skipHint:"pour passer",skip:"passer",skipLabel:"Passer",products:"Produits",soldOut:"\xC9puis\xE9",submit:"Rechercher",scrollArrow:"Faites d\xE9filer pour voir plus d\u2019options",keepTyping:"Continuez \xE0 taper"},"pt-BR":{language:"pt-BR",proceed:"para continuar",select:"para selecionar",skipHint:"para pular",skip:"pular",skipLabel:"Pular",products:"Produtos",soldOut:"Esgotado",submit:"Buscar",scrollArrow:"Role para ver mais op\xE7\xF5es",keepTyping:"Continue digitando"},it:{language:"it",proceed:"per continuare",select:"per selezionare",skipHint:"per saltare",skip:"salta",skipLabel:"Salta",products:"Prodotti",soldOut:"Esaurito",submit:"Cerca",scrollArrow:"Scorri per vedere altre opzioni",keepTyping:"Continua a scrivere"},tr:{language:"tr",proceed:"devam etmek i\xE7in",select:"se\xE7mek i\xE7in",skipHint:"atlamak i\xE7in",skip:"atla",skipLabel:"Atla",products:"\xDCr\xFCnler",soldOut:"T\xFCkendi",submit:"Ara",scrollArrow:"Daha fazla se\xE7enek i\xE7in kayd\u0131r",keepTyping:"Yazmaya devam et"},id:{language:"id",proceed:"untuk melanjutkan",select:"untuk memilih",skipHint:"untuk melewati",skip:"lewati",skipLabel:"Lewati",products:"Produk",soldOut:"Habis",submit:"Cari",scrollArrow:"Gulir untuk melihat opsi lainnya",keepTyping:"Teruskan mengetik"},pl:{language:"pl",proceed:"aby kontynuowa\u0107",select:"aby wybra\u0107",skipHint:"aby pomin\u0105\u0107",skip:"pomi\u0144",skipLabel:"Pomi\u0144",products:"Produkty",soldOut:"Wyprzedane",submit:"Szukaj",scrollArrow:"Przewi\u0144, aby zobaczy\u0107 wi\u0119cej opcji",keepTyping:"Pisz dalej"},de:{language:"de",proceed:"zum Fortfahren",select:"zum Ausw\xE4hlen",skipHint:"zum \xDCberspringen",skip:"\xFCberspringen",skipLabel:"\xDCberspringen",products:"Produkte",soldOut:"Ausverkauft",submit:"Suchen",scrollArrow:"Scrolle f\xFCr weitere Optionen",keepTyping:"Weitertippen"},nl:{language:"nl",proceed:"om door te gaan",select:"om te selecteren",skipHint:"om over te slaan",skip:"overslaan",skipLabel:"Overslaan",products:"Producten",soldOut:"Uitverkocht",submit:"Zoeken",scrollArrow:"Scrol voor meer opties",keepTyping:"Blijf typen"},sv:{language:"sv",proceed:"f\xF6r att forts\xE4tta",select:"f\xF6r att v\xE4lja",skipHint:"f\xF6r att hoppa \xF6ver",skip:"hoppa \xF6ver",skipLabel:"Hoppa \xF6ver",products:"Produkter",soldOut:"Sluts\xE5ld",submit:"S\xF6k",scrollArrow:"Skrolla f\xF6r fler alternativ",keepTyping:"Forts\xE4tt skriva"},nb:{language:"nb",proceed:"for \xE5 fortsette",select:"for \xE5 velge",skipHint:"for \xE5 hoppe over",skip:"hopp over",skipLabel:"Hopp over",products:"Produkter",soldOut:"Utsolgt",submit:"S\xF8k",scrollArrow:"Rull ned for \xE5 se flere alternativer",keepTyping:"Fortsett \xE5 skrive"},da:{language:"da",proceed:"for at forts\xE6tte",select:"for at v\xE6lge",skipHint:"for at springe over",skip:"spring over",skipLabel:"Spring over",products:"Produkter",soldOut:"Udsolgt",submit:"S\xF8g",scrollArrow:"Rul for flere muligheder",keepTyping:"Forts\xE6t med at skrive"},fi:{language:"fi",proceed:"jatkaaksesi",select:"valitaksesi",skipHint:"ohittaaksesi",skip:"ohita",skipLabel:"Ohita",products:"Tuotteet",soldOut:"Loppuunmyyty",submit:"Hae",scrollArrow:"Vierit\xE4 n\xE4hd\xE4ksesi lis\xE4\xE4 vaihtoehtoja",keepTyping:"Jatka kirjoittamista"},ja:{language:"ja",proceed:"\u3067\u6B21\u3078",select:"\u3067\u9078\u629E",skipHint:"\u3067\u30B9\u30AD\u30C3\u30D7",skip:"\u30B9\u30AD\u30C3\u30D7",skipLabel:"\u30B9\u30AD\u30C3\u30D7",products:"\u5546\u54C1",soldOut:"\u58F2\u308A\u5207\u308C",submit:"\u691C\u7D22",scrollArrow:"\u30B9\u30AF\u30ED\u30FC\u30EB\u3057\u3066\u4ED6\u306E\u5019\u88DC\u3092\u898B\u308B",keepTyping:"\u5165\u529B\u3092\u7D9A\u3051\u308B"},ko:{language:"ko",proceed:"\uACC4\uC18D",select:"\uC120\uD0DD",skipHint:"\uAC74\uB108\uB6F0\uAE30",skip:"\uAC74\uB108\uB6F0\uAE30",skipLabel:"\uAC74\uB108\uB6F0\uAE30",products:"\uC0C1\uD488",soldOut:"\uD488\uC808",submit:"\uAC80\uC0C9",scrollArrow:"\uB354 \uB9CE\uC740 \uC635\uC158\uC744 \uBCF4\uB824\uBA74 \uC2A4\uD06C\uB864\uD558\uC138\uC694",keepTyping:"\uACC4\uC18D \uC785\uB825\uD558\uC138\uC694"},"zh-CN":{language:"zh-CN",proceed:"\u7EE7\u7EED",select:"\u9009\u62E9",skipHint:"\u8DF3\u8FC7",skip:"\u8DF3\u8FC7",skipLabel:"\u8DF3\u8FC7",products:"\u5546\u54C1",soldOut:"\u552E\u7F44",submit:"\u641C\u7D22",scrollArrow:"\u5411\u4E0B\u6EDA\u52A8\u67E5\u770B\u66F4\u591A\u9009\u9879",keepTyping:"\u7EE7\u7EED\u8F93\u5165"},"zh-TW":{language:"zh-TW",proceed:"\u7E7C\u7E8C",select:"\u9078\u64C7",skipHint:"\u7565\u904E",skip:"\u7565\u904E",skipLabel:"\u7565\u904E",products:"\u5546\u54C1",soldOut:"\u552E\u5B8C",submit:"\u641C\u5C0B",scrollArrow:"\u5411\u4E0B\u6372\u52D5\u67E5\u770B\u66F4\u591A\u9078\u9805",keepTyping:"\u7E7C\u7E8C\u8F38\u5165"}},Vo={pt:"pt-BR",no:"nb",nn:"nb"};function k(t){let[e,...n]=t?.toLowerCase().split("-")??[];if(e==="zh"){let i=n.some(s=>["hant","tw","hk","mo"].includes(s));return pn[i?"zh-TW":"zh-CN"]}let r=Vo[e]??e;return Object.prototype.hasOwnProperty.call(pn,r)?pn[r]:Yr}function mn(t,e,n=k()){return t?{key:"enter",hint:n.proceed}:e?{key:"tab",hint:n.select}:{key:"\u2192",hint:n.skipHint}}function gn(t){let e=o=>{o.ctrlKey||Qr(o.target,t,o.deltaX,o.deltaY)||o.preventDefault()},n=0,r=0,i=o=>{let a=o.touches[0];a&&(n=a.clientX,r=a.clientY)},s=o=>{if(o.touches.length!==1)return;let a=o.touches[0],l=n-a.clientX,d=r-a.clientY;n=a.clientX,r=a.clientY,o.cancelable&&!Qr(o.target,t,l,d)&&o.preventDefault()};return t.addEventListener("wheel",e,{passive:!1}),t.addEventListener("touchstart",i,{passive:!0}),t.addEventListener("touchmove",s,{passive:!1}),()=>{t.removeEventListener("wheel",e),t.removeEventListener("touchstart",i),t.removeEventListener("touchmove",s)}}function Qr(t,e,n,r){let i=t instanceof Element?t:null;for(;i;){if(r!==0&&qo(i,r)||n!==0&&Ko(i,n))return!0;if(i===e)break;i=i.parentElement}return!1}var Xr=/^(auto|scroll|overlay)$/;function qo(t,e){return t.scrollHeight<=t.clientHeight||!Xr.test(getComputedStyle(t).overflowY)?!1:e>0?t.scrollTop+t.clientHeight<t.scrollHeight-1:t.scrollTop>0}function Ko(t,e){if(t.scrollWidth<=t.clientWidth)return!1;let n=getComputedStyle(t);if(!Xr.test(n.overflowX))return!1;let r=Math.abs(t.scrollLeft),i=t.scrollWidth-t.clientWidth;return(n.direction==="rtl"?e<0:e>0)?r<i-1:r>0}var Jr=new WeakMap,Zr=new WeakSet;function Y(t,e,n){if(Jr.set(t,n),Zr.has(t))return;Zr.add(t);let r=()=>Jr.get(t),i=s=>{if(!(s instanceof Element))return null;let o=s.closest(e.itemSelector);return o&&t.contains(o)?o:null};e.onClick&&t.addEventListener("click",s=>{let o=i(s.target);o&&e.onClick?.(o,r(),s)}),e.onEnter&&t.addEventListener("mouseenter",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onEnter?.(o,r())},!0),e.onLeave&&t.addEventListener("mouseleave",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onLeave?.(o,r())},!0),e.preventMousedown&&t.addEventListener("mousedown",s=>s.preventDefault())}function Q(t){return Number.parseInt(t.dataset.aiaIndex??"-1",10)}function X(t){t.offsetWidth}var zo={selectedIso:null,selectedRange:null,rangeStart:null};function Oe(t){if(!T(t.activeFormatType))return zo;let e=t.editingIdentified;if(e){let{iso:r,isoEnd:i}=e;return{selectedIso:i?null:r,selectedRange:r&&i?we(r,i):null,rangeStart:t.dateRangeStart}}let n=Ie(t.editingParam);return{selectedIso:n?null:_t(t.editingParam?.text),selectedRange:n,rangeStart:t.dateRangeStart}}function fn(t){return t.pendingStart?we(t.pendingStart,t.highlightedIso??t.pendingStart):t.selected}function hn(t,e){if(t==null)return{selected:!1,inRange:!1};let{selectedIso:n,range:r}=e,i=t===n||r!=null&&(t===r.start||t===r.end),s=r!=null&&t>r.start&&t<r.end;return{selected:i,inRange:s}}var ei="data-aia-key";function J(t,e,n){let r=new Map;for(let o of Array.from(t.children)){let a=o.getAttribute(ei);a!=null&&r.set(a,o)}let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=n.keyOf(a,o);i.add(l);let d=r.get(l);d||(d=n.create(a,o),d.setAttribute(ei,l)),n.update?.(d,a,o),t.children[o]!==d&&t.insertBefore(d,t.children[o]??null),s.push(d)}for(let[o,a]of r)i.has(o)||a.remove();return s}function ti(t,e){if(!e.interactive)return null;let n=e.options[Q(t)];return n?.is_tappable?n:null}var jo={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(t,e)=>{if(t.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(t.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let n=ti(t,e);n&&(t.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&ti(t,e)&&e.callbacks.onHighlight(Q(t))},onLeave:(t,e)=>{t.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,Q(t))}};function ri(t,e,n,r,i,s,o,a=!0){let l=t.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=Xo(),t.appendChild(l),X(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}Y(l,jo,{options:e,callbacks:o,interactive:a});let d=l.querySelector(".magicx-aia-datepicker-month");d&&(d.textContent=Lt(i));let c=l.querySelector(".magicx-aia-datepicker-grid");c&&Yo(c,e,n,r,s)}function Yo(t,e,n,r,i){let s=F(new Date),o=fn({pendingStart:i.rangeStart,highlightedIso:V(e[n]),selected:i.selectedRange});J(t,e,{keyOf:(a,l)=>V(a)??`pad-${l}`,create:a=>Qo(a),update:(a,l,d)=>{let c=V(l),u=hn(c,{selectedIso:i.selectedIso,range:o}),f=d===n&&l.is_tappable;a.id=`${r}-option-${d}`,a.dataset.aiaIndex=String(d),a.setAttribute("aria-selected",String(f)),a.classList.toggle("magicx-aia-date-cell--past",c!=null&&c<s),a.classList.toggle("magicx-aia-date-cell--highlighted",f),a.classList.toggle("magicx-aia-date-cell--today",c!=null&&c===s),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function Qo(t){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let n=Nt(t);if(n==null)return e.className="magicx-aia-date-cell magicx-aia-date-cell--blank",e.setAttribute("aria-hidden","true"),e.tabIndex=-1,e;e.className="magicx-aia-date-cell magicx-aia-date-cell--day",e.tabIndex=0,e.setAttribute("aria-label",t.text);let r=document.createElement("span");return r.className="magicx-aia-date-cell-number",r.textContent=String(n),e.appendChild(r),e}function Xo(){let t=document.createElement("div");t.className="magicx-aia-datepicker",t.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let n=document.createElement("span");n.className="magicx-aia-datepicker-month",n.setAttribute("data-aia-date-month",""),n.setAttribute("aria-live","polite"),e.append(ni("prev","Previous month","\u2039"),n,ni("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let s of Ve){let o=document.createElement("span");o.className="magicx-aia-datepicker-weekday",o.textContent=s,r.appendChild(o)}let i=document.createElement("div");return i.className="magicx-aia-datepicker-grid",i.setAttribute("data-aia-date-grid",""),t.append(e,r,i),t}function ni(t,e,n){let r=document.createElement("button");return r.type="button",r.tabIndex=-1,r.className="magicx-aia-datepicker-nav",r.setAttribute(`data-aia-date-${t}`,""),r.setAttribute("aria-label",e),r.textContent=n,r.disabled=!0,r}var Jo={itemSelector:"[data-aia-pill]",onClick:(t,e)=>{if(e.loading||t.disabled)return;let n=Number.parseInt(t.dataset.aiaPillIndex??"-1",10);n>=0&&e.onSelectPill(n)},preventMousedown:!0},ii=[125,69];function oi(t,e){return e?1:t===0?.7:t===1?.4:.2}function ut(t,e,n,r,i=!1,s=!1,o=!1){let a=t.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",t.appendChild(a)),Y(a,Jo,{onSelectPill:r,loading:s}),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<ii.length;l++){let d=ii[l],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${i?" magicx-aia-pill--rounded":""}`,c.style.width=`${d}px`,c.style.opacity=String(oi(l,!1)),a.appendChild(c)}return}s?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let l of a.querySelectorAll("[data-aia-pill-skeleton]"))l.remove();J(a,e,{keyOf:l=>`${l.type?.kind??""}|${Be(l)?1:0}|${l.parameter}|${l.text}`,create:l=>{let d=document.createElement("button");if(d.type="button",d.tabIndex=-1,d.setAttribute("data-aia-pill",""),d.setAttribute("contenteditable","false"),Be(l)){d.setAttribute("data-aia-smart-suggestion",E(l)?"header":"");let c=document.createElement("span");c.className="magicx-aia-smart-suggestion-text",c.textContent=l.text;let u=document.createElement("span");u.className="magicx-aia-smart-suggestion-sparkle",u.innerHTML=Ot,d.append(c,u)}else d.textContent=l.text;return d.disabled=!0,d},update:(l,d,c)=>{let u=l,f=o&&c===n&&!s,p=["magicx-aia-pill"];i&&p.push("magicx-aia-pill--rounded"),s&&p.push("magicx-aia-pill--skeleton"),u.className=p.join(" "),u.style.width="",u.style.opacity=String(oi(c,f)),u.dataset.aiaPillIndex=String(c),s?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),X(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=s}function bn(t){t.querySelector(".magicx-aia-pill-list")?.remove()}var Zo=32;function si(t,e){if(e.ctrlKey)return null;let n=e.deltaY||0,r=e.deltaX||0;if(!n||Math.abs(r)>=Math.abs(n))return null;let i=t.scrollWidth-t.clientWidth;if(i<=1)return null;let s=t.scrollLeft,o=n;return e.deltaMode===1?o*=32:e.deltaMode===2&&(o*=t.clientWidth),Math.max(0,Math.min(i,s+o))}function Sn(t){let e=n=>{let r=si(t,n);r!==null&&(n.preventDefault(),t.scrollLeft=r)};return t.addEventListener("wheel",e,{passive:!1}),()=>t.removeEventListener("wheel",e)}var ai=Intl.Segmenter,li=ai?new ai(void 0,{granularity:"grapheme"}):null;function yn(t){let e=t.trim().normalize("NFC").toUpperCase();if(li)for(let n of li.segment(e))return n.segment;return Array.from(e)[0]??"?"}var xn=120,es=360;function ts(t){let e=t.pathname;return t.hostname==="cdn.shopify.com"&&e.startsWith("/s/files/")||e.startsWith("/cdn/shop/")?/\.png$/i.test(e)?{format:"pjpg"}:/\.webp$/i.test(e)?{format:null}:null:null}function ci(t,e){let n;try{n=new URL(t,typeof document>"u"?void 0:document.baseURI)}catch{return t}let r=ts(n);return r?(n.searchParams.set("width",String(e)),r.format&&n.searchParams.set("format",r.format),t.startsWith("/")&&!t.startsWith("//")?`${n.pathname}${n.search}${n.hash}`:n.href):t}function vn(t,e){let n=ci(t,e);return n===t?[t]:[n,t]}function pt(t){let e=t?.trim();return e?vn(e,360):[]}function ns(t){return pt(t)[0]}var Pn=new WeakMap,Tn=new WeakMap,di=new WeakMap;function ui(t,e,n,r,i,s="row",o="image",a=k()){let l=t.querySelector(".magicx-aia-products");if(e.length===0){l?.remove();return}if(!l){l=document.createElement("section"),l.className="magicx-aia-products",l.setAttribute("data-aia-products",""),l.setAttribute("role","group"),l.setAttribute("aria-labelledby",`${n}-products-label`);let u=document.createElement("div");u.className="magicx-aia-products-label",u.id=`${n}-products-label`,u.setAttribute("data-aia-products-label",""),u.textContent=a.products;let f=document.createElement("div");f.className="magicx-aia-products-row",f.setAttribute("data-aia-products-row",""),Sn(f),l.append(u,f),t.appendChild(l)}l.setAttribute("data-aia-products-layout",s);let d=l.querySelector(".magicx-aia-products-label");d&&d.textContent!==a.products&&(d.textContent=a.products);let c=l.querySelector(".magicx-aia-products-row");if(c){J(c,e,{keyOf:u=>is(u),create:u=>os(u,r,i,o,a),update:(u,f,p)=>{Pn.set(u,f),rs(u,f.price),u.id=`${n}-product-${p}`,u.dataset.aiaIndex=String(p),di.get(u)?.(o);let m=u.querySelector(".magicx-aia-product-badge");m&&m.textContent!==a.soldOut&&(m.textContent=a.soldOut)}}),X(c);for(let u of c.querySelectorAll("[data-aia-product]")){let f=Tn.get(u);f&&(Tn.delete(u),f())}}}function En(t,e){let n=t.querySelectorAll("[data-aia-product]");for(let r of n)r.tabIndex=e?0:-1}function rs(t,e){let n=t.querySelector(".magicx-aia-product-price");if(!e){n?.remove();return}n||(n=document.createElement("span"),n.className="magicx-aia-product-price",t.querySelector(".magicx-aia-product-title")?.after(n)),n.textContent!==e&&(n.textContent=e)}function is(t){return[t.id,t.title,t.url,t.imageUrl,t.vendor,t.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function os(t,e,n,r,i){let s=document.createElement("a");s.className="magicx-aia-product",s.setAttribute("data-aia-product",""),s.setAttribute("role","option"),s.setAttribute("aria-selected","false"),s.tabIndex=0;let o=document.createElement("span");o.className="magicx-aia-product-media",o.setAttribute("aria-hidden","true");let a=pt(t.imageUrl),l=a[0],d=!!l,c=()=>{o.replaceChildren(),o.removeAttribute("data-aia-image-loaded"),o.toggleAttribute("data-aia-product-placeholder",r==="image"),o.toggleAttribute("data-aia-product-initial",r==="initial"),r==="initial"&&(o.textContent=yn(t.title))};if(di.set(s,p=>{p!==r&&(r=p,d||c())}),l){let p=document.createElement("img"),m=0;p.onload=()=>o.setAttribute("data-aia-image-loaded",""),p.onerror=()=>{let S=a[++m];if(S){p.src=S;return}d=!1,c()},p.className="magicx-aia-product-image",p.src=l,p.alt="",p.loading="lazy",p.decoding="async",o.appendChild(p)}else c();s.appendChild(o);let u=document.createElement("span");if(u.className="magicx-aia-product-body",t.vendor){let p=document.createElement("span");p.className="magicx-aia-product-vendor",p.textContent=t.vendor,u.appendChild(p)}let f=document.createElement("span");if(f.className="magicx-aia-product-title",f.textContent=t.title,u.appendChild(f),t.available===!1){s.setAttribute("data-aia-product-sold-out","");let p=document.createElement("span");p.className="magicx-aia-product-badge",p.textContent=i.soldOut,u.appendChild(p)}return s.appendChild(u),Tn.set(s,()=>{t.url&&(s.href=t.url),s.addEventListener("click",p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0||(p.preventDefault(),e(Pn.get(s)??t))})}),s.addEventListener("keydown",p=>{p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),e(Pn.get(s)??t))}),s.addEventListener("focus",()=>n(!0)),s.addEventListener("blur",p=>{p.relatedTarget?.closest("[data-aia-dropdown]")||n(!1)}),s}var ss=80,as=150,ls=280,cs=16,wn="--aia-option-enter-delay";function In(t,e,n,r="below"){let i=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,t)/i);if(r!=="above")return s*80;let o=Math.max(1,Math.ceil(Math.max(0,n)/i));return Math.max(0,o-1-s)*80}function Cn(t,e){let n=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,t)/n))-1)*80+280}var pi="http://www.w3.org/2000/svg",ds=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function us(t,e){let n=t.toLowerCase();return n.startsWith("on")||n.includes("href")||n==="style"||n==="xml:base"||n==="id"||n==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var ps=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],ms=/^[a-zA-Z0-9#.,%\s()-]+$/;function gs(t){let e=[];for(let n of ps){let r=t.getAttribute(n);r===null||!ms.test(r)||/url\s*\(/i.test(r)||e.push(`${n}: ${r.trim()}`)}e.length>0&&t.setAttribute("style",e.join("; "))}function mi(t){for(let e of Array.from(t.attributes))us(e.name,e.value)&&t.removeAttribute(e.name);gs(t);for(let e of Array.from(t.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let n=e;!ds.has(n.localName)||n.namespaceURI!==pi?n.remove():mi(n)}else e.remove()}function se(t){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(t,"image/svg+xml"),n=e.documentElement;return!n||n.localName!=="svg"||n.namespaceURI!==pi||e.getElementsByTagName("parsererror").length>0?null:(mi(n),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false"),new XMLSerializer().serializeToString(n))}function mt(t){return t.text}function ae(t){return ft(t)[0]??null}function ft(t){let e=fs(t);return e?vn(e,120):[]}function fs(t){if(!t)return null;let e=t.trim();if(e==="")return null;let n;try{n=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.href}function Ae(t){return t===void 0||!Number.isInteger(t)||t<0?null:t.toLocaleString()}var gi={one:"item",other:"items"};function hs(t,e=gi){let n=Ae(t);if(n===null)return null;let r=typeof e=="string"?e:t===1?e.one:e.other;return r===""?n:`${n} ${r}`}function fi(t){return ae(t.image_url)!==null}var gt=new Map;function bs(t){let e=t.icon_svg;if(!e)return!1;let n=gt.get(e);return n===void 0&&(n=se(e)!==null,gt.size>=256&&gt.clear(),gt.set(e,n)),n}function On(t,e,n){return!e&&!n?!1:t.every(r=>!r.is_tappable||n&&fi(r)||e&&bs(r))}var hi=new WeakMap;function Ss(t,e,n){let r=e.length,i=sn(),s=hi.get(t),o=n&&s&&an(s.options,e)?s.plan:null,a=!o&&!n&&nn(r,i)?on(t):null,l=o??rn(r,i,a?.rowWidths??null,a?.gridWidth??null);return n||hi.set(t,{options:e,plan:l}),t.style.gridTemplateColumns=l.template,t.style.setProperty("--aia-grid-max-height",l.maxHeight),t.querySelectorAll("[data-aia-option]").forEach((d,c)=>{d.classList.toggle("magicx-aia-option--scroll-hint",!n&&l.scrollHintIndices.includes(c))}),l.cols}function bi(t,e){if(e.loading||!e.interactive)return null;let n=e.options[Q(t)];return n?.is_tappable?n:null}var ys={itemSelector:"[data-aia-option]",onClick:(t,e)=>{let n=bi(t,e);n&&(t.classList.add("magicx-aia-option--pressed"),e.onSelect(n),setTimeout(()=>t.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(t,e)=>{bi(t,e)&&e.onHighlight(Q(t))},onLeave:(t,e)=>e.onHighlight(-1,Q(t))};function Si(t,e,n,r,i,s,o,a="",l="below",d=!0,c=!0,u=!0,f=!0){let p=t.querySelector(".aia-grid");if(e.length===0){p?.remove();return}p||(p=document.createElement("div"),p.className="aia-grid magicx-aia-grid",p.setAttribute("data-scroll",""),p.style.setProperty("--aia-grid-min","250px"),p.style.setProperty("--aia-grid-max","1fr"),p.style.setProperty("--aia-grid-gap","0"),t.appendChild(p)),Y(p,ys,{options:e,onSelect:r,onHighlight:i,loading:o,interactive:f});let m=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a;let S=On(e,d,c);xs(p,e,n,s,o,{showIcons:d&&S,showImages:c&&S,showCounts:u});let x=Ss(p,e,o);vs(p,e.length,x,o,l),m&&(p.scrollTop=0)}function xs(t,e,n,r,i,s){let o=i?"1":"0",a=t.dataset.aiaGroup??"",{showIcons:l,showImages:d,showCounts:c}=s,u=l?m=>m.icon??m.icon_svg??"":()=>"",f=d?m=>ae(m.image_url)??"":()=>"",p=c?m=>Ae(m.item_count)??"":()=>"";J(t,e,{keyOf:m=>`${m.text}\0${m.parameterLabel??""}\0${u(m)}\0${f(m)}\0${p(m)}\0${o}\0${a}`,create:(m,S)=>{let x=Ps(m,i,s);return i||(x.dataset.aiaEntering=""),x},update:(m,S,x)=>{if(An.get(m)!==(S.matchedText??"")){let g=m.querySelector(".magicx-aia-option-text");g&&yi(g,S),An.set(m,S.matchedText??"")}let h=x===n&&!i;m.id=`${r}-option-${x}`,m.dataset.aiaIndex=String(x),m.setAttribute("aria-selected",String(h)),m.classList.toggle("magicx-aia-option--highlighted",h)}})}function vs(t,e,n,r,i){for(let s of t.querySelectorAll("[data-aia-entering]")){if(!r){let o=Number.parseInt(s.dataset.aiaIndex??"-1",10);o>=0&&s.style.setProperty(wn,`${In(o,n,e,i)}ms`)}delete s.dataset.aiaEntering}}var An=new WeakMap;function yi(t,e){if(t.replaceChildren(),e.matchedText)for(let n of cn(mt(e),e.matchedText))if(n.bold){let r=document.createElement("strong");r.className="magicx-aia-option-match",r.textContent=n.text,t.appendChild(r)}else t.appendChild(document.createTextNode(n.text));else t.appendChild(document.createTextNode(mt(e)));if(e.parameterLabel){t.appendChild(document.createTextNode(" "));let n=document.createElement("span");n.className="magicx-aia-option-parameter",n.textContent=e.parameterLabel,t.appendChild(n)}}function Ps(t,e,{showIcons:n,showImages:r,showCounts:i}){let s=document.createElement("div");s.setAttribute("role","option"),s.setAttribute("data-aia-option",""),e&&s.setAttribute("data-aia-loading",""),s.tabIndex=e||!t.is_tappable?-1:0;let o=["magicx-aia-option"];t.is_tappable?o.push("magicx-aia-option--tappable"):o.push("magicx-aia-option--non-tappable"),s.className=o.join(" ");let a=document.createElement("span");a.className="magicx-aia-option-content";let l=r?ft(t.image_url):[],d=l[0];if(d){let p=document.createElement("span");p.className="magicx-aia-option-image",p.setAttribute("aria-hidden","true");let m=document.createElement("img");m.setAttribute("alt",""),m.setAttribute("loading","lazy"),m.setAttribute("decoding","async"),m.setAttribute("referrerpolicy","no-referrer"),m.setAttribute("draggable","false");let S=0;m.onload=()=>p.setAttribute("data-aia-image-loaded",""),m.onerror=()=>{let x=l[++S];x?m.src=x:m.hidden=!0},m.src=d,p.appendChild(m),a.appendChild(p),s.dataset.aiaImage=""}let c=!d&&n&&t.icon_svg?se(t.icon_svg):null;if(c){let p=document.createElement("span");p.className="magicx-aia-option-icon",p.setAttribute("aria-hidden","true"),p.innerHTML=c,a.appendChild(p),t.icon&&(s.dataset.aiaIcon=t.icon)}let u=document.createElement("span");if(u.className="magicx-aia-option-text",yi(u,t),An.set(s,t.matchedText??""),a.appendChild(u),t.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=t.tag,a.appendChild(p)}let f=i?Ae(t.item_count):null;if(f!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=f,a.appendChild(p),s.dataset.aiaItemCount=String(t.item_count)}return s.appendChild(a),s}var xi="magicx-aia-scroll-arrow",vi="data-aia-scroll-arrow",ge="data-aia-visible",Pi=1e3,Ti=160,Ei="--aia-scroll-arrow-bottom",Ts="Scroll down for more options",Es="[data-aia-products-label]",ws=4,Is=8,Cs=240;function Os(t,e,n,r){let i=t.scrollTop,s=n?.requestAnimationFrame,o=t.ownerDocument?.visibilityState==="hidden";if(!s||o||kn(t)){t.scrollTop=i+e,r();return}let a=n.performance?.now?.()??Date.now(),l=()=>n.performance?.now?.()??Date.now(),d=()=>{let c=Math.min(1,(l()-a)/Cs),u=1-(1-c)*(1-c);t.scrollTop=i+e*u,c<1?s.call(n,d):r()};s.call(n,d)}function As(t=document){let e="http://www.w3.org/2000/svg",n=t.createElementNS(e,"svg");n.setAttribute("viewBox","0 0 16 16"),n.setAttribute("width","18"),n.setAttribute("height","18"),n.setAttribute("fill","none"),n.setAttribute("stroke","currentColor"),n.setAttribute("stroke-width","1.75"),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),n.setAttribute("focusable","false");let r=t.createElementNS(e,"path");return r.setAttribute("d","M4 6.5 8 10.5l4-4"),n.appendChild(r),n}function wi(t=document,e=k()){let n=t.createElement("button");return n.type="button",n.tabIndex=-1,n.className=xi,n.setAttribute(vi,""),n.setAttribute("aria-label",e.scrollArrow),n.setAttribute("aria-hidden","true"),n.disabled=!0,n.appendChild(As(t)),n}function ks(t){let e=t.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function kn(t){return t.closest('[data-animations="off"]')?!0:!!t.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function Ln({dropdown:t,grid:e,button:n}){let r=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;n.disabled=!0;let s=null,o=null,a=null,l=null,d=g=>{if(g){if(n.hasAttribute(ge))return;if(n.setAttribute(ge,""),n.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),kn(e)){n.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&n.hasAttribute(ge)&&(n.disabled=!1)},Pi)}else n.removeAttribute(ge),n.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,n.disabled=!0},c=g=>{let b=0,y=g;for(;y&&y!==t;)b+=y.offsetTop,y=y.offsetParent instanceof HTMLElement?y.offsetParent:null;return b},u=()=>{let g=t.querySelector(Es),b;if(g){let y=c(g)+g.offsetHeight/2;b=t.clientHeight-y-n.offsetHeight/2}else{let y=c(e),I=r&&Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0;b=t.clientHeight-(y+e.offsetHeight)+(I>0?0:Is)}n.style.setProperty(Ei,`${Math.max(0,Math.round(b))}px`)},f=()=>{if(i||o!==null||a!==null)return;let g=e.querySelector("[data-aia-option][data-aia-loading]")!==null,b=e.scrollHeight-e.clientHeight-e.scrollTop;d(!g&&b>ws)},p=()=>{if(i)return;u();let g=e.getAttribute("data-aia-group")??"";if(g!==s){s=g,d(!1),o!==null&&clearTimeout(o);let b=e.querySelectorAll("[data-aia-option]").length,y=kn(e)?0:Cn(b,ks(e));o=setTimeout(()=>{o=null,f()},y);return}f()},m=()=>{i||o!==null||(d(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,f()},Ti))};e.addEventListener("scroll",m,{passive:!0});let S=g=>g.preventDefault(),x=()=>{let g=r?(Number.parseFloat(r.getComputedStyle(e).paddingTop)||0)+(Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0):0,b=Math.max(1,e.clientHeight-g);Os(e,b,r,m)};n.addEventListener("mousedown",S),n.addEventListener("click",x);let h=null;return r&&typeof r.ResizeObserver=="function"&&(h=new r.ResizeObserver(()=>{u(),f()}),h.observe(e)),p(),{update:p,destroy(){i||(i=!0,o!==null&&clearTimeout(o),o=null,a!==null&&clearTimeout(a),a=null,l!==null&&clearTimeout(l),l=null,n.disabled=!0,e.removeEventListener("scroll",m),n.removeEventListener("mousedown",S),n.removeEventListener("click",x),h?.disconnect(),n.removeAttribute(ge),n.setAttribute("aria-hidden","true"))}}}var fe="data-aia-fit",ht="--aia-dropdown-fit-height";function Rn({dropdown:t,isOpen:e}){let n=t.ownerDocument?.defaultView??null,r=!1,i=!1,s=null,o=null,a=null,l=()=>{t.removeAttribute(fe),t.style.removeProperty(ht)},d=p=>{let S=`${s}|${(p??t).scrollHeight}|${t.offsetWidth}`;if(a?.key===S)return a.height;let x=p?.scrollTop??0;t.removeAttribute(fe);let h=t.offsetHeight;return t.setAttribute(fe,""),p&&x&&(p.scrollTop=x),a={key:S,height:h},h},c=()=>{if(r)return;if(!e()){i=!1;return}i||(i=!0,l());let p=t.hasAttribute(fe),m=t.querySelector(".aia-grid")?.getAttribute("data-aia-group")??null,S=m!==s;s=m;let x=Rs(t,n);if(x===null)return;let h=Ls(t);if(p){if(d(h)<=x){l();return}}else if(t.offsetHeight<=x)return;let g=`${Math.max(160,Math.floor(x))}px`;t.style.getPropertyValue(ht)!==g&&t.style.setProperty(ht,g),p?S&&h&&(h.scrollTop=0):t.setAttribute(fe,"")},u=()=>{r||o!==null||!n||(o=n.requestAnimationFrame(()=>{o=null,c()}))},f=n?.visualViewport??null;return f?.addEventListener("resize",u),f?.addEventListener("scroll",u),n?.addEventListener("resize",u),n?.addEventListener("scroll",u,{capture:!0,passive:!0}),c(),{update:c,destroy(){r||(r=!0,o!==null&&n?.cancelAnimationFrame(o),f?.removeEventListener("resize",u),f?.removeEventListener("scroll",u),n?.removeEventListener("resize",u),n?.removeEventListener("scroll",u,{capture:!0}))}}}function Ls(t){for(let e of Array.from(t.children))if(e.classList.contains("aia-stack"))return e;return null}function Rs(t,e){if(!e)return null;let n=e.visualViewport,r=n?n.offsetTop:0,i=n?n.height:e.innerHeight;if(!i)return null;let s=t.offsetParent,o=s?s.getBoundingClientRect().top:0,a=s?o+t.offsetTop:t.getBoundingClientRect().top;return t.closest("[data-options-position]")?.getAttribute("data-options-position")==="above"?(s?a+t.offsetHeight:t.getBoundingClientRect().bottom)-r-8:r+i-a-8}var Ms=[159,119,164];function yt(t){let e=document.createElement("div");return e.id=t,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",n=>n.preventDefault()),gn(e),e}var bt=new WeakMap;function Ds(t,e,n){let r=bt.get(t);if(r||(r={button:wi(t.ownerDocument,n),grid:null,controller:null},t.appendChild(r.button),bt.set(t,r)),r.button.getAttribute("aria-label")!==n.scrollArrow&&r.button.setAttribute("aria-label",n.scrollArrow),r.grid!==e&&(r.controller?.destroy(),r.controller=null,r.grid=e,e)){r.controller=Ln({dropdown:t,grid:e,button:r.button});return}r.controller?.update()}var St=new WeakMap;function Ii(t){let e=St.get(t);if(e){e.update();return}St.set(t,Rn({dropdown:t,isOpen:()=>t.classList.contains("magicx-aia-dropdown--visible")}))}function Mn(t){St.get(t)?.destroy(),St.delete(t);let e=bt.get(t);e&&(e.controller?.destroy(),bt.delete(t))}function xt(t,e){let n=e.strings??k(),{filteredOptions:r,activeIndex:i,isOpen:s,isLoading:o,showPills:a,isActivePillSelected:l,onSelect:d,onHighlight:c,onPillClick:u,onSkip:f}=e,p=Ct(e.pills,n.keepTyping),m=At(p),S=a&&p.length>0,x=r.length>0,h=e.products.length>0,g=s&&(x||S||o||h);if(g?t.classList.add("magicx-aia-dropdown--visible"):t.classList.remove("magicx-aia-dropdown--visible"),o?t.setAttribute("data-aia-loading",""):t.removeAttribute("data-aia-loading"),!g){En(t,!1),Ii(t);return}h?t.setAttribute("data-aia-has-products",""):t.removeAttribute("data-aia-has-products"),t.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let b=t.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),t.appendChild(b));let y=e.showSkipButton&&m&&!e.isInputEmpty,I=S||o&&a||y,P=b.querySelector(".magicx-aia-pill-bar");if(I){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),b.insertBefore(P,b.firstChild));let v=P.querySelector(".magicx-aia-pill-scroll");v||(v=document.createElement("span"),v.className="magicx-aia-pill-scroll",v.setAttribute("data-aia-pill-scroll",""),P.insertBefore(v,P.firstChild)),ut(v,a?p:[],0,u,!0,o&&a,l),Hs(P,y,o||e.skipDisabled,p[0],f,n)}else P&&P.remove();let O=e.suggestions[0],R=O?`${O.parameter} ${O.text}`:"",C=T(e.formatType),A=C&&!o;Si(b,C?[]:r,i,d,c,e.listboxId,o,R,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Ds(t,b.querySelector(".aia-grid"),n),ri(b,A?r:[],i,e.listboxId,A?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:c,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let L=b.querySelector(".magicx-aia-skeleton-bars");if(o&&(!x||C)){if(!L){L=document.createElement("div"),L.className="magicx-aia-skeleton-bars",L.setAttribute("data-aia-skeleton-bars","");for(let v of Ms){let H=document.createElement("span");H.className="magicx-aia-skeleton-bar",H.style.width=`${v}px`,L.appendChild(H)}b.appendChild(L)}}else L&&L.remove();ui(b,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image",n),En(t,!0);let q=b.querySelector(".magicx-aia-footer")??Ws(n),Z=i>=0&&!!r[i]?.is_tappable;Fs(q,mn(Z,e.isInputEmpty,n)),q.isConnected||b.appendChild(q),_s(b,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"]),Ii(t)}function _s(t,e){let n=e.map(r=>t.querySelector(`:scope > ${r}`)).filter(r=>r!==null);for(let r=0;r<n.length;r++)t.children[r]!==n[r]&&t.insertBefore(n[r],t.children[r]??null)}var Ns={itemSelector:".magicx-aia-skip",onClick:(t,e)=>{e.loading||e.onSkip()}};function Hs(t,e,n,r,i,s){Y(t,Ns,{onSkip:i,loading:n});let o=t.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent=s.skip,o.disabled=!0,t.appendChild(o),X(o)),o.textContent!==s.skip&&(o.textContent=s.skip),o.setAttribute("aria-label",r?`${s.skipLabel} ${r.text}`:s.skipLabel),o.disabled=n}function Fs(t,{key:e,hint:n}){let r=t.querySelector(".magicx-aia-footer-key"),i=t.querySelector(".magicx-aia-footer-hint");!r||!i||(r.textContent!==e&&(r.textContent=e),i.textContent!==n&&(i.textContent=n))}function Ws(t){let e=document.createElement("footer");e.className="magicx-aia-footer",e.setAttribute("data-aia-footer","");let n=document.createElement("div");n.className="aia-cluster magicx-aia-footer-row",n.setAttribute("data-align","center"),n.setAttribute("data-justify","between"),n.setAttribute("data-nowrap","");let r=document.createElement("div");r.className="aia-cluster magicx-aia-footer-hint-group",r.setAttribute("data-align","center"),r.style.setProperty("--aia-cluster-gap","5px");let i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let s=document.createElement("span");s.className="magicx-aia-footer-hint",s.textContent=t.select,r.append(i,s);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=un(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let l=document.createElement("span");return l.className="magicx-aia-footer-badge",l.textContent="Autocomplete",o.append(a,l),n.append(r,o),e.append(n),e}function Ci(t,e){let n=yt(e.listboxId);return t.appendChild(n),{dropdown:n}}function Dn(t,e,n){let r=Oe(e);xt(t.dropdown,{strings:n.strings,suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:G(e.editingIdentified.parameter),required:!0,options:e.filteredOptions}]:e.dropdownSuggestion??e.actionableSuggestions[0]?[{...e.dropdownSuggestion??e.actionableSuggestions[0],options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:r.selectedIso,selectedDateRange:r.selectedRange,dateRangeStart:r.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:n.selectOption,onHighlight:(i,s)=>{s!==void 0&&n.store.get().activeDropdownIndex!==s||n.store.set({activeDropdownIndex:i})},onPillClick:n.setActivePill,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:i=>n.store.set({isFocused:i})})}var Bs=6,Us=.3;function Oi(t){return t<=0?"0px":`${(-Math.min(Us,2*Bs/t)).toFixed(3)}px`}var Ai=new Map;function $s(t,e,n){let r=Ai.get(e);if(r!==void 0){t.style.setProperty("--aia-chip-image-fit",r),t.setAttribute("data-aia-image-loaded","");return}let i=n.createElement("img");i.setAttribute("referrerpolicy","no-referrer"),i.onload=()=>{if(!t.isConnected)return;t.setAttribute("data-aia-image-loaded","");let s=t.getBoundingClientRect().height,o=Number.parseFloat(getComputedStyle(t).fontSize);if(!(s>0&&o>0&&i.naturalWidth>0&&i.naturalHeight>0))return;let a=`${(s/o*(i.naturalWidth/i.naturalHeight)).toFixed(3)}em`;Ai.set(e,a),t.style.setProperty("--aia-chip-image-fit",a)},i.src=e}function _n(t){let{input:e,segments:n,newParamId:r,editingParamId:i,placeholderText:s,isFocused:o}=t,a=t.showChipIcons??!0,l=t.showChipImages??!0,d=n.length===0;e.dataset.aiaEmpty=d?"true":"false",Kr(e,d?s:"");let c=n.map(g=>g.type==="completed"?`${g.type}:${g.value}${a?g.param.icon??g.param.icon_svg??"":""}${l?ae(g.param.image_url)??"":""}`:`${g.type}:${g.value}`).join("\0"),u=e.dataset.segKey??"",f=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(c===u&&(r??"")===f&&(i??"")===p)return;if(c===u){e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";for(let g of e.querySelectorAll("strong[data-param-id]")){let b=g.dataset.paramId,y=g.dataset.seg==="completed"&&b===r;g.classList.toggle("magicx-aia-shimmer-revealed",y),g.classList.toggle("magicx-aia-shimmer-sweep",y),g.classList.toggle("magicx-aia-segment--editing",b===i)}return}let m=o?W(e):null;e.dataset.segKey=c,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let S=_(e),x=S.createDocumentFragment(),h=0;for(let g of n)if(h+=g.value.length,g.type==="completed"){let b=S.createElement("strong");b.dataset.seg="completed",b.dataset.paramId=g.param.id;let y=g.param.id===r,I=g.param.id===i,P=["magicx-aia-segment","magicx-aia-segment--completed"];y&&P.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),I&&P.push("magicx-aia-segment--editing"),b.className=P.join(" "),b.style.letterSpacing=Oi(g.value.length);let O=l?ae(g.param.image_url):null;if(O){let C=S.createElement("span");C.className="magicx-aia-segment-image",C.setAttribute("contenteditable","false"),C.setAttribute("aria-hidden","true"),C.style.setProperty("--aia-chip-image",`url("${O}")`),$s(C,O,S),b.appendChild(C),b.dataset.aiaImage=""}let R=!O&&a&&g.param.icon_svg?se(g.param.icon_svg):null;if(R){let C=S.createElement("span");C.className="magicx-aia-segment-icon",C.setAttribute("contenteditable","false"),C.setAttribute("aria-hidden","true"),C.innerHTML=R,b.appendChild(C),g.param.icon&&(b.dataset.aiaIcon=g.param.icon)}b.appendChild(S.createTextNode(g.value)),x.appendChild(b)}else if(g.type==="identified"){let b=S.createElement("strong");b.dataset.seg="identified",b.dataset.paramId=g.param.id;let y=["magicx-aia-segment","magicx-aia-segment--completed"];g.param.id===i&&y.push("magicx-aia-segment--editing"),b.className=y.join(" "),b.style.letterSpacing=Oi(g.value.length),b.textContent=g.value,x.appendChild(b)}else x.appendChild(S.createTextNode(g.value));e.replaceChildren(x),e.dataset.aiaTextLength=String(h),m!=null?N(e,Math.max(0,Math.min(m,h))):o&&Tr(e)&&N(e,h)}var Gs='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function ki(t=k()){let e=document.createElement("button");return e.type="button",e.className="magicx-aia-submit",e.setAttribute("aria-label",t.submit),e.setAttribute("data-aia-submit",""),e.innerHTML=Gs.replace('aria-label="Submit"',`aria-label="${t.submit}"`),e}function Vs(){let t=document.createElement("div");return t.setAttribute("contenteditable","plaintext-only"),t.contentEditable==="plaintext-only"}function Li(t,e){let n=e.firstElementChild;if(!n){e.removeAttribute("data-aia-pill-wrapped");return}let r=n.getBoundingClientRect(),i=t.getBoundingClientRect();r.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ri(t,e){let{listboxId:n}=e,r=yt(n);t.appendChild(r);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),t.appendChild(i);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),i.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Vs()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",n),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let l=null,d=null;e.submitButton===void 0?(l=ki(e.strings),i.appendChild(l),d=l):e.submitButton!==null&&(d=e.submitButton,d.hasAttribute("data-aia-submit")||d.setAttribute("data-aia-submit",""),d.setAttribute("data-aia-submit-slot",""),i.appendChild(d));let c=new AbortController,{signal:u}=c,f=!1,p=0,m=()=>{let h=Xe(o),b=h.length>0&&h[0]!==h[0].toUpperCase()?h[0].toUpperCase()+h.slice(1):h;e.handleChange(b)},S=()=>{let h=j(o)?.node??null;if(!h||!o.contains(h))return null;let y=(h.nodeType===Node.ELEMENT_NODE?h:h.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return y&&Pr(o,y)?null:y};if(i.addEventListener("click",h=>{h.target?.closest("[data-aia-pill]")||o.focus()},{signal:u}),o.addEventListener("input",()=>{f||(p=performance.now(),m(),e.handleCaretAfterInput(W(o)))},{signal:u}),_(o).addEventListener("selectionchange",()=>{let h=j(o);if(!h||!o.contains(h.node))return;let g=h.collapsed?S():null,b=e.store.get(),y=b.editingParam?.id??b.editingIdentified?.id??null;if(g&&g!==y){e.startEditingParam(g);return}performance.now()-p<50||e.handleCaretMove(W(o))},{signal:u}),o.addEventListener("click",h=>{let g=Gt(o,h.target);g&&(e.startEditingParam(g),Vt(o,g))},{signal:u}),o.addEventListener("compositionstart",()=>{f=!0,o.setAttribute("data-aia-composing","true")},{signal:u}),o.addEventListener("compositionend",()=>{f=!1,o.removeAttribute("data-aia-composing"),m()},{signal:u}),o.addEventListener("beforeinput",h=>{let g=h,b=g.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){h.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":g.data??"";e.replaceEditingRange(y)&&h.preventDefault()}},{signal:u}),o.addEventListener("paste",h=>{h.preventDefault();let g=(h.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let b=_(o),y=Ke(o);if(!y||!o.contains(y.startContainer))return;y.deleteContents();let I=b.createTextNode(g);y.insertNode(I),y.setStartAfter(I),Te(o,y.startContainer,y.startOffset),m()},{signal:u}),o.addEventListener("keydown",h=>e.handleKeyDown(h),{signal:u}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),d&&d.addEventListener("click",h=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;h.stopPropagation(),e.endTypedWord?.();let y=e.store.get();e.onSubmit(ie(y.text,y.completedParams,y.skippedParams,{identifiedParams:y.identifiedParams,isReady:y.isReady,customFields:y.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){o.focus();let h=j(o);(!h||!o.contains(h.node))&&Te(o,o,0)}if(typeof ResizeObserver<"u"){let h=new ResizeObserver(()=>Li(o,a));h.observe(o),c.signal.addEventListener("abort",()=>h.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:r,submitButton:l,abort:c}}function Nn(t,e,n){let{input:r,inlinePillContainer:i,dropdown:s,submitButton:o}=t,{pillPlacement:a,setActivePill:l,selectOption:d,store:c}=n;r.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${n.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?r.setAttribute("aria-activedescendant",u):r.removeAttribute("aria-activedescendant"),o){let h=n.strings??k();o.getAttribute("aria-label")!==h.submit&&o.setAttribute("aria-label",h.submit);let g=o.querySelector("svg");g&&g.getAttribute("aria-label")!==h.submit&&g.setAttribute("aria-label",h.submit);let b=!!e.text||e.completedParams.length>0;o.disabled=!b}let f=r.dataset.newParamId??"",p=e.newParamId!==null&&e.newParamId!==f;if(_n({input:r,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:n.showChipIcons??!0,showChipImages:n.showChipImages??!0}),a==="inline"){let h=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,g=It(e.actionableSuggestions);h||g.length>0?ut(i,g,0,l,!1,h,e.isActivePillSelected):bn(i)}else bn(i);Li(r,i),p?(r.focus(),N(r,e.caretOffset??e.text.length)):e.isFocused&&Xe(r)!==e.text&&N(r,e.text.length);let m=e.editingParam?{parameter:e.editingParam.suggestionParameter,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{parameter:e.editingIdentified.parameter,text:G(e.editingIdentified.parameter),required:!0,options:[]}:null,S=e.dropdownSuggestion??m??e.actionableSuggestions[0],x=Oe(e);xt(s,{strings:n.strings,suggestions:S?[{...S,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:n.listboxId,pills:m?[m]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:n.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:n.showOptionIcons??!0,showOptionImages:n.showOptionImages??!0,showOptionCounts:n.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:n.productsLayout??"row",productImageFallback:n.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:x.selectedIso,selectedDateRange:x.selectedRange,dateRangeStart:x.rangeStart,optionsPosition:n.optionsPosition??"below",onSelect:d,onHighlight:(h,g)=>{g!==void 0&&c.get().activeDropdownIndex!==g||c.set({activeDropdownIndex:h})},onPillClick:l,onSkip:n.skipActivePill,onPreviousMonth:n.showPreviousMonth,onNextMonth:n.showNextMonth,onProductSelect:n.selectProduct,onProductFocusChange:h=>c.set({isFocused:h})})}function Hn(t){let e=t,n=new Set,r=[],i=!1;return{get:()=>e,set:s=>{let o=typeof s=="function"?s(e):s,a=e;if(e={...e,...o},r.push([e,a]),!i){i=!0;try{let l=0;for(let d=r.shift();d;d=r.shift()){if(++l>1e4)throw r.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,u]=d;for(let f of n)f(c,u)}}catch(l){throw r.length=0,l}finally{i=!1}}},subscribe:s=>(n.add(s),()=>{n.delete(s)})}}function Mi(t,e){let n,r,i=s=>(s!==n&&(n=s,r=e(s)),r);return{get:()=>{let s=t.get();return{...s,...i(s)}},set:s=>{typeof s=="function"?t.set(o=>{let a={...o,...i(o)};return s(a)}):t.set(s)},peek:s=>{let o={...t.get(),...s};return{...o,...e(o)}},subscribe:s=>t.subscribe((o,a)=>{let l={...a,...i(a)},d={...o,...i(o)};s(d,l)})}}var Fn=new WeakSet,Di=new WeakMap;function Ni(t){return t.nodeType===Node.DOCUMENT_NODE}function qs(t){return Ni(t)?t:t.ownerDocument}function Ks(t){let e=Di.get(t);if(e)return e;let n=t.defaultView?.CSSStyleSheet;if(typeof n!="function")return null;try{let r=new n;return typeof r.replaceSync!="function"?null:(r.replaceSync(Fi),Di.set(t,r),r)}catch{return null}}function _i(t,e){if(e.querySelector("style[data-magicx-aia]"))return;let n=t.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Fi,e.appendChild(n)}function Hi(t){if(typeof document>"u")return;let e=t??document;if(Fn.has(e))return;let n=qs(e);if(Ni(e)){let s=e.head??e.documentElement;if(!s)return;_i(n,s),Fn.add(e);return}let r=Ks(n),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):_i(n,e),Fn.add(e)}var Fi=`.aia-stack {
2
2
  display: flex;
3
3
  flex-direction: column;
4
4
  gap: var(--aia-stack-space, 0.5rem);
@@ -2681,5 +2681,5 @@ function T(t){return t==="date"||t==="date-range"}function B(t){return t?.type?.
2681
2681
  max-height: none;
2682
2682
  overflow: visible;
2683
2683
  }
2684
- `;var xt=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(r){this.report(e,r,e);return}}runListener(e,n,r=e){try{return n(),!0}catch(i){return this.report(e,i,r),!1}}report(e,n,r){this.reported.has(r)||(this.reported.add(r),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,n))}};var vt=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let r=`${String(e)}#${++this.registrationCount}`,i=(...o)=>n(...o);this.keys.set(i,r);let s=this.listeners[e];return s||(s=new Set,this.listeners[e]=s),s.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...n){let r=this.listeners[e];if(!r)return!0;let i=!0;for(let s of r)this.boundary.runListener(String(e),()=>s(...n),this.keys.get(s)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Pt=class{constructor(){this.timers=new Map}schedule(e,n,r){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),n()},r);this.timers.set(e,i)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};function qs(t){let e;try{e=new URL(t??q).host}catch{return null}let n=ke.get(e);return n?`https://${n}`:null}var Fi=new WeakMap;function Wi(t,e){if(!t.head)return;let n=qs(e);if(!n)return;let r=Fi.get(t);r||(r=new Map,Fi.set(t,r));let i=r.get(n);i||(i=t.createElement("link"),i.rel="preconnect",i.href=n,r.set(n,i)),t.head.append(i)}var Oe=class{constructor(e,n="auto",r){this.container=e;this.mode=n;this.onResolve=r;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Wn(t){return t.isDropdownOpen&&!t.isLoading}var Ks=50,zs=new Set(["search_started","submit","product_click","impression"]),js="newParam",Bi="suggestionRemoval",Ys="selectionAnimation",Bn="skeletonExit",Qs=650,Xs=0;function Js(){return`:ac-${++Xs}:`}var Ui=170,Zs=100;function $i(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],traditionalAutocomplete:!1,customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,dropdownHeld:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Un=class{constructor(e,n={}){this.inputStore=Hn($i());this._listboxId=Js();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Pt;this.boundary=new xt;this.subscriberCount=0;this.emitter=new vt(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;this.openWordText=null;this.heldIdentified=null;this.lastImpressionKey="";this.visibleImpression=!1;this.destroyed=!1;this.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=n,this.renderMode=n.renderMode??"full",this.store=Ri(this.inputStore,r=>Nr(r,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.holdOpen=new $e(this.store,e),this.pillsController=new Ze(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:s})}}),this.reEdit=new lt({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new et(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1,()=>this.opts.language,()=>this.opts.mapProducts),this.optionSource=new Je(this.store,()=>this.opts.optionOverrides,{onAnswer:r=>{r==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(r,i)=>{r==="pill"&&i.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new Ue(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,()=>this.opts.language,{getProductId:()=>this.opts.productId,getCurrency:()=>this.opts.currency,onRequest:({query:r,signal:i,isCurrent:s})=>{Wi(this.container.ownerDocument,this.opts.apiConfig?.endpoint),this.productsController.run(r,i,s).catch(()=>{})},onAutoMatch:({active:r,matched:i,rawQuery:s})=>{let o=r.options??[];this.fireTelemetry("option",{raw_query:s,selected_option:i.text,other_options:o.filter(a=>a.text!==i.text).map(a=>a.text),key:r.parameter,position:oe(o,i.text),chip_origin:"typed"})},onResponse:({requestId:r,funnelTelemetry:i,visibleImpression:s})=>{this.lastRequestId=r,this.funnelTelemetry=i,this.visibleImpression=s,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:r=>this.productsController.forResponse(r),consumerTick:(r,i)=>this.optionSource.tick(r,i),isWordOpen:()=>this.isWordOpen(),holdIdentified:r=>{this.heldIdentified={text:this.store.get().text,candidates:r}}}),this.keyboardController=new Xe(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption:r=>this.selectOption(r),removeParamAtCaret:r=>this.removeParamAtCaret(r),startEditingParamAtCaret:r=>this.startEditingParamAtCaret(r),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill(),endTypedWord:()=>this.endTypedWord()}),this.unsubscribers.push(this.store.subscribe((r,i)=>{r.text!==i.text&&this.emitter.emit("change",r.text),r.completedParams!==i.completedParams&&this.emitter.emit("paramsChange",r.completedParams),r.isFocused!==i.isFocused&&(r.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",r)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.subscribeVisibleImpression(),this.unsubscribers.push(this.store.subscribe((r,i)=>{if(r.text===i.text&&r.completedParams===i.completedParams||r.identifiedParams.length===0)return;let{valid:s,invalid:o}=xe(r.text,r.completedParams,r.identifiedParams);o.length>0&&this.store.set({identifiedParams:s})})),this.unsubscribers.push(this.store.subscribe((r,i)=>{if(r.identifiedParams===i.identifiedParams)return;let s=r.editingIdentified;if(!s||r.identifiedParams.some(l=>l.id===s.id))return;let o=0,a;for(let l of r.segments){if(l.type==="identified"&&o===s.anchor&&l.value===s.text){a=l.param;break}o+=l.value.length}if(a){this.store.set({editingIdentified:{...s,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(r=>{let i=r.pendingRangeStart;!i||i.key===we(r)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((r,i)=>{let s=r.pendingSpan;if(!s||r.text===i.text&&r.completedParams===i.completedParams&&r.identifiedParams===i.identifiedParams)return;let o=s.anchor;if(r.text!==i.text){let l=rr(i.text,r.text,o);if(l===null){this.store.set({pendingSpan:null});return}o=l}r.text.slice(o).trim().length===0||tr(r.segments,o)?this.store.set({pendingSpan:null}):o!==s.anchor&&this.store.set({pendingSpan:{anchor:o,snapshot:s.snapshot}})})),this.renderMode!=="headless"&&(Ni(this.opts.styleRoot??re(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let{isFocused:e,dropdownHeld:n}=this.store.get();this.optionSource.reset(),this.store.set({...$i(),isFocused:e,dropdownHeld:n,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.lastRequestId=null,this.lastImpressionKey="",this.pendingSearchStarted=!1,this.fetchController.doFetch("",[])}resetAfterSubmit(){this.opts.resetOnSubmit!==!1&&this.reset()}destroy(){this.destroyed=!0,this.fetchController.dispose(),this.optionSource.dispose(),this.holdOpen.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(Kr(this.domRefs.input),Mn(this.domRefs.dropdown)),this.dropdownRefs&&Mn(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}prefillText(e){this.applyTextChange(e,!1)}noteSearchStarted(){this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{}))}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let r of this.store.get().segments){let i=n;if(n+=r.value.length,r.type!=="text"&&e>i&&e<=n)return{kind:r.type,param:r.param,start:i,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(r=>r.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(r=>r.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:r}=this.store.get(),{start:i,end:s}=n;if(e===s){let{text:l,removed:u}=at(r,i,s);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>i?Math.max(i,d.filterBase-u):d.filterBase,l.length),...this.withoutChip(d,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let o=Kt(r,e),a=r.slice(0,o)+r.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),N(n.input,e);else{let r=this.opts.setCursor;r&&this.boundary.runListener("setCursor",()=>r(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let r=n.identifiedParams.find(u=>u.id===e);if(!r)return!1;let i=B(r);if(!T(i))return!1;let s=i==="date-range"?nt(r.text):null,o=0,a=-1;for(let u of n.segments){if(u.type!=="text"&&u.param.id===e){a=o;break}o+=u.value.length}if(a<0)return!1;let l=a+r.text.length;return this.store.set({editingIdentified:{id:e,parameter:r.parameter,anchor:a,tail:l,text:r.text,iso:s?s.start:Qt(r),isoEnd:s?s.end:null,format:i},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:l,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.parameter,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),r=n.products.findIndex(s=>s.id===e.id),i=n.customFields?.items?.matched?.find(s=>s.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...i&&{origin_id:i},position:r>=0?r+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.applyTextChange(e,!0)}applyTextChange(e,n){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,n)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!T(n.activeFormatType)||!n.dateView)return;let r=Mt(n.dateView,e);this.store.set({dateViewMonth:{...r,key:we(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=e.suggestions.filter(a=>a.parameter==="placeholder"),r=e.suggestions.filter(a=>a.parameter!=="placeholder");if(r.length===0||E(r[0]))return;let i=r[0],s=r.slice(1),o=e.skippedParams.some(a=>a.parameter===i.parameter);this.store.set({suggestions:[...n,...s],pillTapped:s.length>0,activeDropdownIndex:-1,...o?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),parameter:i.parameter,suggestionPlaceholder:i.text}]}}),s.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(r=>{this.boundary.runListener("subscribe",()=>e(r),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}getRequestId(){return this.lastRequestId}buildResult(){let e=this.store.get();return ie(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}refreshProducts(){this.opts.mapProducts&&this.productsController.refresh()}update(e){let n=this.opts.products,r=this.opts.mapProducts,i=this.opts.showProducts,s=this.opts.optionOverrides;Object.assign(this.opts,e),"language"in e&&this.updateLanguageAttribute(),"optionOverrides"in e&&e.optionOverrides!==s&&this.optionSource.refresh(),"products"in e&&e.products!==n||"showProducts"in e&&e.showProducts!==i?this.productsController.resync():"mapProducts"in e&&e.mapProducts!==r&&this.productsController.refresh(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==void 0||e.productImageFallback!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0||"language"in e)&&this.store.set({}),e.value!==void 0&&this.setValue(e.value),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=!this.store.get().text;this.applyOption(e),n&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let i=G(e);if(i){let s=n.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:i,key:we(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Rr(s,i));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(Bn),this.reEdit.selectOption(e);return}let r=Ur(n,e);if(r){if(this.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:r.telemetry.selectedOption,other_options:T(n.activeFormatType)?[]:r.telemetry.otherOptions,key:r.telemetry.key,position:T(n.activeFormatType)?null:r.telemetry.position,chip_origin:"tap"}),this.timers.clear(Bn),this.store.set({...r.patch,...st(n)}),this.startSelectionAnimationTimer(),this.timers.clear(Bi),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(Bi,()=>{this.store.get().suggestions.includes(i)&&this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==i)}))},Ui)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Ys,()=>this.store.set({inSelectionAnimation:!1}),Ui)}resolveVisitorId(){let e=this.opts.visitorId;if(typeof e!="function")return e;try{return e()}catch{return}}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}subscribeVisibleImpression(){this.unsubscribers.push(this.store.subscribe((e,n)=>{this.visibleImpression&&(!e.isDropdownOpen&&n.isDropdownOpen&&(this.lastImpressionKey=""),Wn(e)&&!Wn(n)&&queueMicrotask(()=>this.fireImpression()))}))}fireImpression(){if(this.funnelTelemetry!==!0||this.destroyed)return;let e=this.store.get();if(this.visibleImpression&&!Wn(e))return;let n=e.suggestions.filter(s=>s.parameter!=="placeholder"&&!E(s)).map(s=>({key:s.parameter,options:(s.options??[]).slice(0,Ks).map(o=>o.text)})),r=e.products.map(s=>s.id);if(n.length===0&&r.length===0)return;let i=JSON.stringify([n,r]);i!==this.lastImpressionKey&&(this.lastImpressionKey=i,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:r}))}fireTelemetry(e,n){let r=this.funnelTelemetry===!0;if(!r&&zs.has(e))return;if(!r&&e==="option"){let{key:s,position:o,chip_origin:a,...l}=n;n=l}let i=this.resolveSource();Br({source:i,sessionId:this.sessionId,visitorId:r?this.resolveVisitorId():void 0,requestId:r?this.lastRequestId:null,keepalive:r,type:e,language:te(this.opts.language),queryData:n,apiConfig:this.opts.apiConfig})}updateLanguageAttribute(){let{language:e}=k(this.opts.language);e!=="en"?this.container.dataset.aiaLanguage=e:delete this.container.dataset.aiaLanguage}setupContainer(){this.container.classList.add("magicx-aia"),this.updateLanguageAttribute(),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new Oe(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,get strings(){return k(e.opts.language)},get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get showChipIcons(){return e.opts.showChipIcons??!0},get showChipImages(){return e.opts.showChipImages??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.resetAfterSubmit(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i,!0),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Li(this.container,n);let r=()=>{this.domRefs&&Nn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),Nn(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,get strings(){return k(e.opts.language)},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Ii(this.container,n);let r=()=>{this.dropdownRefs&&Dn(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),Dn(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(rt),r=()=>e();n.addEventListener("change",r),this.unsubscribers.push(()=>n.removeEventListener("change",r))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let r={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(r);return}this.timers.schedule(Bn,()=>this.store.set(r),Zs)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(js,()=>this.store.set({newParamId:null}),Qs)}))}handleChange(e,n){let r=this.store.get();n&&e&&!r.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:s}=sr(e,r.completedParams);s.length>0&&this.store.set({completedParams:i});let o=this.heldIdentified;this.heldIdentified=null,this.openWordText=n&&/\S$/.test(e)?e:null,this.maybePromoteExactMatch(e),o&&/^\s+$/.test(e.slice(o.text.length))&&e.startsWith(o.text)&&this.admitIdentified(o.candidates),this.maybeOpenPendingSpan()}isWordOpen(){return this.opts.commitOnWordEnd===!0&&this.openWordText===this.store.get().text}admitIdentified(e){let n=this.store.get(),{valid:r}=xe(n.text,n.completedParams,e);r.length!==0&&this.store.set({identifiedParams:[...n.identifiedParams,...r]})}endTypedWord(){if(!this.isWordOpen())return!1;let e=this.heldIdentified;this.heldIdentified=null,this.openWordText=null;let n=this.store.get();this.maybePromoteExactMatch(n.text),e?.text===n.text&&this.admitIdentified(e.candidates);let r=this.store.get();return r.completedParams!==n.completedParams||r.identifiedParams!==n.identifiedParams}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=K(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=er(e.segments,n);e.text.slice(r).trim().length!==0&&this.store.set({pendingSpan:{anchor:r,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(s=>s.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionParameter,e.optionQuery))return;let n=e.caretOffset??e.editingAnchor,r=e.text.slice(e.editingAnchor,n);ne(e.editingParam.options,r).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:r}=D(e.text,e.completedParams);this.fetchController.doFetch(n,r)}commitIdentifiedDate(e){let n=this.store.get(),r=n.editingIdentified;if(!r)return;if(n.text.slice(r.anchor,r.tail)!==r.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=n.text.slice(0,r.anchor),s=n.text.slice(r.tail),o=r.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" "?`${o} `:o,u=i+l+s,d=u.length,c={id:crypto.randomUUID(),placeholder:"",parameter:r.parameter,text:o,value:e.value,kind:e.kind,suggestionParameter:r.parameter,suggestionPlaceholder:$(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:r.parameter,position:null,chip_origin:"tap"}),this.store.set({text:u,completedParams:[...n.completedParams,c],identifiedParams:n.identifiedParams.filter(f=>f.id!==r.id),newParamId:c.id,filterBase:d,caretOffset:d,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(d),this.fetchNow()}maybePromoteExactMatch(e){let n=this.store.get();if(T(n.activeFormatType)||this.isWordOpen())return;let r=it({mode:"fresh",text:e,completedParams:n.completedParams,suggestions:n.suggestions,filterBase:n.filterBase,filterInProgress:n.filterInProgress,phraseExactMatch:this.fetchController.isPhraseExactMatch()});if(r){if(this.funnelTelemetry===!0){let i=n.actionableSuggestions[0],s=i.options??[];this.fireTelemetry("option",{raw_query:D(e,n.completedParams).rawQuery,selected_option:r.option.text,other_options:s.filter(o=>o.text!==r.option.text).map(o=>o.text),key:i.parameter,position:oe(s,r.option.text),chip_origin:"typed"})}this.store.set(r.patch)}}};export{Un as AIAutocomplete,zr as ATTRIBUTION_URL,Zt as DATE_RANGE_META_END,Jt as DATE_RANGE_META_START,mi as DEFAULT_OPTION_COUNT_UNIT,Oe as ModeController,rt as OPTIONS_GRID_MOBILE_QUERY,wn as OPTION_ENTER_DELAY_VAR,os as OPTION_ENTER_FADE_MS,ss as OPTION_ENTER_RISE_MS,as as OPTION_ENTER_RISE_PX,is as OPTION_ENTER_STAGGER_MS,xn as OPTION_IMAGE_WIDTH,Fo as PLACEHOLDER_FADE_OUT_MS,ue as PLACEHOLDER_LEAVING_ATTR,Wo as PLACEHOLDER_SWAP_GAP_MS,No as PLACEHOLDER_TYPE_MS,Ho as PLACEHOLDER_WORD_PAUSE_MS,Jo as PRODUCT_IMAGE_WIDTH,wr as PRODUCT_PATH_PREFIX,Xo as PRODUCT_ROW_PX_PER_LINE,kr as RANGE_SEPARATOR,zn as SCHEMA_VERSION,xi as SCROLL_ARROW_ATTR,Ti as SCROLL_ARROW_BOTTOM_VAR,yi as SCROLL_ARROW_CLASS,vi as SCROLL_ARROW_FADE_MS,vs as SCROLL_ARROW_LABEL,Pi as SCROLL_ARROW_SCROLL_IDLE_MS,me as SCROLL_ARROW_VISIBLE_ATTR,Vn as SKIPPED_PARAM_TEXT,Ot as SMART_SUGGESTION_SPARKLE_SVG,ge as VIEWPORT_FIT_ATTR,ft as VIEWPORT_FIT_HEIGHT_VAR,Ge as WEEKDAY_LABELS,Mt as addMonths,Sn as attachProductRowWheel,Ln as attachScrollArrow,Rn as attachViewportFit,un as buildAttributionUrl,Dt as buildDateOptions,D as buildQuery,ie as buildSubmitResult,Nt as cellDay,G as cellIso,Gt as chipIdFromTap,Mr as computeOptionsGridLayout,gn as containScroll,Hn as createStore,qt as cursorIsAtEnd,hn as dateCellMarks,Ie as dateSelectionFor,Qe as extractPlainText,ce as formatAbsoluteDate,gr as formatDate,Lr as formatDateRange,Ce as formatOptionCount,W as getCursorOffset,mn as getFooterHint,At as hasSkippablePill,cn as highlightParts,$ as identifiedParamLabel,T as isCalendarFormat,sn as isOptionsGridMobileViewport,Fe as isSmartSuggestion,E as isTraditionalAutocompleteSuggestion,F as isoDate,Vt as keepCaretOnChip,Ct as labelTraditionalAutocomplete,ot as matchTypedPhrase,on as measureOptionsGrid,Lt as monthLabel,nn as needsOptionsGridMeasurement,gs as optionCountLabel,In as optionEnterDelayMs,gi as optionHasImage,gt as optionImageSources,ae as optionImageSrc,pt as optionLabel,Cn as optionsEntranceDurationMs,tn as optionsGridTemplateColumns,On as optionsShowLeadingVisuals,Ve as parseDate,Pe as parseLooseDate,nt as parseLooseDateRange,Ut as plainTextLength,rn as planOptionsGrid,Kt as previousGraphemeBoundary,Ir as productFromMatchedItem,ut as productImageSources,es as productImageSrc,yn as productInitial,oi as productRowWheelTarget,Yt as productsFromCustomFields,_n as renderEditableContent,B as resolveFormatType,Qt as resolveIdentifiedDate,an as sameOptionRows,se as sanitizeOptionIconSvg,Ft as scrollCaretIntoView,_t as selectedIsoFromText,Ee as selectedRangeFor,N as setCursorOffset,li as shopifyImageSrc,he as toWireIdentifiedParams,Hr as typedFragment,k as uiStringsFor,fn as visibleDateRange,be as withSkippedParams,It as withoutTraditionalAutocomplete};
2684
+ `;var vt=class{constructor(){this.reported=new Set}run(e,n){try{return n()}catch(r){this.report(e,r,e);return}}runListener(e,n,r=e){try{return n(),!0}catch(i){return this.report(e,i,r),!1}}report(e,n,r){this.reported.has(r)||(this.reported.add(r),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,n))}};var Pt=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,n){let r=`${String(e)}#${++this.registrationCount}`,i=(...o)=>n(...o);this.keys.set(i,r);let s=this.listeners[e];return s||(s=new Set,this.listeners[e]=s),s.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...n){let r=this.listeners[e];if(!r)return!0;let i=!0;for(let s of r)this.boundary.runListener(String(e),()=>s(...n),this.keys.get(s)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Tt=class{constructor(){this.timers=new Map}schedule(e,n,r){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),n()},r);this.timers.set(e,i)}clear(e){let n=this.timers.get(e);n!==void 0&&(clearTimeout(n),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};function zs(t){let e;try{e=new URL(t??K).host}catch{return null}let n=Re.get(e);return n?`https://${n}`:null}var Wi=new WeakMap;function Bi(t,e){if(!t.head)return;let n=zs(e);if(!n)return;let r=Wi.get(t);r||(r=new Map,Wi.set(t,r));let i=r.get(n);i||(i=t.createElement("link"),i.rel="preconnect",i.href=n,r.set(n,i)),t.head.append(i)}var ke=class{constructor(e,n="auto",r){this.container=e;this.mode=n;this.onResolve=r;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function Wn(t){return t.isDropdownOpen&&!t.isLoading}var js=50,Ys=new Set(["search_started","submit","product_click","impression"]),Qs="newParam",Ui="suggestionRemoval",Xs="selectionAnimation",Bn="skeletonExit",Js=650,Zs=0;function ea(){return`:ac-${++Zs}:`}var $i=170,ta=100;function Gi(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],traditionalAutocomplete:!1,customFields:null,optionSearch:null,activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,dropdownHeld:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var Un=class{constructor(e,n={}){this.inputStore=Hn(Gi());this._listboxId=ea();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Tt;this.boundary=new vt;this.subscriberCount=0;this.emitter=new Pt(this.boundary);this.sessionId=crypto.randomUUID();this.lastRequestId=null;this.searchStartedSessionId=null;this.funnelTelemetry=null;this.pendingSearchStarted=!1;this.openWordText=null;this.heldIdentified=null;this.lastImpressionKey="";this.visibleImpression=!1;this.destroyed=!1;this.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=n,this.renderMode=n.renderMode??"full",this.store=Mi(this.inputStore,r=>Nr(r,this.opts)),n.onSubmit&&this.emitter.on("submit",n.onSubmit),n.onResult&&this.emitter.on("result",n.onResult),n.onError&&this.emitter.on("error",n.onError),n.onChange&&this.emitter.on("change",n.onChange),n.onParamsChange&&this.emitter.on("paramsChange",n.onParamsChange),n.onStateChange&&this.emitter.on("stateChange",n.onStateChange),n.onFocus&&this.emitter.on("focus",n.onFocus),n.onBlur&&this.emitter.on("blur",n.onBlur),n.onProductSelect&&this.emitter.on("productSelect",n.onProductSelect),n.value!==void 0&&this.store.set({text:n.value}),n.completedParams!==void 0&&this.store.set({completedParams:n.completedParams}),this.holdOpen=new Ge(this.store,e),this.pillsController=new et(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:s})}}),this.reEdit=new ct({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new tt(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1,()=>this.opts.language,()=>this.opts.mapProducts),this.optionSource=new Ze(this.store,()=>this.opts.optionOverrides,{onAnswer:r=>{r==="edit"?this.reEdit.promoteIfExact():this.maybePromoteExactMatch(this.store.get().text)},onMiss:(r,i)=>{r==="pill"&&i.length>0&&this.fetchController.attemptNow()}}),this.fetchController=new $e(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,()=>this.resolveSource(),()=>this.opts.additionalContext,()=>this.opts.language,{getProductId:()=>this.opts.productId,getCurrency:()=>this.opts.currency,onRequest:({query:r,signal:i,isCurrent:s})=>{Bi(this.container.ownerDocument,this.opts.apiConfig?.endpoint),this.productsController.run(r,i,s).catch(()=>{})},onAutoMatch:({active:r,matched:i,rawQuery:s})=>{let o=r.options??[];this.fireTelemetry("option",{raw_query:s,selected_option:i.text,other_options:o.filter(a=>a.text!==i.text).map(a=>a.text),key:r.parameter,position:oe(o,i.text),chip_origin:"typed"})},onResponse:({requestId:r,funnelTelemetry:i,visibleImpression:s})=>{this.lastRequestId=r,this.funnelTelemetry=i,this.visibleImpression=s,this.pendingSearchStarted&&(this.pendingSearchStarted=!1,this.fireTelemetry("search_started",{})),this.fireImpression(),this.emitter.hasListeners("result")&&this.emitter.emit("result",this.buildResult())},productsForResponse:r=>this.productsController.forResponse(r),consumerTick:(r,i)=>this.optionSource.tick(r,i),isWordOpen:()=>this.isWordOpen(),holdIdentified:r=>{this.heldIdentified={text:this.store.get().text,candidates:r}}}),this.keyboardController=new Je(this.store,{columns:n.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.resetAfterSubmit():void 0,selectOption:r=>this.selectOption(r),removeParamAtCaret:r=>this.removeParamAtCaret(r),startEditingParamAtCaret:r=>this.startEditingParamAtCaret(r),exitEditMode:()=>this.exitEditMode(),exitEditingIdentified:()=>this.exitEditingIdentified(),skipActivePill:()=>this.skipActivePill(),endTypedWord:r=>this.endTypedWord(r)}),this.unsubscribers.push(this.store.subscribe((r,i)=>{r.text!==i.text&&this.emitter.emit("change",r.text),r.completedParams!==i.completedParams&&this.emitter.emit("paramsChange",r.completedParams),r.isFocused!==i.isFocused&&(r.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",r)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.subscribeSkeletonMirror(),this.subscribeVisibleImpression(),this.unsubscribers.push(this.store.subscribe((r,i)=>{if(r.text===i.text&&r.completedParams===i.completedParams||r.identifiedParams.length===0)return;let{valid:s,invalid:o}=Pe(r.text,r.completedParams,r.identifiedParams);o.length>0&&this.store.set({identifiedParams:s})})),this.unsubscribers.push(this.store.subscribe((r,i)=>{if(r.identifiedParams===i.identifiedParams)return;let s=r.editingIdentified;if(!s||r.identifiedParams.some(l=>l.id===s.id))return;let o=0,a;for(let l of r.segments){if(l.type==="identified"&&o===s.anchor&&l.value===s.text){a=l.param;break}o+=l.value.length}if(a){this.store.set({editingIdentified:{...s,id:a.id}});return}this.store.set({editingIdentified:null,activeDropdownIndex:-1})})),this.unsubscribers.push(this.store.subscribe(r=>{let i=r.pendingRangeStart;!i||i.key===Ce(r)||this.store.set({pendingRangeStart:null})})),this.unsubscribers.push(this.store.subscribe((r,i)=>{let s=r.pendingSpan;if(!s||r.text===i.text&&r.completedParams===i.completedParams&&r.identifiedParams===i.identifiedParams)return;let o=s.anchor;if(r.text!==i.text){let l=rr(i.text,r.text,o);if(l===null){this.store.set({pendingSpan:null});return}o=l}r.text.slice(o).trim().length===0||tr(r.segments,o)?this.store.set({pendingSpan:null}):o!==s.anchor&&this.store.set({pendingSpan:{anchor:o,snapshot:s.snapshot}})})),this.renderMode!=="headless"&&(Hi(this.opts.styleRoot??re(this.container)),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.optionSource.start(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let{isFocused:e,dropdownHeld:n}=this.store.get();this.optionSource.reset(),this.store.set({...Gi(),isFocused:e,dropdownHeld:n,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.lastRequestId=null,this.lastImpressionKey="",this.pendingSearchStarted=!1,this.fetchController.doFetch("",[])}resetAfterSubmit(){this.opts.resetOnSubmit!==!1&&this.reset()}destroy(){this.destroyed=!0,this.fetchController.dispose(),this.optionSource.dispose(),this.holdOpen.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs&&(zr(this.domRefs.input),Mn(this.domRefs.dropdown)),this.dropdownRefs&&Mn(this.dropdownRefs.dropdown),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}prefillText(e){this.applyTextChange(e,!1)}noteSearchStarted(){this.searchStartedSessionId!==this.sessionId&&(this.searchStartedSessionId=this.sessionId,this.funnelTelemetry===null?this.pendingSearchStarted=!0:this.fireTelemetry("search_started",{}))}setValue(e){let n=this.store.get();if(n.editingIdentified&&e!==n.text){this.store.set({text:e,editingIdentified:null,activeDropdownIndex:-1});return}this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let n=this.store.get().text.length;this.store.set({caretOffset:n,isFocused:!0}),this.scheduleSetCursor(n)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let n=0;for(let r of this.store.get().segments){let i=n;if(n+=r.value.length,r.type!=="text"&&e>i&&e<=n)return{kind:r.type,param:r.param,start:i,end:n}}return null}withoutChip(e,n){return n.kind==="completed"?{completedParams:e.completedParams.filter(r=>r.id!==n.param.id)}:{identifiedParams:e.identifiedParams.filter(r=>r.id!==n.param.id)}}removeParamAtCaret(e){let n=this.findChipSpanAt(e);if(!n)return!1;let{text:r}=this.store.get(),{start:i,end:s}=n;if(e===s){let{text:l,removed:d}=lt(r,i,s);return this.store.set(c=>({text:l,filterBase:Math.min(c.filterBase>i?Math.max(i,c.filterBase-d):c.filterBase,l.length),...this.withoutChip(c,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let o=Kt(r,e),a=r.slice(0,o)+r.slice(e);return this.store.set(l=>({text:a,filterBase:Math.min(l.filterBase,a.length),...this.withoutChip(l,n),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}startEditingParamAtCaret(e){let n=this.findChipSpanAt(e);return!n||n.kind!=="completed"||n.end!==e?!1:(this.reEdit.start(n.param.id),this.store.get().editingParam?.id===n.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let n=this.domRefs;if(n)n.input.focus(),N(n.input,e);else{let r=this.opts.setCursor;r&&this.boundary.runListener("setCursor",()=>r(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let n=this.store.get();if(n.editingIdentified?.id===e)return!0;let r=n.identifiedParams.find(d=>d.id===e);if(!r)return!1;let i=U(r);if(!T(i))return!1;let s=i==="date-range"?rt(r.text):null,o=0,a=-1;for(let d of n.segments){if(d.type!=="text"&&d.param.id===e){a=o;break}o+=d.value.length}if(a<0)return!1;let l=a+r.text.length;return this.store.set({editingIdentified:{id:e,parameter:r.parameter,anchor:a,tail:l,text:r.text,iso:s?s.start:Qt(r),isoEnd:s?s.end:null,format:i},editingParam:null,editingAnchor:null,editingTail:null,caretOffset:l,activeDropdownIndex:-1,pillTapped:!0}),!0}exitEditingIdentified(){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1})}startEditingParam(e){this.reEdit.start(e),this.store.get().editingParam?.id!==e&&this.startEditingIdentified(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){let n=this.store.get().editingIdentified;n&&e!=null&&(e<n.anchor||e>n.tail)&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}clearHighlight(e){this.store.get().activeDropdownIndex===e&&this.store.set({activeDropdownIndex:-1})}prepareSubmit(){this.endTypedWord(!0)}recordSubmit(e){this.fireTelemetry("submit",{query:e.query,completed_pills:e.completed_params.filter(n=>n.placeholder).map(n=>({key:n.parameter,value:n.text??""}))})}selectProduct(e){let n=this.store.get(),r=n.products.findIndex(s=>s.id===e.id),i=n.customFields?.items?.matched?.find(s=>s.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:n.text,product_id:e.id,...i&&{origin_id:i},position:r>=0?r+1:null}),this.emitter.emit("productSelect",e)}handleTextChange(e){this.applyTextChange(e,!0)}applyTextChange(e,n){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,n)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let n=this.store.get();if(!T(n.activeFormatType)||!n.dateView)return;let r=Mt(n.dateView,e);this.store.set({dateViewMonth:{...r,key:Ce(n)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let n=e.suggestions.filter(a=>a.parameter==="placeholder"),r=e.suggestions.filter(a=>a.parameter!=="placeholder");if(r.length===0||E(r[0]))return;let i=r[0],s=r.slice(1),o=e.skippedParams.some(a=>a.parameter===i.parameter);this.store.set({suggestions:[...n,...s],pillTapped:s.length>0,activeDropdownIndex:-1,...o?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),parameter:i.parameter,suggestionPlaceholder:i.text}]}}),s.length===0&&this.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let n=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(r=>{this.boundary.runListener("subscribe",()=>e(r),n)})}getState(){return this.store.get()}getResult(){return this.buildResult()}getRequestId(){return this.lastRequestId}buildResult(){let e=this.store.get();return ie(e.text,e.completedParams,e.skippedParams,{identifiedParams:e.identifiedParams,isReady:e.isReady,customFields:e.customFields})}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,n){return this.emitter.on(e,n)}refreshProducts(){this.opts.mapProducts&&this.productsController.refresh()}update(e){let n=this.opts.products,r=this.opts.mapProducts,i=this.opts.showProducts,s=this.opts.optionOverrides;Object.assign(this.opts,e),"language"in e&&this.updateLanguageAttribute(),"optionOverrides"in e&&e.optionOverrides!==s&&this.optionSource.refresh(),"products"in e&&e.products!==n||"showProducts"in e&&e.showProducts!==i?this.productsController.resync():"mapProducts"in e&&e.mapProducts!==r&&this.productsController.refresh(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0||e.showOptionIcons!==void 0||e.showOptionImages!==void 0||e.showOptionCounts!==void 0||e.productsLayout!==void 0||e.productImageFallback!==void 0||e.showChipIcons!==void 0||e.showChipImages!==void 0||"language"in e)&&this.store.set({}),e.value!==void 0&&this.setValue(e.value),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let n=!this.store.get().text;this.applyOption(e),n&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let n=this.store.get();if(n.activeFormatType==="date-range"){let i=V(e);if(i){let s=n.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:i,key:Ce(n)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(Rr(s,i));return}}if(n.editingIdentified){this.commitIdentifiedDate(e);return}if(n.editingParam&&n.editingAnchor!=null&&n.editingTail!=null){this.timers.clear(Bn),this.reEdit.selectOption(e);return}let r=$r(n,e);if(r){if(this.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:r.telemetry.selectedOption,other_options:T(n.activeFormatType)?[]:r.telemetry.otherOptions,key:r.telemetry.key,position:T(n.activeFormatType)?null:r.telemetry.position,chip_origin:"tap"}),this.timers.clear(Bn),this.store.set({...r.patch,...at(n)}),this.startSelectionAnimationTimer(),this.timers.clear(Ui),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(Ui,()=>{this.store.get().suggestions.includes(i)&&this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==i)}))},$i)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Xs,()=>this.store.set({inSelectionAnimation:!1}),$i)}resolveVisitorId(){let e=this.opts.visitorId;if(typeof e!="function")return e;try{return e()}catch{return}}resolveSource(){return this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk")}subscribeVisibleImpression(){this.unsubscribers.push(this.store.subscribe((e,n)=>{this.visibleImpression&&(!e.isDropdownOpen&&n.isDropdownOpen&&(this.lastImpressionKey=""),Wn(e)&&!Wn(n)&&queueMicrotask(()=>this.fireImpression()))}))}fireImpression(){if(this.funnelTelemetry!==!0||this.destroyed)return;let e=this.store.get();if(this.visibleImpression&&!Wn(e))return;let n=e.suggestions.filter(s=>s.parameter!=="placeholder"&&!E(s)).map(s=>({key:s.parameter,options:(s.options??[]).slice(0,js).map(o=>o.text)})),r=e.products.map(s=>s.id);if(n.length===0&&r.length===0)return;let i=JSON.stringify([n,r]);i!==this.lastImpressionKey&&(this.lastImpressionKey=i,this.fireTelemetry("impression",{query:e.text,pills:n,product_ids:r}))}fireTelemetry(e,n){let r=this.funnelTelemetry===!0;if(!r&&Ys.has(e))return;if(!r&&e==="option"){let{key:s,position:o,chip_origin:a,...l}=n;n=l}let i=this.resolveSource();Ur({source:i,sessionId:this.sessionId,visitorId:r?this.resolveVisitorId():void 0,requestId:r?this.lastRequestId:null,keepalive:r,type:e,language:te(this.opts.language),queryData:n,apiConfig:this.opts.apiConfig})}updateLanguageAttribute(){let{language:e}=k(this.opts.language);e!=="en"?this.container.dataset.aiaLanguage=e:delete this.container.dataset.aiaLanguage}setupContainer(){this.container.classList.add("magicx-aia"),this.updateLanguageAttribute(),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new ke(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,n={store:this.store,listboxId:this.listboxId,get strings(){return k(e.opts.language)},get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get showChipIcons(){return e.opts.showChipIcons??!0},get showChipImages(){return e.opts.showChipImages??!0},get optionsPosition(){return e.opts.optionsPosition??"below"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.resetAfterSubmit(),endTypedWord:()=>e.endTypedWord(!0),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth(),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i,!0),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ri(this.container,n);let r=()=>{this.domRefs&&Nn(this.domRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),Nn(this.domRefs,this.store.get(),n),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,n={store:this.store,listboxId:this.listboxId,get strings(){return k(e.opts.language)},get showSkipButton(){return e.opts.showSkipButton??!0},get showOptionIcons(){return e.opts.showOptionIcons??!0},get showOptionImages(){return e.opts.showOptionImages??!0},get showOptionCounts(){return e.opts.showOptionCounts??!0},get productsLayout(){return e.opts.productsLayout??"row"},get productImageFallback(){return e.opts.productImageFallback??"image"},get optionsPosition(){return e.opts.optionsPosition??"below"},selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),skipActivePill:()=>this.skipActivePill(),selectProduct:i=>this.selectProduct(i),showPreviousMonth:()=>this.showPreviousMonth(),showNextMonth:()=>this.showNextMonth()};this.dropdownRefs=Ci(this.container,n);let r=()=>{this.dropdownRefs&&Dn(this.dropdownRefs,this.store.get(),n)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),Dn(this.dropdownRefs,this.store.get(),n),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let n=window.matchMedia(it),r=()=>e();n.addEventListener("change",r),this.unsubscribers.push(()=>n.removeEventListener("change",r))}subscribeBatchedRender(e){let n=!1;this.unsubscribers.push(this.store.subscribe(()=>{n||(n=!0,queueMicrotask(()=>{n=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,n)=>{if(!e.skeletonOptions)return;if(!n.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!n.isLoading||e.isLoading)return;let r={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(r);return}this.timers.schedule(Bn,()=>this.store.set(r),ta)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,n)=>{e.newParamId&&e.newParamId!==n.newParamId&&this.timers.schedule(Qs,()=>this.store.set({newParamId:null}),Js)}))}handleChange(e,n){let r=this.store.get();n&&e&&!r.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:s}=sr(e,r.completedParams);s.length>0&&this.store.set({completedParams:i});let o=this.heldIdentified;this.heldIdentified=null,this.openWordText=n&&/\S$/.test(e)?e:null,this.maybePromoteExactMatch(e),o&&/^\s+$/.test(e.slice(o.text.length))&&e.startsWith(o.text)&&this.admitIdentified(o.candidates),this.maybeOpenPendingSpan()}isWordOpen(){return this.opts.commitOnWordEnd===!0&&this.openWordText===this.store.get().text}admitIdentified(e){let n=this.store.get(),{valid:r}=Pe(n.text,n.completedParams,e);r.length!==0&&this.store.set({identifiedParams:[...n.identifiedParams,...r]})}endTypedWord(e=!1){let n=this.isWordOpen();if(!n&&!e)return!1;let r=this.heldIdentified;this.heldIdentified=null,this.openWordText=null;let i=this.store.get();this.maybePromoteExactMatch(i.text,e?"submit":"fresh",n),r?.text===i.text&&this.admitIdentified(r.candidates);let s=this.store.get();return s.completedParams!==i.completedParams||s.identifiedParams!==i.identifiedParams}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let n=z(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=er(e.segments,n);e.text.slice(r).trim().length!==0&&this.store.set({pendingSpan:{anchor:r,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(s=>s.id===e.editingParam?.id)||this.optionSource.owns(e.editingParam.suggestionParameter,e.optionQuery))return;let n=e.caretOffset??e.editingAnchor,r=e.text.slice(e.editingAnchor,n);ne(e.editingParam.options,r).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:n,completedParams:r}=D(e.text,e.completedParams);this.fetchController.doFetch(n,r)}commitIdentifiedDate(e){let n=this.store.get(),r=n.editingIdentified;if(!r)return;if(n.text.slice(r.anchor,r.tail)!==r.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=n.text.slice(0,r.anchor),s=n.text.slice(r.tail),o=r.anchor===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" "?`${o} `:o,d=i+l+s,c=d.length,u={id:crypto.randomUUID(),placeholder:"",parameter:r.parameter,text:o,value:e.value,kind:e.kind,suggestionParameter:r.parameter,suggestionPlaceholder:G(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:D(n.text,n.completedParams).rawQuery,selected_option:e.text,other_options:[],key:r.parameter,position:null,chip_origin:"tap"}),this.store.set({text:d,completedParams:[...n.completedParams,u],identifiedParams:n.identifiedParams.filter(f=>f.id!==r.id),newParamId:u.id,filterBase:c,caretOffset:c,editingIdentified:null,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.startSelectionAnimationTimer(),this.scheduleSetCursor(c),this.fetchNow()}maybePromoteExactMatch(e,n="fresh",r=!1){let i=this.store.get();if(T(i.activeFormatType)||this.isWordOpen())return;let s=ot({mode:n,finishWord:r,text:e,completedParams:i.completedParams,suggestions:i.suggestions,filterBase:i.filterBase,filterInProgress:i.filterInProgress,phraseExactMatch:this.fetchController.isPhraseExactMatch()});if(s){if(this.funnelTelemetry===!0){let o=n==="submit"&&s.suggestion?s.suggestion:i.actionableSuggestions[0],a=o.options??[];this.fireTelemetry("option",{raw_query:D(e,i.completedParams).rawQuery,selected_option:s.option.text,other_options:a.filter(l=>l.text!==s.option.text).map(l=>l.text),key:o.parameter,position:oe(a,s.option.text),chip_origin:"typed"})}this.store.set(s.patch)}}};export{Un as AIAutocomplete,jr as ATTRIBUTION_URL,Zt as DATE_RANGE_META_END,Jt as DATE_RANGE_META_START,gi as DEFAULT_OPTION_COUNT_UNIT,ke as ModeController,it as OPTIONS_GRID_MOBILE_QUERY,wn as OPTION_ENTER_DELAY_VAR,as as OPTION_ENTER_FADE_MS,ls as OPTION_ENTER_RISE_MS,cs as OPTION_ENTER_RISE_PX,ss as OPTION_ENTER_STAGGER_MS,xn as OPTION_IMAGE_WIDTH,Bo as PLACEHOLDER_FADE_OUT_MS,pe as PLACEHOLDER_LEAVING_ATTR,Uo as PLACEHOLDER_SWAP_GAP_MS,Fo as PLACEHOLDER_TYPE_MS,Wo as PLACEHOLDER_WORD_PAUSE_MS,es as PRODUCT_IMAGE_WIDTH,wr as PRODUCT_PATH_PREFIX,Zo as PRODUCT_ROW_PX_PER_LINE,kr as RANGE_SEPARATOR,zn as SCHEMA_VERSION,vi as SCROLL_ARROW_ATTR,Ei as SCROLL_ARROW_BOTTOM_VAR,xi as SCROLL_ARROW_CLASS,Pi as SCROLL_ARROW_FADE_MS,Ts as SCROLL_ARROW_LABEL,Ti as SCROLL_ARROW_SCROLL_IDLE_MS,ge as SCROLL_ARROW_VISIBLE_ATTR,Vn as SKIPPED_PARAM_TEXT,Ot as SMART_SUGGESTION_SPARKLE_SVG,fe as VIEWPORT_FIT_ATTR,ht as VIEWPORT_FIT_HEIGHT_VAR,Ve as WEEKDAY_LABELS,Mt as addMonths,Sn as attachProductRowWheel,Ln as attachScrollArrow,Rn as attachViewportFit,un as buildAttributionUrl,Dt as buildDateOptions,D as buildQuery,ie as buildSubmitResult,Nt as cellDay,V as cellIso,Gt as chipIdFromTap,Mr as computeOptionsGridLayout,gn as containScroll,Hn as createStore,qt as cursorIsAtEnd,hn as dateCellMarks,Oe as dateSelectionFor,Xe as extractPlainText,de as formatAbsoluteDate,gr as formatDate,Lr as formatDateRange,Ae as formatOptionCount,W as getCursorOffset,mn as getFooterHint,At as hasSkippablePill,cn as highlightParts,G as identifiedParamLabel,T as isCalendarFormat,sn as isOptionsGridMobileViewport,Be as isSmartSuggestion,E as isTraditionalAutocompleteSuggestion,F as isoDate,Vt as keepCaretOnChip,Ct as labelTraditionalAutocomplete,st as matchTypedPhrase,on as measureOptionsGrid,Lt as monthLabel,nn as needsOptionsGridMeasurement,hs as optionCountLabel,In as optionEnterDelayMs,fi as optionHasImage,ft as optionImageSources,ae as optionImageSrc,mt as optionLabel,Cn as optionsEntranceDurationMs,tn as optionsGridTemplateColumns,On as optionsShowLeadingVisuals,qe as parseDate,Ee as parseLooseDate,rt as parseLooseDateRange,Ut as plainTextLength,rn as planOptionsGrid,Kt as previousGraphemeBoundary,Ir as productFromMatchedItem,pt as productImageSources,ns as productImageSrc,yn as productInitial,si as productRowWheelTarget,Yt as productsFromCustomFields,_n as renderEditableContent,U as resolveFormatType,Qt as resolveIdentifiedDate,an as sameOptionRows,se as sanitizeOptionIconSvg,Ft as scrollCaretIntoView,_t as selectedIsoFromText,Ie as selectedRangeFor,N as setCursorOffset,ci as shopifyImageSrc,be as toWireIdentifiedParams,Fr as typedFragment,k as uiStringsFor,fn as visibleDateRange,Se as withSkippedParams,It as withoutTraditionalAutocomplete};
2685
2685
  //# sourceMappingURL=index.mjs.map