@magicx-eng/ai-autocomplete-vanilla 0.42.1 → 0.43.0
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.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
function P(n){return n==="date"||n==="date-range"}function X(n){return n?.type?.kind==="date"?"date":n?.type?.kind==="date_range"?"date-range":"options"}var Oe=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 li="https://api.ai-autocomplete.com",re=`${li}/api/suggest`,Sn=new WeakMap;function ue(n){return n?.type==="accessToken"}function di(n){if(!(!n||ue(n)))return n}function Ae(n){let e=Sn.get(n.getAccessToken);return e||(e=new Oe(n),Sn.set(n.getAccessToken,e)),e}function Le(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Re(n){let e=di(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function pe(n){return n.map(e=>({parameter:e.parameter,text:e.text}))}var xn="skipped";function me(n,e){if(e.length===0)return n;let t=new Set(n.map(i=>i.parameter)),r=e.filter(i=>!t.has(i.parameter)).map(i=>({placeholder:"",parameter:i.parameter,text:xn,kind:null}));return r.length>0?[...n,...r]:n}var ci="0.42.1",Pn="1.0",yn=!1;function ui(n,e){return{placeholder:n.placeholder,parameter:n.parameter,...e&&{text:n.value??n.text},kind:n.kind}}function ge(n){return n??(typeof navigator<"u"?navigator.language:"en-US")}function pi(n,e,t,r,i,s,o,a,l,c,d){let u=e.find(p=>p.parameter==="contact"&&p.metadata?.contact_account_count)?.metadata?.contact_account_count,g=typeof u=="number"?u:void 0;return{data:{raw_query:n,completed_params:me(e.map(p=>ui(p,t)),l??[]),...o&&o.length>0&&{identified_params:pe(o)},...a&&a.length>0&&{recently_suggested:a},...g!=null&&{contact_account_count:g},...c!==void 0&&{additional_context:c}},meta:{request_id:i,request_at:new Date().toISOString(),language:ge(d),client_version:ci,session_id:r,source:s,schema_version:Pn}}}async function vn(n,e,t,r,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:r,signal:i})}async function En(n,e,t){let r=t.apiConfig,i=!t.maskCompletedText,s=pi(n,e,i,t.sessionId,t.requestId??crypto.randomUUID(),t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext,t.language),o=Le(r),a=r?.endpoint??re,l=JSON.stringify(s);if(ue(r)){let u=Ae(r),g=await u.getToken(),p=await vn(a,o,g,l,t.signal);if(p.status===401){let f=await u.getToken(!0);p=await vn(a,o,f,l,t.signal)}if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}let c=Re(r);!c&&!yn&&(yn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let d=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}var Me=/[\p{L}\p{N}]/u,mi=/['\u2019-]/;function wn(n,e,t){let r=n[e];if(r===void 0)return!1;if(Me.test(r))return!0;let i=n[e+t];return mi.test(r)&&i!==void 0&&Me.test(i)}function gi(n,e,t){let r=e+t.length;return!(Me.test(t[0])&&wn(n,e-1,-1)||Me.test(t[t.length-1])&&wn(n,r,1))}function W(n,e,t=0,r=()=>!0){if(e.length===0)return n.indexOf(e,t);let i=-1,s=n.indexOf(e,t);for(;s!==-1;){if(r(s)){if(gi(n,s,e))return s;i===-1&&(i=s)}s=n.indexOf(e,s+1)}return i}function L(n,e){let t=n,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}}}`,u=p=>W(t,a.text,p,f=>!s.some(x=>f<x.end&&f+a.text.length>x.start)),g=u(o);if(g===-1&&(g=u(0)),g!==-1){t=t.slice(0,g)+d+t.slice(g+a.text.length);let p=d.length-a.text.length;for(let f of s)f.start>=g+a.text.length&&(f.start+=p,f.end+=p);s.push({start:g,end:g+d.length}),o=g>=o?g+d.length:o+p}i.push({...a,placeholder:d})}return{rawQuery:t,completedParams:i}}function q(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function De(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function fe(n,e,t){let r=n.slice(e);if(t||e===0||n[e-1]===" ")return r;let i=r.indexOf(" ");return i===-1?"":r.slice(i+1)}function Tn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let r=t.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=t.length-o.length;return n.length-a}}return 0}function j(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let r=t.toLowerCase();return n.filter(i=>!i.is_tappable||i.text.toLowerCase().includes(r))}function ke(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let r=t.toLowerCase();return n.find(i=>i.is_tappable&&i.text.toLowerCase()===r)??null}function he(n,e,t,r,i){let s=fe(e,t,r),o=ke(n,s);if(o||!i||!s.trim())return o;if(s===e.slice(t))return null;let a=e.lastIndexOf(" ",t-1)+1;return ke(n,e.slice(a))}function In(n,e){return e?n.map(t=>e[t.parameter]?{...t,options:[]}:t):n}function fi(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function z(n){let e=fi(n);return e.length>0?e.join(" "):n}function B(n,e){return n.parameter||e}function Cn(n,e){let t=0,r=e;for(let i of n)t+=i.value.length,i.type!=="text"&&(r=Math.max(r,t));return r}function On(n,e){let t=0;for(let r of n){let i=t+r.value.length;if(r.type==="text"&&i>e&&r.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=i}return!0}function An(n,e){let t=[],r=new Set;for(let i of[...n,...e])i.parameter==="placeholder"||r.has(i.parameter)||(r.add(i.parameter),t.push({parameter:i.parameter,text:i.text}));return t}function Ln(n,e,t){if(n===e)return t;let r=Math.min(n.length,e.length),i=0;for(;i<r&&n[i]===e[i];)i++;if(i>=t)return t;let s=0;for(;s<r-i&&n[n.length-1-s]===e[e.length-1-s];)s++;return n.length-s<=t?t+(e.length-n.length):null}function _e(n,e){let t=[],r=[],i=0;for(let s of e){let o=W(n,s.text,i);if(o===-1){r.push(s);continue}t.push({start:o,end:o+s.text.length,param:s}),i=o+s.text.length}return{located:t,missing:r}}function Rn(n,e){let{located:t}=_e(n,e);return t.length>0?t[t.length-1].end:0}function Mn(n,e,t){let r=[],i=[],s=0;for(let o of t){let a=W(n,o.text,s,l=>!e.some(c=>l<c.end&&l+o.text.length>c.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 kn(n,e,t=[]){let r=_e(n,e).located,i=Mn(n,r,t).located,s=[...r.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...i.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),o=[],a=0;for(let c of s)c.start>a&&o.push({type:"text",value:n.slice(a,c.start)}),o.push(c.segment),a=c.end;let l=n.slice(a);return l&&o.push({type:"text",value:l}),o}function Dn(n,e){let{located:t,missing:r}=_e(n,e);return{valid:t.map(i=>i.param),invalid:r}}function be(n,e,t){let r=_e(n,e).located,{located:i,missing:s}=Mn(n,r,t);return{valid:i.map(o=>o.param),invalid:s}}function _n(n,e){let t=e?.endpoint??re,r=t.replace(/\/suggest(?=[?#]|$)/,`/starting-state/${encodeURIComponent(n)}`);return r===t?void 0:r}async function Nn(n){try{let e=await n;if(!e.ok)return null;let t=await e.json();return Array.isArray(t?.data?.suggestions)?t:null}catch{return null}}function hi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var bi=100,Si=300,xi=2,Ne=class{constructor(e,t,r,i,s,o,a,l,c,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=r;this.getMaskCompletedText=i;this.getOnError=s;this.getSessionId=o;this.getSource=a;this.getAdditionalContext=l;this.getLanguage=c;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,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(r=>{(r.text!==e||r.completedParams!==t)&&(e=r.text,t=r.completedParams,this.scheduleFetch())})}isPhraseExactMatch(){return this.phraseExactMatch}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){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?An(o.pendingSpan.snapshot,o.actionableSuggestions):void 0,l=crypto.randomUUID(),c=e===""&&t.length===0&&o.skippedParams.length===0&&o.identifiedParams.length===0?this.startingStateUrl():void 0,d=c?await Nn(fetch(c,{signal:r.signal})):null;if(i!==this.fetchVersion)return;let u=d??await En(e,t,{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()});if(i!==this.fetchVersion)return;this.phraseExactMatch=u.meta?.phrase_exact_match===!0;let g=(u.data.input??[]).filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),parameter:v.parameter,text:v.text,...v.type?{type:v.type}:{}})),p=this.callbacks.isWordOpen?.()??!1,f=this.store.get().text.toLowerCase(),x=v=>p&&f.endsWith(v.text.toLowerCase()),y=g.filter(v=>!x(v));p&&this.callbacks.holdIdentified?.(g.filter(x));let b=In(u.data.suggestions??[],this.getOptionOverrides()),m=u.data.input??[],h=m[m.length-1],S=this.store.get().text,I,w;if(h?.state==="in_progress"){w=!0;let v=S.toLowerCase().lastIndexOf(h.text.toLowerCase());I=v!==-1?v:s}else w=!1,I=s;let C=b.filter(v=>v.parameter!=="placeholder")[0],T=null;if(C&&!p&&!P(X(C))){let v=he(C.options,S,I,w,this.phraseExactMatch);v&&(T={id:crypto.randomUUID(),placeholder:"",parameter:B(v,C.parameter),text:v.text,value:v.value,kind:v.kind,suggestionParameter:C.parameter,suggestionValueType:C.type,suggestionPlaceholder:C.text,options:C.options??[],metadata:v.metadata,icon:v.icon,icon_svg:v.icon_svg,image_url:v.image_url},b=b.filter(H=>H!==C),this.callbacks.onAutoMatch?.({active:C,matched:v,rawQuery:e}))}let F=u.data.custom_fields??null,A=this.callbacks.productsForResponse?.(F);this.store.set(v=>{let H=T?[...v.completedParams,T]:v.completedParams,k=be(v.text,H,y).valid,$=new Set(o.skippedParams.map(E=>E.id)),Ce=new Set(v.skippedParams.filter(E=>!$.has(E.id)).map(E=>E.parameter));return{suggestions:Ce.size>0?b.filter(E=>E.parameter==="placeholder"||!Ce.has(E.parameter)):b,isLoading:!1,isReady:u.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:I,filterInProgress:w,identifiedParams:k,customFields:F,...A!==void 0?{products:A}:{},...T?{completedParams:H}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:u.meta?.funnel_telemetry===!0})}catch(o){let a=hi(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?_n(e,this.getApiConfig()):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(xi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},bi),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1,!0),Si)}attemptFetch(e,t=!1){let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let i=this.callbacks.consumerTick?.(r,e)??"no";if(i==="asked")return!0;if(i==="owns")return!1;let s=r.suggestions.filter(S=>S.parameter==="placeholder").map(S=>S.text).join(" "),o=q(r.text,r.filterBase,s),a=fe(r.text,o,r.filterInProgress),c=r.suggestions.filter(S=>S.parameter!=="placeholder")[0],d=P(r.activeFormatType),g=(c&&!d?j(c.options,a):[]).filter(S=>S.is_tappable),p=c&&!d&&!this.callbacks.isWordOpen?.()?he(c.options,r.text,o,r.filterInProgress,this.phraseExactMatch)!==null:!1,f=a.trim().length>0;if(g.length>0&&!p&&f||De(r.text,r.completedParams.length,s))return!1;let{rawQuery:x,completedParams:y}=L(r.text,r.completedParams),b=x.length<r.lastRawQuery.length,m=Math.abs(x.length-r.lastRawQuery.length),h=t&&x!==r.lastRawQuery;return b||m>=e||h?(this.doFetch(x,y),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ie=["January","February","March","April","May","June","July","August","September","October","November","December"],Fe=["S","M","T","W","T","F","S"],Wn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Bn="aiaDate",Un="aiaDay",Fn=n=>String(n).padStart(2,"0");function _(n){return`${n.getFullYear()}-${Fn(n.getMonth()+1)}-${Fn(n.getDate())}`}function pt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function yi(n){let e=pt(n).getTime()-pt(new Date).getTime();return Math.round(e/864e5)}function $n(n){let e=yi(n);return e>=0&&e<7?Wn[n.getDay()]:oe(n)}function oe(n){return n.getFullYear()===new Date().getFullYear()?`${ie[n.getMonth()]} ${n.getDate()}`:`${ie[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function He(n){if(!n)return null;let e=Wn.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=pt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let r=ie.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(r<0)return null;let i=Number(t[2]),s=t[3]?Number(t[3]):new Date().getFullYear(),o=new Date(s,r,i);return o.getMonth()!==r||o.getDate()!==i?null:o}function mt(n){return`${ie[n.month]} ${n.year}`}function gt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function qn(n){return{year:n.getFullYear(),month:n.getMonth()}}function ft(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Hn(){return{text:"",is_tappable:!1,kind:null}}function ht(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),r=[];for(let i=0;i<e;i++)r.push(Hn());for(let i=1;i<=t;i++){let s=new Date(n.year,n.month,i);r.push({text:$n(s),is_tappable:!0,kind:null,metadata:{[Bn]:_(s),[Un]:i}})}for(;r.length%Fe.length!==0;)r.push(Hn());return r}function bt(n){let e=He(n);return e?_(e):null}function U(n){let e=n?.metadata?.[Bn];return typeof e=="string"?e:null}function St(n){let e=n?.metadata?.[Un];return typeof e=="number"?e:null}function vi(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function J(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&vi(e)?e:n.ownerDocument??n}function R(n){return n.ownerDocument??n}function Pi(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Gn(n){let e=J(n);return!Pi(e)||typeof e.getSelection=="function"?null:e}function Vn(n){let e=Gn(n);if(!e)return null;let t=R(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Kn(n,e){let t=n,r;try{r=t.getComposedRanges({shadowRoots:[e]})}catch{r=t.getComposedRanges(e)}return r.length>0?r[0]:null}function xt(n){let t=J(n).getSelection?.();return t||(R(n).getSelection?.()??null)}function G(n){let e=xt(n);if(!e||e.rangeCount===0)return null;let t=Vn(n);if(t){let r=Kn(e,t);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 We(n){let e=xt(n);if(!e||e.rangeCount===0)return null;let t=Vn(n);if(!t)return e.getRangeAt(0);let r=Kn(e,t);if(!r)return null;let i=R(n).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function Se(n,e,t){let r=xt(n);if(!r)return null;if(Gn(n))return r.collapse(e,t),r;let i=R(n).createRange();return i.setStart(e,t),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function Be(n,e){let t=n?J(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ue=2,Ei="magicx-aia";function Yn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function wi(n){let e=R(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let r=n;for(;r&&r!==e.body&&r!==e.documentElement;){let i=r.scrollWidth>r.clientWidth,s=r.scrollHeight>r.clientHeight;if(i||s){let o=t.getComputedStyle(r);if(i&&Yn(o.overflowX)||s&&Yn(o.overflowY))return r}if(r.classList.contains(Ei))return null;r=r.parentElement}return null}function yt(n){let e=We(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=wi(n);if(!t||typeof e.getBoundingClientRect!="function")return;let r=e.getBoundingClientRect();if(r.height===0)return;let i=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let s=i.left+t.clientLeft,o=s+t.clientWidth;r.right>o?t.scrollLeft+=r.right-o+Ue:r.left<s&&(t.scrollLeft-=s-r.left+Ue)}if(t.scrollHeight>t.clientHeight){let s=i.top+t.clientTop,o=s+t.clientHeight;r.bottom>o?t.scrollTop+=r.bottom-o+Ue:r.top<s&&(t.scrollTop-=s-r.top+Ue)}}var Xn='[contenteditable="false"]',Pt="strong[data-param-id]",se;function Ti(){if(se!==void 0)return se;let n=globalThis.Intl.Segmenter;if(!n)return se=null,null;try{se=new n(void 0,{granularity:"grapheme"})}catch{se=null}return se??null}function $e(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Xn))return!0;t=t.parentNode}return!1}function qe(n){return R(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return $e(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ge(n){let e=qe(n),t="",r=e.nextNode();for(;r;)t+=r.data,r=e.nextNode();return t}function Et(n){let e=qe(n),t=0,r=e.nextNode();for(;r;)t+=r.data.length,r=e.nextNode();return t}function N(n){let e=G(n);if(!e)return null;let t=e.node,r=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let i=t;if($e(i,n)&&i!==n)return null;let s=0;for(let o=0;o<r&&o<i.childNodes.length;o++)s+=wt(i.childNodes[o],n);return s+vt(i,n)}return t.nodeType!==Node.TEXT_NODE||$e(t,n)?null:vt(t,n)+r}function wt(n,e){if(n.nodeType===Node.TEXT_NODE)return $e(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Xn))return 0;let r=0;for(let i of Array.from(t.childNodes))r+=wt(i,e);return r}function vt(n,e){let t=qe(e),r=0,i=t.nextNode();for(;i;){if(i===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(i))return r;r+=i.data.length,i=t.nextNode()}return r}function M(n,e){let t=R(n),r=Math.max(0,Math.min(e,Et(n))),i=qe(n),s=0,o=null,a=0,l=i.nextNode(),c=null;for(;l;){let u=l.data.length;if(r<s+u){o=l,a=r-s;break}if(r===s+u){let g=i.nextNode();g?(o=g,a=0):(o=l,a=u);break}s+=u,c=l,l=i.nextNode()}let d=t.createRange();if(o){let u=o.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===o.data.length?d.setStartAfter(u):d.setStart(o,a):d.setStart(o,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),Se(n,d.startContainer,d.startOffset)&&(Ii(n,d,r),yt(n))}function Qn(n,e){if(!n||!e.contains(n))return null;let r=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Pt)??null;return r&&e.contains(r)?r:null}function Ii(n,e,t){let r=Qn(G(n)?.node??null,n);if(r&&r!==Qn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function jn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let r=N(n);return r!==null&&t===`${r}:${e}`}function zn(n){return J(n).activeElement===n}function Tt(n,e){if(!e||e.nodeType===void 0)return null;let t=e,i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(Pt);if(!i||!n.contains(i))return null;let s=G(n);return s&&!s.collapsed?null:i.dataset.paramId??null}function It(n,e){let t=null;for(let o of n.querySelectorAll(Pt))if(o.dataset.paramId===e){t=o;break}if(!t)return;let r=vt(t,n),i=r+wt(t,n),s=N(n);s!=null&&s>=r&&s<=i||M(n,r)}function Ct(n){let e=N(n);return e==null?!1:e>=Et(n)}function Ot(n,e){if(e<=0)return 0;let t=Ti();if(!t)return e-1;let r=n.slice(0,e),i=0;for(let{index:s}of t.segment(r))s<e&&(i=s);return i}function Z(n,e,t=[],r={}){let{rawQuery:i,completedParams:s}=L(n,e);return{query:n.trim(),raw_query:i,completed_params:me(s,t),identified_params:pe(r.identifiedParams??[]),is_ready:r.isReady??!1,...r.customFields?{custom_fields:r.customFields}:{}}}function At(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?Ct(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?N(n):null}var Ve=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=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 c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=At(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let f=P(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(l.length===0)return;this.store.set({activeDropdownIndex:f});break}if(e.preventDefault(),l.length===0)return;if(P(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let g=l.indexOf(t.activeDropdownIndex),p=g<l.length-1?g+1:0;this.store.set({activeDropdownIndex:l[p]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let g=At(e.target,t),p=!!t.editingParam;if(!g&&!p)break;e.preventDefault();let f=P(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(o)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(l.length===0)return;this.store.set({activeDropdownIndex:f});break}if(l.length===0)break;if(e.preventDefault(),P(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%o<o-1){let g=t.activeDropdownIndex+1;g<t.filteredOptions.length&&t.filteredOptions[g]?.is_tappable&&this.store.set({activeDropdownIndex:g})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,g=t.editingTail;this.ctx.exitEditMode?.(),M(u,g);break}At(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%o>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),M(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Lt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,r,s);else if(a){this.ctx.endTypedWord?.();let d=this.store.get();a(Z(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=t.filteredOptions.map((p,f)=>p.is_tappable?f:-1).filter(p=>p!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.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 u=d.indexOf(t.activeDropdownIndex),g;if(u<0)g=e.shiftKey?d.length-1:0;else{let p=e.shiftKey?-1:1;g=(u+p+d.length)%d.length}this.store.set({activeDropdownIndex:d[g]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),M(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let i=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=i;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,t){let r=_(new Date),i=e.filteredOptions.findIndex(o=>U(o)===r);if(i>=0)return i;let s=e.filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1);return(t?s[s.length-1]:s[0])??0}stepDateDay(e,t){for(let r=e.activeDropdownIndex+t;r>=0&&r<e.filteredOptions.length;r+=t)if(e.filteredOptions[r]?.is_tappable){this.store.set({activeDropdownIndex:r});return}}stepDateWeek(e,t){let r=e.activeDropdownIndex+t;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 t=Be(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let i=Be(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===t)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,r,i){let s=Be(i,`${r}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}};var Ke=class{constructor(e,t,r={}){this.store=e;this.getOverrides=t;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,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){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(t>1&&!o&&s<t)return"owns"}return this.ask(r),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(P(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionParameter)?{mode:"edit",key:t.id,parameter:t.suggestionParameter,suggestion:{parameter:t.suggestionParameter,text:t.suggestionPlaceholder,required:!0,options:t.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,t){return this.lastMiss!=null&&this.lastMiss.parameter===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.parameter],r=++this.version;if(!t||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=t(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,t,r,i){let s;try{let o=await t;if(r.aborted||i!==this.version)return;s=Array.isArray(o)?o:[]}catch(o){if(r.aborted||i!==this.version||Ci(o))return;this.logOnce(o),s=[]}this.commit(e,s,i)}commit(e,t,r){if(r!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;t.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:t}:o.editingParam,optionSearch:s}));else{let o={...e.suggestion,options:t};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}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let r=this.store.get().optionSearch;r&&r.parameter===e.parameter&&r.query===e.query&&r.status===t||this.store.set({optionSearch:{parameter:e.parameter,query:e.query,status:t}})}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 Ci(n){return n instanceof Error&&n.name==="AbortError"}var Ye=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),r=t.suggestions.filter(c=>c.parameter!=="placeholder");if(e<0||e>=r.length)return;let i=r[e],s=r.filter((c,d)=>d!==e),o=t.suggestions.filter(c=>c.parameter==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=L(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:i.text,otherPills:s.map(d=>d.text)})}let a=[...o,i,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Zn="/products/",Jn="https://relative.invalid";function Oi(n){if(!n)return;let e;try{e=new URL(n,`${Jn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Jn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function er(n,e){let t=Oi(n.item_url)??Li(n);return{id:n.source_id,title:n.title,...t&&{url:t},imageUrl:n.image_url||null,...n.price&&{price:Ai(n.price,n.currency,e)},...n.vendor&&{vendor:n.vendor},...typeof n.available=="boolean"&&{available:n.available}}}function Ai(n,e,t){if(t===void 0||!e||!/^\d+(\.\d+)?$/.test(n))return n;try{return new Intl.NumberFormat(t,{style:"currency",currency:e}).format(Number(n))}catch{return n}}function Li(n){if(!n.handle)return;let e=`${Zn}${encodeURIComponent(n.handle)}`;return n.variant_id?`${e}?variant=${encodeURIComponent(n.variant_id)}`:e}function Rt(n,e){return(n?.items.matched??[]).map(t=>er(t,e))}var Qe=class{constructor(e,t,r=()=>!0,i=()=>{}){this.store=e;this.getConfig=t;this.isEnabled=r;this.getLanguage=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return Rt(e,ge(this.getLanguage()))}async run(e,t,r){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(r);return}let s=()=>t.aborted||!r()||!this.owns(i);try{let o=await i.fetch(e,t);if(s())return;let a=i.transform(o),l=Array.isArray(a)?a:[],c=i.limit!=null?l.slice(0,i.limit):l;if(s())return;this.commit(c)}catch(o){if(t.aborted||Ri(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??[])}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 Ri(n){return n instanceof Error&&n.name==="AbortError"}function Mi(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function tr(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:ie.findIndex(t=>t.toLowerCase().startsWith(e))}function ki(n,e,t){let r=new Date(t.getFullYear(),n,e);if(r.getMonth()!==n||r.getDate()!==e)return null;let i=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(r>=i)return r;let s=new Date(t.getFullYear()+1,n,e);return s.getMonth()===n&&s.getDate()===e?s:null}function nr(n,e,t){let r=new Date(n,e,t);return r.getMonth()===e&&r.getDate()===t?r:null}function xe(n,e={}){if(!n)return null;let t=e.today??new Date,r=Mi(n.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(r);if(i){let l=nr(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?_(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(r);if(s){let l=tr(s[1]);if(l>=0)return Xe(l,Number(s[2]),s[3],t)}let o=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(o){let l=tr(o[2]);if(l>=0)return Xe(l,Number(o[1]),o[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(r);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?Xe(c-1,l,a[3],t):c>12&&l<=12?Xe(l-1,c,a[3],t):null}return null}function Xe(n,e,t,r){if(t){if(t.length!==4)return null;let s=nr(Number(t),n,e);return s?_(s):null}let i=ki(n,e,r);return i?_(i):null}function Mt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:xe(n.text,e)}var ir=" - ",Dt="aiaDateRangeStart",_t="aiaDateRangeEnd";function ye(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var kt=/^\d{4}-\d{2}-\d{2}$/;function rr(n){if(!kt.test(n))return null;let[e,t,r]=n.split("-").map(Number),i=new Date(e,t-1,r);return i.getMonth()===t-1&&i.getDate()===r?i:null}var Di=/\s+(?:to|through|thru|until|til|till)\s+/g,_i=/[-–—]/g;function Ni(n){let e=[];for(let t of[Di,_i]){t.lastIndex=0;let r=t.exec(n);for(;r!==null;)e.push([n.slice(0,r.index),n.slice(r.index+r[0].length)]),r=t.exec(n)}return e}function je(n,e={}){if(!n)return null;let t=new Set,r=null;for(let[i,s]of Ni(n.trim())){let o=xe(i.trim(),e);if(!o)continue;let a=xe(s.trim(),e);!a||a<o||(t.add(`${o}|${a}`),r={start:o,end:a})}return t.size===1?r:null}function or(n){let e=rr(n.start),t=rr(n.end);return!e||!t?"":n.start===n.end?oe(e):`${oe(e)}${ir}${oe(t)}`}function sr(n,e){let t=ye(n,e);return{text:or(t),is_tappable:!0,kind:null,metadata:{[Dt]:t.start,[_t]:t.end}}}function ve(n,e={}){let t=n?.metadata?.[Dt],r=n?.metadata?.[_t];return typeof t=="string"&&typeof r=="string"&&kt.test(t)&&kt.test(r)?ye(t,r):je(n?.text,e)}var ze="(max-width: 768px)";var Fi="var(--aia-option-row-height, 37px)",Hi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ar(n,e){return e?Nt(1,Math.min(n,5)):Nt(1,Math.min(n,4))}function Nt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Fi} + ${Hi})`}}function Ht(n,e){return!e&&n>=5}function Wt(n,e,t,r){if(!(!e&&n>=5&&Wi(t,r))){let o=ar(n,e);return{...o,template:Ft(o.cols),scrollHintIndices:!e&&n>o.rows?[o.rows-1]:[]}}let s=6;return{...Nt(2,3),template:Ft(2),scrollHintIndices:n>s?[s-2,s-1]:[]}}function Wi(n,e){return!n||n.length===0||e==null||e<=0||n.some(r=>r<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function Bt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.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",t.appendChild(a)}n.appendChild(t);let r=Array.from(t.children).map(o=>o.offsetWidth);t.remove();let i=getComputedStyle(n),s=n.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:r,gridWidth:s}}function Ft(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ut(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(ze).matches}function $t(n,e){return!n||n.length!==e.length?!1:n.every((t,r)=>t.text===e[r].text)}function lr(n,e){let t=e.dropdownTrigger??"auto",r=e.closeDropdownOnBlur??!0,o=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=r?n.isFocused:!0;return o&&a}if(t==="auto"){let a=r?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(o||n.isLoading)&&a&&c}return t==="manual"?(o||n.isLoading)&&n.pillTapped:!1}function Pe(n){if(n.editingIdentified){let{parameter:t,anchor:r}=n.editingIdentified;return`identified:${t}@${r}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.parameter??""}`}function dr(n){if(!n)return gt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Bi(n){let e=He(n);return e?qn(e):gt()}function cr(n,e){let t=kn(n.text,n.completedParams,n.identifiedParams),r=n.suggestions.filter(E=>E.parameter!=="placeholder"),i=r[0],s=n.suggestions.filter(E=>E.parameter==="placeholder").map(E=>E.text).join(" "),o=q(n.text,Math.min(n.filterBase,n.text.length),s),l=o===0&&De(n.text,n.completedParams.length,s)?"":fe(n.text,o,n.filterInProgress),c=i?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,g,p,f;if(d&&n.editingParam&&n.editingAnchor!=null){let E=n.editingParam.id,ne=n.completedParams.some(ai=>ai.id===E),ce=n.caretOffset??n.editingAnchor,bn=ne?"":n.text.slice(n.editingAnchor,ce);g=bn.trim(),p=n.editingParam.options,f=n.editingParam.suggestionParameter,u=j(n.editingParam.options,bn)}else g=l.trim(),p=c,f=i?.parameter,u=j(c,l);let x=n.optionSearch,y=x!=null&&f!=null&&x.parameter===f;y&&x.status==="done"&&x.query===g&&(u=p);let b=y&&x.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(E=>E.is_tappable));let h=n.editingIdentified,S=d?n.editingParam&&{type:n.editingParam.suggestionValueType}:i,I=h?h.format:X(S),w=d&&I==="date-range"?ve(n.editingParam):null,D=null,C=null;if(P(I)){let E=Pe({...n,actionableSuggestions:r}),ne=n.dateViewMonth;D=ne&&ne.key===E?{year:ne.year,month:ne.month}:h?dr(h.iso):w?dr(w.start):Bi(n.editingParam?.text),u=ht(D);let ce=n.pendingRangeStart;I==="date-range"&&ce&&ce.key===E&&(C=ce.iso)}let T=E=>m?E.is_tappable:!0,F;if(d){let E=n.editingParam?.options??[];F=n.editingParam!=null&&E.filter(T).length===0}else F=i!=null&&c.filter(T).length===0;let A=lr({inEditMode:d||h!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||b,pillTapped:n.pillTapped,activePillHasNoOptions:F,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),v=A&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable,H=n.skeletonOptions!==null&&n.skeletonRequested&&!n.isLoading&&!n.editingParam&&!n.inSelectionAnimation,k=n.isLoading&&!n.editingParam&&!n.inSelectionAnimation||b||H,$=k&&n.skeletonOptions!==null,Ce=$&&n.skeletonOptions?n.skeletonOptions:u,hn=$?n.skeletonSuggestion:null;return{segments:t,actionableSuggestions:r,filteredOptions:u,dropdownLoading:k,dropdownOptions:Ce,dropdownSuggestion:hn,skeletonExiting:H,activeFormatType:I,dateView:D,dateRangeStart:C,placeholderText:s,optionQuery:g,isSearchingOptions:b,isDropdownOpen:A,isActivePillSelected:v}}function Je(n){return n.mode==="fresh"?Ui(n):$i(n)}function Ui(n){let{text:e,completedParams:t,suggestions:r,filterBase:i,filterInProgress:s,phraseExactMatch:o}=n,l=r.filter(S=>S.parameter!=="placeholder")[0];if(!l?.options)return null;let c=r.filter(S=>S.parameter==="placeholder").map(S=>S.text).join(" "),d=q(e,i,c),u=he(l.options,e,d,s,o===!0);if(!u)return null;let g=u.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(g),f=p>=0?p:Math.max(0,e.length-u.text.length),x=f+u.text.length,y=e.slice(f,x),m=x<e.length&&e[x]===" "?x+1:x,h={id:crypto.randomUUID(),placeholder:"",parameter:B(u,l.parameter),text:y,value:u.value,kind:u.kind,suggestionParameter:l.parameter,suggestionValueType:l.type,suggestionPlaceholder:l.text,options:l.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...t,h],suggestions:r.filter(S=>S!==l),filterBase:m,newParamId:h.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m,option:u}}function $i(n){let{text:e,completedParams:t,editingParam:r,editingAnchor:i,editingTail:s}=n;if(t.some(h=>h.id===r.id))return null;let o=e.slice(i,s),a=ke(r.options,o);if(!a)return null;let l=a.text.toLowerCase(),c=o.toLowerCase().lastIndexOf(l),d=i+Math.max(0,c),u=d+a.text.length,g=e.slice(d,u),p=u<e.length&&e[u]===" "?u+1:u,f=e.length,x={id:crypto.randomUUID(),placeholder:"",parameter:B(a,r.suggestionParameter),text:g,value:a.value,kind:a.kind,suggestionParameter:r.suggestionParameter,suggestionValueType:r.suggestionValueType,suggestionPlaceholder:r.suggestionPlaceholder,options:r.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},y=t.length,b=0;for(let h=0;h<t.length;h++){let S=W(e,t[h].text,b);if(S!==-1){if(S>=p){y=h;break}b=S+t[h].text.length}}let m=[...t];return m.splice(y,0,x),{patch:{text:e,completedParams:m,newParamId:x.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1},caretPos:f,option:a}}var qi=6e4;function Gi(n){return typeof TextEncoder>"u"?n.length*3:new TextEncoder().encode(n).length}function Vi(n){return(n??re).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Ki(n){return ue(n)?`Bearer ${await Ae(n).getToken()}`:Re(n)}async function ur(n){try{let e=Vi(n.apiConfig?.endpoint),t=Le(n.apiConfig),r=await Ki(n.apiConfig);r&&(t.Authorization=r);let i=JSON.stringify({source:n.source,session_id:n.sessionId,...n.visitorId&&{visitor_id:n.visitorId},...n.requestId&&{request_id:n.requestId},type:n.type,...n.language&&{language:n.language},at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:i,...n.keepalive&&Gi(i)<=qi&&{keepalive:!0}})}catch{}}function ee(n,e){let t=n.findIndex(r=>r.text===e);return t>=0?t+1:null}function pr(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let r=n.filterBase,i=n.text.slice(0,r),s=i.length===0&&n.text.length===0,o=i.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(i=`${n.placeholderText} `);let a=Math.min(Rn(n.text,n.completedParams),i.length),l=Tn(i.slice(a),e.text);l>0&&(i=i.slice(0,i.length-l));let c=i.length>0&&i[i.length-1]!==" ",d=`${i}${c?" ":""}${e.text} `,u=(s||o)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,g=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=g>=0?u.slice(g,g+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",parameter:B(e,t.parameter),text:p,value:e.value,kind:e.kind,suggestionParameter:t.parameter,suggestionValueType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},x=n.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text),key:t.parameter,position:ee(t.options??[],e.text)},consumedSuggestion:t,remainingActionable:x}}function Ze(n){let e=P(n.activeFormatType)||n.filteredOptions.length===0?null:n.filteredOptions,t=n.editingParam,r=t?{parameter:t.suggestionParameter,text:t.suggestionPlaceholder,required:!0,options:t.options}:n.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?r:null,skeletonRequested:!1}}function et(n,e,t){let r=n.slice(0,e),i=n.slice(t),s=(r===""||r.endsWith(" "))&&i.startsWith(" ");return s&&(i=i.slice(1)),{text:r+i,removed:t-e+(s?1:0)}}var tt=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let r=t.completedParams.find(o=>o.id===e);if(!r)return;let i=0,s=-1;for(let o of t.completedParams){let a=W(t.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 t=this.deps.store.get(),r=t.editingParam,i=t.editingAnchor,s=t.editingTail;if(!r||i==null||s==null||!t.completedParams.some(l=>l.id===r.id))return!1;let{text:o}=e===""?et(t.text,i,s):{text:t.text.slice(0,i)+e+t.text.slice(s)},a=i+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==r.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),r={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(r.editingParam=null,r.editingAnchor=null,r.editingTail=null,r.activeDropdownIndex=-1):t.editingTail!=null&&(r.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(r),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.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 t=this.deps.store.get(),r=t.editingParam,i=t.editingAnchor,s=t.editingTail;if(!r||i==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:r.options.filter(b=>b.text!==e.text).map(b=>b.text),key:r.suggestionParameter,position:ee(r.options,e.text),chip_origin:"tap"});let o=t.text.slice(0,i),a=t.text.slice(s),l=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=o+d+a,g=u.length,p={id:crypto.randomUUID(),placeholder:"",parameter:B(e,r.suggestionParameter),text:l,value:e.value,kind:e.kind,suggestionParameter:r.suggestionParameter,suggestionValueType:r.suggestionValueType,suggestionPlaceholder:r.suggestionPlaceholder,options:r.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},f=t.completedParams.findIndex(b=>b.id===r.id),x=t.completedParams.filter(b=>b.id!==r.id),y=f>=0?Math.min(f,x.length):x.length;x.splice(y,0,p),this.deps.store.set({text:u,completedParams:x,newParamId:p.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...Ze(t)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(g),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Je({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Yi=33,Qi=70,Xi=120,ji=50,ae="data-aia-placeholder-leaving",le=new WeakMap;function nt(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function zi(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function gr(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function fr(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(gr(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],r=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>fr(n,e),33+r)}function mr(n,e){gr(n,e,0),e.timer=setTimeout(()=>fr(n,e),33)}function hr(n,e){let t=le.get(n);if(e===""){t&&(nt(t),le.delete(n)),n.removeAttribute(ae),delete n.dataset.placeholder;return}if(t?.target===e)return;if(zi(n)){t&&nt(t),n.removeAttribute(ae),le.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let r={target:e,shown:0,timer:null},i=t&&t.shown>0?t:null;if(t&&nt(t),le.set(n,r),i){n.setAttribute(ae,""),r.timer=setTimeout(()=>{r.timer=null,n.removeAttribute(ae),n.isConnected&&mr(n,r)},170);return}n.removeAttribute(ae),mr(n,r)}function br(n){let e=le.get(n);e&&(nt(e),le.delete(n))}var Sr="https://ai-autocomplete.com";function qt(n=Sr){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}var Ji={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"},Zi={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"};function O(n){return n?.split("-")[0]?.toLowerCase()==="es"?Zi:Ji}function Gt(n,e,t=O()){return n?{key:"enter",hint:t.proceed}:e?{key:"tab",hint:t.select}:{key:"\u2192",hint:t.skipHint}}function Vt(n){let e=o=>{o.ctrlKey||xr(o.target,n,o.deltaX,o.deltaY)||o.preventDefault()},t=0,r=0,i=o=>{let a=o.touches[0];a&&(t=a.clientX,r=a.clientY)},s=o=>{if(o.touches.length!==1)return;let a=o.touches[0],l=t-a.clientX,c=r-a.clientY;t=a.clientX,r=a.clientY,o.cancelable&&!xr(o.target,n,l,c)&&o.preventDefault()};return n.addEventListener("wheel",e,{passive:!1}),n.addEventListener("touchstart",i,{passive:!0}),n.addEventListener("touchmove",s,{passive:!1}),()=>{n.removeEventListener("wheel",e),n.removeEventListener("touchstart",i),n.removeEventListener("touchmove",s)}}function xr(n,e,t,r){let i=n instanceof Element?n:null;for(;i;){if(r!==0&&eo(i,r)||t!==0&&to(i,t))return!0;if(i===e)break;i=i.parentElement}return!1}var yr=/^(auto|scroll|overlay)$/;function eo(n,e){return n.scrollHeight<=n.clientHeight||!yr.test(getComputedStyle(n).overflowY)?!1:e>0?n.scrollTop+n.clientHeight<n.scrollHeight-1:n.scrollTop>0}function to(n,e){if(n.scrollWidth<=n.clientWidth)return!1;let t=getComputedStyle(n);if(!yr.test(t.overflowX))return!1;let r=Math.abs(n.scrollLeft),i=n.scrollWidth-n.clientWidth;return(t.direction==="rtl"?e<0:e>0)?r<i-1:r>0}var vr=new WeakMap,Pr=new WeakSet;function V(n,e,t){if(vr.set(n,t),Pr.has(n))return;Pr.add(n);let r=()=>vr.get(n),i=s=>{if(!(s instanceof Element))return null;let o=s.closest(e.itemSelector);return o&&n.contains(o)?o:null};e.onClick&&n.addEventListener("click",s=>{let o=i(s.target);o&&e.onClick?.(o,r(),s)}),e.onEnter&&n.addEventListener("mouseenter",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onEnter?.(o,r())},!0),e.onLeave&&n.addEventListener("mouseleave",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onLeave?.(o,r())},!0),e.preventMousedown&&n.addEventListener("mousedown",s=>s.preventDefault())}function K(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function Y(n){n.offsetWidth}var no={selectedIso:null,selectedRange:null,rangeStart:null};function Ee(n){if(!P(n.activeFormatType))return no;let e=n.editingIdentified;if(e){let{iso:r,isoEnd:i}=e;return{selectedIso:i?null:r,selectedRange:r&&i?ye(r,i):null,rangeStart:n.dateRangeStart}}let t=ve(n.editingParam);return{selectedIso:t?null:bt(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Kt(n){return n.pendingStart?ye(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Yt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:r}=e,i=n===t||r!=null&&(n===r.start||n===r.end),s=r!=null&&n>r.start&&n<r.end;return{selected:i,inRange:s}}var Er="data-aia-key";function Q(n,e,t){let r=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Er);a!=null&&r.set(a,o)}let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);i.add(l);let c=r.get(l);c||(c=t.create(a,o),c.setAttribute(Er,l)),t.update?.(c,a,o),n.children[o]!==c&&n.insertBefore(c,n.children[o]??null),s.push(c)}for(let[o,a]of r)i.has(o)||a.remove();return s}function wr(n,e){if(!e.interactive)return null;let t=e.options[K(n)];return t?.is_tappable?t:null}var ro={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(n,e)=>{if(n.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(n.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let t=wr(n,e);t&&(n.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&wr(n,e)&&e.callbacks.onHighlight(K(n))},onLeave:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,K(n))}};function Ir(n,e,t,r,i,s,o,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=so(),n.appendChild(l),Y(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}V(l,ro,{options:e,callbacks:o,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=mt(i));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&io(d,e,t,r,s)}function io(n,e,t,r,i){let s=_(new Date),o=Kt({pendingStart:i.rangeStart,highlightedIso:U(e[t]),selected:i.selectedRange});Q(n,e,{keyOf:(a,l)=>U(a)??`pad-${l}`,create:a=>oo(a),update:(a,l,c)=>{let d=U(l),u=Yt(d,{selectedIso:i.selectedIso,range:o}),g=c===t&&l.is_tappable;a.id=`${r}-option-${c}`,a.dataset.aiaIndex=String(c),a.setAttribute("aria-selected",String(g)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<s),a.classList.toggle("magicx-aia-date-cell--highlighted",g),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===s),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function oo(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=St(n);if(t==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",n.text);let r=document.createElement("span");return r.className="magicx-aia-date-cell-number",r.textContent=String(t),e.appendChild(r),e}function so(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(Tr("prev","Previous month","\u2039"),t,Tr("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let s of Fe){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",""),n.append(e,r,i),n}function Tr(n,e,t){let r=document.createElement("button");return r.type="button",r.tabIndex=-1,r.className="magicx-aia-datepicker-nav",r.setAttribute(`data-aia-date-${n}`,""),r.setAttribute("aria-label",e),r.textContent=t,r.disabled=!0,r}var ao={itemSelector:"[data-aia-pill]",onClick:(n,e)=>{if(e.loading||n.disabled)return;let t=Number.parseInt(n.dataset.aiaPillIndex??"-1",10);t>=0&&e.onSelectPill(t)},preventMousedown:!0},Cr=[125,69];function Or(n,e){return e?1:n===0?.7:n===1?.4:.2}function rt(n,e,t,r,i=!1,s=!1,o=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),V(a,ao,{onSelectPill:r,loading:s}),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Cr.length;l++){let c=Cr[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=`${c}px`,d.style.opacity=String(Or(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();Q(a,e,{keyOf:l=>`${l.parameter}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.disabled=!0,c},update:(l,c,d)=>{let u=l,g=o&&d===t&&!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(Or(d,g)),u.dataset.aiaPillIndex=String(d),s?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),Y(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=s}function Qt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var lo=32;function Ar(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,r=e.deltaX||0;if(!t||Math.abs(r)>=Math.abs(t))return null;let i=n.scrollWidth-n.clientWidth;if(i<=1)return null;let s=n.scrollLeft,o=t;return e.deltaMode===1?o*=32:e.deltaMode===2&&(o*=n.clientWidth),Math.max(0,Math.min(i,s+o))}function Xt(n){let e=t=>{let r=Ar(n,t);r!==null&&(t.preventDefault(),n.scrollLeft=r)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var Lr=Intl.Segmenter,Rr=Lr?new Lr(void 0,{granularity:"grapheme"}):null;function jt(n){let e=n.trim().normalize("NFC").toUpperCase();if(Rr)for(let t of Rr.segment(e))return t.segment;return Array.from(e)[0]??"?"}var zt=120,co=360;function uo(n){let e=n.pathname;return n.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 Mr(n,e){let t;try{t=new URL(n,typeof document>"u"?void 0:document.baseURI)}catch{return n}let r=uo(t);return r?(t.searchParams.set("width",String(e)),r.format&&t.searchParams.set("format",r.format),n.startsWith("/")&&!n.startsWith("//")?`${t.pathname}${t.search}${t.hash}`:t.href):n}function Jt(n,e){let t=Mr(n,e);return t===n?[n]:[t,n]}function it(n){let e=n?.trim();return e?Jt(e,360):[]}function po(n){return it(n)[0]}var Zt=new WeakMap,kr=new WeakMap;function Dr(n,e,t,r,i,s="row",o="image",a=O()){let l=n.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",`${t}-products-label`);let u=document.createElement("div");u.className="magicx-aia-products-label",u.id=`${t}-products-label`,u.setAttribute("data-aia-products-label",""),u.textContent=a.products;let g=document.createElement("div");g.className="magicx-aia-products-row",g.setAttribute("data-aia-products-row",""),Xt(g),l.append(u,g),n.appendChild(l)}l.setAttribute("data-aia-products-layout",s);let c=l.querySelector(".magicx-aia-products-label");c&&c.textContent!==a.products&&(c.textContent=a.products);let d=l.querySelector(".magicx-aia-products-row");if(d){Q(d,e,{keyOf:u=>mo(u),create:u=>go(u,r,i,o,a),update:(u,g,p)=>{u.id=`${t}-product-${p}`,u.dataset.aiaIndex=String(p),kr.get(u)?.(o);let f=u.querySelector(".magicx-aia-product-badge");f&&f.textContent!==a.soldOut&&(f.textContent=a.soldOut)}}),Y(d);for(let u of d.querySelectorAll("[data-aia-product]")){let g=Zt.get(u);g&&(Zt.delete(u),g())}}}function en(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let r of t)r.tabIndex=e?0:-1}function mo(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor,n.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function go(n,e,t,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=it(n.imageUrl),l=a[0],c=!!l,d=()=>{o.replaceChildren(),o.toggleAttribute("data-aia-product-placeholder",r==="image"),o.toggleAttribute("data-aia-product-initial",r==="initial"),r==="initial"&&(o.textContent=jt(n.title))};if(kr.set(s,p=>{p!==r&&(r=p,c||d())}),l){let p=document.createElement("img"),f=0;p.onerror=()=>{let x=a[++f];if(x){p.src=x;return}c=!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 u=document.createElement("span");if(u.className="magicx-aia-product-body",n.vendor){let p=document.createElement("span");p.className="magicx-aia-product-vendor",p.textContent=n.vendor,u.appendChild(p)}let g=document.createElement("span");if(g.className="magicx-aia-product-title",g.textContent=n.title,u.appendChild(g),n.price){let p=document.createElement("span");p.className="magicx-aia-product-price",p.textContent=n.price,u.appendChild(p)}if(n.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),Zt.set(s,()=>{n.url&&(s.href=n.url),s.addEventListener("click",p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0||(p.preventDefault(),e(n))})}),s.addEventListener("keydown",p=>{p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),e(n))}),s.addEventListener("focus",()=>t(!0)),s.addEventListener("blur",p=>{p.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),s}var fo=80,ho=150,bo=280,So=16,tn="--aia-option-enter-delay";function nn(n,e,t,r="below"){let i=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,n)/i);if(r!=="above")return s*80;let o=Math.max(1,Math.ceil(Math.max(0,t)/i));return Math.max(0,o-1-s)*80}function rn(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}function te(n){return ot(n)[0]??null}function ot(n){let e=xo(n);return e?Jt(e,120):[]}function xo(n){if(!n)return null;let e=n.trim();if(e==="")return null;let t;try{t=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.href}function we(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var _r={one:"item",other:"items"};function yo(n,e=_r){let t=we(n);if(t===null)return null;let r=typeof e=="string"?e:n===1?e.one:e.other;return r===""?t:`${t} ${r}`}function vo(n){return te(n.image_url)!==null}var Nr="http://www.w3.org/2000/svg",Po=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function Eo(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var wo=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],To=/^[a-zA-Z0-9#.,%\s()-]+$/;function Io(n){let e=[];for(let t of wo){let r=n.getAttribute(t);r===null||!To.test(r)||/url\s*\(/i.test(r)||e.push(`${t}: ${r.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function Fr(n){for(let e of Array.from(n.attributes))Eo(e.name,e.value)&&n.removeAttribute(e.name);Io(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Po.has(t.localName)||t.namespaceURI!==Nr?t.remove():Fr(t)}else e.remove()}function Te(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==Nr||e.getElementsByTagName("parsererror").length>0?null:(Fr(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function on(n){return n.text}var Hr=new WeakMap;function Co(n,e,t){let r=e.length,i=Ut(),s=Hr.get(n),o=t&&s&&$t(s.options,e)?s.plan:null,a=!o&&!t&&Ht(r,i)?Bt(n):null,l=o??Wt(r,i,a?.rowWidths??null,a?.gridWidth??null);return t||Hr.set(n,{options:e,plan:l}),n.style.gridTemplateColumns=l.template,n.style.setProperty("--aia-grid-max-height",l.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((c,d)=>{c.classList.toggle("magicx-aia-option--scroll-hint",!t&&l.scrollHintIndices.includes(d))}),l.cols}function Wr(n,e){if(e.loading||!e.interactive)return null;let t=e.options[K(n)];return t?.is_tappable?t:null}var Oo={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=Wr(n,e);t&&(n.classList.add("magicx-aia-option--pressed"),e.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(n,e)=>{Wr(n,e)&&e.onHighlight(K(n))},onLeave:(n,e)=>e.onHighlight(-1,K(n))};function Br(n,e,t,r,i,s,o,a="",l="below",c=!0,d=!0,u=!0,g=!0){let p=n.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"),n.appendChild(p)),V(p,Oo,{options:e,onSelect:r,onHighlight:i,loading:o,interactive:g});let f=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a,Ao(p,e,t,s,o,{showIcons:c,showImages:d,showCounts:u});let x=Co(p,e,o);Lo(p,e.length,x,o,l),f&&(p.scrollTop=0)}function Ao(n,e,t,r,i,s){let o=i?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=s,u=l?f=>f.icon??f.icon_svg??"":()=>"",g=c?f=>te(f.image_url)??"":()=>"",p=d?f=>we(f.item_count)??"":()=>"";Q(n,e,{keyOf:f=>`${f.text}\0${u(f)}\0${g(f)}\0${p(f)}\0${o}\0${a}`,create:(f,x)=>{let y=Ro(f,i,s);return i||(y.dataset.aiaEntering=""),y},update:(f,x,y)=>{let b=y===t&&!i;f.id=`${r}-option-${y}`,f.dataset.aiaIndex=String(y),f.setAttribute("aria-selected",String(b)),f.classList.toggle("magicx-aia-option--highlighted",b)}})}function Lo(n,e,t,r,i){for(let s of n.querySelectorAll("[data-aia-entering]")){if(!r){let o=Number.parseInt(s.dataset.aiaIndex??"-1",10);o>=0&&s.style.setProperty(tn,`${nn(o,t,e,i)}ms`)}delete s.dataset.aiaEntering}}function Ro(n,e,{showIcons:t,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||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.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?ot(n.image_url):[],c=l[0];if(c){let p=document.createElement("span");p.className="magicx-aia-option-image",p.setAttribute("aria-hidden","true");let f=document.createElement("img");f.setAttribute("alt",""),f.setAttribute("loading","lazy"),f.setAttribute("decoding","async"),f.setAttribute("referrerpolicy","no-referrer"),f.setAttribute("draggable","false");let x=0;f.onerror=()=>{let y=l[++x];y?f.src=y:f.hidden=!0},f.src=c,p.appendChild(f),a.appendChild(p),s.dataset.aiaImage=""}let d=!c&&t&&n.icon_svg?Te(n.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),n.icon&&(s.dataset.aiaIcon=n.icon)}let u=document.createElement("span");if(u.className="magicx-aia-option-text",u.textContent=on(n),a.appendChild(u),n.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=n.tag,a.appendChild(p)}let g=i?we(n.item_count):null;if(g!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=g,a.appendChild(p),s.dataset.aiaItemCount=String(n.item_count)}return s.appendChild(a),s}var Ur="magicx-aia-scroll-arrow",$r="data-aia-scroll-arrow",de="data-aia-visible",qr=1e3,Gr=160,Vr="--aia-scroll-arrow-bottom",Mo="Scroll down for more options",ko="[data-aia-products-label]",Do=4,_o=8,No=240;function Fo(n,e,t,r){let i=n.scrollTop,s=t?.requestAnimationFrame,o=n.ownerDocument?.visibilityState==="hidden";if(!s||o||sn(n)){n.scrollTop=i+e,r();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/No),u=1-(1-d)*(1-d);n.scrollTop=i+e*u,d<1?s.call(t,c):r()};s.call(t,c)}function Ho(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let r=n.createElementNS(e,"path");return r.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(r),t}function Kr(n=document,e=O()){let t=n.createElement("button");return t.type="button",t.tabIndex=-1,t.className=Ur,t.setAttribute($r,""),t.setAttribute("aria-label",e.scrollArrow),t.setAttribute("aria-hidden","true"),t.disabled=!0,t.appendChild(Ho(n)),t}function Wo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function sn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function an({dropdown:n,grid:e,button:t}){let r=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;t.disabled=!0;let s=null,o=null,a=null,l=null,c=m=>{if(m){if(t.hasAttribute(de))return;if(t.setAttribute(de,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),sn(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&t.hasAttribute(de)&&(t.disabled=!1)},qr)}else t.removeAttribute(de),t.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,t.disabled=!0},d=m=>{let h=0,S=m;for(;S&&S!==n;)h+=S.offsetTop,S=S.offsetParent instanceof HTMLElement?S.offsetParent:null;return h},u=()=>{let m=n.querySelector(ko),h;if(m){let S=d(m)+m.offsetHeight/2;h=n.clientHeight-S-t.offsetHeight/2}else{let S=d(e),I=r&&Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0;h=n.clientHeight-(S+e.offsetHeight)+(I>0?0:_o)}t.style.setProperty(Vr,`${Math.max(0,Math.round(h))}px`)},g=()=>{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;c(!m&&h>Do)},p=()=>{if(i)return;u();let m=e.getAttribute("data-aia-group")??"";if(m!==s){s=m,c(!1),o!==null&&clearTimeout(o);let h=e.querySelectorAll("[data-aia-option]").length,S=sn(e)?0:rn(h,Wo(e));o=setTimeout(()=>{o=null,g()},S);return}g()},f=()=>{i||o!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,g()},Gr))};e.addEventListener("scroll",f,{passive:!0});let x=m=>m.preventDefault(),y=()=>{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);Fo(e,h,r,f)};t.addEventListener("mousedown",x),t.addEventListener("click",y);let b=null;return r&&typeof r.ResizeObserver=="function"&&(b=new r.ResizeObserver(()=>{u(),g()}),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,t.disabled=!0,e.removeEventListener("scroll",f),t.removeEventListener("mousedown",x),t.removeEventListener("click",y),b?.disconnect(),t.removeAttribute(de),t.setAttribute("aria-hidden","true"))}}}var Bo=[159,119,164];function at(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),Vt(e),e}var st=new WeakMap;function Uo(n,e,t){let r=st.get(n);if(r||(r={button:Kr(n.ownerDocument,t),grid:null,controller:null},n.appendChild(r.button),st.set(n,r)),r.button.getAttribute("aria-label")!==t.scrollArrow&&r.button.setAttribute("aria-label",t.scrollArrow),r.grid!==e&&(r.controller?.destroy(),r.controller=null,r.grid=e,e)){r.controller=an({dropdown:n,grid:e,button:r.button});return}r.controller?.update()}function ln(n){let e=st.get(n);e&&(e.controller?.destroy(),st.delete(n))}function lt(n,e){let t=e.strings??O(),{filteredOptions:r,activeIndex:i,isOpen:s,isLoading:o,pills:a,showPills:l,isActivePillSelected:c,onSelect:d,onHighlight:u,onPillClick:g,onSkip:p}=e,f=a.length>0,x=l&&f,y=r.length>0,b=e.products.length>0,m=s&&(y||x||o||b);if(m?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!m){en(n,!1);return}b?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products"),n.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let h=n.querySelector(".aia-stack");h||(h=document.createElement("div"),h.className="aia-stack",h.style.setProperty("--aia-stack-space","8px"),n.appendChild(h));let S=e.showSkipButton&&f&&!e.isInputEmpty,I=x||o&&l||S,w=h.querySelector(".magicx-aia-pill-bar");if(I){w||(w=document.createElement("div"),w.className="magicx-aia-pill-bar aia-cluster",w.setAttribute("data-nowrap",""),w.setAttribute("data-aia-pillbar",""),h.insertBefore(w,h.firstChild));let k=w.querySelector(".magicx-aia-pill-scroll");k||(k=document.createElement("span"),k.className="magicx-aia-pill-scroll",k.setAttribute("data-aia-pill-scroll",""),w.insertBefore(k,w.firstChild)),rt(k,l?a:[],0,g,!0,o&&l,c),Go(w,S,o||e.skipDisabled,a[0],p,t)}else w&&w.remove();let D=e.suggestions[0],C=D?`${D.parameter} ${D.text}`:"",T=P(e.formatType),F=T&&!o;Br(h,T?[]:r,i,d,u,e.listboxId,o,C,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),Uo(n,h.querySelector(".aia-grid"),t),Ir(h,F?r:[],i,e.listboxId,F?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:u,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let A=h.querySelector(".magicx-aia-skeleton-bars");if(o&&(!y||T)){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let k of Bo){let $=document.createElement("span");$.className="magicx-aia-skeleton-bar",$.style.width=`${k}px`,A.appendChild($)}h.appendChild(A)}}else A&&A.remove();Dr(h,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image",t),en(n,!0);let v=h.querySelector(".magicx-aia-footer")??Ko(t),H=i>=0&&!!r[i]?.is_tappable;Vo(v,Gt(H,e.isInputEmpty,t)),v.isConnected||h.appendChild(v),$o(h,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function $o(n,e){let t=e.map(r=>n.querySelector(`:scope > ${r}`)).filter(r=>r!==null);for(let r=0;r<t.length;r++)n.children[r]!==t[r]&&n.insertBefore(t[r],n.children[r]??null)}var qo={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function Go(n,e,t,r,i,s){V(n,qo,{onSkip:i,loading:t});let o=n.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,n.appendChild(o),Y(o)),o.textContent!==s.skip&&(o.textContent=s.skip),o.setAttribute("aria-label",r?`${s.skipLabel} ${r.text}`:s.skipLabel),o.disabled=t}function Vo(n,{key:e,hint:t}){let r=n.querySelector(".magicx-aia-footer-key"),i=n.querySelector(".magicx-aia-footer-hint");!r||!i||(r.textContent!==e&&(r.textContent=e),i.textContent!==t&&(i.textContent=t))}function Ko(n){let e=document.createElement("footer");e.className="magicx-aia-footer",e.setAttribute("data-aia-footer","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-row",t.setAttribute("data-align","center"),t.setAttribute("data-justify","between"),t.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=n.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=qt(),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),t.append(r,o),e.append(t),e}function Yr(n,e){let t=at(e.listboxId);return n.appendChild(t),{dropdown:t}}function dn(n,e,t){let r=Ee(e);lt(n.dropdown,{strings:t.strings,suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:z(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:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:r.selectedIso,selectedDateRange:r.selectedRange,dateRangeStart:r.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:(i,s)=>{s!==void 0&&t.store.get().activeDropdownIndex!==s||t.store.set({activeDropdownIndex:i})},onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Yo=6,Qo=.3;function Qr(n){return n<=0?"0px":`${(-Math.min(Qo,2*Yo/n)).toFixed(3)}px`}function cn(n){let{input:e,segments:t,newParamId:r,editingParamId:i,placeholderText:s,isFocused:o}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",hr(e,c?s:"");let d=t.map(m=>m.type==="completed"?`${m.type}:${m.value}${a?m.param.icon??m.param.icon_svg??"":""}${l?te(m.param.image_url)??"":""}`:`${m.type}:${m.value}`).join("\0"),u=e.dataset.segKey??"",g=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===u&&(r??"")===g&&(i??"")===p)return;if(d===u){e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";for(let m of e.querySelectorAll("strong[data-param-id]")){let h=m.dataset.paramId,S=m.dataset.seg==="completed"&&h===r;m.classList.toggle("magicx-aia-shimmer-revealed",S),m.classList.toggle("magicx-aia-shimmer-sweep",S),m.classList.toggle("magicx-aia-segment--editing",h===i)}return}let f=o?N(e):null;e.dataset.segKey=d,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let x=R(e),y=x.createDocumentFragment(),b=0;for(let m of t)if(b+=m.value.length,m.type==="completed"){let h=x.createElement("strong");h.dataset.seg="completed",h.dataset.paramId=m.param.id;let S=m.param.id===r,I=m.param.id===i,w=["magicx-aia-segment","magicx-aia-segment--completed"];S&&w.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),I&&w.push("magicx-aia-segment--editing"),h.className=w.join(" "),h.style.letterSpacing=Qr(m.value.length);let D=l?te(m.param.image_url):null;if(D){let T=x.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${D}")`),h.appendChild(T),h.dataset.aiaImage=""}let C=!D&&a&&m.param.icon_svg?Te(m.param.icon_svg):null;if(C){let T=x.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=C,h.appendChild(T),m.param.icon&&(h.dataset.aiaIcon=m.param.icon)}h.appendChild(x.createTextNode(m.value)),y.appendChild(h)}else if(m.type==="identified"){let h=x.createElement("strong");h.dataset.seg="identified",h.dataset.paramId=m.param.id;let S=["magicx-aia-segment","magicx-aia-segment--completed"];m.param.id===i&&S.push("magicx-aia-segment--editing"),h.className=S.join(" "),h.style.letterSpacing=Qr(m.value.length),h.textContent=m.value,y.appendChild(h)}else y.appendChild(x.createTextNode(m.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(b),f!=null?M(e,Math.max(0,Math.min(f,b))):o&&zn(e)&&M(e,b)}var Xo='<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 Xr(n=O()){let e=document.createElement("button");return e.type="button",e.className="magicx-aia-submit",e.setAttribute("aria-label",n.submit),e.setAttribute("data-aia-submit",""),e.innerHTML=Xo.replace('aria-label="Submit"',`aria-label="${n.submit}"`),e}function jo(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function jr(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let r=t.getBoundingClientRect(),i=n.getBoundingClientRect();r.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function zr(n,e){let{listboxId:t}=e,r=at(t);n.appendChild(r);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),n.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",jo()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),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,c=null;e.submitButton===void 0?(l=Xr(e.strings),i.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),i.appendChild(c));let d=new AbortController,{signal:u}=d,g=!1,p=0,f=()=>{let b=Ge(o),h=b.length>0&&b[0]!==b[0].toUpperCase()?b[0].toUpperCase()+b.slice(1):b;e.handleChange(h)},x=()=>{let b=G(o)?.node??null;if(!b||!o.contains(b))return null;let S=(b.nodeType===Node.ELEMENT_NODE?b:b.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&jn(o,S)?null:S};if(i.addEventListener("click",b=>{b.target?.closest("[data-aia-pill]")||o.focus()},{signal:u}),o.addEventListener("input",()=>{g||(p=performance.now(),f(),e.handleCaretAfterInput(N(o)))},{signal:u}),R(o).addEventListener("selectionchange",()=>{let b=G(o);if(!b||!o.contains(b.node))return;let m=b.collapsed?x():null,h=e.store.get(),S=h.editingParam?.id??h.editingIdentified?.id??null;if(m&&m!==S){e.startEditingParam(m);return}performance.now()-p<50||e.handleCaretMove(N(o))},{signal:u}),o.addEventListener("click",b=>{let m=Tt(o,b.target);m&&(e.startEditingParam(m),It(o,m))},{signal:u}),o.addEventListener("compositionstart",()=>{g=!0},{signal:u}),o.addEventListener("compositionend",()=>{g=!1,f()},{signal:u}),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 S=h.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&b.preventDefault()}},{signal:u}),o.addEventListener("paste",b=>{b.preventDefault();let m=(b.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let h=R(o),S=We(o);if(!S||!o.contains(S.startContainer))return;S.deleteContents();let I=h.createTextNode(m);S.insertNode(I),S.setStartAfter(I),Se(o,S.startContainer,S.startOffset),f()},{signal:u}),o.addEventListener("keydown",b=>e.handleKeyDown(b),{signal:u}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",b=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;b.stopPropagation(),e.onSubmit(Z(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){o.focus();let b=G(o);(!b||!o.contains(b.node))&&Se(o,o,0)}if(typeof ResizeObserver<"u"){let b=new ResizeObserver(()=>jr(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 un(n,e,t){let{input:r,inlinePillContainer:i,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;r.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?r.setAttribute("aria-activedescendant",u):r.removeAttribute("aria-activedescendant"),o){let b=t.strings??O();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 g=r.dataset.newParamId??"",p=e.newParamId!==null&&e.newParamId!==g;if(cn({input:r,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0,showChipImages:t.showChipImages??!0}),a==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?rt(i,e.actionableSuggestions,0,l,!1,b,e.isActivePillSelected):Qt(i)}else Qt(i);jr(r,i),p?(r.focus(),M(r,e.caretOffset??e.text.length)):e.isFocused&&Ge(r)!==e.text&&M(r,e.text.length);let f=e.editingParam?{parameter:e.editingParam.suggestionParameter,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{parameter:e.editingIdentified.parameter,text:z(e.editingIdentified.parameter),required:!0,options:[]}:null,x=e.dropdownSuggestion??f??e.actionableSuggestions[0],y=Ee(e);lt(s,{strings:t.strings,suggestions:x?[{...x,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:t.listboxId,pills:f?[f]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:y.selectedIso,selectedDateRange:y.selectedRange,dateRangeStart:y.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:(b,m)=>{m!==void 0&&d.get().activeDropdownIndex!==m||d.set({activeDropdownIndex:b})},onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:b=>d.set({isFocused:b})})}function pn(n){let e=n,t=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 c=r.shift();c;c=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,u]=c;for(let g of t)g(d,u)}}catch(l){throw r.length=0,l}finally{i=!1}}},subscribe:s=>(t.add(s),()=>{t.delete(s)})}}function Jr(n,e){let t,r,i=s=>(s!==t&&(t=s,r=e(s)),r);return{get:()=>{let s=n.get();return{...s,...i(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...i(o)};return s(a)}):n.set(s)},peek:s=>{let o={...n.get(),...s};return{...o,...e(o)}},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...i(a)},c={...o,...i(o)};s(c,l)})}}var mn=new WeakSet,Zr=new WeakMap;function ti(n){return n.nodeType===Node.DOCUMENT_NODE}function zo(n){return ti(n)?n:n.ownerDocument}function Jo(n){let e=Zr.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let r=new t;return typeof r.replaceSync!="function"?null:(r.replaceSync(ri),Zr.set(n,r),r)}catch{return null}}function ei(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ri,e.appendChild(t)}function ni(n){if(typeof document>"u")return;let e=n??document;if(mn.has(e))return;let t=zo(e);if(ti(e)){let s=e.head??e.documentElement;if(!s)return;ei(t,s),mn.add(e);return}let r=Jo(t),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):ei(t,e),mn.add(e)}var ri=`.aia-stack {
|
|
1
|
+
function P(n){return n==="date"||n==="date-range"}function X(n){return n?.type?.kind==="date"?"date":n?.type?.kind==="date_range"?"date-range":"options"}var Oe=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 li="https://api.ai-autocomplete.com",re=`${li}/api/suggest`,Sn=new WeakMap;function ue(n){return n?.type==="accessToken"}function di(n){if(!(!n||ue(n)))return n}function Ae(n){let e=Sn.get(n.getAccessToken);return e||(e=new Oe(n),Sn.set(n.getAccessToken,e)),e}function Le(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function Re(n){let e=di(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}function pe(n){return n.map(e=>({parameter:e.parameter,text:e.text}))}var xn="skipped";function me(n,e){if(e.length===0)return n;let t=new Set(n.map(i=>i.parameter)),r=e.filter(i=>!t.has(i.parameter)).map(i=>({placeholder:"",parameter:i.parameter,text:xn,kind:null}));return r.length>0?[...n,...r]:n}var ci="0.43.0",Pn="1.0",yn=!1;function ui(n,e){return{placeholder:n.placeholder,parameter:n.parameter,...e&&{text:n.value??n.text},kind:n.kind}}function ge(n){return n??(typeof navigator<"u"?navigator.language:"en-US")}function pi(n,e,t,r,i,s,o,a,l,c,d){let u=e.find(p=>p.parameter==="contact"&&p.metadata?.contact_account_count)?.metadata?.contact_account_count,g=typeof u=="number"?u:void 0;return{data:{raw_query:n,completed_params:me(e.map(p=>ui(p,t)),l??[]),...o&&o.length>0&&{identified_params:pe(o)},...a&&a.length>0&&{recently_suggested:a},...g!=null&&{contact_account_count:g},...c!==void 0&&{additional_context:c}},meta:{request_id:i,request_at:new Date().toISOString(),language:ge(d),client_version:ci,session_id:r,source:s,schema_version:Pn}}}async function vn(n,e,t,r,i){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:r,signal:i})}async function En(n,e,t){let r=t.apiConfig,i=!t.maskCompletedText,s=pi(n,e,i,t.sessionId,t.requestId??crypto.randomUUID(),t.source,t.identifiedParams,t.recentlySuggested,t.skippedParams,t.additionalContext,t.language),o=Le(r),a=r?.endpoint??re,l=JSON.stringify(s);if(ue(r)){let u=Ae(r),g=await u.getToken(),p=await vn(a,o,g,l,t.signal);if(p.status===401){let f=await u.getToken(!0);p=await vn(a,o,f,l,t.signal)}if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}let c=Re(r);!c&&!yn&&(yn=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),c&&(o.Authorization=c);let d=await fetch(a,{method:"POST",headers:o,body:l,signal:t.signal});if(!d.ok)throw new Error(`API error: ${d.status} ${d.statusText}`);return d.json()}var Me=/[\p{L}\p{N}]/u,mi=/['\u2019-]/;function wn(n,e,t){let r=n[e];if(r===void 0)return!1;if(Me.test(r))return!0;let i=n[e+t];return mi.test(r)&&i!==void 0&&Me.test(i)}function gi(n,e,t){let r=e+t.length;return!(Me.test(t[0])&&wn(n,e-1,-1)||Me.test(t[t.length-1])&&wn(n,r,1))}function W(n,e,t=0,r=()=>!0){if(e.length===0)return n.indexOf(e,t);let i=-1,s=n.indexOf(e,t);for(;s!==-1;){if(r(s)){if(gi(n,s,e))return s;i===-1&&(i=s)}s=n.indexOf(e,s+1)}return i}function L(n,e){let t=n,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}}}`,u=p=>W(t,a.text,p,f=>!s.some(x=>f<x.end&&f+a.text.length>x.start)),g=u(o);if(g===-1&&(g=u(0)),g!==-1){t=t.slice(0,g)+d+t.slice(g+a.text.length);let p=d.length-a.text.length;for(let f of s)f.start>=g+a.text.length&&(f.start+=p,f.end+=p);s.push({start:g,end:g+d.length}),o=g>=o?g+d.length:o+p}i.push({...a,placeholder:d})}return{rawQuery:t,completedParams:i}}function q(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function De(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function fe(n,e,t){let r=n.slice(e);if(t||e===0||n[e-1]===" ")return r;let i=r.indexOf(" ");return i===-1?"":r.slice(i+1)}function Tn(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let r=t.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=t.length-o.length;return n.length-a}}return 0}function j(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let r=t.toLowerCase();return n.filter(i=>!i.is_tappable||i.text.toLowerCase().includes(r))}function ke(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let r=t.toLowerCase();return n.find(i=>i.is_tappable&&i.text.toLowerCase()===r)??null}function he(n,e,t,r,i){let s=fe(e,t,r),o=ke(n,s);if(o||!i||!s.trim())return o;if(s===e.slice(t))return null;let a=e.lastIndexOf(" ",t-1)+1;return ke(n,e.slice(a))}function In(n,e){return e?n.map(t=>e[t.parameter]?{...t,options:[]}:t):n}function fi(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[^a-zA-Z0-9]+/).filter(Boolean).map(e=>e.toLowerCase())}function z(n){let e=fi(n);return e.length>0?e.join(" "):n}function B(n,e){return n.parameter||e}function Cn(n,e){let t=0,r=e;for(let i of n)t+=i.value.length,i.type!=="text"&&(r=Math.max(r,t));return r}function On(n,e){let t=0;for(let r of n){let i=t+r.value.length;if(r.type==="text"&&i>e&&r.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=i}return!0}function An(n,e){let t=[],r=new Set;for(let i of[...n,...e])i.parameter==="placeholder"||r.has(i.parameter)||(r.add(i.parameter),t.push({parameter:i.parameter,text:i.text}));return t}function Ln(n,e,t){if(n===e)return t;let r=Math.min(n.length,e.length),i=0;for(;i<r&&n[i]===e[i];)i++;if(i>=t)return t;let s=0;for(;s<r-i&&n[n.length-1-s]===e[e.length-1-s];)s++;return n.length-s<=t?t+(e.length-n.length):null}function _e(n,e){let t=[],r=[],i=0;for(let s of e){let o=W(n,s.text,i);if(o===-1){r.push(s);continue}t.push({start:o,end:o+s.text.length,param:s}),i=o+s.text.length}return{located:t,missing:r}}function Rn(n,e){let{located:t}=_e(n,e);return t.length>0?t[t.length-1].end:0}function Mn(n,e,t){let r=[],i=[],s=0;for(let o of t){let a=W(n,o.text,s,l=>!e.some(c=>l<c.end&&l+o.text.length>c.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 kn(n,e,t=[]){let r=_e(n,e).located,i=Mn(n,r,t).located,s=[...r.map(c=>({start:c.start,end:c.end,segment:{type:"completed",value:c.param.text,param:c.param}})),...i.map(c=>({start:c.start,end:c.end,segment:{type:"identified",value:c.param.text,param:c.param}}))].sort((c,d)=>c.start-d.start),o=[],a=0;for(let c of s)c.start>a&&o.push({type:"text",value:n.slice(a,c.start)}),o.push(c.segment),a=c.end;let l=n.slice(a);return l&&o.push({type:"text",value:l}),o}function Dn(n,e){let{located:t,missing:r}=_e(n,e);return{valid:t.map(i=>i.param),invalid:r}}function be(n,e,t){let r=_e(n,e).located,{located:i,missing:s}=Mn(n,r,t);return{valid:i.map(o=>o.param),invalid:s}}var hi=new Map([["api.ai-autocomplete.com","cdn.ai-autocomplete.com"],["dev-api.ai-autocomplete.com","dev-cdn.ai-autocomplete.com"]]);function _n(n,e){let t=e?.endpoint??re,r=t.replace(/\/suggest(?=[?#]|$)/,`/starting-state/${encodeURIComponent(n)}`);if(r!==t)return r.replace(/^https:\/\/([^/?#]+)/,(i,s)=>{let o=hi.get(s);return o?`https://${o}`:i})}async function Nn(n){try{let e=await n;if(!e.ok)return null;let t=await e.json();return Array.isArray(t?.data?.suggestions)?t:null}catch{return null}}function bi(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Si=100,xi=300,yi=2,Ne=class{constructor(e,t,r,i,s,o,a,l,c,d={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=r;this.getMaskCompletedText=i;this.getOnError=s;this.getSessionId=o;this.getSource=a;this.getAdditionalContext=l;this.getLanguage=c;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,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(r=>{(r.text!==e||r.completedParams!==t)&&(e=r.text,t=r.completedParams,this.scheduleFetch())})}isPhraseExactMatch(){return this.phraseExactMatch}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){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?An(o.pendingSpan.snapshot,o.actionableSuggestions):void 0,l=crypto.randomUUID(),c=e===""&&t.length===0&&o.skippedParams.length===0&&o.identifiedParams.length===0?this.startingStateUrl():void 0,d=c?await Nn(fetch(c,{signal:r.signal})):null;if(i!==this.fetchVersion)return;let u=d??await En(e,t,{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()});if(i!==this.fetchVersion)return;this.phraseExactMatch=u.meta?.phrase_exact_match===!0;let g=(u.data.input??[]).filter(v=>v.source==="identified").map(v=>({id:crypto.randomUUID(),parameter:v.parameter,text:v.text,...v.type?{type:v.type}:{}})),p=this.callbacks.isWordOpen?.()??!1,f=this.store.get().text.toLowerCase(),x=v=>p&&f.endsWith(v.text.toLowerCase()),y=g.filter(v=>!x(v));p&&this.callbacks.holdIdentified?.(g.filter(x));let b=In(u.data.suggestions??[],this.getOptionOverrides()),m=u.data.input??[],h=m[m.length-1],S=this.store.get().text,I,w;if(h?.state==="in_progress"){w=!0;let v=S.toLowerCase().lastIndexOf(h.text.toLowerCase());I=v!==-1?v:s}else w=!1,I=s;let C=b.filter(v=>v.parameter!=="placeholder")[0],T=null;if(C&&!p&&!P(X(C))){let v=he(C.options,S,I,w,this.phraseExactMatch);v&&(T={id:crypto.randomUUID(),placeholder:"",parameter:B(v,C.parameter),text:v.text,value:v.value,kind:v.kind,suggestionParameter:C.parameter,suggestionValueType:C.type,suggestionPlaceholder:C.text,options:C.options??[],metadata:v.metadata,icon:v.icon,icon_svg:v.icon_svg,image_url:v.image_url},b=b.filter(H=>H!==C),this.callbacks.onAutoMatch?.({active:C,matched:v,rawQuery:e}))}let F=u.data.custom_fields??null,A=this.callbacks.productsForResponse?.(F);this.store.set(v=>{let H=T?[...v.completedParams,T]:v.completedParams,k=be(v.text,H,y).valid,$=new Set(o.skippedParams.map(E=>E.id)),Ce=new Set(v.skippedParams.filter(E=>!$.has(E.id)).map(E=>E.parameter));return{suggestions:Ce.size>0?b.filter(E=>E.parameter==="placeholder"||!Ce.has(E.parameter)):b,isLoading:!1,isReady:u.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:I,filterInProgress:w,identifiedParams:k,customFields:F,...A!==void 0?{products:A}:{},...T?{completedParams:H}:{}}}),this.callbacks.onResponse?.({requestId:l,funnelTelemetry:u.meta?.funnel_telemetry===!0})}catch(o){let a=bi(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?_n(e,this.getApiConfig()):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(yi)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Si),this.slowDebounceTimer=setTimeout(()=>this.attemptFetch(1,!0),xi)}attemptFetch(e,t=!1){let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let i=this.callbacks.consumerTick?.(r,e)??"no";if(i==="asked")return!0;if(i==="owns")return!1;let s=r.suggestions.filter(S=>S.parameter==="placeholder").map(S=>S.text).join(" "),o=q(r.text,r.filterBase,s),a=fe(r.text,o,r.filterInProgress),c=r.suggestions.filter(S=>S.parameter!=="placeholder")[0],d=P(r.activeFormatType),g=(c&&!d?j(c.options,a):[]).filter(S=>S.is_tappable),p=c&&!d&&!this.callbacks.isWordOpen?.()?he(c.options,r.text,o,r.filterInProgress,this.phraseExactMatch)!==null:!1,f=a.trim().length>0;if(g.length>0&&!p&&f||De(r.text,r.completedParams.length,s))return!1;let{rawQuery:x,completedParams:y}=L(r.text,r.completedParams),b=x.length<r.lastRawQuery.length,m=Math.abs(x.length-r.lastRawQuery.length),h=t&&x!==r.lastRawQuery;return b||m>=e||h?(this.doFetch(x,y),!0):!1}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var ie=["January","February","March","April","May","June","July","August","September","October","November","December"],Fe=["S","M","T","W","T","F","S"],Wn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],Bn="aiaDate",Un="aiaDay",Fn=n=>String(n).padStart(2,"0");function _(n){return`${n.getFullYear()}-${Fn(n.getMonth()+1)}-${Fn(n.getDate())}`}function pt(n){return new Date(n.getFullYear(),n.getMonth(),n.getDate())}function vi(n){let e=pt(n).getTime()-pt(new Date).getTime();return Math.round(e/864e5)}function $n(n){let e=vi(n);return e>=0&&e<7?Wn[n.getDay()]:oe(n)}function oe(n){return n.getFullYear()===new Date().getFullYear()?`${ie[n.getMonth()]} ${n.getDate()}`:`${ie[n.getMonth()]} ${n.getDate()} ${n.getFullYear()}`}function He(n){if(!n)return null;let e=Wn.findIndex(a=>a.toLowerCase()===n.trim().toLowerCase());if(e>=0){let a=pt(new Date),l=(e-a.getDay()+7)%7;return new Date(a.getFullYear(),a.getMonth(),a.getDate()+l)}let t=/^\s*([A-Za-z]+)\s+(\d{1,2})(?:\s+(\d{4}))?\s*$/.exec(n);if(!t)return null;let r=ie.findIndex(a=>a.toLowerCase()===t[1].toLowerCase());if(r<0)return null;let i=Number(t[2]),s=t[3]?Number(t[3]):new Date().getFullYear(),o=new Date(s,r,i);return o.getMonth()!==r||o.getDate()!==i?null:o}function mt(n){return`${ie[n.month]} ${n.year}`}function gt(){let n=new Date;return{year:n.getFullYear(),month:n.getMonth()}}function qn(n){return{year:n.getFullYear(),month:n.getMonth()}}function ft(n,e){let t=new Date(n.year,n.month+e,1);return{year:t.getFullYear(),month:t.getMonth()}}function Hn(){return{text:"",is_tappable:!1,kind:null}}function ht(n){let e=new Date(n.year,n.month,1).getDay(),t=new Date(n.year,n.month+1,0).getDate(),r=[];for(let i=0;i<e;i++)r.push(Hn());for(let i=1;i<=t;i++){let s=new Date(n.year,n.month,i);r.push({text:$n(s),is_tappable:!0,kind:null,metadata:{[Bn]:_(s),[Un]:i}})}for(;r.length%Fe.length!==0;)r.push(Hn());return r}function bt(n){let e=He(n);return e?_(e):null}function U(n){let e=n?.metadata?.[Bn];return typeof e=="string"?e:null}function St(n){let e=n?.metadata?.[Un];return typeof e=="number"?e:null}function Pi(n){return n.nodeType===Node.DOCUMENT_NODE?!0:n.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in n}function J(n){let e=typeof n.getRootNode=="function"?n.getRootNode():null;return e&&Pi(e)?e:n.ownerDocument??n}function R(n){return n.ownerDocument??n}function Ei(n){return n.nodeType===Node.DOCUMENT_FRAGMENT_NODE}function Gn(n){let e=J(n);return!Ei(e)||typeof e.getSelection=="function"?null:e}function Vn(n){let e=Gn(n);if(!e)return null;let t=R(n).getSelection?.();return!t||typeof t.getComposedRanges!="function"?null:e}function Kn(n,e){let t=n,r;try{r=t.getComposedRanges({shadowRoots:[e]})}catch{r=t.getComposedRanges(e)}return r.length>0?r[0]:null}function xt(n){let t=J(n).getSelection?.();return t||(R(n).getSelection?.()??null)}function G(n){let e=xt(n);if(!e||e.rangeCount===0)return null;let t=Vn(n);if(t){let r=Kn(e,t);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 We(n){let e=xt(n);if(!e||e.rangeCount===0)return null;let t=Vn(n);if(!t)return e.getRangeAt(0);let r=Kn(e,t);if(!r)return null;let i=R(n).createRange();return i.setStart(r.startContainer,r.startOffset),i.setEnd(r.endContainer,r.endOffset),i}function Se(n,e,t){let r=xt(n);if(!r)return null;if(Gn(n))return r.collapse(e,t),r;let i=R(n).createRange();return i.setStart(e,t),i.collapse(!0),r.removeAllRanges(),r.addRange(i),r}function Be(n,e){let t=n?J(n):typeof document<"u"?document:null;return t?typeof t.getElementById=="function"?t.getElementById(e):typeof document<"u"?document.getElementById(e):null:null}var Ue=2,wi="magicx-aia";function Yn(n){return n==="auto"||n==="scroll"||n==="hidden"||n==="overlay"}function Ti(n){let e=R(n),t=e.defaultView;if(!t?.getComputedStyle)return null;let r=n;for(;r&&r!==e.body&&r!==e.documentElement;){let i=r.scrollWidth>r.clientWidth,s=r.scrollHeight>r.clientHeight;if(i||s){let o=t.getComputedStyle(r);if(i&&Yn(o.overflowX)||s&&Yn(o.overflowY))return r}if(r.classList.contains(wi))return null;r=r.parentElement}return null}function yt(n){let e=We(n);if(!e||!e.collapsed||!n.contains(e.startContainer))return;let t=Ti(n);if(!t||typeof e.getBoundingClientRect!="function")return;let r=e.getBoundingClientRect();if(r.height===0)return;let i=t.getBoundingClientRect();if(t.scrollWidth>t.clientWidth){let s=i.left+t.clientLeft,o=s+t.clientWidth;r.right>o?t.scrollLeft+=r.right-o+Ue:r.left<s&&(t.scrollLeft-=s-r.left+Ue)}if(t.scrollHeight>t.clientHeight){let s=i.top+t.clientTop,o=s+t.clientHeight;r.bottom>o?t.scrollTop+=r.bottom-o+Ue:r.top<s&&(t.scrollTop-=s-r.top+Ue)}}var Xn='[contenteditable="false"]',Pt="strong[data-param-id]",se;function Ii(){if(se!==void 0)return se;let n=globalThis.Intl.Segmenter;if(!n)return se=null,null;try{se=new n(void 0,{granularity:"grapheme"})}catch{se=null}return se??null}function $e(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Xn))return!0;t=t.parentNode}return!1}function qe(n){return R(n).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return $e(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function Ge(n){let e=qe(n),t="",r=e.nextNode();for(;r;)t+=r.data,r=e.nextNode();return t}function Et(n){let e=qe(n),t=0,r=e.nextNode();for(;r;)t+=r.data.length,r=e.nextNode();return t}function N(n){let e=G(n);if(!e)return null;let t=e.node,r=e.offset;if(!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let i=t;if($e(i,n)&&i!==n)return null;let s=0;for(let o=0;o<r&&o<i.childNodes.length;o++)s+=wt(i.childNodes[o],n);return s+vt(i,n)}return t.nodeType!==Node.TEXT_NODE||$e(t,n)?null:vt(t,n)+r}function wt(n,e){if(n.nodeType===Node.TEXT_NODE)return $e(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Xn))return 0;let r=0;for(let i of Array.from(t.childNodes))r+=wt(i,e);return r}function vt(n,e){let t=qe(e),r=0,i=t.nextNode();for(;i;){if(i===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(i))return r;r+=i.data.length,i=t.nextNode()}return r}function M(n,e){let t=R(n),r=Math.max(0,Math.min(e,Et(n))),i=qe(n),s=0,o=null,a=0,l=i.nextNode(),c=null;for(;l;){let u=l.data.length;if(r<s+u){o=l,a=r-s;break}if(r===s+u){let g=i.nextNode();g?(o=g,a=0):(o=l,a=u);break}s+=u,c=l,l=i.nextNode()}let d=t.createRange();if(o){let u=o.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?a===0?d.setStartBefore(u):a===o.data.length?d.setStartAfter(u):d.setStart(o,a):d.setStart(o,a)}else c?d.setStart(c,c.data.length):d.setStart(n,0);d.collapse(!0),Se(n,d.startContainer,d.startOffset)&&(Ci(n,d,r),yt(n))}function Qn(n,e){if(!n||!e.contains(n))return null;let r=(n.nodeType===Node.ELEMENT_NODE?n:n.parentElement)?.closest(Pt)??null;return r&&e.contains(r)?r:null}function Ci(n,e,t){let r=Qn(G(n)?.node??null,n);if(r&&r!==Qn(e.startContainer,n)){n.dataset.aiaCaretEscapedChip=`${t}:${r.dataset.paramId}`;return}delete n.dataset.aiaCaretEscapedChip}function jn(n,e){let t=n.dataset.aiaCaretEscapedChip;if(!t)return!1;let r=N(n);return r!==null&&t===`${r}:${e}`}function zn(n){return J(n).activeElement===n}function Tt(n,e){if(!e||e.nodeType===void 0)return null;let t=e,i=(t.nodeType===Node.ELEMENT_NODE?t:t.parentElement)?.closest(Pt);if(!i||!n.contains(i))return null;let s=G(n);return s&&!s.collapsed?null:i.dataset.paramId??null}function It(n,e){let t=null;for(let o of n.querySelectorAll(Pt))if(o.dataset.paramId===e){t=o;break}if(!t)return;let r=vt(t,n),i=r+wt(t,n),s=N(n);s!=null&&s>=r&&s<=i||M(n,r)}function Ct(n){let e=N(n);return e==null?!1:e>=Et(n)}function Ot(n,e){if(e<=0)return 0;let t=Ii();if(!t)return e-1;let r=n.slice(0,e),i=0;for(let{index:s}of t.segment(r))s<e&&(i=s);return i}function Z(n,e,t=[],r={}){let{rawQuery:i,completedParams:s}=L(n,e);return{query:n.trim(),raw_query:i,completed_params:me(s,t),identified_params:pe(r.identifiedParams??[]),is_ready:r.isReady??!1,...r.customFields?{custom_fields:r.customFields}:{}}}function At(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?Ct(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Lt(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?N(n):null}var Ve=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=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 c=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let d=At(e.target,t),u=!!t.editingParam;if(!d&&!u&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(c)break;e.preventDefault();let f=P(t.activeFormatType)?this.dateEntryIndex(t,!1):l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(l.length===0)return;this.store.set({activeDropdownIndex:f});break}if(e.preventDefault(),l.length===0)return;if(P(t.activeFormatType)){this.stepDateWeek(t,7);break}if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let g=l.indexOf(t.activeDropdownIndex),p=g<l.length-1?g+1:0;this.store.set({activeDropdownIndex:l[p]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!c)break;let g=At(e.target,t),p=!!t.editingParam;if(!g&&!p)break;e.preventDefault();let f=P(t.activeFormatType)?this.dateEntryIndex(t,!0):this.firstTappableInBottomRow(o)??l[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(l.length===0)return;this.store.set({activeDropdownIndex:f});break}if(l.length===0)break;if(e.preventDefault(),P(t.activeFormatType)){this.stepDateWeek(t,-7);break}if(t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let d=l.indexOf(t.activeDropdownIndex),u=d>0?d-1:l.length-1;this.store.set({activeDropdownIndex:l[u]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,1);break}if(t.activeDropdownIndex%o<o-1){let g=t.activeDropdownIndex+1;g<t.filteredOptions.length&&t.filteredOptions[g]?.is_tappable&&this.store.set({activeDropdownIndex:g})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let u=e.target.closest("[data-aia-input]")??e.target,g=t.editingTail;this.ctx.exitEditMode?.(),M(u,g);break}At(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),P(t.activeFormatType)){this.stepDateDay(t,-1);break}if(t.activeDropdownIndex%o>0){let d=t.activeDropdownIndex-1;d>=0&&t.filteredOptions[d]?.is_tappable&&this.store.set({activeDropdownIndex:d});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let d=Lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingAnchor;this.ctx.exitEditMode?.(),M(d,u);break}if(this.ctx.startEditingParamAtCaret){let d=Lt(e.target);d!=null&&this.ctx.startEditingParamAtCaret(d)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let d=Lt(e.target);if(d==null)break;this.ctx.removeParamAtCaret(d)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,r,s);else if(a){this.ctx.endTypedWord?.();let d=this.store.get();a(Z(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=t.filteredOptions.map((p,f)=>p.is_tappable?f:-1).filter(p=>p!==-1);if(d.length===0)break;if(!t.isDropdownOpen){if(t.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 u=d.indexOf(t.activeDropdownIndex),g;if(u<0)g=e.shiftKey?d.length-1:0;else{let p=e.shiftKey?-1:1;g=(u+p+d.length)%d.length}this.store.set({activeDropdownIndex:d[g]});break}case"Escape":{if(t.dateRangeStart){this.store.set({pendingRangeStart:null});break}if(t.editingIdentified){this.ctx.exitEditingIdentified?.(),this.store.set({activeDropdownIndex:-1});break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let d=e.target.closest("[data-aia-input]")??e.target,u=t.editingTail;this.ctx.exitEditMode?.(),M(d,u)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let i=Math.floor((t.filteredOptions.length-1)/e)*e;for(let s=i;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}dateEntryIndex(e,t){let r=_(new Date),i=e.filteredOptions.findIndex(o=>U(o)===r);if(i>=0)return i;let s=e.filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1);return(t?s[s.length-1]:s[0])??0}stepDateDay(e,t){for(let r=e.activeDropdownIndex+t;r>=0&&r<e.filteredOptions.length;r+=t)if(e.filteredOptions[r]?.is_tappable){this.store.set({activeDropdownIndex:r});return}}stepDateWeek(e,t){let r=e.activeDropdownIndex+t;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 t=Be(e,this.ctx.listboxId);if(!t)return this.ctx.columns;let i=Be(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===t)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,r,i){let s=Be(i,`${r}-option-${e}`);s?s.click():this.ctx.selectOption(t[e])}};var Ke=class{constructor(e,t,r={}){this.store=e;this.getOverrides=t;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,t){return this.hasOverride(e)&&!this.missCovers(e,t)}tick(e,t){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(t>1&&!o&&s<t)return"owns"}return this.ask(r),"asked"}sync(e){let t=this.resolveTarget(e);if(!t){this.current&&(this.cancel(),this.current=null),e.optionSearch&&this.store.set({optionSearch:null});return}this.current&&this.current.key===t.key||this.ask(t)}resolveTarget(e){if(P(e.activeFormatType)||e.editingIdentified)return null;let t=e.editingParam;if(t&&e.editingAnchor!=null)return this.hasOverride(t.suggestionParameter)?{mode:"edit",key:t.id,parameter:t.suggestionParameter,suggestion:{parameter:t.suggestionParameter,text:t.suggestionPlaceholder,required:!0,options:t.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,t){return this.lastMiss!=null&&this.lastMiss.parameter===e&&this.lastMiss.query===t}ask(e){this.cancel();let t=this.getOverrides()?.[e.parameter],r=++this.version;if(!t||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=t(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,t,r,i){let s;try{let o=await t;if(r.aborted||i!==this.version)return;s=Array.isArray(o)?o:[]}catch(o){if(r.aborted||i!==this.version||Oi(o))return;this.logOnce(o),s=[]}this.commit(e,s,i)}commit(e,t,r){if(r!==this.version)return;let i=this.resolveTarget(this.store.get());if(!i||i.key!==e.key)return;t.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:t}:o.editingParam,optionSearch:s}));else{let o={...e.suggestion,options:t};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}))}t.length===0?this.callbacks.onMiss?.(e.mode,e.query):this.callbacks.onAnswer?.(e.mode,e.query)}setSearch(e,t){let r=this.store.get().optionSearch;r&&r.parameter===e.parameter&&r.query===e.query&&r.status===t||this.store.set({optionSearch:{parameter:e.parameter,query:e.query,status:t}})}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 Oi(n){return n instanceof Error&&n.name==="AbortError"}var Ye=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),r=t.suggestions.filter(c=>c.parameter!=="placeholder");if(e<0||e>=r.length)return;let i=r[e],s=r.filter((c,d)=>d!==e),o=t.suggestions.filter(c=>c.parameter==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:c}=L(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:c,selectedPill:i.text,otherPills:s.map(d=>d.text)})}let a=[...o,i,...s],l=this.store.peek({suggestions:a}).filteredOptions.findIndex(c=>c.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:l})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var Zn="/products/",Jn="https://relative.invalid";function Ai(n){if(!n)return;let e;try{e=new URL(n,`${Jn}/`)}catch{return}if(!(e.protocol!=="http:"&&e.protocol!=="https:"))return n.startsWith("/")?e.origin===Jn?n:void 0:/^https?:\/\//i.test(n)?n:void 0}function er(n,e){let t=Ai(n.item_url)??Ri(n);return{id:n.source_id,title:n.title,...t&&{url:t},imageUrl:n.image_url||null,...n.price&&{price:Li(n.price,n.currency,e)},...n.vendor&&{vendor:n.vendor},...typeof n.available=="boolean"&&{available:n.available}}}function Li(n,e,t){if(t===void 0||!e||!/^\d+(\.\d+)?$/.test(n))return n;try{return new Intl.NumberFormat(t,{style:"currency",currency:e}).format(Number(n))}catch{return n}}function Ri(n){if(!n.handle)return;let e=`${Zn}${encodeURIComponent(n.handle)}`;return n.variant_id?`${e}?variant=${encodeURIComponent(n.variant_id)}`:e}function Rt(n,e){return(n?.items.matched??[]).map(t=>er(t,e))}var Qe=class{constructor(e,t,r=()=>!0,i=()=>{}){this.store=e;this.getConfig=t;this.isEnabled=r;this.getLanguage=i;this.hasLoggedError=!1}forResponse(e){if(!this.isEnabled())return[];if(!this.getConfig())return Rt(e,ge(this.getLanguage()))}async run(e,t,r){if(!this.isEnabled())return;let i=this.getConfig();if(!i)return;if(e.trim().length===0){this.clear(r);return}let s=()=>t.aborted||!r()||!this.owns(i);try{let o=await i.fetch(e,t);if(s())return;let a=i.transform(o),l=Array.isArray(a)?a:[],c=i.limit!=null?l.slice(0,i.limit):l;if(s())return;this.commit(c)}catch(o){if(t.aborted||Mi(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??[])}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 Mi(n){return n instanceof Error&&n.name==="AbortError"}function ki(n){return n.replace(/(\d+)(?:st|nd|rd|th)\b/g,"$1")}function tr(n){let e=n.toLowerCase().replace(/\.$/,"");return e.length<3?-1:ie.findIndex(t=>t.toLowerCase().startsWith(e))}function Di(n,e,t){let r=new Date(t.getFullYear(),n,e);if(r.getMonth()!==n||r.getDate()!==e)return null;let i=new Date(t.getFullYear(),t.getMonth(),t.getDate());if(r>=i)return r;let s=new Date(t.getFullYear()+1,n,e);return s.getMonth()===n&&s.getDate()===e?s:null}function nr(n,e,t){let r=new Date(n,e,t);return r.getMonth()===e&&r.getDate()===t?r:null}function xe(n,e={}){if(!n)return null;let t=e.today??new Date,r=ki(n.trim().toLowerCase()).replace(/\s+/g," "),i=/^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(r);if(i){let l=nr(Number(i[1]),Number(i[2])-1,Number(i[3]));return l?_(l):null}let s=/^([a-z]+)\.? (\d{1,2})(?:,? (\d{4}))?$/.exec(r);if(s){let l=tr(s[1]);if(l>=0)return Xe(l,Number(s[2]),s[3],t)}let o=/^(\d{1,2}) (?:of )?([a-z]+)\.?(?:,? (\d{4}))?$/.exec(r);if(o){let l=tr(o[2]);if(l>=0)return Xe(l,Number(o[1]),o[3],t)}let a=/^(\d{1,2})[/\-.](\d{1,2})(?:[/\-.](\d{2,4}))?$/.exec(r);if(a){let l=Number(a[1]),c=Number(a[2]);return l>12&&c<=12?Xe(c-1,l,a[3],t):c>12&&l<=12?Xe(l-1,c,a[3],t):null}return null}function Xe(n,e,t,r){if(t){if(t.length!==4)return null;let s=nr(Number(t),n,e);return s?_(s):null}let i=Di(n,e,r);return i?_(i):null}function Mt(n,e={}){let t=n.isoDate;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:xe(n.text,e)}var ir=" - ",Dt="aiaDateRangeStart",_t="aiaDateRangeEnd";function ye(n,e){return n<=e?{start:n,end:e}:{start:e,end:n}}var kt=/^\d{4}-\d{2}-\d{2}$/;function rr(n){if(!kt.test(n))return null;let[e,t,r]=n.split("-").map(Number),i=new Date(e,t-1,r);return i.getMonth()===t-1&&i.getDate()===r?i:null}var _i=/\s+(?:to|through|thru|until|til|till)\s+/g,Ni=/[-–—]/g;function Fi(n){let e=[];for(let t of[_i,Ni]){t.lastIndex=0;let r=t.exec(n);for(;r!==null;)e.push([n.slice(0,r.index),n.slice(r.index+r[0].length)]),r=t.exec(n)}return e}function je(n,e={}){if(!n)return null;let t=new Set,r=null;for(let[i,s]of Fi(n.trim())){let o=xe(i.trim(),e);if(!o)continue;let a=xe(s.trim(),e);!a||a<o||(t.add(`${o}|${a}`),r={start:o,end:a})}return t.size===1?r:null}function or(n){let e=rr(n.start),t=rr(n.end);return!e||!t?"":n.start===n.end?oe(e):`${oe(e)}${ir}${oe(t)}`}function sr(n,e){let t=ye(n,e);return{text:or(t),is_tappable:!0,kind:null,metadata:{[Dt]:t.start,[_t]:t.end}}}function ve(n,e={}){let t=n?.metadata?.[Dt],r=n?.metadata?.[_t];return typeof t=="string"&&typeof r=="string"&&kt.test(t)&&kt.test(r)?ye(t,r):je(n?.text,e)}var ze="(max-width: 768px)";var Hi="var(--aia-option-row-height, 37px)",Wi="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ar(n,e){return e?Nt(1,Math.min(n,5)):Nt(1,Math.min(n,4))}function Nt(n,e){return{cols:n,rows:e,maxHeight:`calc(${e} * ${Hi} + ${Wi})`}}function Ht(n,e){return!e&&n>=5}function Wt(n,e,t,r){if(!(!e&&n>=5&&Bi(t,r))){let o=ar(n,e);return{...o,template:Ft(o.cols),scrollHintIndices:!e&&n>o.rows?[o.rows-1]:[]}}let s=6;return{...Nt(2,3),template:Ft(2),scrollHintIndices:n>s?[s-2,s-1]:[]}}function Bi(n,e){return!n||n.length===0||e==null||e<=0||n.some(r=>r<=0)?!1:Math.ceil(Math.max(...n))*2<=e}function Bt(n){if(typeof document>"u")return null;let e=Array.from(n.querySelectorAll("[data-aia-option]"));if(e.length===0)return null;let t=document.createElement("div");t.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",t.appendChild(a)}n.appendChild(t);let r=Array.from(t.children).map(o=>o.offsetWidth);t.remove();let i=getComputedStyle(n),s=n.clientWidth-(Number.parseFloat(i.paddingLeft)||0)-(Number.parseFloat(i.paddingRight)||0)-(Number.parseFloat(i.columnGap)||0);return{rowWidths:r,gridWidth:s}}function Ft(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function Ut(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(ze).matches}function $t(n,e){return!n||n.length!==e.length?!1:n.every((t,r)=>t.text===e[r].text)}function lr(n,e){let t=e.dropdownTrigger??"auto",r=e.closeDropdownOnBlur??!0,o=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let a=r?n.isFocused:!0;return o&&a}if(t==="auto"){let a=r?n.isFocused:!0,l=n.text.replace(/\s+$/,"").length,c=n.caretOffset==null||n.caretOffset>=l;return(o||n.isLoading)&&a&&c}return t==="manual"?(o||n.isLoading)&&n.pillTapped:!1}function Pe(n){if(n.editingIdentified){let{parameter:t,anchor:r}=n.editingIdentified;return`identified:${t}@${r}`}return n.editingParam!=null&&n.editingAnchor!=null?`edit:${n.editingParam?.id}`:`pill:${n.actionableSuggestions[0]?.parameter??""}`}function dr(n){if(!n)return gt();let[e,t]=n.split("-").map(Number);return{year:e,month:t-1}}function Ui(n){let e=He(n);return e?qn(e):gt()}function cr(n,e){let t=kn(n.text,n.completedParams,n.identifiedParams),r=n.suggestions.filter(E=>E.parameter!=="placeholder"),i=r[0],s=n.suggestions.filter(E=>E.parameter==="placeholder").map(E=>E.text).join(" "),o=q(n.text,Math.min(n.filterBase,n.text.length),s),l=o===0&&De(n.text,n.completedParams.length,s)?"":fe(n.text,o,n.filterInProgress),c=i?.options??[],d=n.editingParam!=null&&n.editingAnchor!=null,u,g,p,f;if(d&&n.editingParam&&n.editingAnchor!=null){let E=n.editingParam.id,ne=n.completedParams.some(ai=>ai.id===E),ce=n.caretOffset??n.editingAnchor,bn=ne?"":n.text.slice(n.editingAnchor,ce);g=bn.trim(),p=n.editingParam.options,f=n.editingParam.suggestionParameter,u=j(n.editingParam.options,bn)}else g=l.trim(),p=c,f=i?.parameter,u=j(c,l);let x=n.optionSearch,y=x!=null&&f!=null&&x.parameter===f;y&&x.status==="done"&&x.query===g&&(u=p);let b=y&&x.status==="loading",m=e.showNonTappableOptions===!1;m&&(u=u.filter(E=>E.is_tappable));let h=n.editingIdentified,S=d?n.editingParam&&{type:n.editingParam.suggestionValueType}:i,I=h?h.format:X(S),w=d&&I==="date-range"?ve(n.editingParam):null,D=null,C=null;if(P(I)){let E=Pe({...n,actionableSuggestions:r}),ne=n.dateViewMonth;D=ne&&ne.key===E?{year:ne.year,month:ne.month}:h?dr(h.iso):w?dr(w.start):Ui(n.editingParam?.text),u=ht(D);let ce=n.pendingRangeStart;I==="date-range"&&ce&&ce.key===E&&(C=ce.iso)}let T=E=>m?E.is_tappable:!0,F;if(d){let E=n.editingParam?.options??[];F=n.editingParam!=null&&E.filter(T).length===0}else F=i!=null&&c.filter(T).length===0;let A=lr({inEditMode:d||h!=null,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading||b,pillTapped:n.pillTapped,activePillHasNoOptions:F,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),v=A&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable,H=n.skeletonOptions!==null&&n.skeletonRequested&&!n.isLoading&&!n.editingParam&&!n.inSelectionAnimation,k=n.isLoading&&!n.editingParam&&!n.inSelectionAnimation||b||H,$=k&&n.skeletonOptions!==null,Ce=$&&n.skeletonOptions?n.skeletonOptions:u,hn=$?n.skeletonSuggestion:null;return{segments:t,actionableSuggestions:r,filteredOptions:u,dropdownLoading:k,dropdownOptions:Ce,dropdownSuggestion:hn,skeletonExiting:H,activeFormatType:I,dateView:D,dateRangeStart:C,placeholderText:s,optionQuery:g,isSearchingOptions:b,isDropdownOpen:A,isActivePillSelected:v}}function Je(n){return n.mode==="fresh"?$i(n):qi(n)}function $i(n){let{text:e,completedParams:t,suggestions:r,filterBase:i,filterInProgress:s,phraseExactMatch:o}=n,l=r.filter(S=>S.parameter!=="placeholder")[0];if(!l?.options)return null;let c=r.filter(S=>S.parameter==="placeholder").map(S=>S.text).join(" "),d=q(e,i,c),u=he(l.options,e,d,s,o===!0);if(!u)return null;let g=u.text.toLowerCase(),p=e.toLowerCase().lastIndexOf(g),f=p>=0?p:Math.max(0,e.length-u.text.length),x=f+u.text.length,y=e.slice(f,x),m=x<e.length&&e[x]===" "?x+1:x,h={id:crypto.randomUUID(),placeholder:"",parameter:B(u,l.parameter),text:y,value:u.value,kind:u.kind,suggestionParameter:l.parameter,suggestionValueType:l.type,suggestionPlaceholder:l.text,options:l.options??[],metadata:u.metadata,icon:u.icon,icon_svg:u.icon_svg,image_url:u.image_url};return{patch:{text:e,completedParams:[...t,h],suggestions:r.filter(S=>S!==l),filterBase:m,newParamId:h.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m,option:u}}function qi(n){let{text:e,completedParams:t,editingParam:r,editingAnchor:i,editingTail:s}=n;if(t.some(h=>h.id===r.id))return null;let o=e.slice(i,s),a=ke(r.options,o);if(!a)return null;let l=a.text.toLowerCase(),c=o.toLowerCase().lastIndexOf(l),d=i+Math.max(0,c),u=d+a.text.length,g=e.slice(d,u),p=u<e.length&&e[u]===" "?u+1:u,f=e.length,x={id:crypto.randomUUID(),placeholder:"",parameter:B(a,r.suggestionParameter),text:g,value:a.value,kind:a.kind,suggestionParameter:r.suggestionParameter,suggestionValueType:r.suggestionValueType,suggestionPlaceholder:r.suggestionPlaceholder,options:r.options,metadata:a.metadata,icon:a.icon,icon_svg:a.icon_svg,image_url:a.image_url},y=t.length,b=0;for(let h=0;h<t.length;h++){let S=W(e,t[h].text,b);if(S!==-1){if(S>=p){y=h;break}b=S+t[h].text.length}}let m=[...t];return m.splice(y,0,x),{patch:{text:e,completedParams:m,newParamId:x.id,filterBase:f,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:f,activeDropdownIndex:-1},caretPos:f,option:a}}var Gi=6e4;function Vi(n){return typeof TextEncoder>"u"?n.length*3:new TextEncoder().encode(n).length}function Ki(n){return(n??re).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Yi(n){return ue(n)?`Bearer ${await Ae(n).getToken()}`:Re(n)}async function ur(n){try{let e=Ki(n.apiConfig?.endpoint),t=Le(n.apiConfig),r=await Yi(n.apiConfig);r&&(t.Authorization=r);let i=JSON.stringify({source:n.source,session_id:n.sessionId,...n.visitorId&&{visitor_id:n.visitorId},...n.requestId&&{request_id:n.requestId},type:n.type,...n.language&&{language:n.language},at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:i,...n.keepalive&&Vi(i)<=Gi&&{keepalive:!0}})}catch{}}function ee(n,e){let t=n.findIndex(r=>r.text===e);return t>=0?t+1:null}function pr(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let r=n.filterBase,i=n.text.slice(0,r),s=i.length===0&&n.text.length===0,o=i.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(i=`${n.placeholderText} `);let a=Math.min(Rn(n.text,n.completedParams),i.length),l=Tn(i.slice(a),e.text);l>0&&(i=i.slice(0,i.length-l));let c=i.length>0&&i[i.length-1]!==" ",d=`${i}${c?" ":""}${e.text} `,u=(s||o)&&d.length>0?d[0].toUpperCase()+d.slice(1):d,g=u.toLowerCase().lastIndexOf(e.text.toLowerCase()),p=g>=0?u.slice(g,g+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",parameter:B(e,t.parameter),text:p,value:e.value,kind:e.kind,suggestionParameter:t.parameter,suggestionValueType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},x=n.actionableSuggestions.length-1;return{patch:{text:u,filterBase:u.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:u.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text),key:t.parameter,position:ee(t.options??[],e.text)},consumedSuggestion:t,remainingActionable:x}}function Ze(n){let e=P(n.activeFormatType)||n.filteredOptions.length===0?null:n.filteredOptions,t=n.editingParam,r=t?{parameter:t.suggestionParameter,text:t.suggestionPlaceholder,required:!0,options:t.options}:n.actionableSuggestions[0]??null;return{skeletonOptions:e,skeletonSuggestion:e?r:null,skeletonRequested:!1}}function et(n,e,t){let r=n.slice(0,e),i=n.slice(t),s=(r===""||r.endsWith(" "))&&i.startsWith(" ");return s&&(i=i.slice(1)),{text:r+i,removed:t-e+(s?1:0)}}var tt=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let r=t.completedParams.find(o=>o.id===e);if(!r)return;let i=0,s=-1;for(let o of t.completedParams){let a=W(t.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 t=this.deps.store.get(),r=t.editingParam,i=t.editingAnchor,s=t.editingTail;if(!r||i==null||s==null||!t.completedParams.some(l=>l.id===r.id))return!1;let{text:o}=e===""?et(t.text,i,s):{text:t.text.slice(0,i)+e+t.text.slice(s)},a=i+e.length;return this.deps.store.set(l=>({text:o,completedParams:l.completedParams.filter(c=>c.id!==r.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),this.promoteIfExact(),!0}caretAfterInput(e){let t=this.deps.store.get(),r={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(r.editingParam=null,r.editingAnchor=null,r.editingTail=null,r.activeDropdownIndex=-1):t.editingTail!=null&&(r.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(r),this.promoteIfExact()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.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 t=this.deps.store.get(),r=t.editingParam,i=t.editingAnchor,s=t.editingTail;if(!r||i==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:r.options.filter(b=>b.text!==e.text).map(b=>b.text),key:r.suggestionParameter,position:ee(r.options,e.text),chip_origin:"tap"});let o=t.text.slice(0,i),a=t.text.slice(s),l=i===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,d=a.length===0||a[0]!==" "?`${l} `:l,u=o+d+a,g=u.length,p={id:crypto.randomUUID(),placeholder:"",parameter:B(e,r.suggestionParameter),text:l,value:e.value,kind:e.kind,suggestionParameter:r.suggestionParameter,suggestionValueType:r.suggestionValueType,suggestionPlaceholder:r.suggestionPlaceholder,options:r.options,metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url},f=t.completedParams.findIndex(b=>b.id===r.id),x=t.completedParams.filter(b=>b.id!==r.id),y=f>=0?Math.min(f,x.length):x.length;x.splice(y,0,p),this.deps.store.set({text:u,completedParams:x,newParamId:p.id,filterBase:g,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:g,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0,...Ze(t)}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(g),this.deps.fetchNow()}promoteIfExact(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Je({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var Qi=33,Xi=70,ji=120,zi=50,ae="data-aia-placeholder-leaving",le=new WeakMap;function nt(n){n.timer!==null&&(clearTimeout(n.timer),n.timer=null)}function Ji(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function gr(n,e,t){e.shown=t,n.dataset.placeholder=e.target.slice(0,t)}function fr(n,e){if(e.timer=null,!n.isConnected||e.shown>=e.target.length||(gr(n,e,e.shown+1),e.shown>=e.target.length))return;let t=e.target[e.shown-1],r=t===" "||t==="-"?70:0;e.timer=setTimeout(()=>fr(n,e),33+r)}function mr(n,e){gr(n,e,0),e.timer=setTimeout(()=>fr(n,e),33)}function hr(n,e){let t=le.get(n);if(e===""){t&&(nt(t),le.delete(n)),n.removeAttribute(ae),delete n.dataset.placeholder;return}if(t?.target===e)return;if(Ji(n)){t&&nt(t),n.removeAttribute(ae),le.set(n,{target:e,shown:e.length,timer:null}),n.dataset.placeholder=e;return}let r={target:e,shown:0,timer:null},i=t&&t.shown>0?t:null;if(t&&nt(t),le.set(n,r),i){n.setAttribute(ae,""),r.timer=setTimeout(()=>{r.timer=null,n.removeAttribute(ae),n.isConnected&&mr(n,r)},170);return}n.removeAttribute(ae),mr(n,r)}function br(n){let e=le.get(n);e&&(nt(e),le.delete(n))}var Sr="https://ai-autocomplete.com";function qt(n=Sr){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}var Zi={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"},eo={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"};function O(n){return n?.split("-")[0]?.toLowerCase()==="es"?eo:Zi}function Gt(n,e,t=O()){return n?{key:"enter",hint:t.proceed}:e?{key:"tab",hint:t.select}:{key:"\u2192",hint:t.skipHint}}function Vt(n){let e=o=>{o.ctrlKey||xr(o.target,n,o.deltaX,o.deltaY)||o.preventDefault()},t=0,r=0,i=o=>{let a=o.touches[0];a&&(t=a.clientX,r=a.clientY)},s=o=>{if(o.touches.length!==1)return;let a=o.touches[0],l=t-a.clientX,c=r-a.clientY;t=a.clientX,r=a.clientY,o.cancelable&&!xr(o.target,n,l,c)&&o.preventDefault()};return n.addEventListener("wheel",e,{passive:!1}),n.addEventListener("touchstart",i,{passive:!0}),n.addEventListener("touchmove",s,{passive:!1}),()=>{n.removeEventListener("wheel",e),n.removeEventListener("touchstart",i),n.removeEventListener("touchmove",s)}}function xr(n,e,t,r){let i=n instanceof Element?n:null;for(;i;){if(r!==0&&to(i,r)||t!==0&&no(i,t))return!0;if(i===e)break;i=i.parentElement}return!1}var yr=/^(auto|scroll|overlay)$/;function to(n,e){return n.scrollHeight<=n.clientHeight||!yr.test(getComputedStyle(n).overflowY)?!1:e>0?n.scrollTop+n.clientHeight<n.scrollHeight-1:n.scrollTop>0}function no(n,e){if(n.scrollWidth<=n.clientWidth)return!1;let t=getComputedStyle(n);if(!yr.test(t.overflowX))return!1;let r=Math.abs(n.scrollLeft),i=n.scrollWidth-n.clientWidth;return(t.direction==="rtl"?e<0:e>0)?r<i-1:r>0}var vr=new WeakMap,Pr=new WeakSet;function V(n,e,t){if(vr.set(n,t),Pr.has(n))return;Pr.add(n);let r=()=>vr.get(n),i=s=>{if(!(s instanceof Element))return null;let o=s.closest(e.itemSelector);return o&&n.contains(o)?o:null};e.onClick&&n.addEventListener("click",s=>{let o=i(s.target);o&&e.onClick?.(o,r(),s)}),e.onEnter&&n.addEventListener("mouseenter",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onEnter?.(o,r())},!0),e.onLeave&&n.addEventListener("mouseleave",s=>{let o=s.target;o instanceof HTMLElement&&o.matches(e.itemSelector)&&e.onLeave?.(o,r())},!0),e.preventMousedown&&n.addEventListener("mousedown",s=>s.preventDefault())}function K(n){return Number.parseInt(n.dataset.aiaIndex??"-1",10)}function Y(n){n.offsetWidth}var ro={selectedIso:null,selectedRange:null,rangeStart:null};function Ee(n){if(!P(n.activeFormatType))return ro;let e=n.editingIdentified;if(e){let{iso:r,isoEnd:i}=e;return{selectedIso:i?null:r,selectedRange:r&&i?ye(r,i):null,rangeStart:n.dateRangeStart}}let t=ve(n.editingParam);return{selectedIso:t?null:bt(n.editingParam?.text),selectedRange:t,rangeStart:n.dateRangeStart}}function Kt(n){return n.pendingStart?ye(n.pendingStart,n.highlightedIso??n.pendingStart):n.selected}function Yt(n,e){if(n==null)return{selected:!1,inRange:!1};let{selectedIso:t,range:r}=e,i=n===t||r!=null&&(n===r.start||n===r.end),s=r!=null&&n>r.start&&n<r.end;return{selected:i,inRange:s}}var Er="data-aia-key";function Q(n,e,t){let r=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Er);a!=null&&r.set(a,o)}let i=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],l=t.keyOf(a,o);i.add(l);let c=r.get(l);c||(c=t.create(a,o),c.setAttribute(Er,l)),t.update?.(c,a,o),n.children[o]!==c&&n.insertBefore(c,n.children[o]??null),s.push(c)}for(let[o,a]of r)i.has(o)||a.remove();return s}function wr(n,e){if(!e.interactive)return null;let t=e.options[K(n)];return t?.is_tappable?t:null}var io={itemSelector:"[data-aia-date-cell], [data-aia-date-prev], [data-aia-date-next]",onClick:(n,e)=>{if(n.hasAttribute("data-aia-date-prev")){e.callbacks.onPreviousMonth();return}if(n.hasAttribute("data-aia-date-next")){e.callbacks.onNextMonth();return}let t=wr(n,e);t&&(n.classList.add("magicx-aia-date-cell--pressed"),e.callbacks.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-date-cell--pressed"),170))},onEnter:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&wr(n,e)&&e.callbacks.onHighlight(K(n))},onLeave:(n,e)=>{n.hasAttribute("data-aia-date-cell")&&e.callbacks.onHighlight(-1,K(n))}};function Ir(n,e,t,r,i,s,o,a=!0){let l=n.querySelector(".magicx-aia-datepicker");if(!i||e.length===0){l?.remove();return}if(!l){l=ao(),n.appendChild(l),Y(l);for(let u of l.querySelectorAll(".magicx-aia-datepicker-nav"))u.disabled=!1}V(l,io,{options:e,callbacks:o,interactive:a});let c=l.querySelector(".magicx-aia-datepicker-month");c&&(c.textContent=mt(i));let d=l.querySelector(".magicx-aia-datepicker-grid");d&&oo(d,e,t,r,s)}function oo(n,e,t,r,i){let s=_(new Date),o=Kt({pendingStart:i.rangeStart,highlightedIso:U(e[t]),selected:i.selectedRange});Q(n,e,{keyOf:(a,l)=>U(a)??`pad-${l}`,create:a=>so(a),update:(a,l,c)=>{let d=U(l),u=Yt(d,{selectedIso:i.selectedIso,range:o}),g=c===t&&l.is_tappable;a.id=`${r}-option-${c}`,a.dataset.aiaIndex=String(c),a.setAttribute("aria-selected",String(g)),a.classList.toggle("magicx-aia-date-cell--past",d!=null&&d<s),a.classList.toggle("magicx-aia-date-cell--highlighted",g),a.classList.toggle("magicx-aia-date-cell--today",d!=null&&d===s),a.classList.toggle("magicx-aia-date-cell--selected",u.selected),a.classList.toggle("magicx-aia-date-cell--in-range",u.inRange)}})}function so(n){let e=document.createElement("div");e.setAttribute("role","option"),e.setAttribute("data-aia-option",""),e.setAttribute("data-aia-date-cell","");let t=St(n);if(t==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",n.text);let r=document.createElement("span");return r.className="magicx-aia-date-cell-number",r.textContent=String(t),e.appendChild(r),e}function ao(){let n=document.createElement("div");n.className="magicx-aia-datepicker",n.setAttribute("data-aia-datepicker","");let e=document.createElement("div");e.className="magicx-aia-datepicker-header";let t=document.createElement("span");t.className="magicx-aia-datepicker-month",t.setAttribute("data-aia-date-month",""),t.setAttribute("aria-live","polite"),e.append(Tr("prev","Previous month","\u2039"),t,Tr("next","Next month","\u203A"));let r=document.createElement("div");r.className="magicx-aia-datepicker-weekdays",r.setAttribute("aria-hidden","true");for(let s of Fe){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",""),n.append(e,r,i),n}function Tr(n,e,t){let r=document.createElement("button");return r.type="button",r.tabIndex=-1,r.className="magicx-aia-datepicker-nav",r.setAttribute(`data-aia-date-${n}`,""),r.setAttribute("aria-label",e),r.textContent=t,r.disabled=!0,r}var lo={itemSelector:"[data-aia-pill]",onClick:(n,e)=>{if(e.loading||n.disabled)return;let t=Number.parseInt(n.dataset.aiaPillIndex??"-1",10);t>=0&&e.onSelectPill(t)},preventMousedown:!0},Cr=[125,69];function Or(n,e){return e?1:n===0?.7:n===1?.4:.2}function rt(n,e,t,r,i=!1,s=!1,o=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),V(a,lo,{onSelectPill:r,loading:s}),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let l=0;l<Cr.length;l++){let c=Cr[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=`${c}px`,d.style.opacity=String(Or(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();Q(a,e,{keyOf:l=>`${l.parameter}-${l.text}`,create:l=>{let c=document.createElement("button");return c.type="button",c.tabIndex=-1,c.setAttribute("data-aia-pill",""),c.setAttribute("contenteditable","false"),c.textContent=l.text,c.disabled=!0,c},update:(l,c,d)=>{let u=l,g=o&&d===t&&!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(Or(d,g)),u.dataset.aiaPillIndex=String(d),s?u.setAttribute("data-aia-loading",""):u.removeAttribute("data-aia-loading")}}),Y(a);for(let l of a.querySelectorAll("[data-aia-pill]"))l.disabled=s}function Qt(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var co=32;function Ar(n,e){if(e.ctrlKey)return null;let t=e.deltaY||0,r=e.deltaX||0;if(!t||Math.abs(r)>=Math.abs(t))return null;let i=n.scrollWidth-n.clientWidth;if(i<=1)return null;let s=n.scrollLeft,o=t;return e.deltaMode===1?o*=32:e.deltaMode===2&&(o*=n.clientWidth),Math.max(0,Math.min(i,s+o))}function Xt(n){let e=t=>{let r=Ar(n,t);r!==null&&(t.preventDefault(),n.scrollLeft=r)};return n.addEventListener("wheel",e,{passive:!1}),()=>n.removeEventListener("wheel",e)}var Lr=Intl.Segmenter,Rr=Lr?new Lr(void 0,{granularity:"grapheme"}):null;function jt(n){let e=n.trim().normalize("NFC").toUpperCase();if(Rr)for(let t of Rr.segment(e))return t.segment;return Array.from(e)[0]??"?"}var zt=120,uo=360;function po(n){let e=n.pathname;return n.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 Mr(n,e){let t;try{t=new URL(n,typeof document>"u"?void 0:document.baseURI)}catch{return n}let r=po(t);return r?(t.searchParams.set("width",String(e)),r.format&&t.searchParams.set("format",r.format),n.startsWith("/")&&!n.startsWith("//")?`${t.pathname}${t.search}${t.hash}`:t.href):n}function Jt(n,e){let t=Mr(n,e);return t===n?[n]:[t,n]}function it(n){let e=n?.trim();return e?Jt(e,360):[]}function mo(n){return it(n)[0]}var Zt=new WeakMap,kr=new WeakMap;function Dr(n,e,t,r,i,s="row",o="image",a=O()){let l=n.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",`${t}-products-label`);let u=document.createElement("div");u.className="magicx-aia-products-label",u.id=`${t}-products-label`,u.setAttribute("data-aia-products-label",""),u.textContent=a.products;let g=document.createElement("div");g.className="magicx-aia-products-row",g.setAttribute("data-aia-products-row",""),Xt(g),l.append(u,g),n.appendChild(l)}l.setAttribute("data-aia-products-layout",s);let c=l.querySelector(".magicx-aia-products-label");c&&c.textContent!==a.products&&(c.textContent=a.products);let d=l.querySelector(".magicx-aia-products-row");if(d){Q(d,e,{keyOf:u=>go(u),create:u=>fo(u,r,i,o,a),update:(u,g,p)=>{u.id=`${t}-product-${p}`,u.dataset.aiaIndex=String(p),kr.get(u)?.(o);let f=u.querySelector(".magicx-aia-product-badge");f&&f.textContent!==a.soldOut&&(f.textContent=a.soldOut)}}),Y(d);for(let u of d.querySelectorAll("[data-aia-product]")){let g=Zt.get(u);g&&(Zt.delete(u),g())}}}function en(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let r of t)r.tabIndex=e?0:-1}function go(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor,n.available===!1?"sold-out":""].map(e=>e??"").join("\0")}function fo(n,e,t,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=it(n.imageUrl),l=a[0],c=!!l,d=()=>{o.replaceChildren(),o.toggleAttribute("data-aia-product-placeholder",r==="image"),o.toggleAttribute("data-aia-product-initial",r==="initial"),r==="initial"&&(o.textContent=jt(n.title))};if(kr.set(s,p=>{p!==r&&(r=p,c||d())}),l){let p=document.createElement("img"),f=0;p.onerror=()=>{let x=a[++f];if(x){p.src=x;return}c=!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 u=document.createElement("span");if(u.className="magicx-aia-product-body",n.vendor){let p=document.createElement("span");p.className="magicx-aia-product-vendor",p.textContent=n.vendor,u.appendChild(p)}let g=document.createElement("span");if(g.className="magicx-aia-product-title",g.textContent=n.title,u.appendChild(g),n.price){let p=document.createElement("span");p.className="magicx-aia-product-price",p.textContent=n.price,u.appendChild(p)}if(n.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),Zt.set(s,()=>{n.url&&(s.href=n.url),s.addEventListener("click",p=>{p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0||(p.preventDefault(),e(n))})}),s.addEventListener("keydown",p=>{p.key!=="Enter"&&p.key!==" "||(p.preventDefault(),e(n))}),s.addEventListener("focus",()=>t(!0)),s.addEventListener("blur",p=>{p.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),s}var ho=80,bo=150,So=280,xo=16,tn="--aia-option-enter-delay";function nn(n,e,t,r="below"){let i=Math.max(1,Math.floor(e)),s=Math.floor(Math.max(0,n)/i);if(r!=="above")return s*80;let o=Math.max(1,Math.ceil(Math.max(0,t)/i));return Math.max(0,o-1-s)*80}function rn(n,e){let t=Math.max(1,Math.floor(e));return(Math.max(1,Math.ceil(Math.max(0,n)/t))-1)*80+280}function te(n){return ot(n)[0]??null}function ot(n){let e=yo(n);return e?Jt(e,120):[]}function yo(n){if(!n)return null;let e=n.trim();if(e==="")return null;let t;try{t=new URL(e,typeof document>"u"?void 0:document.baseURI)}catch{return null}return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.href}function we(n){return n===void 0||!Number.isInteger(n)||n<0?null:n.toLocaleString()}var _r={one:"item",other:"items"};function vo(n,e=_r){let t=we(n);if(t===null)return null;let r=typeof e=="string"?e:n===1?e.one:e.other;return r===""?t:`${t} ${r}`}function Po(n){return te(n.image_url)!==null}var Nr="http://www.w3.org/2000/svg",Eo=new Set(["svg","g","path","circle","ellipse","line","polyline","polygon","rect"]);function wo(n,e){let t=n.toLowerCase();return t.startsWith("on")||t.includes("href")||t==="style"||t==="xml:base"||t==="id"||t==="name"||/^\s*javascript:/i.test(e)||/url\s*\(\s*['"]?\s*[^#'"\s)]/i.test(e)}var To=["fill","stroke","stroke-width","stroke-linecap","stroke-linejoin","fill-rule","clip-rule","opacity","fill-opacity","stroke-opacity"],Io=/^[a-zA-Z0-9#.,%\s()-]+$/;function Co(n){let e=[];for(let t of To){let r=n.getAttribute(t);r===null||!Io.test(r)||/url\s*\(/i.test(r)||e.push(`${t}: ${r.trim()}`)}e.length>0&&n.setAttribute("style",e.join("; "))}function Fr(n){for(let e of Array.from(n.attributes))wo(e.name,e.value)&&n.removeAttribute(e.name);Co(n);for(let e of Array.from(n.childNodes))if(e.nodeType===Node.ELEMENT_NODE){let t=e;!Eo.has(t.localName)||t.namespaceURI!==Nr?t.remove():Fr(t)}else e.remove()}function Te(n){if(typeof DOMParser>"u"||typeof XMLSerializer>"u")return null;let e=new DOMParser().parseFromString(n,"image/svg+xml"),t=e.documentElement;return!t||t.localName!=="svg"||t.namespaceURI!==Nr||e.getElementsByTagName("parsererror").length>0?null:(Fr(t),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false"),new XMLSerializer().serializeToString(t))}function on(n){return n.text}var Hr=new WeakMap;function Oo(n,e,t){let r=e.length,i=Ut(),s=Hr.get(n),o=t&&s&&$t(s.options,e)?s.plan:null,a=!o&&!t&&Ht(r,i)?Bt(n):null,l=o??Wt(r,i,a?.rowWidths??null,a?.gridWidth??null);return t||Hr.set(n,{options:e,plan:l}),n.style.gridTemplateColumns=l.template,n.style.setProperty("--aia-grid-max-height",l.maxHeight),n.querySelectorAll("[data-aia-option]").forEach((c,d)=>{c.classList.toggle("magicx-aia-option--scroll-hint",!t&&l.scrollHintIndices.includes(d))}),l.cols}function Wr(n,e){if(e.loading||!e.interactive)return null;let t=e.options[K(n)];return t?.is_tappable?t:null}var Ao={itemSelector:"[data-aia-option]",onClick:(n,e)=>{let t=Wr(n,e);t&&(n.classList.add("magicx-aia-option--pressed"),e.onSelect(t),setTimeout(()=>n.classList.remove("magicx-aia-option--pressed"),170))},onEnter:(n,e)=>{Wr(n,e)&&e.onHighlight(K(n))},onLeave:(n,e)=>e.onHighlight(-1,K(n))};function Br(n,e,t,r,i,s,o,a="",l="below",c=!0,d=!0,u=!0,g=!0){let p=n.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"),n.appendChild(p)),V(p,Ao,{options:e,onSelect:r,onHighlight:i,loading:o,interactive:g});let f=p.dataset.aiaGroup!==a;p.dataset.aiaGroup=a,Lo(p,e,t,s,o,{showIcons:c,showImages:d,showCounts:u});let x=Oo(p,e,o);Ro(p,e.length,x,o,l),f&&(p.scrollTop=0)}function Lo(n,e,t,r,i,s){let o=i?"1":"0",a=n.dataset.aiaGroup??"",{showIcons:l,showImages:c,showCounts:d}=s,u=l?f=>f.icon??f.icon_svg??"":()=>"",g=c?f=>te(f.image_url)??"":()=>"",p=d?f=>we(f.item_count)??"":()=>"";Q(n,e,{keyOf:f=>`${f.text}\0${u(f)}\0${g(f)}\0${p(f)}\0${o}\0${a}`,create:(f,x)=>{let y=Mo(f,i,s);return i||(y.dataset.aiaEntering=""),y},update:(f,x,y)=>{let b=y===t&&!i;f.id=`${r}-option-${y}`,f.dataset.aiaIndex=String(y),f.setAttribute("aria-selected",String(b)),f.classList.toggle("magicx-aia-option--highlighted",b)}})}function Ro(n,e,t,r,i){for(let s of n.querySelectorAll("[data-aia-entering]")){if(!r){let o=Number.parseInt(s.dataset.aiaIndex??"-1",10);o>=0&&s.style.setProperty(tn,`${nn(o,t,e,i)}ms`)}delete s.dataset.aiaEntering}}function Mo(n,e,{showIcons:t,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||!n.is_tappable?-1:0;let o=["magicx-aia-option"];n.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?ot(n.image_url):[],c=l[0];if(c){let p=document.createElement("span");p.className="magicx-aia-option-image",p.setAttribute("aria-hidden","true");let f=document.createElement("img");f.setAttribute("alt",""),f.setAttribute("loading","lazy"),f.setAttribute("decoding","async"),f.setAttribute("referrerpolicy","no-referrer"),f.setAttribute("draggable","false");let x=0;f.onerror=()=>{let y=l[++x];y?f.src=y:f.hidden=!0},f.src=c,p.appendChild(f),a.appendChild(p),s.dataset.aiaImage=""}let d=!c&&t&&n.icon_svg?Te(n.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),n.icon&&(s.dataset.aiaIcon=n.icon)}let u=document.createElement("span");if(u.className="magicx-aia-option-text",u.textContent=on(n),a.appendChild(u),n.tag){let p=document.createElement("span");p.className="magicx-aia-option-tag",p.textContent=n.tag,a.appendChild(p)}let g=i?we(n.item_count):null;if(g!==null){let p=document.createElement("span");p.className="magicx-aia-option-count",p.textContent=g,a.appendChild(p),s.dataset.aiaItemCount=String(n.item_count)}return s.appendChild(a),s}var Ur="magicx-aia-scroll-arrow",$r="data-aia-scroll-arrow",de="data-aia-visible",qr=1e3,Gr=160,Vr="--aia-scroll-arrow-bottom",ko="Scroll down for more options",Do="[data-aia-products-label]",_o=4,No=8,Fo=240;function Ho(n,e,t,r){let i=n.scrollTop,s=t?.requestAnimationFrame,o=n.ownerDocument?.visibilityState==="hidden";if(!s||o||sn(n)){n.scrollTop=i+e,r();return}let a=t.performance?.now?.()??Date.now(),l=()=>t.performance?.now?.()??Date.now(),c=()=>{let d=Math.min(1,(l()-a)/Fo),u=1-(1-d)*(1-d);n.scrollTop=i+e*u,d<1?s.call(t,c):r()};s.call(t,c)}function Wo(n=document){let e="http://www.w3.org/2000/svg",t=n.createElementNS(e,"svg");t.setAttribute("viewBox","0 0 16 16"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","none"),t.setAttribute("stroke","currentColor"),t.setAttribute("stroke-width","1.75"),t.setAttribute("stroke-linecap","round"),t.setAttribute("stroke-linejoin","round"),t.setAttribute("aria-hidden","true"),t.setAttribute("focusable","false");let r=n.createElementNS(e,"path");return r.setAttribute("d","M4 6.5 8 10.5l4-4"),t.appendChild(r),t}function Kr(n=document,e=O()){let t=n.createElement("button");return t.type="button",t.tabIndex=-1,t.className=Ur,t.setAttribute($r,""),t.setAttribute("aria-label",e.scrollArrow),t.setAttribute("aria-hidden","true"),t.disabled=!0,t.appendChild(Wo(n)),t}function Bo(n){let e=n.style.gridTemplateColumns.trim();return e?Math.max(1,e.split(/\s+/).length):1}function sn(n){return n.closest('[data-animations="off"]')?!0:!!n.ownerDocument?.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)").matches}function an({dropdown:n,grid:e,button:t}){let r=e.ownerDocument?.defaultView??(typeof window<"u"?window:null),i=!1;t.disabled=!0;let s=null,o=null,a=null,l=null,c=m=>{if(m){if(t.hasAttribute(de))return;if(t.setAttribute(de,""),t.setAttribute("aria-hidden","false"),l!==null&&clearTimeout(l),sn(e)){t.disabled=!1;return}l=setTimeout(()=>{l=null,!i&&t.hasAttribute(de)&&(t.disabled=!1)},qr)}else t.removeAttribute(de),t.setAttribute("aria-hidden","true"),l!==null&&clearTimeout(l),l=null,t.disabled=!0},d=m=>{let h=0,S=m;for(;S&&S!==n;)h+=S.offsetTop,S=S.offsetParent instanceof HTMLElement?S.offsetParent:null;return h},u=()=>{let m=n.querySelector(Do),h;if(m){let S=d(m)+m.offsetHeight/2;h=n.clientHeight-S-t.offsetHeight/2}else{let S=d(e),I=r&&Number.parseFloat(r.getComputedStyle(e).paddingBottom)||0;h=n.clientHeight-(S+e.offsetHeight)+(I>0?0:No)}t.style.setProperty(Vr,`${Math.max(0,Math.round(h))}px`)},g=()=>{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;c(!m&&h>_o)},p=()=>{if(i)return;u();let m=e.getAttribute("data-aia-group")??"";if(m!==s){s=m,c(!1),o!==null&&clearTimeout(o);let h=e.querySelectorAll("[data-aia-option]").length,S=sn(e)?0:rn(h,Bo(e));o=setTimeout(()=>{o=null,g()},S);return}g()},f=()=>{i||o!==null||(c(!1),a!==null&&clearTimeout(a),a=setTimeout(()=>{a=null,g()},Gr))};e.addEventListener("scroll",f,{passive:!0});let x=m=>m.preventDefault(),y=()=>{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);Ho(e,h,r,f)};t.addEventListener("mousedown",x),t.addEventListener("click",y);let b=null;return r&&typeof r.ResizeObserver=="function"&&(b=new r.ResizeObserver(()=>{u(),g()}),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,t.disabled=!0,e.removeEventListener("scroll",f),t.removeEventListener("mousedown",x),t.removeEventListener("click",y),b?.disconnect(),t.removeAttribute(de),t.setAttribute("aria-hidden","true"))}}}var Uo=[159,119,164];function at(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),Vt(e),e}var st=new WeakMap;function $o(n,e,t){let r=st.get(n);if(r||(r={button:Kr(n.ownerDocument,t),grid:null,controller:null},n.appendChild(r.button),st.set(n,r)),r.button.getAttribute("aria-label")!==t.scrollArrow&&r.button.setAttribute("aria-label",t.scrollArrow),r.grid!==e&&(r.controller?.destroy(),r.controller=null,r.grid=e,e)){r.controller=an({dropdown:n,grid:e,button:r.button});return}r.controller?.update()}function ln(n){let e=st.get(n);e&&(e.controller?.destroy(),st.delete(n))}function lt(n,e){let t=e.strings??O(),{filteredOptions:r,activeIndex:i,isOpen:s,isLoading:o,pills:a,showPills:l,isActivePillSelected:c,onSelect:d,onHighlight:u,onPillClick:g,onSkip:p}=e,f=a.length>0,x=l&&f,y=r.length>0,b=e.products.length>0,m=s&&(y||x||o||b);if(m?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!m){en(n,!1);return}b?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products"),n.toggleAttribute("data-aia-skeleton-exiting",!!e.skeletonExiting);let h=n.querySelector(".aia-stack");h||(h=document.createElement("div"),h.className="aia-stack",h.style.setProperty("--aia-stack-space","8px"),n.appendChild(h));let S=e.showSkipButton&&f&&!e.isInputEmpty,I=x||o&&l||S,w=h.querySelector(".magicx-aia-pill-bar");if(I){w||(w=document.createElement("div"),w.className="magicx-aia-pill-bar aia-cluster",w.setAttribute("data-nowrap",""),w.setAttribute("data-aia-pillbar",""),h.insertBefore(w,h.firstChild));let k=w.querySelector(".magicx-aia-pill-scroll");k||(k=document.createElement("span"),k.className="magicx-aia-pill-scroll",k.setAttribute("data-aia-pill-scroll",""),w.insertBefore(k,w.firstChild)),rt(k,l?a:[],0,g,!0,o&&l,c),Vo(w,S,o||e.skipDisabled,a[0],p,t)}else w&&w.remove();let D=e.suggestions[0],C=D?`${D.parameter} ${D.text}`:"",T=P(e.formatType),F=T&&!o;Br(h,T?[]:r,i,d,u,e.listboxId,o,C,e.optionsPosition??"below",e.showOptionIcons??!0,e.showOptionImages??!0,e.showOptionCounts??!0,!e.skipDisabled),$o(n,h.querySelector(".aia-grid"),t),Ir(h,F?r:[],i,e.listboxId,F?e.dateView:null,{selectedIso:e.selectedDateIso,selectedRange:e.selectedDateRange,rangeStart:e.dateRangeStart},{onSelect:d,onHighlight:u,onPreviousMonth:e.onPreviousMonth,onNextMonth:e.onNextMonth},!e.skipDisabled);let A=h.querySelector(".magicx-aia-skeleton-bars");if(o&&(!y||T)){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let k of Uo){let $=document.createElement("span");$.className="magicx-aia-skeleton-bar",$.style.width=`${k}px`,A.appendChild($)}h.appendChild(A)}}else A&&A.remove();Dr(h,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange,e.productsLayout??"row",e.productImageFallback??"image",t),en(n,!0);let v=h.querySelector(".magicx-aia-footer")??Yo(t),H=i>=0&&!!r[i]?.is_tappable;Ko(v,Gt(H,e.isInputEmpty,t)),v.isConnected||h.appendChild(v),qo(h,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-datepicker",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function qo(n,e){let t=e.map(r=>n.querySelector(`:scope > ${r}`)).filter(r=>r!==null);for(let r=0;r<t.length;r++)n.children[r]!==t[r]&&n.insertBefore(t[r],n.children[r]??null)}var Go={itemSelector:".magicx-aia-skip",onClick:(n,e)=>{e.loading||e.onSkip()}};function Vo(n,e,t,r,i,s){V(n,Go,{onSkip:i,loading:t});let o=n.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,n.appendChild(o),Y(o)),o.textContent!==s.skip&&(o.textContent=s.skip),o.setAttribute("aria-label",r?`${s.skipLabel} ${r.text}`:s.skipLabel),o.disabled=t}function Ko(n,{key:e,hint:t}){let r=n.querySelector(".magicx-aia-footer-key"),i=n.querySelector(".magicx-aia-footer-hint");!r||!i||(r.textContent!==e&&(r.textContent=e),i.textContent!==t&&(i.textContent=t))}function Yo(n){let e=document.createElement("footer");e.className="magicx-aia-footer",e.setAttribute("data-aia-footer","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-row",t.setAttribute("data-align","center"),t.setAttribute("data-justify","between"),t.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=n.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=qt(),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),t.append(r,o),e.append(t),e}function Yr(n,e){let t=at(e.listboxId);return n.appendChild(t),{dropdown:t}}function dn(n,e,t){let r=Ee(e);lt(n.dropdown,{strings:t.strings,suggestions:e.editingIdentified?[{parameter:e.editingIdentified.parameter,text:z(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:t.listboxId,pills:e.actionableSuggestions,showPills:!0,showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:r.selectedIso,selectedDateRange:r.selectedRange,dateRangeStart:r.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:t.selectOption,onHighlight:(i,s)=>{s!==void 0&&t.store.get().activeDropdownIndex!==s||t.store.set({activeDropdownIndex:i})},onPillClick:t.setActivePill,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Qo=6,Xo=.3;function Qr(n){return n<=0?"0px":`${(-Math.min(Xo,2*Qo/n)).toFixed(3)}px`}function cn(n){let{input:e,segments:t,newParamId:r,editingParamId:i,placeholderText:s,isFocused:o}=n,a=n.showChipIcons??!0,l=n.showChipImages??!0,c=t.length===0;e.dataset.aiaEmpty=c?"true":"false",hr(e,c?s:"");let d=t.map(m=>m.type==="completed"?`${m.type}:${m.value}${a?m.param.icon??m.param.icon_svg??"":""}${l?te(m.param.image_url)??"":""}`:`${m.type}:${m.value}`).join("\0"),u=e.dataset.segKey??"",g=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===u&&(r??"")===g&&(i??"")===p)return;if(d===u){e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";for(let m of e.querySelectorAll("strong[data-param-id]")){let h=m.dataset.paramId,S=m.dataset.seg==="completed"&&h===r;m.classList.toggle("magicx-aia-shimmer-revealed",S),m.classList.toggle("magicx-aia-shimmer-sweep",S),m.classList.toggle("magicx-aia-segment--editing",h===i)}return}let f=o?N(e):null;e.dataset.segKey=d,e.dataset.newParamId=r??"",e.dataset.editingParamId=i??"";let x=R(e),y=x.createDocumentFragment(),b=0;for(let m of t)if(b+=m.value.length,m.type==="completed"){let h=x.createElement("strong");h.dataset.seg="completed",h.dataset.paramId=m.param.id;let S=m.param.id===r,I=m.param.id===i,w=["magicx-aia-segment","magicx-aia-segment--completed"];S&&w.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),I&&w.push("magicx-aia-segment--editing"),h.className=w.join(" "),h.style.letterSpacing=Qr(m.value.length);let D=l?te(m.param.image_url):null;if(D){let T=x.createElement("span");T.className="magicx-aia-segment-image",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.style.setProperty("--aia-chip-image",`url("${D}")`),h.appendChild(T),h.dataset.aiaImage=""}let C=!D&&a&&m.param.icon_svg?Te(m.param.icon_svg):null;if(C){let T=x.createElement("span");T.className="magicx-aia-segment-icon",T.setAttribute("contenteditable","false"),T.setAttribute("aria-hidden","true"),T.innerHTML=C,h.appendChild(T),m.param.icon&&(h.dataset.aiaIcon=m.param.icon)}h.appendChild(x.createTextNode(m.value)),y.appendChild(h)}else if(m.type==="identified"){let h=x.createElement("strong");h.dataset.seg="identified",h.dataset.paramId=m.param.id;let S=["magicx-aia-segment","magicx-aia-segment--completed"];m.param.id===i&&S.push("magicx-aia-segment--editing"),h.className=S.join(" "),h.style.letterSpacing=Qr(m.value.length),h.textContent=m.value,y.appendChild(h)}else y.appendChild(x.createTextNode(m.value));e.replaceChildren(y),e.dataset.aiaTextLength=String(b),f!=null?M(e,Math.max(0,Math.min(f,b))):o&&zn(e)&&M(e,b)}var jo='<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 Xr(n=O()){let e=document.createElement("button");return e.type="button",e.className="magicx-aia-submit",e.setAttribute("aria-label",n.submit),e.setAttribute("data-aia-submit",""),e.innerHTML=jo.replace('aria-label="Submit"',`aria-label="${n.submit}"`),e}function zo(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function jr(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let r=t.getBoundingClientRect(),i=n.getBoundingClientRect();r.top>=i.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function zr(n,e){let{listboxId:t}=e,r=at(t);n.appendChild(r);let i=document.createElement("div");i.className="magicx-aia-input-wrapper",i.setAttribute("data-aia-input-wrapper",""),n.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",zo()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),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,c=null;e.submitButton===void 0?(l=Xr(e.strings),i.appendChild(l),c=l):e.submitButton!==null&&(c=e.submitButton,c.hasAttribute("data-aia-submit")||c.setAttribute("data-aia-submit",""),c.setAttribute("data-aia-submit-slot",""),i.appendChild(c));let d=new AbortController,{signal:u}=d,g=!1,p=0,f=()=>{let b=Ge(o),h=b.length>0&&b[0]!==b[0].toUpperCase()?b[0].toUpperCase()+b.slice(1):b;e.handleChange(h)},x=()=>{let b=G(o)?.node??null;if(!b||!o.contains(b))return null;let S=(b.nodeType===Node.ELEMENT_NODE?b:b.parentElement)?.closest("strong[data-param-id]")?.dataset.paramId??null;return S&&jn(o,S)?null:S};if(i.addEventListener("click",b=>{b.target?.closest("[data-aia-pill]")||o.focus()},{signal:u}),o.addEventListener("input",()=>{g||(p=performance.now(),f(),e.handleCaretAfterInput(N(o)))},{signal:u}),R(o).addEventListener("selectionchange",()=>{let b=G(o);if(!b||!o.contains(b.node))return;let m=b.collapsed?x():null,h=e.store.get(),S=h.editingParam?.id??h.editingIdentified?.id??null;if(m&&m!==S){e.startEditingParam(m);return}performance.now()-p<50||e.handleCaretMove(N(o))},{signal:u}),o.addEventListener("click",b=>{let m=Tt(o,b.target);m&&(e.startEditingParam(m),It(o,m))},{signal:u}),o.addEventListener("compositionstart",()=>{g=!0},{signal:u}),o.addEventListener("compositionend",()=>{g=!1,f()},{signal:u}),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 S=h.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&b.preventDefault()}},{signal:u}),o.addEventListener("paste",b=>{b.preventDefault();let m=(b.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let h=R(o),S=We(o);if(!S||!o.contains(S.startContainer))return;S.deleteContents();let I=h.createTextNode(m);S.insertNode(I),S.setStartAfter(I),Se(o,S.startContainer,S.startOffset),f()},{signal:u}),o.addEventListener("keydown",b=>e.handleKeyDown(b),{signal:u}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:u}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:u}),c&&c.addEventListener("click",b=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;b.stopPropagation(),e.onSubmit(Z(m.text,m.completedParams,m.skippedParams,{identifiedParams:m.identifiedParams,isReady:m.isReady,customFields:m.customFields}))&&e.afterSubmit?.()},{signal:u}),e.autoFocus!==!1){o.focus();let b=G(o);(!b||!o.contains(b.node))&&Se(o,o,0)}if(typeof ResizeObserver<"u"){let b=new ResizeObserver(()=>jr(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 un(n,e,t){let{input:r,inlinePillContainer:i,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:l,selectOption:c,store:d}=t;r.setAttribute("aria-expanded",String(e.isDropdownOpen));let u=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(u?r.setAttribute("aria-activedescendant",u):r.removeAttribute("aria-activedescendant"),o){let b=t.strings??O();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 g=r.dataset.newParamId??"",p=e.newParamId!==null&&e.newParamId!==g;if(cn({input:r,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused,showChipIcons:t.showChipIcons??!0,showChipImages:t.showChipImages??!0}),a==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?rt(i,e.actionableSuggestions,0,l,!1,b,e.isActivePillSelected):Qt(i)}else Qt(i);jr(r,i),p?(r.focus(),M(r,e.caretOffset??e.text.length)):e.isFocused&&Ge(r)!==e.text&&M(r,e.text.length);let f=e.editingParam?{parameter:e.editingParam.suggestionParameter,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:e.editingIdentified?{parameter:e.editingIdentified.parameter,text:z(e.editingIdentified.parameter),required:!0,options:[]}:null,x=e.dropdownSuggestion??f??e.actionableSuggestions[0],y=Ee(e);lt(s,{strings:t.strings,suggestions:x?[{...x,options:e.dropdownOptions}]:[],filteredOptions:e.dropdownOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.dropdownLoading,skeletonExiting:e.skeletonExiting,listboxId:t.listboxId,pills:f?[f]:e.actionableSuggestions,showPills:a==="dropdown",showSkipButton:t.showSkipButton&&!e.editingParam&&!e.editingIdentified,skipDisabled:e.inSelectionAnimation,showOptionIcons:t.showOptionIcons??!0,showOptionImages:t.showOptionImages??!0,showOptionCounts:t.showOptionCounts??!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,productsLayout:t.productsLayout??"row",productImageFallback:t.productImageFallback??"image",formatType:e.activeFormatType,dateView:e.dateView,selectedDateIso:y.selectedIso,selectedDateRange:y.selectedRange,dateRangeStart:y.rangeStart,optionsPosition:t.optionsPosition??"below",onSelect:c,onHighlight:(b,m)=>{m!==void 0&&d.get().activeDropdownIndex!==m||d.set({activeDropdownIndex:b})},onPillClick:l,onSkip:t.skipActivePill,onPreviousMonth:t.showPreviousMonth,onNextMonth:t.showNextMonth,onProductSelect:t.selectProduct,onProductFocusChange:b=>d.set({isFocused:b})})}function pn(n){let e=n,t=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 c=r.shift();c;c=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,u]=c;for(let g of t)g(d,u)}}catch(l){throw r.length=0,l}finally{i=!1}}},subscribe:s=>(t.add(s),()=>{t.delete(s)})}}function Jr(n,e){let t,r,i=s=>(s!==t&&(t=s,r=e(s)),r);return{get:()=>{let s=n.get();return{...s,...i(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...i(o)};return s(a)}):n.set(s)},peek:s=>{let o={...n.get(),...s};return{...o,...e(o)}},subscribe:s=>n.subscribe((o,a)=>{let l={...a,...i(a)},c={...o,...i(o)};s(c,l)})}}var mn=new WeakSet,Zr=new WeakMap;function ti(n){return n.nodeType===Node.DOCUMENT_NODE}function Jo(n){return ti(n)?n:n.ownerDocument}function Zo(n){let e=Zr.get(n);if(e)return e;let t=n.defaultView?.CSSStyleSheet;if(typeof t!="function")return null;try{let r=new t;return typeof r.replaceSync!="function"?null:(r.replaceSync(ri),Zr.set(n,r),r)}catch{return null}}function ei(n,e){if(e.querySelector("style[data-magicx-aia]"))return;let t=n.createElement("style");t.setAttribute("data-magicx-aia",""),t.textContent=ri,e.appendChild(t)}function ni(n){if(typeof document>"u")return;let e=n??document;if(mn.has(e))return;let t=Jo(e);if(ti(e)){let s=e.head??e.documentElement;if(!s)return;ei(t,s),mn.add(e);return}let r=Zo(t),i=e.adoptedStyleSheets;r&&Array.isArray(i)?i.includes(r)||(e.adoptedStyleSheets=[...i,r]):ei(t,e),mn.add(e)}var ri=`.aia-stack {
|
|
2
2
|
display: flex;
|
|
3
3
|
flex-direction: column;
|
|
4
4
|
gap: var(--aia-stack-space, 0.5rem);
|
|
@@ -2265,5 +2265,5 @@ function P(n){return n==="date"||n==="date-range"}function X(n){return n?.type?.
|
|
|
2265
2265
|
background: var(--aia-surface, #ffffff);
|
|
2266
2266
|
}
|
|
2267
2267
|
}
|
|
2268
|
-
`;var dt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(r){this.report(e,r,e);return}}runListener(e,t,r=e){try{return t(),!0}catch(i){return this.report(e,i,r),!1}}report(e,t,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.`,t))}};var ct=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let r=`${String(e)}#${++this.registrationCount}`,i=(...o)=>t(...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,...t){let r=this.listeners[e];if(!r)return!0;let i=!0;for(let s of r)this.boundary.runListener(String(e),()=>s(...t),this.keys.get(s)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var ut=class{constructor(){this.timers=new Map}schedule(e,t,r){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),t()},r);this.timers.set(e,i)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var Ie=class{constructor(e,t="auto",r){this.container=e;this.mode=t;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)}};var Zo=50,es=new Set(["search_started","submit","product_click","impression"]),ts="newParam",ii="suggestionRemoval",ns="selectionAnimation",gn="skeletonExit",rs=650,is=0;function os(){return`:ac-${++is}:`}var oi=170,ss=100;function si(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var fn=class{constructor(e,t={}){this.inputStore=pn(si());this._listboxId=os();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ut;this.boundary=new dt;this.subscriberCount=0;this.emitter=new ct(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.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Jr(this.inputStore,r=>cr(r,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ye(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:s})}}),this.reEdit=new tt({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Qe(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1,()=>this.opts.language),this.optionSource=new Ke(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 Ne(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,onRequest:({query:r,signal:i,isCurrent:s})=>{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:ee(o,i.text),chip_origin:"typed"})},onResponse:({requestId:r,funnelTelemetry:i})=>{this.lastRequestId=r,this.funnelTelemetry=i,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 Ve(this.store,{columns:t.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.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}=be(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===Pe(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=Ln(i.text,r.text,o);if(l===null){this.store.set({pendingSpan:null});return}o=l}r.text.slice(o).trim().length===0||On(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??J(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 e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...si(),isFocused:e,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.fetchController.dispose(),this.optionSource.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&&(br(this.domRefs.input),ln(this.domRefs.dropdown)),this.dropdownRefs&&ln(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 t=this.store.get();if(t.editingIdentified&&e!==t.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 t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let r of this.store.get().segments){let i=t;if(t+=r.value.length,r.type!=="text"&&e>i&&e<=t)return{kind:r.type,param:r.param,start:i,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(r=>r.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(r=>r.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:r}=this.store.get(),{start:i,end:s}=t;if(e===s){let{text:l,removed:c}=et(r,i,s);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>i?Math.max(i,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let o=Ot(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,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),M(t.input,e);else{let r=this.opts.setCursor;r&&this.boundary.runListener("setCursor",()=>r(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let r=t.identifiedParams.find(c=>c.id===e);if(!r)return!1;let i=X(r);if(!P(i))return!1;let s=i==="date-range"?je(r.text):null,o=0,a=-1;for(let c of t.segments){if(c.type!=="text"&&c.param.id===e){a=o;break}o+=c.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:Mt(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 t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.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(t=>t.placeholder).map(t=>({key:t.parameter,value:t.text??""}))})}selectProduct(e){let t=this.store.get(),r=t.products.findIndex(s=>s.id===e.id),i=t.customFields?.items?.matched?.find(s=>s.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:t.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,t){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,t)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!P(t.activeFormatType)||!t.dateView)return;let r=ft(t.dateView,e);this.store.set({dateViewMonth:{...r,key:Pe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.parameter==="placeholder"),r=e.suggestions.filter(a=>a.parameter!=="placeholder");if(r.length===0)return;let i=r[0],s=r.slice(1),o=e.skippedParams.some(a=>a.parameter===i.parameter);this.store.set({suggestions:[...t,...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 t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(r=>{this.boundary.runListener("subscribe",()=>e(r),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return Z(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,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,r=this.opts.showProducts,i=this.opts.optionOverrides;Object.assign(this.opts,e),"language"in e&&this.updateLanguageAttribute(),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==r)&&this.productsController.resync(),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 t=!this.store.get().text;this.applyOption(e),t&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let i=U(e);if(i){let s=t.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:i,key:Pe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(sr(s,i));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.timers.clear(gn),this.reEdit.selectOption(e);return}let r=pr(t,e);if(r){if(this.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:r.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:r.telemetry.otherOptions,key:r.telemetry.key,position:P(t.activeFormatType)?null:r.telemetry.position,chip_origin:"tap"}),this.timers.clear(gn),this.store.set({...r.patch,...Ze(t)}),this.startSelectionAnimationTimer(),this.timers.clear(ii),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(ii,()=>{this.store.get().suggestions.includes(i)&&this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==i)}))},oi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(ns,()=>this.store.set({inSelectionAnimation:!1}),oi)}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")}fireImpression(){if(this.funnelTelemetry!==!0)return;let e=this.store.get(),t=e.suggestions.filter(s=>s.parameter!=="placeholder").map(s=>({key:s.parameter,options:(s.options??[]).slice(0,Zo).map(o=>o.text)})),r=e.products.map(s=>s.id);if(t.length===0&&r.length===0)return;let i=JSON.stringify([t,r]);i!==this.lastImpressionKey&&(this.lastImpressionKey=i,this.fireTelemetry("impression",{query:e.text,pills:t,product_ids:r}))}fireTelemetry(e,t){let r=this.funnelTelemetry===!0;if(!r&&es.has(e))return;if(!r&&e==="option"){let{key:s,position:o,chip_origin:a,...l}=t;t=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:ge(this.opts.language),queryData:t,apiConfig:this.opts.apiConfig})}updateLanguageAttribute(){O(this.opts.language).language==="es"?this.container.dataset.aiaLanguage="es":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 Ie(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get strings(){return O(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=zr(this.container,t);let r=()=>{this.domRefs&&un(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),un(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get strings(){return O(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=Yr(this.container,t);let r=()=>{this.dropdownRefs&&dn(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),dn(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(ze),r=()=>e();t.addEventListener("change",r),this.unsubscribers.push(()=>t.removeEventListener("change",r))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,t)=>{if(!e.skeletonOptions)return;if(!t.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!t.isLoading||e.isLoading)return;let r={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(r);return}this.timers.schedule(gn,()=>this.store.set(r),ss)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(ts,()=>this.store.set({newParamId:null}),rs)}))}handleChange(e,t){let r=this.store.get();t&&e&&!r.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:s}=Dn(e,r.completedParams);s.length>0&&this.store.set({completedParams:i});let o=this.heldIdentified;this.heldIdentified=null,this.openWordText=t&&/\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 t=this.store.get(),{valid:r}=be(t.text,t.completedParams,e);r.length!==0&&this.store.set({identifiedParams:[...t.identifiedParams,...r]})}endTypedWord(){if(!this.isWordOpen())return!1;let e=this.heldIdentified;this.heldIdentified=null,this.openWordText=null;let t=this.store.get();this.maybePromoteExactMatch(t.text),e?.text===t.text&&this.admitIdentified(e.candidates);let r=this.store.get();return r.completedParams!==t.completedParams||r.identifiedParams!==t.identifiedParams}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=q(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=Cn(e.segments,t);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 t=e.caretOffset??e.editingAnchor,r=e.text.slice(e.editingAnchor,t);j(e.editingParam.options,r).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:r}=L(e.text,e.completedParams);this.fetchController.doFetch(t,r)}commitIdentifiedDate(e){let t=this.store.get(),r=t.editingIdentified;if(!r)return;if(t.text.slice(r.anchor,r.tail)!==r.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=t.text.slice(0,r.anchor),s=t.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,c=i+l+s,d=c.length,u={id:crypto.randomUUID(),placeholder:"",parameter:r.parameter,text:o,value:e.value,kind:e.kind,suggestionParameter:r.parameter,suggestionPlaceholder:z(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[],key:r.parameter,position:null,chip_origin:"tap"}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(g=>g.id!==r.id),newParamId:u.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 t=this.store.get();if(P(t.activeFormatType)||this.isWordOpen())return;let r=Je({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress,phraseExactMatch:this.fetchController.isPhraseExactMatch()});if(r){if(this.funnelTelemetry===!0){let i=t.actionableSuggestions[0],s=i.options??[];this.fireTelemetry("option",{raw_query:L(e,t.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:ee(s,r.option.text),chip_origin:"typed"})}this.store.set(r.patch)}}};export{fn as AIAutocomplete,Sr as ATTRIBUTION_URL,_t as DATE_RANGE_META_END,Dt as DATE_RANGE_META_START,_r as DEFAULT_OPTION_COUNT_UNIT,Ie as ModeController,ze as OPTIONS_GRID_MOBILE_QUERY,tn as OPTION_ENTER_DELAY_VAR,ho as OPTION_ENTER_FADE_MS,bo as OPTION_ENTER_RISE_MS,So as OPTION_ENTER_RISE_PX,fo as OPTION_ENTER_STAGGER_MS,zt as OPTION_IMAGE_WIDTH,Xi as PLACEHOLDER_FADE_OUT_MS,ae as PLACEHOLDER_LEAVING_ATTR,ji as PLACEHOLDER_SWAP_GAP_MS,Yi as PLACEHOLDER_TYPE_MS,Qi as PLACEHOLDER_WORD_PAUSE_MS,co as PRODUCT_IMAGE_WIDTH,Zn as PRODUCT_PATH_PREFIX,lo as PRODUCT_ROW_PX_PER_LINE,ir as RANGE_SEPARATOR,Pn as SCHEMA_VERSION,$r as SCROLL_ARROW_ATTR,Vr as SCROLL_ARROW_BOTTOM_VAR,Ur as SCROLL_ARROW_CLASS,qr as SCROLL_ARROW_FADE_MS,Mo as SCROLL_ARROW_LABEL,Gr as SCROLL_ARROW_SCROLL_IDLE_MS,de as SCROLL_ARROW_VISIBLE_ATTR,xn as SKIPPED_PARAM_TEXT,Fe as WEEKDAY_LABELS,ft as addMonths,Xt as attachProductRowWheel,an as attachScrollArrow,qt as buildAttributionUrl,ht as buildDateOptions,L as buildQuery,Z as buildSubmitResult,St as cellDay,U as cellIso,Tt as chipIdFromTap,ar as computeOptionsGridLayout,Vt as containScroll,pn as createStore,Ct as cursorIsAtEnd,Yt as dateCellMarks,Ee as dateSelectionFor,Ge as extractPlainText,oe as formatAbsoluteDate,$n as formatDate,or as formatDateRange,we as formatOptionCount,N as getCursorOffset,Gt as getFooterHint,z as identifiedParamLabel,P as isCalendarFormat,Ut as isOptionsGridMobileViewport,_ as isoDate,It as keepCaretOnChip,Bt as measureOptionsGrid,mt as monthLabel,Ht as needsOptionsGridMeasurement,yo as optionCountLabel,nn as optionEnterDelayMs,vo as optionHasImage,ot as optionImageSources,te as optionImageSrc,on as optionLabel,rn as optionsEntranceDurationMs,Ft as optionsGridTemplateColumns,He as parseDate,xe as parseLooseDate,je as parseLooseDateRange,Et as plainTextLength,Wt as planOptionsGrid,Ot as previousGraphemeBoundary,er as productFromMatchedItem,it as productImageSources,po as productImageSrc,jt as productInitial,Ar as productRowWheelTarget,Rt as productsFromCustomFields,cn as renderEditableContent,X as resolveFormatType,Mt as resolveIdentifiedDate,$t as sameOptionRows,Te as sanitizeOptionIconSvg,yt as scrollCaretIntoView,bt as selectedIsoFromText,ve as selectedRangeFor,M as setCursorOffset,Mr as shopifyImageSrc,pe as toWireIdentifiedParams,O as uiStringsFor,Kt as visibleDateRange,me as withSkippedParams};
|
|
2268
|
+
`;var dt=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(r){this.report(e,r,e);return}}runListener(e,t,r=e){try{return t(),!0}catch(i){return this.report(e,i,r),!1}}report(e,t,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.`,t))}};var ct=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let r=`${String(e)}#${++this.registrationCount}`,i=(...o)=>t(...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,...t){let r=this.listeners[e];if(!r)return!0;let i=!0;for(let s of r)this.boundary.runListener(String(e),()=>s(...t),this.keys.get(s)??String(e))||(i=!1);return i}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var ut=class{constructor(){this.timers=new Map}schedule(e,t,r){this.clear(e);let i=setTimeout(()=>{this.timers.delete(e),t()},r);this.timers.set(e,i)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var Ie=class{constructor(e,t="auto",r){this.container=e;this.mode=t;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)}};var es=50,ts=new Set(["search_started","submit","product_click","impression"]),ns="newParam",ii="suggestionRemoval",rs="selectionAnimation",gn="skeletonExit",is=650,os=0;function ss(){return`:ac-${++os}:`}var oi=170,as=100;function si(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],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,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1,skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1,dateViewMonth:null,pendingRangeStart:null,editingIdentified:null}}var fn=class{constructor(e,t={}){this.inputStore=pn(si());this._listboxId=ss();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ut;this.boundary=new dt;this.subscriberCount=0;this.emitter=new ct(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.emitSubmit=e=>(this.recordSubmit(e),this.emitter.emit("submit",e));this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=Jr(this.inputStore,r=>cr(r,this.opts)),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onResult&&this.emitter.on("result",t.onResult),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new Ye(this.store,{onPillSelected:({rawQuery:r,selectedPill:i,otherPills:s})=>{this.fireTelemetry("pill",{raw_query:r,selected_pill:i,other_pills:s})}}),this.reEdit=new tt({store:this.store,scheduleSetCursor:r=>this.scheduleSetCursor(r),fireTelemetry:(r,i)=>this.fireTelemetry(r,i),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Qe(this.store,()=>this.opts.products,()=>this.opts.showProducts!==!1,()=>this.opts.language),this.optionSource=new Ke(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 Ne(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,onRequest:({query:r,signal:i,isCurrent:s})=>{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:ee(o,i.text),chip_origin:"typed"})},onResponse:({requestId:r,funnelTelemetry:i})=>{this.lastRequestId=r,this.funnelTelemetry=i,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 Ve(this.store,{columns:t.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.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}=be(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===Pe(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=Ln(i.text,r.text,o);if(l===null){this.store.set({pendingSpan:null});return}o=l}r.text.slice(o).trim().length===0||On(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??J(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 e=this.store.get().isFocused;this.optionSource.reset(),this.store.set({...si(),isFocused:e,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.fetchController.dispose(),this.optionSource.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&&(br(this.domRefs.input),ln(this.domRefs.dropdown)),this.dropdownRefs&&ln(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 t=this.store.get();if(t.editingIdentified&&e!==t.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 t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let r of this.store.get().segments){let i=t;if(t+=r.value.length,r.type!=="text"&&e>i&&e<=t)return{kind:r.type,param:r.param,start:i,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(r=>r.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(r=>r.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:r}=this.store.get(),{start:i,end:s}=t;if(e===s){let{text:l,removed:c}=et(r,i,s);return this.store.set(d=>({text:l,filterBase:Math.min(d.filterBase>i?Math.max(i,d.filterBase-c):d.filterBase,l.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(i),!0}let o=Ot(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,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(o),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),M(t.input,e);else{let r=this.opts.setCursor;r&&this.boundary.runListener("setCursor",()=>r(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingIdentified(e){let t=this.store.get();if(t.editingIdentified?.id===e)return!0;let r=t.identifiedParams.find(c=>c.id===e);if(!r)return!1;let i=X(r);if(!P(i))return!1;let s=i==="date-range"?je(r.text):null,o=0,a=-1;for(let c of t.segments){if(c.type!=="text"&&c.param.id===e){a=o;break}o+=c.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:Mt(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 t=this.store.get().editingIdentified;t&&e!=null&&(e<t.anchor||e>t.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(t=>t.placeholder).map(t=>({key:t.parameter,value:t.text??""}))})}selectProduct(e){let t=this.store.get(),r=t.products.findIndex(s=>s.id===e.id),i=t.customFields?.items?.matched?.find(s=>s.source_id===e.id)?.origin_id;this.fireTelemetry("product_click",{query:t.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,t){this.store.get().editingIdentified&&this.store.set({editingIdentified:null,activeDropdownIndex:-1}),this.handleChange(e,t)}showPreviousMonth(){this.pageDateView(-1)}showNextMonth(){this.pageDateView(1)}pageDateView(e){let t=this.store.get();if(!P(t.activeFormatType)||!t.dateView)return;let r=ft(t.dateView,e);this.store.set({dateViewMonth:{...r,key:Pe(t)},activeDropdownIndex:-1})}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(a=>a.parameter==="placeholder"),r=e.suggestions.filter(a=>a.parameter!=="placeholder");if(r.length===0)return;let i=r[0],s=r.slice(1),o=e.skippedParams.some(a=>a.parameter===i.parameter);this.store.set({suggestions:[...t,...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 t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(r=>{this.boundary.runListener("subscribe",()=>e(r),t)})}getState(){return this.store.get()}getResult(){return this.buildResult()}buildResult(){let e=this.store.get();return Z(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,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products,r=this.opts.showProducts,i=this.opts.optionOverrides;Object.assign(this.opts,e),"language"in e&&this.updateLanguageAttribute(),"optionOverrides"in e&&e.optionOverrides!==i&&this.optionSource.refresh(),("products"in e&&e.products!==t||"showProducts"in e&&e.showProducts!==r)&&this.productsController.resync(),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 t=!this.store.get().text;this.applyOption(e),t&&this.store.get().text&&this.noteSearchStarted()}applyOption(e){let t=this.store.get();if(t.activeFormatType==="date-range"){let i=U(e);if(i){let s=t.dateRangeStart;if(!s){this.store.set({pendingRangeStart:{iso:i,key:Pe(t)}});return}this.store.set({pendingRangeStart:null}),this.selectOption(sr(s,i));return}}if(t.editingIdentified){this.commitIdentifiedDate(e);return}if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.timers.clear(gn),this.reEdit.selectOption(e);return}let r=pr(t,e);if(r){if(this.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:r.telemetry.selectedOption,other_options:P(t.activeFormatType)?[]:r.telemetry.otherOptions,key:r.telemetry.key,position:P(t.activeFormatType)?null:r.telemetry.position,chip_origin:"tap"}),this.timers.clear(gn),this.store.set({...r.patch,...Ze(t)}),this.startSelectionAnimationTimer(),this.timers.clear(ii),r.remainingActionable>0){let i=r.consumedSuggestion;this.timers.schedule(ii,()=>{this.store.get().suggestions.includes(i)&&this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==i)}))},oi)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(rs,()=>this.store.set({inSelectionAnimation:!1}),oi)}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")}fireImpression(){if(this.funnelTelemetry!==!0)return;let e=this.store.get(),t=e.suggestions.filter(s=>s.parameter!=="placeholder").map(s=>({key:s.parameter,options:(s.options??[]).slice(0,es).map(o=>o.text)})),r=e.products.map(s=>s.id);if(t.length===0&&r.length===0)return;let i=JSON.stringify([t,r]);i!==this.lastImpressionKey&&(this.lastImpressionKey=i,this.fireTelemetry("impression",{query:e.text,pills:t,product_ids:r}))}fireTelemetry(e,t){let r=this.funnelTelemetry===!0;if(!r&&ts.has(e))return;if(!r&&e==="option"){let{key:s,position:o,chip_origin:a,...l}=t;t=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:ge(this.opts.language),queryData:t,apiConfig:this.opts.apiConfig})}updateLanguageAttribute(){O(this.opts.language).language==="es"?this.container.dataset.aiaLanguage="es":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 Ie(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get strings(){return O(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=zr(this.container,t);let r=()=>{this.domRefs&&un(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),un(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get strings(){return O(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=Yr(this.container,t);let r=()=>{this.dropdownRefs&&dn(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(r),this.subscribeViewportBreakpoint(r),dn(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(ze),r=()=>e();t.addEventListener("change",r),this.unsubscribers.push(()=>t.removeEventListener("change",r))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeSkeletonMirror(){this.unsubscribers.push(this.store.subscribe((e,t)=>{if(!e.skeletonOptions)return;if(!t.isLoading&&e.isLoading){e.skeletonRequested||this.store.set({skeletonRequested:!0});return}if(!t.isLoading||e.isLoading)return;let r={skeletonOptions:null,skeletonSuggestion:null,skeletonRequested:!1};if(!e.skeletonExiting){this.store.set(r);return}this.timers.schedule(gn,()=>this.store.set(r),as)}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(ns,()=>this.store.set({newParamId:null}),is)}))}handleChange(e,t){let r=this.store.get();t&&e&&!r.text&&this.noteSearchStarted(),this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:s}=Dn(e,r.completedParams);s.length>0&&this.store.set({completedParams:i});let o=this.heldIdentified;this.heldIdentified=null,this.openWordText=t&&/\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 t=this.store.get(),{valid:r}=be(t.text,t.completedParams,e);r.length!==0&&this.store.set({identifiedParams:[...t.identifiedParams,...r]})}endTypedWord(){if(!this.isWordOpen())return!1;let e=this.heldIdentified;this.heldIdentified=null,this.openWordText=null;let t=this.store.get();this.maybePromoteExactMatch(t.text),e?.text===t.text&&this.admitIdentified(e.candidates);let r=this.store.get();return r.completedParams!==t.completedParams||r.identifiedParams!==t.identifiedParams}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=q(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),r=Cn(e.segments,t);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 t=e.caretOffset??e.editingAnchor,r=e.text.slice(e.editingAnchor,t);j(e.editingParam.options,r).some(s=>s.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:r}=L(e.text,e.completedParams);this.fetchController.doFetch(t,r)}commitIdentifiedDate(e){let t=this.store.get(),r=t.editingIdentified;if(!r)return;if(t.text.slice(r.anchor,r.tail)!==r.text){this.store.set({editingIdentified:null,activeDropdownIndex:-1});return}let i=t.text.slice(0,r.anchor),s=t.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,c=i+l+s,d=c.length,u={id:crypto.randomUUID(),placeholder:"",parameter:r.parameter,text:o,value:e.value,kind:e.kind,suggestionParameter:r.parameter,suggestionPlaceholder:z(r.parameter),options:[],metadata:e.metadata,icon:e.icon,icon_svg:e.icon_svg,image_url:e.image_url};this.fireTelemetry("option",{raw_query:L(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:[],key:r.parameter,position:null,chip_origin:"tap"}),this.store.set({text:c,completedParams:[...t.completedParams,u],identifiedParams:t.identifiedParams.filter(g=>g.id!==r.id),newParamId:u.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 t=this.store.get();if(P(t.activeFormatType)||this.isWordOpen())return;let r=Je({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress,phraseExactMatch:this.fetchController.isPhraseExactMatch()});if(r){if(this.funnelTelemetry===!0){let i=t.actionableSuggestions[0],s=i.options??[];this.fireTelemetry("option",{raw_query:L(e,t.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:ee(s,r.option.text),chip_origin:"typed"})}this.store.set(r.patch)}}};export{fn as AIAutocomplete,Sr as ATTRIBUTION_URL,_t as DATE_RANGE_META_END,Dt as DATE_RANGE_META_START,_r as DEFAULT_OPTION_COUNT_UNIT,Ie as ModeController,ze as OPTIONS_GRID_MOBILE_QUERY,tn as OPTION_ENTER_DELAY_VAR,bo as OPTION_ENTER_FADE_MS,So as OPTION_ENTER_RISE_MS,xo as OPTION_ENTER_RISE_PX,ho as OPTION_ENTER_STAGGER_MS,zt as OPTION_IMAGE_WIDTH,ji as PLACEHOLDER_FADE_OUT_MS,ae as PLACEHOLDER_LEAVING_ATTR,zi as PLACEHOLDER_SWAP_GAP_MS,Qi as PLACEHOLDER_TYPE_MS,Xi as PLACEHOLDER_WORD_PAUSE_MS,uo as PRODUCT_IMAGE_WIDTH,Zn as PRODUCT_PATH_PREFIX,co as PRODUCT_ROW_PX_PER_LINE,ir as RANGE_SEPARATOR,Pn as SCHEMA_VERSION,$r as SCROLL_ARROW_ATTR,Vr as SCROLL_ARROW_BOTTOM_VAR,Ur as SCROLL_ARROW_CLASS,qr as SCROLL_ARROW_FADE_MS,ko as SCROLL_ARROW_LABEL,Gr as SCROLL_ARROW_SCROLL_IDLE_MS,de as SCROLL_ARROW_VISIBLE_ATTR,xn as SKIPPED_PARAM_TEXT,Fe as WEEKDAY_LABELS,ft as addMonths,Xt as attachProductRowWheel,an as attachScrollArrow,qt as buildAttributionUrl,ht as buildDateOptions,L as buildQuery,Z as buildSubmitResult,St as cellDay,U as cellIso,Tt as chipIdFromTap,ar as computeOptionsGridLayout,Vt as containScroll,pn as createStore,Ct as cursorIsAtEnd,Yt as dateCellMarks,Ee as dateSelectionFor,Ge as extractPlainText,oe as formatAbsoluteDate,$n as formatDate,or as formatDateRange,we as formatOptionCount,N as getCursorOffset,Gt as getFooterHint,z as identifiedParamLabel,P as isCalendarFormat,Ut as isOptionsGridMobileViewport,_ as isoDate,It as keepCaretOnChip,Bt as measureOptionsGrid,mt as monthLabel,Ht as needsOptionsGridMeasurement,vo as optionCountLabel,nn as optionEnterDelayMs,Po as optionHasImage,ot as optionImageSources,te as optionImageSrc,on as optionLabel,rn as optionsEntranceDurationMs,Ft as optionsGridTemplateColumns,He as parseDate,xe as parseLooseDate,je as parseLooseDateRange,Et as plainTextLength,Wt as planOptionsGrid,Ot as previousGraphemeBoundary,er as productFromMatchedItem,it as productImageSources,mo as productImageSrc,jt as productInitial,Ar as productRowWheelTarget,Rt as productsFromCustomFields,cn as renderEditableContent,X as resolveFormatType,Mt as resolveIdentifiedDate,$t as sameOptionRows,Te as sanitizeOptionIconSvg,yt as scrollCaretIntoView,bt as selectedIsoFromText,ve as selectedRangeFor,M as setCursorOffset,Mr as shopifyImageSrc,pe as toWireIdentifiedParams,O as uiStringsFor,Kt as visibleDateRange,me as withSkippedParams};
|
|
2269
2269
|
//# sourceMappingURL=index.mjs.map
|